query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Abstract the problem of waiting for some condition to occur with a timeout. Loop on checkFunction, calling readyCallback when it succeeds, or calling timeoutCallback after MEDIA_WAIT_DURATION milliseconds.
function checkTimeoutLoop( checkFunction, readyCallback, timeoutCallback ){ var ready = false; // perform one check function doCheck(){ if ( _interruptLoad ) { return; } // run the check function ready = checkFunction(); if ( ready ) { // if success, call the ready callback readyCallback(); } else { // otherwise, prepare for another loop setTimeout( doCheck, STATUS_INTERVAL ); } } // set a timeout to occur after timeoutDuration milliseconds setTimeout(function(){ // if success hasn't already occured, call timeoutCallback if ( !ready ) { timeoutCallback(); } }, MEDIA_WAIT_DURATION ); //init doCheck(); }
[ "function waitFor(test, onReady, timeOutMillis, onTimeout) {\n var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30001, //< Default Max Timeout is 30s\n start = new Date().getTime(),\n condition = false,\n interval = setInterval(\n function() {\n if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {\n // If not time-out yet and condition not yet fulfilled\n condition = (typeof(test) === \"string\" ? eval(test) : test()); // defensive code\n } else {\n if(!condition) {\n // If condition still not fulfilled (timeout but condition is 'false')\n typeof(onTimeout) === \"string\" ? eval(onTimeout) : onTimeout();\n } else {\n // Condition fulfilled (condition is 'true')\n typeof(onReady) === \"string\" ? eval(onReady) : onReady(); // Do what it's supposed to do once the condition is fulfilled\n }\n clearInterval(interval); // Stop this interval\n }\n },\n 100\n ); // repeat check every 100ms\n}", "function waitForPopcorn( readyCallback, timeoutCallback, mediaType ) {\n if ( mediaType !== \"object\" ) {\n checkTimeoutLoop(function(){\n return ( !!window.Popcorn[ mediaType ] );\n }, readyCallback, timeoutCallback, PLAYER_WAIT_DURATION );\n }\n else{\n readyCallback();\n }\n }", "function timeCheck(finishCallback, waitingCallback) {\n var d,\n h,\n m,\n s;\n condition = false;\n var interval = setInterval(function () {\n d = new Date();\n h = d.getHours();\n m = d.getMinutes();\n s = d.getSeconds();\n if (condition) {\n clearInterval(interval);\n finishCallback();\n } else {\n if (h === 23 & m >= 57 & s >= 13) {\n condition = true;\n } else {\n waitingCallback();\n }\n }\n }, 250);\n}", "function waitTimeout() {\n var index;\n if (sozi.document.frames[currentFrameIndex].timeoutEnable) {\n waiting = true;\n index = (currentFrameIndex + 1) % sozi.document.frames.length;\n nextFrameTimeout = window.setTimeout(function () {\n exports.moveToFrame(index);\n },\n sozi.document.frames[currentFrameIndex].timeoutMs\n );\n }\n }", "function waitToSync(funct, done, timeout, caller) {\n //This is a hack synchronize to wait until funct() returns true or timeout becomes < 0.\n caller = caller || '';\n if ((funct === undefined) || typeof (funct) != 'function') return;\n function waiting() {\n if (!funct()) {\n var dt = new Date();\n console.log(caller + \" waiting: \" + dt.toLocaleTimeString());\n if ((timeout - 1000) > 0)\n setTimeout(waiting, 1000); //1 second.\n else {\n\n console.log(caller + ': waitToSync timed out!!!');\n document.body.style.cursor = 'default';\n }\n timeout -= 1000;\n }\n else {\n if (done !== undefined && (typeof done === 'function'))\n done();\n }\n }\n waiting();\n}", "function waitForSpeech(func, options)\n{\n if (!speechReady)\n {\n\tsetTimeout(waitForSpeech,100,func,options);\n }\n else\n {\n\tfunc(options);\n }\n}", "function limitedInterval(callback, waitTime, limitTime){\n let checkTime = 0;\n setInterval(() => {\n checkTime += waitTime;\n if(checkTime < limitTime){ \n callback();\n } else {\n clearInterval();\n }\n }, waitTime);\n}", "function waitForLibraries (self, callback, timeout)\n{\n timeout = timeout || 150;\n if (self.rdf === undefined || $.ui === undefined)\n {\n console.log(\"Waiting for libraries to load.\");\n window.setTimeout(callback, timeout);\n return true;\n }\n return false;\n}", "function waitMediaToLoad(mediaSource, timeout = 30000)\n{\n // a promise that resolves as soon as the media is loaded\n const waitUntil = eventName => new Promise((resolve, reject) => {\n _utils_utils__WEBPACK_IMPORTED_MODULE_3__[\"Utils\"].log(`Loading media ${mediaSource} ...`);\n\n const timer = setTimeout(() => {\n reject(new _utils_errors__WEBPACK_IMPORTED_MODULE_2__[\"TimeoutError\"](`Can't load ${mediaSource}: timeout (${timeout}ms)`));\n }, timeout);\n\n mediaSource.addEventListener(eventName, ev => {\n clearTimeout(timer);\n resolve(mediaSource);\n });\n });\n\n // check if the media is already loaded\n // if it's not, wait until it is\n if(mediaSource && mediaSource.constructor) {\n switch(mediaSource.constructor.name) {\n case 'HTMLImageElement':\n if(mediaSource.complete && mediaSource.naturalWidth !== 0)\n return Promise.resolve(mediaSource);\n else\n return waitUntil('load');\n\n case 'HTMLVideoElement':\n if(mediaSource.readyState >= 4)\n return Promise.resolve(mediaSource);\n else\n return waitUntil('canplaythrough');\n //return waitUntil('canplay'); // use readyState >= 3\n\n case 'HTMLCanvasElement':\n return Promise.resolve(mediaSource);\n\n case 'ImageBitmap':\n return Promise.resolve(mediaSource);\n }\n }\n\n // unrecognized media type\n throw new _utils_errors__WEBPACK_IMPORTED_MODULE_2__[\"IllegalArgumentError\"](`Can't load the media: unrecognized media type. ${mediaSource}`);\n}", "function checkTimeSinceLastAjaxUpdate() {\n var timeSinceLastAjaxReturn = new Date().getTime() - lastReady;\n\n if (listenerCount > 0 && timeSinceLastAjaxReturn < MAX_WAIT) {\n //listeners are still present and we haven't reached our timeout\n window.setTimeout(checkTimeSinceLastAjaxUpdate, TIMEOUT);\n }\n else {\n //no more listener, call the callback\n callbackFunctionName();\n }\n}", "async waitForSecurityChecksResults(timeout) {\n for (let i = 0; i < timeout; i++) {\n const results = await this.getSecurityChecksResults();\n\n if (results && results.length) {\n break;\n }\n\n I.wait(1);\n }\n }", "onTimeout(){\n\t\tthis.callback.apply(null, this.args)\n\t\tthis.continue()\n\t}", "function holdIt() {\n if (myDebug) {alert(\"--- Waiting \" + waitSeconds + \" seconds ---\");}\n\n if (waitSeconds < 1) {\n waitSeconds = 1;\n }\n\n setTimeout(tuneIt,waitSeconds*1000);\n\n}", "function waitforgo() {\n $(\"#startingblock\").hide(\"slide\", { direction: \"left\" }, 250);\n setTimeout(() => {\n $(\"#mixplaycontrols\").show(\"slide\", { direction: \"right\" }, 250).show();\n }, 500);\n\n log(\"Waiting for you to login...\");\n $.ajax(\"https://mixer.com/api/v1/oauth/shortcode/check/\" + data.handle)\n .done((result, statusText, xhr) => {\n // console.log(xhr);\n switch (xhr.status) {\n case 204:\n setTimeout(waitforgo, 2000);\n break;\n case 200:\n // console.log(result.code);\n data.codetwo = result.code;\n finalstep();\n }\n })\n .fail((xhr, textStatus) => {\n switch (xhr.status) {\n case 403:\n // console.log(\"Why you say no?\");\n alert(\"You said no, now you have to reload.\");\n break;\n case 404:\n // console.log(\"You waited too long\");\n alert(\"You took too long, now you have to reload.\");\n break;\n }\n });\n}", "function waitForEnoughOutputValueMessages(timeout, callback) {\n if (timeout === undefined) timeout = 3000;\n\n // This is a bit of a hack: we want the callback to be invoked _after_\n // the outputs are assigned. Because the shiny:message event is\n // triggered just before the output values are assigned, we need to\n // wait for the next tick of the eventloop.\n var callbackWrapper = function(timedOut) {\n setTimeout(function() { callback(timedOut); }, 0);\n };\n\n // Check that a message contains `values` field.\n function checkMessage(e) {\n if (e.message && e.message.values) {\n found++;\n // shinytest2.log(\"Found message with values field.\");\n\n if (foundEnough()) {\n $(document).off(\"shiny:message\", checkMessage);\n clearTimeout(timeoutCallback);\n\n callbackWrapper(false);\n }\n }\n }\n\n $(document).on(\"shiny:message\", checkMessage);\n\n // If timeout elapses without finding message, remove listener and\n // invoke `callback(true)`.\n var timeoutCallback = setTimeout(function() {\n shinytest2.log(\"Timed out without finding message with values field.\");\n\n $(document).off(\"shiny:message\", checkMessage);\n\n callbackWrapper(true);\n }, timeout);\n }", "function checkFinished () {\n console.log(fileLoadCount+\" files loaded\")\n if (fileLoadCount == fileLoadThreshold) {\n console.log(\"basicFileLoader - callback: \"+cFunc.name);\n cFunc();\n }\n }", "function pollForElement(selector, callback) {\n if (elementExists(selector)) {\n callback();\n } else {\n setTimeout(function() {\n pollForElement(selector, callback);\n }, 100);\n }\n }", "function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }", "waitFor(model, condition = (response) => true) {\n const self = this;\n let currentLoop = null;\n \n return new Promise((resolve, reject) => {\n if (!model) { return reject(\"No model provided\"); }\n if (!model._modelType) { return reject(\"No modelType provided\"); }\n \n // Poll the status of the model every second using recursive iteration\n const startLooping = (func) => {\n return later(() => {\n currentLoop = startLooping(func);\n self.get('store').findRecord(model._modelType, model._id, {\n reload: true\n }).then(response => {\n if (condition(response)) {\n cancel(currentLoop);\n resolve(response);\n }\n }).catch(err => {\n cancel(currentLoop);\n reject(err);\n });\n }, 1000);\n };\n \n // Start polling\n currentLoop = startLooping();\n });\n }", "function repeatForDuration(msecs, fn) {\n var start = WinJS.Utilities._now(),\n end = start + msecs;\n while (WinJS.Utilities._now() < end) {\n if (fn) { fn(); }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string from the provided time in milliseconds, considering the requested precision to display miliseconds. It always returns a full string in the format: hh:mm:ss.xx Precision can be 1 (during playback) or 2 (when stopped)
function msToStringWithPrecision(ms, precision) { var h = Math.floor(ms / 3600000); ms -= (h * 3600000); var m = Math.floor(ms / 60000); ms -= (m * 60000); var s = Math.floor(ms / 1000); ms -= (s * 1000); var finalTime = ""; finalTime += ((h < 10) ? "0" + h : h) + ":"; finalTime += ((m < 10) ? "0" + m : m) + ":"; finalTime += ((s < 10) ? "0" + s : s); if (precision === 1) { finalTime += "." + ((ms < 10) ? "0" : parseInt(ms / 100)); } else { if (ms < 10) { finalTime += ".00"; } else if (ms < 100) { finalTime += ".0" + parseInt(ms / 10); } else { finalTime += "." + parseInt(ms / 10); } } return finalTime; }
[ "function msToStringWithPrecision(ms, precision)\n{\n var h = Math.floor(ms / 3600000)\n ms -= (h * 3600000)\n\n var m = Math.floor(ms / 60000)\n ms -= (m * 60000)\n\n var s = Math.floor(ms / 1000)\n ms -= (s * 1000)\n\n var finalTime = \"\"\n finalTime += ((h < 10) ? \"0\" + h : h) + \":\"\n finalTime += ((m < 10) ? \"0\" + m : m) + \":\"\n finalTime += ((s < 10) ? \"0\" + s : s)\n if (precision === 1)\n finalTime += \".\" + ((ms < 10) ? \"0\" : parseInt(ms / 100))\n else\n {\n if (ms < 10)\n finalTime += \".00\"\n else if (ms < 100)\n finalTime += \".0\" + parseInt(ms / 10)\n else\n finalTime += \".\" + parseInt(ms / 10)\n }\n\n return finalTime\n}", "printTime(){\n let min = Math.floor(this.project._pot/60);\n let sec = Math.floor(this.project._pot)-min*60;\n let msec = Math.floor((this.project._pot-Math.floor(this.project._pot))*1000);\n if(sec<10) sec = \"0\"+sec;\n if(min<10) min = \"0\"+min;\n return min+\":\"+sec+\":\"+msec;\n }", "function getTimeString(totalMins)\r\n { \r\n const hours = Math.floor(totalMins / 60); \r\n const minutes = totalMins % 60;\r\n const hoursLabel = hours === 1 ? 'hr.' : 'hrs.'\r\n const minsLabel = minutes === 1 ? 'min.' : 'mins.'\r\n \r\n let timeString = '';\r\n if (hours > 0 && minutes > 0) \r\n timeString = hours + ' ' + hoursLabel + ' ' + minutes + ' ' + minsLabel;\r\n else if (hours > 0 && minutes === 0) \r\n timeString = hours + ' ' + hoursLabel;\r\n else if (hours === 0) \r\n timeString = minutes + ' ' + minsLabel;\r\n return timeString; \r\n }", "function getDuration(time) {\n var minutes = Math.floor(time / 60000);\n var seconds = ((time % 60000) / 1000).toFixed(0);\n if (seconds < 10) {\n seconds = '0' + seconds;\n }\n return minutes + \":\" + seconds;\n}", "function getTimerText() {\n let result = '';\n if(minutes.toString().length === 1)\n result = '0' + minutes;\n else\n result = minutes;\n result += ':';\n if(seconds.toString().length === 1)\n result += '0' + seconds;\n else\n result += seconds;\n return result;\n }", "function MillisecondsToCMIDuration(n) {\n\tvar hms = \"\";\n\tvar dtm = new Date();\tdtm.setTime(n);\n\tvar h = \"000\" + Math.floor(n / 3600000);\n\tvar m = \"0\" + dtm.getMinutes();\n\tvar s = \"0\" + dtm.getSeconds();\n\tvar cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);\n\thms = h.substr(h.length-4)+\":\"+m.substr(m.length-2)+\":\";\n\thms += s.substr(s.length-2)+\".\"+cs.substr(cs.length-2);\n\treturn hms\n}", "function utilToCssTime(msec) {\n\t\tif (typeof msec !== 'number' || Number.isNaN(msec) || !Number.isFinite(msec)) {\n\t\t\tlet what;\n\n\t\t\tswitch (typeof msec) {\n\t\t\tcase 'string':\n\t\t\t\twhat = `\"${msec}\"`;\n\t\t\t\tbreak;\n\n\t\t\tcase 'number':\n\t\t\t\twhat = String(msec);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\twhat = Object.prototype.toString.call(msec);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthrow new Error(`invalid milliseconds: ${what}`);\n\t\t}\n\n\t\treturn `${msec}ms`;\n\t}", "function timestampWithMs() {\n return Date.now() / 1000;\n}", "formatVideoLength(time = null){\n if(time == null) return ;\n \n var a = time.match(/\\d+H|\\d+M|\\d+S/g);\n var result = 0;\n \n var d = { 'H': 3600, 'M': 60, 'S': 1 };\n var num;\n var type;\n \n for (var i = 0; i < a.length; i++) {\n num = a[i].slice(0, a[i].length - 1);\n type = a[i].slice(a[i].length - 1, a[i].length);\n \n result += parseInt(num) * d[type];\n }\n\n //Format seconds to actual time\n d = Number(result);\n var h = Math.floor(d / 3600);\n var m = Math.floor(d % 3600 / 60);\n var s = Math.floor(d % 3600 % 60);\n\n var hDisplay = h > 0 ? h + (h == 1 ? \" hour, \" : \" hours, \") : \"\";\n var mDisplay = m > 0 ? m + (m == 1 ? \" minute, \" : \" minutes, \") : \"\";\n var sDisplay = s > 0 ? s + (s == 1 ? \" second\" : \" seconds\") : \"\";\n return hDisplay + mDisplay + sDisplay;\n }", "function displayTime(hours,miutes,seconds,milliseconds){\n\t\tdocument.getElementById(\"timerBoard\").innerHTML = padZero(hours,2)+\":\"+padZero(minutes,2)+\":\"+padZero(seconds,2)+\":\"+padZero(milliseconds,3);\n\t}", "function getTime(time) {\n var tempTime;\n tempTime = replaceAt(time, 2, \"h\");\n tempTime = replaceAt(tempTime, 5, \"m\");\n tempTime += \"s\";\n return tempTime;\n }", "function getTimeInMilliseconds(h, m, s, ms){\n return h * 3600000 + m * 60000 + s * 1000 + ms; \n}", "function format_duration(duration) {\n return Math.floor(duration / 60) + \":\" + two_digits(duration % 60);\n }", "function precision_function() {\n var a = 1234567.89876543210;\n document.getElementById(\"precision\").innerHTML = a.toPrecision(10);\n}", "getWaitTime(t) {\n let _now = new Date();\n let _then = new Date(parseInt(t));\n let _t = (_now - _then) / 1000;\n let _m = Math.floor(_t / 60);\n let _s = _t - (_m * 60);\n\n _m = this._timeDigit(_m); //pretty strings\n _s = this._timeDigit(_s);\n\n return `${_m}:${_s}`; \n }", "function format_speed(speed) {\n return Number(speed).toFixed(2) + ' Mbps';\n}", "function posToMs(x, timescale, tickSize)\n{\n // tickSize : 1000 * timescale = x : result\n return parseInt(x * (1000 * timescale) / tickSize);\n}", "function iso8601Str( startMilliseconds, endMilliseconds, t ) {\n s= new Date(t).toJSON();\n if ( endMilliseconds - startMilliseconds > 100*24*86400000 ) {\n s= s.substring(0,11)+\"00:00Z\";\n } else if ( endMilliseconds - startMilliseconds > 5*24*86400000 ) {\n s= s.substring(0,13)+\":00Z\";\n } else if ( endMilliseconds - startMilliseconds > 43200000 ) {\n s= s.substring(0,16)+\"Z\";\n } else if ( endMilliseconds - startMilliseconds > 3600000 ) {\n s= s.substring(0,19)+\"Z\";\n }\n return s;\n}", "function changeTimeFormat(sec) {\n seconds = Math.round(sec);\n min = Math.floor(sec / 60);\n minutes = (min >= 10) ? min : \"0\" + min;\n seconds = Math.floor(seconds % 60);\n seconds = (seconds >= 10) ? seconds : \"0\" + seconds;\n return minutes + \":\" + seconds;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the "result" coordinates with the Vector2 divided by the given one coordinates
divideToRef(otherVector, result) { result.x = this.x / otherVector.x; result.y = this.y / otherVector.y; return this; }
[ "divideToRef(otherVector, result) {\n return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n }", "divide(otherVector) {\n return new Vector2(this.x / otherVector.x, this.y / otherVector.y);\n }", "divide(otherVector) {\n return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);\n }", "divide(otherVector) {\n return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n }", "function lineDividing(x1, y1, x2, y2, a, b) {\n\tp1 = (b * x1 + a * x2) / (a + b);\n\tp2 = (b * y1 + a * y2) / (a + b);\n\treturn { p1, p2 };\n}", "multiplyToRef(otherVector, result) {\n return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);\n }", "function division(a, b) {\n //tu codigo debajo\n let resultado = a / b;\n return resultado;\n​\n}", "function DIVIDE() {\n for (var _len6 = arguments.length, values = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n values[_key6] = arguments[_key6];\n }\n\n // Return `#NA!` if 2 arguments are not provided.\n if (values.length !== 2) {\n return error$2.na;\n }\n\n // decompose values into a and b.\n var a = values[0];\n var b = values[1];\n\n // You cannot divide a number by 0.\n\n if (b === 0) {\n return error$2.div0;\n }\n\n // Return `#VALUE!` if either a or b is not a number.\n if (!ISNUMBER(a) || !ISNUMBER(b)) {\n return error$2.value;\n }\n\n // Return the product\n return a / b;\n}", "static NormalizeToRef(vector, result) {\n result.copyFrom(vector);\n result.normalize();\n }", "multiplyByFloats(x, y) {\n return new Vector2(this.x * x, this.y * y);\n }", "function computeProjection(v1, v2) {\n return dot(v1, v2);\n}", "function increment(v1, v2, dst) {\r\n let d = dist(v1.x, v1.y, v2.x, v2.y);\r\n let t = dst/d;\r\n if (t < 0) return v1;\r\n if (t > 1) return v2;\r\n let x = ((1 - t) * v1.x) + (t * v2.x);\r\n let y = ((1 - t) * v1.y) + (t * v2.y);\r\n return new Vector(x, y);\r\n}", "addToRef(otherVector, result) {\n return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }", "get centre() { return new vector2(this.centrex, this.centrey);}", "static Normalize(vector) {\n const newVector = new Vector2(vector.x, vector.y);\n newVector.normalize();\n return newVector;\n }", "division(a,b) {\n if( b === 0) {\n return 0;\n } else {\n return a/b;\n }\n }", "static Center(value1, value2) {\n const center = Vector4.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }", "static Center(value1, value2) {\n const center = Vector2.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }", "static CrossToRef(left, right, result) {\n const x = left.y * right.z - left.z * right.y;\n const y = left.z * right.x - left.x * right.z;\n const z = left.x * right.y - left.y * right.x;\n result.copyFromFloats(x, y, z);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves metaData for multiple studies at once. This function calls retrieveStudyMetadata several times, asynchronously, and waits for all of the results to be returned.
function retrieveStudiesMetadata(server, studyInstanceUids, seriesInstanceUids) { // Create an empty array to store the Promises for each metaData retrieval call var promises = []; // Loop through the array of studyInstanceUids studyInstanceUids.forEach(function (studyInstanceUid) { // Send the call and resolve or reject the related promise based on its outcome var promise = retrieveStudyMetadata(server, studyInstanceUid, seriesInstanceUids); // Add the current promise to the array of promises promises.push(promise); }); // When all of the promises are complete, this callback runs var promise = Promise.all(promises); // Warn the error on console if some retrieval failed promise.catch(function (error) { return log$1.warn(error); }); return promise; }
[ "function getMetaData(container, callback) {\n var $item,\n model,\n id,\n i,\n chunk,\n chunksize,\n requestIds,\n missingIds = {};\n\n $('[data-id]', container).each(function (i, row) {\n $item = $(row);\n model = $item.attr('data-class');\n id = $item.attr('data-id');\n\n if (!domStack[model]) {\n domStack[model] = {};\n ids[model] = [];\n }\n if (!domStack[model][id]) {\n domStack[model][id] = [];\n }\n if (domStack[model][id].indexOf($item) === -1) {\n domStack[model][id].push($item);\n }\n if (ids[model].indexOf(id) === -1) {\n ids[model].push(id);\n\n if (!missingIds[model]) {\n missingIds[model] = [];\n }\n missingIds[model].push(id);\n }\n });\n\n /**\n * successHandler\n *\n * Response is either an id-indexed array, or a single result\n *\n * @param response $response\n */\n function successHandler(response) {\n var id;\n\n if (!metaData[model]) {\n metaData[model] = {};\n }\n\n if (response.id) {\n id = response.id;\n metaData[model][id] = response;\n return;\n }\n\n for (id in response) {\n if (response.hasOwnProperty(id)) {\n metaData[model][id] = response[id];\n }\n }\n }\n\n for (model in ids) {\n if (ids.hasOwnProperty(model)) {\n i = 0;\n chunksize = 30;\n\n if (missingIds[model]) {\n\t\t\t\t\t$.ajax({\n\t\t\t\t\t\tasync: false,\n\t\t\t\t\t\ttype: 'POST',\n\t\t\t\t\t\turl: $.url('/admin/data/' + model),\n\t\t\t\t\t\tdata: JSON.stringify(missingIds[model]),\n\t\t\t\t\t\tsuccess: successHandler\n\t\t\t\t\t});\n }\n }\n }\n\n if (callback) {\n callback();\n }\n }", "function getStudies(url) {\n tableId = \"studyTable\";\n httpGet(url, populateTable);\n}", "function fetchS3Galleries(files, metalsmith, done) {\n var metadata = metalsmith.metadata();\n metadata.images = {};\n var s3 = new AWS.S3();\n\n var params = {\n Bucket: 'thefurrybrotherhood'\n };\n\n s3.listObjects(params, function(err, data) {\n if (err) {\n console.log(err, err.stack);\n } else {\n var BASE_URL = 'https://s3-eu-west-1.amazonaws.com/thefurrybrotherhood/';\n\n // https://s3-eu-west-1.amazonaws.com/thefurrybrotherhood/jake%3Asomething\n data.Contents.forEach(function(item) {\n\n var fileParts = item.Key.split('~');\n var gallery = fileParts[0];\n\n if (!metadata.images[gallery]) {\n metadata.images[gallery] = [];\n }\n\n if (item.Key.indexOf('@') === -1) {\n var srcParts = item.Key.split('.')\n var small = srcParts[0] + '@1x.' + srcParts[1];\n metadata.images[gallery].push({\n regular: BASE_URL + encodeURI(item.Key),\n small: BASE_URL + encodeURI(small) \n });\n }\n });\n\n // console.log(\">>> Metadata.images\", metadata.images);\n }\n\n done();\n });\n}", "function loadStudies(values) {\n\trequire([\"dojo/ready\", \"dijit/form/MultiSelect\", \"dijit/form/Button\", \"dojo/dom\", \"dojo/_base/window\"], function(ready, MultiSelect, Button, dom, win){\n\t\tready(function(){\n\t\t\tif (studiesMultiSelect != null) studiesMultiSelect.destroyRecursive(true);\n\t\t\tselStudies = dom.byId('selectStudies');\n\t\t\tselStudies.innerHTML = '';\n\t\t\t$.each(values, function(i, val) {\n\t\t\t\tvar c = win.doc.createElement('option');\n\t\t\t\tc.innerHTML = val;\n\t\t\t\tc.value = val;\n\t\t\t\tselStudies.appendChild(c);\n\t\t\t});\n\t\t\tstudiesMultiSelect = new MultiSelect({ name: 'selectStudies', value: '' }, selStudies);\n\t\t\tstudiesMultiSelect.watch('value', function () {\n\t\t\t\tloadDatasets(emptyValue);\n\t\t\t\tloadLibraries(emptyValue);\n\t\t\t\tloadMethods(emptyValue);\n\t\t\t\tloadSites(emptyValue, false);\n\t\t\t\t$('#analysisSpecifications').css('display', 'none');\n\t\t\t\t$('#statusQueryWrapperDiv').css('display', 'none');\n\t\t\t\t$('#queryDiv').css('display', 'none');\n\t\t\t\tvar selValues = studiesMultiSelect.get('value');\n\t\t\t\tif (selValues != null) { \n\t\t\t\t\tif (selValues.length == 1) {\n\t\t\t\t\t\trenderAvailableDatasets();\n\t\t\t\t\t\t$('#continueButton').removeAttr('disabled');\n\t\t\t\t\t} else if (selValues.length > 1) {\n\t\t\t\t\t\tstudiesMultiSelect.set('value', '');\n\t\t\t\t\t\t$('#continueButton').attr('disabled', 'disabled');\n\t\t\t\t\t} else if (selValues.length == 0) {\n\t\t\t\t\t\t$('#continueButton').attr('disabled', 'disabled');\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t\tstudiesMultiSelect.startup();\n\t\t});\n\t});\n}", "function renderAvailableStudies() {\n\t// some clean up\n\t$('#analysisSpecifications').css('display', 'none');\n\t$('#clearResultsDiv').hide();\n\t\n\t// send the request\n\tvar url = HOME + '/query?action=getStudies';\n\tscanner.GET(url, true, postRenderAvailableStudies, null, null, 0);\n}", "function processThings(things) {\n let wikidataLookups = [];\n things.forEach(thing => {\n let wikidataURL = getWikidataURL(thing.urls);\n if (wikidataURL === undefined) {\n // We want a result array that maps against the original query, so\n // we pad it with 'null' values for any unexpectedly missing URLs\n wikidataLookups.push(Promise.resolve(null));\n return;\n }\n\n if (thing.sync === undefined)\n thing.sync = {};\n if (thing.sync.description === undefined) {\n thing.sync.description = {\n active: true,\n source: 'wikidata'\n };\n }\n wikidataLookups.push(limit(() => wikidata.lookup(wikidataURL)));\n });\n Promise\n .all(wikidataLookups)\n .then(wikidataResults => {\n let thingUpdates = [];\n\n things.forEach((thing, index) => {\n\n let syncActive = thing.sync && thing.sync.description && thing.sync.description.active,\n hasDescription = wikidataResults[index] &&\n wikidataResults[index].data && wikidataResults[index].data.description;\n\n if (syncActive && hasDescription) {\n thing.description = wikidataResults[index].data.description;\n thing.sync.description.updated = new Date();\n thing.sync.description.source = 'wikidata';\n thingUpdates.push(thing.save());\n }\n });\n Promise\n .all(thingUpdates)\n .then(updatedThings => {\n console.log(`Sync complete. ${updatedThings.length} items updated.`);\n console.log(`Updating search index now.`);\n Promise\n .all(updatedThings.map(search.indexThing))\n .then(() => {\n console.log('Search index updated.');\n process.exit();\n })\n .catch(error => {\n console.log('Problem updating search index. The error was:');\n console.log(error);\n process.exit(1);\n });\n })\n .catch(error => {\n console.log('Problem performing updates. The error was:');\n console.log(error);\n process.exit(1);\n });\n })\n .catch(error => {\n console.log('Problem performing lookups for sync. The error was:');\n console.log(error);\n process.exit(1);\n });\n\n}", "function showHumans(selectHumans){\n return new Promise(function(resolve, reject){\n db.pool.query(selectHumans, function(err, rows){\n\n if(err){\n next(err);\n return;\n }\n \n // populate page_data with Humans, where each human is the data from the \"rows\" result of the query\n human_page_data.humans = [];\n for (row in rows) {\n human = {};\n \n human.encounterID = rows[row].encounterID;\n human.firstName = rows[row].firstName;\n human.lastName = rows[row].lastName;\n human.birthday = rows[row].birthday;\n \n human_page_data.humans.push(human);\n }\n resolve(console.log(\"Humans found\"));\n });\n \n });\n }", "function loadTrackUris(trackDatas, callback) {\r\n var total = trackDatas.length;\r\n var trackUris = new Array(trackDatas.length);\r\n var completed = 0;\r\n\r\n function doSearch(index, trackData) {\r\n var url = \"http://api.spotify.com/v1/search\";\r\n var artistName = trackData['artistName'];\r\n var trackName = trackData['trackName'];\r\n $.ajax(url, {\r\n data: {\r\n 'q': 'artist:\"' + artistName + '\"+' + 'track:\"' + trackName + '\"',\r\n 'type': 'track'\r\n },\r\n success: function (data) {\r\n console.log(data);\r\n var items = data.tracks.items;\r\n trackUris[index] = items.length > 0 ? items[0].uri : \"\";\r\n },\r\n error: console.log,\r\n complete: function () {\r\n complete(index);\r\n }\r\n });\r\n }\r\n\r\n function complete(index) {\r\n if (trackUris[index] === undefined) {\r\n trackUris[index] = \"\";\r\n }\r\n completed++;\r\n console.log('Finished ' + completed + '/' + total);\r\n if (total === completed) {\r\n callback(trackUris.filter(function(trackUri) {\r\n return trackUri !== undefined && trackUri.length != 0;\r\n }));\r\n }\r\n }\r\n\r\n trackDatas.each(doSearch);\r\n }", "function getPlaylistMetaData(opts, callback) {\n debug('fn: getPlaylistMetaData');\n var listId;\n\n if (typeof opts === 'string') {\n listId = opts;\n }\n\n if (_typeof(opts) === 'object') {\n listId = opts.listId || opts.playlistId;\n }\n\n var _opts$hl2 = opts.hl,\n hl = _opts$hl2 === void 0 ? 'en' : _opts$hl2,\n _opts$gl2 = opts.gl,\n gl = _opts$gl2 === void 0 ? 'US' : _opts$gl2;\n var uri = \"https://www.youtube.com/playlist?hl=\".concat(hl, \"&gl=\").concat(gl, \"&list=\").concat(listId);\n\n var params = _url.parse(uri);\n\n params.headers = {\n 'user-agent': _userAgent,\n 'accept': 'text/html',\n 'accept-encoding': 'gzip',\n 'accept-language': \"\".concat(hl, \"-\").concat(gl)\n };\n\n _dasu.req(params, function (err, res, body) {\n if (err) {\n callback(err);\n } else {\n if (res.status !== 200) {\n return callback('http status: ' + res.status);\n }\n\n if (_debugging) {\n var fs = require('fs');\n\n var path = require('path');\n\n fs.writeFileSync('dasu.response', res.responseText, 'utf8');\n }\n\n try {\n _parsePlaylistInitialData(body, callback);\n } catch (err) {\n callback(err);\n }\n }\n });\n}", "async function fetchInfo(specs, options) {\n if (!specs || specs.find(spec => !spec.shortname || !spec.url)) {\n throw \"Invalid list of specifications passed as parameter\";\n }\n\n options = Object.assign({}, options);\n options.timeout = options.timeout || 30000;\n\n // Compute information from W3C API\n let remainingSpecs = specs;\n const w3cInfo = await fetchInfoFromW3CApi(remainingSpecs, options);\n\n // Compute information from Specref for remaining specs\n remainingSpecs = remainingSpecs.filter(spec => !w3cInfo[spec.shortname]);\n const specrefInfo = await fetchInfoFromSpecref(remainingSpecs, options);\n\n // Extract information directly from the spec for remaining specs\n remainingSpecs = remainingSpecs.filter(spec => !specrefInfo[spec.shortname]);\n const specInfo = await fetchInfoFromSpecs(remainingSpecs, options);\n\n // Merge results\n const results = {};\n specs.map(spec => spec.shortname).forEach(name => results[name] =\n (w3cInfo[name] ? Object.assign(w3cInfo[name], { source: \"w3c\" }) : null) ||\n (specrefInfo[name] ? Object.assign(specrefInfo[name], { source: \"specref\" }) : null) ||\n (specInfo[name] ? Object.assign(specInfo[name], { source: \"spec\" }) : null));\n\n // Add series info from W3C API\n results.__series = w3cInfo.__series;\n\n return results;\n}", "function fetchData() {\n // Wait for any ongoing sync to finish. We won't sync a SCORM while it's being played.\n return $mmaModScormSync.waitForSync(scorm.id).then(function() {\n // Get attempts data.\n return $mmaModScorm.getAttemptCount(scorm.id).then(function(attemptsData) {\n return determineAttemptAndMode(attemptsData).then(function() {\n // Fetch TOC and get user data.\n var promises = [];\n promises.push(fetchToc());\n promises.push($mmaModScorm.getScormUserData(scorm.id, attempt, offline).then(function(data) {\n userData = data;\n }));\n\n return $q.all(promises);\n });\n }).catch(showError);\n });\n }", "function getMostPopularShared() {\n var url = 'https://api.nytimes.com/svc/mostpopular/v2/mostshared/Magazine/7.json';\n let params = {\n q: 'query',\n 'api-key': '85b2939e3df349dd8502775e8623d350'\n }\n url += '?' + $.param(params)\n $.ajax({\n url: url,\n method: 'GET',\n }).done(function(data) {\n console.log(data);\n\n // Define which results will be displayed and display them\n for (var i = 0; i < 5; i++) {\n var title = data.results[i].title;\n $('.shared').show();\n var article_url = data.results[i].url;\n var abstract = data.results[i].abstract;\n\n // Use bracket notation for media-metadata\n var image = data.results[i].media[0]['media-metadata'][0].url;\n console.log(image);\n \n // Display results in HTML\n $('#results').append(\"<li><h3>\" + title + \n \"</h3>\" + abstract + \"<br><br>\" + \"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a></li>\");\n $('#summary-shared').append(\"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a>\");\n } \n }).fail(function(err) {\n throw err;\n });\n }", "function getArtists(id) {\n var access_token = getAccessToken();\n fetch('https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=10', {\n headers: {\n 'Authorization': 'Bearer ' + access_token\n }\n }).then(res => res.json()).then(data => {\n console.log(\"artist data\");\n console.log(data);\n getTracks(id, data)\n })\n}", "function searchStudies(userAccessToken, inputDataObject) {\n\n //null selected study\n selectedStudy = null;\n\n /* PARAMS\n patientBirthday:\n patientFirstName:\n toDate:\n patientLastName:\n patientId:101050\n accession:\n companyDomain:bmi.qubs.com\n from:0\n fromDate:\n size:10\n studyDescription:\n */\n\n var params = {\n patientId: 101050,\n companyDomain: \"bmi.qubs.com\",\n from: 0,\n size: 10\n };\n //var paramStr = jQuery.param(params);\n var paramStr = jQuery.param(inputDataObject);\n\n console.log(\"Input object\",paramStr);\n $(\"#patients-table tr\").remove();\n\n var loaderIndicator = document.getElementById(\"patients-loading-indicator\");\n var patientsListTable = document.getElementById(\"patients-table\");\n //var noSearchResultsState = document.getElementById(\"noSearchResultsState\");\n\n //show loading indicator\n loaderIndicator.style.display = \"block\"\n\n\n var xhr = new XMLHttpRequest();\n xhr.withCredentials = false;\n\n xhr.addEventListener(\"readystatechange\", function () {\n\n if (this.readyState === 4) {\n loaderIndicator.style.display = \"none\"\n\n if (xhr.status == 200) {\n showTableEmptyStates(false);\n studyListData = JSON.parse(this.responseText);\n total_count = studyListData.total;\n var showcount = Math.ceil(total_count / size)\n\n console.log(showcount);\n addpager(total_count, pagenum);\n studyListData.items.forEach(function (study) {\n addStudyToTable(study);\n\n });\n } else {\n var study = null;\n showSideBarEmptyStates(true);\n showTableEmptyStates(true);\n }\n\n }\n });\n\n //support for shared studies\n var publicToken = getParameterByName(\"token\");\n var accessionNo = getParameterByName(\"a\");\n var companyDomain = getParameterByName(\"d\");\n\n\n\n if (accessionNo != null) {\n xhr.open(\"POST\", api_studies_url); //secure api\n xhr.setRequestHeader(\"content-type\", \"application/json\");\n xhr.setRequestHeader(\"authorization\", userAccessToken);\n\n var searchParams = JSON.stringify({\n \"accessionNumber\": accessionNo,\n \"companyDomain\": companyDomain\n });\n\n xhr.send(searchParams);\n\n } else if (publicToken != null) {\n xhr.open(\"POST\", api_public_studies_url); //public api\n xhr.setRequestHeader(\"content-type\", \"application/json\");\n var publicTokenJson = JSON.stringify({\n \"publicToken\": publicToken\n });\n xhr.send(publicTokenJson);\n\n } else {\n xhr.open(\"GET\", api_studies_url + \"?\" + paramStr); //secure api\n xhr.setRequestHeader(\"content-type\", \"application/json\");\n xhr.setRequestHeader(\"authorization\", userAccessToken);\n xhr.send(null);\n }\n \n\n //Adding the pagnation \n function addpager(total_count, pagenum){\n console.log(pagenum);\n pagenum = pagenum;\n var pager = jQuery('.pager');\n var prev = jQuery('<a href=\"#\" onclick=\"newsearch('+(pagenum-1)+')\" class=\"prev disabled\"><i class=\"icon-arrow-left\"></i></a>').appendTo(pager);\n var ul = jQuery('<ul></ul>').appendTo(pager);\n\n var show_num = Math.ceil(total_count / size);\n var li = '';\n\n\n //\n var first_page = 0;\n var last_page;\n if (pagenum <= show_page_count){\n first_page = 0;\n if(show_num < show_page_count){\n last_page = show_num;\n }else{\n last_page = show_page_count;\n }\n \n }else if(pagenum > show_page_count){\n first_page = Math.floor((pagenum-1)/show_page_count) * show_page_count ;\n last_page = first_page + show_page_count;\n }\n\n for(var i = first_page; i<last_page ; i++){\n li += '<li class=\"'+(((i+1)==pagenum)?\"active\":\"\")+'\"><a href=\"#\" onclick=\"newsearch('+(i+1)+')\" >'+ (i+1) +'</a></li>';\n }\n jQuery(li).appendTo(ul);\n var next = jQuery('<a href=\"#\" class=\"next\" onclick=\"newsearch('+(pagenum+1)+')\"><i class=\"icon-arrow-right\"></i></a>').appendTo(pager);\n if(pagenum==1){\n pager.find(\".prev\").addClass(\"disabled\");\n pager.find(\".next\").removeClass(\"disabled\");\n }\n if(pagenum != 1 && pagenum!= show_num){\n pager.find(\".prev\").removeClass(\"disabled\");\n pager.find(\".next\").removeClass(\"disabled\");\n }\n if(pagenum==show_num){\n pager.find(\".prev\").removeClass(\"disabled\");\n pager.find(\".next\").addClass(\"disabled\");\n }\n \n }\n\n //Adding the study Table\n function addStudyToTable(studyItem) {\n\n var study = null;\n showSideBarEmptyStates(true);\n\n\n //check if item is assignedstudy or just study\n if (checkNested(studyItem, \"elasticId\")) {\n study = studyItem.study;\n } else {\n study = studyItem;\n }\n\n var canDeleteStudies = false;\n var canShareStudies = false;\n var canTransferToWAHStudies = false;\n\n /*\n if (userPermissionsData != null) {\n\n userPermissionsData.Items.forEach(function(permission) {\n\n\n if (permission.companyDomain === study.companyDomain) {\n\n if (permission.shareStudies == true) {\n canShareStudies = true;\n }\n\n if (permission.deleteStudies == true) {\n canDeleteStudies = true;\n }\n\n if (permission.transferToWAH == true) {\n canTransferToWAHStudies = true;\n }\n\n }\n\n\n\n }, this);\n\n\n }\n */\n\n /*\n <td data-title=\"Patient Name\"><span class=\"txt\"><a href=\"#\">John Doe</a></span></td>\n <td data-title=\"Patient ID\"><span class=\"txt\">109886</span></td>\n <td data-title=\"Birthdate\"><span class=\"txt\"><time datetime=\"2017-05-11\">18/11/1985</time></span></td>\n <td data-title=\"Descriptions\"><span class=\"txt\">US Pelvis</span></td>\n <td data-title=\"Accession\"><span class=\"txt\">333001</span></td>\n <td data-title=\"Date\"><span class=\"txt\"><time datetime=\"2017-05-11\">21/03/2017</time></span></td>\n <td data-title=\"Modality\"><span class=\"txt\">US</span></td>\n <td data-title=\"Images\"><span class=\"txt\">35</span></td>\n */\n\n var studyRow = document.createElement('tr');\n\n var patientNameRow = document.createElement('td');\n patientNameRow.setAttribute(\"data-title\", \"Patient Name\");\n patientNameRow.innerHTML = '<span class=\"txt\">' + study.patientLastName + \" \" + study.patientFirstName + '</span>';\n\n var patientIdRow = document.createElement('td');\n patientIdRow.setAttribute(\"data-title\", \"Patient ID\");\n patientIdRow.innerHTML = '<span class=\"txt\">' + study.patientId + '</span>';\n\n\n var patientBirthDateRow = document.createElement('td');\n patientBirthDateRow.setAttribute(\"data-title\", \"Birthdate\");\n \n var birthdate = study.patientBirthDate;\n var b_year = birthdate.substring(0,4);\n var b_month = birthdate.substring(4,6);\n var b_date = birthdate.substring(6,8);\n\n var birthdateFormat = b_date + \"/\" + b_month + \"/\" + b_year;\n\n // patientBirthDateRow.innerHTML = '<span class=\"txt\"><time datetime=\"' + study.patientBirthDate + '\">' + study.patientBirthDate + '</time></span>';\n \n patientBirthDateRow.innerHTML = '<span class=\"txt\"><time datetime=\"' + birthdateFormat + '\">' + birthdateFormat + '</time></span>';\n //patientBirthDateRow.innerHTML = '<span class=\"txt\"><time datetime=\"' + study.studyDate + '\">' + study.studyDate + '</time></span>';\n var studyDescriptionRow = document.createElement('td');\n studyDescriptionRow.setAttribute(\"data-title\", \"Descriptions\");\n if (checkNested(study, \"studyDescription\")) {\n studyDescriptionRow.innerHTML = '<span class=\"txt\">' + study.studyDescription + '</span>';\n } else {\n studyDescriptionRow.innerHTML = '<span class=\"txt\"></span>';\n }\n\n\n\n\n var accessionRow = document.createElement('td');\n accessionRow.setAttribute(\"data-title\", \"Accession\");\n accessionRow.innerHTML = '<span class=\"txt\">' + study.accessionNumber + '</span>';\n\n var studyDateRow = document.createElement('td');\n studyDateRow.setAttribute(\"data-title\", \"Date\");\n //studyDateRow.innerHTML = '<span class=\"txt\"><time datetime=\"2017-05-11\">21/03/2017</time></span></td>';\n studyDateRow.innerHTML = '<span class=\"txt\"><time datetime=\"' + study.studyDateFormatted + '\">' + study.studyDateFormatted + '</time></span>';\n\n var modalityRow = document.createElement('td');\n modalityRow.setAttribute(\"data-title\", \"Modality\");\n modalityRow.innerHTML = '<span class=\"txt\">' + study.modality + '</span>';\n\n var numImagesRow = document.createElement('td');\n numImagesRow.setAttribute(\"data-title\", \"Images\");\n numImagesRow.innerHTML = '<span class=\"txt\">' + study.instanceCount + '</span>';\n\n studyRow.appendChild(patientNameRow);\n studyRow.appendChild(patientIdRow);\n studyRow.appendChild(patientBirthDateRow);\n studyRow.appendChild(studyDescriptionRow);\n studyRow.appendChild(accessionRow);\n studyRow.appendChild(studyDateRow);\n studyRow.appendChild(modalityRow);\n studyRow.appendChild(numImagesRow);\n\n // Append the row to the study list\n var studyRowElement = $(studyRow).appendTo('#patients-table');\n\n $(studyRowElement).click(function (event) {\n if (event.target.cellIndex !== 18 && event.target.cellIndex !== undefined) {\n $(\"#patients-table tr\").removeClass('row-highlight');\n studyRowElement.addClass(\"row-highlight\");\n \n loadSidebar(study);\n console.log(\"STUDY\",study.companyLogo);\n }\n });\n\n $(studyRowElement).dblclick(function (event) {\n if (event.target.cellIndex !== 18 && event.target.cellIndex !== undefined) {\n $('body').addClass('img-opened');\n $(\"#patients-table tr\").removeClass('row-highlight');\n studyRowElement.addClass(\"row-highlight\");\n \n runWithAccessToken(study, openStudyForViewing);\n\n }\n });\n\n function loadSidebar(study) {\n //set selected study\n selectedStudy = study;\n\n console.log(study.qubsStudyInstanceUid);\n //get history\n runWithAccessToken(study.patientId, getPatientHistory);\n runWithAccessToken(study.qubsStudyInstanceUid, getAppointmentDetails);\n\n\n\n setupSideBarButtons(study);\n showSideBarEmptyStates(false);\n document.getElementById(\"company-name\").innerHTML = '<a target=\"_blank\" href=\"' + study.website + '\" >' + study.company + '</a>';;\n document.getElementById(\"imageCount\").innerHTML = study.instanceCount;\n\n var patientSex = \"\";\n if (checkNested(study, \"patientSex\")) {\n patientSex = study.patientSex;\n }\n\n var age = \"\";\n if (checkNested(study, \"age\")) {\n age = study.age;\n }\n\n document.getElementById(\"patient-name\").innerHTML = study.patientFirstName + \" \" + study.patientLastName +\n '<span class=\"age\" >(' + age + 'y ' + patientSex + ')</span>';\n\n document.getElementById(\"email\").innerHTML = study.email;\n\n var phoneNumber = study.phone.replace(/\\s/g, '');\n document.getElementById(\"phone\").innerHTML = '<a class=\"tel\" href=\"tel:' + phoneNumber + '\">' + study.phone + '</a>';\n\n\n //\n function holder_reset(){\n $('body').removeClass('img-opened');\n\n var holder = jQuery('#content');\n\n var refferal_result = holder.find('.refferal-result');\n if (refferal_result.length) {\n refferal_result.remove();\n }\n var report_result = holder.find('.report-result');\n if (report_result.length) {\n report_result.remove();\n }\n\n if($(\"#content .patient-list\").css('display')=='block'){\n $(\"#content .patient-list\").css('display','none');\n }\n\n if($(\"#content .report-nav\").css('display')=='block'){\n $(\"#content .report-nav\").remove();\n }\n\n if($(\"#content .result.report\").css('display')=='block'){\n $(\"#content .result.report\").remove();\n }\n\n if($(\"#content .refferal-result\").css('display')=='block'){\n $(\"#content .refferal-result\").remove();\n }\n }\n\n function setupSideBarButtons(study) {\n\n //remove previous events\n $('#study-report').off('click touchstart');\n $('#study-images').off('click touchstart');\n $('#study-download').off('click touchstart');\n $('#study-share').off('click touchstart');\n $('#study-activity').off('click touchstart');\n $('#study-manage').off('click touchstart');\n $('#study-referral').off('click touchstart');\n $('#study-attachments').off('click touchstart');\n\n\n $(\"#study-report\").on('click touchstart', function () {\n holder_reset();\n //$('body').addClass('refferal-opened');\n // runWithAccessToken(study.qubsStudyInstanceUid, getReport);\n runWithAccessToken(study, getReport);\n \n });\n\n $(\"#study-images\").on('click touchstart', function () {\n holder_reset();\n $('body').addClass('img-opened');\n runWithAccessToken(study, openStudyForViewing);\n });\n\n\n $(\"#study-download\").on('click touchstart', function () {\n runWithAccessToken(study, downloadZip);\n });\n\n $('#study-share').fancybox({\n helpers: {\n overlay: {\n css: {\n background: 'rgba(0, 0, 0, 0.65)'\n }\n }\n },\n afterLoad: function(current, previous) {\n // handle custom close button in inline modal\n if(current.href.indexOf('#') === 0) {\n jQuery(current.href).find('a.close').off('click.fb').on('click.fb', function(e){\n e.preventDefault();\n jQuery.fancybox.close();\n });\n }\n },\n href: '#notification-popup'\n });\n\n $(\"#study-activity\").on('click touchstart', function () {\n\n });\n\n $(\"#study-manage\").on('click touchstart', function () {\n\n });\n\n $(\"#study-referral\").on('click touchstart', function () {\n holder_reset();\n runWithAccessToken(study, getReferrals);\n // runWithAccessToken(study.qubsStudyInstanceUid, getReferrals);\n \n\n // $('body').addClass('img-opened');\n });\n\n $(\"#study-attachments\").on('click touchstart', function () {\n\n });\n\n }\n\n\n }\n }\n}", "function callStackAPI() {\n $.ajax({\n url: urlStack,\n method: \"GET\"\n }).then(function (response) {\n for (var i = 0; i < 5; i++) {\n var qstnObject = {};\n var keywordURL = \"\";\n var keywordTitle = \"\";\n qstnObject.keywordURL = response.items[i].link;\n qstnObject.keywordTitle = response.items[i].title;\n questionsArray.push(qstnObject);\n }\n showQuestions(questionsArray);\n })\n}", "function track_api(page) {\n let fmaWsUrl = `https://freemusicarchive.org/api/get/tracks.json?api_key=${FMA_API}&album_id=${\n release_attributes.albumid\n }&limit=20&page=${parseInt(page)}`;\n\n var promise_track_api = $.getJSON(fmaWsUrl, function () {\n LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api.state()}`);\n }).done(function (tracksjson) {\n LOGGER.debug(` >> Track page ${page} > DONE `);\n LOGGER.debug(tracksjson);\n tracks_api_array.push(tracksjson.dataset);\n });\n\n return promise_track_api.promise();\n}", "function addMetaData(container, callback) {\n $('[data-id]', container).each(function (i, row) {\n var $item, model, id, data;\n\n $item = $(row);\n model = $item.attr('data-class');\n id = $item.attr('data-id');\n\n if (metaData && metaData[model] && metaData[model][id]) {\n data = metaData[model][id];\n appendMetaData(row, model, id, data);\n }\n });\n\n if (callback) {\n callback();\n }\n }", "async function getLyrics(array) {\n let allRequests = [];\n array.forEach((trackEntry) => {\n allRequests.push(\n axios(\n `${baseURL}${lyricsSearch}track_id=${trackEntry.trackId}&${apiKey}`\n ).then((response) => {\n return {\n artist: joinedArtistNameForFileName,\n trackName: trackEntry.trackName,\n trackId: trackEntry.trackId,\n lyrics: response.data.message.body.lyrics.lyrics_body,\n };\n })\n );\n });\n let lyricsArray = Promise.all(allRequests);\n return lyricsArray;\n}", "function getSongs(Query) {\n var spotify = new Spotify(LiriTwitterBOT.spotify);\n if (!Query) {\n Query = \"what's+my+age+again\";\n };\n spotify.search({ type: 'track', query: Query }, function(err, data) {\n if ( err ) {\n console.log('Error occurred: ' + err);\n return;\n }\n console.log(data);\n // Do something with 'data' \n });\n\n // var queryURL = 'https://api.spotfiy.com/v1/search?q=' + query + '&limit=5&type=track';\n // request(queryURL, function(err, response, body) {\n // if (err) {\n // console.log(err);\n // };\n // body = JSON.parse(body);\n // console.log(body);\n // for (var i = 0; i < body.tracks.items.length; i++) {\n // logObject = input + \", \" + query + \", \" + body.tracks.items[i].artists[0].name + \", \" + body.tracks.items[i].name\n // body.tracks.items[i].name + \", \" + body.tracks.items[i].preview_url + \", \" + body.tracks.items[i].album.name + \"\\n\";\n // }; //end of loop\n // writeLog(logObject);\n // });\n}", "function getVideoMetaData(opts, callback) {\n debug('fn: getVideoMetaData');\n var videoId;\n\n if (typeof opts === 'string') {\n videoId = opts;\n }\n\n if (_typeof(opts) === 'object') {\n videoId = opts.videoId;\n }\n\n var _opts$hl = opts.hl,\n hl = _opts$hl === void 0 ? 'en' : _opts$hl,\n _opts$gl = opts.gl,\n gl = _opts$gl === void 0 ? 'US' : _opts$gl;\n var uri = \"https://www.youtube.com/watch?hl=\".concat(hl, \"&gl=\").concat(gl, \"&v=\").concat(videoId);\n\n var params = _url.parse(uri);\n\n params.headers = {\n 'user-agent': _userAgent,\n 'accept': 'text/html',\n 'accept-encoding': 'gzip',\n 'accept-language': \"\".concat(hl, \"-\").concat(gl)\n };\n params.headers['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15';\n\n _dasu.req(params, function (err, res, body) {\n if (err) {\n callback(err);\n } else {\n if (res.status !== 200) {\n return callback('http status: ' + res.status);\n }\n\n if (_debugging) {\n var fs = require('fs');\n\n var path = require('path');\n\n fs.writeFileSync('dasu.response', res.responseText, 'utf8');\n }\n\n try {\n _parseVideoInitialData(body, callback);\n } catch (err) {\n callback(err);\n }\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the profile of other users
function showOtherUser(){ removeFollowList(); removeSearchArea(); var userId = this.dataset.user; // get the user of the clicked name or image showedUser = userId; removeWritenFields(); removeErrorSuccesFields(); document.getElementById("profileSection").style.display = "block"; document.getElementById("messagesSection").style.display = "none"; hideAllProfileSection(); document.getElementById("showProfile").style.display = "block"; getOtherProfile(userId); }
[ "static displayProfiles() {\r\n const profiles = Store.getProfiles();\r\n profiles.forEach((profile) => {\r\n\r\n // If the profile doesn't exist add it to the list\r\n if (!Store.profileExists(profile)) {\r\n Profile.addProfileToList(profile);\r\n }\r\n // Otherwise, if the object has been changed, \r\n //remove the previous element from the list and add updated\r\n else if (changed) {\r\n const list = document.querySelector('#profileList');\r\n list.removeChild(list.lastChild);\r\n Profile.addProfileToList(profile);\r\n }\r\n });\r\n }", "function generateUserProfile() {\n // Populate the user information in profile section\n $(\"#profile-name\").append(` ${currentUser.name}`);\n $(\"#profile-username\").append(` ${currentUser.username}`);\n $(\"#profile-account-date\").append(` ${currentUser.createdAt.slice(0, 10)}`);\n\n // Display user's name in nav welcome area\n $navUserProfile.append(`${currentUser.username}`);\n }", "_onProfileBtnClick() {\n // toggle the visibility of authedUser component\n this._componenets.authedUser.hidden = !this._componenets.authedUser.hidden\n }", "function displayUsername() {\n $navWelcome.children('#nav-user-profile').text(currentUser.username);\n $navWelcome.show();\n }", "function fillUserProfile() {\n if (!currentUser) return null;\n\n $('#user-profile section')\n .children('#profile-name')\n .append(' ' + currentUser.name);\n\n $('#user-profile section')\n .children('#profile-username')\n .append(' ' + currentUser.username);\n\n const date = convertDate(currentUser.createdAt);\n\n $('#user-profile section')\n .children('#profile-account-date')\n .append(' ' + date);\n }", "function getAdminProfile() {\n FYSCloud.API.queryDatabase(\n \"SELECT * FROM profile WHERE user_id = ?\",\n [admin[0].user_id]\n\n ).done(function(adminDetails) {\n admin = adminDetails[0];\n // check if there is an avatar\n if(admin.avatar !== null) {\n $('#navbarAvatar').attr('src', admin.avatar);\n }\n }).fail(function(reason) {\n console.log(reason);\n });\n }", "get userProfile() {\n return spPost(ProfileLoaderFactory(this, \"getuserprofile\"));\n }", "function showUserProfile(myId) {\r\n if (myId < 1) { \r\n return false; \r\n } else {\r\n clearDiv(\"recordView\");\r\n var myURL = \"UsersProfileView.php?U=\" + myId;\r\n processAjax (myURL, \"recordView\");\r\n setBlockVis(\"recordView\", \"block\");\r\n return true;\r\n }\r\n}", "get ownerUserProfile() {\n return spPost(this.getParent(ProfileLoaderFactory, \"_api/sp.userprofiles.profileloader.getowneruserprofile\"));\n }", "function showIcon() {\n const user = User.getUser();\n const profileImage = [...document.getElementsByClassName('user-image')];\n profileImage.forEach((element) => {\n element.style.backgroundImage = `url(${ROOT}/${user.profile})`;\n });\n document.getElementById('userName').innerHTML = `${user.firstname} ${user.othernames} ${user.lastname}`;\n document.getElementById('userEmail').innerHTML = user.email;\n document.getElementById('userFirstName').innerHTML = user.firstname;\n}", "function getUsers(data){\n users = JSON.parse(data).results;\n if(currentView == USERS_VIEW)\n renderUsers();\n}", "renderUserFavoriteMoveForProfile(profile) {\n let users = this.props.users\n let movies = this.props.movies\n return <li\n key={profile.id}>{`${users[profile.userID].name}\\'s favorite movie is \"${movies[profile.favoriteMovieID].name}.\"`}</li>\n }", "function userProfilePage() {\n log('user profile page')\n\n let $userLink = document.querySelector('a.hnuser')\n if ($userLink == null) {\n log('not a valid user')\n return\n }\n\n let userId = $userLink.innerText\n let $currentUserLink = document.querySelector('a#me')\n let currentUser = $currentUserLink ? $currentUserLink.innerText : ''\n let ignoredUsers = getIgnoredUsers()\n let $tbody = $userLink.closest('table').querySelector('tbody')\n\n if (userId == currentUser) {\n let first = 0\n ignoredUsers.forEach((ignoredUserId) => {\n $tbody.appendChild(\n h('tr', null,\n h('td', {valign: 'top'}, first++ == 0 ? 'blocked:' : ''),\n h('td', null,\n h('a', {href: `/user?id=${ignoredUserId}`}, ignoredUserId),\n h('a', {\n href: '#',\n onClick: function(e) {\n e.preventDefault()\n if (ignoredUsers.has(ignoredUserId)) {\n ignoredUsers.delete(ignoredUserId)\n this.firstElementChild.innerText = 'block'\n }\n else {\n ignoredUsers.add(ignoredUserId)\n this.firstElementChild.innerText = 'unblock'\n }\n setIgnoredUsers(ignoredUsers)\n }\n },\n ' (', h('u', null, 'unblock'), ')'\n )\n )\n )\n )\n })\n }\n else {\n $tbody.appendChild(\n h('tr', null,\n h('td'),\n h('td', null,\n h('a', {\n href: '#',\n onClick: function(e) {\n e.preventDefault()\n if (ignoredUsers.has(userId)) {\n ignoredUsers.delete(userId)\n this.firstElementChild.innerText = 'block'\n }\n else {\n ignoredUsers.add(userId)\n this.firstElementChild.innerText = 'unblock'\n }\n setIgnoredUsers(ignoredUsers)\n }\n },\n h('u', null, ignoredUsers.has(userId) ? 'unblock' : 'block')\n )\n )\n )\n )\n }\n}", "function toggleProfileView() {\n var profileContainer = _$('.profile-container')\n var profileEditor = _$('.profile-editor')\n profileContainer.classList.toggle('d-none')\n profileContainer.classList.toggle('d-inline')\n profileEditor.classList.toggle('d-none')\n profileEditor.classList.toggle('d-inline')\n}", "function renderProfileData(url) {\n axios.get(url)\n .then((res) => {\n const starsURL = `https://api.github.com/users/${res.data.login}/starred`;\n userInfo = res.data;\n username = userInfo.login;\n getProfileStars(starsURL);\n });\n}", "function loadUserProfile(targetUserData) {\n console.log(targetUserData);\n name.text(targetUserData.name);\n name.attr('style', 'color: black;')\n age.text(targetUserData.age);\n gender.text(targetUserData.gender);\n joined.text(targetUserData.joined);\n hikes.text(targetUserData.hikes);\n rep.text(targetUserData.rep);\n addBadge(targetUserData);\n bio.text(targetUserData.bio);\n bio.attr('style', \"color: black;\")\n addTags(targetUserData);\n emptyLinks(targetUserData);\n}", "function bindNameAndImagesToProfile(){\n var userPics = document.getElementsByClassName(\"userImage\");\n var userPseudoName = document.getElementsByClassName(\"pseudoName\");\n\n for(var x = 0; x < userPics.length; x++){\n // update the image of the user\n userPics[x].src = \"services/getAvatar.php?userId=\" + userPics[x].dataset.user + \"&size=small\"\n + \"&random=\"+new Date().getTime();\n // add event listener for click\n userPics[x].addEventListener(\"click\", showOtherUser);\n }\n\n for(var x = 0; x < userPseudoName.length; x++){\n userPseudoName[x].addEventListener(\"click\", showOtherUser);\n }\n unbindShowProfileUserShowOptions(); // unbind the click on the author in choise list\n}", "function getProfile(direction) {\n var i = currentProfileIndex;\n switch (direction) {\n case \"next\":\n if (i + 1 < profiles.length) { // Check that profile is not out-of-bounds\n retrieveProfile(i + 1);\n } else {\n retrieveProfile(i); // Refresh the user's profile\n };\n break;\n case \"previous\":\n if (i - 1 >= 0) { // Check that profile is not out-of-bounds\n retrieveProfile(i - 1);\n } else {\n retrieveProfile(i); // Refresh the user's profile\n };\n break;\n }\n}", "function updateProfileOptions(currentProfile) {\n // show profile specific route options\n var i, el;\n for (var profile in list.showElements) {\n if (currentProfile == profile) {\n for (i = 0; i < list.showElements[profile].show.length; i++) {\n el = $(list.showElements[profile].show[i]);\n el.show();\n }\n for (i = 0; i < list.showElements[profile].hide.length; i++) {\n el = $(list.showElements[profile].hide[i]);\n el.hide();\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new Color4 copied from the current one
clone() { return new Color4(this.r, this.g, this.b, this.a); }
[ "function Color4(/**\n * Defines the red component (between 0 and 1, default is 0)\n */r,/**\n * Defines the green component (between 0 and 1, default is 0)\n */g,/**\n * Defines the blue component (between 0 and 1, default is 0)\n */b,/**\n * Defines the alpha component (between 0 and 1, default is 1)\n */a){if(r===void 0){r=0;}if(g===void 0){g=0;}if(b===void 0){b=0;}if(a===void 0){a=1;}this.r=r;this.g=g;this.b=b;this.a=a;}// Operators", "toColor4(alpha = 1) {\n return new Color4_1.Color4(this.r, this.g, this.b, alpha);\n }", "toLinearSpace() {\n const convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n }", "static Red() {\n return new Color4(1.0, 0, 0, 1.0);\n }", "static Purple() {\n return new Color4(0.5, 0, 0.5, 1);\n }", "static Green() {\n return new Color4(0, 1.0, 0, 1.0);\n }", "static Clear() {\n return new Color4(0, 0, 0, 0);\n }", "static White() {\n return new Color4(1, 1, 1, 1);\n }", "static Yellow() {\n return new Color4(1, 1, 0, 1);\n }", "multiply(color) {\n return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);\n }", "function currentColor() {\n\treturn new Color({red: color.red, green: color.green, blue: color.blue})\n}", "static Red() {\n return new Color3(1, 0, 0);\n }", "static FromArray(array, offset = 0) {\n return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }", "static FromColor3(color3, alpha = 1.0) {\n return new Color4(color3.r, color3.g, color3.b, alpha);\n }", "static Blue() {\n return new Color4(0, 0, 1.0, 1.0);\n }", "static Magenta() {\n return new Color4(1, 0, 1, 1);\n }", "static Black() {\n return new Color4(0, 0, 0, 1);\n }", "static Purple() {\n return new Color3(0.5, 0, 0.5);\n }", "toLinearSpace() {\n const convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper function to describe a token as a string for debugging
function getTokenDesc(token) { var value = token.value; return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind; }
[ "StringLiteral() {\n const token = this._eat(\"STRING\");\n return factory.StringLiteral(token.value.slice(1, -1));\n }", "function maybeQuoteSymbol(symbol) {\n if (symbol.description === undefined) {\n return symbol.toString();\n }\n\n if (/^[a-zA-Z_][a-zA-Z_.0-9]*$/.test(symbol.description)) {\n return symbol.toString();\n }\n\n return `Symbol(${quoteString(symbol.description)})`;\n }", "expandMacroAsText(name) {\n const tokens = this.expandMacro(name);\n\n if (tokens) {\n return tokens.map(token => token.text).join(\"\");\n } else {\n return tokens;\n }\n }", "_completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n\n if (datatype === undefined) return; // No datatype means an error occurred\n\n literal = this._literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n\n case 'langcode':\n literal = this._literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return {\n token,\n literal\n };\n }", "defaultToken(){}", "displaySymbol(symbol) {\n return symbol === '' ? ' ' : symbol;\n }", "function createFieldToken(field){\n \n createFieldToken(field, '', '');\n \n}", "function prettyPrint(term) {\n switch (term.tag) {\n case \"ground\":\n switch (term.type) {\n case \"string\":\n return term.value;\n\n case \"bool\":\n case \"int\":\n return JSON.stringify(term.value)\n\n default:\n throw \"Non-exhaustive pattern match in prettyPrintern ground types: \" + term.type;\n }\n\n case \"send\":\n return \"@\" + prettyPrint(term.chan) + \"!(\" + prettyPrint(term.message) + \")\";\n\n default:\n throw \"Non-exhaustive pattern match in prettyPrint: \" + term.tag;\n }\n}", "function setToken(token_temp) {\n token = token_temp\n}", "getKeywordToken() {\r\n return this.compilerNode.keywordToken;\r\n }", "Identifier() {\n const name = this._eat(\"IDENTIFIER\").value;\n return {\n type: \"Identifier\",\n name,\n };\n }", "function get_variable_display(instrPtr, variableLoc, objData) { \n var varName = variableLoc.name\n var varLoc = variableLoc.value\n\n // resolve structs that are split between registers\n if (objData[varName] && variableLoc.hasOwnProperty('var_offset') && variableLoc['var_offset'] != null) {\n var offset = variableLoc['var_offset'];\n var name = varName + \".\" + objData[varName][offset];\n return name + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\";\n }\n\n // resolve names for xword ptrs\n if (objData[varName] && instrPtr) {\n var reg = instrPtr[0]\n var offset = instrPtr[2] != \"\" ? parseInt(instrPtr[2], 16) : 0;\n if (reg == varLoc && objData[varName][offset]) {\n var sign = offset >= 0 ? \"+\" : \"\";\n var name = varName + \".\" + objData[varName][offset];\n return name + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\" + sign + '0x' + offset.toString(16);\n }\n }\n return varName + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\";\n}", "addToken(token) {\n this.output.push(token);\n }", "function getDrillDownTokenParam(portletId)\r\n\t{\r\n\t\tif (ddt[portletId])\r\n\t\t{\r\n\t\t\tvar type = ddt[portletId].type;\r\n\t\t\tvar value = ddt[portletId].value;\r\n\r\n\t\t\tif (type == TOKEN_ACTIONAL_ID)\r\n\t\t\t{\r\n\t\t\t\treturn '&ddt.li=' + value;\r\n\t\t\t}\r\n\t\t\telse if (type == TOKEN_NAME)\r\n\t\t\t{\r\n\t\t\t\treturn '&ddt.name=' + value;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn '';\r\n\t}", "function generateStringDecl(node)\n\t{\n\t\t// Get the Id object\n\t\tvar idObject = node.children[0].item;\n\n\t\t// No declaration necessary, but we must make a table entry\n\t\tgetReferenceTableKey(idObject);\n\t}", "addToken() {\n\t\t//Do nothing if there is no input.\n\t\tif (!this.newNameField.value) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar newName = this.newNameField.value;\n\n\t\t//Truncate the name.\n\t\twhile (newName.endsWith(\" \")) {\n\t\t\tnewName = newName.substring(0, newName.length - 1);\n\t\t}\n\t\twhile (newName.startsWith(\" \")) {\n\t\t\tnewName = newName.substring(1, newName.length);\n\t\t}\n\n\t\tthis.newNameField.value = \"\";\n\t\tthis.addName(newName);\n\t}", "function identAndHighlightMacro(origin) {\n\n // count the number of slashes before character i in origin\n function countSlashes(i) {\n var count = 0;\n while(count < i && origin.charAt(i-count-1) == '\\\\')\n count++;\n return count;\n }\n\n var len = origin.length;\n var result = \"\";\n var ident= \"\\n\";\n var parenLevel = 0;\n var string = 0; //0 = none 1=\" 2='\n var lineLen = 0;\n\n for (var i = 0; i < len; ++i) {\n var c = origin.charAt(i);\n switch (c) {\n case '>': lineLen++; result+=\"&gt;\"; break;\n case '<': lineLen++; result+=\"&lt;\"; break;\n case '&': lineLen++; result+=\"&amp;\"; break;\n case ')':\n result+=\")\";\n if (!string) {\n parenLevel--;\n if (parenLevel < 0) parenLevel = 0;\n }\n break;\n case '(':\n result+=\"(\";\n if (!string && i > 1)\n parenLevel++;\n break;\n case ';':\n result+=\";\";\n if (parenLevel==0 && !string) {\n result += ident;\n lineLen = 0;\n }\n break;\n case '{':\n result+=\"{\";\n if (parenLevel==0 && !string) {\n ident+=\" \";\n result+=ident;\n lineLen = 0;\n }\n break;\n case '}':\n if (parenLevel==0 && !string) {\n if (lineLen == 0 && ident.length > 2)\n result = result.slice(0, -2)\n result += \"}\";\n ident = ident.slice(0, -2);\n if (i+1 < len && origin.charAt(i+1) != ';') {\n result += ident;\n lineLen = 0;\n }\n } else {\n result+=\"}\";\n }\n break;\n case '\"':\n if (string == 0) {\n result += \"<q>\\\"\"\n string = 1;\n } else if (string == 1 && (countSlashes(i)%2) == 0) {\n string = 0;\n result += \"\\\"</q>\"\n } else {\n result += c;\n }\n break;\n case '\\'':\n if (string == 0) {\n result += \"<kbd>\\'\"\n string = 2;\n } else if (string == 2 && (countSlashes(i)%2) == 0) {\n string = 0;\n result += \"\\'</kbd>\"\n } else {\n result += c;\n }\n break;\n case ' ':\n if (lineLen != 0)\n result += \" \";\n break;\n default:\n lineLen++;\n result+=c;\n break;\n }\n }\n result = result.replace(/\\b(auto|void|int|bool|long|uint|unsigned|signed|char|float|double|volatile|const)\\b/g,\"<em>$1</em>\");\n result = result.replace(/\\b(asm|__attribute__|break|case|catch|class|__finally|__exception|__try|const_cast|continue|copnstexpr|private|public|protected|__declspec|default|delete|deprecated|dllexport|dllimport|do|dynamic_cast|else|enum|explicit|extern|if|for|friend|goto|inline|mutable|naked|namespace|new|noinline|noreturn|nothrow|operator|register|reinterpret_cast|return|selectany|sizeof|static|static_cast|struct|switch|template|this|thread|throw|true|typeof|false|try|typedef|typeid|typename|union|using|uuid|virtual|while)\\b/g,\"<b>$1</b>\");\n result = result.replace(/\\b(\\d+)\\b/g,\"<var>$1</var>\");\n result = result.replace(/\\b(0x[0-9a-f]+)\\b/gi,\"<var>$1</var>\");\n return result;\n }", "function getToken(c) {\n return c >= 128 && c < 128 + TOKENS.length ? TOKENS[c - 128] : undefined;\n}", "function printCool(name) {\n return `${name} is cool.`\n}", "function printCodePointAt(lexer, location) {\n const code = lexer.source.body.codePointAt(location);\n\n if (code === undefined) {\n return _tokenKind.TokenKind.EOF;\n } else if (code >= 0x0020 && code <= 0x007e) {\n // Printable ASCII\n const char = String.fromCodePoint(code);\n return char === '\"' ? \"'\\\"'\" : `\"${char}\"`;\n } // Unicode code point\n\n return 'U+' + code.toString(16).toUpperCase().padStart(4, '0');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the value multiplied by 100 ie: calculateImageSize(1) => 100 calculateImageSize(2) => 200 calculateImageSize(3) => 300 calculateImageSize(4) => 400
function calculateImageSize(value) { }
[ "calculateImageNumber()\n {\n const { cardCount, maxCardCount, numImages } = this;\n\n if (cardCount === 0)\n return false;\n \n return Math.ceil(cardCount/maxCardCount * numImages);\n }", "function change_image(n) {\n full_image(images += n);\n}", "function increaseImage() {\n \t\t++currentImage;\n \t\tif(currentImage > totalImages) {\n \t\t\tcurrentImage = 1;\n \t\t}\n \t}", "function countPixelsInImages() {\n var i, imageTotal = 0, currentImage = 0, images = document.getElementsByTagName('img');\n\n for (i = 0; i < images.length; i = i + 1) {\n currentImage = images[i].naturalWidth * images[i].naturalHeight\n imageTotal += currentImage;\n\n if (currentImage > benchmarkForImage && images[i].naturalWidth !== images[i].width) {\n logResizedImages.push(images[i].src);\n } else if (currentImage > benchmarkForImage) {\n logLargeImages.push(images[i].src);\n } \n }\n\n return imageTotal;\n }", "function multiplyBy10(result) {\r\n return 10 * result;\r\n}", "function current_image(n) {\n full_image(images = n);\n}", "function scaleImage(scalePercentage){\n\n imgInContainer.style.width=scalePercentage+\"%\";\n imgInContainer.style.height= \"auto\";\n\n}", "function calculateNewSize(query, callback){\n\n\t//Raw param\n\tvar widthOrHeight = query.size;\n\t// Set to true if user passed in width by height\n\tvar nSizeHandW = false;\n\t// Set to default raw query\n\tvar nWidth = nHeight = widthOrHeight;\n\t//Split by 'x' (times char) and seperate the size\n\tif(widthOrHeight.indexOf(\"x\") != -1){\n\t\t var whArr = widthOrHeight.split(\"x\");\n\t\t nWidth = whArr[0];\n\t\t nHeight = whArr[1];\n\t\t nSizeHandW = true;\n\t}\n\t// Empty object to populate\n\tvar imageSize = {};\n\n\teasyimg.info(getImagePath(query.source)).then(function(stdout){\n\t\t//Get current size\n\t\tvar cWidth, cHeight;\n\t\tconsole.log(stdout);\n\t\tcWidth = stdout.width;\n\t\tcHeight = stdout.height;\n\t\tif(cWidth === undefined || cHeight === undefined){\n\t\t\timageSize =\t{ width : roundSize(nWidth) };\n\t\t}else if(nSizeHandW){\n\t\t\t// If new height and width make sure they are smaller than the current image.\n\t\t\tnWidth = Math.min(nWidth,cWidth);\n\t\t\tnHeight = Math.min(nHeight,cHeight);\n\t\t\t//Set new file path\n\t\t\timageSize =\t{\n\t\t\t\theight : roundSize(nHeight),\n\t\t\t \twidth : roundSize(nWidth)\n\t\t\t };\n\t\t}else{\n\t\t\t// resize to to the smallest size\n\t\t\tif(cWidth >= cHeight){\n\t\t\t\timageSize =\t{ width : roundSize(Math.min(nWidth,cWidth)) };\n\t\t\t}else{\n\t\t\t\tvar ratio = cHeight/cWidth;\n\t\t\t\timageSize = { width : roundSize(ratio * nHeight) };\n\t\t\t}\n\t\t}\n\t\tcallback(null, imageSize);\n\t}).catch((err)=>{\n\t\tconsole.log(\"error while getting info\", err);\n\t\tcallback(false, null);\n\t\treturn;\n\t});\n}", "function calculatePercentage(percentage) {\n return (5000 / 100) * percentage;\n}", "function rawMultiplier(componentCount){\r\n if(this.componentCount >= 6){\r\n return .3;\r\n }\r\n else{ \r\n return 0.225;\r\n }\r\n \r\n}", "function imagenAnterior(actual, total) {\n if (actual === 0) {\n return total - 1;\n } else {\n return actual - 1;\n }\n}", "function percentToPixel(size, max)\n{\n let percentRegexp = /^[0-9]{1,3}%$/;\n let pixelRegexp = /^[0-9]*px$/;\n\n if (pixelRegexp.exec(size))\n {\n return parseInt(size);\n }\n else if (percentRegexp.exec(size))\n {\n return (parseInt(size) / 100.0) * max;\n }\n else\n return parseInt(size);\n}", "function divByFive(num){\n return num/5\n}", "getLoadingCompletionPercentage(){\n\t\treturn this.getNumberOfImagesLoaded()/this.getTotalNumberOfImages();\n\t}", "function scale(value) {\r\n return Math.floor(screenHeight / baselineHeight * value);\r\n}", "function _updateImageScale ( values, handle ) {\n\t\tupdateScale.call( this, values, handle );\n\t}", "function calculateItemTotal(numItems, itemValue){\r\n\tvar total;\r\n\ttotal = numItems * itemValue;\r\n\ttotal = Number(total); //Needed to add this or else no output was recieved.\r\n\treturn total;\r\n}", "function decreaseImage() {\n \t--currentImage\n \tif(currentImage < 1){\n \tcurrentImage = totalImages;\n \t }\n \t}", "function percentOf(num, num2){\n return (num/num2)*100\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method intercepts each open preferences event emitted by the native app and opens preferences page.
_handleOpenPreferences(evt) { evt = JSON.parse(evt); this._analyticsLogic.logEvent({ screenName: evt.data.screenName }); this._navigationManager.navigateTo(EventNames.MENUITEMS_OPENPREFERENCES); }
[ "openDictionary() {\n // Prevent creating of new window\n if (this.window && !this.window.isDestroyed() && !this.window.isVisible()) {\n this.showWindow();\n } else if (this.window.isDestroyed()) {\n this.window = this.createWindow();\n this.window.once('ready-to-show', () => this.showWindow());\n }\n }", "function onOpen(event){\n\t\tvar oQuickViewContent = event.getSource().getContent()[0];\n\t\t// Data is loaded and content is rendered at this point of time, \n\t\t// so call the setKeyboardNavigation function directly\n\t\t//setKeyboardNavigation.call(oQuickViewContent);\n\t}", "populateHotWindow(event, loadSettings) {\n if (/composer/.test(loadSettings.windowType)) {\n NylasEnv.timer.split('open-composer-window');\n }\n this.loadSettings = loadSettings;\n this.constructor.loadSettings = loadSettings;\n\n this.packages.loadPackages(loadSettings.windowType);\n this.deserializePackageStates();\n this.packages.activate();\n\n this.emitter.emit('window-props-received',\n loadSettings.windowProps != null ? loadSettings.windowProps : {});\n\n const browserWindow = this.getCurrentWindow();\n if (browserWindow.isResizable() !== loadSettings.resizable) {\n browserWindow.setResizable(loadSettings.resizable);\n }\n\n if (!loadSettings.hidden) {\n this.displayWindow();\n }\n }", "function openPopupPromoCode() {\n window.location.hash = '#?promoCodePopup';\n $body.addClass('overflow');\n $overlayPromoCode.addClass('open');\n scrollTo($body, 0, 500, $overlayPromoCode);\n }", "function openOptionsPage() {\n runtime.openOptionsPage();\n}", "enableExternalInteractions_() {\n this.win.addEventListener('message', (event) => {\n if (!this.isPromptUiOn_) {\n return;\n }\n\n let consentString;\n let metadata;\n const data = getData(event);\n\n if (!data || data['type'] != 'consent-response') {\n return;\n }\n\n if (!data['action']) {\n user().error(TAG, 'consent-response message missing required info');\n return;\n }\n if (data['info'] !== undefined) {\n if (typeof data['info'] != 'string') {\n user().error(\n TAG,\n 'consent-response info only supports string, ' +\n '%s, treated as undefined',\n data['info']\n );\n data['info'] = undefined;\n }\n if (data['action'] === ACTION_TYPE.DISMISS) {\n if (data['info']) {\n this.user().error(\n TAG,\n 'Consent string value %s not applicable on user dismiss, ' +\n 'stored value will be kept and used',\n data['info']\n );\n }\n data['info'] = undefined;\n }\n consentString = data['info'];\n metadata = this.validateMetadata_(data['consentMetadata']);\n }\n\n const iframes = this.element.querySelectorAll('iframe');\n\n for (let i = 0; i < iframes.length; i++) {\n if (iframes[i].contentWindow === event.source) {\n const {action, purposeConsents} = data;\n // Check if we have a valid action and valid state\n if (\n !isEnumValue(ACTION_TYPE, action) ||\n !this.isReadyToHandleAction_()\n ) {\n continue;\n }\n if (\n purposeConsents &&\n Object.keys(purposeConsents).length &&\n action !== ACTION_TYPE.DISMISS\n ) {\n this.validatePurposeConsents_(purposeConsents);\n this.consentStateManager_.updateConsentInstancePurposes(\n purposeConsents\n );\n }\n this.handleAction_(action, consentString, metadata);\n }\n }\n });\n }", "function handleOpenPermaOptions() {\n $('#bubble').toggle();\n }", "showWindow() {\n this.window.show();\n this.window.webContents.send('open-dictionary');\n }", "constructor() { \n \n Prefs.initialize(this);\n }", "function openKeyManager() {\n window.browsingContext.topChromeWindow.openDialog(\n \"chrome://openpgp/content/ui/enigmailKeyManager.xhtml\",\n \"enigmail:KeyManager\",\n \"dialog,centerscreen,resizable\",\n {\n cancelCallback: null,\n okCallback: null,\n }\n );\n}", "function passiveModeWindowSizeListener() {\n var passiveModeWindowSize = document.getElementById(\"passiveModeWindowSize\");\n passiveModeWindowSize.addEventListener(\"input\", function() {\n var newVal = passiveModeWindowSize.value;\n chrome.storage.local.get(function(storage) {\n var cachedSettings = storage[\"cachedSettings\"];\n var oldSettings = storage[\"settings\"];\n if (!cachedSettings) {\n if (!oldSettings) {\n // Use default Settings\n oldSettings = initialSettings;\n }\n cachedSettings = oldSettings;\n }\n\n cachedSettings[\"passiveModeWindowSize\"] = newVal;\n var passiveModeWindowSizeVal = document.getElementById(\"passiveModeWindowSizeVal\");\n passiveModeWindowSizeVal.innerHTML = newVal;\n chrome.storage.local.set({ \"cachedSettings\": cachedSettings });\n });\n });\n}", "function popupPVAsWindow_onload(e)\n{\n\t// set flag\n\tasPopupWindow = true;\n\n\t// initialise fields\n\tgblPromptTitle = window.opener.gblPromptTitle;\n\tgblPromptFieldId = window.opener.gblPromptFieldId;\n\tgblPromptId = window.opener.gblPromptId;\n\tgblPromptDecode = window.opener.gblPromptDecode;\n\tgblPromptSecurity = window.opener.gblPromptSecurity;\n\tgblPromptFile = window.opener.gblPromptFile;\n\tgblPromptKeys = window.opener.gblPromptKeys;\n\tgblReturnFieldNames = window.opener.gblReturnFieldNames;\n\tgblReturnFieldLabels = window.opener.gblReturnFieldLabels;\n\tgblReturnFieldPositions = window.opener.gblReturnFieldPositions;\n\tgblReturnFieldLengths = window.opener.gblReturnFieldLengths;\n\tgblBackStart = window.opener.gblBackStart;\n\tgblBackLength = window.opener.gblBackLength;\n\tgblDataFields = window.opener.gblDataFields;\n\tgblDbFields = window.opener.gblDbFields;\n\tgblReturnFieldHdrPos = window.opener.gblReturnFieldHdrPos;\n\tgblMaxResults = window.opener.gblMaxResults;\n\t\n\tgetNewPVList(gblPromptTitle,gblPromptFieldId,gblPromptId,gblPromptDecode,gblPromptSecurity,gblPromptFile,gblPromptKeys,\n\t\t\t\t\t\tgblReturnFieldNames,gblReturnFieldLabels,gblReturnFieldPositions,gblReturnFieldLengths,\n\t\t\t\t\t\tgblBackStart,gblBackLength,\n\t\t\t\t\t\tgblDataFields,gblDbFields,gblReturnFieldHdrPos,\n\t\t\t\t\t\ttrue,gblMaxResults\n\t\t\t\t\t\t);\n\t\n}", "function userPreferences(){\r\n var user_id = $(\"#user_id\").val(); \r\n preferences = getDefaultWindow(\"user_preferences\",500,350);\r\n preferences.setText(\"Gurski [User Preferences]\");\r\n preferences.progressOn();\r\n preferences.center();\r\n preferences.attachURL(\"../src/Linker.class.php?action=user_preferences&user_id=\"+user_id+\"\"); \r\n}", "onWindowPropsReceived(callback) {\n return this.emitter.on('window-props-received', callback);\n }", "launchNewWindow(p) {\n let appInfo = this.app.get_app_info();\n let actions = appInfo.list_actions();\n if (this.app.can_open_new_window()) {\n this.animateLaunch();\n // This is used as a workaround for a bug resulting in no new windows being opened\n // for certain running applications when calling open_new_window().\n //\n // https://bugzilla.gnome.org/show_bug.cgi?id=756844\n //\n // Similar to what done when generating the popupMenu entries, if the application provides\n // a \"New Window\" action, use it instead of directly requesting a new window with\n // open_new_window(), which fails for certain application, notably Nautilus.\n if (actions.indexOf('new-window') == -1) {\n this.app.open_new_window(-1);\n }\n else {\n let i = actions.indexOf('new-window');\n if (i !== -1)\n this.app.launch_action(actions[i], global.get_current_time(), -1);\n }\n }\n else {\n // Try to manually activate the first window. Otherwise, when the app is activated by\n // switching to a different workspace, a launch spinning icon is shown and disappers only\n // after a timeout.\n let windows = this.getWindows();\n if (windows.length > 0)\n Main.activateWindow(windows[0])\n else\n this.app.activate();\n }\n }", "function getHashToOpenPromoPopup() {\n var hash = window.location.hash;\n if (hash == '#?promoCodePopup'){\n openPopupPromoCode();\n }\n if (hash == '#?sectionApp'){\n var percent = windowWidth / 100;\n var offset = (windowWidth >= 768) ? 2 * percent : 3.5 * percent;\n scrollTo($('#section-app'), offset);\n }\n }", "apply() {\n localStorage.setItem(SETTINGS_KEY, this.export());\n const event = new SettingsEvent();\n event.fire();\n }", "function setupSearchPreferences(){\r\n\t\t// Set the initial search preferences, which are updated everytime a search is performed\r\n\t\tif(localStorage.hasOwnProperty('bSearchPreferencesCreated') != true){\r\n\t\t\t// Comments\r\n\t\t\tvar aDayOfWeek = new Object();\r\n\t\t\taDayOfWeek['su'] = 1;\r\n\t\t\taDayOfWeek['mo'] = 1;\r\n\t\t\taDayOfWeek['tu'] = 1;\r\n\t\t\taDayOfWeek['we'] = 1;\r\n\t\t\taDayOfWeek['th'] = 1;\r\n\t\t\taDayOfWeek['fr'] = 1;\r\n\t\t\taDayOfWeek['sa'] = 1;\r\n\t\t\r\n\t\t\t// oCurrentSearchSettings\r\n\t\t\tvar oCurrentSearchSettings = new Object();\r\n\t\t\toCurrentSearchSettings['sLocationName']\t\t= 'Amsterdam';\r\n\t\t\toCurrentSearchSettings['fLocationLat']\t\t= 52.378;\r\n\t\t\toCurrentSearchSettings['fLocationLng']\t\t= 4.9;\r\n\t\t\toCurrentSearchSettings['iLocationRadius']\t= iDefaultLocationRadius;\r\n\t\t\toCurrentSearchSettings['iPriceMin']\t\t\t= iDefaultPriceMin;\r\n\t\t\toCurrentSearchSettings['iPriceMax']\t\t\t= iDefaultPriceMax;\r\n\t\t\toCurrentSearchSettings['iDayOffsetFrom']\t= 0;\r\n\t\t\toCurrentSearchSettings['iDayOffsetTo']\t\t= iDefaultDateMax;\r\n\r\n\t\t\toCurrentSearchSettings['dStartDate']\t\t= new Date();\r\n\t\t\toCurrentSearchSettings['dEndDate']\t\t\t= oCurrentSearchSettings['dStartDate'].addDays(iDefaultDateMax);\r\n\r\n\t\t\toCurrentSearchSettings['aDayOfWeek']\t\t= JSON.stringify(aDayOfWeek);\r\n\t\t\tlocalStorage.setItem('oCurrentSearchSettings', JSON.stringify(oCurrentSearchSettings));\r\n\t\t\t\r\n\t\t\tvar oPanelSearchSettings = new Object();\r\n\t\t\toPanelSearchSettings['sLocationName']\t\t= oCurrentSearchSettings['sLocationName'];\r\n\t\t\toPanelSearchSettings['fLocationLat']\t\t= oCurrentSearchSettings['fLocationLat'];\r\n\t\t\toPanelSearchSettings['fLocationLng']\t\t= oCurrentSearchSettings['fLocationLng'];\r\n\t\t\toPanelSearchSettings['iLocationRadius']\t\t= oCurrentSearchSettings['iLocationRadius'];\r\n\t\t\toPanelSearchSettings['iPriceMin']\t\t\t= oCurrentSearchSettings['iPriceMin'];\r\n\t\t\toPanelSearchSettings['iPriceMax']\t\t\t= oCurrentSearchSettings['iPriceMax'];\t\t\t\r\n\t\t\toPanelSearchSettings['iDayOffsetFrom']\t\t= oCurrentSearchSettings['iDayOffsetFrom'];\r\n\t\t\toPanelSearchSettings['iDayOffsetTo']\t\t= oCurrentSearchSettings['iDayOffsetTo'];\r\n\t\t\t\r\n\t\t\toPanelSearchSettings['dStartDate']\t\t\t= oCurrentSearchSettings['dStartDate'];\r\n\t\t\toPanelSearchSettings['dEndDate']\t\t\t= oCurrentSearchSettings['dEndDate'];\r\n\r\n\t\t\toPanelSearchSettings['aDayOfWeek']\t\t\t= oCurrentSearchSettings['aDayOfWeek'];\r\n\t\t\tlocalStorage.setItem('oPanelSearchSettings', JSON.stringify(oPanelSearchSettings));\r\n\r\n\t\t\t// Comments\r\n\t\t\tlocalStorage.setItem(\"bSearchPreferencesCreated\",\t\ttrue);\r\n\t\t\tlocalStorage.setItem(\"iMusicFactIndex\",\t\t\t\t\ttrue);\r\n\t\t};\r\n\t}", "function openOptions() \r\n{ \r\n\tchrome.tabs.create({url:\"options.html\"}); \r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes keys that are no longer in the map from the _keys array
function _cleanupKeys() { if (this._count == this._keys.length) { return; } var srcIndex = 0; var destIndex = 0; var seen = {}; while (srcIndex < this._keys.length) { var key = this._keys[srcIndex]; if (_hasKey(this._map, key) && !_hasKey(seen, key) ) { this._keys[destIndex++] = key; seen[key] = true; } srcIndex++; } this._keys.length = destIndex; }
[ "deleteKeys(keys) {\n if (Array.isArray(keys)) {\n for (const key of keys) {\n if (isPlainOldJavaScriptObject(this.data)) {\n delete this.data[key];\n }\n }\n }\n }", "removeKeys () {\n this._eachPackages(function (_pack) {\n _pack.remove()\n })\n }", "remove(key) {\n var item = this.map[key];\n if (!item) return;\n this._removeItem(item);\n }", "function clearKeys() {\n for (var i = 0; i < 10; i++) {\n keysDown[i] = false;\n }\n}", "function getUnUsedKeys(allKeys, usedKeys) {\n\t//TODO\n if (Array.isArray(allKeys) && Array.isArray(usedKeys)) {\n let newArr = allKeys.concat(usedKeys),\n unusedKeys = [];\n\n // sort the values, and then remove duplicate values in loop\n newArr.sort();\n for(let i = 0; i < newArr.length; i++){\n if(newArr[i] !== newArr[i+1]) {\n unusedKeys.push(newArr[i]);\n } else {\n i++;\n }\n }\n return unusedKeys;\n } else {\n console.log('error: The first parameter and the second parameter should be an Array');\n }\n}", "remove(key) {\n let index = Hash.hash(key, this.sizeLimit);\n\n if (\n this.hashTable[index].length === 1 &&\n this.hashTable[index][0][0] === key\n ) {\n delete this.hashTable[index];\n } else {\n for (let i = 0; i < this.hashTable[index].length; i++) {\n if (this.hashTable[index][i][0] === key) {\n delete this.hashTable[index][i];\n }\n }\n }\n }", "reset() {\n this.map = new Map();\n }", "function removeKeyOnly() {\r\n document.getElementById('keyonly').outerHTML = '';\r\n}", "function uniqueKeys(events) {\n const arrayOfKeys = [];\n for (const e of events) {\n for (const k of e.data().keySeq()) {\n arrayOfKeys.push(k);\n }\n }\n return new Immutable.Set(arrayOfKeys);\n}", "function eraseMap() {\n document.body.removeChild(map);\n }", "function clearOlderEntries(browsingData, dateKey) {\n for (var key in browsingData) {\n if (key !== dateKey) {\n delete browsingData[key];\n }\n }\n}", "function Keymap(keys, options) {\n\t this.options = options || {}\n\t this.bindings = Object.create(null)\n\t if (keys) this.addBindings(keys)\n\t }", "function hastableKeys(dict)\n {\n var ids = [];\n\n for (var id in dict)\n {\n if (dict.hasOwnProperty(id))\n ids.push(id);\n }\n\n return ids;\n }", "function clearMap() {\n for (var i = 0; i < facilityMarkers.length; ++i) {\n facilityMarkers[i].setMap(null);\n }\n facilityMarkers = [];\n}", "function clearMarkers() {\n let initialCitiesLength = Object.keys(INITIALCITIES).length;\n for (let i = MARKERS.length - 1; i >= initialCitiesLength; i--) {\n MARKERS[i].setMap(null);\n MARKERS.splice(i, 1);\n }\n }", "reset() {\n this._registry = new Map();\n }", "function clearhail() {\n if (hailArray) {\n for (i in hailArray) {\n hailArray[i].setMap(null);\n }\n }\n}", "function DDLightbarMenu_RemoveAllItemHotkeys()\n{\n\tfor (var i = 0; i < this.items.length; ++i)\n\t\tthis.items[i].hotkeys = \"\";\n}", "static unbind(keys, classRef) {\n for (const key of keys) {\n for (const i in listeners[key]) {\n if (listeners[key][i] === classRef) {\n delete listeners[key][i]\n }\n }\n }\n }", "remove(key) {\n if (this._data[key]) {\n this._busyMemory -= this._lifeTime[key].size;\n delete this._data[key];\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invoke this method to explicitly process change detection and its sideeffects. In development mode, `tick()` also performs a second change detection cycle to ensure that no further changes are detected. If additional changes are picked up during this second cycle, bindings in the app have sideeffects that cannot be resolved in a single change detection pass. In this case, Angular throws an error, since an Angular application can only have one change detection pass during which all change detection must complete.
tick() { if (this._runningTick) { throw new Error('ApplicationRef.tick is called recursively'); } try { this._runningTick = true; for (let view of this._views) { view.detectChanges(); } // Note that we have still left the `isDevMode()` condition in order to avoid // creating a breaking change for projects that still use the View Engine. if ((typeof ngDevMode === 'undefined' || ngDevMode) && isDevMode()) { for (let view of this._views) { view.checkNoChanges(); } } } catch (e) { // Attention: Don't rethrow as it could cancel subscriptions to Observables! this._zone.runOutsideAngular(() => this._exceptionHandler.handleError(e)); } finally { this._runningTick = false; } }
[ "function runObservers () {\n try {\n queuedObservers.forEach(runObserver);\n } finally {\n currentObserver = undefined;\n queuedObservers.clear();\n }\n}", "notify_speed_update() {\n this.speed_update = true;\n }", "function safeApply() {\n $rootScope.$$phase || $rootScope.$apply();\n }", "watch() {\n if (this.shouldUpdate()) {\n this.trigger('change', this.rect);\n }\n\n if(!this.shouldStop){\n window.requestAnimationFrame(() => this.watch());\n }\n }", "function handleModelChange(newValue, oldValue) {\n\t\t\t// If we try to call render right away, two things will go wrong:\n\t\t\t// first, we won't give the ngValue directive time to pipe the\n\t\t\t// correct value into ngModle; and second, it will force an\n\t\t\t// undesirable repaint of the browser. As such, we'll perform the\n\t\t\t// Uniform synchronization at a later point in the $digest.\n\t\t\tscope.$evalAsync(synchronizeUniform);\n\t\t}", "function tick() {\n document.querySelector('#clocks').replaceChildren(\n createList(clocksConfig)\n );\n // 3b. Repeat the timer - call for the next click\n setTimeout(tick, 1000);\n}", "tick(deltaT) {\n\t var particles = this.children.slice(0);\n\t var current = particles.shift();\n\t var pLen = particles.length;\n\t while (pLen > 0) {\n\t\tfor (var i = 0; i < pLen; i++) {\n\t\t addForces(current, particles[i]);\n\t\t}\n\t\tcurrent = particles.shift();\n\t\tpLen = particles.length;\n\t }\n\t // We've added all the required forces to all our children, so\n\t // call update on them.\n\t update(deltaT);\n\t}", "checkTicks() { // CHECK\n for(var prop in this.connected_routers_list) {\n //update when shutdown\n if (this.recieved_list[this.tick][prop] == undefined && this.recieved_list[this.tick-1][prop] == undefined) {\n this.setCostInfinite(prop);\n }\n\n //update when a router from shut-down to start\n if (this.recieved_list[this.tick][prop] != undefined) {\n this.connected_routers_list[prop] = 1;\n if (this.connected_routers_list[prop] == Number.MAX_VALUE) {\n this.connected_routers_list[prop] = x.routers[prop].connected_routers_list[this.id];\n }\n }\n } \n }", "_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }", "function runObserver (observer) {\n currentObserver = observer;\n observer();\n}", "function runClock() {\n\t\tcurrenttime = setInterval(updateRegularClock, 1000);\n\t}", "function tick() {\n // Clear the interval\n clearInterval(interval);\n // Replace that cleared interval\n interval = setInterval(() => {\n function lookupData(currencies=Object.keys(addresses)) {\n if (currencies.length > 0) {\n const currency = currencies.pop();\n // Account for change addresses\n let baseCurrency = currency;\n if (currency.indexOf('_CHANGE') > -1) {\n baseCurrency = currency.slice(0, currency.indexOf('_CHANGE'));\n }\n // Fetch the state data with our set of addresses for this currency\n fetchStateData(baseCurrency, addresses, currentPage, (err, data) => {\n if (err) {\n // Log the error if it arises\n postMessage({ type: \"error\", currency, data: err });\n } else {\n // If we got a non-error response, post the data back to the\n // main thread.\n postMessage({ type: \"dataResp\", currency, data })\n }\n lookupData(currencies);\n })\n } else {\n // We are done looping through currencies\n postMessage({ type: \"iterationDone\" })\n }\n }\n \n lookupData();\n }, LOOKUP_DELAY)\n }", "function runCouette(){\n\tmodule = \"couette\";\n\tinit();\n\tlet {ctx, canvas} = getCtxCanvas();\n\tctx.save();\n\tctx.transform(1, 0, 0, -1, 0, canvas.height);\n\tintervId = setInterval(drawCouette, 1000 / FPS);\n}", "loop() {\n clearTimeout(this.persistentLoop);\n // emit loop event to any active persistent tool\n EventBus.$emit(\"loop\", this.loopCount);\n\n // redraw canvas\n if (this.file && this.file.selectionCanvas) this.onRedrawCanvas();\n\n // increase loop iteration\n ++this.loopCount;\n\n // re-run persistence loop\n this.persistentLoop = setTimeout(() => this.loop(), 25);\n }", "function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n });\n } // notifyObservers", "loopLights() {\n console.log('[johnny-five] Lights Looping.');\n this.buildLoop();\n\n this.loop = setTimeout(() => {\n this.buildLoop();\n }, 8000);\n }", "loop () {\n if (!this.shouldLoop) {\n return\n }\n\n window.requestAnimationFrame(this.loop.bind(this))\n\n // When not clicking the orientation values can be rounded more, so that\n // less messages are sent.\n const rounding = this.isClicking ? 100 : 25\n const orientation = this.gyroscope.getOrientation(rounding)\n\n this.gyroplane.updateOrientation(orientation)\n\n try {\n const coordinates = this.gyroplane.getScreenCoordinates()\n this.lazy.update(coordinates)\n } catch (e) {\n this.gyroplane.init()\n }\n\n // Get the lazy coordinates.\n const { x, y } = this.lazy.getBrushCoordinates()\n\n // Set the new values to the array.\n this.intArray.set([\n Math.round(x),\n Math.round(y),\n this.isClicking ? 1 : 0,\n Math.round(this.touch.y)\n ], 0)\n\n // Only send the data if it actually has changed.\n if (\n this.prevArray[0] !== this.intArray[0] ||\n this.prevArray[1] !== this.intArray[1] ||\n this.prevArray[2] !== this.intArray[2] ||\n this.prevArray[3] !== this.intArray[3]\n ) {\n this._onDataChange(this.buffer)\n this.prevArray.set(this.intArray, 0)\n }\n }", "setTicksPassed(newTicksPassed) {\n this.ticksPassed = newTicksPassed\n }", "function updateClock(){\n document.getElementById(\"app\").innerHTML = currentTime();\n\n updateStopWatches();\n}", "run() {\n function main(tFrame) {\n game = window.game;\n game.stopMain = window.requestAnimationFrame(main);\n var nextTick = game.lastTick + game.tickLength;\n var numTicks = 0;\n\n //If tFrame < nextTick then 0 ticks need to be updated (0 is default for numTicks).\n //If tFrame = nextTick then 1 tick needs to be updated (and so forth).\n //Note: As we mention in summary, you should keep track of how large numTicks is.\n //If it is large, then either your game was asleep, or the machine cannot keep up.\n if (tFrame > nextTick) {\n var timeSinceTick = tFrame - game.lastTick;\n numTicks = Math.floor(timeSinceTick / game.tickLength);\n }\n\n queueUpdates(game, numTicks);\n game.render(tFrame);\n game.lastRender = tFrame;\n }\n\n function queueUpdates(game, numTicks) {\n for (var i = 0; i < numTicks; i++) {\n game.lastTick = game.lastTick + game.tickLength; //Now lastTick is this tick.\n game.update(game.lastTick);\n }\n }\n\n this.lastTick = performance.now();\n this.lastRender = this.lastTick; //Pretend the first draw was on first update.\n this.tickLength = 20; //This sets your simulation to run at 20Hz (50ms)\n\n this.setInitialState();\n\n this.time_start = performance.now();\n main(performance.now()); // Start the cycle\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
register the app of the user on Manarah API once the app is installed and get an API token to use it for authenticating the app in other api calls
static registerApp(firebaseId, permissionsGranted) { console.log('reg.....'); // call the api passing the fb id and notifications granted flag return axios.post(API_URL + API_ENDPOINTS.registerApp, { fb_id: firebaseId, granted: permissionsGranted }).then((response) => { console.log(response); // get the token from response and save it to Asyncstorage and redux let token = response.data.token; AsyncStorage.setItem('user@apiKey', token); store.dispatch(apiKeyActionCreators.getApiKey(token)); }).catch((err) => { console.log(err.response); }); }
[ "function register(){\n\tfunction asyncCallback(status, result){\n \tkony.print(\"\\n------status------>\"+status);\n \tif(status==400){\n \t\tkony.print(\"\\n------result------>\"+JSON.stringify(result));\n \t\tif(result[\"opstatus\"]==8009)\n \t\t{\n \t\t\tif(result[\"message\"]!=undefined)\n \t\t\t\tupdateMessaageAlert(result[\"message\"]);\n \t\t\telse\n \t\t\t\tupdateMessaageAlert(\"email/mobile already registered\");\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\t//updateMessaageAlert(\"mobile or email already regestered..\");\n \t\t\treturn;\n \t\t}\n \t\tif(result[\"errmsg\"]!=undefined){\n \t\t\tupdateMessaageAlert(result[\"errmsg\"]);\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\treturn;\n \t\t}if(result[\"opstatus\"]==0){\t\n \t\t\taudienceID=result[\"id\"];\n \t\t\tkony.store.setItem(\"audienceID\", audienceID);\n \t\t\tupdateMessaageAlert(\"\"+result[\"message\"]);\n \t\t\tfrmProfilePreShow();\n \t\t\tfrmProfile.show();\n \t\t\tfrmRegistration.destroy();\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t}\n \t\telse{\n \t\t\tupdateMessaageAlert(\"unable to process please try later..\");\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\treturn;\n \t\t}\n \t}\n }\n var inputParamTable={\n \thttpheaders:{\n \t\t\"AccessSecret\":accessSecret,\n \t\t\"AccessToken\":accessToken,\n \t\t\"Content-Type\":\"application/json\"\n \t},\n\t\t\thttpconfig:{method:\"POST\"},\n\t\t\tserviceID:\"CreateAudience\",appID:\"kmsapp\",\n\t\t\tchannel:\"rc\",\n\t\t\tactive: \"\\\"\"+audienceStatus+\"\\\"\",\n \t\t\temail: \"\\\"\"+audienceEmail+\"\\\"\",\n \t\t\temailSubscription:\"\\\"\"+audienceEmailSubs+\"\\\"\",\n \t\t\tfirstName: \"\\\"\"+audienceFirstName+\"\\\"\",\n \t\t\tlastName: \"\\\"\"+audienceLastName+\"\\\"\",\n \t\t\tmobileNumber: \"\\\"\"+audienceMob+\"\\\"\",\n \t\t\tpushSubscription: \"\\\"\"+audiencePushSubs+\"\\\"\",\n \t\t\tsmsSubscription: \"\\\"\"+audienceSmsSubs+\"\\\"\",\n \t\t\tkmsurl:KMSPROP.kmsserverurl\n\t};\n var url=appConfig.url;\n // var url=\"http://10.10.12.145:8080/middleware/MWServlet\";\n kony.print(\"\\n----url----->\"+url) ; \n try{\n kony.application.showLoadingScreen(\"sknLoading\",\"registering...\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\t\tvar connHandle = kony.net.invokeServiceAsync(\n url,inputParamTable,asyncCallback);\n\t}catch(err){\n \tkony.print(\"\\nexeption in invoking service---\\n\"+JSON.stringify(err));\n\t \talert(\"Error\"+err);\n\t \tkony.application.dismissLoadingScreen();\n\t}\t\n}", "function createJWTForAPIsAccess(phoneNo, apiKey){\n return fetch((\"https://app.aibers.health/createJWTForAPIsAccess\"), {\n method: \"POST\",\n headers: {Accept: 'application/json','Content-Type': 'application/json'},\n body: JSON.stringify({\n pno: phoneNo,\n apiKey: apiKey\n})\n }).then(response => response.json());\n}", "register (credentials){\n return Api().post('register', credentials)\n }", "function authApp(successCallback) {\n\tvar s = getSignature(); // gets signature\n\t\n\t// See more documentation on the wiki \n\t// -- http://wiki.quickblox.com/Authentication_and_Authorization#API_Session_Creation\n\tvar url = 'https://admin.quickblox.com/auth';\n\tvar data = 'app_id=' + QB.appId + \n\t\t\t'&auth_key=' + QB.authKey + \n\t\t\t'&nonce=' + s.nonce + \n\t\t\t'&timestamp=' + s.timestamp + \n\t\t\t'&signature=' + s.signature;\n\t\n\tconsole.log('[DEBUG] Authenticate specified application: POST ' + url + '?' + data);\n\t\n\t$.ajax({\n\t type: 'POST',\n\t url: url,\n\t data: data,\n\t success: successCallback,\n\t error: errorCallback\n\t});\n}", "static buildAppToken(appId, appCertificate, expire) {\n \tconst token = new AccessToken(appId, appCertificate, null, expire);\n \tconst serviceChat = new ServiceChat();\n \tserviceChat.add_privilege(ServiceChat.kPrivilegeApp, expire);\n \ttoken.add_service(serviceChat);\n \treturn token.build();\n }", "async function apiManagementCreateAuthorizationProviderOobGoogle() {\n const subscriptionId = process.env[\"APIMANAGEMENT_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"APIMANAGEMENT_RESOURCE_GROUP\"] || \"rg1\";\n const serviceName = \"apimService1\";\n const authorizationProviderId = \"google\";\n const parameters = {\n displayName: \"google\",\n identityProvider: \"google\",\n oauth2: {\n grantTypes: {\n authorizationCode: {\n clientId: \"\",\n clientSecret: \"\",\n scopes:\n \"openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email\",\n },\n },\n redirectUrl:\n \"https://authorization-manager.consent.azure-apim.net/redirect/apim/apimService1\",\n },\n };\n const credential = new DefaultAzureCredential();\n const client = new ApiManagementClient(credential, subscriptionId);\n const result = await client.authorizationProvider.createOrUpdate(\n resourceGroupName,\n serviceName,\n authorizationProviderId,\n parameters\n );\n console.log(result);\n}", "function callServerForToken(authUrl) {\r\n let nameAndToken;\r\n fetch(authUrl)\r\n .then((response) =>{\r\n return response.json();\r\n })\r\n .then((data) => {\r\n nameAndToken = [data.athlete.firstname, data.access_token];\r\n welcome(data.athlete.firstname);\r\n getActivities(data.access_token);\r\n })\r\n return nameAndToken;\r\n }", "async function doAblyTokenRequestWithAuthURL() {\n clearStatus();\n writeStatus(\"Requesting TokenDetails object from auth server\");\n\n ably = new Ably.Realtime({ authUrl: \"/tokenrequest\" });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n}", "appSignIn() {\r\n\r\n if (!msalApp) {\r\n return null\r\n }\r\n\r\n console.log('appSignIn')\r\n this.login().then( () => {\r\n if ( this.user()) {\r\n console.log('user signed in');\r\n // Automaticaly assign accessToken\r\n this.acquireToken().then (accessToken => {\r\n this.accessToken = accessToken \r\n console.log('accessToken: '+ this.accessToken); \r\n store.dispatch('auth/loginSuccess'); \r\n }); \r\n } else {\r\n console.error('Failed to sign in');\r\n store.dispatch('auth/loginFailure'); \r\n } \r\n });\r\n\r\n}", "static async register(data) {\n const duplicateCheck = await db.query(\n `SELECT username \n FROM users \n WHERE username = $1`,\n [data.username]\n );\n\n if (duplicateCheck.rows[0]) {\n throw new ExpressError(\n `There already exists a user with username '${data.username}`,\n 400\n );\n }\n\n const hashedPassword = await bcrypt.hash(data.password, BCRYPT_WORK_FACTOR);\n\n // create shrimpy user\n const shrimpy_user_id = await client.createUser(data.username);\n\n if (!shrimpy_user_id)\n throw new ExpressError(\"Could not create user in Shrimpy\");\n\n // create API keys in shrimpy for user management\n await client.createApiKeys(shrimpy_user_id);\n\n const result = await db.query(\n `INSERT INTO users \n (username, password, email, shrimpy_user_id) \n VALUES ($1, $2, $3, $4) \n RETURNING username, password, email, shrimpy_user_id`,\n [data.username, hashedPassword, data.email, shrimpy_user_id]\n );\n\n return result.rows[0];\n }", "function sessionApp(next) {\n\n\tconsole.log(\"Asking a new challenge ...\");\n\t\n\t//Asking a new challenge\n\trequest(freebox.url+'login', function (error, response, body) {\n\n\t\tif (!error && response.statusCode == 200) {\n\n\t\t\tbody = JSON.parse(body);\n\n\t\t\tapp.logged_in = body.result.logged_in; //Update login status\n\t\t\tapp.challenge = body.result.challenge; //Update challenge\n\n\t\t\t//Update password\n\t\t\tapp.password = crypto.createHmac('sha1', app.app_token).update(app.challenge).digest('hex'); \n\n\t\t\t//If we're not logged_in\n\t\t\tif (!app.logged_in)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tconsole.log(\"App is not logged in\");\n\t\t\t\t\n\t\t\t\t//POST app_id & password\n\t\t\t\tvar options = {\n\t\t\t\t\turl : freebox.url+'login/session/',\n\t\t\t\t\tmethod : 'POST',\n\t\t\t\t\tjson : {\n\t\t\t\t\t\t\"app_id\" : app.app_id,\n\t\t\t\t\t\t\"app_version\" : app.app_version,\n\t\t\t\t\t\t\"password\" : app.password,\n\t\t\t\t\t\t},\n\t\t\t\t\tencode : 'utf-8'\n\t\t\t\t};\n\n\t\t\t\trequest(options, function (error, response, body) {\n\n\t\t\t\t\tif ( !error && (response.statusCode == 200 || response.statusCode == 403) ) {\n\n\t\t\t\t\t\tapp.challenge = body.result.challenge; //Update challenge\n\n\t\t\t\t\t\tif (response.statusCode == 200) { //OK\n\t\t\t\t\t\t\tapp.session_token = body.result.session_token; //Save session token\n\t\t\t\t\t\t\tapp.logged_in = true; //Update login status\n\t\t\t\t\t\t\tapp.permissions = body.result.permissions;\n\n\t\t\t\t\t\t\tconsole.log(\"App is now logged in ...\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(next) next();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(response.statusCode == 403) { //Forbidden\n\t\t\t\t\t\t\tapp.logged_in = false; //Update login status\n\t\t\t\t\t\t\tconsole.log(body.msg + ' : ' + body.error_code);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconsole.log(\"App cannot log in ...\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(error);\n\t\t\t\t\t}\n\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.log(error);\n\t\t}\n\n\t});\n\n}", "function pushRegistration()\n{\tif(frmUrl.txtBoxAppId.text!==\"\"&&frmUrl.txtBoxSenderID.text!==\"\"&&frmUrl.txtBoxUrl.text!==\"\"){\n KMSPROP.kmsServerUrl=frmUrl.txtBoxUrl.text;\n KMSPROP.appId=frmUrl.txtBoxAppId.text;\n KMSPROP.senderID=frmUrl.txtBoxSenderID.text;\n\t}\n else{\n alert(\"The URL, APPID and SenderId Should not be Empty\");\n return;\n }\n\tkony.print(\"\\n\\n----in pushRegister----\\n\");\n\t//subsFrom=from;\n\tisDeleteAudience=false;\n\tvar devName = kony.os.deviceInfo().name;\n//\talert(\"devName\" + devName);\n\tkony.application.showLoadingScreen(\"sknLoading\",\"please wait..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\tif(devName==\"android\")\n\t{\n\t\tcallbackAndroidSetCallbacks();\n\t\tcallbackAndroidRegister();\n\t}else if((devName==\"iPhone\")||(devName==\"iPhone Simulator\")||(devName==\"iPad\")||(devName==\"iPad Simulator\"))\n\t{\n\t\tcallbackiPhoneSetCallbacks();\n\t\tcallbackiPhoneRegister();\n\t}\n}", "async function apiManagementCreateAuthorizationProviderGenericOAuth2() {\n const subscriptionId = process.env[\"APIMANAGEMENT_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"APIMANAGEMENT_RESOURCE_GROUP\"] || \"rg1\";\n const serviceName = \"apimService1\";\n const authorizationProviderId = \"eventbrite\";\n const parameters = {\n displayName: \"eventbrite\",\n identityProvider: \"oauth2\",\n oauth2: {\n grantTypes: {\n authorizationCode: {\n authorizationUrl: \"https://www.eventbrite.com/oauth/authorize\",\n clientId: \"\",\n clientSecret: \"\",\n refreshUrl: \"https://www.eventbrite.com/oauth/token\",\n scopes: \"\",\n tokenUrl: \"https://www.eventbrite.com/oauth/token\",\n },\n },\n redirectUrl:\n \"https://authorization-manager.consent.azure-apim.net/redirect/apim/apimService1\",\n },\n };\n const credential = new DefaultAzureCredential();\n const client = new ApiManagementClient(credential, subscriptionId);\n const result = await client.authorizationProvider.createOrUpdate(\n resourceGroupName,\n serviceName,\n authorizationProviderId,\n parameters\n );\n console.log(result);\n}", "function tokenFunc() {\n\tlet data = {username : process.env.WORDPRESS_USER, password : process.env.WORDPRESS_PASS};\n\treturn new Promise(function(resolve, reject) {\n\t\trequest({\n\t\t\turl: process.env.WORDPRESS_ROOT_PATH + \"/wp-json/jwt-auth/v1/token\",\n\t\t\tContentType : 'application/x-www-form-urlencoded',\n\t\t\tmethod: \"POST\",\n\t\t\tform: data\n\t\t}, function(error, response, body) {\n\t\t\tif(error) {\n\t\t\t\treject(error)\n\t\t\t} else {\n\t\t\t\tlet info = body.substring(body.indexOf(\"{\"));\n\t\t\t\tinfo = JSON.parse(info);\n\t\t\t\tinfo = info.token;\n\t\t\t\tresolve(info);\n\t\t\t\t/*\n\t\t\t\trequest({\n\t\t\t\t\turl: process.env.WORDPRESS_ROOT_PATH + '/wp-json/jwt-auth/v1/token/validate',\n\t\t\t\t\tContentType: 'application/json',\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tauth: {'bearer' : info},\n\t\t\t\t\tjson: true\n\t\t\t\t}, function(error, response, body) {\n\t\t\t\t\tif(error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t\tif(body == undefined) {\n\t\t\t\t\t\treject(\"Not a real postID\");\n\t\t\t\t\t}\n\t\t\t\t\tbody = body.substring(body.indexOf(\"{\"));\n\t\t\t\t\tbody = JSON.parse(body);\n\t\t\t\t\tconsole.log(body);\n\t\t\t\t\tif(body.code == \"jwt_auth_valid_token\") {\n\t\t\t\t\t\tresolve(info);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t}\n\t\t});\n\t});\n}", "async function doJwtAuth() {\n clearStatus();\n writeStatus(\"Requesting JWT from auth server...\");\n\n ably = new Ably.Realtime({ authUrl: \"/ably-jwt\" });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n}", "post(data, callback) {\n // Check fro required field(s)\n const phone =\n typeof data.payload.phone === 'string'\n && data.payload.phone.trim().length === 10\n ? data.payload.phone.trim()\n : false;\n\n const password =\n typeof data.payload.password === 'string'\n && data.payload.password.trim().length\n ? data.payload.password.trim()\n : false;\n\n if(phone && password) {\n // Lookup matching user\n _data.read('users', phone, (err, userData) => {\n if(!err && userData) {\n // Hash the sent password\n const hashedPassword = helpers.hash(password);\n if(hashedPassword === userData.hashedPassword) {\n // If valid create a new random token, set expiration 1 hour in the future\n const id = helpers.createRandomString(20);\n const expires = Date.now() + 1000 * 60 * 60;\n const tokenObject = {\n phone,\n id,\n expires\n };\n\n // Store the token\n _data.create('tokens', id, tokenObject, err => {\n if(!err) {\n callback(200, tokenObject);\n }\n else {\n callback(500, { Error: 'Couldn\\'t create new token' });\n }\n })\n }\n else {\n callback(400, { Error: 'Incorrect password' });\n }\n }\n else {\n callback(400, { Error: 'Couldn\\'t find user' });\n }\n })\n }\n else {\n callback(400, { Error: 'Missing required fields' });\n }\n }", "setUserToken (callback) {\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'put',\n\t\t\t\tpath: '/provider-set-token/newrelic',\n\t\t\t\tdata: {\n\t\t\t\t\ttoken: RandomString.generate(20),\n\t\t\t\t\tteamId: this.team.id\n\t\t\t\t},\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}", "function sendToken(app, req, res, err, user, info) {\n\tif (err)\n\t\t\treturn done(err);\n\n\tif (!user)\n\t\treturn res.json(401, { error: info });\n\n\t//user has authenticated correctly thus we create a JWT token\n\tvar token = jwt.sign(user, app.get('jwtSecret'), {\n\t\texpiresInMinutes: 1440 // expires in 24 hours\n\t});\n\n\t// Sets the response to contain the token and a success confirmation.\n\tres.json({ \n\t\tsuccess: true,\n\t\ttoken : token\n\t});\n}", "function PhoneRegister(country_code, cellphone, sms_code, pass_word, pass_word_hash, invit_code, wechat, group_id, suc_func, error_func) {\n let api_url = 'reg_phone.php',\n post_data = {\n 'country_code': country_code,\n 'cellphone': cellphone,\n 'sms_code': sms_code,\n 'pass_word': pass_word,\n 'pass_word_hash': pass_word_hash,\n 'invit_code': invit_code,\n 'wechat': wechat,\n 'group_id': group_id\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a point to the server.
function postPoint(x, y) { jsonRequest('/point', 'POST', {point: {x: x, y: y} }, null); }
[ "function sendCoords(coords, url, username) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"POST\", url); \n xmlhttp.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8\");\n xmlhttp.setRequestHeader(\"Purpose\", \"sendCoords\");\n xmlhttp.setRequestHeader(\"Username\", username);\n xmlhttp.setRequestHeader(\"Access-Control-Allow-Origin\", \"*\");\n xmlhttp.setRequestHeader(\"Coords\", coords.latitude.toString() + ' ' + coords.longitude.toString());\n xmlhttp.send(coords.latitude.toString() + ' ' + coords.longitude.toString());\n\tconsole.log(\"sent: \" + coords.latitude.toString() + ' ' + coords.longitude.toString());\n}", "function send( type, data ) {\n\tServer.send( type, data );\n}", "write(buffer) {\n this.wsSocket.send(buffer);\n }", "function writePosition(x,y){\n //refers to the place and set the value\n database.ref('ball/position').set({\n 'x':position.x+x,\n 'y':position.y+y\n })\n\n}", "function playerSendPloy(data) {\n\t// console.log('Player ID: ' + data.playerId + ' answered a question with: ' + data.answer);\n\n\t// The player's ploy is attached to the data object. \\\n\t// Emit an event with the ploy so it can be saved by the 'Host'\n\tio.sockets.in(data.gameId).emit('hostSavePloy', data);\n}", "function SendData(lat,long,head){\n // Retrieving the latitude value passed into this constructor\n this.lat = lat;\n // Retrieving the longitude value passed into this constructor\n this.long = long;\n // Retrieving the heading value passed into this constructor\n this.head = head;\n // Storing the latitude, longitude, and heading values in a JavaScript object\n const data = { latitude: lat, longitude: long, heading: head};\n // Using the fetch API to send the data to the server in JSON format\n // Specifying the URL to the send the data to \n fetch('/location', {\n // Setting the HTTP method to POST\n method: 'POST',\n // Specifying the HTTP header content type to JSON\n headers: {\n 'Content-Type': 'application/json',\n },\n // Sending the data object to the server in JSON format using the function JSON.stringify \n body: JSON.stringify(data),\n })\n // Using the method then to return the response from the server in JSON format\n .then(response => response.json())\n // Accessing the response \n .then(data => {\n // Converting the JSON response to a JavaScript object and accessing the value\n const value = JSON.parse(data.received);\n // Getting the domain name of the web host\n const host = window.location.hostname;\n // Creating a URL link to the location page\n const url = `https://${host}:5000/location`;\n // If the value from the response object equals true then the current page is replaced with the URL above\n if(value == true){window.location.replace(url);}\n })\n // Catching any errors and printing them to the console, currently no errors have been thrown for this built\n .catch((error) => {\n console.error('Error:', error);\n });\n}", "sendEvent (action) {\n let event = this.buildKiteEvent(action);\n let msg = JSON.stringify(event);\n\n this.outgoingSocket.send(msg, 0, msg.length, KiteOutgoing.PORT, KiteOutgoing.HOST);\n }", "function drawPoint() {\n push();\n noStroke();\n fill(String(this.color));\n ellipse(this.x, this.y, this.strokeSize, this.strokeSize);\n pop();\n}", "function sendMessageToServer(message) {\n socket.send(message);\n }", "send(peer_id, data) {\n this.peers[peer_id].send(data);\n }", "sendInfo() {\n this.sendPlayers();\n this.sendObjects();\n }", "function point(xx,yy){\nthis.x = xx;\nthis.y = yy;\n}", "function chartPoint(data, symbol) {\n chartsymbol = symbol + '_updatedchart';\n if (Number(data)) {\n chartentry[symbol] = [time, Number(data)];\n io.sockets.emit(chartsymbol, chartentry[symbol]);\n //console.log(chartsymbol + ':' + chartentry[symbol]);\n }\n}", "function displayCoordinates(pnt) {\n var lat = pnt.lat();\n lat = lat.toFixed(4);\n var lng = pnt.lng();\n lng = lng.toFixed(4);\n \n var res = setRectangle(new google.maps.LatLng(lat,lng), selBoxSize);\n \n sendMessageData(\"SEND_GEOPOSITION_MESSAGE\",[lat,lng,res[0],res[1]]);\n console.log(\"Latitude: \" + lat + \" Longitude: \" + lng);\n}", "addPointToPointEntities(name, position) {\n var pointEntity = new Entity({\n name: name,\n position: new ConstantPositionProperty(position),\n billboard: {\n image: this.svgPoint,\n eyeOffset: new Cartesian3(0.0, 0.0, -50.0)\n }\n });\n this.pointEntities.entities.add(pointEntity);\n this.dragHelper.updateDraggableObjects(this.pointEntities);\n if (isDefined(this.onPointClicked)) {\n this.onPointClicked(this.pointEntities);\n }\n }", "function sendgpstoemail() {\n\t\n\t// send gps to selected email\n\t//ajax(\"sendgps\",{id:cid,email:email},function(d) {\n\t\tinfo(\"GPS data sent to \"+email);\n\t//});\n\n}", "function geoSuccess(position) {\n var lat = position.coords.latitude;\n var lng = position.coords.longitude;\n window._TRACKER.geo = `${lat}|${lng}`;\n }", "function sendPlayerMove(index) {\n\tsocket.emit('player move', index);\n }", "function clickOnPoint() {\n var x = 58,\n y = 275;\n _DygraphOps[\"default\"].dispatchMouseDown_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseMove_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseUp_Point(g, x, y);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the new added catalog name is legal or not. The new added catalog name cannot be zero, cannot longer than 10 characters,too. Also need to check the duplication.
function CheckCatalog( $NewCatalogString ) { if($CatalogInputString.length == 0) { alert("Catalog Name cannot be blank!"); return -1; } else if($CatalogInputString.length > 10) { alert("It is too long! Input it one more time."); return -1; } else if(0) { alert("This catalog name is already exist."); return -1; } else { return 0; } }
[ "function validName(input) {\n return input.length > 0\n }", "function name_check() {\r\n name_warn();\r\n final_validate();\r\n}", "function groupNameValid(name) {\n return (typeof name === \"string\" && name.length <= 50 && name.length > 2)\n}", "checkName(item) {\n var name = item.name;\n if(name.length > 28) {\n return name.substr(0,28)+'...';\n } else {\n return name;\n }\n }", "function addCourse() {\n var spaced = addSpace(document.getElementById(\"input\").value);\n var Sanitize1 = spaced;\n var upperCase = Sanitize1.toUpperCase();\n var re = /^[A-Z]{4}\\s{1}[A-Z0-9]+/;\n if (re.test(upperCase) == 0) {\n alert(\"Not a Valid Input. Please follow this format: COEN 10\");\n document.getElementById(\"input\").innerHTML = \"\";\n return;\n }\n\n if (courses.indexOf(upperCase) != -1) {\n alert(\"This Course has Already Been Entered\");\n return;\n }\n courses.push(upperCase);\n populate();\n}", "function check_gardening_botanical_name() \n\t\t{ \n\t\t\tvar boname_length = $(\"#update_gardening_botanical_name\").val().length;\n\n\t\t\tif(boname_length == \"\" || boname_length == null)\n\t\t\t\t{\n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Please fill in data into the field\"); \n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t\t}\n\t\t\t\n\t\t\telse if(boname_length <2 || boname_length > 20) {\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Should be between 2-20 characters\");\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t}\n\t\t\t\n\t\t\telse \n\t\t\t{\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").hide();\n\t\t\t}\n\t\t}", "function isNameOK(field) {\r\n\t\r\n\tvar name = field.value.trim();\r\n\tconsole.log(name); // TEST CODE\r\n\t\r\n\tif (emptyString(name)) {\r\n\t\talert('Le nom du groupe doit être renseigné.');\r\n\t\treturn false;\r\n\t}\r\n\telse if (fiftyChar(name)) {\r\n\t\talert('Le nom du groupe ne peut pas dépasser cinquante caractères.');\r\n\t\treturn false;\r\n\t}\r\n\telse {\r\n\t\treturn true;\r\n\t}\r\n}", "function check_blog_name() {\n\t$blogNameInput = jQuery('#blogname');\n\tblogName = $blogNameInput.val();\n\n\t// if a group blog already exists a hidden blog name input still exists on the page\n\t// so we'll bail here if that's the case\n\tif ($blogNameInput.attr('type') == 'hidden') { return false; }\n\n\t// subdomains cannot be longer than 63 characters so we need to enforce that\n\tif (blogName && blogName.length > 63) {\n\n\t\t// remove any existing warning\n\t\tjQuery('#blog-name-warning').remove();\n\n\t\t// alert the user tha their subdomain is too long\n\t\t$blogNameInput.css('borderColor', 'red')\n\t\t\t\t\t\t\t\t\t.next()\n\t\t\t\t\t\t\t\t\t.after('<p>This blog name is over 63 characters. This is not allowed, choose something a bit shorter.</p>')\n\t\t\t\t\t\t\t\t\t.next('p')\n\t\t\t\t\t\t\t\t\t.attr('id', 'blog-name-warning')\n\t\t\t\t\t\t\t\t\t.css('color', 'red');\n\n\t\t// hide the next button\n\t\tjQuery('#group-creation-next').hide()\n\n\t\t// else, check if the blog's subdomain is over 15 characters\n\t} else if (blogName && blogName.length >= 15) {\n\n\t\t// remove any existing warning\n\t\tjQuery('#blog-name-warning').remove();\n\n\t\t// alert the user that their subdomain should probably be shortened\n\t\t$blogNameInput.css('borderColor', 'red')\n\t\t\t\t\t\t\t\t\t.next()\n\t\t\t\t\t\t\t\t\t.after('<p>This blog name is over 15 characters. For a URL that is more memorable and easier to type, consider something a bit shorter.</p>')\n\t\t\t\t\t\t\t\t\t.next('p')\n\t\t\t\t\t\t\t\t\t.attr('id', 'blog-name-warning')\n\t\t\t\t\t\t\t\t\t.css('color', 'red');\n\n\t\t// show the next button\n\t\tjQuery('#group-creation-next').show()\n\n\t} else {\n\t\t//reset inputs\n\t\tjQuery('#blog-name-warning').remove();\n\t\t$blogNameInput.css('borderColor', '#eee');\n\t\tjQuery('#group-creation-next').show();\n\t}\n\n\t/* @mention Compose Scrolling */\n\tif ( jQuery.query.get('r') && jQuery('textarea#whats-new').length ) {\n\t\tjq.scrollTo( jq('textarea#whats-new'), 500, {\n\t\t\toffset:-325,\n\t\t\teasing:'easeOutQuad'\n\t\t} );\n\t}\n\n\t// Fix bbPress !important styling - Thanks bbPress!\n\tjQuery('body.logged-in p.bbp-forum-description').attr('style', 'margin-right: 120px !important');\n}", "function saveRecord_PreventDuplicateScheduleName(type)\r\n{\r\n var stBDSName = nlapiGetFieldValue('name');\r\n var isValid = true;\r\n var arrBDS = getDuplicateBillDistributionSchedule(stBDSName);\r\n \r\n //alert(arrBDS + ' ' + stBDSName + ' ' + type + ' ' + 'id=' + nlapiGetRecordId());\r\n \r\n if(arrBDS)\r\n {\r\n alert('Error Duplicate Record. Details: There is already a Bill Distribution Schedule Name \"' + stBDSName + '\" that exists.');\r\n isValid = false;\r\n }\r\n return isValid;\r\n}", "function isValidPackageName(name) {\n // return isNormalPackageName(name) || isScopedPackageName(name);\n return validate(name).validForNewPackages;\n}", "function customerHasValidLastName (cust) {\n return typeof cust === 'string' && cust !== '' && cust.length < 501;\n}", "function existsNameAlready() {\r\n\t\t$requests.getAllCategories(self.getCategories);\r\n\r\n\t\tfor (var i = 0; i < self.existingCategories.length; i++)\r\n\t {\r\n\t if (self.existingCategories[i].name === self.name)\r\n\t {\r\n\t return true;\r\n\t }\r\n\t }\r\n\t return false;\r\n\t\t\r\n\t}", "function ValidNameField(sender) {\n var id = $(sender).attr('id');\n var nameField = $('#' + id).val();\n var regexpp = /^[a-zA-Z][a-zA-ZéüöóêåÁÅÉá .´'`-]*$/\n var Exp = /^[0-9]+$/;\n\n if (nameField.length > 0) {\n if (nameField.trim() == '')\n return false\n else {\n if (Exp.test(nameField.trim()))\n return false\n else\n return regexpp.test(nameField)\n }\n } else\n return true;\n}", "function validateUpdateOwnerName(firstname,e) {\n if (!isValidName(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει τουλάχιστον δύο χαρακτήρες)');\n e.preventDefault();\n } else if (!isOnlyLetters(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει μόνο γράμματα)');\n e.preventDefault();\n } else {\n $(\".nameOwnerUpdateErr\").text(\"\");\n }\n } //end function ", "function validUsername(username) {\n return (username.trim().length) >= 3;\n}", "function hasValidNameField(manifest) {\n return misc_utils_1.isTruthyString(manifest[ManifestFieldNames.Name]);\n}", "function validateSetNameInput(value) {\n return !!value && value.length < maxSetName && value in allSets === false && reservedSetNames.indexOf(value) === -1;\n }", "isTickerValid(str) {\n str.trim();\n if (/^[a-zA-Z]+$/.test(str) && str.length <= 4) {\n return true;\n }\n return false;\n }", "function isValidGroupName(name) {\n\treturn isValidUsername(name);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function which iterates across each account given inside an object with email/password pair. And execute the given callback function, with those parameters.
function forEachAccount( accountObject, func ) { // Iterate each email-pass pair for(var email in accountObject) { if(accountObject.hasOwnProperty(email)) { // Get the password, var pass = accountObject[email]; // Login loginAccount( email, pass ); // Callback function func(email, pass); } } }
[ "function processSignupCallback(request, email, password, done){\n\t\t\n\t}", "getAccountsAsync(callback) {\n this.web3.eth.getAccounts((err, res) => {\n callback(err, res);\n });\n }", "function findUserByEmail(array, value, callback) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].email === value) {\n callback(null, array[i]);\n return;\n }\n }\n callback(null, undefined);\n}", "function iterateAvatars(err, obj) {\n if (err) {\n throw err;\n }\n\n for (var index in obj) {\n let login = obj[index].login;\n let path = \"avatars/\" + login; //missing .jpg or .png here, will be added in downloadImageByURL\n let avatarURL = obj[index].avatar_url;\n\n downloadImageByURL(avatarURL, path);\n }\n}", "returnableAccount(account){}", "static findUserByEmail(email, callback) {\n Account.findOne({'email': email}, (err, data) => {\n if(err) {\n return callback(err, null);\n } else {\n return callback(null, data);\n }\n });\n }", "inviteUserToCompanies (callback) {\n\t\tBoundAsync.timesSeries(\n\t\t\tthis,\n\t\t\t2,\n\t\t\tthis.inviteUserToCompany,\n\t\t\tcallback\n\t\t);\n\t}", "function matchingID(email, pass) {\n for (let key in users) {\n if ((users[key].password === pass) && (users[key].email === email)) {\n return users[key].id;\n }\n }\n}", "function getAccount(username){\n var matchedAccount;\n\n accounts.forEach(function(account){\n if (account.username === username){\n matchedAccount = account;\n }\n\n });\n\n return matchedAccount;\n\n\n}", "getItinerary(account_id, callback) {\n let sql = \"SELECT * FROM reservations WHERE user=$account_id\";\n this.db.all(sql, {\n $user: account_id\n }, (err, rows) => {\n if(err) {\n throw(err);\n }\n return callback(rows);\n });\n }", "function handleUserGetProfileOnSuccess(user_get_profile_obj, billerCorpId, programId, isMsg) {\n\t/* Check first and last name against property file default name. */\n if (user_get_profile_obj.user.firstName == messages[\"createAccount.firstNameInput\"]) {\n \tuser_get_profile_obj.user.firstName = \"\";\n }\n\n if (user_get_profile_obj.user.lastName == messages[\"createAccount.lastNameInput\"]) {\n \tuser_get_profile_obj.user.lastName = \"\";\n }\n\n bpGetCorpAccountMap[11] = user_get_profile_obj.user.firstName;\n bpGetCorpAccountMap[13] = user_get_profile_obj.user.lastName;\n bpGetCorpAccountMap[9] = user_get_profile_obj.user.phone;\n bpGetCorpAccountMap[20] = user_get_profile_obj.user.email;\n bpGetCorpAccountMap[22] = user_get_profile_obj.user.phone;\n if (user_get_profile_obj.userAddress != null) {\n \tbpGetCorpAccountMap[14] = user_get_profile_obj.userAddress.address1;\n \tbpGetCorpAccountMap[15] = user_get_profile_obj.userAddress.address2;\n \tbpGetCorpAccountMap[16] = user_get_profile_obj.userAddress.city;\n \tbpGetCorpAccountMap[17] = user_get_profile_obj.userAddress.state;\n \tbpGetCorpAccountMap[18] = user_get_profile_obj.userAddress.zip;\n }\n handleGetBillerCreds(billerCorpId, programId, isMsg);\n}", "function createAccount(account, masterPassword){\r\nvar accounts = getAccounts(masterPassword);\r\naccounts.push(account);\r\n\r\n}", "function finishedCreatingCallback(err, usersForCloudFormation, IAMuserPassword, groupName) {\n if(err) {\n cloudformationsender.sendResponse(theEvent, theContext, \"FAILED\", {});\n\t}\n\telse {\t\n\t cloudformationsender.sendResponse(theEvent, theContext, \"SUCCESS\", {\n \"IamPassword\": IAMuserPassword,\n \"Users\": usersForCloudFormation,\n \"IamGroup\": groupName \n });\n }\n}", "function validateAccount() {\n let uName = document.getElementById('username').value;\n let pword = document.getElementById('password').value;\n testAccount(uName, pword);\n}", "signup(username, password, email, callback) {\n let sql = \"SELECT * FROM users WHERE username=$username\";\n var self = this;\n this.db.get(sql, {\n $username: username\n }, (err, rows) => {\n if(err) {\n throw(err);\n } else if(!rows) {\n let insert_statement = \"INSERT INTO users(username, password, admin, email) VALUES ($username, $password, $admin, $email)\";\n this.db.run(insert_statement, {\n $username: username,\n $password: password,\n $admin: false,\n $email: email,\n }, (err) => {\n if(err) {\n throw(err);\n }\n });\n // logs in if conditions are met\n //console.log(\"gave true\");\n callback(true);\n } else {\n //console.log(rows);\n callback(false);\n }\n\n });\n }", "function getAll() {\r\n var i = 0;\r\n var trans = db.transaction([\"utenti\"]);\r\n var store = trans.objectStore(\"utenti\");\r\n\r\n store.openCursor().onsuccess = function(event) {\r\n var cursor = event.target.result;\r\n if (cursor) {\r\n arrayUsers[i]= [cursor.value.username, cursor.value.credito];\r\n i++;\r\n cursor.continue();\r\n }\r\n };\r\n}", "getEmails(callback) {\n this.emailTracking\n .orderBy(\"created_at\")\n .onSnapshot(snapshot => {\n snapshot.docChanges().forEach(change => {\n if(change.type === \"added\") {\n // do stuff with all emails in the database (check for time, check for seats, etc)\n // console.log(\"going through emails\");\n callback(change.doc.data());\n }\n })\n })\n }", "function performTasksOnSuccessfulLogin() {\n exports.changePasswordAtNextLogon = null;\n exports.loggedInAccountDisplayText = null;\n\n //spWebService.setHeader('X-ReadiNow-Client-Version', spAppSettings.initialSettings.platformVersion); // For information purposes only\n\n if (exports.isSignedIn() &&\n exports.accountId) {\n\n spConsoleService.getSessionInfo().then(function (sessionInfo) {\n spAppSettings.setSessionInfo(sessionInfo);\n });\n\n spEntityService.getEntity(exports.accountId, 'changePasswordAtNextLogon, accountHolder.name, k:defaultNavSection.name, k:defaultNavElement.{ name, k:resourceInFolder*.{ name, isOfType.alias} }', { hint: 'checklogin', batch: true }).then(function (account) {\n if (account) {\n exports.defaultUserLandingInfo = exports.defaultUserLandingInfo || {};\n exports.defaultUserLandingInfo.defaultNavSection = account.defaultNavSection;\n exports.defaultUserLandingInfo.defaultNavElement = account.defaultNavElement;\n\n // Check to see if the user must change the password at login time and caches it locally.\n exports.changePasswordAtNextLogon = account.changePasswordAtNextLogon;\n\n // if the current user account is linked to an accountholder then use the accountholder name else use username for display text\n var accountHolder = account.getLookup('core:accountHolder');\n if (accountHolder && accountHolder.idP) {\n exports.accountHolderId = accountHolder.idP;\n }\n if (accountHolder && accountHolder.name) {\n exports.loggedInAccountDisplayText = accountHolder.name;\n }\n else {\n exports.loggedInAccountDisplayText = exports.getAuthenticatedIdentity().username;\n }\n }\n });\n }\n }", "function multipleCallbacks (myObject, callback1, callback2){\n var myObject = {status: ['success', 'error']};\n var keyValue = Object.values(myObject.status);\n for (let i=0; i<keyValue.length; i++){\n if (keyValue[i] === 'success'){\n return callback1;\n } else return callback2;\n}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Account Report Add function to show bank customer report
function accountReport(customer) { showAccountInfo(customer.accountHolder, customer.accountNumber, customer.businessName); showAddresses(customer.addresses); showPhoneNums(customer.phoneNumbers); showTransactions(customer.accountTransactions, customer.balance); if (customer.favMelon === 'casaba' || customer.numPets > 5){ console.log("Congratz on being a dope customer!"); } }
[ "function createVoucherReport(journal, report, docNumber, rowsToProcess) {\n\n //Each voucher on a new page\n report.addPageBreak();\n\n var date = \"\";\n var doc = \"\"; \n var desc = \"\";\n var totDebit = \"\";\n var totCredit = \"\";\n var line = 0;\n var totTransaction = calculateTotalTransaction(docNumber, journal, report); //Calculate the total value of the transaction\n\n /* Calculate the total number of pages used to print each voucher */\n var totRows = calculateTotalRowsOfTransaction(docNumber, journal, report);\n if (totRows > generalParam.numberOfRows) {\n var totalPages = Banana.SDecimal.divide(totRows, generalParam.numberOfRows);\n totalPages = parseFloat(totalPages);\n totalPages += 0.499999999999999;\n var context = {'decimals' : 0, 'mode' : Banana.SDecimal.HALF_UP}\n totalPages = Banana.SDecimal.round(totalPages, context);\n } else {\n var totalPages = 1;\n }\n\n //Define table info: name and columns\n var tableInfo = report.addTable(\"table_info\");\n var col1 = tableInfo.addColumn(\"col1\");\n var col2 = tableInfo.addColumn(\"col2\");\n var col3 = tableInfo.addColumn(\"col3\");\n var col4 = tableInfo.addColumn(\"col4\");\n var col5 = tableInfo.addColumn(\"col5\");\n var col6 = tableInfo.addColumn(\"col6\");\n var col7 = tableInfo.addColumn(\"col7\");\n var col8 = tableInfo.addColumn(\"col8\");\n var col9 = tableInfo.addColumn(\"col9\");\n var col10 = tableInfo.addColumn(\"col10\");\n var col11 = tableInfo.addColumn(\"col11\");\n\n //Define table transactions: name and columns\n\n if (Banana.document.table('ExchangeRates')) {\n var table = report.addTable(\"table\");\n var ct1 = table.addColumn(\"ct1\");\n var ct2 = table.addColumn(\"ct2\");\n var ct3 = table.addColumn(\"ct3\");\n var ct4 = table.addColumn(\"ct4\");\n var ct5 = table.addColumn(\"ct5\");\n var ct5 = table.addColumn(\"ct6\");\n var cts1 = table.addColumn(\"cts1\");\n var ct4 = table.addColumn(\"ct7\");\n var cts2 = table.addColumn(\"cts2\");\n var ct5 = table.addColumn(\"ct8\");\n var cts3 = table.addColumn(\"cts3\");\n var ct6 = table.addColumn(\"ct9\");\n } else {\n var table = report.addTable(\"table\");\n var c1 = table.addColumn(\"c1\");\n var c2 = table.addColumn(\"c2\");\n var c3 = table.addColumn(\"c3\");\n var cs1 = table.addColumn(\"cs1\");\n var c4 = table.addColumn(\"c4\");\n var cs2 = table.addColumn(\"cs2\");\n var c5 = table.addColumn(\"c5\");\n var cs3 = table.addColumn(\"cs3\");\n var c6 = table.addColumn(\"c6\");\n }\n\n //Define table signatures: name and columns\n var tableSignatures = report.addTable(\"table_signatures\");\n var colSig1 = tableSignatures.addColumn(\"colSig1\");\n var colSig2 = tableSignatures.addColumn(\"colSig2\");\n var colSig3 = tableSignatures.addColumn(\"colSig3\");\n var colSig4 = tableSignatures.addColumn(\"colSig4\");\n var colSig5 = tableSignatures.addColumn(\"colSig5\");\n var colSig6 = tableSignatures.addColumn(\"colSig6\");\n\n //Select from the journal all the given rows, take all the needed data, calculate totals and create the vouchers print\n for (j = 0; j < rowsToProcess.length; j++) {\n for (i = 0; i < journal.rowCount; i++) {\n if (i == rowsToProcess[j]) {\n var tRow = journal.row(i);\n date = tRow.value(\"Date\");\n }\n }\n }\n\n /* 1. Print the date and the voucher number */\n printInfoVoucher(tableInfo, report, docNumber, date, totalPages);\n\n /* 2. Print the all the transactions data */\n printTransactions(table, journal, line, rowsToProcess);\n \n /* 3. Print the total line */\n printTotal(table, totDebit, totCredit, report, totalPages, totTransaction);\n \n /* 4. Print the signatures line */\n printSignatures(tableSignatures, report);\n\n currentPage++;\n}", "function WriteAccount(acct)\n{\n\tif (typeof(acct) == \"undefined\" || acct == null || !acct)\n\t\treturn \"\"\n\n\tvar Info = \"\"\n\n\tif (Employee.work_country == \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_35\",\"DD\")+\": \"+acct.description+\"\\n\"\n\t}\n\telse\n\t{\n\t\tInfo += getSeaPhrase(\"DD_36\",\"DD\")+\": \"+acct.description+\"\\n\"\n\t}\n\n\tif (Employee.work_country == \"UK\" || acct.country_code == \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_37\",\"DD\")+\": \"+maskDigits(acct.ebank_id, \"x\", 4)+\"\\n\"\n\t}\n\telse if (Employee.work_country == \"CA\" || acct.country_code == \"CA\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_38\",\"DD\")+\": \"+maskDigits(acct.ca_inst_nbr, \"x\", 4)+\"\\n\"\n\t\t+ getSeaPhrase(\"DD_39\",\"DD\")+\": \"+maskDigits(acct.ca_transit_nbr, \"x\", 4)+\"\\n\"\n\t}\n\telse\n\t{\n\t\tInfo += getSeaPhrase(\"DD_40\",\"DD\")+\": \"+maskDigits(acct.ebank_id, \"x\", 4)+\"\\n\"\n\t}\n\n\tInfo += getSeaPhrase(\"DD_41\",\"DD\")+\": \"+maskDigits(acct.ebnk_acct_nbr, \"x\", 4)+\"\\n\"\n\n\tif (Employee.work_country == \"UK\" || acct.country_code == \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_42\",\"DD\")+\": \"+maskDigits(acct.bank_roll_no, \"x\", 4)+\"\\n\"\n\t}\n\n\tInfo += getSeaPhrase(\"DD_43\",\"DD\")+\": \"+acct.ach_dist_order+\"\\n\"\n\n\tif (Employee.work_country != \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_44\",\"DD\")+\": \"\n\t\tif (acct.net_percent != 0)\n\t\t\tInfo += TruncateNbr(acct.net_percent,3)+ per +\" \\n\"\n\t\telse Info += TruncateNbr(acct.deposit_amt,2)+\"\\n\"\n\t}\n\n\tif (Employee.work_country == \"UK\" || acct.country_code == \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_45\",\"DD\")+\": \"\n\t\tif (acct.account_type_xlt.charAt(0) == \"C\")\n\t\t\tInfo += getSeaPhrase(\"DD_46\",\"DD\")+\"\\n\"\n\t\telse Info += getSeaPhrase(\"DD_47\",\"DD\")+\"\\n\"\n\t\tInfo += getSeaPhrase(\"DD_48\",\"DD\")+\": \"+acct.check_desc+\"\\n\"\n\t\t+ getSeaPhrase(\"DD_49\",\"DD\")+\": \"\n\n\t\tif (NonSpace(acct.payable_to))\n\t\t\tInfo += acct.payable_to+\"\\n\"\n\t\telse\n\t\t\tInfo += Employee.first_name+\" \"+Employee.last_name+\"\\n\"\n\n\t\tif (acct.deposit_amt == 0)\n\t\t\tInfo += getSeaPhrase(\"DD_50\",\"DD\")+\": 0.00\\n\"\n\t\telse\n\t\t\tInfo += getSeaPhrase(\"DD_50\",\"DD\")+\": \"+TruncateNbr(acct.deposit_amt,2)+\"\\n\"\n\t\tif (acct.net_percent == 0)\n\t\t\tInfo += getSeaPhrase(\"DD_51\",\"DD\")+\": 0.000\"+ per +\" \\n\"\n\t\telse\n\t\t\tInfo += getSeaPhrase(\"DD_51\",\"DD\")+\": \"+TruncateNbr(acct.net_percent,3)+ per +\" \\n\"\n\t}\n\telse if (Employee.work_country == \"CA\" || acct.country_code == \"CA\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_52\",\"DD\")+\": \"+acct.check_desc+\"\\n\"\n\t}\n\telse\n\t{\n\t\tInfo += getSeaPhrase(\"DD_45\",\"DD\")+\": \"\n\t\tif (acct.account_type_xlt.charAt(0) == \"C\")\n\t\t\tInfo += getSeaPhrase(\"DD_53\",\"DD\")+\"\\n\"\n\t\telse Info += getSeaPhrase(\"DD_47\",\"DD\")+\"\\n\"\n\t}\n\n\tInfo += getSeaPhrase(\"DD_54\",\"DD\")+\": \"\n\tif (acct.default_flag == \"Y\")\n\t\tInfo += getSeaPhrase(\"DD_55\",\"DD\")+\"\\n\"\n\telse Info += getSeaPhrase(\"DD_56\",\"DD\")+\"\\n\"\n\n\tif (Employee.work_country == \"UK\" || acct.country_code == \"UK\")\n\t{\n\t\tInfo += getSeaPhrase(\"DD_57\",\"DD\")+\": \"\n\t}\n\telse\n\t{\n\t\tInfo += getSeaPhrase(\"DD_58\",\"DD\")+\": \"\n\t}\n\tInfo += acct.beg_date+\"\\n\"\n\n\tif (NonSpace(acct.end_date))\n\t\tInfo += getSeaPhrase(\"DD_59\",\"DD\")+\": \"+fmttoday+\"\\n\"\n\tInfo += \"\\n\"\n\n\treturn Info\n}", "function printReport() {\n\n\tvar report = Banana.Report.newReport(param.reportName);\n\n\treport.addParagraph(param.title, \"heading1\");\n\treport.addParagraph(\" \");\n\treport.addParagraph(param.headerLeft + \" - \" + param.headerRight, \"heading3\");\n\treport.addParagraph(\"Periodo contabile: \" + Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"heading4\");\n\treport.addParagraph(\" \");\n\t\n\tvar table = report.addTable(\"table\");\n\ttableRow = table.addRow();\n\ttableRow.addCell(\"ID\", \"bold\", 1);\n\ttableRow.addCell(\"GRUPPO\", \"bold\", 1)\n\ttableRow.addCell(\"DESCRIZIONE\", \"bold\", 1);\n\ttableRow.addCell(\"IMPORTO\", \"bold\", 1);\n\n\tfor (var k = 0; k < form.length; k++) {\n\t\n\tif (form[k].sum) {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"bold\", 1);\n\t\ttableRow.addCell(form[k].gr, \"bold\", 1);\n\t\ttableRow.addCell(form[k].description, \"bold\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight bold\", 1);\n\t} else {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"\", 1);\n\t\ttableRow.addCell(form[k].gr, \"\", 1);\n\t\ttableRow.addCell(form[k].description, \"\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight\", 1);\n\t\t}\n\t}\n\n\t//Add the footer to the report\n\taddFooter(report)\n\n\t//Print the report\n\tvar stylesheet = createStyleSheet();\n\tBanana.Report.preview(report, stylesheet);\n}", "function monthlyReport() {\n\n}", "function createAccount (account) {\r\n accounts.push(account);\r\n return account;\r\n}", "init() {\n this.drawAccountInfo();\n }", "function addHeader(report) {\n var pageHeader = report.getHeader();\n pageHeader.addClass(\"header\");\n if (param.company) {\n pageHeader.addParagraph(param.company, \"heading\");\n }\n pageHeader.addParagraph(\"VAT Report Transactions currency to CHF\", \"heading\");\n pageHeader.addParagraph(Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"\");\n pageHeader.addParagraph(\" \", \"\");\n pageHeader.addParagraph(\" \", \"\");\n}", "returnableAccount(account){}", "function phpVATReport(params) {\n if (params) {\n var VATReportObject = Wtf.getCmp(params.reportID);\n if (VATReportObject == null) {\n VATReportObject = new Wtf.account.phpVATReport({\n title: Wtf.util.Format.ellipsis(params.title),\n tabTip: params.titleQtip,\n id: params.reportID,\n closable: true,\n border: false,\n params: params,\n layout: 'fit',\n iconCls: 'accountingbase receivepaymentreport'\n });\n Wtf.getCmp('as').add(VATReportObject);\n }\n Wtf.getCmp('as').setActiveTab(VATReportObject);\n Wtf.getCmp('as').doLayout();\n }\n}", "function CSRSaleWiseCustomer() {\r\n\tvar input = document.getElementById('csrcatId'), list = document\r\n\t\t\t.getElementById('csrcatId_drop'), i, csrcatId;\r\n\tfor (i = 0; i < list.options.length; ++i) {\r\n\t\tif (list.options[i].value === input.value) {\r\n\t\t\tcsrcatId = list.options[i].getAttribute('data-value');\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tvar params = {};\r\n\tparams[\"mscatId\"] = csrcatId;\r\n\tparams[\"methodName\"] = \"CCSRSaleWiseCustomer\";\r\n\r\n\t$\r\n\t\t\t.post(\r\n\t\t\t\t\t'/SMT/jsp/utility/controller.jsp',\r\n\t\t\t\t\tparams,\r\n\t\t\t\t\tfunction(data) {\r\n\t\t\t\t\t\t$('#CSR3SaleWiseCustomerReport').dataTable()\r\n\t\t\t\t\t\t\t\t.fnClearTable();\r\n\t\t\t\t\t\tvar jsonData = $.parseJSON(data);\r\n\t\t\t\t\t\tvar catmap = jsonData.list;\r\n\r\n\t\t\t\t\t\t$(document)\r\n\t\t\t\t\t\t\t\t.ready(\r\n\t\t\t\t\t\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t\t\t\t\t\t$('#CSR3SaleWiseCustomerReport')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.DataTable(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfnRowCallback : function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnRow,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taData,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tiDisplayIndex) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"th:first\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnRow)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tiDisplayIndex + 1);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn nRow;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"footerCallback\" : function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trow,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tend,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdisplay) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar api = this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.api(), data;\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Remove\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// formatting\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// to get\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// integer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// data for\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// summation\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar intVal = function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn typeof i === 'string' ? i\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.replace(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/[\\$,]/g,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'') * 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: typeof i === 'number' ? i\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: 0;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t5)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t5)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t6)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t6)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t7)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t7)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t8)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t8)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/*\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * // Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * pageTotal =\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 11 )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * function\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * (a, b) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * return\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * intVal(a) +\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * intVal(b); },\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 0 );\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * //\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * footer $(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * api.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 11\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * ).footer()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * ).html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * parseFloat(pageTotal).toFixed(2)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * );\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * console.log(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * pageTotal);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * // Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * pageTotal =\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 12 )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * .reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * function\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * (a, b) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * return\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * intVal(a) +\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * intVal(b); },\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 0 );\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * //\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * footer $(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * api.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * 12\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * ).footer()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * ).html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * parseFloat(pageTotal).toFixed(2)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * );\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * console.log(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * pageTotal);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdestroy : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsearching : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolumns : [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"srNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"billNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"barcodeNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"categoryName\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"itemName\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"quantity\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"salePrice\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"gst\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"spWithoutTax\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"discount\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"taxAmount\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"ReturnAmount\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"saleReturnDate\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/*\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * {\"data\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"totalperItem\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"width\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"5%\",\"defaultContent\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"\",\"class\":\"hidden\"},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * {\"data\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"gst\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"width\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"5%\",\"defaultContent\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"\"}, {\"data\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"taxAmount\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"width\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"5%\",\"defaultContent\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"\"}, {\"data\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"totalAmt\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"width\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"5%\",\"defaultContent\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * \"\"},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t],\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdom : 'Bfrtip',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbuttons : [\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'copyHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'excelHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'csvHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'pdfHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle : function() {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn \"Category Wise Credit Customer Sale Return Report\";\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torientation : 'landscape',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageSize : 'LEGAL',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitleAttr : 'PDF'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} ]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tvar mydata = catmap;\r\n\t\t\t\t\t\t$('#CSR3SaleWiseCustomerReport').dataTable().fnAddData(\r\n\t\t\t\t\t\t\t\tmydata);\r\n\r\n\t\t\t\t\t}).error(function(jqXHR, textStatus, errorThrown) {\r\n\t\t\t\tif (textStatus === \"timeout\") {\r\n\t\t\t\t\t$(loaderObj).hide();\r\n\t\t\t\t\t$(loaderObj).find('#errorDiv').show();\r\n\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n}", "function createAccount(account, masterPassword){\r\nvar accounts = getAccounts(masterPassword);\r\naccounts.push(account);\r\n\r\n}", "reportBalance (bal) {\n if (this.funded || this.assetID === -1) return\n const page = this.page\n const asset = app().assets[this.assetID]\n const fee = this.regFee\n\n if (bal.available <= fee.amount) {\n page.balance.textContent = Doc.formatCoinValue(bal.available, asset.info.unitinfo)\n return\n }\n\n Doc.show(page.balCheck)\n Doc.hide(page.balUncheck, page.balanceBox)\n this.funded = true\n if (this.progressed) this.success()\n }", "function displayInfo(name, account, business) {\n console.log(`Account Holder Name: ${name}`);\n console.log(`Account Holder Number: ${account}`);\n console.log(`Business Name: ${business}`);\n}", "function addFooter(report, param) {\n var date = new Date();\n var d = Banana.Converter.toLocaleDateFormat(date);\n report.getFooter().addClass(\"footer\");\n report.getFooter().addText(d + \" - \" + param.pageCounterText + \" \");\n report.getFooter().addFieldPageNr();\n}", "function calculateTotalTransaction(docNumber, journal, report) {\n \n var tDebit = \"\";\n var tCredit = \"\";\n var arr = [];\n\n for (var i = 0; i < journal.rowCount; i++) {\n var tRow = journal.row(i);\n if (tRow.value('Doc') === docNumber) {\n var amount = Banana.SDecimal.abs(tRow.value('JAmount'));\n if (Banana.SDecimal.sign(tRow.value('JAmount')) > 0 ) {\n tDebit = Banana.SDecimal.add(tDebit, amount, {'decimals':2});\n } else {\n tCredit = Banana.SDecimal.add(tCredit, amount, {'decimals':2});\n }\n }\n }\n arr.push(tDebit);\n arr.push(tCredit);\n return arr;\n}", "function addFooter(report) {\n report.getFooter().addClass(\"footer\");\n var versionLine = report.getFooter().addText(param.bananaVersion + \", \" + param.scriptVersion + \", \", \"description\");\n //versionLine.excludeFromTest();\n report.getFooter().addText(\"Pagina \", \"description\");\n report.getFooter().addFieldPageNr();\n}", "onCreditAdd() {\n\t\tconst newCredit = new Credit(this.props.uuidGenerator.generate());\n\t\tthis.order.credits.push(newCredit);\n\t}", "loadAtmCash(amount) {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n this.cash += amount;\n console.log('ATM account credited to' + amount);\n this.logs.push(this.currentUser.id + 'ATM account credited to' + amount)\n } else console.log('Access is denied')\n } else console.log('authorization required');\n }", "function printBillerData() {\n\t$(\"#addBil_billerName\").html(bp_biller_corp_creds_obj.name);\n\t$('#addBil_billerType').text(bp_biller_corp_creds_obj.industryCategory);\n\tvar postingCategories = bp_biller_corp_creds_obj.postingCategories;\n\tvar postingCatgry = \"\";\n\tfor (var index = 0; index < postingCategories.length; index++) {\n\t\tif (postingCategories[index].id === 1|| postingCategories[index].id === 4) {\n\t\t\tpostingCatgry = messages[\"postingCategoryDesc.1\"];\n\t\t\t$(\"#addBil_deliveryIcon\").show();\n\t\t\tpostingCatgrylabel = postingCategories[index].label;\n\t\t\tIsExpress = true;\n\t\t} else if (postingCategories[index].id === 2|| postingCategories[index].id === 3) {\n\t\t\t/*postingCatgry1 = messages[\"postingCategoryDesc.2\"];*/\n\t\t\t$(\"#addBil_deliveryIcon\").hide();\n\t\t\tpostingCatgrylabel1 = postingCategories[index].label;\n\t\t}\n\t}\n\tif(addBill){\n\t\t$(\"#addEditLabel\").html(messages[\"addBill.addBillLabel\"]);\n\t}else{\n\t\t$(\"#addEditLabel\").html(messages[\"addBill.editBill\"]);\n\t}\n\t$('#addBil_postingCategoryLanguage').text(postingCatgry);\n\tif($('#addBil_postingCategoryLanguage').html().length == 0){\n\t\t$('.add_bill_txt.pipe').hide();\n\t}else{\n\t\t$('.add_bill_txt.pipe').show();\n\t}\n\tif (userNickName === null) {\n\t\tuserNickName = bp_biller_corp_creds_obj.name;\n\t\tvar nickNameCounter = 1;\n\t\tuserNickName = getUniqueNickname(userNickName, nickNameCounter, userNickName);\n\t}\n\t$('#nickName').val(userNickName);\n\t$('#nickName').focus();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Borrowed from node source without `normalizedArgsSymbol` symbol setting (net.js) Returns an array [options] or [options, cb]
function normalizeArgs(args) { var arr; if (args.length === 0) { arr = [{}, null]; arr[normalizedArgsSymbol] = true; return arr; } var arg0 = args[0]; var options = {}; if (typeof arg0 === 'object' && arg0 !== null) { // (options[...][, cb]) options = arg0; } else if (isPipeName(arg0)) { // (path[...][, cb]) options.path = arg0; } else { // ([port][, host][...][, cb]) options.port = arg0; if (args.length > 1 && typeof args[1] === 'string') { options.host = args[1]; } } var cb = args[args.length - 1]; if (typeof cb !== 'function') arr = [options, null]; else arr = [options, cb]; return arr; }
[ "function normalizeRequestArgs(\n httpModule,\n requestArgs,\n) {\n let callback, requestOptions;\n\n // pop off the callback, if there is one\n if (typeof requestArgs[requestArgs.length - 1] === 'function') {\n callback = requestArgs.pop() ;\n }\n\n // create a RequestOptions object of whatever's at index 0\n if (typeof requestArgs[0] === 'string') {\n requestOptions = urlToOptions(new url.URL(requestArgs[0]));\n } else if (requestArgs[0] instanceof url.URL) {\n requestOptions = urlToOptions(requestArgs[0]);\n } else {\n requestOptions = requestArgs[0];\n }\n\n // if the options were given separately from the URL, fold them in\n if (requestArgs.length === 2) {\n requestOptions = { ...requestOptions, ...requestArgs[1] };\n }\n\n // Figure out the protocol if it's currently missing\n if (requestOptions.protocol === undefined) {\n // Worst case we end up populating protocol with undefined, which it already is\n /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // Because of that, we cannot rely on `httpModule` to provide us with valid protocol,\n // as it will always return `http`, even when using `https` module.\n //\n // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue.\n if (nodeVersion.NODE_VERSION.major && nodeVersion.NODE_VERSION.major > 8) {\n requestOptions.protocol =\n _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) ||\n _optionalChain([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) ||\n _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]);\n } else {\n requestOptions.protocol =\n _optionalChain([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) ||\n _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) ||\n _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]);\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n }\n\n // return args in standardized form\n if (callback) {\n return [requestOptions, callback];\n } else {\n return [requestOptions];\n }\n}", "function normalizeOptions(options) {\n options = options || {};\n return {\n concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages),\n format: options.format === undefined ? isomorphic_node_1.format\n : (typeof options.format === \"function\" ? options.format : false),\n };\n}", "function getArguments(cmd) {\n var args;\n $.jsonRPC.request('doc.help', {\n params: [cmd],\n async: false,\n success: function(result) {\n args = result.arguments;\n }\n });\n return args;\n }", "function argv(state, head, kwterm) {\n var result = [];\n var cs = clone(state);\n var t;\n while ((t = term(cs, head, kwterm)) !== undefined) {\n result.push(t);\n }\n\n if (result.length === 0) {\n error('Term expected', state);\n } else {\n copy(cs, state);\n return result.length === 1 ? result[0] : result;\n }\n }", "_parse(args) {\n const parsed = args.map(arg => {\n if (arg.includes('=')) {\n const [flag, value] = arg.split('=');\n const command = this._commandParser.getCommand(flag);\n return new Argument(command, value);\n } else {\n const command = this._commandParser.getCommand(arg);\n return new Argument(command, null);\n }\n });\n\n return parsed;\n }", "function parseArgList(arglist) {\n Blockly.Quizme.options = {};\n if (arglist) {\n var params = arglist.split('&');\n for (var i = 0; i < params.length; i++) {\n var keyval = params[i].split('=');\n Blockly.Quizme.options[keyval[0]] = keyval[1];\n }\n }\n}", "function getArguments(node) {\n if (node && node.arguments && node.arguments.length > 0) {\n return node.arguments;\n }\n return [];\n}", "_validateCommandArguments() {\n const validatedCommandList = _map(this.commandList, (command) => {\n if (typeof command === 'undefined') {\n return null;\n }\n\n const errorMessage = command.validateArgs();\n\n if (errorMessage) {\n // we only return here so all the errors can be thrown at once\n // from within the calling method\n return errorMessage;\n }\n\n command.parseArgs();\n });\n\n return _compact(validatedCommandList);\n }", "static GetOptions(options, defaultOptions) {\n let _options = {};\n if (!options) {\n options = {};\n }\n if (!defaultOptions) {\n defaultOptions = LowPolyPathBuilder.GetDefaultOptions(options ? options.version : undefined);\n }\n for (let param in defaultOptions) {\n if (options[param] === undefined) {\n _options[param] = defaultOptions[param];\n }\n else {\n _options[param] = options[param];\n }\n }\n return _options;\n }", "function GetModuleArgSpec(model, options, appendMainModuleOptions, mainModule, useSdk) {\n var argSpec = GetArgSpecFromOptions(model, options, \"\", mainModule, useSdk);\n if (appendMainModuleOptions) {\n argSpec.push(argSpec.pop() + \",\");\n //if (this.NeedsForceUpdate)\n //{\n // argSpec.push(\"force_update=dict(\");\n // argSpec.push(\" type='bool'\");\n // argSpec.push(\"),\");\n //}\n argSpec.push(\"state=dict(\");\n argSpec.push(\" type='str',\");\n argSpec.push(\" default='present',\");\n argSpec.push(\" choices=['present', 'absent']\");\n argSpec.push(\")\");\n }\n return argSpec;\n}", "get rawArgs() {\n // Slice prefix + command name and trim the start/ending spaces.\n return this.message.content.slice(this.prefix.length + this.invokedName.length).trim();\n }", "function findOptsFromArgs(args, allowExtra) {\n var startArg;\n var endArg;\n var svcs = [];\n var insts = [];\n var extra = [];\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n var eq = arg.indexOf('=');\n if (eq === -1) {\n if (allowExtra) {\n extra.push(arg);\n continue;\n } else {\n throw new errors.UsageError('invalid argument, no \"=\": ' + arg);\n }\n }\n var field = arg.slice(0, eq);\n var value = arg.slice(eq + 1);\n switch (field) {\n case 'service':\n case 'svc':\n case 's':\n svcs.push(value);\n break;\n case 'instance':\n case 'inst':\n case 'i':\n insts.push(value);\n break;\n case 'start':\n startArg = value;\n break;\n case 'end':\n endArg = value;\n break;\n default:\n if (allowExtra) {\n extra.push(arg);\n } else {\n throw new errors.UsageError('unknown field: ' + field);\n }\n }\n }\n\n var dates = parseStartEnd(startArg, endArg);\n\n return {svcs: svcs, insts: insts, start: dates.start, end: dates.end,\n extra: extra};\n}", "static get parseOptionTypes() {\n return {\n ...super.parseOptionTypes,\n ext: 'Array',\n };\n }", "function DEFAULTS(){\n defaultArgs = [];\n for (var i = 0; i<arguments.length; i++) {\n defaultArgs.push(arguments[i]);\n }\n}", "function normalizeOptions(options) {\n try {\n options.schemeDefinition = getSchemeDefinition(options);\n }\n catch (e) {\n console.error(e.message);\n throw e; // rethrow to stop process\n }\n}", "get options() {\n return this._options;\n }", "function printArguments() {\n var i;\n console.log(OS.eol + 'Commands provided to function:');\n for (i = 0; i < process.argv.length; i += 1) {\n console.log(i + ': ' + process.argv[i]);\n }\n }", "function handle_options(optionsArray) {\n var programName = [];\n var currentItem = optionsArray.shift();\n var defaults = amberc.createDefaultConfiguration();\n\n while (currentItem != null) {\n switch (currentItem) {\n case '-C':\n defaults.configFile = optionsArray.shift();\n break;\n case '-p':\n optionsArray.shift.split(',').forEach(function (pairString) {\n var mapping = pairString.split(':');\n defaults.paths[mapping[0]] = mapping[1];\n });\n break;\n case '-l':\n defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));\n break;\n case '-g':\n defaults.jsGlobals.push.apply(defaults.jsGlobals, optionsArray.shift().split(','));\n break;\n case '-n':\n defaults.amdNamespace = optionsArray.shift();\n break;\n case '-D':\n defaults.outputDir = optionsArray.shift();\n break;\n case '-d':\n amber_dir = path.normalize(optionsArray.shift());\n break;\n case '-v':\n defaults.verbose = true;\n break;\n case '-h':\n case '--help':\n case '?':\n case '-?':\n print_usage_and_exit();\n break;\n default:\n defaults.stFiles.push(currentItem);\n break;\n }\n currentItem = optionsArray.shift();\n }\n\n if (1 < programName.length) {\n throw new Error('More than one name for ProgramName given: ' + programName);\n } else {\n defaults.program = programName[0];\n }\n return defaults;\n}", "async function proposeProp14Args() {\n const mixOracle = await ethers.getContract(\"MixOracle\");\n const chainlinkOracle = await ethers.getContract(\"ChainlinkOracle\");\n\n const args = await proposeArgs([\n {\n contract: mixOracle,\n signature: \"registerTokenOracles(string,address[],address[])\",\n args: [\"USDC\", [chainlinkOracle.address], [addresses.mainnet.openOracle]],\n },\n {\n contract: mixOracle,\n signature: \"registerTokenOracles(string,address[],address[])\",\n args: [\"USDT\", [chainlinkOracle.address], [addresses.mainnet.openOracle]],\n },\n {\n contract: mixOracle,\n signature: \"registerTokenOracles(string,address[],address[])\",\n args: [\"DAI\", [chainlinkOracle.address], [addresses.mainnet.openOracle]],\n },\n ]);\n const description = \"Disable uniswap oracle\";\n return { args, description };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests a new shuffled deck from the API. Returns array of objects.
static async newDeck() { try { console.log("Generating deck...") const response = await Axios.get(`${API}/spreads/shuffled`); let deck = response.data console.log("Deck complete."); for (let card of deck) { this.prepCard(card); } return deck; } catch(error) { console.error(error); }; }
[ "static async newMajorDeck() {\n try {\n console.log(\"Generating deck...\")\n const response = await Axios.get(`${API}/cards`);\n let deck = response.data\n console.log(\"Deck complete.\");\n \n //The first 22 cards returned are the major arcana, we drop the rest.\n deck.splice(22)\n \n // Swap cards around to shuffle them.\n for (let i = 0; i < deck.length; i++) {\n let rand = Math.floor(Math.random() * 22);\n [deck[i], deck[rand]] = [deck[rand], deck[i]];\n }\n \n for (let card of deck) {\n this.prepCard(card);\n }\n return deck; \n\n } catch(error) {\n console.error(error);\n };\n }", "function allCards(){\n createFile();\n var data = fs.readFileSync('deck.json');\n var dataParsed = JSON.parse(data);\n var keys = dataParsed[Object.keys(dataParsed)[0]];\n var allCards = \"https://deckofcardsapi.com/api/deck/\" + keys + \"/draw/?count=52\";\n return allCards;\n}", "function createFile(){\n var url = \"https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1\";\n request(url, function(error, response, body){\n if(!error && response.statusCode === 200){\n var data = JSON.stringify(body, null, 2);\n var data1 = JSON.parse(data, null, 2);\n fs.writeFileSync('deck.json', data1);\n }\n });\n}", "function shuffleDeck(deck)\n{\n\t//Create an empty, temporary deck.\n\tshuffledDeck = [];\n\t\n\t/*\n\t\tThe algorithm pulls random cards, one at a time, from the deck and places them into the new deck.\n\t\t\n\t\tThe loop will run for as long as there are cards in the original deck.\n\t*/\n\twhile (deck.length > 0)\n\t{\n\t\t//getRandomInteger comes from utilities.js\n\t\tvar idx = getRandomInteger(0, deck.length - 1);\n\t\tvar card = deck.splice(idx, 1)[0];\n\t\tshuffledDeck.push(card);\n\t}\n\t\n\treturn shuffledDeck;\n}", "function randomDeck(rDeckName, rDeckUrl){\n\tvar randomNum = Math.floor(Math.random()*12);\n\tvar deckChoice = {\n\t\tdeck: rDeckName[randomNum],\n\t\turl: rDeckUrl[randomNum]\n\t}\n\tgetDecklist(deckChoice);\n}", "dealRandomCardsFromDeck(nb) {\n\n let out = new Array(nb);\n let temp = new Card();\n\n for(var i = 0; i < nb; i++) {\n do {\n temp = this.deck.randomCardObject();\n } while(this.cardsDealt.includes(temp));\n\n // Add the card to the cards dealt and to the output array\n this.cardsDealt.push(temp);\n out[i] = temp;\n }\n\n return out;\n }", "async function _getCardsAPI() {\r\n try {\r\n const data = await fetch(\"https://api.pokemontcg.io/v1/cards\");\r\n if (!data) throw new Error();\r\n const cards = await data.json();\r\n const cardsData = await [...Object.values(cards)][0];\r\n const names = await cardsData.map((card) => card.name).sort();\r\n\r\n names.forEach(function (name) {\r\n const html = `<button type= \"button\" class=\"cardButton\" id=\"${name.toLowerCase()}\">${name}</button>`;\r\n listContainer.insertAdjacentHTML(\"beforeend\", html);\r\n\r\n // Save cards data into the local storage. This avoid having to make an AJAX call for each card button click. Saving it into a local storage is not really a good practice as the file is not safe. I do not know how to use Redux...yet!\r\n const save = JSON.stringify(cardsData);\r\n localStorage.setItem(\"cardsData\", save);\r\n\r\n return cardsData;\r\n });\r\n } catch (err) {\r\n _errorMsg(listContainer);\r\n listContainer.style.display = \"none\";\r\n cardInfo.style.display = \"none\";\r\n back.addEventListener(\"click\", _errorMsg(cardPage));\r\n console.log(err);\r\n }\r\n}", "function updateDeck() {\n\tshuffledCardsArray = shuffle(cards); // Calls shuffle function\n\tcreateDeck(shuffledCardsArray); // Calls createDeck function (that takes shuffled array as an argument)\n}", "function deckId(){\n createFile();\n var data = fs.readFileSync('deck.json');\n var dataParsed = JSON.parse(data);\n var keys = dataParsed[Object.keys(dataParsed)[0]];\n var oneCard = \"https://deckofcardsapi.com/api/deck/\" + keys + \"/draw/?count=1\";\n return oneCard;\n}", "function shuffleAction() {\n const shuffledList = cards.slice().sort(() => Math.random() - 0.5);\n return createCard(shuffledList);\n}", "function generateDeck(){\n // Generate a card number holder so we never re-use cards\n for(i=0;i<52;i++){\n app.unpickedCards.push({cardNumber:i});\n }\n\n var suits = [\n { name:'S','display':'Spades'},\n { name:'H','display':'Hearts'},\n { name:'D','display':'Diamonds'},\n { name:'C','display':'Clubs'},\n ];\n\n var facecards = [\n {'name':'J','display':'Jack','value':11},\n {'name':'Q','display':'Queen','value':12},\n {'name':'K','display':'King','value':13},\n {'name':'A','display':'Ace','value':14},\n ]\n\n suits.forEach(function(suit){\n for(i=2; i<11; i++){\n app.cards.push({\n 'name':i+suit.name,\n 'display':i,\n 'suit':suit.display,\n 'value':i,\n 'ownerId':null\n });\n }\n facecards.forEach(function(facecard){\n app.cards.push({\n 'name':facecard.name+suit.name,\n 'display':facecard.display,\n 'suit':suit.display,\n 'value':facecard.value,\n 'ownerId':null\n });\n });\n });\n}", "function getDeck(){\n var shuffledCards, deck;\n $(\".deck\").show(\"explode\", 1000);\n $(\".score-panel\").show();\n shuffledCards = shuffle(cardTypes);\n $(\".card\").each(function(index){\n $(this).show(\"explode\" );\n $(this).children().attr(\"class\", \"fa fa-\" + shuffledCards[index]);\n })\n deck = $(\".deck\").children();\n moves = 0;\n moveCounter();\n displayCard(deck);\n restart();\n }", "static createDeck() {\n for (let i = 0; i < 4; i++) {\n for (let j = 1; j <= 7; j++) {\n let obj = { suit: i, value: j };\n deck.push(obj);\n }\n }\n }", "shuffleElements() { \n this.deck.shuffle();\n }", "function getDealerCards() {\n for (i = 0; i < 2; i++) {\n const rndIdx = Math.floor(Math.random() * tempDeck.length);\n dealerHand.push(tempDeck.splice(rndIdx, 1)[0]);\n }\n renderDeckInContainer(dealerHand, dealerContainer);\n dealerScore.innerHTML = `dealer has: ${doTheDealerMath()}`;\n check();\n}", "function generateStandardDeck()\n{\n\t//The deck starts as an empty array.\n\tvar deck = [];\n\t\n\t/*\n\t\tA double for loop will create all 52 cards, running the 13 ranks each 4 times for the suits.\n\t*/\n\tfor (var r = ACE; r <= KING; r++)\n\t\tfor (var s = CLUB; s <= SPADE; s++)\n\t\t{\n\t\t\t/*\n\t\t\t\tBy declaring the card as an empty object, we can begin to create member variables (rank, suit, and cardImg) dynamically, assigning them values on the fly.\n\t\t\t\t\n\t\t\t\tEach call to new Object() creates a new object in card so that the loop creates 52 individual cards.\n\t\t\t*/\n\t\t\tvar card = new Object();\n\t\t\tcard.rank = r;\n\t\t\tcard.suit = s;\n\t\t\tcard.cardImg = r + \"-\" + s + \".png\";\n\t\t\tdeck.push(card);\n\t\t}\n\t\t\n\t//return the completed array.\n\treturn deck;\n}", "function getCards() {\n axios({\n method: \"GET\",\n url: \"https://omgvamp-hearthstone-v1.p.rapidapi.com/cards\",\n headers: {\n \"content-type\": \"application/octet-stream\",\n \"x-rapidapi-host\": \"omgvamp-hearthstone-v1.p.rapidapi.com\",\n \"x-rapidapi-key\": \"174f54c7e9msh385aea11f59db8ep1eecbfjsna5431ab42c87\",\n useQueryString: true,\n params: {\n locale: \"ptBR\",\n },\n },\n })\n .then((response) => {\n const filteredCards = response.data.Basic.map((card) => card.attack);\n if (filteredCards !== undefined) {\n setCards(response.data.Basic);\n }\n })\n .catch((error) => {\n console.log(error);\n });\n }", "function draw() {\n\n // Create the endpoint url \n const path = (deckId === '') ? `new/draw/?count=1` : `${deckId}/draw/?count=1`;\n const url = endpoint + path;\n\n // Call the endpoint\n fetch(url)\n .then(response => response.json())\n .then(json => { \n deckId = json.deck_id;\n document.cookie = deckId;\n displayCard(json.cards[0]); // Read the first card\n updateCount(json.remaining); //3. Update the count remaining\n });\n\n}", "function shuffle(deck) {\n\t// Shuffle\n\tfor (let i=0; i<1000; i++) {\n\t // Swap two randomly selected cards.\n\t let pos1 = Math.floor(Math.random()*deck.length);\n\t let pos2 = Math.floor(Math.random()*deck.length);\n\n\t // Swap the selected cards.\n\t [deck[pos1], deck[pos2]] = [deck[pos2], deck[pos1]];\n\t}\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates a new bounding box renderer in a scene.
function BoundingBoxRenderer(scene){/** * The component name helpfull to identify the component in the list of scene components. */this.name=BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;/** * Color of the bounding box lines placed in front of an object */this.frontColor=new BABYLON.Color3(1,1,1);/** * Color of the bounding box lines placed behind an object */this.backColor=new BABYLON.Color3(0.1,0.1,0.1);/** * Defines if the renderer should show the back lines or not */this.showBackLines=true;/** * @hidden */this.renderList=new BABYLON.SmartArray(32);this._vertexBuffers={};this.scene=scene;scene._addComponent(this);}
[ "function BoundingBox() {\n this._internalModel = new BoundingBoxFilterModel();\n}", "setBoundingBox() {\n /**\n * Array of `Line` objects defining the boundary of the Drawing<br>\n * - using these in `View.addLine` to determine the end points of {@link Line} in the {@link model}\n * - these lines are not added to the `Model.elements` array\n */\n this.boundaryLines = []\n\n // TODO; set these values in main\n\n // top left\n let tlPt = new Point(\"-4\", \"-4\")\n // bottom right\n let brPt = new Point(\"4\", \"4\")\n\n // top right\n let trPt = new Point(brPt.x, tlPt.y)\n // bottom left\n let blPt = new Point(tlPt.x, brPt.y)\n\n let lineN = new Line(tlPt, trPt)\n this.boundaryLines.push(lineN)\n\n let lineS = new Line(blPt, brPt)\n this.boundaryLines.push(lineS)\n\n let lineW = new Line(tlPt, blPt)\n this.boundaryLines.push(lineW)\n\n let lineE = new Line(trPt, brPt)\n this.boundaryLines.push(lineE)\n }", "set boundingBoxMode(value) {}", "function AxesViewer(scene,scaleLines){if(scaleLines===void 0){scaleLines=1;}this._xline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];this._yline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];this._zline=[BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero()];/**\n * Gets or sets a number used to scale line length\n */this.scaleLines=1;this.scaleLines=scaleLines;this._xmesh=BABYLON.Mesh.CreateLines(\"xline\",this._xline,scene,true);this._ymesh=BABYLON.Mesh.CreateLines(\"yline\",this._yline,scene,true);this._zmesh=BABYLON.Mesh.CreateLines(\"zline\",this._zline,scene,true);this._xmesh.renderingGroupId=2;this._ymesh.renderingGroupId=2;this._zmesh.renderingGroupId=2;this._xmesh.material.checkReadyOnlyOnce=true;this._xmesh.color=new BABYLON.Color3(1,0,0);this._ymesh.material.checkReadyOnlyOnce=true;this._ymesh.color=new BABYLON.Color3(0,1,0);this._zmesh.material.checkReadyOnlyOnce=true;this._zmesh.color=new BABYLON.Color3(0,0,1);this.scene=scene;}", "function ConstructHitBoxes() {\n\t\tfunction CreateHitBox(w, h, d, x, y, z, rotx = 0.0, roty = 0.0, rotz = 0.0, area = \"\") {\n\t\t\tvar geo = new THREE.BoxGeometry(w, h, d);\n\t\t\tvar mat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF });\n\t\t\tmat.transparent = true;\n\t\t\tmat.opacity = 0.0;\n\n\t\t\tvar cube = new THREE.Mesh(geo, mat);\n\t\t\tcube.name = \"hitbox\";\n\t\t\tcube[\"selected\"] = false;\n\t\t\tcube[\"hovering\"] = true;\n\t\t\tcube[\"area\"] = area;\n\t\t\tcube.frustumCulled = false;\n\t\t\tscene.add(cube);\n\n\n\t\t\tcube.rotation.x = rotx;\n\t\t\tcube.rotation.y = roty;\n\t\t\tcube.rotation.z = rotz;\n\n\t\t\tcube.position.x = x;\n\t\t\tcube.position.y = y;\n\t\t\tcube.position.z = z;\n\n\t\t}\n\n\t\tCreateHitBox(3.5, 3.2, 0.1, 0.01, 0.5, 1.2, 0.1, 0, 0.0, \"front\"); // front\n\t\tCreateHitBox(3.4, 2.6, 0.1, 0.2, 0.6, -0.17, 0.2, 0.0, 0.0, \"back\"); // back\n\t\tCreateHitBox(0.5, 2.5, 2.4, -1.90, 0.1, 0.4, 0, 0, 0.21, \"frills\"); // left\n\t\tCreateHitBox(0.5, 2.7, 2.4, 2.095, 0.80, 0.4, 0, 0, 0, \"frills\"); // right\n\t\tCreateHitBox(3.4, 1.0, 2.4, 0.2, -1.0, 0.4, 0.0, 0.0, 0.1, \"frills\"); // bottom\n\t}", "createRect(){\n let rect = Rect.createRect(this.activeColor);\n this.canvas.add(rect);\n this.notifyCanvasChange(rect.id, \"added\");\n }", "function getBoundingBox() {\n var rect = self.getViewRect();\n \n return new T5.Geo.BoundingBox(\n T5.GeoXY.toPos(T5.XY.init(rect.x1, rect.y2), radsPerPixel),\n T5.GeoXY.toPos(T5.XY.init(rect.x2, rect.y1), radsPerPixel));\n }", "createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }", "function definePlane() {\n game.addObject({\n type : 'rect',\n x : 0,\n y : 350,\n width : 800,\n height : 125,\n color : '#333'\n });\n game.draw();\n }", "function BoundingBox2D(min, max) {\n if (typeof min === \"undefined\") { min = new Vapor.Vector2(); }\n if (typeof max === \"undefined\") { max = new Vapor.Vector2(); }\n this.min = min;\n this.max = max;\n }", "get MeshRenderer() {}", "function PhysicsViewer(scene){/** @hidden */this._impostors=[];/** @hidden */this._meshes=[];/** @hidden */this._numMeshes=0;this._scene=scene||BABYLON.Engine.LastCreatedScene;var physicEngine=this._scene.getPhysicsEngine();if(physicEngine){this._physicsEnginePlugin=physicEngine.getPhysicsPlugin();}}", "create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }", "function Renderable() {\n\tthis.mPos = new Vec2(0, 0);\n\tthis.mSize = new Vec2(0, 0);\n\tthis.mOrigin = new Vec2(0, 0);\n\tthis.mAbsolute = false;\n\t\n\tthis.mDepth = 0;\n\t\n\tthis.mTransformation = new Matrix3();\n\tthis.mScale = new Vec2(1.0, 1.0);\n\tthis.mRotation = 0;\n\tthis.mSkew = new Vec2();\n\tthis.mAlpha = 1.0;\n\tthis.mCompositeOp = \"source-over\";\n\t\n\tthis.mLocalBoundingBox = new Polygon(); // the local bounding box is in object coordinates (no transformations applied)\n\tthis.mGlobalBoundingBox = new Polygon(); // the global bounding box is in world coordinates (transformations applied)\n\t\n\tthis.mLocalMask = new Polygon();\n\tthis.mGlobalMask = new Polygon();\n}", "function makeBox(ctx)\n{\n // box\n // v6----- v5\n // /| /|\n // v1------v0|\n // | | | |\n // | |v7---|-|v4\n // |/ |/\n // v2------v3\n //\n // vertex coords array\n var vertices = new Float32Array(\n [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front\n 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right\n 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top\n -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left\n -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom\n 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ] // v4-v7-v6-v5 back\n );\n\n // normal array\n var normals = new Float32Array(\n [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left\n 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom\n 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ] // v4-v7-v6-v5 back\n );\n\n\n // texCoord array\n var texCoords = new Float32Array(\n [ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front\n 0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right\n 1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top\n 1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left\n 0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom\n 0, 0, 1, 0, 1, 1, 0, 1 ] // v4-v7-v6-v5 back\n );\n\n // index array\n var indices = new Uint8Array(\n [ 0, 1, 2, 0, 2, 3, // front\n 4, 5, 6, 4, 6, 7, // right\n 8, 9,10, 8,10,11, // top\n 12,13,14, 12,14,15, // left\n 16,17,18, 16,18,19, // bottom\n 20,21,22, 20,22,23 ] // back\n );\n\n var retval = { };\n\n retval.normalObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, normals, ctx.STATIC_DRAW);\n\n retval.texCoordObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, texCoords, ctx.STATIC_DRAW);\n\n retval.vertexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, vertices, ctx.STATIC_DRAW);\n\n ctx.bindBuffer(ctx.ARRAY_BUFFER, null);\n\n retval.indexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);\n ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, indices, ctx.STATIC_DRAW);\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);\n\n retval.numIndices = indices.length;\n retval.indexType = ctx.UNSIGNED_BYTE;\n return retval;\n}", "createRenderer() {\r\n return new GameMapRenderer(this);\r\n }", "function initScene() {\n gScene = new THREE.Scene();\n gScene.background = new THREE.Color(0xcccccc);\n gScene.fog = new THREE.FogExp2(0xcccccc, 0.002);\n}", "updateBB() {\n this.lastWorldBB = this.worldBB;\n this.worldBB = new BoundingBox(\n this.pos.x, this.pos.y, this.dim.x, this.dim.y);\n }", "function GroundGeometry(id,scene,/**\n * Defines the width of the ground\n */width,/**\n * Defines the height of the ground\n */height,/**\n * Defines the subdivisions to apply to the ground\n */subdivisions,canBeRegenerated,mesh){if(mesh===void 0){mesh=null;}var _this=_super.call(this,id,scene,canBeRegenerated,mesh)||this;_this.width=width;_this.height=height;_this.subdivisions=subdivisions;return _this;}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function sets the current row in the GridView
function setGridViewCurrentRow(gridView, rowId) { for (var i = 0, len = gridView.rows.length; i < len; i++) { var nextRow = gridView.rows[i]; if (nextRow.bindingContext.id === rowId) { nextRow.makeCurrent(); return; } } }
[ "function highlight_curr_row()\r\n{\r\n\r\n\t// temporarily turn off table rendering\r\n\tdata_view.beginUpdate();\r\n\r\n // get current row\r\n\tvar curr_data_row = convert_row_ids([curr_row_selected])[0];\r\n var item = data_view.getItemById(curr_data_row);\r\n var num_cols = item.length;\r\n\r\n // update current row (set to draw box around it -- see select_rows())\r\n item[num_cols-1] = item[num_cols-1] + 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(curr_data_row, item);\r\n\r\n // update previous row\r\n if (prev_row_selected != null) {\r\n\r\n // get previous row\r\n var prev_data_row = convert_row_ids([prev_row_selected])[0];\r\n item = data_view.getItemById(prev_data_row);\r\n\r\n // remove box around previous row\r\n item[num_cols-1] = item[num_cols-1] - 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(prev_data_row, item);\r\n }\r\n\r\n\t// turn on table rendering\r\n\tdata_view.endUpdate();\r\n\r\n}", "setRow(index, row) {\n return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);\n }", "function selectrow() {\n\n var grid = jQuery(\"#FieldGrid\");\n var roleKey = grid.getGridParam(\"selrow\");\n var ParentId = grid.jqGrid(\"getCell\", roleKey, \"ID\").toString();\n if (ParentId != null) {\n jQuery(\"#TestCaseFieldValuesGrid\").setGridParam({ url: \"/TestCaseFieldValues/GetFieldValues/?parentRowID=\" + ParentId });\n jQuery(\"#TestCaseFieldValuesGrid\").trigger(\"reloadGrid\", [{ page: 1 }]);\n\n jQuery(\"#TestCaseFieldValuesGrid\").setGridParam({ url: \"/TestCaseFieldValues/EditFieldValues/?parentRowID=\" + ParentId });\n jQuery(\"#TestCaseFieldValuesGrid\").trigger(\"reloadGrid\", [{ page: 1 }]);\n $(\"#TestCaseFieldValuesGrid\").show();\n\n }\n}", "function changeToNextField(e) {\n $sel = $sel.next(\"td.editable\");\n if($sel.length < 1) {\n $sel = $sel.parent(\"tr.griderRow\").siblings(\"tr:first\").find(\"td.editable:first\");\n }\n setSelectedCell($sel);\n $sel.trigger(\"click\");\n }", "function SetRowHeight() {\n var grid = this.GetGrid();\n var rowHeight = GetRowHeight.call(this);\n var ids = grid.getDataIDs();\n\n for (var i = 0, len = ids.length; i < len; i++) {\n grid.setRowData(ids[i], false, { height: rowHeight });\n }\n }", "function updateSelectedRows() {\n var selectedList = [];\n if (grid.api) {\n var selectedRows = grid.api.selection.getSelectedRows();\n _.each(selectedRows, function (row) {\n selectedList.push(row[component.constants.ROW_IDENTIFIER]);\n });\n }\n component.onSelectRows(selectedList);\n }", "function scrollToRow(targetGrid, rowIndex) {\n var rowHeight = 23; // rowheight\n var index = jQuery(targetGrid).getInd(id);\n jQuery(targetGrid).closest(\".ui-jqgrid-bdiv\").scrollTop(rowHeight * index);\n}", "function SetRowColor(row)\r\n{\r\n if (row.getAttribute(\"selected\") == 1)\r\n {\r\n StyleSetAttributes(row, \"background-color: yellow;\");\r\n }\r\n else if (row.rowIndex % 2 == 1)\r\n {\r\n //StyleSetAttributes(row, \"background-color: lightgoldenrodyellow;\");\r\n StyleSetAttributes(row, \"background-color: #FFF3C3;\");\r\n }\r\n else\r\n {\r\n //StyleSetAttributes(row, \"background-color: #FFFF99;\");\r\n StyleSetAttributes(row, \"background-color: #F6CCC0;\");\r\n }\r\n}", "onGridBeforeRenderRows() {\n // grid rows are being rerendered, meaning the underlying data might be changed.\n // the editor probably won't be over the same record, so cancel\n if (this.editorContext && this.editorContext.editor.isVisible) {\n this.cancelEditing();\n }\n }", "function changeRowTitle(obj, row) {\r\n NewGridObj.dimTitles[RowDimId][row] = obj.innerHTML;\r\n}", "function markSelected(btn) {\n if (lastRowSelected != null)\n lastRowSelected.classList.remove(\"selected\");// remove the last row selected(last row = DOM element)\n let row = (btn.parentNode).parentNode; // button is in TD which is in Row\n row.className = 'selected'; // mark as selected\n lastRowSelected = row;\n}", "function scrollToSelectedRow(gridSelector) {\r\n var gridWrapper = document.querySelector(gridSelector);\r\n if (gridWrapper) {\r\n var selectedRow = gridWrapper.querySelector(\"tr.k-state-selected\");\r\n if (selectedRow) {\r\n selectedRow.scrollIntoView();\r\n }\r\n }\r\n}", "function selectedRowToInput()\n {\n \n for(var i = 1; i < table.rows.length; i++)\n {\n table.rows[i].onclick = function()\n {\n // get the seected row index\n rIndex = this.rowIndex;\n document.getElementById(\"Nattraction\").value = this.cells[0].innerHTML;\n document.getElementById(\"Pricechild\").value = this.cells[1].innerHTML;\n document.getElementById(\"Priceadult\").value = this.cells[2].innerHTML;\n document.getElementById(\"total\").value = this.cells[3].innerHTML;\n };\n }\n }", "addNewRow(){\n this.canvas.unshift([1,1,0,0,0,0,0,0,0,0,0,0,1,1]);\n }", "function setGridEvents() {\n $table.find(\"td.editable\").live(\"mousedown\", function() {\n $sel = $(this);\n setSelectedCell($sel);\n var editor = columns[$(this).attr(\"col\")].editor;\n $('#' + editor).trigger(\"hide\");//, [getCellValue(this)]);\n }).live(\"click\", function(e) {\n var editor = columns[$(this).attr(\"col\")].editor;\n $('#' + editor).trigger(\"show\", [this, getCellValue(this)]);\n });\n\n // Tabl events\n $table.bind({\n 'addRow': function() {\n addNewRow();\n }\n });\n\n }", "clickHandler(event, row) {\n\n\n let attribute = event.target.getAttribute(this.atts.dataAttribute);\n let readonly = this.readOnlyArray.indexOf(attribute) ? false : true;\n\n //set current row of out filtered row\n this.vGrid.filterRow = row;\n\n //get data ref\n this.vGrid.currentRowEntity = this.vGrid.collectionFiltered[row];\n\n ///loop properties and set them to current entity\n let data = this.vGrid.currentRowEntity;\n for (var k in data) {\n if (data.hasOwnProperty(k)) {\n if (this.vGrid.currentEntity[k] !== data[k]) {\n this.vGrid.currentEntity[k] = data[k];\n this.vGrid.skipNextUpdateProperty.push(k)\n }\n }\n }\n\n\n //have user added on double click event?\n if (this.vGrid.$parent[this.eventOnDblClick] && event.type === \"dblclick\") {\n setTimeout(()=> {\n this.vGrid.$parent[this.eventOnDblClick](this.vGrid.currentRowEntity[this.vGrid.sgkey], attribute, event);\n }, 15)\n }\n\n\n //use helper function to edit cell\n this.vGrid.vGridCellEdit.editCellhelper(row, event, readonly);\n\n }", "_handleLeftClickRow(event)\r\n {\r\n if (this.view.allowMultipleSelection)\r\n {\r\n // Wipe everything if ctrl key not selected.\r\n if (!event[this._multipleSelectionKey])\r\n {\r\n $(event.currentTarget).addClass('active clickable-row').siblings().removeClass('active');\r\n }\r\n else\r\n {\r\n $(event.currentTarget).toggleClass('active');\r\n }\r\n\r\n // If shift down, select range.\r\n if (event[this._rangeSelectionKey])\r\n {\r\n $(this._lastTarget).addClass('active clickable-row')\r\n if ($(this._lastTarget).index() <= $(event.currentTarget).index())\r\n {\r\n $(this._lastTarget).nextUntil(event.currentTarget).addClass('active clickable-row');\r\n }\r\n else\r\n {\r\n $(event.currentTarget).nextUntil(this._lastTarget).addClass('active clickable-row');\r\n }\r\n }\r\n else\r\n {\r\n $(event.currentTarget).addClass('active clickable-row');\r\n this._lastTarget = event.currentTarget;\r\n }\r\n }\r\n else\r\n {\r\n $(event.currentTarget).addClass('active clickable-row').siblings().removeClass('active');\r\n this._lastTarget = event.currentTarget;\r\n }\r\n }", "function selectRow(target, step){ \n\t\tvar opts = $.data(target, 'combogrid').options; \n\t\tvar grid = $.data(target, 'combogrid').grid; \n\t\tif (opts.multiple) return; \n\t\t \n\t\tif (!step){ \n\t\t\tvar selected = grid.datagrid('getSelected'); \n\t\t\tif (selected){ \n\t\t\t\tsetValues(target, [selected[opts.idField]]);\t// set values \n\t\t\t\t$(target).combo('hidePanel');\t// hide the drop down panel \n\t\t\t} \n\t\t\treturn; \n\t\t} \n\t\t \n\t\tvar selected = grid.datagrid('getSelected'); \n\t\tif (selected){ \n\t\t\tvar index = grid.datagrid('getRowIndex', selected[opts.idField]); \n\t\t\tgrid.datagrid('unselectRow', index); \n\t\t\tindex += step; \n\t\t\tif (index < 0) index = 0; \n\t\t\tif (index >= grid.datagrid('getRows').length) index = grid.datagrid('getRows').length - 1; \n\t\t\tgrid.datagrid('selectRow', index); \n\t\t} else { \n\t\t\tgrid.datagrid('selectRow', 0); \n\t\t} \n\t}", "clearSelectedRow() {\n var $row = this.$table.find('tr.active');\n $row.removeClass('active');\n this.removeEditable($row);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of unique values.
function _unique(values) { return Array.from(new Set(values)); }
[ "function unique(arr) {\n return Array.from(new Set(arr));\n }", "function uniqueArr(arr) {\n\treturn [...new Set(arr.filter(x => x > 0))];\n}", "function UNIQUE(array) {\n return array.reduce(function (p, c) {\n if (p.indexOf(c) < 0) p.push(c);\n return p;\n }, []);\n}", "get uniqueValues() {\n var _a;\n const replaceWithNull = this.traits.replaceWithNullValues;\n const values = this.values.map(value => {\n if (value.length === 0) {\n return \"\";\n }\n else if (replaceWithNull && replaceWithNull.indexOf(value) >= 0) {\n return \"\";\n }\n return value;\n });\n const count = countBy(values);\n const nullCount = (_a = count[\"\"]) !== null && _a !== void 0 ? _a : 0;\n delete count[\"\"];\n function toArray(key, value) {\n return [key, value];\n }\n const countArray = Object.keys(count).map(key => toArray(key, count[key]));\n countArray.sort(function (a, b) {\n return b[1] - a[1];\n });\n return {\n values: countArray.map(a => a[0]),\n counts: countArray.map(a => a[1]),\n numberOfNulls: nullCount\n };\n }", "function unique(A) {\n if (A instanceof NdArray) {\n A = A.toArray();\n }\n\n var hash = {}, result = [];\n for ( var i = 0, l = A.length; i < l; ++i ) {\n if ( !hash.hasOwnProperty(A[i]) ) { \n hash[ A[i] ] = true;\n result.push(A[i]);\n }\n }\n return result;\n }", "function unique(animals) {//Pass in animals arr\n var result = [];//store dedup arr\n $.each(animals, function(i, e) {//for each animal index, element\n if ($.inArray(e, result) == -1) result.push(e);//if any element returns -1 push to result arr\n });\n return result;\n }", "function unique_strings_array(arr) {\n var a = [];\n for (var i = 0, l = arr.length; i < l; i++) {\n if (a.indexOf(arr[i]) === -1) {\n a.push(arr[i]);\n }\n }\n return a;\n}", "nunique() {\n return (new Set(this.values)).size;\n }", "function uniqMethod() {\n\tvar testarray=[1,2,2,1,2,3,1,1,1,4,4,4,4,3,3,5,6,6,7,7];\n\tvar result=_.uniq(testarray);\n\tconsole.log(result);\n}", "function GetCheckedUserIdsToArray() {\n checked_user_ids = $('.check-all').filter(\":checked\").map(function () {\n return $(this).attr('user_id');\n }).get();\n}", "getAllUstensils(recipes) {\n let allUstensilArray = [];\n for (let recipe of recipes) {\n allUstensilArray.push(recipe.ustensils);\n }\n let flatUstensilArray = allUstensilArray.flat();\n let uniqAllUstensilArray = [...new Set(flatUstensilArray)];\n return uniqAllUstensilArray;\n }", "function findUniques(nums) {\n var newNums = [];\n\n for (var i = 0; i < nums.length; i++) {\n if (newNums.indexOf(nums[i]) < 0 )\n newNums.push(nums[i])\n }\n return newNums \n}", "unique() {\n const newValues = new Set(this.values);\n let series = new Series(Array.from(newValues));\n return series;\n }", "function uniqueKeys(events) {\n const arrayOfKeys = [];\n for (const e of events) {\n for (const k of e.data().keySeq()) {\n arrayOfKeys.push(k);\n }\n }\n return new Immutable.Set(arrayOfKeys);\n}", "getUnseen() {\n\t\tlet unseen = [];\n\t\tfor (let question of this.conv.user.storage.history.history) {\n\t\t\tif (!question || !question.seenCount || question.seenCount === 0) {\n\t\t\t\tunseen.push(question.questionNumber);\n\t\t\t}\n\t\t}\n\t\treturn unseen;\n\t}", "function getUniqueValue(variable_sys_id) {\n var values=[];\n\tvar ids = [];\n\tvar a = [];\n var gr = new GlideRecord('sc_item_option');\n gr.addQuery('item_option_new', variable_sys_id);\n gr.orderBy('value');\n gr.query();\n while (gr.next()){\n values.push(gr.getValue('value'));\n ids.push(gr.getValue('sys_id'));\n }\n\t\n var l = values.length;\n for (var i = 0; i < l; i++) {\n for (var j = i + 1; j < l; j++) {\n if (values[i] === values[j])\n j = ++i;\n }\n a.push(ids[i]);\n }\n return a;\n}", "function getUniqueNames(dataStore){\n var uniqueArray = [];\n for(var i=0;i<dataStore.length;i++){\n if(uniqueArray.indexOf(dataStore[i].name) ==-1){\n uniqueArray.push(dataStore[i].name);\n }\n }\n return uniqueArray;\n}", "function countUniqueValues(arr) {\n if (arr.length === 0) {\n return 0;\n }\n var i = 0;\n for (var j = 1; j < arr.length; j++) {\n if (arr[i] !== arr[j]) {\n i++;\n arr[i] = arr[j];\n }\n }\n return i + 1;\n}", "function uniteUnique(...uniqueArray) {\n// spreads ([1], [2,[1,0]], [3, 2,[1,0]]) to ([1], [2,1,0], [3,2,1,0])\n console.log(\"uniqueArray: \" + uniqueArray);\n \n // .reduce() with .concat() ([1], [2,1,0], [3,2,1,0]) to ([1], [2,1,0], [3,2,1,0])\n return uniqueArray.reduce(function(accumulator,currentValue){\n //\n return accumulator.concat(currentValue).filter(function(element,index,array){\n console.log(\"element: \" + element + \", index: \" + index + \", array: \" +array);\n \n \n // return the element only if it exists at its own index position\n return index == array.indexOf(element);\n \n });\n });\n }", "function mergeUnique(arr1, arr2) {\n return arr1.concat(arr2).filter((element, index, array) => array.indexOf(element) === index)\n //return Array.from(new Set(concat(arr1, arr2))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get your public key with a callback function
function getPubkey(callback) { sbot.whoami(function(err, msg) { if(err) { console.log('getPubkey(callback) err', err, '\n\n\n\n') return callback(err) } else { console.log('getPubkey(callback) msg', msg, '\n\n\n\n') return callback(null, msg) } }) }
[ "function getPublicKey(req, res) {\n var key_path = './server/keystore/key/public_key.pem';\n return g_fs.readFileAsync(key_path, \"ascii\")\n .then(function (content) {\n return res.send(content);\n })\n .catch(function (exception) {\n console.log(\"error fetching key\");\n res.sendStatus(400);\n });\n }", "function getClientKey() {\n\n }", "function getConsumerKey(){\n prompt( 'Enter OAuth consumer key:', function( key ){\n consumerKey = key;\n getConsumerSecret();\n } );\n }", "initRSA() {\n let me = this;\n ajax.getRSAKey(me.location.protocol, me.location.hostname, me.location.port, function(e, o) {\n if (o && o.success === true) {\n me.rsaKey = o.key;\n me.tc = o.ts;\n me.emit('ready');\n } else {\n me.emit('error', e);\n }\n });\n }", "function genKeys(cb){\n // gen private\n cp.exec('openssl genrsa 368', function(err, priv, stderr) {\n // tmp file\n var randomfn = './' + Math.random().toString(36).substring(7);\n fs.writeFileSync(randomfn, priv);\n // gen public\n cp.exec('openssl rsa -in '+randomfn+' -pubout', function(err, pub, stderr) {\n // delete tmp file\n fs.unlinkSync(randomfn);\n // callback\n cb(JSON.stringify({public: pub, private: priv}, null, 4));\n });\n\n });\n}", "function generateKeyPair() {\n\n // check if an active public key has been set for us in the server side\n $.ajax({\n type: 'POST',\n url: '/publicKeyExists',\n success: function(data) {\n\n if ( data == false ) {\n\n // generate our keys\n var keySize = 2048;\n var crypt = new JSEncrypt({default_key_size: keySize});\n crypt.getKey();\n\n // set a new private RSA key\n var privateKey = crypt.getPrivateKey();\n localStorage.setItem('privateKey', privateKey);\n\n // set a new public RSA key\n var publicKey = crypt.getPublicKey();\n localStorage.setItem('publicKey', publicKey);\n\n // send the public key to the server\n $.ajax({\n type: 'POST',\n url: '/publicKeyStore',\n data: { publicKey: publicKey },\n success: function(data) {\n if ( data == \"OK\" ) {\n // everything is ok, remove the loader\n loaded();\n }\n else {\n // Something went wrong\n alertError(\"Something went wrong\")\n }\n }\n });\n\n }\n else {\n // The public key is already created and stored\n loaded();\n }\n\n }\n });\n\n}", "validPublicKey(publicKey){}", "async _publicKeyFromCertificate (crtPath) {\n let output = '';\n await this.opensslCommand(\n ['x509', '-noout', '-in', crtPath, '-pubkey', '-outform', 'pem'],\n (o => { output += o; })\n );\n return output;\n }", "function KeychainAccess() {\n\n}", "function forgeKey(privateKey) {\n return function() {\n // convert PEM-formatted private key to a Forge private key\n const forgePrivateKey = forge.pki.privateKeyFromPem(privateKey);\n // get a Forge public key from the Forge private key\n const forgePublicKey = forge.pki.setRsaPublicKey(\n forgePrivateKey.n,\n forgePrivateKey.e\n );\n // convert the Forge public key to a PEM-formatted public key\n const publicKey = forge.pki.publicKeyToPem(forgePublicKey);\n\n return publicKey;\n\n // Below is a curried version with arrow functions\n // Given a private key, get a function that can generate a public key\n // const getPublicKey = (forgePrivateKey) => () => forge.pki.publicKeyToPem(forge.pki.setRsaPublicKey(forgePrivateKey.n, forgePrivateKey.e));\n };\n}", "function importPubKey() {\n var newPubKey = new PubKeys(\n {raw_key: ctrl.raw_key, self_signature: ctrl.self_signature}\n );\n newPubKey.$save(\n function(newPubKey_) {\n raiseAlert('success', '', 'Public key saved successfully');\n $uibModalInstance.close(newPubKey_);\n },\n function(httpResp) {\n raiseAlert('danger',\n httpResp.statusText, httpResp.data.title);\n ctrl.cancel();\n }\n );\n }", "ListOfYourPublicSSHKeys() {\n let url = `/me/sshKey`;\n return this.client.request('GET', url);\n }", "static generateKey(){\n\t\tlet kparams = {};\n\t\treturn new kaltura.RequestBuilder('playready_playreadydrm', 'generateKey', kparams);\n\t}", "getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }", "getFioPublicKey() {\n return this.publicKey;\n }", "function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256ripe160(hex2bytes(k))); }", "function generateKeypair(cmd) {\n\tlet keypair_path = cmd.output;\n\n\tif (keypair_path == null) {\n\t\tlet cfg_dir = configdir(\"webhookify\");\n\t\tif (!fs.existsSync(cfg_dir)) {\n\t\t\tmkdirp.sync(cfg_dir);\n\t\t}\n\t\tkeypair_path = path.join(cfg_dir, \"key.pem\");\n\t}\n\n\tif (fs.existsSync(keypair_path)) {\n\t\tconsole.log(\"The specified keyfile already exists.\");\n\t\treturn;\n\t}\n\n\tconsole.log(\"Generating keypair with 2048 bit modulus...\");\n\tlet keypair = rsa_utils.generateKeyPair();\n\n\tconsole.log(`Writing keypair to ${keypair_path}...`);\n\tfs.writeFileSync(keypair_path, keypair.privateKey, { mode: 0o400 });\n\n\tconsole.log(\"The public component of your keypair is as follows:\");\n\tconsole.log();\n\tconsole.log(keypair.publicKey);\n\tconsole.log();\n\tconsole.log(\"Please copy & paste this to the webhookify website.\");\n}", "ComputeKeyIdentifier() {\n\n }", "validPrivateKey(privateKey){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to store list of ports into local storage.
function storePortList() { let string = JSON.stringify(localList); localStorage.setItem("storkey", string); }
[ "function storeDataToLS(port)\r\n{\r\n\tif(typeof (Storage) !== \"undefined\")\r\n\t{\r\n\t\tlocalStorage.setItem(portKey,JSON.stringify(port)) //The port instance with the new data is uploaded into the localStorage\r\n\t}\r\n\telse\r\n\t{\r\n\t\talert(\"The current browser doesn't support local storage\");\r\n\t}\r\n}", "saveToStore() {\n localStorage.setItem(STORAGE.TAG, JSON.stringify(this.list));\n }", "function storeCityArray() {\n localStorage.setItem('cities', JSON.stringify(cityList));\n}", "_store (tasks) {\n this.onListChanged(tasks);\n localStorage.setItem('tasks', JSON.stringify(tasks));\n }", "function saveStorage() {\r\n //acessando a variavel global localStorage, e inserindo o todo para fucar armazenado\r\n //é nessessário transformar em jason pois o localstorage não entende array\r\n localStorage.setItem(\"list_todo\", JSON.stringify(todos));\r\n}", "function storeTrip() {\n localStorage.setItem(\"trips\", JSON.stringify(allTrips));\n}", "function saveSchedules() {\n\t\tlocalStorage.setItem(\"aPossibleSchedules\", JSON.stringify(aPossibleSchedules));\n\t}", "function saveRealmList() {\n \"use strict\";\n window.gmSetValue(\"realmList2\", realmList);\n}", "function saveBoard() {\n window.localStorage.setItem(\"board\", board.toJSON());\n}", "function saveHosts() {\n var file = __dirname + \"/\" + hostsFile;\n if (hosts && _.keys(hosts).length > 0) {\n\tvar out = ['# Format: <ip address><space><host name>',\n\t\t '# <host name> beginning with * is frozen and will not be updated',\n\t\t ''];\n\t\n\t_.each(hosts, function (host, ip) {\n\t out.push(ip + ' ' + host);\n\t});\n\tnoLoadHosts = true; // Prevent hosts from being reloaded while we write it\n\tfs.writeFile(file, out.join('\\n') + '\\n', function() {\n\t console.log('Saved ' + _.keys(hosts).length + ' hosts to ' + file);\n\t setTimeout(function() {\n\t\tnoLoadHosts = false; // Pause so we don't trigger reload from writing the file\n\t }, 500);\n\t});\n }\n}", "function storeNames() {\n // Stringify and set \"names\" key in localStorage to names array\n localStorage.setItem(\"names\", JSON.stringify(names));\n }", "function savePreSetPlans()\r\n{\r\nlocalStorage.setItem(\"planUP\"+1,JSON.stringify(planUP)); \r\nlocalStorage.setItem(\"planUM\"+1,JSON.stringify(planUM)); \r\nlocalStorage.setItem(\"planUR\"+1,JSON.stringify(planUR)); \r\nlocalStorage.setItem(\"planHP\"+1,JSON.stringify(planHP)); \r\nlocalStorage.setItem(\"planHM\"+1,JSON.stringify(planHM)); \r\nlocalStorage.setItem(\"planHR\"+1,JSON.stringify(planHR)); \r\nlocalStorage.setItem(\"planOP\"+1,JSON.stringify(planOP)); \r\nlocalStorage.setItem(\"planOM\"+1,JSON.stringify(planOM)); \r\nlocalStorage.setItem(\"planOR\"+1,JSON.stringify(planOR)); \r\nlocalStorage.setItem(\"planBP\"+1,JSON.stringify(planBP)); \r\nlocalStorage.setItem(\"planBM\"+1,JSON.stringify(planBM)); \r\nlocalStorage.setItem(\"planBR\"+1,JSON.stringify(planBR)); \r\n}", "function addPortToOpenedPorts(port) {\n var comPortIsInOpen = false;\n for (var i=0; i < global.comPorts.length; i++) {\n if (port == global.comPorts[i]) {\n comPortIsInOpen = true;\n }\n }\n\n if (!comPortIsInOpen) {\n global.comPorts.push(port);\n }\n}", "function storeSchedule() {\n console.log('store schedules')\n // grab the ONE, current schedule\n const currSchedule = timerSchArray \n console.log('Storing: ', currSchedule)\n\n // try to grab the current storage array \n const currStoredStr = localStorage.getItem('interval-workout-schedules') \n const currStored = JSON.parse(currStoredStr)\n\n let newStored = []\n\n if (currStored) {\n // storage is not empty\n newStored = currStored\n }\n \n if (currSchedule.length > 0) newStored.push(currSchedule)\n localStorage.setItem('interval-workout-schedules', JSON.stringify(newStored))\n\n displaySchedules()\n}", "_store() {\n try {\n window.sessionStorage.setItem('playQueue', JSON.stringify(this._array));\n } catch(e) {}\n }", "function saveToLocalStorage() {\n localStorage.setItem(\"startTime\", startTime);\n localStorage.running = running;\n localStorage.paused = paused;\n localStorage.tableSize = tableSize;\n localStorage.setItem(\"historyTable\", historyTable.innerHTML);\n localStorage.setItem(\"timeDisplay\", timeDisplay.innerHTML);\n localStorage.useStorage = 1;\n}", "function storeDayDataInLocalStorage(selectedDay, task, hours, minutes) {\n let days;\n if (localStorage.getItem(\"days\") === null) {\n days = [];\n } else {\n days = JSON.parse(localStorage.getItem(\"days\"));\n }\n\n days.push([selectedDay, task, hours, minutes]);\n\n localStorage.setItem(\"days\", JSON.stringify(days));\n}", "function storePref () {\n localStorage.setItem('pref', JSON.stringify(pref));\n}", "function save() {\n storage.setItem( LS_CELL_NAME, angular.toJson( wishlist ) )\n }", "function saveDuration(number){\r\n durationArray.push(number);\r\n localStorage.setItem(\"durationLocal\", JSON.stringify(durationArray));\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save team as image
function saveTeam(screen) { var modalImage = $("#image-modal-body"); modalImage.html('<img src="/images/loading.gif" id="loading-gif"/>'); if (screen < 1600 && screen > 479) { $('#team-name').css({ 'padding': '0px 0px', 'padding-bottom': '10px' }); } else if (screen > 1600) { $('#body-grid').css({ 'margin-top': '0' }); } var watermark = document.createElement('div'); watermark.id = 'watermark'; watermark.innerHTML = 'inazuma-team-builder.tk'; document.getElementById('field-players-container').parentElement.appendChild(watermark); var element = document.getElementsByTagName('BODY')[0]; // var teamName = $('#team-name').val() + '.png'; html2canvas(element, { allowTaint: true, useCORS: true, width: 1280, height: 500 }).then(function (canvas) { canvas.setAttribute("id", "canvas"); canvas.setAttribute("crossOrigin", "anonymous"); // canvas.setAttribute("width", "1280"); // canvas.setAttribute("height", "500"); canvas.getContext('2d').imageSmoothingEnabled = false; modalImage.html('<p id="save-instructions">To save: right click + "Save image as"</p>'); modalImage.append(canvas); if (screen < 1600 && screen > 479) { teamName.css({ 'padding-bottom': '0px', 'padding': '3px 0px' }); } else if (screen > 1600) { $('#body-grid').css({ 'margin-top': '-2%' }); } watermark.remove(); console.log(canvas); $("#canvas").click(function () { window.open(canvas.toDataURL(), '_blank').focus(); }); }); }
[ "saveToPNG() {\n this.downloadEl.download = 'pattar.png';\n this.downloadEl.href = this.renderCanvas.toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\");\n this.downloadEl.click();\n }", "function save() {\n\n var image = canvas.toDataURL(\"image/png\");\n //grab the title the user entered\n var title = document.getElementById('nameForm').value;\n //save into collection called sketches, this is found in items.js\n Meteor.call('sketches.insert', title , image);\n console.log(title+\" has been saved!\");\n //console.log(image);\n // save this image (along with other attributes) in a Drawings array/list as custom data under the user ID\n}", "function saveLastDrawing() {\n lastImage.src = canvas.toDataURL('image/png');\n }", "function SaveCurLayerset(){\n var lySetCur = docRef.activeLayer;\n var isLayer = lySetCur.typename == \"ArtLayer\"? true: false;\n var diagName = \"输出目录:当前选择的是 \" + (isLayer? \"层\": \"组\"); //FIXME: not displayed on windows\n var DirSaved = Folder.selectDialog(diagName); // using \"var path\" get wrong directory\n \n if(DirSaved == null)return;\n var file; //file name saved\n if(isLayer){ \n file = new File(DirSaved + \"/50.jpg\");\n ExportLayer(lySetCur, file);\n }else{\n var lysCount = lySetCur.artLayers.length\n for (var i = 0; i < lysCount; i++) {\n var lyCur = lySetCur.artLayers[i];\n //* layers order: from top to bottom; output order: from bottom to top\n var invertIndex = lysCount-i-1; \n var fileName = (invertIndex==4) ? 15: invertIndex + 1; //1, 2, 3, 4, 15\n file = new File(DirSaved + \"/\" + fileName + \".jpg\");\n ExportLayer(lyCur, file);\n }\n }\n\n alert(\"主人,我已经把图片都导出去了!\");\n}", "handleSave() {\n const can = document.getElementById('paint');\n const img = new Image();\n\n /**\n * If the state of the default canvas is the same that\n * the canvas after click on save we show an error instead\n * send the image in png to the father component\n */\n if (can.toDataURL() === this.state.defaultCanvas) {\n alert('Canvas is blank');\n } else {\n img.src = can.toDataURL('image/png');\n this.props.onReciveSign(img.src);\n }\n }", "function returnImage(team){\n\n team = team.replace(/\\s+/g, '');\n\n if(team == 'St.LouisBlues'){\n return(<Image style={styles.logo} source={require('../assets/St.LouisBlues.png')}/>);\n }else if(team == 'MontréalCanadiens'){\n return(<Image style={styles.logo} source={require('../assets/MontrealCanadiens.png')}/>);\n }else{\n return(<Image style={styles.logo} source={Images.logos[team]}/>);\n }\n\n}", "saveProjectedImage() {\n let imgInf = this.image_config.image_info;\n\n if (typeof imgInf.projection !== PROJECTION.NORMAL) {\n let url =\n this.context.server + this.context.getPrefixedURI(IVIEWER) +\n '/save_projection/?image=' + imgInf.image_id +\n \"&projection=\" + imgInf.projection +\n \"&start=\" + imgInf.projection_opts.start +\n \"&end=\" + imgInf.projection_opts.end;\n if (this.context.initial_type !== INITIAL_TYPES.WELL &&\n typeof imgInf.parent_id === 'number')\n url += \"&dataset=\" + imgInf.parent_id;\n\n $.ajax({\n url: url,\n success: (resp) => {\n let msg = \"\";\n if (typeof resp.id === 'number') {\n let linkWebclient = this.context.server +\n this.context.getPrefixedURI(WEBCLIENT) +\n \"/?show=image-\" + resp.id;\n let linkIviewer = this.context.server +\n this.context.getPrefixedURI(IVIEWER) +\n \"/?images=\" + resp.id;\n if (this.context.initial_type !== INITIAL_TYPES.WELL &&\n typeof imgInf.parent_id === 'number')\n linkIviewer += \"&dataset=\" + imgInf.parent_id;\n msg =\n \"<a href='\" + linkWebclient + \"' target='_blank'>\" +\n \"Navigate to Image in Webclient</a><br>\" +\n \"<br><a href='\" + linkIviewer + \"' target='_blank'>\" +\n \"Open Image in iviewer</a>\";\n } else {\n msg = \"Failed to create projected image\";\n if (typeof resp.error === 'string')\n console.error(resp.error);\n }\n Ui.showModalMessage(msg, 'Close');\n }\n });\n }\n // hide context menu\n this.hideContextMenu();\n // prevent link click behavior\n return false;\n }", "function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }", "downloadTurtle() {\r\n let canvas = $('#canvas').find('canvas');\r\n let numCanv = canvas.length;\r\n\r\n if (canvas.get(1)) {\r\n $('#trtDownload').attr({\r\n 'download': 'turtle.png',\r\n 'href': canvas.get(numCanv - 1).toDataURL('image/png')\r\n })\r\n\r\n toastr.success('Turlet image downloaded!');\r\n } else {\r\n toastr.error('No image to download!');\r\n }\r\n }", "function saveFile(folderPath, width, height) {\n\t\tdupToNewFile();\n\t\tvar docRef2 = app.activeDocument;\n\t\tresizeDoc(docRef2, width, height);\n\n\t\tfileName = fileName.replace(/\\.[^\\.]+$/, '');\n\t\tvar folder = Folder(folderPath);\n\t\tvar extension,\n\t\t\tsfwOptions;\n\t\tif (isPng) {\n\t\t\textension = \".png\";\n\t\t\t\n\t\t\tsfwOptions = new ExportOptionsSaveForWeb(); \n\t\t\tsfwOptions.format = SaveDocumentType.PNG; \n\t\t\tsfwOptions.includeProfile = false; \n\t\t\tsfwOptions.interlaced = 0; \n\t\t\tsfwOptions.optimized = true; \n\t\t\tsfwOptions.quality = 100;\n\t\t\tsfwOptions.PNG8 = false;\n\t\t} else {\n\t\t\textension = \".jpg\";\n\t\t\t\n\t\t\tsfwOptions = new ExportOptionsSaveForWeb(); \n\t\t\tsfwOptions.format = SaveDocumentType.JPEG; \n\t\t\tsfwOptions.quality = 100; \n\t\t\tsfwOptions.includeProfile = true; \n\t\t\tsfwOptions.optimised = true; \n\t\t}\n\t\t\t\n\t\tif(!folder.exists) {\n\t\t\tfolder.create();\n\t\t}\n\n\t\tvar saveFile = File(folder + \"/\" + fileName + extension);\n\n\t\t// Export the layer as a PNG\n\t\tactiveDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);\n\n\t\t// Close the document without saving\n\t\tactiveDocument.close(SaveOptions.DONOTSAVECHANGES);\n\t}", "function downloadCanvas() {\n saveCanvas('ohwow', 'png');\n}", "addExportCanvasListener(){\n uiElements.BTN_EXPORT.addEventListener(\"click\", () => {\n uiElements.CANAVS.toBlob(function(blob){\n saveAs(blob, \"image.png\");\n });\n });\n }", "_downloadSvgAsPng() {\n savesvg.saveSvgAsPng(document.getElementById(\"svg\"), \"timeline.png\");\n }", "function saveToCameraRoll() {\n\tif (typeof canvas2ImagePlugin !== 'undefined') {\n\t\tcanvas2ImagePlugin.saveImageDataToLibrary(\n\t\tfunction(msg) {\n\t\t\t//console.log(msg);\n\t\t}, function(err) {\n\t\t\t//console.log(err);\n\t\t}, 'savespot');\n\t}\n}", "function download_anim()\n{\n //build_anim_data();\n var anim_blob = new Blob([anim_content], { type: \"application/octet-stream\"});\n var filename=$(\"#filename\").val()+\".poi\";\n saveAs(anim_blob, filename);\n\n}", "function convertCanvastoImage(){\n var filename=document.getElementById(\"filename\").value;\n var canvas=document.getElementById(\"canvasID\"+pageCanvas);\n canvas.toBlob(function(blob){\n\t saveAs(blob, filename +\".jpg\");\n }, \"image/jpg\");\n $(\"#configPopUp\").dialog('destroy');\n\treturn;\n}", "capture(){\n // Create a hidden canvas of the appropriate size\n let output = document.createElement(\"canvas\");\n output.setAttribute(\"height\", this.height);\n output.setAttribute(\"width\", this.width);\n output.style.display = \"none\";\n\n let outputCtx = output.getContext(\"2d\");\n\n // Draw each canvas to the hidden canvas in order of z index\n for(let z=0; z < privateProperties[this.id].canvases.length; z++){\n outputCtx.drawImage(privateProperties[this.id].canvases[i], 0, 0);\n }\n\n // Get the image data\n let dataUrl = output.toDataURL();\n\n // Save the image as a png\n let a = document.createElement(\"a\");\n a.href = dataUrl;\n a.download = \"ScreenShot\" + (new Date().getDate())+\".png\";\n document.body.appendChild(a);\n a.click();\n a.remove();\n }", "save() {\n\n let files = new Visitor(\n this.fullName,\n this.age,\n this.visitDate,\n this.visitTime,\n this.comments,\n this.assistedBy\n );\n let fileData = JSON.stringify(files)\n const fs = require('fs');\n\n id++;\n\n fs.writeFile(`visitor${id}.json`, fileData, err => {\n if (err) {\n throw (Error + 'Cannot save file');\n } else {\n console.log('File was saved');\n\n }\n });\n\n return 'File was saved';\n }", "function downloadImage() {\n var link = document.createElement('a');\n link.download = 'diagram.png';\n link.href = myDiagram.makeImage().src;\n link.click();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=== latest Blog Carousel ===
function latestBlogCarousel() { if ($('.latest-blog-carousel').length) { $('.latest-blog-carousel').owlCarousel({ dots: true, loop: true, margin: 30, nav: false, navText: [ '<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>' ], autoplayHoverPause: false, autoplay: 6000, smartSpeed: 1000, responsive: { 0: { items: 1 }, 600: { items: 1 }, 800: { items: 2 }, 1024: { items: 2 }, 1100: { items: 3 }, 1200: { items: 3 } } }); } }
[ "buildCarousel() {\n // Subclasses may override.\n }", "function fullBodyCarousel(){\n\t$('.full-body-carousel').owlCarousel({\n items:1,\n loop:false,\n center:true,\n margin:0,\n URLhashListener:true,\n autoplayHoverPause:true,\n startPosition: 'URLHash',\n animateOut: 'fadeOut',\n animateIn: 'fadeIn'\n });\n}", "function owl_main_carousel() {\r\n //owl slider\r\n var owl = $(\"#main-carousel\");\r\n owl.owlCarousel({\r\n nav: true, // Show next and prev buttons\r\n smartSpeed: 1000,\r\n dotsSpeed: 1000,\r\n dragEndSpeed: true,\r\n dragEndSpeed: 1000,\r\n singleItem: true,\r\n pagination: false,\r\n\r\n items: 1,\r\n });\r\n }", "function truethemes_flexslider_for_gallery_post_format(){\n jQuery('.karma-blog-slider').flexslider({\n animation: \"slide\",\n start: function(slider) {\n slider.removeClass('loading');\n}\n});\njQuery(\".karma-blog-slider .flex-prev\").addClass('fa fa-chevron-left').text('');\njQuery(\".karma-blog-slider .flex-next\").addClass('fa fa-chevron-right').text('');\n}", "function createCarousel() {\n\n\t\t\tvar slide = [];\n\n\t\t\tfor (var i = 0; i < currentMap[0].checkpoints.length; i++) {\n\t\t\t\t//background: url('+ currentMap[0].checkpoints[i].image +') no-repeat center center; background-size: cover;\n\t\t\t\tslide = '<div class=\"slide full-height\" id=\"slide'+(i + 1)+'\" data-zoom=\"'+currentMap[0].checkpoints[i].zoomLevel+'\">\\\n\t\t\t\t\t\t\t<div class=\"landscape-image full-height\" style=\"backgroundColor:#000;\"></div>\\\n\t\t\t\t\t\t </div>';\n\n\t\t\t\t $('#carousel').append(slide);\n\n\n\t\t\t};\n\n\t\t\tsetTimeout(function(){\n\n\t\t\t\t$('#carousel').slick({\n\t\t\t\t\tdots: false,\n\t\t\t\t\tspeed: 200,\n\t\t\t\t\tinfinite: true,\n\t\t\t\t\tadaptiveHeight: true,\n\t\t\t\t\tcenterMode: false,\n\t\t\t\t\tslidesToShow: 1,\n\t\t\t\t\tnextArrow: '.next',\n \t\t\t\t\tprevArrow: '.previous'\n\t\t\t\t});\n\n\t\t\t}, 500);\n\n\t\t}", "function init_galleryslider(){\n var $owl = $(\".slider-thumbnail\");\n $owl.imagesLoaded( function(){\n $owl.owlCarousel({\n autoPlay : 3000,\n slideSpeed : 600,\n stopOnHover : true,\n items : 4,\n itemsDesktop : [1199,4],\n itemsDesktopSmall : [979,3],\n itemsTablet : [600,2],\n itemsMobile : [479,1],\n navigation : true,\n navigationText : [ '<i class=\"fa fa-angle-left\"></i>', '<i class=\"fa fa-angle-right\"></i>'],\n });\n });\n}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) {\n this.playSlideshow()\n }\n }", "function goToPreviousImage() {\n clearInterval(automaticSlideInstance);\n var oldIndex = currentIndex;\n var oldDot = carouselNavigationContainer[oldIndex];\n\n currentIndex = currentIndex === 0 ? numberOfImages - 1 : currentIndex - 1;\n var currentDot = carouselNavigationContainer[currentIndex];\n\n changeNavigationDot(oldDot, currentDot);\n animateSlide(oldIndex, currentIndex);\n\n setTimeout(automaticSlide, 0);\n}", "function setupPortfolio()\r\n{\r\n setupSliderAndThumbs();\r\n}", "function initCycleCarousel() {\n\tjQuery('.slider').scrollAbsoluteGallery({\n\t\tmask: '.mask',\n\t\tslider: '.slideset',\n\t\tslides: '.slide',\n\t\tbtnPrev: 'a.btn-prev',\n\t\tbtnNext: 'a.btn-next',\n\t\tpagerLinks: '.pagination li',\n\t\tstretchSlideToMask: true,\n\t\tpauseOnHover: true,\n\t\tmaskAutoSize: true,\n\t\tautoRotation: true,\n\t\tswitchTime: 3000,\n\t\tanimSpeed: 500\n\t});\n}", "function nextArticle(){\r\n //hide all\r\n for(var index = 0; index < articleContainers.length; index++){\r\n if(articleContainers[index] != null){\r\n articleContainers[index].style.display = \"none\";\r\n }\r\n }\r\n if(currentArticle < articleSRC.length-1){\r\n // increment current\r\n currentArticle++;\r\n //show current\r\n articleContainers[currentArticle].style.display = 'block';\r\n //set current article\r\n document.querySelector('#current-article-1').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n document.querySelector('#current-article-2').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n // if not loaded create next\r\n if(currentArticle < articleSRC.length-1 && articles[currentArticle+1] == null){\r\n loadJSON(currentArticle+1)\r\n }\r\n }else if(currentArticle < articleSRC.length){\r\n \r\n // Show the rating page\r\n document.querySelector('#rating').style.display = 'block';\r\n currentArticle++;\r\n document.querySelector('#current-article-1').textContent = 'Rating Page';\r\n document.querySelector('#current-article-2').textContent = 'Rating Page';\r\n }\r\n}", "function brandsCarousel(){\n $('.brands-items-carousel').slick({\n infinite: true,\n slidesToShow: 4,\n slidesToScroll: 1,\n arrows: false,\n autoplay: true,\n autoplaySpeed: 1000000,\n speed: 6000,\n useCSS: false,\n swipeToSlide: false,\n responsive: [\n {\n breakpoint: 767,\n settings: {\n slidesToShow: 3,\n }\n },\n {\n breakpoint: 575,\n settings: {\n slidesToShow: 2,\n }\n } \n ]\n });\n }", "function prevArticle(){\r\n document.querySelector('#rating').style.display = 'none';\r\n if(currentArticle > 0){\r\n //hide all\r\n for(var index = 0; index < articleContainers.length; index++){\r\n if(articleContainers[index] != null){\r\n articleContainers[index].style.display = \"none\";\r\n }\r\n }\r\n //decrement currnet\r\n currentArticle--;\r\n // show current\r\n articleContainers[currentArticle].style.display = 'block'\r\n //show current article number\r\n document.querySelector('#current-article-1').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n document.querySelector('#current-article-2').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n }else{\r\n console.log(\"ERROR: no previous articles\")\r\n }\r\n}", "slideNext() {\n super.slideNext();\n this.slides[this.lastSlide].style.opacity = 0;\n this.slides[this._index].style.opacity = 1;\n }", "mixSlides() {\n let items = this.state.items;\n let len = this.state.dataslide;\n let indicators = [];\n items = this.randomizeArr(items, len);\n\n for (let i = 0; i < len; i++) {\n let active = this.state.first === items[i];\n indicators.push(<CarouselLi dataslide={i} active={active} />);\n }\n this.setState({ indicators: indicators, items: items });//set the random order and indicators\n\n }", "function setBxSlider() {\r\n $('.bxslider.catalog').bxSlider({\r\n mode: 'fade',\r\n pagerCustom: '#bx-pager',\r\n preloadImages: 'visible',\r\n pager: true,\r\n speed: 500,\r\n controls: true,\r\n adaptiveHeight: true,\r\n adaptiveHeightSpeed: 500,\r\n nextText: \"\",\r\n prevText: \"\",\r\n onSliderLoad: function($elemIndex){\r\n setImageSliderControls(null, $elemIndex);\r\n Baralaye.Template.VAlign();\r\n },\r\n onSlideBefore: function($elem){\r\n Baralaye.Template.VAlign($elem);\r\n },\r\n onSlideAfter: function($elem){\r\n setImageSliderControls($elem, null);\r\n }\r\n });\r\n }", "function grid_carousel_alt(){\n $('.services-carousel').slick({\n slidesToShow: 3,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 1500,\n arrows: false,\n dots: false,\n pauseOnHover: false,\n responsive: [{\n breakpoint: 1200,\n settings: {\n slidesToShow: 2\n }\n }, {\n breakpoint: 768,\n settings: {\n slidesToShow:1\n }\n }]\n });\n }", "function showBlog() {\n\n document.querySelectorAll('.js-card-desktop').forEach(card => {\n card.addEventListener('click', (e)=>{\n e.preventDefault();\n cardContent.innerHTML = drawBlog(myDictionary[`n${e.target.dataset.id}`]);\n })\n })\n}", "function newsSlider() {\n $(document).ready(function () {\n $('.news-slider').slick({\n slidesToShow: 3,\n // Стрелки\n // arrows: true,\n\n // Navigation Buttons previous and next\n prevArrow: $('.news__navigation-previous'),\n nextArrow: $('.news__navigation-next'),\n\n // Dots\n // dotsClass: 'news__slick-dots',\n appendDots: $('.news__section-dots'),\n dots: true,\n // infinite: true,\n autoplay: true,\n autoplaySpeed: 4000,\n // Responsive\n responsive: [{\n breakpoint: 992,\n settings: {\n slidesToShow: 2\n }\n },\n {\n breakpoint: 769,\n settings: {\n slidesToShow: 1\n }\n },\n {\n breakpoint: 576,\n // settings: 'unslick',\n settings: {\n slidesToShow: 1\n }\n },\n ]\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables are input types A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).
function VariablesAreInputTypes(context) { return { VariableDefinition: function VariableDefinition(node) { var type = Object(_utilities_typeFromAST__WEBPACK_IMPORTED_MODULE_3__["typeFromAST"])(context.getSchema(), node.type); // If the variable type is not an input type, return an error. if (type && !Object(_type_definition__WEBPACK_IMPORTED_MODULE_2__["isInputType"])(type)) { var variableName = node.variable.name.value; context.reportError(new _error_GraphQLError__WEBPACK_IMPORTED_MODULE_0__["GraphQLError"](nonInputTypeOnVarMessage(variableName, Object(_language_printer__WEBPACK_IMPORTED_MODULE_1__["print"])(node.type)), [node.type])); } } }; }
[ "enterTypeVariable(ctx) {\n\t}", "function validateTypesToStore(expType, savedType, index, variable) {\n if (expType === savedType) {\n if (savedType === 'i') {\n emit(`istore ${index}`, -1);\n } else if (expType === 's') {\n emit(`astore ${index}`, -1);\n }\n } else {\n console.error(`ERROR: types not matching`);\n process.exit(1);\n }\n }", "if (type instanceof GraphQLNonNull) {\n if (!valueAST) {\n if (type.ofType.name) {\n return [ `Expected \"${String(type.ofType.name)}!\", found null.` ];\n }\n return [ 'Expected non-null value, found null.' ];\n }\n return isValidLiteralValue(type.ofType, valueAST);\n }", "function get_var_operand_types( operands_byte, operands_type )\n\t{\n\t\tfor ( var i = 0; i < 4; i++ )\n\t\t{\n\t\t\toperands_type.push( (operands_byte & 0xC0) >> 6 );\n\t\t\toperands_byte <<= 2;\n\t\t}\n\t}", "function get_var_operand_types(operands_byte, operands_type) {\r\n for (var i = 0; i < 4; i++) {\r\n operands_type.push((operands_byte & 0xC0) >> 6);\r\n operands_byte <<= 2;\r\n }\r\n }", "check_type(parent_var_type, node, curr_var_type) {\n if (parent_var_type !== curr_var_type) {\n if (!this.invalid_semantic_programs.includes(this._current_ast.program)) {\n this.invalid_semantic_programs.push(this._current_ast.program);\n } // if\n this.output[this.output.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, ERROR, `Type mismatch error: tried to perform an operation on [${curr_var_type}] with [${parent_var_type}] at ${node.getToken().lineNumber}:${node.getToken().linePosition}`) // OutputConsoleMessage\n ); // this.output[this.output.length - 1].push\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, ERROR, `Type mismatch error: tried to perform an operation on [${curr_var_type}] with [${parent_var_type}] at ${node.getToken().lineNumber}:${node.getToken().linePosition}`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n this._error_count += 1;\n return false;\n } // if\n return true;\n }", "['@kind']() {\n super['@kind']();\n if (this._value.kind) return;\n\n this._value.kind = 'variable';\n }", "wrapType(field) {\n if (\n field.type instanceof GraphQLNonNull &&\n field.type.ofType instanceof GraphQLScalarType\n ) {\n field.type = new GraphQLNonNull(new NotEmptyType(field.type.ofType));\n } else if (field.type instanceof GraphQLScalarType) {\n field.type = new NotEmptyType(field.type);\n } else {\n throw new Error(`Not a scalar type: ${field.type}`);\n }\n }", "function processUserInputVariables(event) {\n var timeoutVariablesInput = null;\n clearTimeout(timeoutVariablesInput);\n timeoutVariablesInput = setTimeout(function () {\n // get diff from old value / new value\n var newValue = document.getElementById(\"numbOfVariables\").value;\n\n if (newValue === \"\") {\n // nothing to do, waiting for user input\n // return;\n } else if (newValue < 1) {\n // the input is negative, set the old\n // value\n document.getElementById(\"numbOfVariables\").value = numbOfVariables;\n // return;\n } else {\n\n var diffVariables = newValue - numbOfVariables;\n\n if (diffVariables > 0) {\n for (var i = 0; i < diffVariables; i++) {\n numbOfVariables++;\n addVariable();\n }\n } else if (diffVariables < 0) {\n for (var j = diffVariables; j < 0; j++) {\n if (numbOfVariables < 2) {\n break;\n }\n numbOfVariables--;\n removeVariable();\n }\n }\n }\n\n }, 500);\n\n }", "function processVariable(variableContent) {\n\n\tswitch (variableContent.type) {\n\t\tcase \"SassString\":\n\n\t\t\tif (variableContent.value.includes(\"var(\")) {\n\t\t\t\tval = variableContent.value;\n\t\t\t} else {\n\t\t\t\tval = `\"${variableContent.value}\"`\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"SassNumber\":\n\t\t\tval = variableContent.value + variableContent.unit;\n\t\t\tbreak;\n\t\tcase \"SassColor\":\n\t\t\tval = variableContent.value.hex;\n\t\t\tbreak;\n\t\tcase \"SassList\":\n\t\t\t//Lists are strange objects, but the \"expression\" is what we want here.\n\t\t\tval = variableContent.declarations[0].expression;\n\n\t\t\tbreak;\n\t\tcase \"default\":\n\t\t\tconsole.error(\"UNEXPECTED TYPE\", variableContent.type);\n\t\t\tprocess.exit();\n\t\t\tbreak;\n\t}\n\treturn val;\n}", "function isVar(node) {\n return t.isVariableDeclaration(node, { kind: \"var\" }) && !node[_constants.BLOCK_SCOPED_SYMBOL];\n}", "function lce_expr_var(input)\n{\n\tthis.type = \"V\";\n\tthis.data = strip_ws(input);\n\n\tthis.copy = function()\n\t{\n\t\treturn new lce_expr_var(this.data);\n\t}\n\t\n\tthis.toString = function()\n\t{\n\t\treturn this.data;\n\t}\n}", "function refinedVariableType(value, mergedTable, query, templateElement) {\n if (value === '$implicit') {\n // Special case the ngFor directive\n const ngForDirective = templateElement.directives.find(d => {\n const name = compiler_1.identifierName(d.directive.type);\n return name == 'NgFor' || name == 'NgForOf';\n });\n if (ngForDirective) {\n const ngForOfBinding = ngForDirective.inputs.find(i => i.directiveName == 'ngForOf');\n if (ngForOfBinding) {\n // Check if there is a known type for the ngFor binding.\n const bindingType = new expression_type_1.AstType(mergedTable, query, {}).getType(ngForOfBinding.value);\n if (bindingType) {\n const result = query.getElementType(bindingType);\n if (result) {\n return result;\n }\n }\n }\n }\n }\n // Special case the ngIf directive ( *ngIf=\"data$ | async as variable\" )\n if (value === 'ngIf') {\n const ngIfDirective = templateElement.directives.find(d => compiler_1.identifierName(d.directive.type) === 'NgIf');\n if (ngIfDirective) {\n const ngIfBinding = ngIfDirective.inputs.find(i => i.directiveName === 'ngIf');\n if (ngIfBinding) {\n const bindingType = new expression_type_1.AstType(mergedTable, query, {}).getType(ngIfBinding.value);\n if (bindingType) {\n return bindingType;\n }\n }\n }\n }\n // We can't do better, return any\n return query.getBuiltinType(symbols_1.BuiltinType.Any);\n}", "function UserInput(){\n let Input = READLINE.question(\"what operation do you want addition, subtraction, multiplication, or division?\")\n\nif (input == \"addition\"){\n\tlet addinput1 = READLINE.question(\"what is your first number?\");\n\tlet addinput2 = READLINE.question(\"what is your second number?\");\n\treturn addNumbers((parselnt (addinput1), parselnt (addinput2)));\n}\n\nelse if ( input == \"subtraction\"){\n\tlet subinput1 = READLINE.question(\"what is your first number?\");\n\tlet subinput2 = READLINE.question(\"what is your second number?\");\n\treturn subNumbers((parselnt (subinput1), parselnt (subinput2)));\n}\n\nelse if (input == \"multiplication\"){\n\tlet multiplyinput1 = READLINE.question(\"what is your first number?\");\n\tlet multiplyinput2 = READLINE.question(\"what is your second number?\");\n\treturn multiplyNumbers((parselnt (multiplyinput1), parselnt (multiplyinput2)));\n}\n\nelse if (input == \"division\"){\n\tlet divideinput1 = READLINE.question(\"what is your first number?\");\n\tlet divideinput2 = READLINE.question(\"what is your second number?\");\n\treturn divideNumbers((parselnt (divideinput1), parselnt (divideinput2)));\n\t}\n}", "function assertSaneArgs (args) {\n for (var i = args.length - 1; i >= 0; i--) {\n var arg = args[i]\n assertHasProperty(arg, 'name')\n assertHasProperty(arg, 'type')\n // assertHasProperty(arg, 'def')\n var def = arg.def\n if (def && !(def instanceof Literal)) {\n throw new Error('Expected default to be an AST.Literal')\n }\n }// for\n}// assertSaneArgs", "enterNumericType(ctx) {\n\t}", "function checkInput(game) {\n if (game.inputVariables.length === 0) {\n errors.push(\"A game must define at least one input variable\");\n }\n var inputObject;\n for (var i = 0; i < game.inputVariables.length; i++) {\n inputObject = game.inputVariables[i];\n var textField = inputObject.textField ? 1 : 0;\n var scrollDown = inputObject.scrollDown ? 1 : 0;\n var checkBox = inputObject.checkBox ? 1 : 0;\n var sum = textField + scrollDown + checkBox;\n // must define exactly one of three\n if (sum < 1) {\n errors.push(\"An input variable must define a textField, scrollDown or checkBox attribute\");\n }\n else if (sum > 1) {\n errors.push(\"An input variable must either have a textField, scrollDown or checkBox attribute, but not several of them\");\n }\n // textfield\n if (textField === 1) {\n // textfield braucht type (in string, number) und default, default muss richtiger type\n var tf = inputObject.textField;\n if (tf.type) {\n if (tf.type === \"string\" || tf.type === \"number\")\n ;\n else {\n errors.push(\"Input variable '\" + inputObject.name + \"': A textField can be of type 'string' or 'number'\");\n }\n } else {\n errors.push(\"Input variable '\" + inputObject.name + \"': textField must define a type (string or number).\");\n }\n if (tf.default) {\n if (tf.type && typeof tf.default !== tf.type) {\n errors.push(\"Input variable '\" + inputObject.name + \"': default value in textField does not match type\");\n }\n } else {\n errors.push(\"Input variable '\" + inputObject.name + \"': textField must define the default attribute\");\n }\n // generelle methode: objekt darf maximal + array, andere attribute falsch? benötigt?\n }\n // scrolldown\n else if (scrollDown === 1) {\n scrollCheck(inputObject.scrollDown, inputObject.name);\n }\n // checkbox\n else if (checkBox === 1) {\n scrollCheck(inputObject.checkBox, inputObject.name);\n }\n // Warning if calculation function is not defined\n if (inputObject.calculationFunction) {\n if (typeof inputObject.calculationFunction !== \"function\") {\n errors.push(\"Input variable '\" + inputObject.name + \"': calculationFunction must be a function.\");\n }\n } else {\n warnings.push(\"Input variable '\" + inputObject.name + \"': No calculation function specified. Game cannot be used in simulation or with computer players\");\n }\n }\n }", "handleInput(input) {\n // input is number\n if (!isNaN(input)) {\n this.handleNumber(input);\n // input is decimal\n } else if (input === \"decimal\") {\n this.handleDecimal();\n } else {\n // input is an operator\n this.handleOperator(input);\n }\n }", "static create(field, constraint, schema) {\n if (field.type instanceof GraphQLScalarType) {\n field.type = new this(field.type, constraint);\n } else if (field.type instanceof GraphQLNonNull\n && field.type.ofType instanceof GraphQLScalarType) {\n field.type = new GraphQLNonNull(new this(field.type.ofType, constraint));\n } else if (isWrappingType(field.type) && field.type instanceof GraphQLList) {\n field.type = new GraphQLList(new this(field.type, constraint));\n } else {\n throw new Error(`Type ${field.type} cannot be validated. Only scalars are accepted`);\n }\n\n const typeMap = schema.getTypeMap();\n let { type } = field;\n if (isWrappingType(type)) {\n type = type.ofType;\n }\n\n if (isNamedType(type) && !typeMap[type.name]) {\n typeMap[type.name] = type;\n }\n }", "*createVariables(variables){\n\n\t\tfor (let variable of variables){\n\t\t\n\t\t\t//console.log('STATUS: creating variable', variable);\n\t\t\t\t\t\t\n\t\t\tvar state = yield this.command('varCreate', {'name': '-', 'frame': '*', 'expression': variable.name});\n\t\t\tif (!state.status){\n\t\t\t\tthrow(new nonFatalError('bad varCreate return state'));\n\t\t\t}\n\t\t\t\n\t\t\t// save the variable's state\n\t\t\tif (state.status.name){\n\t\t\t\tvariable.key = variable.name;\n\t\t\t\tvariable.name = state.status.name;\n\t\t\t}\n\t\t\tif (state.status.value)\n\t\t\t\tvariable.value = state.status.value;\n\t\t\tif (state.status.type)\n\t\t\t\tvariable.type = state.status.type;\n\t\t\tif (state.status.numchild)\n\t\t\t\tvariable.numchild = parseInt(state.status.numchild);\n\t\t\t\n\t\t\tif (variable.numchild) {\n\t\t\t\tconsole.log('STATUS: variable created, listing children', variable);\n\t\t\t\tthis.recursionCounter = 0;\n\t\t\t\tvariable = yield _co(this, 'listChildren', variable);\n\t\t\t} else {\n\t\t\t\tconsole.log('STATUS: variable created, no children', variable);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\treturn Promise.resolve();\n\t\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the screen models object with screen model of each screen.
static _initScreenModels() { const artistsRepository = new ArtistsRepository(); const albumsRepository = new AlbumsRepository(); const songsRepository = new SongsRepository(); this._screenModels = { artistsListScreenModel: new ArtistsListScreenModel(artistsRepository), artistDetailsScreenModel: new ArtistDetailsScreenModel(artistsRepository), albumsListScreenModel: new AlbumsListScreenModel(albumsRepository), albumDetailsScreenModel: new AlbumDetailsScreenModel(albumsRepository), songsListScreenModel: new SongsListScreenModel(songsRepository) } }
[ "static getScreenModels() {\n if (!this._screenModels) {\n this._initScreenModels();\n }\n\n return this._screenModels;\n }", "initGameObjets(){\n\t\tlet modele = this.controller.modele;\n\t\t//Init les objets\n\t\tthis.scene.add(modele.table.model);\n\t\tthis.scene.add(modele.environment.model)\n\t\tthis.scene.add(modele.board.model)\t\t\n\t}", "function init_model () {\n setup_board ();\n setup_houses ();\n setup_clues ();\n}", "function initUIElements() {\n document.getElementById('splash_image').src = SPLASH_SCREEN_SRC;\n document.getElementById('logo_image').src = LOGO_IMAGE_SRC;\n\n promoImageElement = document.getElementById('promo_image');\n titleElement = document.getElementById('loading_title');\n descriptionElement = document.getElementById('loading_description');\n\n splashScreen = document.querySelector(\"#splash_screen\");\n loadingScreen = document.querySelector(\"#loading_screen\");\n playerScreen = document.querySelector(\"#player\");\n errorScreen = document.querySelector(\"#error_screen\");\n screens = [ splashScreen, loadingScreen, playerScreen, errorScreen ];\n screenController = new _ScreenController(screens);\n }", "init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}", "function init(){\n homeScreen.createHomePage();\n beaverEvents.addModel(beaverApp);\n beaverEvents.addModel(beaverRelations);\n beaverEvents.getViewState(homeScreen);\n beaverEvents.getViewState(profileView);\n beaverEvents.activeView = homeScreen.name;\n beaverEvents.viewState.homeScreen.showMapButton();\n // Display beavers\n beaverEvents.displayBeavers();\n // beaverEvents.getGeoLocation();\n homeScreenHandlers.setupEvents();\n}", "init() {\n const squaresCopy = this.board.squares.slice(0);\n this.board.placePlayers(this.players, squaresCopy);\n this.board.placeWeapons(this.weapons, squaresCopy);\n this.board.placeWalls(this.nbOfWalls, squaresCopy);\n }", "initialize() {\n\t\tconst weekTR = {ends:{value:7,unit:'days'},starts:{value:60,unit:'minutes'}};\n\t\tconst monthTR = {ends:{value:1,unit:'months'},starts:{value:60,unit:'minutes'}};\n\t\t\n\t\tthis.models['UserElectricityNowModel'] = this.master.modelRepo.get('UserElectricityNowModel');\n\t\tthis.models['UserElectricityNowModel'].subscribe(this);\n\t\t\n\t\tthis.models['UserElectricityDayModel'] = this.master.modelRepo.get('UserElectricityDayModel');\n\t\tthis.models['UserElectricityDayModel'].subscribe(this);\n\t\t\n\t\tconst model_ElectricityWeek = new UserApartmentModel({name:'UserElectricityWeekModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:weekTR});\n\t\tmodel_ElectricityWeek.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityWeekModel',model_ElectricityWeek);\n\t\tthis.models['UserElectricityWeekModel'] = model_ElectricityWeek;\n\t\t\n\t\tconst model_ElectricityMonth = new UserApartmentModel({name:'UserElectricityMonthModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:monthTR});\n\t\tmodel_ElectricityMonth.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityMonthModel',model_ElectricityMonth);\n\t\tthis.models['UserElectricityMonthModel'] = model_ElectricityMonth;\n\t\t\n\t\t\n\t\tthis.models['MenuModel'] = this.master.modelRepo.get('MenuModel');\n\t\tthis.models['MenuModel'].subscribe(this);\n\t\t\n\t\tthis.view = new UserElectricityView(this);\n\t\t// If view is shown immediately and poller is used, like in this case, \n\t\t// we can just call show() and let it start fetching... \n\t\t//this.show(); // Try if this view can be shown right now!\n\t}", "function setupWorms()\n{\n\tvar playingWorms = getPlayingWorms();\n\t$.each(playingWorms, function(index, worm) {\n\t\tif(worm.active) {\n\t\t\tvar currentWorm = new Worm(worm.color);\n\t\t\tplayingWormsObjetcs.push(currentWorm);\n\t\t}\n\t});\n}", "_initStyles() {\n const styles = this.constructor.styles !== undefined ? this.constructor.styles : this.styles();\n if (!styles) { return }\n this.styleSheet = new ScreenStyle(styles, this.id);\n }", "async init() {\n this.handleEventHandlers()\n await this.model.load().then(\n res => {\n if (res) {\n this.setupView(res)\n }\n }\n )\n }", "static init()\n {\n let aeROM = Component.getElementsByClass(document, PCx86.APPCLASS, \"rom\");\n for (let iROM = 0; iROM < aeROM.length; iROM++) {\n let eROM = aeROM[iROM];\n let parmsROM = Component.getComponentParms(eROM);\n let rom = new ROMx86(parmsROM);\n Component.bindComponentControls(rom, eROM, PCx86.APPCLASS);\n }\n }", "constructor() { \n \n ActionDisplayEntities.initialize(this);\n }", "function init() {\n createjs.Ticker.framerate = animateFps;\n Promise.all([Promise.all(initValueProviders()), Promise.all(initAnimates())]).then(() => {\n Promise.all([initWidgets()]).then(() => {\n resolveValueProviders();\n Object.entries(models).forEach(([, model]) => model.init());\n javascript.onBeforeModelRun.forEach(fn => fn());\n Object.entries(models).forEach(([, model]) => model.play());\n Object.entries(widgets).forEach(([, widget]) => widget.updateComponent());\n spinner.hide();\n });\n });\n}", "function renderScreen() {\n ship.render()\n for (var rock in rocks.rockList) {\n rocks.rockList[rock].render()\n }\n for (var bullet in bullets.bulletList) {\n bullets.bulletList[bullet].update(screen.width, screen.height);\n bullets.bulletList[bullet].render()\n }\n}", "create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }", "function loadOnScreen(){\n\tHeadingArray = getOnScreenHeadingArray();\n URLArray = getOnScreenURLArray();\n\t\n\tfor(var i = 0; i<HeadingArray.length; i++)\n\t getFeed(HeadingArray[i],URLArray[i]);\n}", "function InitBoardVars()\n{\n\t//Initializing history table\n\tfor(let i = 0; i < MAXGAMEMOVES; i++) \n\t{\n\t\tGameBoard.history.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tcastlePerm: 0,\n\t\t\tenPas: 0,\n\t\t\tfiftyMove: 0,\n\t\t\tposKey: 0\n\t\t});\n\t}\t\n\t//Initializing Pv Table\n\tfor (let i = 0; i < PVENTRIES; i++)\n\t{\n\t\tGameBoard.PvTable.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tposKey: 0\n\t\t});\n\t}\n}", "function ScreenScheme() {\n _classCallCheck(this, ScreenScheme);\n\n ScreenScheme.initialize(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
path: path of template return: templateVersion with path is given ex: path = static/js/base/workspaces/list.html return static/js/base/workspaces/templates/v1/list.html?v=23
function templateVersion(path){ //Tweak alway get root if ( path[0] != "/" ){ path = "/" + path; } var seperate_arr = path.split("/"); if (seperate_arr.length > 2){ //Add "templates" before the end item of array seperate_arr.splice(seperate_arr.length - 1,0,"templates",template_version_string); path = seperate_arr.join("/"); } console.log(path); return path + timeStampParam(); }
[ "function KgbTemplateUrl(relPath) {\n return 'views/theme-' + KgbEnv.theme + '/' + relPath + '.html';\n}", "function getTemplate() {\n if (!$scope.state || _.indexOf($scope.viewStates, $scope.state) === -1) {\n throw new Error('Missing $scope.state');\n }\n var template;\n switch ($scope.state) {\n case 'upsell':\n template = 'enterprise/templates/reports-partial-upsell.html';\n break;\n case 'monthly':\n template = 'enterprise/templates/reports-partial-monthly.html';\n break;\n case 'csv':\n template = 'enterprise/templates/reports-partial-csv.html';\n break;\n }\n return template;\n }", "storeTemplate(name, template) {\n let configSnippetsPath = path.join(this.projectFolder, \"config-snippets\", name);\n this.utils.writeJsonFile(configSnippetsPath, template);\n return configSnippetsPath;\n }", "function getTemplateByName(req, res) {\n\tqueryName(req.swagger.params.name.value, function(array){\n\t\tif (array.length > 0) {\n\t\t\tres.json(array[0]);\n\t\t} else {\n\t\t\tres.statusCode = 404;\n\t\t\tres.json({message: \"Not Found\"});\n\t\t}\n\t});\n}", "getTemplate(name) {\n return this.templates.find(template => template.name === name);\n }", "function template(title) {\n var initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var content = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : \"\";\n // there is nothing special except window.__STATE__. All we need to do is grab the initial state from\n // window.__STATE__ and pass it to our configureStore() function as the initial state.\n var scripts = '';\n\n if (content) {\n // To pass along the state, the template attaches state to window.__STATE__ inside a <script> tag.\n // Now you can read state on the client side by accessing window.__STATE__.\n // We also include the SSR companion assets/client.js client-side application in another script tag.\n scripts = \"<script>window.__STATE__ = \".concat(JSON.stringify(initialState), \"</script><script src=\\\"assets/client.js\\\"></script>\");\n } else {\n // If you request the pure client version, it only puts assets/bundle.js inside the script tag.\n // we use `` symbols because we need string to compose it in html tag instead of object\n scripts = \"<script src=\\\"../assets/bundle.js\\\"></script>\"; // this version will return incorrect string and client rendering will work incorrect.\n //scripts = `<script src=\"../assets/bundle.js\" />`;\n // will provide object to us instead of string\n //scripts = (<script src=\"../assets/bundle.js\" />);\n } // returns composed version\n\n\n return \"<html lang=\\\"en\\\">\\n <head>\\n <meta charSet=\\\"utf-8\\\" />\\n <title>\".concat(title, \"</title>\\n <link href=\\\"../assets/style.css\\\" rel=\\\"stylesheet\\\" />\\n </head>\\n <body>\\n <div class=\\\"content\\\"><div id=\\\"app\\\" class=\\\"wrap-inner\\\">\").concat(content, \"</div>\\n <div>\").concat(scripts, \"</div>\\n </body>\\n </html>\");\n}", "function getTemplateDirective(){\r\n\t\tconsole.log(\"getTemplateDirective fired!\")\r\n\t\tvar ddo = {\r\n\t\t\ttemplateURL: \"views/static/listItem.html\"\r\n\t\t};\r\n\t\treturn ddo;\r\n\t}", "getV3TemplatesGitlabCiYmlsName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesGitlabCiYmlsName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function getTemplateInstallPackage(template, originalDirectory) {\n let templateToInstall = 'ins-template';\n if (template) {\n if (template.match(/^file:/)) {\n templateToInstall = `file:${path.resolve(originalDirectory, template.match(/^file:(.*)?$/)[1])}`;\n } else if (template.includes('://') || template.match(/^.+\\.(tgz|tar\\.gz)$/)) {\n // for tar.gz or alternative paths\n templateToInstall = template;\n } else {\n // Add prefix 'ins-template-' to non-prefixed templates, leaving any\n // @scope/ and @version intact.\n const packageMatch = template.match(/^(@[^/]+\\/)?([^@]+)?(@.+)?$/);\n const scope = packageMatch[1] || '';\n const templateName = packageMatch[2] || '';\n const version = packageMatch[3] || '';\n\n if (templateName === templateToInstall || templateName.startsWith(`${templateToInstall}-`)) {\n // Covers:\n // - ins-template\n // - @SCOPE/ins-template\n // - ins-template-NAME\n // - @SCOPE/ins-template-NAME\n templateToInstall = `${scope}${templateName}${version}`;\n } else if (version && !scope && !templateName) {\n // Covers using @SCOPE only\n templateToInstall = `${version}/${templateToInstall}`;\n } else {\n // Covers templates without the `ins-template` prefix:\n // - NAME\n // - @SCOPE/NAME\n templateToInstall = `${scope}${templateToInstall}-${templateName}${version}`;\n }\n }\n }\n\n return Promise.resolve(templateToInstall);\n}", "getV3TemplatesDockerfilesName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesDockerfilesName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function loadTemplate() {\n\t\t\t\t\t// template url\n\t \tvar url = '/spot/partials/filters.html';\n\t\t\t\t\treturn $templateCache.get(url) || $http.get(url, { cache : true });\n\t\t\t\t}", "function version_segment_from_url() {\n var path = window.location.pathname;\n var language_segment = language_segment_from_url();\n var version_segment = '(?:(?:' + version_regexs.join( '|' ) + ')/)';\n var version_regexp = language_segment + '(' + version_segment + ')';\n var match = path.match( version_regexp );\n if ( match !== null )\n return match[ 1 ];\n return ''\n }", "function getVersion(page) {\r\n\tif (dbug) console.log(\"wwvf-cs::Getting Version.\");\r\n\tvar rv = null;\r\n\tif (page) {\r\n\t\tvar xVer = /v((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/i;\r\n\t\tif (page != \"\" && page.match(/Web Experience Toolkit/i)) {\r\n\t\t\t/*var vNumRe = /\\* (.*?) v(\\d[\\d\\.a-z]+)/;\r\n\t\t\tvar wet3v = /\\* Version: v(\\d[\\d\\.a-zA-Z\\-]+)/;\r\n\t\t\tvar wet30 = /Web Experience Toolkit/;\r\n\t\t\tvar wet40 = /v((\\d+(\\.|-[a-z]\\d*))+(-development|release)?)/i;*/\r\n\t\t\tvar clf2Theme = /(CLF 2.0 theme|CSS presentation layer) v(\\d+.\\S+)/i;\r\n\t\r\n\t\t\tvar clf2ThemeVer = page.match(clf2Theme);\r\n\t\t\tif (clf2ThemeVer) {\r\n\t\t\t\trv = \"2.x\";\r\n\t\t\t} else {\r\n\t\t\t\t// Can't be WET 2.0.\r\n\t\t\t\tvar totVer = page.match(xVer);\r\n\t\t\t\tif (!totVer) {\r\n\t\t\t\t\tif (page.match(/Web Experience Toolkit|WET/i)) {\r\n\t\t\t\t\t\ttotVer = page.match(/\\* +((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (totVer) {\r\n\t\t\t\t\trv = totVer[1];\r\n\t\t\t\t} else {\r\n\t\t\t\t\trv = \"?\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rv;\r\n}", "getV3TemplatesLicensesName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesLicensesName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "getTemplate(type) {\n switch (type) {\n case SHIP_TYPE_1:\n return SHIP_TYPE_1_TEMPLATE;\n\n case SHIP_TYPE_2:\n return SHIP_TYPE_2_TEMPLATE;\n\n case SHIP_TYPE_3:\n return SHIP_TYPE_3_TEMPLATE;\n }\n }", "getV3TemplatesGitignoresName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesGitignoresName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "getAndCompileTemplateToRenderSync(theme, templateThemeName, data, name) {\n const view = this;\n\n if (theme && view.configuration.templates[templateThemeName]) {\n // theme template\n let template = hbs.compile(fs.readFileSync(view.configuration.templates[templateThemeName], 'utf8'));\n\n // save in cache if not found ... this may ocurs for templates with fallback\n if (view.loadFromCache()) {\n // cache it if are prod env\n view.templateCache[templateThemeName] = template;\n }\n\n return template;\n } else if (view.configuration.templates[name]) {\n // plugin template\n return hbs.compile(fs.readFileSync(view.configuration.templates[name], 'utf8'));\n } else if (view.loadFromCache() && view.templateCache[name]) {\n return view.templateCache[name];\n } else if (data && data.fallbackTemplate) {\n // fallback template\n return hbs.compile(fs.readFileSync(data.fallbackTemplate, 'utf8'));\n } else {\n return null;\n }\n }", "loadTemplate(name) {\n let configSnippetsPath = path.join(this.projectFolder, \"config-snippets\", name);\n return {\n resource: this.utils.readJsonFile(configSnippetsPath),\n resourcePath: path.join(\"config-snippets\", name)\n }\n }", "getTemplate(tname) {\n let template = this.templates[tname]\n if (!template) {\n template = new Template(this, tname);\n this.templates[tname] = template;\n }\n return template;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This represents a compatibility override for an addon.
function AddonCompatibilityOverride(aType, aMinVersion, aMaxVersion, aAppID, aAppMinVersion, aAppMaxVersion) { this.type = aType; this.minVersion = aMinVersion; this.maxVersion = aMaxVersion; this.appID = aAppID; this.appMinVersion = aAppMinVersion; this.appMaxVersion = aAppMaxVersion; }
[ "SetCompatibleWithPlatform() {}", "SetCompatibleWithAnyPlatform() {}", "SetCompatibleWithEditor() {}", "function patchFennecWindow(window) {\n // This function has a structure similar to patchTabBrowserWindow.\n const loadURI = window.BrowserApp && window.BrowserApp.loadURI;\n if (!loadURI) {\n let windowtype = window.document.documentElement.getAttribute('windowtype');\n if (windowtype === 'navigator:browser') {\n if (window.BrowserApp) {\n console.warn('BrowserApp.loadURI method not found in tabbrowser!');\n } else {\n console.warn('BrowserApp object not found in mobile tabbrowser!');\n }\n }\n return;\n }\n\n if (loadURI.length !== 3) {\n console.warn('Function signature of BrowserApp.loadURI has changed!');\n }\n\n function BrowserApp_loadURI_withHttpsFixup(aURI, aBrowser, aParams) {\n // These parameters are set in mobile/android/chrome/content/browser.js,\n // in the observe method, case \"Tab:Load\" (which in turn is triggered by\n // loadUrl(String,String,int,int) in mobile/android/base/Tabs.java).\n if (isEnabled && aParams && aParams.userRequested && !aParams.isSearch) {\n arguments[0] = maybeFixupURL(aURI);\n }\n return loadURI.apply(this, arguments);\n }\n BrowserApp_loadURI_withHttpsFixup[ADDON_SESSION_TAG] = loadURI;\n window.BrowserApp.loadURI = BrowserApp_loadURI_withHttpsFixup;\n}", "activatePolyfill_() {}", "function ParentThirdPartyInterface() {}", "function ParentThirdPartyClass() {}", "function override(overrides){\r\n return newElementHolderProxy(undefined,overrides)\r\n }", "function extend_IE8(element) {\r\n if (!element || elementIsExtended(element)) return element;\r\n \r\n var t = element.tagName;\r\n if (t && (/^(?:object|applet|embed)$/i.test(t))) {\r\n extendElementWith(element, Element.Methods);\r\n extendElementWith(element, Element.Methods.Simulated);\r\n extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]);\r\n }\r\n \r\n return element;\r\n }", "install() {\n\t\t// this preamble is copied from the base implementation to make sure that we can run install\n\t\tconsole.assert(this.getStatus()!=States.NoLongerCompatile, `PolyfillObjectMixin '${this.name}' can not be installed because the target Atom code has changed since it was written`);\n\t\tif (this.getStatus()!=States.Uninstalled) return;\n\n\t\tdeps.changeStart(this);\n\n\t\t// save the old tree-view.autoReveal value and then get rid of its schema\n\t\tconst oldValue = atom.config.get('tree-view.autoReveal');\n\t\tatom.config.removeSchema('tree-view.autoReveal');\n\t\tthis.origAutorevealSchema = atom.config.getSchema('tree-view.autoReveal');\n\n\t\t// do the normal polyfill install\n\t\tsuper.install();\n\n\t\t// find and replace the handler that TreeView registers with the workspace center object\n\t\tconst handlers = atom.workspace.getCenter().paneContainer.emitter.handlersByEventName[\"did-change-active-pane-item\"];\n\t\tfor (let i=0; i<handlers.length; i++) {\n\t\t\tif (/tree-view.autoReveal/.test(handlers[i])) {\n\t\t\t\tthis.prevHandler = handlers[i];\n\t\t\t\thandlers[i] = (...p)=>{this.target.repondToActiveEditorFocusChange(...p)}\n\t\t\t}\n\t\t}\n\n\t\t// if the user had it set to the non-default value, then set it in its new place\n\t\tif (oldValue)\n\t\t\tatom.config.set('tree-view.autoTrackActivePane.autoReveal', true);\n\n\t\tdeps.changeEnd(this);\n\t}", "_setCompatibilityOptions() {\n // Convert the product config to a placement configuration\n this.config.backwards = 'Ad';\n this.config.type = okanjo.Placement.ContentTypes.products;\n\n // Id / single mode is now ids\n this.config.url = null;\n if (this.config.id) {\n this.config.ids = [this.config.id];\n } else {\n okanjo.warn('Ad widget should have parameter `id` set.');\n }\n this.config.take = 1;\n delete this.config.id;\n\n // Content is automatically determined whether the placement element contains children\n delete this.config.content;\n }", "function super_fn() {\n if (!oldFn) {\n return\n }\n each(arguments, function(arg, i) {\n args[i] = arg\n })\n return oldFn.apply(self, args)\n }", "GetCompatibleWithEditor() {}", "function disableOverride() {\r\n\twindow.parseHTML = noChange;\r\n\twindow.parseJS\t = noChange;\r\n\twindow.parseURL = noChange;\r\n}", "overrideUrl(iUrl) {\n return iUrl;\n }", "_enableExtensibility() {\n\t\t\tvar aExtensionData;\n\t\t\tABAPAccess.getExtensionData = function(sServiceUri, sEntityTypeName, sEntitySetName) {\n\t\t\t\taExtensionData = [{ businessContext: `${sEntityTypeName} EntityTypeContext`, description: \"Other BusinessContext description\" }, { businessContext: `${sEntitySetName} EntitySetContext`, description: \"Some BusinessContext description\"}];\n\t\t\t\treturn Promise.resolve({\n\t\t\t\t\textensionData: aExtensionData,\n\t\t\t\t\tentityType: sEntityTypeName,\n\t\t\t\t\tserviceVersion: \"some dummy ServiceVersion 0.0.1\",\n\t\t\t\t\tserviceName: sServiceUri\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tABAPExtensibilityVariant.prototype.getNavigationUri = function() {\n\t\t\t\treturn Promise.resolve(\"./extensibilityTool.html\");\n\t\t\t};\n\n\t\t\tvar oUshellContainer = ObjectPath.get(\"sap.ushell.Container\");\n\t\t\tif (oUshellContainer) {\n\t\t\t\tABAPAccess.isExtensibilityEnabled = function() {\n\t\t\t\t\treturn Promise.resolve(true);\n\t\t\t\t};\n\t\t\t\tsap.ushell.Container = Object.assign({}, sap.ushell.Container, {\n\t\t\t\t\tgetLogonSystem() {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tgetName() {\n\t\t\t\t\t\t\t\treturn \"ABC\";\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgetClient() {\n\t\t\t\t\t\t\t\treturn \"123\";\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tisTrial() {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\toCore.getEventBus().subscribe(\"sap.ui.core.UnrecoverableClientStateCorruption\", \"RequestReload\", function() {\n\t\t\t\tMessageBox.warning(\"Service Outdated, Please restart the UI - In real world other dialog will come up, that can restart the UI\");\n\t\t\t});\n\t\t}", "function MockConfigAddon() {\n MockConfigAddon.superclass.constructor.apply(this, arguments);\n }", "function Window_ModPatchConfig() {\r\n this.initialize.apply(this, arguments);\r\n}", "setCustomAppearance(app) {\n //TODO\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For first challenge to filter data with country USA and write to file
async function filterCountry() { const data = await fs.readFileSync('input/main.csv'); const records = parser(data, { columns: true }); const results = []; const headers = ['SKU', 'DESCRIPTION', 'YEAR', 'CAPACITY', 'URL', 'PRICE', 'SELLER_INFORMATION', 'OFFER_DESCRIPTION', 'COUNTRY']; //Filter data that have country as USA and add it to a temporary array records.forEach(element => { if (element['COUNTRY'].includes('USA')) { results.push(element); } }); //console.log(results[0]); //Convert Js Objects to string and write to a csv file stringifier(results, { header: true, columns: headers }, (err, data) => { fs.writeFile('output/filteredCountry.csv', data, () => { console.log('Written to filteredCountry.csv'); lowestPrice(); }); }); }
[ "function filterCountry(aliens) {\n return aliens.country == $countryInput.value.trim().toLowerCase();\n}", "function data_cleaning_countries_name(suicideData, countriesJson) {\n let all_countries_in_cjson = _.uniqBy(countriesJson.features, 'properties.name');\n for (let c of all_countries_in_cjson) {\n let currentCjsonCountry = c.properties.name;\n let entry = _.filter(suicideData, function(d) {\n\n if (d.country.indexOf(currentCjsonCountry) != -1) {\n d.country = currentCjsonCountry;\n }\n });\n }\n\n let all_countries_in_sjson = _.uniqBy(suicideData, 'country');\n for (let i of all_countries_in_sjson) {\n let currentSjsonCountry = i.country;\n let entry = _.filter(countriesJson.features, function(d) {\n\n if (d.properties.name.indexOf(currentSjsonCountry) != -1) {\n d.properties.name = currentSjsonCountry;\n }\n });\n }\n}", "function searchForCountry() {\n header.innerHTML = country;\n fetchData(country);\n}", "function loadCountries(){\n\tvar currline = [];\n\tfs.readFile('./countryList.txt', 'utf-8', function(err, data){\n\t\tif (err) throw err;\n\t\t\n\t\tvar lines = data.toString().trim().split('\\n');\n\t\t\n\t\tfor (var i = 0; i < lines.length; i++){\n\t\t\tcurrline = lines[i].split(',');\n\t\t database.create({ code: currline[0], country: currline[1]}, function(err, doc){\n\t\t \tif(!err){\n \t\t\t\tconsole.log(doc.toString());\n \t\t\t} else {\n \t\t\t\tconsole.log(\"Database error: \" + err);\n \t\t\t}\n \t\t});\n\t\t}\n\t});\n}", "function populateResultsTable_by_country() {\n\n\t\t\tvar selectedStates = $(\"#statesListbox_by_country\").val() || [];\n\t\t\tvar HSarray = selected_HS6_Codes\n\n\t\t\timportResultsTable_by_country = searchDBByAbbr(importDestinationDB, selectedStates);\n\t\t\texportResultsTable_by_country = searchDBByAbbr(exportDestinationDB, selectedStates);\n\t\t\tconsole.log('selectedStates: ')\n\t\t\tconsole.log(selectedStates)\n\t\t\tconsole.log('importResultsTable_by_country: ')\n\t\t\tconsole.log(importResultsTable_by_country)\n\t\t\tconsole.log('exportResultsTable_by_country: ')\n\t\t\tconsole.log(exportResultsTable_by_country)\n\t\t\tdrawChart_by_country()\n\t\t\tdrawWorldMap_by_country()\n\t\t}", "function categorizeCountries(pattern) {\n return countriesAll.filter(country => country.includes(pattern));\n}", "function lowestPrice() {\n const data = fs.readFileSync('output/filteredCountry.csv');\n\n const records = parser(data, { columns: true });\n const results = {};\n const final = []\n const headers = ['SKU', 'FIRST_MINIMUM_PRICE', 'SECOND_MINIMUM_PRICE'];\n\n //remove $ sign and convert to float and group prices under same SKUs\n records.forEach(record => {\n if (/^[\\$*]/.test(record['PRICE'])) { \n var price = parseFloat(record['PRICE'].split('$')[1]);\n if (record['SKU'] in results) {\n results[`${record.SKU}`].push(price);\n } else { \n results[`${record.SKU}`] = []; \n results[`${record.SKU}`].push(price);\n }\n }\n });\n\n //Sort prices and create data objects to write to file \n for (var x in results) {\n if (results[x].length > 1) {\n results[x].sort((a, b) => { a - b }); \n } \n final.push({\n SKU: x,\n FIRST_MINIMUM_PRICE: results[x][0],\n SECOND_MINIMUM_PRICE: results[x][results[x].length > 1 ? 1 : 0]\n });\n }\n \n //console.log(results.length);\n //console.log(final[0]);\n\n //Convert Js Objects to string and write to a csv file\n stringifier(final, { header: true, columns: headers }, (err, data) => {\n fs.writeFile('output/lowestPrice.csv', data, () => {\n console.log('Written to lowestPrice.csv');\n });\n });\n}", "function countryFind1(arr) {\n let resultArr = [];\n for (i=0 ; i < arr.length ; i++) {\n if(arr[i].includes(\"land\")){\n resultArr.push(arr[i]);\n }\n }\n\n return resultArr; \n}", "function searchByCountryName() {\n const selectedCountryName = convertToLowerCase(select.value);\n result = products.filter(item => {\n return item.shipsTo.some(shippingCountry => {\n return convertToLowerCase(shippingCountry) === select.value;\n });\n });\n renderProducts(result);\n}", "filterTopTenCountries(data) { \n let header = data['columns'].map(header => header);\n let lastEntryInHeaders = (header[header.length - 1])\n \n //sort data in descending order by total numbers\n let countriesSortedByTotalNumbers = data.sort(compareTotal);\n function compareTotal(a, b) {\n let country1 = a[lastEntryInHeaders]; \n let country2 = b[lastEntryInHeaders]; \n\n let comparison = 0;\n if (country1 > country2) {\n comparison = -1;\n } else if (country1 < country2) {\n comparison = 1;\n }\n return comparison;\n }\n return countriesSortedByTotalNumbers.slice(0, 10)\n }", "function printCountry(country) {\n\t\tvar valStripped = country.replace(\" \", \"\");\n\t\t$(\"#ecf_countries_list\").append(`\n\t\t<div class='cbx'> \n\t\t\t<span> \n\t\t\t\t<input type='checkbox' name='ecf_${valStripped}' \n\t\t\t\t\tid='ecf_${valStripped}' value='${country}' \n\t\t\t\t\tclass='cbx ecf_country_checkbox' checked />\n\t\t\t\t<label for='ecf_${valStripped}'>\n\t\t\t\t\t<span class='cbx'>${country}</span>\n\t\t\t\t</label>\n\t\t\t</span>\n\t\t</div>`);\n\t}", "function areaCodeFilter(Jobject) {\n for (var i = 0; i < geocodeData.length; i++) {\n if (Jobject.zipcode == geocodeData[i].postalCode) {\n return true;\n }\n }\n return false;\n }", "function countryChange() {\n country = document.getElementById(countryName + \"-select\").value;\n updateData();\n }", "function getGoalsByCountry(){\n\t\tvar country = hashValue;\n\t\tcountry = country.charAt(0).toUpperCase() + country.substring(1);\n\t\tshotsPerCountry = _.where(data, {TEAM: country});\n\t\t$('h1#title').html('All of '+ country + '\\'s goals and shots at the 2014 World Cup mapped: click on the dots for more info')\n\t\t_.each(shotsPerCountry, populateGoals);\n\t}", "async getCities(country) {\n // get yesterday's date\n const offset = new Date().getTimezoneOffset() * 60000;\n const yesterday = new Date(Date.now() - 86400000 - offset)\n .toISOString()\n .slice(0, -5);\n\n // complete request\n const query = `?country=${country}&parameter=pm25&date_from=${yesterday}&limit=500&order_by=value&sort=desc`;\n const response = await fetch(this.openaqURI + query);\n const data = await response.json();\n\n // fill array without repeated cities\n let i = 0;\n const results = [];\n while (results.length < 20) {\n if (results.indexOf(data.results[i].city) === -1) {\n results.push(data.results[i].city);\n results.push(data.results[i].value);\n }\n i += 1;\n }\n // group array [[city, value], ...]\n const chunkedResults = [];\n for (let j = 0; j < results.length; j += 2) {\n chunkedResults.push(results.slice(j, j + 2));\n }\n\n return chunkedResults;\n }", "function casesByCountry (){\n\n let today = dateToday();\n let endPoint = 'https://api.covid19tracking.narrativa.com/api/' \n let queryCountriesUrl = endPoint + today; \n let URL = {\n url: queryCountriesUrl,\n method: \"GET\" \n } \n\n // making request to pull all Covid data by countries\n $.ajax(URL).then(function(response){\n countriesData(response.dates[today].countries); \n });\n}", "function showcountries() {\r\nlet finland = new Destination(\"Finland\", \"Europe\", 5.5);\r\nlet southAfrica = new Destination(\"South Africa\", \"Africa\",55 );\r\nlet thailand = new Destination(\"Thailand\", \"Asia\", 68);\r\n let allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\n\r\ndocument.getElementById('country1').innerHTML = (finland.toString());\r\ndocument.getElementById('country2').innerHTML = (southAfrica.toString());\r\ndocument.getElementById('country3').innerHTML = (thailand.toString());\r\n\r\n}", "function formatCountry(country) {\n let formattedCountry;\n if (country === 'USA') {\n formattedCountry = 'the United States';\n } else if (country === 'UK') {\n formattedCountry = 'the United Kingdom';\n } else if (country === 'S.Korea') {\n formattedCountry = 'South Korea';\n } else if (country === 'CAR') {\n formattedCountry = 'the Central African Republic';\n } else if (country === 'DRC') {\n formattedCountry = 'the Democratic Republic of the Congo / Congo Kinshasa';\n } else if (country === 'Congo') {\n formattedCountry = 'the Congo Republic / Congo Brazzaville';\n } else if (country === 'U.S. Virgin Islands') {\n formattedCountry = 'the U.S. Virgin Islands';\n } else {\n formattedCountry = country;\n }\n return formattedCountry;\n}", "function listOfCounty(country) {\n let listOfVolcanoes = [];\n for (const vol of volcanoes) {\n if (vol.Country == country) {\n listOfVolcanoes.push(vol)\n }\n }\n return listOfVolcanoes;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
manages all of the different cases for which the fire rate will change based on the bar_control position
function colliding() { var x = bar_control.x; var y = bar_control.y; var rotation = bar_control.rotation; // hack-fix for situations when orientation changed with moving part if (rotation != 180) { firing_rate.base = 11; firing_rate.text = firing_rate.base.toString(); return; } // different movement depending on whether it's a large rf or small rf if (inner_rf.width == 25) { if (bar_control.width == 25) { // most interaction is straight bar if (rotation == 180) { // large bar at middle or top of green bar if (between(x, y, inner_rf.x, inner_rf.x+inner_rf.width, inner_rf.y, inner_rf.y+inner_rf.height)) { if(y > inner_rf.y+200) { distance = bar_control.y - inner_rf.y - 200; firing_rate.base = calculate_fire_rate_medium(distance-10, 55); firing_rate.text = firing_rate.base.toString(); } else { // bar top top firing_rate.text = "90"; firing_rate.base = 90; } } else if (between(x, y, inner_rf.x-inner_rf.width, inner_rf.x+2*inner_rf.width, inner_rf.y, inner_rf.y+1.2*inner_rf.height)) { firing_rate.text = "2"; firing_rate.base = 2; } else { firing_rate.text = "10"; firing_rate.base = 10; } } else if (rotation == 135 || rotation == 235) { } } else { if (rotation == 180) { if (between(x, y, inner_rf.x, inner_rf.x+inner_rf.width, inner_rf.y, inner_rf.y+inner_rf.height)) { if(y > inner_rf.y+200) { firing_rate.text = "22"; firing_rate.base = 22; } else { firing_rate.text = "55"; firing_rate.base = 55; } } else if (between(x, y, inner_rf.x-inner_rf.width, inner_rf.x+2*inner_rf.width, inner_rf.y, inner_rf.y+1.2*inner_rf.height)) { firing_rate.text = "2"; firing_rate.base = 2; } else { firing_rate.text = "10"; firing_rate.base = 10; } } } //smaller width rf } else { if (bar_control.width == 12.5) { // most interaction is straight bar if (rotation == 180) { if (between(x, y, inner_rf.x, inner_rf.x+inner_rf.width, inner_rf.y, inner_rf.y+inner_rf.height)) { if(y > inner_rf.y+200) { firing_rate.text = "55"; firing_rate.base = 55; } else { firing_rate.text = "90"; firing_rate.base = 90; } } else if (between(x, y, inner_rf.x-inner_rf.width, inner_rf.x+2*inner_rf.width, inner_rf.y, inner_rf.y+1.2*inner_rf.height)) { firing_rate.text = "2"; firing_rate.base = 2; } else { firing_rate.text = "10"; firing_rate.base = 10; } } else if (rotation == 135 || rotation == 235) { } } else { if (rotation == 180) { if (between(x, y, inner_rf.x, inner_rf.x+inner_rf.width, inner_rf.y, inner_rf.y+inner_rf.height)) { if(y > inner_rf.y+200) { firing_rate.text = "22"; firing_rate.base = 22; } else { firing_rate.text = "55"; firing_rate.base = 55; } } else if (between(x, y, inner_rf.x-inner_rf.width, inner_rf.x+2*inner_rf.width, inner_rf.y, inner_rf.y+1.2*inner_rf.height)) { firing_rate.text = "2"; firing_rate.base = 2; } else { firing_rate.text = "10"; firing_rate.base = 10; } } } } }
[ "function updateBars(code) {\n\n\t\t\t// get all the rows in graphic_data concerning current AREACD.\n\t\t\tvar data = graphic_data.filter(function(d) {return d.AREACD == code})\n\t\t\t// \"transpose\" this data into the right format for stacking\n\t\t\ttransposedData = []\n\t\t\tvarnames.forEach( function(d) {\n\t\t\t\tvar tmp_obj = {}\n\t\t\t\ttmp_obj.key = d\n\t\t\t\tdata.forEach( function(k) {\n\t\t\t\t\ttmp_obj[k[dvc.bar.stackVar]] = k[d]\n\t\t\t\t})\n\t\t\t\ttransposedData.push(tmp_obj)\n\t\t\t})\n\t\t\t// bind new data to bars\n\t\t\tbarg.data(stack(transposedData))\n\n\t\t\t// when data is very different for certain areas, it might be necessary to transition to a new x axis\n\t\t\t// get previous upper limit of x domain\n\t\t\tvar prevMax = x.domain()[1];\n\n\t\t\t// set new upper limit of x domain as newMax\n\t\t\t// by default it's the same as the old one\n\t\t\tvar newMax = x.domain()[1];\n\t\t\t// here's an example of some code to change the axis in specific parts of London\n\t\t\t// if (code == 'E09000001' || code == 'E09000030') {\n\t\t\t// \tvar newMax = 40;\n\t\t\t// } else if (code.slice(0,3) == 'E09') {\n\t\t\t// \tvar newMax = 16;\n\t\t\t// } else {\n\t\t\t// \tvar newMax = 5;\n\t\t\t// }\n\n\t\t\tif (prevMax == newMax) { // no change in domain so just move the bars\n\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t.data(function(d) {return d})\n\t\t\t\tmoveBars(100)\n\t\t\t} else {\n\t\t\t\t// change in domain so change x.domain, move axis, contexual lines, data bars\n\t\t\t\tx.domain([0,newMax])\n\n\t\t\t\tvar transitionTime = 600;\n\n\t\t\t\td3.selectAll('.x.axis')\n\t\t\t\t\t.transition() // transition x axis\n\t\t\t\t\t.duration(transitionTime)\n\t\t\t\t\t.call(xAxis)\n\t\t\t\t\t.on(\"start\", function() {\n\t\t\t\t\t\td3.selectAll(\"line.line\") // transition contextual lines at same time as axis\n\t\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t\t.duration(transitionTime)\n\t\t\t\t\t\t\t.attr(\"x1\", function(d) { return x(d.value)})\n\t\t\t\t\t\t\t.attr(\"x2\", function(d) { return x(d.value)})\n\t\t\t\t\t\t\t.on(\"start\", function() {\n\t\t\t\t\t\t\t\tmoveBars(transitionTime) // transition bars with axis\n\t\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.on(\"end\", function() {\n\t\t\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t\t\t.data(function(d) {return d})\n\t\t\t\t\t\tmoveBars(400)\n\t\t\t\t\t})\n\n\t\t\t} // end if else statement\n\n\t\t\tfunction moveBars(t) {\n\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t.transition()\n\t\t\t\t\t.duration(t)\n\t\t\t\t\t.attr(\"width\", function(d) { return x(d[1]) - x(d[0]) })\n\t\t\t\t\t.attr(\"x\", function(d) { return x(d[0]) })\n\t\t\t}\n\t\t}", "function bound_bar_control() {\n\n\t\trotation = bar_control.rotation;\n\n\t\tif (rotation == 180) {\n\n\t\t\tif(bar_control.x < bar_control.width) {\n\t\t\t\tbar_control.x = bar_control.width;\n\t\t\t}\n\t\t\tif (bar_control.y < bar_control.height) {\n\t\t\t\tbar_control.y = bar_control.height;\n\t\t\t}\n\n\t\t\tif (bar_control.y > moving_section.height) {\n\t\t\t\tbar_control.y = moving_section.height;\n\t\t\t}\n\n\t\t\tif (bar_control.x > moving_section.width) {\n\t\t\t\tbar_control.x = moving_section.width;\n\t\t\t}\n\n\t\t} else if (rotation == 90) {\n\n\t\t\tif(bar_control.x < bar_control.height) {\n\t\t\t\tbar_control.x = bar_control.height;\n\t\t\t}\n\t\t\tif (bar_control.y < 0) {\n\t\t\t\t\tbar_control.y = 0;\n\t\t\t}\n\t\t\tif (bar_control.y > moving_section.height - bar_control.width) {\n\t\t\t\t\tbar_control.y = moving_section.height - bar_control.width;\n\t\t\t}\n\n\t\t\tif (bar_control.x > moving_section.width) {\n\t\t\t\t\tbar_control.x = moving_section.width;\n\t\t\t}\n\n\t\t} else if (rotation == 270) {\n\n\t\t\tif(bar_control.x < 0) {\n\t\t\t\tbar_control.x = 0;\n\t\t\t}\n\t\t\tif (bar_control.y < bar_control.width) {\n\t\t\t\t\tbar_control.y = bar_control.width;\n\t\t\t}\n\t\t\tif (bar_control.y > moving_section.height) {\n\t\t\t\t\tbar_control.y = moving_section.height;\n\t\t\t}\n\n\t\t\tif (bar_control.x > moving_section.width - bar_control.height) {\n\t\t\t\t\tbar_control.x = moving_section.width - bar_control.height;\n\t\t\t}\n\n\t\t} \n\t\t\n\t}", "function oxygenBarLogic()\n{\n\tif(oxygenCommand.w > 0)\n {\n oxygenCommand.w -= oxygenRate;\n drowningLogic(false); //We are not currently drowning\n score++;\n\t\t}\n else\n { \n drowningLogic(true);\n }\n}", "function updateConditionsTrackChart2(){\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar temp = getDpsActive();\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar myData = \t[{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"blue\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"Active\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: dpsActive\r\n\t\t\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"winCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.winCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.winCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.winCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.winCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.winCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.winCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t},{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"lossCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.lossCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.lossCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.lossCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.lossCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.lossCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.lossCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t}];\r\n\t\t\t\r\n\t\t\t\t\t// Options to display value on top of bars\r\n\t\t\t\t\tvar myoption = {\r\n\t\t\t\t\t\ttooltips: {\r\n\t\t\t\t\t\t\tenabled: true\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\thover: {\r\n\t\t\t\t\t\t\tanimationDuration: 1\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\tanimation: {\r\n\t\t\t\t\t\tduration: 1,\r\n\t\t\t\t\t\tonComplete: function () {\r\n\t\t\t\t\t\t\tvar chartInstance = this.chart,\r\n\t\t\t\t\t\t\t\tctx = chartInstance.ctx;\r\n\t\t\t\t\t\t\t\tctx.textAlign = 'center';\r\n\t\t\t\t\t\t\t\tctx.fillStyle = \"rgba(0, 0, 0, 1)\";\r\n\t\t\t\t\t\t\t\tctx.textBaseline = 'bottom';\r\n\t\t\t\t\t\t\t\tthis.data.datasets.forEach(function (dataset, i) {\r\n\t\t\t\t\t\t\t\t\tvar meta = chartInstance.controller.getDatasetMeta(i);\r\n\t\t\t\t\t\t\t\t\tmeta.data.forEach(function (bar, index) {\r\n\t\t\t\t\t\t\t\t\t\tvar data = dataset.data[index];\r\n\t\t\t\t\t\t\t\t\t\tctx.fillText(data, bar._model.x, bar._model.y - 5);\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t};\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart = new CanvasJS.Chart(\"chartContainer5\", {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tbackgroundColor: \"black\",\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\ttitle: {\r\n\t\t\t\t\t\t\t\t\t\ttext: \"Conditions Success Rate\",\r\n\t\t\t\t\t\t\t\t\t\tfontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisX: {\r\n\t\t\t\t\t\t\t\t\t\t//title: \"Conditions\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisY: {\r\n\t\t\t\t\t\t\t\t\t\ttitle: \"Count\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t\t//interval: 10\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tlegend: {\r\n\t\t\t\t\t\t\t\t\t\tcursor:\"pointer\",\r\n\t\t\t\t\t\t\t\t\t\titemclick : toggleDataSeries\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\ttoolTip: {\r\n\t\t\t\t\t\t\t\t\t\tshared: true,\r\n\t\t\t\t\t\t\t\t\t\tcontent: toolTipFormatter\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tdata: myData, \t// Chart data\r\n\t\t\t\t\t\t\t\t\toptions: myoption \t// Chart Options [This is optional paramenter use to add some extra things in the chart].\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart.render();\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t }", "_precalculateBarPositions() {\n\n\t\tif ( ! this._initDone )\n\t\t\treturn;\n\n\t\tlet minLog, bandWidth;\n\n\t\tthis._analyzerBars = [];\n\n\t\tif ( this._mode % 10 == 0 ) {\n\t\t// Discrete frequencies or area fill modes\n\t\t\tthis._barWidth = 1;\n\n\t\t\tminLog = Math.log10( this._minFreq );\n\t\t\tbandWidth = this._canvas.width / ( Math.log10( this._maxFreq ) - minLog );\n\n\t\t\tconst minIndex = this.freqToBin( this._minFreq, 'floor' );\n\t\t\tconst maxIndex = this.freqToBin( this._maxFreq );\n\n\t \t\tlet lastPos = -999;\n\n\t\t\tfor ( let i = minIndex; i <= maxIndex; i++ ) {\n\t\t\t\tconst freq = this.binToFreq( i ); // frequency represented by this index\n\t\t\t\tconst pos = Math.round( bandWidth * ( Math.log10( freq ) - minLog ) ); // avoid fractionary pixel values\n\n\t\t\t\t// if it's on a different X-coordinate, create a new bar for this frequency\n\t\t\t\tif ( pos > lastPos ) {\n\t\t\t\t\tthis._analyzerBars.push( { posX: pos, dataIdx: i, endIdx: 0, factor: 0, peak: 0, hold: 0, accel: 0 } );\n\t\t\t\t\tlastPos = pos;\n\t\t\t\t} // otherwise, add this frequency to the last bar's range\n\t\t\t\telse if ( this._analyzerBars.length )\n\t\t\t\t\tthis._analyzerBars[ this._analyzerBars.length - 1 ].endIdx = i;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t// Octave bands modes\n\n\t\t\t// how many notes grouped in each band?\n\t\t\tlet groupNotes;\n\n\t\t\tif ( this._mode == 8 )\n\t\t\t\tgroupNotes = 24;\n\t\t\telse if ( this._mode == 7 )\n\t\t\t\tgroupNotes = 12;\n\t\t\telse if ( this._mode == 6 )\n\t\t\t\tgroupNotes = 8;\n\t\t\telse if ( this._mode == 5 )\n\t\t\t\tgroupNotes = 6;\n\t\t\telse\n\t\t\t\tgroupNotes = this._mode; // for modes 1, 2, 3 and 4\n\n\t\t\t// generate a table of frequencies based on the equal tempered scale\n\n\t\t\tconst root24 = 2 ** ( 1 / 24 );\n\t\t\tconst c0 = 440 * root24 ** -114; // ~16.35 Hz\n\n\t\t\tlet temperedScale = [];\n\t\t\tlet i = 0;\n\t\t\tlet freq;\n\n\t\t\twhile ( ( freq = c0 * root24 ** i ) <= this._maxFreq ) {\n\t\t\t\tif ( freq >= this._minFreq && i % groupNotes == 0 )\n\t\t\t\t\ttemperedScale.push( freq );\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tminLog = Math.log10( temperedScale[0] );\n\t\t\tbandWidth = this._canvas.width / ( Math.log10( temperedScale[ temperedScale.length - 1 ] ) - minLog );\n\n\t\t\t// divide canvas space by the number of frequencies (bars) to display\n\t\t\tthis._barWidth = this._canvas.width / temperedScale.length;\n\t\t\tthis._calculateBarSpacePx();\n\n\t\t\tlet prevBin = 0; // last bin included in previous frequency band\n\t\t\tlet prevIdx = -1; // previous bar FFT array index\n\t\t\tlet nBars = 0; // count of bars with the same index\n\n\t\t\ttemperedScale.forEach( ( freq, index ) => {\n\t\t\t\t// which FFT bin best represents this frequency?\n\t\t\t\tconst bin = this.freqToBin( freq );\n\n\t\t\t\tlet idx, nextBin;\n\t\t\t\t// start from the last used FFT bin\n\t\t\t\tif ( prevBin > 0 && prevBin + 1 <= bin )\n\t\t\t\t\tidx = prevBin + 1;\n\t\t\t\telse\n\t\t\t\t\tidx = bin;\n\n\t\t\t\t// FFT does not provide many coefficients for low frequencies, so several bars may end up using the same data\n\t\t\t\tif ( idx == prevIdx ) {\n\t\t\t\t\tnBars++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// update previous bars using the same index with a smoothing factor\n\t\t\t\t\tif ( nBars > 1 ) {\n\t\t\t\t\t\tfor ( let i = 1; i <= nBars; i++ )\n\t\t\t\t\t\t\tthis._analyzerBars[ this._analyzerBars.length - i ].factor = ( nBars - i ) / nBars;\n\t\t\t\t\t}\n\t\t\t\t\tprevIdx = idx;\n\t\t\t\t\tnBars = 1;\n\t\t\t\t}\n\n\t\t\t\tprevBin = nextBin = bin;\n\t\t\t\t// check if there's another band after this one\n\t\t\t\tif ( temperedScale[ index + 1 ] !== undefined ) {\n\t\t\t\t\tnextBin = this.freqToBin( temperedScale[ index + 1 ] );\n\t\t\t\t\t// and use half the bins in between for this band\n\t\t\t\t\tif ( nextBin - bin > 1 )\n\t\t\t\t\t\tprevBin += Math.round( ( nextBin - bin ) / 2 );\n\t\t\t\t}\n\n\t\t\t\tconst endIdx = prevBin - idx > 0 ? prevBin : 0;\n\n\t\t\t\tthis._analyzerBars.push( {\n\t\t\t\t\tposX: index * this._barWidth,\n\t\t\t\t\tdataIdx: idx,\n\t\t\t\t\tendIdx,\n//\t\t\t\t\tfreq, // nominal frequency for this band\n//\t\t\t\t\trange: [ this.binToFreq( idx ), this.binToFreq( endIdx || idx ) ], // actual range of frequencies\n\t\t\t\t\tfactor: 0,\n\t\t\t\t\tpeak: 0,\n\t\t\t\t\thold: 0,\n\t\t\t\t\taccel: 0\n\t\t\t\t} );\n\n\t\t\t} );\n\t\t}\n\n\t\tthis._calculateLedProperties();\n\n\t\t// Create the X-axis scale in the auxiliary canvases\n\n\t\tconst scaleHeight = this._canvas.height * .03 | 0, // circular scale height (radial mode)\n\t\t\t radius = this._circScale.width >> 1, // this is also used as the center X and Y coordinates of the circScale canvas\n\t\t\t radialY = radius - scaleHeight * .75, // vertical position of text labels in the circular scale\n\t\t\t tau = 2 * Math.PI,\n\t\t\t freqLabels = [ 16, 31, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000 ];\n\n\t\t// clear canvases\n\t\tthis._labels.width |= 0;\n\t\tthis._circScale.width |= 0;\n\n\t\tthis._labelsCtx.fillStyle = this._circScaleCtx.strokeStyle = '#000c';\n\t\tthis._labelsCtx.fillRect( 0, 0, this._labels.width, this._labels.height );\n\n\t\tthis._circScaleCtx.arc( radius, radius, radius - scaleHeight / 2, 0, tau );\n\t\tthis._circScaleCtx.lineWidth = scaleHeight;\n\t\tthis._circScaleCtx.stroke();\n\n\t\tthis._labelsCtx.fillStyle = this._circScaleCtx.fillStyle = '#fff';\n\t\tthis._labelsCtx.font = `${ this._labels.height >> 1 }px sans-serif`;\n\t\tthis._circScaleCtx.font = `${ scaleHeight >> 1 }px sans-serif`;\n\t\tthis._labelsCtx.textAlign = this._circScaleCtx.textAlign = 'center';\n\n\t\tfor ( const freq of freqLabels ) {\n\t\t\tconst label = ( freq >= 1000 ) ? `${ freq / 1000 }k` : freq,\n\t\t\t\t x = bandWidth * ( Math.log10( freq ) - minLog );\n\n\t\t\tthis._labelsCtx.fillText( label, x,\tthis._labels.height * .75 );\n\n\t\t\t// avoid overlapping wrap-around labels in the circular scale\n\t\t\tif ( x > 0 && x < this._canvas.width ) {\n\t\t\t\tconst angle = tau * ( x / this._canvas.width ),\n\t\t\t\t\t adjAng = angle - Math.PI / 2, // rotate angles so 0 is at the top\n\t\t\t\t\t posX = radialY * Math.cos( adjAng ),\n\t\t\t\t\t posY = radialY * Math.sin( adjAng );\n\n\t\t\t\tthis._circScaleCtx.save();\n\t\t\t\tthis._circScaleCtx.translate( radius + posX, radius + posY );\n\t\t\t\tthis._circScaleCtx.rotate( angle );\n\t\t\t\tthis._circScaleCtx.fillText( label, 0, 0 );\n\t\t\t\tthis._circScaleCtx.restore();\n\t\t\t}\n\t\t}\n\t}", "updateBars(data) {\n\t\t/* Pixel color */\n\t\tlet colorBar = this.updateBar(data, \"color\", d3.select(\".colorbar\"), this.totalBars);\n\t\tif (colorBar) colorBar.style(\"fill\", (d, i) => {return d3.rgb(d.color.red,d.color.blue,d.color.green);});\n\n\t\t/* Pixel render time */\n\t\tlet timeBar = this.updateBar(data, \"time\", d3.select(\".timebar\"), this.totalBars);\n\t\tvar timeColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_render_time, this.rawData.max_render_time])\n .range(['black','white']);\n\t\tif (timeBar) timeBar.style(\"fill\", (d) => {return timeColor(d.time);});\n\n\t\t/* Total secondary rays */\n\t\tlet secondaryRayBar = this.updateBar(data, \"branches\", d3.select(\".branchesbar\"), this.totalBars);\n\t\tvar srColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_secondary_rays, this.rawData.max_secondary_rays])\n .range(['black','white']);\n\t\tif (secondaryRayBar) secondaryRayBar.style(\"fill\", (d) => {return srColor(d.branches);});\n\n\t\t/* Total samples */\n\t\tlet samplesBar = this.updateBar(data, \"samples\", d3.select(\".samplesbar\"), this.totalBars);\n\t\tvar scColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_sample_count, this.rawData.max_sample_count])\n .range(['black','white']);\n\t\tif (samplesBar) samplesBar.style(\"fill\", (d) => {return scColor(d.samples);});\n\n\t\t/* Pixel depth */\n\t\tlet depthBar = this.updateBar(data, \"depth\", d3.select(\".depthbar\"), this.totalBars);\n\t\tvar dColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_depth, this.rawData.max_depth])\n .range(['black','white']);\n\t\tif (depthBar) depthBar.style(\"fill\", (d) => {return dColor(d.depth);});\n\n\t\t/* Pixel variance */\n\t\tlet varianceBar = this.updateBar(data, \"variances\", d3.select(\".variancebar\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_variance, this.rawData.max_variance])\n .range(['black','white']);\n\t\tif (varianceBar) varianceBar.style(\"fill\", (d) => {return vColor(d.variance);});\n\n\t\t/* Ray Box interections */\n\t\tlet boxBar = this.updateBar(data, \"boxIntersections\", d3.select(\".boxIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_box_intersections, this.rawData.max_box_intersections])\n .range(['black','white']);\n\t\tif (boxBar) boxBar.style(\"fill\", (d) => {return vColor(d.boxIntersections);});\n\n\t\t/* Ray Obj interections */\n\t\tlet objBar = this.updateBar(data, \"objIntersections\", d3.select(\".objIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_primitive_intersections, this.rawData.max_primitive_intersections])\n .range(['black','white']);\n\t\tif (objBar) objBar.style(\"fill\", (d) => {return vColor(d.objIntersections);});\n\n\t\t/* Selectable bars */\n\t\tlet selectableBar = this.updateSelectable(data, d3.select(\".selectableBar\"))\n\t}", "magicBar() {\n\n if (this.magic < 100) {\n //always increasing the magic as it restores with time but slower than how\n //much it takes to fire the spell\n this.magic += 0.5;\n }\n //making the healthbar follow the player but not at the edges\n //of the background image\n if (player.x > camXMin && state === \"Forest\") {\n // a satisfying distance so the healthbar is not off\n //when it follows the player\n this.magicBarX = player.x + this.magicBarOff;\n if (player.x > camXMax) {\n this.magicBarX = camXMax + this.magicBarOff;\n }\n if (state === \"Dungeon\") {\n //putting it back to the starting value\n this.magicBarX = width - 310;\n }\n }\n let magicSize;\n magicSize = map(this.magic, 0, this.maxMagic, 0, 300);\n\n push();\n //light blue color\n fill(178, 189, 244);\n //creating the light blue rectangle on bottom\n rect(this.magicBarX, this.barY, 300, 20);\n if (this.magic > 0) {\n //the dark blue color on top\n fill(66, 87, 191);\n //creating the rectangle that is mapped, the dark blue one, the magic\n rect(this.magicBarX, this.barY, magicSize, 20);\n }\n pop();\n }", "function update() {\n // populate the analyser buffer with frequency bytes\n analyser.getByteFrequencyData(buffer);\n // look for trigger signal\n for (var i = 0; i < analyser.frequencyBinCount; i++) {\n var percent = buffer[i] / 256;\n // TODO very basic / naive implementation where we only look\n // for one bar with amplitude > threshold\n // proper way will be to find the fundamental frequence of the square wave\n if (percent > config.threshold) {\n events.dispatch('signal');\n return;\n }\n }\n}", "function setBarLine(){\n\tmusicalElements += \"| \";\n}", "function drawUpdateBar(){\n\t\t\td3.select(\"#bar-cover #bar-chart\").selectAll(\"svg\").remove();\n\t\t\tdrawBar();\n\t\t}", "function handleSwitchUnits()\n{\n if(units == 0)\n units = 1;\n else\n units = 0;\n}", "function fixLowBarNumbers() {\n $(\".bar\").each(function() {\n if ($(this).height() <= 30) {\n $(this).children(\".value\").each(function() {\n $(this).css(\"top\", -30);\n });\n }\n });\n }", "function barposition(bl1) {\n // find the min. difference between any points\n // in any traces in bl1\n var pvals = [];\n bl1.forEach(function(i) {\n gd.calcdata[i].forEach(function(v) { pvals.push(v.p); });\n });\n var dv = Lib.distinctVals(pvals),\n pv2 = dv.vals,\n barDiff = dv.minDiff;\n\n // check if all the traces have only independent positions\n // if so, let them have full width even if mode is group\n var overlap = false,\n comparelist = [];\n\n if(fullLayout.barmode === 'group') {\n bl1.forEach(function(i) {\n if(overlap) return;\n gd.calcdata[i].forEach(function(v) {\n if(overlap) return;\n comparelist.forEach(function(cp) {\n if(Math.abs(v.p - cp) < barDiff) overlap = true;\n });\n });\n if(overlap) return;\n gd.calcdata[i].forEach(function(v) {\n comparelist.push(v.p);\n });\n });\n }\n\n // check forced minimum dtick\n Axes.minDtick(pa, barDiff, pv2[0], overlap);\n\n // position axis autorange - always tight fitting\n Axes.expand(pa, pv2, {vpad: barDiff / 2});\n\n // bar widths and position offsets\n barDiff *= 1 - fullLayout.bargap;\n if(overlap) barDiff /= bl.length;\n\n var barCenter;\n function setBarCenter(v) { v[pLetter] = v.p + barCenter; }\n\n for(var i = 0; i < bl1.length; i++) {\n var t = gd.calcdata[bl1[i]][0].t;\n t.barwidth = barDiff * (1 - fullLayout.bargroupgap);\n t.poffset = ((overlap ? (2 * i + 1 - bl1.length) * barDiff : 0) -\n t.barwidth) / 2;\n t.dbar = dv.minDiff;\n\n // store the bar center in each calcdata item\n barCenter = t.poffset + t.barwidth / 2;\n gd.calcdata[bl1[i]].forEach(setBarCenter);\n }\n }", "function bar(){\n push();\n fill(50);\n noStroke();\n\n // draw centerBar\n rect(\n width/2,\n height/2,\n centerBar.width,\n centerBar.height,\n centerBar.round,\n );\n\n // draw centerBar text\n fill(100);\n textSize(centerBar.height*0.4);\n textAlign(LEFT, CENTER);\n text(stationName, 100, height/2);\n\n // draw platform number badges and text\n var alternate = [-1, 1, -1, 1];\n textSize(40);\n textAlign(CENTER, CENTER);\n for (i = 0; i < qtyPlatforms; i++){\n //badges\n fill(75);\n stroke(15);\n strokeWeight(5);\n ellipse( space * (i+1) + offset, height/2- (centerBar.height/2*alternate[i]), 60);\n\n // text\n noStroke();\n fill(15);\n text((i+1).toString(), space * (i+1) + offset, height/2- (centerBar.height/2*alternate[i]));\n }\n\n pop();\n}", "function updateHealthButtons() {\r\n\r\n\t\tvar h = parseInt( $( \"#healthBar\" ).text() );\r\n\t\tvar foodLimit = parseInt( $( \"#foodLimit\" ).text() );\r\n\t\tvar giftLimit = parseInt( $( \"#giftLimit\" ).text() );\r\n\t\tif( foodLimit == 0 ) {\r\n\t\t\tdisableButton( $( \"#newEatButton\" ) );\r\n\r\n\t\t} else {\r\n\t\t\tif( selectedFood ) {\r\n\t\t\t\tvar eatQ = parseInt( selectedFood.attr( \"indexselect\" ) ) * 10;\r\n\t\t\t\tif( (eatQ + h) > 100 ) {\r\n\t\t\t\t\tdisableButton( $( \"#newEatButton\" ) );\r\n\t\t\t\t} else {\r\n\t\t\t\t\tenableButton( $( \"#newEatButton\" ) );\r\n\t\t\t\t}\r\n\r\n\t\t\t} else enableButton( $( \"#newEatButton\" ) );\r\n\t\t}\r\n\r\n\t\tif( giftLimit == 0 ) {\r\n\t\t\tdisableButton( $( \"#newGiftButton\" ) );\r\n\r\n\t\t} else {\r\n\t\t\tif( selectedGift ) {\r\n\t\t\t\tvar useQ = parseInt( selectedGift.attr( \"indexselect\" ) ) * 10;\r\n\t\t\t\tif( (useQ + h) > 100 ) {\r\n\t\t\t\t\tdisableButton( $( \"#newGiftButton\" ) );\r\n\t\t\t\t} else {\r\n\t\t\t\t\tenableButton( $( \"#newGiftButton\" ) );\r\n\t\t\t\t}\r\n\r\n\t\t\t} else enableButton( $( \"#newGiftButton\" ) );\r\n\t\t}\r\n\r\n\t\tupdateFightButtons();\r\n\t}", "manageCollitions () {\n var paramRobot = this.robot.getParameters();\n for (var i = 0; i < this.maxFly; ++i) {\n var paramFly = this.fly[i].getParameters();\n var distance = Math.sqrt(Math.pow((paramFly.x - paramRobot.pos.x),2) + Math.pow((paramFly.y - paramRobot.pos.y),2)\n + Math.pow((paramFly.z - paramRobot.pos.z),2));\n\n if (distance <= (paramRobot.radio + paramFly.radio)) {\n this.fly[i].setCollision();\n this.lastHealth = this.health;\n\n if (!paramFly.behaviour) {\n this.health -= 10;\n if (this.health < 0) this.health = 0;\n } else if (paramFly.behaviour) {\n var scorePlus = Math.floor(Math.random()*(5+1))\n this.health += 5 - scorePlus;\n this.score += scorePlus;\n this.setScore();\n if(this.health > 100) this.health = 100;\n }\n this.manageHUD();\n this.hud.changeSize(this.health);\n this.hudRobot.changeSize(this.health);\n }\n }\n }", "drawBarsRemoveOld(){\n }", "function extraFixedBarista() {\n var normalBarista = getNum(\"normalbarista\");\n var autoBarista = getNum(\"autogratbarista\");\n if (autoBarista > 0) {\n document.getElementById(\"autogratbarista\").innerHTML = (Number(autoBarista) + extraTip.barista).toFixed(2);\n } else if (normalBarista > 0) {\n document.getElementById(\"normalbarista\").innerHTML = (Number(normalBarista) + extraTip.barista).toFixed(2);\n }\n}", "function changeStatus() {\n var text = \"Time Range Bar: <b>\" + boolToOnOff(mainfocus)\n + \"</b>,&nbsp;&nbsp; Time Range Filter: <b>\" + boolToOnOff(timeBarFilter)\n + \"</b>,&nbsp;&nbsp; Normalised: <b>\" + boolToOnOff(isMainNormalised)\n + \"</b>,&nbsp;&nbsp; Night Mode: <b>\" + boolToOnOff(backgroundcolour)\n + \"</b>,&nbsp;&nbsp; High Quality: <b>\" + boolToOnOff((d3.select('#' + 'fancyvis').property('className').indexOf('btn-info') >= 0));\n if (mainfocus) text += \"</b>,&nbsp;&nbsp; Year Range: <b>\" + timeBarIndexes[0] + ':' + timeBarIndexes[1];\n d3.select(\"#\" + 'mainstatus').attr('text-anchor', 'middle').html(text);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the last child of this subtree.
get lastChild() { return this.childBefore(this.end + 1); }
[ "function lastElementChild(element) {\n var child = element.lastChild;\n while (child !== null && child.nodeType !== 1) {\n child = child.previousSibling;\n }\n return child;\n}", "function lastAncestor(node,pred){var ancestors=listAncestor(node);return lists.last(ancestors.filter(pred));}", "function last() {\n return _navigationStack[_navigationStack.length - 1];\n }", "getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }", "function getLastBox(bed) {\n\tif (isEmpty(bed))\n\t\treturn undefined;\n\telse {\n\t\treturn bed.boxes.slice(-1).pop();\n\t}\n}", "findMax() { \n if(this.isEmpty()) return Number.MIN_VALUE;\n return this.heap[0];\n }", "function lastSibling (node, parentNode) \r\n{\r\n\tvar lastChild = 0;\r\n\tfor (i=0; i< TreeNodes.length; i++) \r\n\t{\r\n\t\tvar nodeValues = TreeNodes[i].split(\"|\");\r\n\t\tif (nodeValues[1] == parentNode)\r\n\t\t\tlastChild = nodeValues[0];\r\n\t}\r\n\tif (lastChild == node) return true;\r\n\treturn false;\r\n}", "getChildInTree() {\n if (!this._children || this._children.length === 0)\n return null;\n for (var ch of this._children) {\n if (ch.isStartingPerson)\n return ch;\n if (ch.getChildInTree())\n return ch;\n }\n return null;\n }", "last(root, path) {\n var p = path.slice();\n var n = Node$1.get(root, p);\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break;\n } else {\n var i = n.children.length - 1;\n n = n.children[i];\n p.push(i);\n }\n }\n\n return [n, p];\n }", "function lastElement(array){\n if (array.length > 0){\n return array[array.length-1];\n }\n return null;\n}", "getLastColumn(){\n\t\tif(!this.isGroup){\n\t\t\treturn this;\n\t\t}else{\n\t\t\tif(this.columns.length){\n\t\t\t\treturn this.columns[this.columns.length -1].getLastColumn();\n\t\t\t}else{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "function getLastSibling(node) {\n let sibling = node;\n\n while (sibling && sibling.next) {\n sibling = sibling.next;\n }\n\n return sibling;\n}", "get back() {\n return this.get(this.length - 1);\n }", "function lastCollectionElem(obj){\n\t//get first element, if any\n\tvar elem = $(obj).last();\n\t//check if collection is empty (i.e. has no first element)\n\tif( elem.length == 0 ){\n\t\t//return null if it is empty\n\t\treturn null;\n\t}\n\t//return first element\n\treturn elem[0];\n}", "function lastItemOffset(node) {\n var item = node.lastChild;\n if (!item) {\n return 0;\n }\n var menuRect = node.getBoundingClientRect();\n var itemRect = item.getBoundingClientRect();\n return menuRect.bottom - itemRect.bottom;\n }", "child(root, index) {\n if (Text.isText(root)) {\n throw new Error(\"Cannot get the child of a text node: \".concat(JSON.stringify(root)));\n }\n\n var c = root.children[index];\n\n if (c == null) {\n throw new Error(\"Cannot get child at index `\".concat(index, \"` in node: \").concat(JSON.stringify(root)));\n }\n\n return c;\n }", "get lastItem() {\n return !this.buttons\n ? undefined\n : this.mainItems[this.mainItems.length - 1];\n }", "tail() {\n return null;\n }", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "get(root, path) {\n var node = root;\n\n for (var i = 0; i < path.length; i++) {\n var p = path[i];\n\n if (Text.isText(node) || !node.children[p]) {\n throw new Error(\"Cannot find a descendant at path [\".concat(path, \"] in node: \").concat(JSON.stringify(root)));\n }\n\n node = node.children[p];\n }\n\n return node;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate every layers in a corpuUid
setAll({ state, dispatch, commit }, { corpuUid }) { // Loop over every layers uids Object.keys(state.actives).forEach(uid => { // Loop over every layers in a corpuUid state.lists[corpuUid].forEach(l => { // Activate the layer dispatch('set', { id: l.id, corpuUid, uid }) }) }) }
[ "setup() {\n for (const layer in this.layerRegistry) {\n this.layers.set(`${layerRegistry[layer]}Layer`, this.game.add.group());\n this.game.world.bringToTop(this.layers.get(`${layerRegistry[layer]}Layer`));\n }\n }", "list({ dispatch, commit, rootState, rootGetters }, { corpuId, corpuUid }) {\n dispatch('sync/start', `layersList-${corpuUid}`, { root: true })\n return rootState.api\n .getLayers({ filter: { id_corpus: corpuId } })\n .then(r => {\n dispatch('sync/stop', `layersList-${corpuUid}`, { root: true })\n\n // Format server response\n const layers = r.data.map(l => ({\n name: l.name,\n id: l._id,\n description: l.description || {},\n permission: rootGetters['user/permission'](l.permissions),\n permissions: {\n users: rootGetters['users/permissions'](\n (l.permissions && l.permissions.users) || {}\n ),\n groups: rootGetters['groups/permissions'](\n (l.permissions && l.permissions.groups) || {}\n )\n },\n fragmentType: l.fragment_type || {},\n metadataType: l.data_type || {},\n annotations: l.annotations || []\n }))\n\n // Commit list to a corpuUid\n commit('list', { layers, corpuUid })\n\n // Activate every layers in the list\n // dispatch('setAll', { corpuUid })\n\n return layers\n })\n .catch(e => {\n dispatch('sync/stop', `layersList-${corpuUid}`, { root: true })\n dispatch('messages/error', e.message, { root: true })\n\n throw e\n })\n }", "static set AllLayers(value) {}", "function activateTextures()\n{\n\t\tfor(var i=0;i<textureImages.length;i+=2){\n\t\t\t\tif(i==0){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE0)\n\t\t\t\t}else if(i==2){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE1);\n\t\t\t\t}else if(i==4){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE2);\n\t\t\t\t}else if(i==6){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE3);\n\t\t\t\t\t\t// Above 6 is \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// If index is 0 to 4 it is ordinary 2d texture \n\t\t\t\t// if index is 6 or higher it is a cube map\n\t\t\t\tif(i>=0 && i<=4){\n\t\t\t\t\t\tgl.bindTexture(gl.TEXTURE_2D, Textures[i/2]);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n\t\t\t\t\t\tgl.uniform1i(gl.getUniformLocation(shaderProgram, textureImages[i+1]), i/2); \t// Texture ID\n\t\t\t\t}else if(i==6){\n\t\t\t\t\t\tgl.bindTexture(gl.TEXTURE_CUBE_MAP, Textures[i/2]);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\t\t\t\t\t\tgl.uniform1i(gl.getUniformLocation(shaderProgram, textureImages[i+1]), i/2); \t// Texture Cube\n\t\t\t\t}\n\t\t\t\t\n\t\t}\n}", "addLayerSelection() {\n let mapButtonsContainer = this.ref.createMapButtonsContainer(this.map.height);\n let layerButtonContainer = this.ref.createDiv(\"layerButtonContainer\");\n let layerButtonList = this.ref.createLayerButtonList(\"layerButtonList\");\n\n for (let i = 0; i < this.ref.maxZ; i++) {\n let layerButton = this.ref.createLayerButton(\"layerButton-\" + String(i), \"layer-button\");\n layerButtonList.append(layerButton);\n }\n\n layerButtonContainer.append(layerButtonList);\n document.querySelector(\"body\").append(mapButtonsContainer);\n let layerSelector = this.ref.createDiv(\"mapLayerSelector\");\n\n for (let i = nrOfLayers - 1; i >= 0; i--) {\n let layerA = this.ref.createLayerA(\"#\", i + 1);\n layerA.addEventListener('click', (e) => {\n let selectedNr = Number(e.target.innerText) - 1;\n if (this.displayLayers.includes(selectedNr)) {\n let elIndex = this.displayLayers.indexOf(selectedNr);\n e.target.classList.remove('active');\n\n if (elIndex > -1)\n this.displayLayers.splice(elIndex, 1);\n } else {\n this.displayLayers.push(selectedNr);\n e.target.classList.add('active');\n\n }\n this.repaintMapCube(cubes, \"\", this.enhancedCubes, this.scaffoldingCubesCords, false)\n\n });\n layerSelector.append(layerA);\n }\n mapButtonsContainer.append(layerSelector);\n }", "activateLayerParents(layer, parentReactivationNeeded) {\n let currentLayer = layer;\n while (this.mapsInterface.getLayerArray()[currentLayer.pid]) {\n currentLayer = this.mapsInterface.getLayerArray()[currentLayer.pid];\n currentLayer.display = true;\n if (currentLayer.projectId === this.editor.projectController.currentProject.id) {\n if (parentReactivationNeeded) {\n this.mapsInterface.hideLayer(currentLayer.id);\n }\n this.mapsInterface.showLayer(currentLayer.id);\n }\n }\n }", "function hpuaActive (surfHpua, cpyHpua) {\n return surfHpua + cpyHpua\n}", "_drawLayersInViewport(gl, {\n layers,\n moduleParameters: globalModuleParameters,\n pass,\n target,\n viewport,\n view\n }, drawLayerParams) {\n const glViewport = getGLViewport(gl, {\n moduleParameters: globalModuleParameters,\n target,\n viewport\n });\n\n if (view && view.props.clear) {\n const clearOpts = view.props.clear === true ? {\n color: true,\n depth: true\n } : view.props.clear;\n Object(_luma_gl_core__WEBPACK_IMPORTED_MODULE_2__[\"withParameters\"])(gl, {\n scissorTest: true,\n scissor: glViewport\n }, () => Object(_luma_gl_core__WEBPACK_IMPORTED_MODULE_2__[\"clear\"])(gl, clearOpts));\n } // render layers in normal colors\n\n\n const renderStatus = {\n totalCount: layers.length,\n visibleCount: 0,\n compositeCount: 0,\n pickableCount: 0\n };\n Object(_luma_gl_core__WEBPACK_IMPORTED_MODULE_2__[\"setParameters\"])(gl, {\n viewport: glViewport\n }); // render layers in normal colors\n\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n const {\n shouldDrawLayer,\n layerRenderIndex,\n moduleParameters,\n layerParameters\n } = drawLayerParams[layerIndex]; // Calculate stats\n\n if (shouldDrawLayer && layer.props.pickable) {\n renderStatus.pickableCount++;\n }\n\n if (layer.isComposite) {\n renderStatus.compositeCount++;\n } else if (shouldDrawLayer) {\n // Draw the layer\n renderStatus.visibleCount++; // overwrite layer.context.viewport with the sub viewport\n\n moduleParameters.viewport = viewport;\n\n try {\n layer._drawLayer({\n moduleParameters,\n uniforms: {\n layerIndex: layerRenderIndex\n },\n parameters: layerParameters\n });\n } catch (err) {\n layer.raiseError(err, `drawing ${layer} to ${pass}`);\n }\n }\n }\n\n return renderStatus;\n }", "function prerender() {\n if (tileEngine.layers) {\n tileEngine.layers.map(function (layer) {\n layer._d = false;\n layerMap[layer.name] = layer;\n\n if (layer.visible !== false) {\n tileEngine._r(layer, offscreenContext);\n }\n });\n }\n }", "function updateLayerOrder() {\n angular.forEach($scope.layers, function(my_layer) {\n my_layer.layer.set('position', getMyLayerPosition(my_layer.layer));\n })\n }", "function updateControlCubes()\n{\n\tfor (var c in objController) {\n\t\tif (objController[c]) objController[c].update();\n\t}\n}", "setAlphas() {\n this.r3a1_exitDoor.alpha = 1.0;\n this.character.alpha = 1.0;\n this.r3a1_char_north.alpha = 0.0;\n this.r3a1_char_south.alpha = 0.0;\n this.r3a1_char_west.alpha = 0.0;\n this.r3a1_char_east.alpha = 0.0;\n this.r3a1_map.alpha = 0.0;\n this.r3a1_notebook.alpha = 0.0;\n this.r3a1_activityLocked.alpha = 0.0;\n this.r3a1_E_KeyImg.alpha = 0.0;\n this.r3a1_help_menu.alpha = 0.0;\n this.r3a1_redX.alpha = 0.0;\n this.r3a1_greenCheck.alpha = 0.0;\n //this.r3a1_hole.alpha = 0.0;\n this.hideActivities();\n this.profile.alpha = 0.0;\n }", "update(state, { layer, corpuUid }) {\n const index = state.lists[corpuUid].findIndex(l => l.id === layer.id)\n Vue.set(state.lists[corpuUid], index, layer)\n }", "setupLayers() {\n this.d3.select(this.holderSelector).selectAll('*').remove();\n\n this.createSVGLayer();\n this.createPointsLayer();\n this.createTargetsLayer();\n }", "function addToActiveLayers(layerid) {\r\n var theIndex = getActiveLayerIndex(layerid);\r\n if (theIndex === -1) {\r\n WMVisLayers.push(layerid);\r\n }\r\n setSharing();\r\n}", "function touchUpLayerSelection() {\n try {\n // Select all Layers\n var idselectAllLayers = stringIDToTypeID(\"selectAllLayers\");\n var desc252 = new ActionDescriptor();\n var idnull = charIDToTypeID(\"null\");\n var ref174 = new ActionReference();\n var idLyr = charIDToTypeID(\"Lyr \");\n var idOrdn = charIDToTypeID(\"Ordn\");\n var idTrgt = charIDToTypeID(\"Trgt\");\n ref174.putEnumerated(idLyr, idOrdn, idTrgt);\n desc252.putReference(idnull, ref174);\n executeAction(idselectAllLayers, desc252, DialogModes.NO);\n // Select the previous layer\n var idslct = charIDToTypeID(\"slct\");\n var desc209 = new ActionDescriptor();\n var idnull = charIDToTypeID(\"null\");\n var ref140 = new ActionReference();\n var idLyr = charIDToTypeID(\"Lyr \");\n var idOrdn = charIDToTypeID(\"Ordn\");\n var idBack = charIDToTypeID(\"Back\");\n ref140.putEnumerated(idLyr, idOrdn, idBack);\n desc209.putReference(idnull, ref140);\n var idMkVs = charIDToTypeID(\"MkVs\");\n desc209.putBoolean(idMkVs, false);\n executeAction(idslct, desc209, DialogModes.NO);\n } catch (e) {\n // do nothing\n }\n}", "activate()\r\n\t{\r\n\t\t// TODO\r\n\t\tsuper.activate();\r\n\t\tthis.gl.enableVertexAttribArray(this.colorAttribLocation);\r\n\t\tthis.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.colorBufferObject);\r\n\t\tthis.gl.vertexAttribPointer\r\n\t\t(\r\n\t\t\tthis.colorAttribLocation,\r\n\t\t\t3,\r\n\t\t\tthis.gl.FLOAT,\r\n\t\t\tthis.gl.FALSE,\r\n\t\t\t3 * Float32Array.BYTES_PER_ELEMENT,\r\n\t\t\t0\r\n\t\t);\r\n\r\n\t\tthis.gl.enableVertexAttribArray(this.normalAttribLocation);\r\n\t\tthis.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.normalBufferObject);\r\n\t\tthis.gl.vertexAttribPointer(\r\n\t\t\tthis.normalAttribLocation,\r\n\t\t\t3,\r\n\t\t\tthis.gl.FLOAT,\r\n\t\t\tthis.gl.FALSE,\r\n\t\t\t3 * Float32Array.BYTES_PER_ELEMENT,\r\n\t\t\t0\r\n\t\t);\r\n\t}", "changeColorRed() {\n this.planet.loadTexture('planetred');\n this.mini.loadTexture('planetred');\n }", "function DisableTranspOptionalLayers(index, id_minus, id_plus, checkboxId)\n{\n\n\tvar checkid = document.getElementById(checkboxId);\n\n\n\tif (checkid.checked == true)//check if the layer is selected\n\t{\n\t\tvar optionOpacity = optionalArray[index];//localte which global opacity layer it is\n\n\t\t//Disables the buttons.\n\t\tif (optionOpacity < maxOpacity) {\n\t\t\tdocument.getElementById(id_minus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_minus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_minus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity > minOpacity) {\n\t\t\tdocument.getElementById(id_plus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_plus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_plus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\t\t}\n\t}\n\telse\n\t{\n\t\t//Disables the buttons.\n\t\tdocument.getElementById(id_minus).disabled = true;\n\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\n\t\tdocument.getElementById(id_plus).disabled = true;\n\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the user presses the button to choose a different package version. Presents a dialog of available package versions to choose from.
_startChoose(e) { let target = e.target; if (target.nodeName !== 'BUTTON') { target = target.parentElement; } this._chosenServer = target.dataset.server; let choices = this._state.packages[target.dataset.app]; let chosen = choices.findIndex(choice => choice.Name === target.dataset.name); this._push_selection.choices = choices; this._push_selection.chosen = chosen; this._push_selection.show(); }
[ "findVersions() {\n this.state.versionData.forEach(yearData => {\n if(yearData.year === this.state.selectedYear) {\n yearData.terms.forEach(termData => {\n if(termData.term === this.state.selectedTerm.toLowerCase()) {\n this.setState({ versionOptions: termData.versions }, \n // below sets the default selected to the first entry so if Load Version is pressed \n // without a version being selected by the user the latest version is loaded\n () => {if(termData.versions.length>0) this.setState({selectedVersion: termData.versions[0]})}\n );\n }\n });\n }\n });\n }", "function showPicker() {\n var html = HtmlService.createHtmlOutputFromFile('Picker.html')\n .setWidth(600)\n .setHeight(425)\n .setSandboxMode(HtmlService.SandboxMode.IFRAME);\n SpreadsheetApp.getUi().showModalDialog(html, 'Select a HotDocs Component File');\n}", "onDepChanged() {\n\t\tif (atom.packages.isPackageActive(this.dependentPkgs)) {\n\t\t\tthis.el.classList.remove('unsupportted')\n\t\t\tthis.el.onclick = '';\n\t\t} else {\n\t\t\tthis.el.classList.add('unsupportted')\n\t\t\tthis.el.onclick = async ()=>{\n\t\t\t\ttry { await atom.packages.installPackage(this.dependentPkgs, {\n\t\t\t\t\textraButtons: [\n\t\t\t\t\t\t{\ttext:'remove the Font Size Group',\n\t\t\t\t\t\t\tonDidClick:()=>{atom.config.set('bg-tree-view-toolbar.buttons.fontGroup',false);}}\n\t\t\t\t\t]}\n\t\t\t\t)} catch(e) {\n\t\t\t\t\tconsole.log(e)\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}", "function onPrompt(results) {\n\t\talert(\"You selected button number \" + results.buttonIndex + \" and entered \" + results.input1);\n\t}", "handleVersionChange(event) {\n this.setState({ selectedVersion: event.currentTarget.value });\n }", "function ShowDialog() {\n try {\n var options =\n {\n autoSize: true,\n allowMaximize: true,\n title: 'Version History',\n showClose: true,\n url: _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/Versions.aspx?list=' + _spPageContextInfo.listId + '&ID=' + GetUrlKeyValue('ID') + '&Source=' + _spPageContextInfo.webServerRelativeUrl + '/Lists/' + _spPageContextInfo.listTitle + '/AllItems.aspx',\n };\n SP.UI.ModalDialog.showModalDialog(options);\n }\n catch (e) {\n console.log(e);\n }\n}", "function supervisorView() {\n console.log('\\r\\n');\n inquirer\n .prompt(\n {\n name: \"supervisorOptions\",\n type: \"list\",\n message: \"Please select an option from the following list: \\r\\n\",\n choices: [\n \"View Product Sales by Department\",\n \"Create New Department\"\n ]\n\n })\n .then(function (answer) {\n switch (answer.supervisorOptions) {\n case \"View Product Sales by Department\":\n viewProductsSalesByDept();\n break;\n\n case \"Create New Department\":\n createNewDept();\n break;\n }\n })\n}", "toggleVersions() {\n let newState = !(this.state.VersionSelectToggle);\n this.handleGetSchedulerRunVersions();\n this.setState( {VersionSelectToggle: newState});\n }", "function openVendorSelection()\n{\n\tif (document.forms[1].rdoNew.checked == true)\n\t{\n\t\t$('#vendorSelection').empty();\n\t}\n\telse\n\t{\n\t\t$('#vendorSelection').load('scriptFiles/selectVendorNames.php');\n\t}\n}", "function fingerChoice() {\n choiceDialog(0, 0, ghostDialog, 14000);\n}", "function loadVersions() {\n showMessage(\"Loading available API versions ...\");\n console.log(\"loadVersions() started\");\n osapi.jive.connects.get({\n alias : ALIAS,\n href : '/services/data'\n }).execute(function (response) {\n console.log(\"loadVersions() response = \" + JSON.stringify(response));\n if (response.error) {\n if (response.error.code == 401) {\n console.log(\"Received a 401 response, triggering reconfiguration\");\n osapi.jive.connects.reconfigure(ALIAS, response, function(feedback) {\n console.log(\"Received reconfigure feedback \" + JSON.stringify(feedback));\n loadVersions();\n })\n }\n else {\n alert(\"Error \" + response.error.code + \" loading data: \" + response.error.message);\n }\n }\n else {\n versions = response.content;\n var html = \"\";\n $.each(versions, function(index, v) {\n html += '<li class=\"version-item\">'\n + '<a class=\"version-link\" href=\"#\" data-index=\"' + index + '\">' + v.label + '</a>'\n + ' (Version ' + v.version + ')</li>';\n });\n $(\"#versions-list\").html(\"\").html(html);\n $(\".version-link\").click(function() {\n var index = $(this).attr(\"data-index\");\n version = versions[index];\n $(\".version-title\").html(\"\").html(version.label + ' (Version ' + version.version + ')');\n loadResources();\n });\n showOnly(\"versions-div\");\n }\n });\n}", "function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}", "_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }", "function insertProjectVersionInDOM() {\n var oldvalue = \"<b><u>Version :</u></b> \";\n document.getElementById(\"projectVersion\").innerHTML = oldvalue + getSelectedVersionsName();\n}", "function click_btn_revision(){\n\t$(\"#btn_revision\").click(function(){\n\t\tif( $('#div_revision').is(\":visible\") ){\n\t\t\t//si esta visible\n\t\t}else{\n\t\t\t//si no esta visible\n\t\t\t$('#texto_seleccion').text('SELECCIONE UNA INSPECCIÓN');\n\t\t\t$('#div_btn_informe_inicial').hide('fast');\n\t\t\t$('#div_btn_eliminadas').hide('fast');\n\t\t\t$('#div_btn_revision').hide('fast');\n\t\t\t$('#div_revision').show('fast'); //muetras el div\n\t\t\t$('#div_btn_regresar').show('fast');\n\t\t}\n \t});\n}", "function getWidgetVersions(obj, objectName) {\n\tvar id = $(obj).val();\n\tfillSelectbox($(\"select[name='\"+ objectName +\"']\"), map[id], \"No Versions available\");\n}", "function showPicker() {\n var html = HtmlService.createHtmlOutputFromFile('Picker.html')\n .setWidth(700)\n .setHeight(500)\n .setSandboxMode(HtmlService.SandboxMode.IFRAME);\n SpreadsheetApp.getUi().showModalDialog(html, 'Select an Elephant Grass spreadsheet to import');\n}", "function btnChoice(e) {\n\tplayer.choice = e.target.id\n\tdisplayResults()\n}", "function showLicense(uploadIndex)\n{\n var selected = $('licenseselector'+uploadIndex).value;\n \n // Make sure we have the current license\n if (!config_licenses || !config_licenses[selected]) return;\n \n // Open the popup\n doPopup(config_licenses[selected][1], 'license');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`setBits` is an array of strings, containing the names for each bit that sould be set to 1. `bitIndex` is same as in `readBitField()`. Returns a Buffer, ready to be written out with `BerWriterwriteString()`.
function writeBitField(setBits, bitIndex) { var bitLen = bitIndex.length; var blen = Math.ceil(bitLen / 8); var unused = blen * 8 - bitLen; var bits = Buffer.alloc(1 + blen); // zero-filled bits[0] = unused; for (var i = 0; i < bitLen; ++i) { var byteN = 1 + Math.floor(i / 8); var bit = 7 - (i % 8); var mask = 1 << bit; var name = bitIndex[i]; if (name === undefined) continue; var bitVal = (setBits.indexOf(name) !== -1); if (bitVal) { bits[byteN] |= mask; } } return (bits); }
[ "function setBit(number,i) {\n\treturn number | (1 << i);\n}", "get bitString() {\n return this.extnValueObj.subs[0].toBitString();\n }", "function BitSetFunctor(length) {\r\n var ADDRESS_BITS_PER_WORD = 5;\r\n var BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;\r\n var BIT_INDEX_MASK = BITS_PER_WORD - 1;\r\n var SIZE = ((length + (BITS_PER_WORD - 1)) >> ADDRESS_BITS_PER_WORD) << ADDRESS_BITS_PER_WORD;\r\n\r\n function BitSet() {\r\n /* How many bits are set. */\r\n this.count = 0;\r\n /* Do we need to recompute the count? */\r\n this.dirty = 0;\r\n /* Size of the bit array. */\r\n this.size = SIZE;\r\n /* The word array. */\r\n this.bits = new Uint32Array(SIZE >> ADDRESS_BITS_PER_WORD);\r\n }\r\n\r\n function BitSetS() {\r\n this.count = 0;\r\n this.dirty = 0;\r\n this.size = SIZE;\r\n this.bits = 0;\r\n }\r\n\r\n var singleword = (SIZE >> ADDRESS_BITS_PER_WORD) === 1;\r\n var Ctor = singleword ? BitSetS : BitSet;\r\n\r\n Ctor.ADDRESS_BITS_PER_WORD = ADDRESS_BITS_PER_WORD;\r\n Ctor.BITS_PER_WORD = BITS_PER_WORD;\r\n Ctor.BIT_INDEX_MASK = BIT_INDEX_MASK;\r\n Ctor.singleword = singleword;\r\n\r\n BitSet.prototype = {\r\n recount: function recount() {\r\n if (!this.dirty) {\r\n return;\r\n }\r\n\r\n var bits = this.bits;\r\n var c = 0;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var v = bits[i];\r\n v = v - ((v >> 1) & 0x55555555);\r\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333);\r\n c += ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;\r\n }\r\n\r\n this.count = c;\r\n this.dirty = 0;\r\n },\r\n\r\n set: function set(i) {\r\n var n = i >> ADDRESS_BITS_PER_WORD;\r\n var old = this.bits[n];\r\n var b = old | (1 << (i & BIT_INDEX_MASK));\r\n this.bits[n] = b;\r\n this.dirty |= old ^ b;\r\n },\r\n\r\n setAll: function setAll() {\r\n var bits = this.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n bits[i] = 0xFFFFFFFF;\r\n }\r\n this.count = this.size;\r\n this.dirty = 0;\r\n },\r\n\r\n assign: function assign(set) {\r\n this.count = set.count;\r\n this.dirty = set.dirty;\r\n this.size = set.size;\r\n for (var i = 0, j = this.bits.length; i < j; i++) {\r\n this.bits[i] = set.bits[i];\r\n }\r\n },\r\n\r\n clear: function clear(i) {\r\n var n = i >> ADDRESS_BITS_PER_WORD;\r\n var old = this.bits[n];\r\n var b = old & ~(1 << (i & BIT_INDEX_MASK));\r\n this.bits[n] = b;\r\n this.dirty |= old ^ b;\r\n },\r\n\r\n get: function get(i) {\r\n var word = this.bits[i >> ADDRESS_BITS_PER_WORD];\r\n return ((word & 1 << (i & BIT_INDEX_MASK))) !== 0;\r\n },\r\n\r\n clearAll: function clearAll() {\r\n var bits = this.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n bits[i] = 0;\r\n }\r\n this.count = 0;\r\n this.dirty = 0;\r\n },\r\n\r\n _union: function _union(other) {\r\n var dirty = this.dirty;\r\n var bits = this.bits;\r\n var otherBits = other.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var old = bits[i];\r\n var b = old | otherBits[i];\r\n bits[i] = b;\r\n dirty |= old ^ b;\r\n }\r\n this.dirty = dirty;\r\n },\r\n\r\n intersect: function intersect(other) {\r\n var dirty = this.dirty;\r\n var bits = this.bits;\r\n var otherBits = other.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var old = bits[i];\r\n var b = old & otherBits[i];\r\n bits[i] = b;\r\n dirty |= old ^ b;\r\n }\r\n this.dirty = dirty;\r\n },\r\n\r\n subtract: function subtract(other) {\r\n var dirty = this.dirty;\r\n var bits = this.bits;\r\n var otherBits = other.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var old = bits[i];\r\n var b = old & ~otherBits[i];\r\n bits[i] = b;\r\n dirty |= old ^ b;\r\n }\r\n this.dirty = dirty;\r\n },\r\n\r\n negate: function negate() {\r\n var dirty = this.dirty;\r\n var bits = this.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var old = bits[i];\r\n var b = ~old;\r\n bits[i] = b;\r\n dirty |= old ^ b;\r\n }\r\n this.dirty = dirty;\r\n },\r\n\r\n forEach: function forEach(fn) {\r\n release || assert(fn);\r\n var bits = this.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var word = bits[i];\r\n if (word) {\r\n for (var k = 0; k < BITS_PER_WORD; k++) {\r\n if (word & (1 << k)) {\r\n fn(i * BITS_PER_WORD + k);\r\n }\r\n }\r\n }\r\n }\r\n },\r\n\r\n toArray: function toArray() {\r\n var set = [];\r\n var bits = this.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n var word = bits[i];\r\n if (word) {\r\n for (var k = 0; k < BITS_PER_WORD; k++) {\r\n if (word & (1 << k)) {\r\n set.push(i * BITS_PER_WORD + k);\r\n }\r\n }\r\n }\r\n }\r\n return set;\r\n },\r\n\r\n equals: function equals(other) {\r\n if (this.size !== other.size) {\r\n return false;\r\n }\r\n var bits = this.bits;\r\n var otherBits = other.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n if (bits[i] !== otherBits[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n },\r\n\r\n contains: function contains(other) {\r\n if (this.size !== other.size) {\r\n return false;\r\n }\r\n var bits = this.bits;\r\n var otherBits = other.bits;\r\n for (var i = 0, j = bits.length; i < j; i++) {\r\n if ((bits[i] | otherBits[i]) !== bits[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n },\r\n\r\n toBitString: function toBitString(on, off) {\r\n on = on || \"1\";\r\n off = off || \"0\";\r\n var str = \"\";\r\n for (var i = 0; i < length; i++) {\r\n str += this.get(i) ? on : off;\r\n }\r\n return str;\r\n },\r\n\r\n length: length,\r\n\r\n toString: function toString(names) {\r\n var set = [];\r\n for (var i = 0; i < length; i++) {\r\n if (this.get(i)) {\r\n set.push(names ? names[i] : i);\r\n }\r\n }\r\n return set.join(\", \");\r\n },\r\n\r\n isEmpty: function isEmpty() {\r\n this.recount();\r\n return this.count === 0;\r\n },\r\n\r\n clone: function clone() {\r\n var set = new BitSet();\r\n set._union(this);\r\n return set;\r\n }\r\n };\r\n\r\n BitSetS.prototype = {\r\n recount: function recount() {\r\n if (!this.dirty) {\r\n return;\r\n }\r\n\r\n var c = 0;\r\n var v = this.bits;\r\n v = v - ((v >> 1) & 0x55555555);\r\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333);\r\n c += ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;\r\n\r\n this.count = c;\r\n this.dirty = 0;\r\n },\r\n\r\n set: function set(i) {\r\n var old = this.bits;\r\n var b = old | (1 << (i & BIT_INDEX_MASK));\r\n this.bits = b;\r\n this.dirty |= old ^ b;\r\n },\r\n\r\n setAll: function setAll() {\r\n this.bits = 0xFFFFFFFF;\r\n this.count = this.size;\r\n this.dirty = 0;\r\n },\r\n\r\n assign: function assign(set) {\r\n this.count = set.count;\r\n this.dirty = set.dirty;\r\n this.size = set.size;\r\n this.bits = set.bits;\r\n },\r\n\r\n clear: function clear(i) {\r\n var old = this.bits;\r\n var b = old & ~(1 << (i & BIT_INDEX_MASK));\r\n this.bits = b;\r\n this.dirty |= old ^ b;\r\n },\r\n\r\n get: function get(i) {\r\n return ((this.bits & 1 << (i & BIT_INDEX_MASK))) !== 0;\r\n },\r\n\r\n clearAll: function clearAll() {\r\n this.bits = 0;\r\n this.count = 0;\r\n this.dirty = 0;\r\n },\r\n\r\n _union: function _union(other) {\r\n var old = this.bits;\r\n var b = old | other.bits;\r\n this.bits = b;\r\n this.dirty = old ^ b;\r\n },\r\n\r\n intersect: function intersect(other) {\r\n var old = this.bits;\r\n var b = old & other.bits;\r\n this.bits = b;\r\n this.dirty = old ^ b;\r\n },\r\n\r\n subtract: function subtract(other) {\r\n var old = this.bits;\r\n var b = old & ~other.bits;\r\n this.bits = b;\r\n this.dirty = old ^ b;\r\n },\r\n\r\n negate: function negate() {\r\n var old = this.bits;\r\n var b = ~old;\r\n this.bits = b;\r\n this.dirty = old ^ b;\r\n },\r\n\r\n forEach: function forEach(fn) {\r\n release || assert(fn);\r\n var word = this.bits;\r\n if (word) {\r\n for (var k = 0; k < BITS_PER_WORD; k++) {\r\n if (word & (1 << k)) {\r\n fn(k);\r\n }\r\n }\r\n }\r\n },\r\n\r\n toArray: function toArray() {\r\n var set = [];\r\n var word = this.bits;\r\n if (word) {\r\n for (var k = 0; k < BITS_PER_WORD; k++) {\r\n if (word & (1 << k)) {\r\n set.push(k);\r\n }\r\n }\r\n }\r\n return set;\r\n },\r\n\r\n equals: function equals(other) {\r\n return this.bits === other.bits;\r\n },\r\n\r\n contains: function contains(other) {\r\n var bits = this.bits;\r\n return (bits | other.bits) === bits;\r\n },\r\n\r\n isEmpty: function isEmpty() {\r\n this.recount();\r\n return this.count === 0;\r\n },\r\n\r\n clone: function clone() {\r\n var set = new BitSetS();\r\n set._union(this);\r\n return set;\r\n },\r\n\r\n toBitString: BitSet.prototype.toBitString,\r\n toString: BitSet.prototype.toString,\r\n\r\n length: length,\r\n };\r\n\r\n return Ctor;\r\n}", "function setThirdBit(num) {\n\treturn (num | 4).toString(2)\n}", "setMem(bitmask) {\n MMU.wb(regHL[0], MMU.rb(regHL[0]) | bitmask);\n return 16;\n }", "function makeProtocolTypeBitList() {\n g_ProtocolTypeBit = {};\n\n // Set all protocol numbers as PROTOCOL_TYPE_BIT_UNSUPPORTED to the protocol type bit list.\n for (let i=0; i<256; ++i) {\n g_ProtocolTypeBit[i.toString()] = PROTOCOL_TYPE_BIT_UNSUPPORTED;\n }\n\n // Overwrite by supported protocol.\n for (const key in t_SupportedProtocolTypeBit) {\n if (t_SupportedProtocolTypeBit.hasOwnProperty(key)) {\n g_ProtocolTypeBit[key] = t_SupportedProtocolTypeBit[key];\n }\n }\n\n // Append all protocol object-groups' type bits to the protocol type bit list.\n for (const key in g_ObjectGroup_Protocol) {\n if (g_ObjectGroup_Protocol.hasOwnProperty(key)) {\n const array = g_ObjectGroup_Protocol[key];\n let intProtocolTypeBit = PROTOCOL_TYPE_BIT_NONE;\n for (let i=0; i<array.length; ++i) {\n intProtocolTypeBit |= getProtocolTypeBit(array[i]);\n }\n g_ProtocolTypeBit[key] = intProtocolTypeBit;\n }\n }\n\n // Append all service objects as PROTOCOL_TYPE_BIT_SERVICE to the protocol type bit list.\n for (const key in g_Object_Service) {\n if (g_Object_Service.hasOwnProperty(key)) {\n g_ProtocolTypeBit[key] = PROTOCOL_TYPE_BIT_SERVICE;\n }\n }\n\n // Append all service object-groups as PROTOCOL_TYPE_BIT_SERVICE to the protocol type bit list.\n for (const key in g_ObjectGroup_Service) {\n if (g_ObjectGroup_Service.hasOwnProperty(key)) {\n g_ProtocolTypeBit[key] = PROTOCOL_TYPE_BIT_SERVICE;\n }\n }\n}", "function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}", "changeLedsColor(binaryNumber) {\n\n let ledList = this.state.leds;\n let binaryString = binaryNumber.toString();\n\n let binaryDiff = 8 - binaryString.length;\n\n for (let i=0;i<binaryDiff;i++) {\n ledList[i].color = 'grey';\n }\n\n for (let i=0;i<binaryString.length;i++) {\n let ledIndex = i + binaryDiff;\n\n if (binaryString.charAt(i) === '1') {\n ledList[ledIndex].color = 'green';\n } else {\n ledList[ledIndex].color = 'grey';\n }\n }\n\n this.setState({leds: ledList});\n }", "writeValue(buffer, value) {\n assert.isBuffer(buffer);\n assert.instanceOf(value, [ArrayBuffer, Uint8Array]);\n buffer\n .addAll(flexInt.makeValueBuffer(value.byteLength))\n .addAll(value);\n }", "setByte(depth) {\n this.write(\"<\".repeat(depth) + \"[-]\"); // go the value, and zero it\n this.write(\">\".repeat(depth)); // go back to the top of the stack\n this.write(\"[\"); // repeat until the value at tope is 0\n this.write(`-${\"<\".repeat(depth)}+${\">\".repeat(depth)}`); // decrement the stack-top and increment the target byte\n this.write(\"]\"); // end loop.\n this.write(\"<\"); // move pointer one step back.\n }", "function determineBitfieldType(count) {\n\tif (count <= 8) {\n\t\treturn \"uint8\";\n\t} else if (count > 8 && count <= 16) {\n\t\treturn \"uint16\";\n\t} else if (count > 16 && count <= 32) {\n\t\treturn \"uint32\";\n\t} else if (count > 32 && count <= 64) {\n\t\treturn \"uint64\";\n\t} else {\n\t\tconsole.error(\"The number of bools is too damn high!\");\n\t}\n}", "static bytes11(v) { return b(v, 11); }", "function FilterGroupBitVector(filterData){\n this.filters = [];\n this.name = filterData.name;\n this.type = filterData.type;\n this.columnInData = parseInt(filterData.columnInData);\n for(var i in filterData.filters){\n var filter = new Filter(this, filterData.filters[i].name, 'Bit', 'false');\n this.filters[i] = filter;\n } // for i\n\n this.filterObjects = filterObjects;\n this.updateOldGroupFilterValues = updateOldGroupFilterValues;\n\n function updateOldGroupFilterValues($scope){\n for(var i in this.filters){\n var filter = this.filters[i];\n oldFilterValues[filter.id] = filter.value;\n }\n }\n\n function filterObjects($scope){\n var matchVector = '';\n for(var i in this.filters){\n var filter = this.filters[i];\n if(filter.value == 'true'){\n matchVector += '1';\n numberSelectedOptions++;\n }else{\n matchVector += '0';\n }\n oldFilterValues[filter.id] = filter.value;\n }\n if(matchVector == 0){\n return;\n }\n var a = parseInt(matchVector,2);\n var selectionsTmp = [];\n for(var i in $scope.selections){\n var selection = $scope.selections[i];\n var bitVector = selection[this.columnInData];\n\n var b = parseInt(bitVector,2);\n var res = a & b;\n //Variant OR\n if(res != 0){\n var resAsString = res.toString(2);\n //Calculate amount of 1 in string\n var numberMatches = 0;\n for(var j = 0; j < resAsString.length;j++){\n var c = resAsString.charAt(j);\n if(c == '1'){\n numberMatches++;\n }\n } //for j\n selection[NUMBER_MATCHES] += numberMatches;\n selectionsTmp[selectionsTmp.length] = selection;\n } //if res\n } //for i\n $scope.selections = selectionsTmp;\n }//this.filterObjects\n} //FilterGroupBitVector", "function inWord(bit) {\n return Math.floor((bit | 0) / 32);\n }", "static bytes17(v) { return b(v, 17); }", "static bytes9(v) { return b(v, 9); }", "function SoundBites(audioParams, templates) {\n\n\t\tthis.templates = templates;\n\n\t\tthis.original = this.templates.map(function (temp) {\n\t\t\ttemp.type = 'dockedInSoundSelector';\n\t\t\ttemp.audioParams = audioParams;\n\t\t\treturn new SoundBite(temp);\n\t\t});\n\n\t\tthis.inuse = [];\n\t\tthis.all = [];\n\t\tthis.getAllBites();\n\t}", "static bytes15(v) { return b(v, 15); }", "setAt(idx, val) {\n try {\n if (idx >= this.length || idx < 0) throw new Error('Index is invalid!');\n let targetNode = this._getNode(idx);\n targetNode.val = val;\n } catch (e) {\n console.warn(e);\n }\n }", "writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Then we add a new country 2 seconds later
function newCountry(country, callback) { setTimeout(function() { // Add into the array countries.push(country); // Execute the callback callback(); }, 2000 ); }
[ "function handleAdd() {\n if (selectedTimeZone) {\n let newTimeZones = [...myTimeZones, selectedTimeZone]\n setMyTimeZones(newTimeZones)\n localStorage.setItem(TIME_ZONE_KEY, JSON.stringify(newTimeZones))\n }\n }", "function submitCountry()\n{\n let currentUserRef = localStorage.getItem(CURRENT_USER_KEY); // Retrieving the current user key\n let userCountry = document.getElementById(\"countriesId\").value; // Retrieving the user input country \n let userStartDate = new Date(document.getElementById(\"tripStartDate\").value); // Retrieving the user input date\n\t\n\t// Checking that the date is in the future\n\tif(userStartDate >= Date.now())\n {\n let countryValid = false; // Sets country as invalid\n\t\t\n\t\t// The following code will run for the length of the country array \n\t\tfor(let i = 0; i < countryData.length;i++)\n {\n if(userCountry === countryData[i]) // Checks that the user's selected country is in the array\n {\n countryValid = true; // Set country as valid\n listOfUsers.users[currentUserRef].createTrip(userStartDate,currentUserRef,userCountry); // Creating a new trip using the information\n\t\t\t\tupdateLocalStorage(listOfUsers,USERS_DATA_KEY); // Updating local storage\n\t\t\t\tgetData(userCountry); // Retrieving the country selected by the user \n\t\t\t\tbreak;\n }\n }\n if(!countryValid) // If the country is invalid \n {\n alert(\"Invalid Country\"); // Alerting the user that the country is invalid\n location.reload(); // Refreshes the page \n }\n }\n else // If the date is in the past\n {\n alert(\"Invalid Date: Please select a date in the future\"); // Alerting the user that the date is invalid\n location.reload(); // Refreshes the page \n } \n}", "function countryTimer() {\r\n countryElement.style.display = 'none';\r\n setTimeout(respondCountry, 1000);\r\n setTimeout(displayColour, 2000);\r\n}", "function addCountry(name, capital, population){\n nestedObject.data.continents.europe.countries[name] = {\n capital: capital,\n population: population\n }\n }", "function update_city_options(country_name)\r\n\t{\r\n\t\t$('#billing-city').html(city_list_cache[country_name]);\r\n\t}", "function addOption() {\n var province = profile.province;\n var country = profile.country;\n province.options[province.options.length] = SelectProvince;\n country.options[country.options.length] = SelectCountry;\n}", "function countryChange() {\n country = document.getElementById(countryName + \"-select\").value;\n updateData();\n }", "function save_existing_account()\r\n {\r\n if(!validate_dwolla_id()) return;\r\n\r\n charity_info.dwolla_id=$(\"#dwolla_id\").val();\r\n\r\n $.ajax(\r\n {\r\n url: \"/save_charity\",\r\n type: \"POST\",\r\n data: charity_info,\r\n success:\r\n function(data)\r\n {\r\n if(data.success)\r\n {\r\n charity_info.id=data.charity_id;\r\n $(\"#charity_id\").html(charity_info.id);\r\n _gaq.push([\"_trackPageView\",\"/register/step3\"]);\r\n show_next();\r\n }\r\n else\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was an internal problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n },\r\n error:\r\n function(data)\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was a problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n }); //end save_charity ajax call\r\n }", "function addToFacebank(name) {\n\n\t// <Prevent browser caching>\n\tmax = 9999999999999999;\n\tmin = 1000000000000000;\n\tvar id = Math.floor(Math.random() * (max - min)) + min;\n\tvar url = \"../data/facebank/\" + name + \"Banked.jpg?id=\" + id;\n\t// </ Prevent Browser Caching>\n\n\t// Hard Code a bunch of descriptions in for the people found by the face\n\t// tracker.\n\tdescription = \"\";\n\tswitch (name) {\n\tcase \"Andrew\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Mark\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Paul\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Nick\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Meg\":\n\t\tdescription = \"MIT Design student and Mentor\"\n\t\tbreak;\n\tcase \"Federico\":\n\t\tdescription = \"Director of MIT Media Labs\"\n\t\tbreak;\n\tdefault:\n\t\tdescripion = \"New Challenger!\"\n\t}\n\tfaceBank[name] = createNotification(name, description, url);\n\tconsole.log(\"ADDED TO FACEBANK\");\n}", "function addLocation() {\n\n personAwardLogic.addLocation($scope.awardLocation, personReferenceKey).then(function (response) {\n\n var locationId = null;\n if (appConfig.APP_MODE == 'offline') {\n locationId = response.insertId;\n } else {\n\n locationId = response.data.InsertId;\n }\n\n addPersonAward(locationId);\n\n }, function (err) {\n appLogger.error('ERR' + err);\n });\n }", "function generateCountry(data) {\n\tvar rand = Math.floor((Math.random() * data.features.length));\n\tvar country = data.features[rand].properties.name;\n\treturn country;\n}", "function showContries(){\n setTimeout(function(){\n let html = '';\n countries.forEach(function(country){\n html += `<li>${country}</li>`;\n });\n document.getElementById('carrito').innerHTML = html;\n }, 1000);\n}", "pickCountry( country ) {\n\t\tconst event = {...this.state.event};\n\t\t// Grab the current picking player\n\t\tconst pickingPlayer = this.props.players[ this.state.picker.key ];\n\n\t\t// if the picks don't exist yet in this event, create it.\n\t\t// let picks = event.picks || []; // Can probably remove this since we're putting the picks on the player state now instead of event state\n\t\tlet playerPicks = pickingPlayer.picks || [];\n\n\n\t\t// Can probably remove this since we're putting the picks on the player state now instead of event state\n\t\t// picks.push({\n\t\t// \tplayer: pickingPlayer,\n\t\t// \tcountry: country\n\t\t// });\n\n\t\tplayerPicks.push({\n\t\t\tcountry: country,\n\t\t\tevent: this.state.event\n\t\t});\n\t\tpickingPlayer.picks = playerPicks;\n\n\t\t// Sync the event with the new pick\n\t\tevent.picked = true;\n\t\tthis.setState({ event: event });\n\t\tthis.props.updateEvent( this.state.event.key, event );\n\n\t\t// This player is done picking, find a new one.\n\t\tpickingPlayer.isPicking = false;\n\t\tpickingPlayer.hasPicked = true;\n\t\tthis.props.updatePlayer( this.state.picker.key, pickingPlayer);\n\n\t\tthis.getNextPicker();\n\t}", "function loadCountries(){\n\tvar currline = [];\n\tfs.readFile('./countryList.txt', 'utf-8', function(err, data){\n\t\tif (err) throw err;\n\t\t\n\t\tvar lines = data.toString().trim().split('\\n');\n\t\t\n\t\tfor (var i = 0; i < lines.length; i++){\n\t\t\tcurrline = lines[i].split(',');\n\t\t database.create({ code: currline[0], country: currline[1]}, function(err, doc){\n\t\t \tif(!err){\n \t\t\t\tconsole.log(doc.toString());\n \t\t\t} else {\n \t\t\t\tconsole.log(\"Database error: \" + err);\n \t\t\t}\n \t\t});\n\t\t}\n\t});\n}", "addCTA({ country, width, height, onImageLoad, cta }) {\n if (Object.keys(cta).length > 0) {\n const { dx, dy, dWidth, dHeight } = cta;\n const src = `static/cta/${width}x${height}/${country}.jpg`;\n const image = new Image;\n image.src = src;\n image.onload = () => {\n this.addImage(image, dx, dy, dWidth, dHeight);\n onImageLoad();\n };\n }\n }", "function _trackPostRegistrationFloodlight() {\n\t\t// This tracking was only designated for New York.\n\t\tif($CITY_CONSTANT == 'newyork') {\n\t\t\tvar axel = Math.random() + \"\";\n\t\t\tvar a = axel * 10000000000000;\n\t\t\t\n\t\t\t// Utilize a different Floodlight iframe depending on which type of registration was performed.\n\t\t\tswitch(_postRegistration) {\n\t\t\t\tcase 'NWE':\n\t\t\t\t\t$('body').append('<iframe src=\"http://fls.doubleclick.net/activityi;src=2934628;type=price390;cat=pnyre888;ord=' + a + '?\" width=\"1\" height=\"1\" frameborder=\"0\" style=\"display:none\"></iframe>');\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'WE':\n\t\t\t\t\t$('body').append('<iframe src=\"http://fls.doubleclick.net/activityi;src=2934628;type=price390;cat=pnyre607;ord=' + a + '?\" width=\"1\" height=\"1\" frameborder=\"0\" style=\"display:none\"></iframe>');\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "function createAccount()\n{\n let nameRef = document.getElementById(\"name\");\n let emailIdRef = document.getElementById(\"emailId1\");\n let password1Ref = document.getElementById(\"password1\");\n let password2Ref = document.getElementById(\"password2\");\n if(password1Ref.value == password2Ref.value)\n {\n accounts.addAccount(emailIdRef.value);\n let user = accounts.getAccount(accounts.count - 1); //to get the last account\n user.name = nameRef.value;\n user.password = password1Ref.value;\n if (getDataLocalStorageTrip() != undefined)\n {\n let trip = getDataLocalStorageTrip();\n user.addTrip(trip._tripId);\n //subtracting -1 to access the last trip\n user.getTripIndex(user._trips.length -1)._country = trip._country;\n user.getTripIndex(user._trips.length -1)._date = trip._date;\n user.getTripIndex(user._trips.length -1)._start = trip._start;\n user.getTripIndex(user._trips.length -1)._end = trip._end;\n user.getTripIndex(user._trips.length -1)._stops = trip._stops;\n trip = \"\"; //to clear the trip local data\n updateLocalStorageTrip(trip);\n }\n updateLocalStorageUser(user)\n updateLocalStorageAccount(accounts); //updating the new accounts array into the local storage\n alert(\"Account created successfully\");\n window.location = \"index.html\"; \n }\n else\n {\n alert(\"ERROR! Password does not match\");\n }\n}", "merge(country){\n this.states = this.states.concat(country.states);\n this.states = this.states.filter(function(state, iState,self){\n var firstIndex = self.findIndex(function(findState){\n return findState.name == state.name;\n })\n\n if (firstIndex != iState){\n this.states[firstIndex].cities = this.states[firstIndex].cities.concat(this.states[iState].cities);\n return false;\n }\n else\n return true;\n \n }, this);\n }", "function getCountryFromApi(country) {\n if (country === \"faroe islands\") {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n throw new Error(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n }\n\n const url = `https://agile-oasis-81673.herokuapp.com/api/country/${country}`;\n\n request(url)\n .then((rawCountryData) => {\n let translateRes, geoCodeRes, timeZone1Res, timeZone2Res;\n\n let countryData = findCountry(rawCountryData, country);\n\n $(\"html\").removeClass(\"first-background\");\n $(\"html\").addClass(\"second-background\");\n\n const googleTranslatePromise = googleTranslateApi(countryData).then(\n (res) => {\n translateRes = res;\n }\n );\n\n const geoCodingPromise = geoCodeCapitalApi(countryData)\n .then((res) => {\n geoCodeRes = res;\n return timeZoneApi1(geoCodeRes);\n })\n .then((res) => {\n timeZone1Res = res;\n return timeZoneApi2(timeZone1Res);\n })\n .then((res) => {\n timeZone2Res = res;\n });\n\n Promise.all([googleTranslatePromise, geoCodingPromise]).then(() => {\n $(\"body\").addClass(\"centered\");\n let countryCapital = countryData.capital;\n let countryName = countryData.name;\n displayTimeResults(\n timeZone2Res,\n countryCapital,\n countryName,\n translateRes\n );\n restartButton();\n $(\"header\").addClass(\"hidden\");\n $(\"footer\").addClass(\"hidden\");\n });\n })\n .catch((err) => {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list! \" +\n err.message +\n \".\"\n );\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes an ability dictionary in order to prevent multiple lookups for ability IDs
function createAbilityDict() { let abilDict = {}; return new Promise(function(resolve,reject) { $.getJSON(apiBase + "/IdLists/Ability", function(abilJSON) { abilJSON.forEach((json) => { abilDict[json.Value.toLowerCase()] = json.Key; }); resolve(abilDict); }); }); }
[ "function isValidAbility(id) {\n if (typeof id === 'undefined' || id == null) {\n return false;\n };\n if (typeof ABILITIES[id.toLowerCase()] === 'undefined') {\n return false;\n } else {\n return true;\n };\n}", "constructor() {\n this.game = undefined;\n\n this.mapKey = undefined; // should be string with name of map\n this.playerProperties = undefined; // should be object with properties of player\n this.monsterProperties = undefined; // should be array of objects with properties of each monster\n this.defaultAbilities = undefined; // should be array of default abilities\n\n this.player = undefined; // defined in createPlayer(); included here to avoid IDE warning\n }", "init(){\n\t\tthis.calcStats();\n\t\tthis.hpRem = this.getStatValue(Stat.HP);\n\n\t\tthis.poisoned = false;\n\t\tthis.regen = false;\n\t\tthis.shield = false;\n\n this.healableDamage = 0; //damage that can be healed through heart collection\n\n this.eventListenReg.clear();\n\n this.warriorSkills.forEach((skill)=>{\n skill.apply();\n });\n\t}", "constructor() {\n this.stringToIdMap = new Map();\n }", "setupCardAbilities(ability) {\n this.action({\n target: {\n numCards: 3,\n mode: 'upTo',\n controller: 'self',\n cardType: 'creature',\n cardCondition: (card) => card.hasHouse('logos'),\n gameAction: ability.actions.exhaust()\n },\n then: {\n alwaysTriggers: true,\n condition: (context) => context.preThenEvents.some((event) => !event.cancelled),\n gameAction: ability.actions.sequentialForEach((context) => ({\n num: context.preThenEvents.filter((event) => !event.cancelled).length,\n action: ability.actions.playCard((context) => ({\n revealOnIllegalTarget: true,\n target: context.player.deck[0]\n }))\n }))\n }\n });\n }", "function internal_initialiseAclRule(access) {\n let newRule = createThing();\n newRule = setIri(newRule, rdf.type, acl.Authorization);\n if (access.read) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);\n }\n if (access.append && !access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);\n }\n if (access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);\n }\n if (access.control) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);\n }\n return newRule;\n}", "static generateAbilityCode(characterCode) {\n switch (characterCode) {\n case 'q': return 'Abilities[1]';\n case 'w': return 'Abilities[2]';\n case 'e': return 'Abilities[3]';\n case 'r': return 'Abilities[4]';\n case 't': return '\"talent\"';\n case 'n': return '\"nil\"';\n default: return '';\n }\n }", "function mapSpecialAbilitiesData () {\n formattedInput.special_abilities.forEach (async function (specialAbility, index) {\n \n // SET THE FEATTYPE\n let featType = \"misc\";\n \n setSpecialAbilityItem(specialAbility, featType, \"Special Ability\");\n \n });\n}", "static generateAbilityArray(str) {\n const abilities = [];\n for (let i = 0; i < str.length; i += 1) {\n abilities[i] = this.generateAbilityCode(str[i]);\n }\n return abilities;\n }", "initializeList(listOfIds) {\n let currentObjectivesCount = parseInt(getValue('cmi.object._count'));\n if (currentObjectivesCount) {\n DEBUG.log('objectives already initialized');\n return;\n } else {\n listOfIds.forEach(obj => this.addObjective(obj));\n }\n }", "function addAI() {\n\n\tif (!availableIDs.length) {\n\t\t// No more room\n\t\treturn;\n\t}\n\n\tlogger.info(\"Adding AI\");\n\n\tclientCount++;\n\tvar playerID = availableIDs.pop();\n var newHand = new Hand(0);\n\tvar ai = new Player(playerID, null, \"Agent \" + playerID, newHand);\n\n\t// Give hand to new player\n\tdealHand(ai, FACEDOWN);\n ai.hand.faceDown.sort(function(a,b) {return a.value()-b.value()});\n ai.hand.showing.sort(function(a,b) {return a.value()-b.value()});\n\n var aiClient = {\n \"id\": ai.id\n };\n\n // Map this player ID to the AI object\n AIs[ai.id] = aiClient;\n\n // Map the new player and connection handle to this client uid\n clients[aiClient.id] = {\n \"player\": ai,\n \"playTurn\": function() {\n setTimeout(AITurn, AI_TURN_TIME);\n },\n \"connection\": null\n };\n\n addAICommon(ai);\n\n}", "function InitHashKeys() {\n var index = 0;\n for (index = 0; index < 14 * 120; ++index) {\n PieceKeys[index] = RAND_32();\n }\n\n SideKey = RAND_32();\n\n for(index = 0; index < 16; ++index) {\n CastleKeys[index] = RAND_32();\n }\n}", "function loadElementsAttributes(abilityNames, defenseNames, attributeNames){\n\tvar output = ''\n\t\n\t//Load main abilities\n\tfor (var i = 0; i < abilityNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{ability}', abilityNames[i], abilityTemplate);\n\t\toutput += replaceAll('{ABILITY}', abilityNames[i].toUpperCase(), buffer);\n\t}\n\t\n\t//Load defense abilities\n\tfor (var i = 0; i < defenseNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{defense}', defenseNames[i], defenseTemplate);\n\t\toutput += replaceAll('{DEFENSE}', defenseNames[i].toUpperCase(), buffer);\n\t}\n\tabilityContainer.innerHTML = output;\n\t\n\toutput = '';\n\t//Load attributes\n\tfor (var i = 0; i < attributeNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{attr}', attributeNames[i], attributeTemplate);\n\t\toutput += replaceAll('{Attr}', capitalize(attributeNames[i]), buffer);\n\t}\n\tattributes.innerHTML = output;\n}", "function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }", "static generateLevelingAbilityCode(str) {\n const abilityArray = this.generateAbilityArray(str);\n const code = LuaCodeGenerator.createLuaTable('AbilityToLevelUp', abilityArray, false);\n return code;\n }", "addPermission(permission, region = 'default') {\n if (!permission.id) {\n return;\n }\n this.authorizedMap[permission.id] = this.authorizedMap[permission.id] || {};\n // set default values\n permission.geographies = permission.geographies || [];\n permission.organizations = permission.organizations || [];\n permission.isAuthorized = permission.organizations.length > 0;\n this.authorizedMap[permission.id][region] = permission;\n }", "async _loadDicts() {\n // Remove if replace is unset\n if (!game.user || !game.user.isGM || this.data.name.replace !== \"replace\") {\n // Useful to free up memory? its \"just\" up to 17MB...\n // delete this.dict;\n return;\n }\n if (!this.dict) this.dict = {};\n const options = this.data.name.options;\n let languages = this.languages;\n for (let lang of languages) {\n if (this.dict[lang]) continue;\n this.dict[lang] = (await import(`./dict/${lang}.js`)).lang;\n }\n }", "initAnagramsCache() {\n const keys = Object.keys(this.dictionary.getDictionary());\n const stopWatch = StopWatch.create();\n stopWatch.start();\n const totalKeys = keys.length;\n let numWords = 0;\n for(let key of keys){\n let anagrams = this.findAnagrams(key);\n this.anagramsCache[key] = anagrams.anagrams;\n numWords++;\n if(numWords % 1000 === 0) {\n log.info(numWords + '/' + totalKeys + ' completed');\n }\n if(numWords % 25000 === 0) {\n log.info('25k anagrams completed in: ' + stopWatch.elapsed.seconds + ' seconds');\n }\n }\n stopWatch.stop();\n log.info('Cache completed in: ' + stopWatch.elapsed.seconds + ' seconds');\n }", "function init (){\n\tvar num_troops = 120/num_player;\n\t//initialize map with same number of troops for each player\n\tfor (var i=0 ; i < num_troops; i++){\n\t\tfor(game.currentUserTurn ;game.currentUserTurn<num_player; game.currentUserTurn++){\n\t\t\t//calling object\n\n\t\t\tgame.regions[].controlledBy=game.currentUserTurn;\n\t\t\taddTroops (game.currentUserTurn, game.regions[territory]);\n\t\t\t//game.regions[/*input*/].controlledBy=game.currentUserTurn;\n\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the second last block
getSecondLastBlock (callback) { if (this.chainLength <= 1) { let err = new Error('this.chainLength <= 1, failed to get second last block') return callback(err, null) } this.getBlock(this.chainLength - 2, callback) }
[ "getLatestBlock() {\n return this.chain[this.chain.length - 1];\n }", "function getLastChunk(chunks) {\n return chunks[chunks.length - 1];\n}", "function getNextBlock () {\n\n // ensure something to pull from\n fillBag();\n\n // take block from next pieces queue\n let nextBlock = nextPieces.pop();\n\n // ensure STILL something to pull from\n fillBag();\n \n return nextBlock;\n}", "function getIthBlockFromEnd(i, file) {\n let blockSizeInBytes = 16;\n if (fs.existsSync(file)) {\n let fileSizeInBytes = fs.statSync(file)[\"size\"];\n if (fileSizeInBytes >= i * blockSizeInBytes) {\n let start = fileSizeInBytes - i * blockSizeInBytes;\n let length = Math.min(fileSizeInBytes - start, blockSizeInBytes);\n return readBytesFromFile(file, start, length);\n }\n }\n\n return null;\n}", "function getLastBox(bed) {\n\tif (isEmpty(bed))\n\t\treturn undefined;\n\telse {\n\t\treturn bed.boxes.slice(-1).pop();\n\t}\n}", "function getLastBlockheightAtStartup() {\n if (!source) return;\n rise.blocks\n .getHeight()\n .then(({ height }) => {\n chrome.storage.local.set({ lastseenblockheight: height });\n })\n .catch(() => {\n notifyConnectionProblems('RISE node');\n });\n}", "getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }", "tail() {\n return null;\n }", "async latestDsBlock() {\n return await this.baseJsonRpcRequest('GetLatestDsBlock');\n }", "function last() {\n return _navigationStack[_navigationStack.length - 1];\n }", "function last(arr, cb) {\n return cb(items[items.length - 1]);\n}", "function get_block_position( itm_block ){\n\t\t\t\tvar min_index = stack_length.indexOf( get_min_val(stack_length) );\n\t\t\t\tvar size = get_size_block( itm_block );\n\t\t\t\tvar out = [];\n\n\t\t\t\t// если в одну колонку влезает\n\t\t\t\tif( size[0] == 1 )\n\t\t\t\t{\n\t\t\t\t\tout.push( stack_length[min_index] * ( single_size + opt.distance ) );\n\t\t\t\t\tout.push( min_index * (single_size + opt.distance) );\n\t\t\t\t\tstack_length[min_index] = stack_length[min_index] + size[1];\n\n\t\t\t\t\t// более чем в один блок\n\t\t\t\t} else {\n\t\t\t\t\tvar time_steck_length = stack_length.concat(); \t\t//\tвременная переменная для хранения длинн\n\t\t\t\t\tvar sub_max = get_max_val( time_steck_length.slice(min_index,min_index+size[0]) );\n\n\t\t\t\t\twhile( out.length == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tmin_index = time_steck_length.indexOf( get_min_val(time_steck_length.slice(0, time_steck_length.length - size[0] + 1)) );\n\t\t\t\t\t\tsub_max = get_max_val( time_steck_length.slice(min_index,min_index+size[0]) );\n\n\t\t\t\t\t\tif( sub_max != time_steck_length[min_index] ){\n\t\t\t\t\t\t\ttime_steck_length[min_index] = time_steck_length[min_index] + 1;\n\t\t\t\t\t\t\tmin_index = time_steck_length.indexOf( get_min_val(time_steck_length) );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tout.push( time_steck_length[min_index] * ( single_size + opt.distance ) );\n\t\t\t\t\t\t\tout.push( min_index*(single_size + opt.distance) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsub_max = size[1] + time_steck_length[min_index];\n\t\t\t\t\tfor (var i = min_index; i < min_index + size[0]; i++) {\n\t\t\t\t\t\tstack_length[i] = sub_max;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\n\t\t\t\treturn out;\n\t\t\t}", "function readLastMainChainIndex( handleLastMcIndex )\n{\n\tdb.query\n\t(\n\t\t\"SELECT MAX( main_chain_index ) AS last_mc_index FROM units\",\n\t\tfunction( rows )\n\t\t{\n\t\t\tvar last_mc_index;\n\n\t\t\t//\t...\n\t\t\tlast_mc_index\t= rows[ 0 ].last_mc_index;\n\n\t\t\tif ( last_mc_index === null )\n\t\t\t{\n\t\t\t\t//\tempty database\n\t\t\t\tlast_mc_index = 0;\n\t\t\t}\n\n\t\t\t//\t...\n\t\t\thandleLastMcIndex( last_mc_index );\n\t\t}\n\t);\n}", "function traverseToRealDifficulty (block, chain, cb) {\n var traverse = (err, prev) => {\n if (err) return cb(err)\n var onInterval = prev.height % this.interval === 0\n if (onInterval || prev.header.bits !== this.genesisHeader.bits) {\n return cb(null, prev)\n }\n chain.getBlock(prev.header.prevHash, traverse)\n }\n chain.getBlock(block.header.prevHash, traverse)\n}", "function getLast(evt){\n\tindex--;\n\tif (index < 0){\n\t\tindex = Object.keys(photoData).length -1;\n\t};\n\tswapPic(index);\n}", "function getLast() {\n return lastRemoved;\n}", "async latestTxBlock() {\n return await this.baseJsonRpcRequest('GetLatestTxBlock');\n }", "function DDLightbarMenu_GetTopItemIdxOfLastPage()\n{\n\tvar numItemsPerPage = this.size.height;\n\tif (this.borderEnabled)\n\t\tnumItemsPerPage -= 2;\n\tvar topItemIndex = this.NumItems() - numItemsPerPage;\n\tif (topItemIndex < 0)\n\t\ttopItemIndex = 0;\n\treturn topItemIndex;\n}", "function getLastDo () {\n var tmpDo = firstDo;\n while (tmpDo.nextDo) { tmpDo = tmpDo.nextDo; }\n return tmpDo;\n }", "_lastHeading() {\n const headings = this._allHeadings();\n return headings[headings.length - 1];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop visualizing the source node and disconnect it.
disconnect() { if (this.source) { this.source.disconnect(this.analyser); this.source = null; } }
[ "disconnect() {\n\t\t\tthis.connected = false;\n\t\t\t// Emitting event 'disconnect', 'exit' and finally 'close' to make it similar to Node's childproc & cluster\n\t\t\tthis._emitLocally('disconnect');\n\t\t}", "stopTrackingMouse() {\n if (this._pointerWatch)\n this._pointerWatch.remove();\n\n this._pointerWatch = null;\n }", "function stopVisualization(){\n\t\twindow.cancelAnimationFrame(request_animation);\n\t\tamplitude_container.innerHTML = '';\n\t}", "terminateConnectPreview(event) {\n if (!event.shiftKey) {\n if (this.isPreviewing && !this.didConnect) {\n this.removeDrawnArrow();\n if (this.wasConnected && this.hasInputTarget) {\n this.inputTarget.value = null;\n const evt = new CustomEvent(\"form:submit\", {bubbles: true, cancelable: true});\n this.element.dispatchEvent(evt);\n this.wasConnected = false;\n }\n }\n\n this.isPreviewing = false;\n }\n }", "removeEdge() {\n this.graph[fromNode] = true;\n this.graph[toNode] = true;\n }", "function updateModelOnConnectionDetach() {\n self.jsPlumbInstance.bind('connectionDetached', function (connection) {\n\n // set the isDesignViewContentChanged to true\n self.configurationData.setIsDesignViewContentChanged(true);\n\n var target = connection.targetId;\n var targetId = target.substr(0, target.indexOf('-'));\n /*\n * There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')\n * section in partition connection point. So once we substr with '-' we don't get any value. So we\n * explicitly set the targetId. Simply if targetId is '' that means this connection is related to a\n * partition.\n * */\n if (targetId === '') {\n targetId = target;\n } else if (!self.configurationData.getSiddhiAppConfig()\n .getDefinitionElementById(targetId, true, true)) {\n console.log(\"Target element not found!\");\n }\n var targetElement = $('#' + targetId);\n\n var source = connection.sourceId;\n var sourceId = source.substr(0, source.indexOf('-'));\n /*\n * There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')\n * section in partition connection point. So once we substr with '-' we don't get any value. So we\n * explicitly set the sourceId. Simply if sourceId is '' that means this connection is related to a\n * partition.\n * */\n if (sourceId === '') {\n sourceId = source;\n } else if (!self.configurationData.getSiddhiAppConfig()\n .getDefinitionElementById(sourceId, true, true)) {\n console.log(\"Source element not found!\");\n }\n var sourceElement = $('#' + sourceId);\n\n // removing edge from the edgeList\n var edgeId = '' + sourceId + '_' + targetId + '';\n self.configurationData.removeEdge(edgeId);\n\n var model;\n\n if (sourceElement.hasClass(constants.SOURCE) && targetElement.hasClass(constants.STREAM)) {\n self.configurationData.getSiddhiAppConfig().getSource(sourceId)\n .setConnectedElementName(undefined);\n\n } else if (targetElement.hasClass(constants.SINK) && sourceElement.hasClass(constants.STREAM)) {\n self.configurationData.getSiddhiAppConfig().getSink(targetId)\n .setConnectedElementName(undefined);\n\n } else if (targetElement.hasClass(constants.AGGREGATION)\n && (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {\n model = self.configurationData.getSiddhiAppConfig().getAggregation(targetId)\n model.setConnectedSource(undefined);\n if(sourceElement.hasClass(constants.STREAM)) {\n model.resetModel(model);\n }\n } else if (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TABLE)\n || sourceElement.hasClass(constants.AGGREGATION) || sourceElement.hasClass(constants.WINDOW)\n || sourceElement.hasClass(constants.TRIGGER)\n || sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {\n\n // if the sourceElement has the class constants.PARTITION_CONNECTION_POINT then that is\n // basically a stream because a connection point holds a connection to a stream.\n // So we replace that sourceElement with the actual stream element.\n if (sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {\n var sourceConnection = self.jsPlumbInstance.getConnections({target: sourceId});\n var sourceConnectionId = sourceConnection[0].sourceId;\n var connectedStreamId = sourceConnectionId.substr(0, sourceConnectionId.indexOf('-'));\n sourceElement = $('#' + connectedStreamId);\n sourceId = connectedStreamId;\n }\n\n if ((sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.WINDOW)\n || sourceElement.hasClass(constants.TRIGGER))\n && (targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)\n || targetElement.hasClass(constants.WINDOW_QUERY)\n || targetElement.hasClass(constants.FUNCTION_QUERY))) {\n model = self.configurationData.getSiddhiAppConfig()\n .getWindowFilterProjectionQuery(targetId);\n model.resetInputModel(model);\n\n } else if (targetElement.hasClass(constants.JOIN)) {\n model = self.configurationData.getSiddhiAppConfig().getJoinQuery(targetId);\n var queryInput = model.getQueryInput();\n var sourceElementObject =\n self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId);\n if (sourceElementObject !== undefined) {\n var disconnectedElementSourceName = (sourceElementObject.element).getName();\n if (!queryInput) {\n console.log(\"Join query output is undefined!\");\n return;\n }\n var firstConnectedElement = queryInput.getFirstConnectedElement();\n var secondConnectedElement = queryInput.getSecondConnectedElement();\n if (!firstConnectedElement && !secondConnectedElement) {\n console.log(\"firstConnectedElement and secondConnectedElement are undefined!\");\n } else if (firstConnectedElement &&\n (firstConnectedElement.name === disconnectedElementSourceName ||\n !firstConnectedElement.name)) {\n queryInput.setFirstConnectedElement(undefined);\n } else if (secondConnectedElement\n && (secondConnectedElement.name === disconnectedElementSourceName ||\n !secondConnectedElement.name)) {\n queryInput.setSecondConnectedElement(undefined);\n } else {\n console.log(\"Error: Disconnected source name not found in join query!\");\n return;\n }\n\n // if left or sources are created then remove data from those sources\n if (queryInput.getLeft() !== undefined\n && queryInput.getLeft().getConnectedSource() === disconnectedElementSourceName) {\n queryInput.setLeft(undefined);\n } else if (queryInput.getRight() !== undefined\n && queryInput.getRight().getConnectedSource() === disconnectedElementSourceName) {\n queryInput.setRight(undefined);\n }\n model.resetInputModel(model);\n }\n\n } else if (sourceElement.hasClass(constants.STREAM)\n || sourceElement.hasClass(constants.TRIGGER)) {\n\n var disconnectedElementName;\n if (sourceElement.hasClass(constants.STREAM)) {\n disconnectedElementName =\n self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();\n } else {\n disconnectedElementName =\n self.configurationData.getSiddhiAppConfig().getTrigger(sourceId).getName();\n }\n\n if (targetElement.hasClass(constants.PATTERN)) {\n model = self.configurationData.getSiddhiAppConfig().getPatternQuery(targetId);\n model.resetInputModel(model, disconnectedElementName);\n } else if (targetElement.hasClass(constants.SEQUENCE)) {\n model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(targetId);\n model.resetInputModel(model, disconnectedElementName);\n }\n }\n\n } else if (targetElement.hasClass(constants.STREAM) || targetElement.hasClass(constants.TABLE)\n || targetElement.hasClass(constants.WINDOW)) {\n if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)\n || sourceElement.hasClass(constants.WINDOW_QUERY)\n || sourceElement.hasClass(constants.FUNCTION_QUERY)\n || sourceElement.hasClass(constants.JOIN)\n || sourceElement.hasClass(constants.PATTERN)\n || sourceElement.hasClass(constants.SEQUENCE)) {\n\n if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)\n || sourceElement.hasClass(constants.WINDOW_QUERY)\n || sourceElement.hasClass(constants.FUNCTION_QUERY)) {\n model = self.configurationData.getSiddhiAppConfig()\n .getWindowFilterProjectionQuery(sourceId);\n } else if (sourceElement.hasClass(constants.JOIN)) {\n model = self.configurationData.getSiddhiAppConfig().getJoinQuery(sourceId);\n } else if (sourceElement.hasClass(constants.PATTERN)) {\n model = self.configurationData.getSiddhiAppConfig().getPatternQuery(sourceId);\n } else if (sourceElement.hasClass(constants.SEQUENCE)) {\n model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(sourceId);\n }\n model.resetOutputModel(model);\n }\n }\n\n // validate source and target elements\n checkJSONValidityOfElement(self, sourceId, true);\n checkJSONValidityOfElement(self, targetId, true);\n });\n }", "disconnect() {\n\t\tthis.debug('Requesting disconnect from peer');\n\t}", "function stopShareScreen(){\n let videoTrack = window.localStream.myVidStream()[0];\n var sender = currentPeer.getSenders().find(function(s){\n return s.track.kind == videoTrack.kind;\n })\n sender.replaceTrack(videoTrack)\n}", "function ChooseLinkCancel() {\n // detach connection\n if (Conn) {\n jsPlumb.detach(Conn);\n }\n DummyConnection = '';\n Core.UI.Dialog.CloseDialog($Dialog);\n }", "stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }", "function mouseouthandler(event) {\n //console.log(\"the mouse is no longer over canvas:: \" + event.target.id);\n mouseIn = 'none';\n }", "function clearFilter(context) { \n // iterate over all the nodes in the graph and show them (unhide)\n var self = context;\n if (self && self.GraphVis) {\n self.GraphVis.showAll(true);\n }\n \n self.GraphVis.gv.fit();\n}", "function hideDragLine() {\r\n if (editable) {\r\n dragLine.classed(\"hidden\", true);\r\n\r\n // Reset mouse down and up nodes\r\n mousedownNode = null;\r\n mouseupNode = null;\r\n restart();\r\n }\r\n}", "function isDisconnected(node){return!node||!node.parentNode||node.parentNode.nodeType===11;}", "function stop() {\n testTransport.removeListener(\"close\", find);\n testTransport.close();\n }", "stop() {\n if (!this.isStarted()) {\n throw new Error('cannot stop backend: not started yet');\n }\n this.started = false;\n this.logWriter.writeLine(`stopping backend for ${this.previewUriScheme}:// at port ${this.serverPort}`);\n this.server.stop();\n }", "detach() {\n this.surface = null;\n this.dom = null;\n }", "static cleanVideoSource(videoElement){if(!videoElement){return;}// forgets about that element 😢\ntry{videoElement.srcObject=null;}catch(err){videoElement.src='';}if(videoElement){videoElement.removeAttribute('src');}}", "stop() {\n this.target = undefined;\n // @ts-expect-error\n const pathfinder = this.bot.pathfinder;\n pathfinder.setGoal(null);\n // @ts-expect-error\n this.bot.emit('stoppedAttacking');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a BR at the end of blocks that only contains an IMG or INPUT since these might be floated and then they won't expand the block
function addBrToBlockIfNeeded(block) { var lastChild; // IE will render the blocks correctly other browsers needs a BR if (!isIE) { block.normalize(); // Remove empty text nodes that got left behind by the extract // Check if the block is empty or contains a floated last child lastChild = block.lastChild; if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) { dom.add(block, 'br'); } } }
[ "function _isLineBreakOrBlockElement(element) {\r\n if (_isLineBreak(element)) {\r\n return true;\r\n }\r\n\r\n if (wysihtml5.dom.getStyle(\"display\").from(element) === \"block\") {\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "convertLineBreaksToNonBreaking() {\n for (const breakEl of document.querySelectorAll('.coding-line br')) {\n const parentNode = breakEl.parentNode;\n if (parentNode.childNodes.length === 1) {\n parentNode.innerHTML = '&nbsp;';\n } else {\n breakEl.remove();\n }\n }\n }", "insertBreak(editor) {\n editor.insertBreak();\n }", "_wrapDefaultBlockToListInner() {\n this.wwe.get$Body().find('li').each((index, node) => {\n if ($(node).children('div, p').length <= 0) {\n $(node).wrapInner('<div />');\n $(node).find('div').children('ul, ol').appendTo(node);\n }\n });\n }", "function _genHtmlIpBlocks(name, classes, onKeyUp) {\n\tvar html = \"\";\n\tif(!isDefined(onKeyUp)) onKeyUp = \"NumfieldEntry(this);\";\n\t[\".\",\".\",\".\",\"\"].forEach(function(dot, i) {\n\t\tvar id = name + (i+1);\n\t\tvar inputAttribs = {type:'text', class: classes[i] +\" ip-adress\", maxLength: 3, name: id, id: id, onkeyup: onKeyUp, onchange: \"validate_group('\" + name + \"')\"};\n\t\thtml += htmlDiv( {class:'field'}, htmlTag(\"input\", inputAttribs, \"\")) + htmlTag(\"label\", {for: id, class:'input-connect-dot'}, dot);\n\t});\n\treturn html;\n}", "handleNewLine(editorState, event) {\n // https://github.com/jpuri/draftjs-utils/blob/e81c0ae19c3b0fdef7e0c1b70d924398956be126/js/keyPress.js#L64\n if (isSoftNewlineEvent(event)) {\n return this.addLineBreak(editorState);\n }\n\n const content = editorState.getCurrentContent();\n const selection = editorState.getSelection();\n const key = selection.getStartKey();\n const offset = selection.getStartOffset();\n const block = content.getBlockForKey(key);\n\n const isDeferredBreakoutBlock = [BLOCK_TYPE.CODE].includes(\n block.getType(),\n );\n\n if (isDeferredBreakoutBlock) {\n const isEmpty =\n selection.isCollapsed() &&\n offset === 0 &&\n block.getLength() === 0;\n\n if (isEmpty) {\n return EditorState.push(\n editorState,\n Modifier.setBlockType(\n content,\n selection,\n BLOCK_TYPE.UNSTYLED,\n ),\n 'change-block-type',\n );\n }\n\n return false;\n }\n\n return this.handleHardNewline(editorState);\n }", "function appendTimeBlock(){\n \n for(var i = startTimeBlock; i < endTimeBlock + 1; i++){\n createTimeBlock()\n saveSymbol.attr('save',i)\n textArea.addClass(`block-${i}`)\n \n time.text(`${timeBlock = moment(i, 'h').format('h A')}`)\n\n if(currentTime > i){\n textAreaDiv.addClass('past')\n }\n else if(currentTime < i){\n textAreaDiv.addClass('future')\n }\n else{\n textAreaDiv.addClass('present')\n }\n row.append(time, textAreaDiv, submitDiv)\n timeBlockEl.append(row)\n }\n \n}", "adjustToFill(currentWidth, availableRowWidth, domRow, imageCount) {\n let i = 0;\n while (currentWidth < availableRowWidth) {\n const imageContainer = domRow.querySelector('.image-wrapper:nth-child(' + (i + 1) + ') .gallery-image');\n imageContainer.style.width = (imageContainer.offsetWidth + 1) + 'px';\n // next image in the row\n i = (i + 1) % imageCount;\n currentWidth++;\n }\n\n i = 0;\n while (currentWidth > availableRowWidth) {\n const imageContainer = domRow.querySelector('.image-wrapper:nth-child(' + (i + 1) + ') .gallery-image');\n imageContainer.style.width = (imageContainer.offsetWidth - 1) + 'px';\n // next image in the row\n i = (i + 1) % imageCount;\n currentWidth--;\n }\n }", "function insert () {\n var link = escape($('#redactor-redimage-link').val());\n var title = escape($('#redactor-redimage-title').val());\n\n this.insert.html('<img src=\"' + link + '\" alt=\"' + title + '\">');\n this.modal.close();\n }", "function addFields () {\n\t\n\t$(\"#contestantsForm\").append('<input type=\"text\" /><br/><input type=\"text\" /><br/>');\n}", "function htmlEndBlock()\n{\n print(\"<!-- END OF PAGE BODY -->\\n\\n\");\n print(\"\\t\\t\\t</td>\\n\");\n print(\"\\t\\t</tr>\\n\");\n print(\"\\t</table>\\n\");\n //print(\"\\t<hr />\\n\");\n}", "insertImagesToEditor(images) {\n let imgsHtml = '';\n images.forEach(img => {\n imgsHtml += `<figure class=\"image\"><img src=\"${img.urlMedium}\" alt=\"${img.alt}\" title=\"${img.title}\"><figcaption>${img.caption}</figcaption></figure>`;\n img.selected = false; // remove the checkmark\n });\n const viewFragment = this.editor.data.processor.toView(imgsHtml);\n const modelFragment = this.editor.data.toModel(viewFragment);\n this.editor.model.insertContent(modelFragment, this.editor.model.document.selection);\n }", "function moveFooterIcons() {\n let block = $(\".js-footer-icons\");\n let windowInnerWidth = window.innerWidth;\n\n if (!block) return;\n\n if (windowInnerWidth < 850) {\n $(\".footer__top\").append(block);\n } else {\n block.insertAfter(\".social__list\");\n }\n}", "function addImagesToParagraphs(images, name){\n var intervall;\n var imagesAdded = 0;\n var paragraphs = O(\"artistExtended\").getElementsByTagName(\"p\");\n\n paragraphs.length > 15 ? intervall = 3 : intervall = 2;\n\n for(var i = 3; i < paragraphs.length; i += intervall){\n\n if (imagesAdded < images.length) {\n var tempImg = document.createElement(\"img\");\n tempImg.src = images[imagesAdded++].url;\n tempImg.alt = name + \" image\";\n if(imagesAdded % 2 == 0){\n tempImg.className = \"imgFill imgFloatLeft\";\n }else{\n tempImg.className = \"imgFill imgFloatRight\";\n }\n paragraphs[i].insertBefore(tempImg, paragraphs[i].firstChild);\n\n\n }\n }\n}", "function addFillersToEmptyImages(item) {\n if (item.image.localeCompare(\"\") == 0 ) {\n item.image = \"https://www.universitycounselingjobs.com/institution/logo/logo2(4).png\"\n }\n}", "function EndTextBlock() {\n\tif (arguments.length != 0) {\n\t\terror('Error 110: EndTextBlock(); must have empty parentheses.');\n\t}\n\telse if (EDITOR_OBJECT == null ) {\n\t\terror(\t'Error 111: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if ( !(EDITOR_OBJECT instanceof text_block) ) {\n\t\terror(\t'Error 112: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if (!ERROR_FOUND) {\n\t\tvar current_text_block = EDITOR_OBJECT;\n\t\tvar block_html = \t'<span class=\"' + \n\t\t\t\t\t\t\tcurrent_text_block.class + \n\t\t\t\t\t\t\t'\" ' + \n\t\t\t\t\t\t\tcurrent_text_block.html + '\">';\n\n\t\tfor (j = 0; j < current_text_block.content.length; j++) {\n\t\t\tvar item = current_text_block.content[j];\n\t\t\tblock_html += item.html;\n\t\t}\n\n\t\tcurrent_text_block.html = block_html + '</span>';\n\t\tEDITOR_OBJECT = EDITOR_STACK.pop();\n\t\tconsole.log(block_html);\n\t}\n}", "function processImageSafeway(image) {\n\t// Assume this is a safeway receipt\n\t// Look for the word \"bal\" which is going to signal the end of the receipt, and total money spent\n\tconsole.log(\"THIS IS A SAFEWAY RECEIPT!\");\n\n\tvar receiptBeginLine = 0;\n\tvar receiptEndLine = 99999;\n\tfor (var i = 0; i < image._arrayOfLines.length; i++) {\n\t\tfor (var b = 0; b < image._arrayOfLines[i]._arrayOfBlocks.length; b++) {\n\t\t\tvar currBlock = image._arrayOfLines[i]._arrayOfBlocks[b];\n\t\t\tif (currBlock._contents.toLowerCase() == \"bal\" && i < receiptEndLine) {\n\t\t\t\t// we have the last block. Exit looking at stuff\n\t\t\t\treceiptEndLine = i + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\timage._arrayOfLines = image._arrayOfLines.slice(receiptBeginLine, receiptEndLine);\n\n\t// Go through the rest of the lines of the receipt, tagging lines that are possible price/product lines\n\t// Possible price lines: \n\t// \t\t- Have a price on the right 1/2 of the receipt\n\t\n\tvar imageMidX = (image._leftX + image._rightX) / 2;\n\tvar things_bought = [];\n\tfor (var i = 0; i < image._arrayOfLines.length; i++) {\n\t\tvar item = {}\n\t\tvar lastIndexUntilPrice = 99999;\n\t\tfor (var k = 0; k < image._arrayOfLines[i]._arrayOfBlocks.length; k++) {\n\t\t\tvar currBlock = image._arrayOfLines[i]._arrayOfBlocks[k];\n\n\t\t\tif (currBlock._midX > imageMidX) {\n\t\t\t\t// Block is on the right side\n\t\t\t\tif (getNumberVersion(currBlock._contents) != false) {\n\t\t\t\t\tif (k < lastIndexUntilPrice) {\n\t\t\t\t\t\tlastIndexUntilPrice = k;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (item.price != undefined) {\n\t\t\t\t\t\t// Didnt picked up the \".\"\n\t\t\t\t\t\titem.price = item.price + (\".\" + currBlock._contents);\n\t\t\t\t\t} else {\n\t\t\t\t\t\titem.price = getNumberVersion(currBlock._contents);\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\n\t\tif (item.price != undefined) {\n\t\t\tif (lastIndexUntilPrice > image._arrayOfLines[i]._arrayOfBlocks.length) {\n\t\t\t\tconsole.log(\"Something went wrong. Aborting\")\n\t\t\t\tconsole.log(\"lastIndexUntilPrice = \" + lastIndexUntilPrice)\n\t\t\t}\n\t\t\t// Need to extract all of the things until lastIndexUntilPrice\n\t\t\tfor (var k = 0; k < lastIndexUntilPrice; k++) {\n\t\t\t\tvar currBlock = image._arrayOfLines[i]._arrayOfBlocks[k];\n\t\t\t\tif (item.name == undefined) {\n\t\t\t\t\titem.name = currBlock._contents\n\t\t\t\t} else {\n\t\t\t\t\titem.name = item.name + \" \" + currBlock._contents;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (item.price != undefined && item.name != undefined) {\n\t\t\t// Push a copy\n\t\t\tthings_bought.push(JSON.parse(JSON.stringify(item)));\n\t\t\titem = {}\n\t\t}\n\t}\n\n\tconsoleLogArray(things_bought);\n\n\treturn \"Done\"\n}", "function mergeFootnoteDivs(tinymceBody){\n var foonoteDivs = tinymceBody.getElementsByClassName(\"footnotes\");\n var i;\n var indexOfLastFnDiv = foonoteDivs.length - 1;\n for(i = 0; i < indexOfLastFnDiv; i++){\n moveOlsFromOneFnDivToAnotherStackingUpwards(foonoteDivs.item(indexOfLastFnDiv), foonoteDivs.item(i));\n }\n deleteAllButOneFootnoteDiv(tinymceBody, foonoteDivs);\n}", "function processNote($a, ratio) {\n var noteWidth = ratio ? parseInt(ratio, 10) : 4;\n var mainWidth = 12 - noteWidth;\n // assume blockquote being the note container\n var note = $a.closest(\"blockquote\");\n // default to the parent\n if(note.size() == 0) note = $a.parent();\n var sibling = note.prev();\n var row = $(\"<div>\").addClass(\"row\");\n var c1 = $(\"<div>\").addClass(\"col-md-\" + mainWidth).appendTo(row);\n var c2 = $(\"<div>\").addClass(\"col-md-\" + noteWidth).appendTo(row);\n note.after(row);\n note.detach().appendTo(c2);\n sibling.detach().appendTo(c1);\n note.css({\n fontSize: \"85%\",\n marginLeft: 20,\n });\n }", "function addBlock(label) {\n // make sure label is unique identifier\n var newlabel = label;\n var counter = 1;\n var found;\n do {\n found = topBlock.forEachChild(function(child){\n if (child.getLabel() == newlabel) {\n newlabel = label + counter;\n counter += 1;\n return false;\n }\n return true;\n });\n } while (!found);\n label = newlabel;\n\n // create the new block; pass it a handle to the top-level (i.e. its parent)\n // logic block so that it can access other procedures in the program\n var element = new FlowBlockVisual(ctx,label,topBlock.getLogic());\n element.setHeightChangeCallback(resizeCanvas);\n topBlock.addChild(element);\n modified = true;\n drawScreen();\n return element;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
searches the entire frameset and returns the frame with name frmname
function findFrame(w, frmname) { var res = null; if (frmname != '') { res = w.frames[frmname]; // if it's not in the current window // search the sub-frames if (res == null) { var L = w.frames.length; var i; for (i = 0; i < L; i++) { res = findFrame(w.frames[i], frmname); if (res != null) { break; } } } } else { result = this; } return res; }
[ "async getFrame(page, name) {\n return await this.getEvalFrame(page.mainFrame(), { frame: name });\n }", "function frameType(frame) {\n var frameClass = frame.attr(\"class\");\n if (frameClass.indexOf(\"readyFrame\") != -1)\n return \"readyFrame\";\n else if (frameClass.indexOf(\"ackRRFrame\") != -1)\n return \"ackRRFrame\";\n else if (frameClass.indexOf(\"ackREJFrame\") != -1)\n return \"ackREJFrame\";\n else if (frameClass.indexOf(\"ackPollFrame\") != -1)\n return \"ackPollFrame\";\n else if (frameClass.indexOf(\"transmittedFrame\") != -1)\n return \"transmittedFrame\";\n else if (frameClass.indexOf(\"infoFrame\") != -1)\n return \"infoFrame\";\n else if (frameClass.indexOf(\"ackFinalFrame\") != -1)\n return \"ackFinalFrame\";\n}", "function frameIn(frame){\n // curatam clasa active din meniu daca exista\n cleanActiveFrame();\n\n // element activ in meniu\n var element = document.getElementById(frame);\n element.classList.add(\"active\");\n}", "function getFormByFormId(id) {\n var formId;\n var formName;\n var formParent;\n var availableTabs;\n var docSelectorForWebForms;\n\n if (id === \"F16\") {\n formId = 'F16';\n formName = 'INFO_GENERIC';\n formParent = 'formInfo';\n } else if (id === \"F21\") {\n formId = id;\n formName = 'VISIT';\n formParent = 'formInfo';\n } else if (id === \"F22\" || id === \"F23\" || id === \"F24\") {\n formId = id;\n formName = 'EVENT_FORM';\n formParent = 'formInfo';\n } else if (id === \"F25\") {\n formId = id;\n formName = 'VISIT_MANAGER';\n formParent = 'formInfo';\n } else if (id === \"F27\") {\n formId = id;\n formName = 'GALLERY';\n formParent = 'formInfo';\n } else if (id === \"F51\") {\n formId = id;\n formName = 'REVIEW_UD_ARC';\n formParent = 'formReview';\n } else if (id === \"F52\") {\n formId = id;\n formName = 'REVIEW_UD_NODE';\n formParent = 'formReview';\n } else if (id === \"F53\") {\n formId = id;\n formName = 'REVIEW_UD_CONNEC';\n formParent = 'formReview';\n } else if (id === \"F54\") {\n formId = id;\n formName = 'REVIEW_UD_GULLY';\n formParent = 'formReview';\n } else if (id === \"F55\") {\n formId = id;\n formName = 'REVIEW_WS_ARC';\n formParent = 'formReview';\n } else if (id === \"F56\") {\n formId = id;\n formName = 'REVIEW_WS_NODE';\n formParent = 'formReview';\n } else if (id === \"F57\") {\n formId = id;\n formName = 'REVIEW_WS_CONNEC';\n formParent = 'formReview';\n } else {\n formId = 'F11';\n formName = 'INFO_UD_NODE';\n formParent = 'formInfo';\n elementSelectorForWebForms = 'v_ui_element_x_node';\n docSelectorForWebForms = 'v_ui_doc_x_node';\n }\n\n var retorn = {};\n retorn.formId = formId;\n retorn.formName = formName;\n retorn.formParent = formParent;\n retorn.formTabs = _getTabsForFormID(formId);\n return retorn;\n }", "function findFormByTitle(title){\n for (var i in forms) {\n if (forms[i].title === title) {\n return forms[i];\n }\n }\n return null;\n }", "get_frame(slug) {\n return this.nav_functions.get(slug)();\n }", "function getFrames() {\n\t\tvar result = [];\n\t\tvar frames = targetWindow.document.getElementsByTagName(\"iframe\");\n\t\tforEach(frames, function(frame) {\n\t\t\tresult.push({\n\t\t\t\tsrc: frame.src,\n\t\t\t\tname: frame.name,\n\t\t\t\tid: frame.id,\n\t\t\t\tposition: flatten(frame.getBoundingClientRect())\n\t\t\t});\n\t\t});\n\t\treturn result;\n\t}", "getMacro(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const inst = this.stack[i]._getMacro(name);\n if (inst !== null) {\n return inst;\n }\n }\n return null;\n }", "function getFrameData(tab, frameId) {\n var framesOfTab = frames.get(tab);\n if (framesOfTab) {\n if (frameId in framesOfTab) {\n return framesOfTab[frameId];\n }\n if (frameId !== -1) {\n return framesOfTab[0];\n }\n }\n return null;\n }", "function toggleFrames(imgName) {\n\n\t//Show home page if img name is empty\n\tif(imgName === '')\n\t{\n\t\tparent.frame2.location=urls[\"home\"];\n\t\treturn;\n\t}\n\t\n\t//Update frame source if empty\n\tif(imgName !== 'frame2' && imgName !== 'settings')\n\t{\n\t\tvar frameSrc = parent.document.getElementById(imgName + 'Frame').src;\n\t\tif(frameSrc == 'undefined' || frameSrc === '' || frameSrc === window.location.origin + \"/frame.html\")\n\t\t\tparent.document.getElementById(imgName + 'Frame').src = urls[imgName];\n\t}\n\t\n\t//Get the content frameset\n var frameset = parent.document.getElementById(\"content\");\n\tvar count=0;\n\tframeSetCols = \"\";\n\tvar frameIndex = -1;\n\t\n\t//Update the frameset cols, to make the frame corresponding to this imgName visible\n\tfor(i=1;i<frameset.children.length - 1;i++)\n\t{\n\t var frame = frameset.children[i];\n\t\tif(frameSetCols !== '')\n\t\t{\n\t\t\tframeSetCols += \",\"\n\t\t\tframeIndex = i;\n\t\t}\n\t\tif(frame.id === imgName + 'Frame' || frame.id === imgName)\n\t\t{\n\t\t\tframeSetCols += \"*\";\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tframeSetCols += \"0%\";\n\t\t}\n\t\t\n\t}\n\tframeset.cols= \"5%,\" + frameSetCols + \",5%\";\n}", "function getParentFormName(elt) {\n\t\twhile (elt && elt.nodeName && elt.nodeName.toUpperCase() !== 'HTML' && elt.nodeName.toUpperCase() !== 'FORM') {\n\t\t\telt = elt.parentNode;\n\t\t}\n\t\tif (elt && elt.nodeName && elt.nodeName.toUpperCase() === 'FORM') {\n\t\t\treturn getFormElementName(elt);\n\t\t}\n\t}", "getFrameAuthor(frameIndex) {\r\n return this.meta.current.fsid;\r\n }", "function widgetFrameLoaded(id) {\n\n //iframe DOM object\n var frameObj = document.getElementById(\"customFieldFrame_\" + id);\n\n // flag to show or hide console logs\n var enableLog = false;\n\n // if the iframe not full rendered don't do anything at it first\n if ( !frameObj.hasClassName('custom-field-frame-rendered') ) {\n enableLog && console.log('Not rendered yet for', id);\n return;\n }\n\n //register widget to JCFServerCommon object\n //useful while debugging forms with widgets\n JCFServerCommon.frames[id] = {};\n JCFServerCommon.frames[id].obj = frameObj;\n var src = frameObj.src;\n\n JCFServerCommon.frames[id].src = src;\n JCFServerCommon.submitFrames = [];\n\n //to determine whether submit message passed form submit or next page\n var nextPage = true;\n //to determine which section is open actually\n var section = false;\n\n //we are changing iframe src dynamically\n //at first load iframe does not have src attribute that is why it behaves like it has form's URL\n //to prevent dublicate events if it is form url return\n // if(src.match('/form/')) {\n // console.log(\"returning from here\");\n // return;\n // }\n\n var referer = src;\n //form DOM object\n var thisForm = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n\n //detect IE version\n function getIEVersion() {\n var match = navigator.userAgent.match(/(?:MSIE |Trident\\/.*; rv:)(\\d+)/);\n return match ? parseInt(match[1]) : undefined;\n }\n\n // check a valid json string\n function IsValidJsonString(str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n }\n\n //send message to widget iframe\n function sendMessage(msg, id, to) {\n\n var ref = referer;\n if(to !== undefined) { //to option is necesaary for messaging between widgets and themes page\n ref = to;\n }\n\n if (document.getElementById('customFieldFrame_' + id) === null) {\n return;\n }\n if (navigator.userAgent.indexOf(\"Firefox\") != -1) {\n XD.postMessage(msg, ref, getIframeWindow(window.frames[\"customFieldFrame_\" + id]));\n } else {\n if (getIEVersion() !== undefined) { //if IE\n XD.postMessage(msg, ref, window.frames[\"customFieldFrame_\" + id]);\n } else {\n XD.postMessage(msg, ref, getIframeWindow(window.frames[\"customFieldFrame_\" + id]));\n }\n }\n }\n\n window.sendMessage2Widget = sendMessage;\n\n //function that gets the widget settings from data-settings attribute of the iframe\n function getWidgetSettings() {\n var el = document.getElementById('widget_settings_' + id);\n return (el) ? el.value : null;\n }\n\n // function to check if a widget is required\n function isWidgetRequired(id) {\n var classNames = document.getElementById('id_' + id).className;\n return classNames.indexOf('jf-required') > -1;\n }\n\n //send message to widget iframe and change data-status to ready\n function sendReadyMessage(id) {\n\n var background = navigator.userAgent.indexOf(\"Firefox\") != -1 ? window.getComputedStyle(document.querySelector('.form-all'), null).getPropertyValue(\"background-color\") : getStyle(document.querySelector('.form-all'), \"background\");\n var fontFamily = navigator.userAgent.indexOf(\"Firefox\") != -1 ? window.getComputedStyle(document.querySelector('.form-all'), null).getPropertyValue(\"font-family\") : getStyle(document.querySelector('.form-all'), \"font-family\");\n //send ready message to widget\n //including background-color, formId, questionID and value if it is edit mode (through submissions page)\n\n var msg = {\n type: \"ready\",\n qid: id + \"\",\n formID: document.getElementsByName('formID')[0].value,\n required: isWidgetRequired(id),\n background: background,\n fontFamily: fontFamily\n };\n\n // if settings not null, include it\n var _settings = getWidgetSettings();\n if ( _settings && decodeURIComponent(_settings) !== '[]' ) {\n msg.settings = _settings;\n }\n\n // data-value attribute is set if form is in editMode.\n var wframe = document.getElementById('customFieldFrame_' + id);\n\n // helper function\n function _sendReadyMessage(id, msg) {\n // put a custom class when ready\n $(document.getElementById('customFieldFrame_' + id)).addClassName('frame-ready');\n\n // send ready message\n sendMessage(JSON.stringify(msg), id);\n }\n\n // make sure we get the data first before sending ready message, only when msg.value undefined\n var isEditMode = ((document.get.mode == \"edit\" || document.get.mode == \"inlineEdit\" || document.get.mode == 'submissionToPDF') && document.get.sid);\n if ( isEditMode ) {\n // if edit mode do some polling with timeout\n // interval number for each check in ms\n var interval = 50;\n // lets give the check interval a timeout in ms\n var timeout = 5000;\n // will determine the timeout value\n var currentTime = 0;\n\n var editCheckInterval = setInterval(function(){\n // clear interval when data-value attribute is set on the iframe\n // that means the 'getSubmissionResults' request has now the question data\n if ( wframe.hasAttribute('data-value') || (currentTime >= timeout) ) {\n // clear interval\n clearInterval(editCheckInterval);\n\n // renew value, whether its empty\n msg.value = wframe.getAttribute(\"data-value\");\n\n // send message\n enableLog && console.log('Ready message sent in', currentTime, msg);\n _sendReadyMessage(id, msg);\n }\n\n currentTime += interval;\n }, interval);\n } else {\n // set value\n msg.value = wframe.getAttribute(\"data-value\");\n\n // send message\n enableLog && console.log('Sending normal ready message', msg);\n _sendReadyMessage(id, msg);\n }\n }\n\n // expose ready message function\n window.JCFServerCommon.frames[id]['sendReadyMessage'] = sendReadyMessage;\n\n //bind receive message event\n //a message comes from form\n XD.receiveMessage(function(message) {\n\n // don't parse some unknown text from third party api of widgets like google recapthca\n if ( !IsValidJsonString(message.data) ) {\n return;\n }\n\n //parse message\n var data = JSON.parse(message.data);\n\n // filter out events from other frames which cause form hang up\n // specially if there are multiple widgets on 1 form\n if ( parseInt(id) !== parseInt(data.qid) ) {\n return;\n }\n\n //sendSubmit\n if (data.type === \"submit\") {\n enableLog && console.log('widget submit', document.getElementById(\"input_\" + data.qid));\n // make sure thats its not an oEmbed widget\n // oEmbed widgets has no hidden input to read\n if ( document.getElementById(\"input_\" + data.qid) )\n {\n if (typeof data.value === 'number') {\n data.value = data.value + \"\";\n }\n var required = $(document.getElementById(\"input_\" + data.qid)).hasClassName('widget-required') || $(document.getElementById(\"input_\" + data.qid)).hasClassName('validate[required]');\n var input_id_elem = document.getElementById(\"input_\" + data.qid);\n\n // if the element/question was set to required, we do some necessary validation to display and error or not\n if (required) {\n if ( (data.hasOwnProperty('valid') && data.valid === false) && JotForm.isVisible(document.getElementById(\"input_\" + data.qid))) {\n input_id_elem.value = \"\";\n\n // put a custom error msg if necessary, only if error object is present\n var req_errormsg = \"This field is required\";\n if ( typeof data.error !== 'undefined' && data.error !== false ) {\n req_errormsg = ( data.error.hasOwnProperty('msg') ) ? data.error.msg : req_errormsg;\n }\n\n JotForm.errored(input_id_elem, req_errormsg);\n //return;\n } else {\n JotForm.corrected(input_id_elem);\n if (data.value !== undefined) {\n input_id_elem.value = data.value;\n } else {\n input_id_elem.value = \"\";\n }\n }\n } else {\n\n // if not required and value property has a value set\n // make it as the hidden input value\n if (data && data.hasOwnProperty('value') && data.value !== false) {\n input_id_elem.value = data.value;\n } else {\n input_id_elem.value = '';\n input_id_elem.removeAttribute('name');\n }\n }\n }\n\n // flag the iframe widget/oEmbed widget already submitted\n if ( JCFServerCommon.submitFrames.indexOf(parseInt(data.qid)) < 0 ) {\n JCFServerCommon.submitFrames.push(parseInt(data.qid));\n }\n\n // check for widget required/errors and prevent submission\n var allInputs = $$('.widget-required, .widget-errored');\n var sendSubmit = true;\n for (var i = 0; i < allInputs.length; i++) {\n if (allInputs[i].value.length === 0 && JotForm.isVisible(allInputs[i])) {\n sendSubmit = false;\n }\n }\n //if widget is made required by condition\n // var requiredByConditionInputs = document.getElementsByClassName(\"form-widget validate[required]\");\n // console.log(\"requiredByConditionInputs\". requiredByConditionInputs.length);\n\n // for(var i=0; i<requiredByConditionInputs.length; i++) {\n // if(requiredByConditionInputs[i].value.length === 0 && JotForm.isVisible(requiredByConditionInputs[i])) {\n // sendSubmit = false;\n // }\n // }\n\n if (!nextPage) {\n enableLog && console.log('next page', nextPage);\n if (JotForm.validateAll() && sendSubmit) {\n enableLog && console.log('sendSubmit', nextPage, sendSubmit);\n var tf = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n // Don't submit if form has Stripe. Stripe submits the form automatically after credit card is tokenized\n var isEditMode = [\"edit\", \"inlineEdit\", \"submissionToPDF\"].indexOf(document.get.mode) > -1;\n if (!(typeof Stripe === \"function\" && JotForm.isPaymentSelected() && !isEditMode)) {\n // we will submit the form if all widgets already submitted\n // because some widgets need to do their own processes before sending submit\n // check if all frames submitted a message, thats the time we fire a form submit\n if ( $$('.custom-field-frame').length === JCFServerCommon.submitFrames.length ) {\n enableLog && console.log('All frames submitted', JCFServerCommon.submitFrames);\n _submitLast.submit(tf, 50); //submit form with 50 ms delay, submitting only the last call\n } else {\n enableLog && console.log('Not all frames submitted', JCFServerCommon.submitFrames);\n }\n }\n }\n } else {\n\n // var proceedSection = true;\n // section.select(\".widget-required\").each(function(inp) {\n // if (inp.value.length === 0) {\n // proceedSection = false;\n // }\n // });\n\n // //@diki\n // //validate current section\n // var sectionValidated = true;\n // section.select('*[class*=\"validate\"]').each(function(inp) {\n // if (inp.validateInput === undefined) {\n // return; /* continue; */\n // }\n // if (!( !! inp.validateInput && inp.validateInput())) {\n // sectionValidated = JotForm.hasHiddenValidationConflicts(inp);\n // }\n // });\n\n // if (proceedSection && sectionValidated) {\n // if (window.parent && window.parent != window) {\n // window.parent.postMessage('scrollIntoView', '*');\n // }\n // if (JotForm.nextPage) {\n // JotForm.backStack.push(section.hide()); // Hide current\n // JotForm.currentSection = JotForm.nextPage.show();\n // //Emre: to prevent page to jump to the top (55389)\n // if (typeof $this !== \"undefined\" && !$this.noJump) {\n // JotForm.currentSection.scrollIntoView(true);\n // }\n // JotForm.enableDisableButtonsInMultiForms();\n // } else if (section.next()) { // If there is a next page\n // if(section.select(\".widget-required\").length > 0) {\n // JotForm.backStack.push(section.hide()); // Hide current\n // // This code will be replaced with condition selector\n // JotForm.currentSection = section.next().show();\n // JotForm.enableDisableButtonsInMultiForms();\n // }\n // }\n // JotForm.nextPage = false;\n // }\n }\n }\n\n //sendData\n if (data.type === \"data\") {\n document.getElementById(\"input_\" + data.qid).value = data.value;\n JotForm.triggerWidgetCondition(data.qid);\n JotForm.triggerWidgetCalculation(data.qid);\n }\n\n //show/hide form errors\n if ( data.type === \"errors\" ) {\n var inputElem = document.getElementById(\"input_\" + data.qid);\n // check the action\n if ( data.action === 'show' ) {\n // show error\n if ( JotForm.isVisible(inputElem) ) {\n JotForm.corrected(inputElem);\n inputElem.value = '';\n inputElem.addClassName('widget-errored');\n JotForm.errored(inputElem, data.msg);\n }\n } else if ( data.action === 'hide' ) {\n // hide error\n inputElem.removeClassName('widget-errored');\n JotForm.corrected(inputElem);\n }\n }\n\n //requestFrameSize\n if (data.type === \"size\") {\n var width = data.width,\n height = data.height;\n\n if (width !== undefined && width !== null) {\n if (width === 0 || width === \"0\") {\n width = \"auto\";\n } else {\n width = width + \"px\";\n }\n document.getElementById('customFieldFrame_' + data.qid).style.width = width;\n }\n if (height !== undefined && height !== null) {\n document.getElementById('customFieldFrame_' + data.qid).style.height = height + \"px\";\n //for IE8 : also update height of li element\n if ( getIEVersion() !== undefined ) {\n document.getElementById('cid_' + data.qid).style.height = height + \"px\";\n }\n }\n }\n\n //replaceWidget\n if (data.type === \"replace\") {\n var inputType = data.inputType,\n isMobile = data.isMobile;\n\n var parentDiv = $(\"customFieldFrame_\" + data.qid).up(),\n inputName = $(\"input_\" + data.qid).readAttribute(\"name\");\n\n //remove frame\n $(\"customFieldFrame_\" + data.qid).remove();\n $(\"input_\" + data.qid).up().remove();\n var newInput = \"\";\n switch (inputType) {\n case \"control_fileupload\":\n var tf = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n tf.setAttribute('enctype', 'multipart/form-data');\n\n if (!isMobile) {\n newInput = '<input class=\"form-upload validate[upload]\" type=\"file\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\" file-accept=\"pdf, doc, docx, xls, xlsx, csv, txt, rtf, html, zip, mp3, wma, mpg, flv, avi, jpg, jpeg, png, gif\"' +\n 'file-maxsize=\"10240\">';\n }\n // console.log(\"widget is mobile\", widget.isMobile);\n parentDiv.insert(newInput);\n break;\n case \"control_textbox\":\n newInput = '<input class=\"form-textbox\" type=\"text\" data-type-\"input-textbox\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\">';\n parentDiv.insert(newInput);\n break;\n case \"control_textarea\":\n newInput = '<textarea class=\"form-textarea\" type=\"text\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\" cols=\"40\" rows=\"6\"></textarea>';\n parentDiv.insert(newInput);\n break;\n default:\n break;\n }\n }\n\n }, document.location.protocol + '//' + frameObj.src.match(/^(ftp:\\/\\/|https?:\\/\\/)?(.+@)?([a-zA-Z0-9\\.\\-]+).*$/)[3]);\n\n // immediately send the settings to widget\n enableLog && console.log('sending settings', getWidgetSettings(), (new Date()).getTime());\n sendMessage(JSON.stringify({\n type: \"settings\",\n settings: getWidgetSettings()\n }), id);\n\n //if widget is not visible do not send ready message (it may be on next page)\n //instead send ready message on next page click\n var widgetSection = JotForm.getSection(frameObj);\n\n if (frameObj && JotForm.isVisible(widgetSection) && JotForm.isVisible(frameObj) && typeof frameObj.up('.form-section-closed') === 'undefined') {\n sendReadyMessage(id);\n }\n\n //on form submit\n Event.observe(thisForm, 'submit', function(e) {\n if (document.getElementById('customFieldFrame_' + id) === null) {\n return;\n }\n Event.stop(e);\n nextPage = false;\n sendMessage(JSON.stringify({\n type: \"submit\",\n qid: id + \"\"\n }), id + \"\");\n });\n\n //on pagebreak click\n $$(\".form-pagebreak-next\").each(function(b, i) {\n\n $(b).observe('click', function(e) {\n\n //get the section where the button is clicked\n //this is to identify what section we were previously in\n //so that we only need to send the submit message to that previous widget from the previous page\n section = this.up('.form-section');\n nextPage = true;\n if (section.select(\"#customFieldFrame_\" + id).length > 0) {\n enableLog && console.log('Sending submit message for iframe id', id, \"from section\", this.up('.form-section'), \"and iframe\", frameObj);\n sendMessage(JSON.stringify({\n type: \"submit\",\n qid: id + \"\"\n }), id + \"\");\n Event.stop(e);\n }\n\n //send ready message to the next widget of the page only if the section is fully visible\n //we need to get the actual frameobj and section of the next widget on the next page\n //for us to send the ready for that widget\n var checkIntevarl = setInterval(function(){\n\n // get the actual widget attach to this event\n frameObj = document.getElementById(\"customFieldFrame_\" + id);\n if ( frameObj ) {\n // get its form section\n section = $(frameObj).up('.form-section');\n\n if (frameObj && JotForm.isVisible(section) && JotForm.isVisible(frameObj)) {\n // if fframe and section is visible\n // throw ready message to every widget that was inside of it\n clearInterval(checkIntevarl);\n enableLog && console.log('Sending ready message for iframe id', id, \"from section\", section);\n sendReadyMessage(id);\n }\n } else {\n // missing iframe - it was replace by a normal question field\n // usually happens on ie8 browsers - for widgets that using JFCustomWidget.replaceWidget method\n clearInterval(checkIntevarl);\n }\n }, 100);\n });\n });\n}", "function findSuperframeWindowClicked(x){\n for(var i = 0; i < windowdata.length; i++){\n if(((i * windowSize) / contigLength) * superframewidth < x &&\n (((i + 1) * windowSize) / contigLength) * superframewidth > x){\n displaysuperframesegment(i);\n highlightBox(i)\n }\n }\n}", "lookupFrameIndex(frameId, pauseEvent) {\n const currentFrame = this._frameHandles.get(frameId);\n if (!currentFrame || !currentFrame.callFrameId || !pauseEvent) {\n return -1;\n }\n return pauseEvent.callFrames.findIndex(frame => frame.callFrameId === currentFrame.callFrameId);\n }", "static getStackFrame(id) {\n return stacks[id]\n }", "static build(frame, logger) {\n if(frame.template === INTRO_FRAME_TEMPLATE) {\n return new IntroFrame(frame, logger);\n } else if(frame.template === STATEMENTS_FRAME_TEMPLATE) {\n return new StatementsBodyFrame(frame, logger);\n } else if(frame.template === SUMMARY_COUNT_FRAME_TEMPLATE) {\n return new SummaryFrameCount(frame, logger);\n } else if(frame.template === LIKERT_FRAME_TEMPLATE) {\n return new LikertFrame(frame, logger);\n } else if(frame.template === SELF_REPORT_FRAME_TEMPLATE) {\n return new SelfReportFrame(frame, logger);\n } else if(frame.template === CONSENT_FRAME_TEMPLATE) {\n return new ConsentDisclosureFrame(frame, logger);\n } else if (frame.template === END_FRAME_TEMPLATE) {\n return new EndFrame(frame, logger);\n } else {\n throw new Error('Frame template not recognized ' + frame.template);\n }\n }", "function getFormElem() {\r\n\t\treturn _self.form.getFormElem();\r\n\t}", "function checkIfFramed()\n{\n var anchors, i;\n\n if (window.parent != window) { // Only if we're not the top document\n anchors = document.getElementsByTagName('a');\n for (i = 0; i < anchors.length; i++)\n if (!anchors[i].hasAttribute('target'))\n\tanchors[i].setAttribute('target', '_parent');\n document.body.classList.add('framed'); // Allow the style to do things\n }\n}", "function uploadDone(name, myRId) {\r\n var frame = frames[name];\r\n if (frame) {\r\n var ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n if (ret.length) {\r\n alert(ret);\r\n frame.document.getElementsByTagName(\"body\")[0].innerHTML = \"\";\r\n showRecordView(myRId);\r\n }\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the given data into the given destination object
function set_data(dest, key, data, context) { // If there is a transformation function, call the function. if (typeof context.transform == 'function') { dest = dest || {} data = context.transform(data, context.src, dest, context.srckey, context.destkey) } // See if data is null and there is a default if (typeof context.default !== 'undefined' && (data == null || typeof data == 'undefined')) { // There is a default function, call the function to set the default if (typeof context.default == 'function') { dest = dest || {} data = context.default(context.src, context.srckey, dest, context.destkey) } // The default is a specific value else data = context.default } // Set the object to the data if it is not undefined if (typeof data !== 'undefined' && key && key.name) { // Set the data if the data is not null, or if the 'allow nulls' key is set, or if there is a default (in the case of default=null, make sure to write this out) if (data !== null || key.nulls || (typeof context.default !== 'undefined' && context.default == null)) { dest = dest || {} dest[key.name] = data } } // Return the dest variable back to the caller. return dest }
[ "set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }", "setTransactionDataObject (transactionData)\r\n {\r\n this.transactionData=transactionData;\r\n }", "set origData(val) {\n this._origData = val;\n }", "function update_obj(dest, key, data, keys, context)\n{\n // There are further instructions remaining - we will need to recurse\n if (keys.length) {\n // There is a pre-existing destination object. Recurse through to the object key\n if (dest !== null && typeof dest !== 'undefined') {\n let o = update(dest[key.name], data, keys, context)\n if (o !== null && typeof o !== 'undefined')\n dest[key.name] = o\n }\n // There is no pre-existing object. Check to see if data exists before creating a new object\n else {\n // Check to see if there is a value before creating an object to store it\n let o = update(null, data, keys, context)\n if (o !== null) {\n dest = {}\n dest[key.name] = o\n }\n }\n }\n // This is a leaf. Set data into the dest\n else\n dest = set_data(dest, key, data, context)\n\n return dest\n}", "function applyData(object, data) {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n object[key] = data[key];\n }\n }\n }", "function setObj(addr, obj) {\n console.log(addr);\n dbContract.set(addr, JSON.stringify(obj));\n}", "setResourceData(state, {resource, data}) {\n _.forIn(data, (value, key) => {\n resource[key] = value\n })\n }", "setData(data) {\n if (!data) {\n console.log('oops.. no data');\n return;\n }\n\n // console.log('got data...', data);\n this.data = data;\n if (this.script) {\n document.body.removeChild(this.script);\n this.script = undefined;\n }\n\n this.preloadImages(this.data.items);\n }", "static async putAssetData(ctx, assetKey, assetData) {\n\t\t//Convert input JSON object to buffer and store it to blockchain\n\t\tlet dataBuffer = Buffer.from(JSON.stringify(assetData));\n\t\tawait ctx.stub.putState(assetKey, dataBuffer);\n\t}", "function setRoute(route, dataObj) {\n var path = route,\n data = [];\n if (dataObj !== null && dataObj !== undefined) {\n path += \"?\";\n for (var prop in dataObj) {\n if (prop !== 'undefined' && dataObj.hasOwnProperty(prop)) {\n data.push(prop + '=' + encodeURIComponent(dataObj[prop]));\n }\n }\n path += data.join('&');\n }\n\n //console.log('Router, setting URL fragment to: ' + path);\n\n updateURLFragment(path);\n }", "_setData() {\n this._global[this._namespace] = this._data;\n }", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "setUserData (user = {}) {\n this.memory.set(this.getName(\"userData\"), user);\n }", "function SET_PAGE_DATA(state, value) {\n state.page.data = value;\n}", "function setDataToBeDeleted(destination,source){\n var devices = getDevicesNodeJSON();\n\tvar allline =[];\n\tvar dstArr2 = destination.split(\".\");\n\tvar srcArr2 = source.split(\".\");\n\tfor(var i = 0; i < devices.length; i++){\n\t\tif(dstArr2[0] == devices[i].ObjectPath || srcArr2[0] == devices[i].ObjectPath){\n\t\t\tallline = gettargetmap(devices[i].ObjectPath,allline);\n\t\t}\n\t}\n\tvar linkData = \"\";\n\tfor(var t=0; t<allline.length; t++){\n\t\tvar source = allline[t].Source;\t\n\t\tvar destination = allline[t].Destination;\t\n\t\tvar srcArr = source.split(\".\");\n\t\tvar dstArr = destination.split(\".\");\n\t\tvar portobject;\n\t\tvar portobject2;\n\t\tvar srcName = \"\";\n\t\tvar dstName = \"\";\n\t\tvar srcPortName = \"\";\n\t\tvar dstPortName = \"\";\n\t\tif((srcArr[0] == srcArr2[0] && dstArr[0] == dstArr2[0]) || (dstArr[0] == srcArr2[0] && srcArr[0] == dstArr2[0])){\n\t\t\tportobject = getPortObject2(source);\n\t\t\tportobject2 = getPortObject2(destination);\n\t\t\tif(portobject.PortName != \"\"){\n\t\t\t\tsrcPortName = portobject.PortName;\n\t\t\t}else{\n\t\t\t\tvar pathArr = source.split(\"_\");\n\t\t\t\tvar portPath = pathArr[pathArr.length-1].split(\"_\");\n\t\t\t\tsrcPortName = pathArr[pathArr.length-1];\n\t\t\t\tif(portPath[0] != \"Port\"){\n\t\t\t\t\tsrcPortName = \"Port_\"+portPath[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(portobject2.PortName != \"\"){\n\t\t\t\tdstPortName = portobject2.PortName;\n\t\t\t}else{\n\t\t\t\tvar pathArr = destination.split(\"_\");\n\t\t\t\tvar portPath = pathArr[pathArr.length-1].split(\"_\");\n\t\t\t\tdstPortName = pathArr[pathArr.length-1];\n\t\t\t\tif(portPath[0] != \"Port\"){\n\t\t\t\t\tdstPortName = \"Port_\"+portPath[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar srcDevice = getDeviceObject2(srcArr[0]);\n\t\t\tvar dstDevice = getDeviceObject2(dstArr[0]);\n\t\t\tif(srcDevice.DeviceName != \"\"){\n\t\t\t\tsrcName = srcDevice.DeviceName;\n\t\t\t}else{\n\t\t\t\tsrcName = srcDevice.ObjectPath;\n\t\t\t}\n\t\t\tif(dstDevice.DeviceName != \"\"){\n\t\t\t\tdstName = dstDevice.DeviceName;\n\t\t\t}else{\n\t\t\t\tdstName = dstDevice.ObjectPath;\n\t\t\t}\n\t\t\tvar path = source + \"::\" + destination;\n\t\t\tvar linkName = srcName + \"->\" + srcPortName + \"<-->\" + dstName + \"->\" + dstPortName;\n\t\t\tlinkData += \"<tr><td><input type='checkbox' class='linkiddelete' did='\"+path+\"' onclick='selectAllConnectivivty(this)'/></td>\";\n\t\t\tlinkData += \"<td><span>\"+linkName+\"</span></td></tr>\";\n\t\t}\n\t}\n\t$('#deleteLinkTable > tbody').empty().append(linkData)\n}", "function setPortObject(port,action){\n\tif(action == \"source\"){\n\t\tportspeedflag = true;\n\t\tportflag = true;\n\t\tsourcePath = port.ObjectPath;\n\t\tif(port.SwitchInfo != \"\"){\n\t\t\tvar switchArr2 = port.SwitchInfo.split(\"^\");\n\t\t\tsourceSwitch = switchArr2[0];\n\t\t}\n\t}else{\n\t\tportspeedflag2 = true;\n\t\tportflag2 = true;\n\t\tdstPath = port.ObjectPath;\n\t\tif(port.SwitchInfo != \"\"){\n\t\t\tvar switchArr2 = port.SwitchInfo.split(\"^\");\n\t\t\tdestSwitch = switchArr2[0];\n\t\t}\n\t}\n}", "setDestino(destino) {\n this.destino = destino;\n }", "update ( data ) {\n if ( !this.deepEqual(data, this.data) ) {\n Object.assign(this.data, data);\n this.notify();\n }\n }", "function set_object_props(obj, from, whitelist) {\n\tvar wl = whitelist.split(\",\");\n\tfor(var i=0; i<wl.length; i++) {\n\t\tvar prop = wl[i];\n\t\tif (undefined !== obj[prop] && undefined !== from[prop]) {\n\t\t\t//console.log(\"WL update prop %s obj:%s -> to %s\", prop, obj[prop], from[prop]);\n\t\t\tobj[prop] = from[prop];\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that the experiment branch is set and returns it.
function ensureExperimentBranch() { return new Promise(resolve => { // TESTING CODE try { let forcedBranch = Services.prefs.getCharPref("browser.urlbar.experiment.unified-urlbar.branch"); resolve(forcedBranch); } catch (ex) {} let experiments = Experiments.instance(); // This experiment has 3 user groups: // * "control" : Users with default search bar setup. // No UI changes. // * "customized": Users who customized the search bar position. // Add one-off buttons. // * "unified" : Add one-off search buttons to the location bar and // customize away the search bar. let branch = experiments.getActiveExperimentBranch(); if (branch) { resolve(branch); return; } let placement = CustomizableUI.getPlacementOfWidget("search-container"); if (!placement || placement.area != "nav-bar") { branch = "customized"; } else { let coinFlip = Math.floor(2 * Math.random()); branch = coinFlip ? "control" : "unified"; } let id = experiments.getActiveExperimentID(); experiments.setExperimentBranch(id, branch).then(() => resolve(branch)); }); }
[ "function getBranch() {\n return new baseService()\n .setPath('ray', '/company/branch/' + vm.currentBranch)\n .execute()\n .then(function (res) {\n vm.branchName = res.name;\n });\n }", "function getBranch(payload) {\n\n if ( payload.ref ) {\n // ref example: \"refs/tags/simple-tag\", this will get the last string\n return payload.ref.split(\"/\")[2];\n } else {\n return payload.pull_request.head.ref;\n }\n\n}", "function restoreEnvironment(startingBranch, cb){\n mess.status(\"Returning to original branch\");\n git.checkout(startingBranch, () => {\n mess.success(\"Returned to original branch\");\n return cb();\n });\n}", "async function getCurrentCommitHash( repoDir, branch ) {\n let info = await getCurrentCommitInfo( repoDir, branch );\n return info.commit;\n}", "async function checkoutRelease(alternate) {\n console.log(\"Checking out the release branch...\");\n\n // Make sure we're on a release branch that matches dev\n if (shell.exec('git checkout release').code !== 0) {\n if (shell.exec('git checkout -b release').code !== 0) {\n console.log('Could not switch to the release branch. Make sure the branch exists locally.');\n process.exit(1);\n }\n }\n\n // Make sure we have the latest from the remote\n if (shell.exec('git fetch --all').code !== 0) {\n console.log('Could not fetch from remote servers.');\n process.exit(1);\n }\n\n console.log(\"Resetting the release branch to the latest contents in dev...\");\n // Make sure we are exactly what is in dev\n if (shell.exec(`git reset --hard ${ENSURE_REMOTE}/dev${alternate ? `-${alternate}` : \"\"}`).code !== 0) {\n console.log(`Could not reset branch to dev${alternate ? `-${alternate}` : \"\"}`);\n process.exit(1);\n }\n}", "getPreviousEnvironment() {\n\n }", "getCondition() {\n errors.throwNotImplemented(\"getting condition (dequeue options)\");\n }", "BCS() { if (this.C) this.PC = this.checkBranch_(this.MP); }", "_isDefaultBoard() {\n return this._getCurrentBoard() && this._getCurrentBoard().default\n }", "getCurrentStaircase() {\n\t\treturn this.staircases[this.stairIndex].staircase;\n\t}", "static ensureBlackboard(ecs, aspect) {\n // create if needed\n if (!aspect.blackboards.has(AISentinel.name)) {\n let position = aspect.get(Component.Position);\n let bb = {\n home: position.p.copy(),\n fsm: new SentinelFSM(ecs, aspect),\n };\n aspect.blackboards.set(AISentinel.name, bb);\n }\n // return it\n return aspect.blackboards.get(AISentinel.name);\n }", "function getCurrentState() {\n var sheet = simulationSheet();\n var row = lastRow();\n var instructionTable = programSheet().getDataRange().getValues();\n var machine = {\n step: parseInt(row[COL_STEP]),\n pc: parseInt(row[COL_PC],16),\n stack: JSON.parse(row[COL_STACK]),\n memory: JSON.parse(row[COL_MEMORY]),\n instruction: row[COL_INSTRUCTION],\n instructionTable: instructionTable,\n pcRows: buildPcRows(instructionTable)\n };\n updateExtraInfo(machine);\n return machine;\n}", "static getStatePath() {\n const {isSpec, mainWindow, configDirPath} = this.getLoadSettings();\n if (isSpec) {\n return 'spec-saved-state.json';\n } else if (mainWindow) {\n return path.join(configDirPath, 'main-window-state.json');\n }\n return null;\n }", "function decisionTwo(){\n switch(trackBranch){\n case \"A1\":\n decisionTwoBrA();\n break;\n case \"B1\":\n decisionTwoBrB();\n break;\n case \"C1\":\n decisionTwoBrC();\n break;\n }\n }", "get effectiveRegion() {\n return this.action.actionProperties.resource?.env.region\n ?? this.action.actionProperties.region;\n }", "function get_random_state() {\n // Since the only valid initial states are OPEN and BLOCKED, we can just round the random number to either 0 or 1 and map it to one of the board states\n var random_value = Math.round(Math.random());\n return (random_value == 0) ? board_state.OPEN : board_state.BLOCKED;\n }", "getCurrentlySelectedComponent() {\n return simulationArea.lastSelected;\n }", "function getEnv() {\n env = env || new Benchmine.Env();\n\n return env;\n }", "function launchBranchJourney() {\n var linkData = {\n campaign: \"campaign cannot be changed\",\n feature: \"feature cannot be changed\",\n channel: \"channel was changed by javascript\",\n stage: \"stage was changed by javascript\",\n tags: [\"tag was changed by javascript\"],\n data: {\n custom_bool: true,\n \"custom_int (todays date)\": Date.now(),\n \"custom_string (url)\": window.location.href,\n $journeys_icon_image_url:\n \"https://www.valorebooks.com/campus-life/wp-content/uploads/icon_340.png\",\n $journeys_button_get_no_app: \"changed!\",\n $journeys_button_get_has_app: \"changed!\",\n $journeys_description: \"Description reset by button click\",\n },\n };\n branch.setBranchViewData(linkData);\n //function to launch journey with flags to disable banner animations\n branch.track(\n \"pageview\",\n {},\n { disable_entry_animation: true, disable_exit_animation: true }\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function compares new gift lists and new private gift lists to the old gift lists and old private gift lists.
function checkGiftLists(updatedUserData){ var newGiftList = updatedUserData.giftList; var newPrivateGiftList = updatedUserData.privateList; if(newGiftList == undefined){} else if(newGiftList != undefined) { for (var i = 0; i < userBoughtGiftsArr.length; i++) { var a = findUIDItemInArr(userBoughtGiftsArr[i].uid, newGiftList); if (a != -1) { //console.log(newGiftList[a]); checkGiftData(userBoughtGiftsArr[i], newGiftList[a], updatedUserData.name); } } } if(newPrivateGiftList == undefined){} else if(newPrivateGiftList.length != undefined) { for (var i = 0; i < userBoughtGiftsArr.length; i++) { var a = findUIDItemInArr(userBoughtGiftsArr[i], newPrivateGiftList); if (a != -1) { //console.log(newPrivateGiftList[a]); checkGiftData(userBoughtGiftsArr[i], newPrivateGiftList[a], updatedUserData.name); } } } }
[ "function gotSomethingDifferent(){\n if (prevDetections.length != detections.length){\n return true;\n }\n var prev = getCountedObjects(prevDetections);\n var curr = getCountedObjects(detections);\n for (var k in curr){\n if (curr[k] !== prev[k]){\n return true;\n }\n }\n for (var k in prev){\n if (prev[k] !== curr[k]){\n return true;\n }\n }\n return false;\n}", "function compareChangedWords(user, exp) {\n //inputs [user] and [exp] are arrays\n let userArray = [];\n let expArray = [];\n\n user.forEach(function(data) {\n userArray.push(JSON.stringify(data));\n })\n\n exp.forEach(function(data) {\n expArray.push(JSON.stringify(data));\n })\n\n let ans = JsDiff.diffArrays(userArray, expArray);\n let implementedChanges = []; //a pair of added and removed values\n let unimplementedChanges = [];\n let unnecessaryChanges = [];\n\n for (let i = 0; i < ans.length; i++) {\n if ((ans[i].added === undefined && ans[i].removed === true)) {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n change = JSON.parse(change);\n delete change[\"count\"];\n unnecessaryChanges.push(change);\n })\n } else if ((ans[i].added === true && ans[i].removed === undefined)) {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n unimplementedChanges.push(JSON.parse(change));\n })\n } else {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n implementedChanges.push(JSON.parse(change));\n })\n }\n }//end for loop\n\n let implementedArray = [];\n for (let i = 0; i < implementedChanges.length - 1; i++) {\n //make sure every 'removed' is followed by an 'added'\n if (implementedChanges[i].removed === true && implementedChanges[i+1].added === true) {\n let pair = {\n 'removed': implementedChanges[i].value,\n 'added': implementedChanges[i+1].value,\n 'concept': parseInt(wordToConceptCode[implementedChanges[i].value])\n }\n implementedArray.push(pair);\n }\n }\n\n\n let unimplementedArray = [];\n for (let i = 0; i < unimplementedChanges.length - 1; i++) {\n //make sure every 'removed' is followed by an 'added'\n if (unimplementedChanges[i].removed === true && unimplementedChanges[i+1].added === true) {\n let pair = {\n 'to_remove': unimplementedChanges[i].value,\n 'to_add': unimplementedChanges[i+1].value,\n 'concept': - parseInt(wordToConceptCode[unimplementedChanges[i].value])\n }\n unimplementedArray.push(pair);\n }\n }\n return {\n 'implemented_changes': implementedArray,\n 'unimplemented_changes': unimplementedArray,\n 'unnecessary_changes': unnecessaryChanges\n }\n}", "function itemChanged(r1, r2) {\n for( var key in r1 ) {\n\n // TODO: this should be a black list\n if( key == \"data\" ) continue;\n\n if( typeof r1[key] == \"string\" ) {\n if( r1[key] != r2[key] ) return true;\n } else {\n if( !r2[key] ) return true;\n if( r1[key].length != r2[key].length ) return true;\n for( var i = 0; i < r1[key].length; i++ ) {\n if( typeof r1[key][i] != typeof r2[key][i] ) return true;\n\n if( typeof r1[key][i] == 'object' ) {\n if( JSON.stringify(r1[key][i]) != JSON.stringify(r2[key][i]) ) return true;\n } else {\n if( r1[key][i] != r2[key][i] ) return true;\n }\n\n \n }\n }\n }\n return false;\n}", "function compareBoard(old) {\n for (let i = 0; i < gameBoard.length; i++) {\n for (let k = 0; k < gameBoard.length; k++) {\n if (old[i][k] !== gameBoard[i][k]) {\n return true;\n }\n }\n }\n return false;\n}", "function compareBrandsToCatalog(popularItems, catalogItems) {\n // get string values from catalog brands\n var brandsInCatalog = [];\n for (var j = 0; j < catalogItems.length; j++) {\n \tconsole.log(catalogItems[j].brand_name.S);\n \tbrandsInCatalog.push(catalogItems[j].brand_name.S.toLowerCase());\n }\n console.log(brandsInCatalog);\n // get string values from brands mentioned on twitter\n var brandsOnTwitter = [];\n for (var i = 0; i < popularItems.length; i++) {\n \tconsole.log(popularItems[i].Brand.S);\n \tbrandsOnTwitter.push(popularItems[i].Brand.S.toLowerCase());\n };\n console.log(brandsOnTwitter);\n // make a list of items on twitter missing from catalog\n var recommendedBrands = [];\n for (var k = 0; k < brandsOnTwitter.length; k++) {\n \tconsole.log(brandsOnTwitter[k]);\n \tconsole.log(brandsInCatalog.indexOf(brandsOnTwitter[k]));\n \tvar index = brandsInCatalog.indexOf(brandsOnTwitter[k]);\n \tif (index != -1) {\n \t\trecommendedBrands.push(brandsOnTwitter[k]);\n \t}\n }\n console.log(recommendedBrands);\n updateTableDisplay(recommendedBrands);\n}", "function checkGiftData(currentGiftData, newGiftData, giftOwner){\n var updateGiftBool = false;\n if(currentGiftData.description != newGiftData.description) {\n console.log(\"Description Updated: \" + currentGiftData.description + \" \" + newGiftData.description);\n updateGiftBool = true;\n }\n if(currentGiftData.link != newGiftData.link) {\n //console.log(\"Link Updated\");\n updateGiftBool = true;\n }\n if(currentGiftData.title != newGiftData.title) {\n //console.log(\"Title Updated\");\n updateGiftBool = true;\n }\n if(currentGiftData.where != newGiftData.where) {\n //console.log(\"Where Updated\");\n updateGiftBool = true;\n }\n\n if(updateGiftBool) {\n if (newGiftData.uid == currentModalOpen){\n currentModalOpen = \"\";\n console.log(\"Closed modal\");\n modal.style.display = \"none\";\n }\n changeGiftElement(newGiftData, giftOwner);\n }\n }", "function compareArrays() {\n\n for (var i = 0; i < game.player.length; i++) {\n if (game.player[i] !== game.turns[i]) {\n var result = false;\n } else if (game.player[i] === game.turns[i]) {\n result = true;\n }\n }\n return result;\n }", "function oldAndCache () {\n let tweets = oldTweets.concat(tweetCache).sort((a, b) => a.timestamp > b.timestamp)\n // remove duplicates by comparing id\n for (let x = tweets.length - 1; x >= 0; x--) {\n for (let y = x-1; y >= 0; y--) {\n if (tweets[x].id == tweets[y].id) {\n tweets.splice(x, 1)\n break\n }\n }\n\n // Remove tweets that are banned/deleted by admin\n for (let y = 0; y < deleted.length; y++) {\n if (tweets[x].id == deleted[y].id) {\n tweets.splice(x, 1)\n break\n }\n }\n }\n console.log('Old and cache: ', tweets)\n return tweets\n}", "compare(a, b) {\n for (i in this.collections) {\n for (j in a) {\n if (j == i)\n this.collections.push(j);\n }\n\n for (k in b) {\n if (k == i)\n this.collections.push(k);\n }\n }\n }", "static verifyClues(oldclues, newclues) {\n\n // make sure that each old clue corresponds to a new clue.\n Object.keys(oldclues).forEach((direction) => {\n if (newclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n\n Object.keys(newclues[direction]).forEach((number) => {\n if (newclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n\n // make sure that each new clue corresponds to an old clue.\n Object.keys(newclues).forEach((direction) => {\n if (oldclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n Object.keys(newclues[direction]).forEach((number) => {\n if (oldclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n }", "function matchFriends(friends, newFriend) {\n var closestDifference;\n var matchedFriend;\n\n //loop through the old friends array\n for (var i = 0; i < friends.length; i++) {\n\n //define a new varible equal to one friend at any index\n var friend = friends[i];\n\n //set the difference equal to 0 to start\n var difference = 0;\n\n\n\n //loop through the length of the scores in the new friend array\n for (var j = 0; j < newFriend.scores.length; j++) {\n\n //set the index of each score for the newFriend equal to a new variable\n var answerA = newFriend.scores[j];\n\n //call that same variable since the indexes will be the same for the friend variable\n var answerB = friend.scores[j];\n\n //redefine the difference variable equal to the total sum of each absolute value difference between each difference\n difference = difference + (Math.abs(answerA - answerB));\n\n }\n if (difference < closestDifference || closestDifference === undefined) {\n closestDifference = difference;\n matchedFriend = friend;\n }\n }\n return {\n name: matchedFriend.name,\n photo: matchedFriend.photo\n };\n}", "static compare(oldSets, newSets, textDiff, comparator) {\n var _a;\n let minPoint = (_a = comparator.minPointSize) !== null && _a !== void 0 ? _a : -1;\n let a = oldSets.filter(set => set.maxPoint >= BigPointSize ||\n set != RangeSet.empty && newSets.indexOf(set) < 0 && set.maxPoint >= minPoint);\n let b = newSets.filter(set => set.maxPoint >= BigPointSize ||\n set != RangeSet.empty && oldSets.indexOf(set) < 0 && set.maxPoint >= minPoint);\n let sharedChunks = findSharedChunks(a, b);\n let sideA = new SpanCursor(a, sharedChunks, minPoint);\n let sideB = new SpanCursor(b, sharedChunks, minPoint);\n textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));\n if (textDiff.empty && textDiff.length == 0)\n compare(sideA, 0, sideB, 0, 0, comparator);\n }", "relativeComplement(otherSet) {\n let newSet = new BetterSet();\n this.forEach(item => {\n if (!otherSet.has(item)) {\n newSet.add(item);\n }\n });\n return newSet;\n }", "function svConfigComparisor(oldConfig, newConfig) {\n var tempConfig = { ...oldConfig };\n var tempConfig2 = { ...newConfig };\n for (confIndex in oldConfig) {\n //console.log(\"index = \"+index)\n if (typeof oldConfig[confIndex] == \"object\" && typeof tempConfig2[confIndex] == \"object\") {\n tempConfig[confIndex] = svConfigComparisor(oldConfig[confIndex], tempConfig2[confIndex])\n } else {\n if (newConfig[confIndex]) {\n tempConfig[confIndex] = tempConfig2[confIndex]\n }\n }\n }\n return tempConfig\n}", "function compareSet(base,arr){\r\n\tvar tot = 0;\r\n\tvar matched_any = false;\r\n\tvar breakable = false;\r\n\tvar invalid = false;\r\n\t\r\n\tvar words = base.words;\r\n\tvar in_arr = arr;\r\n\t\r\n\tvar a = 0;\r\n\tvar b = 0;\r\n\t\r\n\tfor (b in words) {\r\n\t\tvar b_w = words[b];\r\n\t\t\t\r\n\t\tfor(a in in_arr){\r\n\t\t\tvar in_w = in_arr[a];\r\n\t\t\t\r\n\t\t\tif(typeof(b_w) == \"object\"){\r\n\t\t\t\tconsole.log(\"checkList in keylist - \" + base.action);\r\n\t\t\t\tif(iterateCheckList(b_w,in_w)){\r\n\t\t\t\t\tvar invalid = false;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar invalid = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(typeof(b_w) == \"function\"){\r\n\t\t\t\tconsole.log('function in keylist - ' + base.action);\r\n\t\t\t\tvar b = b_w(in_w); //TODO if match => userInput.check[base.id] = in_w\r\n\t\t\t\tif(b == true){\r\n\t\t\t\t\t//userInput.check[base.id] = in_w;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(b_w == in_w){\r\n\t\t\t\ttot += 1;\r\n\t\t\t\tif (base.any) {\r\n\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(breakable)\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\tvar tot_a = tot/in_arr.length; \t// the % of matched words in 'arr'\r\n\tvar tot_b = typeof(words) == \"object\" ? tot/words.length : 0.5; \t// the % of matched words in 'base'\r\n\t\r\n\t// if base.any && matched_any => return 1.0 else return median of tot_a & tot_b\r\n\tvar p = matched_any ? 1.0 : (tot_a+tot_b)*0.5;\r\n\tif (invalid)\r\n\t\tp = 0;\r\n\t\r\n\t//var f = p < 0.5 ? 0 : p;\r\n\t\r\n\t/* console.log(\"tot_matched: \" + tot,\r\n\t\t\t\t\"percent: \" + (tot_a+tot_b)*0.5,\r\n\t\t\t\t\"final score: \" + p); */\r\n\t\r\n\treturn p;\r\n}", "function isDifferrent(existing, entry) {\n\tfor (var prop in entry) {\n\t\tif (existing.hasOwnProperty(prop)) {\n\t\t\t// comparing array of interests otherwise suggests new data present\n\t\t\tif ((typeof entry[prop] !== 'object' && existing[prop] !== entry[prop])\n\t\t\t\t|| (typeof entry[prop] == 'object' && !arraysEqual(existing[prop], entry[prop]))) {\n\n\t\t\t\t// ****ideally want this logged to a temp file\n\t\t\t\t// console.log(`updated ${prop}: ${entry.orgName.substr(0,20)}: ${existing[prop]} -> ${entry[prop]}`);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else {\n\t\t\t// new data field supplied, also considered an update\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function updatePeopleData(prevData, optimalPairs) {\n //create copy of prevData into peopleData:\n const peopleData = [];\n prevData.map((person) => peopleData.push(person));\n\n //create copy of optimalPairs into pairsData\n const pairsData = [];\n optimalPairs.map((pair) => pairsData.push(pair));\n\n const newPeopleData = []; //will be adding to, and returning this array\n while (pairsData.length > 0) {\n const currPair = pairsData.pop();\n const memberOneId = currPair[0];\n const memberTwoId = currPair[1];\n const memberOneIndex = peopleData.findIndex(\n (person) => person[0] === memberOneId\n );\n const memberTwoIndex = peopleData.findIndex(\n (person) => person[0] === memberTwoId\n );\n let personOne = peopleData[memberOneIndex];\n let personTwo = peopleData[memberTwoIndex];\n const memberOneMatchQueue = personOne[3].split(\",\");\n const memberTwoMatchQueue = personTwo[3].split(\",\");\n const memberOneNewMatchQueue = memberOneMatchQueue.filter(\n (id) => id != memberTwoId\n );\n const memberTwoNewMatchQueue = memberTwoMatchQueue.filter(\n (id) => id != memberOneId\n );\n\n //reassign matchQueues. Index at 3 is the matchQueue:\n personOne[3] = memberOneNewMatchQueue.toString();\n personTwo[3] = memberTwoNewMatchQueue.toString();\n\n //insert into newPeopleData array\n const lengthSoFar = newPeopleData.length;\n const insertIndexOne = Math.floor(Math.random() * (lengthSoFar + 1)); //random int from 0 to lengthSoFar\n const insertIndexTwo = Math.floor(Math.random() * (lengthSoFar + 1));\n newPeopleData.splice(insertIndexOne, 0, personOne);\n newPeopleData.splice(insertIndexTwo, 0, personTwo);\n }\n // console.log(\"peopleData, after loop:\", peopleData)\n // console.log(\"newPeopleData, after loop:\", newPeopleData)\n\n const peopleDataID = [];\n const newPeopleDataID = [];\n peopleData.map((person) => peopleDataID.push(person[0]));\n newPeopleData.map((person) => newPeopleDataID.push(person[0]));\n\n const missingPeopleID = peopleDataID.filter(\n (id) => newPeopleDataID.indexOf(id) === -1\n ); //IDs of people not paired\n\n while (missingPeopleID.length > 0) {\n //insert person when there's an odd number, or they weren't paired\n const lengthSoFar = newPeopleData.length;\n const insertIndex = Math.floor(Math.random() * (lengthSoFar + 1)); //random int from 0 to lengthSoFar\n const lastIndex = missingPeopleID.length - 1;\n const nextPerson = peopleData.filter(\n (person) => person[0] == missingPeopleID[lastIndex]\n )[0];\n missingPeopleID.pop();\n newPeopleData.splice(insertIndex, 0, nextPerson);\n }\n return newPeopleData;\n}", "updateBlackoutList(){\r\n this.blackoutList = [];\r\n for(var i = 0; i < this.prosumers.length; i++) {\r\n if(this.prosumers[i].blackout == true) {\r\n this.blackoutList.push(this.prosumers[i].username);\r\n }\r\n }\r\n\r\n /*for(var i = 0; i < this.consumers.length; i++) {\r\n if(this.consumers[i].blackout == true) {\r\n this.blackoutList.push(this.consumers[i].username);\r\n }\r\n }*/\r\n\r\n }", "function makePairs(validTeams){\n let pairs = [];\n let teamNames = [];\n \n for(let i = 0; i < validTeams.length; i++){\n teamNames.push(validTeams[i].name);\n }\n\n for (let i = 0; i < teamNames.length - 1; i++) {\n for (let j = i + 1; j < teamNames.length; j++) {\n pairs.push([teamNames[i], teamNames[j]]);\n }\n }\n\n let names = [...teamNames];\n let shuffledPairs = [];\n let index = 0;\n\n while(pairs.length != 0){\n let pair = pairs.find(element => (teamNames.includes(element[0]) && teamNames.includes(element[1])))\n if(teamNames.length == 0){\n teamNames = [...names];\n continue;\n }\n \n shuffledPairs.push(pair);\n let pairIndex = pairs.indexOf(pair);\n if (index !== -1) {\n pairs.splice(pairIndex, 1);\n }\n\n teamNames = teamNames.filter(val => val !== pair[0]);\n teamNames = teamNames.filter(val => val !== pair[1]);\n }\n \n return shuffledPairs;\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ajax_comments_submit() Handles the actual AJAX request
function ajax_comments_submit() { if(ajax_comment_loading) return false; ajax_comments_loading(true); var ol = ajax_comments_find_list(); var f = ajax_comments_find_element(ajax_comments_form, 'form'); new Ajax.Request(f.action, { method: 'post', asynchronous: true, postBody: Form.serialize(f), onLoading: function(request) { request['timeout_ID'] = window.setTimeout(function() { switch (request.readyState) { case 1: case 2: case 3: request.abort(); ajax_comments_message('Timeout\nThe server is taking a long time to respond. Try again in a few minutes.', false); break; } }, 25000); }, onFailure: function(request) { var r = request.responseText; msg = r.substring(r.indexOf('</h1>') + 5, r.indexOf('</body>')); ajax_comments_message(msg, false); }, onComplete: function(request) { ajax_comments_loading(false); window.clearTimeout(request['timeout_ID']); if(request.status!=200) return; f.comment.value=''; // Reset comment if (ajax_comments_hide_on_success) { f.remove(); // remove form // remove theme-specific elements while (ajax_comments_hide.length > 0) { Element.remove(ajax_comments_hide.pop()); } } new Insertion.Bottom(ol, request.responseText); var li = ol.lastChild, className = li.className; li.hide(); li.addClassName('ajax'); if (ajax_comments_odd) { li.addClassName('alt'); } else { li.removeClassName('alt'); } ajax_comments_odd = !ajax_comments_odd; ajax_comments_message('Your comment has been saved.', true); new Effect.Appear(li, { duration:1.5, afterFinish: function() { new Effect.Highlight(ajax_comments_msgc, { duration:3, startcolor:'#99ff00' }); } }); } }); return false; }
[ "function postSubComment(e) {\n var commentId = e.getAttribute(\"data-id\");\n var subCommentsId = $(\"#sub-comment\" + commentId);\n var content = $(subCommentsId).val();\n if (!content) {\n alert(\"comment can not be empty\");\n return;\n }\n $.ajax({\n type: \"POST\",\n url: \"/comment\",\n contentType: 'application/json',\n data: JSON.stringify({\n \"parentId\": commentId,\n \"content\" : content,\n \"type\" : 2\n }),\n success: function (response) {\n if (response.code == 200) {\n // $(\"#comment_block\").hide();\n window.location.reload();\n } else {\n alert(response.message);\n }\n console.log(response);\n },\n dataType: \"json\"\n });\n}", "function submitkommentar(){\n\n $(\"#progress\").css(\"display\", \"table-row\");\n\n $.ajax({url: \"/api/lagreKommentar.php\",\n data: {kommentar: $(\"#tekstfelt\").val(),\n dato: new Date().toLocaleDateString(),\n album: albumId,\n bilde: bilde,\n navn: bruker},\n type: \"POST\",\n dataType: \"html\",\n success: function(data){\n $(\"#progress\").css(\"display\", \"none\");\n var commentNode = $.parseHTML(data);\n $(commentNode).find(\".slettkommentar\").click(slettKommentar);\n $(\"#progress\").before(commentNode);\n },\n error: function(a, b){\n $(\"#progress\").css(\"display\", \"none\");\n alert(\"Noe gikk galt, kommentaren ble ikke lagret\");\n }\n });\n }", "function comment(type, id, element) {\r\r\n if( jQuery(element).siblings('textarea').val().length != 0) {\r\r\n var content = jQuery(element).siblings('textarea').val();\r\r\n jQuery(element).siblings('textarea').val('');\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxComment',\r\r\n 'post_id': id,\r\r\n 'content' : content\r\r\n },\r\r\n function(response){\r\r\n // Append new comment to comment thread\r\r\n jQuery(element).parents('.comment-thread-wrapper').children('.comment-thread').prepend(response);\r\r\n // Increase number of comments\r\r\n var comments = parseInt(jQuery(element).parents('.social').children('.comments').children('span').html()) + 1;\r\r\n jQuery(element).parents('.social').children('.comments').children('span').html(comments);\r\r\n jQuery(element).siblings('textarea').val('');\r\r\n }\r\r\n );\r\r\n }\r\r\n}", "function answerComment(type, id, comment_id, element) {\r\r\n var content = jQuery(element).siblings('textarea').val();\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxAnswerComment',\r\r\n 'post_id': id,\r\r\n 'comment_id': comment_id,\r\r\n 'content' : content\r\r\n },\r\r\n function(response){\r\r\n jQuery(element).parents('.comment-thread-wrapper[data-comment]').each(function(){\r\r\n // Prepend the comment child to the right parent\r\r\n if(jQuery(this).attr('data-comment') == comment_id) {\r\r\n jQuery(this).children('.comment-thread').prepend(response);\r\r\n }\r\r\n });\r\r\n // Increase number of comments\r\r\n var comments = parseInt(jQuery(element).parents('.social').children('.comments').children('span').html()) + 1;\r\r\n jQuery(element).parents('.social').children('.comments').children('span').html(comments);\r\r\n jQuery(element).siblings('textarea').val('');\r\r\n }\r\r\n );\r\r\n}", "handleCommentPosted(name, comment) {\n\n\t\tvar self = this;\n\n\t\t$.ajax({\n\t\t\turl: \"/api/comment/\",\n\t\t \ttype: \"post\",\n\t\t \tdata: {\n\t\t \t\tname: name, \n\t\t \t\tcomment: comment, \n\t\t \t\tcompany: this.state.companyToRender.name\n\t\t \t},\n\t\t \tsuccess: function(response) {\n\n\t\t \t\t//create copy of current comment state\n\t\t \t\tvar commentArray = self.state.comments.slice();\n\n\t\t \t\t//push to top of array\n \t\t\tcommentArray.unshift(response);\n\n \t\t\t//reset the state to include the new comment\n \t\t\tself.setState({comments: commentArray});\n\n\t\t \t},\n\t\t \terror: function(xhr) {\n\t\t \tthrow new Error('An error saving a comment to the database has occurred.');\n\t\t \t}\n\t\t});\n\t}", "function submitQuestionAjax(e){\n e.preventDefault();\n\n var $status = $(\"#status\"),\n $loadingImage = $status.find(\"img\"),\n $loadingMessage = $status.find(\"p\"),\n $form = $(e.target),\n status, img;\n\n // set loaing state\n $loadingImage.attr({ src:\"/static/questions/img/loading.gif\" });\n $loadingMessage.html(\"Submitting question...\");\n\n // fade in loading message\n $status\n .css({opacity:0})\n .animate({opacity:1}, 500, function() {\n\n // post form\n var formData = $form.serialize();\n $.post(\"/ajax_suggest\", formData, function(data, textStatus, jqXHR) {\n\n // process result\n if (data === \"success\") {\n status = \"Your question has been added! Why not add another?\";\n img = \"/static/questions/img/tick.gif\";\n } else {\n console.log(data, textStatus);\n status = \"Sorry, there was an error submitting your question, please try again...\";\n img = \"/static/questions/img/cross.gif\";\n }\n\n // display result and remove status\n $loadingImage.fadeOut(250);\n $loadingMessage.fadeOut(250, function(){\n $loadingMessage.html(status).fadeIn(250);\n $loadingImage.attr({src:img}).fadeIn(250);\n });\n $status.delay(3000).animate({opacity:0}, 250);\n\n // reset form\n $form.find(\"#id_question\").val(\"\");\n //$form.find(\"#id_twitter_user\").val(\"\");\n });\n });\n }", "function updateCommentCount() {\n var return_data = \"\";\n var hr = new XMLHttpRequest();\n var url = \"controls/commentControl.php\";\n var vars = \"comment_count=true\";\n hr.open(\"POST\", url, true);\n hr.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n hr.onreadystatechange = function() {\n if(hr.readyState == 4 && hr.status == 200) {\n return_data = hr.responseText; \n if (return_data != 0) { \n var comment_count_message = return_data + \" Comments\";\n document.getElementById(\"comment-header\").innerHTML = comment_count_message; \n }\n }\n }\n hr.send(vars);\n}", "function submitUpdate()\n{\n $(\"#update_form\").submit(function(e) {\n e.preventDefault();\n var currentUser = $(\"h1.blog-title\").first().text().trim();\n var url = $(this).attr(\"action\");\n var guid = getUuid($(this).find(\"select\").first().attr(\"id\"));\n var permissionVal = $(\"#post_permission-\"+guid).val();\n var categoryVal = $(\"#edit_post_category-\"+guid).val();\n var titleVal = $(\"#post_title-\"+guid).val();\n var descriptionVal = $(\"#edit_post_description-\"+guid).val();\n var contentVal = $(\"#edit_post_content-\"+guid).val();\n $.ajax({\n url: url,\n type: \"POST\",\n data: {\n \"id\": guid,\n \"permission\": permissionVal,\n \"category\": categoryVal,\n \"title\": titleVal,\n \"description\": descriptionVal,\n \"content\": contentVal\n },\n success: function(data) {\n var newpostDiv = makePostDiv(guid, currentUser, data[\"posts\"][0]);\n \n $(\"#edit_post-\"+guid).empty().remove();\n $(\"#post_wall-\"+guid).replaceWith(newpostDiv);\n postButtonClickEvent();\n },\n error: function(jqXHR, textStatus, errorThrown) {\n console.log(jqXHR);\n console.log(textStatus);\n console.log(errorThrown);\n }\n \n });\n });\n}", "function addComment() \n{\n\tvar content = $('textarea#content').val(); \n\tvar id_movie = GetURLParameter('id_movie'); \n\tSaveComment(content, id_movie); \n\t\n}", "function postComment () {\n let postContent = document.getElementById('comment').value;\n let postTitle = document.getElementById('title').value;\n // Body of the comment post to send to the server\n let post = {\n\t\ttitle : postTitle,\n\t\tcontent : postContent\n\t}\n // send the post\n makeRequest('posts', 'POST', post, auth.jwtToken);\n getAllPosts();\n}", "function ajax_comments_message(message, succeeded) {\n if (!ajax_comments_msgc) {\n ajax_comments_msgc = $('ajax-comments-message');\n \n if (ajax_comments_msgc == null) {\n var ol = ajax_comments_find_list();\n new Insertion.After(ol, '<div id=\"ajax-comments-message\"></div>');\n ajax_comments_msgc = $('ajax-comments-message');\n }\n }\n \n if (ajax_comments_msgc.empty()) {\n new Insertion.Bottom(ajax_comments_msgc, '<div>' + message + '</div>');\n }\n else {\n ajax_comments_msgc.firstChild.replace('<div>' + message + '</div>');\n }\n\n if (!succeeded) {\n ajax_comments_msgc.addClassName('error');\n } else {\n ajax_comments_msgc.removeClassName('error');\n }\n}", "function onSubmit(event) {\n event.preventDefault();\n var url=$(this).closest('form').attr('action'),\n data=$(this).closest('form').serialize(),\n type=$(this).closest('form').attr('method');\n console.log(url);\n $.ajax({\n url:url,\n type:type,\n data:data,\n success:onSuccess\n });\n\n }", "function createNewComment(){\n\n var newComment = document.getElementById( 'comment-input' ).value;\n\n if( newComment.trim() !== '' ){\n\n var newCommentTime = getTimestamp();\n var onPostID = getPostIDforComment();\n\n if( onPostID !== '' ){\n var newCommentObject = {\n postid: onPostID,\n timestamp: newCommentTime,\n commentContent: newComment\n };\n uploadPost( newCommentObject, \"/posts/\" + onPostID + \"/createNewComment\", function(err){\n if(err){\n alert(\"Error creating comment.\");\n }\n else{\n console.log(\"Success adding comment.\");\n }\n });\n\n closeCreateCommentMenu();\n addNewCommentToDOM( newCommentObject );\n\n }\n\n }\n else{\n alert(\"You cannot leave a blank comment.\");\n }\n\n}", "function construct(){\n if( typeof( commentIdOrData ) == \"object\" ){\n data = commentIdOrData;\n } else {\n data[\"commentId\"] = commentIdOrData;\n }\n\n var $comment = $( \"#comment-\" + data[\"commentId\"] );\n \n var retrievedHTML = false; \n var html = '';\n\n if( $comment.length ){\n html = $comment.get();\n retrievedHTML = true;\n }\n\n if( !retrievedHTML ){\n html = generateHTML();\n if(html){ \n retrievedHTML = true;\n }\n } \n\n $.when(\n ajaxGetThread(\n {\n c: $this.getData( \"commentId\" ), \n single: true\n },\n {\n dataFilter: function( d, t ){\n d = JSON.parse( d );\n data = WPTCComment.convertDataForClient( d[0] );\n return JSON.stringify( data );\n }\n }, retrievedHTML )\n ).done( function( htmlR ){\n \n /**\n * If html code hasn't been generated yet, create it using\n * data from ajax call.\n */\n if( !html ){\n data[\"defaults\"] = false;\n properties[\"remote\"] = true;\n data = htmlR;\n html = generateHTML(); \n }\n\n if( data[\"defaults\"] ){\n data = WPTCComment.readDataFromHTML( html ); \n }\n\n // Attach generated html code to DOM\n if( $comment.length == 0 ){ \n $dom[\"list\"] = $( html ).appendTo( wptcO.wptcCommentsStorage );\n } else { \n $dom[\"list\"] = $comment;\n }\n\n $dom[\"dropzone\"] = $( wptcO.wptcDropzone.generateHTML( $this ) ).appendTo( wptcO.wptcCommentsStorageDropzone ); \n \n $dom[\"list\"].data( \"wptcCommentObject\", $this );\n $dom[\"dropzone\"].data( \"wptcCommentObject\", $this );\n \n $this.draggabify().droppabify();\n\n //Bind expand/collapse links \n $dom[\"list\"].find( \"a.tc-show-more\" ).live( \"click\", function(){ $this.expandSubthread()} );\n $dom[\"list\"].find( \"a.tc-show-less\" ).live( \"click\", function(){ $this.collapseSubthread()} );\n\n //If there was any callback passed, call it.\n if( callback ){\n callback( $this, $dom[\"list\"] );\n } \n }); \n }", "function updateComments(id){\n\n // Show comments box\n $('#msgb-comments').show();\n\n // only load comments if a topic is picked\n if($.qs[\"mbt\"] !== undefined){\n p = {\"method\":\"updateComments\",\"params\":{\"topic_id\":$.qs[\"mbt\"],\"comment_id\":id}};\n $.post('api.php',p,function(v){ fillComments(v) }); // ajax and call fill\n }\n\n // Insert comments from API into DOM\n function fillComments(o){\n console.log(\"Filling comments:\");\n _.each(o,function(o,i){\n console.log(o);\n $T = $('#msgb-comment-template').clone().removeAttr(\"id\").attr(\"data-id\", o.id);\n $T.find('.msgb-comment-body').html(o.content);\n $T.find('.msgb-comment-header').html(\"Bryan Potts,<time \");\n $('#msgb-comments').append($T);\n });\n $('.msgb-delete-comment').on(\"click\", function(){ deleteComment($(this).parent().parent(\".msgb-comment\")) });\n }\n }", "function addComment(url, comment, highlight, callback, parent_comment) {\n $.post(baseUrl + \"/api/v1/history-data\", {\n 'url': url,\n 'message': comment,\n 'highlight': highlight,\n // 'tags': JSON.stringify(tags),\n 'parent_comment': parent_comment,\n 'csrfmiddlewaretoken': user.csrf, \n }).done(function(res, status, xhr) {\n var location = xhr.getResponseHeader(\"Location\")\n callback(res);\n window.location.reload();\n });\n }", "function contactSubmit() {\n $(this).submit();\n }", "function onclickBtnReply(e) {\n e.preventDefault();\n /**\n * handle action on clicking reply button\n * take the input reply and insert it in\n * replies area\n */\n\n /**\n * get the identifier of the comment\n * @type {*|string}\n */\n\n var id = e.currentTarget.id.split(\"-\")[1];\n\n /**\n * Get id of the reply input area\n * @type {string}\n */\n var replyInputId = \"#comment-\" + id + \"-reply-input\";\n\n /**\n * get the input reply area\n * and store it in the reply\n * @type {*|void|jQuery}\n */\n var reply = $(replyInputId).val();\n\n /**\n * Clear the input reply area\n */\n $(replyInputId).val();\n\n\n /**\n * get the number of replies of this comment\n * to give beside prefix\n */\n\n var repliesAreaId = \"#comment-\" + id + \"-repliesArea\";\n /**\n * Get number of childern to determine the number of replies\n * @type {jQuery}\n */\n var count = $(repliesAreaId).children().length;\n\n /**\n * add 1 to the number of replies\n */\n\n let numOfRepliesId = \"#comment-\" + id + \"-numOfReplies\";\n let numOfReplies = parseInt($(numOfRepliesId).text()) + 1;\n $(numOfRepliesId).text(\"\" + numOfReplies);\n\n /**\n *Create replies using the Reply of prototype\n * @type {Reply}\n */\n\n var date = new Date().toJSON().slice(0, 10);\n var obj = new Reply(id, count);\n obj.date = date;\n obj.text = reply;\n obj.creation();\n\n\n /**\n * Make the reply button disabled\n */\n\n\n $(\"#\" + e.currentTarget.id).attr('disabled', 'disabled');\n\n\n}", "function submitProblemFile(data,name,onsubmit)\n{\n var req = new XMLHttpRequest();\n req.onreadystatechange = function() {\n if (req.readyState == 4 && req.status == 200)\n {\n var jobid = req.responseText;\n\n if (onsubmit != null)\n {\n onsubmit(name,jobid);\n }\n }\n }\n req.open(\"POST\",\"/api/submit?jobname=\"+name,true);\n req.send(data);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function add type films on search panel in 3 columns for search films by type
function typeOfFilms(data){ var typeslinks = $('.list', data).children('tbody').children('tr').children('td').children('ul').children('li').children('a'); typeslinks.each(function(i){ if (i < 5){ var type = '<a href="http://www.kinopoisk.ru' + $(this).attr('href') + '" target="_blank">' + $(this).text() + '</a>'; $('#searchfirst').append(type + '</br>'); } if (i > 5 && i < 11){ var type = '<a href="http://www.kinopoisk.ru' + $(this).attr('href') + '" target="_blank">' + $(this).text() + '</a>'; $('#searchsecond').append(type + '</br>'); } if (i > 11 && i < 17){ var type = '<a href="http://www.kinopoisk.ru' + $(this).attr('href') + '" target="_blank">' + $(this).text() + '</a>'; $('#searchthird').append(type + '</br>'); } }); }
[ "function fnInsertLabelFilters(){\r\n if(FC$.Page==\"Products\"){ \r\n var insertLabelSearchFilter = document.querySelectorAll(\".SearchFil\") \r\n for (i = 0; i < insertLabelSearchFilter.length; i++) {\r\n insertLabelSearchFilter[i].setAttribute(\"aria-label\",\"Search Fil\");\r\n } \r\n var insertLabelInputFilter = document.getElementsByName(\"CatFil\");\r\n for (i = 0; i < insertLabelInputFilter.length; i++) {\r\n insertLabelInputFilter[i].setAttribute(\"aria-label\",\"Cat Fil\");\r\n } \r\n }\r\n }", "function buildFilteredTable (type) {\n // Generate \"add column\" cell.\n\n clearElement(addColumnDiv)\n addColumnDiv.appendChild(generateColumnAddDropdown(type))\n\n const query = generateQuery(type)\n\n updateTable(query, type)\n }", "function displayFilmsData(data) {\r\n cartegoriesCounter = 0;\r\n var listBox = document.getElementById(\"searchResults\");\r\n listBox.innerHTML = \"\";\r\n listBox.innerHTML = \"<p>Title: \" + data.results[0].title + \"</p>\" +\r\n \"<br><p>Episode: \" + data.results[0].episode_id + \"</p><br>\" +\r\n \"<p>Opening Crawl:</p><br><p>\" + data.results[0].opening_crawl +\r\n \"<br><p>Director: \" + data.results[0].director + \"</p><br>\" +\r\n \"<p>Producer(s): \" + data.results[0].producer + \"</p>\";\r\n }", "selectModelsByType(type) {\n return this.filterAllByProperty('type', type)\n }", "function handleSearch() {\n\n $(document).on('click', '.search-by-genre', function (event) {\n event.preventDefault();\n \n let genre = $('#search-by-genre').val();\n STORE.genre = genre;\n STORE.searchType = 'genre';\n searchMovieAPI();\n \n });\n\n $(document).on('click', '.search-popular', function (event) {\n event.preventDefault();\n \n STORE.searchType = 'popular';\n searchMovieAPI();\n });\n\n}", "function datatables_search(dt) {\n dt.columns('task_type:name').search('current').draw()\n}", "function set_search_type(type) {\n if (type == \"D\") {\n lastSearchType = \"D\";\n $('#search_diary_button').addClass('ui-priority-primary').removeClass('ui-priority-secondary');\n $('#search_epg_button').addClass('ui-priority-secondary').removeClass('ui-priority-primary');\n } else {\n lastSearchType = \"E\";\n $('#search_diary_button').addClass('ui-priority-secondary').removeClass('ui-priority-primary');\n $('#search_epg_button').addClass('ui-priority-primary').removeClass('ui-priority-secondary');\n }\n }", "function update_filters() {\n //get currently selected (or unselected values for all ids in columns.head)\n for (var i = 0; i < columns.length; i++) {\n columns[i].filter = $('#'+columns[i].cl).val();\n }\n\n // apply filter\n filtered_dataset = full_dataset.filter(filter_function);\n filtered_unique_columns = unique_columns.map(column_filter);\n\n // update display\n update_select_boxes();\n generate_table();\n}", "function setup(array) {\n let searchInput = document.getElementById(\"search-field\");\n searchInput.addEventListener(\"input\", (event) => {\n let value = event.target.value.toLowerCase();\n let foundLists = array.filter((show) => {\n let toLowerCaseName = show.name.toLowerCase();\n let toLowerCaseSummary = show.summary.toLowerCase();\n\n return (\n toLowerCaseName.includes(value) || toLowerCaseSummary.includes(value)\n );\n });\n\n displayAllShows(foundLists);\n\n document.getElementById(\n \"results\"\n ).innerHTML = `Displaying ${foundLists.length} / ${array.length}`;\n\n\n });\n\n}", "function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}", "handleClick (type) {\n this.props.setFilter(type);\n }", "function onSelectFieldType( type ) {\n\n\n \n /** \n\n switch( type ) {\n\n case 'new':\n\n apiFetch( { path: '/dev/wp-json/wp/v2/posts' } ).then( posts => {\n console.log( 'new', posts );\n } );\n\n break;\n\n case 'existing':\n\n apiFetch( { path: '/dev/wp-json/wp/v2/posts' } ).then( posts => {\n console.log( 'existing', posts );\n } );\n\n \n break;\n }\n\n */\n\n\n setAttributes( { fieldType: type } )\n\n\n }", "function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}", "function filtrando(text){\n setListagemComFiltro(\n listagens.filter((item) =>\n {\n return item.nome.toLowerCase().includes(text.toLowerCase());\n })\n );\n setNomefiltro(text)\n }", "function filter() {\r\n $(\"input[name=filterBtn]\").click(function() {\r\n // Get form values\r\n let title = $(\"#title\").val();\r\n let pickedGenre = $(\"select[name='genreSelect'] option:selected\").val();\r\n\r\n // Clear current result space\r\n $(\"#filteredMovies\").html(\"\");\r\n\r\n // result flag\r\n var found = false;\r\n\r\n if (title == \"\" && pickedGenre != \"\") {\r\n movies.forEach(function(currObj) {\r\n if (currObj.genre == pickedGenre) {\r\n request(queryReview(currObj.title, queryNYTMovie), queryMovie(currObj.title, queryOMDb), currObj);\r\n found = true;\r\n }\r\n });\r\n } \r\n else { // Handles when title given, or no genre or title given\r\n const titleRegEx = new RegExp(\"^\" + title, \"i\");\r\n movies.forEach(function(currObj) {\r\n if (titleRegEx.test(currObj.title)) {\r\n request(queryReview(title, queryNYTMovie), queryMovie(title, queryOMDb), currObj);\r\n found = true;\r\n }\r\n });\r\n }\r\n ensureResults(found);\r\n // reveal results in modal\r\n modal.style.display = \"block\";\r\n });\r\n}", "searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }", "function filterNames() {\n document.getElementsByClassName(\"pagination\")[0].innerHTML = ' '; \n let filterValue = document.getElementById('input').value.toUpperCase(); \n let ul = document.getElementById('names'); \n let li = ul.querySelectorAll('li.student-item'); \n const searchResults = []; \n for(let i = 0; i < li.length; i++) {\n li[i].style.display = 'none'; \n let h3 = li[i].getElementsByTagName('h3')[0]; \n \n if (h3.innerHTML.toUpperCase().includes(filterValue)) { \n searchResults.push(li[i]); \n li[i].style.display = '' \n } \n \n if(searchResults.length === 0) {\n noNamesDiv.style.display = '' \n } else {\n noNamesDiv.style.display = 'none' \n }\n \n } \n showPage(searchResults,1); \n appendPageLinks(searchResults); \n}", "function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }", "function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(2) Write a function where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number.
function guess_number(){ const number = Math.ceil((Math.random() * 10)); function g(){ print("Guess a number from 1-10.") const guess = readline(); if (guess == number){ print("You guessed correctly."); return; } else { g(); } } g(); }
[ "function guess() {\n\n // WRITE YOUR EXERCISE 4 CODE HERE\n let guess = 0;\n let number= 0;\n let attempt = 0;\nnumber = (Math.floor(Math.random()* 1000) + 1);\nguess = prompt (\"Please enter your guess. The range is a random integer between 1 to 1,000.\")\nattempt += 1\nwhile (guess != number){\n if (guess > 1000 || guess < 1 || guess%1 != 0)\n guess = prompt (\"Invalid guess. Try a valid number between 1 to 1,000.\")\nif (guess < number) {\n guess = prompt (\"Guess too small. Try another number between 1 to 1,000.\")\n attempt += 1\n}\nif (guess > number) {\n guess = prompt (\"Guess too big. Try another number between 1 to 1,000.\")\n attempt += 1\n}\n}\nif (guess == number) {\n var p = document.getElementById(\"guess-output\");\n p.innerHTML = \"You did it! The random integer was \" + number + \" and you took \" + attempt + \" tries or try (if you somehow got the random interger in your first guess) to figure out the random integer.\"\n}\n ////////////////// DO NOT MODIFY\n check('guess'); // DO NOT MODIFY\n ////////////////// DO NOT MODIFY\n}", "function favNumber(){\n\n var myNum = 8;\n var tries = 4;\n \n while(tries > 0){\n \n var userInput = prompt('Can you guess my favorite number?');\n var userInputInt = parseInt(userInput);\n \n if(userInputInt < myNum){\n alert('too small');\n tries --;\n } else if(userInputInt === myNum){\n alert('you are correct');\n tries --;\n break;\n } else if(userInputInt > myNum){\n alert('too large');\n tries--;\n } else {\n alert('The correct answer is 8');\n }\n }\n}", "function guessNumber(){\n\n let guess = user.value;\n user.value = '';\n\n /* Random Math Function */\n let number = Math.floor(Math.random() * 5 + 1);\n\n /* Correct guess */\n if(guess == number){\n story.innerHTML = `Bra jobbat! Du gissade ${number} och det var rätt och nu har spöket försvunnit och ingen behöver vara rädd mer!`;\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n\n /* Guesss was to high */\n }else if(guess > number){\n story.innerHTML = 'Fel! Det var för högt. Försök igen!';\n\n /* Guess was to low */\n } else if(guess < number){\n story.innerHTML = 'Fel! Det var för lågt. Försök igen!';\n }\n }", "function guessingGame(userInput) {\n \n \n \n if ((!userInput) || (!userInputRangeLowEl) || (!userInputRangeHighEl)){\n if (submitBtnEl.value === \"Start\") {\n submitBtnEl.value = \"Submit\"\n }\n msgDisplayEl.innerHTML = \"Please guess a number\"\n } else if (parseInt(userInput) === ranNumber) {\n document.body.innerHTML = '<nav><header>You guessed it right after <span>'+ numberOfGuesses +'</span> tirals ! Great job!\\n <INPUT TYPE=\"button\" onClick=\"history.go(0)\" VALUE=\"Play Again\"></header></nav> <style> nav { background-color: #2F4E81; color: #fff; font-weight: bolder; height: 5em; text-align: center; margin: 0px auto;} header { padding:1em; width: auto; margin: auto;} span{color: red;}<\\style>';\n \n clearInput();\n console.log(ranNumber);\n submitBtnEl.value = \"Start\";\n submitBtn2El.value = \"Pick\";\n \n \n \n \n \n } else if (userInput > ranNumber) {\n msgDisplayEl.innerHTML = \"Your number is greater than the secret number!\"\n clearInput();\n submitBtnEl.value = \"Guess Again!\";\n submitBtn2El.value = \"Already Picked!\";\n numberOfGuesses++;\n \n } else if (userInput < ranNumber) {\n msgDisplayEl.innerHTML = \"Your number is less than the secret number!\"\n clearInput();\n submitBtn2El.value = \"Already Picked!\";\n submitBtnEl.value = \"Guess Agina!!\";\n numberOfGuesses++;\n \n }\n\n\n}", "function checkInputNumber() {\n let userGuess = enteredNumber.value;\n\n if (userGuess == randomNumber) {\n alert('You are Winner!')\n } else {\n alert('Wrong answer!')\n }\n}", "function secretNum() {\n var ip = parseInt(prompt(\"Enter number\",\"\"));\n var random = ((Math.random()*10)+1);\n if(ip == random) {\n document.write(\"Congo! you guess it write\");\n } else {\n document.write(\"Try again\");\n }\n}", "function guess() {\n\t\t// Capture the guess value:\n\t\tvar inputValue = document.getElementById(\"input\").value;\n\t\t\n\t\t// Verify the guess is a number using the previously defined function (isNumber()):\n\t\tvar isNum = isNumber(inputValue);\n\t\tif ( isNum === false) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"red\", true, \"You must enter a number!\");\n\t\t\tupdateGameGuesses(inputValue, \"Not a number\");\n\n\t\t// Was the guess too low?\n\t\t} else if ( inputValue < ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too low\");\n\t\t\tupdateGameGuesses(inputValue, \"Too low\");\n\n\t\t// Was the guess too high?\n\t\t} else if ( inputValue > ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too high\");\n\t\t\tupdateGameGuesses(inputValue, \"Too high\");\n\n\t\t// Was the guess correct?\n\t\t} else if (ranNum == inputValue) { \n\t\t\tguesses += 1;\n\t\t\t// Display a message if the user guessed correctly on their first try:\n\t\t\tif(guesses === 1) {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It only took you one guess!\", \"Start again (it's ready).\");\n\t\t\t// Display a message if the user required 2 or more guesses:\n\t\t\t} else {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It took you \" + guesses + \" guesses.\", \"Start again (it's ready).\")\n\t\t\t}\n\t\t\tupdateGameGuesses(inputValue, \"Correct\");\n\n\t\t\t// For this one game, that was guessed correctly, store the game stats:\n\t\t\tvar gameStat = [numRange, ranNum, guesses];\n\t\t\t// Add the game stat to an array that persists for the window session (is emptied after a page refresh):\n\t\t\tvar sessionScore = new Array();\n\t\t\tsessionScore[sessionScore.length] = gameStat;\n\n\t\t\t// Display the Session Scores in a table:\n\t\t\tfor( var i = 0; i < sessionScore.length; i++ ) {\n\t\t\t\tvar gameStat = sessionScore[i],\n\t\t\t\ttr = document.createElement(\"tr\"),\n\t\t\t\ttd0 = document.createElement(\"td\"),\n\t\t\t\ttd1 = document.createElement(\"td\"),\n\t\t\t\ttd2 = document.createElement(\"td\");\n\n\t\t\t\ttd0.appendChild(document.createTextNode(\"1 to \" + gameStat[0]));\n\t\t\t\ttd1.appendChild(document.createTextNode(gameStat[1]));\n\t\t\t\ttd2.appendChild(document.createTextNode(gameStat[2]));\n\t\t\t\ttr.appendChild(td0);\n\t\t\t\ttr.appendChild(td1);\n\t\t\t\ttr.appendChild(td2);\n\t\t\t\tsessionScoreTable.appendChild(tr);\n\t\t\t}\n\n\t\t\t// Reset the game:\n\t\t\tresetGameGuessesTable();\n\t\t\tgameGuesses.length = 0;\n\t\t\tgameStat = 0;\n\t\t\tguesses = 0;\n\t\t\tnewRanNum();\n\t\t}\n\t}", "function AskMax()\n{\n let maxlet = prompt(\"what the highest number you want to guess between? (must be higher than 10)\");\n max = ValidateIntegerMax(maxlet);\n\n return max;\n}", "function alert(guess) {\n\n if (guess < 0 || guess > 9) {\n\n console.log(`ERROR: ${guess} is out of range 0 - 9.`);\n }\n\n}", "function suggestGuess(){\n\tif(guess<answer){\n\t\treturn \" guess higher.\";\n\t} else{\n\t\treturn \" guess lower.\";\n\t}\n}", "function checkIfNumber(input) {\n\tlet i =0;\n\tlet value = input;\n\tif (!isNaN(value)) {\n\t\tpointsToWin = value;\n\t} else {\n\t\tdo {\n\t\t\talert(input + \" is not a number. Please enter a number 1-9.\");\n\t\t\tif (!isNaN(value = prompt(\"Please enter number of points to win (1-9).\") ) ) {\n\t\t\t\ti =+ 1;\n\t\t\t}\n\t\t} while (i !=1);\n\t\tpointsToWin = value;\n\t}\n}", "function guessOrNot(){\n\n const option = user.value;\n user.value = '';\n\n \n if(option === 'gissa' || option === 'GISSA' || option === 'Gissa'){\n\n story.innerHTML = 'Du är modig du! Gissa på ett tal mellan (1 - 5)';\n btn.onclick = guessNumber;\n btn.innerHTML = 'Gissa';\n\n /**\n * Function guessNumber selected.\n * User inputs a guess to make ghost dissapear.\n */\n function guessNumber(){\n\n let guess = user.value;\n user.value = '';\n\n /* Random Math Function */\n let number = Math.floor(Math.random() * 5 + 1);\n\n /* Correct guess */\n if(guess == number){\n story.innerHTML = `Bra jobbat! Du gissade ${number} och det var rätt och nu har spöket försvunnit och ingen behöver vara rädd mer!`;\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n\n /* Guesss was to high */\n }else if(guess > number){\n story.innerHTML = 'Fel! Det var för högt. Försök igen!';\n\n /* Guess was to low */\n } else if(guess < number){\n story.innerHTML = 'Fel! Det var för lågt. Försök igen!';\n }\n }\n\n }else if(option === 'ut'|| option === 'UT' || option === 'Ut'){\n story.innerHTML = 'Jag förstår dig! Det ät läskigt med spöken.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n }\n }", "function factorialPrompt() {\n\tvar a = prompt(\"Please enter a positive number\", 8);\n\tif (a < 0) {\n\t\talert(\"Please enter a POSITIVE number\");\n\t}\n\telse {\n\t\tvar b = calculateFactorial(a);\n\t\talert(b);\n\t}\n}", "function computerGuessGen() {\n\treturn Math.floor(Math.random() * 101) + 19;\n}", "function Subtraction() {\n var notANumber;\n var subtractionAnswer;\n var subtractionNumber1 = 0;\n var subtractionNumber2 = 0;\n var subtractionOutput;\n \n subtractionNumber1 = FirstNumber();\n subtractionNumber2 = Math.floor(Math.random() * subtractionNumber1);\n \n subtractionAnswer = prompt(\"What is \" + subtractionNumber1 + \" - \" + subtractionNumber2 + \"?\");\n\n while (isNaN(subtractionAnswer)) {\n notANumber = alert(subtractionAnswer + \" is not a valid answer. Please use the numeric pad.\");\n subtractionAnswer = prompt(\"What is \" + subtractionNumber1 + \" - \" + subtractionNumber2 + \"?\");\n }\n \n subtractionAnswer = Number(subtractionAnswer);\n \n if (subtractionAnswer === (subtractionNumber1 - subtractionNumber2)) {\n subtractionOutput = CorrectAnswer(subtractionAnswer);\n } else {\n subtractionOutput = IncorrectAnswer(subtractionAnswer);\n }\n return(subtractionOutput);\n}", "function generateNum() {\n\n /*TODO 2: implement the body of the function here to return a random number between 0 and 1*/\n\n}", "function compareNumber(){\n var insideInputAsAString = number.value;\n var insideInput = parseInt(insideInputAsAString);\n if (insideInput===randomNumber){\n clues.innerHTML = 'HAS GANADO, CAMPEONA';\n console.log('HAS GANADO, CAMPEONA');\n }else if(insideInput<randomNumber){\n clues.innerHTML = 'Demasiado pequeño';\n console.log('Demasiado pequeño');\n }else if(insideInput>randomNumber){\n clues.innerHTML = 'Demasiado alto';\n console.log('Demasiado alto');\n }\n}", "function genRandomInteger() {\n let max = 6; // total number of game buttons that represents the upper bound \n let min = 1; // lower bound\n return Math.floor(Math.random() * (max - min + 1) + min);\n}", "function promptAnswer() {\n r = printRandQuestion();\n let answer = prompt('Whats the correct answer?');\n\n // Check if player wants to exit\n if (answer !== 'exit') {\n\n // Check answer and display result plus total score, then start again\n questions[r].checkAnswer(parseInt(answer));\n promptAnswer();\n\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 368 A game of table tennis almost always sounds like Ping! followed by Pong! Therefore, you know that Player 2 has won if you hear Pong! as the last sound (since Player 1 didn't return the ball back). Given an array of Ping!, create a function that inserts Pong! in between each element. Also: If win equals True, end the list with Pong!. If win equals False, end with Ping! instead.
function pingPong(arr, win) { const a = []; for (let i = 0; i < arr.length; i++) { if (arr[i] === "Ping!" && arr[i+1] === "Ping!") { a.push("Ping!"); a.push("Pong!") } else { a.push("Ping!") } } if (win) a.push("Pong!"); return a; }
[ "checkFinished(row, col, player){\n let winningStreak = [];\n\n //Checking for a streak vertically in the column of the inserted token\n let streak = [];\n let streakReached = false;\n for(let i=0; i<this.rows; i++){\n if(this.field[i][col] == player){\n streak.push([i,col]);\n if(streak.length == this.toWin){\n streakReached = true;\n i=this.rows;\n }\n }\n else streak = [];\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak horizontally in the row of the inserted token\n streakReached = false;\n streak = [];\n for(let i=0; i<this.cols; i++){\n if(this.field[row][i] == player){\n streak.push([row,i]);\n if(streak.length == this.toWin) streakReached = true;\n }\n else{\n if(!streakReached) streak = [];\n else i=this.cols;\n }\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak diagonally from top left to bottom right in the\n //line of the inserted token and adding it to the winningStreak Array.\n let spots;\n if(this.rows >= this.cols) spots = this.rows;\n else spots = this.cols;\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,1));\n\n //Checking for a streak diagonally from bottom left to top right in the\n //line of the inserted token and adding it to the winningStreak Array.\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,-1));\n\n if(winningStreak.length >= this.toWin) return winningStreak;\n else if(this.freeLots == 0) return false;\n return null;\n }", "function checkPlayerArray() {\n\tif (arrayJug.length == arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\tcontador = contador + 100;\n\t\tscore_elem.innerHTML = \"Score: \" + contador;\n\t\tconsole.log(\"Turno AI\")\n\t\tsetTimeout(function(){\n\t\t\tpaseDeTurno(true);\n\t\t}, 500);\n\t}\n\telse if (arrayJug.length != arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\treturn;\n\t}\n\telse {\n\t\tanimacionGmOver()\n\t}\t\n\n}", "compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }", "function guess(wordToGuess, wordState, currGuess){\n \tfor(let i = 0; i < wordToGuess.length; i++){\n\t\tif(wordToGuess[i] == currGuess){\n\t\t\twordState[i] = currGuess;\n\t \t} \t\n \t }\n \t \n \t displayWordState(wordState);\n \t const won = checkWon(wordState);\n\n\t window.alert('You won!')\n\t\t\n\n }", "function jump_possible(board, player)\n{\n // initiate array to contain all possible moves\n var Moves = [];\n // ensure game is not over\n if (hasWon(board) != 0)\n {\n return Moves;\n }\n // check if player 2\n if (player == 2)\n {\n // treated player incorrectly throughout function, if player = 2, then maps\n // to a tile value of 3\n player = 3;\n }\n if (player == 1)\n {\n // iterate over each row index for board\n for (var i = 0; i < 8; i++)\n {\n // iterate over each column index for board\n for (var x = 0; x < 8; x++)\n {\n // dealing with player 1 regular piece\n if (board[i][x] == player)\n {\n // ensure not on bottom boundary\n if (i + 1 <= board.length - 1)\n {\n // ensure not on right boundary\n if (x + 1 <= board.length - 1)\n {\n // check if bottom right diagonal is empty\n if (board[i + 1][x + 1] == 0)\n {\n // make 2d array with starting, landing indexes\n var temp = [[i, x], [i + 1,x + 1]];\n // add to Moves array\n Moves.push(temp);\n }\n }\n // ensure not on left boundary\n if (x - 1 >= 0)\n {\n // check if bottom left cell is empty\n if (board[i + 1][x - 1] == 0)\n {\n // make 2d array with starting, landing indexes\n var temp = [[i, x], [i + 1, x - 1]];\n // add to Moves array\n Moves.push(temp);\n }\n }\n }\n // checking for captures now \n // ensure not hopping beyond bottom boundary\n if (i + 2 <= board.length - 1)\n {\n // ensure not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if right diagonal cell is opponent and next diagonal is empty\n if ((board[i + 1][x + 1] == 3 || board[i + 1][x + 1] == 4) && board[i + 2][x + 2] == 0)\n {\n // make 2d array with starting, landing indexes\n var temp = [[i, x], [i + 2, x + 2]];\n // add to Moves array\n Moves.push(temp);\n }\n }\n // ensure not hopping beyond left boundary\n if (x - 2 >= 0)\n {\n // if left diagonal is opponent and next diagonal is empty\n if ((board[i + 1][x - 1] == 3 || board[i + 1][x - 1] == 4) && board[i + 2][x - 2] == 0)\n {\n // make 2d array with starting, landing indexes\n var temp =[[i, x], [i + 2, x - 2]];\n // add to Moves array\n Moves.push(temp);\n }\n }\n }\n }\n // now checking king for player 1, need to check more directions\n // if cell contains a king for player 1\n else if (board[i][x] == 2)\n {\n // if not on right boundary\n if (i + 1 <= board.length - 1)\n {\n // if not on bottom boundary\n if (x + 1 <= board.length - 1)\n {\n // if bottom right diagonal is empty\n if (board[i + 1][x + 1] == 0)\n {\n // add bottom right move\n var temp = [[i, x], [i + 1, x + 1]];\n Moves.push(temp);\n }\n }\n // if not on left boundary\n if (x - 1 >= 0)\n {\n // if bottom left diagonal is empty\n if (board[i + 1][x - 1] == 0)\n {\n // add bottom left move\n var temp = [[i, x], [i + 1, x - 1]];\n Moves.push(temp);\n }\n }\n }\n // if not on top boundary\n if (i - 1 >= 0)\n {\n // if not on right boundary\n if (x + 1 <= board.length - 1)\n {\n // if top right diagonal is empty\n if (board[i - 1][x + 1] == 0)\n {\n // add top right move\n var temp = [[i, x], [i - 1, x + 1]];\n Moves.push(temp);\n }\n }\n // if not on left boundary\n if (x - 1 >= 0)\n {\n // if top left diagonal is empty\n if (board[i - 1][x - 1] == 0)\n {\n // add top left move\n var temp = [[i, x], [i - 1, x - 1]];\n Moves.push(temp);\n }\n }\n }\n // checking for captures now \n // if not hopping beyond bottom boundary\n if (i + 2 <= board.length - 1)\n {\n // if not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if bottom right diagonal is opponent and next diagonal is empty\n if ((board[i + 1][x + 1] == 3 || board[i + 1][x + 1] == 4) && board[i + 2][x + 2] == 0)\n {\n // add bottom right hop\n var temp = [[i, x], [i + 2, x + 2]];\n Moves.push(temp);\n }\n }\n // if not hopping beyond left boundary\n if (x - 2 >= 0)\n {\n // if bottom left diagonal is opponent and next diagonal is empty\n if ((board[i + 1][x - 1] == 3 || board[i + 1][x - 1] == 4) && board[i + 2][x - 2] == 0)\n {\n // add bottom left hop\n var temp =[[i, x], [i + 2, x - 2]];\n Moves.push(temp);\n }\n }\n }\n // if not hopping beyond top boundary\n if (i - 2 >= 0)\n {\n // if not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if top right diagonal is opponent and next diagonal is empty\n if ((board[i - 1][x + 1] == player + 2 || board[i - 1][x + 1] == player + 3) && board[i - 2][x + 2] == 0)\n {\n // add top right hop\n var temp = [[i, x], [i - 2, x + 2]];\n Moves.push(temp);\n }\n }\n // if not hopping beyond left boundary\n if (x - 2 >= 0)\n {\n // if top left diagonal is opponent and next diagonal is empty\n if ((board[i - 1][x - 1] == player + 2 || board[i - 1][x - 1] == player + 3) && board[i - 2][x - 2] == 0)\n {\n // add top left hop\n var temp =[[i, x], [i - 2, x - 2]];\n Moves.push(temp);\n }\n }\n }\n }\n }\n }\n }\n // so we know it's the other player \n else\n {\n // iterate over each row index\n for (var i = 0; i < board.length; i++)\n {\n // iterate over each column index\n for (var x = 0; x < board[0].length; x++)\n {\n // dealing with other player's regular piece\n if (board[i][x] == player)\n {\n // if not on top boundary\n if (i - 1 >= 0)\n {\n // if not on right boundary\n if (x + 1 <= board.length - 1)\n {\n // if top right diagonal is empty\n if (board[i - 1][x + 1] == 0)\n {\n // add top right move\n var temp = [[i, x], [i - 1, x + 1]];\n Moves.push(temp);\n }\n }\n // if not on left boundary\n if (x - 1 >= 0)\n {\n // if top left diagonal is empty\n if (board[i - 1][x - 1] == 0)\n {\n // add top left move\n var temp = [[i, x], [i - 1, x - 1]];\n Moves.push(temp);\n }\n }\n }\n // checking for captures now \n // if not hopping beyond top boundary\n if (i - 2 >= 0)\n {\n // if not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if top right diagonal is opponent and next diagonal is empty \n if ((board[i - 1][x + 1] == player - 1 || board[i - 1][x + 1] == player - 2) && board[i - 2][x + 2] == 0)\n {\n // add top right hop\n var temp = [[i, x], [i - 2, x + 2]];\n Moves.push(temp);\n }\n }\n // if not hopping beyond left boundary\n if (x - 2 >= 0)\n {\n // if top left diagonal is opponent and next diagonal is empty\n if ((board[i - 1][x - 1] == player - 1 || board[i - 1][x - 1] == player - 2) && board[i - 2][x - 2] == 0)\n {\n // add top left hop\n var temp =[[i, x], [i - 2, x - 2]];\n Moves.push(temp);\n }\n }\n }\n }\n // now checking king for other player, need to check more directions\n // if cell contains other player's king\n else if (board[i][x] == player + 1)\n {\n // if not on bottom boundary\n if (i + 1 <= board.length - 1)\n {\n // if not on right boundary\n if (x + 1 <= board.length - 1)\n {\n // if bottom right diagonal is empty\n if (board[i + 1][x + 1] == 0)\n {\n // add bottom right move\n var temp = [[i, x], [i + 1, x + 1]];\n Moves.push(temp);\n }\n }\n // if not on left boundary\n if (x - 1 >= 0)\n {\n // bottom left is empty\n if (board[i + 1][x - 1] == 0)\n {\n // add bottom left move\n var temp = [[i, x], [i + 1, x - 1]];\n Moves.push(temp);\n }\n }\n }\n // if not on top boundary\n if (i - 1 >= 0)\n {\n // if not on right boundary\n if (x + 1 <= board.length - 1)\n {\n // if top right diagonal is empty\n if (board[i - 1][x + 1] == 0)\n {\n // add top right move\n var temp = [[i, x], [i - 1, x + 1]];\n Moves.push(temp);\n }\n }\n // if not on left boundary\n if (x - 1 >= 0)\n {\n // if top left diagonal is empty\n if (board[i - 1][x - 1] == 0)\n {\n \n // add top left move\n var temp = [[i, x], [i - 1, x - 1]];\n Moves.push(temp);\n }\n }\n }\n // checking for captures now \n // if not hopping beyond bottom boundary\n if (i + 2 <= board.length - 1)\n {\n // if not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if bottom right diagonal is opponent and next diagonal is empty\n if ((board[i + 1][x + 1] == player - 1 || board[i + 1][x + 1] == player - 2) && board[i + 2][x + 2] == 0)\n {\n // add bottom right hop\n var temp = [[i, x], [i + 2, x + 2]];\n Moves.push(temp);\n }\n }\n // if not hopping beyond left boundary\n if (x - 2 >= 0)\n {\n // if bottom left diagonal is opponent and next diagonal is empty\n if ((board[i + 1][x - 1] == player - 1 || board[i + 1][x - 1] == player - 2) && board[i + 2][x - 2] == 0)\n {\n // add bottom left hop\n var temp =[[i, x], [i + 2, x - 2]];\n Moves.push(temp);\n }\n }\n }\n // if not hopping beyond top boundary\n if (i - 2 >= 0)\n {\n // if not hopping beyond right boundary\n if (x + 2 <= board[0].length - 1)\n {\n // if top right diagonal is opponent and next diagonal is empty\n if ((board[i - 1][x + 1] == player - 1 || board[i - 1][x + 1] == player - 2) && board[i - 2][x + 2] == 0)\n {\n // add top right hop\n var temp = [[i, x], [i - 2, x + 2]];\n Moves.push(temp);\n }\n }\n // if not hopping beyond let boundary\n if (x - 2 >= 0)\n {\n // if top left diagonal is opponent and next diagonal is empty\n if ((board[i - 1][x - 1] == player - 1 || board[i - 1][x - 1] == player - 2) && board[i - 2][x - 2] == 0)\n {\n // add top left hop\n var temp =[[i, x], [i - 2, x - 2]];\n Moves.push(temp);\n }\n }\n }\n }\n }\n }\n }\n // to store all possible jumps available\n var jumpMoves = [];\n // iterate over Moves\n for (var i = 0; i < Moves.length; i++)\n {\n // if a capture exists\n if (Math.abs(Moves[i][0][0] - Moves[i][1][0]) != 1)\n {\n // add to jumpMoves\n jumpMoves.push(Moves[i]);\n }\n }\n // if jumps exist\n if (jumpMoves.length > 0)\n {\n // return array of jumps\n return jumpMoves;\n }\n // return array of possible moves\n return Moves;\n}", "function playStrategy (guesses, callback) {\n // Timeout makes it look like the AI is \"thinking\"\n setTimeout(function () {\n callback(randomCell(guesses));\n }, 500);\n \n function randomCell (board) {\n return [\n _.random(guesses.length-1),\n _.random(guesses[0].length-1)\n ];\n }\n }", "function addPlayer(total, index, arr) {\n let players = [];\n for(let i = 0; i < total; i++) {\n if(i === index) {\n players.push('X');\n }\n if (arr[i]){\n players.push(arr[i]);\n }\n }\n return players;\n}", "function check_game_winner(state) {\n\n //Patters variable is an array of patterns with each pattern itself an array of x/y co-oridinates.\n //In order to create the pattern matching technique, every possible winning pattern had to be identified with the co-ordinates recorded.\n //Each individual array is a set of x/y co-ordinates. The first number in the array is x and the second, y. The co-ordinates represent one square obtained by a marker\n //in a winning pattern.\n var patterns = [\n //Start of Diagonal winning patterns top left to right ( \\ )\n //1st column Diagonal\n [[0, 0], [1, 1], [2, 2], [3, 3]], //Works\n [[0, 1], [1, 2], [2, 3], [3, 4]], //Works\n [[0, 2], [1, 3], [2, 4], [3, 5]], //Works\n //2nd column Diagonal\n [[1, 0], [2, 1], [3, 2], [4, 3]], //Works\n [[1, 1], [2, 2], [3, 3], [4, 4]], //Works\n [[1, 2], [2, 3], [3, 4], [4, 5]], //Works\n //3rd column Diagonal\n [[2, 0], [3, 1], [4, 2], [5, 3]], //Works\n [[2, 1], [3, 2], [4, 3], [5, 4]], //Works\n [[2, 2], [3, 3], [4, 4], [5, 5]], //Works\n //4th column Diagonal\n [[3, 0], [4, 1], [5, 2], [6, 3]], //Works\n [[3, 1], [4, 2], [5, 3], [6, 4]], //Works\n [[3, 2], [4, 3], [5, 4], [6, 5]], //Works\n //Start of Diagonal winning patterns top right to left ( / )\n //7th column Diagonal\n [[6, 0], [5, 1], [4, 2], [3, 3]], //Works\n [[6, 1], [5, 2], [4, 3], [3, 4]], //Works\n [[6, 2], [5, 3], [4, 4], [3, 5]], //Works\n //6th column Diagonal\n [[5, 0], [4, 1], [3, 2], [2, 3]], //Works\n [[5, 1], [4, 2], [3, 3], [2, 4]], //Works\n [[5, 2], [4, 3], [3, 4], [2, 5]], //Works\n //5th column Diagonal\n [[4, 0], [3, 1], [2, 2], [1, 3]], //Works\n [[4, 1], [3, 2], [2, 3], [1, 4]], //Works\n [[4, 2], [3, 3], [2, 4], [1, 5]], //Works\n //4th column Diagonal\n [[3, 0], [2, 1], [1, 2], [0, 3]], //Works\n [[3, 1], [2, 2], [1, 3], [0, 4]], //Works\n [[3, 2], [2, 3], [1, 4], [0, 5]], //Works\n //End of Diagonal pattern matching.\n\n //Horizontal pattern, bottom up\n //1st column Horizontal\n [[0, 5], [1, 5], [2, 5], [3, 5]], //Works\n [[1, 5], [2, 5], [3, 5], [4, 5]], //Works\n [[2, 5], [3, 5], [4, 5], [5, 5]], //Works\n [[3, 5], [4, 5], [5, 5], [6, 5]], //Works\n //2nd column Horizontal\n [[0, 4], [1, 4], [2, 4], [3, 4]], //Works\n [[1, 4], [2, 4], [3, 4], [4, 4]], //Works\n [[2, 4], [3, 4], [4, 4], [5, 4]], //Works\n [[3, 4], [4, 4], [5, 4], [6, 4]], //Works\n //3rd column Horizontal\n [[0, 3], [1, 3], [2, 3], [3, 3]], //Works\n [[1, 3], [2, 3], [3, 3], [4, 3]], //Works\n [[2, 3], [3, 3], [4, 3], [5, 3]], //Works\n [[3, 3], [4, 3], [5, 3], [6, 3]], //Works\n //4th column Horizontal\n [[0, 2], [1, 2], [2, 2], [3, 2]], //Works\n [[1, 2], [2, 2], [3, 2], [4, 2]], //Works\n [[2, 2], [3, 2], [4, 2], [5, 2]], //Works\n [[3, 2], [4, 2], [5, 2], [6, 2]], //Works\n //5th column Horizontal\n [[0, 1], [1, 1], [2, 1], [3, 1]], //Works\n [[1, 1], [2, 1], [3, 1], [4, 1]], //Works\n [[2, 1], [3, 1], [4, 1], [5, 1]], //Works\n [[3, 1], [4, 1], [5, 1], [6, 1]], //Works\n //6th column Horizontal\n [[0, 0], [1, 0], [2, 0], [3, 0]], //Works\n [[1, 0], [2, 0], [3, 0], [4, 0]], //Works\n [[2, 0], [3, 0], [4, 0], [5, 0]], //Works\n [[3, 0], [4, 0], [5, 0], [6, 0]], //Works\n //End of Horizontal patterns\n\n //Vertical patterns, top down.\n //1st column Vertical\n [[0, 0], [0, 1], [0, 2], [0, 3]], //Works\n [[0, 1], [0, 2], [0, 3], [0, 4]], //Works\n [[0, 2], [0, 3], [0, 4], [0, 5]], //Works\n //2nd column Vertical\n [[1, 0], [1, 1], [1, 2], [1, 3]], //Works\n [[1, 1], [1, 2], [1, 3], [1, 4]], //Works\n [[1, 2], [1, 3], [1, 4], [1, 5]], //Works\n //3rd column Vertical\n [[2, 0], [2, 1], [2, 2], [2, 3]], //Works\n [[2, 1], [2, 2], [2, 3], [2, 4]], //Works\n [[2, 2], [2, 3], [2, 4], [2, 5]], //Works\n //4th column Vertical\n [[3, 0], [3, 1], [3, 2], [3, 3]], //Works\n [[3, 1], [3, 2], [3, 3], [3, 4]], //Works\n [[3, 2], [3, 3], [3, 4], [3, 5]], //Works\n //5th column Vertical\n [[4, 0], [4, 1], [4, 2], [4, 3]], //Works\n [[4, 1], [4, 2], [4, 3], [4, 4]], //Works\n [[4, 2], [4, 3], [4, 4], [4, 5]], //Works\n //6th column Vertical\n [[5, 0], [5, 1], [5, 2], [5, 3]], //Works\n [[5, 1], [5, 2], [5, 3], [5, 4]], //Works\n [[5, 2], [5, 3], [5, 4], [5, 5]], //Works\n //7th column Vertical\n [[6, 0], [6, 1], [6, 2], [6, 3]], //Works\n [[6, 1], [6, 2], [6, 3], [6, 4]], //Works\n [[6, 2], [6, 3], [6, 4], [6, 5]], //Works\n //End of pattern matching\n ];\n\n //Load the current game state\n // var state = this.get('state');\n //Loop over all winning patters (patterns.length)\n for(var pidx = 0; pidx < patterns.length; pidx++) {\n //Assign each pattern to the 'pattern' variable\n var pattern = patterns[pidx];\n //Get the states current value pattern at the patterns first co-orindates\n var winner = state[pattern[0][0]][pattern[0][1]];\n\n if(winner) {\n //Loop over all other co-ordinates starting at 'idx1'. If the winner value is different to the value at any other co-ordinates\n //of the pattern, set the winner to undefined.\n for(var idx = 1; idx < pattern.length; idx++ ) {\n if(winner != state[pattern[idx][0]][pattern[idx][1]]) {\n winner = undefined;\n break;\n }\n }\n //If after checking all other co-ordinates in the pattern, the winner is still set to a value, then set that value as the components\n //winner property and stop checking other patterns.\n if(winner) {\n return winner;\n //this.set('winner', winner)\n //break;\n }\n }\n }\n //Initial assumption of a draw\n var draw = true;\n //Loop over all squares in the state, check if any values are undefined.\n for(var x = 0; x <=6; x++) {\n for(var y = 0; y <=5; y++) {\n if(!state[x][y]) {\n return undefined;\n //draw = false;\n //break;\n }\n }\n }\n //After checking all the squares, set the draw value as the current value of the components 'draw' property.\n //this.set('draw', draw);\n return '';\n}", "function makeHappy(arr){\n let result = arr.map(word => \"Happy \" + word)\n return result\n}", "function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\n}", "function footballPoints(wins, draws, losses) {\n\treturn wins * 3 + draws * 1;\n}", "function neuesBoard(array) {\n let zufall = random(1, 3);\n if (zufall == 1) createBoard(firstArray);\n else if (zufall == 2) createBoard(secondArray);\n else createBoard(thirdArray);\n}", "function addGuesses(guess) {\n guesses.push(guess);\n if (guesses.length == 5) {\n\n canPlay = false;\n $('#status').text('Waiting for other player...');\n\n guesses.sort(function(a, b) {return a-b});\n\n $('#guess_log').text('Guesses: ' + guesses);\n socket.emit('guesses-ships', {\n guesses: guesses,\n ships: myShips,\n player: sessionID\n });\n }\n}", "function pushNextBallsToBoard() {\r\n\tvar nNewEmptyCellKey;\r\n\tvar sNewEmptyCellID;\r\n\r\n\tfor (var i = 0; (i < 3); i++) {\r\n\t\tif ((aNextBalls[i].toAppear !== \"\")\r\n\t\t\t\t&& (!isEmpty(aNextBalls[i].toAppear))) {\r\n\t\t\t// find an empty cell\r\n\t\t\tnNewEmptyCellKey = Math.floor(Math.random() * aEmptyCellIDs.length);\r\n\t\t\tsNewEmptyCellID = aEmptyCellIDs[nNewEmptyCellKey];\r\n\t\t} else {\r\n\t\t\tsNewEmptyCellID = aNextBalls[i].toAppear;\r\n\t\t}\r\n\t\t// set new color, place the ball\r\n\t\tsetColor(aNextBalls[i].color, aCellByIDs[sNewEmptyCellID]); // \r\n\t\tfindColorBlocks(sNewEmptyCellID);\r\n\t\tif (aEmptyCellIDs.length === 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (aEmptyCellIDs.length === 0) {\r\n\t\talert(\"No more empty cells, game ends.\");\r\n\t\tif (nTotalScore > oGameSettings.nHighScore) {\r\n\t\t\twindow.localStorage.highScore = nTotalScore;\r\n\t\t\toGameSettings.nHighScore = nTotalScore;\r\n\r\n\t\t\talert(\"congratulation! you have made a new high score.\")\r\n\t\t}\r\n\t\tnewGame();\r\n\t\treturn true;\r\n\t} else {\r\n\t\tgetNextBallColors();\r\n\t}\r\n\treturn true;\r\n}", "function rollForWinner()\r\n{\r\n var randomNum = Math.floor(Math.random() * raffleArray.length);\r\n winner = raffleArray[randomNum];\r\n\r\n return winner;\r\n}", "function shoutGreetings(array) {\nreturn array.map(elem => \n elem.toUpperCase() + `!`\n)\n}", "function checkForWin(plays)\n{\n let matches = getPossibleMatches(plays);\n\n //scans the object for any instances of 'xxx/' or 'ooo/' which indicates a\n //win\n const winner = Object.values(matches).reduce((result, direction) =>\n {\n if(result !== '_')\n {\n return result;\n }\n if(direction.includes('xxx/'))\n {\n return 'x';\n }\n if(direction.includes('ooo/'))\n {\n return 'o';\n }\n return '_';\n }, '_');\n\n //checks for a tie\n if(plays.indexOf('_') === -1 && winner === '_')\n {\n return 't';\n }\n\n return winner;\n}", "function testWinCondition(row, col) {\n let t = boardState[row][col]; //last played token\n let bs = boardState;\n\n //DOWN\n if (row<=2 && t==bs[row+1][col] && t==bs[row+2][col] && t==bs[row+3][col])\n return (true);\n \n //DIAGONAL FORWARD - POSITION 1\n else if (row>=3 && col<=3 && t==bs[row-1][col+1] && t==bs[row-2][col+2] && t==bs[row-3][col+3])\n return (true);\n //DIAGONAL FORWARD - POSITION 2\n else if (row>=2 && row<=4 && col>=1 && col<=4 && t==bs[row+1][col-1] && t==bs[row-1][col+1] && t==bs[row-2][col+2])\n return (true);\n //DIAGONAL FORWARD - POSITION 3\n else if (row>=1 && row<=3 && col>=2 && col<=5 && t==bs[row+2][col-2] && t==bs[row+1][col-1] && t==bs[row-1][col+1])\n return (true);\n //DIAGONAL FORWARD - POSITION 4\n else if (row<=2 && col>=3 && t==bs[row+3][col-3] && t==bs[row+2][col-2] && t==bs[row+1][col-1])\n return (true);\n\n //DIAGONAL BACKWARD - POSITION 1\n else if (row<=2 && col<=3 && t==bs[row+1][col+1] && t==bs[row+2][col+2] && t==bs[row+3][col+3])\n return (true);\n //DIAGONAL BACKWARD - POSITION 2\n else if (row>=1 && row<=3 && col>=1 && col<=4 && t==bs[row-1][col-1] && t==bs[row+1][col+1] && t==bs[row+2][col+2])\n return (true);\n //DIAGONAL BACKWARD - POSITION 3\n else if (row>=2 && row<=4 && col>=2 && col<=5 && t==bs[row-2][col-2] && t==bs[row-1][col-1] && t==bs[row+1][col+1])\n return (true);\n //DIAGONAL BACKWARD - POSITION 4\n else if (row>=3 && col>=3 && t==bs[row-3][col-3] && t==bs[row-2][col-2] && t==bs[row-1][col-1])\n return (true);\n \n //HORIZONTAL - POSITION 1\n else if (col<=3 && t==bs[row][col+1] && t==bs[row][col+2] && t==bs[row][col+3])\n return (true);\n //HORIZONTAL - POSITION 2\n else if (col>=1 && col<=4 && t==bs[row][col-1] && t==bs[row][col+1] && t==bs[row][col+2])\n return (true);\n //HORIZONTAL - POSITION 3\n else if (col>=2 && col<=5 && t==bs[row][col-2] && t==bs[row][col-1] && t==bs[row][col+1])\n return (true);\n //HORIZONTAL - POSITION 4\n else if (col>=3 && t==bs[row][col-3] && t==bs[row][col-2] && t==bs[row][col-1])\n return (true);\n else \n return (false);\n}", "function searchForPlay(plays)\n{\n //all possible win combinations\n let matches = getPossibleMatches(plays);\n //a dumbed down version of possible win combinations (Basically, a count\n //of numbers of x's, o's, and blanks of each win combination on the board)\n let simplifiedMatches = simplifyMatches(matches);\n //the indexes for win combinations, based on a board like this: 0 1 2\n // 3 4 5\n // 6 7 8\n const matchIndexes = '012/345/678/036/147/258/048/246/';\n // the number of x's and o's respectively in a match possibility\n const typeOfPlays = [\n '02/', //checks if there is a play for a win\n '20/', //checks if the opponent needs to be blocked from a win\n '01/', //checks for possibility of two o tiles and a blank spot\n '00/' //checks for possibility of one o tile in a line of blank spots\n ];\n //the index for the variable 'matchIndexes' to chose\n let matchIndex = -1;\n\n //iterates through 'typeOfPlays' in respective order, and determines an\n //exact 'typeOfPlay' once the best option is found\n typeOfPlays.forEach(typeOfPlay =>\n {\n //checks the possiblility of given 'typeOfPlay'\n let isPlay = ((simplifiedMatches.horizontal.includes(typeOfPlay)) || (simplifiedMatches.vertical.includes(typeOfPlay)) || (simplifiedMatches.diagonal.includes(typeOfPlay)));\n\n //if a typeOfPlay has not yet been determined and a typeOfPlay has now\n //been determined than an exact 'matchIndex' is determined\n if(isPlay && matchIndex === -1)\n {\n matchIndex = determineExactPlay(simplifiedMatches, typeOfPlay);\n }\n });\n\n //checks if a play was found\n if(matchIndex > -1)\n {\n //finds match\n let indexesForMatch = matchIndexes.split('/')[matchIndex].split('');\n\n //iterates through the three spots of the match to find the blank spot\n //to play an 'o'\n for(let i = 0; i < indexesForMatch.length; i++)\n {\n if(plays[indexesForMatch[i]] === '_')\n {\n return indexesForMatch[i];\n }\n }\n }\n\n //if a logical play is not found an 'o' is placed anywhere that is blank\n return plays.indexOf('_');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add restore default handler
function addRestoreDefaultThemeHandler() { $(document).on("click", "#open-chrome-settings-url", function (e) { e.preventDefault(); chrome.tabs.create({ url: 'chrome://settings/' }); }); $(document).on("click", "#restore-default-theme-dialog-body", function (e) { e.preventDefault(); openUrlInNewTab($(this).find("#restore-default-theme-description").attr("src")); }); }
[ "setFallback(handler) {\n const fallbackGroup = new RouteGroup_1.default(constants_1.ROUTES_FALLBACK);\n fallbackGroup.match(null, handler);\n this.fallback = fallbackGroup;\n }", "function restoreAll() {\n clientMethods.forEach(function (methodName) {\n monitor[methodName].restore();\n });\n}", "restoreResource(resourceName, resourceId, callback = null) {\n return axios.put(`/${resourceName}/${resourceId}/restore`).then(callback)\n }", "function setupHandlers() {\n\n function terminate(err) {\n util.log('Uncaught Error: ' + err.message);\n console.log(err.stack);\n if (proc.shutdownHook) {\n proc.shutdownHook(err, gracefulShutdown);\n }\n }\n\n process.on('uncaughtException', terminate);\n\n process.addListener('SIGINT', gracefulShutdown);\n\n process.addListener('SIGHUP', function () {\n util.log('RECIEVED SIGHUP signal, reloading log files...');\n reload(argv);\n });\n\n}", "function restore() {\n // callback on after sync.get\n function onComplete(data) {\n var err = chrome.runtime.lastError;\n var schemaString = err || JSON.stringify(data['copy-agent-schema'], null, 2);\n\n delete chrome.runtime.lastError;\n\t\tdocument.getElementById('copy-agent-schema').value = schemaString;\n }\n\n chrome.storage.sync.get({'copy-agent-schema': defaultSchema}, onComplete);\n}", "function ConventionalHandler() {\r\n}", "restore() {\n FetchServer.restore();\n }", "function extendHandlerObject(handlerObject, path) {\n //Instead of passing an object with only a handler property,\n //the user can pass just that property (the action name, a string).\n //In that case, create a full-fledgec handlerObject now.\n if (typeof handlerObject === 'string') {\n handlerObject = {\n handler: handlerObject,\n };\n }\n //Turn the handler property, now the action name, into a function.\n var handler = handlerObject.handler;\n handlerObject.handler = function(args) {\n args = [handler].concat(args);\n var result = virgilio.execute.apply(virgilio, args);\n if (handlerObject.timeout) {\n result.withTimeout(handlerObject.timeout);\n }\n return result;\n };\n handlerObject.validate = getValidationHandler(handlerObject.schema);\n\n //Extend the handlerObject with defaults.\n handlerObject.transform =\n handlerObject.transform || getDefaultTransform(path);\n handlerObject.respond = handlerObject.respond || defaultRespond;\n handlerObject.error = handlerObject.error || defaultError;\n handlerObject.validationError = handlerObject.validationError ||\n defaultValidationError;\n handlerObject.fallbackError = defaultError;\n return handlerObject;\n }", "static restore() {\n // restore fetch in browser environment:\n if (typeof window !== `undefined` && window.fetch && Object.hasOwnProperty.call(window.fetch, `restore`)) {\n window.fetch.restore();\n }\n // restore fetch in NodeJS environment:\n if (typeof global !== `undefined` && global.fetch && Object.hasOwnProperty.call(global.fetch, `restore`)) {\n global.fetch.restore();\n }\n }", "_addRestoreButton(){\n this.add(this.options, 'restore').name('Restore').onChange((value) => {\n if (this.isView3D) {\n this.threeRenderer.center3DCameraToData(this.dataHandler);\n }else{\n this.threeRenderer.center2DCameraToData(this.dataHandler);\n }\n });\n }", "_onTriggerInternalHelperDefaults(triggerHelper) {\n this.currentFunction = '_onTriggerInternalHelperDefaults';\n super._onTriggerInternalHelperDefaults(triggerHelper);\n }", "function initAll(handler){\r\n let overrideProxy=new Proxy({},{\r\n has:function(target,prop){\r\n return true\r\n },\r\n get:function(target,prop){\r\n return newElementHolderProxy()[prop](handler)\r\n }\r\n }\r\n )\r\n return newElementHolderProxy(undefined,overrideProxy)\r\n }", "setDefaultCallback(callback) {\n this._defaultCallback = callback;\n }", "function normalizeHandlers(routes) {\n routes.forEach((route) => {\n const defaultHandler = route.handler;\n route.handler = async (request, h) => {\n const result = await defaultHandler(request, h);\n return _.isUndefined(result) ? null : result;\n };\n });\n}", "function _new_handlerx( effect_name, reinit_fun, return_fun, finally_fun,\n branches0, handler_kind, handler_tag, wrap_handler_tag)\n{\n // initialize the branches such that we can index by `op_tag`\n // regardless if the `op_tag` is a number or string.\n const branches = new Array(branches0.length);\n for(let i = 0; i < branches0.length; i++) {\n const branch = branches0[i];\n branches[branch.op_tag] = branch;\n if (typeof op_tag !== \"number\") branches[i] = branch;\n }\n var shared_hinfo = null;\n // return a handler function: `action` is executed under the handler.\n return (function(action,local) {\n // only resources need to recreate the `hinfo` due to the handlertag\n // todo: also store the handler tag in the Handler instead of the Info\n var hinfo = shared_hinfo;\n if (hinfo==null) {\n hinfo = new HandlerInfo(effect_name, reinit_fun, return_fun, finally_fun,\n branches, 0, handler_kind, handler_tag);\n }\n if (wrap_handler_tag==null && shared_hinfo==null) {\n shared_hinfo = hinfo;\n }\n\t // the handler action gets the resource argument (the identifier of the handler)\n\t\tconst haction = function() {\n const resource = (wrap_handler_tag==null ? hinfo.handler_tag :\n wrap_handler_tag(hinfo.handler_tag));\n return yield_iter( action( resource ) ); // autoconvert from iterators\n };\n return _handle_action(hinfo, local, haction );\n });\n}", "function attachHandlers(options) {\n // XXXBramble: we want to reuse this code for the UploadFiles extension\n // so we add support for passing exra options here.\n options = options || {};\n options.elem = options.elem || window.document.body;\n // Support optional events hooks\n var noop = function(){};\n options.ondragover = options.ondragover || noop;\n options.ondragleave = options.ondragleave || noop;\n options.ondrop = options.ondrop || noop;\n options.onfilesdone = options.onfilesdone || noop;\n\n // XXXBramble: extra dragleave event for UI updates in UploadFiles\n function handleDragLeave(event) {\n event = event.originalEvent || event;\n event.stopPropagation();\n event.preventDefault();\n\n options.ondragleave(event);\n }\n\n function handleDragOver(event) {\n event = event.originalEvent || event;\n stopURIListPropagation(event);\n\n event.stopPropagation();\n event.preventDefault();\n options.ondragover(event);\n\n var dropEffect = \"none\";\n // XXXBramble: we want to reuse this in the UploadFiles modal, so treat body differently\n if(isValidDrop(event.dataTransfer.types)) {\n if(options.elem === window.document.body) {\n if($(\".modal.instance\").length === 0) {\n dropEffect = \"copy\";\n }\n } else {\n dropEffect = \"copy\";\n }\n }\n event.dataTransfer.dropEffect = dropEffect;\n }\n\n function handleDrop(event) {\n event = event.originalEvent || event;\n stopURIListPropagation(event);\n\n event.stopPropagation();\n event.preventDefault();\n options.ondrop(event);\n\n processFiles(event.dataTransfer, function(err) {\n if(err) {\n console.log(\"[Bramble] error handling dropped files\", err);\n }\n\n options.onfilesdone();\n\n if(options.autoRemoveHandlers) {\n var elem = options.elem;\n $(elem)\n .off(\"dragover\", handleDragOver)\n .off(\"dragleave\", handleDragLeave)\n .off(\"drop\", handleDrop);\n\n elem.removeEventListener(\"dragover\", codeMirrorDragOverHandler, true);\n elem.removeEventListener(\"dragleave\", codeMirrorDragLeaveHandler, true);\n elem.removeEventListener(\"drop\", codeMirrorDropHandler, true);\n }\n });\n }\n\n // For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g.\n // the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel)\n $(options.elem)\n .on(\"dragover\", handleDragOver)\n .on(\"dragleave\", handleDragLeave)\n .on(\"drop\", handleDrop);\n\n // Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops\n // propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag\n // events. See bug #10617.\n var codeMirrorDragOverHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDragOver(event);\n }\n };\n var codeMirrorDropHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDrop(event);\n }\n };\n var codeMirrorDragLeaveHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDragLeave(event);\n }\n };\n options.elem.addEventListener(\"dragover\", codeMirrorDragOverHandler, true);\n options.elem.addEventListener(\"dragleave\", codeMirrorDragLeaveHandler, true);\n options.elem.addEventListener(\"drop\", codeMirrorDropHandler, true);\n }", "function RestoreNewSystem(restorePath)\r\n{\r\n\t// Verify that the directories and files are there\r\n\tif (! CheckFolderExists (restorePath))\r\n\t\t{\r\n\t\tthrow \"Cannot find folder \" + restorePath ;\r\n\t\t}\r\n\tif (! CheckFolderExists (restorePath + \"\\\\ACP Settings\"))\r\n\t\t{\r\n\t\tthrow \"Cannot find folder \" + restorePath + \"\\\\ACP Settings\";\r\n\t\t}\r\n\tif (! CheckFolderExists (restorePath + \"\\\\FMx Settings\"))\r\n\t\t{\r\n\t\tthrow \"Cannot find folder \" + restorePath + \"\\\\FMx Settings\";\r\n\t\t}\r\n\tif (! CheckFolderExists (restorePath + \"\\\\Maxim Settings\"))\r\n\t\t{\r\n\t\tthrow \"Cannot find folder \" + restorePath + \"\\\\Maxim Settings\";\r\n\t\t}\r\n\tif (! CheckFolderExists (restorePath + \"\\\\Maxim Settings\\\\Settings\"))\r\n\t\t{\r\n\t\tthrow \"Cannot find folder \" + restorePath + \"\\\\Maxim Settings\\\\Settings\";\r\n\t\t}\r\n\t\r\n\tDisconnectACP();\r\n\t// Stop FocusMax and Maxim. \r\n\tif(!StopProcess(FOCUSMAX))\r\n Console.PrintLine(\"*** Failed to stop FocusMax\");\r\n Util.WaitForMilliseconds(1000);\r\n if(!StopProcess(MAXIM))\r\n Console.PrintLine(\"*** Failed to stop MaxIm\");\r\n Util.WaitForMilliseconds(1000);\r\n \r\n RestoreACPSettings(restorePath + \"\\\\ACP Settings\");\r\n\t\r\n\t\r\n RestoreFMxSettings(restorePath + \"\\\\FMx Settings\");\r\n\t\r\n\tRestoreMaximSettings(restorePath + \"\\\\Maxim Settings\");\r\n\t\r\n}", "_restoreGnomeShellFunctions() {\n // Restore normal Dash\n if (this._settings.get_boolean('hide-dash')) {\n if (!DashToDock) {\n // Show normal dash (if no dash-to-dock)\n Main.overview.dash.show();\n Main.overview.dash.set_width(-1);\n // This forces the recalculation of the icon size\n Main.overview.dash._maxHeight = -1;\n }\n }\n\n // Restore source of swarm animation to normal apps button\n if (GSFunctions['BaseAppView_doSpringAnimation']) {\n AppDisplay.BaseAppView.prototype._doSpringAnimation = GSFunctions['BaseAppView_doSpringAnimation'];\n }\n\n // Show normal workspaces thumbnailsBox\n Main.overview._overview._controls._thumbnailsSlider.opacity = 255;\n\n // Restore normal WorkspaceSwitcherPopup_show function\n WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show = GSFunctions['WorkspaceSwitcherPopup_show'];\n\n // Restore normal LayoutManager _updateRegions function\n Layout.LayoutManager.prototype._updateRegions = GSFunctions['LayoutManager_updateRegions'];\n\n // Restore normal WorkspacesDisplay _updateworksapgesActualGeometray function\n WorkspacesView.WorkspacesDisplay.prototype._updateWorkspacesActualGeometry = GSFunctions['WorkspacesDisplay_updateWorkspacesActualGeometry'];\n\n // Restore normal WorkspacesView _setActualGeometry function\n WorkspacesView.WorkspacesViewBase.prototype.setActualGeometry = GSFunctions['WorkspacesViewBase_setActualGeometry'];\n WorkspacesView.WorkspacesViewBase.prototype.setMyActualGeometry = null;\n }", "function handler(req, res, next) {\n readEntity(req, res, () => patchHandler(req, res, next))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates and positions the small glow elements on the screen
static generateSmallGlows(number) { let h = $(window).height(); let w = $(window).width(); let scale = (w > h) ? h/800 : w/1200; h = h/scale; w = w/scale; for(let i = 0; i < number; i++) { let left = Math.floor(Math.random()*w) / 1280 * 100; let top = Math.floor(Math.random()*(h/2)) / 800 * 100; let size = Math.floor(Math.random()*8) + 4; $('.small-glows').prepend('<div class="small-glow"></div>'); let noise = $('.small-glows .small-glow').first(); noise.css({left: left + '%', top: top + '%', height: size, width: size}); } }
[ "function render() {\n background.removeAllChildren();\n\n // TODO: 2 - Part 2\n // this fills the background with a obnoxious yellow\n // you should modify this to suit your game\n var backgroundFill = draw.rect(canvasWidth, groundY, '#5d43a3');\n background.addChild(backgroundFill);\n \n // TODO: 3 - Add a moon and starfield //+cloud buddy\n \n var circle;\n for(var i = 0; i < 700; i++) {\n circle = draw.circle(1, '#faf67d', '#dec14e', 1);\n circle.x = canvasWidth * Math.random();\n circle.y = groundY * Math.random();\n background.addChild(circle);\n }\n \n var cursedMoon = draw.bitmap('img/cursedmoon.png');\n cursedMoon.x = 500;\n cursedMoon.y = 0;\n cursedMoon.scaleX = 0.4;\n cursedMoon.scaleY = 0.3;\n background.addChild(cursedMoon);\n \n var happyCloud = draw.bitmap('img/happycloudfriend.png');\n happyCloud.x = 0;\n happyCloud.y = 0; \n happyCloud.scaleX = 0.3;\n happyCloud.scaleY = 0.3;\n background.addChild(happyCloud);\n \n // TODO: 5 - Add buildings! Q: This is before TODO 4 for a reason! Why?\n //I added some other stuff besides the required buildings.\n \n ufo = draw.bitmap('img/pinkufo.png');\n ufo.x = 150;\n ufo.y = -100;\n ufo.scaleX = 0.8; \n ufo.scaleY = 0.8; \n background.addChild(ufo);\n \n for(var fNum = 0; fNum < 150; fNum++) {\n fish = draw.bitmap('img/flyingfish.png');\n fish.scaleX = 0.05;\n fish.scaleY = 0.05; //am very tired type type toopity toop toop tip\n fish.x = canvasWidth * Math.random(); //(translation: figure out how you're going to put this fishys in)\n fish.y = groundY * Math.random();\n background.addChild(fish);\n }\n\n //Required buildings below >>>\n for(var i = 0; i < 8; i++) {\n var buildingHeights = [300, 130, 190, 175, 250, 300, 190, 250];\n var buildingColors = ['Purple', 'Indigo', 'DarkBlue', 'Teal', 'Pink', 'Red', 'Purple', 'Indigo', 'DarkBlue', 'Teal'];\n var building = draw.rect(75, buildingHeights[i], buildingColors[i], 'LightGray', 1);\n building.x = 200 * i;\n building.y = groundY - buildingHeights[i];\n background.addChild(building);\n buildings.push(building);\n }\n //Required buildings above <<<\n \n alienHouse = draw.bitmap('img/alienhouse.png');\n alienHouse.x = 1100;\n alienHouse.y = groundY - 296;\n alienHouse.scaleX = 0.6; \n alienHouse.scaleY = 0.6;\n background.addChild(alienHouse);\n \n // TODO 4: Part 1 - Add a tree //+something else\n tree = draw.bitmap('img/weirdtree.png');\n tree.x = 930;\n tree.y = groundY - 265;\n tree.scaleX = 0.2;\n tree.scaleY = 0.2;\n background.addChild(tree);\n \n sign = draw.bitmap('img/pinkwoodsign.png');\n sign.x = 1450;\n sign.y = groundY - 395;\n sign.scaleX = 0.3;\n sign.scaleY = 0.3;\n background.addChild(sign);\n \n /*blueDuck = draw.bitmap('img/bigblueduck.png');\n blueDuck.x = 300;\n blueDuck.y = 265;\n blueDuck.scaleX = 0.4;\n blueDuck.scaleY = 0.4;\n background.addChild(blueDuck);*/\n \n } // end of render function - DO NOT DELETE", "function setupHUDelements(){\n\tfor (var i = 0; i < 10; i++){ //Set up bitmaps now so that all we do later is turn them on\n\t\thudElements.eggBitmaps[i] = new createjs.Bitmap(imageEgg);\n\t\thudElements.eggBitmaps[i].sourceRect = new createjs.Rectangle(0,0,20,30);\n\t\thudElements.eggBitmaps[i].x = (thecanvas.width - 20) - (15 * i);\n\t\thudElements.eggBitmaps[i].y = 245;\n\t\thudElements.eggBitmaps[i].scaleX = .5;\n\t\thudElements.eggBitmaps[i].scaleY = .5;\n\t}\n\t\n\thudElements.scoreText = new createjs.Text(\"score: \" + score, \"16px Arial\", \"#fff\");\n\thudElements.scoreText.x = 10;\n\thudElements.scoreText.y = 260;\n\tstage.addChild(hudElements.scoreText);\n\t\n\thudElements.speedText = new createjs.Text(\"speed: \", \"16px Arial\", \"#fff\");\n\thudElements.speedText.x = 150;\n\thudElements.speedText.y = 260;\n\tstage.addChild(hudElements.speedText);\n\t\n hudElements.speedBarG = new createjs.Graphics();\n\thudElements.speedBarG.beginFill(\"#d33\");\n\thudElements.speedBarG.rect(0,0,1, 20);\n\thudElements.speedBarShape = new createjs.Shape(hudElements.speedBarG);\n\thudElements.speedBarShape.x = 200;\n\thudElements.speedBarShape.y = 245;\n\t\n\tstage.addChild(hudElements.speedBarShape);\n\t\n}", "function drawStart(x, y, size, alpha){\r\n\tvar blue = color(\"blue\");\r\n\tblue.setAlpha(alpha);\r\n\r\n\tfill(blue);\r\n\t//rect(x+size/5, y+size/5, size*3/5);\r\n\trect(x+size/4, y+size/4, size/2);\r\n}", "function Create_mini_frame()\n{\n var $frame = CreateCircle(1.2,40,true);\n util_ChangeColor($frame,new Color(94/255,94/255,94/255,1));\n \n _create_circle_notch($frame,1,12,new Vector3(0.02,0.02,0.1),Color.white);\n \n _create_circle_text($frame,[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\"],0.8,0.04,-0.01,Color.white);\n \n return $frame;\n}", "function createElementsForPopup() {\r\n _dom.el.css(\"position\", \"absolute\");\r\n _dom.el.addClass(\"s-c-p-popup\");\r\n _dom.arrow = $(\"<div></div>\")\r\n .appendTo(_dom.el)\r\n .addClass(\"s-c-p-arrow\");\r\n _dom.arrowInner = $(\"<div></div>\")\r\n .appendTo(_dom.arrow)\r\n .addClass(\"s-c-p-arrow-inner\");\r\n }", "function updateGlowStatus(isglow, color) {\r\n clearCanvas(); /* Clear the Canvas first */\r\n drawglow = isglow;\r\n glowClr = color;\r\n drawcells(); /* Redraw the cells */\r\n}", "makeWell() {\n stroke(116, 122, 117);\n strokeWeight(2);\n fill(147, 153, 148);\n ellipse(125, 75, this.pxl, this.pxl);\n fill(0, 0, 255);\n ellipse(125, 75, this.pxl - 10, this.pxl - 10);\n }", "function greenSquare() {\n if(mouseX <= 375 && mouseX >= 25 && mouseY <= 375 && mouseY >= 25 && mouseIsPressed) {\n fill(124,252,0);\n } else {\n fill(0,200,95);\n }\n rect(displacement, displacement, 350, 350);\n}", "initialise_ghosts() {\r\n\r\n // Set up the ghosts animaton sequences for the ghost movement\r\n for (var i = 0; i < this.data.ghosts.length; i ++) {\r\n for (var s=0; s<7; s++) {\r\n this.data.ghosts[i].set_animation_sequence(s, 4, 0, 3); \r\n } \r\n this.data.ghosts[i].set_sprite_status_alive();\r\n this.data.ghosts[i].set_attack_method(i); \r\n this.data.ghosts[i].animate_start(); \r\n }\r\n\r\n\r\n // Set each ghosts start position.\r\n //this.data.ghosts[0].set_position(12 * 24, 12*24 + 12);\r\n this.data.ghosts[0].set_position(16 * 24, 11 * 24 + 12); // red\r\n this.data.ghosts[1].set_position(16 * 24, 14 * 24 + 12); // pink\r\n this.data.ghosts[2].set_position(14 * 24, 14 * 24 + 12); // cyan\r\n this.data.ghosts[3].set_position(18 * 24, 14 * 24 + 12); // yellow\r\n\r\n // Set ghost target for escaping ghost house.\r\n this.data.ghosts[0].set_initial_target(372, 280); // red\r\n this.data.ghosts[1].set_initial_target(372, 280); // pink\r\n this.data.ghosts[2].set_initial_target(372, 280); // cyan\r\n this.data.ghosts[3].set_initial_target(372, 280); // yellow\r\n\r\n // default speed.\r\n var speed = 4, attack = 30, scatter = 7;\r\n var num_levels = this.game_levels.length;\r\n if (this.game_data.level < num_levels) {\r\n speed = this.game_levels[this.game_data.level].ghost_speed;\r\n attack = this.game_levels[this.game_data.level].attack;\r\n scatter = this.game_levels[this.game_data.level].scatter;\r\n }\r\n\r\n for (var i = 0; i < this.data.ghosts.length; i ++) {\r\n this.data.ghosts[i].set_home_position(16 * 24, 14 * 24 + 12);\r\n this.data.ghosts[i].initialise();\r\n this.data.ghosts[i].set_speed(speed);\r\n this.data.ghosts[i].set_attack_count(attack);\r\n this.data.ghosts[i].set_scatter_count(scatter);\r\n }\r\n\r\n this.data.ghosts[1].ghost.release_count=20;\r\n this.data.ghosts[2].ghost.release_count=30;\r\n this.data.ghosts[3].ghost.release_count=40;\r\n\r\n\r\n\r\n // Set scatter locations.\r\n this.data.ghosts[0].set_scatter_target(24*24, 0); // red\r\n this.data.ghosts[1].set_scatter_target(5*24, 0); // pink\r\n this.data.ghosts[2].set_scatter_target(24*24, 28*24) // cyan\r\n this.data.ghosts[3].set_scatter_target(3*24, 28*24) // yellow\r\n\r\n \r\n }", "function lightingSetUp(){\n\n keyLight = new THREE.DirectionalLight(0xFFFFFF, 1.0);\n keyLight.position.set(3, 10, 3).normalize();\n keyLight.name = \"Light1\";\n\n fillLight = new THREE.DirectionalLight(0xFFFFFF, 1.2);\n fillLight.position.set(0, -5, -1).normalize();\n fillLight.name = \"Light2\";\n\n backLight = new THREE.DirectionalLight(0xFFFFFF, 0.5);\n backLight.position.set(-10, 0, 0).normalize();\n backLight.name = \"Light3\";\n\n scene.add(keyLight);\n scene.add(fillLight);\n scene.add(backLight);\n}", "function showStars() {background(\n\t0, 0, 40, sparkle_trail);\n\n\t////moon///\n\tif (started) {\n\t\tfill(255);\n\t\tellipse(100, 100, 150, 150);\n\t\tfill(0, 0, 40);\n\t\tellipse(130, 90, 130, 130);\n\t}////moon///\n\n\tif (!showingStars) {showingStars = true;\n\t\tfor (let i = 0; i < 300; i++) {stars[i] = new Star;}\n\t}\n\tfor (let i = 0; i < stars.length; i++) {\n\t\tstars[i].show();\n\t}\n}////////MAKE 300 STARS AND SHOW THEM////////", "function revealGhosts()\n {\n // Set the position and dimensions of ghostOne to match those of the v-divider.\n ghostOne.style.height = v_Div.style.height;\n ghostOne.style.width = v_Div.style.width;\n ghostOne.style.bottom = 'auto';\n ghostOne.style.right = 'auto';\n ghostOne.style.top = '0px';\n ghostOne.style.left = tlDiv.style.width;\n\n // Set the position and dimensions of ghostTwo to match those of the h-divider.\n ghostTwo.style.height = h_Div.style.height;\n ghostTwo.style.width = h_Div.style.width;\n ghostTwo.style.bottom = 'auto';\n ghostTwo.style.right = 'auto';\n ghostTwo.style.left = '0px';\n ghostTwo.style.top = tlDiv.style.height;\n\n // Reveal the ghost divs\n ghostOne.style.visibility = 'visible';\n ghostTwo.style.visibility = 'visible';\n }", "drawToolRow() {\n let $Div = $('<div />').attr({ id: 'top-row'});\n let $MineCount = $('<input/>').attr({ type: 'text', id: 'mine-count', name: 'mine-count', readonly: true}).val(25);\n let $Timer = $('<input/>').attr({ type: 'text', id: 'timer', name: 'timer', readonly: true}).val('0000');\n let $GridSize = $('<input/>').attr({ type: 'text', id: 'grid-size', name: 'grid-size'}).val(15); // value is the size of the grid. Always a square\n let $Reset = $('<input />').attr({ type: 'button', id: 'reset-button'}).val('Reset').addClass('reset-button');\n let $Music= $('<input />').attr({ type: 'button', id: 'music-button'}).val('Music').addClass('music-button');\n let $gameScreen = $('#game-screen');\n\n $Div.append($MineCount).append($Timer).append($GridSize).append($Reset).append($Music);\n $gameScreen.prepend($Div);\n \n }", "paintShieldBars() {\n if (this.level == this.oldLevel)\n return -1;\n this.oldLevel = this.level;\n var level = this.level;//TODO: fix, don't need two variables\n //console.log(`set to level ${level}`);\n\n if (typeof this.shieldPix != \"undefined\") { // start over\n this.shieldPix.destroy();\n }\n if (level < 1) {\n //console.log(\"oh shit no shield\");\n this.shieldBody.setY(360*assetsDPR);\n return;\n }\n\n var shieldBarWork = [];\n\n var remain = level;\n var spreadTotal = 0;\n var painted = 0;\n\n // as many as 10 bars need to be painted\n for (var bar=0;bar<10;bar++) {\n\n // the boring base height: each bar can be up to 10 high, the last might be shorter, and then 0 for all the rest\n var base = Math.max(0,Math.min(10,level-bar*10));\n if (base > 0)\n painted++; // count the number of bars we're gonna paint\n remain = remain - base;\n var spread = base + remain; // spread them out in interesting fashion\n shieldBarWork.push(spread);\n spreadTotal += spread; // ... and beyond that your guess is as good as mine, will try harder next time\n }\n //console.log(\"painting \" + painted + \" bars\");\n\n var shieldBar = [];\n var finalSumHack = 0;\n for (bar=0;bar<10;bar++) {\n var final = Math.round(level*shieldBarWork[bar]/spreadTotal,0);\n shieldBar.push(final);\n finalSumHack += final;\n }\n shieldBar[0] += level - finalSumHack;\n\n var bottom = 150;\n var blockHeight = 0;\n var shieldPix = this.game.add.graphics({\n x:0,\n y:0\n });\n\n let shieldScale = .5;\n let offset = 280;\n for (bar=0;bar<10;bar++) {\n var alpha = (level-bar*10)/10;\n if (alpha>1)\n alpha = 1;\n //console.log(alpha + \" \" + shieldBar[bar]);\n if (alpha > 0) {\n var top = bottom - shieldBar[bar] +1;\n\n shieldPix.fillStyle(this.fullColorHex ((9-bar)*15,25*bar*(10/painted),255), alpha);\n if (level == 100 && bar==0) {\n //console.log(\"top \" + (top*shieldScale+offset));\n }\n shieldPix.fillRect(318*assetsDPR,(top*shieldScale+offset)*assetsDPR,298*assetsDPR,shieldBar[bar]*shieldScale*assetsDPR);\n blockHeight += shieldBar[bar]*shieldScale; //accumulate the height of all the bars... TODO: finalSumHack?\n bottom = top-1;\n }\n }\n\n shieldPix.closePath();\n this.shieldPix = shieldPix;\n\n // the actual collision body\n var shieldTop = (top*shieldScale+offset)*assetsDPR;\n this.shieldBody.setY(shieldTop);\n }", "function createsnow() {\n let snowContainer = document.getElementById('snow_container');\n snowContainer.innerHTML = '';\n\n // Specify how much snow you want.\n // Based on CSS, only goes up to a max of 50.\n let numSnowFlakes = 50;\n for (; numSnowFlakes > 0; numSnowFlakes--) {\n let snowFlake = document.createElement(\"div\");\n snowFlake.className = 'snow';\n snowContainer.append(snowFlake);\n }\n}", "function createLockLevelPopUp(){\n\t\t\t\t\t\t\tvar levelChoose=new lib.levelChooseBoard();\n\t\t\t\t\t\t\tlevelChoose.x=myStage/2-levelChoose.nominalBounds.width/2;\n\t\t\t\t\t\t\tlevelChoose.y=myStage/2-levelChoose.nominalBounds.height/2;\n\t\t\t\t\t\t\tstage.addChild(levelChoose);\n\t\t\t\t\t\t}", "function createBlueChunk(elementLength,elementStart){\n var blueChunk = document.createElement('div');\n blueChunk.id = 'blueChunk';\n blueChunk.style.width = elementLength+'px';\n blueChunk.style.height = '16px';\n blueChunk.style.left = elementStart+'px';\n blueChunk.style.top = blueTimelineTop+'px';\n blueChunk.style.position = 'absolute';\n blueChunk.style.backgroundColor = blue;\n document.getElementById('timeline').appendChild(blueChunk);\n }", "function start_snowing(num_snowAmount, num_windSpeed, num_fallSpeed){\n\t//clear first (just incase)\n\tarr_snow_div = [];\n\tarr_snow_ids = [];\n\t//\n\tfor (var i = 0; i<num_snowAmount; ++i){\n\t\t//\n\t\tvar snow_flake = document.createElement(\"div\");\n\t\tsnow_flake.id = \"_snow_flake_\" + String(i);\n\t\tsnow_flake.className = \"snow\";\n\t\t//snow.appendChild(snow_flake);\n\t\t//images\n\t\tsnow_flake.innerHTML = '<img src=' + str_snow_imagePath + arr_snow_images[Math.ceil(Math.random()*arr_snow_images.length)-1] + '>';\n\t\tsnow_flake.style.position = 'absolute';\n\t\tsnow_place_randomly(snow_flake);\n\t\tsnow_flake.style.pointerEvents = \"none\";\n\t\t//\n\t\tdocument.getElementsByTagName(\"body\")[0].appendChild(snow_flake);\n\t\tarr_snow_div.push(snow_flake);\n\t\tinit_snow(snow_flake, i, num_windSpeed, num_fallSpeed);\n\t};\n\t//\n}", "function gravity_spawn()\n{\n\tstop_gravity();\n\tspawn_piece();\n\trender_board(board);\n\tqueue_gravity();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
class "DFS" (debugging function state) declaration: class contains information for the debugger, which was used during execution of specific function input(s): mode: (DBG_MODE) debugging mode fr: (frame) function's frame pos: (position) executed posiition, when execution was transfered away from thie function fc: (funcCall) function call reference output(s): (none)
function dfs(mode, fr, pos, fc){ //assign id this._id = dfs.__nextId++; //assign debugging mode this._mode = mode; //assign frame reference this._frame = fr; //assign execution position this._pos = pos; //null function call reference -- it will be assigned by interpreter during invokeCall this._funcCall = fc; //null returning value of this function call -- will be assigned by debugger this._val = 0; }
[ "function dfsAlgorithm() {\r\n const startingPointNode = setDFSAlgorithm(eventStates)\r\n // Set timer to 1s for Animation Frames (in seconds)\r\n runDFSAlgorithm(startingPointNode, eventStates, 1)\r\n visitedNodesAnimation(eventStates, \"DFS\")\r\n // paintVisitedNodes(eventStates, 1) //Timer set to 1second for Animations\r\n}", "function mazeDFS(thisMap, row, col, kind, stack, rowEnd, colEnd, mazeMap) {\nif(debug) {console.log(\"\\n\"+ kind + \" (\" + row + \", \" + col +\") stack: \" + stack.length);}\n\n //###########################\n //## the cell where we are ##\n //###########################\n var cell = thisMap.map[row][col]\n\n if (debug){\n //markers for debug\n if (cell.visited) {\n var colorMark = colors.a4 //yellow, as already been visited\n var widthMark = 1;\n } else {\n var colorMark = colors.b1 //ligth blue, visited for the first time\n var widthMark = 1;\n }; //a dif color for 1st or 2nd time pass\n\n}\n //########################\n //## mark as visited ##\n //########################\n cell.visited = true; //mark as visited\n\n //######################\n //## move options ##\n //######################\n //wich way can we go?\n switch (kind) {\n case \"make\":\n {\n var moveOpt = thisMap.moveOptions(row, col, \"make\");\n break;\n }\n case \"find\":\n {\n var moveOpt = thisMap.moveOptions(row, col, \"find\", mazeMap);\n break;\n }\n }\nif (debug){\n //markers for debug\n if ((moveOpt.length >= 2)) { // a dif color for archor (archor for the last cell visited with more than one route option)\n var colorMark = colors.a1;\n var widthMark = 1;\n}\n //draw the markers\n //## ligth blue, visited only one time\n //## yellow, has already been visited\n //## pink, archor/shortcut cell\n rectCell = thisMap.grid.cellToRectangle(col, row) //rectangle of current cell\n if(cell.visited) { formDFS.fill(colors.b3).stroke(false).rect(rectCell.resizeCenterTo(rectCell.length() / 20))};\n formDFS.fill(false).stroke(colorMark, widthMark).circle(new Circle(rectCell.center).setRadius(rectCell.length() / 40)); //circle marking the cells visited\n }\n //######################################\n //## we reached a dead-end, move back ##\n //######################################\n if (moveOpt.length == 0) {\n\n var nextCell = stack.pop(); //last cell visited\n if(debug) {console.log (\"mv: \" + moveOpt.length + \" poped: \" + nextCell.row +\", \" + nextCell.col + \" \"+nextCell.NESO);}\n\n\n\n if (kind == \"find\") {\n //###########################\n //## rebuilding the walls ##\n //###########################\n //each cell as walls so 2 walls to erase\n var nextCellMap = thisMap.map[nextCell.row][nextCell.col] //and the next cell wall too\n nextCellMap[nextCell.NESO] = true; //this cell wall\n \tcell[\"SONE\".charAt(\"NESO\".indexOf(nextCell.NESO))] = true;\n\n //experiment drwa a cruve to trace the path\n //curve to trace path\n curvePoints.pop();\n curveFind.disconnect(1);\n\n }\n\n\n } else {\n //########################\n //## move forward ##\n //########################\n\n //choose randomly between our move options\n var nextCell = moveOpt[Math.ceil(Math.random() * moveOpt.length) - 1]\n\n //save on stackMap\n //only need to save when moveOptions.length >= 2, save stack memory for bigger mazes\n //moveOptions.length = 0 dead-end\n //moveOptions.length = 1 only one way, no need to saven\n //moveOptions.length >= 2 in this case we still have routes to explore\n\n //if (kind==\"make\" && (moveOpt.length >2)) {\n\n stack.push({row:row,col:col, NESO:nextCell.NESO});\n if(debug) {console.log (\"mv: \" + moveOpt.length + \" pushed: \" + row + \", \" + col );}\n //} else { //find\n // stack.push({row:row,col:col, NESO:nextCell.NESO});\n //push points to curve\n\n if(kind==\"find\"){\n var centerPoint = thisMap.grid.cellToRectangle(col, row).center;\n curvePoints.push(centerPoint);\n curveFind.to(centerPoint);\n console.log(centerPoint, curvePoints, curveFind)\n }\n //########################\n //## erasing the walls ##\n //########################\n //each cell as walls so 2 walls to erase\n cell[nextCell.NESO] = false; //this cell wall\n \tvar nextCellMap = thisMap.map[nextCell.row][nextCell.col] //and the next cell wall too\n \tnextCellMap[\"SONE\".charAt(\"NESO\".indexOf(nextCell.NESO))] = false;\n\n\n\n };\n\n\n //debug\n if (debug) {\n form.fill(colors.a1)\n //form.text(new Point(20, dL += 10), \"stack: \" + stackMap);\n form.text(new Point(20, dL += 10), \"next: \" + nextCell.row + \", \" + nextCell.col + \", \" + nextCell.NESO)\n }\n\n //recusive exit condition\n switch (kind) {\n case \"make\":\n {\n var condition = (stack.length == 0)\n break;\n }\n case \"find\":\n {\n var condition = ((nextCell.row == rowEnd) && (nextCell.col == colEnd))\n break;\n }\n }\n\n if (condition) {\n stack = []; //reset stack\n return\n }\n\n //###################################\n //## call recursive to next cell ##\n //###################################\n // not working with this metod of maps: setTimout for animation, velocity depends of the size of the grid.\n\n switch (kind) {\n case \"make\":\n {\n return mazeDFS(thisMap, nextCell.row, nextCell.col, \"make\", stack)\n }\n case \"find\":\n {\n\n\n return mazeDFS(thisMap, nextCell.row, nextCell.col, \"find\", stack, rowEnd, colEnd, mazeMap)\n\n }\n }\n}", "static dfs(currentNode,fn,params)\n {\n if(!currentNode)return;\n fn(currentNode,params);\n this.dfs(currentNode.left,fn,params);\n this.dfs(currentNode.right,fn,params);\n }", "function dbg(prs, id, w, h, mode, fr){\n\t//save instance of visualizer\n\tthis._vis = viz.getVisualizer(\n\t\tVIS_TYPE.DBG_VIEW,\t\t\t\t//debugging viewport\n\t\tprs,\t\t\t\t\t\t\t//parser instance\n\t\tid,\t\t\t\t\t\t\t\t//HTML element id\n\t\tw,\t\t\t\t\t\t\t\t//width\n\t\th,\t\t\t\t\t\t\t\t//height\n\t\tfunction(cellView, evt, x, y){\t//mouse-click event handler\n\t\t\t//ES 2017-12-09 (b_01): is visualizer use canvas framework\n\t\t\tvar tmpDoCanvasDraw = viz.__visPlatformType == VIZ_PLATFORM.VIZ__CANVAS;\n\t\t\t//ES 2017-12-09 (b_01): is visualizer use jointjs framework\n\t\t\tvar tmpDoJointJSDraw = viz.__visPlatformType == VIZ_PLATFORM.VIZ__JOINTJS;\n\t\t\t//if clicked command (we can put breakpoint only on command)\n\t\t\t//ES 2017-12-09 (b_01): refactor condition to adopt for Canvas framework\n\t\t\tif( (tmpDoCanvasDraw && cellView._type == RES_ENT_TYPE.COMMAND ) || \n\t\t\t\t(tmpDoJointJSDraw && cellView.model.attributes.type == \"command\") \n\t\t\t){\n\t\t\t\t//get debugger (do not need to pass any values, since\n\t\t\t\t//\tdebugger should exist by now, and thus we should\n\t\t\t\t//\tnot try to create new debugger instance)\n\t\t\t\tvar tmpDbg = dbg.getDebugger();\n\t\t\t\t//ES 2017-12-09 (b_01): declare var for command id\n\t\t\t\tvar tmpCmdId = null;\n\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t//get command id in string representation\n\t\t\t\t\ttmpCmdId = cellView.obj._id.toString();\n\t\t\t\t//ES 2017-12-09 (b_01): else, drawing with JointJS framework\n\t\t\t\t} else {\n\t\t\t\t\t//get command id for this jointJS entity\n\t\t\t\t\t//ES 2017-12-09 (b_01): move var declaration outside of IF\n\t\t\t\t\ttmpCmdId = cellView.model.attributes.attrs['.i_CmdId'].text;\n\t\t\t\t\t//right now command id contains ':' -- filter it out\n\t\t\t\t\ttmpCmdId = tmpCmdId.substring(0, tmpCmdId.indexOf(':'));\n\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t//check if this breakpoint already has been added for this command\n\t\t\t\tif( tmpCmdId in tmpDbg._breakPoints ){\n\t\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t\t//remove breakpoint DIV\n\t\t\t\t\t\t$(tmpDbg._breakPoints[tmpCmdId]).remove();\n\t\t\t\t\t//ES 2017-12-09 (b_01): else, drawing using JointJS framework\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//diconnect breakpoint from this command\n\t\t\t\t\t\tcellView.model.unembed(tmpDbg._breakPoints[tmpCmdId]);\n\t\t\t\t\t\t//remove circle that represents a breakpoint\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId].remove();\n\t\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t\t//delete breakpoint entry in our collection\n\t\t\t\t\tdelete tmpDbg._breakPoints[tmpCmdId];\n\t\t\t\t} else {\t//else, create a breakpoint\n\t\t\t\t\t//ES 2017-12-09 (b_01): declare color constants for breakpoint to be used\n\t\t\t\t\t//\tby all visualizer frameworks\n\t\t\t\t\tvar tmpBrkStroke = \"#00E000\";\t\t//border color\n\t\t\t\t\tvar tmpBrkFill = \"#E00000\";\t\t\t//filling color\n\t\t\t\t\t//ES 2017-12-09 (b_01): declare vars for breakpoint dimensions\n\t\t\t\t\tvar tmpBrkWidth = 15;\n\t\t\t\t\tvar tmpBrkHeight = 15;\n\t\t\t\t\t//ES 2017-12-09 (b_01): x-offset between breakpoint and left side of command\n\t\t\t\t\tvar tmpBrkOffX = 20;\n\t\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t\t//compose html elem ID where to insert breakpoint\n\t\t\t\t\t\tvar tmpCnvMapId = \"#\" + viz.getVisualizer(VIS_TYPE.DBG_VIEW).getCanvasElemInfo(VIS_TYPE.DBG_VIEW)[1];\n\t\t\t\t\t\t//create circle shape DIV and save it inside set of breakpoints\n\t\t\t\t\t\t//\tsee: https://stackoverflow.com/a/25257964\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId] = $(\"<div>\").css({\n\t\t\t\t\t\t\t\"border-radius\": \"50%\",\n\t\t\t\t\t\t\t\"width\": tmpBrkWidth.toString() + \"px\",\n\t\t\t\t\t\t\t\"height\": tmpBrkHeight.toString() + \"px\",\n\t\t\t\t\t\t\t\"background\": tmpBrkFill,\n\t\t\t\t\t\t\t\"border\": \"1px solid \" + tmpBrkStroke,\n\t\t\t\t\t\t\t\"top\": cellView.y.toString() + \"px\",\n\t\t\t\t\t\t\t\"left\": (cellView.x - tmpBrkOffX).toString() + \"px\",\n\t\t\t\t\t\t\t\"position\": \"absolute\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\t//add breakpoint to canvas map\n\t\t\t\t\t\t$(tmpCnvMapId).append(tmpDbg._breakPoints[tmpCmdId]);\n\t\t\t\t\t//ES 2017-12-09 (b_01): else, drawing using JointJS framework\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//create visual attributes for breakpoint\n\t\t\t\t\t\tvar brkPtAttrs = {\n\t\t\t\t\t\t\tposition : {\t//place breakpoint to the left of command id\n\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace x-offset with var\n\t\t\t\t\t\t\t\tx : cellView.model.attributes.position.x - tmpBrkOffX,\n\t\t\t\t\t\t\t\ty : cellView.model.attributes.position.y\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsize : {\t//show small circle\n\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace dimension consts with vars\n\t\t\t\t\t\t\t\twidth : tmpBrkWidth,\n\t\t\t\t\t\t\t\theight : tmpBrkHeight\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tattrs : {\n\t\t\t\t\t\t\t\tcircle : {\n\t\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace color constants with vars\n\t\t\t\t\t\t\t\t\tstroke: tmpBrkStroke,\t//border with green color\n\t\t\t\t\t\t\t\t\tfill : tmpBrkFill\t\t//fill with red color\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\t//create breakpoint circle\n\t\t\t\t\t\tvar tmpCircle = new joint.shapes.basic.Circle(brkPtAttrs);\n\t\t\t\t\t\t//show it in viewport\n\t\t\t\t\t\tviz.getVisualizer(VIS_TYPE.DBG_VIEW)._graph.addCells([tmpCircle]);\n\t\t\t\t\t\t//add this command to collection that maps command id to breakpoint\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId] = tmpCircle;\n\t\t\t\t\t\t//connect breakpoint with this command (so if command moves, so does breakpoint)\n\t\t\t\t\t\tcellView.model.embed(tmpCircle);\n\t\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t}\t//end if breakpoint for this command already exists\n\t\t\t}\t//end if clicked command\n\t\t}\t//end mouse-click event handler\n\t);\t//end retrieve/create visualizer\n\t//draw CFG, starting from global scope\n\tthis._vis.drawCFG(prs._gScp);\n\t//if mode is not set\n\tif( typeof mode == \"undefined\" || mode == null ){\n\t\t//set it to be NON_STOP\n\t\tmode = DBG_MODE.NON_STOP;\n\t}\n\t//reference to the cursor framework object\n\tthis._cursorEnt = null;\n\t//array of framework objects for current command arguments\n\tthis._cmdArgArrEnt = [];\n\t//collection of breakpoints\n\t//\tkey: command_id\n\t//\tvalue: framework entity (visual representation of breakpoint)\n\tthis._breakPoints = {};\n\t//collection that maps command id to framework objects for resulting command value\n\t//\tkey: command id\n\t//\tvalue: framework object for resulting value\n\tthis._cmdToResValEnt = {};\n\t//call stack -- collects DFS (debugging function state(s))\n\tthis._callStack = [];\n\t//create current debugging function state\n\tthis._callStack.push(\n\t\tnew dfs(mode, fr, null, null)\n\t);\n\t//create key stroke handler\n\t$(document).keypress(\t//when key is pressed, fire this event\n\t\tfunction(e){\t\t\t//handler for key press event\n\t\t\t//get debugger (do not need to pass any values)\n\t\t\tvar tmpDbg = dbg.getDebugger();\n\t\t\t//depending on the character pressed by the user\n\t\t\tswitch(e.which){\n\t\t\t\tcase 97:\t\t\t//'a' - again run program\n\t\t\t\t\t//reset static and non-static fields, set current frame, and load vars\n\t\t\t\t\tentity.__interp.restart();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 110:\t\t\t//'n' - next command (step thru)\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.STEP_OVER;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 115:\t\t\t//'s' - step in\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.STEP_IN;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 114:\t\t\t//'r' - run non stop\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.NON_STOP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 118:\t\t\t//'v' - variables\n\t\t\t\t\t//Comment: do not reset mode, we just want to show/hide lookup box\n\t\t\t\t\t//show lookup box with all accessible variables\n\t\t\t\t\ttmpDbg.showEntityLookUpBox();\n\t\t\t\t\t//quit to prevent running next command\n\t\t\t\t\treturn;\n\t\t\t\tcase 113:\t\t\t//'q' - quit\n\t\t\t\t\t//quit debugger\n\t\t\t\t\ttmpDbg.quitDebugger();\n\t\t\t\t\t//quit to prevent running next command\n\t\t\t\t\treturn;\n\t\t\t\tcase 99:\t\t\t//'c' center on cursor\n\t\t\t\t\ttmpDbg.scrollTo(tmpDbg.getDFS()._pos._cmd._id);\n\t\t\t\t\tbreak;\n\t\t\t}\t//end switch -- depending on the key pressed by the user\n\t\t\t//declare var for returned value from RUN function\n\t\t\tvar tmpRunVal;\n\t\t\t//if returning function value from stepped in function\n\t\t\tif( tmpDbg.getDFS()._val != 0 ){\n\t\t\t\t//invoke run and pass in return value\n\t\t\t\tentity.__interp.run(tmpDbg.getDFS()._frame, tmpDbg.getDFS()._val);\n\t\t\t\t//reset return value to 0\n\t\t\t\ttmpDbg.getDFS()._val = 0;\n\t\t\t} else {\t//regular execution\n\t\t\t\t//invoke interpreter's run function\n\t\t\t\ttmpRunVal = entity.__interp.run(tmpDbg.getDFS()._frame);\n\t\t\t}\n\t\t\t//if return value from RUN function is defined and NULL\n\t\t\tif( typeof tmpRunVal != \"undefined\" &&\t//make sure that RUN returned smth \n\t\t\t\ttmpRunVal == null && \t\t\t\t//make sure RUN function quit\n\t\t\t\ttmpDbg._callStack.length > 0 &&\t\t//call stack is not empty\n\n\t\t\t\t//make sure it is not EXIT command\n\t\t\t\ttmpDbg._callStack[tmpDbg._callStack.length - 1]._funcCall != null ){\n\t\t\t\t//pop last entry from call stack\n\t\t\t\tvar tmpLstCallStk = tmpDbg._callStack.pop();\n\t\t\t\t//get functinoid id for the completed function call\n\t\t\t\tvar tmpFuncId = tmpLstCallStk._funcCall._funcRef._id;\n\t\t\t\t//get function call object\n\t\t\t\tvar tmpFuncCallObj = tmpLstCallStk._frame._funcsToFuncCalls[tmpFuncId];\n\t\t\t\t//get return value from completed function call\n\t\t\t\ttmpDbg.getDFS()._val = tmpFuncCallObj._returnVal;\n\t\t\t\t//re-draw cursor\n\t\t\t\ttmpDbg.showCursor();\n\t\t\t}\n\t\t}\t//end handler function\n\t);\n\t//reference to box that stores set of entities currently accessible in the code\n\tthis._entLookupBox = null;\n}", "function DirectedDFS(G, s) {\n var count = 0; // number of vertices reachable from s\n var marked = Array(G.getVertices()).fill(false);\n dfs(G, s);\n\n function dfs(G, v) {\n count++;\n marked[v] = true;\n for (var w of G.getAdjValues(v)) {\n if (!marked[w]) dfs(G, w);\n }\n }\n\n // is there a directed path from the source vertex\n // (or any of the source vertices) and vertex v?\n function marked(v) {\n return marked[v];\n }\n\n // returns the number of verteices reachable from the source vertex\n // (or source vertices)\n function countVertices() {\n return count;\n }\n\n // prints out all the reachable vertices in an array\n function printReachableVertices() {\n var arr = [];\n marked.forEach((entry, index) => {\n if (entry) arr.push(index);\n });\n return arr;\n }\n\n return {\n marked,\n countVertices,\n printReachableVertices\n };\n}", "DFSUtil(vert, visited, stack = []) {\n\n visited[vert] = true;\n \n console.log(vert);\n \n const neighbours = this.AdjList.get(vert);\n \n for (let i in neighbours) {\n\n const neighbour = neighbours[i];\n\n if (!visited[neighbour])\n\n // Because of recursion, we know the algorithm will check nodes closer to the root\n // after traversing the depths of the graph; as function calls get popped off the call\n // stack, the algorithm works its way back to the root.\n this.DFSUtil(neighbour, visited, stack);\n }\n\n stack.push(vert)\n }", "function DFS(source, target)\n{\n\tvar explored = [];\n\tvar stack \t = new ds.Stack();\n\tstack.push(source);\n\twhile(stack.length!=0)\n\t{\n\t\tvar node = stack.pop();\n\t\texplored.push(node);\n\t\tif(node == target)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tunderJS.each(node.getOutgoingEdges(), function(edge) {\n\t\t\t\tif(underJS.indexOf(explored, edge.getHead()) == -1)\n\t\t\t\t{\n\t\t\t\t\tstack.push(edge.getHead());\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\treturn false;\n}", "function showResults() {\n\t\n\t/* Print execution times for each function */\n\t/* Compute hot path */\t\n\tfuncTree = getCleanedTree(funcTree);\n\tcomputeSelfTime(funcTree);\n\ttreeTopDownList = [];\n\tprintTreeTopDown(funcTree, 0);\n\t\n\tfor(var i = 0; i<funcTree.child.length; i++)\n\t{\n\t\tpathTreeString = [];\n\t\tvar tempTime = computeHotPaths(funcTree.child[i]);\n\t\tvar top = pathTreeString.pop();\n\t\tif(!top)\n\t\t{\n\t\t\tpathTreeString.push({ \"name\": funcTree.child[i].name,\n\t\t\t\t\t\t\t\t \"level\": 0} );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpathTreeString.push(top);\n\t\t}\n\t\tif(tempTime > globalMaxExecTime)\n\t\t{\n\t\t\tglobalHotPath = pathTreeString;\n\t\t\tglobalMaxExecTime = tempTime;\n\t\t}\n\t}\n\t\n\tdebugLog(\"Execution times for individual functions:\");\n\tfor (var key in functionStats) {\n\t\tif (functionStats.hasOwnProperty(key)){\n\t\t\tdebugLog(\"ExecTime: \" + functionStats[key].timeOfExec + \"ms for \" +\n\t\t\t\tfunctionStats[key].name+\"()\");\n\t\t}\n\t}\n\n\ttreeTopDownList = [];\n\tprintTreeTopDown(funcTree, 0);\n\t//console.log(treeTopDownList);\n\tprintTable();\n\t\n\t/* Frequency of calls for each function*/\n\tdebugLog(\"<br>Frequency of calls for each function\");\n\tfor (var key in functionStats){\n\t\tif (functionStats.hasOwnProperty(key)){\n\t\t\tdebugLog(\"Hits: \" + functionStats[key].hits +\n\t\t\t\t\" for \" + functionStats[key].name+\"()\");\n\t\t}\t\n\t}\n\n\t/* Print all functions pairs and number of their hits */\n\tdebugLog(\"<br>Edges between caller and callee functions and frequency of calls:\")\n\tfor (var key in functionStats){\n\t\tif (functionStats.hasOwnProperty(key)){\n\t\t\tfor (var key2 in functionStats[key].callers) {\n\t\t\t\tif (functionStats[key].callers.hasOwnProperty(key2)){\n\t\t\t\t\tdebugLog(\"Calls: \" + functionStats[key].callers[key2].hits + \n\t\t\t\t\t\t\" from \"+ functionStats[key].callers[key2].name + \"()-->\" + \n\t\t\t\t\t\tfunctionStats[key].name + \"()\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdebugLog(\"Max executionTime: \" + globalMaxExecTime);\n\tconsole.log(\"Max executionTime: \" + globalMaxExecTime);\n\tdebugLog(\"Path is \");\n\tfor(var x=0 ; x<globalHotPath.length; x++)\n\t{\t\t\n\t\tconsole.log(\" \" + globalHotPath[x].name + \" \");\n\t\tdebugLog(\" \" + globalHotPath[x].name + \"->\");\n\t}\n}", "traverseStack () {\n const stack = []\n this._maxDepth = 0\n EightWays.forEach(towards => { stack.push([0, 0, towards, 1]) })\n while (stack.length) {\n const [sourceX, sourceY, towards, depth] = stack.pop()\n this._maxDepth = Math.max(depth, this._maxDepth)\n\n // Get the neighboring point's coordinates within the IgnitionGrid\n const [x, y] = this.neighboringPoint(sourceX, sourceY, towards)\n this.log(`${depth}: Attempt TRAVERSE source [${sourceX}, ${sourceY}] towards ${DirAbbr[towards]} into [${x}, ${y}]`)\n\n // Get the neighboring point's coordinates within the FireGrid\n const fx = this._walk.ignition.x + x\n const fy = this._walk.ignition.y + y\n let here = `Ign [${x}, ${y}] Fire [${fx}, ${fy}]`\n let msg = `${depth}: RETREAT from ${here}:`\n\n // Test 1 - the neighboring point must be in the IgnitionGrid bounds\n if (!this.inbounds(x, y)) {\n this.log(`${msg} is out of IgnitionGrid bounds`)\n continue // pop the next source-towards from the stack\n }\n\n // Neighboring point is in-bounds, so get its ignition data {dist, time, source, towards}\n const xCol = this.xCol(x)\n const yRow = this.yRow(y)\n const ign = this.get(x, y)\n here = `Ign [${x}, ${y}] [${xCol}, ${yRow}], Fire [${fx}, ${fy}] d=${ign.dist.toFixed(2)}, t=${ign.time.toFixed(2)}`\n msg = `${depth}: RETREAT from ${here}:`\n\n // Test 2 - neighboring point must be unvisited on this walk()\n if (ign.source !== Unvisited) {\n this.log(`${msg} was previously visited`)\n continue // pop the next source-towards from the stack\n }\n\n // Test 3 - neighboring point must be in the FireGrid bounds\n if (!this._fireGrid.inbounds(fx, fy)) {\n this.log(`${msg} is out of FireGrid bounds`)\n continue // pop the next source-towards from the stack\n }\n\n // Test 4 - neighboring point must be reachable from ignition pt during the current period\n const arrives = this._walk.ignition.time + ign.time\n if (arrives >= this._walk.period.ends()) {\n this.log(`${msg} ignites at ${arrives}, after period ends`)\n continue // pop the next source-towards from the stack\n }\n\n // Test 5 - neighboring point must be Burnable\n const status = this._fireGrid.status(fx, fy)\n if (status <= FireStatus.Unburnable) {\n this.log(`${msg} FireGrid status ${status} is Unburnable`)\n continue // pop the next source-towards from the stack\n }\n\n // Test 6 - neighboring point must not have burned in a PREVIOUS period\n if (status !== FireStatus.Unburned && status < this._walk.period.begins()) {\n this.log(`${msg} was previously burned at ${status}`)\n continue // pop the next source-towards from the stack\n }\n\n // This neighboring point is traversable; set its 'source', which also flags it as Visited\n const source = oppositeDir[towards]\n this.setSource(x, y, source)\n this._walk.points.traversed++\n\n // Add all seven non-source neighbors to the stack\n EightWays.forEach(towards => {\n if (towards !== source) stack.push([x, y, towards, depth + 1])\n })\n\n // If the neighboring point is currently unignited...\n if (status === FireStatus.Unburned) {\n this._fireGrid.set(fx, fy, arrives)\n this.log(`${depth}: IGNITED ${here} at ${this._walk.ignition.time} + ${ign.time} = ${arrives}`)\n this._walk.points.ignited++\n // this._burnMap[xCol + yRow * this.cols()] = '*'\n }\n // else if the neighboring point will now be ignited at an earlier time...\n else if (arrives < status) {\n this._fireGrid.set(fx, fy, arrives)\n this.log(`${depth}: IGNITED EARLIER ${here} at ${this._walk.ignition.time} + ${ign.time} = ${arrives}`)\n this._walk.points.ignitedEarlier++\n }\n // else the neighboring point was ignited during a previous burning period\n else {\n this.log(`${depth}: CROSSED ${here}, previously ignited at ${status}`)\n this._walk.points.crossed++\n }\n }\n }", "function dfsNeighboursLoop(i,j,cnodes,callback){\n\tif(j>=cnodes[i].getNeighboursNum()){\n\t\tfillDFSTable(cnodes,i,'f');\n\t\tshowPopupNodeMessage(i,\"Finishing with node\",popupNodeDelay,function(){dfsFinishNode(i,cnodes);callback();});\n\t}else{\n\t\tneighbour = cnodes[cnodes[i].getNeighbour(j)];\n\t\tif(neighbour.getColor()==0){\n\t\t\tfillDFSTable(cnodes,cnodes[i].getNeighbour(j),'d');\n\t\t\tneighbour.pare = i;\n\t\t\tshowPopupNodeMessage(cnodes[i].getNeighbour(j),\"DFS visiting this node\",popupNodeDelay,function(){\n\t\t\t\tdfsVisitVis(cnodes[i].getNeighbour(j),cnodes,function(){dfsNeighboursLoop(i,j+1,cnodes,callback);});\n\t\t\t});\n\t\t}else{\n\t\t\tdfsNeighboursLoop(i,j+1,cnodes,callback);\n\t\t}\n\t}\n}", "dftraverse(){ //callback is a function to be used when you either reached the last node, or exhaust all the previous \r\n (function recurse(currentnode,alpha,beta){\r\n //apply aplha beta pruning here.\r\n /**\r\n * alpha for white, beta for black\r\n */\r\n\r\n if(!currentnode) return;\r\n var effscore = currentnode.score;\r\n //console.log(currentnode.playercolor + \",\" + currentnode.effectivescore);\r\n for(var i = 0; i < currentnode.children.length; i++){\r\n recurse(currentnode.children[i],alpha,beta);\r\n //onsole.log(currentnode.children[i].playercolor + \" \" + currentnode.children[i].effectivescore);\r\n if(currentnode.playercolor == \"W\"){ //maximiser\r\n //get higher score;\r\n effscore = Math.max(effscore, currentnode.children[i].effectivescore);\r\n alpha = Math.max(alpha,effscore);\r\n if(alpha >= beta) break;\r\n }\r\n else{ //minimiser\r\n //get lower score;\r\n effscore = Math.min(effscore, currentnode.children[i].effectivescore);\r\n beta = Math.min(beta,effscore);\r\n if(beta <= alpha) break;\r\n }\r\n //add code to get score here.\r\n }\r\n currentnode.effectivescore = effscore;\r\n //console.log(currentnode.playercolor + \",\" + currentnode.effectivescore);\r\n })(this,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);\r\n }", "function FunctionDetector(analyzer) {\n IRVisitor.call(this);\n\n // Use this to access parameters and metric. We will not modify its scoped maps directly.\n this.analyzer = analyzer;\n\n // Mimics analyzer but for a single scope\n this.functionTypeMap = new SingleScopeMap();\n this.variableTypeMap = {};\n this.variableMetricMap = {};\n this.functionReturnAbstractionMap = new SingleScopeMap();\n this.functionMetricAbstractionMap = new SingleScopeMap();\n\n // Used to store local traversal history / intermediate result\n // This is then combined into the history of the main analyzer to properly stringify for debugging\n this.intermediateResults = {};\n}", "visualizeBFS() {\n // sr = this.state.START_NODE_ROW;\n // sc = this.state.START_NODE_COL;\n if(this.state.done === true){\n alert(\"Clear the grid First\");\n }else {\n console.log(this.state.START_NODE_ROW);\n const {grid} = this.state;\n const startNode = grid[this.state.START_NODE_ROW][this.state.START_NODE_COL];\n const finishNode = grid[this.state.FINISH_NODE_ROW][this.state.FINISH_NODE_COL];\n const visitedNodesInOrder = bfs(grid,startNode,finishNode);\n const nodesInShortestPathOrder = getNodesInShortestPathOrderBFS(finishNode);\n //console.table(visitedNodesInOrder[0]);\n // alert(\"BFS is going to execute\");\n this.setState({'done' : true});\n this.animate(visitedNodesInOrder,nodesInShortestPathOrder);\n //console.log(visitedNodesInOrder.length);\n }\n }", "function addEventsToCfa() {\n addPanEvent(\".cfa-svg\");\n d3.selectAll(\".cfa-node\")\n .on(\"mouseover\", (d) => {\n let message;\n if (Number(d) > 100000) {\n message =\n '<span class=\" bold \">type</span>: function call node <br>' +\n '<span class=\" bold \">dblclick</span>: Select function';\n } else {\n const node = cfaJson.nodes.find((n) => n.index === Number(d));\n message = `<span class=\" bold \">function</span>: ${node.func}`;\n if (d in cfaJson.combinedNodes) {\n message += `<br><span class=\" bold \">combines nodes</span> : ${Math.min.apply(\n null,\n cfaJson.combinedNodes[d]\n )}-${Math.max.apply(null, cfaJson.combinedNodes[d])}`;\n }\n message += `<br> <span class=\" bold \">reverse postorder Id</span>: ${node.rpid}`;\n }\n showToolTipBox(d3.event, message);\n })\n .on(\"mouseout\", () => {\n hideToolTipBox();\n });\n d3.selectAll(\".fcall\").on(\"dblclick\", (d, i) => {\n angular.element($(\"#cfa-toolbar\")).scope().selectedCFAFunction = d3\n .select(`#cfa-node${i} text`)\n .text();\n angular.element($(\"#cfa-toolbar\").scope()).setCFAFunction();\n });\n d3.selectAll(\".cfa-dummy\")\n .on(\"mouseover\", () => {\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">type</span>: placeholder <br> <span class=\" bold \">dblclick</span>: jump to Target node'\n );\n })\n .on(\"mouseout\", () => {\n hideToolTipBox();\n })\n .on(\"dblclick\", () => {\n if (!d3.select(\".marked-cfa-node\").empty()) {\n d3.select(\".marked-cfa-node\").classed(\"marked-cfa-node\", false);\n }\n const selection = d3.select(\n `#cfa-node${d3.select(this).attr(\"id\").split(\"-\")[1]}`\n );\n selection.classed(\"marked-cfa-node\", true);\n const boundingRect = selection.node().getBoundingClientRect();\n $(\"#cfa-container\")\n .scrollTop(boundingRect.top + $(\"#cfa-container\").scrollTop() - 300)\n .scrollLeft(\n boundingRect.left +\n $(\"#cfa-container\").scrollLeft() -\n $(\"#errorpath_section\").width() -\n 2 * boundingRect.width\n );\n });\n d3.selectAll(\".cfa-edge\")\n .on(\"mouseover\", function mouseover() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"3px\");\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">dblclick</span>: jump to Source line'\n );\n })\n .on(\"mouseout\", function mouseout() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"1.5px\");\n hideToolTipBox();\n })\n .on(\"dblclick\", function dblclick(d, i) {\n let edge = findCfaEdge(i);\n if (edge === undefined) {\n // this occurs for edges between graphs - splitting edges\n const thisEdgeData = d3.select(this).attr(\"id\").split(\"_\")[1];\n edge = findCfaEdge({\n v: thisEdgeData.split(\"-\")[0],\n w: thisEdgeData.split(\"-\")[1],\n });\n }\n document.querySelector(\"#set-tab-3\").click();\n let { line } = edge;\n if (line === 0) {\n line = 1;\n }\n if (!d3.select(\".marked-source-line\").empty()) {\n d3.select(\".marked-source-line\").classed(\"marked-source-line\", false);\n }\n const selection = d3.select(`#source-${line} td pre.prettyprint`);\n selection.classed(\"marked-source-line\", true);\n $(\".sourceContent\").scrollTop(\n selection.node().getBoundingClientRect().top +\n $(\".sourceContent\").scrollTop() -\n 200\n );\n });\n d3.selectAll(\".cfa-split-edge\")\n .on(\"mouseover\", function mouseover() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"3px\");\n showToolTipBox(\n d3.event,\n '<span class=\" bold \">type</span>: place holder <br> <span class=\" bold \">dblclick</span>: jump to Original edge'\n );\n })\n .on(\"mouseout\", function mouseout() {\n d3.select(this).select(\"path\").style(\"stroke-width\", \"1.5px\");\n hideToolTipBox();\n })\n .on(\"dblclick\", function dblclick() {\n const edgeSourceTarget = d3.select(this).attr(\"id\").split(\"_\")[1];\n if (!d3.select(\".marked-cfa-edge\").empty()) {\n d3.select(\".marked-cfa-edge\").classed(\"marked-cfa-edge\", false);\n }\n const selection = d3.select(\n `#cfa-edge_${edgeSourceTarget.split(\"-\")[0]}-${\n edgeSourceTarget.split(\"-\")[1]\n }`\n );\n selection.classed(\"marked-cfa-edge\", true);\n const boundingRect = selection.node().getBoundingClientRect();\n $(\"#cfa-container\")\n .scrollTop(boundingRect.top + $(\"#cfa-container\").scrollTop() - 300)\n .scrollLeft(\n boundingRect.left +\n $(\"#cfa-container\").scrollLeft() -\n $(\"#errorpath_section\").width() -\n 2 * boundingRect.width\n );\n });\n}", "function decodeFDCB(z80) {\n z80.incTStateCount(3);\n const offset = z80.readByteInternal(z80.regs.pc);\n z80.regs.memptr = add16(z80.regs.iy, signedByte(offset));\n z80.regs.pc = inc16(z80.regs.pc);\n z80.incTStateCount(3);\n const inst = z80.readByteInternal(z80.regs.pc);\n z80.incTStateCount(2);\n z80.regs.pc = inc16(z80.regs.pc);\n const func = decodeMapFDCB.get(inst);\n if (func === undefined) {\n console.log(\"Unhandled opcode in FDCB: \" + toHex(inst, 2));\n }\n else {\n func(z80);\n }\n}", "initMethodStructures(class_name, function_name)\r\n {\r\n this.node_stack[class_name][function_name] = []; \r\n this.loop_stack[class_name][function_name] = []; // each entry is a stack of the node_str of the head of the inner loop.\r\n // this.switch_stack[class_name][function_name] = [];\r\n this.label_to_node_str[class_name][function_name] = {};\r\n this.label_to_end_block[class_name][function_name] = {};\r\n this.loop_switch_end_stack[class_name][function_name] = [];\r\n this.switch_head_stack[class_name][function_name] = [];\r\n this.default_case[class_name][function_name] = {};\r\n this.last_case[class_name][function_name] = []; \r\n this.try_stack[class_num][function_num] = [];\r\n this.catch_clauses[class_name][function_num] = {}; // key is the try statement\r\n }", "traverseRecursive (sourceX, sourceY, towards, depth) {\n this._maxDepth = Math.max(depth, this._maxDepth)\n // runaway truck ramp\n if (depth > 10000) throw Error('walk() depth exceeds 10000')\n this._walk.points.tested++\n\n // Get the neighboring point's coordinates within the IgnitionGrid\n const [x, y] = this.neighboringPoint(sourceX, sourceY, towards)\n this.log(`${depth}: Attempt TRAVERSE source [${sourceX}, ${sourceY}] towards ${DirAbbr[towards]} into [${x}, ${y}]`)\n\n // Get the neighboring point's coordinates within the FireGrid\n const fx = this._walk.ignition.x + x\n const fy = this._walk.ignition.y + y\n let here = `Ign [${x}, ${y}] Fire [${fx}, ${fy}]`\n let msg = `${depth}: RETREAT from ${here}:`\n\n // Test 1 - the neighboring point must be in the IgnitionGrid bounds\n if (!this.inbounds(x, y)) {\n this.log(`${msg} is out of IgnitionGrid bounds`)\n return false\n }\n\n // Neighboring point is in-bounds, so get its ignition data {dist, time, source, towards}\n const xCol = this.xCol(x)\n const yRow = this.yRow(y)\n const ign = this.get(x, y)\n here = `Ign [${x}, ${y}] [${xCol}, ${yRow}], Fire [${fx}, ${fy}] d=${ign.dist.toFixed(2)}, t=${ign.time.toFixed(2)}`\n msg = `${depth}: RETREAT from ${here}:`\n\n // Test 2 - neighboring point must be unvisited on this walk()\n if (ign.source !== Unvisited) {\n this.log(`${msg} was previously visited`)\n return false\n }\n\n // Test 3 - neighboring point must be in the FireGrid bounds\n if (!this._fireGrid.inbounds(fx, fy)) {\n this.log(`${msg} is out of FireGrid bounds`)\n return false\n }\n\n // Test 4 - neighboring point must be reachable from ignition pt during the current period\n const arrives = this._walk.ignition.time + ign.time\n if (arrives >= this._walk.period.ends()) {\n this.log(`${msg} ignites at ${arrives}, after period ends`)\n return false\n }\n\n // Test 5 - neighboring point must be Burnable\n const status = this._fireGrid.status(fx, fy)\n if (status <= FireStatus.Unburnable) {\n this.log(`${msg} FireGrid status ${status} is Unburnable`)\n return false\n }\n\n // Test 6 - neighboring point must not have burned in a PREVIOUS period\n if (status !== FireStatus.Unburned && status < this._walk.period.begins()) {\n this.log(`${msg} was previously burned at ${status}`)\n return false\n }\n\n // This point is traversable; set its 'source', which also flags it as Visited\n const source = oppositeDir[towards]\n this.setSource(x, y, source)\n this._walk.points.traversed++\n\n // If the neighboring point is currently unignited...\n if (status === FireStatus.Unburned) {\n this._fireGrid.set(fx, fy, arrives)\n this.log(`${depth}: IGNITED ${here} at ${this._walk.ignition.time} + ${ign.time} = ${arrives}`)\n this._walk.points.ignited++\n // this._burnMap[xCol + yRow * this.cols()] = '*'\n } else if (arrives < status) {\n this._fireGrid.set(fx, fy, arrives)\n this.log(`${depth}: IGNITED EARLIER ${here} at ${this._walk.ignition.time} + ${ign.time} = ${arrives}`)\n this._walk.points.ignitedEarlier++\n } else {\n this.log(`${depth}: CROSSED ${here}, previously ignited at ${status}`)\n this._walk.points.crossed++\n }\n\n // Continue traversal by visiting all three neighbors\n EightWays.forEach(towards => {\n if (towards !== source) this.traverseRecursive(x, y, towards, depth + 1)\n })\n return true\n }", "function isNodeEntering(state, interpreter) {\n var updateNeeded = false;\n\n function isSupportedFunctionCall(state) {\n // won't show stepping into and out of member methods (e.g array.slice)\n // because these are built-ins with black-boxed code.\n // User functions may also be object properties, but I am not considering\n // this for this exercise.\n return state.node.type === 'CallExpression' && !state.doneCallee_ && !(state.node.callee && state.node.callee.type === 'MemberExpression');\n }\n\n if (isSupportedFunctionCall(state)) {\n\n var enterNode = {\n name: state.node.callee.name || state.node.callee.id.name,\n parentNode: (0, _lodash.last)(scopeChain) || null,\n paramNames: [],\n interpreterComputedArgs: [],\n // variable information and warnings\n // populated once the interpreter\n // generates scope\n variablesDeclaredInScope: null,\n warningsInScope: new Set(),\n type: 'function',\n status: 'normal'\n };\n\n // set up string tokens for display text\n enterNode.recursion = enterNode.parentNode && enterNode.name === enterNode.parentNode.name;\n enterNode.displayTokens = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].getInitialDisplayTokens(enterNode.name, state.node.arguments, enterNode.parentNode, interpreter);\n enterNode.displayName = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].joinAndFormatDisplayTokens(enterNode.displayTokens, enterNode.recursion);\n\n // the root node carries through information to d3 about overall progress.\n if (nodes.length === 0) {\n enterNode.type = 'root';\n enterNode.errorCount = 0;\n enterNode.status = ''; //d3 manually assigns color to rootNode\n rootNode = enterNode;\n }\n\n // add nodes and links to d3\n nodes.push(enterNode);\n var callLink = getCallLink(enterNode.parentNode, enterNode, 'calling');\n if (callLink) {\n links.push(callLink);\n }\n\n /* Tracking by scope reference allows for\n displaying nested functions and recursion */\n scopeChain.push(enterNode);\n updateNeeded = true;\n }\n return updateNeeded;\n }", "function CodeLocationObj() {\r\n\r\n var module = \"\"\r\n var func = \"\"\r\n var step = \"\";\r\n var box = \"\";\r\n\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method visitNextpage It visits the next page from url taken from poping the visitable list param : None
function visitNextPage() { var _url = _this.visitableList.pop(); var getPage = request(_url, function(error, response, body){ _this.totalVisit += 1; if(_this.toVisit>0 && _this.totalVisit >= _this.toVisit) { continueVisit = false; } if(error) { //Skip to next page if avaiable if(_this.visitableList.length) { visitNextPage(); } _this.emit('error',error, _url); }else { parseLink(response, body, _url); _this.emit('crawl', {url:_url, totalIndexed:_this.totalIndexed}); } }); }
[ "nextPage(){\n BusinessActions.nextPage();\n }", "function processNext() {\n const url = urlsToProcess.shift();\n\n PageFetcher.fetch(url, (pageResult) => {\n processResultFn(pageResult);\n\n const { status, url, raw } = pageResult;\n\n processedUrls.push(url);\n\n if (status != -1) {\n const links = PageLinkExtractor.extractLinks(raw)\n .map((s) => s.trim());\n\n AppLogger.verbose('PageQueue', `Found ${links.length} links on ${url}`);\n\n links.forEach(queue.enqueue);\n }\n\n if (urlsToProcess.length > 0) {\n processNext();\n } else {\n AppLogger.info('PageQueue', 'No more urls to process found!');\n }\n });\n }", "function callNextPage()\n{\n\tvar pageHref;\n\t\t\n\t// If there is a href\n\tif (arguments.length > 0)\n\t{\n\t\t// Get the href from the arguments\n\t\tpageHref = arguments[0];\n\t\t\n\t\t// If there are more results\n\t\tif (arguments.length > 1)\n\t\t{\n\t\t\t// Add the results to the results array\n\t\t\tfor (var i=1; i < arguments.length; i++)\n\t\t\t{\n\t\t\t\tvar hash = arguments[i].split(\":\");\n\t\t\t\t//results.push(hash[1]);\n\t\t\t\tresults[hash[0]] = hash[1];\n\t\t\t}\n\t\t}\n\t\t\n\t\tvar n = 0;\n\t\tfor (var _ in results) { n++; }\n\t\t\n\t\t// if we have results, append them to the href as the query string\n\t\tif (n > 0)\n\t\t{\n\t\t\t// Add ALL the results onto the href as a query string\n\t\t\tpageHref = pageHref + \"?\" + $.param( results );\n\t\t}\n\t\t// This loads the new page\n\t\twindow.location.href = pageHref;\t\n\t}\n\t// else do nothing\n\telse\n\t{\n\t\tconsole.log(\"'callNextPage' function called without any parameters\");\n\t}\n}", "function goToPage(pageNr){\r\n\r\n}", "async getNext() {\n if (this.hasNext) {\n const items = Items([this.parent, this.nextUrl], \"\");\n return items.getPaged();\n }\n return null;\n }", "function pageNaviByDropDown()\r\n\t{\r\n \tvar current_page = getElemnt(\"current_page\");\r\n \tvar nextRecordKey = current_page.value;\r\n \tpageNavi(nextRecordKey);\r\n\t}", "function forceNext() {\n\tmarkPageComplete();\n\t$('#navNext').trigger('click');\t\n\treturn false;\n}", "function goNext( relatedToScreen ) {\n\tdisable();\n\tif(currentScreenNo < noOfScreens) {\n\t\tautobookmark();\n\t\tcurrentScreenNo++;\n\t\tvar contentFolder = ( typeof(relatedToScreen) != \"undefined\" && relatedToScreen )\n\t\t\t? ''\n\t\t\t: getContentFolderName() + '/';\n\t\tframes['myFrame'].location.href = contentFolder + currentScreenNo+ '.htm';\n\t\t//alert(\"going to screen no: \" + currentScreenNo);\n\t\tif(currentScreenNo == noOfScreens) {\n\t\t $('#next_link').attr( 'class', 'navigationButton buttonExit' );\n\t\t\tonLastScreen();\n\t\t\tsubmitCompletion();\n\t\t}\t\t\n\t} else {\n\t\t// send completion signal to LMS\n\t\ttop.close();\n\t}\n\trefreshCounter();\n}", "function scrapeSingleCategoryPage(inputUrl, page){\n incrementRequests();\n\n var categoryPage = inputUrl + \"&p=\" + page;\n request(categoryPage, function (err, resp, body) {\n if (err)\n throw err;\n $ = cheerio.load(body);\n\n //check that we haven't gone over the max page\n var currPage = $(\"li[class='current number-btn']\").first().text();\n //console.log(\"Current Page: \" + currPage);\n if( currPage != page ) {\n console.log(\"Finished: \" + categoryPage);\n decrementRequests();\n return;\n }\n\n //add the product URL to the queue\n $('.product-name a').each(function(index){\n var nextLink = $(this).attr('href');\n console.log(\"Product: \" + nextLink);\n productQueue.push(nextLink);\n });\n\n //scrapeSingleCategoryPage(inputUrl, page+1);\n\n decrementRequests();\n });\n\n}", "function onNextButtonClick() {\n\t\tgotoNextSlide()\n\t}", "function nextClicked() {\n if (currentFeed && currentItemIndex < currentFeed.items.size - 1) {\n currentItemIndex++;\n displayCurrentItem();\n }\n }", "processRequest(\n request: IncomingMessage,\n response: ServerResponse,\n next: (?Error) => mixed,\n ) {\n if (\n request.url === PAGES_LIST_JSON_URL ||\n request.url === PAGES_LIST_JSON_URL_2\n ) {\n // Build list of pages from all devices.\n let result: Array<PageDescription> = [];\n Array.from(this._devices.entries()).forEach(([deviceId, device]) => {\n result = result.concat(\n device\n .getPagesList()\n .map((page: Page) =>\n this._buildPageDescription(deviceId, device, page),\n ),\n );\n });\n\n this._sendJsonResponse(response, result);\n } else if (request.url === PAGES_LIST_JSON_VERSION_URL) {\n this._sendJsonResponse(response, {\n Browser: 'Mobile JavaScript',\n 'Protocol-Version': '1.1',\n });\n } else {\n next();\n }\n }", "function handleNextBtn() {\n // Move the pointer back\n util.movePtr(\"next\");\n\n // Extract the index and url at ptr using object deconstruction\n const { idx, url } = ptr.value;\n\n // Update the index\n util.updateIdx(idx);\n\n // Update the carousel's image\n util.updateImage(url);\n }", "function _page2_page() {\n}", "function getNext(){\r\n // Don't do this if the user asked us not to\r\n if (!forward_fill) return;\r\n\r\n debug(d_med, \"We're getting the next 10!\");\r\n\r\n // Here we want to calculate the url of the next 10 reports\r\n\r\n // If we're on the initial report/message page\r\n if (latest_url.indexOf('s=')==-1){\r\n\tdebug(d_low, \"'s=' not found in url; append '?s=10'\");\r\n\tif (latest_url.indexOf('?')!=-1){\r\n\t latest_url += '&s=10';\r\n\t}\r\n\telse {\r\n\t latest_url += '?s=10';\r\n\t}\r\n }\r\n // Else we should extract and incriment that value by 10 to get the next page\r\n else {\r\n\tdebug(d_low, \"'s=' found in url; increment by 10\");\r\n\r\n\t// Strip off any troublesome #'s...\r\n\tif (latest_url.indexOf('#') != -1) latest_url = latest_url.split('#')[0];\r\n\r\n\ta = latest_url.split('s=')[1];\r\n\t// Hack to avoid infinite recursion, just in case...\r\n\tif (parseInt(a) > 300){\r\n\t updateArrows(true);\r\n\t return;\r\n\t}\r\n\tlatest_url = latest_url.split('s=')[0] + 's='+(parseInt(a)+10);\r\n }\r\n\r\n debug(d_low, latest_url);\r\n\r\n GM_xmlhttpRequest({\r\n\t method: 'GET',\r\n\t\turl: latest_url,\r\n\t\theaders: null,\r\n\t\tonload: onNextLoad});\r\n}", "function recurse() {\n if(linkNextPage != null) {\n $.when( listRepoIssues(linkNextPage) )\n .then( function() { recurse(); } )\n .fail( function() { logErr('Failed getting next page...'); } )\n }\n}", "function pagerLinkHandler() {\n\t\t\tself.parent('form').find(settings.pagerContainer).find('a').each(function() {\n\t\t\t\t$(this).on('click', function(e) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tsetPage(getQueryParam($(this).attr('href'), 'page'));\n\t\t\t\t\t$(this).spinner('on');\n\t\t\t\t\tgetData();\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}", "navigate(page, pushState=true){\n\n if(pushState)window.history.pushState(\"\", \"\", page);\n\n\n\n let cardViewer = this.getCardViewer();\n if(cardViewer!=false && (page!=\"/search\" && page!=\"/\")){\n cardViewer.view(page);\n }else{\n $(\"#content\").fadeOut(500, () => {\n let pageView = this.getPageMaps()[page];\n\n //if there is no route avaible for current page, use the '*' route\n if(pageView==undefined) pageView = this.getPageMaps()[\"*\"];\n\n\n let pageTitle = pageView.getTitle();\n if(pageTitle!=false)document.title = pageTitle;\n\n //after page is done rendering, fade it in for style points\n let x = pageView.render().then(()=>{\n this.currentPage = pageView;\n $(\"#content\").fadeIn(500);\n });\n\n\n\n });\n }\n\n\n }", "function link_users() {\n fetchJSONFile( userlist_url,\n function(users) {\n\n var user_url = users[user()].homepage,\n urls = normalized_user_urls(obj_values(users)),\n\n random_user_link = document.getElementById('tilde_town_ring'),\n next_user_link = document.getElementById('tilde_town_ring_next');\n\n console.log(urls)\n if (next_user_link) { // ensure user has next link\n next_user_link.href = next_item(user_url, urls);\n }\n random_user_link.href = random_item(remove(urls, user_url));\n\n console.log(users)\n console.log(user_url)\n console.log(next_item(user_url, urls))\n console.log(urls)\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
write a function that takes an input array and returns an array of booleans (>=75) or fail (<75)
function passOrFail(array) { // let pass = false; // if (array >= 75) { // pass = true; // } let pass = array.map((x) => x >= 75); return pass; }
[ "function passOrFail(array) {\n //create new array of boolean values testing x>=75\n const grade = array.map((x) => (x >= 75 ? true : false));\n return grade;\n}", "function arrayLessThan100(arr) {\n\treturn arr.reduce((x, i) => x + i) < 100;\n}", "function smallEnough(a, limit){\n // const isBelowThreshold = (currentValue) => currentValue < limit;\n return a.every(currentValue => currentValue <= limit)\n\n}", "function to_bool_arr_cutoff(cutoff){\n return new Function(\"arg\", \"c = \" + cutoff, \"return arg.toString(2).split('').map(elt => elt === '1').slice(0, c);\");\n}", "function positives(arr) {\n return filter(arr, function(elem) {\n return elem > 0;\n });\n}", "function checkEvery(arr) {\n return arr.every(v => v % 3 == 0 )\n}", "function positiveRowsOnly(arr){\n\n \treturn arr.filter(a=>{\n \t\tfor(i=0;i<a.length;i++){\n \t\t\n \t\t if(a[i]>0){\n \t\t\tcontinue;\n \t\t }\n return;\n \t };\n \treturn a;\n }\n \t);\n\n \t\n}", "function moreThanAverage(arr) {\n return filter(arr, function(element){\n return element>arr.length;\n })\n}", "function hasDivisableBy5(array) {\n\tvar bool = false;\n\tarray.forEach(function(number) {\n\t\tif(number % 5 === 0) {\n\t\t\tbool = true;\n\t\t} \n\t});\n\treturn bool;\n}", "function costas_verify ( array ){\n var result;\n var diff_array = array_diff_vector( array );\n var array_set = set_of_values( array );\n var diff_array_set = set_of_values( diff_array );\n //console.log( 'diff_array length', diff_array.length );\n //console.log( 'diff_array_set length', diff_array_set.length );\n return ( diff_array.length === diff_array_set.length && array_set.length === array.length );\n}", "function filterOutliers(array) {\n const arrMean = mean(array);\n return array.filter((value) => value / arrMean < 50);\n}", "function oddeven(arr) {\n\treturn arr.filter(x => x % 2 === 0).length * 2 < arr.length;\n}", "function under50(num) {\n return num < 50;\n}", "function every(array, callback){\n for (let i = 0; i < arr.length; i++){\n if (!callback(arr[i], i, arr)) return false;\n }\n return true;\n}", "function allEvenNumbersReject(array) {\n\t\n}", "function hasOnlyOddNumbers(arr){\n return arr.every(function(num){\n return num % 2 !== 0;\n })\n}", "function partition (pred, arr) {\n// create two blank arrays\nconst success = [];\nconst failure = [];\n// iterate through array given, if something satisfies the predicate, push into array 1; otherwise add to array2\narr.forEach(el => {\n if (pred(el)) {\n success.push(el);\n } else {\n failure.push(el);\n }\n})\n return [success, failure];\n}", "function CheckOn (value, index, ar) {\n return (value > b.minVariance && value < -1 * b.minVariance)\n}", "function checkAge(arr) {\n if(arr.every(function (person) {\n return (person.age > 18);\n })) {\n return true;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
emoji click event handler
function emojiClickEventHandler(emoji){ writeToClipboard(emoji.char); addToFavorite(emoji); }
[ "function imojieClick(emojie) {\n gMeme.lines.push({\n txt: `${emojie}`,\n size: 20,\n align: 'left',\n color: 'red',\n x: 250,\n y: 300\n }, )\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n drawImgText(elImgText)\n}", "function chooseEmoji(e) {\n if(e.target.matches(\".emoji\")) {\n textarea.value += e.target.innerHTML\n }\n}", "function changeEmojiBox()\n{\n console.log('in change Emojii arrived');\n $('#emojis-button').toggle(); \n}", "function emojiInputHandler(event) {\n var userInput = event.target.value;\n // var meaning = emojiDictionary[userInput];\n if (userInput in emojiDictionary) {\n setMeaning(emojiDictionary[userInput]);\n } else setMeaning(\"That's a new one! We don't have this in our database\");\n }", "function handleClickOutside(event) {\n if (\n ref.current &&\n !ref.current.contains(event.target) &&\n !grEmoji.current.contains(event.target)\n ) {\n setEmojiClicked(false);\n }\n }", "_onClickMessage(event) {\r\n\t\tif (event && event.target.classList.contains('narrator-chat')) {\r\n\t\t\t//@ts-ignore\r\n\t\t\tconst roll = $(event.currentTarget);\r\n\t\t\tconst tip = roll.find('.message-metadata');\r\n\t\t\tif (!tip.is(':visible')) tip.slideDown(200);\r\n\t\t\telse tip.slideUp(200);\r\n\t\t}\r\n\t}", "function handleEmotesButton(event) {\n const emote_list = document.querySelector(DOM_STRINGS.emoteList);\n emote_list.classList.toggle(DOM_STRINGS.emoteListActive);\n return;\n}", "function handleClick(evt) {\n const id = evt.target.id;\n let [categoryID, clueID] = id.split('-');\n let clue = categories[categoryID].clues[clueID];\n\n let clueText;\n if (clue.showing = false) {\n clueText = clue.question;\n clue.showing = 'showing question';\n } else if(clue.showing === 'showing question'){\n clueText = clue.answer;\n clue.showing = 'showing answer';\n } else {\n return;\n }\n $(`#${categoryID}-${clueID}`).html(clueText)\n}", "function handleEmotesButton(event) {\n document.querySelector(DOM_STRINGS.emoteList).classList.toggle('emote-list-active')\n }", "async function browseEmojis() {\n const response = await fetch(\"https://unpkg.com/emoji.json@12.1.0/emoji.json\")\n const data = await response.json()\n emojis = data\n // 3. Displaying emojis\n const emoji = emojis.map((e, i) => `<div class=\"emoji\" data-index=\"${i}\">${e.char}</div>`)\n .join(\"\")\n emojimodalbody.innerHTML = emoji\n}", "hitButton(e) {\n c.history.push(e.target.textContent);\n c.controller(e.target.textContent);\n }", "function ex(btn){ \n thePlayerManager.showExercise(btn);\n}", "function vB_Text_Editor_Events()\n{\n}", "function drawEmoji(canvas, img, face) {\n // Obtain a 2D context object to draw on the canvas\n var ctx = canvas.getContext('2d');\n let fp_0 = face.featurePoints[0];\t\n let em = face.emojis.dominantEmoji;\n \n ctx.font = '48px serif';\n ctx.fillText(em, fp_0.x-70, fp_0.y);\n}", "\"click #js-addChat\"(event, instance) {\n if (instance.uiState.get(\"addChat\") == ADD_TXT) {\n instance.uiState.set(\"addChat\", CANCEL_TXT);\n }\n else {\n instance.uiState.set(\"addChat\", ADD_TXT);\n }\n }", "handleBoardKeyPress(e) {\n if (!this.state.helpModalOpen && !this.state.winModalOpen) {\n if (49 <= e.charCode && e.charCode <= 57) {\n this.handleNumberRowClick((e.charCode - 48).toString());\n // undo\n } else if (e.key === \"r\") {\n this.handleUndoClick();\n // redo\n } else if (e.key === \"t\") {\n this.handleRedoClick();\n // erase/delete\n } else if (e.key === \"y\") {\n this.handleEraseClick();\n // notes\n } else if (e.key === \"u\") {\n this.handleNotesClick();\n }\n }\n }", "function insert(emoji) {\n let editor = N.MDEdit.__textarea__;\n\n // Find nearest ':' symbol before cursor on the current line\n editor.selectionStart = Math.max(\n editor.value.lastIndexOf('\\n', editor.selectionStart - 1) + 1,\n editor.value.lastIndexOf(':', editor.selectionStart)\n );\n\n $popup.removeClass('emoji-autocomplete__m-visible');\n\n text_field_update.insert(editor, ':' + emoji + ':');\n }", "onListenButtonClick() {\n this.micIcon.classList.add(\"hidden\");\n this.loader.classList.remove(\"hidden\");\n window.character.listen();\n }", "function sendEvent(button, pos) {\n var term = ace.session.term;\n // term.emit('mouse', {\n // x: pos.x - 32,\n // y: pos.x - 32,\n // button: button\n // });\n\n if (term.vt300Mouse) {\n // NOTE: Unstable.\n // http://www.vt100.net/docs/vt3xx-gp/chapter15.html\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n var data = '\\x1b[24';\n if (button === 0) data += '1';\n else if (button === 1) data += '3';\n else if (button === 2) data += '5';\n else if (button === 3) return;\n else data += '0';\n data += '~[' + pos.x + ',' + pos.y + ']\\r';\n term.send(data);\n return;\n }\n\n if (term.decLocator) {\n // NOTE: Unstable.\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n if (button === 0) button = 2;\n else if (button === 1) button = 4;\n else if (button === 2) button = 6;\n else if (button === 3) button = 3;\n term.send('\\x1b[' + button + ';' + (button === 3 ? 4 : 0) + ';' + pos.y + ';' + pos.x + ';' + (pos.page || 0) + '&w');\n return;\n }\n\n if (term.urxvtMouse) {\n pos.x -= 32;\n pos.y -= 32;\n pos.x++;\n pos.y++;\n term.send('\\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');\n return;\n }\n\n if (term.sgrMouse) {\n pos.x -= 32;\n pos.y -= 32;\n term.send('\\x1b[<' + ((button & 3) === 3 ? button & ~3 : button) + ';' + pos.x + ';' + pos.y + ((button & 3) === 3 ? 'm' : 'M'));\n return;\n }\n\n var data = [];\n\n encode(data, button);\n encode(data, pos.x);\n encode(data, pos.y);\n\n term.send('\\x1b[M' + String.fromCharCode.apply(String, data));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ This is the method that responds to the MouseLeftButtonUpEvent event. / / / Critical Calls DoUserInitiatedNavigation. We also want to protect against replay attacks / and can't assume the IsHyperlinkPressed DP hasn't been tampered with. / private static void
function OnMouseLeftButtonUp(/*object*/ sender, /*MouseButtonEventArgs*/ e) { /*IInputElement*/var element = sender; /*DependencyObject*/var dp = sender; if (element.IsMouseCaptured) { element.ReleaseMouseCapture(); } // // ISSUE - Leave this here because of 1111993. // if (dp.GetValue(IsHyperlinkPressedProperty)) { dp.SetValue(IsHyperlinkPressedProperty, false); // Make sure we're mousing up over the hyperlink if (element.IsMouseOver) { if (e.UserInitiated) { DoUserInitiatedNavigation(sender); } else { DoNonUserInitiatedNavigation(sender); } } } e.Handled = true; }
[ "function DispatchNavigation(/*object*/ sender)\r\n { \r\n var hl = sender instanceof Hyperlink ? hl : null;\r\n if (hl != null)\r\n {\r\n // \r\n // Call the virtual OnClick on Hyperlink to keep old behavior.\r\n // \r\n hl.OnClick(); \r\n }\r\n else \r\n {\r\n DoNavigation(sender);\r\n }\r\n }", "function pointerUp(e) {\n let newMouse = {x: (e.clientX/window.innerWidth)*2-1, y: (e.clientY/window.innerHeight)*-2+1};\n if (mouse.x == newMouse.x && mouse.y == newMouse.y) { onClick(e) }\n}", "function DoUserInitiatedNavigation(/*object*/ sender) \r\n {\r\n// CodeAccessPermission perm = SecurityHelper.CreateUserInitiatedNavigationPermission(); \r\n// perm.Assert(); \r\n\r\n try \r\n {\r\n DispatchNavigation(sender);\r\n }\r\n finally \r\n {\r\n CodeAccessPermission.RevertAssert(); \r\n } \r\n }", "function onPointerUp() {\n recordDelay(delay, evt);\n removeListeners();\n }", "takeOverLinks() {\n delegate(window.document, \"click\", \"a\", event => {\n if (\n event.button !== 0 ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n const link = event.target.closest(\"a\");\n if (\n link.getAttribute(\"href\").charAt(0) === \"#\" ||\n link.host !== window.location.host\n ) {\n return;\n }\n\n if (\n !event.defaultPrevented &&\n !link.hasAttribute(\"data-remote\") &&\n link.protocol.indexOf(\"http\") === 0\n ) {\n event.preventDefault();\n\n // update sidebar links\n if (link.closest(\"aside\")) {\n this.navigate(updateURL(link.href));\n } else {\n this.navigate(link.href);\n }\n }\n });\n }", "function mouseUp(evt) {\n\n mouseIsD = false;\n\n var c = document.getElementById(\"game-canvas\");\n var pos = getMousePos(c, evt);\n\n if(keyThatDown != ''){\n if(clickPos == pos) \n handleDoCommand(keyThatDown, pos);\n else if ( isAdjacent( clickPos , pos ) ) handleSplit(keyThatDown, clickPos, pos)\n }\n\n // console.log(\"Path Before : \", troopPath);\n\n convertRestOfPath();\n\n troopPath = [];\n\n // console.log(\"Path After : \", troopPath);\n\n deletePath();\n checkPath();\n\n}", "function detectArrowClicks() {\n document.getElementById('prev').addEventListener('click', function () {\n changePage(-1);\n });\n document.getElementById('next').addEventListener('click', function () {\n changePage(1);\n });\n}", "function handleHomeClick(e){\n if(!callInitiated || (callAccepted && !callEnded)){\n socketRef.current.disconnect();\n endCall();\n otherUser.current = null;\n setCallAccepted(false);\n if(!callInitiated) return;\n }\n if(otherUser.current || !isPartnerVideo){\n e.preventDefault();\n alert(\"connection active, can't go home\");\n }\n }", "function DoNavigation(/*object*/ sender) \r\n {\r\n /*IInputElement*/var element = sender;\r\n /*DependencyObject*/var dObject = sender;\r\n\r\n /*Uri*/var inputUri = dObject.GetValue(GetNavigateUriProperty(element));\r\n var targetWindow = dObject.GetValue(TargetNameProperty); \r\n RaiseNavigate(element, inputUri, targetWindow); \r\n }", "function keyPressed() {\n if (keyCode === UP_ARROW) {\n hain = true;\n }\n}", "onMoveUpTap_() {\n /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close();\n this.languageHelper.moveLanguage(\n this.detailLanguage_.language.code, true /* upDirection */);\n settings.recordSettingChange();\n }", "function onPrevButtonClick() {\n\t\tgotoPrevSlide()\n\t}", "function runPrevKeyDownEvent() {\n /*\n Check to see if the current playlist has been set\n or null and set the previous song.\n */\n if (config.active_playlist == \"\" || config.active_playlist == null) {\n AudioNavigation.setPrevious();\n } else {\n AudioNavigation.setPreviousPlaylist(config.active_playlist);\n }\n }", "function handleMoveUpWaypointClick(e) {\n //index of waypoint\n var waypointElement = $(e.currentTarget).parent();\n var index = parseInt(waypointElement.attr('id'));\n var prevIndex = index - 1;\n var previousElement = $('#' + prevIndex);\n waypointElement.insertBefore(previousElement);\n //adapt IDs...\n previousElement.attr('id', index);\n waypointElement.attr('id', prevIndex);\n //define the new correct order\n var currentIndex = prevIndex;\n var succIndex = index;\n //-1 because we have an invisible draft waypoint\n var numWaypoints = $('.waypoint').length - 1;\n //decide which button to show\n if (currentIndex === 0) {\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).hide();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n } else {\n //show both\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n if (succIndex == (numWaypoints - 1)) {\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).hide();\n } else {\n //show both\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:movedWaypoints', {\n id1: currentIndex,\n id2: succIndex\n });\n theInterface.emit('ui:routingParamsChanged');\n }", "function keyReleased() {\n if (keyCode === UP_ARROW) {\n hain = false;\n }\n}", "function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if (target.tagName === 'A') {\n href = target.getAttribute('href');\n\n dd(href, 'href');\n \n exp = href.split('/');\n\n // check if internal domain\n is_internal = false;\n for(i=0; i<exp.length; i++)\n {\n \tif(exp[i].indexOf(punch.base_url) !== -1) is_internal = true;\n }\n\n if(exp[0] == \"\") is_internal = true;\n\n //put your logic here...\n if (is_internal) {\n \tdd('Trigger routing!');\n //tell the browser not to respond to the link click\n e.preventDefault();\n }\n }\n}", "function sidestepLinks() {\n linksDrehen();\n schritt();\n rechtsDrehen();\n}", "listenAdminHomeLink() {\n editor.clearMenus();\n editor.showPrimaryMenu();\n event.preventDefault();\n }", "function navHorizontal(forward) {\n var currentlocation=window.location.pathname; //for assisting horizontal navigation and enter event procdeures\n currentlocation=currentlocation.substring(currentlocation.lastIndexOf('/') + 1);\n if(currentlocation == \"home.html\"){ //if the screen the homepage for horizontal scrolling\n app.horizontalScroll = true; //will prevent from accepting the enter keystroke\n app.updateNavItemsHorizontal();\n // app.navItems[1].focus();\n\n // jump to array index for continuous horizontal navigation\n var currentTabIndex = app.currentNavIdHorizontal;\n for (var i = 0; i < app.navItemsHorizontal.length; i++) {\n if (getNavTabIndexHorizontal(i) == currentTabIndex) {\n // app.activeNavItemHorizontal.style.backgroundColor = app.primaryColor;\n var next = i;\n next += forward ? 1 : -1;\n // if (next >= app.navItemsHorizontal.length) {\n // next = 0;\n // }\n // else if (next < 0) {\n // next = app.navItemsHorizontal.length - 1;\n // }\n focusActiveButtonHorizontal(app.navItemsHorizontal[next]);\n break;\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get rune info by id
function getRuneInfo(id) { if (id in rune) return rune[id] else throw new Error ("No rune with id " + id) }
[ "function find_letter(given_id) {\r\n for(var i = 0; i < 7; i++) {\r\n if(game_tiles[i].id == given_id) {\r\n return game_tiles[i].letter;\r\n }\r\n }\r\n // error\r\n return -1;\r\n}", "function get_letter(passed_id) {\n // loop to iterate through the 7 pieces on the rack\n for(var i = 0; i < 7; i++) {\n// console.log(\"Passing; \" + passed_id);\n // case to check if the letter was found\n if(scrabble_tiles[i].id == passed_id) {\n return scrabble_tiles[i].letter;\n }\n }\n // error to indicate if something went wrong.\n return -1;\n}", "async function getPokedex(id) {\n const pokeURL = `https://pokeapi.co/api/v2/pokedex/${id}`;\n const result = await fetch(pokeURL);\n const pokedexData = await result.json();\n //current log return array of 151 pokemon (entry_number, pokemon_species)\n console.log(pokedexData.pokemon_entries);\n}", "function getChampionInfo(id) {\n if (id in champion)\n return champion[id]\n else\n throw new Error (\"No champion with id \" + id)\n }", "function getRow(id) {\n\treturn /spot(\\d)\\d/.exec(id)[1];\n }", "static getAlternativeText(id) {\n const altTexts = {\n 1: \"Interior of Mission Chinese Food\",\n 2: \"Pizza Quattro Formaggi\",\n 3: \"Interior of Kang Ho Dong Baekjeong\",\n 4: \"Outside view of Katz's Delicatessen at night\",\n 5: \"Open kitchen of Roberta's Pizza\",\n 6: \"People queueing at Hometown BBQ\",\n 7: \"Outside view of Superiority Burger\",\n 8: \"Outside view of The Dutch\",\n 9: \"People eating at Mu Ramen\",\n 10: \"Interior of Casa Enrique\"\n };\n return altTexts[id];\n }", "function getElementIDJumlahPesanan (id)\r\n {\r\n var el = \"\";\r\n switch (id)\r\n {\r\n case 0: el = \"ket1\"; break;\r\n case 1: el = \"ket2\"; break;\r\n case 2: el = \"ket3\"; break;\r\n case 3: el = \"ket4\"; break;\r\n case 4: el = \"ket5\"; break;\r\n case 5: el = \"ket6\"; break;\r\n }\r\n return el; \r\n }", "function getPlanetName(id){\n var name;\n switch(id){\n case 1:\n name = 'Mercury'\n break;\n case 2:\n name = 'Venus'\n break;\n case 3:\n name = 'Earth'\n break;\n case 4:\n name = 'Mars'\n break;\n case 5:\n name = 'Jupiter'\n break;\n case 6:\n name = 'Saturn'\n break;\n case 7:\n name = 'Uranus'\n break;\n case 8:\n name = 'Neptune'\n break;\n }\n return name;\n}", "function game_find_unit_by_number(id)\n{\n return units[id];\n}", "function getChampionKey(id)\n {\n return getChampionInfo(id).key;\n }", "function extractPositionFromId(id,type) {\n \n var decal = (type == \"canvas\") ? 0 : 1; \n \n var virgulePosition = _virgulePosition(id)\n var i = +(id.substring(0,virgulePosition));\n var j = +(id.substring(virgulePosition+1,id.length-decal));\n \n return {\"i\":i,\"j\":j};\n}", "getVeteran(id) {\n return this.veteransMapping[id];\n }", "function searchIdArt(name){\n\n\tvar id : int;\n\t\n\tswitch (name) {\n\t\tcase \"Cabeza\" : id = 1; break;\n\t\tcase \"Cuello\" : id = 2; break;\n\t\tcase \"Torso\" : id = 3; break;\n\t case \"Cintura\" : id = 4; break;\n\t case \"ClaviculaI\" : id = 5; break;\n\t\tcase \"HombroI\" : id = 6; break;\n\t\tcase \"CodoI\" : id = 7; break;\n\t case \"MunecaI\" : id = 8; break;\n\t case \"ManoI\" : id = 9; break;\n\t\tcase \"DedoI\" : id = 10; break;\n\t\tcase \"ClaviculaD\" : id = 11; break;\n\t case \"HombroD\" : id = 12; break;\n\t case \"CodoD\" : id = 13; break;\n\t\tcase \"MunecaD\" : id = 14; break;\n\t\tcase \"ManoD\" : id = 15; break;\n\t case \"DedoD\" : id = 16; break;\n\t case \"CaderaI\" : id = 17; break;\n\t\tcase \"RodillaI\" : id = 18; break;\n\t\tcase \"TobilloI\" : id = 19; break;\n\t case \"PieI\" : id = 20; break;\n\t case \"CaderaD\" : id = 21; break;\n\t\tcase \"RodillaD\" : id = 22; break;\n\t\tcase \"TobilloD\" : id = 23; break;\n\t case \"PieD\" : id = 24; break;\n\t}\n\t\n\treturn id;\n}", "function getCol(id) {\n\treturn /spot\\d(\\d)/.exec(id)[1];\n }", "getById(id) {\n return spPost(TimeZones(this, `GetById(${id})`));\n }", "static getChoiceById(id) {\n\t\t// Loop through every choice\n\t\tfor (var i = 0; i < storyData.story.scene.choices.length; i++) {\n\t\t\tvar choice = storyData.story.scene.choices[i];\n\t\t\t// If the IDs match, return this choice\n\t\t\tif (choice.name == id) return choice;\n\t\t}\n\t}", "function get_details(id){\n console.log(\"You clicked Game ID: \" + id);\n fetch_by_id(id);\n}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'get', kparams);\n\t}", "getById(id) {\n return TermGroup(this, id);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get random phrase split into characters in a new array
function getRandomPhraseAsArray(arr) { //index a random phrase and store it in variable const currentPhrase = arr[generateRandomNumber(arr)]; //Split the phrase into individual characters const newArray = currentPhrase.split(''); //return the new array return newArray }
[ "function wordDivide(randomWord) {\n var wordArray = randomWord.split(\"\");\n for (var i = 0; i < wordArray.length; i++) {\n letters.push(wordArray[i]);\n console.log(wordArray[i]);\n }\n}", "function wordToArrayOfLetters(randomWord)\n{\n\tconst wordToGuess = [];\t\t\t\t\t\t\n\tfor(let i=0; i<randomWord.length; i++)\n\t{\n\t\twordToGuess[i*2]= randomWord.charAt(i);\n\t\twordToGuess[i*2+1] = \" \";\n\t}\n\treturn wordToGuess;\n}", "function randomPhrase (phrases){\r\n\treturn phrases[Math.floor(Math.random()*phrases.length)];\r\n\t}", "function wordsGenerator(integer) {\n\twords = [];\n\tchars = 'abcdefghijklmnopqrstuvwxyz'\n\tfor (i=0 ; i < integer ; i++) {\n\t\tvar result = '';\n\t\tvar length = Math.floor((Math.random() * 10) + 1);\n\t for (var j = length; j > 0; --j) { \n\t \tresult += chars[Math.floor(Math.random() * chars.length)];\n\t }\n words.push(result);\n\t\t\n\t}\n\treturn words\n}", "function genPhrase(){\n let subject = subjectsText[Math.floor(Math.random() * subjectsText.length)];\n let verb = verbsText[Math.floor(Math.random() * verbsText.length)];\n let preposition1 = prepositionsText[Math.floor(Math.random() * prepositionsText.length)];\n let preposition2 = prepositionsText[Math.floor(Math.random() * prepositionsText.length)];\n let jargon1 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let jargon2 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let jargon3 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let sentence = subject + \" \" + verb + \" \" + jargon1 + \" \" + preposition1 + \" \" + jargon2 + \" \" + preposition2 + \" \" + jargon3 + \".\";\n return sentence;\n}", "function randomWordList(num) {\nvar wordList = []\n for (j = 0; j < num; j++) {\n wordList.push(randomWord());\n}\nreturn wordList\n}", "function initWord() {\n var ind = randIndex(wordDB.length);\n var randWord = wordDB[ind];\n currentWord = randWord.split('');\n}", "function randomTestGenerator(int) {\n\n // declare empty array\n var testArray = [];\n\n // create function to return random letter of alphabet\n function chooseRandomLetter() {\n\n // create array with each letter of alphabet as separate items\n var alphabetArray = [\"a\", \"b\", \"c\", \"d\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\",\n \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\",\n \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\n\n // create randomLetter variable that picks random item from alphabetArray\n var randomLetter = alphabetArray[Math.floor((Math.random() * 27) + 1)];\n\n // return randomLetter\n return randomLetter;\n };\n\n // create function to return random word using random letters\n function chooseRandomWords() {\n\n // declare empty string randomWord\n var randomWord = \"\";\n\n // loop between 1 and 10 times\n // add a random letter to the randomWord string each time\n for (var i = 0; i < (Math.floor((Math.random() * 10) + 1)); i++) {\n randomWord += chooseRandomLetter();\n };\n\n // return randomWord\n return randomWord;\n };\n\n // loop int amount of times\n // add a random word to the testArray each time\n for (var i = 0; i < int; i++) {\n testArray.push(chooseRandomWords())\n };\n\n // return testArray\n return testArray;\n}", "makeText(numWords = 100) {\n const numWordsAv = Object.keys(this.chains).length;\n let randNum, text;\n \n do {\n randNum = Math.floor(Math.random() * numWordsAv);\n text = [Object.keys(this.chains)[randNum]];\n } while (text[0][0] === text[0][0].toLowerCase())\n\n if (text[0].slice(-1) === '.') {\n return text.toString();\n }\n text = text[0].split(\" \");\n\n for (let i = 0; i < numWords - 2; i++) {\n let pair = text.slice(i, i+2).join(\" \");\n\n let randNum = Math.floor(Math.random() * this.chains[pair].length);\n if (this.chains[pair][randNum] === null ) {\n break;\n } else {\n text.push(this.chains[pair][randNum])\n if (this.chains[pair][randNum].slice(-1) ==='.') break;\n }\n }\n return text.join(\" \")\n }", "function randomWord() {\nvar word = \"\"\n for (var i = 0; i < Math.floor((Math.random() * 10) + 1); i++) {\n var word = word + randomLetter();\n }\nreturn word;\n}", "function tokenize(phrase) {\n\n const tokenArray = [];\n let currToken = \"\";\n\n for (let i = 0; i < phrase.length; i++) {\n if(phrase[i] !== \" \") {\n currToken += phrase[i];\n } else {\n tokenArray.push(currToken);\n currToken = \"\";\n }\n }\n\n tokenArray.push(currToken);\n return tokenArray;\n}", "randomCharactor() {\n let str = '!@#$%^&*()_+?'\n return str[this.random(str.length)]\n }", "getRandomPhrase () {\n\t\tlet newIndex;\n\t\tdo {\n\t\t\tnewIndex = Math.floor(Math.random() * this.phrases.length);\n\t\t} while (this.usedIndexes.indexOf(newIndex) !== -1);\n\t\tthis.usedIndexes.push(newIndex);\n\t\tdocument.body.style.background = this.getRandomColor();\n\t\treturn this.phrases[newIndex];\n\t}", "function splitText(text, ngram = 2) {\n\t const result = [];\n\n\t for (let i = 0; i < text.length - ngram + 1; i++) {\n\t result.push(text.slice(i, i + ngram));\n\t }\n\n\t return result;\n\t}", "getFunText() {\n var texts = [\n [\"bounceIn\", \"Great Job!\", \"1000\"],\n [\"bounceIn\", \"With every tap you help put a family on the map\", \"3000\"],\n [\"bounceIn\", \"Thank you!\", \"1000\"],\n [\"bounceIn\", \"Your effort is helping!\", \"1000\"],\n [\"bounceIn\", \"Keep up the good work!\", \"1000\"],\n ];\n\n\n var random = Math.floor(Math.random() * texts.length);\n return texts[random];\n }", "function randomlySelectSingleCharacter(array){\n\n var i = Math.floor(Math.random() * array.length);\n \n var randomCharacter = String.fromCharCode(array[i]);\n\n return randomCharacter;\n}", "function getWord() {\n for (let i = 0; i < commonWords.length; i++) {\n if (commonWords[i].length > 2) {\n wordList.push(commonWords[i]);\n }\n }\n answerWord = wordList[Math.floor(Math.random() * wordList.length)];\n return answerWord;\n}", "function madlibs(template) {\n const dictionary = {\n adjectives: ['quick', 'lazy', 'sleepy', 'noisy', 'hungry'],\n nouns: ['fox', 'dog', 'head', 'leg', 'tail', 'cat'],\n verbs: ['jumps', 'lifts', 'bites', 'licks', 'pats'],\n adverbs: ['easily', 'lazily', 'noisily', 'excitedly'],\n }\n \n return template.replace(/:[a-z]+:/gi, match => '\"' + selectRandomWord(match) + '\"');\n\n function selectRandomWord(token) {\n let cleanedToken = token.slice(1, token.length - 1).toLowerCase();\n let randomIndex = Math.round(Math.random() * (dictionary[cleanedToken].length - 1));\n return dictionary[cleanedToken][randomIndex];\n }\n\n}", "function genChar(arr){\n\n var rand = Math.random()\n var l = arr.length;\n var i = Math.floor(l * rand); //generate random index\n var char = arr[i]; //select random character from array\n var c = char.toString()\n\n return c\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
accepts element and toggles the index of the option element to deselect. Removes tag
function remove(element) { var index = element.getAttribute('data-index'); select[0].options[index].selected = false; element.parentNode.parentNode.removeChild(element.parentNode); }
[ "deselect(option) {\n this.deselectValue(option.value);\n }", "deselect(option) {\n if (!this.disabled && !option.disabled) {\n option.deselect();\n }\n }", "deselect() {\n if (this.selected != null) {\n this.selected.deselect();\n this.selected = null;\n }\n }", "_onElementDeselect() {\n this._displayNoSelectedElementInfo.apply(this);\n }", "function deactivateOptions(options) {\n options.forEach((item) => {\n item.classList.remove(\"active-option\");\n });\n}", "_rationalize() {\n for (let i = 0; i < this.children.length; i++) {\n if (this._selection === i) {\n this.children[i].setAttribute('selected', '');\n } else {\n this.children[i].removeAttribute('selected');\n }\n }\n }", "unselectCurrentItem() {\n const activePaginationItem = this.paginationItems[this.activeIndexItem];\n\n activePaginationItem.tabIndex = '-1';\n activePaginationItem.ariaSelected = FALSE_STRING;\n activePaginationItem.className = INDICATOR_ACTION;\n\n this.carouselItems[this.activeIndexItem].callbacks.unselect();\n }", "function removecolor() {\n let color = document.getElementById(\"colorSelect\");\n color.remove(color.selectedIndex);\n}", "triggerRemove(value) {\n const selectedOptions = uniq(without(this.state.selected, value));\n this.triggerChange(selectedOptions);\n }", "disableSelect() {\n this.select = false;\n }", "function unselect(self, value){\r\n var opts = self.options;\r\n var combo = self.combo;\r\n var values = combo.getValues();\r\n var index = $.inArray(value+'', values);\r\n if (index >= 0){\r\n values.splice(index, 1);\r\n setValues(self, values);\r\n opts.onUnselect.call(self, opts.finder.getRow(self, value));\r\n }\r\n }", "function toggleScrollSelect(state) {\n if (state) {\n $('#gray').remove();\n }\n else {\n if (!$('#gray').length) {\n var cover = '<select id=\"gray\"><option value=\"no\">Scroll to:</option></select>';\n var selpos = $('#scroller').offset();\n $('#opt4').append(cover);\n $('#gray').offset({ top: selpos.top, left: selpos.left });\n $('#gray').css('z-index', '1000');\n $('#gray').attr('disabled', 'disabled');\n }\n }\n}", "function removerItem(index) {\n const finded = selecionados.indexOf(index);\n if (finded !== -1) {\n selecionados.splice(finded, 1)\n }\n if (selecionados.length === 0) excluirBtn.disabled = true\n}", "function removeSelected () {\n removeSelect0 = document.getElementById(\"selectedCharacter0\");\n console.log(document.getElementById(\"selectedCharacter0\").childNodes);\n while (removeSelect0.hasChildNodes()) {\n removeSelect0.removeChild(removeSelect0.firstChild);\n } // thank google for this @ https://www.w3schools.com/jsref/met_node_removechild.asp\n removeSelect1 = document.getElementById(\"selectedCharacter1\");\n while (removeSelect1.hasChildNodes()) {\n removeSelect1.removeChild(removeSelect1.firstChild);\n }\n}", "function clearNodeOptions() {\n var startList = document.getElementById(\"selectStart\");\n var goalList = document.getElementById(\"selectGoal\");\n\n let length = startList.length;\n for (i = length - 1; i >= 1; i--) {\n startList.removeChild(startList.childNodes[i]);\n goalList.removeChild(goalList.childNodes[i]);\n }\n}", "close() {\n this.removeAttribute('expanded');\n this.firstElementChild.setAttribute('aria-expanded', false);\n // Remove the event listener\n this.dispatchCustomEvent('tk.dropdown.hide');\n }", "function unselectFeature() {\n if (highlight) {\n highlight.remove();\n }\n }", "function moveOptionDown(obj) {\n\tfor (i=obj.options.length-1; i>=0; i--) {\n\t\tif (obj.options[i].selected) {\n\t\t\tif (i != (obj.options.length-1) && ! obj.options[i+1].selected) {\n\t\t\t\tswapOptions(obj,i,i+1);\n\t\t\t\tobj.options[i+1].selected = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function deleteOneSelectOption(sel, value, bDontSetWidth)\n{\n if (isNLDropDown(sel))\n {\n getDropdown(sel).deleteOneOption(value, bDontSetWidth);\n }\n else if (isNLMultiDropDown(sel))\n {\n getMultiDropdown(sel).deleteOneOption(value);\n }\n else if (sel.type == 'select-one' || sel.type == 'select-multiple')\n {\n var opts = sel.options;\n for (var i=0; i < opts.length; i++)\n if (opts[i].value == value)\n opts[i] = null;\n }\n else if ( sel.form.elements[sel.name+\"_display\"] != null )\n {\n sel.form.elements[sel.name+\"_display\"].value = \"\";\n sel.value = \"\";\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a polyfill suite from polyfill.io and then calls the provided callback when it is ready
function polyfill(callback) { callback(); }
[ "function runPolyfill() {\n polyfillCustomElements(document);\n}", "async function polyfill(locale = '') {\n const dataPolyfills = [];\n // Polyfill Intl.getCanonicalLocales if necessary\n if (shouldPolyfillGetCanonicalLocales()) {\n await import(\n /* webpackChunkName: \"intl-getcanonicallocales\" */ '@formatjs/intl-getcanonicallocales/polyfill'\n );\n }\n\n // Polyfill Intl.PluralRules if necessary\n if (shouldPolyfillPluralRules()) {\n await import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/polyfill'\n );\n }\n\n if ((Intl.PluralRules).polyfilled) {\n const lang = locale.split('-')[0];\n switch (lang) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.NumberFormat if necessary\n if (shouldPolyfillNumberFormat()) {\n await import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/polyfill'\n );\n }\n\n if ((Intl.NumberFormat).polyfilled) {\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.DateTimeFormat if necessary\n if (shouldPolyfillDateTimeFormat()) {\n await import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/polyfill'\n );\n }\n\n if ((Intl.DateTimeFormat).polyfilled) {\n dataPolyfills.push(import('@formatjs/intl-datetimeformat/add-all-tz'));\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.RelativeTimeFormat if necessary\n if (shouldPolyfillRelativeTimeFormat()) {\n await import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/polyfill'\n );\n }\n\n if ((Intl).RelativeTimeFormat.polyfilled) {\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n await Promise.all(dataPolyfills);\n}", "function loadIntlPolyfill(locale) {\n if (areIntlLocalesSupported(locale)) {\n return Promise.resolve(locale, false);\n }\n return new Promise(resolve => {\n require.ensure(['intl'], require => {\n require('intl');\n resolve(locale, true);\n }, 'intl-polyfill');\n });\n}", "activatePolyfill_() {}", "waitForDOMContentLoaded() {\n const callback = () => {\n this.isReady = true;\n this.runMethodsThatWaits();\n this.frame.contentWindow.document.removeEventListener(\n \"DOMContentLoaded\",\n callback\n );\n };\n this.frame.contentWindow.document.addEventListener(\n \"DOMContentLoaded\",\n callback\n );\n }", "addFeatureListener(callback) {\n this.featureListeners.push(callback);\n }", "function runPolyfills() {\n // Array.prototype.filter\n // ========================================================\n // SOURCE:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\n if (!Array.prototype.filter) {\n // eslint-disable-next-line no-extend-native\n Array.prototype.filter = function (fun) {\n if (this === void 0 || this === null) {\n throw new TypeError();\n }\n\n var t = Object(this);\n var len = t.length >>> 0;\n\n if (typeof fun !== 'function') {\n throw new TypeError();\n }\n\n var res = [];\n\n for (var _len = arguments.length, restProps = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n restProps[_key - 1] = arguments[_key];\n }\n\n var thisArg = restProps ? restProps[0] : void 0;\n\n for (var i = 0; i < len; i++) {\n if (i in t) {\n var val = t[i]; // NOTE: Technically this should Object.defineProperty at\n // the next index, as push can be affected by\n // properties on Object.prototype and Array.prototype.\n // But that method's new, and collisions should be\n // rare, so use the more-compatible alternative.\n\n if (fun.call(thisArg, val, i, t)) {\n res.push(val);\n }\n }\n }\n\n return res;\n };\n } // Array.prototype.map\n // ========================================================\n // SOURCE:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\n // Production steps of ECMA-262, Edition 5, 15.4.4.19\n // Reference: http://es5.github.io/#x15.4.4.19\n\n\n if (!Array.prototype.map) {\n // eslint-disable-next-line no-extend-native\n Array.prototype.map = function (callback, thisArg) {\n var T;\n var k;\n\n if (this === null || this === undefined) {\n throw new TypeError(' this is null or not defined');\n } // 1. Let O be the result of calling ToObject passing the |this|\n // value as the argument.\n\n\n var O = Object(this); // 2. Let lenValue be the result of calling the Get internal\n // method of O with the argument \"length\".\n // 3. Let len be ToUint32(lenValue).\n\n var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception.\n // See: http://es5.github.com/#x9.11\n\n if (typeof callback !== 'function') {\n throw new TypeError(callback + ' is not a function');\n } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.\n\n\n if (arguments.length > 1) {\n T = thisArg;\n } // 6. Let A be a new array created as if by the expression new Array(len)\n // where Array is the standard built-in constructor with that name and\n // len is the value of len.\n\n\n var A = new Array(len); // 7. Let k be 0\n\n k = 0; // 8. Repeat, while k < len\n\n while (k < len) {\n var kValue = void 0;\n var mappedValue = void 0; // a. Let Pk be ToString(k).\n // This is implicit for LHS operands of the in operator\n // b. Let kPresent be the result of calling the HasProperty internal\n // method of O with argument Pk.\n // This step can be combined with c\n // c. If kPresent is true, then\n\n if (k in O) {\n // i. Let kValue be the result of calling the Get internal\n // method of O with argument Pk.\n kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal\n // method of callback with T as the this value and argument\n // list containing kValue, k, and O.\n\n mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments\n // Pk, Property Descriptor\n // { Value: mappedValue,\n // Writable: true,\n // Enumerable: true,\n // Configurable: true },\n // and false.\n // In browsers that support Object.defineProperty, use the following:\n // Object.defineProperty(A, k, {\n // value: mappedValue,\n // writable: true,\n // enumerable: true,\n // configurable: true\n // });\n // For best browser support, use the following:\n\n A[k] = mappedValue;\n } // d. Increase k by 1.\n\n\n k++;\n } // 9. return A\n\n\n return A;\n };\n } // Array.prototype.forEach\n // ========================================================\n // SOURCE:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\n // Production steps of ECMA-262, Edition 5, 15.4.4.18\n // Reference: http://es5.github.io/#x15.4.4.18\n\n\n if (!Array.prototype.forEach) {\n // eslint-disable-next-line no-extend-native\n Array.prototype.forEach = function (callback, thisArg) {\n var T;\n var k;\n\n if (this === null || this === undefined) {\n throw new TypeError(' this is null or not defined');\n } // 1. Let O be the result of calling ToObject passing the |this| value as the\n // argument.\n\n\n var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the\n // argument \"length\".\n // 3. Let len be ToUint32(lenValue).\n\n var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception.\n // See: http://es5.github.com/#x9.11\n\n if (typeof callback !== \"function\") {\n throw new TypeError(callback + ' is not a function');\n } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.\n\n\n if (arguments.length > 1) {\n T = thisArg;\n } // 6. Let k be 0\n\n\n k = 0; // 7. Repeat, while k < len\n\n while (k < len) {\n var kValue = void 0; // a. Let Pk be ToString(k).\n // This is implicit for LHS operands of the in operator\n // b. Let kPresent be the result of calling the HasProperty internal\n // method of O with\n // argument Pk.\n // This step can be combined with c\n // c. If kPresent is true, then\n\n if (k in O) {\n // i. Let kValue be the result of calling the Get internal method of O with\n // argument Pk\n kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and\n // argument list containing kValue, k, and O.\n\n callback.call(T, kValue, k, O);\n } // d. Increase k by 1.\n\n\n k++;\n } // 8. return undefined\n\n };\n }\n}", "function setup(callback) {\r\n $.ajax('/Handlers/Capability.ashx', {\r\n method: 'POST',\r\n dataType: 'json',\r\n success: function (data) {\r\n Twilio.Device.setup(data.token);\r\n callback();\r\n },\r\n error: function (xhr, status, error) {\r\n alert(error);\r\n }\r\n });\r\n }", "function loadJQuery(callback){\n if (typeof jQuery == 'undefined') {\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.onload=function(){\n jQuery.noConflict();\n $ = jQuery;\n callback();\n };\n script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';\n document.getElementsByTagName('head')[0].appendChild(script);\n } else {\n $ = jQuery;\n callback();\n }\n }", "appLoad(type, callback) {\n const _self = this;\n\n switch (type) {\n case 'loading':\n if (_self.doc.readyState === 'loading') {\n callback();\n }\n\n break;\n case 'dom':\n _self.doc.onreadystatechange = function () {\n if (_self.doc.readyState === 'complete') {\n callback();\n }\n };\n\n break;\n case 'full':\n _self.window.onload = function (e) {\n callback(e);\n };\n\n break;\n default:\n callback();\n }\n }", "async init() {\r\n\t\t// Overwrite if the test unit needs to process before the tests are called.\r\n\t}", "async onPluginRegistered() {\r\n // noop\r\n }", "function addOnloadHook (hookFunct) {\n // Allows add-on scripts to add onload functions\n if (!doneOnloadHook) {\n onloadFuncts[onloadFuncts.length] = makeSafe (hookFunct);\n } else {\n makeSafe (hookFunct)(); // bug in MSIE script loading\n }\n }", "function LoadCalendarScript(callback){\n\tfunction LoadFullCalendarScript(){\n\t\tif(!$.fn.fullCalendar){\n\t\t\t$.getScript('/hiapt/resources/fullcalendar/fullcalendar.js', callback);\n\t\t}\n\t\telse {\n\t\t\tif (callback && typeof(callback) === \"function\") {\n\t\t\t\tcallback();\n\t\t\t}\n\t\t}\n\t}\n\tif (!$.fn.moment){\n\t\t$.getScript('/hiapt/resources/js/moment.min.js', LoadFullCalendarScript);\n\t}\n\telse {\n\t\tLoadFullCalendarScript();\n\t}\n}", "setupInitialization () {\n const finishInitialization = (result) => {\n this.isInitialized = result\n\n // We only want to resolve / reject the init promise once during the initialization flow. Because some trackers\n // do not support reporting \"failures\" we need to support timeouts that can result in race conditions in some\n // situations. In these situations we use the first success / fail callback to determine the tracker state and\n // we change the callbacks to noops to prevent later calls from changing the init state.\n this.onInitializeSuccess = () => {}\n this.onInitializeFail = () => {}\n }\n\n this.initializationCompletePromise = new Promise((resolve, reject) => {\n this.onInitializeSuccess = () => {\n resolve()\n finishInitialization(true)\n }\n\n this.onInitializeFail = (e) => {\n if (!/init timeout/.test(e.message)) {\n console.error(`${this.constructor.name || 'Tracker'} initialization failed`, e)\n }\n reject(e)\n finishInitialization(false)\n }\n })\n }", "function bootSequence(locale = getCurrentLocale()) {\n return loadIntlPolyfill(locale)\n .then(loadLocaleData)\n .then(() => moment.locale(locale)) // Ensure moment is loaded with the correct locale\n .catch(err => console.error(err)); // eslint-disable-line no-console\n}", "function initServiceWorker() {\n if ('serviceWorker' in navigator) {\n navigator.serviceWorker\n .register('../service-worker.js')\n .then(function() { console.log('ServiceWorker Registered');\n }, function(err) {\n console.log('ServiceWorker registration failed: ', err);\n });\n }\n}", "function fireWhenReady(callback) {\n if (!displayOnEvent || slideIsReady) {\n callback();\n } else {\n slideReadyCallbacks.push(callback);\n }\n }", "loadQuill(callback)\n {\n let rootQuillScript = this.element.ownerDocument.querySelector(\n 'script[mycelium-quill-script]'\n )\n\n if (!rootQuillScript)\n {\n console.error(\"Mycelium quill script not found!\")\n return\n }\n\n quillLink = this.contentDocument.createElement(\"script\")\n \n quillLink.onload = () => {\n // register blots\n require(\"../../initialization.js\").setupQuill(this.contentWindow)\n\n // redirect undo and redo commands\n let history = this.contentWindow.Quill.import(\"modules/history\")\n history.prototype.undo = () => {\n this.textPad.quill.history.undo()\n }\n history.prototype.redo = () => {\n this.textPad.quill.history.redo()\n }\n \n callback()\n }\n\n quillLink.src = rootQuillScript.src\n this.contentBody.appendChild(quillLink)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process the grammar and build final data structures and functions
function processGrammar(dict, tokens) { var opts = {}; if (typeof dict === 'string') { dict = lexParser.parse(dict); } dict = dict || {}; opts.options = dict.options || {}; opts.moduleType = opts.options.moduleType; opts.moduleName = opts.options.moduleName; opts.conditions = prepareStartConditions(dict.startConditions); opts.conditions.INITIAL = {rules:[],inclusive:true}; opts.performAction = buildActions.call(opts, dict, tokens); opts.conditionStack = ['INITIAL']; opts.moduleInclude = (dict.moduleInclude || '').trim(); return opts; }
[ "function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}", "function ShapeGrammar(axiom, scene, iterations, \n\t\t\t\t\t\torigin, noise, g1, g2) {\n\tgeo1 = g1;\n\tgeo2 = g2;\n\tthis.axiom = axiom;\n\tthis.grammar = [];\n\tthis.iterations = iterations;\n\tthis.scene = scene;\n\tthis.height = 2.0 * noise;\n\tthis.material;\n\t\n\t// cosine palate input values\n\tvar a = new THREE.Vector3(-3.142, -0.162, 0.688);\n\tvar b = new THREE.Vector3(1.068, 0.500, 0.500);\n\tvar c = new THREE.Vector3(3.138, 0.688, 0.500);\n\tvar d = new THREE.Vector3(0.000, 0.667, 0.500);\n\tvar t = this.height - Math.floor(this.height);\n\n\t// set material color to the pallete result\n\tvar result = palleteColor(a, b, c, t, d);\n\tthis.material = new THREE.MeshLambertMaterial({ color: result });\n\tthis.material.color.setRGB(result.r, result.g, result.b);\n\tthis.material.color.addScalar(0.95);\n\t\n\t// Init grammar for shapes\n\tfor (var i = 0; i < this.axiom.length; i++) {\n\t\tvar node = new SymbolNode(axiom.charAt(i), new THREE.BoxGeometry(1, 1, 1));\n\t\tnode.scale = new THREE.Vector3(1, this.height, 1);\n\t\tnode.position = new THREE.Vector3(origin.x, -0.02, origin.y);\n\t\tnode.material = this.material;\n\n\t\t// add the node to the grammar\n\t\tthis.grammar[i] = node;\n\t} \n\n\t// Function to compute shape grammar for a number of iterations\n\t// Swaps out characters for their grammar rule value\n\tthis.compute = function() {\n\t\t// Repeats for number of iterations\n\t\tfor (var k = 0; k < this.iterations; k++) {\n\t\t\t\n\t\t\t/*\n\t\t\t * Adds children instances to a resulting array \n\t\t\t * and replaces grammar with new list\n\t\t\t */\n\t\t\tvar newArr = [];\n\t\t\tfor (var i = 0; i < this.grammar.length; i++) {\n\t\t\t\tvar symbolNode = this.grammar[i];\n\t\t\t\t// Subdivide rule\n\t\t\t\tif (symbolNode.symbol == 'A') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = subdivideX(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Self rule\n\t\t\t\telse if (symbolNode.symbol == 'B') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = noTrans(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (symbolNode.symbol == 'C') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = stack(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (symbolNode.symbol == 'D') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = buildBaseOrBridge(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (var j = 0; j < newArr.length; j++) {\n\t\t\t\tthis.grammar.push(newArr[j]);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Function to render resulting shape grammar\n\t// Uses node data from shape grammar to create a mesh\n\tthis.render = function() {\n\t\tthis.compute();\n\n\t\tfor (var i = 0; i < this.grammar.length; i++) {\n\t\t\tvar node = this.grammar[i];\n\n\t\t\t// create mesh for building\n\t\t\tvar mesh = new THREE.Mesh(node.geometry, this.material);\n\t\t\t\n\t\t\t// set color of buildings to be the color stored in this instance\n\t\t\tvar mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 } );\n\t\t\tmat.color = this.material.color.clone();\n\t\t\t\n\n\t\t\t// create geometry for wireframe\n\t\t\tvar geo = new THREE.EdgesGeometry( node.geometry );\n\n\t\t\t// add mesh outlines\n\t\t\tvar wireframe = new THREE.LineSegments( geo, mat );\n\t\t\tmesh.add(wireframe);\n\t\t\t\n\t\t\t// set position\n\t\t\tvar p = node.position.clone();\n\t\t\tvar r = node.rotation.clone();\n\n\t\t\t// set rotation\n\t\t\tmesh.position.set(p.x, p.y, p.z);\n\t\t\tmesh.rotation.set(r.x, r.y, r.z);\n\n\t\t\t// set scale\n\t\t\tvar m = new THREE.Vector3().multiplyVectors(node.geomScale, node.scale);\n\t\t\tmesh.scale.set(m.x, m.y, m.z);\n\n\t\t\tmesh.updateMatrix();\n\t\t\tthis.scene.add(mesh);\n\t\t}\n\t}\n}", "cleanUp()\n {\n // grammar empty\n if (!this._rules.length) \n {\n this.clear();\n }\n\n // to remove duplicate rules, we make use of the toString method and Set data Structure.\n let rule = this._rules.map((cur) => \n {\n return cur.toString();\n });\n rule = new Set(rule);\n rule = Array.from(rule); // convert back to array\n this._rules = rule.map((cur) => \n {\n let temp = cur.split('->');\n // if the RHS is '', we make it EMPTY\n if (!temp[1].length)\n {\n temp[1] = EMPTY;\n }\n return new Rule(temp[0], temp[1]);\n });\n\n // remove variables that doesn't have any production rules, i.e. only keep LHS of all rules\n let variables = rule.map((cur) => \n {\n return cur.split('->')[0];\n });\n this._variables = new Set(variables);\n\n // TODO: remove any lingering terminals, hard to do at this point because it is not clear how \n // to idenitify a terminal\n }", "function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }", "function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}", "function CreateJsonGrammar(myna) \n{\n // Setup a shorthand for the Myna parsing library object\n let m = myna; \n\n let g = new function() \n {\n // These are helper rules, they do not create nodes in the parse tree. \n this.escapedChar = m.seq('\\\\', m.char('\\\\/bfnrt\"'));\n this.escapedUnicode = m.seq('\\\\u', m.hexDigit.repeat(4)); \n this.quoteChar = m.choice(this.escapedChar, this.escapedUnicode, m.charExcept('\"'));\n this.fraction = m.seq(\".\", m.digit.zeroOrMore); \n this.plusOrMinus = m.char(\"+-\");\n this.exponent = m.seq(m.char(\"eE\"), this.plusOrMinus.opt, m.digits); \n this.comma = m.text(\",\").ws; \n\n // The following rules create nodes in the abstract syntax tree \n \n // Using a lazy evaluation rule to allow recursive rule definitions \n let _this = this; \n this.value = m.delay(function() { \n return m.choice(_this.string, _this.number, _this.object, _this.array, _this.bool, _this.null); \n }).ast;\n\n this.string = m.doubleQuoted(this.quoteChar.zeroOrMore).ast;\n this.null = m.keyword(\"null\").ast;\n this.bool = m.keywords(\"true\", \"false\").ast;\n this.number = m.seq(this.plusOrMinus.opt, m.integer, this.fraction.opt, this.exponent.opt).ast;\n this.array = m.bracketed(m.delimited(this.value.ws, this.comma)).ast;\n this.pair = m.seq(this.string, m.ws, \":\", m.ws, this.value.ws).ast;\n this.object = m.braced(m.delimited(this.pair.ws, this.comma)).ast;\n };\n\n return m.registerGrammar(\"json\", g);\n}", "function CreateGrammar(myna) {\r\n // Setup a shorthand for the Myna parsing library object\r\n let m = myna; \r\n\r\n let g = new function() {\r\n // comment and whitespace \r\n this.comment \t= m.choice(m.seq(\"/*\", m.advanceUntilPast(\"*/\")), m.seq('//', m.advanceUntilPast(\"\\n\")));\r\n this.ws = m.choice(m.char(\" \\t\\r\\n\"), this.comment).zeroOrMore;\r\n\t\t\r\n\t\t// char class\r\n\t\tthis.escape\t\t\t= m.seq('\\\\', m.choice(m.char('\\\\trn\\'\"'), m.seq('u', m.hexDigit, m.hexDigit, m.hexDigit, m.hexDigit)));\r\n\t\tthis.string \t\t= m.singleQuoted(m.choice(this.escape, m.notChar(\"\\\\'\")).oneOrMore).ast;\r\n\t\tthis.charRange\t\t= m.seq('(', this.string, '..', this.string, ')');\r\n\t\tthis.identifier\t\t= m.seq(m.letter, m.choice(m.letter, '_', '-', m.digit).oneOrMore).ast;\r\n\t\t\r\n\t\t// patterns \r\n let _this = this;\r\n this.group \t\t\t= m.seq('(', this.ws, m.delay(function() { return _this.pattern; }), ')'); // using a lazy evaluation rule to allow recursive rule definitions \r\n\t\tthis.term\t\t\t= m.choice(this.identifier, this.group, this.string, this.charRange);\r\n\t\tthis.repeatOp\t\t= m.char('?+*').ast;\r\n\t\tthis.repeat\t\t\t= m.seq(this.term, this.repeatOp.opt, this.ws);\r\n\t\tthis.concat\t\t\t= this.repeat.oneOrMore;\r\n\t\tthis.altOp\t\t\t= '|'; // m.choice('|','-').ast;\r\n\t\tthis.alternate\t\t= m.seq(this.altOp, this.ws, this.concat);\r\n\t\tthis.pattern \t\t= m.seq(this.concat, this.alternate.zeroOrMore).ast;\r\n\t\t\r\n\t\tthis.defined_as = \":\";\r\n\t\tthis.rule \t\t\t= m.seq(this.ws, this.identifier, this.ws, this.defined_as, this.ws, this.pattern, this.ws, ';', this.ws,).ast; // end each rule with newLine, makes the syntax more orthogonal/robust/simpler\r\n\t\tthis.grammar\t\t= this.rule.oneOrMore.ast;\r\n };\r\n\r\n // Register the grammar, providing a name and the default parse rule\r\n return m.registerGrammar(\"antla\", g, g.grammar);\r\n}", "function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}", "function buildRules( languageNode )\n{\n\tvar contextList, contextNode, sRegExp, rootNode;\t\n\tvar rulePropList, rulePropNode, rulePropNodeAttributes, ruleList, ruleNode;\n\n\trootNode = languageNode.selectSingleNode(\"/*\");\n\t\n\t// first building keyword regexp\n\tbuildKeywordRegExp( languageNode );\t\n\t\n\tcontextList = languageNode.selectNodes(\"contexts/context\");\n\t// create regular expressions for context\n\tfor (contextNode = contextList.nextNode(); contextNode != null; contextNode = contextList.nextNode())\n\t{\n\t\tsRegExp = buildRuleRegExp( languageNode, contextNode );\n\t\t// add attribute\n\t\tcontextNode.setAttribute( \"regexp\", sRegExp );\t\n\t}\n}", "cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }", "_generate(ast) {}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}", "rulesLoad(filename) {\n var fp = new File(filename, \"r\");\n if(!fp.open)\n error(\"fatal\", \"Unable to open grammar file \\\"\" + filename + \"\\\" for reading.\", \"SimpleGrammar.rulesLoad\");\n var tmp = fp.read();\n tmp = tmp.split(/\\n+/);\n var lines = [ ];\n while(tmp.length) {\n var line = tmp.shift().replace(/\\/\\/.*/g, \"\").trim();\n if(line.length)\n lines.push(line);\n }\n\n var nonterminal = /^\\[([^\\]]+)\\]/;\n var replacement = /^(([0-9]+):)?\\s*(.*)/;\n\n var currentNonterminal = null;\n var currentReplacements = [ ];\n\n for(var i = 0, match; i < lines.length; i++) {\n if(match = lines[i].match(nonterminal)) {\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n currentNonterminal = match[1];\n currentReplacements = [ ];\n\n } else if((match = lines[i].match(replacement)) && currentNonterminal !== null) {\n var weight = match[2] === undefined ? 1 : parseInt(match[2]);\n var str = this.textParse(match[3]);\n\n if(isNaN(weight) || weight < 1)\n error(\"fatal\", \"Invalid weight: \" + lines[i], \"SimpleGrammar.rulesLoad\");\n\n currentReplacements.push([str, weight]);\n }\n }\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n }", "function WordParser () {}", "function getGrammar() {\n if($ctrl.grammar === \"intellicheck\"){\n return new IntellicheckGrammar($ctrl.tvFields);\n }else if($ctrl.grammar === \"task\"){\n return new TaskGrammar();\n }else{\n return new DefaultGrammar();\n }\n }", "parseSubmission(s) {\n // define the parser (babel) and the abstract syntax tree generated\n // from parsing the submission\n const babel = require(\"@babel/core\");\n const ast = babel.parse(s.getSubmission);\n // define iterating variable\n let i = 0;\n // define empty arrays for storing individual strings and tokens.\n // The array of strings is used to generate the array of tokens\n //let myStrings : Array<string> = []\n let myTokens = [];\n // myOriginalText = original strings from submission\n // myTypes = the type of expression of each string (e.g. NumericLiteral)\n let myOriginalText = [];\n let myTypes = [];\n // the parser traverses through the abstract syntax tree and adds\n // any strings that it passes through to the array of strings\n babel.traverse(ast, {\n enter(path) {\n myTypes.push(path.node.type);\n myOriginalText.push(path.node.name);\n }\n });\n // each string in the array of strings is used to create a new\n // token, which is then added to the array of tokens\n for (i = 0; i < myOriginalText.length; i++) {\n myTokens.push(new Token_1.default(myOriginalText[i], myTypes[i]));\n }\n // create a TokenManager that holds the array of tokens\n let myTokenManager = new TokenManager_1.default(myTokens);\n // return the TokenManager which holds all of the tokens generated\n // by the strings extracted from the original submission\n return myTokenManager;\n // t1 = new Token(originaltext1: String, identifier1: String)\n // t2 = new Token(originaltext2: String, identifier2: String)\n // ...\n // tokenList = new List<Token>\n // tokenList.add(t1)\n // tokenList.add(t2)\n // ...\n // tmanager = new TokenManager(tokenList)\n // this.tokenizedSubmission = tmanager\n }", "function evaluator() {\n state.seg = segments['intro']; // starting from intro\n var block_ix = 0;\n\n // use global state to synchronize\n var handlers = {\n text : function(text) {\n var $text = $('<p></p>').appendTo($main);\n var timeoutid;\n var line_ix = 0;\n var char_ix = 0;\n state.status = 'printing';\n $triangle.hide();\n var text_printer = function() {\n var line = text.lines[line_ix];\n if (!line) {\n clearTimeout(timeoutid);\n $text.append('<br/>');\n // peek if next block is a branch block\n var next = get_next();\n if (next && next.type == 'branches') {\n next_block()\n } else {\n state.status = 'idle';\n $triangle.show();\n }\n return;\n }\n var interval = state.print_interval;\n if (char_ix < line.length) {\n var c = line[char_ix++];\n if (c == ' ') {\n c = '&nbsp;';\n }\n $text.append(c);\n } else {\n $text.append('<br/>');\n line_ix += 1;\n char_ix = 0;\n interval *= 6; // stop a little bit longer on new line\n }\n timeoutid = setTimeout(text_printer, interval);\n }\n timeoutid = setTimeout(text_printer, state.print_interval);\n },\n branches : function(branches) {\n var $ul = $('<ul class=\"branches\"></ul>').appendTo($main);\n state.status = 'branching'\n settings.cheated = false;\n var blur_cb = function(e) {\n settings.cheated = true;\n };\n $(window).on('blur', blur_cb);\n\n\n $.each(branches.cases, function(ix, branch){\n if (branch.pred == '?' || eval(branch.pred)) {\n var span = $('<span></span>').text(branch.text).data('branch_index', ix);\n $('<li></li>').append(span).appendTo($ul);\n }\n });\n $('li span', $ul).one('click', function(e){\n state.choice = parseInt( $(this).data('branch_index') );\n $(window).off('blur', blur_cb);\n clean_main();\n next_block();\n return false;\n });\n },\n code : function(code) {\n var control = new function() {\n var self = this;\n this.to_label = function(label) {\n self.next_label = label;\n };\n this.jump_to = function(segname) {\n self.next_seg = segname;\n }\n // extra functions\n this.clean_main = clean_main;\n this.reset = function() {\n settings = {}; // need to clean up the settings.\n constants.usual_print = 20; // on following playthrough, have faster printing\n self.jump_to('intro');\n };\n };\n eval(code.code);\n // handle the outcome\n if (control.next_seg) {\n state.seg = segments[control.next_seg];\n if (!state.seg) throw \"invalid segment jump:\" + control.next_seg;\n // jumping into label in another segment\n if (control.next_label) {\n var next = state.seg.labels[control.next_label]\n if (!next)\n throw \"invalid seg+label jump:\" + control.next_seg + \":\" + control.next_label;\n next_block(next);\n } else {\n next_block(state.seg[0]);\n }\n return;\n } else if (control.next_label) {\n var next = state.seg.labels[control.next_label];\n if (!next) throw \"invalid lable jump:\" + control.next_label;\n next_block(next);\n } else {\n next_block();\n }\n },\n label : function(label) {\n if (label.jump) {\n var next = state.seg.labels[label.name];\n if (!next) throw \"invalid jump label:\" + label.name;\n next_block(next);\n } else {\n next_block();\n }\n }\n\n };\n\n function clean_main() {\n $main.empty();\n }\n\n function handle_block() {\n console.log(\"doing block:\")\n console.log(state.block);\n handlers[state.block.type](state.block);\n }\n\n function get_next() {\n var block_in_seg = state.seg.indexOf(state.block);\n return state.seg[block_in_seg+1];\n }\n\n function next_block(block) {\n state.block = block || get_next();\n\n // necessary resets\n state.print_interval = constants.usual_print;\n handle_block();\n }\n\n function global_click_callback(e) {\n if (state.status == 'idle') {\n next_block();\n } else if (state.status == 'printing') {\n state.print_interval /= 5;\n }\n return false;\n }\n $(document).on('click', global_click_callback);\n\n // kick off\n state.block = state.seg[0];\n\n // !!!!!!!!!! DEBUG JUMP\n // state.seg = segments['puzzle'];\n // state.block = state.seg.labels['q1'];\n\n handle_block();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
USDA search results have a 'marketname' element that is comprised of distanceinmiles and actual market name, in one string
function split_distance_marketname(market) { market.distance = market.marketname.match(/(\d+.\d+)/g)[0]; // /(\d+)/g market.marketname = market.marketname.substr(market.distance.length + 1);// adjusted return market; }
[ "parseName() {\n return ionMarkDown_1.Imd.MarkDownToHTML(this.details.artist) + \" - \" + ionMarkDown_1.Imd.MarkDownToHTML(this.details.title);\n }", "function displayStateSearchData(item) {\n // variable that will contain the string with the results\n const itemStringArray = [];\n\n // Iterate over a jQuery object, executing a function for each matched element.\n $.each(item.data, function (itemkey, itemvalue) {\n var mystring = `${itemvalue.fullName}`;\n mystring = mystring.replace('&', 'and');\n let parkCode = itemvalue.parkCode;\n itemStringArray.push(`\n <div class=\"park\">\n <h1>${itemvalue.fullName}</h1>\n <div class=\"park-content\">\n <p>${itemvalue.description}</p>\n <h4>Weather:</h4><p> ${itemvalue.weatherInfo}</p>\n \n <div class=\"map\">\n <iframe title=\"map-${item.fullName}\" width=\"100%\" height=\"450\" frameborder=\"0\" style=\"border:0\"\n src=\"https://www.google.com/maps/embed/v1/place?q=${mystring},${itemvalue.states}&key=AIzaSyBdNRsY4zEYnRfcQ0_ZVVd370D7yuApzhI\" allowfullscreen>\n </iframe>\n </div>\n <div class=\"info\">\n <a class=\"park-alerts\" href=\"#\" data-name=\"${parkCode}\">\n Alert information <i class=\"fas fa-plus right\"></i></a>\n <button class=\"toggle-style toggle-alerts hidden\">Alert information <i class=\"fas fa-minus right\"></i></button>\n <div class=\"alert-results hidden\" aria-live=\"assertive\" data-name=\"${parkCode}\" hidden></div>\n </div>\n <div class=\"info\">\n <a class=\"camping\" href=\"#\" data-name=\"${parkCode}\">\n Campgrounds <i class=\"fas fa-plus right\"></i></a>\n <button class=\"toggle-style toggle-camps hidden\">Campgrounds <i class=\"fas fa-minus right\"></i></button>\n <div class=\"camp-results hidden\" aria-live=\"assertive\" data-name=\"${parkCode}\" hidden></div>\n </div>\n <a class=\"js-result-name\" href=\"${itemvalue.url}\" target=\"_blank\">\n ${itemvalue.fullName}</a>\n </div>\n </div>`\n );\n });\n renderResult(itemStringArray);\n}", "function getnearestweather(latinput, longinput)\n{\n // var forecastobj = {\n // BR: \"Mist\",\n // CL: \"Cloudy\",\n // CR: \"Drizzle\",\n // FA: \"Fair(Day)\",\n // FG: \"Fog\",\n // FN: \"Fair(Night)\",\n // FW: \"Fair & Warm\",\n // HG: \"Heavy Thundery Showers with Gusty Winds\",\n // HR: \"Heavy Rain\",\n // HS: \"Heavy Showers\",\n // HT: \"Heavy Thundery Showers\",\n // HZ: \"Hazy\",\n // LH: \"Slightly Hazy\",\n // LR: \"Light Rain\",\n // LS: \"Light Showers\",\n // OC: \"Overcast\",\n // PC: \"Partly Cloudy (Day)\",\n // PN: \"Partly Cloudy (Night)\",\n // PS: \"Passing Showers\",\n // RA: \"Moderate Rain\",\n // SH: \"Showers\",\n // SK: \"Strong Winds,Showers\",\n // SN: \"Snow\",\n // SR: \"Strong Winds, Rain\",\n // SS: \"Snow Showers\",\n // SU: \"Sunny\",\n // SW: \"Strong Winds\",\n // TL: \"Thundery Showers\",\n // WC: \"Windy,Cloudy\",\n // WD: \"Windy\",\n // WF: \"Windy,Fair\",\n // WR: \"Windy,Rain\",\n // WS: \"Windy, Showers\"\n // };\n\n var forecastobj = {\n BR: \"Not Raining\",\n CL: \"Not Raining\",\n CR: \"Raining\",\n FA: \"Not Raining\",\n FG: \"Not Raining\",\n FN: \"Not Raining\",\n FW: \"Not Raining\",\n HG: \"Raining\",\n HR: \"Raining\",\n HS: \"Raining\",\n HT: \"Raining\",\n HZ: \"Not Raining\",\n LH: \"Not Raining\",\n LR: \"Raining\",\n LS: \"Raining\",\n OC: \"Not Raining\",\n PC: \"Not Raining\",\n PN: \"Not Raining\",\n PS: \"Raining\",\n RA: \"Raining\",\n SH: \"Raining\",\n SK: \"Raining\",\n SN: \"Not Raining\",\n SR: \"Raining\",\n SS: \"Not Raining\",\n SU: \"Not Raining\",\n SW: \"Not Raining\",\n TL: \"Raining\",\n WC: \"Not Raining\",\n WD: \"Not Raining\",\n WF: \"Not Raining\",\n WR: \"Raining\",\n WS: \"Raining\"\n };\n\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n var parser1 = new xml2js.Parser({explicitArray : true, attrkey : 'Child'});\n\n http.get('http://api.nea.gov.sg/api/WebAPI/?dataset=2hr_nowcast&keyref=781CF461BB6606ADC767F3B357E848ED3A27067168AB8007', function(res)\n {\n var response_data = '';\n res.setEncoding('utf8');\n res.on('data', function(chunk)\n {\n response_data += chunk;\n });\n \n res.on('end', function() \n {\n parser1.parseString(response_data, function(err, result) \n {\n if (err) \n {\n console.log('Got error: ' + err.message);\n }\n else \n {\n eyes.inspect(result);\n \n //convert into JSON object\n console.log('Converting to JSON object.');\n var jsonobject2 = JSON.parse(JSON.stringify(result));\n console.log(util.inspect(jsonobject2, false, null));\n\n //read and traverse JSON object\n var nearestdistance1 = 0;\n var showdistanceformat1;\n var showdistance1;\n \n var showlat1;\n var showlong1;\n var nearestForeCast;\n var nearestForeCastName;\n\n console.log(\"name 1: \" + jsonobject2.channel.title);\n console.log(\"name 2: \" + jsonobject2.channel.source);\n console.log(\"date3 : \" +jsonobject2.channel.item[0].forecastIssue[0].Child.date);\n console.log(\"length \"+jsonobject2.channel.item[0].weatherForecast[0].area.length)\n\n for (var i = 0; i < jsonobject2.channel.item[0].weatherForecast[0].area.length; ++i)\n {\n showlat1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lat;\n showlong1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lon;\n showdistance1 = calculatedistance(showlat1, showlong1, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n showdistanceformat1 = Math.round(showdistance1*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat1);\n\n var tempdistance1 = showdistanceformat1;\n if (i == 0)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n if (nearestdistance1 > tempdistance1)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n }\n console.log(\"Distance to Nearest Town : \" + nearestdistance1);\n console.log(\"Forecast in Nearest Town : \" + nearestForeCast);\n console.log(\"Nearest Town : \" + nearestForeCastName);\n\n var forecast = forecastobj[nearestForeCast];\n console.log(\"Forecast in Current Location : \" + forecast);\n }\n });\n });\n\n res.on('error', function(err) \n {\n console.log('Got error: ' + err.message);\n });\n });\n}", "function displayParkSearchData(item) {\n const campgroundStringArray = [];\n if (item.data.length == 0) {\n campgroundStringArray.push(`<div class=\"expanded-info\"><p class=\"no-info\">This park does not have any campgrounds.</p></div>`);\n } else {\n $.each(item.data, function (itemkey, itemvalue) {\n let code = itemvalue.parkCode;\n let water = [];\n let toilets = [];\n let showers = [];\n let reservationUrl = itemvalue.reservationUrl ?? 'google.com';\n console.log(itemvalue);\n\n // create array for result for each amenity\n if (itemvalue.amenities && itemvalue.amenities.potableWater) {\n for (let i = 0; i < itemvalue.amenities.potableWater.length; i++) {\n water.push(itemvalue.amenities.potableWater[i]);\n };\n }\n\n let resUrl;\n\n // create array for result for each amenity\n // for (let i = 0; i < itemvalue.amenities.potableWater.length; i++) {\n // water.push(itemvalue.amenities.potableWater[i]);\n // };\n\n for (let i = 0; i < itemvalue.amenities.toilets.length; i++) {\n toilets.push(itemvalue.amenities.toilets[i]);\n };\n\n for (let i = 0; i < itemvalue.amenities.showers.length; i++) {\n showers.push(itemvalue.amenities.showers[i]);\n };\n\n campgroundStringArray.push(`\n <h3>${itemvalue.name}</h3>\n <div class=\"expanded-info\">\n <p>${itemvalue.description}</p>\n <p>Potable Water: ${water}<br>\n Toilets: ${toilets}<br>\n Showers: ${showers}<br>\n Campsites:<br>\n Total sites: ${itemvalue.campsites.totalSites}<br>\n Electrical Hookups: ${itemvalue.campsites.electricalHookups}<br>\n Group sites: ${itemvalue.campsites.group}<br>\n RV only sites: ${itemvalue.campsites.rvOnly}<br>\n Tent only sites: ${itemvalue.campsites.tentOnly}</p>\n <br>\n <br>\n <a href=${itemvalue.reservationUrl} target=\"_blank\">Make a reservation at: ${itemvalue.reservationUrl}</a>\n </div>`);\n });\n };\n\n renderParkResult(campgroundStringArray);\n}", "function getTreasury(object)\n{\n var distance = object.distance;\n var treasury = Math.trunc(distance/500);\n return treasury;\n}", "function getFormattedSearchResults(searchGeometry, type) {\n var features;\n if (type == 'stones') {\n // Only stones can be filtered by age \n var queryFilter = constructFilter();\n features = map.queryRenderedFeatures(searchGeometry, {layers: [type], filter: queryFilter});\n }\n else {\n features = map.queryRenderedFeatures(searchGeometry, {layers: [type]});\n }\n\n // Creates string representing results \n var searchResults = \"\";\n searchResults += \"<b>\" + type.charAt(0).toUpperCase() + type.slice(1) + \":</b></br>\";\n for (var i = 0; i < features.length; i++) {\n var feature = features[i];\n var name = feature.properties.name;\n // Because of how MapBox treats features, some features may be \n // be split up and returned multiple times in the query \n if (!searchResults.includes(name)) {\n searchResults += \"<li data-type=\" + type + \" onclick=displayInfo(this)>\" + name + \"</li>\";\n }\n }\n if (features.length == 0) {\n searchResults += \"No results found</br>\"\n }\n\n return searchResults;\n}", "displayTopEightMatchedRespondents() {\n console.log(\"\\nTop 8 matches- by matching scores:\");\n console.log(\"===================================\\n\");\n\n for (let i = 0; i < 8; i++) {\n const curr = this.results[this.results.length - 1 - i];\n console.log(i);\n console.log(\n `Name: ${curr.name.slice(0, 1).toUpperCase()}${curr.name.slice(\n 1\n )}`\n );\n console.log(\n `Distance to closest available city: ${curr.closestAvailableCity.distance}km`\n );\n console.log(`Matching Score: ${curr.score}`);\n console.log(\"-------------------------------\");\n }\n }", "function getPlaceName(lat,lon) {\n var api_call2 = \"https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?lat=\" + \n lat + \"&lon=\" + lon + \"&appid=0befa5edd94dc4137482fab569899a79&units=metric\";\n \n // parse data and append to name placeholder\n $.getJSON(api_call2, function(data2) {\n \n $('#name').html(data2.name);\n });\n }", "function single_keyword_special_prices () {\n //The given keyword is 2 chars long. Special prices must be applied and remove discounts;\n if(universalKeyword.length == 2){\n $.each(dependencies.tldList, function (key,value) {\n if('p' in value.s && typeof value.s.p.t[dependencies.t_id] != 'undefined'){\n price = value.s.p.t[dependencies.t_id] ;\n target = $('[data-tld=\"' + key + '\"]').find('.price, .price-container');\n target.removeClass('discount');\n target.find('.regular-price .vat').attr({'data-price':price}).text(convertPrices(price));\n target.find('.reduced-price').remove();\n }\n });\n }\n}", "function webMD(ailments, meds) {\n var output = []\n\n for (var i = 0; i < meds.length; i++) {\n var j = 0;\n while (meds[i].treatableSymptoms.includes(ailments[j])) {\n j++;\n if (j >= ailments.length) {\n output.push(meds[i].name);\n }\n }\n }\n return output\n}", "function wikidata_user_nearby_city(user_lat, user_lon, fk_wikidata){\n\tvar placeInfoList = null;\n\tvar query_str = `\n\t\t\t\t\tPREFIX wd: <http://www.wikidata.org/entity/>\n\t\t\t\t\tPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\t\t\t\t\tPREFIX geo: <http://www.opengis.net/ont/geosparql#>\n\t\t\t\t\tPREFIX wikibase: <http://wikiba.se/ontology#>\n\t\t\t\t\tPREFIX wdt: <http://www.wikidata.org/prop/direct/>\n\t\t\t\t\tPREFIX bd: <http://www.bigdata.com/rdf#>\n\n\t\t\t\t\tSELECT distinct ?place ?placeLabel ?distance ?location \n\t\t\t\t\tWHERE {\n\t\t\t\t\t# geospatial queries\n\t\t\t\t\tSERVICE wikibase:around {\n\t\t\t\t\t# get the coordinates of a place\n\t\t\t\t\t?place wdt:P625 ?location .\n\t\t\t\t\t# create a buffer around (-122.4784360859997 37.81826788900048)\n\t\t\t\t\tbd:serviceParam wikibase:center \"Point(` + user_lon.toString()+ ` ` + user_lat.toString()+ `)\"^^geo:wktLiteral .\n\t\t\t\t\t# buffer radius 2km\n\t\t\t\t\tbd:serviceParam wikibase:radius \"10\" .\n\t\t\t\t\tbd:serviceParam wikibase:distance ?distance .\n\t\t\t\t\t}\n\t\t\t\t\t# retrieve the English label\n\t\t\t\t\tSERVICE wikibase:label {bd:serviceParam wikibase:language \"en\". ?place rdfs:label ?placeLabel .}\n\t\t\t\t\t?place wdt:P31 wd:Q515.\n\t\t\t\t\t#?placeFlatType wdt:P279* wd:Q2221906.\n\n\t\t\t\t\t# show results ordered by distance\n\t\t\t\t\t} ORDER BY ?distance\n\t\t\t\t\t\t`;\n\tconsole.log(query_str);\n\n\tconst P_ENDPOINT = \"https://query.wikidata.org/bigdata/namespace/wdq/sparql\";\n\trequest({\n\t\t\tmethod: \"GET\",\n\t\t\turl: P_ENDPOINT,\n\t\t\theaders: {\n\t\t\t\taccept: 'application/sparql-results+json'\n\t\t\t},\n\t\t\tqs: {\n\t\t\t\tquery: query_str\n\t\t\t}\n\t\t}, (e_req, d_res, s_body) => {\n\t\t\tconsole.log(d_res.headers['content-type']);\n\t\t\t// console.log(e_req);\n\t\t\tif(e_req) {\n\t\t\t\tconsole.log(e_req);\n\t\t\t} else {\n\t\t\t\ttry{\n\t\t\t\t\tvar h_json = JSON.parse(s_body);\n\t\t\t\t\tvar a_bindings = h_json.results.bindings;\n\t\t\t\t\tconsole.log(a_bindings);\n\t\t\t\t\tif(a_bindings.length > 0){\n\t\t\t\t\t\tvar sparqlItem = a_bindings[0];\n\t\t\t\t\t\tvar url = sparqlItem[\"place\"][\"value\"];\n\t\t\t\t\t\tvar label = sparqlItem[\"placeLabel\"][\"value\"];\n\t\t\t\t\t\tvar coord = sparqlItem[\"location\"][\"value\"].replace(\"Point(\", \"\").replace(\")\", \"\").split(\" \");\n\t\t\t\t\t\tvar place_lat = parseFloat(coord[1]);\n\t\t\t\t\t\tvar place_lon = parseFloat(coord[0]);\n\n\t\t\t\t\t\tplaceInfoList = {};\n\t\t\t\t\t\tplaceInfoList[url] = {};\n\t\t\t\t\t\tplaceInfoList[url][\"label\"] = label;\n\t\t\t\t\t\tplaceInfoList[url][\"lat\"] = place_lat;\n\t\t\t\t\t\tplaceInfoList[url][\"long\"] = place_lon;\n\t\t\t\t\t\tplaceInfoList[url][\"r\"] = 1000;\n\n\t\t\t\t\t\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\tplaceInfoList = null;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}catch(jsonParseError){\n\t\t\t\t\tconsole.log(jsonParseError);\n\t\t\t\t\t// fk_geo(null);\n\t\t\t\t\tplaceInfoList = null;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\tfk_wikidata(placeInfoList);\n\t \n\t});\n}", "function employeesFromCompanyPage(html) {\n if (isSalesNavigator()) {\n html = $(html).find(\"code\").last().html();\n json = html.replace(\"<!--\", \"\").replace(\"-->\", \"\");\n return JSON.parse(json)[\"account\"][\"fmtSize\"];\n } else if(isRecruiter()) {\n // TO DO\n return \"\";\n }\n else {\n if (typeof $(html).find(\".company-size p\").text() != \"undefined\" && $(html).find(\".company-size p\").text() != \"\") {\n return $(html).find(\".company-size p\").text();\n }\n else {\n html = $(html).find(\"code\").last().html()\n json = html.replace(\"<!--\", \"\").replace(\"-->\", \"\");\n return JSON.parse(json)[\"size\"];\n }\n }\n}", "getMarketInfo(startingCurrency, endingCurrency) {\n return axios.get(`/marketinfo/${pair(startingCurrency, endingCurrency)}`,\n {\n responseType: \"json\"\n });\n }", "getDistance() {\n const {origin, destination} = this.props;\n if (app.google && origin && destination) {\n const geometry = app.google.maps.geometry.spherical;\n const meters = geometry.computeDistanceBetween(origin, destination);\n const units = unitsMap[this.state.units];\n const distance = meters * units.value;\n const s = distance === 1 ? '' : 's';\n return `${distance.toFixed(3)} ${units.name}${s}`;\n }\n }", "function buildDBPediaQuery (name) {\n\t\tindex = name.indexOf(\"City\");\n\t\tvar sparql;\n\t\tif (index==-1) {//it is a county\n\t\t index = name.indexOf(\"County\");\n\t\t\tvar county = name.substring(index+7); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?map ?wiki \" + //+?area \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Settlement> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Counties_of_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/web> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/mapImage> ?map . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t //\" ?loc <http://dbpedia.org/property/areaKm> ?area . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + county + \"\\\" )) . \" +\n\t\t\t\t\t \" } \";\n\t\t}\n\t\telse {// it is a city\n\t\t\tvar city = name.substring(0,index); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?wiki \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Place> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Cities_in_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/website> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + city + \"\\\" )) . \" +\n\t\t\t\t\t \" } \" ;\n\t\t}\n\t\treturn sparql;\n\t}", "function WCdist(myPos){\n //var WCinfo = new google.maps.InfoWindow({position:myPos, map:map});\n var WCinfo = windows[\"me\"];\n if(typeof WCpos[\"Waldo\"] != 'undefined'){\n var cont = WCinfo.getContent();\n var waldist = google.maps.geometry.spherical.computeDistanceBetween(\n myPos,WCpos[\"Waldo\"],EARTH_RAD); \n WCinfo.setContent(cont.concat(\"You are \",waldist,\" miles from Waldo!<br>\"));\n }\n if(typeof WCpos[\"Carmen Sandiego\"] != 'undefined'){\n var cardist = google.maps.geometry.spherical.computeDistanceBetween(\n myPos,WCpos[\"Carmen Sandiego\"],EARTH_RAD);\n var cont = WCinfo.getContent();\n WCinfo.setContent(\n cont.concat(\"You are \",cardist,\" miles from Carmen Sandiego!<br>\"));\n }\n}", "function getnearestURACarpark(latinput, longinput)\n{\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n\n var token = \"6hf2NfWWja4j12bn3H4z8g62287rha485Fu7ff1F8gVC0R-AbBC-38YT3c856fV3HCZmet2j54+gbCP40u3@Q184ccRQGzcbXefE\";\n var options = {\n url: 'https://www.ura.gov.sg/uraDataService/invokeUraDS?service=Car_Park_Availability',\n headers: {\n 'AccessKey' : '0d5cce33-3002-451b-8f53-31e8c4c54477',\n 'Token' : token\n }\n };\n\n function callback(error, response, body) \n {\n var cv1 = new SVY21();\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n var nearestdistance2 = 0;\n var nearestURAcarparklot;\n var nearestURAcarparkcoordinates;\n var nearestURAcarparklotavailability;\n \n // var currentdate = new Date();\n // var httpdate = new Date(response.headers['date']);\n // var httpgetday = httpdate.getDate();\n // console.log(\"HTTP Respond Date : \" +httpdate);\n // console.log(\"HTTP Get Date : \" +httpgetday);\n // console.log(\"Current Date : \" +currentdate); \n\n if (!error && response.statusCode == 200)\n {\n //Parse data\n var jsonobject3 = JSON.parse(body);\n console.log(\"parse data from URA\");\n console.log(util.inspect(body, false, null));\n \n for (var i = 0; i < jsonobject3.Result.length; ++i)\n {\n //Find car park lot availability for cars\n if (jsonobject3.Result[i].lotType == \"C\")\n {\n console.log(\"URA Carpark No : \" + jsonobject3.Result[i].carparkNo);\n console.log(\"URA Carpark Lot Type : \" + jsonobject3.Result[i].lotType);\n console.log(\"URA Carpark Lot Availability : \" + jsonobject3.Result[i].lotsAvailable);\n console.log(\"URA Carpark Coordinates : \" + jsonobject3.Result[i].geometries[0].coordinates);\n var uracoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n var uracoordinatesresult = uracoordinates.split(\",\");\n console.log(\"URA Carpark Coordinates Latitude (SVY21) : \" + uracoordinatesresult[0]);\n console.log(\"URA Carpark Coordinates Longitude (SVY21) : \" + uracoordinatesresult[1]);\n //Convert SVY21 to Lat/Long\n var getlatlong2 = cv1.computeLatLon(uracoordinatesresult[0], uracoordinatesresult[1]);\n var showlat2 = getlatlong2[0];\n var showlong2 = getlatlong2[1];\n console.log(\"URA Carpark Latitude : \" + showlat2);\n console.log(\"URA Carpark Longitude : \" + showlong2);\n //Calculate distance between URA Carpark and user current location\n var showdistance2 = calculatedistance(showlat2, showlong2, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n var showdistanceformat2 = Math.round(showdistance2*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat2);\n\n //Find nearest URA Carpark\n var tempdistance2 = showdistanceformat2;\n if (i == 0)\n {\n nearestdistance2 = tempdistance2;\n nearestURAcarparklot= jsonobject3.Result[i].carparkNo;\n nearestURAcarparklotavailability= jsonobject3.Result[i].lotsAvailable;\n nearestURAcarparkcoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n }\n if (nearestdistance2 > tempdistance2)\n {\n nearestdistance2 = tempdistance2;\n nearestURAcarparklot= jsonobject3.Result[i].carparkNo;\n nearestURAcarparklotavailability= jsonobject3.Result[i].lotsAvailable;\n nearestURAcarparkcoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n }\n\n }\n }\n\n console.log(\"Nearest URA Carpark (Distance) : \" + nearestdistance2);\n console.log(\"Nearest URA Carpark (Lot No) : \" + nearestURAcarparklot);\n console.log(\"Nearest URA Carpark (Lot Availability) : \" + nearestURAcarparklotavailability);\n }\n }\n\n request(options, callback);\n\n}", "getDataString( unixtime, fromPosition ) {\n\n\t\t// home planet\n\t\tif ( this === Viewer.getViewer().homePlanet ) {\n\n\t\t\treturn this.name;\n\n\t\t}\n\n\t\tthis.updatePositionAndRotation( unixtime );\n\t\ttmp.subVectors( this.posGroup.position, fromPosition );\n\n\t\t// We have to undo the permutation of coordinates we did above\n\t\t// for mesh position, but I don't quite understand why the signs\n\t\t// are as they are.\n\t\tlet xeq = tmp.x;\n\t\tlet yeq = - cosd( j2000obliquity ) * tmp.z - sind( j2000obliquity ) * tmp.y;\n\t\tlet zeq = - sind( j2000obliquity ) * tmp.z + cosd( j2000obliquity ) * tmp.y;\n\t\ttmp.y = yeq;\n\t\ttmp.z = zeq;\n\n\t\tlet distance = tmp.length();\n\t\tlet ra = acosd( xeq / Math.sqrt( xeq * xeq + yeq * yeq ) );\n\t\tif ( yeq < 0 ) ra *= - 1;\n\t\tif ( ra < 0 ) ra += 360;\n\t\tlet decl = 90 - acosd( zeq / tmp.length() );\n\n\n\t\treturn this.name + '; RA: ' + roundTo2( ra ) + '&deg;, D: ' + roundTo2( decl ) +\n\t\t\t'&deg;, dist. ' + roundTo2( distance / unit ) + ' AU';\n\n\t}", "function getnearestURACarparkInformation(carparknoinput)\n{\n //var geturacarparkfromuser = \"K0087\";\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n //To get new token everyday\n var token = \"6hf2NfWWja4j12bn3H4z8g62287rha485Fu7ff1F8gVC0R-AbBC-38YT3c856fV3HCZmet2j54+gbCP40u3@Q184ccRQGzcbXefE\";\n var options = {\n url: 'https://www.ura.gov.sg/uraDataService/invokeUraDS?service=Car_Park_Details',\n headers: {\n 'AccessKey' : '0d5cce33-3002-451b-8f53-31e8c4c54477',\n 'Token' : token\n }\n };\n\n function callback(error, response, body) \n {\n var cv2 = new SVY21();\n var geturacarparkfromuser = carparknoinput;\n \n if (!error && response.statusCode == 200)\n {\n //Parse data\n var jsonobject4 = JSON.parse(body);\n console.log(\"parse data from URA carpark\");\n //console.log(util.inspect(body, false, null));\n\n for (var i = 0; i < jsonobject4.Result.length; ++i)\n {\n //Find car park details for cars\n if (jsonobject4.Result[i].vehCat == \"Car\" && jsonobject4.Result[i].weekdayMin == \"30 mins\")\n {\n //Match car park no from nearby URA carpark and get car park address\n if (jsonobject4.Result[i].ppCode == geturacarparkfromuser)\n {\n console.log(\"URA Carpark Address : \" + jsonobject4.Result[i].ppName);\n var showuracarparkaddress = jsonobject4.Result[i].ppName; \n }\n }\n }\n }\n }\n request(options, callback);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a refund address to altcoin order
function add_refund() { var refund_address = document.getElementById("bnomics-refund-input").value; var flypObj = new Object(); flypObj.uuid = flyp_uuid; flypObj.address = refund_address; var flypObjString= JSON.stringify(flypObj); var refund = new XMLHttpRequest(); refund.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { address_present = true update_altcoin_status('refunded'); info_order(flyp_uuid); } }; refund.open("POST", "https://flyp.me/api/v1/order/addrefund", true); refund.setRequestHeader("Content-type", "application/json"); refund.send(flypObjString); }
[ "function refundOrder(order, resolve, reject){\n if(order === undefined) resolve();\n\n let id = order['id'];\n\n let totalAmount = parseFloat(order['total_price']);\n let amountRefunded = 0;\n\n console.log(order['email']);\n\n const refunds = order['refunds'];\n refunds.forEach((refund)=>{\n let transactions = refund['transactions'];\n\n transactions.forEach((transaction)=>{\n amountRefunded += parseFloat(transaction['amount']);\n });\n });\n\n let amountLeft = totalAmount - amountRefunded;\n\n console.log(\"amounts : \" , amountLeft, totalAmount, amountRefunded);\n if(amountLeft <= 0){\n resolve();\n }else {\n console.log(\"Refunding : \" , amountLeft);\n request({\n uri: `${domain}/admin/orders/${id}/refunds.json`,\n method: \"POST\",\n json: {\n refund: {\n note: \"Cancelling all test orders\",\n transactions: [\n {\n amount: amountLeft,\n kind: \"refund\",\n gateway: \"store-credit\"\n }\n ],\n }\n },\n auth: {\n 'user': conf.username,\n 'pass': conf.password\n }\n }, (err) => {\n if (err) {\n console.log(JSON.stringify(err, null, 2));\n reject();\n }\n\n console.log(\"Refunded Order \", id);\n resolve();\n });\n }\n}", "async function useLockingForRefund(contract, targetAddress, amount) {\n return await contract.functions\n .useForRefund(wallet.alice.publicKey, new SignatureTemplate(wallet.alice.privateKey), wallet.bob.publicKey, new SignatureTemplate(wallet.bob.privateKey))\n .to(targetAddress, amount)\n .withFeePerByte(1)\n .send()\n}", "function createOrderAddress(productId, quantity){\n var inqPromise = inquirerCreateAddress();\n inqPromise.then(function(inqRes){\n var addressObj = {\n address : inqRes.addressLine,\n city : inqRes.myCity,\n state : inqRes.myState,\n zip : inqRes.myZip,\n }\n custQueryHelper.createOrderAndAddressTransaction(connection,productId, quantity, addressObj, currentCustomer);\n });\n}", "function place_pizza_order(rid,tray,price) {\n var args = {\n rid: rid.toString(),\n em: 'detox27@gmail.com',\n tray: tray,\n //tip: '6.66',\n tip: (parseFloat(price,10)*.2).toFixed(2).toString(),\n first_name: 'Slammin',\n last_name: 'Sammy',\n phone: '6666666666',\n zip: '10036',\n addr: '1500 Broadway',\n city: 'New York',\n state: 'NY',\n card_name: 'Slammin Sammy',\n card_number: '4111111111111111',\n card_cvc: '123',\n card_expiry: '06/2006',\n card_bill_addr: '31 High Street',\n card_bill_city: 'New Brunswick',\n card_bill_state: 'NJ',\n card_bill_zip: '08901',\n card_bill_phone: '5555555555',\n delivery_date: 'ASAP'\n };\n ordrin_api.order_guest(args, function(error,data){\n if(error){\n console.log(error);\n }\n else{\n console.log('Order Successful');\n }\n\n });\n\n}", "function getRefund() {\n const tempVal = Math.min(credits - taxBill, 1000);\n const refund = tempVal + withholdings;\n return refund;\n }", "function AddPartsInContract(obj, multi, address, callback) {\n var json = {};\n multi.addtasks.sendTransaction(obj, {\n from: address,\n gas: 3000000\n }, function(err, contract) {\n json.error = err;\n json.success = contract;\n callback(null, json);\n });\n}", "addRekey(reKeyTo, feePerByte = 0) {\n if (reKeyTo !== undefined) {\n this.reKeyTo = address.decodeAddress(reKeyTo);\n }\n if (feePerByte !== 0) {\n this.fee +=\n (ALGORAND_TRANSACTION_REKEY_LABEL_LENGTH +\n ALGORAND_TRANSACTION_ADDRESS_LENGTH) *\n feePerByte;\n }\n }", "unbond({ oracleAddress, endpoint, amount, from, gas }) {\n endpoint = fromAscii(endpoint);\n amount = toBN(amount);\n\n return this.contract.unbond(\n oracleAddress,\n endpoint,\n amount,\n {\n 'from': from,\n 'gas': gas\n }\n );\n }", "function addAddressToRoute(){\n\tvar place = autocomplete.getPlace();\n\n\tif(place === undefined) { //Could not find a place associated with provided address.\n\t\t//TODO replace this with something less terrible\n\t\talert(\"Unable to locate provided address\");\n\t\treturn;\n\t}\n\n\tis_new_place = true;\n\tfor(var i = 0; i < route[\"places\"].length; i++){\n\t\tif (route.places[i].place_id == place.place_id) { \n\t\t\tis_new_place = false; \n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (is_new_place){\n\t\troute.places.push(place);\n updateWeather(place.geometry.location.lat(), place.geometry.location.lng());\n\t}\n\n\tupdateRoute();\n\n // Clear the input field.\n $(\"#autocomplete\").val(\"\");\n}", "function transferOwnership(res,ToAddress,FromAddress,PrivateKey){\r\n web3.eth.defaultAccount = FromAddress;\r\n var count = web3.eth.getTransactionCount(web3.eth.defaultAccount);\r\n var data = contract.transferOwnership.getData(ToAddress);\r\n var gasPrice = web3.eth.gasPrice;\r\n var gasLimit = 300000;\r\n\r\n var rawTransaction = {\r\n \"from\": FromAddress,\r\n \"nonce\": web3.toHex(count),\r\n \"gasPrice\": web3.toHex(gasPrice),\r\n \"gasLimit\": web3.toHex(gasLimit),\r\n \"to\": contractAddress,\r\n \"data\": data,\r\n };\r\n\r\n var privKey = new Buffer(PrivateKey, 'hex');\r\n var tx = new Tx(rawTransaction);\r\n\r\n tx.sign(privKey);\r\n var serializedTx = tx.serialize();\r\n\r\n web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {\r\n if (!err){\r\n res.contentType('application/json');\r\n res.end(JSON.stringify(hash));\r\n }\r\n });\r\n}", "function fulfillOrder(order) {\n\tfor (var i = 0; i < order.items.length; i++) {\n\t\tif (order.items[i].isBase) {\n\t\t\tvar item = baseItems.get(order.items[i].type, order.items[i].name);\n\t\t} else {\n\t\t\tvar item = optionalItems.get(order.items[i].type, order.items[i].name);\n\t\t}\n\t\tif (item.stock < 1) {\n\t\t\tthrow \"ERROR: Trying to fullfill an order without stock\";\n\t\t}\n\t\titem.stock--;\n\t}\n\tvar id = order.setId();\n\torders.unshift(order);\n\tsyncToStorage();\n\treturn id;\n}", "async setBillingAddress(address) {\n const response = await api.shopperBaskets.updateBillingAddressForBasket({\n body: address,\n parameters: {basketId: basket.basketId, shipmentId: 'me'}\n })\n\n setBasket(response)\n }", "function insertSampleAddresses(){\n\tlet flag = 'addressBookFirstUse';\n\tif (!settings.get(flag, true)) return;\n\tconst sampleData = config.addressBookSampleEntries;\n\tif(sampleData && Array.isArray(sampleData)){\n\t\tsampleData.forEach((item) => {\n\t\t\tlet ahash = wsutil.b2sSum(item.address + item.paymentId);\n\t\t\tlet aqr = wsutil.genQrDataUrl(item.address);\n\t\t\titem.qrCode = aqr;\n\t\t\tabook.set(ahash, item);\n\t\t});\n\t}\n\tsettings.set(flag, false);\n\tinitAddressCompletion();\n}", "function determineAddress(productId, quantity){\n var addressId = currentCustomer.id_addresses;\n connection.query(\"SELECT * FROM `Addresses` WHERE id = ?\", addressId, function(addrErr, addrResp){\n if(addrErr) throw addrErr;\n var addr = addrResp[0];\n inquirer.prompt([\n {\n type : \"confirm\",\n message : \"Use default billing and shipping address? (\" + addr.address + \" \" + addr.city + \" \" + addr.state + \" \" + addr.zip + \")\",\n default : true,\n name : \"confirm\",\n }\n ]).then(function(inqResp){\n if(inqResp.confirm){\n //query helper handles order\n custQueryHelper.placeMyOrderTransaction(connection, productId, quantity, addressId, currentCustomer);\n } else {\n //will use query helper eventually\n createOrderAddress(productId, quantity);\n }\n });\n });\n}", "function generateNewAddress(){\n \n server.accounts()\n .accountId(source.publicKey())\n .call()\n .then(({ sequence }) => {\n const account = new StellarSdk.Account(source.publicKey(), sequence)\n const transaction = new StellarSdk.TransactionBuilder(account, {\n fee: StellarSdk.BASE_FEE\n })\n .addOperation(StellarSdk.Operation.createAccount({\n destination: destination.publicKey(),\n startingBalance: '2'\n }))\n .setTimeout(30)\n .build()\n transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))\n return server.submitTransaction(transaction)\n })\n .then(results => {\n console.log('Transaction', results._links.transaction.href)\n console.log('New Keypair', destination.publicKey(), destination.secret())\n })\n\n }", "async function main(to, from) {\n\n const list = await listunspent();\n\n const addresses = new Set();\n const utxosSortedByAddress = list.reduce( (accumulator, utxo) => {\n const address = utxo.address;\n addresses.add(address);\n if (!accumulator[address]) {\n accumulator[address] = [];\n }\n accumulator[address].push(utxo);\n return accumulator;\n }, {});\n\n const addressArray = Array.from(addresses);\n\n if (addressArray.length === 0) {\n console.log('No UTXOs found with 10 or more confirmations.');\n process.exit(0);\n }\n\n let sendFrom = from ? from : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'sendFrom',\n message: `Select an address to migrate:`,\n choices: addressArray,\n default: addressArray[0]\n },\n ]);\n sendFrom = response.sendFrom;\n }\n const utxoArray = utxosSortedByAddress[sendFrom];\n\n let sendTo = to ? to : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n name: 'sendTo',\n message: `Enter address to send to:`\n },\n ]);\n sendTo = response.sendTo;\n if (!sendTo) {\n console.log('Send To address cannot be blank.');\n process.exit(0);\n }\n }\n\n if (!from || !to) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'list',\n name: 'confirm',\n message: `Migrate ${utxoArray.length} UTXOs from ${sendFrom} to ${sendTo}?`,\n choices: ['Continue', 'Cancel']\n },\n ]);\n if (confirm === 'Cancel') {\n console.log('Aborted by user.');\n process.exit(0);\n }\n }\n\n utxoArray.forEach( async (utxo) => {\n const amount = Math.round(utxo.amount * 100000000);\n const minUtxoSize = argv.minUtxoSize ? argv.minUtxoSize : 100000000;\n if (amount > minUtxoSize) {\n const fee = 10000;\n const sendAmount = (amount - fee) / 100000000;\n const send = {};\n send[sendTo] = sendAmount;\n console.log(`Creating txn to send ${sendAmount} from ${sendFrom} to ${sendTo}`);\n let rawTxn = await createrawtransaction([utxo], send).catch((err) => {\n console.log('createrawtransaction Error.', err);\n console.log('Error creating raw transaction with utxo:', utxo);\n process.exit(0);\n });\n const signedTxn = await signrawtransaction(rawTxn).catch((err) => {\n console.log('signrawtransaction',err);\n console.log('Error signing raw transaction:', rawTxn);\n process.exit(0);\n });\n const txid = await sendrawtransaction(signedTxn.hex).catch((err) => {\n console.log('sendrawtransaction', err);\n console.log('Error sending signed transaction hex:', signedTxn);\n process.exit(0);\n });\n console.log(`Sent ${utxo.amount} to ${sendTo}. txid: ${txid}`);\n }\n });\n\n}", "async setShippingAddress(address) {\n const response = await api.shopperBaskets.updateShippingAddressForShipment({\n body: address,\n parameters: {\n basketId: basket.basketId,\n shipmentId: 'me',\n useAsBilling: !basket.billingAddress\n }\n })\n\n setBasket(response)\n }", "async balanceOf(address) {\n await this.getContract()\n return await this.contract.methods.balanceOf(address).call()\n }", "function totalUnspents(addressToGet, network, callback) {\n getUnspents(addressToGet.toString(), network, function(err, address, unspents) {\n totalReturn = 0.0;\n unspents.forEach(function(unspent) {\n totalReturn += parseFloat(unspent.value);\n });\n callback(null, addressToGet, totalReturn);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the player widget is ready, kickoff a play/pause in order to get the data loading. We'll wait on loadedProgress. It's possible for the loadProgress to take time after play(), so we don't call pause() right away, but wait on loadedProgress to be 1 before we do.
function onPlayerReady( data ) { // Turn down the volume and kick-off a play to force load player.bind( SC.Widget.Events.PLAY_PROGRESS, function( data ) { // Turn down the volume. // Loading has to be kicked off before volume can be changed. player.setVolume( 0 ); // Wait for both flash and HTML5 to play something. if( data.currentPosition > 0 ) { player.unbind( SC.Widget.Events.PLAY_PROGRESS ); player.bind( SC.Widget.Events.PAUSE, function() { player.unbind( SC.Widget.Events.PAUSE ); // Play/Pause cycle is done, restore volume and continue loading. player.setVolume( 100 ); player.bind( SC.Widget.Events.SEEK, function() { player.unbind( SC.Widget.Events.SEEK ); onLoaded(); }); // Re seek back to 0, then we're back to default, loaded, and ready to go. player.seekTo( 0 ); }); player.pause(); } }); player.play(); }
[ "function onPlayerReady() {\n const roomCode = this.player.roomCode;\n\n // The player is ready to smack down.\n this.player.ready = true;\n\n // Let everyone else know the player is ready.\n this.broadcast.to(roomCode).emit('show player ready', this.player);\n\n // Check to see if all players are ready.\n if (checkAllPlayersReady(roomCode)) {\n io.in(roomCode).emit('start countdown');\n\n rooms[roomCode].countdownStarted = true;\n\n // Clear the player's texture map to clean up JSON payload.\n for (let player of getPlayersInRoom(roomCode)) {\n player.textureMap = [];\n }\n }\n}", "static waitToLoading() {\n browser.waitForExist(loading, timeToWait, true);\n if (browser.isVisible(introTask)) {\n browser.element(introTaskButton).click();\n }\n browser.waitForExist(introTask, timeToWait, true);\n }", "function playerReady(num) {\n let player = `.p${parseInt(num) + 1}`;\n document.querySelector(`${player} .ready`).classList.toggle('active');\n }", "function loadingScreen() {\r\n textAlign(CENTER);\r\n textSize(40);\r\n image(player, width/4, width/4, width/2, width/2);\r\n text(\"LOADING. . .\", width/2, width/2);\r\n}", "pause() {\n if (this.mediaUpdateTimeout) {\n window.clearTimeout(this.mediaUpdateTimeout);\n this.mediaUpdateTimeout = null;\n }\n\n this.stopRequest();\n if (this.state === 'HAVE_NOTHING') {\n // If we pause the loader before any data has been retrieved, its as if we never\n // started, so reset to an unstarted state.\n this.started = false;\n }\n // Need to restore state now that no activity is happening\n if (this.state === 'SWITCHING_MEDIA') {\n // if the loader was in the process of switching media, it should either return to\n // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media\n // playlist yet. This is determined by the existence of loader.media_\n if (this.media_) {\n this.state = 'HAVE_METADATA';\n } else {\n this.state = 'HAVE_MAIN_MANIFEST';\n }\n } else if (this.state === 'HAVE_CURRENT_METADATA') {\n this.state = 'HAVE_METADATA';\n }\n }", "function onProgress(e) {\n if (video.buffered.length > 0)\n {\n var end = video.buffered.end(0),\n start = video.buffered.start(0);\n load_bar.setAttribute(\"width\", Math.ceil((end - start) / video.duration * 100).toString());\n }\n}", "onPlayed () {\n UIManager.setStatusCast(UIManager.status.READY);\n UIManager.showSplashScreen();\n\n this.isCompleted = true;\n if (this.endedCallback !== null) {\n this.endedCallback();\n }\n\n this.notifySenders.apply(this, arguments);\n\n logger.info(LOG_PREFIX, 'Played');\n }", "static loadBeginning()\n {\n var path = game.load.path;\n\n game.load.path = 'assets/audio/music/';\n game.load.audio('beginning', 'beginning.mp3');\n\n game.load.path = path;\n }", "function audioPreload(requiredAudio,\n loadedAudio,\n completionCallback) {\n\n var numAudiorequired,\n numAudioHandled = 0,\n currentName,\n currentAudio,\n preloadAudioHandler;\n\n // Count our `requiredAudio` by using `Object.keys` to get all \n // \"*OWN* enumerable properties\" i.e. doesn't traverse the prototype chain\n numAudiorequired = Object.keys(requiredAudio).length;\n\n // A handler which will be called when our required audio files are finally\n // loaded (or when the fail to load).\n //\n // At the time of the call, `this` will point to an Audio object, \n // whose `name` property will have been set appropriately.\n //\n preloadAudioHandler = function () {\n\n loadedAudio[this.name] = this;\n\n if (0 === this.width) {\n console.log(\"loading failed for\", this.name);\n }\n\n // Allow this handler closure to eventually be GC'd (!)\n this.onload = null;\n this.onerror = null;\n\n numAudioHandled += 1;\n\n if (numAudioHandled === numAudiorequired) {\n console.log(\"all preload audio files handled\");\n console.log(\"loadedAudio=\", loadedAudio);\n console.log(\"\");\n console.log(\"performing completion callback\");\n\n completionCallback();\n\n console.log(\"completion callback done\");\n console.log(\"\");\n }\n };\n\n // The \"for..in\" construct \"iterates over the enumerable properties \n // of an object, in arbitrary order.\" \n // -- unlike `Object.keys`, it traverses the prototype chain\n //\n for (currentName in requiredAudio) {\n\n // Skip inherited properties from the prototype chain,\n // just to be safe, although there shouldn't be any...\n \n if (requiredAudio.hasOwnProperty(currentName)) {\n console.log(\"preloading audio\", currentName);\n currentAudio = new Audio();\n currentAudio.name = currentName;\n currentAudio.asyncLoad(requiredAudio[currentName], preloadAudioHandler);\n }\n }\n}", "function progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}", "function loadCandidate(candidate) {\n\tliveCandidate = candidate;\n\tupdatePlayer();\n\n\tfunction updatePlayer() {\n\t\tif (updatingPlayer) {\n\t\t\treturn;\n\t\t}\n\t\tupdatingPlayer = true;\n\t\t\n\t\tconsole.log(\"Loading next item...\");\n\t\tif (handle !== null) {\n\t\t\t// there is currently something playing.\n\t\t\t// kill it. This will then trigger the close calback when the process ends, and this\n\t\t\t// will then call the callback below, which will then move into updatePlayerPt2 function\n\t\t\tplayerProcessCloseCallback = function() {\n\t\t\t\tupdatePlayerPt2();\n\t\t\t};\n\t\t\tkillPlayer();\n\t\t}\n\t\telse {\n\t\t\tupdatePlayerPt2();\n\t\t}\n\t\t\n\t\tfunction updatePlayerPt2() {\n\t\t\tif (liveCandidate === null) {\n\t\t\t\tconsole.log(\"There is no item to load.\");\n\t\t\t\tupdatingPlayer = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar candidate = liveCandidate;\n\t\t\t// check this candidate is still available and valid\n\t\t\tvar requestUrl = \"mediaItems/\"+candidate.mediaItem.id;\n\t\t\tapiRequest(requestUrl, function(data) {\n\t\t\t\t\n\t\t\t\tif (candidate !== liveCandidate) {\n\t\t\t\t\t// the candidate to play next has changed whilst the api request was taking place.\n\t\t\t\t\t// make the request again with the new candidate\n\t\t\t\t\tupdatePlayerPt2();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tupdatingPlayer = false;\n\t\t\t\t\tconsole.log(\"Checking next item is still a valid option.\");\n\t\t\t\t\tvar mediaItem = null;\n\t\t\t\t\tif (data !== null) {\n\t\t\t\t\t\tmediaItem = data.data.mediaItem;\n\t\t\t\t\t}\n\t\t\t\t\tif (mediaItem === null || !isMediaItemValid(mediaItem, candidate.type)) {\n\t\t\t\t\t\tconsole.log(\"Item no longer valid.\");\n\t\t\t\t\t\tloadNextItem();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tconsole.log(\"Item valid.\");\n\t\t\t\t\t\tplayItem(candidate.url, candidate.type);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n}", "static load()\n {\n // load non-phaser audio elements for pausing and unpausing\n this.pauseAudio = new Audio('assets/audio/sfx/ui/pause.mp3');\n this.resumeAudio = new Audio('assets/audio/sfx/ui/checkpoint.mp3');\n\n var path = game.load.path;\n game.load.path = 'assets/audio/sfx/levels/';\n\n game.load.audio('open_door', 'open_door.mp3');\n game.load.audio('begin_level', '../ui/begin_level.mp3');\n\n game.load.path = path;\n }", "function loadObjectsAfterWaitingForScripts(){\n\t\tlet waitingTime = 1000;\n\t\tsetTimeout(function () {\n\t\t\tloadDataObjects();\n\t\t\tactionNamespace.actionDrawStartPage();\t\n\t\t}, waitingTime);\n\t}", "function onFlashLoaded() {\n\t\ttrace(\"onFlashLoaded (from Flash)\");\n\t\t\n\t\tset_ready();\n\t}", "function loadPageAudio(audioFile) {\n\t//console.log(\"audioFile: \" +audioFile);\n\t$(shell.audio.playerDiv).off($.jPlayer.event.ended);\n\ttogglePlayPause('end');\n\tshell.caption.currPosition = 0;\n\tshell.timedContent.currPosition = 0;\n\tif (!videoPlaying) {\n\t\tvar audioToLoad;\n\t\tif(audioFile) {\n\t\t\taudioToLoad = audioFile\n\t\t} else {\n\t\t\taudioToLoad = currPageData.audio;\n\t\t}\n\t\t//console.log(audioToLoad);\n\t\tif (audioToLoad && audioToLoad != '' && audioToLoad != ' ') {\n\t\t\t//console.log(\"loading audio: \"+ audioToLoad);\n\t\t\t//Determine the different audio types\n\t\t\tvar audioTypes = shell.audio.audioFileType.split(',');\n\t\t\t// Create the audio media format object \n\t\t\tvar audioPaths = {};\n\t\t\tfor (var i=0; i<audioTypes.length; i++) {\n\t\t\t\tif (i != audioTypes.length-1) audioPaths = audioPaths + \", \";\n\t\t\t\tswitch(audioTypes[i]) {\n\t\t\t\t\tcase('mp3'): \n\t\t\t\t\t\taudioPaths.mp3 = audioToLoad + \".mp3\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase('m4a'):\n\t\t\t\t\t\taudioPaths.m4a = audioToLoad + \".m4a\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase('webma'):\n\t\t\t\t\t\taudioPaths.webma = audioToLoad + \".webm\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase('oga'):\n\t\t\t\t\t\taudioPaths.oga = audioToLoad + \".ogg\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase('fla'):\n\t\t\t\t\t\taudioPaths.fla = audioToLoad + \".flv\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase('wav'):\n\t\t\t\t\t\taudioPaths.wav = audioToLoad + \".wav\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//console.log(\"setting media to \" + audioPaths.mp3);\n\t\t\t$(shell.audio.playerDiv).jPlayer(\"setMedia\", audioPaths);\n\t\t\t//console.log('playing media');\n\t\t\t//disable AUTOPLAY code. #JS addition\n\t\t\tif(!delayPage || (audioToLoad.length>16)){\n\t\t\t\t$(shell.audio.playerDiv).jPlayer(\"play\"); // Attempt to auto play the media\n\t\t\t\ttogglePlayPause();\n\t\t\t}\n\t\t\tif (audioIsDim) enableAudioControls();\n\t\t} else if (audioToLoad == ' ') {\n\t\t\tif (audioIsDim) enableAudioControls();\n\t\t} else {\n\t\t\t//console.log(\"This page has no audio\");\n\t\t\t$(shell.audio.playerDiv).jPlayer(\"clearMedia\");\n\t\t\tdisableAudioControls('none');\n\t\t}\n\t\tif (!shell.caption.isTimedCC) {\n\t\t\tvar ccObjArray = shell.caption.data[shell.currPageId].mainPage;\n\t\t\tif (shell.caption.onSubPage) {\n\t\t\t\tif (shell.caption.onSubSubPage) {\n\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].subPages[shell.caption.subSubPageNum][0];\n\t\t\t\t} else {\n\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].mainPage[0];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tccObjArray = ccObjArray[0]\n\t\t\t}\n\t\t\tloadCCText(ccObjArray.html);\t\t\n\t\t} else {\n\t\t\t$(shell.audio.playerDiv).on($.jPlayer.event.timeupdate, function(event) {\n\t\t\t\taudioPlayerUpdate(event);\n\t\t\t});\n\t\t}\n\t\t$(shell.audio.playerDiv).on($.jPlayer.event.ended, function(event) {\n\t\t\t$(shell.audio.playerDiv).off($.jPlayer.event.ended);\n\t\t\t//console.log('audio ended');\n\t\t\ttogglePlayPause('end');\t\n\t\t\tdisablePlay('end');\n\t\t\taudioEnded();\t\n\t\t});\n\t}\n}", "function pluginLoaded(\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n /**\n * No arguments. */\n)\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n{\n console.log(2, \"Local Plugin Loaded.\");\n Callcast.localplayer = $(\"object.localplayer\").get(0);\n Callcast.InitGocastPlayer(null, null, function(message) {\n /*\n * Initialization successful. */\n console.log(2, \"Local plugin successfully initialized.\");\n /*\n * Set callback functions to add and remove plugins for other\n * participants. */\n Callcast.setCallbackForAddPlugin(addPlugin);\n Callcast.setCallbackForRemovePlugin(removePlugin); \n initializeLocalPlugin();\n }, function(message) {\n /*\n * Failure to initialize. */\n console.log(4, \"Local plugin failed to initialize.\");\n $(\"#errorMsgPlugin\").empty();\n $(\"#errorMsgPlugin\").append('<h1>Gocast.it plugin failed to initialize</h1><p>Please reload the page. [Ctrl + R]</p>');\n openWindow('#errorMsgPlugin');\n });\n}", "play() {\n // rewind when user clicks play on ended scene\n this.goToStartIfEnded();\n this.disablePlayButtonUntilPlaybackStarts();\n this.waitForCanPlayAll().then(() => {\n this.videoElements.forEach(e => e.play());\n });\n }", "playPauseAndUpdate(song = player.currentlyPlaying) {\n player.playPause(song);\n $('#time-control .total-time').text( player.getDuration );\n }", "load(callback) {\n\t\t\t\tlet element = timeline._activePart.element;\n\t\t\t\tlet points = timeline._activePart.points;\n\t\t\t\tfor(let q = 0; q < points.length; q++){\n\t\t\t\t\telement.append(points[q].element);\n\t\t\t\t}\n\t\t\t\telement.children().fadeIn('fast').promise().done(callback);\n\t\t\t\ttimeline.proceeding = false;\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the viewstack layout.
function _createLayout() { this._renderables = { views: [], transferables: [] }; this._viewStack = []; this.layout = new LayoutController({ layout: ViewStackLayout.bind(this), layoutOptions: this.options, dataSource: this._renderables }); this.add(this.layout); this.layout.on('layoutend', _processAnimations.bind(this)); }
[ "createLayout(){\n const container = createComponent('div', {class: 'container'})\n const pageContent = createComponent('div', {id: 'pageContent', class: 'my-5'})\n const welcomeImage = createComponent('img', {src: \"./images/home.png\", style: \"max-width: 100%\"})\n pageContent.append(welcomeImage)\n nav()\n container.append(pageContent)\n document.getElementById('app').append(container)\n }", "function StackWidget() {\n _super.call(this);\n this._m_currentChanged = new Signal();\n this._m_widgetRemoved = new Signal();\n this.classList.add(STACK_WIDGET_CLASS);\n var layout = this.layout = new StackLayout();\n this.setFlag(16 /* DisallowLayoutChange */);\n layout.currentChanged.connect(this._sl_currentChanged, this);\n layout.widgetRemoved.connect(this._sl_widgetRemoved, this);\n }", "function stackTimelineView() {\n\n ViewVideo.OverlayTimeline.CollisionDetection({spacing:0, includeVerticalMargins: true});\n ViewVideo.adjustLayout();\n ViewVideo.adjustHypervideo();\n\n }", "function setupLayout() {\n\t$('body').layout({\n\t\twest__showOverflowOnHover : true,\n\t\tresizable : false,\n\t\tclosable : false\n\t});\n\n\t$('.ui-layout-west a').click(function() {\n\t\tvar id = $(this).attr('id');\n\t\tif (id == 'upload') {\n\t\t $('#uploadForm :input').val('');\n\t\t\t$('#errorBox').html('');\n\t\t\t$('#uploadDialog').dialog('open');\n\t\t} else {\n\t\t\t$('.ui-layout-west a').removeClass('selectedCat');\n\t\t\t$(this).addClass('selectedCat');\n\t\t\tcurrentContent = id;\n\t\t\tgetContent(id);\n\t\t}\n\t\treturn false;\n\t});\n\n // Select default content\n\t$(\".ui-layout-west a[id='\" + currentContent + \"']\").addClass('selectedCat');\n}", "function generateTopSwitchLayout() {\n const div = document.createElement(\"div\");\n div.setAttribute(\"class\", \"top-switch-div\");\n const info = document.createElement(\"button\");\n info.setAttribute(\"id\", \"topSwitchInfoButton\")\n info.setAttribute(\"class\", \"top-switch-button selected\");\n const photos = document.createElement(\"button\");\n photos.setAttribute(\"class\", \"top-switch-button\");\n photos.setAttribute(\"id\", \"topSwitchPhotosButton\")\n info.innerText = \"Information\";\n photos.innerText = \"Photos\";\n info.onclick = () => {\n clearPhotoLayout()\n buildMainPage();\n infoSelected = true\n changeSelection()\n };\n photos.onclick = () => {\n if (GalleryStore.getGallery().photos.length > 0) {\n infoSelected = false\n clearMainPage()\n buildPhotosLayout()\n changeSelection()\n } else {\n createPopupWindow(\"This gallery is empty, please upload some photos first\")\n }\n\n };\n div.appendChild(info);\n div.appendChild(photos);\n return div;\n}", "function createQuestionLayout() {\n var mainDiv = document.getElementsByClassName('display_question');\n var wrapperDiv = document.createElement('div');\n wrapperDiv.className = \"wrapper\";\n mainDiv.appendChild(wrapperDiv);\n for (var j = 0 ; j < 2; j++) {\n var span = document.createElement('span');\n wrapperDiv.appendChild(span);\n }\n span.innerHTML = \"/ \"+quizQuestions.length;\n var ulDdown = document.createElement('ul');\n ulDdown.className = \"dropdown\";\n mainDiv.appendChild(ulDdown);\n var pTag = document.createElement('p');\n pTag.className = \"question\";\n var ulTag = document.createElement('ul');\n mainDiv.appendChild(pTag);\n mainDiv.appendChild(ulTag);\n for (var i = 0 ; i < 4; i++) {\n var liTag = document.createElement('li');\n ulTag.appendChild(liTag);\n var liTag1 = document.createElement('li');\n ulDdown.appendChild(liTag1);\n }\n var button = document.createElement('button');\n button.innerHTML = \"Back\";\n button.className = \"back\";\n //goes back to the table layout when clicked\n button.onclick = finalize;\n mainDiv.appendChild(button);\n}", "setDefaultLayout(){\n this.set('layoutName' , LayoutConfig.defaultLayoutFolderName)\n }", "setConfig(layoutConfig) {\n this.config = this.preInit(layoutConfig)\n\n // scope list of classes\n this.classes = {\n header: [],\n header_container: [],\n header_menu: [],\n subheader: [],\n subheader_container: [],\n content: [],\n content_container: [],\n }\n\n this.attributes = {\n header_menu: {},\n }\n\n // init base layout\n this.initLoader()\n\n // init header\n this.initHeader()\n\n this.initContent()\n\n // init theme\n this.initTheme()\n }", "function createLayout() {\n if (process.argv.length < 3) {\n console.log('Usage: node ' + process.argv[1] + ' [col # row #] *max for both 4');\n process.exit(1);\n }\n /*Create base layout with 1 row for header */\n var layoutWrapper = $('<center class=\"wrapper\"></center>');\n var webkitWrapper = $('<div class=\"webkit\"></div>');\n var outlookWrapperStart = $('<!--[if (gte mso 9)|(IE)]><table width=\"600\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td> <![endif]-->');\n /* Append to the end after everything is done place out side outermost Table but inside webkit-wrapper*/\n var outlookWrapperEnd = $('<!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]-->');\n var outerTable = $('<table class=\"outer\" align=\"center\"></table>');\n var header = $('<tr><td class=\"full-width-image\"> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/header.jpg\" width=\"600\"/></td></tr>');\n webkitWrapper.append(outlookWrapperStart);\n outerTable.append(header);\n /*Here the user will pass in 2 numbers. The ith argument corresponds to the ith row\n the actual value of the argument itself corresponds to number of columns in the ith row.*/\n var layoutSetupList = process.argv;\n /*Iterating through the command line (process.argv) args. Note we start at 2 because in the\n array process.argv[0] holds the path , process.argv[1] holds the process name*/\n for (var position = 2; position < layoutSetupList.length; position += 1) {\n var columnCount = layoutSetupList[position];\n /* Table cannot contain negative or 0 cols*/\n if (columnCount < 1) {\n throw new Error(\"The argument value has to be at least 1!\");\n process.exit(1);\n }\n if (columnCount == 1) {\n outerTable.append('<tr><td class=\"one-column\"><table width=\"100%\"><tr><td class=\"inner contents\"><p class=\"h1\">Lorem ipsum dolor sit amet</p><p>Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent laoreet malesuada cursus. Maecenas scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</p></td></tr></table></td></tr>');\n } else if (columnCount == 2) {\n outerTable.append('<tr><td class=\"two-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"50%\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/two-column-01.jpg\" width=\"280\" alt=\"\"></td></tr><tr><td class=\"text\"> Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"50%\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/two-column-02.jpg\" width=\"280\" alt=\"\"></td></tr><tr><td class=\"text\"> Maecenas sed ante pellentesque, posuere leo id, eleifend dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr>');\n } else if (columnCount == 3) {\n outerTable.append('<tr><td class=\"three-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-01.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-02.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"200\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tr><td class=\"inner\"><table class=\"contents\"><tr><td> <img src=\"https://raw.githubusercontent.com/tutsplus/creating-a-future-proof-responsive-email-without-media-queries/master/images/three-column-03.jpg\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></table></td></tr></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr>');\n } else if (columnCount == 4) {\n outerTable.append('<tr><td class=\"four-column\"> <!--[if (gte mso 9)|(IE)]><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/App-Store-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/Camera-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/iTunes-Store-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td><td width=\"150\" valign=\"top\"> <![endif]--><div class=\"column\"><table width=\"100%\"><tbody><tr><td class=\"inner\"><table class=\"contents\"><tbody><tr><td> <img src=\"http://icons.iconarchive.com/icons/iynque/ios7-style/128/Messages-icon.png\" width=\"180\" alt=\"\"></td></tr><tr><td class=\"text\"> Scelerisque congue eros eu posuere. Praesent in felis ut velit pretium lobortis rhoncus ut erat.</td></tr></tbody></table></td></tr></tbody></table></div> <!--[if (gte mso 9)|(IE)]></td></tr></table> <![endif]--></td></tr><tr>');\n }\n\n }\n webkitWrapper.append(outerTable);\n webkitWrapper.append(outlookWrapperEnd);\n layoutWrapper.append(webkitWrapper);\n return layoutWrapper;\n}", "function applyOrderWidthAndVisibility (layout) {\n var stack = [{node :root , index :0}];\n\n do{\n var current = stack[stack.length-1];\n\n if (current.node.children.length === 0 && current.node.parent) {\n table.find('.' + current.node.parent.id).each(function () {\n /* Appends node to own row */\n $(this).parent().append($(this));\n $(this).removeClass('cm-hidden');\n }).width(layout[current.node.id].width).addClass(!layout[current.node.id].visible ? 'cm-hidden' : ''); /* Apply width and visibility to itself */\n\n \n stack.pop();\n continue; // because there are not more children\n }\n\n if (current.index >= current.node.children.length) {\n stack.pop();\n continue; // because there are not more children\n }\n\n\n if (current.index === 0 && current.node.parent) {\n /* Appends node to own row */\n current.node.DOMelement.parent().append(current.node.DOMelement);\n\n /* Apply width to itself */\n current.node.DOMelement.width(layout[current.node.id].width);\n\n /* Set visiblity */\n current.node.DOMelement.removeClass('cm-hidden');\n current.node.DOMelement.addClass(!layout[current.node.id].visible? 'cm-hidden' : '');\n }\n\n stack.push({node: current.node.children[current.index++], index : 0});\n\n } while ( stack.length > 1);\n table.trigger('colme:reflow');\n }", "createView(){\n super.createView();\n if(this.getView()) {\n for (let h of this.getView().handles) {\n this.addInteractionsToElement(h);\n }\n // this.detach();\n }\n }", "createDumperViewNamespace() {\n if (this.app.isBound('view.resolver')) {\n this.app.make('view.resolver').namespace('dumper', this.app.formatPath(__dirname, 'views', 'dumper'));\n }\n }", "visitCreate_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function buildNorthPane() {\n var l_html = \"<div id=\\\"north_pane\\\" class=\\\"ui-layout-north\\\">\" +\n \"</div>\";\n jQuery(l_html).appendTo('body');\n }", "function LayoutByDays () {\n this._init ();\n}", "function _handleSplitViewVertical() {\n MainViewManager.setLayoutScheme(1, 2);\n }", "function createDrawList()\n\t{\n\t\tvar widLists = view.widgetLists;\n\t\tvar components = [];\n\n\t\tif (layout.divider)\n\t\t\tcomponents.push(widLists.divider);\n\n\t\t// Add the question image or read-only graph (but not both!)\n\t\tif (layout.image)\n\t\t\tcomponents.push(widLists.qImage);\n\n\t\tif (layout.sumCard)\n\t\t\tcomponents.push(widLists.sumCard);\n\n\t\t// Add streak animation\n\t\tif (layout.streak)\n\t\t\tcomponents.push(widLists.streak);\n\n\t\t// Add stars\n\t\tif (layout.stars)\n\t\t\tcomponents.push(widLists.stars);\n\n\t\t// Add score\n\t\tif (layout.score)\n\t\t\tcomponents.push(widLists.score);\n\n\t\tif (layout.statusOverlay)\n\t\t\tcomponents.push(widLists.statusOverlay);\n\n\t\t// Add submission\n\t\tif (layout.submits)\n\t\t\tcomponents.push(widLists.submits);\n\n\t\t// Add dependent pieces\n//\t\tvar q = (layout.divider ? widLists.questionLeft : widLists.questionCenter);\t// Centered question mode\n\t\tvar q = widLists.questionLeft;\n\t\tcomponents.push(q);\n\n\t\t// Add the answer and result widgets\n\t\tif (layout.ansInput)\n\t\t\tcomponents.push(widLists.answerWids);\n//\t\telse if (app.modes.getNavOptions().fwdBack)\t// The presence of forward/back arrows acts as a proxy for determining whether a \"Next Problem\" button should appear\n//\t\t\tcomponents.push(widLists.nextButton);\n\n\t\t// Response text\n\t\tcomponents.push(widLists.responseText);\n\n\t\t// Add Up button\n\t\tif (layout.quizboardUpButton)\n\t\t\tcomponents.push(widLists.quizboardUpButton);\n\n\t\telse if (layout.assignUpButton)\n\t\t\tcomponents.push(widLists.assignUpButton);\n\n\t\t// Add assignment name\n\t\tif (layout.aName)\n\t\t\tcomponents.push(widLists.aName);\n\n\t\t// Add equation input\n\t\tcomponents.push(widLists.keypad);\t\t// Always -- there might be equation steps. We could scan for that to be smarter.\n\n\t\t// Finally, add hidden chapter logo\n//\t\tif (app.isHiddenChapter())\n//\t\t\tcomponents.push(widLists.logo);\n\n\t\t// Move this functionality into a routine!\n\t\tdrawList = fw.drawList(components);\n\t}", "async function createUI() {\n const infectedHosts = await getInfectedHosts();\n infectedHosts.forEach(async (host) => {\n const payloads = await getPayloads(host);\n\n const hostDiv = createHostDiv();\n const hostLink = createHostLink(host);\n\n hostDiv.append(hostLink);\n $(\"#infected_hosts\").append(hostDiv);\n\n payloads.forEach(async (payloadObject) => {\n const userPayloadsDiv = createUserPayloadsDiv();\n const userPayloadsLink = createUserPayloadsLink(payloadObject);\n\n userPayloadsDiv.append(userPayloadsLink);\n\n const payload = await getPayload(host, payloadObject['payload_id']);\n\n const payloadDataDiv = $(\"<pre class=\\\"payload\\\"></pre>\");\n payloadDataDiv.append(payload);\n const containerDiv = $(\"<div class=\\\"container\\\"></div>\");\n containerDiv.css(\"display\", \"none\");\n containerDiv.append(userPayloadsDiv);\n containerDiv.append(payloadDataDiv);\n hostDiv.append(containerDiv);\n });\n });\n }", "function buildEastPane() {\n var l_html = \"<div class=\\\"ui-layout-east\\\">\" +\n \"<div id=\\\"east_title\\\" class=\\\"header ui-widget-header\\\"></div>\" +\n \"<div id=\\\"east_file\\\" class=\\\"file\\\"></div>\" +\n \"<div id=\\\"east_footer\\\" class=\\\"footer ui-widget-header \\\"></div>\" +\n \"</div>\";\n jQuery(l_html).appendTo('body');\n }", "function appViewLayout(){\n\tvar appViewStatus = Number(document.getElementById(\"appsViewStatusOp\").value);\n\t\n\tif(appViewStatus === 0){\n\t\t\n\t\t// Size of HTML document (same as pageHeight/pageWidth in screenshot).\n\t\tvar indention = 65;\n\t\tvar totalWidth = Number(document.documentElement.clientWidth) - indention;\n\t\t\n\t\tdocument.getElementById(\"appsViewStatusOp\").value = \"1\";\n\t\tdocument.getElementById(\"changeTabSet\").setAttribute(\"class\", \"icon mif-enlarge\");\n\t\tdocument.getElementById(\"tabButton\").setAttribute(\"title\", \"Fullscreen View\");\n\t\t\n\t\tAnimate('appBaseArea', indention, '0', totalWidth, '100%', '', 500, '');\n\t\t\n\t}\n\telse{\n\t\tdocument.getElementById(\"appsViewStatusOp\").value = \"0\";\n\t\t\n\t\tdocument.getElementById(\"changeTabSet\").setAttribute(\"class\", \"icon mif-keyboard-tab\");\n\t\tdocument.getElementById(\"tabButton\").setAttribute(\"title\", \"Tab View\");\n\t\t\n\t\tAnimate('appBaseArea', '0', '0', '100%', '100%', '', 500, '');\n\t}\n\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is to extract the first 10 data cells of each subject ID for making the bar chart and to graph that data into a bar chart.
function graph_for_subject_id(){ let top_10_otus_unique_table = [] let top_10_otus_sample_values = [] let top_10_otus_labels = [] let otu_ids_length = database.samples[index]["otu_ids"].length let selected_row = database.samples[index] if (otu_ids_length >= 10){ for (let i=0, n = 10; i<n; i++){ top_10_otus_unique_table.push(`OTU ${selected_row["otu_ids"][i]}`) top_10_otus_sample_values.push(selected_row.sample_values[i]) top_10_otus_labels.push(selected_row.otu_labels[i]) } }else{ for (let i=0, n = otu_ids_length; i<n; i++){ top_10_otus_unique_table.push(`OTU ${selected_row["otu_ids"][i]}`) top_10_otus_sample_values.push(selected_row.sample_values[i]) top_10_otus_labels.push(selected_row.otu_labels[i]) } } // This is the code to create a BAR CHART let data = [{ x: top_10_otus_sample_values, y: top_10_otus_unique_table, orientation: 'h', type: 'bar', mode: 'markers', marker: {size:16}, text: top_10_otus_labels, transforms: [{ type: 'sort', target: 'x', order: 'ascending' }] }]; Plotly.newPlot('bar', data); // This is the code to create a BUBBLE CHART data = [{ x: selected_row["otu_ids"], y: selected_row.sample_values, text: selected_row["otu_labels"], mode: 'markers', marker: { size: selected_row.sample_values, color: selected_row["otu_ids"] } }]; let layout = { xaxis: { title: { text: 'OTU ID', font: { size: 18, } }, }, hovermode: "closest", }; Plotly.newPlot('bubble', data, layout); // This is the code to add the metadata into the website let selection = d3.select("#sample-metadata") selection.selectAll("li").remove() metadata_info = Object.entries(database.metadata[index]) for(x of metadata_info){ selection.append("li").text(`${x[0]}: ${x[1]}`).append("br") } // This is the code to create a GAUGE CHART data = [{ type: "pie", showlegend: false, hole: 0.4, rotation: 90, values: [100 / 9, 100 / 9, 100 / 9, 100 / 9, 100 / 9, 100 / 9, 100 / 9, 100 / 9, 100 / 9, 100], text: ["0-1", "1-2", "2-3", "3-4", "4-5", "5-6", "6-7", "7-8", "8-9", ""], direction: "clockwise", textinfo: "text", textposition: "inside", marker: { colors: ["aqua", "aquamarine", "chartreuse", "chocolate", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "white"] }, }]; let wash_freq = database.metadata[index]["wfreq"] var x1_value = 0 var y1_value = 0 if (wash_freq <= 1){ x1_value = .25 y1_value = .55 }else if (wash_freq <= 2){ x1_value = .25 y1_value = .65 }else if (wash_freq <= 3){ x1_value = .29 y1_value = .76 }else if (wash_freq <= 4){ x1_value = .4 y1_value = .76 }else if (wash_freq <= 5){ x1_value = .5 y1_value = .76 }else if (wash_freq <= 6){ x1_value = .6 y1_value = .76 }else if (wash_freq <= 7){ x1_value = .67 y1_value = .73 }else if (wash_freq <= 8){ x1_value = .75 y1_value = .65 }else if (wash_freq <= 9){ x1_value = .83 y1_value = .55 } layout = { margin: { t: 0, b: 0, l: 0, r: 0 }, shapes:[{ type: 'line', x0: .5, y0: 0.5, x1: x1_value, y1: y1_value, line: { color: 'red', width: 10 } }], hovermode: false, }; Plotly.newPlot("gauge", data, layout, {staticPlot: false}); }
[ "function barchart(selectedID){\n d3.json(\"data/samples.json\").then((data) => {\n var dropdownMenu = d3.select(\"#selDataset\");\n selectedID = dropdownMenu.node().value;\n var samples = data.samples;\n var selectID = samples.filter(person=>person.id==selectedID);\n var valuearray = selectID[0];\n var values = valuearray.sample_values.slice(0,10);\n var IDs = valuearray.otu_ids.map(otu => \"OTU \" + otu);\n var labels = valuearray.otu_labels.slice(0,10);\n // console.log(valuearray);\n\n // Create the trace for plotting\n var trace = {\n x : values,\n y : IDs,\n text : labels,\n type : 'bar',\n orientation : 'h'\n };\n\n // Define the plot layout\n var layout = {\n title: \"Top 10 OTU's for Selected Test Subject\",\n xaxis: { title: \"Sample Value\" },\n yaxis: { title: \"OTU ID\" }\n };\n\n // Define the data\n var plotdata = [trace]\n\n // Create plot using Plotly\n Plotly.newPlot('bar', plotdata, layout)\n\n})}", "function populateTopUsersThisWeekChart(top5Users1Week, id) {\n if(!top5Users1Week.length) {\n\t$(`#${id}`).hide();\n\treturn;\n }\n\n let users = [],\n\ttaskRuns = [];\n for (i = 0; i < top5Users1Week.length; i++) {\n\tusers.push(top5Users1Week[i]['name']);\n\ttaskRuns.push(parseInt(top5Users1Week[i]['task_runs']));\n }\n\n let con = $(`#${id}`).find(\".canvas-container\"),\n\tcanvas = $(`#${id}`).find(\"canvas\"),\n\tdata = {\n\t labels: users,\n\t datasets: getBarDataset(\"contribution\", taskRuns)\n\t};\n let chart = drawBarChart(canvas, con, data);\n let highScore = taskRuns.indexOf(Math.max.apply(Math, taskRuns));\n highlightBar(chart.datasets[0].bars[highScore]);\n chart.update();\n}", "function createBarcharts(){\n\n // bar charts for age-group and birth cohort in county representation\n makeBarchart(d, featuresCB, \"#barchart1Position\",\"barchart1\",firstTimeData(d, selectedCategories), firstTimeData(d, selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2Position\",\"barchart2\",secondTimeData(d, selectedCategories), secondTimeData(d, selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in state representation\n makeBarchart(d, featuresCB, \"#barchart1BLPosition\",\"barchart1BL\",firstTimeDataBL(classes[1], selectedCategories), firstTimeDataBL(classes[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2BLPosition\",\"barchart2BL\",secondTimeDataBL(classes[1], selectedCategories), secondTimeDataBL(classes[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in kv representation\n makeBarchart(d, featuresCB, \"#barchart1KVPosition\",\"barchart1KV\",firstTimeDataKV(aships[1], selectedCategories), firstTimeDataKV(aships[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2KVPosition\",\"barchart2KV\",secondTimeDataKV(aships[1], selectedCategories), secondTimeDataKV(aships[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n\n\n // for the ranking of the top and worst 5 (=cutbarchart) counties when zoomed. If state has equal/less than 10 counties, all counties are shown\n if(lkData().length < 2*cutbarchart){\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",lkData(), numberLK(), \"lk\", rv, 3);\n d3.select(\"#barchart4\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n // 3 points shown in county ranking when zoomed\n else{\n d3.selectAll(\".circles\").remove();\n var worstLk = lkData().slice(cutbarchart,lkData().length);\n var topLk = lkData().slice(0,cutbarchart);\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",topLk, cutbarchart, \"lk\", rv, 3); // top 5 counties\n\n var svgCircles = d3.select(\"#circlesPosition\").append(\"g\")\n .attr(\"class\", \"circles\")\n .append(\"svg\")\n .attr(\"width\", 100)\n .attr(\"height\", 12)\n .attr(\"preserveAspectRatio\", \"xMidYMid meet\")\n .attr(\"viewBox\", \"0 0 \" + d3.select(\"#sidebarRight\").style(\"width\").split(\"px\")[0] + \" 12\")\n .append(\"g\")\n .attr(\"transform\", \"translate(0,0)\");\n\n var circles3 = [{\"cx\": 30, \"cy\":2 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":6 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":10 , \"r\": 1, \"color\": \"black\"}];\n\n var circles = svgCircles.selectAll(\"circle\")\n .data(circles3)\n .enter()\n .append(\"circle\");\n\n var circleAttributes = circles\n .attr(\"cx\", function (d) { return d.cx; })\n .attr(\"cy\", function (d) { return d.cy; })\n .attr(\"r\", function (d) { return d.r; })\n .style(\"fill\", function(d) { return d.color; });\n circleAttributes.attr(\"transform\",\"translate(0,0)\");\n\n makeBarchart(d, featuresCB, \"#barchart4Position\",\"barchart4\",worstLk, cutbarchart, \"lk\", rv, 3); // worst 5 counties\n }\n if(!zoomed){\n d3.select(\"#titel3\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n }", "function monthlyQuestionsChart (result) {\n // Get chart data\n function getMessages (data, channelFilter) {\n const channels = {}\n\n data.forEach(item => {\n const channel = item.MessageText; const id = item.MessageID\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n channels[channel].push(id)\n }\n }\n })\n\n for (channel in channels) {\n channels[channel] = channels[channel].length\n }\n\n return channels\n };\n\n // Sort chart keys descending\n function sortKeysDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] })\n };\n\n // Sort chart values descending\n function sortValuesDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] }).map(key => array[key])\n };\n\n // Combine chart keys and values\n function combineKeysAndValues (keys, values) {\n var result = {}\n for (var i = 0; i < keys.length; i++) { result[keys[i]] = values[i] }\n return result\n }\n\n var monthlyArrayKeys = sortKeysDescending(getMessages(result))\n var monthlyArrayValues = sortValuesDescending(getMessages(result))\n var monthlyCombinedArray = combineKeysAndValues(monthlyArrayKeys, monthlyArrayValues)\n\n // Set data and labels\n var labels = Object.keys(monthlyCombinedArray)\n var data = Object.values(monthlyCombinedArray)\n\n document.getElementById('monthlyTotalQuestions').innerHTML = ''\n\n // Create chart\n var ctx = document.getElementById('monthlyQuestionsChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Questions'\n },\n legend: {\n display: false\n },\n scales: {\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}", "function getBars(){\n for(var i = 0; i < dataset.length; i++){\n let height = getHeight(highNumberForYAxis, max, dataset[i]);\n let width = dataset.length > 2 ? (highNumberForXAxis - lowNumberForXAxis) / dataset.length - barPadding : 70;\n let x = (lowNumberForXAxis + barPadding) + rectangles.length * (highNumberForXAxis - lowNumberForXAxis - 5) / dataset.length;\n let y = highNumberForYAxis - height;\n rectangles.push(<Rect key={rectangles.length} x={x} y={y} width={width} height={height} fill={'rgb(23,153,173)'} />)\n }\n }", "function makeChart(data1) {\n var i, j;\n\n titles = data1.columns;\n titles.shift(); // Since we dont need the 'timestamp' column\n //console.log(data1);\n //console.log(titles);\n\n // Pushing the object skeletons into the 'data' array object\n for (i = 0; i < titles.length; i++) {\n var data_obj = {};\n data_obj.Title = titles[i];\n data_obj.Type = types[i];\n data_obj.Options = options[i];\n data_obj.Responses = [];\n // console.log(data_obj);\n data.push(data_obj);\n }\n\n // Sorting out the responses\n // If we see the multiple responses, they are strings of the form 'Response1, Response2'\n // So they can be split into arrays using the string.split(', ') method\n for (i = 0; i < data1.length; i++) {\n for (j = 0; j < data.length; j++) {\n var res = [];\n // console.log(data1[i][titles[j]].split(\", \"));\n res.push(data1[i][titles[j]].split(\", \"));\n // console.log(res[0]);\n if (j == 1) {\n data[j].Responses.push(res[0]); // Always push the response array for CHECKBOX type\n } else {\n if (res[0].length == 1) {\n // If there is only 1 response, just push the string, no the array\n data[j].Responses.push(res[0][0]); \n } else {\n data[j].Responses.push(res[0]); // If there are multiple responses, push the array\n }\n }\n }\n }\n\n console.log(data);\n\n // EXECUTING THE ABOVE FUNCTIONS BY ITERATING THROUGH THE DATA ELEMENTS\n //window.onload = () => {\n data.forEach((item) => {\n switch (item.Type) {\n case LIST:\n listProcessing(item);\n break;\n case MCQ:\n mcqProcessing(item);\n break;\n case CHECKBOX:\n checkboxProcessing(item);\n break;\n }\n });\n //};\n}", "function populateTop10PercentChart(stats, id) {\n let top10 = stats.n_tr_top_10_percent,\n bottom90 = stats.n_task_runs - top10,\n top10Label = \"Most Active 10%: \" + pluralise(top10, \"contribution\"),\n bottom90Label = \"Remaining 90%: \" + pluralise(bottom90, \"contribution\");\n\n let con = $(`#${id}`).find(\".canvas-container\"),\n canvas = $(`#${id}`).find(\"canvas\"),\n legendCon = $(`#${id}`).find(\".legend-container\"),\n\tdata = getDonutDataset(top10Label, top10, bottom90Label, bottom90);\n drawDonutChart(canvas, con, data, legendCon);\n}", "function createHorizontalBarchart(className,svgWidth,svgHeight,x,y,data,xTitle){\n //set width and height of bar chart\n let svg = d3.select(className)\n .attr(\"width\",svgWidth)\n .attr(\"height\",svgHeight)\n .attr(\"transform\",`translate(${x},${y})`);\n \n //Gaps between the barchart and svg\n let margin = { top: 0, right: 30, bottom:100, left: 100};\n \n //Calculate the real range for x and y scale\n let innerWidth = svgWidth - margin.left - margin.right;\n let innerHeight = svgHeight - margin.top - margin.bottom;\n \n //Round and the values\n let values = Array.from(data.values());\n let keys = Array.from(data.keys());\n \n //X scale of bar chart\n let xScale = d3.scaleLinear()\n .domain([0,d3.max(values)])\n .range([0,innerWidth]);\n \n //y scale of bar chart\n let yScale = d3.scaleBand()\n .domain(keys)\n .range([0,innerHeight])\n .padding(0.05);\n \n //Separate out the barchart\n let g = svg.append(\"g\")\n .attr(\"transform\",`translate(${margin.left},${margin.top})`);\n \n //Left axis with removed ticks\n g.append('g')\n .call(d3.axisLeft(yScale))\n .selectAll('.domain , .tick line')\n .remove();\n \n //this determine the value's format\n let valueType;\n if(d3.mean(values) < 1){\n valueType = \".0%\" \n }else {\n valueType = \".0f\";\n }\n \n g.append('g')\n .call(d3.axisLeft(yScale))\n .selectAll('.domain, .tick line')\n .remove();\n \n //Bottom axis\n let xAxis = g.append('g')\n .call(d3.axisBottom(xScale).tickFormat(d3.format(valueType)).tickSize(-innerHeight))\n .attr('transform',`translate(0,${innerHeight})`);\n \n xAxis.select(\".domain\")\n .remove();\n \n //add bars into the svg\n g.selectAll(\"rect\")\n .data(data)\n .enter()\n .append(\"rect\")\n .attr(\"y\", d => yScale(d[0]))\n .attr(\"height\", yScale.bandwidth())\n .transition()\n .duration(1000)\n .attr(\"width\",d => xScale(d[1]))\n \n \n //append the title\n svg.append(\"text\")\n .attr(\"transform\",`translate(${(margin.left+innerWidth)/2},${innerHeight + margin.bottom/2})`)\n .text(xTitle)\n .attr(\"fill\",\"#b3ecff\")\n .attr(\"font-size\",\"30px\");\n \n}", "function detailBar1() {\n\t\tlet svgHeight = 70;\n\n\t\tvar margin = {top: 5, right: 20, bottom: 0, left: 20}\n\t\t , width = svgWidth - margin.left - margin.right // Use the window's width \n\t\t , height = svgHeight - margin.top - margin.bottom;\n\n\t\tlet xScale = d3.scaleBand().range([0, width]).padding(0.4);\n\t\tlet yScale = d3.scaleLinear().range([height, 0]);\n\n\t\tlet svg = d3.select(\"svg#detail-1-bar-1\")\n\t\t\t\t\t\t.attr(\"width\", svgWidth)\n\t\t\t\t\t\t.attr(\"height\", svgHeight)\n\t\t\t\t\t\t.attr(\"viewBox\", \"0 0 \" + svgWidth + \" \" + svgHeight);\n\n\t\tvar g = svg.append(\"g\")\n\t\t\t\t.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\t\tlet priceData = [records[city][\"2015-2020-price\"]];\n\n\t\txScale = d3.scaleLinear()\n\t\t\t\t.domain([0, price.totalMaximun])\n\t\t\t\t.range([0, width]);\n\n\t\tyScale = d3.scaleBand()\n\t\t\t\t.domain(city)\n\t\t\t\t.range([0, height])\n\t\t\t\t.padding(0.2);\n\n\t\tlet xAxis = g.append(\"g\")\n\t\t\t.attr(\"transform\", \"translate(0,\" + 45 + \")\")\n\t\t\t.call(d3.axisBottom(xScale).tickFormat(function(d){\n\t\t\t\tif (d >= 1000000) {\n\t\t\t\t\treturn d / 1000000 + \"M\";\n\t\t\t\t} else if (d >= 1000) {\n\t\t\t\t\treturn d / 1000 + \"K\";\n\t\t\t\t} else if (d < 1000) {\n\t\t\t\t\treturn d;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.ticks(10))\n\t\t\t.attr(\"class\", \"x-axis\")\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"class\", \"label\")\n\t\t\t.attr(\"x\", 150)\n\t\t\t.attr(\"y\", -40)\n\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t.text(\"Average Home Price (2015-2020)\");\n\n\t\t// Create the bars' container\n\t\tlet bar = g.selectAll(\".bar-price\")\n\t\t\t.data(priceData)\n\t\t\t.enter()\n\t\t\t.append(\"rect\")\n\t\t\t.attr(\"class\", \"bar-price\")\n\t\t\t.attr(\"x\", 0)\n\t\t\t.attr(\"y\", 20)\n\t\t\t.attr(\"width\", function(d) {\n\t\t\t\treturn xScale(d);\n\t\t\t})\n\t\t\t.attr(\"height\", 25)\n\t\t\t.style(\"fill\", colorMain);\n\t}", "function dailyQuestionsChart (result) {\n // Get chart data\n function getMessages (data, channelFilter) {\n const channels = {}\n\n data.forEach(item => {\n const channel = item.MessageText; const id = item.MessageID\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n channels[channel].push(id)\n }\n }\n })\n\n for (channel in channels) {\n channels[channel] = channels[channel].length\n }\n\n return channels\n };\n\n // Sort chart keys descending\n function sortKeysDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] })\n };\n\n // Sort chart values descending\n function sortValuesDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] }).map(key => array[key])\n };\n\n // Combine chart keys and values\n function combineKeysAndValues (keys, values) {\n var result = {}\n for (var i = 0; i < keys.length; i++) { result[keys[i]] = values[i] }\n return result\n }\n\n var dailyArrayKeys = sortKeysDescending(getMessages(result))\n var dailyArrayValues = sortValuesDescending(getMessages(result))\n var dailyCombinedArray = combineKeysAndValues(dailyArrayKeys, dailyArrayValues)\n\n // Set data and labels\n var labels = Object.keys(dailyCombinedArray)\n var data = Object.values(dailyCombinedArray)\n\n document.getElementById('dailyTotalQuestions').innerHTML = ''\n\n // Create chart\n var canvas = document.getElementById('dailyQuestionsChart')\n var ctx = canvas.getContext('2d')\n\n var chart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Questions'\n },\n legend: {\n display: false\n },\n scales: {\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true,\n stepSize: 1\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}", "renderDistinctValues() {\n const values = this.props.data.values;\n const barChartData = values; // values.slice(0, Math.min(TOP_K, values.length));\n return (\n <div className=\"p-2\">\n {this.renderTitle()}\n {this.renderBarChart(barChartData)}\n {this.renderLabel('Distinct Values', values.length.toString())}\n </div>\n );\n }", "function getBarDataset(label, data){\n return [{\n label: label,\n fillColor: \"rgba(151,187,205,0.2)\",\n strokeColor: \"rgba(151,187,205,1)\",\n highlightFill: \"rgba(151,187,205,0.1)\",\n highlightStroke: \"rgba(151,187,205,1)\",\n data: data\n }];\n}", "function barChart(ndx) {\n var dim = ndx.dimension(dc.pluck('created'));\n var group = dim.group();\n \n dc.barChart(\"#bar-chart\")\n .width(350)\n .height(250)\n .margins({top: 30, right: 50, bottom: 45, left: 40})\n .dimension(dim)\n .group(group)\n .transitionDuration(1000)\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Customer created\")\n .yAxisLabel(\"# of customers\")\n .yAxis().ticks(10);\n}", "function separateIntoColumns() {\r\n let bottom = 170;\r\n d3.select(\"#text_container\").style(\"font-size\", \"0\");\r\n d3.select(\"#text-h1-\" + activePart).selectAll(\"span\").each(function() {\r\n let spanClass = d3.select(this).attr(\"class\").split(\"-\")\r\n if (spanClass[0] == \"topic\") {\r\n d3.select(this).style(\"width\", \"29%\")\r\n .style(\"position\", \"absolute\")\r\n .style(\"font-size\", \"1.6vw\")\r\n .style(\"top\", bottom + 'px');\r\n if (spanClass[1] == 1) {\r\n d3.select(this).transition().duration(\"3000\").style(\"left\", \"3%\");\r\n } else if (spanClass[1] == 2) {\r\n d3.select(this).transition().duration(\"3000\").style(\"left\", \"33%\");\r\n\r\n } else if (spanClass[1] == 3) {\r\n d3.select(this).transition().duration(\"3000\").style(\"left\", \"63%\");\r\n }\r\n }\r\n bottom = 70 + this.getBoundingClientRect().bottom + $(this).scrollTop();\r\n });\r\n\r\n d3.select(\"#column-controls\").html(\"\").style(\"display\", \"block\");\r\n topicMap.forEach(function(key, value) {\r\n let thisKey = key;\r\n d3.select(\"#column-controls\").append(\"span\")\r\n .style(\"left\", function(d,i) {\r\n if (thisKey == 1) {\r\n return \"10%\";\r\n } else if (thisKey == 2) {\r\n return \"40%\";\r\n } else if (thisKey == 3) {\r\n return \"70%\";\r\n }\r\n })\r\n .text(value.topic)\r\n .style(\"font-family\", \"Roboto\")\r\n .style(\"position\", 'absolute')\r\n .style(\"color\", \"black\")\r\n .style(\"font-size\", \"18px\");\r\n })\r\n //set back to static and no margin-left\r\n}", "function populateLeaderboardChart(leaderboard, id){\n let users = [],\n\tscores = [];\n for (i = 0; i < leaderboard.length; i++) {\n\tusers.push(leaderboard[i].name);\n\tscores.push(parseInt(leaderboard[i].score));\n }\n\n let con = $(`#${id}`).find(\".canvas-container\"),\n\tcanvas = $(`#${id}`).find(\"canvas\"),\n\tdata = {\n\t labels: users,\n\t datasets: getBarDataset(\"contribution\", scores)\n\t};\n let chart = drawBarChart(canvas, con, data);\n let highScore = scores.indexOf(Math.max.apply(Math, scores));\n highlightBar(chart.datasets[0].bars[highScore]);\n chart.update();\n}", "function assigneeReport() {\r\n selectedReport = \"Assignee\";\r\n\r\n prepareListOfAssignees();\r\n\r\n document.getElementById(\"assignee\").style.backgroundColor = \" #ebeaea\";\r\n document.getElementById(\"status\").style.backgroundColor = \"\";\r\n document.getElementById(\"severity\").style.backgroundColor = \"\";\r\n\r\n document.getElementById(\"right\").innerHTML = \"\";\r\n\r\n // here result is the object in which I am storing data regarding the number of bugs assigned to every individual \r\n let result = {};\r\n\r\n var issuesItem = JSON.parse(localStorage.getItem('bugs'));\r\n\r\n for (let i = 0; i < issuesItem.length; ++i) {\r\n if (!result[issuesItem[i].assignedTo]) {\r\n result[issuesItem[i].assignedTo] = 0;\r\n }\r\n ++result[issuesItem[i].assignedTo];\r\n }\r\n\r\n // now I will create individual object for every assignee-bugs data and then put it in the array named data\r\n var data = [];\r\n Object.entries(result).map(entry => {\r\n let obj = {\r\n x: entry[0],\r\n value: entry[1]\r\n }\r\n data.push(obj);\r\n });\r\n\r\n var chart;\r\n if (selectedChart == \"pie\") {\r\n chart = anychart.pie();\r\n\r\n chart.legend().position(\"right\");\r\n chart.legend().itemsLayout(\"vertical\");\r\n chart.sort(\"desc\");\r\n chart.labels().position(\"outside\");\r\n }\r\n else if (selectedChart == \"column\") {\r\n chart = anychart.column();\r\n chart.yAxis().title(\"Number of bugs\");\r\n\r\n chart.labels(true);\r\n chart.labels().format(\"{%x}\");\r\n chart.labels().rotation(-60);\r\n chart.labels().fontColor(\"Green\");\r\n chart.labels().fontWeight(900);\r\n }\r\n else {\r\n chart = anychart.bar();\r\n chart.yAxis().title(\"Number of bugs\");\r\n chart.labels(true);\r\n }\r\n\r\n chart.title(\"Number of bugs assigned to an INDIVIDUAL\");\r\n chart.data(data);\r\n chart.container(document.getElementById(\"right\"));\r\n chart.draw();\r\n}", "function createCharts(data) {\n\n // first row of charts\n [data.highestVotes, data.numOfTickets, data.ticketStatus].forEach((dataset, i) => {\n\n // selectors for charts canvas divs\n const ids = ['highestVotes', 'numOfTickets', 'ticketStatus'];\n\n // colors arrays\n const backgroundColorsArray = [];\n const borderColorsArray = [];\n\n // assign colors based on length of dataset\n for (let x in dataset) {\n backgroundColorsArray.push(colors[x] + '0.2)');\n borderColorsArray.push(colors[x] + '1)');\n }\n\n // set labels - either first choice or second\n let dataLabels = i < 2 ? ['Bugs', 'Features'] : ['Needs Help', 'In Progress', 'Resolved'];\n\n // 3 bar charts\n var ctx = document.getElementById(ids[i]).getContext('2d');\n var newChart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: dataLabels,\n datasets: [{\n label: 'No. of Tickets: ',\n data: dataset,\n backgroundColor: backgroundColorsArray,\n borderColor: borderColorsArray,\n borderWidth: 1\n }]\n },\n options: {\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n }\n }\n });\n });\n\n // second row of charts\n [data.highestBugs, data.highestFeatures, data.highestStatus].forEach((dataset, i) => {\n\n // selectors for charts canvas divs\n const ids = ['highestBugs', 'highestFeatures', 'highestStatus'];\n\n // colors arrays\n const backgroundColorsArray = [];\n const borderColorsArray = [];\n\n // assign colors based on length of dataset\n for (let x in dataset) {\n backgroundColorsArray.push(colors[x] + '0.2)');\n borderColorsArray.push(colors[x] + '1)');\n }\n\n // label and datasets\n let dataLabels = [];\n let datasetArray = [];\n\n // each dataset needs to be split into two\n // separate arrays of labels and values\n dataset.forEach(item => {\n dataLabels.push(`${item.title}`);\n datasetArray.push(item.votes);\n });\n\n // polar area charts\n var ctx = document.getElementById(ids[i]).getContext('2d');\n var newChart = new Chart(ctx, {\n type: 'polarArea',\n data: {\n labels: dataLabels,\n datasets: [{\n label: 'Status of Tickets',\n data: datasetArray,\n backgroundColor: backgroundColorsArray,\n borderColor: borderColorsArray,\n borderWidth: 1\n }]\n },\n options: {\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n }\n }\n });\n });\n}", "function monthlyMessagesChart (result) {\n // Get chart data\n function getMessagesByChannel (data, channelFilter) {\n const channels = {}\n\n data.forEach(item => {\n const channel = item.MessageChannel; const id = item.MessageID\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n channels[channel].push(id)\n }\n }\n })\n\n for (channel in channels) {\n channels[channel] = channels[channel].length\n }\n\n return channels\n };\n\n // Set data and labels\n var labels = Object.keys(getMessagesByChannel(result))\n var data = Object.values(getMessagesByChannel(result))\n var monthlyTotalMessages = sumArrayValues(getMessagesByChannel(result))\n document.getElementById('monthlyTotalMessages').innerHTML = monthlyTotalMessages\n\n // Create chart\n var ctx = document.getElementById('monthlyMessagesChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'doughnut',\n data: {\n labels: labels,\n datasets: [{\n label: 'Channels',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Messages by Channel'\n },\n legend: {\n position: 'bottom'\n },\n scales: {\n gridLines: {\n display: false\n }\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n }\n }\n }\n })\n}", "function drawBarChart(data, options, element) {\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create event classes from metadata
function decorateEvents(registry, metadata, metadataEvents) { // decorate the events metadata.asLatest.modules.filter((_ref) => { let { events } = _ref; return events.isSome; }).forEach((section, sectionIndex) => { const sectionName = (0, _util.stringCamelCase)(section.name.toString()); section.events.unwrap().forEach((meta, methodIndex) => { const methodName = meta.name.toString(); const eventIndex = new Uint8Array([sectionIndex, methodIndex]); const typeDef = meta.args.map(arg => (0, _getTypeDef.getTypeDef)(arg.toString())); let Types = []; try { Types = typeDef.map(typeDef => (0, _getTypeClass.getTypeClass)(registry, typeDef)); } catch (error) { console.error(error); } metadataEvents[eventIndex.toString()] = class extends _Event.EventData { constructor(registry, value) { super(registry, Types, value, typeDef, meta, sectionName, methodName); } }; }); }); } // create extrinsic mapping from metadata
[ "_createEvents(prefix, events) {\n for(let eventName in events) {\n events[eventName] = new Event(prefix + '_' + eventName, this);\n }\n }", "InstallEventClass(string, string, string, string) {\n\n }", "function createEvent(e) {\n\n let ev = {};\n ev.date_start = `${e.start.year}-${e.start.month.toString().padStart(2,'0')}-${e.start.day.toString().padStart(2,'0')}T`;\n ev.date_end = ev.date_start;\n ev.date_start += e.start.time;\n ev.date_end += e.end.time;\n\n let words = e.content.split('**'); \n// let words = e.content.slice(0,e.content.length - 1).split('**'); \n [ev.apogee, ev.acronym] = getIDs(words[0]);\n ev.isCourse = true;\n if (ev.acronym.indexOf('Evt::') !== -1) {\n ev.isCourse = false;\n [ev.year,ev.tracks] = getYearAndTracks(words[0]);\n }\n else {\n ev.year = (ev.acronym.substr(0,3) === \"S07\" || ev.acronym.substr(0,3) === \"S08\" ) ? 1 : 2;\n // HACK:console.log(ev.apogee);\n ev.tracks = calDB.courses[ev.apogee].tracks.substr(2,2);\n }\n ev.lecturer = getLecturer(words[1]);\n ev.type = getCourseType(words[2]);\n ev.location = getLocation(e.location);\n ev.title = getDescription(e.description);\n ev.ID = createCalendarID(ev);\n ev.group = words[3] || \"All\";\n return ev;\n}", "InstallMultipleEventClasses() {\n\n }", "function createEvent(event){\n\n\t// Event Object: Type, Subtype, Description, StartTimeDate, Freshness, Status, NumberOfNotification, Reliability\t \n\tvar eventObject = new Object();\n\n\t// Type & Subtype Event\n\teventObject.type = event.type.type.charAt(0).toUpperCase() + event.type.type.slice(1).replace(/_/g,\" \");\n\teventObject.subtype = event.type.subtype.charAt(0).toUpperCase() + event.type.subtype.slice(1).replace(/_/g,\" \");\n\n\t// Description Array\n\teventObject.description = event.description;\n\n\t// Start Time Date\n\tvar date = new Date(event.start_time*1000);\n\tvar day = date.getDate();\n\tvar month = date.getMonth();\n\tvar year = date.getFullYear();\n\tvar hours = date.getHours();\n\tvar minutes = date.getMinutes();\n\tvar seconds = date.getSeconds();\n\teventObject.startTime = day+'/'+month+'/'+year+'\\t'+ hours + ':' + minutes + ':' + seconds;\n\teventObject.startTimeUnformatted = parseFloat(event.start_time);\n\t\n\t// Freshness\n\teventObject.freshness = event.freshness;\n\n\t// Event Status\n\tvar status = event.status;\n\teventObject.status = status.charAt(0).toUpperCase() + status.slice(1);\n\tswitch (eventObject.status) {\n\t\tcase \"Open\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-success\">'+eventObject.status;\n\t\t\tbreak;\n\t\tcase \"Closed\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-danger\">'+eventObject.status;\n\t\t\tbreak;\n\t\tcase \"Skeptical\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-warning\">'+eventObject.status;\n\t\t\tbreak;\t\n\t}\n\n\t// Event reliability\n\teventObject.reliability = Math.round( parseFloat(event.reliability * 100)) + \"%\";\n\n\t// Number of Notification\n\teventObject.numNot = event.number_of_notifications;\n\n\t// Event coordinates\n\tif(eventObject.subtype != \"Coda\"){\n\t\teventObject.lat = middlePoint(event.locations).lat();\n\t\teventObject.lng = middlePoint(event.locations).lng();\n\t}\n\telse{\n\t\teventObject.lat = event.locations[0].lat;\n\t\teventObject.lng = event.locations[0].lng;\n\t}\n\t\t\n\t// Event ID\n\teventObject.eventID = event.event_id;\n\n\t// Event address\n\tif(event.route && event.street_number)\n\t\teventObject.address = event.route + \", \" + event.street_number;\n\telse if(event.route)\n\t\teventObject.address = event.route;\n\telse\n\t\teventObject.address = eventObject.lat + \", \" + eventObject.lng;\n\t\n\t// Add event to global Events Array\n\teventArray.push(eventObject);\n\t\n\t// Draw Queue\n\tif(eventObject.subtype.toLowerCase() == \"coda\" && !isiPad){\n\t\tdrawQueue(event);\n\t}\n\n\t// Add Event marker on map\n\taddEventMarker(eventObject);\n\n\t// Html description creation\n\tvar descriptionHtml = \"\";\n\tvar fullArray = checkArray(eventObject.description);\n\tif(fullArray){\n\t\tfor (j in eventObject.description){\n\t\t\tif(eventObject.description[j]){\n\t\t\t\teventObject.description[j] = eventObject.description[j].charAt(0).toUpperCase() + eventObject.description[j].slice(1);\n\t\t\t\tdescriptionHtml = descriptionHtml.concat('<li><p>'+eventObject.description[j]+'</p></li>');\n\t\t\t}\n\t\t}\t\n\t}\n\t\n\t// Add table row\t\t\t\n\t$('#modalBody').append('<tr id=\"'+eventObject.eventID+'tr\">\\\n\t\t\t\t\t\t<td>'+eventObject.type+' > '+eventObject.subtype+'</td>\\\n\t\t\t\t\t\t<td>'+eventObject.startTime+'</td>\\\n\t\t\t\t\t\t<td id='+eventObject.eventID+'>'+eventObject.address+'</td>\\\n\t\t\t\t\t\t<td><div class=\"btn-group\">\\\n\t\t\t\t\t\t\t<a href=\"#\" id=\"'+eventObject.eventID+'but\" class=\"btn btn-inverse dropdown-toggle\" data-toggle=\"dropdown\">Show</a>\\\n\t\t\t\t\t\t\t<ul class=\"dropdown-menu\">'+descriptionHtml+'</ul>\\\n\t\t\t\t\t\t</div></td>\\\n\t\t\t\t\t\t<td>'+eventObject.numNot+' / '+eventObject.reliability+'</td>\\\n\t\t\t\t\t\t<td>'+statusHtml+'</td>\\\n\t\t\t\t\t\t</tr>');\n\tvar butID = \"#\"+eventObject.eventID+\"but\";\t\t\t\n\tif(!fullArray)\n\t\t$(butID).addClass('disabled');\n}", "function create(config) {\n var obj = Object.create(eventedAttr);\n\n config = ( typeof config === 'object' ) ? config : null ;\n\n if (config !== null) {\n obj.initAttr(config);\n obj.initEmitter(config);\n }\n\n return obj;\n }", "function _createMetadata(prototype) {\n let basePrototype = Object.getPrototypeOf(prototype);\n\n let metadata = Object.create(Metadata).init();\n // manually copy properties from the prototypes metadata\n if (basePrototype._espDecoratorMetadata) {\n for (let e of basePrototype._espDecoratorMetadata._events) {\n metadata._events.push(e);\n }\n }\n // define an enumerable property on the constructors to hold the metadata.\n // It needs to be enumerable so TS extends can copy it accross.\n Object.defineProperty(prototype, '_espDecoratorMetadata', {\n value: metadata,\n // by default enumerable is false, I'm just being explicit here.\n // When Typescript derives from a base class it copies all own property to the new instance we don't want the metadata copied.\n // To stop it we set enumerable to false. You'd expect this to work using prototypical inheritance so you can override via the prototype chain.\n // Last I looked that's how babel worked.\n enumerable: false\n });\n return metadata;\n}", "function eventInfoPrepper(body){\n var event_id = (body.event_id) ? body.event_id : null;\n var user = (body.user_id) ? body.user_id : null;\n var start = (body.start_datetime) ? body.start_datetime : null;\n var end = (body.end_datetime) ? body.end_datetime : start;\n var title = (body.title) ? body.title : null;\n var notes = (body.notes) ? body.notes : null;\n var isFullDay = (body.isFullDay) ? body.isFullDay : false;\n var stop_date = (body.rep_stop_date) ? body.rep_stop_date : null;\n var day_month = (body.rep_day_month) ? body.rep_day_month : null;\n var day_week = (body.rep_day_week) ? body.rep_day_week : null;\n var event_type = (body.event_type) ? body.event_type : null;\n var amount = (body.amount) ? body.amount : 0;\n var job_id = (body.job_id) ? body.job_id : null;\n\n return {\n event_id : event_id,\n user : user,\n start : start,\n end : end,\n title : title,\n notes : notes,\n all_day : isFullDay,\n stop_date : stop_date,\n day_month : day_month,\n day_week : day_week,\n event_type : event_type,\n amount : amount,\n job_id : job_id\n };\n}", "function handleEventTypes() {\n var _this = this;\n\n this.allEventTypes = d3\n .set(\n this.initial_data.map(function(d) {\n return d[_this.config.event_col];\n })\n )\n .values()\n .sort();\n this.currentEventTypes = this.config.event_types || this.allEventTypes.slice();\n this.controls.config.inputs.find(function(input) {\n return input.description === 'Event Type';\n }).start = this.currentEventTypes;\n this.config.color_dom = this.currentEventTypes.concat(\n this.allEventTypes\n .filter(function(eventType) {\n return _this.currentEventTypes.indexOf(eventType) === -1;\n })\n .sort()\n );\n this.config.legend.order = this.config.color_dom.slice();\n }", "function createEventsFromRaw() {\n return new Promise((resolve, reject) => {\n const query = {};\n const sourceDbUrl = WILDFIRE_CONFIG.PRIMARY_MONGODB_URL;\n const sourceDbName = \"arcgis\";\n const sourceCollectionName = \"raw\";\n const outputDbUrl = WILDFIRE_CONFIG.PRIMARY_MONGODB_URL;\n const outputDbName = \"arcgis\";\n const outputCollectionName = \"events\";\n // Load each document from the \"raw\" collection\n loadSave(query, sourceDbUrl, sourceDbName, sourceCollectionName, outputDbUrl, outputDbName, outputCollectionName, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n }, (docs, cb) => {\n // Construct each event document from the response objects in the \"raw\" collection\n cb(null, docs.reduce((acc, obj) => {\n const rows = obj.features.map(f => f.attributes);\n return acc.concat(rows);\n }, []));\n });\n });\n}", "generateStubs() {\n this.classBuilder = ClassBuilder.fromDataObject(require(`./stubs-data/data_server.json`), typeHints);\n\n const events = require('./stubs-data/events_server.json');\n events.push(...require('./stubs-data/events_modules.json'));\n\n this.eventSystem = new EventSystem(this.classBuilder, events);\n }", "GetEventClassesForIID() {\n\n }", "function getDraggedElMeta(el) {\n var prefix = fc.dataAttrPrefix;\n var eventProps; // properties for creating the event, not related to date/time\n var startTime; // a Duration\n var duration;\n var stick;\n\n if (prefix) {\n prefix += '-';\n }\n eventProps = el.data(prefix + 'event') || null;\n\n if (eventProps) {\n if (typeof eventProps === 'object') {\n eventProps = $.extend({}, eventProps); // make a copy\n }\n else { // something like 1 or true. still signal event creation\n eventProps = {};\n }\n\n // pluck special-cased date/time properties\n startTime = eventProps.start;\n if (startTime == null) {\n startTime = eventProps.time;\n } // accept 'time' as well\n duration = eventProps.duration;\n stick = eventProps.stick;\n delete eventProps.start;\n delete eventProps.time;\n delete eventProps.duration;\n delete eventProps.stick;\n }\n\n // fallback to standalone attribute values for each of the date/time properties\n if (startTime == null) {\n startTime = el.data(prefix + 'start');\n }\n if (startTime == null) {\n startTime = el.data(prefix + 'time');\n } // accept 'time' as well\n if (duration == null) {\n duration = el.data(prefix + 'duration');\n }\n if (stick == null) {\n stick = el.data(prefix + 'stick');\n }\n\n // massage into correct data types\n startTime = startTime != null ? moment.duration(startTime) : null;\n duration = duration != null ? moment.duration(duration) : null;\n stick = Boolean(stick);\n\n return {eventProps: eventProps, startTime: startTime, duration: duration, stick: stick};\n }", "function makeEvent(item, refid) {\n var event = { 'refid': refid };\n event['etype'] = mapTag(item.tag);\n\n var tree = item.tree;\n for (i in tree) {\n var tag = tree[i].tag;\n var tag_lc = mapTag(tag);\n switch (tag) {\n case 'DATE':\n event['edate'] = formatDate(tree[i].data);\n case 'PLAC':\n event[tag_lc] = tree[i].data;\n break;\n case 'SOUR':\n if (typeof event[tag_lc] === 'undefined') {\n event[tag_lc] = [getSour(tree[i])];\n }\n else {\n event[tag_lc].push(getSour(tree[i]));\n }\n break;\n default:\n text = tag + \": \" + tree[i].data;\n if (typeof event.text === 'undefined') {\n event['text'] = text;\n }\n else {\n event['text'] += '; ' + text;\n }\n break;\n }\n }\n\n return event;\n}", "function _toZipkinAnnotations(events) {\n return events.map(event => ({\n timestamp: core_1.hrTimeToMicroseconds(event.time),\n value: event.name,\n }));\n}", "function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }", "function MeetupEvent(event) {\r\n this.link = event.link;\r\n this.name = event.name;\r\n this.creation_date = new Date(event.time).toString().slice(0, 15);\r\n this.host = event.group.name;\r\n this.created_at = Date.now();\r\n}", "function createEvent(req, res, next){\n //Take the request body... parse it and add the event to the db\n //Once done---> return next();\n}", "function buildEvent(eventType, contactsCache) {\n switch (eventType) {\n // creates the contact, adds it to the cache and return the event\n case 'new':\n var contact = createContact();\n contactsCache.push(contact);\n return {type: eventType, contact: contact};\n\n // randomly deletes a contact from the cache and wraps the deleted id in the event\n case 'delete':\n var contact = contactsCache.splice(Math.floor(Math.random() * contactsCache.length), 1)[0];\n return {type: eventType, contact: {id: contact.id}};\n\n // randomly selects a contact and updates it\n case 'patch':\n var contact = contactsCache[Math.floor(Math.random() * contactsCache.length)];\n var patches = patchContact(contact);\n return {type: eventType, patches: patches};\n\n // unmanaged event types stop the application\n default:\n throw new Error(eventType + ' event is not managed.');\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes styling on each search event
function removePreviousSearchStyles() { const allSvgs = document.querySelectorAll('.icon'); const allLinks = document.querySelectorAll('.social a'); // Restores SVG icons to their original styles allSvgs.forEach(svgIcon => { svgIcon.style.opacity = '1'; }); // Deletes the link text and href allLinks.forEach(link => { link.href = ''; link.innerText = ''; link.style.opacity = '1'; }); // Restores styles for items that are not links city.style.opacity = '1'; companyText.style.opacity = '1'; }
[ "function clearSearchResult() {\n if (current_mode !== mode.search) {\n console.log(\"Warning: request to clear search result when not in search mode.\");\n return;\n }\n path.classed(\"dimmed\", false);\n highlightSelectedLinks(false);\n selected_links = [];\n //displayConnections(false);\n displayInterParents(false);\n resetSearchResultsPanel();\n if (old_focused_source !== null) svg.select(\"#arc-\" + old_focused_source.key).classed(\"highlighted\", false);\n if (old_focused_target !== null) svg.select(\"#arc-\" + old_focused_target.key).classed(\"highlighted\", false);\n current_mode = mode.exploration;\n}", "function hideSearch() {\n\tstate.search = !state.search\n\t$(\"header, #results, #trees\").removeClass(\"search\")\n}", "function clearReadHighlighting() {\n $(\".show-read\").removeClass(\"show-read\");\n assembly.highlight_read_reg = \"\"\n}", "function removeStrainSearch() {\n const resultsContainer = document.querySelector('.results-container')\n while (resultsContainer.lastChild) {\n resultsContainer.removeChild(resultsContainer.lastChild)\n }\n}", "ClearSearch () {\n return { type: types.CLEAR_SEARCH }\n }", "function removeSearchField(event) {\n if (typeof event == 'undefined') {\n console.log(\"No event attached to remove search field!\");\n }\n hideSearchFieldError();\n $(event.target).parents(\".addsearchfielddiv\").remove();\n\n // If there are 3 .searchword elements left\n // then we're back to the original fields, hide reset!\n var numfields = $('.searchword').length;\n if (numfields == 3) {\n $(\"#resetsearch_tool\").hide();\n }\n }", "clearSourceSearch() {\n this.sourceQuery = '';\n this.sourceCategoryResults.length = 0;\n }", "function clear_searchstring()\r\n{\r\n control_sound_exit();\r\n control_canvas_status_search = 1;\r\n searchstring = \"\";\r\n search_sounds = false;\r\n search_images = false;\r\n performclear();\r\n drawControl();\r\n}", "function clearMainSearch() {\n document.getElementById(\"filter-recipe-input\").value = \"\"\n updateRecipeListDOM()\n}", "function destroy() {\n self.formSearch.off(\".zs\");\n }", "function clearNewsDiv() {\n // empties the previous search before we see the search boxes || buttons\n $(\".newsDiv\").empty();\n }", "function clearWriteHighlighting() {\n $(\".show-write\").removeClass(\"show-write\");\n assembly.highlight_write_reg = \"\";\n}", "stopSearching() {\n\t\tthis.liveCounter = this.livePandaUIStr.length + ((MySearchUI.searchGStats && MySearchUI.searchGStats.isSearchOn()) ? this.liveSearchUIStr.length : 0);\n\t\tif (this.timerUnique && this.liveCounter === 0) { if (MySearchTimer) MySearchTimer.deleteFromQueue(this.timerUnique); this.timerUnique = null; }\n\t}", "function clearSearchFilter()\r\n{\r\n\tinnerHTML=document.forms.itemfilter.elements['namesearch'].value = \"\";\r\n\t//innerHTML=document.forms.itemfilter.elements['goldsearch'].value = \"\";\r\n\tinnerHTML=document.forms.itemfilter.elements['recipeclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['auraclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['disassembleclear'].checked = true;\r\n\r\n\tfilterItems();\r\n\treturn;\r\n}", "function reset() {\n $(\"#searchInput\").empty();\n circle.setMap(null);\n}", "function clearHtml() {\n $(\"#searchChart\").remove();\n}", "function searchAgain() {\n $('#new-search').on('click', '#search-again', event => {\n $('#results').toggleClass('hidden');\n $('#form').removeClass('hidden');\n $('#new-search').toggleClass('hidden');\n\n\n\n })\n}", "function resetSearch() {\n\t$searchInput.value = \"\";\n\t$navbarSearchInput.value = \"\";\n\tsetInactiveSearch();\n}", "function clearHighlightsOnPage()\n{\n\tunhighlight(document.getElementsByTagName('body')[0]);\n\tcssstr = \"\";\n\tupdateStyleNode(cssstr);\n\tlastText = \"\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=> ByteArray stringToByteArray(DOMString string);
function stringToByteArray(string){ var byteArray = new Uint8Array(string.length); for(var i = 0; i < string.length; i++){ byteArray[i] = string[i].charCodeAt(0); } return byteArray; }
[ "function hex_str_to_byte_array(in_str) {\n var i\n var out = []\n var str = in_str.replace(/\\s|0x/g, \"\")\n for (i = 0; i < str.length; i += 2) {\n if (i + 1 > str.length) {\n out.push(get_dec_from_hexchar(str.charAt(i)) * 16)\n } else {\n out.push(\n get_dec_from_hexchar(str.charAt(i)) * 16 +\n get_dec_from_hexchar(str.charAt(i + 1))\n )\n }\n }\n return out\n }", "function toByteArray(data) {\n var bytes = [];\n var i;\n for (i = 0; i < data[0].length; ++i) {\n bytes.push(data[0].charCodeAt(i));\n }\n return bytes;\n}", "static bytes(v) { return new Typed(_gaurd, \"bytes\", v); }", "function StringToXML(txt) {\n\tif (window.DOMParser) {\n\t\t// code for Chrome, Firefox, Opera, etc.\n\t\tparser=new DOMParser();\n\t\txml=parser.parseFromString(txt,\"text/xml\");\n\t} else {\n\t\t// code for IE\n\t\txml=new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\txml.async=false;\n\t\txml.loadXML(txt); \n\t};\n\treturn xml;\n}", "function toByteArray(termObj) {\n // note: if we forget new here, we get:\n // TypeError: this.$set is not a function\n const term = new proto.Par(termObj);\n\n const buf = term.toBuffer();\n return buf;\n }", "function getBinary(file) {\n let xhr = new XMLHttpRequest();\n xhr.open(\"GET\", file, false);\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\n xhr.send(null);\n return xhr.responseText;\n}", "static bytes8(v) { return b(v, 8); }", "function decode (string) {\n\n var body = Buffer.from(string, 'base64').toString('utf8')\n return JSON.parse(body)\n}", "function buildDom(htmlString) {\r\n const div = document.createElement(\"div\");\r\n div.innerHTML = htmlString;\r\n return div.children[0];\r\n}", "function toBytes(amount) {\r\n\tamount = amount.split(' ');\r\n\tvar bytes = amount[0];\r\n\r\n\tif ( amount[1] == \"KB\" ) bytes = amount[0] * KB;\r\n\t\telse if ( amount[1] == \"MB\" ) bytes = amount[0] * MB;\r\n\t\telse if ( amount[1] == \"GB\" ) bytes = amount[0] * GB;\r\n\t\telse if ( amount[1] == \"TB\" ) bytes = amount[0] * TB;\r\n\t\telse if ( amount[1] == \"PB\" ) bytes = amount[0] * PB;\r\n\r\n\treturn bytes;\r\n}", "function hex_to_bin(uuid) {\n var hex = uuid.replace(/[\\-{}]/g, '');\n var buff_len = hex.length/2;\n var bb = new ByteBuffer(buff_len);\n for (var i = 0; i < hex.length; i += 2)\n { // Convert each character to a bit\n bb.writeUint8(parseInt(hex.charAt(i) + hex.charAt(i + 1), 16));\n }\n bb.flip();\n return bb;\n}", "function data_enc( string ) {\n\n //ZIH - works, seems to be the fastest, and doesn't bloat too bad\n return 'utf8,' + string\n .replace( /%/g, '%25' )\n .replace( /&/g, '%26' )\n .replace( /#/g, '%23' )\n //.replace( /\"/g, '%22' )\n .replace( /'/g, '%27' );\n\n //ZIH - works, but it's bloaty\n //return 'utf8,' + encodeURIComponent( string );\n\n //ZIH - works, but it's laggy\n //return 'base64,' + window.btoa( string );\n}", "function completeBinary(str) {\n\tlet a = str;\n\twhile (a.length % 8 !== 0) {\n\t\ta = \"0\" + a;\n\t}\n\treturn a;\n}", "function bytesToUint8Array(arr) {\n var l = arr.length;\n var res = new Uint8Array(l);\n for (var i = 0; i < l; i++) {\n res[i] = arr[i];\n }\n return res;\n }", "static bytes2(v) { return b(v, 2); }", "function array2bigint(bytes)\n{\n\tlet hex;\n\n\tif (typeof(bytes) == \"string\")\n\t{\n\t\thex = bytes\n\t\t.split('')\n\t\t.map( c => ('00' + c.charCodeAt(0).toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\tif (typeof(bytes) == \"object\")\n\t{\n\t\thex = Array.from(bytes)\n\t\t.map( c => ('00' + c.toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\t{\n\t\tconsole.log('ERROR', bytes);\n\t}\n\n\tif (hex.length == 0)\n\t{\n\t\tconsole.log(\"ERROR: empty hex string?\", typeof(bytes), bytes);\n\t\thex = \"00\";\n\t}\n\n\tlet bi = BigInt(\"0x\" + hex);\n\t//console.log(bytes, bi);\n\treturn bi;\n}", "function hex2base64(s){ return Crypto.util.bytesToBase64(hex2bytes(s)) }", "function fromBytes(bytes) {\r\n\tvar buffer = bytes;\r\n\tvar units = 'B';\r\n\r\n\tif ( Math.abs(bytes) >= PB ) {\r\n\t buffer = bytes/PB;\r\n\t units = \"PB\";\r\n\t} else if ( Math.abs(bytes) >= TB ) {\r\n\t buffer = bytes/TB;\r\n\t units = \"TB\";\r\n\t} else if ( Math.abs(bytes) >= GB ) {\r\n\t buffer = bytes/GB;\r\n\t units = \"GB\";\r\n\t} else if ( Math.abs(bytes) >= MB ) {\r\n\t buffer = bytes/MB;\r\n\t units = \"MB\";\r\n\t} else if ( Math.abs(bytes) >= KB ) {\r\n\t buffer = bytes/KB;\r\n\t units = \"KB\";\r\n\t}\r\n \r\n\treturn buffer.toFixed(2) + ' ' + units;\r\n}", "function DOMToString(doc) {\n\tvar xml = null;\n\ttry {\n\t\t//Most modern browsers\n\t\tvar ser = new XMLSerializer();\n\t\txml = ser.serializeToString(doc);\n\t} catch (e) {\n\t\t//Older IE\n\t\txml = doc.xml;\n\t}\n\t\n\treturn xml;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hide links for any toolspecific sections that are not present
function hideSwitcherLinks (detectedTools) { Array.from(document.querySelectorAll('a.tool-switcher')) .forEach(link => { if (detectedTools.includes(link.dataset.tool)) return link.style.display = 'none' }) }
[ "function hideSectionsBasedOnPermission(){\n currentUserPermission = currentLoggedInUser.privilege;\n $('.permission-link').hide(); //Hide all navigation links by default\n $('.permission-link').each(function(){ //Show proper sections based on the permission\n if($(this).hasClass('perm-'+currentUserPermission)){\n $(this).show();\n }\n });\n}", "function _disableSection() {\n\n for (var a in __disableSection) {\n if (__disableSection[a]) {\n var id = '#' + a;\n $(id).remove();\n $('.menu-icon').find('a[href=\"'+id+'\"]').parent().remove();\n }\n }\n\n }", "function ViewerToolsHide() {\r\n if( G.VOM.viewerDisplayed ) {\r\n G.VOM.toolbarsDisplayed=false;\r\n ViewerToolsOpacity(0);\r\n }\r\n }", "function disableEditLink() {\n if ( mw.config.get('wgNamespaceNumber') !== 110 && mw.config.get('wgNamespaceNumber') % 2 !== 1 ) { return; }\n var skin = mw.config.get('skin');\n if ( ( skin !== 'oasis' && skin !== 'monaco' && skin !== 'monobook' ) || // might be unnecessary, other skins haven't been checked\n $.inArray( 'sysop', mw.config.get('wgUserGroups') ) > -1 || // disable completely for admins\n typeof enableOldForumEdit !== 'undefined' ||\n !$('#archived-edit-link')[0] ) { return; }\n\n var editLink = ( skin === 'oasis' || skin === 'monaco' ) ? $('#ca-edit') : $('#ca-edit a');\n if ( !editLink[0] ) { return; }\n\n editLink.html('Archived').removeAttr('href').removeAttr('title').css({'color':'gray','cursor':'auto'});\n\n $('span.editsection-upper').remove();\n\n}", "takeOverLinks() {\n delegate(window.document, \"click\", \"a\", event => {\n if (\n event.button !== 0 ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n const link = event.target.closest(\"a\");\n if (\n link.getAttribute(\"href\").charAt(0) === \"#\" ||\n link.host !== window.location.host\n ) {\n return;\n }\n\n if (\n !event.defaultPrevented &&\n !link.hasAttribute(\"data-remote\") &&\n link.protocol.indexOf(\"http\") === 0\n ) {\n event.preventDefault();\n\n // update sidebar links\n if (link.closest(\"aside\")) {\n this.navigate(updateURL(link.href));\n } else {\n this.navigate(link.href);\n }\n }\n });\n }", "function hideFilterLinkIcon() {\n\tvar element = document.querySelector(\"#filter-link\");\n\tif (element) {\n\t\telement.style.display = \"none\";\n\t}\n\t// also deactivate the filter in the toolbar\n\tdetachGlobalFilter();\n}", "function subtest_other_lang_link_hides(w) {\n wait_for_provider_list_loaded(w);\n wait_for_element_invisible(w, \"otherLangDesc\");\n}", "function hideRuleBocks() {\n $(\"#ruleBlock1\").hide();\n $(\"#ruleBlock2\").hide();\n $(\"#ruleBlock3\").hide();\n}", "function hideAllPageTooltips() {\r\n $('[data-toggle=\"tooltip\"]').tooltip('hide');\r\n}", "function unNewsEditLinkChecker() {\n\tif( wgPageName != 'UnNews:Main_Page' || wgIsLogin ) {\n\t\treturn;\n\t}\n\n\teditlinks = document.getElementsByTagName( 'span' );\n\tfor( i = 0; i < editlinks.length; i++ ) {\n\t\tif( editlinks[i].className != 'editor' ) {\n\t\t\tcontinue;\n\t\t}\n\t\teditlinks[i].parentNode.removeChild( editlinks[i] );\n\t}\n}", "function hideBrowserTemplatesInUse()\n{\n templates.forEach(function(element)\n {\n var allowDuplicateVersions = false;//element.duplicate_versions;\n if(allowDuplicateVersions==false)\n {\n var id = element.id;\n if ($(\".\"+id).length > 0)\n {\n $(\"#\"+id).hide();\n }\n }\n });\n}", "function enableLinks() {\n var show = document.getElementsByClassName(\"show\");\n let match = false;\n for (const link of show) {\n match = false;\n enabledLinks.forEach(enabled => {\n if (link.id == enabled) {\n match = true;\n link.style.display = 'block';\n } else if (!match) {\n link.style.display = 'none';\n }\n })\n };\n}", "function hideAllContextMenus() {\n hideContextMenu(ToolbarElement.color_menu(), ToolbarElement.color_toggle()); // hide color menu\n hideContextMenu(ToolbarElement.paragraph_menu(), ToolbarElement.paragraph_toggle()); // hide paragraph menu\n }", "function mapProgrameList() {\n\t\t$('.page-nepad-on-the-continent .view-map-program-list li a').each(function(){\n\t\t\tif($(this).text().length==0){\n\t\t\t $(this).parent().hide();\t\n\t\t\t}\n\t\t});\n\t\t$('#mapsvg svg path').click(function(){\n\t\t\t$('.page-nepad-on-the-continent .view-map-program-list li a').each(function(){\n\t\t\t\tif($(this).text().length==0){\n\t\t\t\t\t$(this).parent().hide();\t\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function ensureLinksHaveTargetInApiIntro() {\n $(\"#intro a\").attr('target', function(i, current) {\n return current || '_self';\n });\n }", "listenDisableMainNavLinks() {\n const links = h.getMainNavLinks();\n _.each(links, link => {\n // Add listener to deactivate main nav\n link.removeEventListener('click', view.mainNavControl);\n // Remove listener to disable main nav\n link.addEventListener('click', view.disableNav, false);\n });\n }", "function hide_important_elements(){\n\tdocument.getElementById('segment_middle_part').style.display\t= \"none\";\n\tdocument.getElementById('groupe_add_container').style.display\t= \"none\";\n\tdocument.getElementById('segment_send_part').style.display\t= \"none\";\n}", "function showAtag() {\n $item.find('a').filter(function (idx) {\n return !$(this).data('rolling');\n }).css('visibility', 'visible');\n }", "function hideEnhancedURLBar() {\n if (ctrlMouseHover)\n return;\n async(function() {\n ctrlMouseHover = true;\n }, 200);\n setOpacity(1);\n enhancedURLBar.style.display = \"none\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
builds out the axes labels
function buildAxesLabels() { vis.axes .data(vis.allAxis).enter() .append("svg:text").classed("axis-labels", true) .text(function(d) { return d; }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return config.w / 2 * (1 - 1.3 * Math.sin(i * config.radians / vis.totalAxes)); }) .attr("y", function(d, i) { return config.h / 2 * (1 - 1.1 * Math.cos(i * config.radians / vis.totalAxes)); }) .attr("font-family", "sans-serif") .attr("font-size", 11 * config.labelScale + "px"); }
[ "function createXAxisLabels(labels, names)\n{\n let x = 0;\n let y = 20;\n let i = 0;\n\n names.forEach(name => \n {\n xLabels[i] = labels.append(\"text\")\n .attr(\"y\", y)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"value\", name) // value to grab for event listener\n .classed(name === chosenXAxis ? \"active\" : \"inactive\", true)\n .text(xAxisText[i]);\n y += 20;\n i += 1;\n });\n return labels;\n}", "function createYAxisLabels(labels, names)\n{\n let x = 0;\n let y = 0;\n let i = 0;\n\n names.forEach(name => \n {\n yLabels[i] = labels.append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", y - margin.left)\n .attr(\"x\", 0 - (height / 2))\n .attr(\"text-anchor\", \"middle\")\n .attr(\"dy\", \"1em\")\n .classed(name === chosenYAxis ? \"active\" : \"inactive\", true)\n .attr(\"value\",name)\n .text(yAxisText[i]);\n\n y += 20;\n i += 1;\n });\n return labels;\n}", "function draw_labels() { \n //Calculate some of the mid and endpoints of lines to get rough positions for the labels\n var bottomThetaX = ((inverseWavelength/6) + 6) * Math.cos(degToRad(0.5 * theta))\n var bottomThetaY = ((inverseWavelength/6) + 6) * Math.sin(degToRad(0.5 * theta))\n var topThetaX = ((inverseWavelength/6) + 8) * Math.cos(degToRad(1.5 * theta))\n var topThetaY = ((inverseWavelength/6) + 8) * Math.sin(degToRad(1.5 * theta))\n var dX = (inverseD/2) * Math.cos(radians_90)\n var dY = (inverseD/2) * Math.sin(radians_90)\n\n ctxe.beginPath()\n ctxe.font = \"12px Verdana\" //Can change font here\n ctxe.fillText(\"A\", EW_CENTER_POINT.x, EW_CENTER_POINT.y + 15)\n ctxe.fillText(\"O\", EW_CENTER_POINT.x + inverseWavelength + 10, EW_CENTER_POINT.y + 6)\n ctxe.fillText(\"1/λ\", EW_CENTER_POINT.x - (inverseWavelength/2) - 5, EW_CENTER_POINT.y + 15)\n canvas_arrow(ctxe,EW_CENTER_POINT.x - (inverseWavelength/2) - 5, EW_CENTER_POINT.y + 9, EW_CENTER_POINT.x - inverseWavelength + 5, EW_CENTER_POINT.y + 9)\n canvas_arrow(ctxe,EW_CENTER_POINT.x - (inverseWavelength/2) + 15, EW_CENTER_POINT.y + 9, EW_CENTER_POINT.x - 5, EW_CENTER_POINT.y + 9)\n ctxe.fillText(\"θ\", EW_CENTER_POINT.x + bottomThetaX, EW_CENTER_POINT.y - bottomThetaY + 5)\n ctxe.fillText(\"θ\", EW_CENTER_POINT.x + topThetaX, EW_CENTER_POINT.y - topThetaY )\n ctxe.fillText(\"d*ₕₖₗ\", EW_CENTER_POINT.x + inverseWavelength - dX - 30, EW_CENTER_POINT.y - dY)\n ctxe.stroke()\n }", "function drawAxisLabelMarkers(arrData) {\n context.lineWidth = \"2.0\";\n // draw y axis\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace, cMargin);\n // draw x axis\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace + cWidth, cMarginHeight);\n context.lineWidth = \"1.0\";\n drawMarkers(arrData);\n}", "function _drawDiagramLabels(paper, label)\n{\n // main label on the top\n paper.text(10, 26, label).attr({\"text-anchor\": \"start\", \"font-size\": \"12px\", \"font-family\": \"sans-serif\"});\n\n // label for y-axis\n var yAxis = paper.text(-27, 100, \"# Mutations\").attr({\"text-anchor\": \"start\", \"font-size\": \"12px\", \"font-family\": \"sans-serif\"});\n yAxis.rotate(270);\n}", "function drawDayLabels() {\n const dayLabelsGroup = svg.select('.day-labels-group');\n const arrayForYAxisLabels = yAxisLabels || daysHuman;\n\n dayLabels = svg.select('.day-labels-group').selectAll('.day-label')\n .data(arrayForYAxisLabels);\n\n dayLabels.enter()\n .append('text')\n .text((label) => label)\n .attr('x', 0)\n .attr('y', (d, i) => i * boxSize)\n .style('text-anchor', 'start')\n .style('dominant-baseline', 'central')\n .attr('class', 'day-label');\n\n dayLabelsGroup.attr('transform', `translate(-${dayLabelWidth}, ${boxSize / 2})`);\n }", "function renderLabels(stateLabels, newXScale, chosenXaxis, newYScale, chosenYAxis) {\n \n stateLabels.transition()\n .duration(1000)\n .attr(\"x\", d => newXScale(d[chosenXAxis]))\n .attr('y', d => newYScale(d[chosenYAxis])+4);\n\n return stateLabels;\n}", "drawChromosomeLabels() {\n var ideo = this;\n\n var chromosomeLabelClass = ideo._layout.getChromosomeLabelClass();\n\n var chrSetLabelXPosition = ideo._layout.getChromosomeSetLabelXPosition();\n var chrSetLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes set's labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .append('text')\n .data(ideo.chromosomesArray)\n .attr('class', 'chromosome-set-label ' + chromosomeLabelClass)\n .attr('transform', chrSetLabelTranslate)\n .attr('x', chrSetLabelXPosition)\n .attr('y', function(d, i) {\n return ideo._layout.getChromosomeSetLabelYPosition(i);\n })\n .attr('text-anchor', ideo._layout.getChromosomeSetLabelAnchor())\n .each(function(d, i) {\n // Get label lines\n var lines;\n if (d.name.indexOf(' ') === -1) {\n lines = [d.name];\n } else {\n lines = d.name.match(/^(.*)\\s+([^\\s]+)$/).slice(1).reverse();\n }\n\n if (\n 'sex' in ideo.config &&\n ideo.config.ploidy === 2 &&\n i === ideo.sexChromosomes.index\n ) {\n if (ideo.config.sex === 'male') {\n lines = ['XY'];\n } else {\n lines = ['XX'];\n }\n }\n\n // Render label lines\n d3.select(this).selectAll('tspan')\n .data(lines)\n .enter()\n .append('tspan')\n .attr('dy', function(d, i) {\n return i * -1.2 + 'em';\n })\n .attr('x', ideo._layout.getChromosomeSetLabelXPosition())\n .attr('class', function(a, i) {\n var fullLabels = ideo.config.fullChromosomeLabels;\n return i === 1 && fullLabels ? 'italic' : null;\n }).text(String);\n });\n\n var setLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .each(function(a, chrSetNumber) {\n d3.select(this).selectAll('.chromosome')\n .append('text')\n .attr('class', 'chrLabel')\n .attr('transform', setLabelTranslate)\n .attr('x', function(d, i) {\n return ideo._layout.getChromosomeLabelXPosition(i);\n }).attr('y', function(d, i) {\n return ideo._layout.getChromosomeLabelYPosition(i);\n }).text(function(d, chrNumber) {\n return ideo._ploidy.getAncestor(chrSetNumber, chrNumber);\n }).attr('text-anchor', 'middle');\n });\n }", "function updateLabelsText(xy, xPos, labelsText) {\n // setup chosenAxis by xy\n var chosenAxis = (xy === \"x\") ? chosenXAxis : chosenYAxis;\n // change text tag\n var enterlabelsText = null; labelsText.enter()\n .append(\"text\");\n // change text tag\n enterlabelsText = labelsText.enter()\n .append(\"text\")\n .merge(labelsText)\n .attr(\"x\", xPos)\n .attr(\"y\", (d,i) => (i+1)*axisPadding)\n .attr(\"value\", d => d) // value to grab for event listener\n .classed(\"active\", d => (d === chosenAxis) ? true:false)\n .classed(\"inactive\", d => (d === chosenAxis) ? false:true)\n .text(d => labelsTitle[d])\n .on(\"click\", updateChart);\n}", "createYTicks() {\n var labelsArray = [];\n for (let i = this.yDomainArray[0]; i <= this.yDomainArray[1]; i += this.yStep) {\n labelsArray.push(this.roundFloat(i));\n }\n this.yTicksArray = labelsArray;\n }", "function setLabelPosition() {\r\n if (document.getElementById(\"rb1\").checked) {\r\n chart.labelRadius = 30;\r\n chart.labelText = \"[[title]]: [[value]]\";\r\n } else {\r\n chart.labelRadius = -30;\r\n chart.labelText = \"[[percents]]%\";\r\n }\r\n chart.validateNow();\r\n }", "function buildLabels() {\n var shown = [];\n for (var n = 0; n < graphPath.nodes.length; n++) {\n // if type not placeholder, add to shown\n if (graphPath.nodes[n].type != \"placeholder\") {\n shown.push(graphPath.nodes[n].group);\n }\n }\n return shown;\n}", "function hiLiteLabel(axis, clicked){\r\n d3.selectAll(\".aText\")\r\n .filter(\".\" + axis)\r\n .filter(\".active\")\r\n .classed(\"inactive\", true)\r\n \r\n clicked.classed(\"inactive\", false).classed(\"active\", true);\r\n}", "addXAxis(ypos, label) {\n\t\tthis.image.drawLine(this.left, ypos, this.right, ypos, BLACK);\n\t\tif (label) {\n\t\t\t// draw the x-axis label\n\t\t\tthis.addText(label, 16, this.left, ypos + 8, this.width, this.padding - 8);\n\t\t}\n\t}", "drawBandLabels(chromosomes) {\n var i, chr, chrs, taxid, ideo, chrModel, chrIndex, textOffsets;\n\n ideo = this;\n\n chrs = [];\n\n for (taxid in chromosomes) {\n for (chr in chromosomes[taxid]) {\n chrs.push(chromosomes[taxid][chr]);\n }\n }\n\n textOffsets = {};\n\n chrIndex = 0;\n for (i = 0; i < chrs.length; i++) {\n chrIndex += 1;\n\n chrModel = chrs[i];\n\n chr = d3.select(ideo.selector + ' #' + chrModel.id);\n\n // var chrMargin = this.config.chrMargin * chrIndex,\n // lineY1, lineY2;\n //\n // lineY1 = chrMargin;\n // lineY2 = chrMargin - 8;\n //\n // if (\n // chrIndex === 1 &&\n // \"perspective\" in this.config && this.config.perspective === \"comparative\"\n // ) {\n // lineY1 += 18;\n // lineY2 += 18;\n // }\n\n textOffsets[chrModel.id] = [];\n\n chr.selectAll('text')\n .data(chrModel.bands)\n .enter()\n .append('g')\n .attr('class', function(d, i) {\n return 'bandLabel bsbsl-' + i;\n })\n .attr('transform', function(d) {\n var transform = ideo._layout.getChromosomeBandLabelTranslate(d, i);\n\n var x = transform.x;\n // var y = transform.y;\n\n textOffsets[chrModel.id].push(x + 13);\n\n return transform.translate;\n })\n .append('text')\n .attr('text-anchor', ideo._layout.getChromosomeBandLabelAnchor(i))\n .text(function(d) {\n return d.name;\n });\n\n // var adapter = ModelAdapter.getInstance(ideo.chromosomesArray[i]);\n // var view = Chromosome.getInstance(adapter, ideo.config, ideo);\n\n chr.selectAll('line.bandLabelStalk')\n .data(chrModel.bands)\n .enter()\n .append('g')\n .attr('class', function(d, i) {\n return 'bandLabelStalk bsbsl-' + i;\n })\n .attr('transform', function(d) {\n var x, y;\n\n x = ideo.round(d.px.start + d.px.width / 2);\n\n textOffsets[chrModel.id].push(x + 13);\n y = -10;\n\n return 'translate(' + x + ',' + y + ')';\n })\n .append('line')\n .attr('x1', 0)\n .attr('y1', function() {\n return ideo._layout.getChromosomeBandTickY1(i);\n })\n .attr('x2', 0)\n .attr('y2', function() {\n return ideo._layout.getChromosomeBandTickY2(i);\n });\n }\n\n for (i = 0; i < chrs.length; i++) {\n chrModel = chrs[i];\n\n var textsLength = textOffsets[chrModel.id].length,\n overlappingLabelXRight,\n index,\n indexesToShow = [],\n prevHiddenBoxIndex,\n xLeft,\n prevLabelXRight,\n prevTextBoxLeft,\n prevTextBoxWidth,\n textPadding;\n\n overlappingLabelXRight = 0;\n\n textPadding = 5;\n\n for (index = 0; index < textsLength; index++) {\n // Ensures band labels don't overlap\n\n xLeft = textOffsets[chrModel.id][index];\n\n if (xLeft < overlappingLabelXRight + textPadding === false) {\n indexesToShow.push(index);\n } else {\n prevHiddenBoxIndex = index;\n overlappingLabelXRight = prevLabelXRight;\n continue;\n }\n\n if (prevHiddenBoxIndex !== index) {\n // This getBoundingClientRect() forces Chrome's\n // 'Recalculate Style' and 'Layout', which takes 30-40 ms on Chrome.\n // TODO: This forced synchronous layout would be nice to eliminate.\n // prevTextBox = texts[index].getBoundingClientRect();\n // prevLabelXRight = prevTextBox.left + prevTextBox.width;\n\n // TODO: Account for number of characters in prevTextBoxWidth,\n // maybe also zoom.\n prevTextBoxLeft = textOffsets[chrModel.id][index];\n prevTextBoxWidth = 36;\n\n prevLabelXRight = prevTextBoxLeft + prevTextBoxWidth;\n }\n\n if (\n xLeft < prevLabelXRight + textPadding\n ) {\n prevHiddenBoxIndex = index;\n overlappingLabelXRight = prevLabelXRight;\n } else {\n indexesToShow.push(index);\n }\n }\n\n var selectorsToShow = [],\n ithLength = indexesToShow.length,\n j;\n\n for (j = 0; j < ithLength; j++) {\n index = indexesToShow[j];\n selectorsToShow.push('#' + chrModel.id + ' .bsbsl-' + index);\n }\n\n this.bandsToShow = this.bandsToShow.concat(selectorsToShow);\n }\n }", "function createAxes(rows, cols) {\n var axes = document.createElementNS(svgNs, 'g');\n axes.setAttribute('id', 'vis-axes')\n \n //y-axis - rows\n for (var i = 0; i < rows; i++) {\n //calc placement\n var xLoc = 0; //constant\n var yLoc = i * rectSize;\n var label = document.createElementNS(svgNs, \"text\")\n var labelNum = rows - i;\n label.innerHTML = labelNum;\n var xTextAdditional = calcDigitPadding(labelNum);\n label.setAttribute('class', 'label');\n label.setAttribute('x', xLoc + xTextAdditional);\n label.setAttribute('y', yLoc + fontSize + outlineWidth);\n axes.appendChild(label);\n }\n\n //x-axis - cols\n for (var i = 0; i < cols ; i++) {\n //calc placement\n var xLoc = i * rectSize;\n var yLoc = (rows - 1) * rectSize; //constant\n var label = document.createElementNS(svgNs, \"text\")\n var labelNum = cols - i;\n label.innerHTML = labelNum;\n label.setAttribute('class', 'label');\n var xTextAdditional = calcDigitPadding(labelNum);\n label.setAttribute('x', xLoc + axisWidth + xTextAdditional);\n label.setAttribute('y', yLoc + fontSize + axisHeight);\n axes.appendChild(label);\n }\n return axes;\n}", "function placeDataLabels() {\n this.points.forEach(function (point) {\n var dataLabel = point.dataLabel, _pos;\n if (dataLabel && point.visible) {\n _pos = dataLabel._pos;\n if (_pos) {\n // Shorten data labels with ellipsis if they still overflow\n // after the pie has reached minSize (#223).\n if (dataLabel.sideOverflow) {\n dataLabel._attr.width =\n Math.max(dataLabel.getBBox().width -\n dataLabel.sideOverflow, 0);\n dataLabel.css({\n width: dataLabel._attr.width + 'px',\n textOverflow: ((this.options.dataLabels.style || {})\n .textOverflow ||\n 'ellipsis')\n });\n dataLabel.shortened = true;\n }\n dataLabel.attr(dataLabel._attr);\n dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);\n dataLabel.moved = true;\n }\n else if (dataLabel) {\n dataLabel.attr({ y: -9999 });\n }\n }\n // Clear for update\n delete point.distributeBox;\n }, this);\n }", "labeled() {\n return getLabels(this.grid);\n }", "function createFormControlLabels() {\n let sectionLabels = [\n 'arts', 'automobiles', 'books', 'business', 'fashion', 'food', 'health', 'home', 'insider', 'magazine', \n 'movies', 'ny region', 'obituaries', 'opinion', 'politics', 'real estate', 'science', 'sports', 'sunday review', \n 'technology', 'theater', 't-magazine', 'travel', 'upshot', 'us', 'world'\n ]\n\n const sectionValues = sectionLabels.map(section => {\n const sectionArr = section.split(' ');\n if (sectionArr.length > 1) {\n section = sectionArr.join('');\n console.log('joining section:', section);\n }\n return section;\n })\n\n /** capitalize each word in selction lables */\n sectionLabels = sectionLabels.map( section => {\n // debugger;\n section = section.split(' ');\n let updatedSection = section.map( item => {\n let firstLetter = item.charAt(0).toUpperCase();\n let remainder = item.slice(1);\n item = firstLetter + remainder;\n return item;\n })\n updatedSection = updatedSection.join(' ');\n return updatedSection;\n })\n\n /** Creating the form labels */\n const formLabels = sectionValues.map( (section, index) => (\n <FormControlLabel\n key={section}\n value={section}\n control={<Radio />}\n label={sectionLabels[index]}\n />\n ))\n\n return formLabels;\n }", "function plotLabels(points, element){\n\tfor(let i=0;i<points.length;i++){\n\t\tpoints[i].label = element.text(`${i}`).font({fill:'black', weight:'bold'});\n\t\tpoints[i].label.move(points[i]['X']+5, points[i]['Y'])\n\t}\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the `ngInjectorDef` type in a way which is immune to accidentally reading inherited value.
function getInjectorDef(type) { return type && type.hasOwnProperty(NG_INJECTOR_DEF) ? type[NG_INJECTOR_DEF] : null; }
[ "getInjectable(name) {\n const node = this.injects[name] || null;\n if (node !== null) {\n return node instanceof Node ? node : this.newNode(node);\n }\n return MISSING_NODE;\n }", "loadIntoExistingLocation(type:Type, location:ElementRef, injector:Injector = null):Promise<ComponentRef> {\n this._assertTypeIsComponent(type);\n var annotation = this._directiveMetadataReader.read(type).annotation;\n var componentBinding = DirectiveBinding.createFromType(type, annotation);\n\n return this._compiler.compile(type).then(componentProtoView => {\n var componentView = this._viewFactory.getView(componentProtoView);\n this._viewHydrator.hydrateDynamicComponentView(\n location, componentView, componentBinding, injector);\n\n var dispose = () => {throw new BaseException(\"Not implemented\");};\n return new ComponentRef(location, location.elementInjector.getDynamicallyLoadedComponent(), componentView, dispose);\n });\n }", "get injector() {\n return this._injector;\n }", "static define() {\n return new AnnotationType()\n }", "static createInjector(settings = {}) {\n const injector = new InjectorService_1.InjectorService();\n injector.logger = logger_1.$log;\n // @ts-ignore\n injector.settings.set(DITest.configure(settings));\n setLoggerLevel_1.setLoggerLevel(injector);\n return injector;\n }", "annotation(type) {\n for (let ann of this.annotations) if (ann.type == type) return ann.value\n return undefined\n }", "function inferDefinitionFromAnnotation(\n annotations\n ) {\n return [...getAnnotationMap(annotations).values()].map(\n (a) => a.definition\n )\n } // CONCATENATED MODULE: ./src/lib/Editor/API/patchConfiguration/AttributeConfigurationGenerator/fillInferDefinitionFromAnnotation/index.js", "_assertTypeIsComponent(type:Type):void {\n var annotation = this._directiveMetadataReader.read(type).annotation;\n if (!(annotation instanceof Component)) {\n throw new BaseException(`Could not load '${stringify(type)}' because it is not a component.`);\n }\n }", "function resolveType(aResource,RDF,BMDS)\n{\n\tvar type = getProperty(aResource,\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",RDF,BMDS);\n\tif (type != \"\")\n\t\ttype = type.split(\"#\")[1];\n\n\tif (type==\"\")\n\t\ttype=\"Immutable\";\n\treturn type;\n}", "getFieldType() {\n return this._fieldTypeId\n }", "function resolveKnownDeclaration(decl) {\n switch (decl) {\n case host_1.KnownDeclaration.JsGlobalObject:\n return exports.jsGlobalObjectValue;\n case host_1.KnownDeclaration.TsHelperAssign:\n return assignTsHelperFn;\n case host_1.KnownDeclaration.TsHelperSpread:\n case host_1.KnownDeclaration.TsHelperSpreadArrays:\n return spreadTsHelperFn;\n default:\n throw new Error(\"Cannot resolve known declaration. Received: \" + host_1.KnownDeclaration[decl] + \".\");\n }\n }", "getBaseTypes() {\r\n return this.getType().getBaseTypes();\r\n }", "function getAnalysisType(){\n let settings = fs.readFileSync(path.resolve(__dirname, '../../../settings.json'));\n return JSON.parse(settings);\n}", "static getType(val) {\n\n if (val instanceof Node) {\n return \"NODE\";\n }\n\n if (typeof(val) === \"string\") {\n return \"STRING\";\n }\n\n if (val instanceof _Node_main_js__WEBPACK_IMPORTED_MODULE_2__.default) {\n return \"YNGWIE\";\n }\n\n return undefined;\n\n }", "getType() {\n return this.type\n }", "getOutputType() {\n if (this.outputType !== null && (typeof (this.outputType) !== null) && this.outputType !== undefined) { return this.outputType; }\n return null;\n }", "createOrReplaceType(name) {\n\t\treturn this.declareType(name);\n\t}", "function getInputNamesFromMetadata(node, typeChecker) {\n if (!node.decorators || !node.decorators.length) {\n return null;\n }\n const decorator = getAngularDecorators(typeChecker, node.decorators)\n .find(d => d.name === 'Directive' || d.name === 'Component');\n // In case no directive/component decorator could be found for this class, just\n // return null as there is no metadata where an input could be declared.\n if (!decorator) {\n return null;\n }\n const decoratorCall = decorator.node.expression;\n // In case the decorator does define any metadata, there is no metadata\n // where inputs could be declared. This is an edge case because there\n // always needs to be an object literal, but in case there isn't we just\n // want to skip the invalid decorator and return null.\n if (decoratorCall.arguments.length !== 1 ||\n !ts.isObjectLiteralExpression(decoratorCall.arguments[0])) {\n return null;\n }\n const metadata = decoratorCall.arguments[0];\n const inputs = metadata.properties.filter(ts.isPropertyAssignment)\n .find(p => getPropertyNameText(p.name) === 'inputs');\n // In case there is no \"inputs\" property in the directive metadata,\n // just return \"null\" as no inputs can be declared for this class.\n if (!inputs || !ts.isArrayLiteralExpression(inputs.initializer)) {\n return null;\n }\n return inputs.initializer.elements.filter(ts.isStringLiteralLike)\n .map(element => element.text.split(':')[0].trim());\n}", "getType () {\n\t\tlet type = this.definition.type;\n\n\t\t// if it's not a relationship or fetched property, it's an attribute\n\t\t// NOTE: Probably need to separate this out into different classes\n\t\ttype !== 'relationship' && type !== 'fetched' && (type = 'attribute');\n\n\t\treturn type;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a task from the front. Sets the next task's start time to removed task's and increases it's duration.
removeFront() { this._taskArr.shift(); /* if(this._taskArr.length === 1) { } else if(this._taskArr.length > 1) { let curr = this._taskArr[0]; let next = this._taskArr[1]; next.setStartTime(curr.startTime); this._taskArr.shift(); } */ }
[ "removeBack() {\n this._taskArr.pop();\n /*\n if(this._taskArr.length === 1) {\n this._taskArr.pop();\n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[this._taskArr.length - 1];\n let prev = this._taskArr[this._taskArr.length - 2];\n prev.setEndTime(curr.endTime);\n }\n */\n }", "addToFront(task) {\n this._taskArr.unshift(task);\n if(this._taskArr.length > 1) {\n this.adjustAllStartTimes(1);\n }\n }", "adjustTaskStartTime(index) {\n if(index < this._taskArr.length && index > 0) {\n let curr = this._taskArr[index];\n let prev = this._taskArr[index - 1];\n if(prev.endTime.compareTo(curr.endTime) >= 0) {\n this.removeAtIndex(index);\n } else {\n curr.setStartTime(prev.endTime);\n }\n }\n }", "removeAtIndex(index, adjustEndTimes = false) {\n if(index === 0) {\n this.removeFront();\n } else if (index === this._taskArr.length - 1) {\n this.removeBack();\n } else if(index > 0 && index < this._taskArr.length) {\n let curr = this._taskArr[index];\n if(adjustEndTimes) {\n let prev = this._taskArr[index - 1];\n if(prev.startTime.compareTo(curr.startTime) >= 0) {\n this.removeAtIndex(index - 1);\n } else {\n prev.setEndTime(curr.startTime);\n }\n this._taskArr.splice(index, 1);\n this.adjustAllEndTimes(index);\n } else {\n let next = this._taskArr[index + 1];\n if(curr.endTime.compareTo(next.endTime) >= 0) {\n this.removeAtIndex(index + 1);\n } else {\n next.setStartTime(curr.startTime);\n }\n this._taskArr.splice(index, 1);\n this.adjustAllStartTimes(index);\n }\n }\n\n }", "moveTaskBack(task) {\n const index = this.state.tasksDone.indexOf(task);\n this.state.tasksDone.splice(index, 1);\n this.state.toDoTasks.unshift(task);\n this.setState({toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }", "function deleteTask(){\n //DECLARE THE VARIABLE FOR THE POSITION OF THE TASK TO BE REMOVED\n var position;\n //LOOP THROUGH, GET POSITION, SPLICE FROM LIST\n for(var i = 0; i < this.tasks.length; i++){\n if(this.tasks[i]._id == id){\n position = this.tasks[i].position;\n this.tasks.splice(tasks[i], 1);\n }\n }\n\n //REMOVE THE ITEM FROM TASK LIST\n //IT IS ASYNC, NO WORRIES\n Task.remove({_id: id}, function(err){\n if(err) {\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n\n //LOOP THROUGH, UPDATE THE TASKS WITH POSITION GREATER THAN DELETED\n for(var i = 0; i < this.tasks.length; i++){\n //IF THE POSITION IS GREATER THAN THE ONE DELETED\n if(this.tasks[i].position > position){\n\n //SUBTRACT ONE FROM THE POSITION TO MAKE UP FOR THE MISSING ONE\n var newPos = this.tasks[i].position - 1;\n\n //UPDATE EACH TASK\n Task.update({_id: this.tasks[i]._id }, { position: newPos }, function(err){\n if(err){\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n }\n }\n\n //REDIRECT TO /\n res.redirect('/');\n }", "addAtIndex(task, index) {\n if(index === 0) {\n this.addToFront(task);\n } else if(index === this._taskArr.length) {\n this.addToBack(task);\n } else if(index < this._taskArr.length) {\n this._taskArr.splice(index,0, task);\n this.adjustTaskStartTime(index + 1);\n }\n }", "removeFromFront() {\n\n if(this.isEmpty()) return null;\n\n var nodeToRemove = this.head;\n\n this.head = this.head.next;\n nodeToRemove.next = null;\n this.counter--;\n return nodeToRemove;\n }", "function deleteTask(){\n // get indx of tasks\n let mainTaskIndx = tasksIndxOf(delTask['colName'], delTask['taskId']);\n // del item\n tasks.splice(mainTaskIndx, 1);\n // close modal\n closeModal();\n // update board\n updateBoard();\n // update backend\n updateTasksBackend();\n}", "function moveTask(index, task, value) {\n $scope.schedule[$scope.currentUserId].splice(index, 1);\n if (value == 1) {\n $scope.schedule[$scope.currentUserId].splice(index - 1, 0, task);\n } else {\n $scope.schedule[$scope.currentUserId].splice(index + 1, 0, task);\n }\n saveUserSchedule();\n }", "addToBack(task) {\n this._taskArr.push(task);\n }", "remove(element) {\n this.removeQueue.add(element);\n }", "function removeCompleted(n){\n //get id of task element(input) from parent elements\n taskElement = n.parentElement.parentElement.parentElement;\n taskId = taskElement.childNodes[0].id;\n //find task instance using the array and the id(index)\n curr = Task.ALLTASKS[taskId]; \n curr.complete();\n taskElement.style.display = 'none';\n addCompletedToDisplay() \n drawPercentage();\n updateReward();\n}", "function deleteTaskFromLocalStorage(task) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(task).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray.splice(index, 1);\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}", "dequeue() {\n // if the queue is empty, return immediately\n if (this.queue.length == 0) return undefined;\n\n // store the item at the front of the queue\n var item = this.queue[this.offset];\n\n // increment the offset and remove the free space if necessary\n if (++this.offset * 2 >= this.queue.length) {\n this.queue = this.queue.slice(this.offset);\n this.offset = 0;\n }\n\n // return the dequeued item\n this.emit('dequeued', this.queue.length, item);\n return item;\n }", "moveToTasksDone(task) {\n if (task !== \"\") {\n this.state.tasksDone.push(task);\n const index = this.state.toDoTasks.indexOf(task);\n this.state.toDoTasks.splice(index,1);\n this.setState({\n toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }\n }", "dequeue() {\r\n let deletedData;\r\n if (isEmpty()) {\r\n return -1;\r\n } else if (this.rear == this.front) {\r\n this.front = -1;\r\n this.rear = -1;\r\n } else {\r\n this.front = (this.front + 1) % this.queueSize;\r\n }\r\n deletedData = this.circularLinkedListQueue.deleteNode(0);\r\n return deletedData;\r\n }", "removeTopDisc() { \n this._discs.pop(); // Remove a disc from the top of the tower \n }", "shift() {\n if (!this.head) return undefined;\n let removed = this.head;\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = removed.next;\n this.head.prev = null;\n removed.next = null;\n }\n\n // removed.next = null;\n this.length--;\n return removed;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detach the properties panel from its parent node.
detach() { const parentNode = this._container.parentNode; if (parentNode) { parentNode.removeChild(this._container); this._eventBus.fire('propertiesPanel.detach'); } }
[ "destroy() {\n if (this.panel) {\n this.panel.destroy();\n this.panel = undefined;\n }\n }", "detach() {\n if (this.hasPrimaryIdentifierAttribute()) {\n const identityMap = this.constructor.getIdentityMap();\n identityMap.removeComponent(this);\n }\n Object.defineProperty(this, '__isAttached', { value: false, configurable: true });\n return this;\n }", "remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }", "disconnect() {\n var parents = this.parents();\n for (var object of parents.keys()) {\n var path = parents.get(object);\n object.unset(path);\n }\n return this;\n }", "detach() {\n this.surface = null;\n this.dom = null;\n }", "unsetNodes(editor, props) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!Array.isArray(props)) {\n props = [props];\n }\n\n var obj = {};\n\n for (var key of props) {\n obj[key] = null;\n }\n\n Transforms.setNodes(editor, obj, options);\n }", "function gui_removeArea(id) {\n\tif (props[id]) {\n\t\t//shall we leave the last one?\n\t\tvar pprops = props[id].parentNode;\n\t\tpprops.removeChild(props[id]);\n\t\tvar lastid = pprops.lastChild.aid;\n\t\tprops[id] = null;\n\t\ttry {\n\t\t\tgui_row_select(lastid, true);\n\t\t\tmyimgmap.currentid = lastid;\n\t\t}\n\t\tcatch (err) {\n\t\t\t//alert('noparent');\n\t\t}\n\t}\n}", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "function removeChildren() {\n plantBox.innerHTML = '';\n}", "hide() {\n this.StartOverPopoverBlock.remove();\n this.StartOverPopoverDiv.remove();\n }", "function detachPlayer() {\n //console.log('detachPlayer');\n playerAttached = false;\n // this is an internal player method to add class to an element\n rmp.fw.addClass(rmpContainer, 'rmp-detach');\n rmp.setPlayerSize(detachedWidth, detachedHeight);\n }", "clear() {\n if (this.props.vars) {\n clearCustomVars(this, this.props.vars);\n }\n this.props.vars = {};\n }", "remove () {\r\n // unclip all targets\r\n this.targets().forEach(function (el) {\r\n el.unclip();\r\n });\r\n\r\n // remove clipPath from parent\r\n return super.remove()\r\n }", "function unCollapse(parent) {\n var parent = $(parent);\n\n // Reset visibility and remove old ellipsis\n $('.ellipsize-hidden', parent).css('visibility', '').\n removeClass('ellipsize-hidden');\n $('.ellipsize-ellipsis', parent).remove();\n\n // Clear width/height cache\n parent.data('ellipsize-width', '');\n parent.data('ellipsize-height', '');\n }", "function clearExistingProposalCoordinators() {\n\t$j('#' + propCoordId).empty();\n}", "function removeIf(el, property) {\n var binding = this\n , parent = el.parentNode\n\n binding.change(function() {\n var value = binding.value(property)\n if (value && el.parentNode) {\n el.parentNode.removeChild(el)\n } else if (value && !el.parentNode) {\n parent.appendChild(el)\n }\n });\n}", "releaseGhostFromPen() {\n let ghost = this.inPen[0];\n ghost.setPath(\"exitPen\");\n ghost.activateElroy();\n \n this.inPen = this.inPen.slice(1);\n }", "destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }", "_collapsePanel(panel) {\n panel.expanded = false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[FUNCTION] FIND REACHABLE POSITIONS
function findReachablePositions(player, position) { // PARAMETERS : player, position reachs = []; // vider le tableau des cases atteignables var surrounds = findSurroundingPositions(position); // create a variable to define surrounding positions var range = 0; // set distance tested to zero // Define reachable positions : top while ( // WHILE... (surrounds[1] !== null) && // ...the position above exist (not outside of the board) (squares[surrounds[1]].player === 0) && // ... AND the position above is not occupied by a player (squares[surrounds[1]].obstacle === 0) && // ... AND the position above is not occupied by an obstacle (range < 3) // ... AND the tested position distance from player position is below 3 ) { // THEN var reach = Object.create(Reach); // create an object reach reachFight = isLeadingToFight(player, surrounds[1]); // define is the reachable position is a fighting position reach.initReach(player, surrounds[1], -10, (range + 1), reachFight); // set properties reachs.push(reach); // push object in array range++; // increase range of position tested surrounds = findSurroundingPositions(position - (10 * range)); // move forward the test } // Define reachable positions : right range = 0; // reset range for next test surrounds = findSurroundingPositions(position); // reset surrounds for next test while ( (surrounds[4] !== null) && (squares[surrounds[4]].player === 0) && (squares[surrounds[4]].obstacle === 0) && (range < 3) ) { var reach = Object.create(Reach); reachFight = isLeadingToFight(player, surrounds[4]); reach.initReach(player, surrounds[4], +1, (range + 1), reachFight); reachs.push(reach); range++; surrounds = findSurroundingPositions(position + (1 * range)); } // Define reachable positions : bottom range = 0; surrounds = findSurroundingPositions(position); while ( (surrounds[6] !== null) && (squares[surrounds[6]].player === 0) && (squares[surrounds[6]].obstacle === 0) && (range < 3) ) { var reach = Object.create(Reach); reachFight = isLeadingToFight(player, surrounds[6]); reach.initReach(player, surrounds[6], +10, (range + 1), reachFight); reachs.push(reach); range++; surrounds = findSurroundingPositions(position + (10 * range)); } // Define reachable positions : left range = 0; surrounds = findSurroundingPositions(position); while ( (surrounds[3] !== null) && (squares[surrounds[3]].player === 0) && (squares[surrounds[3]].obstacle === 0) && (range < 3) ) { var reach = Object.create(Reach); reachFight = isLeadingToFight(player, surrounds[3]); reach.initReach(player, surrounds[3], -1, (range + 1), reachFight); reachs.push(reach); range++; surrounds = findSurroundingPositions(position - (1 * range)); } return reachs; // return array }
[ "function char_position_finder(steps, base){\n\tlet counter = 0,\n\t\t\tposition;\n\t\t// \"arr.some\" is used instead of \"arr.forEach\" so we can break out of the loop as soon as we find the position we're searching for\n\t\tsteps.some( (step, i) => {\n\t\tcounter = step_counter(step, counter);\n\t\tif(counter === base) {\n\t\t\tposition = i+1;\n\t\t\treturn true;\n\t\t}\n\t})\n\t\treturn position || \"Santa Never Reaches the Base\";\n}", "function getPos(callback){\n\tfindPos(genLap, callback);\n}", "findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }", "findNeighbours(){\n \t// Array of all free directions. Starts with all directions\n\tvar freeDirections = [0,1,2,3,4,5,6,7];\n\t// First, define the eight neighbouring locations\n\tvar neighN = this.pos.copy().add(createVector(0,-1));\n\tvar neighS = this.pos.copy().add(createVector(0, 1));\n\tvar neighE = this.pos.copy().add(createVector( 1,0));\n\tvar neighW = this.pos.copy().add(createVector(-1,0));\n\tvar neighNE = this.pos.copy().add(createVector(1, -1));\n\tvar neighSE = this.pos.copy().add(createVector(1, 1));\n\tvar neighNW = this.pos.copy().add(createVector(-1,-1));\n\tvar neighSW = this.pos.copy().add(createVector(-1,1));\n\t\n\t// Make a dictionary, for translating direction-number into location\n\tvar directionDict ={};\n\tdirectionDict[0] = neighN;\n\tdirectionDict[1] = neighS;\n\tdirectionDict[2] = neighE;\n\tdirectionDict[3] = neighW;\n\tdirectionDict[4] = neighNE;\n\tdirectionDict[5] = neighSE;\n\tdirectionDict[6] = neighNW;\n\tdirectionDict[7] = neighSW;\n\t\n\t// Check if the directions are in the occuPos dictionary\n\t// And remove it from the \"freeDirections\" vector if it is\n\tif (occuPos.hasKey(posToDictKey(neighN.x,neighN.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 0){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\tif (occuPos.hasKey(posToDictKey(neighS.x,neighS.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 1){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighE.x,neighE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 2){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighW.x,neighW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 3){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNE.x,neighNE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 4){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSE.x,neighSE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 5){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNW.x,neighNW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 6){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSW.x,neighSW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 7){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Return the vector of free directions and the dictionary for translating the vector \n\treturn [freeDirections,directionDict];\n }", "findNodePos(number) {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n if (this.nodes[layer][node].number === number) return [layer, node];\n }\n }\n return false;\n }", "listContainsPosition(list, pos) {\n for(let p of list) {\n if(p.x == pos.x && p.y == pos.y) {\n return true;\n }\n }\n return false;\n }", "function FIND(find_text) {\n var within_text = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];\n var position = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];\n\n\n // Find the position of the text\n position = within_text.indexOf(find_text, position - 1);\n\n // If found return the position as base 1.\n return position === -1 ? error$2.value : position + 1;\n}", "posById(id){\n let slot = this._index[id];\n return slot ? slot[1] : -1\n }", "function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}", "walkBackWhile(startingPosition, condition) {\n let currentPos = startingPosition;\n let currentChar = this.getChar(currentPos);\n while (condition(currentChar)) {\n currentPos = this.getPrev(currentPos);\n currentChar = this.getChar(currentPos);\n if (currentPos.line === 0 && currentPos.character === 0)\n break;\n }\n return currentPos;\n }", "function findMarker(buf, pos) {\n for (var i = pos; i < buf.length; i++) {\n if (0xff === buf[i ] &&\n 0xe1 === buf[i+1]) {\n return i;\n }\n }\n return -1;\n }", "GetEntityPosition( entity ) { return null; }", "relativeLevelPosition(level, target){\n if(!target){ return [\"none\", \"same\", level]; };\n var difference = target.indexes[level] - this.indexes[level];\n\n if(difference < -1){\n return [\"jump\", \"backwards\", \"by-\" + level];\n } else if(difference == -1){\n return [\"advance\", \"backwards\", \"by-\" + level];\n } else if(difference == 1){\n return [\"advance\", \"forwards\", \"by-\" + level];\n } else if(difference > 1){\n return [\"jump\", \"forwards\", \"by-\" + level];\n }\n\n return [\"none\", \"same\", \"by-\" + level];\n }", "evaluatePosition(x)\n {\n let position=-1;\n if(x instanceof Hashable)\n {\n let hashCode=x.hashVal();\n position= hashCode%this._size;\n }\n return position;\n }", "closestOpenPosn(posn) {\n\t\t//bfs starting from posn\n\t\tvar searchQueue = [posn];\n\t\tvar blacklist = [];\n\t\twhile (searchQueue.length > 0) {\n\t\t\tvar searching = searchQueue.pop();\n\t\t\tvar searchingSquare = this.get(searching);\n\t\t\t//is it a posn we're looking for?\n\t\t\tif (searchingSquare && (!searchingSquare.content || !searchingSquare.content.isObstacle)) {\n\t\t\t\treturn searching; //we found what we're looking for!\n\t\t\t}\n\t\t\t//otherwise, add the current posn to blacklist and keep searching\n\t\t\tblacklist.push(searching);\n\t\t\tvar adjacents = shuffle(this.getExistingAdjacentPosns(searching));\n\t\t\tadjacents.forEach(function(p) { //add every posn in adjacents to the searchQueue\n\t\t\t\tvar posnEqualToCurPos = function(otherPos) {\n\t\t\t\t\treturn otherPos.x == p.x && otherPos.y == p.y;\n\t\t\t\t}\n\t\t\t\t//but only if it's not been blacklisted!\n\t\t\t\tif (blacklist.filter(posnEqualToCurPos).length == 0) {\n\t\t\t\t\tsearchQueue.unshift(p);\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}", "function lookForWhatToMove(key) {\n var coord = \"\";\n for(var r = 0; r < dim_max; r++) {\n for(var c = 0; c < dim_max; c++) {\n if(m[r][c] == 16) {\n //console.log(key);\n switch(key) {\n //a, left\n case 65:\n case 37: if(validate(r, c+1)) coord = r+\";\"+c +\"$\"+ r+\";\"+(c+1); break;\n //w, up\n case 87:\n case 38: if(validate(r+1, c)) coord = r+\";\"+c +\"$\"+ (r+1)+\";\"+c; break;\n //d, right\n case 68:\n case 39: if(validate(r, c-1)) coord = r+\";\"+c +\"$\"+ r+\";\"+(c-1); break;\n //s, down\n case 83:\n case 40: if(validate(r-1, c)) coord = r+\";\"+c +\"$\"+ (r-1)+\";\"+c; break;\n }\n }\n }\n }\n //what is coord?\n //coord = \"emptyCellRow;emptyCellCol$foundCellRow;foundCellCol\"\n return coord;\n}", "function findTriggerPoints() {\n\ttriggersPoints = [];\n\tvar offset = $(\"#content\").scrollTop();\n\tfor (var a = 0, max = hashElements.length; a < max; a += 1) {\n\t\ttriggersPoints.push($(\"#\" + hashElements[a]).offset().top + offsetfindtrigger + offset);\n\t\tif (a + 1 >= max) {\n\t\t\ttriggersPoints.push(triggersPoints[triggersPoints.length - 1] + $(\"#\" + hashElements[a]).height() + offsetfindtrigger);\n\t\t}\n\t}\n}", "getExistingAdjacentPosns(posn) {\n\t\tvar theWorld = this;\n\t\treturn posn.getAdjacentPosnsWithWraparound(theWorld).filter(function(p) {\n\t\t\treturn !!theWorld.get(p);\n\t\t})\n\t}", "function findSnappedLocation(lineLocation){\n\tvar finalLocation=lineLocation;\n\tvar listSize=globalPlList.size;\n\tfor(var i=1;i<=listSize;i++){\n\t\tvar line = globalPlList.get(i.toString());\n\t\tif(line!=undefined){\n\t\t\tvar startPath=line.getPath().getAt(0);\n\t\t\tvar endPath=line.getPath().getAt(1);\n\t\t\tvar tempCircleStart=new google.maps.Circle({\n\t\t\t\tcenter: startPath,\n\t\t\t\tradius: 10\n\t\t\t});\t\n\t\t\tvar tempCircleEnd=new google.maps.Circle({\n\t\t\t\tcenter: endPath,\n\t\t\t\tradius: 10,\n\t\t\t});\t\n\t\t\tvar isStartPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleStart);\n\t\t\tvar isEndPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleEnd);\n\t\t\tif(isStartPath){\n\t\t\t\tfinalLocation=startPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t\telse if(isEndPath){\n\t\t\t\tfinalLocation=endPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlistSize++; //To increase the size if a number is missing from id seq like 1,2,4,5,7 . Here Ids 3 and 6 are missing\n\t\t}\n\t}\n\treturn finalLocation;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setup mainDsu (emulates an SSApp DSU) and the participantManager.
function createMainDSU(callback) { keyssispace.createSeedSSI(domains[0], function (err, aSeedSSI) { console.log("mainDSU (SSApp) seedSSI identifier: " + aSeedSSI.getIdentifier(true)); //Create a main DSU resolver.createDSU(aSeedSSI, (err, dsuInstance) => { //Reached when DSU created if (err) return callback(err); mainDsu = dsuInstance; // set DSUStorage methods on mainDsu mainDsu.getObject = function (path, callback) { mainDsu.readFile(path, function (err, res) { if (err) return callback(err); try { res = JSON.parse(res.toString()); } catch (err) { return callback(err); } callback(undefined, res); }); }; mainDsu.enableDirectAccess = function(callback) { callback(undefined, true); }; participantManager = wizard.Managers.getParticipantManager(mainDsu, domains[0]); orderManager = wizard.Managers.getOrderManager(mainDsu); callback(); }); }); }
[ "function loadDSU() {\n try {\n resolver.loadDSU(DSU_SSI.getSSI(), (err, dsuInstance) => {\n if (err) {\n console.error(err);\n setModal(\"Error\", \"DSU has NOT been loaded, check console\");\n }\n dsu = dsuInstance;\n console.log(\"DSU loaded\", dsu);\n setModal(\"\", \"\");\n })\n } catch (err) {\n console.error(err);\n setModal(\"Error\", \"DSU has NOT been loaded, check console\");\n }\n}", "function initialSetup() {\r\n\r\n\tlet url = 'messenger_profile';\r\n\r\n\tcallRequest(url, api.getStarted, 'Get Started Button');\r\n\tcallRequest(url, api.persistentMenu, 'Persistent Menu');\r\n\tcallRequest(url, api.greeting, 'Greeting');\r\n\tcallRequest(url, api.whitelisted, 'Whitelisted Domain'); \r\n}", "function setUpTests()\n {\n// var fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n var fullInteractionData;\n if(app.scorm.scormProcessGetValue('cmi.suspend_data') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.suspend_data'));\n }\n else if(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n }\n else{\n console.log('There is a problem with test submission.');\n }\n \n // Inject the CMI DB data into the questionBank on first load\n if (fullInteractionData) {\n $.each(fullInteractionData, function (index, value)\n {\n if (!app.questionBank[index]) {\n app.questionBank[index] = value;\n }\n }); \n }\n \n // Setup the current test's question bank\n if (!app.questionBank[testID]) {\n app.questionBank[testID] = [];\n }\n \n return fullInteractionData;\n }", "function setup(cb) {\n console.log(\"initializing ...\");\n var chain = hlc.newChain(\"testChain\");\n chain.setKeyValStore(hlc.newFileKeyValStore(\"/tmp/keyValStore\"));\n chain.setMemberServicesUrl(\"grpc://localhost:50051\");\n chain.addPeer(\"grpc://localhost:30303\");\n console.log(\"enrolling deployer ...\");\n chain.enroll(\"WebAppAdmin\", \"DJY27pEnl16d\", function (err, user) {\n if (err) return cb(err);\n deployer = user;\n console.log(\"enrolling assigner ...\");\n chain.enroll(\"jim\",\"6avZQLwcUe9b\", function (err, user) {\n if (err) return cb(err);\n assigner = user;\n console.log(\"enrolling nonAssigner ...\");\n chain.enroll(\"lukas\",\"NPKYL39uKbkj\", function (err, user) {\n if (err) return cb(err);\n nonAssigner = user;\n });\n });\n });\n}", "function main() {\n\n setUp(config.mongoURL);\n\n\n if (config.getSourcesFromDB) {\n PodcastSource.getFromDatabase(startRunning);\n } else {\n _.forEach(\n config.XMLSource,\n function(sourceEntry) {\n if (sourceEntry.saveToDB) {\n sourceEntry.save(\n function(err) {\n //intentionally not using a callback from here, \n //we only care enough about the write to log an error\n if (err) {\n winston.error('Error saving source to database. [' + sourceEntry.source + ']', err);\n }\n }\n );\n winston.info('Saving source to database: ' + sourceEntry.source);\n }\n }\n );\n startRunning(null, config.XMLSource);\n }\n\n function startRunning(err, sourcesList) {\n if (err) {\n winston.error(err);\n throw err;\n }\n\n if (!sourcesList.length) {\n winston.warn(\"No sources defined, exiting program.\" + \"\\n\" +\n config.cmdline_help_text);\n return tearDown();\n }\n\n processing.runOnSource(\n sourcesList,\n /**\n * Called when each source has completed scraping, or on an error.\n * @param {Error} err Error encountered, if any\n */\n function mainComplete(err) {\n if (err) {\n throw err;\n } else {\n tearDown();\n }\n }\n );\n }\n }", "function initAdmin() {\n\tinitAgenciesAndPrograms();\n\tinitAdminAgencyDropdown();\n\tinitAdminProgramDropdown();\n\talert('You have selected the \"Administrator\" option. Use this option only to add, delete, or edit programs or agencies and their descriptions.');\n}", "async function initTestRunner(){\n\ttry {\n\t\t// Connect web3 with QTUM network\n\t\tconst web3 = await setupNetwork(JANUS_CONFIG);\n\n\t\t// const fundTestAccountResult = await fundTestAccount();\n\n\t\tconst chainId = 'JANUS'\n\t\tconsole.log(`[INFO] - Web3 is connected to the ${JANUS_CONFIG.name} node. Chain ID: ${chainId}`);\n\t\t\n\t\t// Deploy LinkToken or instantiate previously deployed contract\n\t\tconst LinkToken = await setupContract('LinkToken', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed LinkToken contract address in ${JANUS_CONFIG.name} network is: ${LinkToken.address}`);\n\n\t\t// Deploy Oracle or instantiate previously deployed contract\n\t\tconst Oracle = await setupContract('Oracle', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Oracle contract address in ${JANUS_CONFIG.name} network is: ${Oracle.address}`);\n\n\t\t// Configure Chainlink node\n\t\tconst chainlinkData = await setupChainlinkNode(Oracle.address);\n\n\t\t// Deploy Consumer or instantiate previously deployed contract\n\t\tconst Consumer = await setupContract('Consumer', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Consumer contract address in ${JANUS_CONFIG.name} network is: ${Consumer.address}`);\n\t\t\n\t\t//const gasEstimate = await Consumer.requestQTUMPrice.estimateGas({from: process.env.HEX_QTUM_ADDRESS})\n\t\t//console.log(\"estimated gas: \", gasEstimate)\n\t\n\t\tConsumer.requestQTUMPrice({from: process.env.HEX_QTUM_ADDRESS, gas: \"0x4c4b40\", gasPrice: \"0x64\"})\n\t\t.then(function(result){\n\t\t\t// Watch for the RequestFulfilled event of the Consumer contract\n\t\t\tConsumer.RequestFulfilled({\n\t\t\t\t'address': Consumer.address,\n\t\t\t\t'topics': [],\n\t\t\t\t'fromBlock':'latest'\n\t\t\t}, function(error, event){\n\t\t\t\tif (!error){\n\t\t\t\t\tif (event.event == 'RequestFulfilled'){\n\t\t\t\t\t\tConsumer.currentPrice().then(function(price){\n\t\t\t\t\t\t\tconst priceNum = web3.utils.hexToNumber(price);\n\t\t\t\t\t\t\tif (priceNum !== 0){\n\t\t\t\t\t\t\t\tconsole.log('[INFO] - Received QTUM price: ' + (priceNum / 100000000) + ' BTC');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tconsole.log(error);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}catch(e){\n\t\tconsole.error('[ERROR] - Test Runner initialization failed:' + e);\n\t}\n}", "function setup() {\n container.register({\n ChatAPIController: awilix.asClass(_controllers_ChatAPIController__WEBPACK_IMPORTED_MODULE_1__[\"ChatAPIController\"]),\n // services\n chatBotService: awilix.asClass(_use_cases_chatBotService__WEBPACK_IMPORTED_MODULE_2__[\"chatBotService\"]),\n // DAO\n mongoDao: awilix.asValue(mongoDao)\n });\n}", "setUp(options){\n this.setUpDeviceListeners(undefined, this.onOSCMessage);\n this.setUpDevice({ osc: options });\n }", "function initUserData(){\n try{\n if(GLOBALS) {\n GLOBALS.userdata = GLOBALS.service.getUserData();\n } else {\n GLOBALS = {\n userdata: {}\n };\n }\n } catch(er){\n console.log(er);\n }\n\n // temporary - setting up sample userdata for view, if no userdata is present\n if (!(GLOBALS.userdata)) {\n GLOBALS.userdata = {\n meta: {\n title: \"Task Management App\"\n },\n list: [\n {\n _id: \"\",\n name: \"My Task List\",\n modified: \"\",\n cards: [\n {\n task:\"Explore Features\",\n description: \"verify features of app\",\n tags: ['inprocess'],\n users: ['qa'],\n completed: false\n },\n {\n task:\"New Features\",\n description: \"implement new app features\",\n tags: ['new','p2'],\n users: ['developer'],\n completed: false\n }\n ]\n }\n ]\n };\n }\n }", "function setupUserConfig() {\n let cfg = path.join(u.dataLoc(), 'cfg.env')\n if(shell.test(\"-f\", cfg)) return\n\n shell.echo(`\\n\\nCreating configuration file...`)\n shell.echo(`# understand/\n# We use environment variables to configure various skills and services.\n# In order to pass the information to the required components we need to\n# set them in this file.\n\n# For Telegram Channel\nTELEGRAM_TOKEN=\n\n# For what-wine skill\nMASHAPE_KEY=\n\n# for AI Artist Skill\nAIARTIST_HOST=\nAIARTIST_PORT=\n`).to(cfg)\n shell.echo(`Please edit this file: ${cfg}`)\n shell.echo(`To add your own TELEGRAM_TOKEN, etc...\\n\\n`)\n}", "function startServant(adviseLaunchInfo) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_PUBKEY'));\n \n var eedTicket = adviseLaunchInfo.eedTicket,\n eedURL = adviseLaunchInfo.eedURL,\n pubKey = \"\",\n pubKeyUrl = eedURL + '/execution/pubkey',\n that = this;\n \n // FIXME : verify the noServant code\n adviseLaunchInfo.noServant = localStorage.getItem('noServant') === null? false : true; \n if(adviseLaunchInfo.noServant){\n startApp(adviseLaunchInfo);\n return;\n }\n \n $simjq.when(getCOSConfigurations(adviseLaunchInfo)).then(\n \tfunction(){\n \t\t\n \t\tjQuery.support.cors = true;\n \t jQuery.ajax({\n \t url : pubKeyUrl,\n \t type : \"GET\",\n \t beforeSend : function(request) {\n \t request.setRequestHeader(\"EEDTicket\", eedTicket);\n \t request.setRequestHeader(\"Credentials\", \"\");\n \t },\n \t contentType : \"text/plain\",\n \t success : function(returndata, status, xhr) {\n \t console.log(returndata);\n \t \n \t pubKey = $simjq(returndata).find(\"KeyRep\").text().trim();\n \t \n \t // Store decoded key to use as sp-encryption component\n \t adviseLaunchInfo.eedPublicKeyDecoded = pubKey;\n \t \n \t pubKey = encodeURIComponent(pubKey);\n \t adviseLaunchInfo.eedPublicKey = pubKey;\n \t \n \t getEncryptedCredentials(adviseLaunchInfo);\n \t },\n \t error : function(jqXHR, textStatus, errorThrown) {\n \t handleEEDCommFailure(\n \t eedURL,\n \t startServant.bind(that, adviseLaunchInfo),\n \t\t\t\t\tadviseLaunchInfo.translator);\n \t }\n \t });\n },\n function(error){\n \t\n \tcreateLaunchPopOver({\n 'message': translator.translate('LAUNCH_EED_COMM_FAILURE') + '<br/>' \n + error,\n 'close-callback': returnToRALanding\n });\n \t\n });\n}", "function setup(elmApp) {\n elmApp.ports.dragstart.subscribe(processDragStart);\n elmApp.ports.dragover.subscribe(processDragOver);\n }", "function init(input_params) {\n\tvar input_args = input_params.toString().match(/\\S+/g);\n\t//console.log('input_args: ' + input_args);\n\tvar params = ['',''].concat(input_args);\n\t//console.log('client disconnected');\n\tvar d = domain.create();\n\td.on('error', function(err) {\n\t\tconsole.error(\"EXCEPTION IN USER SERVICE APPLICATION:\");\n\t\tconsole.error(\"Error Object:\");\n\t\tutil.inspect(err,{showHidden: true, depth: 1}).split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\tconsole.error(\"Stack trace:\");\n\t\terr.stack.toString().split(/\\r?\\n/)\n\t\t .forEach(function(s) {console.error(s)});\n\t\t// Unload user service application module if possible.\n\t\tif (err.domain && err.domain.service_dir) {\n\t\t\tvar mainModuleFile = require.resolve(err.domain.service_dir);\n\t\t\tunified_service.unrequire(mainModuleFile);\n\t\t}\n\t});\n\td.run(function() {\n\t\tbootstrap.parse(loadAndStart, params);\n\t});\n}", "function main () {\n\tvar initializePromise = initialize();\n\tinitializePromise.then((res) => {\n\t\tuserDetails = res;\n\t\tconsole.log(userDetails)\n\t}, (err) => {\n\t\tconsole.log(err)\n\t})\n}", "function setupSinglePilet(app, api) {\n try {\n var result = app.setup(api);\n if (typeof app.teardown === 'function') {\n var evtName_1 = 'unload-pilet';\n var handler_1 = function (e) {\n if (e.name === app.name) {\n api.off(evtName_1, handler_1);\n app.teardown(api);\n }\n };\n api.on(evtName_1, handler_1);\n }\n return result;\n }\n catch (e) {\n console.error(\"Error while setting up \" + (app === null || app === void 0 ? void 0 : app.name) + \".\", e);\n }\n}", "async function setup() {\n // Deploying provider, connecting to the database and starting express server.\n const port = process.env.SERVERPORT ? process.env.SERVERPORT : 8080;\n await lti.deploy({ port });\n\n // Register platform, if needed.\n await lti.registerPlatform({\n url: process.env.PLATFORM_URL,\n name: 'Platform',\n clientId: process.env.PLATFORM_CLIENTID,\n authenticationEndpoint: process.env.PLATFORM_ENDPOINT,\n accesstokenEndpoint: process.env.PLATFORM_TOKEN_ENDPOINT,\n authConfig: {\n method: 'JWK_SET',\n key: process.env.PLATFORM_KEY_ENDPOINT,\n },\n });\n\n // Get the public key generated for that platform.\n const plat = await lti.getPlatform(\n process.env.PLATFORM_URL,\n process.env.PLATFORM_CLIENTID\n );\n console.log(await plat.platformPublicKey());\n}", "function init() {\n return mediaPlugin.initMedia().then(function () {\n if (pcTW)\n return;\n pcTW = mediaPlugin.createComponent({\n type: 'TuningWizard',\n hide: true\n });\n pcTW.event(onPluginComponentEvent, 'async');\n return pcTW.load().then(function () {\n updateAudioDevices(pcTW.invoke('GetTelephonyDevicesDetails'));\n updateVideoDevices(pcTW.invoke('GetVideoDevicesDescription'));\n // the plugin is extremely chatty - it fires a lot of TEL_DEVICES_CHANGED\n // events, so we postpone event handling until after we load the plugin\n // and get the initial device collection snapshot\n isInitialized = true;\n });\n });\n }", "function setup() {\n\t// Redirect uncaught/unhandled things to console.error (makes logging them to file possible)\n\t// ------------------------------------------------------------------------------\n\tprocess.on('uncaughtException', (err) => {\n\t\tconsole.error(err);\n\t\tprocess.exit(1);\n\t});\n\tprocess.on('unhandledRejection', (reason, p) => {\n\t\tconsole.error('Unhandled Rejection at:', p, 'reason:', reason);\n\t\tprocess.exit(1);\n\t});\n\n\t// Redirect stdout/stderr to log files if app is run as packaged .exe\n\t// --------------------------------------------------------------------\n\tconst stdoutFile = fs.createWriteStream(PATHS.DEBUG_LOG, { flags: 'a' });\n\t// ignore stdout if not run with --debug\n\tconst isDebug = process.argv.includes('--debug');\n\tprocess.stdout.write = function (string, encoding) {\n\t\tif (isDebug) {\n\t\t\tstring = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;\n\t\t\tstdoutFile.write(string, encoding);\n\t\t}\n\t};\n\n\tconst stderrFile = fs.createWriteStream(PATHS.ERROR_LOG, { flags: 'a' });\n\tprocess.stderr.write = function (string, encoding) {\n\t\tstring = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;\n\t\tstderrFile.write(string, encoding);\n\t};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the enhanced urlbar when hover with CTRL key pressed
function hideEnhancedURLBar() { if (ctrlMouseHover) return; async(function() { ctrlMouseHover = true; }, 200); setOpacity(1); enhancedURLBar.style.display = "none"; }
[ "removeShortcut(keys) {\n Mousetrap.unbind(keys)\n }", "function hideLinksBar() {\n\tlinksbarDiv.className = 'page transition down';\n}", "function pressedGlobalShortcutKeys () {\n if (!mb.window.isVisible()) {\n mb.window.show()\n } else {\n mb.hideWindow()\n }\n}", "function disablehotKey() {\n\tnew Richfaces.hotKey('form_recherche:mykey', 'return', '', {\n\t\ttiming : 'immediate'\n\t}, function(event) {\n\t});\n}", "function hideFilterLinkIcon() {\n\tvar element = document.querySelector(\"#filter-link\");\n\tif (element) {\n\t\telement.style.display = \"none\";\n\t}\n\t// also deactivate the filter in the toolbar\n\tdetachGlobalFilter();\n}", "function handleURLBarEvents() {\n // Watch for urlbar value change\n let changeListener = {\n onLocationChange: function(aProgress, aRequest, aURI) {\n newDocumentLoaded = true;\n refreshRelatedArray = true;\n if (!tabChanged)\n origIdentity.collapsed = identityLabel.collapsed = false;\n async(function() {\n if (!tabChanged)\n updateURL();\n else\n tabChanged = false;\n }, 10);\n }\n };\n gBrowser.addProgressListener(changeListener);\n unload(function() {\n gBrowser.removeProgressListener(changeListener);\n }, window);\n listen(window, gBrowser.tabContainer, \"TabSelect\", function() {\n origIdentity.collapsed = false;\n identityLabel.collapsed = false;\n tabChanged = true;\n showingHidden = false;\n try {\n if (enhancedURLBar.nextSibling.hasAttribute(\"isHiddenArrow\"))\n enhancedURLBar.parentNode.removeChild(enhancedURLBar.nextSibling);\n } catch (ex) {}\n if (restyleEnhancedURLBarOnTabChange) {\n restyleEnhancedURLBarOnTabChange = false;\n setupEnhancedURLBarUI();\n }\n async(updateURL);\n });\n listen(window, gBrowser, \"load\", function() {\n async(function() {\n if (!tabChanged)\n updateURL();\n else\n tabChanged = false;\n }, 50);\n });\n listen(window, gURLBar, \"focus\", function() {\n if (editing)\n return;\n reset(1);\n gURLBar.selectTextRange(0, gURLBar.value.length);\n });\n listen(window, gURLBar, \"blur\", function() {\n reset(0);\n if (!tabChanged)\n async(updateURL, pref(\"animationSpeed\") != \"none\"? 210: 10);\n });\n listen(window, gURLBar, \"mouseout\", function() {\n if (ctrlMouseHover && !gURLBar.focused) {\n async(function() {\n if (!ctrlMouseHover)\n return;\n ctrlMouseHover = false;\n setOpacity(0);\n enhancedURLBar.style.display = \"-moz-box\";\n }, 100);\n }\n });\n listen(window, gBrowser, \"DOMTitleChanged\", function(e) {\n if (e.target.title != gBrowser.contentDocument.title)\n return;\n async(function() {\n if (!gURLBar.focused && newDocumentLoaded) {\n origIdentity.collapsed = false;\n identityLabel.collapsed = false;\n titleChanged = true;\n updateURL();\n newDocumentLoaded = false;\n }\n }, 10);\n });\n }", "function ViewerToolsHide() {\r\n if( G.VOM.viewerDisplayed ) {\r\n G.VOM.toolbarsDisplayed=false;\r\n ViewerToolsOpacity(0);\r\n }\r\n }", "function hideUrlBar() {\n if (window.location.hash.indexOf('#') == -1) {\n window.scrollTo(0, 1);\n }\n}", "hideSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(true);\n this._cursorTracker.set_pointer_visible(false);\n }", "function hideAddressBar() {\n window.scrollTo(0, 1); //hide address bar\n}", "function hideMouse()\n{\n if (slidemode) document.body.style.cursor = 'none';\n hideMouseID = 0;\t\t// 0 = timer has fired, cursor is hidden\n}", "_onDashToDockHoverChanged() {\n //Skip if dock is not in dashtodock hover mode\n if (this._settings.get_boolean('dashtodock-hover')) {\n if (DashToDock) {\n if (DashToDock.dockManager) {\n if (DashToDock.dockManager._allDocks[0]._box.hover) {\n if (Main.overview.visible == false) {\n this._hoveringDash = true;\n this._show();\n }\n } else {\n this._hoveringDash = false;\n this._hide();\n }\n } else {\n if (DashToDock.dock._box.hover) {\n if (Main.overview.visible == false) {\n this._hoveringDash = true;\n this._show();\n }\n } else {\n this._hoveringDash = false;\n this._hide();\n }\n }\n }\n }\n }", "function i2uiResizeSlaveonmouseover()\r\n{\r\n if (i2uiResizeSlavewhichEl == null && event.srcElement.id.indexOf(i2uiResizeKeyword) != -1)\r\n {\r\n event.srcElement.style.cursor = \"move\";\r\n }\r\n event.returnValue = true;\r\n}", "function setHotKeys() {\n\tdocument.onkeydown = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\t\tif (key == 18 && !ev.ctrlKey) {\t// start selection, skip Win AltGr\n\t\t\t_hotkeys.alt = true;\n\t\t\t_hotkeys.focus = -1;\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\telse if (ev.altKey && !ev.ctrlKey && ((key>47 && key<58) || (key>64 && key<91))) {\n\t\t\tkey = String.fromCharCode(key);\n\t\t\tvar n = _hotkeys.focus;\n\t\t\tvar l = document.getElementsBySelector('[accesskey='+key+']');\n\t\t\tvar cnt = l.length;\n\t\t\t_hotkeys.list = l;\n\t\t\tfor (var i=0; i<cnt; i++) {\n\t\t\t\tn = (n+1)%cnt;\n\t\t\t\t// check also if the link is visible\n\t\t\t\tif (l[n].accessKey==key && (l[n].offsetWidth || l[n].offsetHeight)) {\n\t\t\t\t\t_hotkeys.focus = n;\n\t // The timeout is needed to prevent unpredictable behaviour on IE.\n\t\t\t\t\tvar tmp = function() {l[_hotkeys.focus].focus();};\n\t\t\t\t\tsetTimeout(tmp, 0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\tif((ev.ctrlKey && key == 13) || key == 27) {\n\t\t\t_hotkeys.alt = false; // cancel link selection\n\t\t\t_hotkeys.focus = -1;\n\t\t\tev.cancelBubble = true;\n \t\t\tif(ev.stopPropagation) ev.stopPropagation();\n\t\t\t// activate submit/escape form\n\t\t\tfor(var j=0; j<this.forms.length; j++) {\n\t\t\t\tvar form = this.forms[j];\n\t\t\t\tfor (var i=0; i<form.elements.length; i++){\n\t\t\t\t\tvar el = form.elements[i];\n\t\t\t\t\tvar asp = el.getAttribute('aspect');\n\n\t\t\t\t\tif (!string_contains(el.className, 'editbutton') && (asp && asp.indexOf('selector') !== -1) && (key==13 || key==27)) {\n\t\t\t\t\t\tpassBack(key==13 ? el.getAttribute('rel') : false);\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (((asp && asp.indexOf('default') !== -1) && key==13)||((asp && asp.indexOf('cancel') !== -1) && key==27)) {\n\t\t\t\t\t\tif (validate(el)) {\n\t\t\t\t\t\t\tif (asp.indexOf('nonajax') !== -1)\n\t\t\t\t\t\t\t\tel.click();\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (asp.indexOf('process') !== -1)\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el, null, 600000);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tev.returnValue = false;\n\t\t\treturn false;\n\t\t}\n\t\tif (editors!==undefined && editors[key]) {\n\t\t\tcallEditor(key);\n\t\t\treturn stopEv(ev); // prevent default binding\n\t\t}\n\t\treturn true;\n\t};\n\tdocument.onkeyup = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\n\t\tif (_hotkeys.alt==true) {\n\t\t\tif (key == 18) {\n\t\t\t\t_hotkeys.alt = false;\n\t\t\t\tif (_hotkeys.focus >= 0) {\n\t\t\t\t\tvar link = _hotkeys.list[_hotkeys.focus];\n\t\t\t\t\tif(link.onclick)\n\t\t\t\t\t\tlink.onclick();\n\t\t\t\t\telse\n\t\t\t\t\t\tif (link.target=='_blank') {\n\t\t\t\t\t\t\twindow.open(link.href,'','toolbar=no,scrollbar=no,resizable=yes,menubar=no,width=900,height=500');\n\t\t\t\t\t\t\topenWindow(link.href,'_blank');\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\twindow.location = link.href;\n\t\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}", "hideContextMenu() {\n this.contextMenuType = '';\n this.moveMenuVisibility = false;\n }", "function deactivateFilterInToolbar() {\n\thideFilterLinkIcon();\n\tupdateFilterState();\n}", "function OnQueryCursor(/*object*/ sender, /*QueryCursorEventArgs*/ e)\r\n { \r\n /*Hyperlink*/var link = sender;\r\n\r\n if (link.IsEnabled && link.IsEditable)\r\n { \r\n if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)\r\n { \r\n e.Cursor = link.TextContainer.TextSelection.TextEditor._cursor; \r\n e.Handled = true;\r\n } \r\n }\r\n }", "function handlerViewControlLayerMouseLeave (e) {\n viewControlLayer.css(\"cursor\", \"url(/assets/javascripts/SVLabel/img/cursors/openhand.cur) 4 4, move\");\n mouseStatus.isLeftDown = false;\n }", "function url_completion_toggle (I) {\r\n if (url_completion_use_bookmarks) {\r\n url_completion_use_bookmarks = false;\r\n url_completion_use_history = true;\r\n } else {\r\n url_completion_use_bookmarks = true;\r\n url_completion_use_history = false;\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
paintStat( g, sheet, stat, value, region, turns ) Paints text for a character stat in a 'char' region: stat is the name of the stat (Life, Craft, etc.); value is null for stats like Gold, or the amount to print for stats like Life; turns is the number of anticlockwise turns to rotate the text.
function paintStat(g, sheet, stat, value, region, turns) { if (value != null) { stat = sprintf(#tal_stat_format, stat, value); } sheet.drawRotatedTitle(g, stat, R(region), Talisman.titleFont, 7, sheet.ALIGN_CENTER, turns); }
[ "function drawStats(stats) {\r\n textAlign(LEFT);\r\n fill('gray');\r\n blendMode(ADD);\r\n drawStat(0, 'objectsDrawn', stats.objectsDrawn, 800);\r\n drawStat(1, 'highestNote', stats.highestNote, 127);\r\n // drawStat(2, 'highestNoteMax', stats.highestNoteMax, 127);\r\n}", "function drawChar(line, col, ch) {\r\n if (line < 0 || line >= LINES || col < 0 || col >= COLUMNS)\r\n return;\r\n //\r\n // attributes\r\n const a = line * COLUMNS + col\r\n const attr = makeAttribute(my.ink, my.paper)\r\n displayColours[a] = attr\r\n //\r\n // index of the first byte of the character in the character set\r\n const chAt = (ch.charCodeAt(0) - 0x20) * CHARSIZE\r\n //\r\n // copy pixel data\r\n for (let i = 0; i < CHARSIZE; i++) {\r\n const at = (line * CHARSIZE + i) * COLUMNS + col\r\n displayPixels[at] = CHARSET[chAt + i]\r\n }\r\n}", "function drawText(line, col, text) {\r\n const length = text.length\r\n for (let i = 0; i < length && line < LINES; i++) {\r\n drawChar(line, col, text.charAt(i))\r\n if (++col >= COLUMNS) {\r\n col = 0\r\n line++\r\n }\r\n }\r\n}", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "function drawCombat(){\n $(\"#combat_area\").empty();\n var m = monsterAtPlayerRoom();\n if(m.length != 0){\n var str = \"Combat with \";\n for(let i = 0; i < m.length; i++){\n draw_name_hp_mp(m[i]);\n str += m[i].name;\n if(i + 1 != m.length){\n str += \", \";\n } else {\n str += \" began.\";\n }\n }\n adddiv(str);\n addlineafter();\n draw_name_hp_mp(player); \n } else {\n adddiv(\"There is no monster to fight...\");\n game_state = PLAY_NON_COMBAT;\n }\n \n}", "function infoText() {\n // Shows \"PAUSE\" if the game is paused (key: SPACEBAR)\n if (pause) {\n fill(255);\n text(\"PAUSE\", gridX - 7*reso, scoreY);\n }\n \n // Shows infos about the commands at the beginning\n if (time < 10) {\n var alpha = 255;\n if (time > 4) { // After some time, the text fades away\n alpha -= (time - 4) * 100;\n }\n fill(255, alpha);\n \n var textX = gridX - 7*reso;\n text(\"MOVE:\", textX, scoreY + 3.5 * reso)\n text(\"ARROWS\", textX, scoreY + 5 * reso)\n text(\"PAUSE:\", textX, scoreY + 8 * reso)\n text(\"SPACEBAR\", textX, scoreY + 9.5 * reso)\n text(\"RESET:\", textX, scoreY + 12.5 * reso)\n text(\"ENTER\", textX, scoreY + 14 * reso)\n }\n}", "RenderChar(draw_list, size, pos, col, c) {\r\n this.native.RenderChar(draw_list.native, size, pos, col, c);\r\n }", "function change_text( player, target_hit )\n{\n\tfor (var i = 0; i < board_sections.length; i++) \n\t{\n\t\tvar section_text = $(board_sections[i]).text();\n\t\tif (target_hit == section_text) \n\t\t{\n\t\t\tif (player.marker == 'X') \n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#91c46b');\n\t\t\t\t$(board_sections[i]).text('X');\n\n\t\t\t}\n\t\t\telse if (player.marker == 'O')\n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#d9534f');\n\t\t\t\t$(board_sections[i]).text('O');\n\t\t\t}\n\t\t}\n\t}\n\tcheck_game( player );\n}", "function drawCivInfo(ctx, civs) {\r\n ctx.font = me.style.fontSize.civ + ' ' + me.style.font;\r\n for (var i = 0, len = civs.length; i < len; i++) {\r\n var civ = civs[i];\r\n var msg = '(' + civ.owners.map(function(x) { return x.name; }).join(', ') + ')';\r\n ctx.fillText(msg, civ.x, civ.y + halfCellH + 27);\r\n }\r\n }", "drawHealth() {\n document.querySelector(\".monster-health__remain\").style.width =\n (this.health / this.startHealth) * 100 + \"%\";\n document.querySelector(\n \".monster-health__remain\"\n ).innerHTML = this.health;\n }", "function drawTime() {\r\n var text = 'God morgon!'\r\n // var text = '06.00'\r\n var textSize = 50\r\n context.fillStyle = getFillstyleString(stampColor[0], stampColor[1], stampColor[2], alpha)\r\n context.font = `${textSize}` + 'px OpenSans'\r\n context.fillText(text, X + RADIUS * Math.sin(-Math.PI/2 + ROTATION * Math.PI) - context.measureText(text).width / 2, Y + RADIUS * Math.cos(Math.PI/2 + ROTATION * Math.PI) + textSize / 2)\r\n // Swedish\r\n putText('Morgon', -0.5)\r\n\r\n putText('Förmiddag', 0.5)\r\n putText('Tidig eftermiddag', 1.5)\r\n putText('Sen eftermiddag', 2.5)\r\n putText('Tidig kväll', 3.5)\r\n putText('Sen kväll', 4.5)\r\n putText('Natt', 5.5)\r\n putText('Natt', 6.5)\r\n \r\n /* // English\r\n putText('Morning', -0.5)\r\n putText('Early lunch', 0.5)\r\n putText('Early Afternoon', 1.5)\r\n putText('Late Afternoon', 2.5)\r\n putText('Early evening', 3.5)\r\n putText('Late evening', 4.5)\r\n putText('Night', 5.5)\r\n putText('Night', 6.5)\r\n */\r\n\r\n /*\r\n var time = 6\r\n for(var i = 0; i < SIZE; i++) {\r\n time = (time + Math.floor(24/SIZE)) % 24\r\n if(time === 6) continue // 06.00 is rendered above\r\n if(time < 10) {\r\n putText('0' + time + '.00', i)\r\n\r\n } else {\r\n putText(time + '.00', i)\r\n }\r\n }\r\n */\r\n if(alpha < 1) alpha += 0.8 / fps\r\n}", "function drawScoreboard() {\r\n \r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Score: \" + score, 20, 380);\r\n\r\n if(score < 20) {\r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Level 1 \", 280, 380);\r\n }\r\n\r\n if(score >= 20) {\r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Level 2 \", 280, 380);\r\n }\r\n}", "ctxDrawText (ctx, string, x, y, cssColor) {\n this.setIdentity(ctx)\n ctx.fillStyle = cssColor\n ctx.fillText(string, x, y)\n ctx.restore()\n }", "function drawResourceValues() {\n if (gameStatus) {\n //Resource bar Coordinates;\n rx = 0;\n ry = 0;\n rw = 660;\n rh = 50;\n\n push();\n\n noStroke();\n fill(255);\n textSize(12);\n textAlign(CENTER, CENTER);\n text(`${money}`, rx + 25 + 40, ry + 30);\n text(`${water}/${max_water}`, rx + 125 + 50, ry + 30);\n text(`${ore}/${max_ore}`, rx + 225 + 50, ry + 30);\n text(`${people}/${max_people}`, rx + 325 + 50, ry + 30);\n text(`${rank}`, rx + 425 + 30, ry + 30);\n text(`Year: ${gameDate}`, rx + 530, ry + 30);\n\n pop();\n }\n}", "drawBoss() {\n ctx.drawImage(this.boss,\n 0, 0, this.boss.width, this.boss.height,\n this.x_boss_pos, this.y_icon_pos,\n icon_width, icon_height);\n \n // Health outer\n ctx.strokeStyle = \"black\";\n ctx.strokeRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, icon_width + 100, 25);\n\n // Health drawing\n ctx.fillStyle = \"red\";\n ctx.fillRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, this.health, 25);\n\n ctx.fillStyle = \"black\";\n ctx.font = '20px Arial';\n ctx.fillText(\"Health: \" + this.health, this.x_boss_pos - 150 - 100, this.y_icon_pos + icon_height + 25);\n }", "function drawInfo(){\n image(blueprint, 0, 0, imgSize, imgSize*5/9);\n fill('#fff8');\n rect(0, height-200, width, 200);\n \n fill(0);\n textStyle(ITALIC);\n textSize(22);\n var infoText = [\"Use WASD directions to navigate the rooms of the house.\", \"Hit 'X' to return to the splash screen.\", \"Hit 'I' to return to the map screen.\", \"Click or press any key again to start house tour.\"] \n for(var i = 0; i<infoText.length; i++){\n text(infoText[i], 175, height-150+i*30, width-350, 100);\n }\n}", "function smiley_text(text, smiley_names, width)\r\n{\r\n var smiley_codes = new Array();\r\n for each (var smiley in smiley_names) // Filters valid smileys\r\n {\r\n if (smileys.hasOwnProperty(smiley))\r\n {\r\n smiley_codes.push(smileys[smiley]);\r\n }\r\n }\r\n \r\n text = text.toUpperCase(); // There are only ascii art representations of caps\r\n var res = \"\";\r\n var cur_smiley = 0;\r\n for (var row = 0; row < rows_per_letter; row++)\r\n {\r\n for each (var chr in text)\r\n {\r\n if (!alphabet.hasOwnProperty(chr))\r\n {\r\n continue;\r\n }\r\n\r\n var cur_row = alphabet[chr][row];\r\n for (var i = 0; i < cur_row.length; i++)\r\n {\r\n var spaces = take_while(\" \", cur_row, i);\r\n if (spaces.length > 0)\r\n {\r\n res += get_spacer_img(spaces.length, width);\r\n i += spaces.length - 1;\r\n }\r\n else\r\n {\r\n res += smiley_codes[cur_smiley % smiley_codes.length];\r\n cur_smiley++;\r\n }\r\n }\r\n res += get_spacer_img(1, width); // Spacing between letters\r\n }\r\n res += \"\\n\";\r\n }\r\n return res;\r\n}", "function drawCellNumbers() {\n\n ctx.fillStyle = 'black';\n ctx.font = 'bold 20px Arial';\n\n let letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];\n\n if (playerColor == 'white') {\n\n //Draw cell numbers\n for (let y = 0; y < 8; y++) {\n\n ctx.fillText(-(y - 8), 0 * CELL_SIZE + 5, (y + 1) * CELL_SIZE - 5);\n\n }\n\n //Draw cell letters\n for (let x = 0; x < 8; x++) {\n\n ctx.fillText(letters[x], (x + 1) * CELL_SIZE - 20, 8 * CELL_SIZE - 5);\n\n }\n\n } else {\n\n //Draw cell numbers\n for (let y = 1; y <= 8; y++) {\n\n ctx.fillText(y, 0 * CELL_SIZE + 5, y * CELL_SIZE - 5);\n\n }\n\n //Draw cell letters\n for (let x = 0; x < 8; x++) {\n\n ctx.fillText(letters[-(x - 7)], (x + 1) * CELL_SIZE - 20, 8 * CELL_SIZE - 5);\n\n }\n\n }\n\n}", "function drawCell(cell) {\n ctx.beginPath();\n ctx.rect(cell.x, cell.y, cell.w, cell.h);\n ctx.fillStyle = CELL_COLOR[cell.type];\n ctx.fill();\n ctx.closePath();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check whether has albumList, if not, insert
function checkAlbumList() { console.log('--checking for db albumList...'); let albumList; try { albumList = db.getData('/albumList'); } catch (err) { albumList = []; db.push('/albumList', albumList); } }
[ "static addAlbum(album) {\n const albums = Storage.getAlbums();\n\n albums.push(album);\n\n localStorage.setItem('albums', JSON.stringify(albums));\n }", "static checkForDuplicate(albumId) {\n const albums = Storage.getAlbums();\n let isDuplicate;\n\n albums.forEach((album) => {\n if(album.albumId === albumId) {\n isDuplicate = true;\n }\n })\n return isDuplicate;\n }", "addAlbum(artistId, albumData) {\n if (artistId === undefined || !albumData.name || !albumData.year) {\n throw new ErrorInsufficientParameters();\n }\n\n const checkArtist = this.getArtistById(artistId);\n\n if(!checkArtist) {\n throw new ErrorDoesntExistsArtist();\n }\n const checkAlbum = this.getAllAlbums().find(album => album.getName() == albumData.name);\n if(checkAlbum) {\n throw new ErrorRepeatAlbum();\n }\n\n const artist = this.getArtistById(artistId);//this.artists.filter(artist => artist.id == artistId)[0].setAlbum(albumData.name, albumData.year);\n \n const album = new Album(albumData.name, albumData.year);\n album.setId(this.counter.getAlbumId())\n return artist.setAlbum(album);\n /* Crea un album y lo agrega al artista con id artistId.\n El objeto album creado debe tener (al menos)):\n - una propiedad name (string)\n - una propiedad year (number)\n */\n }", "function ensureItemIsInFeed () {\n\n if (!vm.activeFeed) {\n return;\n }\n\n var itemIndex = vm.activeFeed.playlist.findIndex(byMediaId(vm.item.mediaid));\n\n if (itemIndex === -1) {\n vm.activeFeed.playlist.unshift(item);\n }\n }", "function populateAlbums (albums, list) {\n\n\t\tfor (var album of albums) {\n\n\t\t\tvar albumTemplate = importTemplate('artist-album-template');\n\n\t\t\tvar albumName = albumTemplate.querySelector('.artist-album-name');\n\t\t\talbumName.textContent = album.name;\n\n\t\t\tvar viewAlbum = emitEvent('view-album', album.name);\n\t\t\talbumName.addEventListener('click', viewAlbum);\n\n\t\t\tvar songList = albumTemplate.querySelector('.album-songs');\n\t\t\tpopulateSongs(album.songs, songList);\n\n\t\t\tlist.appendChild(albumTemplate);\n\n\t\t}\n\n\t}", "loadAlbumTracks() {\n this._ApiFactory.getAlbumsTracks(this.albumId).query({}, (response) => {\n\n const tracks = [];\n response.items.forEach((i) => {\n const track = {\n name: i.name,\n images: i.images,\n duration: this.convertToMinutesSeconds(i.duration_ms)\n }\n tracks.push(track);\n });\n this.tracks = tracks;\n\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }", "addFavorites(song){\n if(this.existentFavorites){\n // Not in Favorites list, push it to the array\n //Get Song index in favorites array, when not found in array, songIndex = -1;\n let songIndex = this.existentFavorites.findIndex(i => i.id === song.id);\n\n if(songIndex === -1) {\n //Add to favorites array\n this.existentFavorites.push(song);\n } else {\n //Already in existentFavorites array, remove it\n this.existentFavorites.splice(songIndex, 1);\n }\n }\n\n //Update LocalStorage\n this.$localStorage.favorites = this.existentFavorites;\n\n //Emit broadcast to update the counter\n // this.$rootScope.$broadcast('onAddToFavoriteEvent', {\n // this.updateFavoriteCount();\n // });\n\n\n this.isFavorite(song);\n }", "function addSongToPlaylist( mixtape, change )\r\n{\r\n\r\n var idx = mixtape.playlists.findIndex((el) => el.id === change.playlistId)\r\n if ( idx === -1 )\r\n {\r\n console.log( \"Playlist with id '\"+change.playlistId+\"' does not exists\");\r\n return;\r\n }\r\n\r\n mixtape.playlists[idx].song_ids.push(change.songId);\r\n\r\n}", "function checkPhotos() {\n\tconsole.log('--checking for photos...');\n\tlet albumList;\n\ttry {\n\t\talbumList = db.getData('/albumList'); // todo, get albumList from real folder\n\t} catch (err) {\n\t\treturn;\n\t}\n\n\talbumList.forEach((albumInfo, albumIndex) => {\n\t\tlet albumPath = path.resolve(paths.albumsFolder, albumInfo.id);\n\t\tlet files = fs.readdirSync(albumPath);\n\t\tlet photos = files.filter((file) => {\n\t\t\treturn !utils.isHiddenItem(file) && utils.isFile(path.resolve(albumPath, file)) && utils.isImg(file);\n\t\t});\n\n\t\tif (photos.length !== albumInfo.images.length) {\n\t\t\t// photos in folder not accordance with db, update db\n\t\t\tlet images = photos.map((img) => {\n\t\t\t\tlet imgPath = path.resolve(albumPath, img);\n\t\t\t\tlet size = sizeOf(imgPath);\n\n\t\t\t\treturn {\n\t\t\t\t\tname: img,\n\t\t\t\t\tsize: [size.width, size.height],\n\t\t\t\t\tdate: fs.statSync(imgPath).birthtimeMs\n\t\t\t\t};\n\t\t\t});\n\n\t\t\timages.sort((a, b) => b.date - a.date);\n\n\t\t\tdb.push('/albumList[' + albumIndex + ']/images', images);\n\t\t}\n\t});\n}", "function addSongsToPlaylist (songs, playlistName, updateViewing, addToEnd) {\n var songIds = $.map(songs, function (song, i) { return { fileid: song.fileId() }; }),\n targetPos = 0;\n\n // if we're snagging, add to bottom (curretly assumes we add to active list)\n if (addToEnd) {\n targetPos = addToEnd;\n }\n\n return self.eventBus.request(\n tms.events.tt.playlist.add,\n {\n api: \"playlist.add\",\n playlist_name: playlistName,\n index: targetPos,\n song_dict: songIds\n },\n tms.events.ext.playlist.add\n )\n .done(function (data) {\n if (updateViewing) {\n var songList = self.songList(); \n self.songList([\"paused\"]);\n\n $.each(songs, function (i, song) {\n // if its a currentSongViewModel we need to convert\n if (song.upvotes) {\n var songModel = song.model.metadata.current_song;\n song = new tms.viewmodels.SongViewModel(songModel);\n } \n\n songList.push(song);\n });\n\n self.songList(songList);\n }\n\n // if the song is playing, mark the playlist\n $.each(songs, function (i, song) {\n if (song.fileId() === self.currentSong().fileId()) {\n $.each(self.playlists(), function (i, playlist) {\n if (playlist.name() === playlistName) {\n playlist.activeSongInList(true);\n return;\n }\n });\n }\n });\n\n // if we added to a non-active list, we need to reset active\n if (self.activePlaylist().name() !== playlistName) {\n self.resetActiveList();\n }\n });\n }", "function addSong(track) {\n socket.emit('add', playlist)\n if(queue.find(song => song.track.uri === track.uri)){\n alert('Song is already on playlist. Please pick another')\n }else{\n s.setAccessToken(`${user.access}`)\n s.addTracksToPlaylist(playlist.playlist.playlistId, [track.uri], function (err, obj) {\n if (err) {\n console.log(err)\n } else {\n getQueue(playlist)\n }\n })}\n }", "function addIfNotPresent(base, item) {\n var i = base.length;\n var found = false;\n while( i-- ) {\n if (base[i].id === item.id) {\n base[i].count++;\n found = true;\n }\n }\n if (!found) {\n item.count = 1;\n base.push(item);\n }\n\n}", "function addTrack() {\n SC.get('/tracks/' + track).then(function(player) {\n\n trackList.push({\n id: player.id,\n trackName: player.title,\n url: player.stream_url,\n artist: player.user.username\n });\n\n if (trackList.length === 1) {\n $('.picked-songs').empty();\n }\n $('.picked-songs').append('<li class=\"column column-block\"><button class=\"button small picked-song\" data-value=\"' + player.id + '\">' + player.title + '</button></li>');\n })\n $('#songName').attr('placeholder', 'Search for another song or artist!')\n }", "syncBanList() {\n let banList = this.omegga.getBanList();\n if (!banList) return;\n banList = banList.banList;\n\n // upsert all bans\n for (const banned in banList) {\n const entry = {\n type: 'banHistory',\n banned,\n bannerId: banList[banned].bannerId,\n created: parseBrickadiaTime(banList[banned].created),\n expires: parseBrickadiaTime(banList[banned].expires),\n reason: banList[banned].reason,\n };\n // depending on implementation, this could potentially check\n // if the ban was already added and emit some kind of\n // new ban event\n this.stores.players.update(entry, {$set: entry}, {upsert: true});\n }\n }", "function displayAddAlbum() {\n listMusicToAdd = new Array();\n $(\"#loading-wrapper\").css(\"display\", \"none\") //prevent the loading-wrapper to display when refreshing the page\n $(\"#container\").empty()\n $(\"#container\").append(`\n <div id=\"main\">\n <div id=\"addAlbumPage\">\n <div id = \"topPageAddAlbum\">\n <img id = \"imageAddAlbum\"src=\"${imageDefault}\" href\"image album\">\n <ol id=\"listMusicsToAdd\">\n </ol>\n </div>\n <form id=\"formAddMusic\">\n <div class=\"form-group\">\n <label for=\"musicTitle\">Titre :</label>\n <input type=\"text\" class=\"form-control\" id=\"musicTitle\">\n </div>\n <div class=\"form-group\">\n <label for=\"music\">Musique :</label>\n <input type=\"file\" class=\"form-control\" id=\"music\" accept=\"audio/*\">\n </div>\n <div class=\"form-group w-25\">\n <input value=\"Ajouter la musique\" type=\"submit\" class=\"form-control\" id=\"submitAddMusic\">\n </div>\n </form>\n <div id=\"errorAddingMusic\"></div>\n <div id =\"AddAlbumPlace\"> </div>\n </div>\n </div>`)\n $(\"#favorite\").empty();\n $('#favorite').append(`<a href=\"#\" data-url =\"/favorite\"> Favoris <i class=\"far fa-heart fa-2x\"></i> </a>`)\n $(\"#formAddMusic\").on(\"submit\", (e) => {\n e.preventDefault()\n if (!verifyType($(\"#music\").prop('files')[0], \"audio\")) {\n onErrorAddingMusic(new Error(\"Mauvais type de fichier.\\n Types acceptés : mp3, aif, flac, mid, wav\"))\n }else {\n $(\"#errorAddingMusic\").empty()\n setFileInfo(e, $(\"#music\").prop(\"files\")[0])\n }\n \n });\n if($(\"#navbar\").text().length == 0){\n displayNavBar();\n displayMenu();\n displayFooter();\n }\n}", "static getAlbums() {\n let albums;\n if (localStorage.getItem('albums') === null) {\n albums = [];\n } else {\n albums = JSON.parse(localStorage.getItem('albums'));\n }\n\n return albums;\n }", "function loadArtistsInSelect(album) {\r\n // array per controllo nomi degli artisti da caricare nella select\r\n var arraySelect = [];\r\n // ciclo per caricare i nomi artisti nella select\r\n for (var i = 0; i < album.length; i++) {\r\n // controlla se il nome artista è già stato inserito nella select\r\n if (!arraySelect.includes(album[i].author)) {\r\n // aggiune il nome artista nell'array di controllo dei nomi\r\n arraySelect.push(album[i].author);\r\n // aggiunge il nome artista alla select\r\n $(\".select-artist\").append(\"<option value='\"+album[i].author+\"'>\"+album[i].author+\"</option>\");\r\n };\r\n };\r\n}", "loadAlbumsDetails() {\n this._ApiFactory.getAlbumDetails(this.albumId).query({}, (response) => {\n\n this.album = {\n name: response.name,\n images: response.images\n }\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }", "function processSongs(songs) {\n // when building our data store we need to make sure not to create a duplicate entry for the artist\n // first we check if table['primary_artist'] exists \n // if it does \n // we increment that lyricSectionLength value by our lyricText length \n // if it doesn't \n // we create a new entry \n songs.map(song => {\n const lyricText = song.lyrics_text.split('\\n\\n');\n const found = ARTISTS_TABLE.some(el => el.artistName === song.primary_artist);\n if (!found) {\n // create a new entry for this artist\n let obj = {\n artistName: song.primary_artist,\n lyricSections: [],\n lyricSectionLength: null,\n };\n // go through the lyrics_text and break out into lyric sections \n obj.lyricSectionLength = lyricText.length;\n lyricText.map(lyricSection => {\n obj.lyricSections.push(lyricSection);\n });\n ARTISTS_TABLE.push(obj);\n } else {\n // primary_artist already exists in db \n // find artist in db\n // increment the lyricSectionLength value by our lyricText length\n ARTISTS_TABLE.map((el) => {\n if (el.artistName === song.primary_artist) {\n el.lyricSectionLength += lyricText.length;\n }\n });\n\n }\n });\n\n\n sortArtistsBySectionTotals(ARTISTS_TABLE);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is to make the Scrabble row droppable and let the program know where a piece is dropped.
function load_droppable_pieces() { var img_location = "scrabbleimages/scrabble_transparent.png"; // the image's location var drop = ""; var scrabbleDropID = "#drop" + i; console.log("Load Droppable Function") for(var i = 0; i < 15; i++) { scrabbleDropID = "#drop" + i; // Making the ID droppable $(scrabbleDropID).droppable ({ // I used the https://jqueryui.com/droppable/#default to help me understand the whole droppable idea drop: function(event, ui) { var drag_scrabbleID = ui.draggable.attr("id"); var drop_scrabbleID = $(this).attr("id"); scrabble_row[find_board_position(drop_scrabbleID)].tile = drag_scrabbleID; get_word(); console.log("Tile is: " + drag_scrabbleID + " - dropped on " + drop_scrabbleID); $(this).append($(ui.draggable)); ui.draggable.css("top", $(this).css("top")); ui.draggable.css("left", $(this).css("left")); ui.draggable.css("position", "relative"); get_word(); }, out: function(event, ui) { var drag_scrabbleID = ui.draggable.attr("id"); var drop_scrabbleID = $(this).attr("id"); if(drag_scrabbleID != scrabble_row[find_board_position(drop_scrabbleID)].tile) { return; } scrabble_row[find_board_position(drop_scrabbleID)].tile = "pieceX"; get_word(); } }); } }
[ "function dropPiece(evt, availableTiles, startx, starty)\n{\n var correct = 0; //variable that decides if the piece was placed in the correct spot\n for(var i = 0; i < availableTiles.length;i++)\n {\n if(intersect(availableTiles[i]))\n {\n correct = 1;\n evt.currentTarget.x = availableTiles[i].x;\n evt.currentTarget.y = availableTiles[i].y;\n var x = evt.currentTarget.gridx;\n var y = evt.currentTarget.gridy;\n var tilex = availableTiles[i].gridx;\n var tiley = availableTiles[i].gridy;\n grid[x][y].placedPiece = \"\"; //since the piece has been moved the starting square is free now\n if(grid[tilex][tiley].placedPiece != \"\")\n {\n stage.removeChild(grid[tilex][tiley].placedPiece); //removes the piece that was on that square from the board\n }\n grid[tilex][tiley].placedPiece = evt.currentTarget; //updates the grid to show that there's a piece on the board at that location\n evt.currentTarget.gridx = tilex;\n evt.currentTarget.gridy = tiley;\n\n break;\n }\n }\n cleanBoard(availableTiles); // cleans the board of all pieces\n\n if(correct == 0) // if the piece was not placed in the correct place, then return it to it's original square.\n {\n evt.currentTarget.x = grid[startx][starty].x;\n evt.currentTarget.y = grid[startx][starty].y;\n }\n else { //if the piece was moved then a turn was made and swap turns and update info\n var startSquare = starty*8+x;\n var endSquare = evt.currentTarget.gridy*8+evt.currentTarget.gridx;\n\n moveMade(startSquare, endSquare); //updates the internal logic of the game\n }\n\n parseFen(fenstr); //refreshes the board\n stage.update();\n}", "function drop(e){\r\n \r\n e.preventDefault();\r\n \r\n background_squares_paint(e.target.id.slice(4, 6), type, dir, \"#7e7e08\"); //It restores the original color of the lockers where the ship was dropped.\r\n\r\n if(ship_validation(type, Number(e.target.id.slice(4,6)), dir, own_board)){ //If the new position is validated...\r\n\r\n click_sound.play();\r\n \r\n var id = e.dataTransfer.getData(\"text/plain\");\r\n \r\n e.target.appendChild(document.getElementById(id)); //...the ship image is put on the board...\r\n\r\n switch(id){ //...and the Ship object is added to the user fleet array. Also the corresponding board positions are overwritten with the ship number.\r\n \r\n case \"ca\":\r\n own_fleet[0] = new Ship(5, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 0);\r\n break;\r\n \r\n case \"v1\":\r\n own_fleet[1] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 1);\r\n break;\r\n \r\n case \"v2\":\r\n own_fleet[2] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 2);\r\n break;\r\n \r\n case \"s1\":\r\n own_fleet[3] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 3);\r\n break;\r\n \r\n case \"s2\":\r\n own_fleet[4] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 4);\r\n break;\r\n \r\n case \"s3\":\r\n own_fleet[5] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 5);\r\n break;\r\n \r\n case \"c1\":\r\n own_fleet[6] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 6);\r\n break;\r\n \r\n case \"c2\":\r\n own_fleet[7] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 7);\r\n break;\r\n \r\n case \"c3\":\r\n own_fleet[8] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 8);\r\n break;\r\n \r\n case \"c4\":\r\n own_fleet[9] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 9);\r\n break;\r\n \r\n case \"b1\":\r\n own_fleet[10] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 10);\r\n break;\r\n \r\n case \"b2\":\r\n own_fleet[11] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 11);\r\n break;\r\n \r\n case \"b3\":\r\n own_fleet[12] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 12);\r\n break;\r\n \r\n case \"b4\":\r\n own_fleet[13] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 13);\r\n break;\r\n \r\n case \"b5\":\r\n own_fleet[14] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 14);\r\n break;\r\n } \r\n }else{ //If the position was not validated, it reports the rejection to the user.\r\n\r\n sign(\"Forbidden place! \\n Please, try again.\");\r\n }\r\n}", "function drop(ev) {\n $('.tile').removeClass('hover');\n ev.preventDefault();\n\n const tile = $(ev.target);\n const row = tile.attr('row');\n const col = tile.attr('col');\n\n if (row !== undefined) {\n if (dragElement.attr('row') !== undefined) {\n const oldRow = dragElement.attr('row');\n const oldCol = dragElement.attr('col');\n craftingTable.insertItem(oldRow, oldCol, null);\n }\n\n craftingTable.insertItem(row, col, dragItem);\n craftingTable.removeResult();\n craftingTable.display();\n }\n}", "function mouseDrop(e) {\n\n if(dropValid(mousePiece)) {\n\n alignPiece(mousePiece);\n\n removeEvent(document, \"mousemove\", mouseMove, false);\n removeEvent(document, \"mouseup\", mouseDrop, false);\n mousePiece.style.cursor = \"pointer\";\n solveCheck()\n }\n }", "function load_droppable_targets() {\r\n var img_url = \"img/graphics_data/Scrabble_Blank.png\"; // URL of the blank image\r\n var drop = \"<img class='droppable' id='drop\" + i + \"' src='\" + img_url + \"'></img>\";\r\n var drop_ID = \"#drop\" + i;\r\n\r\n for(var i = 0; i < 15; i++) {\r\n drop = \"<img class='droppable' id='drop\" + i + \"' src='\" + img_url + \"'></img>\";\r\n drop_ID = \"#drop\" + i;\r\n var pos = $(\"#the_board\").position();\r\n var img_left = 0;\r\n var img_top = -125;\r\n\r\n // Add the img to the screen.\r\n $(\"#board\").append(drop);\r\n\r\n // Reposition the img relative to the board.\r\n $(drop_ID).css(\"left\", img_left).css(\"top\", img_top).css(\"position\", \"relative\");\r\n\r\n // Make the img droppable\r\n $(drop_ID).droppable({\r\n // https://jqueryui.com/droppable/#default\r\n // https://stackoverflow.com/questions/5562853/jquery-ui-get-id-of-droppable-element-when-dropped-an-item\r\n // https://api.jqueryui.com/droppable/#event-out\r\n\r\n drop: function(event, ui) {\r\n var draggableID = ui.draggable.attr(\"id\");\r\n var droppableID = $(this).attr(\"id\");\r\n // Mark the game board var\r\n game_board[find_board_pos(droppableID)].tile = draggableID;\r\n find_word();\r\n },\r\n out: function(event, ui) {\r\n var draggableID = ui.draggable.attr(\"id\");\r\n var droppableID = $(this).attr(\"id\");\r\n\r\n // false movement prevention\r\n if(draggableID != game_board[find_board_pos(droppableID)].tile) {\r\n console.log(\"FALSE ALARM DETECTED.\");\r\n return;\r\n }\r\n\r\n // Mark that a tile was removed \r\n game_board[find_board_pos(droppableID)].tile = \"pieceX\";\r\n\r\n // Update the word\r\n find_word();\r\n }\r\n });\r\n }\r\n}", "drop() {\n this.pos.y++;\n\n if(this.rotatingPieces)\n this.rotate(+1);\n\n this.dropCounter = 0;\n if(this.arena.collide(this)) {\n \n // this.dropInterval = this.DROP_SLOW; // Fix attempt of weird bug // commented because it \"removes\" HASTE\n \n // update position\n this.pos.y--;\n this.arena.merge(this);\n \n let sweepObj = this.arena.sweep();\n this.score += sweepObj.score;\n \n if(sweepObj.rows > 0) {\n this.amountOfBrokenRows += sweepObj.rows;\n this.changeSpeed(sweepObj.rows); \n }\n\n if(sweepObj.rows) {\n this.sendDebuff(sweepObj.rows);\n }\n\n this.events.emit('score', this.score);\n \n this.reset();\n return true; // return true when we collide (used to implement the space btn)\n }\n \n this.events.emit('pos', this.pos);\n }", "function dragdropElementos(){\n $('img').draggable({\n\t\tcontainment: '.panel-tablero',\n grid: [115, 95],\n droppable: 'img',\n\t\trevert: true,\n\t\trevertDuration: 100,\n\t\topacity: 0.8,\n\t\tzIndex: 1,\n\t});\n\t$('img').droppable({\n\t\tdrop: intercambiar\n\t});\n}", "onDragDrop() {\n this.onDragEnd();\n\n // If we dropped a flower at a new position, report that we made a move\n // and generate new flowers\n if (!Map(this._originalTargetCell).equals(Map(this._currentCell))) {\n this.board.resolveMoveAt(this._currentCell);\n }\n }", "async function trigger_drop() {\n resumeGame();\n if (demoIsRunning){\n demoIsRunning = false;\n $(\"#demoLink\").text(\"DEMO\");\n location.reload();\n return;\n }\n \n demoIsRunning= true;\n $(\"#demoLink\").text(\"RESET\");\n \n droppable_items_count *=2;\n\n $draggable_items = $('#draggables').find('.draggable').toArray(); // object -> array\n for (let i = 1; i <13;i++){\n console.log(\"#draggable\"+i + \"...\" + \"#droppable\" + i);\n let draggable = $(\"#draggable\"+i).draggable(),\n droppable = $(\"#droppable\"+i).droppable(),\n droppableOffset = droppable.offset(),\n draggableOffset = draggable.offset(),\n dx = droppableOffset.left - draggableOffset.left,\n dy = droppableOffset.top - draggableOffset.top;\n console.log(i+ \".. dx:\" + dx + \" ... dy:\" + dy);\n \n draggable.animate({\n \"left\": dx - (draggable.width()-droppable.width())/2,\n \"top\": dy - (draggable.height()-droppable.height())/2\n });\n await sleep (200);\n }\n\n await sleep (1000);\n window.alert(\"Pre spustenie hry, je po deme potrebné stlačiť tlačídlo - reset.\");\n pauseGame();\n}", "function drag_start(e){\r\n \r\n e.preventDefault\r\n \r\n//It prepares the image dragged to fit the right size.\r\n dragged_ship.src = e.target.getAttribute(\"src\");\r\n \r\n dragged_ship.className = e.target.className;\r\n \r\n e.dataTransfer.setDragImage(dragged_ship, 15, 15);\r\n \r\n//It stores the dragged ship orientation for the next \"Drag and Drop\" functions.\r\n if(e.target.className == \"vertical\")\r\n dir = 0;\r\n else\r\n dir = 1;\r\n \r\n//It stores the dragged ship type for the next \"Drag and Drop\" functions.\r\n if(e.target.id.startsWith(\"ca\")) \r\n type = 5;\r\n\r\n else if(e.target.id.startsWith(\"v\"))\r\n type = 4;\r\n\r\n else if(e.target.id.startsWith(\"s\"))\r\n type = 3;\r\n\r\n else if(e.target.id.startsWith(\"c\"))\r\n type = 2;\r\n else\r\n type = 1;\r\n \r\n//It set up the Id of event Target as data to be transferred.\r\n e.dataTransfer.setData(\"text/plain\", e.target.id);\r\n \r\n//It cleans the board if the dragged ship still was on it.\r\n if(e.target.parentElement.className == \"square\")\r\n clean_position_ship_draw(e.target, e.target.parentElement.id.slice(4, 6));\r\n}", "function dropBubble(column, duration) {\n var bubble = $.parseHTML('<div class=\"bubble\"></div>');\n\n var x_pos = 40 * column;\n\n // ASSIGN PROPERTIES TO BUBBLES\n var red = Math.floor(Math.random() * 256);\n var green = Math.floor(Math.random() * 256);\n var blue = Math.floor(Math.random() * 256);\n\n $(bubble).css('left', x_pos + 'px');\n $(bubble).css('top', '-25px');\n $(bubble).css('background-color', 'rgb('+red+', '+green+', '+blue+')');\n\n $('#main-container').append(bubble);\n $(bubble).animate( \n {top: '470px'},\n duration * 1, \n \"linear\",\n function () { bubbleHit(bubble, column, duration); }\n );\n }", "function drop_bag(player_obj, contents) {\n\tconsole.log(\"dropping bag\");\n\tif (player_obj.death_bag != null) {\n\t\tvar new_bag = player_obj.death_bag;\n\t\tnew_bag.data.keys = player_obj.inventory.keys;\n\t\tnew_bag.data.augs = player_obj.inventory.augments;\n\t\tnew_bag.data.weapons = player_obj.inventory.weapons;\n\t\tnew_bag.data.loc.x = player_obj.data.x;\n\t\tnew_bag.data.loc.y = player_obj.data.y;\n\t\tnew_bag.data.exp = player_obj.data.exp+player_obj.data.exp_past;\n\t\tcontents.push(new_bag);\n\t\tplayer_obj.death_bag = null;\n\t}\n}", "function spawnDropZone() {\n Sortable.create(trash, {\n group: \"tag\",\n onAdd: function(evt) {\n this.el.removeChild(evt.item)\n }\n })\n Sortable.create(dep, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(arr, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(push, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(taxi, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(rwy, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy1, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy2, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy3, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy4, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy5, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy6, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy7, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy8, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy9, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy10, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n\n}", "function mouseGrab(e) {\n console.log(\"mouseGrab\");\n var evt = e|| window.event;\n mousePiece = evt.target || evt.srcElement;\n maxZ ++;\n\n //Remove piece from array and stop animation\n $(mousePiece).stop(true);\n var index = movingPieces.indexOf(mousePiece);\n movingPieces.splice(index, 1);\n console.log(movingPieces);\n\n //Loop through an array with all removed pieces and assign a stop() to them\n // I think the updating of the animate array is a bit slow so it doesn't always apply when you click the piece\n stoppedPieces.push(mousePiece);\n\n mousePiece.style.zIndex = maxZ; // Place the piece above other objects\n\n mousePiece.style.cursor = \"move\";\n\n var mouseX = evt.clientX; // x-coordinate of pointer\n var mouseY = evt.clientY; // y-coordinate of pointer\n\n /* Calculate the distance from the pointer to the piece */\n diffX = parseInt(mousePiece.style.left) - mouseX;\n diffY = parseInt(mousePiece.style.top) - mouseY;\n\n /* Add event handlers for mousemove and mouseup events */\n addEvent(document, \"mousemove\", mouseMove, false);\n addEvent(document, \"mouseup\", mouseDrop, false);\n }", "function dragFixup(e, ui, col, row) {\n\n var targetId = idFromLocation(col, row);\n var targetX = parseInt($('#'+targetId).attr('data-col'));\n var targetY = parseInt($('#'+targetId).attr('data-row'));\n var targetSizeX = parseInt($('#'+targetId).attr('data-sizex'));\n var targetSizeY = parseInt($('#'+targetId).attr('data-sizey'));\n var targetGrid = $('#'+targetId);\n var startGrid = $('#'+dragStartId);\n if(targetId == dragStartId) {\n // startGrid.offset({\n // top: dragStartOffset.top\n // });\n // setTimeout(function(){\n // startGrid.offset({\n // left: dragStartOffset.left\n // });\n // },500);\n // startGrid.removeClass('player');\n \n } else {\n var startOffset = startGrid.offset();\n var targetOffset = targetGrid.offset();\n startGrid.attr({\n 'data-col': targetGrid.attr('data-col'),\n 'data-row': targetGrid.attr('data-row'),\n 'data-sizex': targetGrid.attr('data-sizex'),\n 'data-sizey': targetGrid.attr('data-sizey')\n });\n startGrid.offset({\n top: targetOffset.top,\n left: targetOffset.left\n });\n targetGrid.attr({\n 'data-col': dragStartX,\n 'data-row': dragStartY,\n 'data-sizex': dragStartSizeX,\n 'data-sizey': dragStartSizeY\n });\n setTimeout(function(){\n targetGrid.offset({\n top: dragStartOffset.top,\n left: dragStartOffset.left\n });\n }, 200);\n \n }\n }", "function capture(capturing_piece_id,square,type=\"\"){\n \n const draggableElement = document.getElementById(capturing_piece_id);\n\n let sqtarget_id = square.id\n let sqtarget_letter = sqtarget_id.slice(0,1);\n let sqtarget_letter_digit = getCodeFromLetter(sqtarget_letter);\n let sqtarget_num = parseInt(sqtarget_id.slice(-1));\n\n if(type===\"enpassant\"){ //enpassant case\n if(sqtarget_num===6){ //wpawn captures bpawn\n let captured_square = document.getElementById((sqtarget_letter+(sqtarget_num-1)));\n addToCapturedList(captured_square.firstChild);\n captured_square.innerHTML=\"\";\n }else{ //otherwise bpawn captures wpawn\n let captured_square = document.getElementById((sqtarget_letter+(sqtarget_num+1)));\n addToCapturedList(captured_square.firstChild);\n captured_square.innerHTML=\"\";\n }\n \n }else{\n addToCapturedList(square.firstChild);\n \n }\n\n square.innerHTML=\"\";\n square.appendChild(draggableElement);\n}", "function dragAndDropItem() {\n $(\".empName\").each(function(){\n $(this).draggable({helper : \"clone\"});\n });\n $(\"#rolesTable ul > li\").droppable({\n drop: function(event, ui) {\n var $className = $(this).find('ul').attr(\"class\");\n if (!($(ui.draggable).hasClass($className))) {\n $(ui.draggable).addClass($className);\n var $li = insert_element($(\"<li></li>\").attr(\"emp\",$(ui.draggable).text()), \"newRow\", $(this).find('ul'));\n $li.text($(ui.draggable).text());\n insert_element($(\"<input/>\").attr(\"type\",\"image\").attr(\"src\",\"images/button.jpg\"), \"cancelButton\", $li);\n updateToDo($className, $(ui.draggable).text());\n }\n onhoverElement($(this).find(\"ul li\"));\n }\n });\n}", "dropTiles() {\n //If we're in drop mode, drop every falling tile by the drop speed.\n //Once the drop distance reaches (or exceeds) the point where the falling\n //tiles reach the next row below it (where the empty tiles are), overwrite\n //the empty tiles with the falling tiles. Copy a new grid, to be safe.\n //Also, don't forget to refresh the buffer above the grid.\n \n if (this.dropTilesNow) {\n this.dropDistance += this.dropSpeed;\n \n if (this.dropDistance > this.TILE_SIZE) {\n const newGrid = this.grid.map((tile) => {\n const tileAbove = this.grid.find((ta) => {\n return ta.row === tile.row - 1 && ta.col === tile.col;\n });\n \n if (tileAbove && tileAbove.isDropping) { //If it's an empty tile receiving a falling tile, overwrite it.\n return {\n row: tile.row,\n col: tile.col,\n value: tileAbove.value,\n isDropping: false,\n };\n } else if (!tileAbove) { //If it's a tile in the buffer row, refresh it.\n return {\n row: tile.row,\n col: tile.col,\n value: this.TILES.random(),\n isDropping: false,\n }\n } else { //Otherwise, keep the tile.\n return {\n row: tile.row,\n col: tile.col,\n value: tile.value,\n isDropping: false,\n };\n }\n });\n this.grid = newGrid;\n \n this.dropDistance = 0;\n this.dropTilesNow = false; //OK, stop dropping.\n }\n }\n \n //Now check if we need to continue dropping.\n //For each tile, check if there's an empty tile below it. If there is, mark\n //the tile as a falling tile.\n\n let doneDropping = true;\n this.grid.map((tile) => {\n const tileBelow = this.grid.find((tb) => {\n return tb.row === tile.row + 1 && tb.col === tile.col;\n });\n if (tileBelow && (tileBelow.value === this.TILES.EMPTY || tileBelow.isDropping)) {\n tile.isDropping = true;\n this.dropTilesNow = true;\n doneDropping = false; //Gotta keep dropping!\n }\n });\n\n return doneDropping;\n }", "function _bindDraggableForDay() {\n var isMouseDown = false,\n isActive;\n $(\"#matrix td\")\n .mousedown(function(e) {\n var all = document.querySelectorAll('td.active'),\n first = '',\n last = '',\n rowID;\n for(var i = 0; i < all.length; i++) {\n if(all[i].id === '')\n all[i].parentNode.removeChild(all[i]);\n }\n var info = this.id.split('-');\n all = document.querySelectorAll('td.active');\n if(all.length > 0) {\n first = parseInt(all[0].id.split('-')[2]);\n last = parseInt(all[all.length - 1].id.split('-')[2]);\n rowID = parseInt(this.id.split('-')[2]);\n if((rowID !== (first - 1) && rowID !== (last + 1)) && (rowID !== first && rowID !== last)) {\n snackBar(\"Uma reserva deverá conter um conjunto de horas consecutivas.\");\n } else {\n if(columnID === '' || this.id.split('-')[1] === columnID) {\n isMouseDown = true;\n columnID = this.id.split('-')[1];\n $(this).toggleClass(\"active\");\n isActive = $(this).hasClass(\"active\");\n return false; // prevent text selection\n } else if(this.id.split('-')[1] !== columnID) {\n snackBar(\"Uma reserva deverá conter apenas uma Sala.\");\n }\n }\n } else {\n rowID = parseInt(this.id.split('-')[2]);\n if (columnID === '' || this.id.split('-')[1] === columnID) {\n isMouseDown = true;\n columnID = this.id.split('-')[1];\n $(this).toggleClass(\"active\");\n isActive = $(this).hasClass(\"active\");\n return false; // prevent text selection\n } else if(this.id.split('-')[1] !== columnID) {\n snackBar(\"Uma reserva deverá conter apenas uma Sala.\");\n }\n }\n })\n .mouseover(function() {\n if (isMouseDown && this.id.split('-')[1] === columnID) {\n var rowID = parseInt(this.id.split('-')[2]);\n // if (isEven(rowID))\n // var id = 'td-' + columnID + '-' + (rowID + 1);\n // else\n // var id = 'td-' + columnID + '-' + (rowID - 1)\n // if (!document.getElementById(id).classList.contains('active'))\n // document.getElementById(id).classList.add('active');\n $(this).toggleClass(\"active\", isActive);\n }\n\n });\n $(document)\n .mouseup(function() {\n isMouseDown = false;\n var activeElements = document.querySelectorAll('td.active');\n if(activeElements.length === 0)\n columnID = '';\n pushToSideBar(\"matrix_day_body\");\n });\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update progress bar and notify server about checked and unchecked checkboxes
function showProgress() { let progressBar = document.getElementById('myBar'); let count = 0; for (let x = 0; x < checkboxes.length; x += 1) { if (checkboxes[x].checked) { checkboxes[x].nextElementSibling.nextElementSibling.removeAttribute('hidden'); count += 1; // When checkbox is checked, send message to server. socket.emit('checked', {message: checkboxes[x].value, id: checkboxes[x].id, list: checkboxes[x].getAttribute('data-list')}); } else if (!checkboxes[x].checked) { checkboxes[x].nextElementSibling.nextElementSibling.setAttribute('hidden', true); // When checkbox is unchecked, send message to server. socket.emit('unchecked', {message: checkboxes[x].value, id: checkboxes[x].id, list: checkboxes[x].getAttribute('data-list')}); } } let percent = percentPerBox * count; progressBar.style.width = percent + '%'; }
[ "function updateStatus() {\n\tfor (let i = 0; i < inputs.length; i++) {\n\t\tif (inputs[i].checked === true) {\n\t\t\tlistItems[i].classList.add('completed');\n\t\t\ttasks[i].completed = true;\n\t\t} else {\n\t\t\tlistItems[i].classList.remove('completed');\n\t\t\ttasks[i].completed = false;\n\t\t}\n\t}\n\n\t// d) Tareas totales. Cada vez que una tarea se marque/desmarque deberíamos actualizar esta información.\n\n\tlet message = document.querySelector('.message');\n\n\tlet completedTasks = document.querySelectorAll('input:checked').length;\n\n\tlet incompleteTasks = parseInt(tasks.length) - parseInt(completedTasks);\n\n\t// Actualizamos mensaje\n\tmessage.innerHTML = `Tienes ${tasks.length} tareas. ${completedTasks} completadas y ${incompleteTasks} por realizar.`;\n}", "function updateCompletedBtn() {\n var checkedCount = $(\"#itemsList input[type=checkbox]:checked\").length;\n\n $(\"#completeItemBtn\").prop(\"disabled\", checkedCount === 0);\n}", "function ready() {\n // Connect to socket.io.\n let socket = io();\n\n let dates = document.getElementsByClassName('date');\n\n for (let x = 0; x < dates.length; x += 1) {\n let d = new Date(dates[x].textContent);\n let months = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December'];\n dates[x].textContent = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();\n }\n\n let lockImg = document.getElementsByClassName('lockImg');\n\n for (let i = 0; i < lockImg.length; i += 1) {\n lockImg[i].addEventListener('click', function(event) {\n lockList(event.target);\n });\n }\n\n // Toggle padlock image and save locked value to database\n function lockList(clickedImg) {\n let src = document.getElementById(clickedImg.id).src;\n let addGoalButton = document.getElementById(clickedImg.id).parentNode.getElementsByClassName('addGoal')[0];\n\n if (src.indexOf('padlock-green.png') != -1) {\n addGoalButton.setAttribute('hidden', true);\n document.getElementById(clickedImg.id).src = '/images/padlock-red.png';\n } else {\n addGoalButton.removeAttribute('hidden');\n document.getElementById(clickedImg.id).src = '/images/padlock-green.png';\n }\n\n socket.emit('lockList', {id: clickedImg.id, list: clickedImg.getAttribute('data-list')});\n }\n\n let checkboxes = document.getElementsByClassName('checkbox');\n let percentPerBox = 100 / checkboxes.length;\n let theCount = 0;\n\n for (let i = 0; i < checkboxes.length; i += 1) {\n checkboxes[i].addEventListener('click', showProgress);\n if (theCount === 0 && checkboxes[i].checked) {\n theCount += 1;\n showProgress();\n }\n }\n\n // Update progress bar and notify server about checked and unchecked checkboxes\n function showProgress() {\n let progressBar = document.getElementById('myBar');\n let count = 0;\n\n for (let x = 0; x < checkboxes.length; x += 1) {\n if (checkboxes[x].checked) {\n checkboxes[x].nextElementSibling.nextElementSibling.removeAttribute('hidden');\n count += 1;\n // When checkbox is checked, send message to server.\n socket.emit('checked', {message: checkboxes[x].value, id: checkboxes[x].id, list: checkboxes[x].getAttribute('data-list')});\n } else if (!checkboxes[x].checked) {\n checkboxes[x].nextElementSibling.nextElementSibling.setAttribute('hidden', true);\n // When checkbox is unchecked, send message to server.\n socket.emit('unchecked', {message: checkboxes[x].value, id: checkboxes[x].id, list: checkboxes[x].getAttribute('data-list')});\n }\n }\n\n let percent = percentPerBox * count;\n progressBar.style.width = percent + '%';\n }\n}", "#updateFormProgress() {\n if (this.#steps?.length) {\n let activeStepIndex = this.#steps.findIndex(\n ({ name }) => name === this.activeStep\n );\n let activeStepCount = activeStepIndex + 1;\n let progress =\n Math.ceil((activeStepIndex / (this.#steps.length - 1)) * 100) || 10;\n let indicator = this.#progressBar.querySelector(\".indicator\");\n indicator.style.setProperty(\"--progress\", progress + \"%\");\n // Ensure progressbar starts translated at -100% before we\n // set --progress to avoid a layout race.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n indicator.toggleAttribute(\"ready\", true);\n });\n });\n this.#progressBar.setAttribute(\"aria-valuenow\", activeStepCount);\n this.#progressBar.setAttribute(\n \"aria-label\",\n interpolate(gettext(\"Step %s of %s\"), [\n activeStepCount,\n this.#steps.length,\n ])\n );\n }\n }", "function updateProcessing(id,percent,state){\n\t\tvar stateBar = getStateBarElement(id);\n\t\tstateBar.innerHTML=state;\n\t\tupdateProgressBar (id, percent);\n\t}", "function updateStatus() {\n Packlink.ajaxService.get(\n checkStatusUrl,\n /** @param {{logs: array, finished: boolean}} response */\n function (response) {\n let logPanel = document.getElementById('pl-auto-test-log-panel');\n\n logPanel.innerHTML = '';\n for (let log of response.logs) {\n logPanel.innerHTML += writeLogMessage(log);\n }\n\n logPanel.scrollIntoView();\n logPanel.scrollTop = logPanel.scrollHeight;\n response.finished ? finishTest(response) : setTimeout(updateStatus, 1000);\n }\n );\n }", "function updateProgress()\n{\n /* Set the width of the progress bars */\n for (const e of progressElts)\n e.style.width = 100 * curslide.b6slidenum / numslides + \"%\";\n\n /* Set the content of .slidenum elements to the current slide number */\n for (const e of slidenumElts)\n e.textContent = curslide.b6slidenum;\n}", "function itemCheckboxListener(event) {\n // HINT: '$(this)' is the checkbox that triggered the event \n // TODO: Use jQuery to save the value of the checkbox as the 'id'\n let id = $(this).val();\n // TODO: Use jQuery to save the html of the span with the id item_text in 'text'\n let text = $(this).parent().find(\"span#item_text\").html();\n // TODO: Use jQuery to save whether the checkbox is checked or not\n let is_complete = $(this).prop('checked');\n\n // Creating the object to send to the server\n let data = {id: id,\n text: text,\n is_complete: is_complete};\n\n // debug message, does the object contain all the right values?\n console.log(\"itemCheckBoxListener\", data);\n\n /* TODO: Create an AJAX call to POST data to the target url:\n * engine.php?a=update\n * TODO: When the response comes back, add or emove the CSS class\n * \"completed\" depending on the value of 'is_complete'.\n * NOTE: \n * Remeber that the JSON response contains item and debug_info.\n */\n \n $.post(\"engine.php?a=update\", data,function(response){\n let json = JSON.parse(response);\n \n (json.item.is_complete ? $(\"li#item_\"+json.item.id).addClass(\"completed\"):\n $(\"li#item_\"+json.item.id).removeClass(\"completed\"))\n });\n}", "function updateStatus() {\n\tchrome.extension.sendRequest(\n\t\t\t{type: \"status?\"}\n\t\t, function(response) {\n\t\t\t$(\"ws_status\").textContent=response.ws_status;\n\t\t\t$(\"pn_status\").textContent=response.pn_status;\n\t\t\t});\t\t\n}", "updateCheck() {\r\n this.setState((oldState) => {\r\n return {\r\n checked: !oldState.checked,\r\n };\r\n });\r\n this.updateChart(this.state.checked)\r\n }", "function checkState() {\n \n \n if(currentState.running == false) {\n return;\n }\n \n // get request of the job information\n $.ajax({\n url: \"job?id=\" + currentState.currentId\n , type: \"GET\"\n\n , success: function (data) {\n \n currentState.running = data.finished !== true;\n currentState.ready = data.finished;\n currentState.status = data.status;\n currentState.fileName = data.fileName;\n if (currentState.running) {\n setTimeout(checkState, 1000);\n }\n updateView();\n } \n });\n}", "function updateCheckCount() {\n var checkedCount = $(\"#itemsList input[type=checkbox]:checked\").length;\n var checkBoxCount = $(\"#itemsList input[type=checkbox]\").length;\n var selectBtn = $(\"#selectItemBtn\");\n\n if (checkedCount == checkBoxCount && checkBoxCount != 0) {\n selectBtn.val(\"Deselect all\");\n }\n else if (checkedCount != checkBoxCount || checkBoxCount == 0) {\n selectBtn.val(\"Select all\");\n }\n\n selectBtn.prop(\"disabled\", checkBoxCount == 0);\n}", "reportProgress (synced, prog) {\n const page = this.page\n if (synced) {\n page.progress.textContent = '100'\n Doc.hide(page.syncUncheck, page.syncRemainBox, page.syncSpinner)\n Doc.show(page.syncCheck)\n this.progressed = true\n if (this.funded) this.success()\n return\n } else if (prog === 1) {\n Doc.hide(page.syncUncheck)\n Doc.show(page.syncSpinner)\n } else {\n Doc.hide(page.syncSpinner)\n Doc.show(page.syncUncheck)\n }\n page.progress.textContent = Math.round(prog * 100)\n\n // The remaining time estimate must be based on more than one progress\n // report. We'll cache up to the last 20 and look at the difference between\n // the first and last to make the estimate.\n const cacheSize = 20\n const cache = this.progressCache\n cache.push({\n stamp: new Date().getTime(),\n progress: prog\n })\n while (cache.length > cacheSize) cache.shift()\n if (cache.length === 1) return\n Doc.show(page.syncRemainBox)\n const [first, last] = [cache[0], cache[cache.length - 1]]\n const progDelta = last.progress - first.progress\n if (progDelta === 0) {\n page.syncRemain.textContent = '> 1 day'\n return\n }\n const timeDelta = last.stamp - first.stamp\n const progRate = progDelta / timeDelta\n const toGoProg = 1 - last.progress\n const toGoTime = toGoProg / progRate\n page.syncRemain.textContent = Doc.formatDuration(toGoTime)\n }", "function progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}", "function handleCheck(e) {\n\t\tsetIsComplete(e.target.checked)\n\t}", "function updateWorkflowStatus(workflowResponse) {\n\n var JSONresponse = JSON.parse(workflowResponse);\n var statusIndicator = document.getElementById(\"myWorkflowStatus\");\n var statusLoader = document.getElementById(\"myLoader\");\n var statusLoaderBar = document.getElementById(\"myLoaderBar\");\n var status = JSONresponse.status;\n statusIndicator.innerHTML = status;\n\n var workflowButton = document.getElementById(\"myWorkflowButton\");\n var tasks = JSONresponse.tasks;\n var numTasks = JSONresponse.workflowDefinition.tasks.length;\n \n if (status == \"RUNNING\") {\n statusLoader.style.visibility = \"visible\";\n workflowButton.disabled = true;\n\n for (var i = 0; i < tasks.length; i++) {\n \n if (tasks[i].status == \"SCHEDULED\" || (tasks[i].status == \"COMPLETED\" && typeof tasks[i + 1] == 'undefined') || (tasks[i].status == \"FAILED\" && typeof tasks[i + 1] == 'undefined')) {\n if (tasks[0].status == \"SCHEDULED\") {\n updateStatusBar(statusLoaderBar, 0);\n }\n statusIndicator.innerHTML = status + \": \" + tasks[i].referenceTaskName;\n } else if (tasks[i].status == \"COMPLETED\") {\n updateStatusBar(statusLoaderBar, (i + 1) / numTasks);\n }\n }\n\n } else if (status == \"COMPLETED\") {\n updateStatusBar(statusLoaderBar, 1);\n workflowButton.disabled = false;\n\n //update series table\n var series_url = URL.eis_qido + \"/EIS.DCM/studies/\" + selectedStudyUID + \"/series?includeField=0008103E,0020000E,00200011,00201209\";\n getSeries(series_url);\n clearInterval(interval);\n\n //update results\n for (var i = 0; i < tasks.length; i++) {\n if (tasks[i].referenceTaskName == \"ai_inferencing\") {\n statusIndicator.innerHTML = status + \" \" + tasks[i].outputData.response.body.prediction[0].geClass + \": Probability = \" + tasks[i].outputData.response.body.prediction[0].probability;\n }\n }\n \n } else {\n updateStatusBar(statusLoaderBar, 1);\n workflowButton.disabled = false;\n clearInterval(interval);\n for (var i = 0; i < tasks.length; i++) {\n if (tasks[i].outputData.response.reasonPhrase == \"BAD REQUEST\") {\n alert(status + \": \" + tasks[i].outputData.response.body.message);\n }\n }\n }\n}", "function Notify() {\n\t\t//fined not checked products from all\n\t\tconst arrayCount = stateProducts.filter(product => (product.bought !== 'checked' && true))\n\t\tsetCount(() => arrayCount.length);\n\t\treturn (arrayCount.length);\n\t}", "function updateBtn(val)\n{\n\n\t//Get the list of the Episode check boxes.\n\tvar fmEpisodeList = Util.Style.g('fmCheck'); //007\n\t\n\tif (fmEpisodeList[val].checked == true) //007 if the item is checked, then add the btnCnt\n\t{\n\t\tbtnCnt++;\n\t}\n\telse //uncheck checkbox\n\t{\n\t\tbtnCnt--; \n\t}\n\t \n\t//if no box is checked or more than 3 boxes are checked, then disabled the Show button\t\n\tif (btnCnt == 0 || btnCnt > 3) //007\n\t{\n\t\t document.getElementById(\"shwBtn\").disabled = true; //007\n\t}\n\telse //007\n\t{\n\t\t document.getElementById(\"shwBtn\").disabled = false; //007\n\t}\n}", "setupDownloadingUI() {\n this.downloadStatus = document.getElementById(\"downloadStatus\");\n this.downloadStatus.textContent = DownloadUtils.getTransferTotal(\n 0,\n this.update.selectedPatch.size\n );\n this.selectPanel(\"downloading\");\n this.aus.addDownloadListener(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reads exactly `p.length` bytes into `p`. If successful, `p` is returned. If the end of the underlying stream has been reached, and there are no more bytes available in the buffer, `readFull()` returns `EOF` instead. An error is thrown if some bytes could be read, but not enough to fill `p` entirely before the underlying stream reported an error or EOF. Any error thrown will have a `partial` property that indicates the slice of the buffer that has been successfully filled with data. Ported from
async readFull(p) { let bytesRead = 0; while (bytesRead < p.length) { try { const rr = await this.read(p.subarray(bytesRead)); if (rr === Deno.EOF) { if (bytesRead === 0) { return Deno.EOF; } else { throw new UnexpectedEOFError(); } } bytesRead += rr; } catch (err) { err.partial = p.subarray(0, bytesRead); throw err; } } return p; }
[ "async read(p) {\n let rr = p.byteLength;\n if (p.byteLength === 0)\n return rr;\n if (this.r === this.w) {\n if (p.byteLength >= this.buf.byteLength) {\n // Large read, empty buffer.\n // Read directly into p to avoid copy.\n const rr = await this.rd.read(p);\n const nread = rr === Deno.EOF ? 0 : rr;\n asserts_ts_1.assert(nread >= 0, \"negative read\");\n // if (rr.nread > 0) {\n // this.lastByte = p[rr.nread - 1];\n // this.lastCharSize = -1;\n // }\n return rr;\n }\n // One read.\n // Do not use this.fill, which will loop.\n this.r = 0;\n this.w = 0;\n rr = await this.rd.read(this.buf);\n if (rr === 0 || rr === Deno.EOF)\n return rr;\n asserts_ts_1.assert(rr >= 0, \"negative read\");\n this.w += rr;\n }\n // copy as much as we can\n const copied = util_ts_1.copyBytes(p, this.buf.subarray(this.r, this.w), 0);\n this.r += copied;\n // this.lastByte = this.buf[this.r - 1];\n // this.lastCharSize = -1;\n return copied;\n }", "async peek(n) {\n if (n < 0) {\n throw Error(\"negative count\");\n }\n let avail = this.w - this.r;\n while (avail < n && avail < this.buf.byteLength && !this.eof) {\n try {\n await this._fill();\n }\n catch (err) {\n err.partial = this.buf.subarray(this.r, this.w);\n throw err;\n }\n avail = this.w - this.r;\n }\n if (avail === 0 && this.eof) {\n return Deno.EOF;\n }\n else if (avail < n && this.eof) {\n return this.buf.subarray(this.r, this.r + avail);\n }\n else if (avail < n) {\n throw new BufferFullError(this.buf.subarray(this.r, this.w));\n }\n return this.buf.subarray(this.r, this.r + n);\n }", "async write(p) {\n if (this.err !== null)\n throw this.err;\n if (p.length === 0)\n return 0;\n let nn = 0;\n let n = 0;\n while (p.byteLength > this.available()) {\n if (this.buffered() === 0) {\n // Large write, empty buffer.\n // Write directly from p to avoid copy.\n try {\n n = await this.wr.write(p);\n }\n catch (e) {\n this.err = e;\n throw e;\n }\n }\n else {\n n = util_ts_1.copyBytes(this.buf, p, this.n);\n this.n += n;\n await this.flush();\n }\n nn += n;\n p = p.subarray(n);\n }\n n = util_ts_1.copyBytes(this.buf, p, this.n);\n this.n += n;\n nn += n;\n return nn;\n }", "fillBuffer() {\n let dataWanted = this.bufferSize - this.dataAvailable;\n\n if (!this._pendingBufferRead && dataWanted > 0) {\n this._pendingBufferRead = this._read(dataWanted);\n\n this._pendingBufferRead.then((result) => {\n this._pendingBufferRead = null;\n\n if (result) {\n this.onInput(result.buffer);\n\n this.fillBuffer();\n }\n });\n }\n }", "available() {\n return this.buf.byteLength - this.n;\n }", "async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);\r\n if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return res.bytesRead;\r\n }", "checkPendingReads() {\n this.fillBuffer();\n\n let reads = this.pendingReads;\n while (reads.length && this.dataAvailable &&\n reads[0].length <= this.dataAvailable) {\n let pending = this.pendingReads.shift();\n\n let length = pending.length || this.dataAvailable;\n\n let result;\n let byteLength = this.buffers[0].byteLength;\n if (byteLength == length) {\n result = this.buffers.shift();\n }\n else if (byteLength > length) {\n let buffer = this.buffers[0];\n\n this.buffers[0] = buffer.slice(length);\n result = ArrayBuffer.transfer(buffer, length);\n }\n else {\n result = ArrayBuffer.transfer(this.buffers.shift(), length);\n let u8result = new Uint8Array(result);\n\n while (byteLength < length) {\n let buffer = this.buffers[0];\n let u8buffer = new Uint8Array(buffer);\n\n let remaining = length - byteLength;\n\n if (buffer.byteLength <= remaining) {\n this.buffers.shift();\n\n u8result.set(u8buffer, byteLength);\n }\n else {\n this.buffers[0] = buffer.slice(remaining);\n\n u8result.set(u8buffer.subarray(0, remaining), byteLength);\n }\n\n byteLength += Math.min(buffer.byteLength, remaining);\n }\n }\n\n this.dataAvailable -= result.byteLength;\n pending.resolve(result);\n }\n }", "async readLine() {\n let line;\n try {\n line = await this.readSlice(LF);\n }\n catch (err) {\n let { partial } = err;\n asserts_ts_1.assert(partial instanceof Uint8Array, \"bufio: caught error from `readSlice()` without `partial` property\");\n // Don't throw if `readSlice()` failed with `BufferFullError`, instead we\n // just return whatever is available and set the `more` flag.\n if (!(err instanceof BufferFullError)) {\n throw err;\n }\n // Handle the case where \"\\r\\n\" straddles the buffer.\n if (!this.eof &&\n partial.byteLength > 0 &&\n partial[partial.byteLength - 1] === CR) {\n // Put the '\\r' back on buf and drop it from line.\n // Let the next call to ReadLine check for \"\\r\\n\".\n asserts_ts_1.assert(this.r > 0, \"bufio: tried to rewind past start of buffer\");\n this.r--;\n partial = partial.subarray(0, partial.byteLength - 1);\n }\n return { line: partial, more: !this.eof };\n }\n if (line === Deno.EOF) {\n return Deno.EOF;\n }\n if (line.byteLength === 0) {\n return { line, more: false };\n }\n if (line[line.byteLength - 1] == LF) {\n let drop = 1;\n if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {\n drop = 2;\n }\n line = line.subarray(0, line.byteLength - drop);\n }\n return { line, more: false };\n }", "function readArrayBufferProgressively(res, callback) {\n if (!callback || !res.body)\n return res.arrayBuffer();\n let contentLength = res.headers.get('Content-Length');\n if (!contentLength)\n return res.arrayBuffer();\n const total = parseInt(contentLength);\n let buffer = new Uint8Array(total);\n let loaded = 0;\n let reader = res.body.getReader();\n let callbackScheduler = new dispatch_scheduler_1.default();\n function accumulateLoadedSize(chunk) {\n buffer.set(chunk.value, loaded);\n loaded += chunk.value.length;\n if (callback) {\n callbackScheduler.request(() => callback(loaded, total));\n }\n if (loaded == total) {\n callbackScheduler.forceDispatch();\n return buffer.buffer;\n }\n else {\n return reader.read().then(accumulateLoadedSize);\n }\n }\n return reader.read().then(accumulateLoadedSize);\n}", "read(size)\n\t{\n\t\tif (this.pos+size > this.input.length)\n\t\t\tsize = this.input.length-this.pos;\n\t\tlet result = this.input.substring(this.pos, this.pos+size);\n\t\tthis.pos += size;\n\t\treturn result;\n\t}", "availableBytes() {\n return this.buffer.byteLength - this.currPtr;\n }", "get bytesRead() {\r\n return this.transport ? this.transport.bytesRead : 0;\r\n }", "async readSlice(delim) {\n let s = 0; // search start index\n let slice;\n while (true) {\n // Search buffer.\n let i = this.buf.subarray(this.r + s, this.w).indexOf(delim);\n if (i >= 0) {\n i += s;\n slice = this.buf.subarray(this.r, this.r + i + 1);\n this.r += i + 1;\n break;\n }\n // EOF?\n if (this.eof) {\n if (this.r === this.w) {\n return Deno.EOF;\n }\n slice = this.buf.subarray(this.r, this.w);\n this.r = this.w;\n break;\n }\n // Buffer full?\n if (this.buffered() >= this.buf.byteLength) {\n this.r = this.w;\n throw new BufferFullError(this.buf);\n }\n s = this.w - this.r; // do not rescan area we scanned before\n // Buffer is not full.\n try {\n await this._fill();\n }\n catch (err) {\n err.partial = slice;\n throw err;\n }\n }\n // Handle last byte, if any.\n // const i = slice.byteLength - 1;\n // if (i >= 0) {\n // this.lastByte = slice[i];\n // this.lastCharSize = -1\n // }\n return slice;\n }", "function BufferReadStream ( source ) {\n\n if ( ! buffer.isBuffer( source ) ) {\n throw( new Error( \"BufferReadStream source must be a buffer.\" ) );\n }\n\n //Call super constructor.\n stream.Readable.call(this);\n\n this._source = source;\n this._index = 0;\n this._length = this._source.length;\n}", "function pump(readable, writable, cb) {\n readable.on('data', function(data) {\n if (!writable.write(data)) {\n readable.pause();\n }\n });\n writable.on('drain', function() {\n readable.resume();\n });\n if (cb) {\n readable.on('end', function() {\n cb();\n });\n }\n}", "function readStrict() {\n var response = openidm.read.apply(null, arguments);\n if (_.isNull(response)) {\n var error_message = arguments[0] ?\n 'The resource ' + arguments[0] + ' does not exist.' :\n 'No resource argument supplied to openidm.read.';\n __.requestError(error_message, 400);\n }\n return response;\n}", "async *_bodyStream() {\n let buf = yield 0; // dummy yield to retrieve user provided buf.\n if (this.headers.has(\"content-length\")) {\n const len = this.contentLength;\n if (len === null) {\n return;\n }\n let rr = await this.r.read(buf);\n let nread = rr === Deno.EOF ? 0 : rr;\n let nreadTotal = nread;\n while (rr !== Deno.EOF && nreadTotal < len) {\n buf = yield nread;\n rr = await this.r.read(buf);\n nread = rr === Deno.EOF ? 0 : rr;\n nreadTotal += nread;\n }\n yield nread;\n }\n else {\n if (this.headers.has(\"transfer-encoding\")) {\n const transferEncodings = this.headers\n .get(\"transfer-encoding\")\n .split(\",\")\n .map((e) => e.trim().toLowerCase());\n if (transferEncodings.includes(\"chunked\")) {\n // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6\n const tp = new mod_ts_3.TextProtoReader(this.r);\n let line = await tp.readLine();\n if (line === Deno.EOF)\n throw new bufio_ts_2.UnexpectedEOFError();\n // TODO: handle chunk extension\n const [chunkSizeString] = line.split(\";\");\n let chunkSize = parseInt(chunkSizeString, 16);\n if (Number.isNaN(chunkSize) || chunkSize < 0) {\n throw new Error(\"Invalid chunk size\");\n }\n while (chunkSize > 0) {\n let currChunkOffset = 0;\n // Since given readBuffer might be smaller, loop.\n while (currChunkOffset < chunkSize) {\n // Try to be as large as chunkSize. Might be smaller though.\n const bufferToFill = buf.subarray(0, chunkSize);\n if ((await this.r.readFull(bufferToFill)) === Deno.EOF) {\n throw new bufio_ts_2.UnexpectedEOFError();\n }\n currChunkOffset += bufferToFill.length;\n buf = yield bufferToFill.length;\n }\n await this.r.readLine(); // Consume \\r\\n\n line = await tp.readLine();\n if (line === Deno.EOF)\n throw new bufio_ts_2.UnexpectedEOFError();\n chunkSize = parseInt(line, 16);\n }\n const entityHeaders = await tp.readMIMEHeader();\n if (entityHeaders !== Deno.EOF) {\n for (const [k, v] of entityHeaders) {\n this.headers.set(k, v);\n }\n }\n /* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6\n length := 0\n read chunk-size, chunk-extension (if any) and CRLF\n while (chunk-size > 0) {\n read chunk-data and CRLF\n append chunk-data to entity-body\n length := length + chunk-size\n read chunk-size and CRLF\n }\n read entity-header\n while (entity-header not empty) {\n append entity-header to existing header fields\n read entity-header\n }\n Content-Length := length\n Remove \"chunked\" from Transfer-Encoding\n */\n return; // Must return here to avoid fall through\n }\n // TODO: handle other transfer-encoding types\n }\n // Otherwise... Do nothing\n }\n }", "function SyncFileBuffer(file)\n{\n var PART_SIZE = 4 << 20,\n ready = false,\n me = this;\n\n this.byteLength = file.size;\n\n if(file.size > (1 << 30))\n {\n console.log(\"Warning: Allocating buffer of \" + (file.size >> 20) + \" MB ...\");\n }\n\n var buffer = new ArrayBuffer(file.size),\n pointer = 0,\n filereader = new FileReader();\n\n this.load = function()\n {\n // Here: Read all parts sequentially\n // Other option: Read all parts in parallel\n filereader.onload = function(e)\n {\n new Uint8Array(buffer, pointer).set(new Uint8Array(e.target.result));\n pointer += PART_SIZE;\n next();\n };\n\n next();\n\n function next()\n {\n if(me.onprogress)\n {\n me.onprogress({\n loaded: pointer, \n total: file.size,\n lengthComputable: true,\n });\n }\n\n if(pointer < file.size)\n {\n filereader.readAsArrayBuffer(file.slice(pointer, Math.min(pointer + PART_SIZE, file.size)));\n }\n else\n {\n ready = true;\n\n if(me.onload)\n {\n me.onload({\n \n });\n }\n }\n }\n }\n\n this.get = function(offset, len, fn)\n {\n if(ready)\n {\n console.assert(offset + len <= buffer.byteLength);\n\n fn(new Uint8Array(buffer, offset, len));\n }\n else\n {\n throw \"SyncFileBuffer: Wait for ready\";\n }\n };\n\n this.get_buffer = function(fn)\n {\n if(ready)\n {\n fn(buffer);\n }\n else\n {\n throw \"SyncFileBuffer: Wait for ready\";\n }\n };\n\n /** @param data {Uint8Array] */\n this.set = function(offset, data, fn)\n {\n if(ready)\n {\n console.assert(offset + data.byteLength <= buffer.byteLength);\n\n new Uint8Array(buffer, offset, data.byteLength).set(data);\n fn();\n }\n else\n {\n throw \"SyncFileBuffer: Wait for ready\";\n }\n };\n}", "async _fetchWrite( fd, offset, length ) { \n const res = await fetch( this.URL, { headers: {\n 'range': `bytes=${offset}-${offset+length}`,\n 'Authorization': `Bearer ${this.token}`\n }});\n if (res.status != 206) \n throw(`error:${res.statusText}, bytes=${offset}-${offset+length}`)\n const buff = await res.buffer();\n fs.writeSync(fd, buff, 0, buff.length, offset);\n return res.status;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load tags to header and hero
function loadTags() { const tags = JSON.parse(sessionStorage.getItem('tags')) tags && tags.headerTags.forEach(tag => { const li = document.createElement('li') li.classList.add('tags__tag') li.innerHTML = `${tag}` headerFields.appendChild(li) }) tags && tags.heroTags.forEach(tag => { const li = document.createElement('li') li.classList.add('tags__tag') li.innerHTML = `${tag}` heroFields.appendChild(li) }) }
[ "collectHeadTags() {\n let tags = {};\n let currentHandlerInfos = this.router.targetState.routerJsState.routeInfos;\n currentHandlerInfos.forEach((handlerInfo) => {\n Object.assign(tags, this._extractHeadTagsFromRoute(handlerInfo.route));\n });\n let tagArray = Object.keys(tags).map((id) => tags[id]);\n this.headData.set('headTags', tagArray);\n }", "loadNiches() {\n this.appData.nicheData.forEach((niche) => {\n this.topHead.innerHTML += `\n <div role=\"listitem\" class=\"top-head\">\n <p id=${niche.nicheSlug} data-head=\"niche\" class=\"para-18 head-para\">${niche.nicheName}</p>\n </div>`;\n })\n }", "collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }", "loadMainHeader() {\n // Get site name and description from store\n const siteName = model.getPostBySlug('site-name', 'settings'),\n siteDescription = model.getPostBySlug('site-description', 'settings');\n view.updateSiteName(siteName.content);\n view.updateSiteDescription(siteDescription.content);\n }", "function loadTopbar() {\n loadSection(\"/Frontend/shared/topbar/topbar.html\")\n .then(html => {\n TOPBARCONTAINER.innerHTML = html;\n })\n .catch(error => {\n console.warn(error);\n });\n}", "setUpParallaxHeader() {\n new Parallax(HEADER);\n }", "function loadScripts() {\n loadPageHeader();\n getPages();\n getStyles();\n getScripts();\n addEventListeners();\n}", "function setNavData()\n{\n //Calling the appropriate function to load header and footer based on the title of the page\n if (document.title == \"BIOPAGE\" || document.title == \"CONTACT\" || document.title == \"PROJECTS\") \n {\n loadHeader();\n loadFooter(); \n } \n}", "function populateHeaderYs() {\n var hdrs = $(\"h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]\");\n for (var i=0; i< hdrs.length; i++) {\n hs.push(hdrs[i]);\n headerYs[hdrs[i].offsetTop] = hdrs[i].id;\n };\n}", "appendLoader(loader) {\n //append to body\n loader.appendTo($(this.section));\n }", "function preload() {\n lemonMilk = loadFont(\"assets/text/LemonMilk.otf\");\n catN = loadImage(\"assets/images/cat.png\");\n lionN = loadImage(\"assets/images/lion.png\");\n jungleN = loadImage(\"assets/images/jungle.jpg\");\n catRetro = loadImage(\"assets/images/catRetro.png\");\n lionRetro = loadImage(\"assets/images/lionRetro.png\");\n jungleRetro = loadImage(\"assets/images/jungleRetro.jpg\");\n}", "function loadAssets() {\n\t\tbackground.src = \"assets/Wall720.png\";\n\t\tTERRAIN_TYPES.BASE.img.src = \"assets/TileSandstone100.png\";\n\t\tTERRAIN_TYPES.LAVA.img.src = \"assets/lava.png\";\n\t\t\n\t\tPLAYER_CLASSES.PALADIN.img.src = \"assets/paladinRun.png\";\n\t\tPLAYER_CLASSES.RANGER.img.src = \"assets/rangerRun.png\";\n\t\tPLAYER_CLASSES.MAGI.img.src = \"assets/magiRun.png\";\n\t\t\n\t\tENEMY_TYPES.RAT.img.src = \"assets/ratRun.png\";\n\t\tENEMY_TYPES.BAT.img.src = \"assets/batRun.png\";\n\t\tENEMY_TYPES.GATOR.img.src = \"assets/gatorRun.png\";\n\t\t\n\t\tPROJECTILE_TYPES.ARROW.img.src = \"assets/arrow.png\";\n\t\tPROJECTILE_TYPES.FIREBALL.img.src = PROJECTILE_TYPES.MAGIFIREBALL.img.src = \"assets/fireball.png\";\n\t\t\n\t\tPARTICLE_TYPES.FLAME.img.src = \"assets/flameParticle.png\";\n\t\tPARTICLE_TYPES.ICE.img.src = PARTICLE_TYPES.FROST.img.src = \"assets/iceParticle.png\";\n\t}", "function getTagsFromPage(callback){\n\t\t\t\t\t\n\t\t\t\t\tconsole.log(request.greeting);\n\t\t\t\t\tvar tags = $(request.greeting);\n\t\t\t\t\tconsole.log(tags);\n\t\t\t\t\tvar tagLength = tags.length;\n\t\t\t\t\tconsole.log(tagLength);\n\n\t\t\t\t\tfor (var i = 0; i < tags.length; i++){\n\t\t\t\t\t\tvar tagObj = $(tags[i]);\n\t\t\t\t\t\ttagList.push(tagObj.html());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcallback();\n\t\t\t}", "function loadTags (filename) {\n var viewdir;\n\n if (tagsLoaded) {\n return; // early return since have already made the requires\n }\n\n viewdir = filename.slice(0, filename.lastIndexOf('/'));\n tagsLoaded = fs.readdirSync(viewdir).map(function (file) {\n var filepath = Path.join(viewdir, file);\n\n if (filepath !== filename && !require.cache[filepath]) {\n require(filepath); //eslint-disable-line\n }\n\n return filepath;\n });\n}", "function definePageElements(){\n playerContainer = document.getElementsByClassName(\"hero\")[0];\n var temp = playerContainer.getElementsByTagName(\"span\");\n for(var i = 0; i < temp.length; i++){\n switch(temp[i].className){\n case \"health\":\n playerHpDisplay = temp[i];\n break;\n case \"mana\":\n playerManaDisplay = temp[i];\n break;\n default:\n console.log(\"Unidentified player span \" + temp[i].name);\n }\n }\n actions = [];\n actionLogDisplay = document.getElementById(\"action-log\");\n starter = document.getElementsByClassName(\"starter\")[0];\n temp = document.getElementById(\"fight-button\");\n gameContainer = document.getElementById(\"game-container\");\n addEvent(temp,'click',startGame,false);\n dragonCanvas = document.getElementById(\"dragon-info\");\n dragonCanvasContext = dragonCanvas.getContext('2d');\n temp = null;\n}", "function resourceOnload() {\n initShowdownExt();\n hljs.initHighlightingOnLoad();\n mermaidAPI.initialize({\n startOnLoad: false\n });\n mermaid.parseError = function(err, hash) {\n console.error(err);\n };\n\n onLoadCallback.call(self);\n }", "function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}", "init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}", "loadBlogPosts() {\n var posts = model.getPostsByType('posts'),\n postsSection = document.createElement('section'),\n primaryContentEL = h.getPrimaryContentEl();\n\n postsSection.id = 'blogPosts';\n // Get markup for each post\n //console.log( posts );\n _.each(posts, post => {\n postsSection.appendChild(h.createPostMarkup(post));\n });\n // Append posts to page\n primaryContentEL.appendChild(postsSection);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a recursive function that takes two parameters and repeats the string n number of times. The first parameter txt is the string to be repeated and the second parameter is the number of times the string is to be repeated.
function repetition(txt, n) { return txt.repeat(n); }
[ "function repeat(input, n){\n var output = ''\n for(var i = 0; i < n; i++){\n output = output + input\n }\n return output\n }", "function repeatString(str, count) { \n // TODO: your code here \n if(count === 0){\n return \"\";\n }\n return str + repeatString(str, count - 1);\n}", "function repeatStringNumTimes(string, times) {\n// Create an empty string to host the repeated string\nvar repeatedString = \"\";\n//Step 2, set the while loop with (times > 0) as the condition to check\nwhile (times > 0) { //as long as times is greater than 0, statement is executed\n repeatedString += string; // repeatedString = repeatedString + string;\n times-- ;\n}\n\n// Step 3 return the repeated String\nreturn repeatedString;\n}", "function repeatPhrase(phrase, n) {\n\tfor (i = 0; i < n; i++) {\n\t console.log(phrase);\n\t}\n}", "function repeat(phrase, x) {\n for (let i = 0; i < x ; i++) {\n console.log(phrase);\n }\n\n}", "function repeat(fn, n) {\nfor(let i=0; i<n; i++) {\n\tfn();\n}\n\n}", "function modifyLast(str, n) {\n\treturn str.slice(0, -1) + str.slice(-1).repeat(n);\n}", "repeat (n, f, o) { for (let i = 0; i < n; i++) f(i, o); return o }", "function generatePattern(n) {\n var number = '';\n var asterisks = '';\n \n for (var i = 1; i <= n; i++) {\n // sets number of asterisks for specific row\n for (var j = n - i; j > 0; j--) {\n asterisks += '*';\n }\n // every time through loop another number gets added on\n number += i;\n console.log(number + asterisks);\n // resets asterisks so it can be looped again\n asterisks = '';\n }\n \n}", "function concat(string, n) {\n n = n || 1;\n var con = '';\n for (var i = 0; i < n; i++) {\n con += string;\n }\n return con;\n}", "function repeatChar(str,char){\n\tvar count=0;\n\tvar str1= str.split(\"\");\n var rep = str1.reduce((x,y)=> {\n if (y == char){\n return\tcount = count + 1\n }});\n return count;\n }", "function repeatSeparator(word, sep, count){\n let s = '';\n for(let i = 0; i < count; i++){\n if(i < count - 1)\n s += word + sep;\n else\n s += word ;\n }\n return s;\n }", "function string(n){\n \tvar i =0;\n \twhile(i<n){\n i++; \n \t return i,\" \",n;\n \t}\n\n }", "function solve(s, n) {\n let sArr = s.split('')\n let strings = []\n for(let i = 0; i < s.length; i+=n){\n strings.push(sArr.slice(i, n+i).join(''))\n console.log(strings)\n }\n return strings\n}", "function repeat(action, times, argument) {\n let count = 0;\n\n const repeater = (arg) => {\n if (count >= times) {\n return arg;\n }\n\n count++;\n\n return action(arg).then(repeater);\n };\n\n return repeater(argument);\n}", "function repeatChar(string,char){\n string= string.toLowerCase()\n string= string.split(\"\")\n var result = string.reduce(function(num,str){\n\nif ( str===char){\n ++num\n}return num\n\n } ,0)\n return result\n}", "function checkRepetition(pLen,str)\n{\n res = \"\";\n for ( i=0; i<str.length ; i++ ) {\n repeated=true;\n for (j=0;j < pLen && (j+i+pLen) < str.length;j++) {\n repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen));\n }\n\n if (j<pLen) repeated=false;\n if (repeated) {\n i+=pLen-1;\n repeated=false;\n } else {\n res+=str.charAt(i);\n }\n }\n return res\n}", "function mirrorFirstCharacters(text, n) {\n let result = text;\n for (let k = n - 1; k >= 0; k--) {\n result += text[k];\n }\n\n return result;\n}", "function partition(str, n) {\n return str.match(new RegExp('.{1,' + n + '}', 'g'));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to activate MutationObserver listener
function addMutationObserver() { const config = { childList: true, attributes: true, subtree: true, }; observer.observe(document, config); }
[ "function addChangesetsObserver() {\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (mutation.type == 'attributes') {\n return;\n }\n searchChangesets();\n });\n });\n\n var config = { attributes: true, childList: true, characterData: true };\n var changesets = document.querySelector('#sidebar_content div.changesets');\n observer.observe(changesets, config);\n}", "observePage() {\n if (!this.observer) {\n this.observer = new MutationObserver((mutations) => {\n if (this.handleMutationsTimeout) {\n // Don't handle the mutations yet after all.\n clearTimeout(this.handleMutationsTimeout)\n }\n\n mutations.forEach((mutation) => {\n // Filter mutations to park.\n if (mutation.addedNodes.length) {\n for (const node of mutation.addedNodes) {\n if (!this.walker.skipNode(node)) {\n this.parkedNodes.push(node)\n }\n }\n } else if (!mutation.removedNodes.length && mutation.target) {\n if (!this.walker.skipNode(mutation.target)) {\n this.parkedNodes.push(mutation.target)\n }\n }\n })\n\n // Assuming nothing happens, scan the nodes in 500 ms - after\n // this the page should've been done dealing with the mutations.\n if (this.parkedNodes.length) {\n this.handleMutationsTimeout = setTimeout(this.handleMutations.bind(this), 500)\n }\n })\n }\n\n if (this.observer) {\n this.observer.observe(document.body, {childList: true, subtree: true})\n }\n }", "addObserver(observer){\n \n this.observers.push(observer)\n }", "observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }", "observe( callback ) {\n if ( this.observing ) {\n return\n }\n\n this.listener = e => {\n if ( !this.observing ) {\n return\n }\n // save for back\n this.oldURL = e.oldURL\n\n callback( {\n newSegment: getHash( e.newURL ),\n oldSegment: getHash( e.oldURL ),\n } )\n }\n\n setTimeout( () => {\n window.addEventListener( 'hashchange', this.listener )\n this.observing = true\n }, 0 )\n }", "function runObserver (observer) {\n currentObserver = observer;\n observer();\n}", "function watchForLarkGallery () {\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (mutation.addedNodes) {\n theLarkGallery();\n }\n });\n });\n observer.observe(document.body, {\n 'childList': true,\n 'subtree': true\n });\n }", "function addMetricsObserver() {\n window.addEventListener('load', () => {\n captureMetrics();\n });\n}", "_observeEntries() {\n this.items.forEach((item) => {\n item.elementsList.forEach((element) => {\n this.observer.observe(element);\n });\n });\n }", "function mo_callback(mutation_list, observer) {\n mutation_list.forEach((mutation) => {\n if(mutation.type == \"attributes\"){\n \n // We have to check whether zoom \"should\" be on, because the\n // fullscreenchange event may not be fast enough, in which case we will\n // catch the mutations caused by exiting full-screen.\n if(zoom_should_be_on()) {\n debug_log(\"Video element mutated.\")\n set_zoom_to_movie_player(mutation.target)\n } else {\n debug_log(\"Video element mutated but zoom should be off.\")\n zoom_off()\n }\n }\n })\n}", "function attachTracklistModificationListeners(onTracklistModifiedByExternalSource) {\n let onEvent = (event) => {\n if(!currentlyModifyingAnyTracklist)\n onTracklistModifiedByExternalSource()\n }\n\n for(trackList of getTracklistNodes()) {\n trackList.addEventListener('DOMNodeInserted', onEvent)\n trackList.addEventListener('DOMNodeRemoved', onEvent)\n }\n}", "addVisibilityListeners() {\n document.addEventListener('visibilitychange', this.updateVisibility);\n this.updateVisibility();\n }", "processPage() {\n this.logger.debug(`${this}start observing`)\n $('head').appendChild(this.stylesheet)\n this.insertIconInDom()\n this.observePage()\n }", "function start_monitoring()\n {\n browser.idle.onStateChanged.addListener(on_idle_state_change);\n }", "initIntersectionObserver() {\n if (this.observer) return;\n // Start loading the image 10px before it appears on screen\n const rootMargin = '10px';\n this.observer = new IntersectionObserver(this.observerCallback, { rootMargin });\n this.observer.observe(this);\n }", "function initializeDeliveryOptionChangeListener() {\n let elements = document.querySelectorAll(\".delivery-option\");\n for (var i = 0; i < elements.length; i++) {\n elements[i].addEventListener(\"change\", function() {\n let loadingElement = document.querySelector(\".item-delivery-options\");\n let observer = new MutationObserver(function(entries) {\n if (!document.querySelector(\".item-delivery-options.loading\")) {\n reinitializeAfterpayPopup(); \n observer.disconnect();\n }\n });\n observer.observe(loadingElement, {attributeFilter: ['class']});\n });\n }\n}", "function start() {\n addEventListener()\n\n }", "function _updateElement() {\n\t\tself.observer.disconnect();\n\t\tself.element.innerHTML = self.history[self.index];\n\t\tself.observer.observe(self.element, OBSERVER_CFG);\n\t}", "#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::Cognito::UserPoolUser resource creates an Amazon Cognito user pool user. Documentation:
function UserPoolUser(props) { return __assign({ Type: 'AWS::Cognito::UserPoolUser' }, props); }
[ "function UserPool(props) {\n return __assign({ Type: 'AWS::Cognito::UserPool' }, props);\n }", "function UserPoolGroup(props) {\n return __assign({ Type: 'AWS::Cognito::UserPoolGroup' }, props);\n }", "function UserPoolClient(props) {\n return __assign({ Type: 'AWS::Cognito::UserPoolClient' }, props);\n }", "function userCreate(username, password, fullName, email, cb){\n //puts arguments into a JSON\n userDetails = {\n username: username,\n password: password,\n fullName: fullName,\n email: email,\n }\n\n newUser = new User(userDetails); // uses JSON to make a new user\n\n //saves new user\n newUser.save(function(err){\n if (err){\n cb(err, null);\n return;\n }\n\n console.log('New User: ' + newUser);\n if (cb) cb(null, newUser);\n });\n}", "function User(props) {\n return __assign({ Type: 'AWS::IAM::User' }, props);\n }", "async function createUser() {\n const response = await fetch(`/api/users/`, {\n method: 'POST',\n body: JSON.stringify(userData),\n headers:{\n 'Content-Type': 'application/json'\n }\n });\n\n if (response.status !== 200) {\n // A server side error occured. Display the\n // error messages.\n handleServerError(response);\n } else {\n clearUserForm();\n // Re-fetch users after creating new\n fetchUsers()\n }\n }", "function UserPoolUserToGroupAttachment(props) {\n return __assign({ Type: 'AWS::Cognito::UserPoolUserToGroupAttachment' }, props);\n }", "function makeUser(usernameInput) {\n const username = usernameInput.value;\n const UserObject = {\n name: username,\n wallet: 75,\n };\n\n return UserObject;\n\n}", "function createUser(req, res){\n var newUser = req.body;\n // use the userModel to create a User using the api \n // the api will \n var users = userModel.createUser(newUser);\n res.json(users);\n }", "createUser (name, email, roleId = undefined) {\n assert.equal(typeof name, 'string', 'name must be string')\n assert.equal(typeof email, 'string', 'email must be string')\n if (roleId) assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest('/user', 'POST', { name, email, user_role_id: roleId })\n }", "function signup(userData){\n console.log(\"creating new user \"+userData.id);\n return User.create(userData)\n }", "function createUser(id, username) {\n let templateUser = JSON.parse(fs.readFileSync(schemaPath + \"user.json\", \"utf8\"));\n templateUser.id = id;\n if (username)\n templateUser.username = username;\n writeUser(id, templateUser);\n}", "async function cognitoLogin({userPoolId, clientId, username, password, region, identityPoolId} ) {\n const poolData = {\n UserPoolId: userPoolId,\n ClientId: clientId\n };\n\n const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);\n\n return new Promise((resolve, reject) => {\n const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({\n Username: username,\n Password: password,\n });\n\n const userData = {\n Username: username,\n Pool: userPool,\n };\n\n const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);\n \n cognitoUser.authenticateUser(authenticationDetails, {\n onSuccess(result) {\n if(region && identityPoolId) {\n AWS.config.region = region;\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId : identityPoolId,\n Logins : { [`cognito-idp.ap-southeast-2.amazonaws.com/${userPoolId}`] : result.getIdToken().getJwtToken()}\n });\n \n AWS.config.credentials.refresh((error) => {\n if (error) {\n console.error(error);\n } else {\n // example: var s3 = new AWS.S3();\n console.log('Successfully logged! Now could using your aws servers example s3 buckets');\n result.getRefreshToken().getToken();\n resolve(result.getAccessToken().getJwtToken());\n }\n });\n\n } else {\n resolve(result.getAccessToken().getJwtToken());\n }\n },\n onFailure(err) {\n reject(err);\n },\n });\n });\n}", "function _createNewUser( userCreateForm, backend ) {\n\n backend.createNewUser(userCreateForm.toJSON(), {\n\n success: function ( response ) {\n // if( !backend.IsAuthenticationManagerBackendResult(response) ) .. throw error ..\n\n var pendingUser = UserCreatePendingConfirm.emptyUserCreatePendingConfirm();\n\n pendingUser.set( response.result );\n\n $.publish( 'created.usercreate.authentication.manager',\n AuthenticationResult.NewSuccessResult( pendingUser ) );\n },\n\n error: function ( response ) {\n // if( !backend.IsAuthenticationManagerBackendResult(response) ) .. throw error ..\n\n $.publish( 'failed.usercreate.authentication.manager',\n AuthenticationResult.NewErrorResult( response.errors, userCreateForm ) );\n }\n\n });\n\n}", "function registerUser(user_name) {\n\t// Register and enroll the user\n\tchain.getMember(user_name, function (err, user) {\n\t\tif (err) {\n\t\t\tconsole.log(\"ERROR: Failed to get \" + user.getName() + \" -- \", err);\n\t\t\tprocess.exit(1);\n\t\t} else {\n\t\t\tapp_user = user;\n\n\t\t\t// User may not be enrolled yet. Perform both registration\n\t\t\t// and enrollment.\n\t\t\tvar registrationRequest = {\n\t\t\t\tenrollmentID: app_user.getName(),\n\t\t\t\taffiliation: \"bank_a\"\n\t\t\t};\n\t\t\tapp_user.registerAndEnroll(registrationRequest, function (err, member) {\n\t\t\t\tif (err) {\n\t\t\t\t\tconsole.log(\"ERROR: Failed to enroll \" +\n\t\t\t\t\t\tapp_user.getName() + \" -- \" + err);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"Successfully registered and enrolled \" +\n\t\t\t\t\t\tapp_user.getName() + \".\\n\");\n\n\t\t\t\t\t// Deploy a chaincode with the new user\n\t\t\t\t\tconsole.log(\"Deploying chaincode now...\");\n\t\t\t\t\tdeployChaincode()\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "function IdentityPool(props) {\n return __assign({ Type: 'AWS::Cognito::IdentityPool' }, props);\n }", "function createUser(email, password) {\n\n // check if email already exist and return that user instead if found\n let user = UserManager.getUserByEmail(email);\n if (user !== null) {\n return user;\n }\n\n // create a default user object from email and password\n user = {\n email,\n password,\n todos: []\n }\n\n let storage = LocalStorageManager.getStorage();\n\n // add user to storage and save\n storage.users.push(user);\n LocalStorageManager.save();\n\n return user;\n }", "function User(userName, fullName, accessType, password){\n this.userName = userName;\n this.accessType = accessType;\n this.password = password;\n this.fullName = fullName; \n}", "function CreateUser(name, age) {\n\tthis.name = name;\n\tthis.age = age;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up the click events for the artist view.
function artistEvents (template, artist) { var plyAll = template.querySelector('.play-all'); plyAll.addEventListener('click', emitEvent('artist: play-all', artist)); var addAll = template.querySelector('.add-all'); addAll.addEventListener('click', emitEvent('artist: add-all', artist)); var back = template.querySelector('.back-button'); back.addEventListener('click', emitEvent('menu: artists')); }
[ "function albumEvents (template, album, artist) {\n\n\t\tvar plyAll = template.querySelector('.play-all');\n\t\tplyAll.addEventListener('click', emitEvent('album: play-all', album));\n\n\t\tvar addAll = template.querySelector('.add-all');\n\t\taddAll.addEventListener('click', emitEvent('album: add-all', album));\n\n\t\tvar back = template.querySelector('.back-button');\n\n\t\t// Returns either to artist view or album list view.\n\t\tif (artist) {\n\t\t\tback.addEventListener('click', emitEvent('view-artist', artist));\n\t\t} else {\n\t\t\tback.addEventListener('click', emitEvent('menu: albums'));\n\t\t}\n\n\t}", "function menuEvents () {\n\n\t\tvar chooseLibrary = document.getElementById('choose-library');\n\t\tvar viewArtists = document.getElementById('view-artists');\n\t\tvar viewAlbums = document.getElementById('view-albums');\n\t\tvar viewSongs = document.getElementById('view-songs');\n\n\t\tchooseLibrary.addEventListener('click', emitEvent('menu: choose-lib'));\n\t\tviewArtists.addEventListener('click', emitEvent('menu: artists'));\n\t\tviewAlbums.addEventListener('click', emitEvent('menu: albums'));\n\t\tviewSongs.addEventListener('click', emitEvent('menu: songs'));\n\n\t}", "function clickArtist(artistId, index, artistName) {\n\t//deselect an artist\n\tif (index !== -1){\n\t\tdeselectArtist(index, artistId);\n\t\taddInteraction('artistDiv', 'deselect', artistId);\n\t}\n\t//select a new artist\n\telse {\n\t\tselectArtist(artistId, artistName);\n\t\taddInteraction('artistDiv', 'select', artistId);\n\t}\n}", "function setupEvents() {\n if (typeof window.ontouchstart !== 'undefined') {\n view.addEventListener('touchstart', tap);\n view.addEventListener('touchmove', drag);\n view.addEventListener('touchend', release);\n }\n view.addEventListener('mousedown', tap);\n view.addEventListener('mousemove', drag);\n view.addEventListener('mouseup', release);\n }", "function addArtistListener(artistName, artistID, num) {\n (function () {\n var id = document.getElementById(num); //get element\n if (id) {\n id.addEventListener('click', function () {\n parent.document.getElementById('mainPane').src = \"artistAlbums.html?artistid=\"\n + artistID + \"&artistName=\" + artistName;\n }, false);\n }\n }());\n}", "async function artistClick(song) {\n let response = await fetch('https://yt-music-api.herokuapp.com/api/yt/artist/' + song.artist.browseId)\n let result = await response.json()\n context.artist = [];\n context.artist.push(result);\n history.push('/artistpage/' + song.artist.browseId);\n }", "function setUpListeners() {\n var i = 0;\n for(i = 0; i < linkIds.length; i++) {\n var anchor = document.getElementById(linkIds[i]);\n $('#'+linkIds[i]).click(function() {\n annotationOnClick(this.id);\n });\n }\n}", "attachEvents() {\n const data = {\n mode: this.drawingMode,\n container: this.canvasDrawer,\n target: this.target\n };\n //When clicking the <label>, fire this event.\n $(this.target).click(data, function () {\n data.container.drawingMode = data.mode;\n data.container.componentSelected(data.target);\n });\n }", "addListeners(e){\r\n this.onToCartClick(e);\r\n this.onFromCartClick(e);\r\n }", "function playbackEvents () {\n\n\t\tvar play = document.getElementById('play');\n\t\tvar overlayPlay = document.getElementById('overlay-play');\n\t\tvar pause = document.getElementById('pause');\n\t\tvar overlayPause = document.getElementById('overlay-pause');\n\t\tvar previous = document.getElementById('previous');\n\t\tvar next = document.getElementById('next');\n\n\t\tplay.addEventListener('click', emitEvent('play'));\n\t\toverlayPlay.addEventListener('click', emitEvent('play'));\n\t\tpause.addEventListener('click', emitEvent('pause'));\n\t\toverlayPause.addEventListener('click', emitEvent('pause'));\n\t\tprevious.addEventListener('click', emitEvent('previous'));\n\t\tnext.addEventListener('click', emitEvent('next'));\n\n\t}", "onCreateEventClick() {\n set(this, 'showCreateEventModal', true);\n }", "viewWasClicked (view) {\n\t\t\n\t}", "function setArtistMarkers(artist, show) {\n var name = artist[\"name\"];\n if(show) {\n // Check if event markers are already created for the artist\n var events_exist = false;\n ms = [];\n for(i = 0; i < markers.length; i++) {\n if(markers[i][\"artist\"] == name) {\n events_exist = true;\n // Set map for the marker\n markers[i][\"marker\"].setMap(map);\n }\n }\n // If no markers exist for the artist, check if there is any by fetching from backend\n if(!events_exist) {\n getArtistEventData(name);\n }\n else {\n // Events exist and are displayed, so set the class\n $(\"#\"+escaped(name)).removeClass(\"artist_notshown\").addClass(\"artist_shown\");\n }\n }\n else {\n for(i=0; i<markers.length; i++) {\n if(markers[i][\"artist\"] == name) {\n // Unset the map from the marker\n markers[i][\"marker\"].setMap(null);\n }\n }\n $(\"#\"+escaped(name)).removeClass(\"artist_shown\").addClass(\"artist_notshown\");\n }\n artist[\"shown\"] = show;\n }", "_initEvent() {\n this.eventManager.listen('hide', this.hide.bind(this));\n this.eventManager.listen('show', this.show.bind(this));\n }", "function activateClicks() {\n\tconsole.log( \"Activating clicker\")\n\tArray.from( ptrAnswers ).forEach( function( item ) {\n\t\tconsole.log( item );\n\t\titem.addEventListener( \"click\", answerSelected );\n\t});\n}", "function overlayEvents () {\n\n\t\tvar closePlayer = document.getElementById('close-player-overlay');\n\t\tvar menuPopup = document.getElementById('popup-menu');\n\n\t\tnowPlaying.addEventListener('click', emitEvent('view-player'));\n\t\tclosePlayer.addEventListener('click', emitEvent('close-player'));\n\n\t\tmenuPopup.addEventListener('click', function openMenu (clickEvent) {\n\t\t\tclickEvent.stopPropagation();\n\t\t\temitEvent('view-menu')();\n\t\t});\n\n\t}", "add_click(func) {\n this.add_event(\"click\", func);\n }", "function setupView() {\n // set home button view point to initial extent\n var homeButton = new Home({\n view: view,\n viewpoint: new Viewpoint({\n targetGeometry: initialExtent\n })\n });\n \n var track = new Track({\n viewModel:{\n view:view,\n scale: 100000\n }\n });\n\n // layer list\n var layerList = new LayerList({\n view: view, \n listItemCreatedFunction: function(event){\n var item = event.item;\n \n if (item.title === \"Trail Heads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"th\"),\n open: true\n }\n } else if (item.title === \"Point of Interest\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"poi\"),\n open: true\n }\n } else if (item.title === \"Visitor Recommendations\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"rec\"),\n open: true\n }\n } else if (item.title === \"Roads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"road\"),\n open: true\n }\n } else if (item.title === \"Trails\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"trail\"),\n open: true\n }\n }\n }\n });\n \n // expand layer list\n layerExpand = new Expand({\n expandIconClass: \"esri-icon-layers\",\n expandTooltip: \"Turn on and off Map Layers\",\n expanded: false,\n view: view,\n content: layerList,\n mode: \"floating\", \n group:\"top-left\"\n });\n \n\n // expand widget for edit area\n editExpand = new Expand({\n expandIconClass: \"esri-icon-edit\",\n expandTooltip: \"Add a Visitor Recommendation\",\n expanded: false,\n view: view,\n content: editArea,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // expand widget for query\n var query = document.getElementById(\"info-div\");\n queryExpand = new Expand ({\n expandIconClass: \"esri-icon-filter\",\n expandTooltip: \"Filter Points of Interest\",\n expanded: false,\n view: view,\n content: query,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // search widget\n var searchWidget = new Search({\n view:view,\n allPlaceholder: \"Search for SNP Places\",\n locationEnabled: false,\n sources: [{\n featureLayer: poi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: poiP\n }, {\n featureLayer:aoi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: aoiP\n }, {\n featureLayer: trailheads,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: trailheadsP\n }, {\n featureLayer:trails,\n resultSymbol: {\n type: \"simple-line\",\n color: [0, 255, 255, 1],\n width: \"2px\"\n },\n outFields: [\"*\"],\n popupTemplate: trailsP\n }]\n });\n // search expand\n searchExpand = new Expand({\n expandIconClass: \"esri-icon-search\",\n expandTooltip: \"Search for SNP Places\",\n view: view,\n content: searchWidget,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // add all widgets to view \n view.ui.move( \"zoom\", \"bottom-right\");\n view.ui.add([homeButton, track, layerExpand], \"bottom-right\")\n view.ui.add([searchExpand, queryExpand, layerExpand, editExpand],\"top-left\");\n }", "function menuClicks () {\n\n\t\tvar menuIcon = document.getElementById('menu-icon');\n\n\t\tmenuIcon.addEventListener('click', Views.showMenu);\n\t\tmenuLinks();\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserdefault_settings_clause.
visitDefault_settings_clause(ctx) { return this.visitChildren(ctx); }
[ "function kh_parseDefault() {\n var value = this.result[SETTINGS_KEYS.DEFAULT];\n if (value) {\n currentSettings.defaultLayouts = value;\n }\n kh_loadedSetting(SETTINGS_KEYS.DEFAULT);\n}", "function parseDefaultSettings() {\n const {defaultSettings: defaultSettingsInCategories} = require('../data/schema/');\n throw new Error('not implemented yet');\n}", "visitDefault_value_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDefault_selectivity_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDefault_selectivity(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitUser_default_role_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDefault_cost_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXml_general_default_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function addDefaultSettings(settings) {\n const _ = require('lodash');\n const defaults = require(\"../../../defaults.json\");\n settings.setAll(_.merge(defaults, settings.getAll()), {prettify: true});\n}", "visitSupplemental_plsql_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function defParser(node_type, parser, mapper){\n\treturn {\n\t\ttype : node_type,\n\t\tparser : parser = parser.mark().map(x => {\n\t\t\tx.value = mapper(x.value);\n\t\t\treturn createAstNode(node_type, x);\n\t\t}),\n\t};\n}", "function setNodeSelectorsDefaultValue() {\n ctrl.nodeSelectors = lodash.chain(ConfigService)\n .get('nuclio.defaultFunctionConfig.attributes.spec.nodeSelector', [])\n .map(function (value, key) {\n return {\n name: key,\n value: value,\n ui: {\n editModeActive: false,\n isFormValid: key.length > 0 && value.length > 0,\n name: 'nodeSelector'\n }\n };\n })\n .value();\n }", "loadEngineDefaults() {\n for (let key in DEFAULT_SETTINGS) {\n const setting = new Setting(key, DEFAULT_SETTINGS[key]);\n super.set(setting.getName(), setting);\n }\n }", "visitSimple_case_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}", "fillOptions(source, target) {\n // Overrride with settings from user and child class\n function eachRecursive(source, target, level) {\n for (var k in source) {\n // Find variable in default settings\n if (typeof source[k] == \"object\" && source[k] !== null) {\n // If the current level is not defined in the target, it is\n // initialized with empty object.\n if (target[k] === undefined) {\n target[k] = {};\n }\n eachRecursive(source[k], target[k]);\n }\n else {\n // We store each leaf property into the default settings\n target[k] = source[k];\n }\n }\n }\n eachRecursive(source, target);\n }", "visitSmall_stmt(ctx) {\r\n console.log(\"visitSmall_stmt\");\r\n if (ctx.expr_stmt() !== null) {\r\n return this.visit(ctx.expr_stmt());\r\n } else if (ctx.del_stmt() !== null) {\r\n return this.visit(ctx.del_stmt());\r\n } else if (ctx.pass_stmt() !== null) {\r\n return this.visit(ctx.pass_stmt());\r\n } else if (ctx.flow_stmt() !== null) {\r\n return this.visit(ctx.flow_stmt());\r\n } else if (ctx.import_stmt() !== null) {\r\n return this.visit(ctx.import_stmt());\r\n } else if (ctx.global_stmt() !== null) {\r\n return this.visit(ctx.global_stmt());\r\n } else if (ctx.nonlocal_stmt() !== null) {\r\n return this.visit(ctx.nonlocal_stmt());\r\n } else if (ctx.assert_stmt() !== null) {\r\n return this.visit(ctx.assert_stmt());\r\n }\r\n }", "visitSelect_only_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds number of operations
function operationNumber(str) { var operators = ['+', '.', '-', '/', '^', '*']; var count = 0; for (var i = 0; i < str.length-1; i++) { if (operators.includes(str[i])) { count++; } } return count; }
[ "function main() {\n let numerator = [3];\n let denominator = [2];\n let count = 0;\n for (let i = 1; i <= 1000; i += 1) {\n // console.log(numerator, denominator);\n let temp = carryForwardSum(numerator, denominator);\n numerator = carryForwardSum(temp, denominator);\n denominator = temp;\n temp = null;\n if (numerator.length > denominator.length) {\n count += 1;\n }\n }\n return count;\n}", "function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}", "function total_sub_instruction_count_aux(id_of_top_ins, aic_array){\n let result = 0 //this.added_items_count[id_of_top_ins]\n let tally = 1 //this.added_items_count[id_of_top_ins]\n for(let i = id_of_top_ins; true ; i++){\n let aic_for_i = aic_array[i] //this.added_items_count[i]\n if (aic_for_i === undefined) {\n shouldnt(\"total_sub_instruction_count_aux got undefined from aic_array: \" + aic_array)\n }\n result += aic_for_i //often this is adding 0\n tally += aic_for_i - 1\n if (tally == 0) { break; }\n else if (tally < 0) { shouldnt(\"in total_sub_instruction_count got a negative tally\") }\n }\n return result\n}", "function getSelectorLen(selector) {\n var len = 0\n walk(selector)\n function walk(pattern, complexPattern) {\n pattern.forEach((sel, i, arr) => {\n\n if (i !== 0 && sel.type !== \"Combinator\" && arr[i-1].type !== \"Combinator\" && !complexPattern)\n // first sub selector needs space (+1 len) in complex?\n // calc like codegen does, if we need space?\n\n // and not id && sel.type !== \"id\" || \"class\", \"attri\"?\n // we do need space after class etc for non complex\n // but not inside complex. the tree removed spaces\n // parent\n // this is dont after, not before though\n len += 1\n\n if (sel.type === \"UniversalSelector\")\n len++\n else if (sel.type === \"IdSelector\")\n len += sel.name.length + 1\n else if (sel.type === \"ClassSelector\")\n len += sel.name.length + 1\n else if (sel.type === \"TagSelector\")\n len += sel.name.length\n else if (sel.type === \"Combinator\")\n len++\n else if (sel.type === \"AttributeSelector\") {\n len += 2 + sel.name.name.length\n if (sel.operator) len += sel.operator.length\n if (sel.value === \"Identifier\") len += sel.value.name.length // if op, there has to be a value?\n if (sel.value === \"String\") len += sel.value.val.length + 2\n if (sel.flag) len += sel.flag.name.length // s or i\n if (sel.value === \"Identifier\" && sel.flag.name) len++ // add space if flag and ident (not needed for string)\n }\n else if (sel.type === \"PsuedoElementSelector\")\n len += sel.name.length + 2\n else if (sel.type === \"PseudoClassSelector\")\n len += sel.name.length + 2\n else if (sel.type === \"ComplexSelector\") {\n if (i !== 0) len++ // add space at start of ComplexSel (unless its first), since if above dont add for first node in arr\n\n walk(sel.selectors, true)\n }\n })\n }\n\n return len\n}", "crotonTripsCounter(state) {\n var crotonTrips = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n crotonTrips++;\n }\n }\n return crotonTrips;\n }", "function count(input) {\n return input.length;\n}", "function nbDig(n, d) {\n let res = 0;\n for (let g = 0; g <= n; g++) {\n let square = (g * g + \"\").split(\"\");\n square.forEach((s) => s == d ? res++ : null)\n } return res;\n}", "function getOperations(){ //-------------> working\n\nvar count = codeLines.length;\n\nfor(var i=0; i<count; i++){ \n\n\t\tvar commentTest = (/@/.test(codeLines[i].charAt(0))); //Checking for comments\n\t\tvar textTest = (/.text/.test( codeLines[i])); //checking for .text keyword \n\t\tvar globalTest = /.global/.test( codeLines[i]); //checking for .global keyword\n\t\tvar mainTest = /main:/.test( codeLines[i]); //checking for main: label -------> Just for now!! should change later!!!!\n\t\tvar labelTest = labels.hasItem(codeLines[i]); \n\t\n\t\tif(!(commentTest||textTest||globalTest||mainTest||!codeLines[i]||labelTest)){ //(!codeLines[i]) check if the line is blank\n\n\t\t\tvar splitLine = codeLines[i].split(/[ ,\\t]+/).filter(Boolean); //-----> working. filter(Boolean) removes null values\n\t\t\tfunctionsHash.setItem(i, splitLine[0]); //Store function names with their line numbers\n\t\t\t\n\t\t}\n\t}\t\n}", "function getStarCount(repos) {\n return repos.reduce((count, { stargazers_count }) => count + stargazers_count, 0);\n}", "function runAll(num){\n let result5 = halfNumber(num)\n let result6 = squareNumber(result5)\n let result7 = areaOfCircle(result6)\n let result8 = percentOf(result7, result6)\n return result8\n}", "function step_counter(step, counter){\n\t\tif(step === '('){\n\t\t\tcounter ++;\n\t\t}\n\t\telse if(step === ')'){\n\t\t\tcounter --;\n\t\t}\n\t\treturn counter;\n}", "function halveCount(a, b) {\n\tlet x = -1;\n\tfor (let i = 0; a > b; i++) {\n\t\ta /= 2;\n\t\tx++;\n\t}\n\treturn x;\n}", "function test(number) {\n for (let i = 0; i < number; i++) {\n const result = findOptimalStrategiesSet(strategiesArr);\n console.log('result', result);\n }\n return _.sum(times)/times.length;\n}", "function PrintandCount() {\n\tvar count = 0;\n\tfor (var i = 512; i < 4096; i++) {\n\t\tif(i % 5 == 0){\n\t\t\tconsole.log(i)\n\t\t\tcount = count + 1\n\t\t}\n\t}\n\tconsole.log(\"number of integers multiple of 5:\", count)\n}", "bitCount() {\n let result = 0;\n for(let i = 0; i < this.array.length; i++){\n result += BitSet.countBits(this.array[i]) // Assumes we never have bits set beyond the end\n ;\n }\n return result;\n }", "numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }", "function getSelectedLayersCount(){\n\t\tvar res = new Number();\n\t\tvar ref = new ActionReference();\n\t\tref.putEnumerated( charIDToTypeID(\"Dcmn\"), charIDToTypeID(\"Ordn\"), charIDToTypeID(\"Trgt\") );\n\t\tvar desc = executeActionGet(ref);\n\t\tif( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){\n\t\t\tdesc = desc.getList( stringIDToTypeID( 'targetLayers' ));\n\t\t\tres = desc.count \n\t\t}else{\n\t\t\tvar vis = app.activeDocument.activeLayer.visible;\n\t\t\tif(vis == true) app.activeDocument.activeLayer.visible = false;\n\t\t\tcheckVisibility();\n\t\t\tif(app.activeDocument.activeLayer.visible == true){\n\t\t\t\tres =1;\n\t\t\t}else{\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tapp.activeDocument.activeLayer.visible = vis;\n\t\t}\n\t\treturn res;\n\t}", "howManyPieces(player, intersections) { \n let count = 0;\n for (var c = 0; c < intersections.length; c++) { \n if (intersections[c] === player) { count++; }\n }\n return count;\n }", "function incrOpcounter() {\n var incr = 0;\n self.queue.forEach(function(args) {\n if (!self.client.isRead(args[0])) {\n incr++;\n }\n });\n if (incr) {\n self.client.incrOpcounter(incr, function(err) {\n if (err) {\n self.client.master.emit('error', err);\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets add item state as true
addItem() { this.setState({ addItem: 'true' }) }
[ "addNewItem() {\n\t\tconst newItem = {itemName: \"\", tag: \"None\", description:\"\", price:\"\", pic:\"\"};\n\t\tthis.setState((prevState, props) => ({\n\t\t\titems: prevState.items.concat(newItem)\n\t\t}))\n\t}", "function addItemShoppingList(newItem) {\n STORE.items.push({name: newItem, checked: false});\n}", "addItem(item) {\n let newItem = { ...item, id: uuidv4() }; //taking the existing item with only name and id coming from the form and adding an id field\n this.setState(state => ({\n items: [...state.items, newItem] //spread operator syntax, it sets items to be all the existing state items plus the new item\n }));\n }", "add(item) {\n this.items.add(item);\n }", "function addItem(item){\n basket.push(item);\n return true;\n}", "addItem() {\n this.setState({\n itemCount: this.state.itemCount + 1\n });\n }", "addItem(itemId, quntity){\n if (itemId in this.items){\n this.items[itemId].quntity += quntity;\n return true;\n }else if (itemId in productList){\n var itemInfo = productList[itemId];\n this.items[itemId] = {unitPrice: itemInfo.unitPrice,\n quntity: quntity};\n return true;\n } else{\n return false;\n }\n\n }", "addNewItem() {\n // we remove whitespace from both sides of the string saved in newItem\n this.newItem = this.newItem.trim();\n if (this.isInputValid(this.newItem)) {\n // if the user input is valid, we add the user input to the todo-list\n this.todos.push(this.newItem);\n } else if (this.todos.includes(this.newItem)) {\n // if the user input already occurs in the todo-list, we notify the user about this fact\n alert('This item already occurs in the list');\n }\n // in any case, we reset the value of the input\n this.newItem = '';\n }", "function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }", "add(recipeId) {\n\n // First see if recipe is already present\n let item = this.getItem(recipeId)\n\n if (!item) {\n this.items.push({\n id: recipeId\n });\n\n }\n // persists to local storage\n this.update();\n }", "addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }", "addChecked() {\n var checked = this.getChecked();\n Object.keys(checked).forEach(fullId => this.__updateId(fullId, checked[fullId] || true));\n this.update(this.assetIdToLabelMods);\n }", "add(state, { layer, corpuUid }) {\n const index = state.lists[corpuUid].length\n Vue.set(state.lists[corpuUid], index, layer)\n }", "toggleAddByDefault(){\n this.add_new_robot = !this.add_new_robot;\n }", "function addItemToWishList(){\n\n\t\t\t\tconsole.log(wishlist);\n\t\t//increase the quantity of the item in case same item is added//\n\t\t\t\tfor (var i in wishlist){\n\t\t\t\t\tif (wishlist[i].name === name){\n\t\t\t\t\t\tif (wishlist[i].size === size){\n\t\t\t\t\t\t\tif (wishlist[i].flavors === flavors){\n\t\t\t\t\t\t\t\twishlist[i].quantity += quantity;\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (wishlist === null){\n\t\t\t\t\twishlist = [];\n\t\t\t\t}\n\t\t\t\t//push new item to wishlist//\n\t\t\t\tvar item = new Item ();\n\t\t\t\tconsole.log(wishlist);\n\t\t\t\tconsole.log(item);\n\t\t\t\twishlist.push(item);\n\t\t\t\tsaveWishList();\n\t\t\t}", "submit() {\n const { currentItem, addItem, inputMode, clearCurrentItem, setItemShowInput, editItem } = this.props\n if (inputMode === 'add') {\n addItem(currentItem);\n } else {\n editItem(currentItem)\n }\n clearCurrentItem();\n setItemShowInput(false);\n }", "add(key, item, toFirstPosition) {\n if (!_.isString(key)) throw new Error('Parameter \"key\" must be a string!');\n if (key in this.dictionary) return false;\n\n this.dictionary[key] = this.linkedList.add(item, toFirstPosition);\n this.dictionary[key].dictKey = key;\n\n return true;\n }", "async function setItemState(state) {\n switch (itemType) {\n case ItemType.issue:\n await client.rest.issues.update({\n owner: item.owner,\n repo: item.repo,\n issue_number: item.number,\n state: state,\n });\n break;\n\n case ItemType.pr:\n await client.rest.pulls.update({\n owner: item.owner,\n repo: item.repo,\n pull_number: item.number,\n state: state,\n });\n break;\n }\n}", "addRecipe(e) {\n e.preventDefault();\n\n StateManager.UpdateValue(\"UI.EditingRecipe.RecipeId\", -1);\n StateManager.UpdateValue(\"UI.SelectedMenuPanel\", \"recipes\");\n StateManager.UpdateValue(\"UI.IsMenuOpen\", true);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determine what station the tablet is
function getStation() { switch (parseInt(localStorage.station, 10)) { case 1: case 4: return (1); case 2: case 5: return (2); case 3: case 6: return (3); } }
[ "function closestBusTrainStation(userData){\n\n}", "function getWeatherStationById(stationid) {\n\n // Ieder weerstation aflopen\n for (var weerstation in weerstations) {\n if (weerstations.hasOwnProperty(weerstation)) {\n if(weerstations[weerstation].stationid === stationid) {\n return weerstations[weerstation];\n }\n }\n }\n}", "function loadCurrentStation() {\n chrome.storage.local.get('currentStation', function(cfg) {\n if ('number' === typeof cfg['currentStation']) {\n selectedStations = {\n 'currentBand': 'FM',\n 'bands': {\n 'FM': cfg['currentStation']\n }\n };\n } else if (cfg['currentStation']) {\n selectedStations = cfg['currentStation'];\n }\n selectBand(Bands[settings.region][selectedStations['currentBand']]);\n var newFreq = selectedStations['bands'][band.getName()];\n if (newFreq) {\n setFrequency(newFreq, false);\n }\n });\n }", "getCurrentDisplayMode() {\n let width = window.innerWidth;\n if (width < 970) {\n if (width >= 750) {\n return 'tablet'\n } else {\n return 'mobile'\n }\n } else if (width < 1170) {\n return 'desktop'\n } else {\n return 'wide'\n }\n }", "function isValidStation(s) {\n return s.match(/^\\s*\\S+\\s*$/)\n }", "function isSensorPacket(packet) {\n let isMinew = (packet.substr(26,4) === 'e1ff');\n let isCodeBlue = (packet.substr(24,6) === 'ff8305');\n if(isMinew) {\n let isTemperatureHumidity = (packet.substr(38,4) === 'a101');\n let isVisibleLight = (packet.substr(38,4) === 'a102');\n let isAcceleration = (packet.substr(38,4) === 'a103');\n if(isTemperatureHumidity || isVisibleLight || isAcceleration) {\n return true;\n }\n }\n if(isCodeBlue) {\n let isPuckyActive = (packet.substr(30,2) === '02');\n return isPuckyActive;\n }\n\n return false;\n}", "function getClosestStation(point) {\n \n // initialize empty distances array\n var distances = [];\n\n // initialize variable to hold index of closest station\n var closest = -1;\n\n // initialize variable to hold location of station being measured\n var stationLoc = null;\n\n // iterate over stations array\n for (var i = 0, n = stations.length; i < n; i++) {\n\n // turn station location into format Maps can use\n stationLoc = new google.maps.LatLng(stations[i].lat, stations[i].lng);\n\n // distance from station to point\n var d = google.maps.geometry.spherical.computeDistanceBetween(point, stationLoc);\n\n // add distance to distances array\n distances.push(d);\n\n // if this station is the closest we've found so far\n if (closest == -1 || d < distances[closest]) {\n\n // set closest to the index of the current station\n closest = i;\n }\n }\n\n // return closest station and location in a format Maps can use\n var closestLocation = new google.maps.LatLng(stations[closest].lat, stations[closest].lng);\n return {station: stations[closest], latlng: closestLocation};\n}", "function findImageDevice(type,manu,model){\n\tvar st = \"\";\n\ttype = type.toLowerCase();\n\tmanu = manu.toLowerCase();\n\tmodel = model.toLowerCase();\n\tif(type.toLowerCase() == \"dut\"){\n/*\t\tif(manu == \"cisco\"){\n\t\t\tvar mtch = model.match(/asr/g);\n\t\t\tif(mtch ==\"\" || mtch != \"asr\"){\n\t\t\t\tst = '/device/cisco_vivid_blue_40.png';\n\t\t\t}else{\t\t\t\t\t\t\t\n\t\t\t\tst= '/device/asr-1k-40px.png';\n\t\t\t}\n\t\t}else if(manu == \"ixia\"){\n\t\t\tst= '/testtool/ixia-40px.png';\n\t\t}*/\n\t}else if(type == \"testtool\"){\n\t\tif(manu == \"ixia\"){\n\t\t\tst= '/model_icons/ixia-40px.png';\n\t\t}\n\t}\n\treturn st;\n\t\t\n}", "servingTeam() {\n if (this.serving == this.players[0]) {\n return(nameWest);\n } else if (this.serving == this.players[1]) {\n return(nameWest);\n } else if (this.serving == this.players[2]) {\n return(nameEast);\n } else if (this.serving == this.players[3]) {\n return(nameEast);\n } else {\n alert(txt_Invalid1 + this.serving\n + txt_Invalid2 + name_e\n + txt_SQComma + name_o\n + txt_SQComma + name_E\n + txt_SQCommaOr + name_O\n + txt_SQParen);\n }\n }", "function retrieveStatus(){\n request(icecastUrl, function (error, response, body) {\n // If error, log it\n var mountpointList = JSON.parse(body).icestats.source;\n // Check for all three mountpoints\n checkStatus(mountpointList, 'listen');\n checkStatus(mountpointList, 'hub');\n checkStatus(mountpointList, 'harrow');\n });\n}", "function getRandomStation(list){\n\t\treturn list[Math.floor(Math.random() * Math.floor(list.length))];\n\t}", "function getMyLocation() {\n\n // Find user's current location and place on map\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(function(position) {\n\n // Find user's current location\n var currentLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);\n \n // Place marker at user's current location\n var userMarker = new google.maps.Marker({\n position: currentLocation,\n map: map\n });\n\n // Center current location when found\n map.panTo(currentLocation);\n\n // Find which station is closest to user by calculating the shortest distance between user and each station\n var smallestDistance = google.maps.geometry.spherical.computeDistanceBetween(currentLocation, stations[0].position) * 0.000621371192;\n\n for (var i = 0; i < stations.length; i++) {\n if (google.maps.geometry.spherical.computeDistanceBetween(currentLocation, stations[i].position) * 0.000621371192 < smallestDistance) {\n smallestDistance = google.maps.geometry.spherical.computeDistanceBetween(currentLocation, stations[i].position) * 0.000621371192;\n closestStation = stations[i];\n }\n }\n\n // Create arrays to draw polyline between user's current position and closest station\n var closestStationArray = new Array();\n closestStationArray.push(currentLocation);\n closestStationArray.push(closestStation.position);\n\n var meToStation = new google.maps.Polyline({\n path: closestStationArray,\n strokeColor: '#000080'\n });\n\n // Rounds to four decimal places\n smallestDistance = Math.round(smallestDistance * 10000) / 10000;\n\n // Create infowindow for user's current location marker which, when clicked upon, indicates closest station\n infoWindowData = \"You are closest to \" + closestStation.name + \" and it is \" + smallestDistance + \" miles away\";\n\n google.maps.event.addListener(userMarker, 'click', function() {\n infoWindow.setContent(infoWindowData);\n infoWindow.open(map, userMarker); \n });\n\n meToStation.setMap(map);\n });\n } else {\n alert(\"Error: The geolocation service failed\");\n }\n}", "function chooseStation() {\n var stationId = window.location.hash.substr(1);\n\n if (!stationId) {\n // this is the default if none selected\n stationId = 'nac_radio';\n }\n\n var station = STATIONS[stationId];\n var streamId = station.streamId;\n var url = station.url;\n var logo = station.logo;\n\n $('.cc_streaminfo').each(function(idx, elem) {\n // add the selected streamId onto .cc_streaminfo element IDs,\n // e.g. cc_strinfo_title => cc_strinfo_title_nundahac\n elem = $(elem);\n elem.attr('id', elem.attr('id') + '_' + streamId);\n });\n $('#radio').attr('src', url);\n $('.radiologo img').attr('src',logo);\n }", "function isLocalStation(stationIp, adviseLaunchInfo){\n\ttry {\n\t\tvar ipArr = stationIp.split(',');\n\t\t\n\t\tif (ipArr.indexOf(adviseLaunchInfo.localIP) > -1)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t\t\n\t} catch(ex){\n\t\treturn false;\n\t}\n}", "getCurrentStaircase() {\n\t\treturn this.staircases[this.stairIndex].staircase;\n\t}", "function getSensor(label){\n\tvar i=0;\n\tvar alabel=\"init\";\n\t// check that a sensorData object exists before trying to access it. When this script runs\n\t// and a rover has not yet sent any status updates there will be no such sensorData object\n\tif (typeof sensorData === 'object'){\n\t\tfor(i=0;i<sensorData.length;i++){\n\t\t\talabel=sensorData[i].label;\n\t//\t\talert(\"seeking \"+label+\" found \"+alabel+\" at \"+i);\n\t\t\tif(alabel==label) return sensorData[i].value;\n\t\t}\n\t}\n\treturn 0;\n}", "function chooseStation() {\n var stationId = window.location.hash.substr(1);\n\n if (!stationId) {\n // this is the default if none selected\n stationId = 'nac_radio';\n }\n\n var station = STATIONS[stationId];\n var streamId = station.streamId;\n var url = station.url;\n var logo = station.logo;\n\n $('.cc_streaminfo').each(function (idx, elem) {\n // add the selected streamId onto .cc_streaminfo element IDs,\n // e.g. cc_strinfo_title => cc_strinfo_title_nundahac\n elem = $(elem);\n elem.attr('id', elem.attr('id') + '_' + streamId);\n });\n $('#radio').attr('src', url);\n $('.radiologo img').attr('src', logo);\n}", "function selectWeather(){\n\tswitch(weather){\n\t\tcase 'Snow':\n\t\t\tweatherCateg=dataMusic.snow;\n\t\t\tdataWeather = 'Snow';\n\t\t\tbreak;\n\t\tcase 'Clear':\n\t\t\tweatherCateg=dataMusic.sun;\n\t\t\tdataWeather = 'Sun';\n\t\t\tbreak;\n\t\tcase 'Clouds':\n\t\t\tweatherCateg=dataMusic.cloud;\n\t\t\tdataWeather = 'Cloud';\n\t\t\tbreak;\n\t\tcase 'Rain':\n\t\t\tweatherCateg=dataMusic.rain;\n\t\t\tdataWeather = 'Rain';\n\t\t\tbreak;\n\t\tcase 'Drizzle':\n\t\t\tweatherCateg=dataMusic.rain;\n\t\t\tdataWeather = 'Rain';\n\t\t\tbreak;\n\t}\n\tselectMusic();\n}", "function getDeviceTypes() {\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
: (dom.Node, [ViewDesc]) Sync the content of the given DOM node with the nodes associated with the given array of view descs, recursing into mark descs because this should sync the subtree for a whole node at a time.
function renderDescs(parentDOM, descs, view) { var dom = parentDOM.firstChild, written = false; for (var i = 0; i < descs.length; i++) { var desc = descs[i], childDOM = desc.dom; if (childDOM.parentNode == parentDOM) { while (childDOM != dom) { dom = rm$2(dom); written = true; } dom = dom.nextSibling; } else { written = true; parentDOM.insertBefore(childDOM, dom); } if (desc instanceof MarkViewDesc) { var pos = dom ? dom.previousSibling : parentDOM.lastChild; renderDescs(desc.contentDOM, desc.children, view); dom = pos ? pos.nextSibling : parentDOM.firstChild; } } while (dom) { dom = rm$2(dom); written = true; } if (written && view.trackWrites == parentDOM) { view.trackWrites = null; } }
[ "function syncTreeNode(content, path, initialLoad) {\n\n if (!$scope.content.isChildOfListView) {\n navigationService.syncTree({ tree: \"media\", path: path.split(\",\"), forceReload: initialLoad !== true }).then(function (syncArgs) {\n $scope.currentNode = syncArgs.node;\n });\n }\n else if (initialLoad === true) {\n\n //it's a child item, just sync the ui node to the parent\n navigationService.syncTree({ tree: \"media\", path: path.substring(0, path.lastIndexOf(\",\")).split(\",\"), forceReload: initialLoad !== true });\n\n //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node \n // from the server so that we can load in the actions menu.\n umbRequestHelper.resourcePromise(\n $http.get(content.treeNodeUrl),\n 'Failed to retrieve data for child node ' + content.id).then(function (node) {\n $scope.currentNode = node;\n });\n }\n }", "static changeNode(node, selection, splits, dom) {\n\t\tif(node == null || node.parentNode == null)\n\t\t\treturn;\n\t\tif(dom == null)\n\t\t\tdom = document;\n\t\tvar master = node.parentNode;\n\t\tmaster.removeChild(node); //ich denke hier werden mehrere kinder möglch sein, deshalb reversing\n\t\tMarkMyWords._highlights[master] = node;\n\t\tfor(var item of splits) {\n\t\t\tmaster.appendChild(item === null ?\n\t\t\t\tMarkMyWords.makeMarkNode(selection, dom) :\n\t\t\t\tdom.createTextNode(item));\n\t\t}\n\t}", "function dwscripts_queueNodeEdit(text, node, replaceRangeStart, replaceRangeEnd, dontFormatForMerge)\n{\n var optionFlags = 0;\n if (dontFormatForMerge)\n {\n optionFlags |= docEdits.QUEUE_DONT_FORMAT_FOR_MERGE;\n }\n\n var nodeSeg = new NodeSegment(node, replaceRangeStart, replaceRangeEnd);\n\n docEdits.queue(text, nodeSeg, \"\", null, optionFlags);\n}", "function seqRender(views, done) {\n // Once all views have been rendered invoke the sequence render\n // callback\n if (!views.length) {\n return done();\n }\n\n // Get each view in order, grab the first one off the stack\n var view = views.shift();\n\n // This View is now managed by LayoutManager *toot*.\n view.__manager__.isManaged = true;\n\n // Render the View and once complete call the next view.\n view.render(function () {\n // Invoke the recursive sequence render function with the remaining\n // views\n seqRender(views, done);\n });\n }", "syncMarkupWithModel() {\n this.#syncLabel()\n this.#syncWidget()\n }", "function sync(oldTree, newTree, patches) {\n patches = patches || [];\n\n if (!Array.isArray(patches)) {\n throw new Error('Missing Array to sync patches into');\n }\n\n if (!oldTree) {\n throw new Error('Missing existing tree to sync');\n }\n\n var oldNodeValue = oldTree.nodeValue;\n var oldChildNodes = oldTree.childNodes;\n var oldChildNodesLength = oldChildNodes ? oldChildNodes.length : 0;\n var oldElement = oldTree.uuid;\n var oldNodeName = oldTree.nodeName;\n var oldIsTextNode = oldNodeName === '#text';\n\n if (!newTree) {\n var removed = [oldTree].concat(oldChildNodes.splice(0, oldChildNodesLength));\n\n patches.push({\n __do__: REMOVE_ENTIRE_ELEMENT,\n element: oldTree,\n toRemove: removed\n });\n\n return patches;\n }\n\n var nodeValue = newTree.nodeValue;\n var childNodes = newTree.childNodes;\n var childNodesLength = childNodes ? childNodes.length : 0;\n var newElement = newTree.uuid;\n var nodeName = newTree.nodeName;\n var newIsTextNode = nodeName === '#text';\n var oldIsFragment = oldTree.nodeName === '#document-fragment';\n var newIsFragment = newTree.nodeName === '#document-fragment';\n var skipAttributeCompare = false;\n\n // Replace the key attributes.\n oldTree.key = newTree.key;\n\n // Fragments should not compare attributes.\n if (oldIsFragment || newIsFragment) {\n skipAttributeCompare = true;\n }\n // If the element we're replacing is totally different from the previous\n // replace the entire element, don't bother investigating children.\n else if (oldTree.nodeName !== newTree.nodeName) {\n patches.push({\n __do__: REPLACE_ENTIRE_ELEMENT,\n old: oldTree,\n new: newTree\n });\n\n return patches;\n }\n\n // If the top level nodeValue has changed we should reflect it.\n if (oldIsTextNode && newIsTextNode && oldNodeValue !== nodeValue) {\n patches.push({\n __do__: CHANGE_TEXT,\n element: oldTree,\n value: newTree.nodeValue\n });\n\n oldTree.nodeValue = newTree.nodeValue;\n\n return patches;\n }\n\n // Most common additive elements.\n if (childNodesLength > oldChildNodesLength) {\n // Store elements in a DocumentFragment to increase performance and be\n // generally simplier to work with.\n var fragment = [];\n\n for (var i = oldChildNodesLength; i < childNodesLength; i++) {\n // Internally add to the tree.\n oldChildNodes.push(childNodes[i]);\n\n // Add to the document fragment.\n fragment.push(childNodes[i]);\n }\n\n oldChildNodesLength = oldChildNodes.length;\n\n // Assign the fragment to the patches to be injected.\n patches.push({\n __do__: MODIFY_ELEMENT,\n element: oldTree,\n fragment: fragment\n });\n }\n\n // Ensure keys exist for all the old & new elements.\n var noOldKeys = !oldChildNodes.some(function (oldChildNode) {\n return oldChildNode.key;\n });\n\n // Remove these elements.\n if (oldChildNodesLength > childNodesLength) {\n (function () {\n // For now just splice out the end items.\n var diff = oldChildNodesLength - childNodesLength;\n var toRemove = [];\n var shallowClone = [].concat(_toConsumableArray(oldChildNodes));\n\n // There needs to be keys to diff, if not, there's no point in checking.\n if (noOldKeys) {\n toRemove = oldChildNodes.splice(oldChildNodesLength - diff, diff);\n }\n // This is an expensive operation so we do the above check to ensure that a\n // key was specified.\n else {\n (function () {\n var newKeys = new Set(childNodes.map(function (childNode) {\n return String(childNode.key);\n }).filter(Boolean));\n\n var oldKeys = new Set(oldChildNodes.map(function (childNode) {\n return String(childNode.key);\n }).filter(Boolean));\n\n var keysToRemove = {};\n var truthy = 1;\n\n // Find the keys in the sets to remove.\n oldKeys.forEach(function (key) {\n if (!newKeys.has(key)) {\n keysToRemove[key] = truthy;\n }\n });\n\n // If the original childNodes contain a key attribute, use this to\n // compare over the naive method below.\n shallowClone.forEach(function (oldChildNode, i) {\n if (toRemove.length >= diff) {\n return;\n } else if (keysToRemove[oldChildNode.key]) {\n var nextChild = oldChildNodes[i + 1];\n var nextIsTextNode = nextChild && nextChild.nodeType === 3;\n var count = 1;\n\n // Always remove whitespace in between the elements.\n if (nextIsTextNode && toRemove.length + 2 <= diff) {\n count = 2;\n }\n // All siblings must contain a key attribute if they exist.\n else if (nextChild && nextChild.nodeType === 1 && !nextChild.key) {\n throw new Error('\\n All element siblings must consistently contain key attributes.\\n '.trim());\n }\n\n // Find the index position from the original array.\n var indexPos = oldChildNodes.indexOf(oldChildNode);\n\n // Find all the items to remove.\n toRemove.push.apply(toRemove, oldChildNodes.splice(indexPos, count));\n }\n });\n })();\n }\n\n // Ensure we don't remove too many elements by accident;\n toRemove.length = diff;\n\n // Ensure our internal length check is matched.\n oldChildNodesLength = oldChildNodes.length;\n\n if (childNodesLength === 0) {\n patches.push({\n __do__: REMOVE_ELEMENT_CHILDREN,\n element: oldTree,\n toRemove: toRemove\n });\n } else {\n // Remove the element, this happens before the splice so that we still\n // have access to the element.\n toRemove.forEach(function (old) {\n return patches.push({\n __do__: MODIFY_ELEMENT,\n old: old\n });\n });\n }\n })();\n }\n\n // Replace elements if they are different.\n if (oldChildNodesLength >= childNodesLength) {\n for (var _i = 0; _i < childNodesLength; _i++) {\n if (oldChildNodes[_i].nodeName !== childNodes[_i].nodeName) {\n // Add to the patches.\n patches.push({\n __do__: MODIFY_ELEMENT,\n old: oldChildNodes[_i],\n new: childNodes[_i]\n });\n\n // Replace the internal tree's point of view of this element.\n oldChildNodes[_i] = childNodes[_i];\n } else {\n sync(oldChildNodes[_i], childNodes[_i], patches);\n }\n }\n }\n\n // Synchronize attributes\n var attributes = newTree.attributes;\n\n if (attributes && !skipAttributeCompare) {\n var oldLength = oldTree.attributes.length;\n var newLength = attributes.length;\n\n // Start with the most common, additive.\n if (newLength > oldLength) {\n var toAdd = slice.call(attributes, oldLength);\n\n for (var _i2 = 0; _i2 < toAdd.length; _i2++) {\n var change = {\n __do__: MODIFY_ATTRIBUTE,\n element: oldTree,\n name: toAdd[_i2].name,\n value: toAdd[_i2].value\n };\n\n var attr = _pools.pools.attributeObject.get();\n attr.name = toAdd[_i2].name;\n attr.value = toAdd[_i2].value;\n\n _pools.pools.attributeObject.protect(attr);\n\n // Push the change object into into the virtual tree.\n oldTree.attributes.push(attr);\n\n // Add the change to the series of patches.\n patches.push(change);\n }\n }\n\n // Check for removals.\n if (oldLength > newLength) {\n var _toRemove = slice.call(oldTree.attributes, newLength);\n\n for (var _i3 = 0; _i3 < _toRemove.length; _i3++) {\n var _change = {\n __do__: MODIFY_ATTRIBUTE,\n element: oldTree,\n name: _toRemove[_i3].name,\n value: undefined\n };\n\n // Remove the attribute from the virtual node.\n var _removed = oldTree.attributes.splice(_i3, 1);\n\n for (var _i4 = 0; _i4 < _removed.length; _i4++) {\n _pools.pools.attributeObject.unprotect(_removed[_i4]);\n }\n\n // Add the change to the series of patches.\n patches.push(_change);\n }\n }\n\n // Check for modifications.\n var toModify = attributes;\n\n for (var _i5 = 0; _i5 < toModify.length; _i5++) {\n var oldAttrValue = oldTree.attributes[_i5] && oldTree.attributes[_i5].value;\n var newAttrValue = attributes[_i5] && attributes[_i5].value;\n\n // Only push in a change if the attribute or value changes.\n if (oldAttrValue !== newAttrValue) {\n var _change2 = {\n __do__: MODIFY_ATTRIBUTE,\n element: oldTree,\n name: toModify[_i5].name,\n value: toModify[_i5].value\n };\n\n // Replace the attribute in the virtual node.\n var _attr = oldTree.attributes[_i5];\n _attr.name = toModify[_i5].name;\n _attr.value = toModify[_i5].value;\n\n // Add the change to the series of patches.\n patches.push(_change2);\n }\n }\n }\n\n return patches;\n}", "function DisplaySimpleSemTree(SemTree, DivForSemTree, DivForTextVersion, DivForButtons, DivForComments) {\n SemTree_SemTreeData = SemTree;\n if (DivForSemTree != \"\") {\n if (document.getElementById(DivForSemTree)) {\n Semtree_TreeDivId = DivForSemTree;\n Semtree_CommentDivId = DivForComments;\n Semtree_AdjustButtons = DivForButtons;\n\n SearchSimilarSubnodes(SemTree);\n UpdateAdjust();\n Animate();\n GenerateComment(-1, -1);\n }\n else {\n alert(\"div \" + DivForSemTree + \" where to display sem tree animation doesn't exist\");\n }\n }\n\n if (DivForTextVersion != \"\") {\n if (document.getElementById(DivForTextVersion)) {\n SemTree_SemTreeData = SemTree;\n DisplayWordList(SemTree_SemTreeData, DivForTextVersion);\n }\n else {\n alert(\"div \" + DivForTextVersion + \" where to display sem tree text doesn't exist\");\n }\n }\n\n}", "function expandAll(d) {\n root.children.forEach(expand);\n update(root);\n }", "function collectRefsRecursive(host, content, refs) {\n var childNodes = host.childNodes;\n for (var i = 0, n = content.length; i < n; ++i) {\n var elem = content[i];\n var type = elem.type;\n if (type === 1 /* Node */) {\n var node = childNodes[i];\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = node;\n collectRefsRecursive(node, elem.children, refs);\n }\n else if (type === 2 /* Component */) {\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = componentMap.get(childNodes[i]);\n }\n }\n }", "_handleModelNodesChanged(event) {\n event.changes.keys.forEach( (value, key) => {\n if (value.action === 'add') {\n let syncedModelNode = event.currentTarget.get(key);// event.object.get(key);\n let modelNodeElement = this._addModelNode(syncedModelNode);\n\n // check if the node was created locally\n if (this._lastLocallyCreatedElementId === syncedModelNode.id) {\n // check if we have children to sync\n let childrenArray = modelNodeElement.getChildrenArray();\n childrenArray.forEach(item => {\n if (this._syncedModelNodes.get(item.id) === undefined) {\n //let sharedState = this.direwolfSpace.sharedStates.set(item.id, Y.Map);\n //item.sharedState = sharedState;\n this._syncedModelNodes.set(item.id, item);\n }\n });\n\n // activate manipulators\n this._activateNodeManipulators(modelNodeElement.element.node);\n modelNodeElement.element.node.classList.add('animated');\n modelNodeElement.element.node.classList.add('fadeIn');\n }\n } else if (value.action === 'delete') {\n // delete\n let modelNode = this._modelNodes[key];\n //TODO: add animation\n modelNode.element.remove();\n delete this._modelNodes[key];\n this._modelNodesDataTree = this._calculateModelNodesDataTree();\n // hide manipulators\n this._modelManipulators.setAttribute('visibility', 'hidden');\n this._elementPropertiesPanel.elementProperties = {};\n this._elementPropertiesPanel.hidden = true;\n this._htmlBindingPropertiesPanel.elementProperties = {};\n this._htmlBindingPropertiesPanel.hidden = true;\n this._deleteButton.disabled = true;\n this._selectedElementTitle = '';\n }\n });\n }", "update_elem(id, type, data){\n //console.log(\"Data to update: \",data);\n //first check if it's the Diagram\n if (id == this.DIAGRAM_GENERAL.data.id) {\n for (var k_data in data) {\n if (data[k_data] != -1) {\n if (k_data == \"name\") {\n if (this.DIAGRAM_GENERAL.data.hasOwnProperty(k_data)) {\n this.DIAGRAM_GENERAL.data[k_data] = data[k_data];\n }\n }else {\n //is a param\n if (this.DIAGRAM_GENERAL.data.hasOwnProperty(\"param\")) {\n this.DIAGRAM_GENERAL.data.param[k_data] = data[k_data];\n }\n }\n }\n }\n return this.DIAGRAM_GENERAL;\n }\n\n var d_elem = this.cy.getElementById(id);\n\n // (1) update it's data first\n var value_updated = false;\n for (var k_data in data) {\n if (data[k_data] != -1) {\n\n if (k_data == \"value\")\n if (data.value != -1)\n value_updated = true;\n\n if (d_elem._private.data.hasOwnProperty(k_data)) {\n d_elem._private.data[k_data] = data[k_data];\n }else if ('param' in d_elem._private.data) {\n //its a param\n if (d_elem._private.data.param.hasOwnProperty(k_data)) {\n d_elem._private.data.param[k_data] = data[k_data];\n }\n }\n }\n }\n if (value_updated) {\n var new_node_data = this.gen_node_data(type, data.value).data;\n d_elem._private.data.value = data.value;\n d_elem._private.data.param = new_node_data.param;\n }\n\n // (2) Its style in the cy diagram\n this.adapt_style(d_elem);\n\n // (2.1) In case is an Edge then STOP HERE\n if(d_elem.isEdge()){\n return d_elem;\n }\n\n // (3) The realtime correlated items (Remove neighborhood edges in case not suitable anymore)\n this.check_node_compatibility(d_elem, true);\n\n // (4) The real time compatible elements of the cy diagram\n this.check_node_compatibility(d_elem);\n\n //update diagram\n this.cy.style().update();\n\n //undo_redo update\n //this.cy_undo_redo.do(\"add\", this.cy.$(\"#\"+d_elem._private.data.id));\n\n return d_elem;\n }", "function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n });\n } // notifyObservers", "function getNodePointers(callback) {\n\tvar nodes = [];\n\tvar deltas = [];\n\n\t// get all modification data\n\tcon.query('SELECT * FROM modifications;', function(err, result) {\n\t\t// clear mod table\n\t\tcon.query('DELETE FROM modifications;', function(err, res) {\n\t\t\tif (err) throw err;\n\t\t});\n\n\t\tfor (var i = 0; i < result.length; i++) {\n\t\t\tif (Math.abs(result[i].delta) > 0) {\n\t\t\t\tglobal.stableTree.traceFullSection(result[i].word.split(''), function(search_res) {\n\t\t\t\t\t// if search completed\n\t\t\t\t\tif (search_res.remainingBranch.length == 0) {\n\t\t\t\t\t\tnodes.push({node: search_res.node, delta: result[i].delta});\t// keep track of node pointer with delta\n\t\t\t\t\t\tdeltas.push(Math.abs(result[i].delta));\t// add delta abs value for alpha calculation later\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tcallback({nodes: nodes, deltas: deltas});\n\t});\n}", "function GenerateComment(i, j) {\n var Width = GetLayerWidth(Semtree_TreeDivId);\n var Height = GetLayerHeight(Semtree_TreeDivId);\n var x = Width / 2;\n var y = Height / 2;\n var Scale = (Width + Height) / 4;\n var X;\n var Y;\n var Html = \"\";\n var SemTree = SemTree_SemTreeData;\n Html += '<a href=\"javascript:GenerateComment(-1,-1)\"><div align=right class=\"SemTree_CommentWindow_Close\">[X]&nbsp;Close</div></a>';\n if ((i < 0) && (j < 0)) {\n Html += \"Click on any word in the graph.\"\n document.getElementById(Semtree_CommentDivId).style.display = \"None\";\n }\n else if ((i >= 0) && (j < 0)) {\n X = (SemTree[i].x - XOffset) * Zoom * Scale + x;\n Y = Height - ((SemTree[i].y - YOffset) * Zoom * Scale + y);\n var k;\n var List = \"\";\n Html += '<h2 class=\"SemTree_CommentWindow_Title\">You clicked on the word \"<b>' + SemTree[i].label + '</b>\".</h2>';\n Html += '<ul>';\n Html += '<li>This is one of the keyword that defines the content of your website<br>(other examples of those important words are: ';\n for (k = 0; k < SemtreeLength(SemTree); k++) {\n if (k != i) {\n if (List != '') {\n List += ', ';\n }\n List += SemTree[k].label;\n }\n }\n Html += '\"' + List + '\").<br>';\n Html += 'This word is likely one that you\\'d like to be SEO optimised.<br>';\n Html += 'If this is the case, here is a link explaining <a href=\"javascript:alert(\\'Not yet !\\')\">how to optimise \"' + SemTree[i].label + '\" on your website</a>.';\n Html += '<li>Sentences containing \"' + SemTree[i].label + '\" also often contain the following words:<br>';\n Html += '<small><ul>';\n for (k = 0; k < SemsubtreeLength(SemTree, i); k++) {\n Html += '<li>' + SemTree[i].subnodes[k].label;\n }\n Html += '</ul></small>';\n Html += 'Combinations such as \"' + SemTree[i].label + ' ' + SemTree[i].subnodes[0].label + '\", ';\n Html += '\"' + SemTree[i].label + ' ' + SemTree[i].subnodes[1].label + '\", ';\n Html += '\"' + SemTree[i].label + ' ' + SemTree[i].subnodes[2].label + '\",... ';\n Html += 'are also good candidates for SEO.';\n Html += '<li>Here are the pages where \"' + SemTree[i].label + '\" appears most:';\n Html += '<small><ul>';\n for (k = 0; k < SemTree[i].urls.length; k++) {\n Html += '<li>Appears ' + SemTree[i].urls[k].count + ' times on <a href=\"' + SemTree[i].urls[k].url + '\" target=_blank>' + SemTree[i].urls[k].url + '</a>';\n }\n Html += '</ul></small>';\n Html += '<li>If \"' + SemTree[i].label + '\" seems odd as representative of your content, you may have ';\n Html += 'an issue with the way your content is written and how it appears to others.<br>';\n Html += 'This link will <a href=\"javascript:alert(\\'Not yet !\\')\">give you advices on how to write content on your site</a>.';\n document.getElementById(Semtree_CommentDivId).style.display = \"\";\n }\n else {\n X = (SemTree[i].subnodes[j].x - XOffset) * Zoom * Scale + x;\n Y = Height - ((SemTree[i].subnodes[j].y - YOffset) * Zoom * Scale + y);\n Html += '<h2 class=\"SemTree_CommentWindow_Title\">You clicked on the word \"<b>' + SemTree[i].subnodes[j].label + '</b>\".</h2>';\n Html += '<ul>';\n Html += '<li>This word is often found in the neighborhood of \"' + SemTree[i].label + '\".';\n List = \"\";\n for (k = 0; k < SemtreeLength(SemTree); k++) {\n if (k != i) {\n var kk;\n for (kk = 0; kk < SemsubtreeLength(SemTree, k); kk++) {\n if (SemTree[i].subnodes[j].label == SemTree[k].subnodes[kk].label) {\n if (List != \"\") {\n List += \", \";\n }\n List += '\"' + SemTree[k].label + '\"';\n }\n }\n }\n }\n if (List != \"\") {\n Html += \"<li>It is also found in the neighborhood of \" + List + \".\";\n }\n Html += '<ul>';\n document.getElementById(Semtree_CommentDivId).style.display = \"\";\n }\n document.getElementById(Semtree_CommentDivId).innerHTML = Html;\n document.getElementById(Semtree_CommentDivId).style.left = X + \"px\";\n document.getElementById(Semtree_CommentDivId).style.top = Y + \"px\";\n}", "function applyToDOM(){\n var hasSortedAll = elmObjsSorted.length===elmObjsAll.length;\n if (isSameParent&&hasSortedAll) {\n if (isFlex) {\n elmObjsSorted.forEach(function(elmObj,i){\n elmObj.elm.style.order = i;\n });\n } else {\n if (parentNode) parentNode.appendChild(sortedIntoFragment());\n else console.warn('parentNode has been removed');\n }\n } else {\n var criterium = criteria[0]\n ,place = criterium.place\n ,placeOrg = place==='org'\n ,placeStart = place==='start'\n ,placeEnd = place==='end'\n ,placeFirst = place==='first'\n ,placeLast = place==='last'\n ;\n if (placeOrg) {\n elmObjsSorted.forEach(addGhost);\n elmObjsSorted.forEach(function(elmObj,i) {\n replaceGhost(elmObjsSortedInitial[i],elmObj.elm);\n });\n } else if (placeStart||placeEnd) {\n var startElmObj = elmObjsSortedInitial[placeStart?0:elmObjsSortedInitial.length-1]\n ,startParent = startElmObj.elm.parentNode\n ,startElm = placeStart?startParent.firstChild:startParent.lastChild;\n if (startElm!==startElmObj.elm) startElmObj = {elm:startElm};\n addGhost(startElmObj);\n placeEnd&&startParent.appendChild(startElmObj.ghost);\n replaceGhost(startElmObj,sortedIntoFragment());\n } else if (placeFirst||placeLast) {\n var firstElmObj = elmObjsSortedInitial[placeFirst?0:elmObjsSortedInitial.length-1];\n replaceGhost(addGhost(firstElmObj),sortedIntoFragment());\n }\n }\n }", "markSeenAll () { // mark this comment and all replies 'seen'\n if (!this.seenByMe) {\n this.seenByMe = true\n const token = localStorage.getItem(\"nb.user\");\n const headers = { headers: { Authorization: 'Bearer ' + token }}\n axios.post(`/api/annotations/seen/${this.id}`,{} ,headers)\n }\n for (let child of this.children) {\n child.markSeenAll()\n }\n }", "function walkViewTree(rootView, fn) {\n let visit_ = view => {\n fn(view);\n\n let nsArray = view.subviews();\n let count = nsArray.count();\n for (let i = 0; i < count; i++) {\n visit_(nsArray.objectAtIndex(i));\n }\n };\n\n visit_(rootView);\n}", "function dfs_mark(elem, config) {\n if(elem.nodeType === elem.TEXT_NODE) {\n if(elem === config.start) {\n config.in_range = true;\n mark_partial(config.doc, elem, config.start_offset, false);\n } else if(elem === config.end) {\n config.terminate = true;\n mark_partial(config.doc, elem, config.end_offset, true);\n } else if(config.in_range) {\n mark_whole(config.doc, elem);\n }\n } else if(elem.nodeType === elem.ELEMENT_NODE) {\n // Note: as we might add <span> nodes, should cache childNodes\n // to avoid infinite loop\n var i, childNodes = slice.call(elem.childNodes, 0);\n for(i = 0;i < childNodes.length && !config.terminate;i++) {\n dfs_mark(childNodes[i], config);\n }\n }\n }", "function fullpath(d, idx) {\r\n idx = idx || 0;\r\n curPath.push(d);\r\n return (\r\n d.parent ? fullpath(d.parent, curPath.length) : '') +\r\n '/<span class=\"nodepath'+(d.data.name === root.data.name ? ' highlight' : '')+\r\n '\" data-sel=\"'+ idx +'\" title=\"Set Root to '+ d.data.name +'\">' +\r\n d.name + '</span>';\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an interpolation binding with 7 expressions.
function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) { var bindingIndex = lView[BINDING_INDEX]; var different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3); different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different; lView[BINDING_INDEX] += 7; // Only set static strings the first time (data will be null subsequent runs). var data = storeBindingMetadata(lView, prefix, suffix); if (data) { var tData = lView[TVIEW].data; tData[bindingIndex] = i0; tData[bindingIndex + 1] = i1; tData[bindingIndex + 2] = i2; tData[bindingIndex + 3] = i3; tData[bindingIndex + 4] = i4; tData[bindingIndex + 5] = i5; } return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + i5 + renderStringify(v6) + suffix : NO_CHANGE; }
[ "function createInterpolator(data, numTimes, numStations) {\n interpolateProgram = GLProgram.create(gl)\n .loadShader('copyVertices')\n .loadShader('interpolate', '#define SIZE ' + numStations)\n .linkProgram()\n .setUniform('wh', canvas.width, canvas.height)\n .setUniform('stations', numStations)\n .setUniform('times', numTimes)\n .createTexture('data', data, numTimes, numStations, { color: 'rgba', type: 'float', minfilter: filterType, magfilter: filterType })\n .bindLoadedTexture('data', 1)\n .defineUnitQuad('vPosition', 'vTexCoord');\n }", "function getPropertyInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 1:\r\n return Identifiers$1.propertyInterpolate;\r\n case 3:\r\n return Identifiers$1.propertyInterpolate1;\r\n case 5:\r\n return Identifiers$1.propertyInterpolate2;\r\n case 7:\r\n return Identifiers$1.propertyInterpolate3;\r\n case 9:\r\n return Identifiers$1.propertyInterpolate4;\r\n case 11:\r\n return Identifiers$1.propertyInterpolate5;\r\n case 13:\r\n return Identifiers$1.propertyInterpolate6;\r\n case 15:\r\n return Identifiers$1.propertyInterpolate7;\r\n case 17:\r\n return Identifiers$1.propertyInterpolate8;\r\n default:\r\n return Identifiers$1.propertyInterpolateV;\r\n }\r\n }", "function replacePlaceholders(quasisDoc, expressionDocs) {\n if (!expressionDocs || !expressionDocs.length) {\n return quasisDoc;\n }\n\n const expressions = expressionDocs.slice();\n let replaceCounter = 0;\n const newDoc = mapDoc$3(quasisDoc, doc => {\n if (!doc || !doc.parts || !doc.parts.length) {\n return doc;\n }\n\n let {\n parts\n } = doc;\n const atIndex = parts.indexOf(\"@\");\n const placeholderIndex = atIndex + 1;\n\n if (atIndex > -1 && typeof parts[placeholderIndex] === \"string\" && parts[placeholderIndex].startsWith(\"prettier-placeholder\")) {\n // If placeholder is split, join it\n const at = parts[atIndex];\n const placeholder = parts[placeholderIndex];\n const rest = parts.slice(placeholderIndex + 1);\n parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);\n }\n\n const atPlaceholderIndex = parts.findIndex(part => typeof part === \"string\" && part.startsWith(\"@prettier-placeholder\"));\n\n if (atPlaceholderIndex > -1) {\n const placeholder = parts[atPlaceholderIndex];\n const rest = parts.slice(atPlaceholderIndex + 1);\n const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\\s\\S]*)/);\n const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:\n // animation: linear ${time}s ease-out;\n\n const suffix = placeholderMatch[2];\n const expression = expressions[placeholderID];\n replaceCounter++;\n parts = parts.slice(0, atPlaceholderIndex).concat([\"${\", expression, \"}\" + suffix]).concat(rest);\n }\n\n return Object.assign({}, doc, {\n parts\n });\n });\n return expressions.length === replaceCounter ? newDoc : null;\n }", "function replacePlaceholders(quasisDoc, expressionDocs) {\n if (!expressionDocs || !expressionDocs.length) {\n return quasisDoc;\n }\n\n const expressions = expressionDocs.slice();\n let replaceCounter = 0;\n const newDoc = mapDoc$1(quasisDoc, doc => {\n if (!doc || !doc.parts || !doc.parts.length) {\n return doc;\n }\n\n let {\n parts\n } = doc;\n const atIndex = parts.indexOf(\"@\");\n const placeholderIndex = atIndex + 1;\n\n if (atIndex > -1 && typeof parts[placeholderIndex] === \"string\" && parts[placeholderIndex].startsWith(\"prettier-placeholder\")) {\n // If placeholder is split, join it\n const at = parts[atIndex];\n const placeholder = parts[placeholderIndex];\n const rest = parts.slice(placeholderIndex + 1);\n parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);\n }\n\n const atPlaceholderIndex = parts.findIndex(part => typeof part === \"string\" && part.startsWith(\"@prettier-placeholder\"));\n\n if (atPlaceholderIndex > -1) {\n const placeholder = parts[atPlaceholderIndex];\n const rest = parts.slice(atPlaceholderIndex + 1);\n const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\\s\\S]*)/);\n const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:\n // animation: linear ${time}s ease-out;\n\n const suffix = placeholderMatch[2];\n const expression = expressions[placeholderID];\n replaceCounter++;\n parts = parts.slice(0, atPlaceholderIndex).concat([\"${\", expression, \"}\" + suffix]).concat(rest);\n }\n\n return Object.assign({}, doc, {\n parts\n });\n });\n return expressions.length === replaceCounter ? newDoc : null;\n}", "function getTextInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 1:\r\n return Identifiers$1.textInterpolate;\r\n case 3:\r\n return Identifiers$1.textInterpolate1;\r\n case 5:\r\n return Identifiers$1.textInterpolate2;\r\n case 7:\r\n return Identifiers$1.textInterpolate3;\r\n case 9:\r\n return Identifiers$1.textInterpolate4;\r\n case 11:\r\n return Identifiers$1.textInterpolate5;\r\n case 13:\r\n return Identifiers$1.textInterpolate6;\r\n case 15:\r\n return Identifiers$1.textInterpolate7;\r\n case 17:\r\n return Identifiers$1.textInterpolate8;\r\n default:\r\n return Identifiers$1.textInterpolateV;\r\n }\r\n }", "function getStylePropInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 1:\r\n return Identifiers$1.styleProp;\r\n case 3:\r\n return Identifiers$1.stylePropInterpolate1;\r\n case 5:\r\n return Identifiers$1.stylePropInterpolate2;\r\n case 7:\r\n return Identifiers$1.stylePropInterpolate3;\r\n case 9:\r\n return Identifiers$1.stylePropInterpolate4;\r\n case 11:\r\n return Identifiers$1.stylePropInterpolate5;\r\n case 13:\r\n return Identifiers$1.stylePropInterpolate6;\r\n case 15:\r\n return Identifiers$1.stylePropInterpolate7;\r\n case 17:\r\n return Identifiers$1.stylePropInterpolate8;\r\n default:\r\n return Identifiers$1.stylePropInterpolateV;\r\n }\r\n }", "static ParseBindingss(bindings) {\n // We start out with a basic config\n const NAME = 'BTooltip';\n let config = {\n delay: getComponentConfig(NAME, 'delay'),\n boundary: String(getComponentConfig(NAME, 'boundary')),\n boundaryPadding: parseInt(getComponentConfig(NAME, 'boundaryPadding'), 10) || 0\n };\n // Process bindings.value\n if (isString(bindings.value)) {\n // Value is tooltip content (html optionally supported)\n config.title = bindings.value;\n }\n else if (isFunction(bindings.value)) {\n // Title generator function\n config.title = bindings.value;\n }\n else if (isObject(bindings.value)) {\n // Value is config object, so merge\n config = Object.assign({}, config, bindings.value);\n }\n // If argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg\n // We must prepend '#' to become a CSS selector\n config.container = `#${bindings.arg}`;\n }\n // Process modifiers\n keys(bindings.modifiers).forEach(mod => {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n }\n else if (/^nofade$/.test(mod)) {\n // No animation\n config.animation = false;\n }\n else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // Placement of tooltip\n config.placement = mod;\n }\n else if (/^(window|viewport|scrollParent)$/.test(mod)) {\n // Boundary of tooltip\n config.boundary = mod;\n }\n else if (/^d\\d+$/.test(mod)) {\n // Delay value\n const delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n }\n else if (/^o-?\\d+$/.test(mod)) {\n // Offset value, negative allowed\n const offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n // Special handling of event trigger modifiers trigger is\n // a space separated list\n const selectedTriggers = {};\n // Parse current config object trigger\n let triggers = isString(config.trigger) ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(trigger => {\n if (validTriggers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Parse modifiers for triggers\n keys(validTriggers).forEach(trigger => {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Sanitize triggers\n config.trigger = keys(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to 'focus'\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // Remove trigger config\n delete config.trigger;\n }\n return config;\n }", "function getAttributeInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 3:\r\n return Identifiers$1.attributeInterpolate1;\r\n case 5:\r\n return Identifiers$1.attributeInterpolate2;\r\n case 7:\r\n return Identifiers$1.attributeInterpolate3;\r\n case 9:\r\n return Identifiers$1.attributeInterpolate4;\r\n case 11:\r\n return Identifiers$1.attributeInterpolate5;\r\n case 13:\r\n return Identifiers$1.attributeInterpolate6;\r\n case 15:\r\n return Identifiers$1.attributeInterpolate7;\r\n case 17:\r\n return Identifiers$1.attributeInterpolate8;\r\n default:\r\n return Identifiers$1.attributeInterpolateV;\r\n }\r\n }", "function createPlusLevelSix() {\n var rangeAB = range(1, 11);\n var numberA = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n var numberB = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n\n var numberSum = numberA + numberB;\n \n var plusEquation = [numberA, numberB, numberSum];\n return plusEquation;\n}", "function Expression(op, as) {\n\tthis.operator = op;\n\t// Break up bound quantifiers: all_x( p(x) ) --> all(x, p(x))\n\tif (this.operator.indexOf(\"_\") >= 0) {\n\t\tvar d = this.operator.split(\"_\");\n\t\tif (d[1][0] === '@') {\n\t\t\treturn new Expression( d[0], [d[1].substr(1)].concat(as) );\n\t\t}\n\t\treturn new Expression( d[0], [new Atom(d[1])].concat(as) );\n\t}\n\tthis.args = as.slice(0);\n}", "function interpolateValue(oldValue, newValue, i, steps) {\n return (((steps - i) / steps) * oldValue) + ((i / steps) * newValue);\n }", "function parseMessage(messageParts, expressions) {\n const replacements = {};\n let translationKey = messageParts[0];\n for (let i = 1; i < messageParts.length; i++) {\n const messagePart = messageParts[i];\n const expression = expressions[i - 1];\n // There is a problem with synthesizing template literals in TS.\n // It is not possible to provide raw values for the `messageParts` and TS is not able to compute\n // them since this requires access to the string in its original (non-existent) source code.\n // Therefore we fall back on the non-raw version if the raw string is empty.\n // This should be OK because synthesized nodes only come from the template compiler and they\n // will always contain placeholder name information.\n // So there will be no escaped placeholder marker character (`:`) directly after a substitution.\n if ((messageParts.raw[i] || messagePart).charAt(0) === PLACEHOLDER_NAME_MARKER) {\n const endOfPlaceholderName = messagePart.indexOf(PLACEHOLDER_NAME_MARKER, 1);\n const placeholderName = messagePart.substring(1, endOfPlaceholderName);\n translationKey += `{$${placeholderName}}${messagePart.substring(endOfPlaceholderName + 1)}`;\n replacements[placeholderName] = expression;\n }\n else {\n const placeholderName = `ph_${i}`;\n translationKey += `{$${placeholderName}}${messagePart}`;\n replacements[placeholderName] = expression;\n }\n }\n return { translationKey, substitutions: replacements };\n}", "function getClassMapInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 1:\r\n return Identifiers$1.classMap;\r\n case 3:\r\n return Identifiers$1.classMapInterpolate1;\r\n case 5:\r\n return Identifiers$1.classMapInterpolate2;\r\n case 7:\r\n return Identifiers$1.classMapInterpolate3;\r\n case 9:\r\n return Identifiers$1.classMapInterpolate4;\r\n case 11:\r\n return Identifiers$1.classMapInterpolate5;\r\n case 13:\r\n return Identifiers$1.classMapInterpolate6;\r\n case 15:\r\n return Identifiers$1.classMapInterpolate7;\r\n case 17:\r\n return Identifiers$1.classMapInterpolate8;\r\n default:\r\n return Identifiers$1.classMapInterpolateV;\r\n }\r\n }", "function createI18nMessageFactory(interpolationConfig) {\r\n var visitor = new _I18nVisitor(_expParser, interpolationConfig);\r\n return function (nodes, meaning, description, id, visitNodeFn) { return visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn); };\r\n }", "function bindNames(args, values, env) {\n var i, j, expr, value, rest;\n\n // if (args.length === 0 && values.length === 0) // empty lists match\n // return true;\n\n for (i = 0, j = 0; i < args.length && j < values.length; ++i, ++j) {\n expr = args[i];\n switch (expr.type) {\n case \"word\": // bind\n if (expr.value && Number.isNaN(expr.value) === false) {\n if (expr.value !== values[j])\n return false;\n } else if (expr.name !== \"_\") { // _ means placeholder -- binds to nothing\n if (Object.prototype.hasOwnProperty.call(env, expr.name) === false) {\n env[expr.name] = values[j];\n } else {\n throw error(`${expr.name} already bound!`);\n }\n }\n break;\n case \"apply\":\n if (expr.operator.type === \"word\") { // deconstruct\n value = values[j];\n\n switch (expr.operator.name) {\n case \"list\": case \"$\":\n if (Array.isArray(value)) {\n if (bindNames(expr.args, value, env) === false) {\n return false;\n }\n } else {\n return false;\n //throw new TypeError(`Can't deconstruct value '${value}' with '${expr.operator.name}' operator!`);\n }\n break;\n case \"code\":\n // todo\n throw new TypeError(\"code pattern matching is not implemented yet!\");\n break;\n case \"'\":\n if (value !== evaluate(expr, env, 0)) {\n return false;\n }\n break;\n // case \"index\":\n // evaluate(expr.args[0], env, 0)[expr.args[1].name] = values[j];\n default:\n // todo: allow bindName for the argument as in >[#\\3 x] / >[x #\\3]\n if ([\"=\", \"<\", \"<=\", \">=\", \"<>\"].indexOf(expr.operator.name) !== -1) {\n if (env[expr.operator.name](value, evaluate(expr.args[0], env, i)) === false) {\n return false;\n }\n } else {\n // unknown deconstruct operator\n // this should probably be validated on function definition\n //throw new TypeError(`Unknown deconstruct operator '${expr.operator.name}'!`);\n return false;\n }\n }\n } else if (expr.operator.type === \"meta\") { // construct/rest\n j = restParameters(expr, env, values, j);\n } else {\n //throw new TypeError(\"Deconstruct operator should be a word as in 'list[a b c]'\");\n return false;\n }\n break;\n }\n }\n // empty list of rest parameters\n if (j === 0 && args[0].operator.type === \"meta\") {\n if (Object.prototype.hasOwnProperty.call(env, args[0].args[0].name) !== false) {\n throw error(`${args[0].args[0].name} already bound! Can't bind to rest...`)\n }\n env[args[0].args[0].name] = [];\n }\n if (j < values.length) {\n //throw new TypeError(\"Too many arguments while calling the function!\");\n //return fail(\"Too many arguments while calling the function!\");\n return false;\n }\n if (i < args.length) {\n //throw new TypeError(\"Too few arguments while calling the function!\");\n return false;\n }\n //return success();\n return true;\n}", "function interpolate(x, xl, xh, yl, yh) {\n var r = 0;\n if ( x >= xh ) {\n r = yh;\n } else if ( x <= xl ) {\n r = yl;\n } else if ( (xh - xl) < 1.0E-8 ) {\n r = yl+(yh-yl)*((x-xl)/1.0E-8);\n } else {\n r = yl+(yh-yl)*((x-xl)/(xh-xl));\n }\n return r;\n }", "_evalExpression(exp) {\n exp = exp.trim();\n\n // catch special cases, with referenced properties, e.g. resourceGroup().location\n let match = exp.match(/(\\w+)\\((.*)\\)\\.(.*)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n let funcProps = match[3].toLowerCase();\n if(funcName == 'resourcegroup' && funcProps == 'id') return 'resource-group-id'; \n if(funcName == 'resourcegroup' && funcProps == 'location') return 'resource-group-location'; \n if(funcName == 'subscription' && funcProps == 'subscriptionid') return 'subscription-id'; \n if(funcName == 'deployment' && funcProps == 'name') return 'deployment-name'; \n }\n \n // It looks like a function\n match = exp.match(/(\\w+)\\((.*)\\)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n //console.log(`~~~ function: *${funcName}* |${funcParams}|`);\n \n if(funcName == 'variables') {\n return this._funcVariables(this._evalExpression(funcParams));\n }\n if(funcName == 'uniquestring') {\n return this._funcUniquestring(this._evalExpression(funcParams));\n } \n if(funcName == 'concat') {\n return this._funcConcat(funcParams, '');\n }\n if(funcName == 'parameters') {\n // This is a small cop out, but we can't know the value of parameters until deployment!\n // So we just display curly braces around the paramter name. It looks OK\n return `{{${this._evalExpression(funcParams)}}}`;\n } \n if(funcName == 'replace') {\n return this._funcReplace(funcParams);\n } \n if(funcName == 'tolower') {\n return this._funcToLower(funcParams);\n } \n if(funcName == 'toupper') {\n return this._funcToUpper(funcParams);\n } \n if(funcName == 'substring') {\n return this._funcSubstring(funcParams);\n } \n if(funcName == 'resourceid') {\n // Treat resourceId as a concat operation with slashes \n let resid = this._funcConcat(funcParams, '/');\n // clean up needed\n resid = resid.replace(/^\\//, '');\n resid = resid.replace(/\\/\\//, '/');\n return resid;\n } \n }\n\n // It looks like a string literal\n match = exp.match(/^\\'(.*)\\'$/);\n if(match) {\n return match[1];\n }\n\n // It looks like a number literal\n match = exp.match(/^(\\d+)/);\n if(match) {\n return match[1].toString();\n }\n\n // Catch all, just return the expression, unparsed\n return exp;\n }", "function bindDynamicKeys(baseObj, values) {\n for (var i = 0; i < values.length; i += 2) {\n var key = values[i];\n if (typeof key === 'string' && key) {\n baseObj[values[i]] = values[i + 1];\n }\n else if (key !== '' && key !== null) {\n // null is a special value for explicitly removing a binding\n warn$2(\"Invalid value for dynamic directive argument (expected string or null): \".concat(key), this);\n }\n }\n return baseObj;\n }", "function tweenIteration() {\n var iteration = d3.interpolateNumber(+label.text(), maxIteration);\n return function (t) {\n displayIteration(iteration(t));\n };\n }", "function interpolateValues(values, getter, i, iteration) {\n if (i > 0) {\n var ta = iterations[i], tb = iterations[i - 1],\n t = (iteration - ta) / (tb - ta);\n return getter(values[i]) * (1 - t) + getter(values[i - 1]) * t;\n }\n return getter(values[i]);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to test if a keyboard event should be ignored
function shouldIgnore(event) { var mapIgnoredKeys = { 9:true, // Tab 16:true, 17:true, 18:true, // Shift, Alt, Ctrl 37:true, 38:true, 39:true, 40:true, // Arrows 91:true, 92:true, 93:true // Windows keys }; return mapIgnoredKeys[event.which]; }
[ "function disableKeyEvents() {\n lumx.isFocus = false;\n $document.off('keydown keypress', _onKeyPress);\n }", "keyDown(key) {\n if(this.keydowns[key]) {\n return true;\n }\n return false;\n }", "function isKeyPressedValid(e) {\n return (e.keyCode == 8 || e.keyCode == 46) || // backspace and delete keys\n (e.keyCode > 47 && e.keyCode < 58) || // number keys\n (e.keyCode == 32) || // spacebar & return key(s)\n (e.keyCode > 64 && e.keyCode < 91) || // letter keys\n (e.keyCode > 95 && e.keyCode < 112) || // numpad keys\n (e.keyCode > 180); // ;=,-./ etc...`\n }", "is_special_key(event){\n var allowable_is_special_key = [8,35,36,37,38,39,40,46, 9, 27, 13, 110, 116,115];\n var key = event.which || event.keyCode || event.charCode;\n var is_special = allowable_is_special_key.includes(key);\n //if ctrl+a or alt+a is down do not prevent\n var is_special_a = key === 65 && (event.ctrlKey === true || event.metaKey === true)\n //if meta+shift+a or alt+a is down do not prevent\n var is_special_r = key === 82 && (event.shiftKey === true || event.metaKey === true)\n if(is_special || is_special_a || is_special_r ){\n return true;\n }\n return false;\n }", "function isControlInput(event) {\n const keys = [\n UP, DOWN, LEFT, RIGHT, ENTER, ESC, TAB, SHIFT,\n CTRL, ALT, CAPSLOCK, CMDLEFT, CMDRIGHT,\n ];\n return (keys.indexOf(event.keyCode) > -1);\n }", "function IsKeyReleased(user_key_index) {\r\n return bind.IsKeyReleased(user_key_index);\r\n }", "isHeld(key) {\n if(!this.keyStates[key]) {\n return false;\n }\n return this.keyStates[key].isPressed;\n }", "function keyDown() {\r\n checkOverflow(this);\r\n}", "function MobileNoOnly(evt) //[0..9,+]\n{\n var charCode = (evt.which) ? evt.which : event.keyCode\n if ((charCode >= 48 && charCode <= 57) || (charCode == 43) || (charCode == 8))\n return true;\n else\n return false;\n}", "function unexpectedEventsNotDispatched()/* : Boolean*/\n {\n for (var i/*:uint*/ = 0; i < this._unexpectedEventTypes$_LKQ.length; ++i )\n {\n var unexpectedEvent/* : String*/ = this._unexpectedEventTypes$_LKQ[i];\n \tif ( this.unexpectedEventNotDispatched( unexpectedEvent ) == false )\n \t{\n \t\treturn false;\n \t}\n }\n\n return true;\n }", "async preventKeyEvent() {\n this.dummyTextArea.focus();\n await sleep(0);\n this.focus();\n }", "handleBoardKeyPress(e) {\n if (!this.state.helpModalOpen && !this.state.winModalOpen) {\n if (49 <= e.charCode && e.charCode <= 57) {\n this.handleNumberRowClick((e.charCode - 48).toString());\n // undo\n } else if (e.key === \"r\") {\n this.handleUndoClick();\n // redo\n } else if (e.key === \"t\") {\n this.handleRedoClick();\n // erase/delete\n } else if (e.key === \"y\") {\n this.handleEraseClick();\n // notes\n } else if (e.key === \"u\") {\n this.handleNotesClick();\n }\n }\n }", "function pressIt() {\n $('#typing').on('keydown', function(e) {\n if (e.which === 71){\n alert(\"you pressed G\");\n return;\n }\n })\n}", "function disableEnterButton()\n{\n\t$('html').on('keypress', function(e)\n\t{\n\t\tif (e.keyCode == 13)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t});\n}", "function disableKeyListenersForCell(cell) {\n cell.element[0].addEventListener(\n 'focus',\n () => {\n Jupyter.keyboard_manager.disable();\n },\n true\n );\n }", "function keyReleased() {\n if (keyCode === UP_ARROW) {\n hain = false;\n }\n}", "function IsKeyPressed(user_key_index, repeat = true) {\r\n return bind.IsKeyPressed(user_key_index, repeat);\r\n }", "function is_qwerty_active() {\n jQuery( \"div#qwerty-indicator\" ).empty();\n var focus = document.activeElement.tagName;\n if ( focus == 'TEXTAREA' || focus == 'INPUT' ) {\n jQuery( \"div#qwerty-indicator\" ).html('<img src=\"\" style=\"float:right\" /><h4><span class=\"glyphicon glyphicon glyphicon-volume-off\" aria-hidden=\"true\" style=\"color:#d9534f\"></span> Keyboard disabled</h4><p>Click here to enable QWERTY keyboard playing.</p>');\n return false;\n }\n else {\n jQuery( \"div#qwerty-indicator\" ).html('<img src=\"\" style=\"float:right\" /><h4><span class=\"glyphicon glyphicon glyphicon-volume-down\" aria-hidden=\"true\"></span> Keyboard enabled</h4><p>Press QWERTY keys to play current tuning.</p>');\n return true;\n }\n}", "function disablehotKey() {\n\tnew Richfaces.hotKey('form_recherche:mykey', 'return', '', {\n\t\ttiming : 'immediate'\n\t}, function(event) {\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: Pump_In_Sales Author: Louis Bodnar Purpose: Uses quadratic curves to draw a colorful figure with labeled sections. Each section's height is relative to its weighted value. Arguments: Pump_In_Sale(canvas_name, x_position, y_position, width, height, data); Data format: [[value, label, color], ... ] Example: Pump_In_Sale("myCanvas", 0, 0, 300, 100, [ [53, "Detroit Sales", "ff0000"], [13, "Chicago Sales", "9933dd"] ]);
function Pump_In_Sale(c, x, y, w, h, d) { var canvas = document.getElementById(c); var context = canvas.getContext("2d"); context.save() var blX = x; // bottom left var blY = y + h; var trX = x + w; // top right var trY = y; var midX = x + (w / 2); var midY = y + (h / 2); var controlX = x; var controlY = y; d.sort(); // puts the smallest data on top // find sum of all data for spacing var i = 0; var sum = 0; for (i = 0; i < d.length; i = i + 1) { sum = sum + parseInt(d[i][0]); } // draw first line of figure context.beginPath(); context.moveTo(blX, blY); midY = y; context.quadraticCurveTo(controlX, midY, midX, midY); context.quadraticCurveTo(trX, midY, trX, trY); context.quadraticCurveTo(trX, blY, midX, blY); context.quadraticCurveTo(controlX, blY, blX, blY); context.fillStyle = d[0][2]; context.fill(); // draw lines to finish figure for (i = 0; i < d.length; i = i + 1) { context.beginPath(); context.moveTo(blX, blY); var temp = ((d[i][0] / sum) * h) midY = midY + temp; context.quadraticCurveTo(controlX, midY, midX, midY); context.quadraticCurveTo(trX, midY, trX, trY); context.quadraticCurveTo(trX, blY, midX, blY); context.quadraticCurveTo(controlX, blY, blX, blY); if (i + 1 == d.length) { context.fillStyle = d[i][2]; } else { context.fillStyle = d[i + 1][2]; } context.fill(); // Draw text var text_size = 14; if (temp < text_size) { text_size = temp; } if (text_size < 8) { text_size = 8; } context.font = "bold " + text_size + "pt Calibri"; context.fillStyle = "#ffffff"; context.fillText(d[i][1], x + (w*11/24), midY - temp / 2 + text_size / 2); } context.restore(); }
[ "function Used_Vehicle_Sale(c, x, y, w, h, d) {\n var canvas = document.getElementById(c);\n var ctx = canvas.getContext(\"2d\");\n ctx.save();\n ctx.scale(w/150,h/130);\n x = x/(w/150);\n y = y/(h/130);\n\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"black\";\n ctx.lineWidth = 1;\n //outer rectangle\n ctx.roundRect(x+0, y, 150, 130, 5);\n ctx.stroke();\n //inner rectangle\n ctx.roundRect(x+5, y+5, 140, 120, 5).stroke();\n //fill the inner rectangle\n ctx.fill();\n ctx.beginPath();\n //color of the \"FOR SALE\" text\n ctx.font = \"bold 20pt Calibri\";\n ctx.fillStyle = \"#EEEE00\";\n ctx.fillText(\"FOR SALE\", x+10, y+30);\n\n ctx.beginPath();\n ctx.fillStyle = \"white\";\n //rectangle for date display\n ctx.fillRect(x+10, y+40, 130, 35);\n //rectangle for data display\n ctx.fillRect(x+10, y+80, 130, 35);\n\n ctx.fillStyle = \"black\";\n //date\n ctx.fillText(monthname[d[0].getMonth()] +\" \"+d[0].getFullYear().toString().substr(2, 3), x+35, y+70);\n //data\n ctx.fillText(addCommas(d[1]), x+60, y+110);\n ctx.restore();\n}", "function drawQuadratic () {\n\n\t\t\tfunction dataArrays (beta, maxweather, maxpayout, crop) {\n\t\t\t\t// for quadratic equation 0 = ax^2 + bx + c\n\t\t\t\tvar a = beta;\n\t\t\t\tvar b = -2 * maxweather * beta;\n\t\t\t\tvar c = (beta * maxweather * maxweather) + maxpayout;\n\t\t\t\tvar root_part = Math.sqrt((b*b) - 4*a*c);\n\t\t\t\tvar denominator = 2*a;\n\n\t\t\t\t//calculate roots of payout parabola\n\t\t\t\tvar root1 = (-b + root_part)/denominator;\n\t\t\t\tvar root2 = (-b - root_part)/denominator;\n\n\n\t\t\t\t// Find points (x,y) with x = weather, y= payout which delineate \"normal\" range -- additional point beyond vertex and roots\n\t\t\t\tvar upper = [];\n\t\t\t\tvar lower = [];\n\t\t\t\tvar upperNormalTheshold = newPoint(upper, \"+\");\n\t\t\t\tvar lowerNormalThreshold = newPoint(lower, \"-\");\n\n\t\t\t\tfunction newPoint (threshold, sign) {\n\n\t\t\t\t\tif (sign === \"+\") {\n\t\t\t\t\t\tthreshold[0] = maxweather + .33*Math.sqrt(maxpayout/(-beta));\n\t\t\t\t\t}\n\n\t\t\t\t\telse {\n\t\t\t\t\t\tthreshold[0] = maxweather - .33*Math.sqrt(maxpayout/(-beta));\n\t\t\t\t\t\tthreshold[2] = crop;\n\t\t\t\t\t}\n\n\t\t\t\t\tthreshold[1] = Ycoordinate(threshold[0]);\n\t\t\t\t\treturn threshold;\n\t\t\t\t};\n\n\n\t\t\t\tfunction Ycoordinate (bound) {\n\t\t\t\t\tvar boundPayout = beta * Math.pow((bound - maxweather), 2) + maxpayout;\n\t\t\t\t\treturn boundPayout;\n\t\t\t\t};\n\n\n\t\t\t\t//output array of (x,y) points for use in jqPlot chart: [root1, lower normal-weather bound, vertex, upper normal-weather bound, root2]\n\t\t\t\tparabolaArray = [[root1, 0, null], lower, [maxweather, maxpayout, null], upper, [root2, 0, null]];\n\n\t\t\t\treturn parabolaArray;\n\t\t\t}; //end of dataArrays\n\n\n\t\t\t// Call dataArrays function and create parabolaArrays for A and B\n\t\t\tvar plotA = dataArrays(game.continuous.betaA, game.continuous.maxAweather, game.continuous.maxApayout, \"A\");\n\t\t\tvar plotB = dataArrays(game.continuous.betaB, game.continuous.maxBweather, game.continuous.maxBpayout, \"B\");\n\n\n\t\t\t// Set upper bounds on graph\n\t\t\tvar upperBoundX = 1000; //default value for upper bound of graph x-axis\n\t\t\tvar upperBoundY = 250; //default value for upper bound of graph y-axis\n\n\t\t\tfunction findUpperBoundX () {\n\t\t\t//modifies upper bound on x-axis based on largest parabola root (point at which crop value is (X,0) with largest possible value of X)\n\t\t\t\tvar root1A = plotA[0][0];\n\t\t\t\tvar root2A = plotA[4][0];\n\t\t\t\tvar root1B = plotB[0][0];\n\t\t\t\tvar root2B = plotB[4][0];\n\n\t\t\t\tvar rootArray = [root1A, root2A, root1B, root2B];\n\t\t\t\tvar maxRoot = Math.max.apply(Math, rootArray);\n\t\t\t\tvar minRoot = Math.min.apply(Math, rootArray);\n\n\t\t\t\tupperBoundX = Math.ceil(maxRoot/100)*100;\n\n\t\t\t\tgame.continuous.gameRoots.topRoot = maxRoot;\n\t\t\t\tgame.continuous.gameRoots.bottomRoot = minRoot;\n\n\t\t\t\treturn upperBoundX;\n\t\t\t};\n\n\t\t\tfindUpperBoundX();\n\n\t\t\tfunction findUpperBoundY () {\n\t\t\t\tvar vertexA = plotA[2][1];\n\t\t\t\tvar vertexB = plotB[2][1];\n\n\t\t\t\tif (vertexA > vertexB) {\n\t\t\t\t\tupperBoundY = vertexA;\n\t\t\t\t}\n\n\t\t\t\telse {\n\t\t\t\t\tupperBoundY = vertexB;\n\t\t\t\t}\n\n\t\t\t\treturn upperBoundY;\n\t\t\t};\n\n\t\t\tfindUpperBoundY();\n\n\t\t\t// Set values for tick marks\n\t\t\tvar maxX = [upperBoundX+100];\n\t\t\tvar maxY = [upperBoundY+50];\n\t\t\tvar ticksY = [[0, \"\"], [game.continuous.maxApayout, game.continuous.maxApayout], [game.continuous.maxBpayout, game.continuous.maxBpayout], [upperBoundY, \"\"], [maxY, \"\"]];\n\t\t\tvar ticksWeatherX = [[]]; // populated below\n\t\t\tvar ticksWeatherY = [];\n\n\n\t\t\t// Create graphable data array for historicWeather using freqency of values\n\t\t\tfunction historicWeatherHistogram () {\n\n\t\t\t\tvar range = Math.max.apply(Math, game.continuous.historicWeather) - 0;\n\t\t\t\tvar intervalNumber = 2*Math.ceil(Math.sqrt(game.continuous.historicWeather.length)); // total intervals is 8 and the interval numbers are 0,1,2,3,4,5,6,7 in the case of 50 turns\n\t\t\t\tvar intervalWidth = range/intervalNumber;\n\n\t\t\t\t//console.log(\"range: \" + range + \" number of intervals: \" + intervalNumber + \" interval width: \" + intervalWidth);\n\n\t\t\t\tfunction countOccurrence(newinterval) { //this functions runs for each interval\n\n\t\t\t\t\tvar intervalBottom = newinterval*intervalWidth;\n\t\t\t\t\tvar intervalTop = ((newinterval+1)*intervalWidth);\n\n\t\t\t\t\t//console.log(intervalBottom + \" to \" + intervalTop);\n\n\t\t\t\t\tvar count = 0;\n\t\t\t\t\tvar scaleCount = 0;\n\n\t\t\t\t\tfunction originalCount () {\n\t\t\t\t\t\tfor (var i =0; i < game.continuous.historicWeather.length; i++) {\n\n\t\t\t\t\t\t\tif (game.continuous.historicWeather[i] >= intervalBottom && game.continuous.historicWeather[i] < intervalTop) {\n\t\t\t\t\t\t\t\tcount += 1;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\telse if (newinterval === (intervalNumber-1) && game.continuous.historicWeather[i] >= intervalBottom) {\n\t\t\t\t\t\t\t\tcount +=1;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tcount = count;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn count;\n\t\t\t\t\t};\n\n\t\t\t\t\toriginalCount();\n\n\t\t\t\t\tfunction scaleToYaxis () {\n\t\t\t\t\t\t// Takes the average of maxA and maxB payout, multiples count by a percentage of the average,\n\t\t\t\t\t\t// to scale \"count\" up to the y-axis units of payout points.\n\t\t\t\t\t\tif (game.continuous.maxBpayout > game.continuous.maxApayout) {\n\t\t\t\t\t\t\tscaleCount = count*0.10*(game.continuous.maxApayout);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tscaleCount = count*0.10*(game.continuous.maxBpayout);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcount = scaleCount;\n\t\t\t\t\t\t//console.log(\"scaleCount is \" + scaleCount);\n\t\t\t\t\t};\n\n\t\t\t\t\tscaleToYaxis();\n\n\t\t\t\t\treturn [intervalBottom, count, null];\n\n\t\t\t\t}; // end countOccurrence();\n\n\t\t\t\t//creates empty array to fill with arrays ([interval number, count, null])\n\t\t\t\tvar frequency = [];\n\n\t\t\t\t//populates each item j in frequency array using value of countOccurrence()\n\t\t\t\t\t// (countOccurence called j times, for each item in frequency array)\n\t\t\t\tfor (var j = 0; j < intervalNumber; j++) {\n\t\t\t\t\tfrequency[j] = countOccurrence(j);\n\t\t\t\t}\n\n\t\t\t\tfunction ticksWeather () {\n\n\t\t\t\t\tfor (var j = 0; j <= intervalNumber; j++) {\n\n\t\t\t\t\t\tticksWeatherX[j] = [parseInt(j*(maxX/intervalNumber))];\n\n\t\t\t\t\t\tif (j == 0 || j==intervalNumber*.25 || j==intervalNumber*.5 || j== intervalNumber*.75 || j == intervalNumber) {\n\t\t\t\t\t\t\tticksWeatherX[j][1] = parseInt(j*(maxX/intervalNumber));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tticksWeatherX[j][1] = \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn ticksWeatherX;\n\t\t\t\t};\n\n\t\t\t\tticksWeather();\n\n\t\t\t\treturn frequency;\n\t\t\t}; //end historicWeatherHistogram\n\n\n\t\t\tgame.histogram = historicWeatherHistogram();\n\t\t\t//console.log(\"Histogram data ([intervalBottom, count, null]): \" + game.histogram);\n\n\t\t\t// Find largest number of occurences: sets game.meanHistoricWeather equal to most frequent weather interval\n\n\t\t\tfunction findMax () {\n\t\t\t\tvar countArray = [];\n\t\t\t\tfor (var i = 0; i < game.histogram.length; i++) {\n\t\t\t\t\tcountArray[i] = game.histogram[i][1];\n\t\t\t\t}\n\n\t\t\t\tvar mostFrequent = Math.max.apply(Math, countArray);\n\n\t\t\t\tfor (var j = 0; j<game.histogram.length; j++) {\n\t\t\t\t\tif (mostFrequent == game.histogram[j][1]) {\n\t\t\t\t\t\tgame.meanHistoricWeather = game.histogram[j][0];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn game.meanHistoricWeather;\n\t\t\t};\n\n\t\t\tfindMax();\n\n\t\tchartObjects = {\n\t\t\tpayoutObj: {\n\t\t\t\tseriesArray: [],\n\t\t\t\tcanvasOverlayLine: {verticalLine:{\n\t\t\t\t\t\tname: 'resultsLine',\n\t x: undefined, // this positions the line on the x-axis\n\t lineWidth: 4,\n\t color: 'rgb(255, 204, 51)', //yellow\n\t shadow: false\n\t\t\t\t}},\n\t\t\t\tcolor: [\"#000\",\"#820000\", \"#3811c9\"]\n\t\t\t},\n\t\t\thistoryObj: {\n\t\t\t\tseriesArray: [],\n\t\t\t\tcanvasOverlayLine: {verticalLine:{\n\t\t\t\t\t\tname: 'avgHistoricWeather',\n\t\t\t \tx: game.continuous.climateArray[0].mean,\n\t\t\t \tlineWidth: 4,\n\t\t\t \tcolor: '#3811c9', //blue\n\t\t\t \tshadow: false\n\t\t\t\t}},\n\t\t\t\tcolor: [\"rgba(152, 152, 152, 1)\", \"#820000\", \"#3811c9\"]\n\t\t\t},\n\t\t\tgivensObj: {\n\t\t\t\tseriesArray: [],\n\t\t\t\tcanvasOverlayLine: {verticalLine:{\n\t\t\t\t\t\tname: 'resultsLine',\n\t x: undefined, // this positions the line on the x-axis\n\t lineWidth: 4,\n\t color: 'rgb(255, 204, 51)', //yellow\n\t shadow: false\n\t\t\t\t}},\n\t\t\t\tcolor: [\"#000\", \"#820000\", \"#3811c9\"]\n\t\t\t}\n\t\t};\n\n\t\t// Create options object for jqPlot graph using optionsObj and setOptions()\n\t\t\tfunction setOptions (seriesName, showData, showLabel) {\n\n\t\t\t\tif (seriesName === \"payoutObj\" || seriesName === \"givensObj\") {\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][0] = {};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][1] =\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t \t // CropA\n\t\t\t\t\t\t \t label: \"Crop A\",\n\t\t\t\t\t\t lineWidth: 2,\n\t\t\t\t\t\t showMarker: false,\n\t\t\t\t\t\t renderer:$.jqplot.LineRenderer,\n\t\t\t\t\t\t xaxis:'xaxis',\n\t\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t\t show: true\n\t\t\t\t\t\t };\n\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][2] = {\n\t\t\t\t\t\t // CropB\n\t\t\t\t\t\t label: \"Crop B\",\n\t\t\t\t\t\t lineWidth: 2,\n\t\t\t\t\t\t showMarker: false,\n\t\t\t\t\t\t renderer:$.jqplot.LineRenderer,\n\t\t\t\t\t\t xaxis:'xaxis',\n\t\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t\t show: true\n\t\t\t\t\t\t };\n\t\t\t\t}\n\n\t\t\t\telse if (seriesName === \"historyObj\") {\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][0] = {\n\t\t\t\t\t\t\t\t// Weather\n\t\t\t\t\t \tlabel: \"Weather\",\n\t\t\t\t\t \tshowMarker: false,\n\t\t\t\t\t \trenderer:$.jqplot.BarRenderer,\n\t\t\t\t\t \trendererOptions: {\n\t\t\t\t\t \t\tbarWidth: 10,\n\t\t\t\t\t \t\tbarPadding: 0,\n\t \t\t\tbarMargin: 0,\n\t \t\t\tbarWidth: 10,\n\t\t\t\t\t \tfillToZero: true,\n\t\t\t\t\t \tshadowAlpha: 0\n\t\t\t\t\t \t},\n\t\t\t\t\t \txaxis:'xaxis',\n\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t \tshow: true\n\t\t\t\t\t};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][1] = {};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][2] = {};\n\t\t\t\t}\n\n\t\t\t\tgame.continuous.optionsObj[seriesName] = {\n\t\t\t\t\t series:\n\t\t\t\t\t chartObjects[seriesName][\"seriesArray\"]\n\t\t\t\t\t ,\n\n\t\t\t\t\t seriesColors:\n\t\t\t\t\t \t\tchartObjects[seriesName][\"color\"]\n\t\t\t\t\t ,\n\n\n\t\t\t\t\t grid: {\n\t\t\t \t\tdrawGridlines: true,\n\t\t\t \t\tshadow: false,\n\t\t\t \t\tborderWidth: 1,\n\t\t\t \t\tdrawBorder: true,\n\t\t\t \t },\n\n\t\t\t \t // The \"seriesDefaults\" option is an options object that will\n\t\t\t \t //be applied to all series in the chart.\n\t\t\t\t\t seriesDefaults: {\n\t\t\t\t\t shadow: false,\n\t\t\t\t\t rendererOptions: {\n\t\t\t\t\t smooth: true,\n\t\t\t\t\t highlightMouseOver: false,\n\t\t\t\t\t highlightMouseDown: false,\n\t\t\t \t\t\thighlightColor: null,\n\t\t\t \t\t\t},\n\t\t\t\t\t\t\t markerOptions: {\n\t\t\t \t\tshadow: false,\n\t\t\t\t\t },\n\n\n\t\t\t\t\t //pointLabels uses the final value in parabolaArray[i] as its data\n\t\t\t\t\t pointLabels: {\n\t\t\t\t\t \tshow: showData,\n\t\t\t\t\t \tlocation:'nw',\n\t\t\t\t\t \typadding: 3,\n\t\t\t\t\t \txpadding: 3,\n\t\t\t\t\t \tformatString: \"%#.0f\"\n\t\t\t\t\t }\n\t\t\t\t\t },\n\n\t\t\t\t\t axesDefaults: {\n\t \t\t\t\tlabelRenderer: $.jqplot.CanvasAxisLabelRenderer\n\t \t\t\t\t },\n\t\t\t\t\t axes: {\n\n\t\t\t \t\txaxis:{\n\t\t\t \t\t\tticks: ticksWeatherX,\n\t\t\t \t\t\tborderWidth: 1.5,\n\t\t\t \t\t\trendererOptions:{\n\t\t\t \ttickRenderer:$.jqplot.AxisTickRenderer\n\t\t\t },\n\t\t\t \ttickOptions:{\n\t\t\t mark: \"cross\",\n\t\t\t //formatString: \"%#.0f\",\n\t\t\t showMark: true,\n\t\t\t showGridline: true\n\t\t\t },\n\n\t\t\t \t\t\tlabel:'Rainfall (inches)',\n\t\t\t \t\t\tlabelRenderer: $.jqplot.AxisLabelRenderer,\n\t\t\t \t\t\tlabelOptions: {\n\t\t\t \t\t\tfontFamily: 'Georgia, serif',\n\t\t\t \t\t\tfontSize: '12pt'\n\t\t\t \t\t\t}\n\t\t\t \t\t},\n\n\t\t\t \t\tyaxis:{\n\t\t\t \t\t\tticks: ticksY,\n\t\t\t \t\t\trendererOptions:{\n\t\t\t \ttickRenderer:$.jqplot.CanvasAxisTickRenderer\n\t\t\t },\n\n\t\t\t \ttickOptions:{\n\t\t\t mark: \"cross\",\n\t\t\t showLabel: showData,\n\t\t\t //formatString: \"%#.0f\",\n\t\t\t showMark: true,\n\t\t\t showGridline: true\n\t\t\t },\n\n\t\t\t \t\t\tlabel:'Points',\n\t\t\t \t\t\tlabelRenderer: $.jqplot.CanvasAxisLabelRenderer,\n\t\t\t\t\t\t\t\t\tlabelOptions: {\n\t\t\t\t \t\t\tfontFamily: 'Georgia, serif',\n\t\t\t\t \t\t\tfontSize: '12pt',\n\t\t\t\t \t\t\tshow: showLabel\n\t\t\t \t\t\t\t}\n\t\t\t \t\t\t}\n\t\t\t \t\t }, // end of axes\n\n\t\t\t\t\t\tcanvasOverlay: {\n\t\t\t \t\tshow: true,\n\t\t\t\t objects:\n\n\t\t\t\t \t[chartObjects[seriesName][\"canvasOverlayLine\"]]\n\n\t\t\t\t\t\t} // end of canvasOverlay\n\n\t\t\t\t\t}; // end optionsObj object\n\n\t\t\t\treturn game.continuous.optionsObj[seriesName];\n\t\t\t}; //end function setOptions()\n\n\t// writes crop payout dataset to game object\n\t\t\tgame.continuous.payoutData = [[null], plotA, plotB];\n\n\n\t//CHART 1: draw graph in #crop_payouts_chart of A/B payouts (intro dialog)\n\t\t\tsetOptions(\"payoutObj\", true, true);\n\t\t\tvar payoutChart = $.jqplot(\"crop_payouts_chart\", game.continuous.payoutData, game.continuous.optionsObj.payoutObj);\n\n\t// CHART 2: draw graph in #history_histogram (for intro dialog) using optionsObj above\n\n\t\t\tsetOptions(\"historyObj\", false, false);\n\t\t\tvar historyChart = $.jqplot(\"history_histogram\", [game.histogram, [null], [null]], game.continuous.optionsObj.historyObj);\n\n\n\t//CHART 3: draw graph in sidebar #chartdiv using optionsObj above\n\t\t\tsetOptions(\"givensObj\", false, true);\n\t\t\tgame.continuous.givensChart = $.jqplot(\"chartdiv\", game.continuous.payoutData, game.continuous.optionsObj.givensObj);\n\n\t\t}", "function DrawProspectCount(c,x,y,d) {\n\tvar canvas = document.getElementById(c);\n\tvar context = canvas.getContext(\"2d\");\n\tvar lineWidth = 10;\n\tcontext.save();\n\t//draw tables\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#000000\";\n\tcontext.beginPath();\n\tcontext.rect(x+20, y , 130, -60);\n\tcontext.fill();\n\n\tcontext.beginPath();\n\tcontext.moveTo(x, y-65);\n\tcontext.lineTo(x+170, y-65);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\t//\n\tcontext.beginPath();\n\tcontext.arc(x+130, y-80, 25, Math.PI, 2* Math.PI, false);\n\tcontext.rect(x+105, y-70 , 50, -10);\n\tcontext.fillStyle = \"#000000\";\n\tcontext.fill();\n\t\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x+100, y-113);\n\tcontext.lineTo(x+160, y-113);\n\tcontext.lineTo(x+150, y-140);\n\tcontext.lineTo(x+110, y-140);\n\tcontext.lineTo(x+100, y-113);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"square\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\tcontext.fillStyle = \"#000000\";\n\tcontext.fill();\n\t\n\t\n\t//draw sit man\n\tcontext.beginPath();\n\tcontext.arc(x+50, y-120, 20, 0, 2 * Math.PI, false);\n\tcontext.fillStyle = \"#000000\";\n\tcontext.fill();\n\tcontext.beginPath();\n\t\n\tcontext.moveTo(x+50, y - 120);\n\tcontext.lineTo(x+40, y - 70);\n\tcontext.moveTo(x+48, y - 90);\n\tcontext.quadraticCurveTo(x +90, y -45, x+50, y-110);\n\tcontext.moveTo(x+48, y - 90);\n\tcontext.quadraticCurveTo(x +30, y -85, x+10, y-110);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\t//draw stand man\n\tcontext.beginPath();\n\tcontext.arc(x-45, y-140, 20, 0, 2 * Math.PI, false);\n\tcontext.fillStyle = \"#000000\";\n\tcontext.fill();\n\tcontext.beginPath();\n\t\n\tcontext.moveTo(x-45, y - 150);\n\tcontext.lineTo(x-45, y - 5);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x-45, y - 70);\n\tcontext.quadraticCurveTo(x -60, y -25, x-70, y-10);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x-45, y - 110);\n\tcontext.quadraticCurveTo(x -30, y -45, x-10, y-110);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x-45, y - 110);\n\tcontext.lineTo(x-70, y - 70);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\t\n\t//write text\n\tcontext.font = \"32pt Calibri\";\n\tcontext.fillStyle = \"#ffffff\";\n\tcontext.fillText(d, x+40, y-20);\n\t\n\tcontext.font = \"32pt Calibri\";\n\tcontext.fillStyle = \"#FFFFFF\";\n\tcontext.fillText(\"Prospect Count\", x-100, y-230);\n\n\tcontext.restore();\n}", "function DrawEffectiveness(c,x,y,date,d,b)\n{\n\tvar canvas = document.getElementById(c);\n\tvar context = canvas.getContext(\"2d\");\n\tcontext.save();\n\t\t\t\t\n\tvar lineWidth = 7;\n\tvar maxHeight = 200;\n\tvar bHeight = 0;\n\tvar dHeight = 0;\n\t\n\tbHeight = maxHeight * (b-1);\n\tdHeight = maxHeight * (d-1);\n\t//write text\n\tcontext.beginPath();\n\tcontext.fillStyle = \"#ffffff\";\n\tcontext.font = \"24pt Calibri\";\n\tcontext.fillText(\"Effectiveness\", x, y);\n\tcontext.fillText(\"100%\" , x+640, y+15);\n\tcontext.fillText(monthname[date.getMonth()] , x, y+30);\n\t\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x+60, y +20);\n\tcontext.lineTo(x+700, y +20);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#ffffff\";\n\tcontext.stroke();\n\t\n\t\n\tcontext.beginPath();\n\tcontext.arc(x+310, y+17-bHeight, 75, Math.PI, 2* Math.PI, false);\n\tcontext.rect(x+235, y+17 , 150, -bHeight);\n\tcontext.fillStyle = \"#2554C7\";\n\tcontext.fill();\n\n\tcontext.beginPath();\n\tcontext.arc(x+510, y+23-dHeight, 75, 0, Math.PI, false);\n\tcontext.rect(x+435, y+23 , 150, -dHeight);\n\tcontext.fillStyle = \"#38ACEC\";\n\tcontext.fill();\n\n\tcontext.beginPath();\n\tcontext.fillStyle = \"#000000\";\n\tcontext.font = \"24pt Calibri\";\n\tcontext.fillText(\"Brand\", x+270, y-30);\n\tcontext.fillText(Math.round(b*100)+\"%\", x+280, y);\n\tcontext.fillText(Math.round(d*100)+\"%\", x+490, y+60);\n\tcontext.fillText(\"Dealer\", x+470, y+90);\n\t \n\tcontext.restore();\n}", "renderPivotTable(context, canvas, data) {\n\n let bw = this.bw;\n let bh = this.bh;\n const p = this.p;\n\n //to clear the Canvas the befor pivoting the table\n context.clearRect(10.5, 10, canvas.width, canvas.height)\n\n //Drawing rows on the table...\n for (let x = 0; x <= bw; x += 200) {\n context.moveTo(0.5 + x + p, p);\n context.lineTo(0.5 + x + p, bh + p);\n }\n\n //Drawing column on the table...\n for (let y = 0; y <= bh; y += 40) {\n context.moveTo(p, 0.5 + y + p);\n context.lineTo(bw + p, 0.5 + y + p);\n }\n\n context.strokeStyle = \"black\";\n context.stroke();\n\n //logic for rowSpan\n for (let z1 = 0, a = 0, b = 0, c = 0, d = 0; z1 < ((this.keys.length - 1) - (this.passedValues.length - 2)); z1++) {\n\n if (z1 == 0) {\n a = 11;\n b = 50;\n c = 199;\n d = 3;\n }\n context.clearRect(a, b, c, d)\n a += 200;\n }\n\n //logic for columnSpan\n for (let x1 = 0, a = 0, b = 0, c = 0, d = 0; x1 < this.passedValues.length - 2; x1++) {\n if (x1 == 0) {\n a = (((this.keys.length - 1) - (this.passedValues.length - 2)) * 200) + 200 + 10.5, b = 10.5, c = 3, d = 39.5;\n }\n for (let y1 = 0; y1 < this.list.length; y1++) {\n if (y1 == this.list.length - 1) {\n a += 200;\n break;\n }\n context.clearRect(a, b, c, d)\n a += 200;\n }\n }\n\n //logic to remove the extra boxes...\n context.clearRect(10.5, bh + 10.5, canvas.width, canvas.height);\n context.clearRect(bw + 11, 9.5, canvas.width, canvas.height);\n\n\n //logic to create header...\n //Removing column to pivot element from header\n let headerKeys = this.keys; //Storing the Keys of the objects in headerKeys Variable\n\n //Logic to remove the choosen column to be pivoted \n for (let i1 = headerKeys.length - 1; i1--;) {\n if (headerKeys[i1] === this.passedValues[0]) headerKeys.splice(i1, 1);\n }\n\n\n for (var i1 = 1; i1 < this.passedValues.length - 1; i1++) {\n let index1 = headerKeys.indexOf(this.passedValues[i1]);\n headerKeys.splice(index1, 1);\n }\n\n for (var i1 = 1; i1 < this.passedValues.length - 1; i1++) {\n headerKeys.push(this.passedValues[i1]);\n }\n\n console.log(\"Header keys after removing Pivoting Column: \", headerKeys);\n\n //Logic to print the data into the table for the pivoting table...\n let pivotTableData = [];\n\n for (let h2 = 0; h2 < this.primaryList.length; h2++) {\n let tempDataArray = [];\n for (let h1 = 0; h1 < data.length; h1++) {\n if ((data[h1])[this.passedValues[this.passedValues.length - 1]] == this.primaryList[h2]) {\n tempDataArray.push(data[h1]);\n }\n }\n\n tempDataArray = tempDataArray.sort();\n\n // console.log(\"TEMP. ARRAY DATA: \",tempDataArray);\n \n let temparray = tempDataArray;\n\n for (let h3 = 0; h3 < temparray.length; h3++) {\n let keyarr = [];\n for (let h4 = 0; h4 < this.passedValues.length - 1; h4++) {\n console.log(temparray[h3][this.passedValues[h4]]);\n keyarr.push(temparray[h3][this.passedValues[h4]]);\n delete temparray[h3][this.passedValues[h4]];\n }\n\n console.log(\"keyarr: \",keyarr);\n\n for (let h5 = 1; h5 < keyarr.length; h5++) {\n for (let h4 = 1; h4 < this.passedValues.length - 1; h4++) {\n temparray[h3][this.passedValues[h4]] = keyarr[h4];\n }\n }\n }\n\n pivotTableData.push(temparray);\n\n }\n\n // console.log(\"temp aRRAY dATA: \",pivotTableData);\n\n //Logic to print the data to the Canvas...\n\n //To print the value of the Table Excluding Header...\n\n let DataArray = [];\n for (let p1 = 0; p1 < pivotTableData.length; p1++) {\n\n var tempObj = {};\n for (let p2 = 0; p2 < pivotTableData[p1].length; p2++) {\n\n let arr = Object.keys(pivotTableData[p1][p2]).map(function (key) { return pivotTableData[p1][p2][key]; });\n let arrkeys = Object.keys(pivotTableData[p1][p2]);\n\n for (let count = 0; count < arr.length;) {\n if (count < (headerKeys.length - (this.passedValues.length - 2))) {\n tempObj[headerKeys[count]] = (arr)[count];\n ++count;\n }\n else {\n\n if (count == headerKeys.length) {\n break;\n }\n if (typeof (tempObj[arrkeys[count]]) != 'object') {\n tempObj[arrkeys[count]] = [];\n }\n tempObj[arrkeys[count]].push((arr)[count]);\n ++count;\n }\n }\n\n }\n DataArray.push(tempObj);\n }\n\n //To print the data into the pivot table...\n\n for (let y = 120, max = 0, count = 0; y <= bh; y += 40) {\n\n for (let x = 0, keyCount = 0; x < bw; x += 200) {\n\n context.font = \"normal 16px tahoma\";\n context.fillStyle = 'black';\n\n if (keyCount < (headerKeys.length - (this.passedValues.length - 2))) {\n context.fillText((DataArray[count])[this.keys[keyCount]], 0.5 + x + 15, y);\n ++keyCount;\n }\n else {\n\n max = this.list.length;\n for (let pd = 0; pd < max; pd++) {\n if (((DataArray[count])[this.keys[keyCount]][pd]) == undefined || ((DataArray[count])[this.keys[keyCount]][pd]) == null || ((DataArray[count])[this.keys[keyCount]][pd]) == \"\") {\n context.fillText(\"\", 0.5 + x + 15, y);\n }\n else {\n context.fillText(((DataArray[count])[this.keys[keyCount]][pd]), 0.5 + x + 15, y);\n }\n x += 200\n }\n x -= 200;\n ++keyCount;\n }\n\n }\n ++count;\n if (count == DataArray.length) {\n break;\n }\n }\n\n //To Print the Header... \n for (let x = 0, keyCount = 0; x <= bw; x += 200) {\n context.font = \"bold 19px Verdana\";\n context.fillStyle = 'black';\n if (keyCount < (headerKeys.length - (this.passedValues.length - 2))) {\n context.fillText(headerKeys[keyCount], 0.5 + x + 70, 60);\n ++keyCount;\n }\n else {\n if (keyCount == headerKeys.length) {\n break;\n }\n else {\n if (this.list.length == 1) {\n\n // console.log(Math.ceil(list.length / 2));\n context.fillText(headerKeys[keyCount], 0.5 + ((Math.ceil(this.list.length / 2)) * 200 + (x - 160.5)) + 15, 10 + 25);\n ++keyCount\n x = (Math.ceil(this.list.length / 2)) * 200 + (x - 160.5);\n // console.log(keyCount);\n }\n else {\n\n // console.log(Math.ceil(list.length / 2));\n context.fillText(headerKeys[keyCount], 0.5 + ((Math.ceil(this.list.length / 2)) * 200 + (x - 160.5)) + 15, 10 + 25);\n ++keyCount\n x = (Math.ceil(this.list.length / 2)) * 200 + x;\n // console.log(keyCount);\n }\n }\n }\n }\n\n //to print the second line of header...\n for (let x = 0, keyCount = 0; x <= bw; x += 200) {\n context.font = \"bold 19px Verdana\";\n context.fillStyle = 'black';\n if (keyCount < (headerKeys.length - (this.passedValues.length - 2))) {\n\n ++keyCount;\n }\n else {\n if (keyCount == this.keys.length) {\n break;\n }\n else {\n var tempArr = this.list;\n for (var i2 = 0; i2 < tempArr.length; i2++) {\n context.fillText(tempArr[i2], 0.5 + x + 15, 10 + 25 + 40);\n x += 200;\n }\n x -= 200;\n ++keyCount;\n }\n }\n\n }\n\n }", "function Draw3PL(c,x,y,w,h,myArray){\n\tvar canvas = document.getElementById(c);\n\tvar cxt = canvas.getContext(\"2d\");\n\tcxt.save();\n\t//Adjust chart width and height\n\tw=w-20; h=h-50;\n\tvar max = 0; //Innitialise maximum bar height to zero\n\tvar len=0; //Innitialise no of bars to zero\n\tvar c1 = \"#7FFF24\";\n\tvar c2 = \"#ffffff\";\n\tsum = 0;\n\tfor(key in myArray)\n\t{\n\t\tif(myArray[key] > max) max = myArray[key];\n\t\tsum += myArray[key];\n\t\tlen++;\n\t}\n\tvar border = 4; //Changing the border mar distort the graph\n\tvar bar_h = (h-border)/len;\n\tvar gradient = cxt.createLinearGradient(w/2, 50, w/2, h);\n\tgradient.addColorStop(0, '#000');\n\tgradient.addColorStop(0.1, '#eee'); \n\tgradient.addColorStop(0.5, '#fff'); \n\tgradient.addColorStop(1, '#000'); \n\t\n\tmax = max - border;\n\ttxtArea = w*0.2;\n\tfull = w -(border*2)-txtArea;\n\tcxt.strokeStyle='#fff';\n\tcxt.save();\n\t\n\tcxt.shadowOffsetX = border/2;\n\tcxt.shadowOffsetY = border/2;\n\tcxt.shadowBlur = border/2;\n\tcxt.shadowColor = \"black\";\n\tcxt.fillStyle=c1;\n\tn=0;\n\tfor(key in myArray)\n\t{\n\t\tcxt.fillRect(border+txtArea+x,(border*2)+(bar_h*n)+y,(myArray[key]/max)*full,bar_h-border);\n\t\tn++;\n\t}\n\t\n\tcxt.shadowColor = \"#fff\";\n\tn=0;\n\tfor(key in myArray)\n\t{\n\t\tcxt.strokeRect(border+txtArea+x,(border*2)+(bar_h*n)+y,(myArray[key]/max)*full,bar_h-border);\n\t\tn++;\n\t}\n\t\n\tcxt.shadowOffsetX = border/-2;\n\tn=0;\n\tfor(key in myArray)\n\t{\n\t\tcxt.strokeRect(border+txtArea+x,(border*2)+(bar_h*n)+y,((myArray[key]/max)*full),bar_h-border);\n\t\tn++;\n\t}\n\tcxt.shadowOffsetY = border/-2;\n\tn=0;\n\tfor(key in myArray)\n\t{\n\t\tcxt.strokeRect(border+txtArea+x,(border*2)+(bar_h*n)+y,((myArray[key]/max)*full),bar_h-border);\n\t\tn++;\n\t}\n\tcxt.restore();\n\tcxt.save();\n\tcxt.font = 'bold 14px sans-serif';\n\tcxt.shadowOffsetX = 1;\n\tcxt.shadowOffsetY = 1;\n\tcxt.shadowBlur = 1;\n\tcxt.shadowColor = \"white\";\n\tn=0;\n\tfor(key in myArray)\n\t{\n\t\tcxt.fillStyle=c2;\n\t\tcxt.fillText(key, (border+10)+x-45, (border*2)+(bar_h*n)+(bar_h/1.8)+y,txtArea-15);\n\t\tcxt.fillText(myArray[key], (border+10+txtArea)+x, \n\t\t\t\t\t\t(border*2)+(bar_h*n)+(bar_h/1.8)+y,full);\n\t\tn++;\n\t}\n\tcxt.restore();\n\n\tcxt.fillStyle = c2;\n\tcxt.font = '28pt Calibri';\n\tcxt.fillText(\"New 3PL Leads\", (border*1.5)+x+40,y, w);\n\n}", "function addPaintAndSupplies(totalCost, callback) {\r\n\r\n let cost = prompt(\"Enter the cost for the paint and supplies :\");\r\n\r\n cost = parseFloat(cost);\r\n\r\n if (cost > 100)\r\n\r\n cost *= 1.1;\r\n\r\n\r\n\r\n // Get a handle for the paint paragraph\r\n\r\n let paintArea = document.querySelector(\".paint\");\r\n\r\n paintArea.innerHTML = `Paint $ ${cost.toFixed(2)}`;\r\n\r\n callback(totalCost + cost);\r\n\r\n return (totalCost + cost);\r\n\r\n}", "function itemCallback(data){\n subtotal(data.salePrice);\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows(chartData);\n\n // Set chart options\n var options = {'title':'Daily Summary Of Total Units By Methods Of Plucking',\n 'width':400,\n 'height':300};\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('pieChart_div'));\n chart.draw(data, options);\n }", "shop() {\n // this sets the current scene to \"shop\"\n this.current = \"shop\";\n \n // this draws the floor\n background(148, 82, 52);\n \n //this draws the shelves\n for (let i = 0; i < 4; i++) {\n this.vShelf(50 + this.pxl * 3 * i, 400);\n }\n \n for (let i = 0; i < 2; i++) {\n this.hShelf(25 + this.pxl * 4 * i, 0);\n }\n \n // this draws the welcome mat\n this.mat(2, height/2 - this.pxl);\n \n // this draws a counter\n stroke(191, 179, 157);\n strokeWeight(4);\n for (let i = 0; i < 4; i++) {\n fill(204, 191, 169);\n rect(400 + this.pxl * i, 125, this.pxl, this.pxl);\n }\n \n // this makes Janine\n janine.makeRight();\n }", "function profit(info) {\n //return console.log((info.inventory * info.sellPrice)-(info.inventory * info.costPrice)); // 54000 gewinn - 39204\n // shorter:\n return console.log(Math.round(info.inventory * (info.sellPrice-info.costPrice))); // needs to be rounded in this case\n}", "function display_pet_page() {\n str = '';\n for (i = 0; i < products.length; i++) {\n str += `\n <section class=\"pups\">\n <h2>${products[i].color}</h2>\n <p>$${products[i].price}</p>\n <label id=\"quantity${i}_label\"}\">Quantity</label>\n <input type=\"text\" placeholder=\"# of Puppies\" name=\"quantity${i}\" \n onkeyup=\"checkQuantityTextbox(this);\">\n <img src=\"./images/${products[i].image}\">\n </section>\n `;\n }\n return str;\n }", "function shopMenu() {\n fill(0, 200, 144);\n rect(0, 0, width, height);\n fill(255, 0, 0);\n rect(windowWidth - 3 * blockWidth, 0, 3 * blockWidth, 3 * blockHeight);\n fill(255);\n rect(blockWidth * 5, blockHeight * 5, windowWidth - (10* blockWidth), windowHeight - (10* blockHeight));\n rectMode(CORNERS);\n fill(0);\n textSize(20);\n text(\"press '1' to Buy a unit of basic infantry unit please and thank you, it will cost 10 gold and 10 resources\",blockWidth * 6, blockHeight * 6, blockWidth * 11, blockHeight * 11);\n if (turn>20){\n text(\"press '2' to Buy a unit of less basic infantry unit please and thank you, it will cost 20 gold and 20 resources\",blockWidth * 18, blockHeight * 6, blockWidth * 11, blockHeight * 11);\n }\n\n rectMode(CORNER);\n\n}", "function priceSummary(price, discount, quantity){\n\t\t$(\"#no_of_items\").text(quantity);\n\t\tvar savings = (discount/100.0)*(price)*(quantity)*1.0;\n\t\tvar total_price = (price*quantity)-savings;\n\t\tconsole.log(total_price);\n\t\t$(\"#offer_price\").text(total_price);\n\t\t$(\"#total_price\").text(total_price);\n\t\t$(\"#savings\").text(\"Your Total Savings on this order Rs. \"+savings);\n\t}", "function createChart(quantity) {\n\treturn new Highcharts.Chart({\n\t\tchart : {\n\t\t\trenderTo : 'container',\n\t\t\tdefaultSeriesType : 'bar',\n\t\t\tevents : {\n\t\t\t\tload : updateChart(quantity)\n\t\t\t}\n\t\t},\n\t\tcredits : {\n\t\t\tenabled : true,\n\t\t\thref : \"http://nest.lbl.gov/products/spade/\",\n\t\t\ttext : 'Spade Data Management'\n\t\t},\n\t\ttitle : {\n\t\t\ttext : 'Total Counts for SPADE'\n\t\t},\n\t\tsubtitle : {\n\t\t\ttext : 'Loading ...'\n\t\t},\n\t\txAxis : {\n\t\t\ttitle : {\n\t\t\t\ttext : 'Activity',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tminWidth : '140px'\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tyAxis : [ {\n\t\t\ttitle : {\n\t\t\t\ttext : 'counts',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}],\n\t\tseries : [ {\n\t\t\tname : 'suspended'\n\t\t}, {\n\t\t\tname : 'pending'\n\t\t}, {\n\t\t\tname : 'executing'\n\t\t}, {\n\t\t\tname : 'total'\n\t\t} ]\n\t});\n}", "function drawPool() {\n //Draws water\n strokeWeight(2);\n fill(0, 0, 100, 220);\n rect(0, height-100, width, 100);\n\n //Pool deck\n fill(242, 242, 210);\n rect(0, height-102, 50, 102);\n rect(width-50, height-102, 50, 102);\n stroke(242, 242, 210);\n rect(0, height-20, width, 20);\n stroke(0);\n\n //Lines of the pool deck\n line(0, height-102, 0, height);\n line(50, height-21, width-50, height-21);\n strokeWeight(1);\n stroke(0);\n fill(0, 255, 0);\n\n //Diving boards\n rect(0, 110 * 1.5 - 11, width/3 + 10 + 3, 10);\n rect(0, 110 * 4.2 - 11, width/3 + 10 + 3, 10);\n}", "function generateBaskets() {\n container = document.getElementById('container');\n var square_dummy = document.getElementById(\"Square1\");\n var rect_dummy = square_dummy.getBoundingClientRect();\n var i = 0;\n for (point in basket_points) {\n basket = document.createElement('div'); \n basket.setAttribute('id', 'Basket' + (i + 1));\n basket.setAttribute('style', 'position: absolute; border:3px solid black; text-align:center');\n basket.style.left = basket_points[point].x + 'px';\n basket.style.top = basket_points[point].y + 'px';\n basket.style.width = rect_dummy.width * 3 + 'px';\n basket.style.height = rect_dummy.height * 2 + 'px';\n container.appendChild(basket);\n i++;\n }\n}", "function AddPen(pen_data)\n {\n if (!pens[pen_data.name]) {return;}\n\n $('#nopen').remove();\n\n let selected = !current_pen;\n const $entry = $(`<div class='pen-entry${selected ? ' selected' : ''}'><span class='pen-dot'></span> ${pen_data.name}</div>`);\n $entry.data('pen', pen_data.name);\n $entry.attr('id', `pen_${pen_data.name.replace(' ', '_').replace(' ', '_')}`);\n\n pens[pen_data.name].d = pen_data.d; // Set durability to pen durability\n\n if (pen_data.name == 'Rainbow Pen')\n {\n $entry.find('span.pen-dot').css('background-color', 'none');\n $entry.find('span.pen-dot').addClass('rainbow');\n }\n else\n {\n $entry.find('span.pen-dot').css('background-color', pens[pen_data.name].c);\n }\n\n $('div.pen-container').append($entry);\n\n if (selected)\n {\n current_pen = pen_data.name;\n }\n }", "function DrawTable(c,x,y)\n{\n\tvar canvas = document.getElementById(c);\n\tvar context = canvas.getContext(\"2d\");\n\tcontext.save();\n\tvar lineWidth = 7;\n\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#000000\";\n\tcontext.beginPath();\n\tcontext.rect(x, y, 100, -60);\n\tcontext.fill();\n\n\tcontext.beginPath();\n\tcontext.moveTo(x-30, y - 60);\n\tcontext.lineTo(x+130, y - 60);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#000000\";\n\tcontext.stroke();\n\tcontext.restore();\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for removing an online user to the widget (when someone logs out, for example).
function muut_remove_online_user(user) { if(user.path.substr(0,1) == '@') { var username = user.path.substr(1); } var username_for_selector = tidy_muut_username(username); widget_online_users_wrapper.find('.m-user-online_' + username_for_selector).fadeOut(500, function() { $(this).remove() }); muut_update_online_users_widget(); }
[ "function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }", "admin_remove_user(user_id) {\n if (Roles.userIsInRole(Meteor.userId(), ['admin'])) {\n Meteor.users.remove(user_id);\n return \"OK\";\n }else { return -1; }\n }", "function delUserForMeeting( data, callback ) {\n\t\t\tvar url = '/meetingdelusers';\n\n\t\t\tnew IO({\n\t\t\t\turl: url,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: data,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t\tcallback(data);\n\t\t\t\t}\n\t\t\t});\n\n\t\t}", "logoutUser() {\n this.get('session').invalidate();\n }", "removeUserFromChannel(username, channel){\n var index = -1;\n var ch = this.getChannelByName(channel);\n if(ch != null){\n for (var i = 0; i < ch.users.length; i++) {\n var u = ch.users[i];\n if(u.name == username){\n index = i;\n }\n }\n }\n if(index > -1 && ch != null){\n ch.users.splice(index, 1);\n }\n io.emit('refreshchannels', [this.name, username]);\n dbDelete({groupname: this.name, channelname: channel, username: username}, \"channel_users\");\n }", "function removeVoter(user) {\n var pokerCard = document.getElementById(user);\n votingContainer.removeChild(pokerCard);\n var rosterEntry = document.getElementById(user);\n messageContainer.removeChild(rosterEntry);\n}", "function onLogOut(button) {\n let passwordVault = new PasswordVault();\n let buttonId = button.id;\n let removePrefix = buttonId.replace(/\\bbtn\\S/ig, \"\");\n\n // Return text and image to default\n // childNodes[0] - img\n // childNodes[1] - p\n document.getElementById(buttonId).childNodes[0].src = \"/img/Avatar-48x48.png\";\n document.getElementById(buttonId).childNodes[1].innerText = removePrefix;\n\n main.removePivotItems(removePrefix);\n\n try {\n // reg expression removed 'btn-' from id \n let credential = passwordVault.retrieve(\"OauthToken\", removePrefix);\n\n passwordVault.remove(credential);\n } catch (err) {\n // retrive has not found user\n }\n }", "removeSocketFormUser(userID, socketID) {\n // If have connections\n if (isUserOnline(userID)) {\n socketIDs[userID].sockets.map(function (socket, index) {\n // If the socket is correct socket want to remove\n if (socket === socketID) {\n socketIDs[userID].sockets.splice(index, 1);\n // If have no socket in list, remove this list\n if (socketIDs[userID].sockets.length <= 0) {\n delete socketIDs[userID];\n }\n return false;\n }\n });\n }\n }", "function passwordManagerRemove(aUsername) {\n return cal.auth.passwordManagerRemove(aUsername, aUsername, \"Google Calendar\");\n}", "static tamper() {\n del(\"user\").then(() => {\n localStorage.removeItem(\"role\");\n location.reload();\n });\n }", "function logout() {\n localStorage.setItem(\"isLoggedIn\", false)\n localStorage.removeItem('username')\n showPantryList()\n location.reload()\n}", "function removeCurrentUserIDFromLocalStorage() \r\n{\r\n localStorage.removeItem(\"currentUserID\");\r\n}", "function removeUser( domain, user, callback ) {\n\tgetBlockList( domain, function( list ) {\n\t\tvar index = list.indexOf( user );\n\n\t\tif( index != -1 ) {\n\t\t\tlist.splice( index, 1 );\n\t\t\tsetBlockList( domain, list, callback );\n\t\t}\n\t} );\n}", "function muut_update_online_users_widget() {\n if(show_anon_count) {\n update_anon_count();\n }\n if(show_num_logged_in) {\n update_num_logged_in();\n }\n }", "function removeScore() {\n localStorage.removeItem(\"user\");\n var removeBtn = document.querySelector(\"#removeBtn\");\n var userList = document.querySelector(\"#userList\");\n removeBtn.parentNode.removeChild(removeBtn);\n userList.parentNode.removeChild(userList);\n liMax = 0;\n}", "deleteUser( id ) {\n fluxUserManagementActions.deleteUser( id );\n }", "function removeUserSocialAccount(provider) {\n vm.success = vm.error = null;\n\n UsersService.removeSocialAccount(provider)\n .then(onRemoveSocialAccountSuccess)\n .catch(onRemoveSocialAccountError);\n }", "function logoutListener() {\n loggedIn = false;\n }", "function removeOAuthProvider (req, res) {\n let user = req.user,\n provider = req.param('provider');\n\n if (user && provider) {\n // Delete the additional provider\n if (user.additionalProvidersData[provider]) {\n delete user.additionalProvidersData[provider];\n\n // Then tell mongoose that we've updated the additionalProvidersData field\n user.markModified('additionalProvidersData');\n }\n\n user.save(function(err) {\n if (err) {\n res.status(400).send({\n message: err.message\n });\n return;\n } else {\n req.login(user, function(err) {\n if (err) {\n res.status(400).send(err);\n } else {\n res.json(user);\n }\n });\n }\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates or updates an animated gif from a set of photos linked to the the photo with id of rootid
function updateAnimation(rootid, path) { // enumerate all input foto's for animation db.query("select id, time, filename from photo where id=$1 or rootid=$1 order by time", [rootid]) .then(function(rows){ if (rows.length > 0) { // at least one photo found, create animation var outputfilename = Path.join(path, Path.parse(rows[0].filename).name + ".gif"); console.log(outputfilename); var graphicsMagic = gm(); // do NOT use rows.forEach() here! for (var i = 0; i < rows.length; i++) { var fullfilename = Path.join(path, rows[i].filename); // do not use async exists or stat here! if (fs.existsSync(fullfilename)) { graphicsMagic.in('-delay', 100).in(fullfilename); } else { return console.log("file " + fullfilename + " is missing") } } //console.log("FINAL ARGS: " + graphicsMagic.args()); graphicsMagic.write(outputfilename, function(err){ if (err) { console.log("hiero: " + err); } else { db.query("update photo set animationfilename=$1 where id=$2", [Path.parse(outputfilename).base, rootid]) .catch(function(err){ console.log(err); }) } }); } }) .catch(function(err){ console.log(err); }); }
[ "function updateGrid(){\n for(var id = 0; id < numPhotos; id++){\n var selector = $(\"#\"+id);\n selector.attr('src', photoData[i]['src']);\n }\n}", "function setPhotos(p){\n\t\t\tfunction setPic(sp){\n\t\t\t\tvar id=\"\";\n\t\t\t\tfor(i in sp){\n\t\t\t\t\tif(i>3)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\n\t\t\t\t\t\tid=\"#photoimg\"+i;\n\t\t\t\t\t\t$(id).css('background-image','url('+sp[i].images[i].source+')');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(p.photos==undefined||p.photos==null)\n\t\t\t{\n\t\t\t\t$('#photoimg0').html(\"<h4>NO PHOTOS</h4>\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsetPic(p.photos.data);\n\t\t\t}\n\n\n\t\t}", "function displayLocalFiles(response){\n var gifNameList= document.getElementById(\"localGifs\");\n var obj = JSON.parse(response);\n for(i=0; i<obj.gifList.length;i++){\n var gifName = obj.gifList[i];\n var thumbnail = gifName.replace('.gif','-thumbnail.png');\n gifNameList.innerHTML += \"<li style='margin-bottom: 30px' id='\"+gifName+\"'>\" + gifName\n +\"<br/><img id='\"+gifName+\"viewer' style='margin-top:5px' src='/content/\"+thumbnail+\"' />\"\n +\" <button class='button' id='\"+gifName+\"player' style='margin-top: 10px' type='button' onclick=\\\"previewGif('\"+gifName+\"')\\\">Preview</button>\"\t\n +\" <button class='button' id='\"+gifName+\"playerLed' style='' type='button' onclick=\\\"playGif('\"+gifName+\"')\\\">Play</button>\"\t\n +\" <button class='button' id='\"+gifName+\"playerLedStop' style='display:none' type='button' onclick=\\\"stopGif('\"+gifName+\"')\\\">Stop</button>\"\t\n +\" <div id='\"+gifName+\"playMessage' style='display:none'>Loading Gif For Playback</div>\"\n + \"</li>\" ;\n }\n}", "function renderGif() {\n var animal = $(this).attr(\"data-name\");\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=MJ68Z6txRmEzdp8Ow2QiKvYGwxbb9ip4&limit=10&rating=pg\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n $(\"#gif-div\").empty();\n $(\"#gifHeader\").html(`<h5>${animal} GIFs, click on the GIF to animate it!</h5>`);\n var results = response.data;\n for (var j = 0; j < results.length; j++) {\n var animalDiv = $(\"<div>\").addClass(\"animalDiv\");\n var p = $(\"<p>\")\n .addClass(\"card-text\")\n .html(`Rating: ${results[j].rating.toUpperCase()}`);\n var animalImage = $(\"<img>\")\n .addClass(\"gif img-thumbnail\")\n .attr(\"data-state\", \"still\")\n .attr(\"data-still\", results[j].images.fixed_width_still.url)\n .attr(\"data-animate\", results[j].images.fixed_width.url)\n .attr(\"src\", results[j].images.fixed_width_still.url);\n var addFavorite = $(\"<button>\")\n .addClass(\"btn btn-success favButton\")\n .attr(\"type\", \"button\")\n .text(\"Add to Favorites\");\n animalDiv.append(p, animalImage, addFavorite);\n $(\"#gif-div\").prepend(animalDiv);\n }\n });\n }", "function updateImages(lastChild, i) {\n const flipCardBack = lastChild.appendChild(document.createElement('div'));\n flipCardBack.setAttribute('class', 'flip-card-back');\n\n const title = flipCardBack.appendChild(document.createElement('h1'));\n const description = flipCardBack.appendChild(document.createElement('h4'));\n const image = flipCardBack.appendChild(document.createElement('img'));\n\n title.innerHTML = `${imagesArr[i].name}`;\n description.innerHTML = `${imagesArr[i].email}`;\n image.src = '/assets/delete.svg';\n image.setAttribute('id', `${i}`)\n}", "function displayGifInfo() {\n $(\"#gif-view\").empty();\n\n var gif = $(this).attr(\"data-name\");\n var apiKey = \"sZmTHcl0nlShQnrXB4IR0MhHnLYZWOIu\"\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + gif + \"&api_key=\" +apiKey+ \"&limit=10\";\n\n // Creates AJAX call for the specific gif button being clicked\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function(response) {\n \n var results = response.data;\n console.log(results);\n \n // Looping over every result item\n for (var i = 0; i < results.length; i++) {\n // Creates a img to hold the gif\n var gifDiv = $(\"<div>\").addClass(\"gifSection\").prependTo(\"#gif-view\");\n\n var gif = results[i].images.fixed_height.url;\n var gifStill = results[i].images.fixed_height_still.url;\n \n // $(gifDiv).html(\"<br></br>\");\n $(\"<img>\").attr({\n \"src\": gifStill,\n \"data-animate\": gif,\n \"data-still\": gifStill,\n \"data-state\": \"still\",\n }).addClass(\"gif\").prependTo(gifDiv);\n // var showTitle = $('<h6>').text(results[i].title);\n var showRating = $('<p>').text(results[i].rating)\n .addClass(\"font-weight-bold text-uppercase\");\n $(gifDiv).append(showRating);\n };\n \n });\n\n }", "function updateCurImg(){\n console.log('attempting to update current image');\n\n\n //get the peek peekInsert\n var peekInsert = document.getElementById('peekOutsideDiv');\n if(peekInsert.currentId) var result = results[peekInsert.currentId];\n\n if(peekInsert.currentId && !result.hasImg){\n console.log('requesting image for id: ' + peekInsert.currentId);\n //if the image has not been downloaded yet then send another request to the server\n requestSingleImg(peekInsert.currentId, function(){});\n }\n\n setTimeout(function(){updateCurImg()}, 1000);\n}", "function showImage(n, i, m){\n document.getElementById(\"img--\"+m).src = \"./album/\"+n+\"/\"+i+\".jpg\";\n}", "function list_entry_pics( entry_id ) {\r\n\t\t\r\n\t\t$( '#entrypics_wrap' ).hv_ajax_loader( 'toggle_loading', 'on' );\r\n\t\t$.ajax({\r\n\t\t\turl: 'list_entry_pics.php'\r\n\t\t\t,type: 'POST'\r\n\t\t\t,data: {\r\n\t\t\t\t'entry_id': entry_id\r\n\t\t\t}\r\n\t\t\t,dataType: 'json'\r\n\t\t\t,success: function(data){\r\n\t\t\t\tif ( data!=0 ) {\r\n\t\t\t\t\t$( 'div#entrypics_cont .entrypic' ).addClass( 'entrypic_to_remove' );\r\n\t\t\t\t\t$.each( data.posts, function( i, pic ) {\r\n\t\t\t\t\t\tvar id = parseInt( pic.id );\r\n\t\t\t\t\t\tif ( typeof $( 'div#'+id ) != 'undefined' && $( 'div#'+id ).length==0 ) {\r\n\t\t\t\t\t\t\tvar tumb_url = 'game_folders/'+game_id+'/'+entry_id+'/tumb_'+id+'.jpg';\r\n\t\t\t\t\t\t\tvar url = 'game_folders/'+game_id+'/'+entry_id+'/'+id+'.jpg';\r\n\t\t\t\t\t\t\t$( '<div/>' )\r\n\t\t\t\t\t\t\t\t.addClass( 'entrypic' )\r\n\t\t\t\t\t\t\t\t.attr( 'id', id )\r\n\t\t\t\t\t\t\t\t.prependTo( 'div#entrypics_cont' );\r\n\t\t\t\t\t\t\t$( '<img/>' )\r\n\t\t\t\t\t\t\t\t.addClass( 'entrypic_img' )\r\n\t\t\t\t\t\t\t\t.attr( 'src', tumb_url )\r\n\t\t\t\t\t\t\t\t.prependTo( 'div#'+id )\r\n\t\t\t\t\t\t\t\t.click( function(){\r\n\t\t\t\t\t\t\t\t\twindow.open( url );\r\n\t\t\t\t\t\t\t\t} );\r\n\t\t\t\t\t\t\tif ( act_user_is_gm ) {\r\n\t\t\t\t\t\t\t\t$( '<div/>' )\r\n\t\t\t\t\t\t\t\t\t.addClass( 'del_entrypic' )\r\n\t\t\t\t\t\t\t\t\t.prependTo( 'div#'+id )\r\n\t\t\t\t\t\t\t\t\t.click( function(){\r\n\t\t\t\t\t\t\t\t\t\tdel_entrypic( entry_id, id );\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\t$( 'div#'+id ).removeClass( 'entrypic_to_remove' );\r\n\t\t\t\t\t});\r\n\t\t\t\t\t$( 'div#entrypics_cont .entrypic_to_remove' ).remove();\r\n\t\t\t\t}\r\n\t\t\t\tvar entry_width = 0;\r\n\t\t\t\t$( 'div#entrypics_cont .entrypic' ).each( function(){\r\n\t\t\t\t\tentry_width += $( this ).outerWidth()+10;\r\n\t\t\t\t});\r\n\t\t\t\t$( 'div#entrypics_cont' ).width( entry_width );\r\n\t\t\t},\r\n\t\t\tcomplete: function() {\r\n\t\t\t\t$( '#entrypics_wrap' ).hv_ajax_loader( 'toggle_loading', 'off' );\r\n\t\t\t}\r\n\t\t});\r\n\t}", "function loadPhotoIdList() {\n\t\t$.ajax({\n \t\t\turl: \"rest/Image/list\",\n\t\t\tsuccess:function(data) {\n\t\t\t\tconsole.log('rest/Image/list server response: ' + data);\n \t\t\tvar regex = /([\\d]+)/g;\n \t\t\tvar matched = null;\n \t\t\twhile ( matched = regex.exec(data) ) {\n\t\t\t\t\tloadSceneObject( 'rest/Image/' + matched[0] + '.xml', matched[0] );\n\t\t\t\t}\n \t\t} \n\t\t});\n\t}", "function displaygiphyInfo() {\n var jet = $(this).attr('data-name');\n var jetTrimmed = $.trim(jet); // trim extra spaces\n jetTrimmed = jetTrimmed.replace(/ /g, \"+\"); // change space to +\n\n var queryURL = \"http://api.giphy.com/v1/gifs/search?q=\" + jetTrimmed + \"&limit=10&api_key=dc6zaTOxFJmzC \";\n // Creates AJAX call for the specific jet being \n $.ajax({\n url: queryURL,\n method: 'GET'\n }).done(function(response) {\n console.log(response);\n\n var state = 'still';\n for (i = 0; i < 10; i++) {\n // Creates a generic div to hold the giphy\n var gifDiv = $('<div class=\"giphy\">');\n var gifDiv = $('<div>').attr('class', 'giphy');\n // Creates an element to have the rating displayed\n var rating = $('<p>').text(\"Rating: \" + response.data[i].rating);\n var data_animate = response.data[i].images.downsized_medium.url;\n var data_still = response.data[i].images.original_still.url;\n // rating\n gifDiv.append(rating);\n\n // Creates an element to hold the image \n var image = $('<img>').attr(\"src\", data_still); //response.data[i].images.downsized_medium.url);\n image.attr('data-state', 'still');\n image.attr('data-still', data_still);\n image.attr('data-animate', data_animate);\n image.attr('class', 'animeImage');\n // Appends the image\n gifDiv.append(image);\n\n // Puts the entire jet above the previous jets.\n $('#jetsView').prepend(gifDiv);\n }\n });\n\n }", "function displayFavGif() {\n $(\"#movies-view\").empty();\n for (var i=0; i<favGif.length; i++) {\n var FavImage = $(\"<img>\").attr(\"src\", favGif[i]);\n $(\"#movies-view\").prepend(FavImage);\n }\n}", "function Refresh_Image(the_id)\n{\n var data = {\n action: 'x2_get_image',\n id: the_id\n };\n\t\t\n jQuery.get(ajaxurl, data, function(response)\n\t\t{\n\n if(response.success === true)\n\t\t\t{\n jQuery('#x2-preview-image').replaceWith( response.data.image );\n }\n });\n}", "function updateMathias() {\n\tconsole.log(images[index]);\n\t$(\".image-holder\").html(\"<img src ='images/\" + images[index] + \"'/>\");\n\n}", "function findImgId(e) {\n setPicId(e.target.id);\n handleShow();\n }", "function loadZoomInImages(i) {\n\t\tif (i < 77) {\n\t\t\tpicnumstring = ('00000' + i).slice(-5);\n\t\t\tinnerProject = currentProject();\n\t\t\tpicstring = '/sequences/rotate/ZOOMIN/' + innerProject + '/' + innerProject + '_' + picnumstring + '.jpg';\n\t\t\t$('#configurator .inset-0').prepend('<img class=\"hidden sequence-image inner-' + innerProject + '-' + picnumstring + '\" src=\"' + picstring + '\">');\n\n\n\t\t\tanimTimer = setTimeout(function() { loadZoomInImages(i + 1) }, 50);\n\n\t\t\t\n\t\t} else {\n\t\t\tloadedProjects.push(innerProject);\n\t\t}\n\n\t}", "function showTrendingGifs(json, i) {\n\tconst gifCard = document.createElement(\"div\");\n\tgifCard.setAttribute(\"class\", \"gifCard\");\n\tgifCard.setAttribute(\"id\", `gif${i}`);\n\tgifCard.innerHTML = `\n <img class=\"gifCard__gif\" src=\"${json.images.downsized.url}\" alt=\"${json.title}\">`;\n\t$trendingTrack.appendChild(gifCard);\n\n\t// Creates a hover over the gif with gif's info and action buttons\n\tconst gifHover = document.createElement(\"div\");\n\tgifHover.setAttribute(\"class\", \"gifHover hidden\");\n\tgifHover.setAttribute(\"id\", `gifHover${i}`);\n\n\tgifHover.innerHTML = `<div class=\"gifHover__icons\">\n <img class=\"gif-icons\" src=\"assets/mobile/icon-fav-hover.svg\" alt=\"icon fav\" id=\"fav${i}\">\n <img class=\"gif-icons\" src=\"assets/mobile/icon-download.svg\" alt=\"icon download\" onclick=\"downloadGif('${json.images.original.url}', '${json.title}')\">\n <img class=\"gif-icons\" id=\"max-${i}\" src=\"assets/mobile/icon-max.svg\" alt=\"icon max\">\n </div>\n <div class=\"gifHover__textBox\">\n <p class=\"gifHover__textBox__text\">${json.username}</p>\n <p class=\"gifHover__textBox__text\">${json.title}</p>\n </div>`;\n\tgifCard.appendChild(gifHover);\n\n\t// Maximizes gif when clicked max button\n\tlet maxIcon = document.getElementById(`max-${i}`);\n\tmaxIcon.setAttribute(\n\t\t\"onclick\",\n\t\t`maximizeGif('${json.images.downsized.url}', '${json.username}', '${json.title}', '${i}')`,\n\t);\n\n\t// In mobile maximizes gif when touched, in desktop\n\t// display hover when mouse move over gif\n\tgifCard.addEventListener(\"mouseover\", () => {\n\t\tif (window.innerWidth > 990) {\n\t\t\tlet hoverOn = document.getElementById(`gifHover${i}`);\n\t\t\thoverOn.classList.remove(\"hidden\");\n\t\t} else {\n\t\t\tmaximizeGif(json.images.downsized.url, json.username, json.title, i);\n\t\t}\n\t});\n\tgifCard.addEventListener(\"mouseout\", () => {\n\t\tlet hoverOut = document.getElementById(`gifHover${i}`);\n\t\thoverOut.classList.add(\"hidden\");\n\t});\n\n\t// Adds a click event on close button to close maximized Gifs\n\t$maxGifBtnClose.addEventListener(\"click\", closeMax);\n\n\t// Add scroll function to buttons on desktop carousel\n\taddScrollToCarousel();\n\n\t// Changes fav icon when clicked\n\tlet favIcon = document.getElementById(`fav${i}`);\n\tfavIcon.addEventListener(\"click\", () => {\n\t\tlet isFavHidden = $favouriteSection.classList.contains(\"hidden\");\n\t\tif (!isFavHidden) {\n\t\t\taddToFavourites(json.images.downsized.url, json.title, json.username);\n\t\t\tchangeHoverIcon(`fav${i}`, json.images.downsized.url);\n\t\t\tdisplayFavourites();\n\t\t} else {\n\t\t\taddToFavourites(json.images.downsized.url, json.title, json.username);\n\t\t\tchangeHoverIcon(`fav${i}`, json.images.downsized.url);\n\t\t}\n\t});\n}", "function renderGifs(response, $giphyModal, trumbowyg, mustEmpty) {\n var width = ($giphyModal.width() - 20) / 3;\n\n var html = response.data\n .filter(function (gifData) {\n return gifData.images.downsized.url !== '';\n })\n .map(function (gifData) {\n var image = gifData.images.downsized,\n imageRatio = image.height / image.width;\n\n return '<div class=\"img-container\"><img src=' + image.url + ' width=\"' + width + '\" height=\"' + imageRatio * width + '\" loading=\"lazy\" onload=\"this.classList.add(\\'tbw-loaded\\')\"/></div>';\n })\n .join('')\n ;\n\n if (mustEmpty === true) {\n if (html.length === 0) {\n if ($('.' + trumbowyg.o.prefix + 'giphy-no-result', $giphyModal).length > 0) {\n return;\n }\n\n html = '<img class=\"' + trumbowyg.o.prefix + 'giphy-no-result\" src=\"' + trumbowyg.o.plugins.giphy.noResultGifUrl + '\"/>';\n }\n\n $giphyModal.empty();\n }\n $giphyModal.append(html);\n $('img', $giphyModal).on('click', function () {\n trumbowyg.restoreRange();\n trumbowyg.execCmd('insertImage', $(this).attr('src'), false, true);\n $('img', $giphyModal).off();\n trumbowyg.closeModal();\n });\n }", "function updateSrcs() {\n\t\t$('#img1').attr('src', gifArray[championIndex]);\n\t\t$('#img2').attr('src', gifArray[challengerIndex]);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getUserBrowser function purpose: returns the common name of the user's browser
function getUserBrowser() { var agent = navigator.userAgent.toLowerCase (); var browser = "Unknown browser"; if (agent.search ("msie") > -1) { browser = "Internet Explorer"; } else { if (agent.search ("firefox") > -1) { browser = "Firefox"; } else { if (agent.search ("opera") > -1) { browser = "Opera"; } else { if (agent.search ("safari") > -1) { if (agent.search ("chrome") > -1) { browser = "Google Chrome"; } else { browser = "Safari"; } } } } } return browser; }
[ "function getBrowser() {\n var browserObj = $.browser;\n if (browserObj.hasOwnProperty(\"chrome\")) {\n return Browsers.CHROME;\n } else if (browserObj.hasOwnProperty(\"mozilla\")) {\n return Browsers.FIREFOX;\n } else if (browserObj.hasOwnProperty(\"msie\")) {\n return Browsers.INTERNET_EXPLORER;\n } else {\n return Browsers.OTHER;\n }\n}", "function checkBrowser(){\n\tvar browserInfo = navigator.userAgent;\n\tif(browserInfo.indexOf(\"Firefox\")!=-1)userBrowser=\"Firefox\";\n\tif(browserInfo.indexOf(\"Chrome\")!=-1)userBrowser=\"Chrome\";\n\tif(browserInfo.indexOf(\"Safari\")!=-1)userBrowser=\"Safari\";\n}", "function convertBrowserNameToUserFriendlyName(browserName) {\n for (var baseName in USER_FRIENDLY_BROWSER_NAMES) {\n if (!browserName.startsWith(baseName))\n continue;\n var userFriendlyBaseName = USER_FRIENDLY_BROWSER_NAMES[baseName];\n var suffix = browserName.substring(baseName.length);\n if (suffix.length === 0)\n return userFriendlyBaseName;\n else if (/^\\d+$/.test(suffix))\n return userFriendlyBaseName + '(' + suffix + ')';\n }\n return '\\'' + browserName + '\\' browser';\n }", "function browserNameVersion(){\n let ua = window.navigator.userAgent, tem,\n M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) || [];\n if(/trident/i.test(M[1])){\n tem = /\\brv[ :]+(\\d+)/g.exec(ua) || [];\n return 'IE '+(tem[1] || '');\n }\n if(M[1]=== 'Chrome'){\n tem = ua.match(/\\b(OPR|Edge)\\/(\\d+)/);\n if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');\n }\n M= M[2]? [M[1], M[2]]: [window.navigator.appName, window.navigator.appVersion, '-?'];\n if((tem = ua.match(/version\\/(\\d+)/i))!= null) M.splice(1, 1, tem[1]);\n return M.join('|');\n }", "function checkBrowser()\r\n{\r\n\tvar theAgent = navigator.userAgent.toLowerCase();\r\n\tif(theAgent.indexOf(\"msie\") != -1)\r\n\t{\r\n\t\tif(theAgent.indexOf(\"opera\") != -1)\r\n\t\t{\r\n\t\t\treturn \"opera\";\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn \"ie\";\r\n\t\t}\r\n\t}\r\n\telse if(theAgent.indexOf(\"netscape\") != -1)\r\n\t{\r\n\t\treturn \"netscape\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"firefox\") != -1)\r\n\t{\r\n\t\treturn \"firefox\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"mozilla/5.0\") != -1)\r\n\t{\r\n\t\treturn \"mozilla\";\r\n\t}\r\n\telse if(theAgent.indexOf(\"\\/\") != -1)\r\n\t{\r\n\t\tif(theAgent.substr(0,theAgent.indexOf('\\/')) != 'mozilla')\r\n\t\t{\r\n\t\t\treturn navigator.userAgent.substr(0,theAgent.indexOf('\\/'));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn \"netscape\";\r\n\t\t} \r\n\t}\r\n\telse if(theAgent.indexOf(' ') != -1)\r\n\t{\r\n\t\treturn navigator.userAgent.substr(0,theAgent.indexOf(' '));\r\n\t}\r\n\telse\r\n\t{ \r\n\t\treturn navigator.userAgent;\r\n\t}\r\n}", "function getSessionAppName() {\n var sessionToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\n\n if (!sessionToken) {\n sessionToken = getSessionToken();\n }\n\n var session = jsontokens.decodeToken(sessionToken).payload;\n assert(session.app_domain, 'Missing app_domain in session ' + sessionToken);\n\n var domainName = session.app_domain;\n var urlInfo = urlparse.parse(domainName);\n if (!urlInfo.slashes) {\n domainName = 'http://' + domainName;\n }\n\n var appname = urlparse.parse(domainName).host;\n assert(appname, 'Unparseable app_domain in session ' + sessionToken);\n return appname;\n}", "get browser() {\n if (browser)\n return browser;\n if (Page.replacementBrowser) {\n browser = Page.replacementBrowser;\n console.log('Setting the browser');\n return Page.replacementBrowser;\n }\n throw new Error(\"Replacement browser not set on Page\");\n }", "function findUserName() {\n var thisENV = process.env,\n possibleVariables = ['USER', 'USERNAME'],\n i;\n for (i = 0; i < possibleVariables.length; i += 1) {\n if (possibleVariables[i]) {\n return thisENV[possibleVariables[i]];\n }\n }\n return null;\n}", "function verificarBrowser(){\n // Verificando Browser\n if(Is.appID==\"IE\" && Is.appVersion<6 ){\n var msg = \"Este sistema possui recursos não suportados pelo seu Navegador atual.\\n\";\n msg += \"É necessário fazer uma atualização do browser atual para a versão 6 ou superior,\\n\";\n msg += \"ou poderá instalar o Navegador Firefox.\\n\";\n //msg += \"\\nDados do seu Navegador:\";\n //msg += \"\\n Browser:\"+Is.appName+\"\\n ID:\"+Is.appID+\"\\n Versão:\"+Is.appVersion;\n msg += \"\\n Baixar firefox agora?\";\n if(confirm(msg)){\n document.location.replace(\"http://br.mozdev.org/\");\n return false;\n }else{\n return false;\n }\n }else{\n return true;\n }\n}", "async function findMyName() {\n try {\n return cross_spawn_1.default.sync('git', ['config', '--get', 'user.name']).stdout.toString().trim();\n }\n catch {\n return '';\n }\n}", "function getUserInfo() {\n\ttry {\n\t\treturn os.userInfo();\n\t} catch (e) {\n\t\t/* istanbul ignore next */\n\t\treturn {};\n\t}\n}", "function getUserAgent(model) {\n if (model.match(/qemu/i)) {\n return \"Emulator\";\n }\n try {\n if (navigator && navigator.userAgent) {\n console.log(\"userAgent=\" + navigator.userAgent);\n return (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i)) ? \"iOS\" : \"Android\";\n } else {\n return \"Android\";\n }\n } catch (err) {\n return \"Android\";\n }\n }", "function getClientType() {\n var clientType=\"IE\";\n //alert(\"getting client type\");\t \n\n try { \n var appVersion = window.external.GetSystemInfo(\"APP_VERSION\");\n //alert(appVersion);\n var appInfo= appVersion.split(\",\");\n var appName = appInfo[0];\n \n if(appName == \"CONNECT Player\"){\n clientType=\"MARLIN\";\n }else{\n clientType=\"OPEN_MG\";\n }\n }\n catch (e) {}\n //alert(clientType);\n return clientType;\n}", "function convertProcessNameToUserFriendlyName(processName,\n opt_requirePlural) {\n switch (processName) {\n case 'browser_process':\n return opt_requirePlural ? 'browser processes' : 'the browser process';\n case 'renderer_processes':\n return 'renderer processes';\n case 'gpu_process':\n return opt_requirePlural ? 'GPU processes' : 'the GPU process';\n case 'ppapi_process':\n return opt_requirePlural ? 'PPAPI processes' : 'the PPAPI process';\n case 'all_processes':\n return 'all processes';\n case 'unknown_processes':\n return 'unknown processes';\n default:\n return '\\'' + processName + '\\' processes';\n }\n }", "function getGitUserName(){\n return new Promise((resolve, reject) => {\n shell.exec('git config user.name', (code,stdout,stderr) => {\n if (stdout) {\n if (stdout === '') { \n console.log('rejected user.name - empty string', code, stdout); \n reject();\n }\n else {\n resolve(stdout);\n }\n } else {\n console.log('rejected user.name', code, stderr); \n reject();\n }\n });\n });\n}", "function toDesktop(req){\n return req.cookies.desktop_interface == 'true';\n}", "get siteTitle() {\n if (this.manifest && this.manifest.title) {\n return this.manifest.title;\n }\n return \"\";\n }", "function Chrome() {\n if (!(this instanceof Chrome)) {\n \treturn new Chrome();\n }\n \n this.name = 'Google Chrome';\n this.uaname = 'chrome';\n this.version = ua.indexOf(this.uaname) != -1 ? parseInt(ua.split(this.uaname + \"/\")[1]) : false;\n}", "function retrieveUAFromRequest() {\n\n \tvar currentUASet = environment.get(\"User-Agent\");\n if (currentUASet == null || currentUASet.isEmpty()) {\n logMessage(\"No User-Agent specified in the evaluation request environment parameters.\");\n return false;\n }\n currentUA = currentUASet.iterator().next();\n logMessage(\"User-Agent found with this resource request: \" + currentUA);\n \n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the URL for a callable with the given name.
_url(name) { const projectId = this.app.options.projectId; if (this.emulatorOrigin !== null) { const origin = this.emulatorOrigin; return `${origin}/${projectId}/${this.region}/${name}`; } if (this.customDomain !== null) { return `${this.customDomain}/${name}`; } return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`; }
[ "getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }", "function computeURL() {\n var url = settings.url;\n if (typeof settings.url == 'function') {\n url = settings.url.call();\n }\n return url;\n }", "httpsCallable(name) {\n return data => {\n const promise = getNativeModule(this).httpsCallable(name, {\n data\n });\n return promise.then(errorOrResult);\n };\n }", "function complianceURL(name, url) {\n return '<a href=\"' + url + '\" target=\"_blank\">' + ' <i class=\"far fa-3x fa-folder-open\"></i></a>'\n }", "getParameterByUrlName(name) {\n\t name = name.replace(/[\\[]/, \"\\\\[\").replace(/[\\]]/, \"\\\\]\");\n\t var regex = new RegExp(\"[\\\\?&]\" + name + \"=([^&#]*)\"),\n\t results = regex.exec(location.search);\n\t return results === null ? \"\" : decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n\n\t // console.log(this.getParameterByUrlName('cotizacion_id')) how work\n\t // https://es.stackoverflow.com/questions/445/c%C3%B3mo-obtener-valores-de-la-url-get-en-javascript\n\t}", "function serviceURL(svc){\n return getEndpointURL('/service.php'+svc); \n}", "urlForResource(name) {\n return this.nativeResourceLoader.urlForResource(name);\n }", "function getPublicUrl (bucketName,filename) {\n return `https://storage.googleapis.com/${bucketName}/${filename}`;\n }", "function createUrl(username, projectName) {\n return `http://www.github.com/${username}/${projectName}`\n}", "function nameOf(fun) {\n var ret = fun.toString();\n ret = ret.substr('function '.length);\n ret = ret.substr(0, ret.indexOf('('));\n return ret;\n }", "function getPageNameFromUrl(urlString) {\n var urlObject = _url.default.parse(urlString);\n\n if ((0, _isFunction.default)(customExtractionFunction)) {\n return customExtractionFunction(urlObject);\n } else if (!isValidUrlObject(urlObject)) {\n return urlString;\n } else {\n return buildDefaultPageName(urlObject);\n }\n}", "function getServerURL(name){\n for(i in SERVERS){\n if(SERVERS[i].name == name){ return SERVERS[i].url; }\n }\n\n return \"Error: server \" + name + \" does not exist\";\n}", "getURL() {\n return EHUrls.getDegree(this._code, this._school);\n }", "static async UrlShortener() {\n\n }", "function get_UrlArg() {\n var loc = $(location).attr('href');\n var loc_separator = loc.indexOf('#');\n return (loc_separator == -1) ? '' : loc.substr(loc_separator + 1);\n }", "function getCallService (sweetpServerUrl, projectName) {\n\treturn _.partial(sweetp.callService, sweetpServerUrl, projectName);\n}", "getByUrl(name) {\n return Folder(this).concat(`('${encodePath(name)}')`);\n }", "function tagUrl(tag) {\n return webbase + \"resourceview.php?tag=\" + tag; // this is probably wrong!\n }", "function repoLink(name) {\n return '<a class=\"repo\" href=\"https://github.com/'+name+'\">'+name+'</a>';\n}", "function GetRateCurr(url, curCode, rateDate, FunctionName) {\n\n if (curCode != '') {\n if (curCode == 'IDR') {\n\n var strFun = FunctionName;\n var strParam = 1;\n //Create the function\n var fn = window[strFun];\n\n //Call the function\n fn(strParam);\n\n }\n else {\n var data = { CurCode: curCode, RateDate: rateDate };\n GetDataJson(url, \"POST\", FunctionName, data);\n\n }\n }\n\n return;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts BST 'data' values to [array]
cvtBST() { var arr = []; arr.push(this.root.data); // get array - depth-first this.cvtToArray(this.root.left, arr); this.cvtToArray(this.root.right, arr); return arr; }
[ "function flattenTreeData(data) {\n var dataMap = data.reduce(function(map, node) {\n map[node.name] = node;\n return map;\n }, {});\n\n // create the tree array\n var treeData = [];\n data.forEach(function(node) {\n // add to parent\n var parent = dataMap[node.parent];\n if (parent) {\n // create child array if it doesn't exist\n (parent.children || (parent.children = []))\n // add node to child array\n .push(node);\n } else {\n // parent is null or missing\n treeData.push(node);\n }\n });\n\n return treeData;\n}", "inOrder() {\r\n\r\n let resultsArr = [];\r\n\r\n let _walk = node => {\r\n if (node.left) _walk(node.left);\r\n resultsArr.push(node.value);\r\n if (node.right) _walk(node.right);\r\n }\r\n\r\n _walk(this.root);\r\n\r\n return resultsArr\r\n}", "traverseBreadth(){\n let queue = new Queue();\n let arr = [];\n let current = this.root;\n\n queue.enqueue( current );\n\n while( queue.size > 0 ){\n\n current = queue.dequeue().val;\n arr.push( current.value );\n\n if( current.left !== null ) queue.enqueue( current.left );\n if( current.right !== null ) queue.enqueue( current.right );\n }\n\n return arr;\n }", "getData() {\n const { tree, props } = this\n const { root } = props\n\n /* Create a new root, where each node contains height, depth, and parent.\n * Embeds the old node under the data attribute of the new node */\n const rootHierarchy = d3.hierarchy(\n root,\n (d) => d.children && Object.values(d.children)\n )\n\n /* Adds x, y to each node */\n tree(rootHierarchy)\n\n /* Return the array of nodes */\n const data = rootHierarchy.descendants()\n\n /* Use fixed depth to maintain position as items are added / removed */\n data.forEach((d) => {\n d.y = d.depth * 180\n })\n return data\n }", "function traverse(node) {\n data.push(node.value);\n if (node.left) {\n traverse(node.left);\n }\n if (node.right) {\n traverse(node.right);\n }\n }", "function breadthFirstArray(root) {\n\n}", "traverseDepthPostOrder(){\n let arr = [];\n\n function traverse( node ){\n if( node.left !== null ) traverse( node.left );\n if( node.right !== null ) traverse( node.right );\n\n arr.push( node.value );\n }\n\n traverse( this.root );\n return arr;\n }", "_checkAndConvertToArray(node) {\n if (node === null || typeof node === 'undefined') {\n return null;\n }\n if (typeof node !== 'object') {\n return node;\n }\n let obj = {};\n let numKeys = 0;\n let maxKey = 0;\n let allIntegerKeys = true;\n for (let key in node) {\n if (!node.hasOwnProperty(key)) {\n continue;\n }\n let childNode = node[key];\n obj[key] = this._checkAndConvertToArray(childNode);\n numKeys++;\n const integerRegExp = /^(0|[1-9]\\d*)$/;\n if (allIntegerKeys && integerRegExp.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n }\n if (allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n let array = [];\n _.forOwn(obj, (val, key) => {\n array[key] = val;\n });\n return array;\n }\n return obj;\n }", "traverseDepthInOrder(){\n let arr = [];\n\n function traverse( node ){\n if( node.left !== null ) traverse( node.left );\n arr.push( node.value );\n if( node.right !== null ) traverse( node.right );\n }\n\n traverse( this.root );\n return arr;\n }", "function traverseDeserialize(data) {\n if(index > data.length || data[index] === \"#\") {\n return null;\n }\n var node = new TreeNode(parseInt(data[index]));\n index++;\n node.left = traverseDeserialize(data);\n index++;\n node.right = traverseDeserialize(data);\n return node;\n }", "function preOrderToString(node, arr) {\n if (node === null) {\n arr.push('X');\n return;\n }\n arr.push(node.val);\n preOrderToString(node.left, arr);\n preOrderToString(node.right, arr);\n return arr;\n }", "traverseDepthPreOrder(){\n let arr = [];\n\n function traverse( node ){\n arr.push( node.value );\n\n if( node.left !== null ) traverse( node.left );\n if( node.right !== null ) traverse( node.right );\n }\n\n traverse( this.root );\n return arr;\n }", "depthFirstSearch(array) {\n // create an empty working array with root node\n let workingArray = [this]\n // while the workingArray has elements in the array\n while (workingArray.length) {\n // remove the first element/node of the workingArray\n let node = workingArray.shift()\n // push the first element/node's names into array\n array.push(node.name)\n // using spread operator, take every element from node's children array and push into the START of the workingArray\n workingArray.unshift(...node.children)\n }\n // return array\n return array\n }", "function buildBalancedTree(array) {\n if (array.length == 0) { return null; }\n\n var mid = Math.floor((array.length)/2);\n var n = new treeNode(null, array[mid], null);\n\n var arrayOnLeft = array.slice(0, mid);\n n.left = buildBalancedTree(arrayOnLeft);\n\n var arrayOnRight= array.slice(mid+1);\n n.right = buildBalancedTree(arrayOnRight);\n\n return n;\n }", "function storeTreeCoords() {\n var treeId, treeObj, trunkTop, leafsTop;\n\n $trees.forEach(function ($tree) {\n treeId = $tree.getAttribute(\"data-id\");\n treesData[\"tree\" + treeId] = {};\n treeObj = treesData[\"tree\" + treeId];\n treeObj.isRight = $tree.classList.contains(\"m--right\");\n treeObj.$treeTrunk = $tree.querySelector(\".svgBg__tree-trunk\");\n treeObj.$treeLeafs = $tree.querySelector(\".svgBg__tree-leafs\");\n treeObj.trunkInitArrD = treeObj.$treeTrunk.getAttribute(\"d\").split(\" \");\n treeObj.leafsInitArrD = treeObj.$treeLeafs.getAttribute(\"d\").split(\" \");\n trunkTop = treeObj.trunkInitArrD[2];\n leafsTop = treeObj.leafsInitArrD[3];\n treeObj.trunkInitX = +trunkTop.split(\",\")[0];\n treeObj.leafsInitX = +leafsTop.split(\",\")[0];\n treeObj.trunkInitY = +trunkTop.split(\",\")[1];\n treeObj.leafsInitY = +leafsTop.split(\",\")[1];\n });\n }", "function createSaveArray( SCOObj ) {\n var arr = new Array();\n arr[0] = (SCOObj.hasOwnProperty('complete') && SCOObj.complete) ? 1 : 0;\n arr[1] = (SCOObj.hasOwnProperty('childrenComplete') && SCOObj.childrenComplete) ? 1 : 0;\n arr[2] = (SCOObj.hasOwnProperty('visited') && SCOObj.visited) ? 1 : 0;\n \n // when object has branches;\n if ( SCOObj.hasOwnProperty('branches') && SCOObj.branches && SCOObj.branches.length > 0 ) {\n arr[3] = new Array();\n // go through each branch\n\t\t//console.log(\"shell.js line 2780. Go through each branch\")\n for ( var i = 0; i < SCOObj.branches.length; i++ ) {\n arr[3][i] = createSaveArray( SCOObj.branches[i] );\n }\n }\n \n return arr;\n}", "function buildTree(root, data, dimensions, value) {\n zeroCounts(root);\n var n = data.length,\n nd = dimensions.length;\n for (var i = 0; i < n; i++) {\n var d = data[i],\n v = +value(d, i),\n node = root;\n\n for (var j = 0; j < nd; j++) {\n var dimension = dimensions[j],\n category = d[dimension],\n children = node.children;\n node.count += v;\n node = children.hasOwnProperty(category) ? children[category]\n : children[category] = {\n children: j === nd - 1 ? null : {},\n count: 0,\n parent: node,\n dimension: dimension,\n name: category , \n class : d.class\n };\n }\n node.count += v;\n }\n return root;\n }", "toArray() {\n const keys = this[ _schema ].keys,\n data = this[ _data ],\n changes = this[ _changeset ],\n arr = []\n\n for (let i = keys.length; i--;) {\n const key = keys[ i ],\n val = changes[ key ] || data[ key ]\n\n if (val != null)\n arr.push(key, val)\n }\n\n return arr\n }", "function convertTree(atoms, bonds, tree) {\n if (tree === null) {\n return [atoms, bonds];\n }\n if (tree.type === \"atom\") {\n const treeIdx = idxString(tree.idx);\n atoms[treeIdx] = {idx: treeIdx, symbol: tree.symbol, connections: []};\n if (tree.bonds) {\n tree.bonds.forEach(function(b) {\n const toIdx = idxString(b.to.idx);\n atoms[treeIdx].connections.push(toIdx);\n bonds.push({from: treeIdx, to: toIdx, bondType: b.bondType});\n convertTree(atoms, bonds, b.to);\n atoms[toIdx].connections.push(treeIdx);\n });\n }\n }\n return [atoms, bonds];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
norm() is required because of stupid, noninternational sorting in js. Normalizes the icelandic characters to put them in their place
function norm(str){ return str .toLowerCase() .replace(/Á|á/,'azzz').replace(/É|é/,'ezzz').replace(/Í|í/,'izzz') .replace(/Ð|ð/,'dzzz').replace(/Ó|ó/,'ozzz').replace(/Ú|ú/,'uzzz') .replace(/Ý|ý/,'yzzz').replace(/Þ|þ/,'zz').replace(/Æ|æ/,'zzz').replace(/Ö|ö/,'zzzz'); }
[ "function _normalize(phrase) {\n\n // Lower case it\n phrase = phrase.toLocaleLowerCase();\n\n // Normalize special characters by using the characters in the charMap hash\n phrase = phrase.replace(/[,./!?àáâãāçćčèéêëēėęîïíīįìłñńňôòóōõřśšťûüùúūůÿýžżŻź]/g, function(ch) {\n return charMap[ch] || ch;\n });\n\n return phrase;\n }", "function normalize(word) {\n\n return stem(word.toLowerCase()).replace(/[^a-z]/g, '');\n\n}", "function normalize(w) {\n w = w.toLowerCase();\n var c = has(w);\n while (c != \"\") { //keep getting rid of punctuation as long as it has it\n var index = w.indexOf(c);\n if (index == 0) w = w.substring(1, w.length);\n else if (index == w.length - 1) w = w.substring(0, w.length - 1);\n else w = w.substring(0, index) + w.substring(index + 1, w.length);\n c = has(w);\n }\n return w;\n\n}", "function changeUppercase(str)\n{\n if(str==\"\" || eval(str)==0)\n return \"\\u96f6\";\n \n if(str.substring(0,1) == \"-\")\n { \n if(eval(str.substring(1)) < 0.01)\n return \"\\u91d1\\u989d\\u6709\\u8bef!!\";\n else\n str = str.substring(1);\n }\n \n var integer_part=\"\";\n var decimal_part=\"\\u6574\";\n var tmpstr=\"\";\n var twopart=str.split(\".\");\n \n //\\u5904\\u7406\\u6574\\u578b\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u524d\\u7684\\u6574\\u6570\\u4f4d\\uff09\n var intlen=twopart[0].length;\n \n if (intlen > 0 && eval(twopart[0]) != 0)\n {\n var gp=0;\n var intarray=new Array();\n \n while(intlen > 4)\n {\n intarray[gp]=twopart[0].substring(intlen-4,intlen);\n gp=gp+1;\n intlen=intlen-4;\n }\n \n intarray[gp]=twopart[0].substring(0,intlen);\n \n for(var i=gp;i>=0;i--)\n {\n integer_part=integer_part+every4(intarray[i])+pubarray3[i];\n }\n\n integer_part=replace(integer_part,\"\\u4ebf\\u4e07\",\"\\u4ebf\\u96f6\");\n integer_part=replace(integer_part,\"\\u5146\\u4ebf\",\"\\u5146\\u96f6\");\t\n\n while(true)\n {\n if (integer_part.indexOf(\"\\u96f6\\u96f6\")==-1)\n break;\n\n integer_part=replace(integer_part,\"\\u96f6\\u96f6\",\"\\u96f6\");\n }\n \n integer_part=replace(integer_part,\"\\u96f6\\u5143\",\"\\u5143\");\n\n /*\\u6b64\\u5904\\u6ce8\\u91ca\\u662f\\u4e3a\\u4e86\\u89e3\\u51b3100000\\uff0c\\u663e\\u793a\\u4e3a\\u62fe\\u4e07\\u800c\\u4e0d\\u662f\\u58f9\\u62fe\\u4e07\\u7684\\u95ee\\u9898\\uff0c\\u6b64\\u6bb5\\u7a0b\\u5e8f\\u628a\\u58f9\\u62fe\\u4e07\\u622a\\u6210\\u4e86\\u62fe\\u4e07\n tmpstr=intarray[gp];\n \n if (tmpstr.length==2 && tmpstr.charAt(0)==\"1\")\n {\n intlen=integer_part.length;\n integer_part=integer_part.substring(char_len,intlen);\n }\n */\n }\n \n //\\u5904\\u7406\\u5c0f\\u6570\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u540e\\u7684\\u6570\\u503c\\uff09\n tmpstr=\"\";\n if(twopart.length==2 && twopart[1]!=\"\")\n {\n if(eval(twopart[1])!=0)\n {\n decimal_part=\"\";\n intlen= (twopart[1].length>2) ? 2 : twopart[1].length;\n \n for(var i=0;i<intlen;i++)\n {\n tmpstr=twopart[1].charAt(i);\n decimal_part=decimal_part+pubarray1[eval(tmpstr)]+pubarray4[i];\n }\n \n decimal_part=replace(decimal_part,\"\\u96f6\\u89d2\",\"\\u96f6\");\n decimal_part=replace(decimal_part,\"\\u96f6\\u5206\",\"\");\n \n if(integer_part==\"\" && twopart[1].charAt(0)==0)\n {\n intlen=decimal_part.length;\n decimal_part=decimal_part.substring(char_len,intlen);\n }\n }\n }\n \n tmpstr=integer_part+decimal_part;\n \n return tmpstr;\n}", "function alpha (stra, strb) {\n // lowercase everything\n var a = stra.toLowerCase ();\n var b = strb.toLowerCase ();\n // test for length\n if (a.length == b.length) {\n // first letter difference\n for (var i = 0; i < a.length; i++) {\n if (a.charCodeAt (i) != b.charCodeAt (i)) {\n if (a.charCodeAt (i) < b.charCodeAt (i)) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n return 0;\n } else if (a.length < b.length) {\n for (var i = 0; i < a.length; i++) {\n if (a.charCodeAt (i) != b.charCodeAt (i)) {\n if (a.charCodeAt (i) < b.charCodeAt (i)) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n var ac = a.charCodeAt (a.length - 1);\n for (var i = a.length; i < b.length; i++) {\n if (ac != b.charCodeAt (i)) {\n if (ac < b.charCodeAt (i)) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n return 0;\n } else {\n for (var i = 0; i < b.length; i++) {\n if (a.charCodeAt (i) != b.charCodeAt (i)) {\n if (a.charCodeAt (i) < b.charCodeAt (i)) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n var bc = b.charCodeAt (b.length - 1);\n for (var i = b.length; i < a.length; i++) {\n if (a.charCodeAt (i) != bc) {\n if (a.charCodeAt (i) < bc) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n return 0;\n }\n}", "function normalize(ruleStr)\r\n{\r\n\tvar retVal = ruleStr.toLowerCase() ;\r\n\tvar re = /,(\\w)/;\r\n\tretVal = retVal.replace(re,\", $1\");\r\n\treturn retVal;\r\n}", "function getSortedLetters(word) {\n word = cleanWord(word);\n var charArray = word.toLowerCase().split(\"\");\n charArray.sort();\n return charArray.join(\"\");\n}", "function getNormalizationFunction() {\n var repl = [];\n for (var i = 0; i < arguments.length; i++) {\n var mapping = arguments[i];\n for ( var key in mapping) {\n repl.push({\n regexp : new RegExp(key, 'gim'),\n value : mapping[key]\n });\n }\n }\n return function(str) {\n if (!str || str == '')\n return '';\n str = str + '';\n for (var i = 0; i < repl.length; i++) {\n var slot = repl[i];\n str = str.replace(slot.regexp, slot.value);\n }\n return str;\n }\n}", "wordToNormIdx(word) {\n if(Array.isArray(word)) {\n var result = [ ];\n for(var i = 0; i < word.length; i++)\n result.push(this._wordToIdx[word[i].toString().toLocaleLowerCase()]);\n return result;\n } else {\n return this.wordToIdx(word.toString().toLocaleLowerCase());\n }\n }", "function stringTransformer(str) {\n // Your code here\n return str.split(' ').reverse().join(' ').split('').map((el)=> {\n if (el == el.toUpperCase()) return el.toLowerCase()\n else if (el == el.toLowerCase()) return el.toUpperCase()\n }).join('')\n}", "function normalizeHeader_(header) {\n var key = \"\";\n var upperCase = false;\n for (var i = 0; i < header.length; ++i) {\n var letter = header[i];\n if (letter == \" \" && key.length > 0) {\n upperCase = true;\n continue;\n }\n if (!isAlnum_(letter)) { \n continue;\n }\n if (key.length == 0 && isDigit_(letter)) {\n continue; // first character must be a letter\n }\n if (upperCase) {\n upperCase = false;\n key += letter.toUpperCase();\n } else {\n key += letter.toLowerCase();\n }\n }\n return key;\n}", "function toAngstroms(l, unit) {\n if (unit == \"A\" || unit == undefined) {\n return l\n }\n if (unit == \"m\") {\n return l * 1.0e10\n }\n if (unit == \"cm\") {\n return l * 1.0e8\n }\n if (unit == \"nm\") {\n return l * 10\n }\n}", "function fix_entities(text) {\nvar i;\nvar ents = {\n\t8364 : \"euro\",\n\t402 : \"fnof\",\n\t8240 : \"permil\",\n\t352 : \"Scaron\",\n\t338 : \"OElig\",\n\t381 : \"#381\",\n\t8482 : \"trade\",\n\t353 : \"scaron\",\n\t339 : \"oelig\",\n\t382 : \"#382\",\n\t376 : \"Yuml\",\n\t162 : \"cent\",\n\t163 : \"pound\",\n\t164 : \"curren\",\n\t165 : \"yen\",\n\t166 : \"brvbar\",\n\t167 : \"sect\",\n\t168 : \"uml\",\n\t169 : \"copy\",\n\n\t170 : \"ordf\",\n\t171 : \"laquo\",\n\t172 : \"not\",\n\t173 : \"shy\",\n\t174 : \"reg\",\n\t175 : \"macr\",\n\t176 : \"deg\",\n\t177 : \"plusmn\",\n\t178 : \"sup2\",\n\t179 : \"sup3\",\n\t180 : \"acute\",\n\t181 : \"micro\",\n\t182 : \"para\",\n\t183 : \"middot\",\n\t184 : \"cedil\",\n\t185 : \"sup1\",\n\t186 : \"ordm\",\n\t187 : \"raquo\",\n\t188 : \"frac14\",\n\t189 : \"frac12\",\n\n\t190 : \"frac34\",\n\t191 : \"iquest\",\n\t192 : \"Agrave\",\n\t193 : \"Aacute\",\n\t194 : \"Acirc\",\n\t195 : \"Atilde\",\n\t196 : \"Auml\",\n\t197 : \"Aring\",\n\t198 : \"AElig\",\n\t199 : \"Ccedil\",\n\t200 : \"Egrave\",\n\t201 : \"Eacute\",\n\t202 : \"Ecirc\",\n\t203 : \"Euml\",\n\t204 : \"Igrave\",\n\t205 : \"Iacute\",\n\t206 : \"Icirc\",\n\t207 : \"Iuml\",\n\t208 : \"ETH\",\n\t209 : \"Ntilde\",\n\n\t210 : \"Ograve\",\n\t211 : \"Oacute\",\n\t212 : \"Ocirc\",\n\t213 : \"Otilde\",\n\t214 : \"Ouml\",\n\t215 : \"times\",\n\t216 : \"Oslash\",\n\t217 : \"Ugrave\",\n\t218 : \"Uacute\",\n\t219 : \"Ucirc\",\n\t220 : \"Uuml\",\n\t221 : \"Yacute\",\n\t222 : \"THORN\",\n\t223 : \"szlig\",\n\t224 : \"agrave\",\n\t225 : \"aacute\",\n\t226 : \"acirc\",\n\t227 : \"atilde\",\n\t228 : \"auml\",\n\t229 : \"aring\",\n\n\t230 : \"aelig\",\n\t231 : \"ccedil\",\n\t232 : \"egrave\",\n\t233 : \"eacute\",\n\t234 : \"ecirc\",\n\t235 : \"euml\",\n\t236 : \"igrave\",\n\t237 : \"iacute\",\n\t238 : \"icirc\",\n\t239 : \"iuml\",\n\t240 : \"eth\",\n\t241 : \"ntilde\",\n\t242 : \"ograve\",\n\t243 : \"oacute\",\n\t244 : \"ocirc\",\n\t245 : \"otilde\",\n\t246 : \"ouml\",\n\t247 : \"divide\",\n\t248 : \"oslash\",\n\t249 : \"ugrave\",\n\t250 : \"uacute\",\n\t251 : \"ucirc\",\n\t252 : \"uuml\",\n\t253 : \"yacute\",\n\t254 : \"thorn\",\n\t255 : \"yuml\",\n\n\n\t913 : \"Alpha\",\n\t914 : \"Beta\",\n\t915 : \"Gamma\",\n\t916 : \"Delta\",\n\t917 : \"Epsilon\",\n\t918 : \"Zeta\",\n\t919 : \"Eta\",\n\t920 : \"Theta\",\n\t921 : \"Iota\",\n\t922 : \"Kappa\",\n\t923 : \"Lambda\",\n\t924 : \"Mu\",\n\t925 : \"Nu\",\n\t926 : \"Xi\",\n\t927 : \"Omicron\",\n\t928 : \"Pi\",\n\t929 : \"Rho\",\n\n\t931 : \"Sigma\",\n\t932 : \"Tau\",\n\t933 : \"Upsilon\",\n\t934 : \"Phi\",\n\t935 : \"Chi\",\n\t936 : \"Psi\",\n\t937 : \"Omega\",\n\n\t8756 : \"there4\",\n\t8869 : \"perp\",\n\n\t945 : \"alpha\",\n\t946 : \"beta\",\n\t947 : \"gamma\",\n\t948 : \"delta\",\n\t949 : \"epsilon\",\n\t950 : \"zeta\",\n\t951 : \"eta\",\n\t952 : \"theta\",\n\t953 : \"iota\",\n\t954 : \"kappa\",\n\t955 : \"lambda\",\n\t956 : \"mu\",\n\t957 : \"nu\",\n\t968 : \"xi\",\n\t969 : \"omicron\",\n\t960 : \"pi\",\n\t961 : \"rho\",\n\t962 : \"sigmaf\",\n\t963 : \"sigma\",\n\t964 : \"tau\",\n\t965 : \"upsilon\",\n\t966 : \"phi\",\n\t967 : \"chi\",\n\t968 : \"psi\",\n\t969 : \"omega\",\n\n\t8254 : \"oline\",\n\t8804 : \"le\",\n\t8260 : \"frasl\",\n\t8734 : \"infin\",\n\t8747 : \"int\",\n\t9827 : \"clubs\",\n\t9830 : \"diams\",\n\t9829 : \"hearts\",\n\t9824 : \"spades\",\n\t8596 : \"harr\",\n\t8592 : \"larr\",\n\t8594 : \"rarr\",\n\t8593 : \"uarr\",\n\t8595 : \"darr\",\n\t8220 : \"ldquo\",\n\t8221 : \"rdquo\",\n\t8222 : \"bdquo\",\n\t8805 : \"ge\",\n\t8733 : \"prop\",\n\t8706 : \"part\",\n\t8226 : \"bull\",\n\t8800 : \"ne\",\n\t8801 : \"equiv\",\n\t8776 : \"asymp\",\n\t8230 : \"hellip\",\n\t8212 : \"mdash\",\n\t8745 : \"cap\",\n\t8746 : \"cup\",\n\t8835 : \"sup\",\n\t8839 : \"supe\",\n\t8834 : \"sub\",\n\t8838 : \"sube\",\n\t8712 : \"isin\",\n\t8715 : \"ni\",\n\t8736 : \"ang\",\n\t8711 : \"nabla\",\n\t8719 : \"prod\",\n\t8730 : \"radic\",\n\t8743 : \"and\",\n\t8744 : \"or\",\n\t8660 : \"hArr\",\n\t8658 : \"rArr\",\n\t9674 : \"loz\",\n\t8721 : \"sum\",\n\n\t8704 : \"forall\",\n\t8707 : \"exist\",\n\t8216 : \"lsquo\",\n\t8217 : \"rsquo\",\n\t161 : \"iexcl\",\n\n// other entities\n\t977 : \"thetasym\",\n\t978 : \"upsih\",\n\t982 : \"piv\",\n\t8242 : \"prime\",\n\t8243 : \"Prime\",\n\t8472 : \"weierp\",\n\t8465 : \"image\",\n\t8476 : \"real\",\n\t8501 : \"alefsym\",\n\t8629 : \"crarr\",\n\t8656 : \"lArr\",\n\t8657 : \"uArr\",\n\t8659 : \"dArr\",\n\t8709 : \"empty\",\n\t8713 : \"notin\",\n\t8727 : \"lowast\",\n\t8764 : \"sim\",\n\t8773 : \"cong\",\n\t8836 : \"nsub\",\n\t8853 : \"oplus\",\n\t8855 : \"otimes\",\n\t8901 : \"sdot\",\n\t8968 : \"lceil\",\n\t8969 : \"rceil\",\n\t8970 : \"lfloor\",\n\t8971 : \"rfloor\",\n\t9001 : \"lang\",\n\t9002 : \"rang\",\n\t710 : \"circ\",\n\t732 : \"tilde\",\n\t8194 : \"ensp\",\n\t8195 : \"emsp\",\n\t8201 : \"thinsp\",\n\t8204 : \"zwnj\",\n\t8205 : \"zwj\",\n\t8206 : \"lrm\",\n\t8207 : \"rlm\",\n\t8211 : \"ndash\",\n\t8218 : \"sbquo\",\n\t8224 : \"dagger\",\n\t8225 : \"Dagger\",\n\t8249 : \"lsaquo\",\n\t8250 : \"rsaquo\"\n};\n\n\tvar new_text = '';\n\nvar temp = new RegExp();\n\ttemp.compile(\"[a]|[^a]\", \"g\");\n\n\tvar parts = text.match(temp);\n\n\tif (!parts) return text;\n\tfor (i=0; i<parts.length; i++) {\n\t\tvar c_code = parseInt(parts[i].charCodeAt());\n\t\tif (ents[c_code]) {\n\t\t\tnew_text += \"&\"+ents[c_code]+\";\";\n\t\t} else new_text += parts[i];\n\t}\n\n\treturn new_text;\n}", "function normL1(x) {\n\treturn x.reduce(function (acc, curr) { \n\t\treturn acc + Math.abs(curr - uniform);\n\t}, 0);\n}", "function convertToLowerCase(grid, dictionary){\n for( let i=0; i<grid.length; i++){\n for(let j=0; j<grid[i].length; j++){\n grid[i][j] = grid[i][j].toLowerCase();\n }\n }\n \n for(let i =0; i<dictionary.length; i++){\n dictionary[i] = dictionary[i].toLowerCase();\n }\n}", "function getLinkRewriteFromString(str)\n\t{\n\t\tstr = str.toUpperCase();\n\t\tstr = str.toLowerCase();\n\t\t\n\t\t/* Lowercase */\n\t\tstr = str.replace(/[\\u00E0\\u00E1\\u00E2\\u00E3\\u00E4\\u00E5\\u0101\\u0103\\u0105\\u0430]/g, 'a');\n str = str.replace(/[\\u0431]/g, 'b');\n\t\tstr = str.replace(/[\\u00E7\\u0107\\u0109\\u010D\\u0446]/g, 'c');\n\t\tstr = str.replace(/[\\u010F\\u0111\\u0434]/g, 'd');\n\t\tstr = str.replace(/[\\u00E8\\u00E9\\u00EA\\u00EB\\u0113\\u0115\\u0117\\u0119\\u011B\\u0435\\u044D]/g, 'e');\n str = str.replace(/[\\u0444]/g, 'f');\n\t\tstr = str.replace(/[\\u011F\\u0121\\u0123\\u0433\\u0491]/g, 'g');\n\t\tstr = str.replace(/[\\u0125\\u0127]/g, 'h');\n\t\tstr = str.replace(/[\\u00EC\\u00ED\\u00EE\\u00EF\\u0129\\u012B\\u012D\\u012F\\u0131\\u0438\\u0456]/g, 'i');\n\t\tstr = str.replace(/[\\u0135\\u0439]/g, 'j');\n\t\tstr = str.replace(/[\\u0137\\u0138\\u043A]/g, 'k');\n\t\tstr = str.replace(/[\\u013A\\u013C\\u013E\\u0140\\u0142\\u043B]/g, 'l');\n str = str.replace(/[\\u043C]/g, 'm');\n\t\tstr = str.replace(/[\\u00F1\\u0144\\u0146\\u0148\\u0149\\u014B\\u043D]/g, 'n');\n\t\tstr = str.replace(/[\\u00F2\\u00F3\\u00F4\\u00F5\\u00F6\\u00F8\\u014D\\u014F\\u0151\\u043E]/g, 'o');\n str = str.replace(/[\\u043F]/g, 'p');\n\t\tstr = str.replace(/[\\u0155\\u0157\\u0159\\u0440]/g, 'r');\n\t\tstr = str.replace(/[\\u015B\\u015D\\u015F\\u0161\\u0441]/g, 's');\n\t\tstr = str.replace(/[\\u00DF]/g, 'ss');\n\t\tstr = str.replace(/[\\u0163\\u0165\\u0167\\u0442]/g, 't');\n\t\tstr = str.replace(/[\\u00F9\\u00FA\\u00FB\\u00FC\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173\\u0443]/g, 'u');\n str = str.replace(/[\\u0432]/g, 'v');\n\t\tstr = str.replace(/[\\u0175]/g, 'w');\n\t\tstr = str.replace(/[\\u00FF\\u0177\\u00FD\\u044B]/g, 'y');\n\t\tstr = str.replace(/[\\u017A\\u017C\\u017E\\u0437]/g, 'z');\n\t\tstr = str.replace(/[\\u00E6]/g, 'ae');\n str = str.replace(/[\\u0447]/g, 'ch');\n str = str.replace(/[\\u0445]/g, 'kh');\n\t\tstr = str.replace(/[\\u0153]/g, 'oe');\n str = str.replace(/[\\u0448]/g, 'sh');\n str = str.replace(/[\\u0449]/g, 'ssh');\n str = str.replace(/[\\u044F]/g, 'ya');\n str = str.replace(/[\\u0454]/g, 'ye');\n str = str.replace(/[\\u0457]/g, 'yi');\n str = str.replace(/[\\u0451]/g, 'yo');\n str = str.replace(/[\\u044E]/g, 'yu');\n str = str.replace(/[\\u0436]/g, 'zh');\n\n\t\t/* Uppercase */\n\t\tstr = str.replace(/[\\u0100\\u0102\\u0104\\u00C0\\u00C1\\u00C2\\u00C3\\u00C4\\u00C5\\u0410]/g, 'A');\n str = str.replace(/[\\u0411]/g, 'B');\n\t\tstr = str.replace(/[\\u00C7\\u0106\\u0108\\u010A\\u010C\\u0426]/g, 'C');\n\t\tstr = str.replace(/[\\u010E\\u0110\\u0414]/g, 'D');\n\t\tstr = str.replace(/[\\u00C8\\u00C9\\u00CA\\u00CB\\u0112\\u0114\\u0116\\u0118\\u011A\\u0415\\u042D]/g, 'E');\n str = str.replace(/[\\u0424]/g, 'F');\n\t\tstr = str.replace(/[\\u011C\\u011E\\u0120\\u0122\\u0413\\u0490]/g, 'G');\n\t\tstr = str.replace(/[\\u0124\\u0126]/g, 'H');\n\t\tstr = str.replace(/[\\u0128\\u012A\\u012C\\u012E\\u0130\\u0418\\u0406]/g, 'I');\n\t\tstr = str.replace(/[\\u0134\\u0419]/g, 'J');\n\t\tstr = str.replace(/[\\u0136\\u041A]/g, 'K');\n\t\tstr = str.replace(/[\\u0139\\u013B\\u013D\\u0139\\u0141\\u041B]/g, 'L');\n str = str.replace(/[\\u041C]/g, 'M');\n\t\tstr = str.replace(/[\\u00D1\\u0143\\u0145\\u0147\\u014A\\u041D]/g, 'N');\n\t\tstr = str.replace(/[\\u00D3\\u014C\\u014E\\u0150\\u041E]/g, 'O');\n str = str.replace(/[\\u041F]/g, 'P');\n\t\tstr = str.replace(/[\\u0154\\u0156\\u0158\\u0420]/g, 'R');\n\t\tstr = str.replace(/[\\u015A\\u015C\\u015E\\u0160\\u0421]/g, 'S');\n\t\tstr = str.replace(/[\\u0162\\u0164\\u0166\\u0422]/g, 'T');\n\t\tstr = str.replace(/[\\u00D9\\u00DA\\u00DB\\u00DC\\u0168\\u016A\\u016C\\u016E\\u0170\\u0172\\u0423]/g, 'U');\n str = str.replace(/[\\u0412]/g, 'V');\n\t\tstr = str.replace(/[\\u0174]/g, 'W');\n\t\tstr = str.replace(/[\\u0176\\u042B]/g, 'Y');\n\t\tstr = str.replace(/[\\u0179\\u017B\\u017D\\u0417]/g, 'Z');\n\t\tstr = str.replace(/[\\u00C6]/g, 'AE');\n str = str.replace(/[\\u0427]/g, 'CH');\n str = str.replace(/[\\u0425]/g, 'KH');\n\t\tstr = str.replace(/[\\u0152]/g, 'OE');\n str = str.replace(/[\\u0428]/g, 'SH');\n str = str.replace(/[\\u0429]/g, 'SHH');\n str = str.replace(/[\\u042F]/g, 'YA');\n str = str.replace(/[\\u0404]/g, 'YE');\n str = str.replace(/[\\u0407]/g, 'YI');\n str = str.replace(/[\\u0401]/g, 'YO');\n str = str.replace(/[\\u042E]/g, 'YU');\n str = str.replace(/[\\u0416]/g, 'ZH');\n\n\t\tstr = str.toLowerCase();\n\n\t\tstr = str.replace(/[^a-z0-9\\s\\'\\:\\/\\[\\]-]/g,'');\n\t\t\n\t\tstr = str.replace(/[\\u0028\\u0029\\u0021\\u003F\\u002E\\u0026\\u005E\\u007E\\u002B\\u002A\\u002F\\u003A\\u003B\\u003C\\u003D\\u003E]/g, '');\n\t\tstr = str.replace(/[\\s\\'\\:\\/\\[\\]-]+/g, ' ');\n\n\t\t// Add special char not used for url rewrite\n\t\tstr = str.replace(/[ ]/g, '-');\n\t\tstr = str.replace(/[\\/\\\\\"'|,;%]*/g, '');\n\n\t\treturn str;\n\t}", "function ignoreCaseComparator(s1, s2) {\n var s1lower = s1.toLowerCase();\n var s2lower = s2.toLowerCase();\n return s1lower > s2lower? 1 : (s1lower < s2lower? -1 : 0);\n}", "order(words){cov_25grm4ggn6.f[7]++;cov_25grm4ggn6.s[40]++;if(!words){cov_25grm4ggn6.b[15][0]++;cov_25grm4ggn6.s[41]++;return[];}else{cov_25grm4ggn6.b[15][1]++;}//ensure we have a list of individual words, not phrases, no punctuation, etc.\nlet list=(cov_25grm4ggn6.s[42]++,words.toString().match(/\\w+/g));cov_25grm4ggn6.s[43]++;if(list.length==0){cov_25grm4ggn6.b[16][0]++;cov_25grm4ggn6.s[44]++;return[];}else{cov_25grm4ggn6.b[16][1]++;}cov_25grm4ggn6.s[45]++;return list.sort((a,b)=>{cov_25grm4ggn6.f[8]++;cov_25grm4ggn6.s[46]++;return this.rank(a)<=this.rank(b)?(cov_25grm4ggn6.b[17][0]++,1):(cov_25grm4ggn6.b[17][1]++,-1);});}", "function removeSpecialChars(str) {\n let transliterated = transliterate(str)\n return transliterated.replace(/[-\\/' ]/ig, '').toLowerCase();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }