query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Get the AudioContext. Assuming this would be called when it's time to play.
getContext() { if (!this.audioContext) { let AudioContext = window.AudioContext || window.webkitAudioContext; this.audioContext = new AudioContext(); this.audioContext.resume(); } return this.audioContext; }
[ "function WebAudioExtended() {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n /* global AudioContext */\n this.context = new AudioContext();\n this.soundBuffer = null;\n}", "get sampleRate() {\n if (this._buffer) {\n return this._buffer.sampleRate;\n } else {\n return (0, _Global.getContext)().sampleRate;\n }\n }", "function isAudioContext(arg) {\n return (0, _standardizedAudioContext.isAnyAudioContext)(arg);\n}", "function getContext(){\n \n if(!domain.active || !domain.active.context){\n if(this.mockContext) return this.mockContext\n \n logger.error(\"getContext called but no active domain\", domain.active);\n logger.error(\"Caller is \", arguments.callee && arguments.callee.caller && arguments.callee.caller.name, arguments.callee && arguments.callee.caller );\n throw \"Context not available. This may happen if the code was not originated by Angoose\"; \n } \n \n return domain.active.context;\n}", "constructor () {\r\n this.context = new AudioContext(); //AudioContext for Oscillators to generate tones\r\n this.debug = false;\r\n this.duration = Piano2.DEFAULT_DURATION;\r\n this.toneType = Piano2.DEFAULT_TONE;\r\n }", "function initAudio() {\n\n // Default values for the parameters\n AudBuffSiz = 4096;\n AudAmplify = 0.02;\n AudAmpScale = 0.8; // 1.3 is good to emphasise \"peakiness\", 0.5 good to \"smooth\" the sounds out a bit\n AudMinFreq = 30.0; // In Hz\n AudMaxFreq = 900.0;\n\n AudioCtx = new AudioContext();\n GainNode = AudioCtx.createGain();\n //GainNode.connect(AudioCtx.destination);\n //GainNode.gain.value = 1;\n AudSampleRate = AudioCtx.sampleRate;\n AudioBuffer = AudioCtx.createBuffer(1, AudBuffSiz, AudSampleRate);\n\n PlayingSpec = -1;\n\n}", "function startRenderingAudio(context) {\n\t\tconst renderTryMaxCount = 3\n\t\tconst renderRetryDelay = 500\n\t\tconst runningMaxAwaitTime = 500\n\t\tconst runningSufficientTime = 5000\n\t\tlet finalize = () => undefined\n\t\tconst resultPromise = new Promise((resolve, reject) => {\n\t\t\tlet isFinalized = false\n\t\t\tlet renderTryCount = 0\n\t\t\tlet startedRunningAt = 0\n\t\t\tcontext.oncomplete = (event) => resolve(event.renderedBuffer)\n\t\t\tconst startRunningTimeout = () => {\n\t\t\t\tsetTimeout(\n\t\t\t\t\t() => reject(makeInnerError('timeout' /* Timeout */)),\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\trunningMaxAwaitTime,\n\t\t\t\t\t\tstartedRunningAt + runningSufficientTime - Date.now(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst tryRender = () => {\n\t\t\t\ttry {\n\t\t\t\t\tcontext.startRendering()\n\t\t\t\t\tswitch (context.state) {\n\t\t\t\t\t\tcase 'running':\n\t\t\t\t\t\t\tstartedRunningAt = Date.now()\n\t\t\t\t\t\t\tif (isFinalized) {\n\t\t\t\t\t\t\t\tstartRunningTimeout()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t// Sometimes the audio context doesn't start after calling `startRendering` (in addition to the cases where\n\t\t\t\t\t\t// audio context doesn't start at all). A known case is starting an audio context when the browser tab is in\n\t\t\t\t\t\t// background on iPhone. Retries usually help in this case.\n\t\t\t\t\t\tcase 'suspended':\n\t\t\t\t\t\t\t// The audio context can reject starting until the tab is in foreground. Long fingerprint duration\n\t\t\t\t\t\t\t// in background isn't a problem, therefore the retry attempts don't count in background. It can lead to\n\t\t\t\t\t\t\t// a situation when a fingerprint takes very long time and finishes successfully. FYI, the audio context\n\t\t\t\t\t\t\t// can be suspended when `document.hidden === false` and start running after a retry.\n\t\t\t\t\t\t\tif (!document.hidden) {\n\t\t\t\t\t\t\t\trenderTryCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tisFinalized &&\n\t\t\t\t\t\t\t\trenderTryCount >= renderTryMaxCount\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tmakeInnerError('suspended' /* Suspended */),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsetTimeout(tryRender, renderRetryDelay)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttryRender()\n\t\t\tfinalize = () => {\n\t\t\t\tif (!isFinalized) {\n\t\t\t\t\tisFinalized = true\n\t\t\t\t\tif (startedRunningAt > 0) {\n\t\t\t\t\t\tstartRunningTimeout()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\treturn [resultPromise, finalize]\n\t}", "audioPlayer(\n audio = false,\n currentTrack = 0,\n skipAutoPlay = true,\n autoPlay = false\n ){\n\n // set default settings\n this.frequencyBarsEnable = null,\n this.oscilloscopeEnable = null,\n this.infoEnable = null,\n this.trackDuration = 0,\n this.currentPosition = 0,\n this.position = 0,\n this.startTime = 0,\n this.audioInit = false,\n this.audioEnd = false,\n this.resume = false,\n this.playing = false,\n this.currentTrack = currentTrack,\n this.skipAutoPlay = skipAutoPlay,\n this.autoPlay = autoPlay,\n this.audioRaw = audio;\n\n try {\n // Fix up prefixing\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n this.context = new AudioContext();\n }\n catch(e) {\n alert('Web Audio API is not supported in this browser');\n }\n\n var audioInfo;\n var audioCount;\n\n if(audio){\n this.audioPlay = document.querySelector(this.selectorClass);\n audioInfo = JSON.parse(audio);\n audioCount = audioInfo.tracks.length;\n this.audioInfo = audioInfo;\n } else if (this.audio) {\n this.audioPlay = document.querySelector(this.selectorClass);\n audioInfo = JSON.parse(this.audio);\n audioCount = audioInfo.tracks.length;\n this.audioInfo = audioInfo;\n }\n\n this.tracks = audioInfo.tracks.length;\n this.tracks--;\n this.playButton = this.audioPlay.querySelector('button.play');\n this.audioPosition = this.audioPlay.querySelector('.audio-position input[type=range]');\n\n this.gainNode = this.context.createGain();\n\n if (this.audioPlay.querySelector('.oscilloscope')){\n this.audioOscilloscope(this);\n }\n\n if (this.audioPlay.querySelector('.frequency-bars')){\n this.audioFrequencyBars(this);\n }\n\n if (this.audioPlay.querySelector('.audio-info')){\n this.audioInformation(this);\n }\n\n if(this.audioPlay.querySelector('button.stop')){\n this.stopButton = this.audioPlay.querySelector('button.stop');\n this.stopButton.onclick = () => this.stopAudio(true);\n }\n\n if(this.audioPlay.querySelector('button.next')){\n this.nextButton = this.audioPlay.querySelector('button.next');\n if(this.currentTrack == this.tracks){\n this.nextButton.classList.add(\"disabled\");\n this.nextButton.disabled = true;\n }\n if(this.currentTrack < this.tracks){\n this.nextButton.classList.remove(\"disabled\");\n this.nextButton.disabled = false;\n this.nextButton.onclick = () => this.nextAudio();\n }\n }\n\n if(this.audioPlay.querySelector('button.prev')){\n this.prevButton = this.audioPlay.querySelector('button.prev');\n if(this.currentTrack == 0){\n this.prevButton.classList.add(\"disabled\");\n this.prevButton.disabled = true;\n }\n if(this.currentTrack > 0){\n this.prevButton.classList.remove(\"disabled\");\n this.prevButton.disabled = false;\n this.prevButton.onclick = () => this.prevAudio();\n }\n }\n\n if(this.audioPlay.querySelector('div.volume')){\n this.volWrap = this.audioPlay.querySelector('.volume');\n this.volButton = this.audioPlay.querySelector('.volume > a');\n this.volDrop = this.audioPlay.querySelector('.volume > .dropdown-content');\n this.volInput = this.audioPlay.querySelector('.volume > .dropdown-content > li > .range-field > input');\n\n if(this.getCookie('mxvol')){\n this.volInput.value = this.getCookie('mxvol');\n this.gainNode.gain.value = this.getCookie('mxvol');\n } else {\n this.volInput.value = 1;\n this.gainNode.gain.value = 1;\n }\n\n this.volButton.onclick = () => {\n this.volDrop.classList.toggle(\"active\");\n };\n\n /**\n *\n * Detect Volume Range Change and set gainNode\n *\n */\n this.volInput.addEventListener('input', function(event){\n thisMedia.gainNode.gain.value = this.value;\n var currGain = thisMedia.gainNode.gain.value;\n thisMedia.gainNode.gain.setValueAtTime(currGain, thisMedia.context.currentTime + 1);\n thisMedia.setCookie('mxvol',this.value,1);\n }, true);\n\n document.addEventListener('click', (event) => {\n if(this.volDrop.classList.contains(\"active\")) {\n this.volDrop.classList.remove(\"active\");\n }\n }, true);\n\n }\n\n\n\n\n this.context.ended = this.endedAudio();\n\n this.playButton.onclick = () => this.playAudio(this.oAnalyser,this.fAnalyser,0);\n\n if(this.autoPlay){\n this.playButton.className = this.playButton.className.replace(/\\bplay\\b/g, \"pause\");\n this.pauseButton = this.audioPlay.querySelector('button.pause');\n if(this.audioPlay.querySelector('button.pause i').innerHTML !== \"pause\"){\n this.audioPlay.querySelector('button.pause i').innerHTML = \"pause\";\n }\n this.playAudio(this.oAnalyser,this.fAnalyser,0);\n this.pauseButton.onclick = () => this.pauseAudio();\n }\n\n if(this.audioPlay.querySelector('.audio-cover')){\n var activeCover;\n currentTrack = this.currentTrack;\n activeCover = this.audioPlay.querySelector('.track-' + currentTrack);\n getAverageColor(activeCover.src).then(rgb => {\n this.audioPlay.querySelector('.audio-cover').style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';\n }) // { r: 66, g: 83, b: 25 }\n $(document).ready(function(){\n $('.covers').carousel('set', currentTrack);\n });\n }\n\n if(this.audioPlay.querySelector('div.audio-playlist')){\n this.audioPlay.querySelector('div.audio-playlist').innerHTML = '<table class=\"bordered centered highlight playlist-table\"><tbody></tbody></table>';\n var playlist,\n playliPre = '',\n playliCover,\n trackselector;\n this.audioPlay.querySelector('table.playlist-table tbody').innerHTML = '';\n for (var i = 0; i < audioInfo.tracks.length; i++) {\n if(i == this.currentTrack){\n playlist = '<tr><td><button id=\"track-' + i + '\" data-id=\"' + i + '\" class=\"waves-light btn-floating playlist-play disabled\"><i class=\"material-icons\">equalizer</i></button></td><td>' + audioInfo.tracks[i].title + '</td><td>' + audioInfo.tracks[i].artist + '</td><td>' + audioInfo.tracks[i].album + '</td></tr>';\n } else {\n playlist = '<tr><td><button id=\"track-' + i + '\" data-id=\"' + i + '\" class=\"waves-light btn-floating playlist-play\"><i class=\"material-icons\">play_arrow</i></button></td><td>' + audioInfo.tracks[i].title + '</td><td>' + audioInfo.tracks[i].artist + '</td><td>' + audioInfo.tracks[i].album + '</td></tr>';\n }\n this.audioPlay.querySelector('table.playlist-table tbody').insertAdjacentHTML('beforeend', playlist);\n }\n\n var playlistPlay = this.audioPlay.querySelectorAll(\".playlist-play\"),t;\n playlistPlay.forEach(function(element) {\n t = element.dataset.id;\n element.addEventListener('click', function(event){\n thisMedia.setTrack(this.dataset.id);\n }, true);\n });\n }\n\n var thisMedia = this;\n\n /**\n *\n * Detect Audio Range input and set position\n *\n */\n this.audioPosition.addEventListener('input', function(event){\n var thisTime = this.value;\n if(thisMedia.playing){\n thisMedia.stopAudio(false);\n thisMedia.audioEnd = true;\n thisMedia.audioPlayer(thisMedia.audioRaw,thisMedia.currentTrack);\n setTimeout(function(){\n thisMedia.playAudio(thisMedia.oAnalyser,thisMedia.fAnalyser,thisTime);\n thisMedia.currentPosition = thisTime;\n },100);\n }\n }, true);\n\n }", "createContext() {\n\t\treturn new AssetContext();\n\t}", "getRecording() {\n if (this.audio !== null && (typeof (this.audio) !== null) && this.audio !== undefined) { return this.audio; }\n return null;\n }", "function loadSample(audioContext, url){\n console.log('done');\n return new Promise(function(resolve, reject){\n fetch(url)\n .then((response) => {\n return response.arrayBuffer();\n })\n .then((buffer) =>{\n audioContext.decodeAudioData(buffer, (decodedAudioData) =>{\n resolve(decodedAudioData);\n });\n });\n });\n}", "function loadSong(id){\n var getBuffer = new XMLHttpRequest();\n getBuffer.open('GET', '/media/'+id+'.mp3');\n getBuffer.responseType = 'arraybuffer';\n getBuffer.onload = function(){\n audioContext.decodeAudioData(getBuffer.response, function(buffer){\n songBuffer = buffer;\n play(songBuffer);\n }, function(err){\n console.log(err);\n });\n };\n getBuffer.send();\n}", "function renderAudio() {\n var now = audioContext.currentTime;\n \n if (soundsPlaying)\n {\n if ((loopCount % 100) === 0)\n {\n for (var i = 0; i < NUMBER_OF_SOUND_SOURCES; i++)\n {\n if (waitTimes[i] < (now - prevTime[i]))\n {\n // Play a random sound from this soundsource\n playRandomSound(i);\n waitTimes[i] = ((Math.random() * WAIT_MAX) + WAIT_OFFSET);\n prevTime[i] = now;\n }\n }\n }\n loopCount++;\n }\n \n \n}", "function WebGLSound() {}", "isAudioTrack() {\n return this.getType() === MediaType.AUDIO;\n }", "createAudio() {\n // create an AudioListener and add it to the camera\n let listener = new THREE.AudioListener();\n this.camera.add(listener);\n\n // create a global audio source\n this.sound = new THREE.Audio(listener);\n }", "async enable (app, statsdiv = null) {\n this.app = app\n this.config = this.app.config\n\n this.detector = await getPitchDetector(this.comparePitch)\n\n if (statsdiv) {\n this.stats = new AudioStatsDisplay(statsdiv)\n this.stats.setup() // reveal stats page\n }\n\n // Get the audio context or resume if it already exists\n if (this.context === null) {\n let input = await getAudioInput()\n this.context = input.audioContext\n this.mic = input.mic\n this.media = input.media\n\n this.scriptNode = setupAudioProcess(this.context, this.mic, this.detector)\n\n } else if (this.context.state === 'suspended') {\n await this.context.resume()\n }\n\n this.isActive = true\n console.log('Audio Detection Enabled')\n\n }", "playSample(name)\n {\n if(name in this.bufferLookup)\n {\n let player = this.audio_context.createBufferSource();\n player.buffer = this.bufferLookup[name];\n player.loop = false;\n player.connect(this.masterVolume);\n player.start(this.audio_context.currentTime);\n }\n }", "playCurrent() {\n\n let chord = this.sequence[this.playing]; // get the current chord / track from the sequence\n\n this.tracks[chord][this.mode].play(); // play the track\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function determinesTimeState purpose: given an input hour, the function will determine where it occurs in relation to the current hour input: inputHour is the hour to compare to current hour return: string: "past" if the input hour occurs before the current hour "present" if the input hour is the same as the current hour "future" if the input hour is ahead of the current hour
function determineTimeState(inputHour) { let currentHour = moment().format("H"); if (inputHour < currentHour) return "past"; if (inputHour == currentHour) return "present"; if (inputHour > currentHour) return "future"; }
[ "function checkColor(hour) {\n let now = moment().format('h A');\n let momentTime = moment(now, 'h A');\n let laterMomentTime = moment(hour, 'h A');\n\n\n if (momentTime.isBefore(laterMomentTime)) {\n return \"future\";\n } else if (momentTime.isAfter(laterMomentTime)) {\n return \"past\";\n } else {\n return \"present\";\n }\n}", "function getCurrentHour() {\n var currentHour = dayjs().hour(); //day.js\n\n $(\".time-block\").each(function () { //jquery\n var hourOfWorkTime = parseInt($(this).attr(\"id\").split(\"timehour-\")[1]); \n\n if (hourOfWorkTime < currentHour) {\n $(this).addClass(\"past\");\n }\n else if (hourOfWorkTime === currentHour) {\n $(this).removeClass(\"past\");\n $(this).addClass(\"present\");\n }\n else {\n $(this).removeClass(\"past\");\n $(this).removeClass(\"present\");\n $(this).addClass(\"future\");\n }\n })\n }", "function validateHour() {\n $(\".form-control\").each(function (index) {\n const hourTimeBlock = $(this).attr(\"aria-label\");\n const dateTimeBlock = moment(hourTimeBlock, \"ha\");\n const description = localStorage.getItem(hourTimeBlock);\n\n $(this).val(description);\n\n if (!currentDay.isBefore(dateTimeBlock, \"hour\")) {\n if (currentDay.isSame(dateTimeBlock, \"hour\")) {\n $(this).addClass(\"present\");\n } else {\n $(this).addClass(\"past\");\n }\n } else if (!currentDay.isAfter(dateTimeBlock, \"hour\")) {\n $(this).addClass(\"future\");\n }\n });\n}", "function updateHours()\n{\n let nowHours = new Date();\n let nowHoursString = \"\";\n\n if (nowHours.getHours() === 0 && militaryTime === 0) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n\n else if (nowHours.getHours() < 10 && nowHours.getHours() != 0 && nowHours.getHours() != 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n else if (nowHours.getHours() === 12) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 13 && militaryTime === 0) {\n hoursMath.innerHTML = `0 + 1 = 1`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 1);\n }\n\n else if (nowHours.getHours() > 11 && nowHours.getHours() < 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `0 + ${nowHoursString[0]} = ${nowHoursString[0]}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[0]*1);\n }\n\n else if (nowHours.getHours() <= 23 && nowHours.getHours() >= 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n \n else {\n nowHoursString = nowHours.getHours().toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n\n}", "function checkTime() {\n $.each(hourArr, function (i, value) {\n // If it is the current hour, time block will turn red\n if (moment().isSame(moment().hour(9 + i))) {\n $(\"#text\" + i).addClass(\"present\");\n // If it is a future hour, it will turn green\n } else if (moment().isBefore(moment().hour(9 + i))) {\n $(\"#text\" + i).addClass(\"future\");\n } else {\n // If it is a past hour, it will turn gray\n $(\"#text\" + i).addClass(\"past\");\n };\n });\n}", "function colorizor() {\n var timeOfDay = moment().hour();\n var timeSlots = [9, 10, 11, 12, 13, 14, 15, 16, 17];\n\n $.each(timeSlots, function (index, slot) {\n\n var hrNum = slot < 13 ? slot : slot - 12;\n\n if ((timeOfDay > slot)) {\n $('#hour-' + hrNum).children('.description').addClass('past');\n } else if (timeOfDay < slot) {\n $('#hour-' + hrNum).children('.description').addClass('future');\n } else {\n $('#hour-' + hrNum).children('.description').addClass('present');\n }\n });\n }", "onIncreaseHour() {\n\t\tconst { hour, minute, hourStep } = this.state;\n\t\tconst hourIncreased = hour + hourStep;\n\n\t\tlet inputValue = this.getValue(hourIncreased, minute);\n\n\t\tif (hourIncreased < 24) {\n\t\t\tthis.setState({\n\t\t\t\thour: hourIncreased,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t} else {\n\t\t\tinputValue = this.getValue(0, minute);\n\n\t\t\tthis.setState({\n\t\t\t\thour: 0,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t}\n\t}", "function openHour() {\n var today = new Date();\n var hourNow = today.getHours();\n return hourNow;\n}", "function convertHourToMilitary() {\n\n if (militaryTime === false) {\n militaryTime = true;\n\n }\n}", "function WhatIsTheTime(timeInMirror){\n\n let mir = timeInMirror.split(':')\n let hour = parseFloat(mir[0])\n let min = parseFloat(mir[1])\n let realHour = 11 - hour\n let realMin = 60 - min\n let realTime\n\n //conditionals if mirrored time hour is 11 or 12 because formula doesn't apply\n if (hour ===12){\n realHour = 11\n }\n else if (hour ===11){\n realHour = 12\n }\n\n //for x:00 times, display mirrored hour rather than i.e 7:60\n if(realMin === 60){\n realHour += 1\n realMin = 0\n }\n\n //single digit times need to concatonate 0 when converted back to string\n if(realHour.toString().length===1){\n realHour = '0'+realHour\n }\n if(realMin.toString().length===1){\n realMin = '0'+realMin\n }\n\n //if 6PM, or 12PM -> realTime is the same, else realTime = realHour + realMin based on calculations\n if (timeInMirror===\"06:00\" || timeInMirror===\"12:00\"){\n realTime = timeInMirror\n } else {\n realTime = realHour + ':' + realMin\n }\n\n return realTime\n}", "function getPwm(hour) {\t\n\tif (LOG) { console.log(\"Looking for TP (\" + hour + \") -----------------\"); }\n\tvar rampe_pwm = { blue: -1, white: -1};\n\tif ( !(TPS[0].hour < hour && hour < TPS[TPS.length-1].hour) ) {\t//hour is in implicit period (night)\n\t\ttp1 = TPS[TPS.length-1];\n\t\ttp2 = TPS[0];\n\t\tif (DEBUG) { console.log( 'night: ' + hour + \" (\" + TPS[TPS.length-1].hour + \"-\" + TPS[0].hour +\")\" ); }\n\t\tif (LOG) { console.log('TP1-TP2', tp1, tp2 ); }\n\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t} else {\t//find hour in TPS\n\t\tfor( i = 0; i < TPS.length-1; i++ ) {\n\t\t\ttp1 = TPS[i];\n\t\t\ttp2 = TPS[i+1];\n\t\t\tif ( tp1.hour <= hour && hour <= tp2.hour) {\n\t\t\t\tif (DEBUG) { console.log( tp1.hour + \" <= \" + hour + \" < \" + tp2.hour); }\n\t\t\t\tif (LOG) { console.log( 'TP1-TP2', tp1, tp2 ); }\n\t\t\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t\t\t}\n\t\t}\n\t}\n\treturn ratio;\n}", "function timeInWords(hour, minute) {\n var dict = {\n 00: \" o' clock \",\n 1: \"one minute past \",\n 59: \"one minute to \",\n 45: \"quarter to \",\n 30: \" minutes to \",\n 30: \" minutes past \"\n\n\n }\n let words = [\n \"zero\",\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n \"nine\",\n \"ten\",\n \"eleven\",\n \"twelve\",\n \"thirteen\",\n \"fourteen\",\n \"fifteen\",\n \"sixteen\",\n \"seventeen\",\n \"eightteen\",\n \"nineteen\",\n \"twenty\",\n \"twenty one\",\n \"twenty two\",\n \"twenty three\",\n \"twenty four\",\n \"twenty five\",\n \"twenty six\",\n \"twenty seven\",\n \"twenty eight\",\n \"twenty nine\"\n ];\n if (m == 0) {\n return (words[h] + \" o' clock \");\n } else\n if ((m == 1)) {\n return (\"one minute past \" + words[h]);\n } else if (m == 59) {\n return (\"one minute to \" + words[(h % 12) + 1]);\n } else if (m == 45) {\n return (\"quarter to \" + words[(h % 12) + 1]);\n\n } else if (m <= 30) {\n return (words[m] + \" minutes past \" + words[h])\n } else if (m > 30) {\n return (words[60 - m] + \" minutes to \" + words[(h % 12) + 1])\n }\n console.log(words[h], words[m]);\n}", "function getCurrentHour() {\n return moment().hour();\n}", "function getHoursFromTemplate(){var hours=parseInt(scope.hours,10);var valid=scope.showMeridian?hours>0&&hours<13:hours>=0&&hours<24;if(!valid){return undefined;}if(scope.showMeridian){if(hours===12){hours=0;}if(scope.meridian===meridians[1]){hours=hours+12;}}return hours;}", "onDecreaseHour() {\n\t\tconst { hour, minute, hourStep } = this.state;\n\t\tconst hourDecreased = hour - hourStep;\n\n\t\tlet inputValue = this.getValue(hourDecreased, minute);\n\n\t\tif (hourDecreased >= 0) {\n\t\t\tthis.setState({\n\t\t\t\thour: hourDecreased,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t} else {\n\t\t\tinputValue = this.getValue(24 - hourStep, minute);\n\n\t\t\tthis.setState({\n\t\t\t\thour: 24 - hourStep,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t}\n\t}", "function openMessage(hourNow) {\n var openStatus\n if (hourNow >= 20) {\n openStatus = 'The brewery is closed for the night.';\n } else if (hourNow >= 12) {\n openStatus = 'The brewery is currently open for pick up.';\n } else if (hourNow >= 0 && hourNow < 12) {\n openStatus = \"Don't you think it's a bit early? Check again later.\";\n } else {\n openStatus = 'Operation hours available below! Nothing wrong here ... just scroll down.';\n }\n return openStatus;\n}", "function getHoursFromTemplate() {\n var hours = parseInt(scope.hours, 10);\n var valid = ( scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);\n if (!valid) {\n return undefined;\n }\n\n if (scope.showMeridian) {\n if (hours === 12) {\n hours = 0;\n }\n if (scope.meridian === meridians[1]) {\n hours = hours + 12;\n }\n }\n return hours;\n }", "async function timeTravelToTransition() {\n let startTimeOfNextPhaseTransition = await stakingHbbft.startTimeOfNextPhaseTransition.call();\n\n await validatorSetHbbft.setCurrentTimestamp(startTimeOfNextPhaseTransition);\n const currentTS = await validatorSetHbbft.getCurrentTimestamp.call();\n currentTS.should.be.bignumber.equal(startTimeOfNextPhaseTransition);\n await callReward(false);\n }", "function getTimeGreeting() {\n const date = new Date();\n const hours = date.getHours();\n\n if (hours >= 5 && hours <= 11) {\n return \"Good Morning \";\n } else if (hours >= 12 && hours <= 17) {\n return \"Good Afternoon \";\n } else {\n return \"Good Evening\";\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clicking on word adds properties of image to word
function handleWordClick(event) { // get letter associated with image let image = document.getElementById("image").src.substring(57,58) console.log("image name", image) let word = event.target.value console.log("word selected", word) for (let i=0; i<8; i++) { wordList[word][i]+=images[image][i] } console.log(wordList[word]) document.getElementById("image").src = randImage() }
[ "function addImageAndText(annotationID, objectUrl, x, y, w, h, startOffset, startOffsetXpath, endOffset, endOffsetXpath, editable) {\r\n var image_iframe = document.getElementById('image-input');\r\n var rectDiv = image_iframe.contentWindow.document.createElement(\"div\");\r\n if (editable == true) {\r\n rectDiv.setAttribute('id','selectedImage');\r\n rectDiv.setAttribute('onclick','resetImage(' + x + ',' + y + ',' + (parseInt(x, 10) + parseInt(w,10)) + ','+ (parseInt(y, 10) + parseInt(h,10)) + ')');\r\n\r\n document.getElementById('imageX').value = x;\r\n document.getElementById('imageY').value = y;\r\n document.getElementById('imageW').value = w;\r\n document.getElementById('imageH').value = h;\r\n document.getElementById('image-selection').innerHTML = \"Image Selection \" + w + \" x \" + h + \" px\";\r\n } else {\r\n rectDiv.setAttribute('id','Image_' + annotationID);\r\n rectDiv.setAttribute('onclick' , 'focusImageSelection(this, true)');\r\n }\r\n rectDiv.setAttribute('objectUrl',objectUrl);\r\n rectDiv.setAttribute('x', x);\r\n rectDiv.setAttribute('y', y);\r\n rectDiv.setAttribute('w', w);\r\n rectDiv.setAttribute('h', h);\r\n rectDiv.setAttribute('style','position: absolute; overflow-x: hidden; overflow-y: hidden; z-index: 2; display: block; opacity:0.4; filter:alpha(opacity=40); background-color: rgb(127, 127, 0); cursor:pointer; border: 3px solid yellow; left: ' + x + 'px; top: ' + y + 'px; width: ' + (w - 4) + 'px; height: ' + (h - 4) + 'px;');\r\n image_iframe.contentWindow.document.getElementById('pagediv0').appendChild(rectDiv);\r\n\r\n var verticalOffset = 30;\r\n var text_iframe = document.getElementById('text-input');\r\n var injectedText = text_iframe.contentWindow.document.getElementById('injected-text');\r\n \r\n var selectedText;\r\n\r\n if (text_iframe.contentWindow.getSelection && text_iframe.contentWindow.document.createRange) {\r\n var sel = text_iframe.contentWindow.getSelection();\r\n var range = text_iframe.contentWindow.document.createRange();\r\n range.selectNodeContents(injectedText);\r\n range.setStart(lookupElementByXPath(startOffsetXpath), startOffset);\r\n range.setEnd(lookupElementByXPath(endOffsetXpath), endOffset);\r\n selectedText = range.toString();\r\n sel.removeAllRanges();\r\n sel.addRange(range);\r\n } else if (text_iframe.contentWindow.document.selection && text_iframe.contentWindow.document.body.createTextRange) {\r\n var textRange = text_iframe.contentWindow.document.body.createTextRange();\r\n textRange.moveToElementText(injectedText);\r\n textRange.setStart(lookupElementByXPath(startOffsetXpath), startOffset);\r\n textRange.setEnd(lookupElementByXPath(endOffsetXpath), endOffset);\r\n selectedText = textRange.toString();\r\n textRange.select();\r\n }\r\n\r\n range.collapse(true);\r\n\r\n var markerTextChar = \"\\ufeff\";\r\n var markerTextCharEntity = \"&#xfeff;\";\r\n var markerEl;\r\n var markerId = \"sel_\" + new Date().getTime() + \"_\" + Math.random().toString().substr(2);\r\n\r\n markerEl = text_iframe.contentWindow.document.createElement(\"span\");\r\n markerEl.id = markerId;\r\n markerEl.appendChild(text_iframe.contentWindow.document.createTextNode(markerTextChar) );\r\n range.insertNode(markerEl);\r\n\r\n verticalOffset = markerEl.offsetTop;\r\n var parent = markerEl.parentNode;\r\n parent.removeChild(markerEl);\r\n parent.normalize();\r\n\r\n var svg_links = text_iframe.contentWindow.document.getElementById('svg-links');\r\n var image = text_iframe.contentWindow.document.createElement(\"img\");\r\n if (editable == true) {\r\n image.setAttribute('id','link_image');\r\n\r\n document.getElementById('textStartOffset').value = startOffset;\r\n document.getElementById('startOffsetXpath').value = startOffsetXpath;\r\n document.getElementById('textEndOffset').value = endOffset;\r\n document.getElementById('endOffsetXpath').value = endOffsetXpath;\r\n if (selectedText.toString().length > 60) {\r\n var beginsWith = selectedText.toString().substring(0, 30);\r\n var endsWith = selectedText.toString().substring(selectedText.toString().length - 20);\r\n document.getElementById('text-selection').innerHTML = beginsWith + \"...\" + endsWith;\r\n } else {\r\n document.getElementById('text-selection').innerHTML = selectedText.toString();\r\n }\r\n } else {\r\n image.setAttribute('id','Text_' + annotationID);\r\n }\r\n rectDiv.setAttribute('objectUrl',objectUrl);\r\n image.setAttribute('style','position: absolute; left: 6px; top: ' + (verticalOffset -10) + 'px; cursor: pointer;');\r\n image.setAttribute('height', '16');\r\n image.setAttribute('width', '16');\r\n image.setAttribute('objectUrl',objectUrl);\r\n image.setAttribute('src', '/alignment/link_black.png');\r\n image.setAttribute('onclick', 'highlightImage(this); event.stopPropagation();');\r\n image.setAttribute('startOffset', startOffset);\r\n image.setAttribute('startOffsetXpath', startOffsetXpath);\r\n image.setAttribute('endOffset', endOffset);\r\n image.setAttribute('endOffsetXpath', endOffsetXpath);\r\n\r\n svg_links.appendChild(image);\r\n\r\n if (text_iframe.contentWindow.getSelection) {\r\n if (text_iframe.contentWindow.getSelection().empty) { \r\n text_iframe.contentWindow.getSelection().empty();\r\n } else if (text_iframe.contentWindow.getSelection().removeAllRanges) { \r\n text_iframe.contentWindow.getSelection().removeAllRanges();\r\n }\r\n } else if (text_iframe.contentWindow.document.selection) { \r\n text_iframe.contentWindow.document.selection.empty();\r\n }\r\n }", "function changePhoto () {\n if (currentWord === \"beagle\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/beagle.jpg\"\n }\n if (currentWord === \"boxer\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/boxer.jpg\"\n }\n if (currentWord === \"dachshund\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/dachshund.jpg\"\n }\n if (currentWord === \"corgi\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/corgi.jpg\"\n }\n if (currentWord === \"labrador\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/labrador.jpg\"\n }\n if (currentWord === \"bulldog\") {\n document.getElementById(\"dog-photo\").src=\"assets/images/bulldog.jpg\"\n }\n }", "function newImage() {\n hangman.flagImage.style.opacity = 0;\n hangman.flagImage.style.backgroundImage = 'url(' + flagUrl(hangman.chosenWord) +')'\n }", "function click_word(word,dimension,mouse_event){\n console.log('word ');\n console.log(word);\n console.log('Dimension: ');\n console.log(dimension);\n /*alert('word: '+ item + ' with coordinates: '+ JSON.stringify(dimension));*/\n }", "function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}", "function onClickVocabularyImg() {\n\t// Set flag\n\t$('#scenario_vocabulary').val('vocabulary');\n\n\tonOffAreaScenarioVocabulary(CLIENT.ONVOCABULARY);\n}", "function drawImgText(elText) {\n drawImage(gCurrImg)\n}", "function redrawWordCloud() {\n WordCloud(document.getElementById('canvas'), OPTIONS);\n}", "function imageClicked() {\n var currentSource = $(this).attr('src');\n var altSource = $(this).attr('data-src');\n $(this).attr('src', altSource);\n $(this).attr('data-src', currentSource);\n }", "function replaceEmoteNameWithImgDOM(text) {\n const textArr = text.split(' ');\n const a = textArr.map(word => {\n if(word === \"\") return \"\";\n if(emoteJSON[word]) {\n return(\n `<img\n class=\"message-emote\" \n src=\"https://static-cdn.jtvnw.net/emoticons/v1/${emoteJSON[word].id}/1.0\"\n data-emotename=${word} \n alt=\"${word}\"\n />`\n );\n }\n return word;\n });\n return a.join(' ');\n }", "function WriteImageTxtPH(txtTitle, useAX, isOK, extMenu)\n{\n //WriteTxtPH(txtTitle);\n DW('<table width=480 align = \"center\" bordercolor=\"#FF9900\" border=1 ><tr>');\n // WriteImageLeftSide(useAX, isOK, extMenu); // auto complete <td></td>插件\n DW('<td vAlign=bottom width=252>');\n}", "function setDataLightbox(clickedText) \n{\n $( \".grid a img\" ).each( function()\n {\n if ( $(this).hasClass(clickedText) )\n {\n $(this).parent().attr(\"data-lightbox\", clickedText);\n }\n })\n}", "function gifClicked() {\n largeGifAppears(this);\n automatedSpeech();\n}", "function overviewImgClick(e){\n\tvar i,j,tname,turl,item,c,li,\n\t\ttarget = e.target || e.srcElement,\n\t\ttype = default_types_1,\n\t\tpremium;\n\n\tturl = target.u;\n\n\t//디폴트 타입에서 필요 li 검색\n\tfor (i = 0; i < type.length; i++) {\n\t\ttname = type[i].n;\n\t\tif (tname === turl) {\n\t\t\titem = type[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!item)\n\t\treturn;\n\n\t// click 된 overview Image Name을 가지고 온다.\n\titem.imgName = target.childNodes[0].innerHTML;\n\n\titem.over = true;\n\tactiveMainLi(item, false);\n}", "addClassNameToImageLinksInSelection() {\n const sq = this.wwe.getEditor();\n const { commonAncestorContainer: container } = sq.getSelection();\n\n if (domUtils.isElemNode(container)) {\n let links;\n\n if (container.nodeName === 'A') {\n links = [container];\n } else {\n links = domUtils.findAll(container, 'a');\n }\n\n this._addClassNameToImageLinks(links);\n }\n }", "function replaceEmoteNameWithImgDOM(text) {\n const textArr = text.split(' ');\n const formattedTextArr = textArr.map(word => {\n if(word === EMPTY_STRING) return EMPTY_STRING;\n if(global_emotes[word]) {\n return(\n `<img\n class=\"message-emote\" \n src=\"https://static-cdn.jtvnw.net/emoticons/v1/${global_emotes[word].id}/1.0\"\n data-emotename=${word} \n alt=\"${word}\"\n />`\n );\n }\n return word;\n });\n return formattedTextArr.join(' ');\n}", "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 switch_search_images()\r\n{\r\n search_images = !search_images;\r\n drawControl();\r\n}", "function hover_word(word,dimension,mouse_event){\n var c = $(\"#wordcloud-canvas\")[0];\n var ctx = c.getContext(\"2d\");\n\n if (!dimension){\n ctx.clearRect(0,0,$(\"#wordcloud-canvas\").width(),$(\"#wordcloud-canvas\").height());\n ctx.putImageData(original_cloud,0,0);\n }else{\n if (dimension != last_dimension){\n ctx.clearRect(0,0,$(\"#wordcloud-canvas\").width(),$(\"#wordcloud-canvas\").height());\n ctx.putImageData(original_cloud,0,0);\n }\n last_dimension = dimension;\n ctx.strokeRect(dimension.x,dimension.y,dimension.w,dimension.h);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by PluginManager upon receiving the __FxComponentLoadComplete event
function onLoaded() { Media.log('PluginComponent::onLoaded ' + id()); assert(pluginObj); pluginObj.onObjectLoaded(); }
[ "function loadComponent() {\n Media.log('PluginComponent::loadComponent ' + id());\n assert(state() == PluginComponent.State.Loading);\n assert(pluginObj.state() == Media.PluginObject.State.Attached);\n var args;\n try {\n args = Media.PluginDataHandler.generateBlob.apply(null, loadParams);\n pluginObj.innerObject().Load(specs.type, args);\n }\n catch (error) {\n debugger;\n cleanupPluginObject();\n state.set(PluginComponent.State.Unloaded);\n }\n }", "function resources_loaded_callback(){\n\n console.log(\"Resources loaded.\");\n\n show_loader_div(false);\n show_setting_div(true);\n show_canvas_div(true);\n\n // init mesh manager that may be contains some object loaded by model loader.\n EntityMeshManager.init();\n\n\n }", "function loadManager() {\n Media.log('PluginManager::loadManager');\n if (state() != Media.PluginManager.State.Initializing ||\n pluginObj.state() != Media.PluginObject.State.Attached)\n return;\n var options = Media.PluginDataHandler.generateBlob(language, isRtl);\n try {\n startLoadTimer();\n pluginObj.innerObject().Load('__pluginFx', options);\n }\n catch (error) {\n stopLoadTimer();\n cleanupPluginObject(error);\n state.set(Media.PluginManager.State.Deinitialized);\n }\n }", "function onFlashLoaded() {\n\t\ttrace(\"onFlashLoaded (from Flash)\");\n\t\t\n\t\tset_ready();\n\t}", "function load() {\n Media.log('PluginComponent::load ' + id());\n assert(state() == PluginComponent.State.Unloaded, 'invalid component state');\n assert(pluginMgr.state() == Media.PluginManager.State.Initialized);\n assert(!task || task.promise.state() != 'pending');\n state.set(PluginComponent.State.Loading);\n task = new Task('Loading ' + specs.type + '.', {\n cancel: function (reason) {\n Media.log('PluginComponent::load canceled ' + id());\n isCanceled = true;\n unload();\n task.reject(reason);\n }\n });\n // TODO: figure why LWA merges options passed to this method with ctor options\n // extend the array \n loadParams = [].slice.call(arguments, 0);\n try {\n pluginObj.createInnerObject({\n hide: specs.hide,\n hookEvents: true\n });\n }\n catch (err) {\n if (task.promise.state() == 'pending')\n task.reject(err);\n }\n return task.promise;\n }", "onGraphLoaded() {\n this.axis = new CGFaxis(this, this.graph.axis_length);\n\n this.loadAmbient();\n this.loadBackground();\n this.initLights();\n\n // Adds lights group.\n this.interface.addLightsGroup(this.graph.light);\n\n // Adds camera options\n this.interface.addCameraOptions(this.graph.views);\n\n // Adds Game options\n this.interface.addGame(this.graph.game);\n\n this.loadCamera();\n this.sceneInited = true;\n\n this.oldtime = 0;\n this.setUpdatePeriod(10);\n }", "onGraphLoaded() {\r\n\r\n this.defaultView = this.graph.defaultView;\r\n this.initViews();\r\n\r\n this.camera = this.cameras[this.defaultView];\r\n this.interface.setActiveCamera(this.camera);\r\n\r\n this.axis = new CGFaxis(this, this.graph.referenceLength);\r\n\r\n this.setGlobalAmbientLight(this.graph.ambientSpecs[0], this.graph.ambientSpecs[1], this.graph.ambientSpecs[2], this.graph.ambientSpecs[3]);\r\n this.gl.clearColor(this.graph.backgroundSpecs[0], this.graph.backgroundSpecs[1], this.graph.backgroundSpecs[2], this.graph.backgroundSpecs[3]);\r\n\r\n this.initLights();\r\n // Adds lights group.\r\n this.interface.addLightsGroup(this.graph.lights);\r\n this.interface.addViewsGroup(this.graph.views);\r\n this.interface.addScenesGroup();\r\n this.interface.addMenu();\r\n\r\n this.sceneInited = true;\r\n }", "function optionViewLoaded() {\r\n disableDataUpdate();\r\n LoadingBar.hide();\r\n }", "function onFileLoaded(doc) {\n collaborativeString = doc.getModel().getRoot().get('collabString');\n wireTextBoxes(collaborativeString);\n}", "onDialogLoadedNotification() {\n this._refresh();\n }", "_onAddApplication() {\n this._showLoader();\n this.$.appscoApplicationAddSettings.addApplication();\n }", "notifyLoading(isloading) {\n \n if (isloading) {\n this.dispatchEvent(new CustomEvent('loading'));\n } else {\n this.dispatchEvent(CustomEvent('doneloading'));\n }\n \n\n }", "onAfterShow(msg) {\r\n super.onAfterShow(msg);\r\n this.parent.update();\r\n }", "function checkComplete() {\r\n if (sectionLoaderState.filesLoaded >= sectionLoaderState.filesToLoad.length) complete();\r\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 }", "showComponentSelection() {\r\n // show single piece settings\r\n let label = (this.selectedComponents[0].label === '') \r\n ? 'no label' \r\n : this.selectedComponents[0].label;\r\n this.toggleComponentSettings(true);\r\n $('#component-name').val(label);\r\n this.selectedComponents[0].loadSettings($('#component-control-loader'));\r\n }", "@action appIsLoaded() {\r\n\t\tthis.appLoaded = true;\r\n\t}", "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}", "function initPageFx() {\n $('.animsition').animsition({\n inClass: 'fade-in',\n outClass: 'fade-out-down-sm',\n inDuration: 1000,\n outDuration: 800,\n linkElement: '#primaryMenu a:not([target=\"_blank\"]):not([href^=#])',\n loading: true,\n loadingParentElement: 'body', \n loadingClass: 'loadSpinner',\n unSupportCss: [\n 'animation-duration',\n '-webkit-animation-duration',\n '-o-animation-duration'\n ],\n overlay : false,\n overlayClass : 'animsition-overlay-slide',\n overlayParentElement : 'body'\n });\n }", "function pjaxloadEndCallback() {\n $('.pjaxContents').on(TML.data.eventHandler['transitionEnd'], function () {\n resizeEvent();\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables overseeing in tableview. Retrieves snapshot images from server and displays in a pulldown menu
function overseeInTable() { var maxHeight = ($(window).width()/6)/1.6 $("#menuContainer").resizable({maxHeight:maxHeight}); getCafeTables(cafe, function (response) { var cafes = JSON.parse(response); if(cafes.hasOwnProperty('error')) { console.log(cafes.error); } else { getTableImage(cafe, function(response) { var res = JSON.parse(response); var hasImage = false; var imgId; var imgData if(!res.hasOwnProperty('empty')){ for(var i=2;i<=6;i++){ hasImage = false; for(var j=0;j<res.records.length;j++){ if(res.records[j].roomID == tableId[i]) { imgData = res.records[j].imageData; if(res.records[j].roomID != currentTable ) { initOversee(imgData, '#ddMenu'); } hasImage = true; } console.log(imgID); } if(!hasImage) {initOversee("/img/emptyTable.gif", '#ddMenu');} } } }); } }); }
[ "function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}", "function mouseover_table(){\n $(\".profile tr\").not(':first').hover(\n\t\tfunction () {\n\t\t\t$(this).contents().find(\"img.help\").show();\t\n\t\t}, \n \t\tfunction () {\n\t\t\t$(this).find(\"img.help:last\").hide();\n\t\t}\n\t);\n}", "function viewOriginalImg() {\r\n\tvar linePics = [\"org1_line\",\"org2_line\",\"org3_line\",\"org4_line\",\"org5_line\"];\r\n\tvar barPics = [\"org1_bar\",\"org2_bar\",\"org3_bar\",\"org4_bar\",\"org5_bar\"];\r\n\r\n\tvar pic; //pic = pic id name\r\n\t\r\n\tif(document.getElementById(\"lineBtn\").style.background === \"white\") { //line chart\r\n\t\tpic = linePics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t} else { //bar chart\r\n\t\tpic = barPics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t}\r\n\r\n\t//hide all other pictures and display selected one\r\n\tif(element.style.display == 'none'){\r\n\t\telement.style.display='block';\r\n\t\telement.style.border='1px solid black';\r\n\t\telement.style.position='absolute';\r\n\t\telement.style.right='150px';\r\n\t\telement.style.background='black';\r\n\t\t\r\n\t\tfor(var i = 0; i < linePics.length; i++) {\r\n\t\t\tif(linePics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(linePics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tfor(var i = 0; i < barPics.length; i++) {\r\n\t\t\tif(barPics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(barPics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"white\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"black\"\r\n\t} else {\r\n\t\tcloseAllScreenshots();\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"rgba(255,255,255,0.4)\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"white\"\r\n\t}\r\n}", "function overviewImgClick(e){\n\tvar i,j,tname,turl,item,c,li,\n\t\ttarget = e.target || e.srcElement,\n\t\ttype = default_types_1,\n\t\tpremium;\n\n\tturl = target.u;\n\n\t//디폴트 타입에서 필요 li 검색\n\tfor (i = 0; i < type.length; i++) {\n\t\ttname = type[i].n;\n\t\tif (tname === turl) {\n\t\t\titem = type[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!item)\n\t\treturn;\n\n\t// click 된 overview Image Name을 가지고 온다.\n\titem.imgName = target.childNodes[0].innerHTML;\n\n\titem.over = true;\n\tactiveMainLi(item, false);\n}", "displayImages() {\n observeDocument(node => this.displayOriginalImage(node));\n qa('iframe').forEach(iframe => iframe.querySelectorAll('a[href] img[src]').forEach(this.replaceImgSrc));\n }", "function loadingMainImgAfterLocationIsSelected(id){\r\n\tselectElement(id).innerHTML = \"<img src='layout/img/Design/what-is-on-the-menu-is.png' class='img-responsive img-rounded center-block' alt='' title='loading'/>\";\r\n}", "function updateScreenshotTable(vmsData) {\n\n // disable auto-refresh there are too many VMs\n IMAGE_REFRESH_ENABLE = Object.keys(vmsData).length <= IMAGE_REFRESH_THRESHOLD;\n\n var imageUrls = Object.keys(lastImages);\n for (var i = 0; i < imageUrls.length; i++) {\n if (lastImages[imageUrls[i]].used === false) {\n delete lastImages[imageUrls[i]];\n } else {\n lastImages[imageUrls[i]].used = false;\n }\n }\n\n // Create the HTML element for each screenshot block\n // img has default value of null (http://stackoverflow.com/questions/5775469/)\n var model = $(' \\\n <td> \\\n <a class=\"connect-vm-wrapper\" target=\"_blank\"> \\\n <div class=\"thumbnail\"> \\\n <img src=\"images/ss_unavailable.svg\" style=\"width: 300px; height: 225px;\"> \\\n <div class=\"screenshot-state\"></div> \\\n <div class=\"screenshot-label-host grey\"></div> \\\n <div class=\"screenshot-label grey\"></div> \\\n <div class=\"screenshot-connect grey\">Click to connect</div> \\\n </div> \\\n </a> \\\n </td> \\\n ');\n\n // Fill out the above model for each individual VM info and push into a list\n var screenshotList = [];\n for (var i = 0; i < vmsData.length; i++) {\n var toAppend = model.clone();\n var vm = vmsData[i];\n\n toAppend.find(\"h3\").text(vm.name);\n //toAppend.find(\"a.connect-vm-button\").attr(\"href\", connectURL(vm));\n toAppend.find(\"a.connect-vm-wrapper\").attr(\"href\", connectURL(vm));\n toAppend.find(\"img\").attr(\"data-url\", screenshotURL(vm, 300));\n toAppend.find(\".screenshot-state\").addClass(COLOR_CLASSES[vm.state]).html(vm.state);\n toAppend.find(\".screenshot-label\").html(vm.name);\n toAppend.find(\".screenshot-label-host\").html(\"Host: \" + vm.host);\n //if (vm.type != \"kvm\") toAppend.find(\".connect-vm-button\").css(\"visibility\", \"hidden\");\n\n screenshotList.push({\n \"name\": vm.name,\n \"host\": vm.host,\n \"state\": vm.state,\n \"model\": toAppend.get(0).outerHTML,\n \"vm\": vm,\n });\n }\n\n // Push the list to DataTable\n if ($.fn.dataTable.isDataTable(\"#screenshots-list\")) {\n var table = $(\"#screenshots-list\").dataTable();\n table.fnClearTable(false);\n if (screenshotList.length > 0) {\n table.fnAddData(screenshotList, false);\n }\n table.fnDraw(false);\n } else {\n var table = $(\"#screenshots-list\").DataTable({\n \"autoWidth\": false,\n \"paging\": true,\n \"lengthChange\": true,\n \"lengthMenu\": [\n [12, 24, 48, 96, -1],\n [12, 24, 48, 96, \"All\"]\n ],\n \"pageLength\": 12,\n \"data\": screenshotList,\n \"columns\": [\n { \"title\": \"Name\", \"data\": \"name\", \"visible\": false },\n { \"title\": \"State\", \"data\": \"state\", \"visible\": false },\n { \"title\": \"Host\", \"data\": \"host\", \"visible\": false },\n { \"title\": \"Model\", \"data\": \"model\", \"searchable\": false },\n { \"title\": \"VM\", \"data\": \"vm\", \"visible\": false, \"searchable\": false },\n ],\n \"createdRow\": loadOrRestoreImage,\n \"stateSave\": true,\n \"stateDuration\": 0\n });\n }\n}", "function loadOrRestoreImage (row, data, displayIndex) {\n // Skip if it is a container-type VM\n if (data.vm.type === \"container\") {\n return;\n }\n\n var img = $('img', row);\n var url = img.attr(\"data-url\");\n\n if (Object.keys(lastImages).indexOf(url) > -1) {\n img.attr(\"src\", lastImages[url].data);\n lastImages[url].used = true;\n }\n\n var requestUrl = url + \"&base64=true\" + \"&\" + new Date().getTime();\n\n $.get(requestUrl)\n .done(function(response) {\n lastImages[url] = {\n data: response,\n used: true\n };\n\n img.attr(\"src\", response);\n })\n .fail(function( jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.warn( \"Request Failed: \" + err );\n });\n}", "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "function imageClicked() {\n var currentSource = $(this).attr('src');\n var altSource = $(this).attr('data-src');\n $(this).attr('src', altSource);\n $(this).attr('data-src', currentSource);\n }", "function mouseoverHandler() {\n $('.node').mouseover(function(e) { // mouseover event handler\n toggleSidebar();\n var info = this.id.split('|');\n var title = info[0];\n var code = info[1];\n pageTitle.html(title);\n if (code in queryInfo) {\n pageImage.html('<img src=' + queryInfo[code].url +\n ' style=\"border:solid 2px #666; background-color: #fff\">');\n pageExtract.html(queryInfo[code].extract);\n } else {\n getImageAndExtract(title, code, this);\n }\n });\n $('.node').mouseout(function(e) {\n clearSidebar();\n });\n externalLink();\n}", "function toggleImgOver(e) {\n if(!e) e=event;\n\n if( e.type == \"mouseover\" ) {\n this.src = this.src.replace( g_strOut_ext, g_strOver_ext );\n }\n if( e.type == \"mouseout\" ) {\n this.src = this.src.replace( g_strOver_ext,g_strOut_ext );\n }\n}", "function initScreenshotDataTable() {\n var path = window.location.pathname;\n path = path.substr(0, path.indexOf(\"/tilevnc\"));\n\n updateJSON(path+\"/vms/info.json\", updateScreenshotTable);\n\n if (IMAGE_REFRESH_TIMEOUT > 0) {\n setInterval(function() {\n if (IMAGE_REFRESH_ENABLE) {\n updateJSON(path+\"/vms/info.json\", updateScreenshotTable);\n }\n }, IMAGE_REFRESH_TIMEOUT);\n }\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 previewEvents()\n\t{\n\t\tvar current = jQuery(s_selector).find('.item.current');\n\t\tvar node_id = current.attr('node');\n\t\t\n\t\tif (data[node_id] && !data[node_id].video && data[node_id].b_img)\n\t\t{\n\t\t\tjQuery(p_selector).find('img.preview').css('cursor', 'pointer').click(function(event) {\n\t\t\t\tevent = event || window.event;\n\t\t\t\tvar node = event.target || event.srcElement;\n\t\t\t\t\n\t\t\t\tonShowFullImage(node);\n\t\t\t});\n\t\t}\n\t}", "function updateDraftIcon(treeId)\r\n{\r\n document.getElementById(\"draftLeafHeaderIcon\").style.display = \"inline\";\r\n $('#draftLeafUpdateImage').attr('src',baseUrl+'images/draft_icon_green.png');\r\n}", "function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }", "function imagezIndex(){\n\tvar viewImage = Alloy.createController('imagezIndex', {}).getView();\n\tviewImage.open();\n}", "function showImage(event) {\n\tresetClassNames(); // Klasu \"selected\" treba da ima onaj link cija je slika trenutno prikazana u \"mainImage\" elementu.\n\t\t\t\t\t // Pre stavljanja ove klase na kliknuti link, treba da sklonimo tu klasu sa prethodno kliknutog linka. To onda\n\t\t\t\t\t // postizemo tako sto sklonimo sve klase sa svih linkova, i time smo sigurni da ce i klasa \"selected\" biti uklonjena.\n\tthis.className = \"selected\"; // Stavljamo klasu \"selected\" na kliknuti link.\n\tmainImage.setAttribute(\"src\", this.getAttribute(\"href\")); // Atribut \"src\" elementa \"mainImage\" menjamo tako da postane jednak \"href\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // atributu kliknutog linka. A kako se u \"href\" atributu linka nalazi putanja\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // ka slici, postavljanjem \"src\" atributa na tu putanju, unutar elementa\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // \"mainImage\" ce se prikazati slika iz linka na koji se kliknulo.\n\tevent.preventDefault(); // Na ovaj nacin sprecavamo defoltno ponasanje browser-a, kojim bi se slika iz linka otvorila zasebno.\n\tscale = 1; // Nakon promene slike treba da vratimo zoom nivo na 1, da novoprikazana slika ne bi bila zumirana.\n\tsetScale(); // Kako smo u liniji iznad promenili vrednost \"scale\" globalne promenljive, potrebno je pozvati funkciju \"setScale\", koja onda\n\t\t\t\t// uzima vrednost promenljive \"scale\" i integrise je u CSS.\n\tleftPos = 0; // Nakon promene slike treba da vratimo sliku u inicijalnu poziciju.\n\tsetPosition(); // Kako smo u liniji iznad promenili vrednost \"leftPos\" globalne promenljive, potrebno je pozvati funkciju \"setPosition\"\n\t\t\t\t // koja onda uzima vrednost promenljive \"leftPos\" i integrise je u CSS.\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get DIDs of those who have confirmed the given claim entries
getConfirmerIds(req, res) { const claimEntryIds = req.body.claimEntryIds ClaimService.retrieveConfirmersForClaimsEntryIds(claimEntryIds) .then(results => hideDidsAndAddLinksToNetwork(res.locals.tokenIssuer, results)) .then(results => { res.json({ data: results }).end() }) .catch(err => { console.error(err); res.status(500).json(""+err).end() }) }
[ "ListOfAuthorizedDeferredPaymentAccountForThisCustomer() {\n let url = `/me/paymentMean/deferredPaymentAccount`;\n return this.client.request('GET', url);\n }", "function getActiveUsersIds(channel_members){\n var ids_to_be_returned = [];\n if(channel_members){\n var y;\n for(y in channel_members){\n if(channel_members[y].ChannelUser.active === true){\n ids_to_be_returned.push(channel_members[y].id);\n }\n }\n }\n return ids_to_be_returned;\n}", "function getUserIdsFromCertifierIds(certifier_ids) {\n var user_ids = [];\n certifier_ids.forEach(function(certifier_id) {\n if (isLongUserId(certifier_id)) {\n user_ids.push(certifier_id);\n }\n else if (isLongRoleId(certifier_id)) {\n var auth_member_ids = getUserIdsFromRoleId(certifier_id);\n user_ids = user_ids.concat(auth_member_ids);\n }\n else {\n __.requestError('This function only accepts long user ids and long role ids.', 500);\n }\n });\n return _.uniq(user_ids)\n}", "function getclaimedrecordslist() {\n StaticDataFactory.GetClaimedRecordsList().then(function (data) {\n if(data === undefined)\n {\n return;\n }\n vm.claimedRecords = data.claimedrecords;\n });\n }", "function getInactiveUsersIds(channel_members){\n var ids_to_be_returned = [];\n if(channel_members){\n var y;\n for(y in channel_members){\n if(channel_members[y].ChannelUser.active === false){\n ids_to_be_returned.push(channel_members[y].id);\n }\n }\n }\n return ids_to_be_returned;\n}", "function getIDCards(req, res, next) {\n if (!req.decoded) {\n return next(new errs.ForbiddenError('Current user does not have access to the requested resource.'));\n }\n\n if (req.decoded.userId !== req.params.userId) {\n return next(new errs.ForbiddenError('Current user does not have access to the requested resource.'));\n }\n\n return IDCard.find({ userId: req.params.userId })\n .then(presentIDCards.bind(null))\n .then((presentedIDCards) => {\n res.send(presentedIDCards);\n return next();\n });\n}", "ListOfContractsSignedBetweenYouAndOVH(agreed, contractId) {\n let url = `/me/agreements?`;\n const queryParams = new query_params_1.default();\n if (agreed) {\n queryParams.set('agreed', agreed.toString());\n }\n if (contractId) {\n queryParams.set('contractId', contractId.toString());\n }\n return this.client.request('GET', url + queryParams.toString());\n }", "getInterestIDsByType(userID) {\n const user = this._collection.findOne({ _id: userID });\n const interestIDs = [];\n interestIDs.push(user.interestIDs);\n let careerInterestIDs = [];\n _.map(user.careerGoalIDs, (goalID) => {\n const goal = CareerGoals.findDoc(goalID);\n careerInterestIDs = _.union(careerInterestIDs, goal.interestIDs);\n });\n careerInterestIDs = _.difference(careerInterestIDs, user.interestIDs);\n interestIDs.push(careerInterestIDs);\n return interestIDs;\n }", "function verifyIdToken(idToken, clientId, schoolDomain) {\n\tconst promise = new Parse.Promise();\n\tconst client = new auth.OAuth2(clientId, '', '');\n\tclient.verifyIdToken(idToken, clientId, function(err, loginInfo) {\n\t\t// If there's an error or we need to limit to a schoolDomain...\n\t\tif (err) {\n\t\t\tconsole.log(\"Verification stack trace: \" + err.stack);\n\t\t\tconst errorCode = Parse.Error.OTHER_CAUSE;\n\t\t\tconst error = new Parse.Error(errorCode, \"Error validating token.\");\n\t\t\tpromise.reject(error);\n\t\t} else if (schoolDomain\n\t\t\t&& loginInfo.getPayload()[\"hd\"] != schoolDomain) {\n\n\t\t\tconst errorCode = Parse.Error.INVALID_EMAIL_ADDRESS;\n\t\t\tconst error = new Parse.Error(errorCode, \"Please log in using an \" +\n\t\t\t\t\"@\" + schoolDomain + \" emailAddress.\");\n\t\t\tpromise.reject(error);\n\t\t} else {\n\t\t\tpromise.resolve(loginInfo.getPayload());\n\t\t}\n\t});\n\n\treturn promise;\n}", "function getIds(){\n let url = 'services/getIdsService.php';\n fetchFromJson(url)\n .then(processAnswer)\n .then(updateIds, errorIds);\n}", "getConfIds(dynamodb, params) {\n return new Promise((resolve, reject) => {\n console.log('params ', params);\n dynamodb.scan({\n TableName: \"MRM_Master\",\n ExpressionAttributeValues: {\n \":regions\": {\n S: params.regions\n },\n \":country\": {\n S: params.country\n },\n \":loc\": {\n S: params.loc\n },\n \":building\": {\n N: params.building\n },\n \":floor\": {\n N: params.floor\n }\n },\n FilterExpression: \"regions = :regions and \" +\n \"country = :country and \" +\n \"loc = :loc and \" +\n \"building = :building and \" +\n \"floor = :floor \",\n ProjectionExpression: \"id\"\n }, function(error, data) {\n if (error) {\n reject(error);\n }\n resolve(data.Items);\n })\n });\n }", "function dbResults(completedCourses = [], registeringTo = []) {\n let counter = 0;\n const preReqNotCompleted = [];\n for (let i = 0; i < registeringTo.length; i += 1) {\n for (let j = 0; j < completedCourses.length; ) {\n if (registeringTo[i].dependencies.pre !== completedCourses[j]) {\n // preReqCompleted[counter] = registeringTo[i];\n // counter += 1;\n counter += 1;\n if (counter >= completedCourses.length) {\n preReqNotCompleted.push(registeringTo[i]);\n }\n } else {\n j += 1;\n }\n }\n }\n return preReqNotCompleted;\n}", "function getSignalValuesFromIDs(signalIDList, data){\r\n var retArray = [];\r\n\r\n for (sigIdIdx = 0; sigIdIdx < signalIDList.length; sigIdIdx++){\r\n var found = false;\r\n for (i = 0; i < data.signals.length; i++) {\r\n var signal = data.signals[i];\r\n if (signal.samples.length > 0) {\r\n if (signal.id == signalIDList[sigIdIdx]) {\r\n found = true;\r\n retArray.push(signal.samples[signal.samples.length - 1].val);\r\n break;\r\n }\r\n }\r\n }\r\n if(found == false){\r\n retArray.push(null);\r\n }\r\n }\r\n return retArray;\r\n}", "async function getIdentities() {\n const identities = await Identity.find(\n {},\n '-_id publicKey createdDate',\n ).lean();\n return identities;\n}", "function checkProcessedQuests() {\n let counter = 0;\n db.collection(\"Student_Quests\")\n .where(\"Quest_Participant_IDs\", \"array-contains\", userID)\n .get()\n .then((querySnapshot) => {\n querySnapshot.forEach(doc => {\n if (doc.data().Quest_Status == \"approved\" || doc.data().Quest_Status == \"rejected\") {\n counter++;\n }\n })\n if (counter != 0) {\n enableProcessedQuests();\n }\n })\n .catch((error) => {\n console.log(\"Error getting processed quests: \", error);\n });\n}", "function getUserIdentifications(userDB){\n return userDB.allDocs({\n include_docs : true,\n startkey: 'id',\n endkey: 'id\\ufff0'\n }).then(function(docs){\n return docs.rows;\n });\n}", "function filterDeletedItem(arrayOfItemsPromise) {\n return Promise.all(arrayOfItemsPromise)\n .then((data) => data.filter(item => !item.deleted))\n}", "genRequestedClaims({ claims, context, extraParams }) {\n return Promise.all(\n Object.keys(claims).map(x => {\n let name = x;\n let claim = claims[x];\n\n if (Array.isArray(claims[x])) {\n [name, claim] = claims[x];\n }\n\n if (typeof this[name] === 'function') {\n return this[name]({ claim, context, extraParams });\n }\n\n throw new Error(`Unsupported claim type ${name}`);\n })\n );\n }", "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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new ``uint8`` type for %%v%%.
static uint8(v) { return n(v, 8); }
[ "static bytes8(v) { return b(v, 8); }", "static uint(v) { return n(v, 256); }", "static int8(v) { return n(v, -8); }", "static uint88(v) { return n(v, 88); }", "static uint24(v) { return n(v, 24); }", "static uint240(v) { return n(v, 240); }", "static uint256(v) { return n(v, 256); }", "static uint168(v) { return n(v, 168); }", "static bytes24(v) { return b(v, 24); }", "static uint80(v) { return n(v, 80); }", "static bytes(v) { return new Typed(_gaurd, \"bytes\", v); }", "static uint112(v) { return n(v, 112); }", "static bytes9(v) { return b(v, 9); }", "static uint160(v) { return n(v, 160); }", "static uint208(v) { return n(v, 208); }", "function UInt32toUInt8(value) {\n console.log(value);\n t = [\n value >> 24,\n (value << 8) >> 24,\n (value << 16) >> 24,\n (value << 24) >> 24\n ];\n console.log(t);\n return t;\n}", "static uint56(v) { return n(v, 56); }", "static uint72(v) { return n(v, 72); }", "static bytes7(v) { return b(v, 7); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add functionality to delete buttons created with the tasks
function addDeleteBtns() { let deleteTasks = document.querySelectorAll('input[type="image"]'); deleteTasks.forEach( task => { task.addEventListener('click', (e) => { let selectedId = e.target.dataset.id; //Select trash image id that was clicked let selectedTask = toDoList.findIndex(todo => todo.Id === parseInt(selectedId)); //Find the index of the selected id in the list of task objects toDoList.splice(selectedTask, 1); //Remove that object displayTasks(toDoList); localStorage.setItem('Tasks', JSON.stringify(toDoList)); }); } ); }
[ "'click .delete'() {\n\t\tMeteor.call('tasks.remove', this._id, (error) => {\n\t\t\tif (error)\n\t\t\t\tBert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );\n\t\t\telse\n\t\t\t\tBert.alert( 'Task removed successfully!', 'success', 'growl-top-right' );\n\t\t});\n\t}", "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}", "createDeleteButton(index) {\n let scope = this;\n let deleteButtonElement = document.createElement('button');\n deleteButtonElement.className = cssConstants.ICON + ' ' + cssConstants.EDITOR_FEATURE_DELETE;\n deleteButtonElement.title = langConstants.EDITOR_FEATURE_DELETE;\n deleteButtonElement.setAttribute('feat_id', index);\n jQuery(deleteButtonElement).click(function(event) {\n scope.showDeleteDialog(event.target.getAttribute('feat_id'));\n });\n return deleteButtonElement;\n }", "function removeDeleteButtons() {\n\tYUI().use('node', function (Y) {\n\t\tvar allButtons = Y.all('.lfr-ddm-repeatable-delete-button');\n\t\tallButtons.remove();\n\t});\n}", "function openDeleteLists() {\n // Hide the edit lists\n document.getElementById(\"pagesList\").style.display = \"none\";\n document.getElementById(\"stylesList\").style.display = \"none\";\n document.getElementById(\"scriptsList\").style.display = \"none\";\n // Display the delete lists\n document.getElementById(\"delPagesList\").style.display = \"block\";\n document.getElementById(\"delStylesList\").style.display = \"block\";\n document.getElementById(\"delScriptsList\").style.display = \"block\";\n // Edit text\n document.getElementById(\"instructionText\").childNodes[1].textContent = \"Select a file to delete.\";\n // Get delete button and change the event listener\n document.getElementById(\"delete\").textContent = \"Cancel\";\n document.getElementById(\"delete\").removeEventListener(\"click\", openDeleteLists)\n document.getElementById(\"delete\").addEventListener(\"click\", openEditLists)\n // Change background to show status change\n document.getElementById(\"pageContent\").style.backgroundColor = \"#ababab\";\n document.getElementById(\"pageTitle\").style.opacity = \"0.4\";\n document.getElementById(\"createNewFile\").style.opacity = \"0.4\";\n\n console.log(\"HUB: Deletion tool active\");\n}", "function newTask(task)\n {\n var line=document.createElement('div'); line.classList.add('row','col-sm-12','justify-content-center'); \n tasks.appendChild(line);\n\n var lineText=document.createElement('h2'); lineText.innerHTML=task; //whatever input was\n line.appendChild(lineText);\n\n var lineButton=document.createElement('button'); lineButton.innerHTML=\"DONE\"; //inner=can include strong, etc. within text\n lineButton.setAttribute('type', 'button'); //syntax stuff\n line.appendChild(lineButton);\n\n /* INDIVIDUAL TASK BUTTON EVENT */\n //=this way, you can use each of the button's local info to know which button does what, rather than having variables for each (which is hard to automate anyway) \n lineButton.addEventListener('click', function()\n {\n tasks.removeChild(line); //remove the div+all w/in it\n });\n }", "function viewTaskdeleteThisTask() {\r\n if (confirm(\"You are about to delete this task?\")) {\r\n // Get taskobject === clicked taskCard\r\n TempLocalStorageTaskArray = getLocalStorage(\"task\");\r\n tempIndex = TempLocalStorageTaskArray.findIndex(obj => obj.name === viewTaskTitleDiv.innerHTML);\r\n //delete from localstorage where thisTask === \"task\".name\r\n // finn index og splice fra array\r\n TempLocalStorageTaskArray.splice(tempIndex, 1);\r\n setLocalStorage(\"task\", TempLocalStorageTaskArray);\r\n } else {\r\n console.log('no task was deleted');\r\n }\r\n\r\n\r\n}", "function setupDeleteButtons() {\n const successSnackbar = \n new MDCSnackbar(document.getElementById('delete-success-snackbar'));\n const failureSnackbar = \n new MDCSnackbar(document.getElementById('delete-failure-snackbar'));\n \n const onSuccessfulDelete = () => {\n refreshShortlinks();\n successSnackbar.open();\n }\n\n const onFailedDelete = (reason) => {\n failureSnackbar.labelText = 'Failed to delete shortlink: ' + reason;\n failureSnackbar.open();\n }\n\n const deleteButtons = \n Array.from(document.querySelectorAll('.shortlink-delete'));\n deleteButtons.forEach((button) => {\n button.addEventListener('click', () => {\n ShortlinkMessenger.sendDeleteMessage(button.dataset.toDelete)\n .then(onSuccessfulDelete, onFailedDelete);\n });\n });\n}", "function addDeleteButtons(el, siblings) {\n\tif (siblings === 'before' || siblings === 'both') {\n\t\tel.append('<a class=\"lfr-ddm-repeatable-delete-button icon-minus-sign\" href=\"javascript:;\"></a>');\n\t}\n}", "function deleteView(superviseesData) {\n var deleteIcon = app.getElement(\".icon_delete\");\n\n for (var i = 0; i < deleteIcon.length; i++) {\n deleteIcon[i].addEventListener(\"click\", function() {\n empId = this.getAttribute(\"data-emp\");\n app.modalDisplayTrue(deleteModalView);\n deleteModalText.innerHTML = \"Confirm Delete?\";\n app.modalDisplayTrue(deleteYes);\n app.modalDisplayTrue(deleteNo);\n okDeleteBtn.classList.add(\"display_none\");\n registerDeleteEvent(superviseesData, empId);\n });\n }\n }", "deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }", "function addButtons() {\n target.css({\n 'border-width': '5px'\n });\n //console.log(\"INSIDE addButtons, thisID: \" + thisId + \" and thisKittenId: \" + thisKittenId);\n // append the delete and edit buttons, with data of metric document id, and kitten document id\n target.append(\"<button type='button' class='btn btn-default btn-xs littleX' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>\");\n target.append(\"<button type='button' class='btn btn-default btn-xs littleE' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button>\");\n // set boolean to true that delete and edit buttons exist\n littleButton = true;\n }", "function addRequiredRenewalFormDeleteButtons(){\n\tif(('#requiredRenewalFormsTable thead tr th').length == 2){\n\t\t$('#requiredRenewalFormsTable thead tr').append(\"<th>&nbsp;</th>\");\n\t}\n\t$('#requiredRenewalFormsTable tbody tr').each(function(index){\n\t\tvar id = this.children[0].innerText.trim();\n\t\tvar del = getRequiredRenewalFormDeleteButton(index);\n\t\t$(this).append(del);\n\t\tvar buttonId = \"#remoteDeleteRequiredRenewalForm\" + index;\n\t\t$(buttonId).bind('click', function(){\n\t \t\t$.ajax({\n\t \t\t\turl: '/dcmd/contract/removeFromRequiredRenewalForms',\n\t \t\t\tdata: getRequiredRenewalFormParamsToRemove(id),\n\t \t\t\ttype: 'POST',\n\t \t\t\tsuccess: refreshRequiredRenewalFormData,\n\t \t\t\terror: function(jqXHR, textStatus, errorThrown){\n\t \t\t\t\talert('The removal of form/doc was not complete.');\n\t \t\t\t\talert(errorThrown);\n\t \t\t\t}\n\t \t\t});\n\t\t});\n\t});\n}", "function deleteButton() {\n const idToDelete = $(this)\n .parent()\n .attr('data-id');\n console.log(idToDelete);\n\n API.deleteBill(idToDelete).then(() => {\n refreshBillList();\n });\n}", "function confirmDeleteAndRefresh() {\n View.confirm(getMessage(\"confirmPtaskDelete\"), function (button) {\n if (button === 'yes') {\n var panel = pgnavPageEditorController.assignedTasksGrid;\n if (panel != null && panel.selectedRowIndex >= 0) {\n var parameters = {\n viewName: panel.viewDef.viewName,\n groupIndex: (typeof panel.viewDef.tableGroupIndex === 'undefined') ? 0 : panel.viewDef.tableGroupIndex,\n controlId: (typeof panel.panelId === 'undefined') ? panel.id : panel.panelId,\n version: Ab.view.View.version,\n dataSourceId: panel.dataSourceId\n };\n\n var row = panel.rows[panel.selectedRowIndex];\n if (row != null) {\n var pKeyValues = panel.getPrimaryKeysForRow(row);\n parameters.fieldValues = toJSON(pKeyValues);\n }\n\n var wfrResult = Ab.workflow.Workflow.runRuleAndReturnResult('AbCommonResources-deleteDataRecords', parameters);\n if (wfrResult.code !== 'executed') {\n Ab.workflow.Workflow.handleError(wfrResult);\n }\n }\n\n pgnavPageEditorController.assignedTasksGrid.refresh();\n }\n });\n}", "function deleteClickListener() {\n\t\t$('.container').on('click', '.delete-submission', event => {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\tconst submission = $(event.currentTarget)\n\t\t\t\t.parents('.submission-thumb')\n\t\t\t\t.prop('id');\n\n\t\t\tif (\n\t\t\t\tconfirm(\n\t\t\t\t\t'Are you sure that you would like to permanently remove this submission?'\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tapi\n\t\t\t\t\t.remove(`/api/submissions/${submission}`)\n\t\t\t\t\t.then(() => {\n return api\n .search(`/api/users/mysubmissions`)\n .then(res => {\n $('#user-submissions').empty();\n store.userSubmissions = res;\n \n displayUserSubmissions(res);\n \t })\n });\n\t\t }\n });\n }", "function deleteButtonPressed(entity) {\n db.remove(entity);\n }", "function generateTaskListElements() {\n // getData();//For getting data\n var tabpr = document.getElementById('pr');//accessing parent table\n var newrw = document.createElement(\"tr\");//creating a new row\n var idrw = \"id\";\n var idname = \"fit\" + x;\n newrw.setAttribute(idrw, idname);//Id atteribute by variable name\n newrw.setAttribute(\"class\", \"nwrw\");\n tabpr.appendChild(newrw);//Appended into table\n //Creation of row columns and appending them\n var newcln = document.createElement(\"td\");\n newcln.setAttribute(\"class\", \"cl\");\n newrw.appendChild(newcln);\n var newcln = document.createElement(\"td\");\n newcln.setAttribute(\"class\", \"cl\");\n newrw.appendChild(newcln);\n var newcln = document.createElement(\"td\");\n newcln.setAttribute(\"class\", \"cl\");\n newrw.appendChild(newcln);\n //Creation of row functional buttons and appending them\n var newcln = document.createElement(\"td\");\n //IMP task button\n var impbtn = document.createElement(\"input\");\n impbtn.setAttribute(\"value\", \"IMP\");\n impbtn.setAttribute(\"type\", \"button\");\n impbtn.setAttribute(\"class\", \"tbBtn\");\n var impid = x;\n impbtn.setAttribute(\"id\", impid);\n impbtn.setAttribute(\"onClick\", \"impBtn(id);\");\n newcln.appendChild(impbtn);\n newrw.appendChild(newcln);\n //DEL task button\n var delbtn = document.createElement(\"input\");\n delbtn.setAttribute(\"value\", \"DEL\");\n delbtn.setAttribute(\"type\", \"button\");\n var dlid = x;\n delbtn.setAttribute(\"id\", dlid);\n delbtn.setAttribute(\"onClick\", \" delBtn(id);\");\n delbtn.setAttribute(\"class\", \"tbBtn\");\n newcln.appendChild(delbtn);\n newrw.appendChild(newcln);\n //Edit Task button\n var edtbtn = document.createElement(\"input\");\n edtbtn.setAttribute(\"value\", \"Edit\");\n edtbtn.setAttribute(\"type\", \"button\");\n var edtid = x;\n edtbtn.setAttribute(\"id\", edtid);\n edtbtn.setAttribute(\"class\", \"tbBtn\");\n edtbtn.setAttribute(\"onClick\", \" edtInterface(id);\");//edtInterface();\n newcln.appendChild(edtbtn);\n newrw.appendChild(newcln);\n x = x + 1;\n return x;\n}", "entryButtons() {\n\n document.querySelector(\".entryLog\").addEventListener(\"click\", event => {\n \n // Delete buttons\n if (event.target.id.startsWith(\"delete--\")) {\n const entryToDelete = event.target.id.split(\"--\")[1]\n\n API.deleteJournalEntry(entryToDelete)\n .then(() => API.getJournalEntries())\n .then(entryArray => journalList.renderJournalEntries(entryArray))\n }\n\n // Edit buttons\n if (event.target.id.startsWith(\"edit--\")) {\n const entryToEdit = event.target.id.split(\"--\")[1]\n\n showEntryForm()\n editFormFields(entryToEdit)\n }\n })\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
used to store the location where color is picked / Function checks which side's div is clicked and pop put the colorSelectBox with the position of the div popping out
function colorFieldPicker(onClickSide,side){ onClickSide.on('click', function(event){ //store the class of the colorHolder to a global variable colorHolder = $(this).attr('class'); var yVal = (event.clientY) + "px"; var xVal = (event.clientX) + "px"; $('.colorSelectBox').css({"left": xVal, "top": yVal}).toggle(); //empty the field where it says 'Click to choose colors' $(this).closest('div').find('.gradient').children().empty(); //var visible = $('.colorSelectBox').hasClass('visible'); //if(visible){ // $('.colorSelectBox').hide(); // $('.colorSelectBox').removeClass('visible'); //}else{ // $('.colorSelectBox').show(); // $('.colorSelectBox').addClass('visible'); //} colorPickerOnClick(side); }); }
[ "function userColorPicked(event) {\n clickColor = event.target.value;\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n}", "function selectedColor(color){\n\n color.addEventListener('click', e=>{\n eliminarSeleccion();\n e.target.style.border = '2px solid #22b0b0';\n\n // Agregar color seleccionado al input de color\n document.querySelector('input[name=color]').value = e.target.style.background;\n\n })\n}", "function userMoveColorPick(event) {\n moveColor = event.target.value;\n mouseMoveBtn.style.backgroundColor = moveColor;\n moveButton.style.backgroundColor = moveColor;\n}", "function clickColor(event) {\n const target = event.target;\n selectedColor = target.style.fill;\n}", "function toggleColorbox(e) {\n\tpx.$nav.classList.add('closed');\n\tif (!px.swatching) {\n\t\tpx.swatching = true;\n\t\t// select this color swatch\n\t\ttoggleSelected(e.target, px.$picker);\n\t\tpx.$body.classList.add('x');\n\t} else {\n\t\tpx.swatching = false;\n\t\t// unselect\n\t\ttoggleSelected({}, px.$picker);\n\t\tpx.$body.classList.remove('x');\n\t}\n\tpx.$colorbox.classList.toggle('closed');\n}", "function getSelectedColor(){\n\t\tselectedColor = $('#colorPicker').val();\n\t}", "function open_color_picker(clickedElementId, e)\n{\n\tif (is_saf)\n\t{\n\t\treturn;\n\t}\n\n\tif (!pickerReady)\n\t{\n\t\talert(vbphrase[\"color_picker_not_ready\"]);\n\t\treturn;\n\t}\n\t\n\tpickerElement = fetch_object(\"colorPicker\");\n\t\n\tif (activeElementId == clickedElementId && pickerElement.style.display != \"none\")\n\t{\n\t\tpickerElement.style.display = \"none\";\n\t}\n\telse\n\t{\t\t\n\t\tactiveElementId = clickedElementId;\n\t\tcolorElement = fetch_object(\"color_\" + clickedElementId);\n\t\tpreviewElement = fetch_object(\"preview_\" + clickedElementId);\n\t\t\n\t\t// initialize the preview swatches on the color picker\n\t\tfetch_object(\"oldColor\").style.background = previewElement.style.background;\n\t\tfetch_object(\"newColor\").style.background = previewElement.style.background;\n\t\tfetch_object(\"txtColor\").value = colorElement.value;\n\n\t\t// workaround for internet explorer (no one else supports window.event)\n\t\tif (!e)\n\t\t{\n\t\t\te = window.event;\n\t\t}\n\n\t\t// get the colorPicker's position\n\t\tif(typeof(e.pageX) == \"number\")\n\t\t{\n\t\t\txpos = e.pageX;\n\t\t\typos = e.pageY;\n\t\t}\n\t\telse if (typeof(e.clientX) == \"number\")\n\t\t{\n\t\t\txpos = e.clientX + document.documentElement.scrollLeft;\n\t\t\typos = e.clientY + document.documentElement.scrollTop;\n\t\t}\n\t\t\n\t\t// offset a little\n\t\txpos += 10;\n\t\typos += 5;\n\t\t\n\t\t// reposition colorPicker if result of click + box width is off the page\n\t\tif ((xpos + colorPickerWidth) >= document.body.clientWidth)\n\t\t{\n\t\t\txpos = document.body.clientWidth - colorPickerWidth - 5;\n\t\t}\n\t\t\n\t\t// set the colorPicker's position\n\t\tpickerElement.style.left = xpos + \"px\";\n\t\tpickerElement.style.top = ypos + \"px\";\n\t\t\n\t\t// show the colorPicker\n\t\tpickerElement.style.display = \"\";\n\t}\n}", "function setupColorControls()\n{\n dropper.onclick = () => setDropperActive(!isDropperActive()) ;\n color.oninput = () => setLineColor(color.value);\n colortext.oninput = () => setLineColor(colortext.value);\n\n //Go find the origin selection OR first otherwise\n palettedialog.setAttribute(\"data-palette\", getSetting(\"palettechoice\") || Object.keys(palettes)[0]);\n\n palettedialogleft.onclick = () => { updatePaletteNumber(-1); refreshPaletteDialog(); }\n palettedialogright.onclick = () => { updatePaletteNumber(1); refreshPaletteDialog(); }\n refreshPaletteDialog();\n}", "function surroundingEyeDropper(evt) {\n\t// only do this if the eye dropper is the selected tool\n\tif (document.getElementById(\"eyeDropper\").checked) {\n\t\t// figure out which canvas you're in and get its context\n\t\tvar myCanvas = evt.target;\n\t\tvar myContext = myCanvas.getContext(\"2d\");\n\t\t// get click coordinates in this canvas\n\t\tvar dropperCoords = myCanvas.getBoundingClientRect();\n\t\tvar mouseX = evt.clientX - dropperCoords.left;\n\t\tvar mouseY = evt.clientY - dropperCoords.top;\n\t\t// do not need to adjust for zoom/pan, because the function that reads\n\t\t// the color data uses the current context, not the pre-zoom/pan context\n\t\t// get the color at that pixel in that region\n\t\tvar color = getColorAt(myContext, mouseX, mouseY);\n\t\t// set this as the color choice\n\t\tsetColorChoiceInHTML(color);\n\t} // else do nothing\n}", "function pickUpColor (event) {\n paintBrush = event.target.innerText;\n}", "_onHandlerClick(id, e) {\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent(\"selected-color\", { bubbles: false, detail: { id } })\n\t\t);\n\t}", "function render_select(context)\n{\n\tif(selection_coordinates != null)\n\t{\n\t\tstroke_tile(selection_coordinates.x, selection_coordinates.y, grid_selected_color, context);\n\t}\n}", "function showcolor(){\n let getColorSelected = document.querySelector(\"#colors-selection\").value; //get color selected value\n console.log(getColorSelected)\n if(getColorSelected == null || getColorSelected == undefined){ //set default value if user don't choose the color\n return selectedArticle[0]\n } else {\n selectedArticle[\"selectedColor\"]=getColorSelected;\n console.log(selectedArticle)\n }\n }", "function chwColorChooser(property){\n this.property = property;\n this.element = document.getElementById('chw' + this.property + 'Input');\n this.customGroup = document.getElementById('chw' + this.property + 'CustomGroup');\n this.custom = document.getElementById('chw' + this.property + 'CustomInput');\n this.customOption = document.getElementById('chw' + this.property + 'CustomOption');\n /*\n The color code that replaces the value entered\n by the user, if that vakue is wrong\n */\n this.storedColorCode = \"#000000\";\n /*\n Choice of color changed\n */\n this.colorChoiceChanged = function(){\n if (this.element.value.indexOf('#') == 0){\n this.customGroup.style.display=\"inline\";\n }\n else {\n this.customGroup.style.display=\"none\";\n }\n }\n\n /*\n Show the color with the color code the user entered\n */\n this.showCustomColor = function(){\n if (this.custom.value.match(\"^#(([0-9a-fA-F][9a-fA-F][0-9a-fA-F])|((([0-9a-fA-F]{2})[9a-fA-F]([0-9a-fA-F]){3})))$\")){\n// if (this.custom.value.match(\"^#(([9a-fA-F]{3})|(([9a-fA-F][0-9a-fA-F]){3}))$\")){\n this.custom.style.backgroundColor = this.custom.value;\n this.custom.style.color = \"#000\";\n }\n else if (this.custom.value.match(\"^(([0-9a-fA-F][9a-fA-F][0-9a-fA-F])|((([0-9a-fA-F]{2})[9a-fA-F]([0-9a-fA-F]){3})))$\")){\n// else if (this.custom.value.match(\"^(([9a-fA-F]{3})|(([9a-fA-F][0-9a-fA-F]){3}))$\")){\n this.custom.style.backgroundColor = '#' + this.custom.value;\n this.custom.style.color = \"#000\";\n }\n else if(this.custom.value.match(\"(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)\")){\n this.custom.style.backgroundColor = this.custom.value;\n this.custom.style.color = \"#FFF\";\n }\n else if(this.custom.value.match(\"(^[0-9a-fA-F]{3}$)|(^[0-9a-fA-F]{6}$)\")){\n this.custom.style.backgroundColor = '#' + this.custom.value;\n this.custom.style.color = \"#FFF\";\n }\n }\n\n /*\n Store the previeous color code, which is valid\n */\n this.customColorValueFocus = function(){\n this.storedColorCode = this.custom.value;\n }\n\n /*\n Validate the color code entered by the user\n */\n this.validateCustomColor = function(){\n var selectedFirst = this.element.selectedIndex;\n if(this.custom.value.match(\"^#[0-9a-fA-F]{3}$\")){\n this.customOption.value = '#' + this.custom.value.charAt(1) + this.custom.value.charAt(1) +\n this.custom.value.charAt(2) + this.custom.value.charAt(2) +\n this.custom.value.charAt(3) + this.custom.value.charAt(3);\n }\n else if(this.custom.value.match(\"^[0-9a-fA-F]{3}$\")){\n this.customOption.value = '#' + this.custom.value.charAt(0) + this.custom.value.charAt(0) +\n this.custom.value.charAt(1) + this.custom.value.charAt(1) +\n this.custom.value.charAt(2) + this.custom.value.charAt(2);\n }\n else if(this.custom.value.match(\"^[0-9a-fA-F]{6}$\")){\n this.customOption.value = '#' + this.custom.value;\n }\n else if(this.custom.value.match(\"^#[0-9a-fA-F]{6}$\")){\n this.customOption.value = this.custom.value;\n }\n else{\n this.custom.value = this.storedColorCode;\n this.showCustomColor();\n return false;\n }\n this.element.selectedIndex = selectedFirst;\n }\n this.showCustomColor();\n}", "function addToSelectedColors(color) {\n if (selectedColors.length < maxNumberOfSelectedColors) {\n selectedColorsList.innerHTML = '';\n\n selectedColors.push(color);\n\n selectedColors.forEach(function(color, index) {\n var slicedColor = color.slice(4, -1);\n\n var selectedColorHTML = `<div class=\"selected-color\"><div class=\"selected-color-preview\"></div><div class=\"selected-color-info\"><p class=\"selected-color-value\">${slicedColor}</p><i class=\"selected-copy-btn fa fa-clipboard\" aria-hidden=\"true\"></i></div></div>`;\n selectedColorsList.insertAdjacentHTML('beforeend', selectedColorHTML);\n\n var createdSelectedColor = document.getElementsByClassName('selected-color')[index];\n createdSelectedColor.childNodes[0].style.backgroundColor = color;\n\n document.getElementsByClassName('selected-copy-btn')[index].addEventListener('click', copyToClipboard);\n\n document.getElementsByClassName('selected-color-preview')[index].addEventListener('click', removeSelectedColor);\n });\n\n document.getElementById('selected-colors-counter').innerText = selectedColors.length;\n\n selectedColorsDiv.style.display = 'block';\n }\n}", "function select_color() {\n\tvar selected_color = $(this).css('background-color');\n\t$('#selected-color.swatch').css('background-color', selected_color);\n}", "function mark_selected(block_number) {\n if (block_number === \" \") return;\n\n // Change color for selection of a new block\n for(row = 0; row < game_board.length; row++) {\n for (column = 0; column < game_board[row].length; column++) {\n var div_name = game_board[row][column];\n var child_div = document.getElementById(div_name);\n if(child_div.innerHTML == String(block_number)) {\n child_div.style.backgroundColor = selected_color; \n } else {\n child_div.style.backgroundColor = unselected_color;\n }\n }\n }\n // Write out the collected to our div\n var selected_span = document.getElementById('selected');\n selected_span.innerHTML = String(block_number);\n}", "function displayStackSelectionBox(row,column)\n{\n\tvar tile = map[row][column];\n\tvar stack = tile.stack;\n\t\n\tvar addMoveButton = 0;\n\tvar index = 0;\n\t//check to see if there's a select square here\n\tfor(var i=0;i<movementSquares.length;i++)\n\t{\n\t\tif(movementSquares[i].row == row && movementSquares[i].column == column)\n\t\t{\n\t\t\taddMoveButton = 1;\n\t\t\t\n\t\t}\n\t}\n\t\n\t//background\n\tvar stackSelectionBox = new createjs.Shape();\n\tstackSelectionBox.graphics.beginFill(\"DarkSlateGray\").drawRect(0, 0, 44, 25*(stack.length+addMoveButton));\n\tstackSelectionBox.x = 24*(column+1);\n\tstackSelectionBox.y = 50+24*row;\n\tstackSelectionBox.name = \"stackSelectionBox\";\n\tstage.addChild(stackSelectionBox);\n\t\n\tfor(var i=0;i<stack.length;i++)\n\t{\n\t\t//add button\n\t\tvar SSBButton = new Button(\"SSBButton\",24*(column+1)+20,52+24*row+24*i,20,20);\n\t\tSSBButton.name = \"SSBButton\"+i;\n\t\tSSBButton.text = \"<\";\n\t\tSSBButton.row = row;\n\t\tSSBButton.column = column;\n\t\tSSBButton.target = stack[i];\n\t\tSSBButton.handleButtonEvent = handleSSBBEvent;\n\t\tSSBButton.onClick = function()\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tdeSelectAll();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar tile = map[this.row][this.column]\n\t\t\t\t\t\t\t\tselectedObject = this.target;\n\t\t\t\t\t\t\t\tdisplaySelectBox(this.row,this.column);\n\t\t\t\t\t\t\t\tselectedObject.displayInfo(stage, player);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(isUnit(this.target) == true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = this.target;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0 && selectedUnit.color == player.color && player.onTurn == true)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tdisplayMovementSquares(this.row,this.column);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tSSBButton.draw();\n\t\t\n\t\t//add image\n\t\tvar objectImage = new Image();\n\t\tobjectImage.src = stack[i].image.src;\n\t\tobjectImage.yOffset = i;\n\t\tobjectImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar SSBImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tSSBImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tSSBImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tSSBImage.name = \"SSBImage\";\n\t\t\t\t\t\t\t\tstage.addChild(SSBImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\t\n\t\tindex++;\n\t}\n\t\n\tif(addMoveButton == 1)\n\t{\n\t\t//add move here button\n\t\tvar moveHereButton = new Button(\"moveHereButton\",24*(column+1)+20,52+24*row+24*index,20,20);\n\t\tmoveHereButton.name = \"moveHereButton\";\n\t\tmoveHereButton.text = \"<\";\n\t\tmoveHereButton.row = row;\n\t\tmoveHereButton.column = column;\n\t\t\n\t\tvar placeHolder = [];placeHolder.type = \"Move Here\";\n\t\t\n\t\tmoveHereButton.target = placeHolder;\n\t\tmoveHereButton.handleButtonEvent = handleSSBBEvent;\n\t\tmoveHereButton.onClick = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveSelectedUnit(this.row,this.column);\n\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdisplayMovementSquares(selectedUnit.row,selectedUnit.column);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tremoveMovementSquares();\n\t\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tmoveHereButton.draw();\n\t\t\n\t\t//add image\n\t\tvar moveHereImage = new Image();\n\t\tmoveHereImage.src = \"http://kev1shell.github.io/assets/sprites/other/moveHereSymbol.png\";\n\t\tmoveHereImage.yOffset = index;\n\t\tmoveHereImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar MHImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tMHImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tMHImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tMHImage.name = \"MHImage\";\n\t\t\t\t\t\t\t\tstage.addChild(MHImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t}\n\t\n\tcacheStage();\n\tstage.update();\n\t\n}", "wrapSelection() {\r\n let me = this;\r\n let minX = this.selectionRect.x + this.selectionRect.width;\r\n let minY = this.selectionRect.y + this.selectionRect.height;\r\n let maxX = this.selectionRect.x;\r\n let maxY = this.selectionRect.y;\r\n me.selectedComponents.forEach((component) => {\r\n let screenPos = me.getScreenCoords(component.bounds);\r\n minX = (screenPos.x <= minX) ? screenPos.x : minX;\r\n minY = (screenPos.y <= minY) ? screenPos.y : minY;\r\n maxX = (screenPos.x + component.bounds.width >= maxX) ? screenPos.x + component.bounds.width : maxX;\r\n maxY = (screenPos.y + component.bounds.height >= maxY) ? screenPos.y + component.bounds.height : maxY;\r\n });\r\n me.selectionRect = new createjs.Rectangle(minX, minY, maxX - minX, maxY - minY);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the user's phone number.
async function updatePhoneNumber(user, credential) { await _link$1((0, _util.getModularInstance)(user), credential); }
[ "function ChangePhone(username, newPhoneNum) {\n if (userIsExisting(username)) {\n var x = lib.UserJSON2Obj(user.LayRaMotUser(username));\n try {\n user.CapNhatThongTinUser(username, x.ten_user, x.ngay_sinh, x.gioi_tinh, newPhoneNum, x.email, x.pass);\n return true;\n } catch (ee) {\n return false;\n }\n }\n return false;\n}", "updateEmergencyPhoneNumber(username,phoneNumber){cov_idmd2e41v.f[15]++;cov_idmd2e41v.s[17]++;Citizen.updateOne({username:username},{phoneNumber:phoneNumber},err=>{cov_idmd2e41v.f[16]++;});}", "set PhonePad(value) {}", "resetPasswordWithPhone(phone, code, newPassword, callback) {\n newPassword = AccountsEx._hashPassword(newPassword);\n callback = ensureCallback(callback);\n Accounts.callLoginMethod({\n methodName: prefix + 'resetPasswordWithPhone',\n methodArguments: [{phone, newPassword, code}],\n userCallback: callback\n })\n }", "set NamePhonePad(value) {}", "function reversePhone(number) {\n \n }", "linkPhone(phone, code, password, callback) {\n password = AccountsEx._hashPassword(password);\n callback = ensureCallback(callback);\n return AccountsEx._linkPhone({type: 'default', phone, code, password}, callback);\n }", "function updateContacts(user, sphere, sessionData, view, res, req, isMobile){\n var contacts = sphere.getOtherMembers(user.id);\n\n // add the sphere members to invited user's contacts \n user.addSphereContacts(sphere.memberIds, function(members){\n\n sessionData.contacts = contacts;\n\n user.save(function(err){\n if(err){\n console.log(err);\n }else{\n //render feed \n if(isMobile == \"true\"){\n Session.respondJSON(res, sessionData);\n }else if(view == \"invite\"){\n res.redirect(\"/\");\n }else{\n Session.render(res, view, sessionData);\n }\n\n\n // store session data \n Session.storeData(req, sessionData);\n Session.sendCookie(res, user.email);\n }\n });\n sphere.save(function(err){console.log(err);})\n User.updateMemberContacts(members, user); \n }); \n}", "function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_success, updateUser_error);\n}", "createUserWithPhone(phone, code, password, callback) {\n password = AccountsEx._hashPassword(password);\n callback = ensureCallback(callback);\n Accounts.callLoginMethod({\n methodName: prefix + 'createUserWithPhone',\n methodArguments: [{phone, password, code}],\n userCallback: callback\n });\n }", "loginWithPhone(phone, password, callback) {\n password = AccountsEx._hashPassword(password);\n callback = ensureCallback(callback);\n Accounts.callLoginMethod({\n methodArguments: [{phonePassword: {phone, password}}],\n userCallback: callback\n })\n }", "SET_USER(state, data) {\n state.user.data = data;\n }", "_linkPhone(options, callback) {\n Meteor.call(prefix + '_linkPhone', options, ensureCallback(callback));\n }", "function updateFbUserData() {\n generalServices.addLogEvent('launchController', 'updateFbUserData', 'Start');\n userServices.updateFbUserData()\n .then(function () {\n validateSessionAndState();\n },\n function (error) {\n navigator.splashscreen.hide();\n if (error.source == \"fb\") {\n generalServices.popMessageOk('Facebook data is no longer valid. Please sign in again.');\n } else {\n generalServices.popMessageRetry(\"Connection to PinAndMeet server can't be established. Please check the network connection.\")\n .then(function () {\n updateFbUserData() // Clicked Yes for Retry -> Call this again\n .then(function () {\n resolve();\n },\n function () {\n navigator.splashscreen.hide();\n reject();\n });\n },\n function () {\n // Clicked No for Retry\n userServices.resetAndStartFromLaunch();\n });\n }\n });\n }", "function updateInfo(req, res) {\n User.findOne({_id: req.params.id}, function(err, user) {\n if (err || !user) {\n return res.send({error: 'Could not update user.'});\n }\n \n user.extendedInfo = req.body;\n\n user.save(function(saveErr) {\n if (saveErr) {\n return res.send({error: 'Could not update user'});\n }\n return res.send({success: 'Successfully updated user!'});\n });\n });\n}", "unlinkPhone(phone, code, password, callback) {\n password = AccountsEx._hashPassword(password);\n callback = ensureCallback(callback);\n return AccountsEx._unlinkPhone({type: 'default', phone, code, password}, callback);\n }", "function phoneNoselect() {\n if ($('#msform').length) {\n $(\"#phone\").intlTelInput();\n $(\"#phone\").intlTelInput(\"setNumber\", \"+880\");\n };\n }", "function UpdateUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n user.name = 'Hyper!'\n\t\tdebugger;\n return client.UpdateUser(user, 'administrator', 'Welcome1');\n })\n .then(function (user) {\n debugger;\n });\n}", "function userUpdate(fname, lname, email, pswrd) {\n return $.ajax({\n method: \"PUT\",\n url: \"/api/user\",\n dataType: \"json\",\n contentType: \"application/json\",\n data: JSON.stringify({\n id: userInfo.id,\n fname: fname,\n lname: lname,\n email: email,\n password: pswrd\n })\n });\n}", "function updateUserCount(count) {\n database.ref('players/count').set(count);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a boolean if the task exists in the project
hasTask(taskTitle){ return this._tasks.some(ele=>ele.title==taskTitle); }
[ "hasProject(name) {\n return this.allWorkspaceProjects.has(name);\n }", "function isQaTask(taskName) {\n var isQA = false;\n if (QATasks.has(taskName)) {\n isQA = true;\n }\n return isQA;\n }", "function isUserTask(taskProjectID, userProjectArray){\n for (var i = 0; i < userProjectArray.length; i++){\n if (taskProjectID == userProjectArray[i]){\n return true;\n }\n }\n return false;\n}", "async exists() {\n return $(this.rootElement).isExisting();\n }", "function checkTasksState() {\n var i, j, k, listTasks = Variable.findByName(gm, 'tasks'), taskDescriptor, taskInstance,\n newWeek = Variable.findByName(gm, 'week').getInstance(self), inProgress = false,\n listResources = Variable.findByName(gm, 'resources'), resourceInstance, assignment,\n newclientsSatisfaction = Variable.findByName(gm, 'clientsSatisfaction').getInstance(self);\n for (i = 0; i < listTasks.items.size(); i++) {\n inProgress = false;\n taskDescriptor = listTasks.items.get(i);\n taskInstance = taskDescriptor.getInstance(self);\n for (j = 0; j < listResources.items.size(); j++) {\n resourceInstance = listResources.items.get(j).getInstance(self);\n if (resourceInstance.getActive() == true) {\n for (k = 0; k < resourceInstance.getAssignments().size(); k++) {\n assignment = resourceInstance.getAssignments().get(k);\n if (assignment.getTaskDescriptorId() == taskInstance.getDescriptorId() && taskInstance.getActive() == true) {\n inProgress = true;\n }\n }\n }\n }\n if (inProgress ||\n (newWeek.getValue() >= taskDescriptor.getProperty('appearAtWeek') &&\n newWeek.getValue() < taskDescriptor.getProperty('disappearAtWeek') &&\n newclientsSatisfaction.getValue() >= taskDescriptor.getProperty('clientSatisfactionMinToAppear') &&\n newclientsSatisfaction.getValue() <= taskDescriptor.getProperty('clientSatisfactionMaxToAppear') &&\n taskInstance.getDuration() > 0\n )\n ) {\n taskInstance.setActive(true);\n }\n else {\n taskInstance.setActive(false);\n }\n }\n}", "async checkIfRefExists(ref) {\n try {\n await this.api.git.getRef({ ...this.userInfo, ref });\n return true;\n }\n catch (error) {\n return false;\n }\n }", "Exists() {\n return this.transaction != null;\n }", "exists() {\n return this.element ? true : false;\n }", "isWorkInProgress() {\n return this.json_.work_in_progress === true;\n }", "fileExists() {\n return fs.pathExists(this.location);\n }", "function exists(file) {\n\treturn fs.existsSync(file) && file;\n}", "function currentUserCanViewProject(){\n if (fwPluginUrl.isHomePage){\n return true;\n }\n\n var userProjects = fwPluginUrl.currentUserProjectIDs;\n\n for (var i = 0; i < userProjects.length; i++){\n if (userProjects[i] == fwPluginUrl.currentPageID){\n return true;\n }\n }\n return false;\n}", "hasEntry(...pth) {\n return fs.exists(this.dst, ...pth);\n }", "exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }", "needsReschedule() {\n if (!this.currentTask || !this.currentTask.isRunnable) {\n return true;\n }\n // check if there's another, higher priority task available\n let nextTask = this.peekNextTask();\n if (nextTask && nextTask.priority > this.currentTask.priority) {\n return true;\n }\n return false;\n }", "isCompletedRunCurrent () {\n return this.runCurrent?.RunDigest && Mdf.isRunCompleted(this.runCurrent)\n }", "function manifestExists() {\n return fs.existsSync(testManifestPath);\n}", "function checkInProject() {\n const projectName = helpers.toTitleCase(app.getArgument('projectName'));\n const description = app.getArgument('description');\n\n let userCheckIn = db.ref('checkIn/' + userId);\n\n userCheckIn.once('value').then((snapshot) => {\n if (snapshot.exists() && snapshot.val().checkInStatus) {\n let oldProjectName = snapshot.val().projectName;\n app.ask(`You are currently clocked in to ${oldProjectName}. Simply say, \"Switch\" to log in to another project.`);\n } else {\n let userProjects = db.ref('projects/' + userId);\n\n userProjects.orderByChild('createdOn').once('value').then((snapshot) => {\n\n // if user have not created any projects yet\n if (snapshot.numChildren() <= 0) {\n app.ask(`Sorry! Haven't seen you create a project. Say, \"Create a project\", to create a new project.`);\n return;\n }\n\n let projectNameExists = false;\n snapshot.forEach((childSnapshot) => {\n if (childSnapshot.val().projectName.toUpperCase() === projectName.toUpperCase()) {\n projectNameExists = true;\n }\n });\n\n if (projectNameExists) {\n\n const checkInTime = new Date().getTime();\n\n let date = moment().format('DD-MM-YYYY');\n let userLogs = db.ref('logs/' + userId);\n let userCheckIn = db.ref('checkIn/' + userId);\n\n userCheckIn.set({projectName: projectName, checkInTime: checkInTime, checkInStatus: true});\n userLogs.push({\n projectName: projectName,\n checkInDate: date,\n checkInTime: checkInTime,\n description: description,\n checkOutTime: ''\n });\n\n app.tell(`Great! You have been successfully checked in to ${projectName}.`);\n } else {\n app.ask(`Oops! ${projectName} doesn't exist. Please say \"create a project\" to create a new one.`);\n }\n });\n }\n });\n }", "function hasFoundSolution() {\n return found_solution;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fn close video popup
function closePopupVideo() { $body.removeClass('overflow'); $overlayVideo.removeClass('open'); setTimeout(function () { player.stopVideo(); }, 250); }
[ "function w3_openvd() {\n\tdocument.getElementById(\"closevideo\").style.display = \"block\";\n}", "function closeOverlay(e) {\n if (isVideoOpen === true) {\n const mosVideoWrapper =\n document.getElementsByClassName(\"mos-video-wrapper\");\n const flipCardInner = document.getElementsByClassName(\"flip-card-inner\");\n const mosVideo = document.getElementsByClassName(\"mos-video\");\n\n for (let i = 0; i < mosVideoWrapper.length; i++) {\n mosVideoWrapper[i].style.display = \"none\";\n }\n\n for (let i = 0; i < mosVideo.length; i++) {\n mosVideo[i].pause();\n mosVideo[i].currentTime = 0;\n }\n\n for (let i = 0; i < flipCardInner.length; i++) {\n flipCardInner[i].style.visibility = \"visible\";\n }\n\n setIsVideoOpen(false);\n }\n }", "function closeMaindemo(event){\r\n\t\t$('#social-PopUp').fadeOut();\r\n\t\t$('#social-PopUp-main').fadeOut();\r\n\t}", "function close_popup(popup) {\r\n popup.style.display = \"none\";\r\n}", "function closePopup()\n{\n win.close();\n return true;\n}", "function closecancelpanel(){\n $.modal.close();\n }", "function closeLightbox(e) {\r\n $(e).click(()=>{\r\n if (e === '.close-cursor') {\r\n $('#lightbox-m').hide();\r\n $('.music-slides').hide();\r\n } else if (e === '.movie-close-cursor') {\r\n $('#lightbox-b').hide();\r\n $('.movie-slides').hide();\r\n } else if (e === '.movie-sorted-close') {\r\n $('#lightbox-a').hide();\r\n }\r\n });\r\n}", "close() {\n this.showModal = false;\n\n this.onClose();\n }", "function popupPVAsWindow_onunload(event)\n{\n\ttry\n\t{\n\t\tif (!window.close())\n\t\t{\n\t\t\tdt_pvClosePopUp(false);\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t}\n}", "function close_image() {\n image_viewer.style.display = \"none\";\n}", "function closeModal() {\n\twinningMessage.style.display = 'none';\n}", "function closePopUp() {\n document.getElementById(\"loggerModalWrapper\").style.display = \"none\";\n }", "function closeModal() {\r\n modal.style.display = 'none';\r\n }", "function openVideo(video_id) {\n $(modal.replace(\"{VIDEO_ID}\", video_id)).appendTo('body').modal();\n}", "function close() {\n\tcongratModalEl.style.display = 'none';\t\n}", "function addCloseButtonFunctionality(){\n\t\t\t\n\t\t\t\n\t\t}", "function closeDeviceTypePopUp(){\n\t$('#devicetypePopUp').dialog('destroy');\n}", "function endVideo() {\n var video = document.getElementById('video');\n var audio = document.getElementById('audio');\n audio.parentNode.removeChild(audio);\n video.parentNode.removeChild(video);\n}", "function closeGif() {\n $chosenGif.hide();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new NoiseProceduralTexture
function NoiseProceduralTexture(name,size,scene,fallbackTexture,generateMipMaps){if(size===void 0){size=256;}if(scene===void 0){scene=BABYLON.Engine.LastCreatedScene;}var _this=_super.call(this,name,size,"noise",scene,fallbackTexture,generateMipMaps)||this;_this._time=0;/** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */_this.brightness=0.2;/** Defines the number of octaves to process */_this.octaves=3;/** Defines the level of persistence (0.8 by default) */_this.persistence=0.8;/** Gets or sets animation speed factor (default is 1) */_this.animationSpeedFactor=1;_this.autoClear=false;_this._updateShaderUniforms();return _this;}
[ "function ProceduralTexture(name,size,fragment,scene,fallbackTexture,generateMipMaps,isCube){if(fallbackTexture===void 0){fallbackTexture=null;}if(generateMipMaps===void 0){generateMipMaps=true;}if(isCube===void 0){isCube=false;}var _this=_super.call(this,null,scene,!generateMipMaps)||this;_this.isCube=isCube;/**\n * Define if the texture is enabled or not (disabled texture will not render)\n */_this.isEnabled=true;/**\n * Define if the texture must be cleared before rendering (default is true)\n */_this.autoClear=true;/**\n * Event raised when the texture is generated\n */_this.onGeneratedObservable=new BABYLON.Observable();/** @hidden */_this._textures={};_this._currentRefreshId=-1;_this._refreshRate=1;_this._vertexBuffers={};_this._uniforms=new Array();_this._samplers=new Array();_this._floats={};_this._ints={};_this._floatsArrays={};_this._colors3={};_this._colors4={};_this._vectors2={};_this._vectors3={};_this._matrices={};_this._fallbackTextureUsed=false;_this._cachedDefines=\"\";_this._contentUpdateId=-1;scene=_this.getScene();var component=scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);if(!component){component=new BABYLON.ProceduralTextureSceneComponent(scene);scene._addComponent(component);}scene.proceduralTextures.push(_this);_this._engine=scene.getEngine();_this.name=name;_this.isRenderTarget=true;_this._size=size;_this._generateMipMaps=generateMipMaps;_this.setFragment(fragment);_this._fallbackTexture=fallbackTexture;if(isCube){_this._texture=_this._engine.createRenderTargetCubeTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});_this.setFloat(\"face\",0);}else{_this._texture=_this._engine.createRenderTargetTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});}// VBO\nvar vertices=[];vertices.push(1,1);vertices.push(-1,1);vertices.push(-1,-1);vertices.push(1,-1);_this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]=new BABYLON.VertexBuffer(_this._engine,vertices,BABYLON.VertexBuffer.PositionKind,false,false,2);_this._createIndexBuffer();return _this;}", "function CustomProceduralTexture(name,texturePath,size,scene,fallbackTexture,generateMipMaps){var _this=_super.call(this,name,size,null,scene,fallbackTexture,generateMipMaps)||this;_this._animate=true;_this._time=0;_this._texturePath=texturePath;//Try to load json\n_this._loadJson(texturePath);_this.refreshRate=1;return _this;}", "function createTempImage(){\n tempImage = game.instantiate(new Sprite('./img/beginplaatje.svg'));\n tempImage.setPosition({x: Settings.canvasWidth/2 - 110, y: Settings.canvasHeight/2 - 110});\n tempImage.setSize({x: 200, y: 200});\n}", "function createBg(texture, scene) {\n //create new bG based on the texture\n let tiling = new PIXI.TilingSprite(texture, 1024, 576);\n\n //reset its position and add to scene\n tiling.position.set(0, 0);\n scene.addChild(tiling);\n\n //return it\n return tiling;\n}", "_getVesselTexture(radius, blurFactor) {\n const tplCanvas = document.createElement('canvas');\n const tplCtx = tplCanvas.getContext('2d');\n const diameter = radius * 2;\n tplCanvas.width = (diameter * 2) + 1; // tiny offset between 2 frames\n tplCanvas.height = (diameter * VESSELS_HUES_INCREMENTS_NUM) + VESSELS_HUES_INCREMENTS_NUM;\n\n for (let hueIncrement = 0; hueIncrement < VESSELS_HUES_INCREMENTS_NUM; hueIncrement++) {\n const y = (diameter * hueIncrement) + hueIncrement;\n const yCenter = y + radius;\n\n // heatmap style\n let x = radius;\n const gradient = tplCtx.createRadialGradient(x, yCenter, radius * blurFactor, x, yCenter, radius);\n const hue = hueIncrementToHue(hueIncrement);\n const rgbString = hueToRgbString(hue);\n gradient.addColorStop(0, rgbString);\n\n const rgbOuter = hsvToRgb(wrapHue(hue + 30), 80, 100);\n gradient.addColorStop(1, `rgba(${rgbOuter.r}, ${rgbOuter.g}, ${rgbOuter.b}, 0)`);\n\n tplCtx.fillStyle = gradient;\n tplCtx.fillRect(0, y, diameter, diameter);\n\n // circle style\n x += diameter + 1; // tiny offset between 2 frames\n tplCtx.beginPath();\n tplCtx.arc(x, yCenter, radius, 0, 2 * Math.PI, false);\n tplCtx.fillStyle = rgbString;\n tplCtx.fill();\n }\n\n return tplCanvas;\n }", "generateNoiseImage()\r\n\t{\r\n\t\tconst fracStartTime = performance.now();\r\n\r\n\t\tz42fractalNoise.generateFractalNoiseImageUint16( \r\n\t\t\tthis._plasmaPixels, this._width, this._height, this._currentPalette.length, \r\n\t\t\tthis._options.noise, this._noiseGenes );\r\n\r\n\t\tconsole.debug( \"Fractal generation took %d ms\", performance.now() - fracStartTime );\r\n\t}", "function PerlinNoise() {\n //srandom(clock());\n \n this.perlin_TWOPI = SINCOS_LENGTH;\n this.perlin_PI = this.perlin_TWOPI / 2;\n \n this.cosTable = [];\n for (i = 0; i < SINCOS_LENGTH; i++) {\n //sinLUT[i] = (float) sin(i * DEG_TO_RAD * SINCOS_PRECISION);\n this.cosTable[i] = Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION);\n }\n\n this.perlin = [];\n for (i = 0; i < PERLIN_SIZE + 1; i++) {\n this.perlin[i] = Math.random();\n }\n}", "function RawTexture(data,width,height,/**\n * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n */format,scene,generateMipMaps,invertY,samplingMode,type){if(generateMipMaps===void 0){generateMipMaps=true;}if(invertY===void 0){invertY=false;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,null,scene,!generateMipMaps,invertY)||this;_this.format=format;_this._engine=scene.getEngine();_this._texture=scene.getEngine().createRawTexture(data,width,height,format,generateMipMaps,invertY,samplingMode,null,type);_this.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;_this.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;return _this;}", "function createNozzle(){\n let mtlLoader = new THREE.MTLLoader();\n mtlLoader.setPath('models/');\n mtlLoader.load('nozzle.mtl', mtls => {\n mtls.preload();\n let objLoader = new THREE.OBJLoader();\n objLoader.setMaterials(mtls);\n objLoader.setPath('models/');\n objLoader.load('nozzle.obj', obj => {\n obj.scale.set(20, 20, 20);\n obj.position.set(-0.001, -0.0905, 0);\n self.scene.add(obj);\n render();\n });\n });\n\n }", "function createPortal() {\n var portal = createSprite(350, 250);\n portal.setAnimation(\"lollipop_red_1\");\n portal.scale = 0.7;\n portal.rotationSpeed = -5;\n //portal.debug = true;\n portal.setCollider(\"circle\");\n return portal;\n}", "function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n var material = new THREE.SpriteMaterial( { map: texture, fog: true, } );\n var sprite = new THREE.Sprite( material );\n sprite.scale.set(size, size, size);\n var speed = Math.random() *speed_factor + speed_min;\n\n // Initial placement\n x = (Math.random()*(right-left))-((right-left)/2);\n y = (Math.random()*3000)-1000;\n sprite = new FallingObject(sprite, speed, x, y, -1000, 0, -1, 0);\n sprite.set_box_rules(2000, -1000, left, right);\n\n \n //sprite.place();\n\n return sprite;\n}", "function GenNoise()\n{\n var value;\n for (var i = 0; i < PATTERN_PIXELS; i += 4)\n {\n value = (Math.random() * 255);\n pattern_data.data[i] = value;\n pattern_data.data[i+1] = value;\n pattern_data.data[i+2] = value;\n pattern_data.data[i+3] = PATTERN_ALPHA;\n\n var frame_ind;\n if (transition)\n \tframe_ind = FRAME_IND_ANIM[still_current][anim_frame_current];\n else\n \tframe_ind = FRAME_IND_STILL[still_current];\n\t\tpattern_data.data[i+3] *= FRAME_GRAIN_ALPHA[frame_ind];\n }\n pattern_ctx.putImageData(pattern_data, 0, 0);\n}", "function RawTexture3D(data,width,height,depth,/** Gets or sets the texture format to use */format,scene,generateMipMaps,invertY,samplingMode,textureType){if(generateMipMaps===void 0){generateMipMaps=true;}if(invertY===void 0){invertY=false;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,null,scene,!generateMipMaps,invertY)||this;_this.format=format;_this._engine=scene.getEngine();_this._texture=scene.getEngine().createRawTexture3D(data,width,height,depth,format,generateMipMaps,invertY,samplingMode,undefined,textureType);_this.is3D=true;return _this;}", "function genSquare(xP, yP) {\n let s = new Square(xP, yP);\n stage.addChild(s.view);\n}", "function prepareTerrain() {\n var seedText = document.getElementById(\"seedText\");\n var sizeSlider = document.getElementById(\"worldSize\");\n var scaleSlider = document.getElementById(\"scale\");\n var octavesSlider = document.getElementById(\"octaves\");\n\n var size = parseInt(sizeSlider.value);\n var scale = parseInt(scaleSlider.value) / 1000;\n var octaves = parseInt(octavesSlider.value);\n var simplex = new NoiseCalculator(seedText.value, octaves, scale);\n\n terrain.mesh = new Mesh(gl, simplex, size);\n terrain.plane = new Plane(gl, simplex, size);\n terrain.lowPoly = new LowPoly(gl, simplex, size);\n}", "function drawPrey() {\n fill(preyFill, preyHealth);\n imageMode(CENTER);\n tint(255, preyHealth);\n image(preyImg, preyX, preyY, 75, 75);\n}", "function createPlayer() {\n player = new PIXI.AnimatedSprite(playerSheet.walkSouth);\n player.anchor.set(0.5);\n player.animationSpeed = 0.18;\n player.loop = false;\n player.x = app.view.width / 2;\n player.y = app.view.height / 2;\n app.stage.addChild(player);\n player.play();\n}", "function Terrain_Square(x,y,w,h,type,which_sprite_array,name_of_sprite_sheet){\n\n\tthis.x = x * w;\n\tthis.y = y * h; \n\tthis.w = w;\n\tthis.h = h;\n\n\t//console.log(\"1which_sprite_array is: \" + which_sprite_array);\n\t\n\t//so that these 4 values dont need to be calculated over and over again. \n\tthis.ulc_x = this.x;\n\tthis.urc_x = this.x + this.w;\n\tthis.ulc_y = this.y;\n\tthis.llc_y = this.y + this.h;\n\n\tthis.contains_mouse = false;\n\tthis.color = \"black\";//random default. not associated with any type currently. \n\n\tif(type == 0){\n\t\tthis.color = \"yellow\";\n\t}\n\telse if(type == 1){\n\t\tthis.color = \"red\";\n\t}\n\n\t\n\tthis.type = type; //can it be walked on.\n\tthis.sprite_sheet = document.getElementById(name_of_sprite_sheet);\n\tthis.ssi = new SSI();\n\tthis.ssi.set_x_y_w_h_dw_and_dh(which_sprite_array[0],\n\t\t\t\t\t\t\t\t which_sprite_array[1],\n\t\t\t\t\t\t\t\t which_sprite_array[2],\n\t\t\t\t\t\t\t\t which_sprite_array[3],\n\t\t\t\t\t\t\t\t this.w,\n\t\t\t\t\t\t\t\t this.h\n\t\t\t\t\t\t\t\t );\n\n}", "function createPlayer() {\n\n entityManager.generatePlayer({\n cx : 240,\n cy : 266,\n });\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all event invitations by event id
async getInvitationsByEventId(req, res) { const userAuth = jwt_decode(req.token); const { event_id } = req.params; try { const user = await User.findOne({ cognito_id: userAuth.sub }); // Check if user exist if (!user) { return res.status(400).json({ errMessage: 'User Not Found', }); } const event = await Event.findById(event_id); if (!event) { return res.status(400).json({ errMessage: 'Event Not Found', }); } const invitations = await Invitation.find({ event_id: event._id, is_going: null, }) .populate('user_id') .exec(); return res.status(200).json({ invitations, }); } catch (error) { throw Error(`Error while getting invitation: ${error}`); } }
[ "function getEventAttendees(calendarName, eventid)\n{\n\tvar attendees = {\n\t\t\t'firstName': 'Test',\n\t\t\t'lastName': 'User'\n\t\t\t};\n\t\t\t\n\tvar myEvent = getEvent( calendarName, eventid );\n\t\n\treturn myEvent.attendees;\n}", "deleteInvites(invitedId) {\n return new Promise((resolve, reject) => {\n this.client.del(\n `${this.namespace}:user:${invitedId}:${STATE_KEY.invited}`,\n (err, res) => {\n if (err) { reject(err); }\n debug(`Deleted all invites for ${invitedId}`);\n return resolve(res);\n });\n });\n }", "getAllUserEvents(db, user_id){\n return db\n .from('events')\n .select('*')\n .where({user_id});\n }", "invite(userId, invitedId) {\n // use date for sorted set ordering\n return new Promise((resolve, reject) => {\n this.client.zadd(\n `${this.namespace}:user:${invitedId}:${STATE_KEY.invited}`,\n Date.now(),\n userId,\n (err, res) => {\n if (err) { reject(err); }\n debug(`${userId} invited ${invitedId}`);\n return resolve(res);\n });\n });\n }", "function igcal_getCalendarById(id, e)\r\n{\r\n\tvar o,i1=-2;\r\n\tif(e!=null)\r\n\t{\r\n\t\twhile(true)\r\n\t\t{\r\n\t\t\tif(e==null) return null;\r\n\t\t\ttry{if(e.getAttribute!=null)id=e.getAttribute(\"calID\");}catch(ex){}\r\n\t\t\tif(!ig_csom.isEmpty(id)) break;\r\n\t\t\tif(++i1>1)return null;\r\n\t\t\te=e.parentNode;\r\n\t\t}\r\n\t\tvar ids=id.split(\",\");\r\n\t\tif(ig_csom.isEmpty(ids))return null;\r\n\t\tid=ids[0];\r\n\t\ti1=(ids.length>1)?parseInt(ids[1]):-1;\r\n\t}\r\n\tif((o=igcal_all[id])==null)\r\n\t\tfor(var i in igcal_all)if((o=igcal_all[i])!=null)\r\n\t\t\tif(o.ID==id || o.ID_==id || o.uniqueId==id)break;\r\n\t\t\telse o=null;\r\n\tif(o!=null && i1>-2)o.elemID=i1;\r\n\treturn o;\r\n}", "getAllEvents() {\r\n return Event.all;\r\n }", "function obtenInvitados(tramite){\r\n\t\tvar objetoInvitados = obtenDatosInvitados(tramite);\r\n\t\tif(objetoInvitados != null){\r\n\t\t\tfor(var prop in objetoInvitados){\r\n\t\t\t\tvar partida = objetoInvitados[prop];\r\n\t\t\t\tfor(var propPar in partida)\r\n\t\t\t\t\tpartida[propPar] = (partida[propPar] == \"\" || partida[propPar] == null) ? \"N/A\" : partida[propPar];\r\n\t\t\t\t\r\n\t\t\t\tvar id = obtenTablaLength(\"invitado_table\")+1;\r\n\t\t\t\tvar\trenglon = creaRenglonInvitados(objetoInvitados[prop], id);\r\n\t\t\t\tagregaRenglon(renglon, \"invitado_table\");\r\n\t\t\t}\r\n\t\t\tasignaText(\"span_totalInvitados\", id);\r\n\t\t\tasignaVal(\"numInvitados\", id);\r\n\t\t}\r\n\t}", "findAllEventCanals(req, res){\n Event.getAllEventCanals((err, data) => {\n if (err)\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving event canals.\"\n });\n else res.send(data);\n });\n }", "get eventReceivers() {\n return SPCollection(this, \"EventReceivers\");\n }", "function inventory(req, res, next) {\n\tconst id = req.params.userId;\n\n\tUser.findOne({userId: id}, function(err, user) {\n\t\tif (err) res.send(err)\n\t\tconst inventory = user.inventory.map(function(item){\n\t\t\treturn item.itemId;\n\t\t});\n\t\t//res.json(inventory);\n\t\tItem.find({ itemId: {$in: inventory} }, function(err, items) {\n\t\t\tif(err) res.send(err);\n\t\t\tres.json(items);\n\t\t})\n\t});\n}", "function getSessions(eventId) {\n return request.get(CONFIG.api.sessions + `/events/${eventId}/sessions`)\n}", "function getActiveAttendees(event) {\n if (!event) {\n return;\n }\n\n var attendees = event.attendees,\n num = attendees && attendees.length,\n activeAttendees = event.activeAttendees;\n\n\n !num && (activeAttendees = event.activeAttendees = false);\t// No attendees, no count\n\n if (activeAttendees || activeAttendees === false) { // Did we run already?\n return activeAttendees;\n }\n\n activeAttendees = [];\n for (var i = 0; i < num; ++i) {\n if (!attendees[i].notifyState || attendees[i].notifyState != \"DELETED\") {\n activeAttendees.push(attendees[i]);\n }\n }\n\n return event.activeAttendees = activeAttendees;\n }", "async function eventSubscriptionsGetForResource() {\n const subscriptionId =\n process.env[\"EVENTGRID_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const scope =\n \"subscriptions/8f6b6269-84f2-4d09-9e31-1127efcd1e40/resourceGroups/examplerg/providers/Microsoft.EventHub/namespaces/examplenamespace1\";\n const eventSubscriptionName = \"examplesubscription1\";\n const credential = new DefaultAzureCredential();\n const client = new EventGridManagementClient(credential, subscriptionId);\n const result = await client.eventSubscriptions.get(scope, eventSubscriptionName);\n console.log(result);\n}", "findAllWithDate(req, res){\n if (!req.query.dates) {\n res.status(400).send({\n message: \"Dates can not be null!\"\n });\n return;\n }\n const objDates = JSON.parse(req.query.dates);\n\n Event.getAllWithDate(objDates, (err, data) => {\n if (err) {\n if (err.kind === \"not_found\") {\n res.status(404).send({\n message: `Not found event with date.`\n });\n } else {\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving events with date.\"\n });\n }\n }else {\n res.send(data);\n }\n });\n }", "function listEvents(req, res, next){\n var logger = log.logger;\n var EventModel = models.getModels().Event;\n var listReq = RequestTranslator.parseListEventsRequest(req);\n if(! listReq.uid || ! listReq.env || ! listReq.domain){\n return next({\"error\":\"invalid params missing uid env or domain\",\"code\":400});\n }\n EventModel.queryEvents(listReq.uid, listReq.env, listReq.domain, function(err, events){\n if(err) {\n logger.error(loggerPrefix + 'Events Query Error: ', err);\n return next(err);\n } else {\n req.resultData = ResponseTranslator.mapEventsToResponse(events);\n next();\n }\n });\n}", "function getExchange(id) {\n return fetch(`${url}/exchanges/${id}`)\n .then((res) => res.json())\n .then((res) => res.data);\n}", "function getAllRSVPs (eventID, callback) {\n\n var RSVPs = {\n going: [],\n notGoing: [],\n maybe: []\n };\n var statuses = Object.keys(RSVPs);\n var progressCount = 0;\n\n function report (error, attendanceStatus, data) {\n\n if (error) {\n return callback(error);\n }\n RSVPs[attendanceStatus] = data;\n\n progressCount++;\n\n if (progressCount === statuses.length) {\n\n callback(null, RSVPs);\n }\n }\n\n statuses.forEach((attendanceStatus) => {\n\n getRSVPsForAttendanceStatus(eventID, attendanceStatus, report);\n });\n}", "getSingleUserEvent(db, user_id, id){\n return db\n .from('events')\n .select('*')\n .where({user_id, id});\n }", "function getEmails() {\n let promise = userIdsRef.get().then(querySnap => {\n let usersEmails = [];\n querySnap.forEach(doc => {\n let thatEmail = doc.data().email;\n usersEmails.push(thatEmail);\n });\n return usersEmails;\n });\n return promise;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an string of numbers to array of numbers e.g. extractIntegers("1 2 3") > [1, 2, 3]
function extractIntegers(srcstr) { return srcstr.split(" ").map((substr) => parseInt(substr)); }
[ "function getNumberArraysFromString(string) {\r\n\t let array = [];\r\n\t let re = /\\[(.*?)(?=\\])/g;\r\n\t let matches;\r\n\t do {\r\n\t matches = re.exec(string);\r\n\t if(matches)\r\n\t array.push(matches[1].split(',').map(Number));\r\n\t } while (matches);\r\n\t\r\n\t return array;\r\n\t}", "function toArray(num) {\n\tconst a = num.toString().split(\"\");\n\treturn a.map(x => parseInt(x));\n}", "function parseCsvIdsToNumericArray(ids,delimeter){\n\treturn ids.split(delimeter).map(Number);\n}", "function makeIntList(str)\n\t{\n\t\tif (!str)\n\t\t\treturn [];\n\n\t\tvar out = [];\n\n\t\t$.each(str.split(','), function(idx, val) {\n\t\t\tout.push(parseFloat(val));\n\t\t});\n\n\t\treturn out.sort();\n\t}", "function chunksAsInts(chunks) {\n return chunks.split(',').map(Number);\n}", "function convertIntoArray(string){\n return string.split(\" \");\n}", "function getNumbers(color) {\n const result = [];\n color.split(colorElementDividers).forEach(element => {\n const numberElement = parseFloat(element);\n if (!isNaN(numberElement)) {\n result.push(numberElement);\n }\n });\n return result;\n }", "function getBatchNums(rangesStr, parseValue) {\n var nums = [];\n var count = 0;\n var ranges = rangesStr.split(\",\");\n _.each(ranges, function (range) {\n var bounds = range.split(\"..\");\n if (bounds.length == 1) {\n if (count == BATCH_LIMIT) {\n return;\n }\n nums.push(parseValue(bounds[0]));\n } else if (bounds.length == 2) {\n var minBound = parseValue(bounds[0]);\n var maxBound = parseValue(bounds[1]);\n for (var i = minBound; i <= maxBound; i++) {\n if (count == BATCH_LIMIT) {\n return;\n }\n nums.push(i);\n count++;\n }\n } else {\n console.log(\"Unexpected number of bounds in range: \" + bounds.length);\n }\n });\n return nums;\n }", "function extractNumber(input, start) {\n if(start >= input.length){\n return [ NaN, -1]\n }\n\n let isNeg = 1; \n let number = 0; \n let i;\n for(i = start; i < input.length; i++) {\n if(input[i] === '-'){\n isNeg = -1;\n }else if(input[i] === '(' || input[i] === ')'){\n break;\n }else {\n number = number * 10 + Number(input[i]); \n }\n }\n return [ isNeg * number, i]\n}", "function array (date) {\n return date.split(/\\s+/).map(function (e) { return parseInt(e, 10) });\n}", "castToNumArray(value) {\n if (typeof value === 'number') {\n return [value];\n }\n if (typeof value === 'string') {\n return value.split(',').map((one) => Number(one));\n }\n if (Array.isArray(value)) {\n return value.map((prop) => Number(prop));\n }\n return undefined;\n }", "function _toIntArray(string) {\n var w1\n , w2\n , u\n , r4 = []\n , r = []\n , i = 0\n , s = string + '\\0\\0\\0' // pad string to avoid discarding last chars\n , l = s.length - 1\n ;\n\n while (i < l) {\n w1 = s.charCodeAt(i++);\n w2 = s.charCodeAt(i + 1);\n\n // 0x0000 - 0x007f code point: basic ascii\n if (w1 < 0x0080) {\n r4.push(w1);\n\n } else\n\n // 0x0080 - 0x07ff code point\n if (w1 < 0x0800) {\n r4.push(((w1 >>> 6) & 0x1f) | 0xc0);\n r4.push(((w1 >>> 0) & 0x3f) | 0x80);\n\n } else\n\n // 0x0800 - 0xd7ff / 0xe000 - 0xffff code point\n if ((w1 & 0xf800) != 0xd800) {\n r4.push(((w1 >>> 12) & 0x0f) | 0xe0);\n r4.push(((w1 >>> 6) & 0x3f) | 0x80);\n r4.push(((w1 >>> 0) & 0x3f) | 0x80);\n\n } else\n\n // 0xd800 - 0xdfff surrogate / 0x10ffff - 0x10000 code point\n if (((w1 & 0xfc00) == 0xd800) && ((w2 & 0xfc00) == 0xdc00)) {\n u = ((w2 & 0x3f) | ((w1 & 0x3f) << 10)) + 0x10000;\n r4.push(((u >>> 18) & 0x07) | 0xf0);\n r4.push(((u >>> 12) & 0x3f) | 0x80);\n r4.push(((u >>> 6) & 0x3f) | 0x80);\n r4.push(((u >>> 0) & 0x3f) | 0x80);\n i++;\n\n } else {\n // invalid char\n }\n\n /* _add integer (four utf-8 value) to array */\n if (r4.length > 3) {\n\n // little endian\n r.push(\n (r4.shift() << 0) | (r4.shift() << 8) | (r4.shift() << 16) | (r4.shift() << 24)\n );\n }\n }\n\n return r;\n }", "function intArrayFromString(stringy, dontAddNull, length /* optional */) {\n\tvar ret = (new Runtime.UTF8Processor()).processJSString(stringy);\n\tif (length) {\n\t\tret.length = length;\n\t}\n\tif (!dontAddNull) {\n\t\tret.push(0);\n\t}\n\treturn ret;\n}", "function DigitsInArry (number) \n{ \n let arryOfdigits = [];\n while (number !== 0) \n {\n let units = number % 10;\n arryOfdigits.unshift(units);\n number = Math.floor(number / 10)\n }\n return arryOfdigits;\n}", "function splitNumber(number){\n\t\n\tvar digits = [];\n\t\n\twhile (number > 0){\n\t\t\n\t\tdigits.push(number % 10);\n\t\tnumber = parseInt(number / 10);\n\t\t\n\t}\n\t\n\tdigits.reverse();\n\treturn digits;\n\n}", "function arrayOfNumbers(number) {\n var newArray = [];\n for (i = 1; i <= number; i++) {\n newArray.push(i);\n }\n return newArray;\n}", "function findNumbers(num1, num2) {\n let array = [];\n\n for (x = num1; x <= num2; x++) {\n let elements = x.toString().split(\"\");\n let sum = 0;\n elements.forEach(function (element) {\n sum += element * element * element;\n });\n if (sum === x) array.push(x);\n }\n return array;\n}", "function NumberAddition(str) { \n//search for all the digits in str (returns an array)\nvar nums = str.match(/(\\d)+/g); \n\nif (!nums) {return 0;} //stop if there are no numbers\nelse {\n //convert array elements to numbers using .map()\n //then add all elements together using .reduce()\n return nums.map(function(element, index, array){\n return +element;\n }).reduce(function(previous, current, index, array){\n return previous + current;\n });\n}\n}", "function removeNumericStrings(arr) {\n\tvar arrLen = arr.length;\n\tvar nonNumericArr = [];\n\n\tfor (var i=0; i < arrLen; i++) {\n\t\tif (!checkNumeric(arr[i])) {\n\t\t\tnonNumericArr.push(arr[i]);\n\t\t}\n\t}\n\n\treturn nonNumericArr;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`usersuser` model create event listener to send welcome email to user. It renders the `userwelcomeemail` template to provide the body of the welcome email. The rendered result provides HTML message content, and is stripped of HTML tags to provide plaintext content.
_sendWelcomeEmail(model, user) { this.log.debug('Sending welcome email to', user.email) var link if (user.password) { link = "http://"+application.config.baseUrl+this.baseUrl+"login" } else { link = "http://"+application.config.baseUrl+this.baseUrl+"login-link?token="+user.resetPasswordToken } let tempPass = user.tempPassword delete user.tempPassword templater.render('user-welcome-email', {user, tempPass, link, siteName: application.config.siteName}).then((html) => { let fromEmail = (application.config.users && application.config.users.forgotPasswordEmail) ? application.config.users.forgotPasswordEmail : "noreply@"+((application.config.mailer && application.config.mailer.emailDomain) || application.config.host) return mailer.send(user.email, fromEmail, "Welcome to "+application.config.siteName, striptags(html), {html}) }) }
[ "function welcomeUser(user) {\n user.notify('Welcome ' + user.getName() + '!');\n}", "function welcomeUser() {\n let greeting = \"No Current User\";\n\n if (isLoggedIn === true) {\n greeting = \"Welcome, \" + currentUser.name;\n }\n\n return greeting;\n }", "async inviteUser () {\n\t\tthis.log('NOTE: Inviting user under one-user-per-org paradigm');\n\t\tconst inviterClass = UserInviter;\n\t\tthis.userInviter = new inviterClass({\n\t\t\trequest: this,\n\t\t\tteam: this.team,\n\t\t\tdelayEmail: this._delayEmail,\n\t\t\tinviteType: this.inviteType,\n\t\t\tuser: this.user,\n\t\t\tdontSendEmail: this.dontSendEmail\n\t\t});\n\n\t\tconst userData = {\n\t\t\temail: this.request.body.email.trim()\n\t\t};\n\t\tthis.invitedUsers = await this.userInviter.inviteUsers([userData]);\n\t\tconst invitedUserData = this.invitedUsers[0];\n\t\tthis.transforms.createdUser = invitedUserData.user;\n\t}", "static async inviteUsers(company_id, user_emails) {\n\t\t// find company\n\t\tlet company = await models.Company.findByPk(company_id)\n\t\t// generate random hash\n\t\tlet hash = generator.getRandomString(40)\n\t\t// save hash to db\n\t\tawait models.InviteHash.create({ hash, company_id })\n\n\t\t// send email\n\t\tconst mg = mailgun({ apiKey: 'key-f25a884c247378aa8dd34083fe6e4b28', domain: 'sandbox454409b9d64449f7b661a00c48d6a721.mailgun.org' })\n\t\tconst data = {\n\t\t\tfrom: '<me@samples.mailgun.org>',\n\t\t\tto: user_emails,\n\t\t\tsubject: 'Hello',\n\t\t\ttext: `Dear user you have been invited in ${company.name} <a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>`\n\t\t}\n\t\tmg.messages().send(data, function(error, body) {\n\t\t\tconsole.log(body)\n\t\t})\n\n\t\treturn true\n\n\t\t// // Generate test SMTP service account from ethereal.email\n\t\t// let testAccount = await nodemailer.createTestAccount()\n\t\t// // create reusable transporter object using the default SMTP transport\n\t\t// let transporter = nodemailer.createTransport({\n\t\t// \thost: 'smtp.ethereal.email',\n\t\t// \tport: 587,\n\t\t// \tsecure: false, // true for 465, false for other ports\n\t\t// \tauth: {\n\t\t// \t\tuser: testAccount.user, // generated ethereal user\n\t\t// \t\tpass: testAccount.pass // generated ethereal password\n\t\t// \t}\n\t\t// })\n\n\t\t// send mail with defined transport object\n\t\t// let info = await transporter.sendMail({\n\t\t// \tfrom: '\"Fred Foo 👻\" <foo@example.com>', // sender address\n\t\t// \tto: user_emails, // list of receivers\n\t\t// \tsubject: `Invitation from ${company.name}`, // Subject line\n\t\t// \ttext: `Dear user you have been invited in ${company.name}`, // plain text body\n\t\t// \thtml: `<a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>` // html body\n\t\t// })\n\n\t\t// return nodemailer.getTestMessageUrl(info)\n\t}", "function notifyMember(site,personalMail,firstname,lastname,date){\n var body = \"Documents and information required for employee admission.\";\n var subject = \"Welcome to our company\";\n var options = {name:\"HR Team\",htmlBody:body,replyTo:\"hr@example.com\",from:\"hr@example.com\"};\n MailApp.sendEmail(personalMail,subject,body,options);\n }", "inviteOtherUser (callback) {\n\t\tlet data = {\n\t\t\tteamId: this.team.id,\n\t\t\temail: this.userData[1].user.email\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/users',\n\t\t\t\tdata,\n\t\t\t\ttoken: this.userData[0].accessToken\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}", "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 displayUser() {\n var user = firebase.auth().currentUser;\n var email;\n if (user != null) {\n email = user.email;\n }\n}", "function showUserPanel() {\n\tlcSendValueAndCallbackHtmlAfterErrorCheckPreserveMessage(\"/user/index\",\n\t\t\t\"#userDiv\", \"#userDiv\", null);\n}", "function startRegister() {\n\tif(request.httpParameterMap.MailExisted.value != null && request.httpParameterMap.MailExisted.value != 'true'){\n\t\tapp.getForm('profile').clear();\n\t}\n\n if (app.getForm('login.username').value() !== null) {\n app.getForm('profile.customer.email').object.value = app.getForm('login.username').object.value;\n }\n app.getView({\n ContinueURL: URLUtils.https('Account-RegistrationForm')\n }).render('account/user/registration');\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 }", "onSignUp() {\n const { email } = this.state;\n Alert.alert('Confirmation Email to ' + `${email}` + ' has been sent!');\n }", "function handleCreateAccount() {\n\t$('.open-create-account').on('click', event => {\n\t\t$('.Welcome').addClass(\"hidden\");\n\t\t$('.Create-Account-Page').removeClass(\"hidden\");\n\t});\n}", "async function createUserWithMessage() {\n await models.User.create(\n {\n username: 'andyliwr',\n email: 'andyliwr@outlook.com',\n password: '12345678',\n role: 'admin',\n messages: [\n {\n text: 'Hello, GraphQL!',\n createdAt: new Date()\n }\n ]\n },\n {\n include: [models.Message]\n }\n )\n await models.User.create(\n {\n username: 'andyliwr2',\n email: 'andyliwr2@outlook.com',\n password: '12345678',\n role: 'user',\n messages: [\n {\n text: 'I love you!',\n createdAt: new Date()\n }\n ]\n },\n {\n include: [models.Message]\n }\n )\n}", "setWelcomeMessageMode(welcomeMessageMode) {\n Instabug.setWelcomeMessageMode(welcomeMessageMode);\n }", "showWelcomeMessage(welcomeMessageMode) {\n Instabug.showWelcomeMessageWithMode(welcomeMessageMode);\n }", "function UserName(props) {\n return (\n \n \n <div className=\"user-name-container\">\n <h1 className=\"header-login\">\n Welcome <span className=\"user-name-span\">{props.email}</span>\n </h1>\n </div>\n \n \n );\n}", "function setupUser(loginScreenName) {\n if (userScreenName == null || userScreenName != loginScreenName)\n {\n userScreenName = loginScreenName;\n localStorage.setItem(\"user-screenname\",userScreenName);\n dbConnectionObject.set(userScreenName);\n setupChatRef();\n }\n}", "function userLoggedIn() {\n let username = sessionStorage.getItem('username');\n $('#spanMenuLoggedInUser').text(`Welcome, ` + username + '!');\n $('#viewUserHomeHeading').text(`Welcome, ` + username + '!');\n $('.anonymous').hide();\n $('.useronly').show();\n showView('UserHome')\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Medium create a function that takes in four numbers. Add the first two numbers and return the remainder of dividing the sum of the first two numbers by the difference of the last two numbers
function complicatedMath(n1,n2,n3,n4){ return (n1+n2) % (n3-n4) }
[ "function remainderOfFives({ first, second }) {\n if (first === second) return 0;\n if (first % 5 === second % 5) return Math.min(first, second);\n return Math.max(first, second);\n}", "function fourNums(n1, n2, n3, n4){\n console.log (n1 + n2 - n3 - n4)\n}", "function divBy4(num){\n return num/4\n\n}", "function addSum(a,b){\n var answer = a + b;\n//4. Create a function that returns the difference of two numbers that are arguments. Then console.log the function with the variables from step two as your two arguments.\n\n console.log (answer);\n}", "function fiveNumbersSub(n1, n2, n3, n4, n5) {\n let difference = 100 - n1 - n2 - n3 - n4 - n5;\n console.log(Math.abs(difference));\n}", "function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}", "function promedioDeEdad(a,b,c,d,e){\r\n let suma = a+b+c+d+e;\r\n let promedio = suma/5\r\n return promedio\r\n}", "function multiFourAndReturn(n1,n2,n3,n4){\n return n1*n2*n3*n4\n}", "function modulo4(num){\n return num%4\n}", "function computeSumBetween(num1, num2) {\n\tvar results = 0;\n\tvar count = num1;\n\twhile (num1 < num2){\n\tresults = results + count++;\n\tnum2--;\n\t}\n\treturn results;\n}", "function divByFive(num){\n return num/5\n}", "function GetSum(a, b) {\n if (a == b) {\n return a;\n } else if (a < b) {\n return a + GetSum(a + 1, b);\n } else if (a > b) {\n return a + GetSum(a - 1, b);\n }\n}", "function division(a, b) {\n //tu codigo debajo\n let resultado = a / b;\n return resultado;\n​\n}", "function piSum3(a, b) {\n return sum(\n x => 1.0 / (x * (x + 2)), //piTerm\n a,\n x => x + 4, //piNext\n b\n );\n}", "function arithmeticMean(num1, num2, num3, num4) {\n return (num1 + num2 + num3 + num4) / 4;\n}", "function subtracts(num1, num2, num3, num4) {\n alert(num1 - num2 - num3 - num4);\n}", "function GetSum(a, b) {\n var sum = 0;\n if (a == b) {\n return a;\n } else if (a < b) {\n for (var i = a; i < b + 1; i++) {\n sum += i;\n }\n } else {\n for (var i = b; i < a + 1; i++) {\n sum += i;\n }\n }\n return sum;\n}", "function multiples(n) {\n var sum = 0;\n for (var i = 0; i < n; i++) {\n if (i%5 === 0 || i%7 === 0) {\n sum = sum + i;\n }\n }\n return sum;\n}", "function divid(a,b){\n var z = 10;\n return a/b;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delta Y (current_y previous_y).
getDeltaY() { return (this.getPageY() - ((this.__prevState.pageY !== undefined) ? this.__prevState.pageY : this.getPageY())) * this.getScaleY(); }
[ "_decreaseY() {\n if (!this._invertedY()) {\n this.valueY = Math.max(this.minY, this.valueY - this.stepY);\n } else {\n this.valueY = Math.max(this.maxY, this.valueY - this.stepY);\n }\n }", "_increaseY() {\n if (!this._invertedY()) {\n this.valueY = Math.min(this.maxY, this.valueY + this.stepY);\n } else {\n this.valueY = Math.min(this.minY, this.valueY + this.stepY);\n }\n }", "yTickDelta() {\n return 1;\n }", "function updateYPlot() {\r\n y.domain([0,globalymax])\r\n yAxis.transition().duration(1000).call(d3.axisLeft(y))\r\n }", "function barY(d) {\n return y(current(d));\n }", "function update_y_axis(y) {\n var new_y_offset = Math.abs(y - data[0]) * (1 + graph_buffer);\n if(new_y_offset > y_axis_offset) {\n y_axis_offset = new_y_offset;\n var y_axis_min = data[0] - y_axis_offset;\n var y_axis_max = data[0] + y_axis_offset;\n chart.yAxis[0].setExtremes(y_axis_min, y_axis_max);\n }\n}", "function calculateYScaleAndTranslation() {\n yScale = -graphHeight / (signal.getMaxValue() - signal.getMinValue());\n yTranslation = -yScale * signal.getMaxValue() + topMargin;\n }", "yOffset() {\n const minY = -this.h/2;\n let maxY = -this.requiredHeight + this.h/2;\n if(this.requiredHeight <= this.h) {\n maxY = minY;\n }\n\n return this.scrollPos * (maxY - minY);\n }", "_valueYChanged(value) {\n if (this.enableY) {\n this._handle.style.top = (this._canvas.scrollHeight)\n * ((value - this.minY) / (this.maxY - this.minY)) + 'px';\n }\n }", "function flipY(y) {\n\treturn h - y;\n}", "getMaxY(){ return this.y + this.height }", "downSlider() {\n this.y += this.sliderSpeed;\n this.y = (this.y >= this.usableHeight ? this.usableHeight : this.y);\n }", "function verticalScrollbarPos() {\n\t\tvar top = offset.y + height * pixelSize;\n\t\tvar bottom = canvas.height - offset.y;\n\t\treturn [canvas.width - 15, (top / (top + bottom)) * (canvas.height - 100)];\n\t}", "set originY(value) {\n this._originY = value;\n this.setViewBox(-this._originX, -this._originY, this._width, this._height);\n }", "getPageY() {\n return this.__event.pageY || 0;\n }", "function calculatePlayerYSpeed(player, timeDeltaSec) {\n var isPlayerJustJumped = player.justJumped && !player.isInAirNow;\n\n if (isPlayerJustJumped) {\n player.isInAirNow = true;\n player.speedY = JUMP_SPEED;\n jumpMusic.play()\n } else {\n if (player.isDead) {\n player.speedY = 3\n } else {\n player.speedY = player.speedY + GRAVITY * timeDeltaSec\n }\n }\n}", "get latestDelta() {\n return new Date(this.latestDeltaMs);\n }", "_updateYPosition() {\n this._updateSize();\n }", "getDeltaX() {\n return (this.getPageX() - ((this.__prevState.pageX !== undefined)\n ? this.__prevState.pageX : this.getPageX())) * this.getScaleX();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a panel footer with link
static panelFooter (text, pageUrl, absolute = false, refresh = false, widgetName) { return ( <div className='panel-footer'> {pageUrl && !absolute && <Link className='title-text' to={`/dashboard/${pageUrl}`}> {text} <i className='fa fa-chevron-right'></i> </Link> } {pageUrl && absolute && <a href={pageUrl} target="_blank" className="title-text"> {text} <i className='fa fa-chevron-right'></i> </a> } {!pageUrl && <div>{text}</div> } </div> ); }
[ "function makeNewFooter()\n {\n var wuLogo = document.createElement('img')\n wuLogo.setAttribute('src', 'http://icons.wxug.com/graphics/wu2/logo_130x80.png')\n wuLogo.setAttribute('class', 'img-responsive')\n\n var link = document.createElement('a')\n link.appendChild(wuLogo)\n link.setAttribute('href', 'http://www.wunderground.com')\n link.setAttribute('class', 'col')\n\n var footer = document.createElement('footer')\n footer.appendChild(link)\n footer.setAttribute('class', 'row')\n\n return footer\n }", "function T1_Footer () {\n\n var codeBuffer = \"\";\n\n codeBuffer += '<div class=\"wrapper row3\">';\n codeBuffer += '<footer id=\"footer\" class=\"clear\">';\n codeBuffer += '<p class=\"fl_left\">' + GenerateTitle() + '<a href=\"#\">' + GenerateTitle() + '</a></p>'; \n codeBuffer += '<p class=\"fl_right\">' + GenerateTitle() + '<a target=\"_blank\" href=\"#\">' + GenerateTitle() + '</a></p>'; \n codeBuffer += '</footer>'; \n codeBuffer += '</div>'; \n\n return codeBuffer;\n}", "function updateFooter(obj) {\n\tvar html = '';\n\n\tif (obj != undefined) {\n\t\thtml += '<a href=\"content_main\" class=\"main_link\">Main Menu</a>';\n\t}\n\t\n\tif (obj != undefined && obj.type == 'lesson') {\n\t\thtml += ' - <a href=\"' + obj.parent.index + '\" class=\"role_link\">Lessons</a>';\n\t\tif (obj.prev != null) {\n\t\t\thtml += ' - <a href=\"' + obj.prev.index + '\" class=\"lesson_link\">Previous Lesson</a>';\t\t\t\n\t\t}\n\t\tif (obj.next != null) {\n\t\t\thtml += ' - <a href=\"' + obj.next.index + '\" class=\"lesson_link\">Next Lesson</a>';\t\t\t\n\t\t}\n\t}\n\t\n\t$('#footer').html(html);\n\t\n\t$('#footer .main_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tswitchContent();\n\t});\n\n\t$('#footer .role_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLessons(getRole($(this).attr('href')));\n\t});\n\n\t$('#footer .lesson_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLesson(getLesson($(this).siblings('.role_link').attr('href'), $(this).attr('href')));\n\t});\n}", "refreshFooter() {}", "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}", "function CreateWindowFooter ()\n {\n\t\ttext += \" </table>\\n\";\n\t\ttext += \" </form>\\n\";\n\t\ttext += \" </body>\\n\";\n\t\ttext += \"</html>\\n\";\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 createTiddlerFooter(title,isEditor)\n{\n\tvar theFooter = document.getElementById(\"footer\" + title);\n\tvar tiddler = store.tiddlers[title];\n\tif(theFooter && tiddler instanceof Tiddler)\n\t\t{\n\t\tremoveChildren(theFooter);\n\t\tinsertSpacer(theFooter);\n\t\tif(isEditor)\n\t\t\t{\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tvar lingo = config.views.wikified.tag;\n\t\t\tvar prompt = tiddler.tags.length == 0 ? lingo.labelNoTags : lingo.labelTags;\n\t\t\tvar theTags = createTiddlyElement(theFooter,\"div\",null,null,prompt);\n\t\t\tfor(var t=0; t<tiddler.tags.length; t++)\n\t\t\t\t{\n\t\t\t\tvar theTag = createTagButton(theTags,tiddler.tags[t],tiddler.title);\n\t\t\t\tcreateTiddlyText(theTags,\" \");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n}", "function togle_footer(){\n if(footer_hidden){\n showFooter();\n footer_hidden = false;\n }else{\n hideFooter();\n footer_hidden = true;\n }\n}", "function ListBoxFooter() {\r\n bind.ListBoxFooter();\r\n }", "_defaultFooterRenderer() {}", "function echoFooter()\n{\n echo('</body>');\n echo('</html>');\n}", "function ebiFrameworkUpdateFooterMeta() {\n var d = new Date();\n var html = '<div class=\"columns\">' + '<p class=\"address\">EMBL-EBI, Wellcome Genome Campus, Hinxton, Cambridgeshire, CB10 1SD, UK. +44 (0)1223 49 44 44</p> <p class=\"legal\">Copyright &copy; EMBL ' + d.getFullYear() + ' | EMBL-EBI is <a href=\"http://www.embl.org/\">part of the European Molecular Biology Laboratory</a> | <a href=\"https://www.ebi.ac.uk/about/terms-of-use\">Terms of use</a>' +\n // '<a class=\"readmore float-right\" href=\"http://intranet.ebi.ac.uk\">Intranet</a>' +\n '</p></div>';\n\n function init() {\n try {\n var foot = document.getElementById('ebi-footer-meta');\n foot.innerHTML = html;\n } catch (err) {\n setTimeout(init, 500);\n }\n }\n init();\n}", "function loadFooter() {\n loadSection(\"/Frontend/shared/footer/footer.html\")\n .then(html => {\n document.getElementById(\"footerContainer\").innerHTML = html;\n })\n .catch(error => {\n console.warn(error);\n });\n}", "function createPanel( pw, ph, director ){\n\t\tdashBG = new CAAT.Foundation.ActorContainer().\n\t\t\t\t\tsetPreferredSize( pw, ph ).\n\t\t\t\t\tsetBounds( 0, 0, pw, ph ).\n\t\t\t\t\tsetClip(false);\n\n \n\t\t//create bottom panel\n\t\tfor(var i=0;i<dashBoardEle.length;i++){\n\t\t\tvar oActor = game.__addImageOnScene( game._director.getImage(dashBoardEle[i][0]), 1, 1 );\n\t\t\toActor.\t\t\t\n\t\t\t\tsetLocation(dashBoardEle[i][1], dashBoardEle[i][2]);\n\t\t\t\n\t\t\tdashBG.addChild(oActor);\t\t\t\n\t\t}\t\t\t\n\t\t\n\t\t__createDashBoardTxt();\n\t\t__createDashBoardButton();\t\n\t\t__createIncDecButton();\n\t\treturn dashBG;\n\t}", "function killFooter() {\r\n var footer = storeSalesTable.lastChild;\r\n footer.remove();\r\n}", "onRenderFooterContent() {\n return (\n <div>\n <PrimaryButton onClick={() => this.handleSave()} styles={buttonStyles}>\n Save\n </PrimaryButton>\n <DefaultButton onClick={() => this.dismissPanel()}>Cancel</DefaultButton>\n </div>\n );\n }", "function pdfSetFooter(pdfObject) {\n var number_of_pages = pdfObject.internal.getNumberOfPages()\n var pdf_pages = pdfObject.internal.pages\n var today = new Date();\n var date = today.getDate() + \"/\" + (today.getMonth()+1) + \"/\" + today.getFullYear();\n var myFooter = \"Risk Analysis Report: \" + projectManager.project.name + ' - ' + date\n // Iterate over pages, not including 1st page\n for (var i = 2; i < pdf_pages.length; i++) {\n // We are telling our pdfObject that we are now working on this page\n pdfObject.setPage(i)\n // Set small grey font\n pdfObject.setFontSize(8);\n pdfObject.setTextColor(145, 145, 145);\n // print title\n pdfObject.text(myFooter, 40, 30)\n // print page number\n pdfObject.text('Page: ' + i, 520, 30)\n }\n}", "function Footer() {\r\n return (\r\n <footer className=\"footer\">\r\n <div className=\"footer_items\">\r\n <a\r\n href=\"https://www.facebook.com/profile.php?id=100007830062724\"\r\n target=\"blank\"\r\n >\r\n <img\r\n src=\"/images/FooterIcon/facebook.png\"\r\n alt=\"facebook\"\r\n title=\"facebook\"\r\n />\r\n </a>\r\n <a href=\"https://www.instagram.com\" target=\"blank\">\r\n <img\r\n src=\"/images/FooterIcon/instagram.png\"\r\n alt=\"instagram\"\r\n title=\"instagram\"\r\n />\r\n </a>\r\n <a href=\"https://www.whatsapp.com\" target=\"blank\">\r\n <img\r\n src=\"/images/FooterIcon/whatsapp.png\"\r\n alt=\"whatsapp\"\r\n title=\"whatsapp\"\r\n />\r\n </a>\r\n <a\r\n href=\"https://www.linkedin.com/in/naveen-singh-1a474419a/\"\r\n target=\"blank\"\r\n >\r\n <img\r\n src=\"/images/FooterIcon/linkedin.png\"\r\n alt=\"linkedin\"\r\n title=\"linkedin\"\r\n />\r\n </a>\r\n </div>\r\n <div className=\"footer_desc\">\r\n <p>India</p>\r\n <p>© 2021 Shoe's factory, Inc. All Rights Reserved</p>\r\n <p>Created by Naveen Singh</p>\r\n </div>\r\n </footer>\r\n );\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Skip the playback of the current ad.
skip () { this._debug.log("skip"); // Skip the ad player if (this._vastPlayerManager) { this._vastPlayerManager.skip(); } }
[ "skipNext() {\n const { selectedSongIdx } = this.state\n const isAtLoopPoint = selectedSongIdx >= this.countTracks() - 1 ||\n selectedSongIdx < 0\n\n const songIdx = isAtLoopPoint ? 0 : (selectedSongIdx + 1)\n\n this.selectSong(songIdx)\n this.play(songIdx)\n }", "skipPrevious() {\n const { selectedSongIdx } = this.state\n const songIdx = selectedSongIdx < 1 ? (this.countTracks() - 1)\n : selectedSongIdx -1\n\n this.selectSong(songIdx)\n this.play(songIdx)\n }", "function disablePlay(reason) {\n\t$(shell.audio.play).addClass('dim');\n\t$(shell.audio.play).css('cursor','default');\n\tif (reason == 'end') {\n\t\t$(shell.audio.play).attr('title','Click the replay button to play the audio again.'); \n\t} else {\n\t\t$(shell.audio.play).attr('title','This page has no audio.'); \n\t}\n\taudioIsDim = true;\n}", "pause () {\n\n this._debug.log(\"Pause\");\n // Stop the ad player\n if (this._vastPlayerManager) {\n this._vastPlayerManager.pause();\n }\n }", "function skipToProducts(){\n\tstopVideo();\t\n utils.OpenPage(\"Products recommendation\",\"/Input Management/recommendedProducts.html\",productObj);\n}", "function onContentPauseRequested() {\n isAdPlaying = true;\n videoContent.pause();\n // This function is where you should setup UI for showing ads (for example,\n // display ad timer countdown, disable seeking and more.)\n // setupUIForAds();\n}", "function stopSnippet(){\n return playSong.pause();\n }", "resume() {\n this.paused_ = false;\n this.resetAutoAdvance_();\n }", "function hideaudiowrapper() {\n $(\"#audiowrapper\").animate({'margin-top':'403px'},350);\n $(\"#imgclose\").fadeOut(1000);\n\t$(\"#audio-player\")[0].currentTime = 0;\n\taudioPause();\n}", "function adBlockNotDetected() {\n }", "skipTransaction(transaction, reason) {\n transaction.skip = true;\n\n this.ensureTransactionErrors(transaction);\n if (reason) {\n transaction.errors.push({ severity: 'warning', message: reason });\n }\n\n if (!transaction.test) {\n transaction.test = this.createTest(transaction);\n }\n transaction.test.status = 'skip';\n if (reason) {\n transaction.test.message = reason;\n }\n\n this.ensureTestStructure(transaction);\n }", "function skip_Button(){\n\t$('#skip-btn').on('click', function(event){\n\t\tevent.preventDefault();\n\t\tskipped ++;\n\t\tclear_Data();\n\t\tnew_Game_Board();\n\t});\n}", "function video_doubleclick(e) {\n\te.preventDefault();\n\tthis.currentTime = 0;\n\tthis.play();\n}", "function resumeTrack() {\n if (current_track_id !== null) {\n audioTracks[current_track_id].play();\n }\n}", "function handleAutoSkip() {\r\n\t// By default, the auto-skip method is the same as the reviewtoken. Specific conditions may alter that.\r\n\tvar autoSkipMethod = attributes.reviewtoken;\r\n\r\n\t// The socialApply reviewtoken can force a particular auto-skip type.\r\n\tif ( ( attributes.reviewtoken === 'socialApply' || attributes.reviewtoken === 'socialSubscribe' ) && typeof attributes.socialsrc === 'string' ) {\r\n\t\tswitch ( attributes.socialsrc ) {\r\n\t\t\tcase 'li':\r\n\t\t\t\tautoSkipMethod = 'linkedin';\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'fb':\r\n\t\t\t\tautoSkipMethod = 'facebook';\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tswitch ( autoSkipMethod ) {\r\n\t\tcase 'AwL':\r\n\t\tcase 'linkedin':\r\n\t\t\tsetPleaseWaitMessage(jsStr.tcliwaiting);\r\n\t\t\tsetPleaseWaitNotes(jsStr.tcliescape + ' <a id=\"escapeLinkedIn\" href=\"\">' + jsStr.tcliescapeaction + '</a>.');\r\n\r\n\t\t\tif ( typeof IN === 'object' ) {\r\n\t\t\t\t// Anonymous function as callback function\r\n\t\t\t\tIN.User.authorize((function(){}));\r\n\t\t\t}\r\n\r\n\t\t\tbreak;\r\n\r\n\t\tcase 'facebook':\r\n\t\t\tsetPleaseWaitMessage(jsStr.tcliwaiting.replace(/LinkedIn/g,'Facebook'));\r\n\t\t\tsetPleaseWaitNotes(jsStr.tcliescape.replace(/LinkedIn/g,'Facebook') + ' <a id=\"escapeLinkedIn\" href=\"\">' + jsStr.tcliescapeaction + '</a>.');\r\n\r\n\t\t\tif ( typeof FB === 'object' ) {\r\n\t\t\t\tFB.getLoginStatus(function(response) {\r\n\t\t\t\t\tif ( response.status === 'connected' ) {\r\n\t\t\t\t\t\tloadFBForAutoSkip();\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\tfinishAutoSkipReview();\r\n\r\n\t\t\tbreak;\r\n\t}\r\n}", "function play_stop() {\n if(playing) {\n //video[v_index].play();\n video[v_index].loop();\n } else\n video[v_index].pause();\n\n playing = !playing;\n}", "function skip(testName) {\n \tif (focused$1) {\n \t\treturn;\n \t}\n\n \tvar test = new Test({\n \t\ttestName: testName,\n \t\tskip: true\n \t});\n\n \ttest.queue();\n }", "async disable () {\n // Disconnect everything\n this.mic.disconnect()\n this.scriptNode.disconnect()\n\n // Stop all media stream tracks and remove them\n this.media.getAudioTracks().forEach(\n (element) => {\n element.stop()\n this.media.removeTrack(element)\n }\n )\n\n // Close the context and remove it\n await this.context.close()\n this.context = null\n\n this.stats.teardown() // hide stats page\n this.isActive = false\n console.log('Audio Detection Disabled')\n }", "resetSampleOver() {\n this.audioOver.pause()\n this.audioOver.currentTime = 0\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the next batch of 10 cities processed and display them
function top10Cities() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 1) return; if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { var jsonToEval = xmlhttp.responseText; var responseData=eval(jsonToEval); /* responseData is of the form: [ {"name": "<cityName>", "greenspace": "<green_value>"} ... ] */ for(i = 0; i < 10; i++) { loadCity(responseData[i], i+1); } } else { alert("Error occured getting last 10 cities"); } } xmlhttp.open("GET", "cgi-bin/top10Cities.py", false); xmlhttp.send(); }
[ "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 getAllPlacesByStateAndCity(cities, result, callback) {\n\tvar items_processed = 0;\n\tif (cities.length !== 0) {\n\t\t\tcities.map( (data) => { \n\n\t\t\t\treqStates(`${API_URL}/states/${data.state_id}/cities/${data.city_id}/places`, (json) => {\n\t\t\t\t\titems_processed++;\n\t\t\t\t\tconst places = new Schema('places');\n\t\t\t\t\tlet norm_json = normalize(json, arrayOf(places));\n\t\t\t\t\tconsole.log(\"ta\", norm_json.entities);\n\t\t\t\t\tObject.assign(result.places, norm_json.entities.places);\n\t\t\t\t\tif (items_processed === cities.length) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\tcallback();\n\t\t}\n}", "function displayTenTopCities() {\n for (l = 0; l<10; l++) {\n var res = String.fromCharCode(65+l);\n displayCity = (res+\". \"+citiesScored[l].city + \" \" + (citiesScored[l].score).toFixed(4)+\", \");\n console.log(displayCity);\n $(\"#top10display\").append(displayCity);\n }\n }//End of displayTenTopCities()", "function displayCities() {\n var cityArray = instructorData.additionalData.moreDetails.citiesLivedIn;\n for (var i = 0; i < cityArray.length; i++) {\n console.log(cityArray[i]);\n }\n}", "function getBusinessesByCity(city) {\n $.get(\"/api/city/\" + city, result => {\n $(document.body).html(result);\n document.querySelector(\"#index-business-cards\").scrollIntoView({\n behavior: \"smooth\"\n });\n });\n }", "function showInitialCities() {\n Object.keys(INITIALCITIES).forEach(function(cityName) {\n displayTeleportCity(cityName);\n });\n }", "nextCity(index) {\n this.setState({ slider1ActiveSlide: index });\n this.props.requestClimate(this.props.citys[index].key);\n }", "function nextResult() {\n qc.showBigDatasets = false;\n qwQueryService.nextResult();\n $timeout(swapEditorFocus,10);\n }", "async function getCityWeatherData (TARGET_CITIES, API_KEY, WEATHERBIT_API_URL){\n let finalizedCityWeatherInformationObject = {};\n for (let targetCity in TARGET_CITIES){\n let currentCityName = targetCity;\n let currentCityLat = TARGET_CITIES[targetCity].lat;\n let currentCityLon = TARGET_CITIES[targetCity].lon;\n console.log(\"getCityWeatherData is running for \"+currentCityName)\n try{\n finalizedCityWeatherInformationObject[targetCity] = await callWeatherAPI(\n currentCityName,\n currentCityLat,\n currentCityLon,\n API_KEY,\n WEATHERBIT_API_URL\n );\n }\n catch (error){\n return error; //returns to MainProgramLoop catch\n }\n }\n return finalizedCityWeatherInformationObject;\n}", "async function populateAllLocations(url){\n let response;\n let nextPage='/locations?page=22&perPage=1000';\n \n do{\n let locationIds = [];\n console.log(\"Fetching remote data: \", url+nextPage)\n response = await axios.get(url+nextPage);\n nextPage = response.data.nextPageUri;\n \n for (let i=0, len=response.data.locations.length; i<len; i++){\n locationIds.push(response.data.locations[i].locationId)\n }\n \n let locations = await getIndividualLocations(locationIds);\n \n for (let i=0, len=locations.length; i<len; i++){\n await models.location.create({\n locationid:locations[i].locationId,\n locationname: locations[i].name,\n addressline1: locations[i].postalAddressLine1,\n addressline2: locations[i].postalAddressLine2,\n towncity: locations[i].postalAddressTownCity,\n county: locations[i].postalAddressCounty,\n postalcode: locations[i].postalCode,\n mainservice: (locations[i].gacServiceTypes.length>0) ? locations[i].gacServiceTypes[0].name : null\n })\n }\n } while (nextPage != null);\n }", "function getBusinessesByCityAndCategory(city, category) {\n $.get(\"/api/cityandcategory/\" + city + \"/\" + category, result => {\n $(document.body).html(result);\n document.querySelector(\"#index-business-cards\").scrollIntoView({\n behavior: \"smooth\"\n });\n });\n }", "function loadCity(){\n var url = 'http://api.openweathermap.org/data/2.5/weather?q='+cities.value()+\n '&APPID=f02124924447c73bc1d1626b1bee5f45&units=imperial';//set units=metric if you prefer Celcius\n loadJSON(url,setCity);\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 showTeleportCities() {\n clearMarkers();\n Object.keys(TELEPORTCITIES).forEach(function(cityName, index) {\n let zoomMax = MAP.maxZoom - MAP.minZoom;\n let zoomCurr = MAP.getZoom() - MAP.minZoom;\n if (index % zoomMax < (zoomCurr)) {\n displayTeleportCity(cityName);\n }\n });\n }", "async loadCards() {\n await JsonPlaceholder.get(\"/posts\", {\n params: {\n _start: this.props.cardList.length + 1,\n },\n })\n .then((res) => {\n this.props.fetchCardsSuccess({\n loadMore: !(res.data.length < 10),\n cardList: res.data,\n });\n })\n .catch((err) => {\n this.props.fetchCardsFailed();\n });\n }", "function getTheWeather(citiesList) {\n for (var v = 0; v < citiesList.length; v++) {\n getLocationID(citiesList[v]);\n }\n\n // Timeout is because the HTTP request takes time to return a response and the program continues, I didn't know Nodejs and how to make it wait so there is an artificial delay.\n // The worse the connection is, the longer the delay should be for it to work. Two seconds have always worked for me.\n\n setTimeout(function () {\n for (var c = 0; c < locationsIDList.length; c++) {\n weatherAPICall(\"https://e991c948-8998-4900-bfdf-e553523b48a9:QKv1Wq0yUE@twcservice.eu-gb.mybluemix.net:443/api/weather/v1/geocode/\" + locationsIDList[c][0] + \"/observations.json?units=m&language=en-US\", locationsIDList[c][1]);\n }\n }, 2000);\n}", "function displayTeleportCity(cityName) {\n const general_settings = {\n url : `https://api.teleport.org/api/cities/` ,\n data : {\n search : `${cityName}` ,\n limit : 3\n } ,\n dataType : `json` ,\n type : `GET` ,\n success : function(data) {\n if (verifyTeleportDataNotEmpty(data)) {\n let city = data._embedded[`city:search-results`][0];\n let cityDetails = getTeleportCityInfo(city);\n addMarker(cityDetails);\n }\n } ,\n error : failedSearch ,\n };\n $.ajax(general_settings);\n }", "function show_city_traderoutes()\n{\n if (active_city == null || active_city['trade'] == null) return;\n\n var msg = \"\";\n for (var i = 0; i < active_city['trade'].length; i++) {\n var tcity_id = active_city['trade'][i];\n if (tcity_id == 0) continue;\n var tcity = cities[tcity_id];\n msg += tcity['name'] + \" (\" + active_city['trade_value'][i] + \")\" + \"<br>\";\n }\n if (msg == \"\") msg = \"No traderoutes.\";\n $(\"#city_traderoutes_tab\").html(msg);\n\n}", "function loadMoreResults(){\n results += 10 \n showTruckResults()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]]) This function moves options between select boxes. Works best with multiselect boxes to create the common Windows control effect. Passes all selected values from the first object to the second object and resorts each box. If a third argument of 'false' is passed, then the lists are not sorted after the move. If a fourth string argument is passed, this will function as a Regular Expression to match against the TEXT or the options. If the text of an option matches the pattern, it will NOT be moved. It will be treated as an unmoveable option. You can also put this into the object as follows: onDblClick="moveSelectedOptions(this,this.form.target) This way, when the user doubleclicks on a value in one box, it will be transferred to the other (in browsers that support the onDblClick() event handler).
function moveSelectedOptions(from,to) { // Unselect matching options, if required if (arguments.length>3) { var regex = arguments[3]; if (regex != "") { unSelectMatchingOptions(from,regex); } } // Move them over for (var i=0; i<from.options.length; i++) { var o = from.options[i]; if (o.selected) { to.options[to.options.length] = new Option( o.text, o.value, false, false); } } // Delete them from original for (var i=(from.options.length-1); i>=0; i--) { var o = from.options[i]; if (o.selected) { from.options[i] = null; } } if ((arguments.length<3) || (arguments[2]==true)) { sortSelect(from); sortSelect(to); } from.selectedIndex = -1; to.selectedIndex = -1; }
[ "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 moveSelectedItemsDown(src) {\r\n var i;\r\n for (i = src.options.length - 1; i >= 0; --i) {\r\n var thisitem = src.options[i];\r\n if (thisitem.selected == true) {\r\n // already at the end\r\n if (i == src.options.length - 1) {\r\n return;\r\n } else {\r\n // move the item down\r\n var nextItem = src.options[i + 1];\r\n\r\n thisoption = new Option(thisitem.text, thisitem.value, false, false);\r\n swapoption = new Option(nextItem.text, nextItem.value, false, false);\r\n src.options[i] = swapoption;\r\n src.options[i + 1] = thisoption;\r\n thisoption.selected = true;\r\n }\r\n }\r\n }\r\n}", "function moveSelectedItems(src, dest) {\r\n moveItems(src, dest, true);\r\n}", "function moveOptionUp(obj) {\n\tfor (i=0; i<obj.options.length; i++) {\n\t\tif (obj.options[i].selected) {\n\t\t\tif (i != 0 && !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 copySelectedOptions(from,to) {\n\tvar options = new Object();\n\tfor (var i=0; i<to.options.length; i++) {\n\t\toptions[to.options[i].value] = to.options[i].text;\n\t\t}\n\tfor (var i=0; i<from.options.length; i++) {\n\t\tvar o = from.options[i];\n\t\tif (o.selected) {\n\t\t\tif (options[o.value] == null || options[o.value] == \"undefined\" || options[o.value]!=o.text) {\n\t\t\t\tto.options[to.options.length] = new Option( o.text, o.value, false, false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tif ((arguments.length<3) || (arguments[2]==true)) {\n\t\tsortSelect(to);\n\t\t}\n\tfrom.selectedIndex = -1;\n\tto.selectedIndex = -1;\n\t}", "function _move_between_selects(block, myForm, multiselect1, multiselect2) {\n\n\tvar ida = (block ? multiselect1 : multiselect2);\n\tvar idb = (block ? multiselect2 : multiselect1);\n\n\tvar sa = myForm.getSelect(ida);\n\tvar sb = myForm.getSelect(idb);\n\n\tvar t = myForm.getItemValue(ida);\n\tif (t.length == 0)\n\t\treturn;\n\teval(\"var k={'\" + t.join(\"':true,'\") + \"':true};\");\n\n\tvar w = 0;\n\tvar ind = -1;\n\twhile (w < sa.options.length) {\n\t\tif (k[sa.options[w].value] && sa.options[w].value != 'rhumanos@silencor.pt' && sa.options[w].value != 'administracao@silencor.pt') {\n\t\t\tsb.options.add(new Option(sa.options[w].text, sa.options[w].value));\n\t\t\tsa.options.remove(w);\n\t\t\tind = w;\n\t\t} else {\n\t\t\tw++;\n\t\t}\n\t}\n\n\tif (sa.options.length > 0 && ind >= 0)\n\t\tif (sa.options.length > 0)\n\t\t\tsa.options[t.length > 1 ? 0 : Math.min(ind, sa.options.length - 1)].selected = true;\n}", "function transferSelection(id1, id2) {\n obj1 = document.getElementById(id1).options;\n obj2 = document.getElementById(id2).options;\n for (var i=0; i<obj1.length; i++) {\n if (!obj1[i].selected) continue;\n found = false;\n for (var j=0; j<obj2.length; j++) {\n if (obj2[j].value==obj1[i].value) {\n found = true;\n break;\n }\n }\n if (!found) {\n obj2[obj2.length] = new Option(obj1[i].text, obj1[i].value, false, false);\n }\n }\n}", "function datagrid_toggle_sort_selects() {\n var jq_dds = $('.datagrid .header .sorting dd');\n if (jq_dds.length == 0) return;\n var dd1 = jq_dds.eq(0)\n var dd2 = jq_dds.eq(1)\n var dd3 = jq_dds.eq(2)\n var sb1 = dd1.find('select');\n var sb2 = dd2.find('select');\n var sb3 = dd3.find('select');\n\n if( sb1.val() == '' ) {\n dd2.hide();\n sb2.val('');\n dd3.hide();\n sb3.val('');\n } else {\n dd2.show();\n if( sb2.val() == '' ) {\n dd3.hide();\n sb3.val('');\n } else {\n dd3.show();\n }\n }\n\n $('dl.sorting select option').removeAttr('disabled');\n disable_sort(sb3);\n disable_sort(sb2);\n disable_sort(sb1);\n}", "function moveItemUpToMediumPriorityList() {\n jQuery('#lowPriorityList option:selected').appendTo('#mediumPriorityList');\n jQuery('#lowPriorityList option:selected').remove();\n jQuery('#mediumPriorityList option:selected').prop(\"selected\", false);\n}", "function moveItemUpToHighPriorityList() {\n jQuery('#mediumPriorityList option:selected').appendTo('#highPriorityList');\n jQuery('#mediumPriorityList option:selected').remove();\n jQuery('#highPriorityList option:selected').prop(\"selected\", false);\n}", "function markSelected(controlID, type) {\n $(\"#\" + controlID + \" option\").each(function () {\n if ($(this).val() == type) {\n $(this).prop(\"selected\", true);\n }\n });\n}", "function copySelectedItems(src, dest) {\r\n var i;\r\n\r\n deselectAllItems(dest);\r\n for (i = 0; i < src.options.length; ++i) {\r\n var thisoption = src.options[i];\r\n if (thisoption.selected == true) {\r\n var option = findItemByValue(dest, thisoption.value);\r\n if (option != null) {\r\n option.selected = true;\r\n } else {\r\n appendNewItem(dest, thisoption.text, thisoption.value, true);\r\n }\r\n }\r\n }\r\n}", "function ClearSelectOptions( obj )\n{\n if( obj == undefined || obj == null ) return ;\n try\n {\n for( var i = obj.options.length - 1; i >= 0 ; i -- )\n obj.options.remove(i) ;\n return ;\n }\n catch(err)\n {\n return ;\n }\n}", "function build_your_own_different_dvd_options(optionSet1, optionSet2){\n var focus = 'selectboxit-focus';\n var selected = 'selectboxit-selected'; \n window.firstDvdSelection = false;\n window.seconDDvdSelection = false;\n\n // Find element in first select\n optionSet1.children().each(function(){\n if($(this).hasClass(focus)){\n window.firstDvdSelection = $(this);\n } \n });\n // Find element in second select\n optionSet2.children().each(function(){\n if($(this).hasClass(focus)){\n window.seconDDvdSelection = $(this);\n } \n });\n\n // If they are not undefined and if they are the same\n if(window.firstDvdSelection != false && window.seconDDvdSelection != false){\n if(window.firstDvdSelection.text() == window.seconDDvdSelection.text()){\n // Initialize selectboxit\n var selectBox = $('#build-your-own-two select').selectBoxIt().data('selectBox-selectBoxIt');\n selectBox.selectOption(0);\n } \n }\n }", "function moveItemDownToLowPriorityList() {\n jQuery('#mediumPriorityList option:selected').appendTo('#lowPriorityList');\n jQuery('#mediumPriorityList option:selected').remove();\n jQuery('#lowPriorityList option:selected').prop(\"selected\", false);\n}", "_optionSelected(e) {\n let local = e.target;\n // fire that an option was selected and about what operation\n let ops = {\n element: this,\n operation: this.activeOp,\n option: local.getAttribute(\"id\"),\n };\n this.dispatchEvent(\n new CustomEvent(\"item-overlay-option-selected\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail: ops,\n })\n );\n // don't reset for movement, just confirm / reject actions\n if (this.activeOp != \"move\") {\n this._resetActive();\n this.activeOp = null;\n }\n }", "function select_innerHTML(objeto, innerHTML) {\n /******\n * select_innerHTML - corrige o bug do InnerHTML em selects no IE\n * Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228\n * Vers‹o: 2.1 - 04/09/2007\n * Autor: Micox - N‡iron Josˇ C. Guimar‹es - micoxjcg@yahoo.com.br\n * @objeto(tipo HTMLobject): o select a ser alterado\n * @innerHTML(tipo string): o novo valor do innerHTML\n *******/ \n objeto.innerHTML = \"\"\n var selTemp = document.createElement(\"micoxselect\")\n var opt;\n selTemp.id = \"micoxselect1\"\n document.body.appendChild(selTemp)\n selTemp = document.getElementById(\"micoxselect1\")\n selTemp.style.display = \"none\"\n if (innerHTML.toLowerCase().indexOf(\"<option\") < 0) {//se n‹o ˇ option eu converto\n innerHTML = \"<option>\" + innerHTML + \"</option>\"\n }\n innerHTML = innerHTML.toLowerCase().replace(/<option/g, \"<span\").replace(\n /<\\/option/g, \"</span\")\n selTemp.innerHTML = innerHTML\n\n for ( var i = 0; i < selTemp.childNodes.length; i++) {\n var spantemp = selTemp.childNodes[i];\n\n if (spantemp.tagName) {\n opt = document.createElement(\"OPTION\")\n\n if (document.all) { //IE\n objeto.add(opt)\n } else {\n objeto.appendChild(opt)\n }\n\n //getting attributes\n for ( var j = 0; j < spantemp.attributes.length; j++) {\n var attrName = spantemp.attributes[j].nodeName;\n var attrVal = spantemp.attributes[j].nodeValue;\n if (attrVal) {\n try {\n opt.setAttribute(attrName, attrVal);\n opt.setAttributeNode(spantemp.attributes[j]\n .cloneNode(true));\n } catch (e) {\n }\n }\n }\n //getting styles\n if (spantemp.style) {\n for ( var y in spantemp.style) {\n try {\n opt.style[y] = spantemp.style[y];\n } catch (e) {\n }\n }\n }\n //value and text\n opt.value = spantemp.getAttribute(\"value\")\n opt.text = spantemp.innerHTML\n //IE\n opt.selected = spantemp.getAttribute('selected');\n opt.className = spantemp.className;\n }\n }\n document.body.removeChild(selTemp)\n selTemp = null\n }", "function updateSelBoxes(obj,val)\n{\n selstr = obj.value;\n if (selstr==\"\"){\n obj.value = val;\n return;\n }\n var arr = selstr.split(\", \");\n index = -1;\n for (i=0;i<arr.length;i++){\n if (arr[i]==val){\n //get index of val in array\n index = i;\n }\n }\n if (index > -1){\n //remove val from array\n arr.splice(index,1);\n } else {\n //add val to array\n arr.push(val);\n }\n obj.value = arr.join(\", \");\n}", "function datagrid_activate_mselect_ui(jq_select) {\n var all_opt = $(jq_select).find('option[value=\"-1\"]');\n var use_all_opt = (all_opt.text() == _('-- All --', 'webgrid'));\n if ( use_all_opt ) {\n $(all_opt).detach();\n }\n if (jq_select.data('multipleSelect')) {\n jq_select.hide();\n } else {\n jq_select.webgridMultipleSelect({\n minumimCountSelected: 2,\n filter: true\n });\n jq_select.parent().find('.ms-parent > button, .ms-drop').each(function() {\n $(this).css('width', $(this).width() + 60);\n });\n }\n jq_select.siblings('.ms-parent').show();\n jq_select.attr('multiple', 'multiple');\n if ( use_all_opt ) {\n $(all_opt).prependTo(jq_select);\n }\n}", "function setSelectOptions(options, selector) {\n for (var i=0; i < options.length; i++) {\n var newOption = document.createElement('option');\n\n newOption.text = options[i];\n selector.appendChild(newOption);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FETCH ALL ARCHIVED NOTES
async getAllArchivedNotes(req, res) { try { const archivedNotes = await Notes.find({isArchived: 'true', author: res.user.id.email, isDeleted: false}); logger.verbose( `Status: ${res.statusCode}: Successfully fetched all archived notes` ); return res.status(200).json(archivedNotes); } catch (error) { logger.error(`Status: ${res.statusCode}: ${error.message}`); return res.status(500).json({ message: error }); } }
[ "loadNotesFromDB (context) {\n return db.notes.orderBy('dateModified').reverse().toArray().then((notes) => {\n console.log(`${notes.length} notes loaded from db`)\n return context.commit({\n type: 'setNotes',\n options: notes\n })\n })\n }", "function getAllTextNotes(){\n\tvar count = 0;\n\ttext_noteRef.once(\"value\")\n\t .then(function(snapshot) {\n\t\t snapshot.forEach(function(childSnapshot) {\n\t\t \tcount += 1;\n\t\t var eachNote = childSnapshot.val();\n\t\t showTextNote(childSnapshot.key, eachNote.note);\n\t\t });\n\t });\n}", "function allNotesSortedByChanged(): Array<TNote> {\n const projectNotes = DataStore.projectNotes.slice()\n const calendarNotes = DataStore.calendarNotes.slice()\n const allNotes = projectNotes.concat(calendarNotes)\n const allNotesSortedByDate = allNotes.sort(\n (first, second) => second.changedDate - first.changedDate,\n ) // most recent first\n return allNotesSortedByDate\n}", "getJournals() {\n console.log(\"fetching journals\")\n API.getJournalEntries().then(parsedJournals => {\n displayJournals(parsedJournals);\n })\n }", "async getNotes() {\n\t\ttry {\n\t\t\tconst notes = await readFileAsync(\"db/db.json\", \"utf8\");\n\t\t\treturn JSON.parse(notes);\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}", "async getAllDeletedNotes(req, res) {\n try {\n const deletedNotes = await Notes.find({isDeleted: 'true', author: res.user.id.email});\n logger.verbose(\n `Status: ${res.statusCode}: Successfully fetched all deleted notes`\n );\n return res.status(200).json(deletedNotes);\n } catch (error) {\n logger.error(`Status: ${res.statusCode}: ${error.message}`);\n return res.status(500).json({ message: error });\n }\n }", "getAllNews() {\n\n this.dataBase.findByIndex(\"/news\", [\"_id\", \"title\", \"attachment\"],\"categoryId\", mvc.routeParams.id).then( data => {\n if (data) {\n let length = data.docs.length;\n this.liftNewsInCategory = data.docs.slice(0, length / 2);\n this.rightNewsInCategory = data.docs.slice(length / 2, length);\n mvc.apply();\n } else {\n this.getAllNews()\n }\n }, () => {\n this.getAllNews();\n });\n\n }", "async getDownloadedContent() {\n this.setState({ isLoading: true });\n var content = await DbQueries.queryVersions(\n this.props.language,\n this.props.versionCode,\n this.props.bookId,\n this.props.currentVisibleChapter\n );\n if (content != null) {\n this.setState({\n chapterHeader:\n content[0].chapters[this.state.currentVisibleChapter - 1]\n .chapterHeading,\n downloadedBook: content[0].chapters,\n chapterContent:\n content[0].chapters[this.state.currentVisibleChapter - 1].verses,\n isLoading: false,\n error: null,\n previousContent: null,\n nextContent: null,\n });\n } else {\n this.setState({\n chapterContent: [],\n unAvailableContent: true,\n isLoading: false,\n });\n }\n }", "function fetchArticles() {\n\treturn (dispatch) => {\n\t\tresource(\"GET\", \"articles\")\n\t\t.then(r => dispatch({type: 'articles', \n\t\t\tarticles: sortArticles(r.articles)}))\n\t}\n}", "static async getAll(lessonId) {\n const result = await db.query(\n `SELECT * FROM notes WHERE lesson_id = $1`, [lessonId]);\n if (result.rows.length === 0) {\n throw new ExpressError(`No notes`, 404);\n };\n return result.rows.map(n => new Note(n.id, n.lesson_id, n.note));\n }", "function getNotes(req,res,next){\n Note.find()\n .then(notes=>{\n let head;\n let i = notes.length-1;\n let temp = [];\n let j = -1;\n while(i>=0){ \n let note = notes[i];\n\n let next;\n if(i!==notes.length-1){\n next = temp[j];\n } else {\n next = null;\n }\n let tempNote = {\n note: note.note,\n image: note.image,\n mScore: 1,\n correct: 0,\n incorrect: 0,\n next: next\n };\n temp.push(tempNote); //[note.next = null, note.next = ]\n j++;\n i--;\n }\n head = temp[j];\n req.head = head;\n next();\n });\n}", "async function getNotes(){\n try{\n let arr=[];\n let value=await AsyncStorage.getItem('noteList');\n JSON.parse(value).map((n)=>{\n if(n.category===route.params.name){\n arr.push(n);}\n });\n if(arr.length!==notes.length){\n setNotes(arr);\n }\n }\n catch(error){\n console.log(error);\n }\n }", "getAllEntries() {\n //return a Promise object, which can be resolved or rejected\n return new Promise((resolve, reject) => {\n //use the find() function of the database to get the data, \n //with error first callback function, err for error, entries for data\n this.db.find({}, function(err, entries) {\n //if error occurs reject Promise\n if (err) {\n reject(err);\n //if no error resolve the promise and return the data\n } else {\n resolve(entries);\n //to see what the returned data looks like\n console.log('function all() returns: ', entries);\n }\n })\n })\n }", "function getMediaList( err ) {\n if( err ) {\n Y.log( 'error in deleting attachments', 'error', NAME );\n callback( err );\n return;\n }\n\n Y.doccirrus.mongodb.runDb( {\n 'migrate': true,\n 'action': 'get',\n 'model': 'media',\n 'user': user,\n 'query': {'ownerId': activity._id.toString()},\n 'callback': deleteFiles\n } );\n }", "function getDocsToArchive(criteria, primaryCollection) {\n var deferred = Q.defer();\n\n primaryCollection.find(criteria).toArray(function (err, items) {\n err ? deferred.reject(err) : deferred.resolve(items);\n });\n\n return deferred.promise;\n }", "async function getAllNotesDate(date) {\n const startDate = moment(date).format(\"YYYY-MM-DD\");\n // sets startDate with date passed into function\n const endDate = moment().format(\"YYYY-MM-DD\");\n // sets endDate to now\n\n return getAllNotesDateRange(startDate, endDate);\n // returns all posts between startDate and now using the getAllNotesDateRange function\n}", "getAllDocuments () {\n return this.getAllModels().map(model => model.document)\n }", "function getAllBooks() {\n return books;\n}", "function getLatestParakeetEntries(durationMs) {\n return app.pouchDB.allDocs({\n include_docs: true,\n startkey: 'sensor-entries-raw/' + helpers.isoTimestamp(app.currentTime() - durationMs),\n endkey: 'sensor-entries-raw/' + helpers.isoTimestamp(app.currentTime())\n })\n .then(res => res.rows.map(row => row.doc));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a section for the diagram and returns a pointer to its content
function createDiagramSection() { // Reviews hack: Only do it once if ($('#stroke_order').length == 0) { let sectionHTML = '<section><h2>Stroke Order</h2><div style="width:100%;overflow-x: auto; overflow-y: hidden"><svg id="stroke_order"></svg></div></section>' switch (curPage) { case PageEnum.kanji: $(sectionHTML).insertAfter('.span12 header') break case PageEnum.reviews: console.log('prepend') $('#item-info-col2').prepend(sectionHTML) break case PageEnum.lessons: $('#supplement-kan-breakdown .col1').append(sectionHTML) break } $(strokeOrderCss).appendTo('head') } return $('#stroke_order').empty() }
[ "function notebookStructure(){\n return '<section><div class=\"container\"><div class=\"timeline\"><div class=\"timeline-hline\"></div>'+notebook_content+'</div></div></section>'\n}", "addNodeInDefinition() {\n let node = this.get('selectedNode');\n\n if (isNone(node)) {\n return;\n }\n\n let view = this.get('view.definitionArray');\n\n // Create propertyName\n let propertyName = this.createPropertyName(node, this.get('treeObject').jstree(true));\n \n if (view.findBy('name', propertyName)) {\n return;\n }\n\n let newDefinition;\n switch (get(node, 'type')) {\n case 'property':\n newDefinition = FdViewAttributesProperty.create({\n name: propertyName\n });\n break;\n case 'master':\n newDefinition = FdViewAttributesMaster.create({\n name: propertyName\n });\n break;\n case 'detail':\n newDefinition = FdViewAttributesDetail.create({\n name: propertyName\n });\n break;\n }\n\n let indexOfSelectedProperty = this.getIndexOfSelectedProperty();\n\n if (indexOfSelectedProperty >= 0) {\n view.insertAt(indexOfSelectedProperty + 1, newDefinition);\n } else {\n view.pushObject(newDefinition);\n }\n\n }", "function drawbasiclayout()\n {\n points = []; // for storng title area points inorder\n linepoints = []; // for storing linegap points in discription area\n dispoints = []; // for storng title area points inorder\n\n // Initially titlearea and discriptionarea disabled\n titlekeyactive = false;\n diskeyactive = false;\n\n // Starting cursor positions for title and discription area\n pretitleposx = 0.25 * width;\n predisposx = 0.05 * width;\n pretitleposy = 0.7*0.1*height;\n predisposy = 0.3 * height;\n \n // Drawing Title , line and , Discription on each note \n ctx.clearRect(0,0,width,height);\n ctx.fillStyle = \"bisque\";\n ctx.fillRect(0,0,width,height);\n ctx.fillStyle = \"#141e30\";\n ctx.font = \"30px Pacifico\"; \n ctx.fillText(\"TITLE --\",4,0.7*0.1*height);\n ctx.beginPath();\n ctx.moveTo(0,0.12*height);\n ctx.lineTo(width,0.12*height);\n ctx.stroke();\n ctx.fillStyle='#141e30';\n ctx.font = \"30px Oleo Script\";\n ctx.fillText('DESCRIPTION' , 0.4*width , 0.17*height);\n }", "function creation() {\n return div('creation', \n row(\n col('col-4', div('creation__title title', 'News creation form')) + \n col('col-8', toolbox())\n ) +\n row(\n col('col-12', div('tab-content', textForm() + imageForm()))\n )\n \n ) \n}", "createElement() {\n console.log(this.line);\n this.$line = $('<div></div>')\n .addClass('Hero-graphic__terminal__line');\n\n if (this.line[0] != '') {\n this.$line.append('<span class=\"pre\">'+this.line[0]+'</span>');\n }\n\n this.$line\n .append('<div id=\"'+this.id+'\" class=\"text\"></div>')\n .append('<div class=\"cursor\" style=\"display: none\"></div>');\n }", "function prepareText(section) {\r\n for (let i = 0; i < heirarchy.tree[0].sections.length; i++) {\r\n d3.select(\"#text_container\").append(\"div\")\r\n .attr(\"id\", \"text-h1-\" + i)\r\n .attr(\"class\", \"text-h1\")\r\n .style(\"display\", \"none\")\r\n .html(heirarchy.tree[0].sections[i].text);\r\n }\r\n d3.select(\"#text-h1-\" + section.split(\".\")[1]).style(\"display\", \"block\");\r\n\r\n refreshHighlightTip();\r\n setupTooltips();\r\n\r\n}", "function FunH5oSemSection(eltStart) {\n this.ssArSections = [];\n this.ssElmStart = eltStart;\n /* the heading-element of this semantic-section */\n this.ssElmHeading = false;\n\n this.ssFAppend = function (what) {\n what.container = this;\n this.ssArSections.push(what);\n };\n this.ssFAsHTML = function () {\n var headingText = fnH5oGetSectionHeadingText(this.ssElmHeading);\n headingText = '<a href = \"#' + fnH5oGenerateId(this.ssElmStart) + '\">'\n + headingText\n + '</a>';\n return headingText + fnH5oGetSectionListAsHtml(this.ssArSections);\n };\n }", "function sectionOn() { }", "function addnewsection() {\n sectionNumber ++;\n\n //=======> Create Anther section\n let addSection = document.createElement('section');\n addSection.innerHTML = `\n <section id=\"section${sectionNumber}\" class=\"your-active-class\">\n <div class=\"landing__container\">\n <h2 id=\"se_${sectionNumber}\">Section ${sectionNumber}</h2>\n <p id=\"getActive_${sectionNumber}\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>\n </div>\n </section>`;\n mainSection.appendChild(addSection);\n\n //=======> Create Anther item in navbar\n let addli = document.createElement('li');\n addli.innerHTML = `<li ><a id=\"li_${sectionNumber}\" onclick=\"scroll_to('section${sectionNumber}')\">Section ${sectionNumber}</a></li>`;\n mynavbar.appendChild(addli);\n}", "function createDocumentation( sections ) {\n\n var documentedHtml = '',\n commentHtml = '',\n codeHtml = '',\n pretty = ( settings.pretty ) ? 'prettyprint' : '',\n linenums = 0;\n\n sections.forEach( function( s, indx ) {\n\n // add comments to line count since they always occur in a section before code\n linenums += s.comment.split(/\\|/).length - 1;\n if ( indx === 0) {\n commentHtml = '<div class=\"elucidate-comment-header\">' + formatHeader( s.comment ) + '</div>';\n documentedHtml +=\n '<div class=\"row elucidate-header\"> \\\n <div class=\"col-sm-12\">'+commentHtml+'</div> \\\n </div> \\\n <div class=\"row elucidate-row\"> \\\n <div class=\"col-sm-'+settings.width.comment+' elucidate-col-comment\"><div class=\"elucidate-comment elucidate-hack-width\">'+Array(settings.width.hack).join('&nbsp;')+'</div></div> \\\n <div class=\"col-sm-'+settings.width.code+' elucidate-col-code\"></div></div> \\\n </div>';\n } else {\n commentHtml = '<div class=\"elucidate-comment\">' + cheapMarkdown( s.comment ) + '</div>';\n codeHtml = (s.code !== '') ? '<pre class=\"elucidate-code '+pretty+' linenums:'+(linenums+1).toString() +'\">' + safeHtml( s.code ) + '</pre>' : '';\n documentedHtml +=\n '<div class=\"row elucidate-row\"> \\\n <div class=\"col-sm-'+settings.width.comment+' elucidate-col-comment\">'+commentHtml+'</div> \\\n <div class=\"col-sm-'+settings.width.code+' elucidate-col-code\">'+codeHtml+'</div> \\\n </div>';\n\n }\n // add code to line count\n linenums += s.code.split(/\\n/).length - 1 ;\n } );\n\n return documentedHtml;\n }", "createPlayableSection(section) {\n var playableSection = state.playableSections[section.name] = [];\n section.tracks.forEach(track => {\n var instrument = library.instruments[track.instrument];\n track.notes.forEach(note => {\n var time = 0;\n // Starting to understand this next line. shortest time we'll ever need is about 30ms\n // At 120 bpm, that's the time between 32nd notes, which will only get played for crazy fast doubles\n // But we can have triplets at the 16th level\n // Which makes sense, because that leaves the quarter notes untouched\n // Which is typically where the pulse is\n // And therefore switching from 4 to 3 between the pulse is dank\n note.time.forEach((count, level) => time += player.convertNotationToSteps(count, level)); // 1,0, 4,1\n if (playableSection[time])\n playableSection[time].push(instrument.notes[note.note].howl);\n else\n playableSection[time] = [instrument.notes[note.note].howl];\n });\n });\n return playableSection;\n }", "create() {\n this.children = [];\n this.container = document.createElement(\"div\");\n for (var i = 0; i < this.data.length; i++) {\n this.children.push(interfaceUnit(this.data[i], this.container));\n }\n return this.container;\n }", "function getSection( sectionPos ) {\r\n\t\treturn sections.eq( sectionPos );\r\n\t}", "function drawProgStructHead() {\r\n\r\n var pO = CurProgObj;\r\n var fO = CurFuncObj;\r\n var sO = CurStepObj;\r\n\r\n var com_opt = \"style='float:left' \";\r\n var com_id = getCommentHtmlId(CommentType.StepTitle, 0);\r\n var comment = getCommentStr('div', com_id, com_opt, sO.stepComment);\r\n\r\n // STEP: Span that is placed on the left\r\n //\r\n var curmod = getModuleSelectStr(); // CurModObj.name;\r\n var str = \"<span class='progStructHead'>\" +\r\n \" <span title='Current Module'>\" + curmod + \"</span> ::\";\r\n\r\n var curfunc = getFuncSelectStr();\r\n str += \" <span title='Current Function'>\" + curfunc + \"</span> :: \";\r\n\r\n //\t+ \" <span title='Current Function'>main()</span> :: \";\r\n\r\n // Step selection drop down box\r\n //\r\n str += \"<span> \" + getStepSelectStr() + \"</span>\";\r\n //\r\n // Get step advance arrow buttons\r\n //\r\n str += \"<span> \" + getStepArrowStr() + \"</span>\";\r\n\r\n str += \"<span> &nbsp </span> <span> &nbsp </span> \";\r\n\r\n // Display the step title. If sO.title is empty (null), we use a\r\n // default title. \r\n //\r\n var titletxt = sO.title;\r\n if (!titletxt) {\r\n titletxt = (sO.isHeader) ? DefHeaderTitle : DefStepTitle;\r\n }\r\n //\r\n // TODO: A text area causes a larger vertical space on Firefox. \r\n //\r\n var onc = \" onchange='recordStepTitle(this)' \";\r\n var title = \"<textarea rows='1' cols='30' class='stepTitle' \" +\r\n \" height=16px maxlength=40\" +\r\n\r\n \"id='StepTitle' \" + onc + \">\" + titletxt + \"</textarea>\";\r\n\r\n //title = \"<span class='stepTitleSpan' contenteditable>Title</span>\";\r\n\r\n\r\n // Comment for this step\r\n // NOTE: Changing this order causes Firefox to draw incorrectly\r\n //\r\n str += \"</span>\" + title + comment;\r\n\r\n\r\n // STEP: Start a new span that floats on to the right of the page\r\n //\r\n str += \"<span style='float:right'>\"; // place on the right\r\n var onc = \"\";\r\n\r\n // show parallelism meter only if configuration is done AND showing data\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) && pO.showData) {\r\n\r\n str += getParallelismMeterStr();\r\n\r\n } // if config done AND showing data\r\n\r\n\r\n // We can create a new step if config is done OR if we are in a header\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) || sO.isHeader) {\r\n\r\n onc = \" onclick='newNextStep(\" + fO.curStepNum + \")' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Insert New Step' \" + onc +\r\n \">\";\r\n }\r\n\r\n // We can duplicate a step only after completing it.\r\n // Note: We cannot duplicate the function header step\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) && !sO.isHeader) {\r\n onc = \" onclick='duplicateStep()' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Duplicate Step' \" + onc + \">\";\r\n }\r\n\r\n // We can cancel/delete a step only after starting to configure it\r\n // We can *never* cancel a header step\r\n //\r\n if ((sO.stageInStep >= StageInStep.New) && !sO.isHeader) {\r\n onc = \" onclick='deleteStep()' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Delete Step' \" + onc + \">\";\r\n }\r\n\r\n str += getMenuHeadStr();\r\n\r\n str += \"</span><BR>\"; // floating right span\r\n str += \"<HR>\"; // horizontal divider\r\n\r\n // Information Window\r\n //\r\n str += \"<span id='infoWin'></span>\";\r\n\r\n var head1 = document.getElementById('progHead');\r\n head1.innerHTML = str;\r\n\r\n // updateInfoWin(\"Sample Message\");\r\n}", "function initializeDiagram(cfg) {\n const svgEl = el('sankey_svg');\n svgEl.setAttribute('height', cfg.size_h);\n svgEl.setAttribute('width', cfg.size_w);\n svgEl.setAttribute(\n 'class',\n `svg_background_${cfg.bg_transparent ? 'transparent' : 'default'}`\n );\n svgEl.textContent = ''; // Someday use replaceChildren() instead\n}", "function addSection(id)\n{\n current_template_index=0;\n\n var sectionID = \"section-\"+current_section_index;\n\n showSidebarBrowser();\n $(\".browser-menu-item\").each(function(){\n $(this).prop(\"disabled\", false);\n });\n $(\".sidebar-browser\").attr(\"id\", sectionID);\n $(\".sidebar-browser\").data(\"template-index\", current_template_index);\n\n //html for sidebar section input\n var sectionHtml =\n '<div class=\"sidebar-item sidebar-section\"'+\n 'id=\"'+sectionID+'\">' +\n getSidebarButtonHtml(sectionID) +\n\n '<button class=\"sidebar-btn glyphicon glyphicon-remove remove-section-btn\"'+ //remove section btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '<span id=\"sidebar-title-section-'+ current_section_index +'\">Section Name</span>'+\n '<button class=\"sidebar-btn fa fa-toggle-on toggle-linebreak\"'+ //toggle line break btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '</div>';\n\n current_section_index+=1;\n\n\n $(\".section-list\").append(sectionHtml);\n\n var sectionHtml = '<div class=\"section\" id=\"'+sectionID+'-html\"></div>';\n $(\"#section-container\").append(sectionHtml);\n}", "function ExamSection(){\n\tthis.title = \"\";\n\tthis.descr = \"\";\n\tthis.list = [];\t// list of questions for this exam section\n\t\n\treturn this;\n}", "function kata20(){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section2\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"20--Display 20 solid gray rectangles, each 20px high, with widths ranging evenly from 105px to 200px (remember #4, above).\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section2\");\n let widthDiv=105;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n newElement1.style.width = widthDiv+'px';\n widthDiv+=5;\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}", "makeMetadataPane(program, basicPane, edtasmPane) {\n const div = document.createElement(\"div\");\n div.classList.add(\"metadata\");\n div.style.display = \"flex\";\n const textInfoDiv = document.createElement(\"div\");\n div.appendChild(textInfoDiv);\n const h1 = document.createElement(\"h1\");\n h1.innerText = \"Track \" + program.trackNumber + \", copy \" + program.copyNumber;\n textInfoDiv.appendChild(h1);\n const table = document.createElement(\"table\");\n textInfoDiv.appendChild(table);\n // Add entry with any data cell for value. Returns the key element.\n const addKeyElement = (key, valueElement) => {\n const row = document.createElement(\"tr\");\n const keyElement = document.createElement(\"td\");\n keyElement.classList.add(\"key\");\n keyElement.innerText = key + \":\";\n row.appendChild(keyElement);\n row.appendChild(valueElement);\n table.appendChild(row);\n return keyElement;\n };\n // Add entry with text (possibly clickable) for value.\n const addKeyValue = (key, value, click) => {\n const valueElement = document.createElement(\"td\");\n valueElement.classList.add(\"value\");\n valueElement.innerText = value;\n if (click !== undefined) {\n valueElement.classList.add(\"clickable\");\n valueElement.addEventListener(\"click\", click);\n }\n addKeyElement(key, valueElement);\n };\n addKeyValue(\"Decoder\", program.decoderName);\n addKeyValue(\"Start time\", frameToTimestamp(program.startFrame, this.tape.sampleRate), () => this.originalWaveformDisplay.zoomToFit(program.startFrame - 100, program.startFrame + 100));\n addKeyValue(\"End time\", frameToTimestamp(program.endFrame, this.tape.sampleRate), () => this.originalWaveformDisplay.zoomToFit(program.endFrame - 100, program.endFrame + 100));\n addKeyValue(\"Duration\", frameToTimestamp(program.endFrame - program.startFrame, this.tape.sampleRate, true), () => this.originalWaveformDisplay.zoomToFit(program.startFrame, program.endFrame));\n addKeyValue(\"Binary\", \"Download \" + program.binary.length + \" bytes\", () => {\n // Download binary.\n const a = document.createElement(\"a\");\n a.href = \"data:application/octet-stream;base64,\" + base64EncodeUint8Array(program.binary);\n a.download = program.getShortLabel().replace(\" \", \"-\") + \".bin\";\n a.click();\n });\n if (basicPane !== undefined) {\n addKeyValue(\"Type\", \"Basic program\", () => this.showPane(basicPane));\n }\n else if (edtasmPane !== undefined) {\n addKeyValue(\"Type\", \"Assembly program\" + (edtasmPane.edtasmName ? \" (\" + edtasmPane.edtasmName + \")\" : \"\"), () => this.showPane(edtasmPane));\n }\n else {\n addKeyValue(\"Type\", \"Unknown\");\n }\n // Add editable fields.\n {\n const td = document.createElement(\"td\");\n td.classList.add(\"value\");\n const input = document.createElement(\"input\");\n input.classList.add(\"name\");\n program.onName.subscribe(name => input.value = name);\n input.value = program.name;\n td.appendChild(input);\n addKeyElement(\"Name\", td);\n input.addEventListener(\"input\", event => {\n program.setName(input.value);\n this.tape.saveUserData();\n });\n }\n {\n const td = document.createElement(\"td\");\n td.classList.add(\"value\");\n const input = document.createElement(\"textarea\");\n input.classList.add(\"notes\");\n input.rows = 5;\n program.onNotes.subscribe(notes => input.value = notes);\n input.value = program.notes;\n td.appendChild(input);\n const keyElement = addKeyElement(\"Notes\", td);\n keyElement.classList.add(\"top\");\n input.addEventListener(\"input\", event => {\n program.setNotes(input.value);\n this.tape.saveUserData();\n });\n }\n // Add bit errors.\n let count = 1;\n for (const bitData of program.bitData) {\n if (bitData.bitType === BitType.BAD) {\n addKeyValue(\"Bit error \" + count++, frameToTimestamp(bitData.startFrame, this.tape.sampleRate), () => this.originalWaveformDisplay.zoomToBitData(bitData));\n }\n }\n // Add screenshot.\n const screenshotDiv = document.createElement(\"div\");\n screenshotDiv.style.marginLeft = \"20pt\";\n div.appendChild(screenshotDiv);\n Trs80_Trs80.displayScreenshot(screenshotDiv, program.screenshot);\n program.onScreenshot.subscribe(screenshot => Trs80_Trs80.displayScreenshot(screenshotDiv, screenshot));\n return new Pane(div);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a refresh for the highlighting in 500ms.
function setRefreshTimeout() { clearRefreshTimeout(); _highlightTimeout = setTimeout( refreshCallback, 500 ); }
[ "_updateAutoHighlight(info) {\n const pickingModuleParameters = {\n pickingSelectedColor: info.picked ? info.color : null\n };\n const {\n highlightColor\n } = this.props;\n\n if (info.picked && typeof highlightColor === 'function') {\n pickingModuleParameters.pickingHighlightColor = highlightColor(info);\n }\n\n this.setModuleParameters(pickingModuleParameters); // setModuleParameters does not trigger redraw\n\n this.setNeedsRedraw();\n }", "refresh(timeNow, enableAnimation) {\n }", "_cancelUnhighlight () {\n if (this.unhighlightTimer) {\n clearTimeout(this.unhighlightTimer)\n this.unhighlightTimer = undefined\n }\n }", "function timerFn () {\n if (!needsRedraw) {\n return;\n }\n\n switch (_self.state) {\n case _self.STATE_PENDING:\n // selection dropped, switch to draw selection\n _self.state = _self.STATE_DRAWING;\n marqueeStyle.display = '';\n gui.statusShow('selectionDraw');\n\n case _self.STATE_DRAWING:\n selectionDraw();\n break;\n\n case _self.STATE_SELECTED:\n mouseAreaUpdate();\n break;\n\n case _self.STATE_DRAGGING:\n selectionDrag();\n break;\n\n case _self.STATE_RESIZING:\n selectionResize();\n }\n\n needsRedraw = false;\n }", "_updateAutoHighlight(info) {\n for (const layer of this.getSubLayers()) {\n layer.updateAutoHighlight(info);\n }\n }", "function _highlightTile() {\n var itemSelected = lv_cockpits.winControl.selection.getItems()._value[0];\n if (!itemSelected.data.spotlighted_at) {\n itemSelected.data.spotlighted_at = new Date();\n }\n else\n itemSelected.data.spotlighted_at = null;\n lv_cockpits.winControl.itemDataSource.change(itemSelected.key, itemSelected.data);\n }", "function resetDrawingHighlights() {\n abEamTcController.resetDrawingHighlights();\n}", "function refresh() {\n\tsetInterval(function() {\n\t\tconsole.log(\"refresh\");\n\t\twindow.location.reload();\n\t}, 20000);\n}", "function setColorHighlight( color ){\n \n if(color.r > 0.5) color.r = (color.r * 1.005);\n if(color.g > 0.5) color.g = (color.g * 1.005);\n if(color.b > 0.5) color.b = (color.b * 1.005);\n}", "function scheduleRefresh() {\r\n if (refreshEvent) {\r\n clearTimeout(refreshEvent);\r\n }\r\n refreshEvent = setTimeout(function() {refresh(); refreshEvent = null;}, refreshDelay);\r\n}", "function setGetInterval() {\n setInterval(() => {\n getColor();\n }, 2000);\n}", "function setAutoRefreshTimeout() {\n clearTimeout(autoRefreshTimeoutId);\n if (auth.autoRefresh && typeof auth.expires !== 'undefined') {\n autoRefreshTimeoutId = setTimeout(auth.refresh, auth.expires + 1000);\n }\n }", "function YInputChain_set_refreshRate(newval)\n { var rest_val;\n rest_val = String(newval);\n return this._setAttr('refreshRate',rest_val);\n }", "animatePlaceholderStatus() {\n Animate.blink(this);\n }", "function intervalFunction() {\n\n displayQuoteAndColor();\n setInterval(displayQuoteAndColor, 13000);\n}", "highlightSearchSyntax() {\n console.log('highlightRegexSyntax');\n if (this._highlightSyntax) {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n this.regexField.setBgHtml(this.parseRegex(this.regexField.getTextarea().value));\n } else {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n }\n }", "animateReducingStatus() {\n this._reducingTime = 0;\n let twn = new mag.IndefiniteTween((t) => {\n stage.draw();\n\n this._reducingTime += t;\n\n if (!this._reducing || !this.stage) twn.cancel();\n });\n twn.run();\n }", "function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}", "function highlightFeature(e) {\n e.target.setStyle(highLightStyle);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO(lmr): Make modulus able to be an animated value
function AnimatedModulo(a,modulus){_classCallCheck(this,AnimatedModulo);var _this=_possibleConstructorReturn(this,Object.getPrototypeOf(AnimatedModulo).call(this)); _this._a=a; _this._modulus=modulus; _this._listeners={};return _this;}
[ "function mod_0_360(x) {return mod0Real(360, x);}", "function mod(x, n) {\n return (x % n + n) % n;\n}", "function privateNext() {\n\t \timageCurrent++;\n\t \tif (imageCurrent > image.length - 1) {\n\t \t\timageCurrent = 0;\n\t \t\tcontainer.animate({left: \"+=\" + (sliceWidth * image.length - sliceWidth)}, speedSlice);\n\t \t} else {\n\t \t\tcontainer.animate({left: \"-=\" + sliceWidth}, speedSlice);\n\t \t}\n\t }", "function pressMod() {\n\thandleMulDivMod(MOD);\n}", "function modulo4(num){\n return num%4\n}", "static Repeat(value, length) {\n return value - Math.floor(value / length) * length;\n }", "function setNumber(value, element)\n {\n var percentage = (value - 1) * 11.2;\n\n element.style.backgroundPosition = percentage + \"% 0\";\n }", "function animateCash(number, target) {\n // accomodate target being higher or lower than start val\n var increment = (target - number) / Math.abs(target - number);\n // alert (\"target: \" + target + \" number: \" + number + \" increment: \" + increment);\n var interval = setInterval(function() {\n $(\"#total_cash_label span.value\").text(number);\n if (number >= target) clearInterval(interval);\n number += increment;\n }, 100); \n }", "function mod(x,n) {\r\n var ans=dup(x);\r\n mod_(ans,n);\r\n return trim(ans,1);\r\n }", "function everyinterval(n) {\n if ((myGameArea.frameNo / n) % 1 === 0) {\n return true;\n }\n return false;\n}", "function multThree() {\n\tfor (let i = 3; i <= 90; i++){\n\t\tif (i % 3 === 0) {\n\t\t\tconsole.log(i);\n\t\t}\n\t}\n}", "function abilityModifier(ability){\n return Math.floor((ability - 10)/2)\n}", "function inv_mod(x,y) {\n var q,u,v,a,c,t;\n\n u = ~~x;\n v = ~~y;\n c = 1;\n a = 0;\n do {\n q = ~~(v / u);\n\n t = c;\n c = a - q * c;\n a = t;\n\n t = u;\n u = v - q * u;\n v = t;\n } while (u != 0);\n a = a % y;\n if (a < 0) {\n a = y + a; \n }\n\n return ~~a;\n}", "function expmod3(base, exp, m) {\n if (exp === 0) {\n return 1;\n } else {\n if (isEven(exp)) {\n const toHalf = expmod3(base, exp / 2, m);\n return (toHalf * toHalf) % m;\n } else {\n return (base * expmod3(base, exp - 1, m)) % m;\n }\n }\n}", "function numberChange(now, fx){\n\t\t\t\t\n\t\t\t\t//Round the tick number\n\t\t\t\tnow = Math.floor(now);\n\t\t\t\t\n\t\t\t\t//Reset the previous counter\n\t\t\t\tif(previousValue == -1 * animationNumber){\n\t\t\t\t\tpreviousValue = 0;\n\t\t\t\t}\n\n\t\t\t\t//Get the panel we are putting the number into\n\t\t\t\tvar panel = $('#panel-bottom-square-1');\n\t\t\t\t\n\t\t\t\t//If the panel is empty populate it\n\t\t\t\tif(panel.html().trim() == ''){\n\t\t\t\t\tpanel.html(animationOffset);\n\t\t\t\t}else{\n\t\t\t\n\t\t\t\t\t//Otherwise populate it with some values\n\t\t\t\t\tvar number = parseInt(\n\t\t\t\t\t\tpanel.html()\n\t\t\t\t\t\t\t.replace('EAX, ','')\n\t\t\t\t\t\t\t.replace('H','')\n\t\t\t\t\t);\n\t\t\t\n\t\t\t\t\tvar panelValue = number + now - previousValue;\n\t\t\t\t\tpanel.html('EAX, '+panelValue + 'H');\n\t\t\t\t}\n\n\t\t\t\t//Maintain a previous value\n\t\t\t\tpreviousValue = now;\n\t\t\t}", "function divBy4(num){\n return num/4\n\n}", "function sliderMove()\r\n{\r\n var offset = 0\r\n for (var t = 0; t < sliders.length; t++)\r\n {\r\n var slid = map(sin(angle+offset), -1, 1, 0, 255)\r\n sliders[t].value(slid)\r\n offset += vTest;\r\n } \r\n}", "function testRemainder() {\n const result = remainder(29, 6);\n if(result.value !== 5) {\n console.error('testRemainder - value - FAIL');\n }\n else {\n console.log('testRemainder - value - SUCCESS');\n }\n}", "function remainderOfFives({ first, second }) {\n if (first === second) return 0;\n if (first % 5 === second % 5) return Math.min(first, second);\n return Math.max(first, second);\n}", "function animateCircle() {\r\n\r\n var count = 0;\r\n return window.setInterval(function() {\r\n count = (count + 1) % 200;\r\n\r\n var icons = poly.get('icons');\r\n icons[0].offset = (count / 2) + '%';\r\n poly.set('icons', icons);\r\n }, 40);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be O(height of tree). Example: root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
function solution_1 (root, key) { if (!root) return null; // EDGE CASE: empty input // `find` UTILITY FUNCTION - recursively searches input tree for a node with value matching `key`. // if such a node exists, returns an array containing (1) the node, and (2) its parent node, or null if the matching node is the root. // if such a node does not exist, returns [null, null] function find (node, parent = null) { if (key < node.val) { return node.left ? find(node.left, node) : [null, null]; } else if (key > node.val) { return node.right ? find(node.right, node) : [null, null]; } else { return [node, parent]; } } // INITIALIZATION const [node, parent] = find(root); // set `node` (the node to be removed) and `parent` (a reference to its parent) if (!node) return root; // if `node` is null, then there is no work to be done. we simply return `root` // REMOVE THE NODE BY RECONFIGURING ALL NECESSARY NODE CONNECTIONS if (!node.left && !node.right) { // CASE 1: the `node` to be removed has no children if (parent) { // if `parent` is not null... parent[parent.val < node.val ? 'right' : 'left'] = null; // ...disconnect `parent` in the direction of `node` return root; // ...return original root } return null; // `parent` may be null if the `node` to be removed was the `root`. since `node` has no children, return empty tree (null) } else if (!node.left) { // CASE 2: the `node` to be removed only has a right child if (parent) { // if `parent` is not null... parent[parent.val < node.val ? 'right' : 'left'] = node.right; // ...connect `parent` in the direction of `node` to `node.right` return root; // ...return original root } return node.right; // `parent` may be null if the `node` to be removed was the `root`. since `node` has no left child, return `node.right` } else if (!node.right) { // CASE 3: reverse the logic of case 2 if (parent) { parent[parent.val < node.val ? 'right' : 'left'] = node.left; return root; } return node.left; } else { // CASE 4: the `node` to be removed has both children // find the `replacement` node and its parent (we could either go right, and then keep going as left as possible, or go left, and keep going as right as possible. here i choose the former) let replacement = node.right; let replacementParent = node; while (replacement.left) { replacementParent = replacement; replacement = replacement.left; } // we decided to go right and then left to find replacement. now we have to hook up `replacement.left` to the original `node.left`... replacement.left = node.left; // ...and then hook up `replacement.right` to the original `node.right` (UNLESS `node.right` IS the `replacement`, in which case we can skip this step) if (node.right !== replacement) { replacementParent[ replacementParent.val < replacement.val ? 'right' : 'left' ] = replacement.right; // hook up `replacementParent` in the direction of `replacement` to `replacement.right` replacement.right = node.right // hook up `replacement.right` to original `node.right` } // finally, hook up `parent` to `replacement` and return if (parent) { parent[parent.val < node.val ? 'right' : 'left'] = replacement; return root; // if `parent`, then we simply return the original `root` } else { return replacement; // else, it must be the case that the node we removed was the original `root`, so return `replacement` } } }
[ "delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n if (val === currentNode.val) {\n nodeToRemove = currentNode;\n found = true;\n } else if (val < currentNode.val) {\n parent = currentNode;\n currentNode = currentNode.left;\n } else {\n parent = currentNode;\n currentNode = currentNode.right;\n }\n }\n\n console.log(\"We found the node\");\n console.log('parent node', parent);\n\n // helper variable which returns true if the node we've removing is the left\n // child and false if it's right\n const nodeToRemoveIsParentsLeftChild = parent.left === nodeToRemove;\n\n // if nodeToRemove is a leaf node, remove it\n if (nodeToRemove.left === null && nodeToRemove.right === null) {\n if (nodeToRemoveIsParentsLeftChild) parent.left = null;\n else parent.right = null\n } else if (nodeToRemove.left !== null && nodeToRemove.right === null) {\n // only has a left child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.left;\n } else {\n parent.right = nodeToRemove.left;\n }\n } else if (nodeToRemove.left === null && nodeToRemove.right !== null) {\n // only has a right child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.right;\n } else {\n parent.right = nodeToRemove.right;\n }\n } else {\n // has 2 children\n const rightSubTree = nodeToRemove.right;\n const leftSubTree = nodeToRemove.left;\n // sets parent nodes respective child to the right sub tree\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = rightSubTree;\n } else {\n parent.right = rightSubTree;\n }\n\n // find the lowest free space on the left side of the right sub tree\n // and add the leftSubtree\n let currentLeftNode = rightSubTree;\n let currentLeftParent;\n let foundSpace = false;\n while (!foundSpace) {\n if (currentLeftNode === null) foundSpace = true;\n else {\n currentLeftParent = currentLeftNode;\n currentLeftNode = currentLeftNode.left;\n }\n }\n currentLeftParent.left = leftSubTree;\n return 'the node was successfully deleted'\n }\n }", "remove(key) {\n if (!_.isString(key)) throw new Error('Parameter \"key\" must be a string!');\n\n const node = this.dictionary[key];\n\n if (!node) return null;\n\n delete this.dictionary[key];\n this.linkedList.removeNode(node);\n\n return node.data;\n }", "function removeNode(node, key, index) {\n Array.isArray(node[key])\n ? node[key].splice(index, 1)\n : delete node[key]\n}", "function deleteMinimum(node, removeCallBack) {\n\n if (noChildren(node)) {\n removeCallBack(node);\n return null;\n }\n\n if (rightChildOnly(node)) {\n removeCallBack(node);\n return node.right;\n }\n\n if (node.left) {\n node.left = deleteMinimum(node.left, removeCallBack);\n return node;\n }\n }", "delete(word) {\n\t\t// Helper function:\n\t\t// Works through the levels of the word/key\n\t\t// Once it reaches the end of the word, it checks if the last node\n\t\t// has any children. If it does, we just mark as no longer an end.\n\t\t// If it doesn't, we continue bubbling up deleting the keys until we find a node\n\t\t// that either has other children or is marked as an end.\n\t\tconst deleteHelper = (word, node, length, level) => {\n\t\t\tlet deletedSelf = false;\n\t\t\tif (!node) {\n\t\t\t\tconsole.log(\"Key doesn't exist\");\n\t\t\t\treturn deletedSelf;\n\t\t\t}\n\n\t\t\t// Base case\n\t\t\tif (length === level) {\n\t\t\t\tif (node.keys.length === 0) {\n\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t} else {\n\t\t\t\t\tnode.setNotEnd();\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlet childNode = node.keys.get(word[level]);\n\t\t\t\tlet childDeleted = deleteHelper(word, childNode, length, level + 1);\n\t\t\t\tif (childDeleted) {\n\t\t\t\t\tnode.keys.delete(word[level]);\n\n\t\t\t\t\tif (node.isEnd()) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else if (node.keys.length) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn deletedSelf;\n\t\t};\n\n\t\tdeleteHelper(word, this.root, word.length, 0);\n\t}", "function removeFromDB(r){\n var database = firebase.database();\n var booksRef = database.ref('books');\n\n var key = r.parentNode.parentNode.getAttribute(\"id\");\n booksRef.child(key).remove().then(function(){\n console.log(\"Remove success\");\n }).catch(function(error){\n console.log(\"Remove failed : \", error);\n });\n \n document.querySelector(\"tbody\").innerHTML = \"\";\n retrieveData();\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 }", "delete(leaf) {\n const root = this.root();\n\n if (!root) {\n return false;\n }\n\n if (leaf === root) {\n this._root = null;\n this._numLeafs = 0;\n return true;\n } // Iterate up from the leaf deleteing it from it's parent's branches.\n\n\n let node = leaf.parent;\n let branchKey = leaf.branchKey;\n\n while (node) {\n var _node4;\n\n node.branches.delete(branchKey); // Stop iterating if we hit the root.\n\n if (node === root) {\n if (node.branches.size === 0) {\n this._root = null;\n this._numLeafs = 0;\n } else {\n this._numLeafs--;\n }\n\n return true;\n } // Stop iterating if there are other branches since we don't need to\n // remove any more nodes.\n\n\n if (node.branches.size > 0) {\n break;\n } // Iterate up to our parent\n\n\n branchKey = (_node4 = node) === null || _node4 === void 0 ? void 0 : _node4.branchKey;\n node = node.parent;\n } // Confirm that the leaf we are deleting is actually attached to our tree\n\n\n for (; node !== root; node = node.parent) {\n if (node == null) {\n return false;\n }\n }\n\n this._numLeafs--;\n return true;\n }", "function deviceRootRemove(datastore_id, root_uuid, device_root, file_name, file_tombstone, device_id) {\n var now = new Date().getTime();\n var new_timestamp = device_root['timestamp'] + 1 > now ? device_root['timestamp'] + 1 : now;\n\n device_root['timestamp'] = new_timestamp;\n device_root['tombstones'][file_name] = file_tombstone;\n\n var new_root = deviceRootSerialize(device_id, datastore_id, root_uuid, device_root);\n return new_root;\n}", "_removeNode(tree, path) {\n if(tree){\n if (path.length === 1) {\n delete tree[path[0]];\n return;\n }\n return this._removeNode(tree[path[0]], path.slice(1));\n }\n }", "remove(key) {\n var item = this.map[key];\n if (!item) return;\n this._removeItem(item);\n }", "function deleteNode() {\n nodeToDelete = deleteNodeInp.value();\n nodes.splice(nodeToDelete,1);\n numnodes -= 1;\n //nodes.remove[0];\n //numnodes -= 1;\n}", "function deleteNode(tx, args) {\n if (!args.nodeId) {\n throw new Error('Parameter `nodeId` is mandatory.');\n }\n var nodeId = args.nodeId;\n var node = tx.get(nodeId);\n\n // remove all associated annotations\n var annos = tx.getIndex('annotations').get(nodeId);\n var i;\n for (i = 0; i < annos.length; i++) {\n tx.delete(annos[i].id);\n }\n\n // transfer anchors of ContainerAnnotations to previous or next node:\n // - start anchors go to the next node\n // - end anchors go to the previous node\n var anchors = tx.getIndex('container-annotation-anchors').get(nodeId);\n for (i = 0; i < anchors.length; i++) {\n var anchor = anchors[i];\n var container = tx.get(anchor.container);\n // Note: during the course of this loop we might have deleted the node already\n // so, don't do it again\n if (!tx.get(anchor.id)) continue;\n\n var pos = container.getPosition(anchor.path[0]);\n var path, offset;\n\n if (anchor.isStart) {\n if (pos < container.getLength()-1) {\n var nextNode = container.getChildAt(pos+1);\n if (nextNode.isText()) {\n path = [nextNode.id, 'content'];\n } else {\n path = [nextNode.id];\n }\n tx.set([anchor.id, 'startPath'], path);\n tx.set([anchor.id, 'startOffset'], 0);\n } else {\n tx.delete(anchor.id);\n }\n } else {\n if (pos > 0) {\n var previousNode = container.getChildAt(pos-1);\n if (previousNode.isText()) {\n path = [previousNode.id, 'content'];\n offset = tx.get(path).length;\n } else {\n path = [previousNode.id];\n offset = 1;\n }\n tx.set([anchor.id, 'endPath'], path);\n tx.set([anchor.id, 'endOffset'], offset);\n } else {\n tx.delete(anchor.id);\n }\n }\n }\n // delete nested nodes\n if (node.hasChildren()) {\n node.getChildren().forEach(function(child) {\n deleteNode(tx, { nodeId: child.id });\n });\n }\n\n // hide node from all containers\n each(tx.getIndex('type').get('container'), function(container) {\n // remove from view first\n container.hide(nodeId);\n });\n\n // finally delete the node itself\n tx.delete(nodeId);\n\n return args;\n}", "function pruneAndRecenter(min_prob) {\n\tvar path = [];\n\tvar current = global.stableTree.root;\n\tvar next;\n\n\twhile (true) {\n\n\t\t// keep track of current child branch we're searching\n\t\tif (current.child_index != undefined) {\n\t\t\tcurrent.child_index++;\n\t\t} else {\n\t\t\tcurrent.child_index = 0;\n\t\t}\n\n\t\t// recenter when first encountering a terminal node\n\t\tif (current.child_index == 0 && (current.probability > 0 || current.children.length == 0)) {\n\t\t\tcurrent.probability -= min_prob;\t// recenter probability\n\t\t}\n\n\t\t// get next child\n\t\tif (current.child_index < current.children.length) {\n\t\t\tnext = current.children[current.child_index];\n\t\t} else {\n\t\t\tnext = undefined;\n\t\t\tdelete current.child_index;\n\t\t}\n\n\t\tif (next) {\n\t\t\t// move to child\n\t\t\tpath.push(current);\n\t\t\tcurrent = next;\n\t\t} else if (path.length > 0) {\n\t\t\t// if dead leaf node\n\t\t\tif (current.probability <= 0 && current.children.length == 0) {\n\t\t\t\twhile (true) {\n\t\t\t\t\t// backtrack to last terminal node or last node with > 1 children\n\t\t\t\t\tcurrent = path.pop();\n\t\t\t\t\tif (current.probability != 0 || current.children.length > 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// remove child (and thus, dead branch)\n\t\t\t\tcurrent.children.splice(current.child_index, 1);\n\t\t\t\tcurrent.child_index--;\n\t\t\t} else {\n\t\t\t\t// if normal leaf node, backtrack\n\t\t\t\tcurrent = path.pop();\n\t\t\t}\n\t\t} else {\n\t\t\t// if no next child and path empty, break (back at root)\n\t\t\tbreak;\n\t\t}\n\t}\n\t// debug\n\tconsole.log(\"Finished pruning / recentering\");\n}", "removeNode(node) {\n if (this.graph[node]) {\n delete this.graph[node]\n }\n }", "function _remove(predicate, tree) {\n\tif (isEmpty(tree)) {\n\t\treturn tree;\n\t} else if (R.pipe(R.view(lenses.data), predicate)(tree)) {\n\t\tif (!isEmpty(tree.left) && !isEmpty(tree.right)) {\n\t\t\t// Get in-order successor to `tree`; \"delete\" it; replace values in `tree`.\n\t\t\tconst successorLens =\n\t\t\t\tlensForSuccessorElement(tree);\n\t\t\t// assert(successorLens != null);\n\n\t\t\tconst successor = \n\t\t\t\tR.view(successorLens, tree);\n\t\t\t/*\n\t\tassert.notEqual(\n\t\t\tsuccessor,\n\t\t\tnull,\n\t\t\t`Expected successor of ${JSON.stringify(tree)}`);\n\t\t\t*/\n\n\t\t\treturn R.pipe(\n\t\t\t\tR.set(successorLens, empty),\n\t\t\t\tR.set(lenses.data, R.view(lenses.data, successor))\n\t\t\t)(tree);\n\t\t} else if (!isEmpty(tree.left)) {\n\t\t\treturn tree.left;\n\t\t} else if (!isEmpty(tree.right)) {\n\t\t\treturn tree.right;\n\t\t} else {\n\t\t\treturn empty;\n\t\t}\n\t} else {\n\t\treturn R.pipe(\n\t\t\tR.over(lenses.leftChild, remove(predicate)),\n\t\t\tR.over(lenses.rightChild, remove(predicate))\n\t\t)(tree);\n\t}\n}", "removeNode(value){\n if(this.includes(value)){\n\n let currentNode = this.head;\n while(currentNode.next.value !== value){\n currentNode = currentNode.next;\n }\n currentNode.next = currentNode.next.next;\n }else{\n throw new Error('Value not in list');\n }\n }", "remove(key) {\n if (this._data[key]) {\n this._busyMemory -= this._lifeTime[key].size;\n delete this._data[key];\n }\n }", "_removeItem(item) {\n if (this.head === item) {\n this.head = item.next;\n }\n if (this.tail === item) {\n this.tail = item.prev;\n }\n if (item.prev) {\n item.prev.next = item.next;\n }\n if (item.next) {\n item.next.prev = item.prev;\n }\n delete this.map[item.key];\n this.length -= 1;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Will toggle the inverted property of the Budgie element
changeInversion(){ this.options.inverted = !this.options.inverted; }
[ "invert() {\n for (let i = 0; i < this._data.length; i++) {\n this._data[i] = ~this._data[i];\n }\n }", "setSide (side) {\n this.reversed = (side === 'b')\n }", "setInvertLightness(invertFlag) {\n this._inverse.set_enabled(invertFlag);\n }", "reverseVisibility(){\n for(let i = 0; i < this.children[2].children.length; i++){\n this.children[2].children[i].visible = !this.children[2].children[i].visible;\n }\n }", "invert() {\n quat.invert(this, this);\n return this.check();\n }", "function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }", "toggle() {\n if (this.isChecked()) {\n this.unCheck();\n\n } else {\n this.check()\n }\n }", "setInvertLightness(flag) {\n this._invertLightness = flag;\n if (this._magShaderEffects)\n this._magShaderEffects.setInvertLightness(this._invertLightness);\n }", "invertRows() {\n // flip \"up\" vector\n // we flip up first because invertColumns update projectio matrices\n this.up.multiplyScalar(-1);\n this.invertColumns();\n\n this._updateDirections();\n }", "inverseVelocity() {\n this.enemyVelocity *= -1;\n }", "function flipCell() {\n // Run flip from style.css for the clicked cell (this)\n this.classList.toggle('flip');\n\n flippedCell = this;\n cellColor = flippedCell.dataset.color;\n outcome(cellColor);\n}", "function toggleDictionary() {\n self.dictionaryState = !self.dictionaryState;\n }", "getInvertLightness() {\n return this._invertLightness;\n }", "toggleAudioEq() {\r\n this.setAudioEq(!this.audio.useEq);\r\n }", "invert(doc) {\n let sections = this.sections.slice(),\n inserted = []\n for (let i = 0, pos = 0; i < sections.length; i += 2) {\n let len = sections[i],\n ins = sections[i + 1]\n if (ins >= 0) {\n sections[i] = ins\n sections[i + 1] = len\n let index = i >> 1\n while (inserted.length < index) inserted.push(Text.empty)\n inserted.push(len ? doc.slice(pos, pos + len) : Text.empty)\n }\n pos += len\n }\n return new ChangeSet(sections, inserted)\n }", "onClick() {\n this.happy = !this.happy;\n }", "invert(doc) {\n let sections = this.sections.slice(), inserted = [];\n for (let i = 0, pos = 0; i < sections.length; i += 2) {\n let len = sections[i], ins = sections[i + 1];\n if (ins >= 0) {\n sections[i] = ins;\n sections[i + 1] = len;\n let index = i >> 1;\n while (inserted.length < index)\n inserted.push(Text.empty);\n inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);\n }\n pos += len;\n }\n return new ChangeSet(sections, inserted);\n }", "flipWord(word) {\n this.cards[word].isFlipped = true;\n }", "get invertedDesc() {\n let sections = [];\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0)\n sections.push(len, ins);\n else\n sections.push(ins, len);\n }\n return new ChangeDesc(sections);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property is to get whether the userAgent is IOS.
static get isIos() { return Browser.getValue('isIos', REGX_IOS); }
[ "function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}", "function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}", "function simulateMacSafari3() {\n userAgent.MAC = true;\n userAgent.WINDOWS = false;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = false;\n userAgent.WEBKIT = true;\n userAgent.VERSION = '525';\n}", "_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }", "function IsPC() {\n var userAgentInfo = navigator.userAgent\n var Agents = [\"Android\", \"iPhone\", \"SymbianOS\", \"Windows Phone\", \"iPad\", \"iPod\"]\n var devType = 'PC'\n for (var v = 0; v < Agents.length; v++) {\n if (userAgentInfo.indexOf(Agents[v]) > 0) {\n // Determine the system platform used by the mobile end of the user\n if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {\n //Android mobile phone\n devType = 'Android'\n } else if (userAgentInfo.indexOf('iPhone') > -1) {\n //Apple iPhone\n devType = 'iPhone'\n } else if (userAgentInfo.indexOf('Windows Phone') > -1) {\n //winphone\n devType = 'winphone'\n } else if (userAgentInfo.indexOf('iPad') > -1) {\n //Pad\n devType = 'iPad'\n }\n break;\n }\n }\n docEl.setAttribute('data-dev-type', devType)\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 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 hasNavigator(){return typeof navigator!=='undefined';}", "function simulateMacFirefox() {\n userAgent.MAC = true;\n userAgent.WINDOWS = false;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}", "function getUserBrowser()\n{\n\tvar agent = navigator.userAgent.toLowerCase ();\n\n var browser = \"Unknown browser\";\n if (agent.search (\"msie\") > -1) {\n browser = \"Internet Explorer\";\n }\n else {\n if (agent.search (\"firefox\") > -1) {\n browser = \"Firefox\";\n }\n else {\n if (agent.search (\"opera\") > -1) {\n browser = \"Opera\";\n }\n else {\n if (agent.search (\"safari\") > -1) {\n if (agent.search (\"chrome\") > -1) {\n browser = \"Google Chrome\";\n }\n else {\n browser = \"Safari\";\n }\n }\n }\n }\n }\n\n return browser;\n}", "function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}", "function DetectPalmOS()\n{\n if (uagent.search(devicePalm) > -1)\n location.href='http://www.kraftechhomes.com/home_mobile.php';\n else\n return false;\n}", "get isTouch()\n {\n return \"ontouchstart\" in window;\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}", "function isDesktopSafari() {\n\t\tconst w = window\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'safari' in w,\n\t\t\t\t!('DeviceMotionEvent' in w),\n\t\t\t\t!('ongestureend' in w),\n\t\t\t\t!('standalone' in navigator),\n\t\t\t]) >= 3\n\t\t)\n\t}", "function DetectS60OssBrowser()\n{\n if (uagent.search(engineWebKit) > -1)\n {\n if ((uagent.search(deviceS60) > -1 || \n uagent.search(deviceSymbian) > -1))\n location.href='http://www.kraftechhomes.com/home_mobile.php';\n else\n return false;\n }\n else\n return false;\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 isUniversalAnalyticsObjectAvailable() {\n if (typeof ga !== 'undefined') {\n return true;\n }\n return false;\n}", "function simulateWinFirefox() {\n userAgent.MAC = false;\n userAgent.WINDOWS = true;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}", "get operatingSystem() {\n return this.getStringAttribute('operating_system');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add fields from config.fields to object with information about one package. Only fields from field list will be returned in generated object.
function packageDataToReportData(packageData, config) { let finalData = {} // create only fields specified in the config config.fields.forEach(fieldName => { if ((fieldName in packageData)) { finalData[fieldName] = packageData[fieldName] } else { finalData[fieldName] = config[fieldName].value } }) return finalData }
[ "function fieldFromDerivedFieldConfig(derivedFieldConfigs) {\n var dataLinks = derivedFieldConfigs.reduce(function (acc, derivedFieldConfig) {\n // Having field.datasourceUid means it is an internal link.\n if (derivedFieldConfig.datasourceUid) {\n acc.push({\n // Will be filled out later\n title: '',\n url: '',\n // This is hardcoded for Jaeger or Zipkin not way right now to specify datasource specific query object\n internal: {\n query: {\n query: derivedFieldConfig.url\n },\n datasourceUid: derivedFieldConfig.datasourceUid\n }\n });\n } else if (derivedFieldConfig.url) {\n acc.push({\n // We do not know what title to give here so we count on presentation layer to create a title from metadata.\n title: '',\n // This is hardcoded for Jaeger or Zipkin not way right now to specify datasource specific query object\n url: derivedFieldConfig.url\n });\n }\n\n return acc;\n }, []);\n return {\n name: derivedFieldConfigs[0].name,\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {\n links: dataLinks\n },\n // We are adding values later on\n values: new _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"ArrayVector\"]([])\n };\n}", "function localPackageInfo() {\n // get path to this package\n var thisFileName = jsarguments[0];\n var thisFile = new File(thisFileName);\n var regex = /([^\\/\\\\]*)$/i;\n var packageDir = thisFile.foldername.replace(regex, \"\");\n // load package.json to retrieve details\n var localPackageInfo = new Dict;\n localPackageInfo.import_json(packageDir + \"package.json\");\n // export package information as variables\n this.dir = packageDir;\n this.name = localPackageInfo.get(\"name\");\n this.version = localPackageInfo.get(\"version\");\n this.author = localPackageInfo.get(\"author\");\n this.dict = localPackageInfo;\n}", "function schemaFromAnnotation (annotation){\n\nvar _schema={};\n_schema.description = \"A representation of something\";\n_schema.type = \"object\";\n_schema.properties ={};\n\njQuery.each(annotation.singleFields,\nfunction(i, val) {\n_schema.properties[val.name]={};\n_schema.properties[val.name].description = val.label;\n_schema.properties[val.name].type = val.type;\n_schema.properties[val.name].required = val.required;\n\n});\n\njQuery.each(annotation.groupFields,\nfunction(i, val) {\nconsole.log (val);\n});\n\njQuery.each(annotation.repeatingFields,\nfunction(i, val) {\nconsole.log (val);\n});\n\n\nreturn _schema;\n}", "loadFieldInfo(){\n let fieldInfo = [];\n this.props.orderStore.currentOrder.templateFields.fieldlist.field.forEach(field =>\n this.props.orderStore.fieldInfo.push([field, '']));\n this.props.orderStore.fieldInfo.forEach(field =>\n {\n if(field[0].type == \"SEPARATOR\"){\n field[1] = \"**********\";\n }\n });\n }", "create() {\n const uuid = `urn:uuid:${uuidv4()}`;\n\n this.metadata = new PackageMetadata();\n this.manifest = new PackageManifest();\n this.spine = new PackageSpine();\n this.setUniqueIdentifier(uuid);\n }", "function loadFieldsModel() {\n\t\t\t\tvar initialFieldsModel = angular.isArray(scope.edaEasyFormViewerEasyFormGeneratorFieldsModel) ? loadExistingConfigurationModel(scope.edaEasyFormViewerEasyFormGeneratorFieldsModel) //translate easy form generator to formly fields model\n\t\t\t\t: {};\n\t\t\t\treturn initialFieldsModel;\n\t\t\t}", "async getField(z) {\n assert(typeof z === 'string');\n assert(isAbsolute(z));\n assert(this.field);\n\n const x = join(z, 'package.json');\n const j = await readJSON(x);\n\n if (!isObject(j))\n return null;\n\n let m = j.main;\n let b = j[this.field];\n\n if (isString(m))\n m = await this.normalize(m, z);\n\n if (b === false && isString(m)) {\n b = Object.create(null);\n b[m] = false;\n }\n\n if (isString(b) && isString(m)) {\n b = Object.create(null);\n b[m] = j[this.field];\n }\n\n if (!isObject(b))\n return null;\n\n for (let k of Object.keys(b)) {\n let v = b[k];\n\n delete b[k];\n\n k = await this.normalize(k, z);\n\n if (!k)\n continue;\n\n v = await this.normalize(v, z);\n\n if (!v)\n continue;\n\n b[k] = v;\n }\n\n return b;\n }", "function readFields(input, fields_count, fieldsType) {\n address = input.cursor;\n var fieldsRoot = classFileMember(fieldsType + \"s\", \"\", address, \"...\");\n // fieldsRoot.appendTo(root);\n var fieldsContainer = $(\"<ul/>\");\n fieldsContainer.appendTo(fieldsRoot);\n for (var i = 0; i < fields_count; i++) {\n address = input.cursor;\n var fldRoot = classFileMember(fieldsType + \"[\" + i.toString() + \"]\", \"\", address, \"...\");\n fldRoot.appendTo(fieldsContainer);\n var fldContainer = $(\"<ul/>\");\n fldContainer.appendTo(fldRoot);\n // u2 access_flags;\n accessFlags(input, \"access_flags\").appendTo(fldContainer);\n // u2 name_index;\n classFileMemberU2(input, \"name_index\").appendTo(fldContainer);\n // u2 descriptor_index;\n classFileMemberU2(input, \"descriptor_index\").appendTo(fldContainer);\n // u2 attributes_count;\n address = input.cursor;\n var attributes_count = input.u2();\n classFileMember(\"attributes_count\", attributes_count.toString(), address, input.latestDump)\n .appendTo(fldContainer);\n // attribute_info attributes[attributes_count];\n readAttributes(input, attributes_count).appendTo(fldContainer);\n }\n return fieldsRoot;\n }", "createFields(fieldList) {\n const formFields = fieldList.reduce((fields, field) => ({\n ...fields,\n [field]: createField(field, this.onFieldChange)\n }), {});\n this.fields = { ...formFields };\n }", "_eachPackages (cb) {\n for (let packageName in this._packagesConfig) {\n const packageObject = new Package({\n projectKeysDir: this._projectKeysDir,\n package: this._packagesConfig[packageName],\n sshConfigDir: this._sshConfigDir,\n sshConfigPath: this._sshConfigPath\n }, packageName)\n cb(packageObject)\n }\n }", "static define(config) {\n let field = new StateField(\n nextID++,\n config.create,\n config.update,\n config.compare || ((a, b) => a === b),\n config\n )\n if (config.provide) field.provides = config.provide(field)\n return field\n }", "function addField(fieldType) {\n var newField = null;\n switch (fieldType) {\n case \"Single Line Text Field\":\n newField = { \"label\": \"New Text Field\", \"type\": \"TEXT\", \"placeholder\": \"New Field\"};\n break;\n case \"Multi Line Text Field\":\n newField = { \"label\": \"New Text Field\", \"type\": \"TEXTAREA\", \"placeholder\": \"New Field\"};\n break;\n case \"Date Field\":\n newField = {\"label\": \"New Date Field\", \"type\": \"DATE\"};\n break;\n case \"Dropdown Field\":\n newField = { \"label\": \"New Dropdown\", \"type\": \"OPTIONS\", \"options\": [\n {\"label\": \"Option 1\", \"value\": \"OPTION_1\"},\n {\"label\": \"Option 2\", \"value\": \"OPTION_2\"},\n {\"label\": \"Option 3\", \"value\": \"OPTION_3\"}\n ]};\n break;\n case \"Checkboxes Field\":\n newField = { \"label\": \"New Checkboxes\", \"type\": \"CHECKBOXES\", \"options\": [\n {\"label\": \"Option A\", \"value\": \"OPTION_A\"},\n {\"label\": \"Option B\", \"value\": \"OPTION_B\"},\n {\"label\": \"Option C\", \"value\": \"OPTION_C\"}\n ]};\n break;\n case \"Radio Buttons Field\":\n newField = { \"label\": \"New Radio Buttons\", \"type\": \"RADIOS\", \"options\": [\n {\"label\": \"Option X\", \"value\": \"OPTION_X\"},\n {\"label\": \"Option Y\", \"value\": \"OPTION_Y\"},\n {\"label\": \"Option Z\", \"value\": \"OPTION_Z\"}\n ]};\n break;\n default:\n newField = null;\n }\n if (newField){\n FieldService\n .createFieldForForm($scope.formId, newField)\n .then(\n function (response) {\n $scope.fields.push(response.data);\n }\n );\n }\n\n }", "function generateConfig(){\n var arr,\n numProducts = products.length;\n \n Ext.iterate(structure, function(continent, cities){\n continentGroupRow.push({\n header: continent,\n align: 'center',\n colspan: cities.length * numProducts\n });\n Ext.each(cities, function(city){\n cityGroupRow.push({\n header: city,\n colspan: numProducts,\n align: 'center'\n });\n Ext.each(products, function(product){\n fields.push({\n type: 'int',\n name: city + product\n });\n columns.push({\n dataIndex: city + product,\n header: product,\n renderer: Ext.util.Format.usMoney\n });\n });\n arr = [];\n for(var i = 0; i < 20; ++i){\n arr.push((Math.floor(Math.random()*11) + 1) * 100000);\n }\n data.push(arr);\n });\n })\n }", "getPackageConfig(packageName, packagePath, version) {\n const rawPackageConfig = this.getRawPackageConfig(packageName, packagePath, version);\n return new ProcessedNgccPackageConfig(this.fs, packagePath, rawPackageConfig);\n }", "function annotationFromSchema (inputJsonSchema){\n\nvar _schema={};\n_schema.singleFields=[];\n_schema.groupFields=[];\n_schema.repeatingFields=[];\ndefaultEntry={};\n\n jQuery.each(inputJsonSchema.properties,\n function(i, val) {\n \t_schema.singleFields.unshift({name:i ,label: val.description ? val.description : i, placeholder: i, type: val.type, required: val.required ? val.required : undefined });\n \n});\nreturn _schema;\n}", "visitCreate_package_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "static setRequiredFields(binding) {\n let requiredFields = [];\n\n if (!libThis.evalCodeGroupIsEmpty(binding)) { //code group is not empty\n \n if (libThis.evalIsCodeOnly(binding)) { //Val Code only\n requiredFields.push({\n 'NumberOfFieldsRequired' : 1,\n 'Fields' : \n [\n 'ValuationCodeLstPkr',\n ],\n });\n\n } else if (libThis.evalIsCodeSufficient(binding)) { //Both fields exist and one is required\n requiredFields.push({\n 'NumberOfFieldsRequired' : 1,\n 'Fields' :\n [\n 'ReadingSim', 'ValuationCodeLstPkr',\n ],\n });\n } else { //Reading only\n requiredFields.push({\n 'NumberOfFieldsRequired' : 1,\n 'Fields' :\n [\n 'ReadingSim',\n ],\n });\n }\n\n } else { //Code group empty means Reading only\n requiredFields.push({\n 'NumberOfFieldsRequired' : 1,\n 'Fields' :\n [\n 'ReadingSim',\n ],\n });\n }\n\n return requiredFields;\n }", "function regroupFields(configs){\n\n\tvar timestamps = configs[1];\n\tvar fields = configs[2];\n\tvar n = timestamps.length;\t\n\tvar m = fields.length;\n\n\tvar new_configs = new Array(n);\n\tvar tmp;\n\n\t//prepare the timestamp fields\n\ttimestamps.forEach(function(timestamp_config, index){\n\n\t\ttmp = {};\n\t\ttmp.fields = [];\n\n\t\t//copy the timestamp\n\t\ttmp.fields.push(timestamp_config.field);\n\n\t\t//and other info\n\t\ttmp.store = timestamp_config.store;\n\t\ttmp.source = timestamp_config.source;\n\n\t\t//add to the new config\n\t\tnew_configs[index] = tmp;\n\t});\n\n\n\t//regroup the other fields\n\tvar count_fields = 0;\n\tfor (var i=0; i<n; i++){\n\n\t\tfor (var j=0; j<m; j++){\n\n\t\t\tif (new_configs[i].source.name === fields[j].source.name &&\n\t\t\t\tnew_configs[i].store.name === fields[j].store.name){\n\n\t\t\t\tnew_configs[i].fields.push(fields[j].field);\n\t\t\t\tcount_fields++;\n\t\t\t}\n\t\t}\n\t}\n\n\t//check if all timestamps have their\n\t//field associated\n\tfor (var i=0; i<n; i++){\n\n\t\tif (new_configs[i].fields.length <= 1)\n\t\t\treturn null;\n\t}\n\n\t//check if all fields were assciated\n\t//with a timestamp field:\n\tif (count_fields != m){\n\n\t\treturn null;\n\t}\n\n\treturn new_configs;\n}", "function test_can_access_fields_object() {\n let r = new Contact(kTestFields);\n assert_not_equals(r.attributes, null);\n\n for (let fieldName in kResultingFields) {\n if (is_typed_default(fieldName))\n assert_serializations_equal(r.get(fieldName), kResultingFields[fieldName])\n else {\n assert_items_equal(r.get(fieldName), kResultingFields[fieldName],\n \"Field \" + fieldName + \" not equal: \" + JSON.stringify(r.attributes[fieldName])\n + \" -- \"\n + JSON.stringify(kResultingFields[fieldName]));\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts stock by id values
function sortStock(a, b) { if (parseInt(a[0]) > parseInt(b[0])) return 1; else return -1; }
[ "function valuesSortedById(obj) {\n return $.map(obj, function(x){return x;})\n .sort(function(a,b) {return a.id - b.id;});\n}", "sortDates() {\n this.datedRatings = this.datedRatings.sort(compareValues('id', 'desc'))\n }", "function sortMovieList(data, id) {\n if (id === \"episode\") {\n data.sort((a, b) => a.fields.episode_id > b.fields.episode_id ? 1 :\n b.fields.episode_id > a.fields.episode_id ? -1 : 0);\n } else if (id === \"year\") {\n console.log(id);\n data.sort((a, b) => a.fields.release_date > b.fields.release_date ? 1 :\n b.fields.release_date > a.fields.release_date ? -1 : 0);\n }\n loadScreen(data, \"sort\");\n }", "function sortDrinkByPrice(drinks) {\n\treturn drinks.sort((a, b) => a.price - b.price);\n}", "function sortTable() {\n\t\t\t\t\tsortedBy = $(\"#projects-sort :selected\").text();\n\t\t\t\t\tsortedById = parseInt($(\"#projects-sort\").val());\n\t\t\t\t\tdataTable.order([ [ sortedById, sortOrder ] ]).draw();\n\t\t\t\t}", "getData () {\n return this._data.sort((a, b) => b[this._sortColumn] - a[this._sortColumn])\n }", "function sortGasses()\n{\n var mixArray = Array();\n var mixTable = document.getElementById(\"addGassesHere\");\n\n if (mixTable.rows.length > 1) {\n for (var i = 0; i < mixTable.rows.length; i++)\n mixArray[i] = Array(mixTable.rows[i].cells[0].innerHTML, // Gas Mix\n mixTable.rows[i].cells[1].innerHTML); // Volume needed\n\n mixArray.sort(byMODhighToLow);\n\n for (var i = 0; i < mixArray.length; i++) {\n mixTable.rows[i].cells[0].innerHTML = mixArray[i][0]; // Gas mix\n mixTable.rows[i].cells[1].innerHTML = mixArray[i][1]; // Volume needed\n }\n }\n return;\n}", "function sortFx() {\n function compare(a, b) {\n const currencyA = a.currency.toLowerCase();\n const currencyB = b.currency.toLowerCase();\n\n let comparison = 0;\n if (currencyA > currencyB) {\n comparison = 1;\n } else if (currencyA < currencyB) {\n comparison = -1;\n }\n return comparison;\n }\n\n fxData.fx.sort(compare);\n}", "function sortItemsByPrice(items) {\n var sorted;\n sorted = items.sort(function (a, b) {\n return a.price - b.price;\n })\n return sorted;\n }", "sortDefense(items) {\n\n items.sort(function(a, b){\n\n if(a.def < b.def){ \n \n return -1;\n }\n if(a.def > b.def) {\n \n return 1;\n }\n return 0;\n })\n \n return items;\n \n }", "function sortByRankHandler(){\n // table.classList.remove('data');\n\n // take isolated copy keep the refernce safe\n let sortedByRank = myData.slice();\n sortedByRank.sort(function(a , b){\n return a.rank - b.rank;\n \n \n });\n display.innerHTML = ``;\n\n\n for (let index = 0; index < sortedByRank.length; index++) {\n // '+=' : means adding extra elements , while '=': means replace\n display.innerHTML +=`<tr>\n <td>${index+1}</td>\n <td>${sortedByRank[index].name}</td>\n <td>${sortedByRank[index].type}</td>\n <td>${sortedByRank[index].rank}</td>\n </tr>\n `;\n }\n console.table(sortedByRank);\n }", "updateItemsStock(id, stock) {\n return this.database\n .executeSql(\"UPDATE items SET stock = ? WHERE items_id = ?\", [stock, id])\n .then((_) => {\n this.loadItems();\n });\n }", "function sortByVol(a,b) {\n if (a.volume < b.volume) {\n return 1;\n }\n else if (a.volume > b.volume) {\n return -1;\n }\n else {\n return 0;\n }\n }", "function GetAlbumsSortedBy(id, sortMode, sortOverride) {\n $('#loading_anim_albums').show();\n var sortModes = ['DATE ADDED', 'A TO Z', 'RELEASE YEAR', 'ARTIST'];\n\n leftListId = id;\n\n if (id !== null && id.startsWith(\"albumartists\")) {\n //remove the artist because we do not need to display it when showing albums for an artist\n sortModes.splice(3, 1);\n }\n var theSortMode;\n\n if (sortOverride === false) {\n var idx = sortModes.indexOf(sortMode);\n if (idx == sortModes.length - 1) {\n theSortMode = sortModes[0];\n }\n else {\n theSortMode = sortModes[idx + 1];\n }\n }\n else {\n theSortMode = sortMode;\n }\n\t\n\t//todo: remove hardcoded album width values and get real values\n\tvar xAlbums = Math.floor($(\"#albums\").width() / 130);\n\tvar yAlbums = Math.ceil($(\"#albums\").height() / 161)\n\t//+ 1 row to prevent the div from scrolling while albums are loading\n\tvar numAlbsToGet = xAlbums * yAlbums + xAlbums;\n\t\n\tif(theSortMode === 'ARTIST'){\n\t\tnumAlbsToGet = yAlbums;\n\t}\n\n switch (theSortMode) {\n case \"DATE ADDED\":\n QueryAlbumsSortedByDateAdded(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'DATE ADDED', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'DATE ADDED'));\n }\n });\n break;\n case \"A TO Z\":\n QueryAlbumsSortedByAlbumTitle(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'A TO Z', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'A TO Z'));\n }\n });\n break;\n case \"RELEASE YEAR\":\n QueryAlbumsSortedByReleaseYear(id, 0, numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n if (id.startsWith('albumartists')) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'RELEASE YEAR', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeadersForGenres(id, result, 'RELEASE YEAR'));\n }\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeaders(result, 'RELEASE YEAR'));\n }\n });\n break;\n case \"ARTIST\":\n QueryAlbumsSortedByArtist(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n //just for genres\n UpdateView(CreateAlbumObjectsWithArtistHeadersForGenres(id, result, 'ARTIST', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithArtistHeaders(result, 'ARTIST'));\n }\n });\n }\n\n function UpdateView(result) {\n\t\t//render header\n\t\t$(\"#middle_header\").remove();\n $(\"#content\").append(\"#tmpl_albums_container\", result);\n\t\t\n\t\t$(\"#albums > .inner\").empty();\n\t\t//render results\n\t\t$.each(result.AlbumsOrHeaders,function(idx,value){\n\t\t\tif(value.IsContent === false){\n\t\t\t\t$(\"#albums > .inner\").append(\"#tmpl_album_header\",value);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tRenderAlbumToView($(\"#albums > .inner\"),value.Content);\n\t\t\t}\n\t\t});\n\t\t\n\t\t//for the first row of albums we need to remove the top padding\n\t\t\n\t\t//infinite scroll\n\t\tvar elem = $('#albums')\n elem.scroll(function () {\n\t\t\tif (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {\n\t\t\t\tconsole.log(\"getting more albums...\");\n\t\t\t\tGetMoreAlbums(leftListId);\n\t\t\t}\n });\n\n\t\t\n $('#loading_anim_albums').hide();\n }\n}", "function orderResults(ids, items) {\n\tconst indexed = _.indexBy(items, '_id');\n\treturn ids.map(function(id) { return indexed[id]; });\n}", "function sortNotes(){\n notesList.sort(function(a,b)\n {\n if(a.date < b.date)\n return 1;\n if(a.date > b.date)\n return -1;\n if(a.date == b.date)\n {\n if(a.id < b.id)\n return 1;\n if(a.id > b.id)\n return -1;\n }\n return 0;\n })\n console.log(\"posortowane\");\n}", "function sort(type, page, sr) {\n var order = sessionStorage.getItem(\"order\").split(\",\");\n console.log(\"pre:\" + order);\n switch (type) {\n case 0:\n order.sort(SortByName);\n break;\n case 1:\n order.sort(SortByShowing);\n break;\n case 2:\n order.sort(SortByPopularity);\n break;\n default:\n break;\n }\n console.log(\"posle: \" + order);\n sessionStorage.setItem(\"order\", order.toString());\n showFilms(page, sr);\n}", "function sortEntities( ids, entityMap ) {\n try {\n var entities = [];\n ids.forEach( ( id ) => {\n //IF ID IS STRING THEN TAKE NAME_ID ELSE ID_ID NOTE: DATASTORE SPECIFIC\n if( typeof id === 'string' ) {\n if( entityMap[ 'NAME_' + id ] ) {\n entities.push( entityMap[ 'NAME_' + id ] );\n } else {\n entities.push( null );\n }\n } else {\n if( entityMap[ 'ID_' + id ] ) {\n entities.push( entityMap[ 'ID_' + id ] );\n } else {\n entities.push( null );\n }\n }\n } );\n return entities;\n } catch( error ) {\n throw error;\n }\n }", "function sortTable(table) {\n\tvar store = [];\n\tfor (var i = 0, len = table.rows.length; i < len; i++) {\n\t\tvar row = table.rows[i];\n\t\tvar sortnr = parseInt(row.id);\n\t\tif (!isNaN(sortnr)) store.push([sortnr, row]);\n\t}\n\tstore.sort(function(x, y) {\n\t\treturn x[0] - y[0];\n\t});\n\tfor (var i = 0, len = store.length; i < len; i++) {\n\t\t$(store[i][1]).find(\"td:first\").text(i + 1);\n\t\t$(\"section.jsContainer #js-table tbody\").append($(store[i][1]).get(0));\n\t}\n\tstore = null;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a face list's information, including faceListId, name, userData and faces in the face list. Face list simply represents a list of faces, and could be treated as a searchable data source in Face Find Similar. Http Method GET
faceListGetAFaceListGet(queryParams, headerParams, pathParams) { const queryParamsMapped = {}; const headerParamsMapped = {}; const pathParamsMapped = {}; Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListGetAFaceListGetQueryParametersNameMap)); Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListGetAFaceListGetHeaderParametersNameMap)); Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListGetAFaceListGetPathParametersNameMap)); return this.makeRequest('/facelists/{faceListId}', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped); }
[ "faceListCreateAFaceListPut(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListCreateAFaceListPutQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListCreateAFaceListPutHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListCreateAFaceListPutPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'put', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "faceListDeleteAFaceListDelete(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListDeleteAFaceListDeleteQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListDeleteAFaceListDeleteHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListDeleteAFaceListDeletePathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'delete', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "personGetAPersonFaceGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonGetAPersonFaceGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonGetAPersonFaceGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonGetAPersonFaceGetPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "faceListUpdateAFaceListPatch(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListUpdateAFaceListPatchQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListUpdateAFaceListPatchHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListUpdateAFaceListPatchPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'patch', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "faceListAddAFaceToAFaceListPost(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListAddAFaceToAFaceListPostQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListAddAFaceToAFaceListPostHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListAddAFaceToAFaceListPostPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}/persistedFaces', 'post', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "function faces(name, title, id, data) {\n // create canvas to draw on\n const img = document.getElementById(id);\n if (!img) return;\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.left = `${img.offsetLeft}px`;\n canvas.style.top = `${img.offsetTop}px`;\n // @ts-ignore\n canvas.width = img.width;\n // @ts-ignore\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n // draw title\n ctx.font = '1rem sans-serif';\n ctx.fillStyle = 'black';\n ctx.fillText(name, 2, 15);\n ctx.fillText(title, 2, 35);\n for (const person of data) {\n // draw box around each face\n ctx.lineWidth = 3;\n ctx.strokeStyle = 'deepskyblue';\n ctx.fillStyle = 'deepskyblue';\n ctx.globalAlpha = 0.4;\n ctx.beginPath();\n ctx.rect(person.detection.box.x, person.detection.box.y, person.detection.box.width, person.detection.box.height);\n ctx.stroke();\n ctx.globalAlpha = 1;\n ctx.fillText(`${Math.round(100 * person.genderProbability)}% ${person.gender}`, person.detection.box.x, person.detection.box.y - 18);\n ctx.fillText(`${Math.round(person.age)} years`, person.detection.box.x, person.detection.box.y - 2);\n // draw face points for each face\n ctx.fillStyle = 'lightblue';\n ctx.globalAlpha = 0.5;\n const pointSize = 2;\n for (const pt of person.landmarks.positions) {\n ctx.beginPath();\n ctx.arc(pt.x, pt.y, pointSize, 0, 2 * Math.PI);\n ctx.fill();\n }\n }\n // add canvas to document\n document.body.appendChild(canvas);\n}", "faceListDeleteAFaceFromAFaceListDelete(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListDeleteAFaceFromAFaceListDeleteQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListDeleteAFaceFromAFaceListDeleteHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListDeleteAFaceFromAFaceListDeletePathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}/persistedFaces/{persistedFaceId}', 'delete', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }", "function getAboutForSpeakerOrRefineList(list) {\n response.session('refine.list', 0);\n\n if (list.length === 0) { // Return the about for the speaker\n response.session('Speaker', speaker); // Save for later speaker context\n return Cache.getAboutForSpeaker(speaker);\n }\n\n if (list.length === 1) { // Return the about for the speaker\n var spkr = list[0];\n response.session('Speaker', spkr); // Save for later speaker context\n Output.log('<speaker> ' + spkr.toLowerCase(), request);\n return Cache.getAboutForSpeaker(spkr);\n }\n\n // need to ask which name the user wants\n // another intent will handle it, give that intent some context\n endSession = false;\n response.session('refine.list', 1);\n return Text.whichSpeaker(list.length, speaker) + '?' + Text.join(list) + '?';\n }", "function load_family_ids() {\r\n\t\tids=[];\r\n\t\trequest('xw_controller=clan&xw_action=view&xw_city=1&xw_person='+User.id.substr(2)+'&mwcom=1&xw_client_id=8',function(page) {\r\n\t\t\tvar jpage=$('<div>'+page+'</div>');\r\n\t\t\tjpage.find('#member_list').find('.member_info').each(function(){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tvar fbid = 0, m;\r\n\t\t\t\t\tif (m = /\\d+_(\\d+)_\\d+/.exec($(this).find('.clan_member_pic').attr('src'))) {\r\n\t\t\t\t\t\tfbid = m[1];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(fbid) {\r\n\t\t\t\t\t\tids.push(fbid);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (uglybypass) {}\r\n\t\t\t});\r\n\t\t\t$('#'+spocklet+'_list').val(ids.join(','));\r\n\t\t\t$('#'+spocklet+'_numids').text(ids.length);\r\n\t\t\tlog('Family Loaded');\r\n\t\t});\r\n\t}", "function getLookupList() {\n\n\t\t\t\t\tvar def = $q.defer();\n\n\t\t\t\t\tif ($scope.lookupList === void 0) {\n\n\t\t\t\t\t\tSharePoint.getWeb($scope.schema.LookupWebId).then(function(web) {\n\n\t\t\t\t\t\t\tweb.getList($scope.schema.LookupList).then(function(list) {\n\n\t\t\t\t\t\t\t\t$scope.lookupList = list;\n\n\t\t\t\t\t\t\t\tlist.getProperties({ $expand: 'Forms' }).then(function() {\n\n\t\t\t\t\t\t\t\t\tlist.getFields().then(function() {\n\n\t\t\t\t\t\t\t\t\t\tdef.resolve($scope.lookupList);\n\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t});\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// Returns cached list\n\t\t\t\t\t\tdef.resolve($scope.lookupList);\n\t\t\t\t\t}\n\n\n\t\t\t\t\treturn def.promise;\n\t\t\t\t}", "function detectFaces(img, faceSize = 150) {\r\n return getFacesFromLocations(img, locateFaces(img).map(mmodRect => mmodRect.rect), faceSize)\r\n }", "function getList() {\r\n // URL to access list of all Pokemon names and URLs from PokeAPI\r\n const POKEMON_LIST_URL = \"https://pokeapi.co/api/v2/pokemon/?offset=0&limit=964\";\r\n\r\n // Get data\r\n getData(POKEMON_LIST_URL);\r\n}", "static async list(ctx) {\n // build sql query including any query-string filters; eg ?field1=val1&field2=val2 becomes\n // \"Where field1 = :field1 And field2 = :field2\"\n let sql = 'Select * From Team';\n if (ctx.request.querystring) {\n const filter = Object.keys(ctx.request.query).map(q => `${q} = :${q}`).join(' and ');\n sql += ' Where '+filter;\n }\n sql += ' Order By Name';\n\n try {\n\n const [ teams ] = await Db.query(sql, ctx.request.query);\n\n await ctx.render('teams-list', { teams });\n\n } catch (e) {\n switch (e.code) {\n case 'ER_BAD_FIELD_ERROR': ctx.throw(403, 'Unrecognised Team field'); break;\n default: throw e;\n }\n }\n }", "get adjacentFaces() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the adjacent faces - the face is not bound to a Mesh`);\n\n // Return the list of adjacent faces\n return [\n \n // Find face at edge ab/ba\n this.findAdjacentFaceFromEdgeIndex(0), \n \n // Find face at edge bc/cb\n this.findAdjacentFaceFromEdgeIndex(1),\n\n // Find face at edge ca/ac\n this.findAdjacentFaceFromEdgeIndex(2)];\n }", "function getList(listKey) {\n var json = localStorage[getStorageKey(listKey)];\n var mruObject = json ? JSON.parse(json) : null;\n\n // Return list or new empty array\n return mruObject ? mruObject.list : [];\n }", "function loadConversationList() {\r\n\tconsole.log('loadConversationList');\r\n\r\n\t// Split redirect Uri\r\n\tconst redirectUri = setupClientAndTokenUri();\r\n\t// Authenticate with PureCloud\r\n\tconsole.log('Login implicit grant w/redirectUri:', redirectUri);\r\n\t// Authenticate with PureCloud\r\n\tclient.loginImplicitGrant(clientId, redirectUri)\r\n\t\t.then(() => {\r\n\t\t\tconsole.log('Logged in');\r\n\t\t\t// Get authenticated user's info\r\n\t\t\treturn usersApi.getUsersMe();\r\n\t\t})\r\n\t\t.then((userMe) => {\r\n\t\t\tconsole.log('userMe: ', userMe);\r\n\t\t\tme = userMe;\r\n\t\t\t//\r\n\t\t\tconsole.log('authData token: ', usersApi.apiClient.authData.accessToken );\r\n const token = usersApi.apiClient.authData.accessToken;\r\n\t\t\t// Load conversation list\r\n\t\t\tconversationList = JSON.parse(localStorage.getItem('conversationList'));\r\n\t\t\tconsole.log('Local storage: ', JSON.parse(localStorage.getItem('conversationList')) );\r\n\t\t})\r\n\t\t.catch((err) => console.error(err));\r\n\r\n\tconsole.log('Finish (loadConversationList)');\r\n}", "ListOfU2FAccounts() {\n let url = `/me/accessRestriction/u2f`;\n return this.client.request('GET', url);\n }", "getApiClubSeasonMemberList(season_id, ClubMembersList){\n\n ClubMembersList.setState({members_data: []});\n let API_URL = '';\n\n if(season_id === 'all'){\n API_URL = ClubMembersList.props.API_URL + '/v2.1/clubs/' + ClubMembersList.props.club_id + '/profiles/';\n }\n else {\n API_URL = ClubMembersList.props.API_URL + '/v2.1/clubs/' + ClubMembersList.props.club_id\n + '/profiles/?season_id=' + season_id;\n }\n\n fetch(API_URL, {\n method: \"GET\",\n credentials: 'include',\n })\n .then(response =>\n response.json()\n )\n .then(json_response =>\n ClubMembersList.createDataFromJson(json_response),\n )\n }", "function getFavorites(username){\n\t$.ajax({\n\t url: Url+'/getfavs?Username='+username,\n\t type: \"GET\",\n\t success: listFavorites,\n\t error: displayError,\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renderTMEvents() primary API into TM Events API
function renderTMEvents(startDate, startTime, endDate, endTime, city, state, postalCode, countryCode, radius, maxEvents) { // We are expecting a valid date and city or else stop....TODO: return a valid error code if ((!startDate) || (!endDate) || (!city)) { alert("Fatal Error - no date or city passed into renderTMEvents"); } // Initialize time to 24 hours if not passed in if (!startTime) { startTime = "00:00:00"; } if (!endTime) { endTime = "23:59:59"; } if (!radius) { radius = 150; } // maximum number of events we want returned from Ticket Master event query if (!maxEvents) { maxEvents = "30"; } // construct the TM localStartDateTime needed for the search event TM API var localStartDateTime = "&localStartDateTime=" + startDate + "T" + startTime + "," + endDate + "T" + endTime; //var endDateTime = "&localStartEndDateTime=" + endDate + "T" + endTime + "Z"; // always looking for music events for this app. var classificationId = "&classificationId=KZFzniwnSyZfZ7v7nJ"; //URL into TM API' var url = "https://app.ticketmaster.com/discovery/v2/events.json?size=" + maxEvents + "&apikey=uFdFU8rGqFvKCkO5Jurt2VUNq9H1Wcsx"; var queryString = url + localStartDateTime + classificationId + countryCode; // construct the appropriate parameters needed for TM if (city) { queryString = queryString + "&city=" + city; } if (radius) { queryString = queryString + "&radius=" + radius; } if (postalCode) { queryString = queryString + "&postalCode=" + postalCode; } <<<<<<< HEAD if (state) { queryString = queryString + "&state=" + state; } // console log the queryString console.log(queryString); // make the AJAX call into TM $.ajax({ type: "GET", url: queryString, async: true, dataType: "json", success: function (response) { // we are here if the AJAX call is successful console.log(response); var events = createEvents(response); return events; // console.log(TMEvents); }, error: function (xhr, status, err) { // This time, we do not end up here! // TODO: return an error code for now just setTMEvent to empty TMEvents = ""; console.log(err); } }); }
[ "onRender() {}", "function renderSingleEvent(info) {\n return ('<div class=\"event_block animate-fadein\">' +\n '<div class=\"event_start_info\">' +\n '<div class=\"event_start_dt\">starts at</div>' +\n '<div class=\"event_start_time\">' +\n '<div class=\"time_h\">' + info.acf.hour + '</div>' +\n '<div class=\"time_min_hold\">' +\n '<div class=\"time_m\">' + info.acf.minutes + '</div>' +\n '<div class=\"time_mod\">' + info.acf.format + '</div>' +\n '</div>' +\n '</div>' +\n '</div>' +\n '<div class=\"event_photo_hold\">' +\n '<a href=\"\" title=\"\">' +\n '<img src=\"' + info.acf.featured_image + ' \" alt=\"Event image\" class=\"event_photo\">' +\n '</a>' +\n '<a href=\"' + info.acf.featured_image + '\" title=\"\" class=\"event_info_link\">i</a>' +\n '</div>' +\n '<div class=\"event_main\">' +\n '<a href=\"' + info.acf.featured_image + '\" title=\"\">' +\n '<h3 class=\"event_title\">' + info.post_title + '</h3>' +\n '</a>' +\n '<div class=\"event_desc\">' +\n '<div class=\"event_d_text\">' + info.excerpt + '</div>' +\n '</div>' +\n '<div class=\"event_date_info\">' +\n '<div class=\"event_day\">' + info.acf.recurrency + '</div>' +\n '<div class=\"event_day\" style=\"color: #ff6726;font-weight:600;\">' + info.acf.additional +'</div>' +\n '</div>' +\n '</div>' +\n '</div>');\n}", "function vB_Text_Editor_Events()\n{\n}", "_render() {\n if (this._connected && !!this._template) {\n render(this._template(this), this, {eventContext: this});\n }\n }", "function getEvents(){\nreturn events;\n}", "render() {\n\t\t\tthis.containerElement.fullCalendar(\"removeEvents\");\n\t\t\tthis.containerElement.fullCalendar(\"addEventSource\", [].concat(this.state.schedule));\n\n\t\t\tthis.setDateItemColor();\n\t\t}", "parseEvent() {\n\t\tlet addr = ppos;\n\t\tlet delta = this.parseDeltaTime();\n\t\ttrackDuration += delta;\n\t\tlet statusByte = this.fetchBytes(1);\n\t\tlet data = [];\n\t\tlet rs = false;\n\t\tlet EOT = false;\n\t\tif (statusByte < 128) { // Running status\n\t\t\tdata.push(statusByte);\n\t\t\tstatusByte = runningStatus;\n\t\t\trs = true;\n\t\t} else {\n\t\t\trunningStatus = statusByte;\n\t\t}\n\t\tlet eventType = statusByte >> 4;\n\t\tlet channel = statusByte & 0x0F;\n\t\tif (eventType === 0xF) { // System events and meta events\n\t\t\tswitch (channel) { // System message types are stored in the last nibble instead of a channel\n\t\t\t// Don't really need these and probably nobody uses them but we'll keep them for completeness.\n\n\t\t\tcase 0x0: // System exclusive message -- wait for exit sequence\n\t\t\t\t// console.log('sysex');\n\t\t\t\tlet cbyte = this.fetchBytes(1);\n\t\t\t\twhile (cbyte !== 247) {\n\t\t\t\t\tdata.push(cbyte);\n\t\t\t\t\tcbyte = this.fetchBytes(1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 0x2:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0x3:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0xF: // Meta events: where some actually important non-music stuff happens\n\t\t\t\tlet metaType = this.fetchBytes(1);\n\t\t\t\tlet len;\n\t\t\t\tswitch (metaType) {\n\t\t\t\tcase 0x2F: // End of track\n\t\t\t\t\tthis.skip(1);\n\t\t\t\t\tEOT = true;\n\t\t\t\t\t// console.log('EOT');\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0x51:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tdata.push(this.fetchBytes(len)); // All one value\n\t\t\t\t\tif (this.firstTempo === 0) {\n\t\t\t\t\t\t[this.firstTempo] = data;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x58:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t\tif (this.firstBbar === 0) {\n\t\t\t\t\t\tthis.firstBbar = data[0] / 2 ** data[1];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\t// console.log('Mlen = '+len);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teventType = getIntFromBytes([0xFF, metaType]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tconsole.log('parser error');\n\t\t\t}\n\t\t\tif (channel !== 15) {\n\t\t\t\teventType = statusByte;\n\t\t\t}\n\t\t\tchannel = -1; // global\n\t\t} else {\n\t\t\tswitch (eventType) {\n\t\t\tcase 0x9:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tif (data[1] === 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet ins;\n\t\t\t\t// var ins = currentInstrument[channel]; // Patch out percussion splitting\n\t\t\t\t// TODO: Patch back in, in a new way\n\t\t\t\tif (channel === 9) {\n\t\t\t\t\tthis.trks[tpos].hasPercussion = true;\n\t\t\t\t\t[ins] = data;\n\t\t\t\t} else {\n\t\t\t\t\tins = currentInstrument[channel];\n\t\t\t\t}\n\t\t\t\tlet note = new Note(trackDuration, data[0], data[1], ins, channel);\n\t\t\t\tif ((data[0] < this.trks[tpos].lowestNote && !this.trks[tpos].hasPercussion)\n || this.trks[tpos].lowestNote === null) {\n\t\t\t\t\t[this.trks[tpos].lowestNote] = data;\n\t\t\t\t}\n\t\t\t\tif (data[0] > this.trks[tpos].highestNote && !this.trks[tpos].hasPercussion) {\n\t\t\t\t\t[this.trks[tpos].highestNote] = data;\n\t\t\t\t}\n\t\t\t\tthis.trks[tpos].notes.push(note);\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedInstruments, ins)) {\n\t\t\t\t\tthis.trks[tpos].usedInstruments.push(ins);\n\t\t\t\t}\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedChannels, channel)) {\n\t\t\t\t\tthis.trks[tpos].usedChannels.push(channel);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0xC:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\t// console.log(tpos+': '+data[0]);\n\t\t\t\tcurrentLabel = getInstrumentLabel(data[0]);\n\t\t\t\t// The last instrument on a channel ends where an instrument on the same channel begins\n\t\t\t\t// this.usedInstruments[tpos].push({ins: data[0], ch: channel, start: trackDuration});\n\t\t\t\t// if(notInArr(this.usedInstruments,data[0])){this.usedInstruments.push(data[0])} // Do this for now\n\t\t\t\t[currentInstrument[channel]] = data;\n\t\t\t\tbreak;\n\t\t\tcase 0xD:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t}\n\t\t\tfor (let i = 0; i < noteDelta.length; i++) {\n\t\t\t\tnoteDelta[i] += delta;\n\t\t\t}\n\t\t\tif (eventType === 0x9 && data[1] !== 0) {\n\t\t\t\t// console.log(bpbStuff);\n\t\t\t\tfor (let i = 1; i <= 16; i++) {\n\t\t\t\t\tlet x = (i * noteDelta[channel]) / this.timing;\n\t\t\t\t\tlet roundX = Math.round(x);\n\t\t\t\t\t// console.log(\"Rounded by: \" + roundX-x);\n\t\t\t\t\tthis.trks[tpos].quantizeErrors[i - 1] += Math.round(Math.abs((roundX - x) / i) * 100);\n\t\t\t\t}\n\t\t\t\tnoteDelta[channel] = 0;\n\t\t\t\tthis.noteCount++;\n\t\t\t}\n\t\t}\n\t\tthis.trks[tpos].events.push(new MIDIevent(delta, eventType, channel, data, addr));\n\t\t// console.log('+'+delta+': '+eventType+' @'+channel);\n\t\t// console.log(data);\n\t\t// this.debug++;\n\t\tif (this.debug > 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn EOT;// || this.debug>=4;\n\t}", "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 history_json_to_html(data) {\n var html = \"\";\n for (var i = 0, len = data.events.length; i < len; i++) {\n var event = data.events[i];\n var type_icon;\n switch (event.type) {\n case \"future\":\n case \"future_series\":\n case \"record\":\n type_icon = \"images/745_1_11_Video_1REC.png\";\n break;\n case \"live\":\n type_icon = \"images/tvmast.png\";\n break;\n case \"play\":\n default:\n type_icon = \"images/745_1_10_Video_2Live.png\";\n break;\n }\n var duration = duration_seconds_to_minutes(event.end - event.start + 30);\n\n html += \"<tr class=\\\"event_row visible_event\\\">\";\n\n html += \"<td class=\\\"search_type\\\">\";\n html += \"<img src=\\\"\" + type_icon + \"\\\" width=22 height=22 alt=\\\"\" + event.type + \"\\\" title=\\\"\" + event.type + \"\\\"/>\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_channel\\\">\";\n if (event.channel_name != \"\") {\n html += \"<div>\";\n html += \"<img src=\\\"\" + event.channel_icon_path + \"\\\" width=20 height=20 alt=\\\"\" + escapeHtml(event.channel_name) + \"\\\"/>\";\n html += \"<span>\" + escapeHtml(event.channel_name) + \"</span>\";\n html += \"</div>\";\n }\n html += \"</td>\";\n\n html += \"<td class=\\\"search_title\\\">\";\n html += \"<div>\" + escapeHtml(event.title) + \"</div>\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_synopsis\\\">\";\n html += \"<div>\" + escapeHtml(event.synopsis) + \"</div>\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_datetime\\\" sval=\\\"\" + event.start + \"\\\">\";\n html += formatDateTime(event.start);\n html += \"</td>\";\n \n html += \"<td class=\\\"search_duration\\\" sval=\\\"\" + duration + \"\\\">\";\n html += duration + (duration == 1 ? \" min\" : \" mins\");\n html += \"</td>\";\n\n html += \"<td class=\\\"search_flags\\\">\";\n if (inventory_enabled) {\n if (event.available) {\n html += \"<a class=\\\"inventory\\\" href=\\\"#\\\"><img src=\\\"images/available.png\\\" width=16 height=16 title=\\\"available\\\"></a>\";\n }\n }\n if (event.repeat_crid_count > 0) {\n html += \" <a class=\\\"repeat\\\" prog_crid=\\\"\" + event.event_crid + \"\\\" href=\\\"#\\\"><img src=\\\"images/repeat.png\\\" width=16 height=16 title=\\\"CRID repeat\\\"></a>\";\n } else if (event.repeat_count > 1) {\n html += \" <a class=\\\"dejavu\\\" prog_id=\\\"\" + event.program_id + \"\\\" href=\\\"#\\\"><img src=\\\"images/dejavu.png\\\" width=16 height=16 title=\\\"d&eacute;j&agrave; vu?\\\"></a>\";\n }\n html += \"</td>\";\n\n html += \"</tr>\";\n }\n return $(html);\n }", "function findWebGLEvents(modelHelper, mailboxEvents, animationEvents) {\n for (var event of modelHelper.model.getDescendantEvents()) {\n if (event.title === 'DrawingBuffer::prepareMailbox')\n mailboxEvents.push(event);\n else if (event.title === 'PageAnimator::serviceScriptedAnimations')\n animationEvents.push(event);\n }\n }", "function emitEvent (eventName, data) {\n\n\t\treturn function viewsEmit () {\n\t\t\tviews.emit(eventName, data);\n\t\t};\n\n\t}", "function renderByType() {\n\t\t\t\tswitch(templateEngineRequire.renderType()) {\n\t\t\t\t\tcase 'string':\n\t\t\t\t\t\trenderStringFromFile(templateEngineRequire, viewPath, view.data, function(err,data) {\n\t\t\t\t\t\t\tcallback(err,data);\n\t\t\t\t\t\t});\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'file':\n\t\t\t\t\t\trenderFile(templateEngineRequire, viewPath, view.data, function(err,data) {\n\t\t\t\t\t\t\tcallback(err,data);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcallback(new Error('The template engine has an unsupported renderType'));\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "_registerEvent () {}", "function renderSyncDoc(service, SyncDoc, SessionState, SrcLog, res) {\n\n var data = { temperature: 10, humidity: '0' };\n service\n .documents(SyncDoc)\n .fetch()\n .then(response => {\n\n console.log(SrcLog,\n response.data.temperature,\n response.data.humidity,\n dht11.temperature, dht11.humidity);\n/*\n console.log(SrcLog, response);\n*/\n/*\n if(response.data.temperature === undefined || response.data.humidity === undefined){\n updateSyncControl(service, SyncControl);\n setTimeout(function(){deleteSyncDoc(service, SyncDoc);}, 10000);\n setTimeout(function(){createSyncDoc(service, SyncDoc);}, 30000);\n setTimeout(function(){retrieveSyncDoc(service, SyncDoc, dht11);}, 50000);\n setTimeout(function(){rendering(SessionState, res, dht11);}, 55000);\n }else{\n*/\n dht11 = response.data;\n res.render('dht11', {\n SessionState: SessionState,\n dht11: dht11,\n title: \"Temperature/Humidity monitor for my home\",\n header: \"Some users\"\n });\n/*\n }\n*/\n })\n .catch(error => {\n console.log(error);\n });\n}", "function getEvent(item, refid) {\n var event = { 'refid': refid };\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 'TYPE':\n event['etype'] = tree[i].data;\n break;\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 case 'NOTE':\n event[tag_lc] = cleanPointer(tree[i].data);\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 renderEventsBlock($wrapper, data) {\n var events = '';\n for (var i = 0; i < data.events.length; i++) {\n events += renderSingleEvent(data.events[i]);\n }\n var html = '<li class=\"events_item stickem-container\">';\n html += renderEventBlockHeader(data['formatted_date']);\n html += (\n '<div class=day_block\">' +\n '<div class=\"event_b_list\">' +\n events +\n '</div>' +\n '</div>'\n );\n html += '</li>';\n $wrapper.before(html);\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}", "async function transformToTLJson() {\n var timelineJson = {}\n timelineJson.events = [];\n // list of slide objects (each slide is an event)\n\n //wikiDate is in iso-8601 format \n function parseDate(wikiDate) {\n var wdate = new Date(wikiDate);\n\n return {\n year: wdate.getUTCFullYear(),\n month: wdate.getUTCMonth(),\n day: wdate.getUTCDate(),\n hour: wdate.getUTCHours(),\n minute: wdate.getUTCMinutes(),\n second: wdate.getUTCSeconds(),\n display_date: `Date of discovery: ${wdate.getUTCFullYear()}`\n };\n\n }\n\n function newSlide(wikiElement) {\n var slide = {};\n\n if (wikiElement.dateOfDiscovery) {\n if (wikiElement.dateOfDiscovery.startsWith('-')) {\n let year = wikiElement.dateOfDiscovery.match(/(-\\d+)-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z/);\n if (year) {\n slide.start_date = {\n year: year[1]\n };\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n } else {\n slide.start_date = parseDate(wikiElement.dateOfDiscovery);\n if (isNaN(slide.start_date.year)) {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n }\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n\n slide.text = {\n headline: ` <a href=\"${wikiElement.elementWikiUrl}\">${wikiElement.elementLabel}</a>`,\n text: createTable(selectTableData(wikiElement))\n };\n\n slide.media = {\n url: wikiElement.elementWikiUrl,\n thumbnail: wikiElement.picture\n };\n slide.unique_id = \"a\" + wikiElement.anum;\n slide.autolink = false;\n return slide;\n }\n\n var wikiData = await getData();\n for (var ekey in wikiData) {\n timelineJson.events.push(newSlide(wikiData[ekey]));\n }\n return timelineJson;\n}", "function getEvents() {\n\t/// \\todo add /api/events-since/{index} (and change Traffic Monitor to keep latest\n\tajax(\"/publish/EventLog\", function(r) {\n\t\tconst events = JSON.parse(r).events || [];\n\t\tfor (const event of events.slice(lastEvent+1)) {\n\t\t\tlastEvent = event.index;\n\t\t\tconst row = document.getElementById(\"event-log\").insertRow(0);\n\n\t\t\trow.insertCell(0).textContent = event.name;\n\t\t\trow.insertCell(1).textContent = event.type;\n\n\t\t\tconst cell = row.insertCell(2);\n\t\t\tif(event.isAvailable) {\n\t\t\t\tcell.textContent = \"available\";\n\t\t\t} else {\n\t\t\t\tcell.textContent = \"offline\";\n\t\t\t\trow.classList.add(\"error\");\n\t\t\t}\n\n\t\t\trow.insertCell(3).textContent = event.description;\n\t\t\trow.insertCell(4).textContent = new Date(event.time * 1000).toISOString();\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a simple list of genes and weights. More complex signatures would be possible, but will require some work writing the xena query.
function parse(str) { if (str[0] !== '=') { return; } try { var list = parser(str.slice(1).trim()); return { weights: pluck(list, 0), genes: pluck(list, 1) }; } catch (e) { console.log('parsing error', e); } return; }
[ "function segmentByWeight(gender, products) {\n\tconst sql = `\n\t\tSELECT *\n\t\tFROM ? WHERE name LIKE '%Osprey%' AND (gender = '${gender}' OR gender = 'unisex')\n\t\tORDER BY weight->data->0->val ASC\n\t`;\n\treturn alasql(sql, [products]);\n}", "function genAttrQueries(a, h, t, rxs) {\r\n\t\tvar ra = {\r\n\t\t\titems : [],\r\n\t\t\tsel : '',\r\n\t\t\tmethod : h,\r\n\t\t\ttype : t\r\n\t\t};\r\n\t\tvar y = '';\r\n\t\tvar x = $.isArray(a) ? a : a && typeof a === 'string' ? a.split(',')\r\n\t\t\t\t: [];\r\n\t\tfor (var i = 0; i < x.length; i++) {\r\n\t\t\ty = '[' + x[i] + ']';\r\n\t\t\tra.items.push({\r\n\t\t\t\tname : x[i],\r\n\t\t\t\tsel : y,\r\n\t\t\t\tregExp : new RegExp('\\\\s' + x[i] + rxs, 'ig')\r\n\t\t\t});\r\n\t\t\tra.sel += ra.sel.length > 0 ? ',' + y : y;\r\n\t\t}\r\n\t\treturn ra;\r\n\t}", "function get_genres(str) {\n return str.split(\";\");\n}", "extractLists({ remove = false, ignoreErrors = false } = {}) {\n const lists = {}; // has scalar keys so could be a simple Object\n const onError = ignoreErrors ? (() => true) :\n ((node, message) => { throw new Error(`${node.value} ${message}`); });\n\n // Traverse each list from its tail\n const tails = this.getQuads(null, IRIs[\"default\"].rdf.rest, IRIs[\"default\"].rdf.nil, null);\n const toRemove = remove ? [...tails] : [];\n tails.forEach(tailQuad => {\n const items = []; // the members found as objects of rdf:first quads\n let malformed = false; // signals whether the current list is malformed\n let head; // the head of the list (_:b1 in above example)\n let headPos; // set to subject or object when head is set\n const graph = tailQuad.graph; // make sure list is in exactly one graph\n\n // Traverse the list from tail to end\n let current = tailQuad.subject;\n while (current && !malformed) {\n const objectQuads = this.getQuads(null, null, current, null);\n const subjectQuads = this.getQuads(current, null, null, null);\n let quad, first = null, rest = null, parent = null;\n\n // Find the first and rest of this list node\n for (let i = 0; i < subjectQuads.length && !malformed; i++) {\n quad = subjectQuads[i];\n if (!quad.graph.equals(graph))\n malformed = onError(current, 'not confined to single graph');\n else if (head)\n malformed = onError(current, 'has non-list arcs out');\n\n // one rdf:first\n else if (quad.predicate.value === IRIs[\"default\"].rdf.first) {\n if (first)\n malformed = onError(current, 'has multiple rdf:first arcs');\n else\n toRemove.push(first = quad);\n }\n\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (rest)\n malformed = onError(current, 'has multiple rdf:rest arcs');\n else\n toRemove.push(rest = quad);\n }\n\n // alien triple\n else if (objectQuads.length)\n malformed = onError(current, 'can\\'t be subject and object');\n else {\n head = quad; // e.g. { (1 2 3) :p :o }\n headPos = 'subject';\n }\n }\n\n // { :s :p (1 2) } arrives here with no head\n // { (1 2) :p :o } arrives here with head set to the list.\n for (let i = 0; i < objectQuads.length && !malformed; ++i) {\n quad = objectQuads[i];\n if (head)\n malformed = onError(current, 'can\\'t have coreferences');\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (parent)\n malformed = onError(current, 'has incoming rdf:rest arcs');\n else\n parent = quad;\n }\n else {\n head = quad; // e.g. { :s :p (1 2) }\n headPos = 'object';\n }\n }\n\n // Store the list item and continue with parent\n if (!first)\n malformed = onError(current, 'has no list head');\n else\n items.unshift(first.object);\n current = parent && parent.subject;\n }\n\n // Don't remove any quads if the list is malformed\n if (malformed)\n remove = false;\n // Store the list under the value of its head\n else if (head)\n lists[head[headPos].value] = items;\n });\n\n // Remove list quads if requested\n if (remove)\n this.removeQuads(toRemove);\n return lists;\n }", "function convertSongScript2XML(scriptArray) {\n var xmlSource = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n + '<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 2.0 Partwise//EN\"'\n + ' \"http://www.musicxml.org/dtds/partwise.dtd\">'\n + '<score-partwise>'\n + ' <identification>'\n + ' <encoding>'\n + ' <software>Scratch - sb2musicxml</software>'\n + ' <encoding-date></encoding-date>'\n + ' </encoding>'\n + ' </identification>'\n + ' <part-list>'\n + ' <score-part id=\"P1\">'\n + ' <part-name>MusicXML Part</part-name>'\n + ' </score-part>'\n + ' </part-list>'\n + ' <part id=\"P1\">'\n + ' <measure number=\"1\">'\n + ' <attributes>'\n + ' <divisions></divisions>'\n + ' <time>'\n + ' <beats></beats>'\n + ' <beat-type></beat-type>'\n + ' </time>'\n + ' </attributes>'\n + ' <sound/>'\n + ' </measure>'\n + ' </part>'\n + '</score-partwise>'\n \n var xml = (new DOMParser()).parseFromString(xmlSource, 'text/xml');\n \n // Insert date\n var date = new Date();\n //xml.getElementsByTagName('encoding-date')[0].textContent = date.toLocaleDateString().split('/').join('-');\n xml.querySelector('encoding-date').textContent = [date.getFullYear(), ('0' + (date.getMonth() + 1)).slice(-2), ('0' + date.getDate()).slice(-2)].join('-');\n\n // Default values (may be overwritten later)\n var tempo = 110;\n var beats = 2;\n var beatType = 4;\n var durationPerMeasure; // duration of a measure\n xml.querySelector('divisions').textContent = divisions; // default divisions\n xml.querySelector('sound').setAttribute('tempo', tempo); // default tempo\n xml.querySelector('beats').textContent = beats; // default beats\n xml.querySelector('beat-type').textContent = beatType; // default beat-type\n \n // Start parsing\n var measureNumber = 1;\n var initialNoteFlag = true;\n var cumSumDuration = 0 ; // cumulative duration to check whether a new measure needs to be created or not\n var curMeasureElm = xml.querySelector('measure[number=\"1\"]'); // current measure\n var syllabicState = 'single'; // for English lyric\n var reservedElmForNextMeasure = null; \n\n // Create a note with sound\n function _createSoundNote(step, alter, octave, duration, lyricText, syllabicState) {\n var pitchElm = xml.createElement('pitch'); // pitch {step, alter, octave}\n var stepElm = xml.createElement('step');\n stepElm.textContent = step;\n pitchElm.appendChild(stepElm);\n if (alter != 0) {\n var alterElm = xml.createElement('alter');\n alterElm.textContent = alter;\n pitchElm.appendChild(alterElm);\n }\n var octaveElm = xml.createElement('octave');\n octaveElm.textContent = octave;\n pitchElm.appendChild(octaveElm);\n\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n\n var lyricElm = xml.createElement('lyric'); // lyric {text, syllabic}\n var textElm = xml.createElement('text');\n textElm.textContent = lyricText;\n lyricElm.appendChild(textElm);\n var syllabicElm = xml.createElement('syllabic');\n syllabicElm.textContent = syllabicState;\n lyricElm.appendChild(syllabicElm);\n\n var noteElm = xml.createElement('note'); // note {pitch, duration, lyric}\n noteElm.appendChild(pitchElm);\n noteElm.appendChild(durationElm);\n noteElm.appendChild(lyricElm);\n\n return noteElm;\n }\n\n // Create a new 'rest' note\n function _createRestNote(duration) {\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n var noteElm = xml.createElement('note'); // note {rest, duration}\n noteElm.appendChild(xml.createElement('rest'));\n noteElm.appendChild(durationElm);\n return noteElm;\n }\n\n // Create sound \n function _createTempo(tempo) {\n var soundElm = xml.createElement('sound');\n soundElm.setAttribute('tempo', tempo);\n return soundElm;\n }\n\n // Overwrite duration-related variables (this needs to be called when 'beatType' or 'beats' is updated)\n function _updateDurationSettings() {\n durationPerMeasure = divisions * (4 / beatType) * beats;\n }\n\n // Check the duration of current measure, and create new measure if necessary\n // Also, add one empty measure with 'rest' if the initial note is NOT 'rest'\n function _createNewMeasureIfNecessary(duration, restFlag) {\n if (initialNoteFlag) {\n if (restFlag) { // if initial note is 'rest'\n cumSumDuration = 0; // reset cumSumDuration\n } else { // if initial note is sound (not 'rest'), add one empty measure\n curMeasureElm.appendChild(_createRestNote(durationPerMeasure));\n cumSumDuration = durationPerMeasure; // enforce to create measure=2 immediately after this\n }\n initialNoteFlag = false;\n }\n cumSumDuration += duration;\n if (cumSumDuration > durationPerMeasure) { // create new measure\n curMeasureElm = xml.createElement('measure');\n curMeasureElm.setAttribute('number', ++measureNumber); // increment number\n if (reservedElmForNextMeasure !== null) {\n curMeasureElm.appendChild(reservedElmForNextMeasure);\n console.log('append reserved tempo')\n reservedElmForNextMeasure = null;\n }\n xml.querySelector('part').appendChild(curMeasureElm); \n cumSumDuration = duration;\n } \n }\n\n // Find duration: variable or value\n function _extractDuration(arrayOrValue) {\n var duration = 0;\n if (Array.isArray(arrayOrValue) && arrayOrValue.length > 0 && arrayOrValue[0] === 'readVariable') { // variable\n duration = mapNoteDuration[arrayOrValue[1]];\n } else if (arrayOrValue > 0) { // value\n duration = arrayOrValue * divisions;\n }\n return duration; \n }\n\n _updateDurationSettings(); // update duration settings using default values\n \n for (var i=0; i < scriptArray.length; i++) { // for (var i in scriptArray) {\n if (i==0) continue; // skip\n // Tempo and beat settings\n if (scriptArray[i][0] === 'setTempoTo:') {\n tempo = scriptArray[i][1];\n console.log('tempo: ' + tempo);\n if (cumSumDuration == durationPerMeasure) {\n reservedElmForNextMeasure = _createTempo(tempo); // will add to the next measure\n } else {\n var soundElm = curMeasureElm.querySelector('sound');\n if (soundElm) {\n soundElm.setAttribute('tempo', tempo); // add or overwrite\n } else {\n curMeasureElm.appendChild(_createTempo(tempo)); // add immediately\n }\n console.log('add tempo immediately')\n }\n }\n if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beats') {\n beats = scriptArray[i][2];\n console.log('beats: ' + beats);\n xml.querySelector('beats').textContent = beats; // overwrite default beats\n _updateDurationSettings();\n }\n if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beat-type') {\n beatType = scriptArray[i][2];\n console.log('beat-type: ' + beatType);\n xml.querySelector('beat-type').textContent = beatType; // overwrite default beat-type\n _updateDurationSettings();\n }\n // Add sound note\n if (scriptArray[i][0] === 'noteOn:duration:elapsed:from:'){\n var duration = _extractDuration(scriptArray[i][2]);\n if (duration > 0) {\n if (scriptArray[i-1][0] === 'say:') { // if lyric exists\n try {\n var midiPitch = scriptArray[i][1];\n var step = chromaticStep[midiPitch % 12]; // chromatic step name ('C', etc.)\n var alter = chromaticAlter[midiPitch % 12]; // -1, 0, 1\n var octave = Math.floor(midiPitch / 12) - 1;\n var lyricText = scriptArray[i-1][1];\n if (lyricText.split('').slice(-1)[0] == '-') {\n lyricText = lyricText.replace(/-$/, ''); // remove the last char '-'\n if (syllabicState == 'single' || syllabicState == 'end') {\n syllabicState = 'begin';\n } else if (syllabicState == 'begin' || syllabicState == 'middle') {\n syllabicState = 'middle';\n }\n } else {\n if (syllabicState == 'single' || syllabicState == 'end') {\n syllabicState = 'single';\n } else if (syllabicState == 'begin' || syllabicState == 'middle') {\n syllabicState = 'end';\n }\n }\n console.log('midiPitch: ' + midiPitch + ', duration: ' + duration + ', ' + lyricText, ',' + syllabicState);\n \n // --- Append node ---\n var noteElm = _createSoundNote(step, alter, octave, duration, lyricText, syllabicState);\n _createNewMeasureIfNecessary(duration, false);\n curMeasureElm.appendChild(noteElm);\n } catch (e) {\n alert(e);\n }\n } else {\n console.log('No \"say\" block at i= ' + i);\n }\n } else {\n console.log('No variable at i= ' + i);\n }\n }\n // Add rest\n if (scriptArray[i][0] === 'rest:elapsed:from:') {\n var duration = _extractDuration(scriptArray[i][1]);\n if (duration > 0) {\n try {\n console.log('rest, duration: ' + duration);\n\n // --- Append node ---\n var noteElm = _createRestNote(duration);\n _createNewMeasureIfNecessary(duration, true);\n curMeasureElm.appendChild(noteElm);\n } catch (e) {\n alert(e);\n }\n } else {\n console.log('No variable at i= ' + i);\n }\n }\n }\n return xml;\n}", "constructor(networkText, weightsBuffer) {\n this._network = this._verifyAndParse(networkText);\n this._weights = weightsBuffer;\n\n const version = parseInt(this._network._graphs[0]._version);\n if (version < 5) {\n throw new Error(`IR version ${version} is not supported. ` +\n `Please convert the model using the latest OpenVINO model optimizer`);\n }\n\n this._bindHelperFunctions();\n }", "function parseGenVal(expr) {\n return _.chain(expr)\n .map(function(e){\n if (_.isString(e)) return e;\n if (_.isArray(e)) return parseGenExpr(e); // array but not fn call\n throw {expr: expr, e: e, msg: \"Cannot parse, only supports string/array here, got \" + (typeof e)};\n })\n .value();\n}", "parseSpropParameterSets(str) {\n let nalUnits = [];\n for (let base64String of Array.from(str.split(','))) {\n nalUnits.push(new Buffer(base64String, 'base64'));\n }\n return nalUnits;\n }", "function generateMadlibsWeight(p, products) {\n const lbs = convert(p.weight.data[0].val).from('oz').to('lb');\n const kg = Math.round(convert(p.weight.data[0].val).from('oz').to('kg') * 100) / 100;\n\n var clause = null;\n if (p.gender == 'male') {\n const weight = getStats(p, segmentByWeight(p.gender, products));\n clause = `making it the ${ordinal(weight.position)} lightest backpacking backpack for men in our database`;\n } else if (p.gender == 'female') {\n const weight = getStats(p, segmentByWeight(p.gender, products));\n clause = `making it the ${ordinal(weight.position)} lightest backpacking backpack for women in our database`;\n } else { // unisex\n const weightFemale= getStats(p, segmentByWeight('female', products));\n const weightMale = getStats(p, segmentByWeight('male', products));\n clause = `making it the ${ordinal(weightMale.position)} lightest backpacking backpack for men and the ${ordinal(weightFemale.position)} lightest backpack for women in our database`;\n }\n\n return `<p>See the weight breakdown for the ${p.name}.</p>\n <p>The ${p.name} weighs ${lbs} lbs (${kg} kg), ${clause}.</p>`;\n}", "constructor(input_size, w_min, w_max) {\n // initial optional weight min & max\n w_min = w_min === undefined ? -1 : w_min;\n w_max = w_max === undefined ? +1 : w_max;\n this.inputs = numeric.rep(0, input_size)\n this.weights = utils.create_random_array(input_size, w_min, w_max);\n this.w_grads = numeric.rep(0, input_size);\n this.i_grads = numeric.rep(0, input_size);\n }", "function fromGene(name) {\n }", "initializeWeights() {\n\t\t// Create weights for each node\n\t\tfor (let n = 0; n < this.numNodes; n++) {\n\t\t\tlet nodeWeights = [];\n\t\t\t// Each input gets a random weight\n\t\t\tfor (let i = 0; i < this.numInputs; i++) {\n\t\t\t\t// Add a random weight between -1 and 1\n\t\t\t\tnodeWeights.push(Math.random()*2 - 1);\n\t\t\t}\n\t\t\tthis.weights.push(nodeWeights);\n\t\t}\n\t}", "FormalParameterList() {\n const params = [];\n\n do {\n params.push(this.Identifier());\n } while (this._lookahead.type === \",\" && this._eat(\",\"));\n\n return params;\n }", "aggregation(inputs) {\n let weighted_i = numeric.mul(inputs, this.weights);\n return numeric.sum(weighted_i);\n }", "getAllGPsModels() {\n var encoded = encodeURIComponent(`\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> \n PREFIX owl: <http://www.w3.org/2002/07/owl#>\n PREFIX metago: <http://model.geneontology.org/>\n \n PREFIX enabled_by: <http://purl.obolibrary.org/obo/RO_0002333>\n PREFIX in_taxon: <http://purl.obolibrary.org/obo/RO_0002162>\n \n SELECT ?identifier\t(GROUP_CONCAT(distinct ?gocam;separator=\",\") as ?gocams)\n \n WHERE \n {\n \n GRAPH ?gocam {\n ?gocam metago:graphType metago:noctuaCam . \n ?s enabled_by: ?gpnode . \n ?gpnode rdf:type ?identifier .\n FILTER(?identifier != owl:NamedIndividual) . \n }\n \n }\n GROUP BY ?identifier \n `);\n return \"?query=\" + encoded;\n }", "function extPart_getWeight(partName, theNode)\n{\n //get the weight information\n var retVal = extPart.getLocation(partName);\n\n //if the insert weight is nodeAttribute, add the position of the matched string\n if (retVal == \"nodeAttribute\")\n {\n //get the node string\n var nodeStr = extUtils.convertNodeToString(theNode);\n\n var foundPos = extUtils.findPatternsInString(nodeStr, extPart.getQuickSearch(partName),\n extPart.getSearchPatterns(partName));\n\n if (foundPos)\n {\n retVal += \"+\" + foundPos[0] + \",\" + foundPos[1];\n }\n }\n\n return retVal;\n}", "function SqlParser(rdfSql, params) {\n\tthis.beginTag = ':=';\n\tthis.endTag = '=:';\n\tthis.rdfSql = rdfSql;\n\tthis.params = params;\n}", "function extUtils_getWeightNum(weight)\n{\n if (typeof weight == \"string\")\n {\n var pos = weight.indexOf(\"+\");\n weight = parseInt((pos > 0)? weight.substring(pos+1) : weight);\n }\n\n return weight;\n}", "function ParseOneWine(header, line)\n{\n // OK, let's parse this wine\n var fields = line.split(\"\\t\");\n var wine = {};\n\n // If there isn't at least two fields, we bail\n if (fields.length < 2)\n {\n return null;\n }\n\n // Now read each field and process as integer, string, or float\n // We want to remove the quotes that came from the server response\n myIntFields.forEach(field => {wine[field] = parseInt(fields[header[field]]);});\n myStringFields.forEach(field => {wine[field] = fields[header[field]];});\n myFloatFields.forEach(field => {wine[field] = parseFloat(fields[header[field]]);});\n return wine;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function that creates a new Genre in the database currently, the genre table has 3 entries: Action, Comedy, and Drama add one more Genre of your choice duplicate entries are not allowed (try it to learn about errors)
function insertNewGenre() { // Add code here }
[ "function createGenresTable() {\n client.query(`CREATE TABLE IF NOT EXISTS genres (\n genre_id SERIAL PRIMARY KEY,\n genre VARCHAR UNIQUE\n );`).then(function() {\n console.info('Created genres table');\n });\n }", "function deleteGenreYouAdded() {\n // Add code here\n}", "function validateGenre(genre) {\n const schema = {\n name: Joi.string().min(3).required()\n }\n return Joi.validate(genre,schema);\n}", "function AddMovie() {\n const classes = useStyles();\n const history = useHistory();\n const dispatch = useDispatch();\n const genres = useSelector(store => store.genres);\n\n // local states for form input handling\n const [newMovie, setNewMovie] = useState({\n title: '',\n poster: '',\n genre_id: '',\n description: ''\n });\n \n // On page load, fetch genres from DB\n useEffect(() => {\n dispatch({ type: 'FETCH_GENRES' });\n }, []);\n\n const handleCancelButton = () => {\n history.push('/');\n } // end handleCancelButton\n\n // Handles Submission Event\n const saveMovie = (event) => {\n event.preventDefault();\n // check for any blank inputs\n if (\n newMovie.title === '' || \n newMovie.poster === '' || \n newMovie.genre_id === '' || \n newMovie.description === ''\n ) { // if any are blank, sweetAlert will cancel the submission\n return swal({\n title: 'Seems you forgot something.',\n text: 'Please fill out each input before submission.'\n });\n } else {\n // to prevent early submission, sweetAlert asks:\n swal({\n title: \"Ready to Add?\",\n text: \"Do you want to look at your submission once more before completion?\",\n buttons: true,\n dangerMode: true,\n })\n .then((willAdd) => {\n // if the user hits okay button, dispatch data to saga\n if (willAdd) {\n // tell saga to add a movie with our current local state\n dispatch({\n type: 'ADD_MOVIE',\n payload: newMovie\n });\n\n swal({\n title: \"Your movie has been added!\",\n icon: \"success\",\n }) \n // on success send the user home\n .then(() => history.push('/'))\n .catch(() => {\n swal({\n title: \"It looks like something went wrong.\",\n text: \"Please wait a few minutes and try again.\",\n icon: \"warning\"\n })\n });\n } else { \n swal(\"Add a movie when you're ready.\");\n }\n });\n }\n } // end saveMovie\n\n return(\n <Grid container align=\"center\" justify=\"center\">\n\n {/* Page Title */}\n <Grid item xs={12}>\n <Typography className={classes.formTitle} variant=\"h2\">Add a Movie to the List!</Typography>\n </Grid>\n\n {/* Rendered Form Item w/ Buttons */}\n <Grid item>\n <Paper elevation={5} className={classes.addMoviePaper}>\n <Grid container>\n \n {/* Form */}\n <Grid item xs={12}>\n <form className={classes.addMovieForm} id=\"add-movie-form\">\n <Grid container spacing={2}>\n\n {/* Movie Title Input */}\n <Grid item xs={4}>\n <FormControl fullWidth>\n <TextField\n helperText=\"Input a title for the movie\"\n id=\"title-input\"\n margin=\"normal\"\n label=\"Title:\" \n variant=\"outlined\"\n value={newMovie.title} \n onChange={event => setNewMovie({...newMovie, title: event.target.value})}\n type=\"text\" \n placeholder=\"Title of Movie\" \n required\n />\n </FormControl>\n </Grid>\n\n {/* Movie Poster Input */}\n <Grid item xs={4}>\n <FormControl fullWidth> \n <TextField\n helperText=\"Input an image address for the movie poster.\"\n id=\"poster-input\"\n label=\"Poster:\"\n margin=\"normal\"\n variant=\"outlined\"\n value={newMovie.poster}\n onChange={event => setNewMovie({...newMovie, poster: event.target.value})}\n type=\"url\" \n placeholder=\"Image Address\" \n required\n />\n </FormControl>\n </Grid> \n\n {/* Movie Genre Selector */}\n <Grid item xs={4}>\n <FormControl fullWidth margin=\"normal\">\n {/* Material-UI doesn't accept label as attribute for Select */}\n <InputLabel margin=\"normal\" shrink id=\"genre-input-selector\">\n Genre:\n </InputLabel>\n\n <Select \n labelId=\"genre-input-selector\"\n value={newMovie.genre_id} \n onChange={event => setNewMovie({...newMovie, genre_id: event.target.value})}\n displayEmpty\n required\n >\n {/* This will be the first item displayed, validation does not allow it to be submitted */}\n <MenuItem value=\"\">\n <em>Choose a Genre</em>\n </MenuItem>\n\n {/* Renders our drop down from DB */}\n {genres.map(genre => <MenuItem key={genre.id} value={genre.id}>{genre.name}</MenuItem>)}\n\n </Select>\n <FormHelperText>Choose a genre for the movie.</FormHelperText>\n </FormControl>\n </Grid>\n\n {/* Description Input */}\n <Grid item xs={12}> \n <FormControl fullWidth color=\"secondary\">\n <TextField\n helperText=\"Input a brief movie synopsys.\"\n id=\"description-input\"\n margin=\"normal\" \n label=\"Description:\"\n value={newMovie.description}\n onChange={event => setNewMovie({...newMovie, description: event.target.value})}\n placeholder=\"Movie Description\" \n multiline\n rows={4}\n required\n variant=\"outlined\"\n />\n </FormControl>\n </Grid>\n\n </Grid>\n </form> \n </Grid>\n\n {/* Contains Cancel and Save Button */}\n <Grid item xs={12}>\n <ButtonGroup size=\"large\" variant=\"contained\">\n\n {/* Cancel Button */}\n <Button \n color=\"secondary\" \n form=\"add-movie-form\" \n onClick={handleCancelButton}\n >\n Cancel\n </Button>\n \n {/* Save Button */}\n <Button color=\"primary\" onClick={saveMovie}>Save</Button>\n\n </ButtonGroup>\n </Grid>\n\n </Grid>\n </Paper>\n </Grid>\n\n </Grid>\n );\n} // end AddMovie", "function createMusic (data, cb) {\n connection.query(\n 'INSERT INTO `inventory` SET type=?;INSERT INTO `musics` SET ?, id=LAST_INSERT_ID()', ['music', data],\n (err, result) => {\n if (err) {\n cb(err);\n return;\n }\n readMusic(result[0].insertId, cb);\n });\n}", "function createApgarEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO apgar (patient, appearance1, pulse1, grimace1, activity1, respirations1, total1, time1, ' +\r\n\t\t\t\t' appearance5, pulse5, grimace5, activity5, respirations5, total5, time5)' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), '0', '0', '0', '0', '0', '0', '', '0', '0', '0', '0', '0', '0', ''],\r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}", "function createMagazine (data, cb) {\n connection.query(\n 'INSERT INTO `inventory` SET type=?;INSERT INTO `magazines` SET ?, id=LAST_INSERT_ID()', ['magazine', data],\n (err, result) => {\n if (err) {\n cb(err);\n return;\n }\n readMagazine(result[0].insertId, cb);\n });\n}", "function createMuscularEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO muscular_skeletal (patient, assessed, nocomplaint, muscular)' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', true, ''], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}", "function createGift(giftName, rating) {\n $.post(\"/api/addpresent\", {\n giftName: giftName,\n rating: rating\n })\n .then(function () {\n location.reload();\n // window.location.replace(\"/user/retrieve\");\n // If there's an error, log the error\n })\n\n }", "function guardarOrden() {\n let cliente = $('#cliente').val();\n let descripcion = $('#descripcion').val();\n let fechaRecep = moment().format('DD/MM/YYYY');\n let fechaEntrega = $('#fechaEntrega').val();\n let estado = \"Pendiente\";\n let encargado = $('#encargado').val();\n\n let ordenes = firebase.database().ref('ordenes/');\n let Orden = {\n cliente: cliente,\n descripcion: descripcion,\n fechaRecep: fechaRecep,\n fechaEntrega: fechaEntrega,\n estado: estado,\n encargado: encargado\n }\n\n ordenes.push().set(Orden); //inserta en firebase asignando un id autogenerado por la plataforma\n $('#agregarOrden').modal('hide');\n}", "create(cols, value, callBack) {\n orm.insertOne(\"burgers\", cols, value, res => {\n callBack(res);\n });\n }", "function create(name, year) {\n return MovieModel.create({\n public_id: randomString({ length: 12 }),\n name: name,\n year: year\n });\n}", "function writeGenreRow(genre) {\n\t$(\"#genre-table>tbody\").append(\n\t\t \"<tr>\"\n\t\t+ \"<td><a href=\\\"javascript:getDirectChildren(\\'\"\n\t\t+ jsEscape(genre.ID)\n\t\t+ \"\\', onGetGenreArtists)\\\">\"\n\t\t+ genre.Title +\n\t\t\"</a></td>\"\n\t\t+ \"</tr>\");\n}", "function apiNew(req, res) {\n //console.log('POST /api/breed');\n // create a new breed in the db\n //console.log(req.body);\n if (!req.body.name) {\n res.status(503).send('cannot add a new breed without a name');\n } else if (!req.body.description) {\n res.status(503).send('cannot add a new breed without a description');\n } else if (!req.body.infoSources) {\n res.status(503).send('cannot add a new breed without any info sources');\n } else {\n //console.log('r.b.i: ' + req.body.infoSources);\n let infoList = req.body.infoSources.split(', ');\n //console.log('infoList: ' + infoList);\n //console.log('infoList.length: ' + infoList.length);\n let sheep = new db.Breed({\n name: req.body.name,\n origin: req.body.origin || '',\n status: req.body.status || '',\n stapleLength: req.body.stapleLength || '',\n fleeceWeight: req.body.fleeceWeight || '',\n fiberDiameter: req.body.fiberDiameter || '',\n description: req.body.description,\n image: req.body.image || 'n/a',\n infoSources: [],\n notes: req.body.notes || ''\n });\n\n //console.log(sheep.infoSources);\n for (let i = 0; i < infoList.length; i++) {\n sheep.infoSources.push(infoList[i]);\n }\n\n //console.log(sheep);\n db.Breed.create(sheep, function(err, sheepie) {\n if (err) {\n res.status(503).send('could not add new sheep breed. sorry.');\n } else {\n res.json(sheepie);\n }\n });\n }\n\n}", "function create(band_id, tour_date, venue_id) {\n return db.one(`INSERT INTO tours (band_id, tour_date, venue_id) VALUES ($1,$2,$3) RETURNING *`, [band_id, tour_date, venue_id]);\n}", "function createCourse(name)\r\n{\r\n //Determine the unique ID for the new course\r\n var maxID = 0;\r\n for(course in courses)\r\n {\r\n if(maxID < courses[course].id)\r\n maxID = courses[course].id;\r\n }\r\n //Create the course and add it to the database\r\n var newCourse = new Course(maxID + 1, name, false);\r\n courses.push(newCourse);\r\n}", "function create(req, res) {\n const { data: { name, description, price, image_url } = {} } = req.body\n // dish object for making an update request.\n const newDish = {\n id: nextId(),\n name, \n description,\n price, \n image_url,\n }\n //push new dish onto array of all other dishes\n dishes.push(newDish)\n //send an okay status and the new dish object.\n res.status(201).json({ data: newDish })\n}", "function createItem(url, name = \"\", note = \"\", price = 0, callback = () => {}) {\n chrome.storage.sync.get(['firebase-auth-uid'], function(result){\n var uid = result['firebase-auth-uid'];\n var wishlistRef = database.ref(\"users/\" + uid + \"/wishlist\");\n var itemsRef = database.ref(\"items/\");\n var newItemRef = itemsRef.push({\n gifter : false,\n name : name,\n note : note,\n price : price,\n requester : uid,\n url : url,\n });\n wishlistRef.child(newItemRef.key).set(true).then(function() {\n callback();\n });\n });\n}", "function findRandomGenres(artist){\r\n\tif(artist.genres.length > 1){\r\n\t\tvar random1 = Math.floor(Math.random() * artist.genres.length);\r\n\t\tvar random2 = Math.floor(Math.random() * artist.genres.length);\r\n\t\twhile (random1 == random2){\r\n\t\t\trandom2 = Math.floor(Math.random() * artist.genres.length);\r\n\t\t}\r\n\t\tvar returnData = {randomGenre1 : artist.genres[random1], randomGenre2 : artist.genres[random2]};\r\n\t\t//check to see if these genres contain the word \"christmas\", if so remove it\r\n\t\tif(returnData.randomGenre1.indexOf(\"christmas\") > -1){\r\n\t\t\treturnData.randomGenre1 = returnData.randomGenre1.replace(\"christmas\",\"\");\r\n\t\t}\r\n\t\tif(returnData.randomGenre2.indexOf(\"christmas\") > -1){\r\n\t\t\treturnData.randomGenre2 = returnData.randomGenre2.replace(\"christmas\",\"\");\r\n\t\t}\r\n\t\treturn returnData;\r\n\t}\r\n\telse if(artist.genres.length == 1){\r\n\t\treturn {randomGenre1 : artist.genres[0], randomGenre2 : null}\r\n\t}\r\n\telse{\r\n\t\treturn {randomGenre1 : null, randomGenre2 : null}\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================================================= / Q6 ============================================================================= / Create a ReadingList class by using OOP concept, where: Your class should has: "read" for the number of books that finish reading (number) "unRead" for the number of books that still not read (array of books not read) "toRead" array for the books names that want to read in the future (array of books that we want to read) "currentRead" for the name of the book that is reading currently (string of one book that we are reading) "readBooks" Array of the names of books that finish read (after we read a book we add it the array of the we read) "AddBook" function that: a Accept the book name as parameter (it just take a book as param??) b Add the new book to "toRead" array (.push()) c Increment the number of the unread books. "finishCurrentBook" function that: a Add the "currentRead" to the "readBooks" array b Increment the "read" books c Change the "currentRead" to be the first book from "toRead" array d Decrement the number of "unread" books Now, to make sure that you are actually reading, make a comment below this and type: Yes I am Yez I am Write your code here .....
function ReadingList(){ var read = 0, unRead = 0, toRead = [], currentBook, readBooks = []; return{ read : read, unRead : unRead, toRead : toRead, currentBook : currentBook, readBooks : readBooks, addBook : addBook, finishCurrentBook : finishCurrentBook } }
[ "function ReadingList()\n{\n\n var book={};\n\n book.read = 0;\n book.unread = 0;\n book.toRead = [];\n book.currentRead = undefined;\n book.readBooks = [];\n book.addBook = addBook;\n book.finishCurrentBook = finishCurrentBook;\n return book;\n }", "function changeReadStatus(bookTitle, newValue) {\n\tfor (var book in myLibrary) {\n\t\tif (myLibrary[book].title === bookTitle) {\n\t\t\tmyLibrary[book].read = newValue;\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function readButton(li, book) {\n let button = document.createElement('button');\n button.setAttribute('id', 'read-' + book.title);\n button.textContent = 'Read/Unread'\n button.addEventListener('click', (e) => {\n book.toggleRead();\n appendBooks(library);\n })\n li.appendChild(button);\n}", "function bacaBooks(waktu, books, indeks = 0) {\n if (indeks < books.length) {\n readBooks(waktu, books[indeks], function (sisa) {\n if (sisa > 0) {\n bacaBooks(sisa, books, indeks + 1);\n }\n });\n } else {\n console.log(\"buku habis\");\n }\n}", "function readbook(book) {\n var lev = book.arg;\n var i, tmp;\n if (lev <= 3)\n i = rund((tmp = splev[lev]) ? tmp : 1);\n else\n i = rnd((tmp = splev[lev] - 9) ? tmp : 1) + 9;\n learnSpell(spelcode[i]);\n updateLog(`Spell \\'<b>${spelcode[i]}</b>\\': ${spelname[i]}`);\n updateLog(` ${speldescript[i]}`);\n if (rnd(10) == 4) {\n updateLog(` Your intelligence went up by one!`);\n player.setIntelligence(player.INTELLIGENCE + 1);\n }\n}", "function renderBooks(books) {\n books.forEach(book => {\n listOfBooks.innerHTML += appendBookTitles(book)\n })\n //3.click on a book and be able to see thumbnail, and desc and list of users who liked book\n let listContainer = document.querySelector('#list-panel')\n listContainer.addEventListener('click', (event) => {\n if (event.target.tagName === \"LI\") {\n }\n })\n}", "function Book(title,author,isbn){\n this.title=title;\n this.author=author;\n this.isbn=isbn;\n}", "function getBooksPossessedByAccount(account, books, authors) {\n let resultsArray = [];\n\n //Loop through books array\n for (let i = 0; i < books.length; i++) {\n let author = authors.find((author) => author.id === books[i].authorId);\n let borrowArrayItem = books[i].borrows[0];\n\n //If the first item in the borrows array shows the given borrower has checked the book out\n //then put the book object (with the author object inside) in resultsArray\n if (\n borrowArrayItem.id === account.id &&\n borrowArrayItem.returned === false\n ) {\n let newObject = books[i];\n newObject.author = author;\n resultsArray.push(newObject);\n }\n }\n\n return resultsArray;\n}", "function getReadings(token) {\n\t\tvar readingsURL = \"https://api.readmill.com/v2/users/\"+userObj.id+\"/readings?states=reading,finished,abandoned&access_token=\"+token;\n\t\t$.getJSON( 'functions.php', { url: readingsURL, apiRequest: true, clientId: true }, function(data) {\n\t\t\t\treadingsObj = data.requestedObj.items;\n\t\t\t\t\n\t\t\t\t// get length of reading Object\n\t\t\t\tvar objLength = readingsObj.length;\n\t\t\t\t\n\t\t\t\t// setup an array of book objects with book id, title, and total reading time\n\t\t\t\t// loop through object of readings and create a custom object for use later\n\t\t\t\tfor(i=0; i<objLength; ++i) {\n\t\t\t\t\tif(readingsObj[i].reading.duration > 3600) {\n\t\t\t\t\t\tthisBook = new Object();\n\t\t\t\t\t\tthisBook.readingId = readingsObj[i].reading.id;\n\t\t\t\t\t\tthisBook.bookId = readingsObj[i].reading.book.id;\n\t\t\t\t\t\tthisBook.title = readingsObj[i].reading.book.title;\n\t\t\t\t\t\tthisBook.author = readingsObj[i].reading.book.author;\n\t\t\t\t\t\tthisBook.duration = readingsObj[i].reading.duration;\n\t\t\t\t\t\tbookArray.push(thisBook);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// create data set for pie graph based off bookArray\n\t\t\t\tpieData = setupPieData(bookArray);\n\t\t\t\t\n\t\t\t\tcreatePie('overviewPie', pieData);\n\t\t\t}\n\t\t);\n\t}", "function createBookListItem(book) {\n var $li = $(\"<li>\");\n $li.addClass(\"list-group-item hover-invert cursor-pointer list-bg-color list-item-font\");\n $li.html(book.id + \") \" + book.title + \" by \" + book.author);\n $li.data(\"bookId\", book.id);\n return $li;\n }", "function parseRecommendedBooks(bookList) {\n\n let randomBookIndex = Math.floor(Math.random() * bookList.length);\n let randomBook = bookList[randomBookIndex];\n $.ajax({\n method: \"GET\",\n url: API_URL + randomBook.key + API_OUTPUT_FORMAT,\n success: function(bookInfo) {\n $('#title').val(bookInfo.title); \n $('#author').val(randomBook.authors[0].name);\n $('#genre').val(randomBook.subject[0]);\n if(bookInfo.hasOwnProperty('description') && bookInfo.description.hasOwnProperty('value') && bookInfo.description.value != \"\") {\n $('#pieceInput').val(bookInfo.description.value); \n } else {\n $('#pieceInput').val(NO_BOOK_DESCRIPTION); \n }\n }\n })\n }", "constructor(isbn, size = 'S', key = 'isbn') {\n this.isbn = isbn;\n this.key = key.toUpperCase() + \":\"; //This sets the key variable to uppercase. This is to create the correct web address\n this.bc = new bookCover(isbn, size, key); //This uses the current details to create a new book class, which included the ISBN, size and key\n /* visit https://openlibrary.org/dev/docs/api/books */\n this.url_a = 'https://openlibrary.org/api/books?bibkeys='; //First part of the web address - part A\n this.url_b = '&format=json&jscmd=data'; //last part of the web address - Part B\n /* 'https://openlibrary.org/api/books?bibkeys=ISBN:0201558025&format=json' */\n this.detail = \"\";\n\n \n }", "function haveIRead () {\n //console.log('haveIRead ran');\n if(haveRead === false){\n haveRead = true;\n truRead.classList.add('clicked-button');\n //console.log(haveRead);\n } else if (haveRead === true) {\n haveRead = false;\n truRead.classList.remove('clicked-button');\n //console.log(haveRead);\n } else {\n console.log('Something messed up at the haveIRead function');\n }\n }", "async function updateBooks(indexOfBook, bookWithUpdatedData) {\r\n // copy of current state\r\n const booksState = [...books];\r\n\r\n // update it with new data\r\n booksState[indexOfBook] = bookWithUpdatedData;\r\n console.log(booksState);\r\n\r\n // 4\r\n // update our main state with this new updated booksState\r\n setBooks(booksState);\r\n // wait for 1s then redirect user to the bookSingle page where they can see their updates:\r\n await wait(1000);\r\n // and single page need to know it's coming from update page so set location state to current path when you push it.\r\n history.push({\r\n pathname: `/book/${bookId}`,\r\n state: {\r\n from: location.pathname,\r\n },\r\n });\r\n }", "function generateBooks(model, numberOfBooks){\n \tvar sampleLength = model.length;\n \t// a while-- would be possibly quicker\n \tfor(var i = sampleLength, max = numberOfBooks;i<=max;i++){\n \t\tmodel.push({\n \t\t\tid: i + 1,\n \t\t\tname: model[Math.floor(Math.random() * sampleLength)].name,\n \t\t\tauthor: model[Math.floor(Math.random() * sampleLength)].author,\n \t\t\tgenre: model[Math.floor(Math.random() * sampleLength)].genre,\n \t\t\tpublish_date: model[Math.floor(Math.random() * sampleLength)].publish_date\n \t\t});\n \t}\n \treturn model;\n }", "function getAllBooks() {\n return books;\n}", "function bookFormat(book) {\n if (book['read'] == false) {\n return book['title'] + \" by \" + book['author']\n + \", \" + book['pages'] + \" pages, not read yet\";\n }\n else {\n return book['title'] + \" by \" + book['author'] \n + \", \" + book['pages'] + \" pages, read\";\n }\n}", "function playbooks (book) {\n\tif (book == \"The Beacon\") {\n\t\tdangerMod = -1;\n\t\tfreakMod = -1;\n\t\tsaviorMod = 2;\n\t\tsuperiorMod = 0;\n\t\tmundaneMod = 2;\n\t} else if (book === \"The Bull\") {\n\t\tdangerMod = 2;\n\t\tfreakMod = 1;\n\t\tsaviorMod= -1;\n\t\tsuperiorMod = 1;\n\t\tmundaneMod = -1;\n\t} else if (book === \"The Delinquent\") {\n\t\tdangerMod = 0;\n\t\tfreakMod = 0;\n\t\tsaviorMod = -1;\n\t\tsuperiorMod = 2;\n\t\tmundaneMod = 1;\n\t} else if (book === \"The Doomed\") {\n\t\tdangerMod = 1;\n\t\tfreakMod = 1;\n\t\tsaviorMod = 1;\n\t\tsuperiorMod = -1;\n\t\tmundaneMod = 0;\n\t} else if (book === \"The Janus\") {\n\t\tdangerMod = 0;\n\t\tfreakMod = -1;\n\t\tsaviorMod = 0;\n\t\tsuperiorMod = 0;\n\t\tmundaneMod = 3;\n\t} else if (book === \"The Legacy\") {\n\t\tdangerMod = -1;\n\t\tfreakMod = 0;\n\t\tsaviorMod = 2;\n\t\tsuperiorMod = 0;\n\t\tmundaneMod = 1;\n\t} else if (book === \"The Nova\") {\n\t\tdangerMod = 1;\n\t\tfreakMod = 2;\n\t\tsaviorMod = 0;\n\t\tsuperiorMod = 0;\n\t\tmundaneMod = -1;\n\t} else if (book === \"The Outsider\") {\n\t\tdangerMod = -1;\n\t\tfreakMod = 1;\n\t\tsaviorMod = 0;\n\t\tsuperiorMod = 2;\n\t\tmundaneMod = 0;\n\t} else if (book === \"The Protege\") {\n\t\tdangerMod = -1;\n\t\tfreakMod = 0;\n\t\tsaviorMod = 1;\n\t\tsuperiorMod = 2;\n\t\tmundaneMod = 0;\n\t} else if (book === \"The Transformed\") {\n\t\tdangerMod = 1;\n\t\tfreakMod = 3;\n\t\tsaviorMod = 0;\n\t\tsuperiorMod = -1;\n\t\tmundaneMod = -1;\n\t} \n}", "function retrievedBooks (account, books) {\n let id = account.id\n let allBooksCheckedOut = [];\n for (let i = 0; i < books.length; i ++) {\n if (books[i].borrows[0].returned === false && books[i].borrows[0].id === id) {\n allBooksCheckedOut.push(books[i])\n }\n }\n return allBooksCheckedOut\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create mix guess list copy of original ordered list, but shuffled
shuffleGuessList() { this.mixedGuessList = super.shuffle(this.guessList.slice()); }
[ "function shuffle(list, length) {\n var i, rnd, temp;\n for (i = 0; i < length; i += 1) {\n rnd = i + Math.floor((Math.random() * (length - i)));\n temp = list[i];\n list[i] = list[rnd];\n list[rnd] = temp;\n }\n}", "shuffleElements() { \n this.deck.shuffle();\n }", "function shuffle(){\n\t\n\t\tif(position == 0){ \n\t\t\treturn;\n\t\t}\n\t\t\n\t\tgame.removeAttribute('category'); //Remove the class attribute from the puzzle\n\t\tposition = 0;\n\t\t\n\t\tvar prevBox;\n\t\tvar i = 1;\n\t\tvar stop = setInterval(function(){\n\t\t\tif(i <= 100){\n\t\t\t\tvar next = findNextBoxs(findEmptyBox());\n\t\t\t\tif(prevBox){\n\t\t\t\t\tfor(var j = next.length-1; j >= 0; j--){\n\t\t\t\t\t\tif(next[j].innerHTML == prevBox.innerHTML){\n\t\t\t\t\t\t\tnext.splice(j, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*gets random next box and saves the box for the next loop*/\n\t\t\t\tprevBox = next[random(0, next.length-1)]; //gets random next box\n\t\t\t\tmoveBox(prevBox); //saves position for the next loop\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tclearInterval(stop);\n\t\t\t\tposition = 1;\n\t\t\t}\n\t\t}, 5);\n\t\t\n\t}", "shuffleSpells() {\n this.spellDeck.shuffle();\n }", "shuffle() {\n \n for (let i = 0; i < this._individuals.length; i++) {\n let index = getRandomInt( i + 1 );\n let a = this._individuals[index];\n this._individuals[index] = this._individuals[i];\n this._individuals[i] = a;\n }\n }", "_shuffle() {\n\tif (!this.currentQuestion) throw \"No questions to shuffle.\";\n\tthis.orderChoices = [\n\t this.currentQuestion.correctAnswer,\n\t this.currentQuestion.wrongAnswer\n\t];\n\tif (Math.floor(Math.random() * 2) == 0) {\n\t this.orderChoices.reverse();\n\t}\n }", "function shuffleArray(){\n\tfor(i=0;i<questions.length;i++){\n\t\tvar j = Math.floor(Math.random()*questions.length);\n\t\tvar temp = questions[i];\n\t\tquestions[i] = questions[j];\n\t\tquestions[j] = temp;\n\t}\n}", "function shuffleCards(array){\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tlet randomIndex = Math.floor(Math.random()*array.length);\r\n\t\tlet temp = array[i];\r\n\t\tarray[i] = array[randomIndex];\r\n\t\tarray[randomIndex] = temp;\r\n\t}\r\n}", "static shuffle3(key, src) {\n let ret = [];\n\n let first = key % 3;\n ret.push(src[first]);\n src.splice(first, 1);\n\n let second = key % 2;\n ret.push(src[second]);\n src.splice(second, 1);\n\n ret.push(src[0]);\n return ret;\n }", "function getJurors(jurorList) {\n const shuffleList = jurorList;\n const displaySize = 4; // number of jurors to display\n\n /* randomize list */\n for (let i = jurorList.length - 1; i > 0; i -= 1) {\n const j = Math.floor(Math.random() * (i + 1));\n const temp = jurorList[i];\n shuffleList[i] = shuffleList[j];\n shuffleList[j] = temp;\n }\n\n /* remove extra elements */\n const spliceStart = displaySize - 1;\n const spliceNumber = jurorList.length - displaySize;\n shuffleList.splice(spliceStart, spliceNumber);\n return shuffleList;\n}", "function shuffleCards() {\n for (var j = 0; j < cards.length; j++) {\n cards[j].classList.remove('open', 'show', 'match')\n };\n\n allCards = shuffle(allCards)\n for (var i = 0; i < allCards.length; i++) {\n deck.innerHTML = ''\n for (const e of allCards) {\n deck.appendChild(e)\n }\n }\n}", "function scramble(graph) {\n if (graph.nodes.length < 4) return graph;\n do {\n graph.nodes.forEach (function (node) {\n node[0] = Math.random ();\n node[1] = Math.random ();\n });\n } while (!intersections (graph.links));\n return graph;\n }", "function pickCards(array) {\n let startArr = array;\n let pickedArr = [];\n for (let i = 0; i < 8; i++) {\n let ranNum = (Math.floor(Math.random() * startArr.length));\n pickedArr.push(startArr[ranNum]);\n pickedArr.push(startArr[ranNum]);\n startArr.splice(ranNum, 1);\n }\n return pickedArr;\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 }", "function shuffle_filler_quest(shuffled_indices) {\n q_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n q_list = _.concat(q_list, filler_question[index])\n }\n return q_list;\n}", "function shuffleAnswers(answers) {\n var shuffledAnswers = [];\n var correctAnswerShuffled = 0;\n for(var i = 0 ; i < 4 ; i++)\n {\n var shuffleSpot = getRandomInt(0,answers.length-1);\n if(correctAnswerShuffled == 0 && shuffleSpot == 0)\n {\n multipleChoiceCorrectAnswer=i; \n correctAnswerShuffled=1;\n }\n shuffledAnswers.push( answers.splice(shuffleSpot , 1).toString() ); \n }\n return shuffledAnswers;\n}", "function shuffle() {\n var parent = document.querySelector(\"#container\");\n for (var i = 0; i < parent.children.length; i++) {\n parent.appendChild(parent.children[Math.random() * i | 0]);\n }\n}", "function shuffle_quotes() {\n if (so_far.length < 2) {\n return true;\n }\n erase();\n for (var i = so_far.length - 1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n var temp = so_far[i];\n so_far[i] = so_far[j];\n so_far[j] = temp;\n }\n for (i=0; i< so_far.length; i++) {\n \n add_sth(so_far[i]);\n }\n \n}", "function shuffleAction() {\n const shuffledList = cards.slice().sort(() => Math.random() - 0.5);\n return createCard(shuffledList);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if the prop paramter holds a string, then return the value of the style property that corresponds with the string
function _getstylevalue(el) { if(typeof prop == "string"){ var styleValue; var computedStyle = window.getComputedStyle(el).getPropertyValue(prop); var stylePropValue = el.style[prop]; if (typeof stylePropValue == "undefined" || stylePropValue == ""){ styleValue = computedStyle; } else { styleValue = stylePropValue; } styleValues.push(styleValue); } else { if (debugging) { Logs$1.warn("The prop parameter is required and must be a string"); } } }
[ "function css(ele,style_obj){\n if(ele === null || style_obj === null){\n return \"\";\n }\n\n if(typeof style_obj === \"string\"){\n return ele.style.style_obj;\n }\n}", "getStyleByName(name){\n\t\treturn this.styles[this.findIndexByName(name)];\n\t}", "function intCss(elem, prop) {\r\n return parseInt(vendorCss(elem, prop), 10);\r\n}", "function createStyleProperty(el) {\n\t\tvar style = el.style;\n\t\tvar output = {};\n\t\tfor (var i = 0; i < style.length; ++i) {\n\t\t\tvar item = style.item(i);\n\t\t\toutput[item] = String(style[item]);\n\t\t\t// hack to workaround browser inconsistency with url()\n\t\t\tif (output[item].indexOf('url') > -1) {\n\t\t\t\toutput[item] = output[item].replace(/\\\"/g, '')\n\t\t\t}\n\t\t}\n\t\treturn { name: 'style', value: output };\n\t}", "getStyleByID(styleID){\n\t\treturn this.styles[this.findIndexByID(styleID)];\n\t}", "function getStyleAttribute(style, attr) {\n\tvar N = document.styleSheets.length;\n\tvar styles = document.styleSheets;\n\tvar value;\n\tfor(var i = 0; i < N; i++)\n\t{\n\t\tif(styles[i].rules[0].selectorText == style)\n\t\tvalue = styles[i].rules[0].style[attr];\n\t}\n\treturn value;\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 }", "cramp() {\n return styles[cramp[this.id]];\n }", "function editProperty(ruleStr,styleSheet,property,value,ruleRepeatCount)\r\n{\r\n\tvar rule = findRule(ruleStr,styleSheet.cssRules,ruleRepeatCount);\r\n var execStr = \"rule.style.\"+property+\"=\"+value;\r\n\trule.style[property] = value;\r\n}", "text() {\n return styles[text[this.id]];\n }", "havingStyle(style) {\n if (this.style === style) {\n return this;\n } else {\n return this.extend({\n style: style,\n size: sizeAtStyle(this.textSize, style)\n });\n }\n }", "function addStyleString(style, source) {\n\t\t// We don't use `style.cssText` because browsers must block it when no `unsafe-eval` CSP is presented: https://csplite.com/csp145/#w3c_note\n\t\t// Even though the browsers ignore this standard, we don't use `cssText` just in case.\n\t\tfor (const property of source.split(';')) {\n\t\t\tconst match = /^\\s*([\\w-]+)\\s*:\\s*(.+?)(\\s*!([\\w-]+))?\\s*$/.exec(\n\t\t\t\tproperty,\n\t\t\t)\n\t\t\tif (match) {\n\t\t\t\tconst [, name, value, , priority] = match\n\t\t\t\tstyle.setProperty(name, value, priority || '') // The last argument can't be undefined in IE11\n\t\t\t}\n\t\t}\n\t}", "_setCss(propertyName) {\n if (isPresent(get(this, propertyName))) {\n this.element.style[propertyName] = get(this, propertyName);\n }\n }", "function getStyleRef(id) {\n // Checks for DOM strategy.\n if (document.getElementById) {\n // W3C\n return document.getElementById(id).style;\n } else if (document.all) {\n // IE\n return document.all[id].style;\n } else if (document.layers) {\n // NS\n return document.layers[id];\n }\n}", "sub() {\n return styles[sub[this.id]];\n }", "sup() {\n return styles[sup[this.id]];\n }", "function getStyle (pageName)\n{\n\tvar style = doAction ('DATA_GETCONFIGDATA', 'ObjectName', gSITE_ED_FILE, 'RowName', \n\t\t\t\t\t\t\t\t\tpageName, 'ColName', gSTYLE);\n\treturn (style);\n}", "function findStyleAttributeIndex(attributeType, styleArray) {\n return styleArray.findIndex(s => s.attribute == attributeType);\n}", "function select_style() {\n\tvar elem = document.getElementById(\"style_selection\");\n\tvar style = elem.value;\n\tset_style(style);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description Add dependency as edges to graph Input g / DirectedGraph Output none Exception Conflict Duplicated dependency
_add_service_graph_edges(g) { for (let type of this._types) { for (let neighbour of type.dependency) { try { g.add_edge(neighbour, type) } catch (e) { if (e instanceof error.Conflict && e.message === 'Edge is already existed' ) { let new_err = new error.Conflict('Duplicated dependency') new_err.dependency = [type, neighbour] throw new_err } throw e } } } }
[ "function addEdge() {\n \n //source input box\n twoNodesinp1 = createInput('');\n twoNodesinp1.input(myInputEvent);\n twoNodesinp1.position(800,50);\n twoNodesinp1.size(80,40);\n twoNodesinp1.changed(connectingText1);\n\n //var s = twoNodesinp1.value();\n\n //target input box\n twoNodesinp2 = createInput('');\n twoNodesinp2.input(myInputEvent);\n twoNodesinp2.position(900,50);\n twoNodesinp2.size(80,40);\n twoNodesinp2.changed(connectingText2);\n\n //var t = twoNodesinp2.value();\n\n //make JSON and store to edges list\n //var edge = createEdgeJSON(s,t);\n //edges.push(edge);\n\n\n}", "addEdge(edge) {\n\t // is this edge connected to us at all?\n\t var nodes = edge.getNodes();\n\t if (nodes.a !== this && nodes.b !== this) {\n\t throw new Error(\"Cannot add edge that does not connect to this node\");\n\t }\n\t var edge_id = edge.getID();\n\t // Is it an undirected or directed edge?\n\t if (edge.isDirected()) {\n\t // is it outgoing or incoming?\n\t if (nodes.a === this && !this._out_edges[edge_id]) {\n\t this._out_edges[edge_id] = edge;\n\t this._out_degree += 1;\n\t // Is the edge also connecting to ourselves -> loop ?\n\t if (nodes.b === this && !this._in_edges[edge_id]) {\n\t this._in_edges[edge.getID()] = edge;\n\t this._in_degree += 1;\n\t }\n\t }\n\t else if (!this._in_edges[edge_id]) { // nodes.b === this\n\t this._in_edges[edge.getID()] = edge;\n\t this._in_degree += 1;\n\t }\n\t }\n\t else {\n\t // Is the edge also connecting to ourselves -> loop\n\t if (this._und_edges[edge.getID()]) {\n\t throw new Error(\"Cannot add same undirected edge multiple times.\");\n\t }\n\t this._und_edges[edge.getID()] = edge;\n\t this._und_degree += 1;\n\t }\n\t }", "_build_service_type_graph() {\n this._service_graph = new DirectedGraph()\n\n this._add_service_graph_vertexes(this._service_graph)\n this._add_service_graph_edges(this._service_graph)\n\n let cycles = find_cycles(this._service_graph)\n if (cycles.size > 0) {\n let err = new error.InfiniteLoop('There is cycle dependency between services')\n err.cycles = cycles\n throw err\n }\n }", "_add_service_graph_vertexes(g) {\n for (let type of this._types) {\n try {\n g.add_vertex(type)\n } catch (e) {\n if (e instanceof error.Conflict\n && e.message === 'Vertex is already existed'\n ) {\n let new_err = new error.Conflict('Duplicated service')\n new_err.service_type = type\n throw new_err\n }\n throw e\n }\n }\n }", "_addLink(r1, r2) {\n this.elements.push({\n group: \"edges\",\n data: {\n id: `${r1.id}_${r2.id}`,\n source: r1.id,\n target: r2.id\n } \n })\n }", "function generateEdges (packageName, node) {\n const nameVersion = `${packageName}@${node.version}`\n\n // draw edges from this node to it's deps\n const deps = node.dependencies || {}\n for (let depName in deps) {\n const depNameVersion = `${depName}@${deps[depName].version}`\n out.push(` \"${nameVersion}\" -> \"${depNameVersion}\"`)\n }\n\n // recurse\n for (let depName in deps) {\n generateEdges(depName, deps[depName])\n }\n }", "relDependencyChanged(component, rel) {\n // check if a dependency has been selected\n if (rel.Dependency == \"\") {\n rel.Version = \"\"\n } else {\n // add version to relationship\n rel.Version = \"\"\n for (var c of this.model.Catalog) {\n if (c.Component == component) {\n for (var d in c.Dependencies) {\n if (d == rel.Dependency) {\n rel.Type = c.Dependencies[d].Type\n rel.Version = c.Dependencies[d].Version\n break\n }\n }\n // dependency has already been found\n if (rel.Version != \"\") {\n break\n }\n }\n }\n }\n\n // update GUI\n this.$forceUpdate()\n }", "constructor() {\n // map module.id -> [outgoing connections]\n this.outEdges = {};\n\n // map module.id -> [incoming connections]\n this.inEdges = {};\n\n // map module.id -> module\n this.modules = {};\n\n this.allEdges = [];\n }", "function getDependencyListForGraph(graph) {\n // We need to do this because if A dependecy on bundled B\n // And A has a secondary entry point A/1 we want only to bundle B if it's used.\n // Also if A/1 depends on A we don't want to bundle A thus we mark this a dependency.\n const dependencyList = {\n dependencies: [],\n bundledDependencies: []\n };\n for (const entry of graph.filter(nodes_1.isEntryPoint)) {\n const { bundledDependencies = [], dependencies = {}, peerDependencies = {} } = entry.data.entryPoint.packageJson;\n dependencyList.bundledDependencies = array_1.unique(dependencyList.bundledDependencies.concat(bundledDependencies));\n dependencyList.dependencies = array_1.unique(\n dependencyList.dependencies.concat(\n Object.keys(dependencies),\n Object.keys(peerDependencies),\n entry.data.entryPoint.moduleId\n )\n );\n }\n return dependencyList;\n}", "function ZRelationGraph() {\n this.vertices = {}; // Map<ElementId, Vertex>: maps element id onto its vertex\n this.nrConnectedVertices = 0; // Integer: number of vertices that are connected to at least one other vertex\n this.relations = {}; // Map<ElementId, Map<ElementId, ZRelationSet>>: all relations between two elements\n this.suspended = []; // List<ZRelationSet>: list of suspended relation sets\n // invariant: adding any of these will cause a cycle\n this.zValues = {}; // Map<ElementId, Integer>: assigned z values\n this.changed = {}; // Map<ElementId, Integer>: elements changed since last recalc with their previous value\n this.nrChanged = 0; // Integer: cardinality this.changed\n this.newZValues = {}; // Map<ElementId, Integer>: new z-values\n this.callbackObject = undefined; // Object: used in callback\n this.callbackFunction = undefined; // Function: used in callback\n this.resolveCycleBlockRel = undefined; // For info about relation susp.\n}", "constructor() {\n this.graph = {};\n }", "function createGraphFlow() {\n const info = {\n version: { major:1, minor:2, patch:1, release: new Date(2014, 11, 27) },\n created: new Date(2014, 11, 25),\n authors: [\"Miguel Angelo\"]\n };\n var GF = GraphFlow;\n GF.info = info;\n GF.Error = gfError;\n GF.Result = gfResult;\n GF.Arguments = gfArguments;\n GF.NoOp = NoOp;\n GF.End = finalFunc(End);\n GF.finalFunc = finalFunc;\n GF.defaultCombinator = defaultCombinator;\n GF.defaultInherit = defaultInherit;\n GF.createContext = createContext;\n GF.executor = executor;\n GF.distinct = distinct;\n GF.sequence = sequence;\n GF.alternate = alternate;\n GF.combine = combine;\n var push = Array.prototype.push;\n function GraphFlow() {\n var fs = distinct(normalize(argumentsToArray(arguments)));\n return alternativesCombinator(fs);\n }\n function gfError(value, ctx) {\n this.value = value;\n this.ctx = ctx;\n }\n function gfResult(value, ctx) {\n this.value = value;\n this.ctx = ctx;\n }\n function gfArguments(args) {\n this.args = argumentsToArray(args);\n }\n function finalFunc(f) {\n f.isFinalFunc = true;\n return f;\n }\n function End() {\n }\n function NoOp() {\n return function NoOp() {\n // return all arguments to the next function in the chain\n return new gfArguments(arguments);\n }\n }\n function distinct(array) {\n // http://stackoverflow.com/a/16065720/195417\n return array.filter(function (a, b, c) {\n // keeps first occurrence\n return c.indexOf(a) === b;\n });\n }\n function concat(a, b) {\n return a.concat(b);\n }\n function normalize(fs) {\n return fs\n .map(function(f) {\n return typeof f === 'function' && typeof f.funcs === 'function'\n ? f.funcs()\n : [f];\n })\n .reduce(concat, [])\n .map(function(f){\n return f === null ? NoOp() : f;\n });\n }\n function normalizeArgs(args) {\n return args\n .map(function(arg) {\n return arg instanceof gfArguments\n ? arg.args\n : [arg];\n })\n .reduce(concat, []);\n }\n function argumentsToArray(args) {\n return [].slice.call(args);\n }\n function defaultCombinator(g, argsFn, f) {\n function GoF() {\n var args = argsFn.apply(this, arguments);\n return g.apply(this, args);\n };\n if (g.hasOwnProperty('inherit'))\n GoF.inherit = g.inherit;\n return GoF;\n }\n function defaultInherit(gof, g, f) {\n // `gof` inherits properties owned by `g`, if `gof` does not\n // already own a property with the same name from `g`.\n for (var k in g)\n if (!gof.hasOwnProperty(k) && g.hasOwnProperty(k))\n gof[k] = g[k];\n }\n function createContext(fn, mc) {\n return {};\n }\n function executor(fn, ctx, args, mc) {\n try {\n var ResultClass = fn.Result || mc&&mc.Result || this.Result || gfResult;\n return new ResultClass(fn.apply(ctx, args), ctx);\n }\n catch (ex) {\n var ErrorClass = fn.Error || mc&&mc.Error || this.Error || gfError;\n return new ErrorClass(ex, ctx);\n }\n }\n function sequence() {\n var funcs = argumentsToArray(arguments);\n if (funcs.length) {\n var prev = GraphFlow;\n for (var it = 0; it < funcs.length; it++)\n prev = prev(funcs[it]);\n return prev;\n }\n else\n return NoOp();\n }\n function alternate() {\n return GraphFlow.apply(null, arguments);\n }\n function combine() {\n var funcs = argumentsToArray(arguments);\n if (funcs.length > 1) {\n var gf = GraphFlow.apply(null, funcs\n .map(function(f, i) {\n var mc = GraphFlow(f),\n nextFns = funcs.filter(function(el, idx, arr) { return idx !== i; });\n return GraphFlow(f, mc(combine.apply(null, nextFns)));\n }));\n return gf;\n }\n else if (funcs.length == 1)\n return GraphFlow(funcs[0]);\n else\n return GraphFlow();\n }\n function alternativesCombinator(fs) {\n fs = distinct(fs);\n var fn = function MultiCombinator() {\n //debugger;\n var gs = distinct(normalize(argumentsToArray(arguments)));\n var gofs = fs\n .map(function(f) {\n if (typeof f === 'function') f = [f];\n f = normalize(f);\n\n var someIsFinal = f.some(function(ff) { return ff.isFinalFunc; });\n if (someIsFinal) {\n if (f.length == 1)\n return f[0];\n throw new Error(\"Cannot group functions with 'isFinalFunc' flag.\");\n }\n\n var result = gs\n .map(function(g) {\n var gargsFn = function() {\n var _this = this,\n fargs = arguments;\n return normalizeArgs(\n f.map(function(ff) {\n return ff.apply(_this, fargs);\n }));\n }\n\n var combinator = g.combinator || GF.defaultCombinator || defaultCombinator;\n var gof = combinator.call(GF, g, gargsFn, f);\n if (gof) {\n var inherit = gof.inherit || GF.defaultInherit || defaultInherit;\n inherit.call(GF, gof, g, f);\n }\n\n return gof;\n })\n .filter(function(gof){return gof;});\n\n return result;\n })\n .reduce(concat, []);\n return alternativesCombinator(gofs);\n };\n fn.callAll = function() {\n var _this = this,\n ctxCreator = this.createContext || GF&&GF.createContext || createContext,\n exec = this.executor || GF&&GF.executor || executor,\n args = normalizeArgs(argumentsToArray(arguments));\n return fs\n .map(function(f) {\n var ctx = (f.createContext || ctxCreator).call(GF, f, _this);\n return (f.executor || exec).call(GF, f, ctx, args, _this);\n });\n };\n fn.funcs = function() {\n return fs;\n };\n return fn;\n }\n return GF;\n}", "function xmlToGraph(xml)\n{\n var j_nodes=[];\n var j_edges=[];\n var nodes, edges;\n var node = null;\n var data = null;\n var edge = null;\n var datum, key, val, target, source, directed, vweight;\n var jnode = {};\n var i, j;\n\n\n // MFM Notes: \n // IE treats the XML dom differently than other browsers, so we have to parse the dom differently for IE.\n // When the server/graphml service generates json instead of XML this will avoiding the need to use xmlToGraph at all!\n \n if (window.navigator.appName.indexOf(\"Internet Explorer\") >= 0 || window.navigator.appName.indexOf(\"Microsoft\") >= 0) {\n nodes = xml.childNodes[1].childNodes;\n edges = xml.childNodes[0].childNodes;\n \n\tfor (i = 0; i < nodes.length; i++) {\n node = nodes[i];\n data = node.childNodes; // xml childNodes of the node\n jnode = {\n id: node.attributes.getNamedItem(\"id\").value,\n attrs:[]\n };\n \n for (j = 0; j < data.length; j++) {\n datum=data[j];\n key = datum.attributes[0].value;\n val = \"unknown id\"; // MFM firstChild may be null\n if (datum.firstChild) {\n val = datum.firstChild.text;\n }\n\n if (key=='IdentifierType')\n jnode.idType=val;\n if (key=='Identifier')\n jnode.idVal=val;\n\n if (key=='label') {\n jnode.label=val;\n jnode.name=val;\t\t\t\t\t\t\t\t\n }\n else if (key.indexOf (\"Color\") != -1) {\n switch(val.length) {\n case 6: \n jnode.color=\"#\" + val;\n break;\n case 7:\n jnode.color=val;\n break;\n case 9:\n jnode.color=\"#\" + val.substring(3);\n break;\n case 8:\n jnode.color=\"#\" + val.substring(2);\n break;\n default:\n jnode.color='black';\n break;\n } // switch\n } // is color\n else {\n jnode.attrs.push({key:key,val:val});\n }\n\n } // each data\n j_nodes.push(jnode);\t\t\n\t} // each node\n\n \n\tfor (j = 0; j < edges.length; j++) {\n edge = edges[j];\n //var target=edge.attributes.target.textContent;\n target=edge.attributes.getNamedItem(\"target\").text;\n //var source=edge.attributes.source.textContent;\n source=edge.attributes.getNamedItem(\"source\").text;\n //var directed=edge.attributes.directed.textContent;\n directed=edge.attributes.getNamedItem(\"directed\").text;\n // MFM added weight\n //var vweight = edge.attributes.weight.value;\n vweight = edge.attributes.getNamedItem(\"weight\").value; \n\n // PWG added attributes 1/22/14. Need to test with IE\n var attrs = [];\n var data = edge.childNodes;\n\t\tfor (var i = 0; i < data.length; i++) {\n datum=data[i];\n key = datum.attributes[0].value;\n val = \"unknown id\";\n if (datum.firstChild) {\n val = datum.firstChild.textContent;\n }\n attrs.push({key:key,val:val});\n }\n\n\n\n j_edges.push({source:source, target:target, directed:directed, \"weight\":vweight, \"attrs\":attrs});\n\t} // each edge \n } // end if IE\n else {\n if ((xml.childNodes[0] === undefined) ||\n\t (xml.childNodes[0].childNodes[0] === undefined) ||\n\t (xml.childNodes[0].childNodes[0].attributes.id === undefined)) {\n\t\tnodes=xml.childNodes[1].childNodes;\n\t\tedges=xml.childNodes[0].childNodes;\t\t\n\t}\n\telse {\n\t\tnodes=xml.childNodes[0].childNodes;\n\t\tedges=xml.childNodes[1].childNodes;\t\t\n\t}\n\n\tfor (i = 0; i < nodes.length; i++) {\n\t\tnode = nodes[i];\n\t\tdata=node.childNodes; // xml childNodes of the node\n\t\tjnode = {\n\t\t\tid:node.attributes.id.value,\n\t\t\tattrs:[]\n\t\t};\n\t\tfor (j = 0; j < data.length; j++) {\n datum=data[j];\n key = datum.attributes[0].value;\n val = \"unknown id\"; // MFM firstChild may be null\n if (datum.firstChild) {\n val = datum.firstChild.textContent;\n }\n\n if (key=='IdentifierType')\n jnode.idType=val;\n if (key=='Identifier')\n jnode.idVal=val;\n\n if (key=='label') {\n jnode.label=val;\n jnode.name=val;\t\t\t\t\t\t\t\t\n }\n else if (key.indexOf (\"Color\") != -1) {\n switch(val.length) {\n case 6: \n jnode.color=\"#\" + val;\n break;\n case 7:\n jnode.color=val;\n break;\n case 9:\n jnode.color=\"#\" + val.substring(3);\n break;\n case 8:\n jnode.color=\"#\" + val.substring(2);\n break;\n default:\n jnode.color='black';\n break;\n } // switch\n } // is color\n else {\n jnode.attrs.push({key:key,val:val});\n }\n\n\t\t} // each data\n\t\tj_nodes.push(jnode);\t\t\n\t} // each node\n\n\tfor (j = 0; j < edges.length; j++) {\n\t\tedge = edges[j];\n\t\ttarget=edge.attributes.target.textContent;\n\t\tsource=edge.attributes.source.textContent;\n\t\tdirected=edge.attributes.directed.textContent;\n // MFM added weight\n vweight = edge.attributes.weight.value; \n \n // PWG added attributes 1/22/14\n var attrs = [];\n var data = edge.childNodes;\n\t\tfor (var i = 0; i < data.length; i++) {\n datum=data[i];\n key = datum.attributes[0].value;\n val = \"unknown id\";\n if (datum.firstChild) {\n val = datum.firstChild.textContent;\n }\n attrs.push({key:key,val:val});\n }\n \n\t\tj_edges.push({source:source, target:target, directed:directed, \"weight\":vweight, \"attrs\":attrs});\n\t\t\n\t} // each edge\n }\n return {nodes:j_nodes, edges:j_edges};\n}", "addAdjacent(node) {\n this.adjacents.push(node);\n }", "function buildDiagram(ontologyData){\n\n var ontologyData = ontologyData\n // Create the input graph\n var g = new dagreD3.graphlib.Graph({compound:true})\n .setGraph({edgesep: 10, ranksep: 100, nodesep: 50, rankdir: 'LR'})\n .setDefaultEdgeLabel(function() { return {}; });\n\n var CSS_COLOR_NAMES = ['#ff5656', '#ff7d56', '#ff9956', '#ffbb56','#ffda56','#fffc56','#d7ff56','#b0ff56','#7dff56','#56ffc1','#56ffeb','#56e5ff','#56bbff','#5680ff','#a256ff','#cf56ff','#f356ff','#ff56cc', '#ff569f']\n var takenColorId = 5\n var typeColors = {}\n\n ontologyData.entities.forEach(function(e){\n g.setNode(getNameOfUri(e.type), {style:'fill:none;opacity:0;border:none;stroke:none'})\n views.forEach(function(v){\n e.supertypes.forEach(function(s){\n if(s.includes(v)){\n if(!g.nodes().includes(v))\n g.setNode(v, {label: v + ' view', style: 'fill:' + ONTOLOGY_COLORS[v] + ';stroke:' + ONTOLOGY_COLORS[v] , clusterLabelPos: 'top'})\n g.setParent(getNameOfUri(e.type), v)\n }\n }) \n })\n })\n ontologyData.entities.forEach(function(e){\n Object.keys(ontologyCategories).forEach(function(oc){\n e.supertypes.forEach(function(s){\n ontologyCategories[oc].forEach(function(type){\n if(s.includes(type)){\n if(!g.nodes().includes(oc)){\n g.setNode(oc, {label: oc, id:oc, style: 'fill:' + ONTOLOGY_COLORS[oc] + ';stroke:' + ONTOLOGY_COLORS[oc], clusterLabelPos: 'top'})\n }\n parent = g.parent(getNameOfUri(e.type))\n if(parent && parent != oc){\n g.setParent(parent, oc)\n } else {\n g.setParent(getNameOfUri(e.type), oc)\n }\n }\n })\n })\n })\n })\n\n ontologyData.entities.forEach(function(e){ \n g.setNode(getNameOfUri(e.uri), {id: getNameOfUri(e.uri), label: getNameOfEntity(e), style: 'fill:' + getEntityColor(e)})\n g.setParent(getNameOfUri(e.uri), getNameOfUri(e.type))\n })\n\n ontologyData.relations.forEach(function(r){\n g.setEdge(getNameOfUri(r.source), getNameOfUri(r.target), {class:'in-' + getNameOfUri(r.target) + ' out-' + getNameOfUri(r.source), label: r.name, \n style: \"stroke-dasharray: 5,5;\",\n arrowheadStyle: \"fill: #bec6d8; stroke-width:0\", curve: d3.curveBasis})\n })\n\n g.nodes().forEach(function(v) {\n var node = g.node(v);\n node.rx = 5\n node.ry = 5\n });\n\n // Create the renderer\n var render = new dagreD3.render();\n\n // Set up an SVG group so that we can translate the final graph.\n var svg = d3.select(\"#interactive_diagram_svg\"),\n svgGroup = svg.append(\"g\");\n\n // Set up zoom support\n var zoom = d3.zoom()\n .on(\"zoom\", function() {\n svgGroup.attr(\"transform\", d3.event.transform);\n });\n svg.call(zoom).on(\"dblclick.zoom\", null);\n\n // Run the renderer. This is what draws the final graph.\n render(d3.select(\"svg g\"), g);\n\n //Make ontology layers to be positioned behind everything\n Object.keys(ontologyCategories).forEach(function(oc){\n clusters = document.getElementsByClassName('clusters')[0]\n cluster = document.getElementById(oc)\n if(cluster){\n clusters.insertBefore(cluster, clusters.firstChild)\n }\n })\n\n //Lighten the colors a bit\n d3.selectAll('rect').each(function(){\n color = d3.select(this).style('fill')\n recursiveLighten(d3.select(this))\n })\n\n // Lighten clusters\n lightenClusters(0.9)\n\n // Scale the diagram to fit the screen\n scaleDiagram()\n\n // Add nodepath highlight logic\n var toggleOn = ''\n selectedNodeColor = {id:'', color:''}\n highlightNodepathsOnclick()\n\n // Position clusters\n positionClusters()\n\n // Give nodes title and tooltips on hover\n setTitleToNodes()\n tippy('.nodeRect')\n\n // Create dropdown logic for the arrow button beside the node\n setNodeDropdownLogic()\n\n //--------------------------------------------------------------------\n // HELPERS\n //--------------------------------------------------------------------\n\n function lightenClusters(targetL){\n //Lighten the clusters\n d3.selectAll('.cluster')\n .select('rect')\n .each(function(){\n color = d3.select(this).style('fill')\n newColor = tinycolor(color).toHsl()\n newColor.l = targetL\n\n newColorFill = tinycolor(newColor).toHex().toString()\n \n newColor.l = targetL - 0.1\n newColorStroke = tinycolor(newColor).toHex().toString()\n\n d3.select(this).style('fill', newColorFill)\n d3.select(this).style('stroke', newColorStroke)\n })\n }\n\n function recursiveLighten(rect){\n color = rect.style('fill')\n if(tinycolor(rect.style('fill')).isDark()){\n rect.style('fill', tinycolor(color).lighten(10).toString())\n recursiveLighten(rect)\n }\n }\n\n function scaleDiagram(){\n svgBCR = d3.select('#interactive_diagram_svg').node().getBoundingClientRect()\n gBBox = d3.select('.output').node().getBBox()\n abswidth = Math.abs(svgBCR.width - gBBox.width)\n absheight = Math.abs(svgBCR.height - gBBox.height)\n\n if(absheight < abswidth){\n widthScale = svgBCR.width / gBBox.width\n d3.select('.output')\n .style('transform','scale(' + widthScale + ')')\n }else{\n heightScale = svgBCR.height / gBBox.height\n d3.select('.output')\n .style('transform','scale(' + heightScale + ')')\n }\n }\n\n // Helpers for building the graph\n function getRandomColor(){\n takenColorId = (takenColorId+1)%CSS_COLOR_NAMES.length\n return CSS_COLOR_NAMES[takenColorId]\n }\n\n function getNameOfEntity(entity){\n if(entity.label){\n return entity.label\n }else{\n return getNameOfUri(entity.uri)\n }\n }\n\n function getPrettyName(string){\n name = ''\n for(i in string){\n if(i > 0 && string[i] == string[i].toUpperCase()){\n name += ' ' + string[i].toLowerCase()\n }else if (i == 0 && string[i] == string[i].toLowerCase()){\n name += string[i].toUpperCase()\n }else{\n name += string[i]\n }\n }\n return name\n }\n\n function getSubTree(startEntityUri, list, forward){\n startEntityUri = getNameOfUri(startEntityUri)\n ontologyData.relations.forEach(function(rel){\n if(forward) {\n if(getNameOfUri(rel.source) == startEntityUri){\n getSubTree(rel.target, list, true)\n list.push(rel)\n }\n }else{\n if(getNameOfUri(rel.target) == startEntityUri){\n getSubTree(rel.source, list, false)\n list.push(rel)\n }\n }\n })\n return list\n }\n\n // Helpers for making the graph pretty\n function setTitleToNodes(){\n ontologyData.entities.forEach(function(e){\n d3.select('#' + getNameOfUri(e.uri))\n .select('.nodeRect')\n .attr('title', formatToolTip(e))\n })\n }\n\n function formatToolTip(entity){\n description = entity.dataTypeProperties[0]\n if(description && getNameOfUri(description[0]).includes('Description')){\n description = description[1]\n } else {\n description = ''\n }\n if(description.length > 200){\n description = description.substring(0,200) + '...'\n }\n tooltip='<p><b>Type: </b>' + getPrettyName(getNameOfUri(entity.type)) + '</p>' +\n '<p><b>Name: </b>' + getNameOfEntity(entity) + '</p>' +\n '<p>' + description + '</p>'\n return tooltip\n }\n\n function highlightRelations(entityName){ \n relations = getSubTree(entityName, [], true)\n Array.prototype.push.apply(relations, getSubTree(entityName, [], false))\n\n relations.forEach(function(rel){\n inClass = '.in-' + getNameOfUri(rel.target)\n outClass = '.out-' + getNameOfUri(rel.source)\n\n d3.select(inClass + outClass)\n .select('path.path')\n .transition()\n .duration(250)\n .style(\"stroke\", \"#ff5b5b\")\n .style(\"stroke-dasharray\", \"\")\n\n d3.select(inClass + outClass)\n .select('marker')\n .select('path')\n .transition()\n .duration(250)\n .style(\"fill\", \"#ff5b5b\") \n })\n }\n\n function unlightRelations(){\n d3.selectAll('.edgePath')\n .select('path.path')\n .transition()\n .duration(200)\n .style(\"stroke-dasharray\", \"5, 5\")\n .duration(200)\n .style(\"stroke\", \"#929db5\")\n\n d3.selectAll('.edgePath')\n .select('marker')\n .select('path')\n .transition()\n .duration(200)\n .style(\"fill\", \"#929db5\") \n }\n\n function positionClusters(){\n largestYtop = 0\n largestYbot = 0\n \n d3.selectAll('.cluster').each(function(){\n currentBBox = d3.select(this).node().getBBox()\n if(currentBBox.y < largestYtop){\n largestYtop = currentBBox.y\n }\n if(currentBBox.height + Math.abs(currentBBox.y) > largestYbot){\n largestYbot = currentBBox.height + Math.abs(currentBBox.y)\n }\n })\n largestYbot = largestYbot - Math.abs(largestYtop) + 100\n \n clusterTransform = d3.select('.cluster')\n .attr('transform')\n .replace('translate(', '')\n .replace(')','')\n .split(',')\n clusterTransformY = parseFloat(clusterTransform[1])\n \n d3.selectAll('.cluster').each(function(){ \n currentTransform = d3.select(this)\n .attr('transform')\n .replace(/,\\d+\\.*\\d+/, ',' + clusterTransformY) \n\n d3.select(this)\n .attr('transform', currentTransform)\n \n // Make cluster rects wider\n d3.select(this)\n .select('rect')\n .attr('x', (parseFloat(d3.select(this)\n .select('rect')\n .attr('x')) - 25) + 'px')\n\n d3.select(this)\n .select('rect')\n .attr('width', (parseFloat(d3.select(this)\n .select('rect')\n .attr('width')) + 50) + 'px')\n })\n \n d3.selectAll('.cluster')\n .select('rect').attr('y', largestYtop - 50)\n .attr('height',largestYbot)\n\n\n //Make ontology category clusters bigger\n Object.keys(ontologyCategories).forEach(function(oc){\n cluster = d3.select('#' + oc)\n heightDelta = 150\n if(!cluster.empty()){\n console.log(cluster)\n clusterHeight = parseFloat(cluster.select('rect').attr('height'))\n clusterY = parseFloat(cluster.select('rect').attr('y'))\n cluster.select('rect')\n .attr('height', clusterHeight + heightDelta) \n .attr('y', clusterY - heightDelta/2) \n }\n })\n\n // Style labels\n d3.selectAll('.cluster')\n .each(function(c){\n clusterBBox = d3.select(this).node().getBBox()\n labelBBox = d3.select(this).select('.label').node().getBBox()\n\n // Center labels in cluster\n d3.select(this)\n .select('.label')\n .select('g')\n .attr('transform', 'translate(' + labelBBox.x + ',' + (clusterBBox.y + 10) + ')')\n \n // Set color of label\n color = d3.select(this).select('rect').style('stroke')\n d3.select(this)\n .select('text')\n .style('fill', tinycolor(color).darken(25).toString())\n })\n\n //Label onclick\n d3.selectAll('.cluster')\n .select('.label')\n .on('click', function(){\n rect = d3.select(this.parentNode).select('rect')\n parent = d3.select(this.parentNode)\n\n if(parent.classed('selected')){\n d3.select(this.parentNode)\n .classed('selected', false)\n .classed('unselected', true)\n\n }else{\n d3.selectAll('.selected')\n .each(function(){\n d3.select(this).classed('selected', false)\n d3.select(this).classed('unselected', true)\n \n })\n\n parent\n .classed('unselected', false)\n .classed('selected', true)\n }\n })\n\n d3.selectAll('.cluster')\n .select('rect')\n .attr('rx',50)\n .attr('ry',50)\n }\n\n //Creating the logic for node actions\n function highlightNodepathsOnclick(){\n //ADD ACTIONS THE NODE RECTANGLES\n d3.selectAll('.node')\n .select('rect')\n .attr('class', 'nodeRect')\n .on('click', function(){\n thisClass = d3.select(this.parentNode).attr('id')\n\n if(thisClass == toggleOn){\n unlightRelations()\n toggleOn = ''\n }else{\n toggleOn = thisClass\n unlightRelations()\n highlightRelations(thisClass)\n }\n\n style = d3.select(this)\n .attr('style')\n if(style != 'fill:#ffef68'){\n if (selectedNodeColor['id']){\n d3.select('#' + selectedNodeColor['id'])\n .select('rect')\n .attr('style', 'fill:' + selectedNodeColor['color'])\n }\n selectedNodeColor['color'] = style.substring(5, style.length)\n selectedNodeColor['id'] = d3.select(this.parentNode)\n .attr('id')\n d3.select(this)\n .attr('style', 'fill:#ffef68')\n \n }else{\n d3.select('#' + selectedNodeColor['id'])\n .select('rect')\n .attr('style', 'fill:' + selectedNodeColor['color'])\n selectedNodeColor['color'] = ''\n selectedNodeColor['id'] = ''\n }\n })\n }\n\n function setNodeDropdownLogic(){\n d3.selectAll('.node').each(function(node){\n //CREATE DROP-DOWN BUTTON FOR NODES\n nodeWidth = parseFloat(\n d3.select(this)\n .select('rect')\n .attr('width'))\n nodeHeight = parseFloat(\n d3.select(this)\n .select('rect')\n .attr('height'))\n rectColor = d3.select(this)\n .select('rect')\n .style('fill')\n \n d3.select(this)\n .select('rect')\n .attr('width', nodeWidth + nodeHeight)\n\n d3.select(this)\n .append(\"rect\")\n .attr('class', 'nodeButton')\n .attr('width', nodeHeight)\n .attr('height', nodeHeight)\n .attr('x', nodeWidth/2)\n .attr('y', -nodeHeight/2)\n .attr('rx', '5')\n .attr('ry', '5')\n .style('stroke', 'none')\n .style('cursor', 'pointer')\n .style('opacity', '0')\n .on('mouseover', function(){\n d3.select(this)\n .style('fill','white')\n .transition()\n .duration(200)\n .style('opacity','0.7')\n }).on('mouseout', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity','0')\n }).on('click', function(){\n nodeWidth = parseFloat(\n d3.select(this.parentNode)\n .select('.nodeRect')\n .attr('width'))\n nodeHeight = parseFloat(\n d3.select(this.parentNode)\n .select('.nodeRect')\n .attr('height'))\n \n //CREATE DROPDOWN RECTANGLE\n //Put the node first in the list to avoid overlapping\n this.parentNode.parentNode.appendChild(this.parentNode)\n\n function hideDropdown(){\n d3.selectAll('.node_dropdown')\n .transition()\n .duration(200)\n .attr('height', '1')\n .transition()\n .duration(200)\n .attr('width','0')\n .remove()\n \n d3.selectAll('.drop-down_arrow')\n .transition()\n .duration(100)\n .style('fill', '#2c4c66')\n .style('stroke', '#2c4c66')\n\n d3.selectAll('.drop-down_item')\n .remove()\n\n d3.selectAll('.drop-down_item_text')\n .remove()\n }\n\n if(d3.select(this.parentNode).select('.node_dropdown').empty()){\n\n hideDropdown()\n //Create drop-down box\n d3.select(this.parentNode)\n .append('rect')\n .attr('class', 'node_dropdown')\n .attr('x', (nodeWidth/2+nodeHeight/2)+20)\n .attr('y', -nodeHeight/2)\n .attr('width', '0')\n .attr('height', '1')\n .transition()\n .duration(200)\n .attr('width', '160px')\n .transition()\n .duration(200)\n .attr('height', nodeHeight*3)\n .attr('rx','5')\n .attr('ry','5')\n .style('stroke', '#424242')\n .style('fill', '#424242')\n \n //Drop-down arrow change to white\n d3.select(this.parentNode)\n .select('.drop-down_arrow')\n .transition()\n .duration(250)\n .style('fill', 'white')\n .style('stroke', 'white')\n\n //Create drop-down items\n item_counter = 0\n function addDropdownItem(parent, name){\n d3.select(parent.parentNode)\n .append('rect')\n .attr('class', 'drop-down_item')\n .attr('id', 'drop_down_item' + item_counter)\n .attr('x', (nodeWidth/2+nodeHeight/2)+20)\n .attr('y', (-nodeHeight/2 + nodeHeight*item_counter))\n .attr('width', '160px')\n .attr('height', nodeHeight)\n .attr('rx', 5)\n .attr('ry', 5)\n .style('stroke', 'none')\n .style('fill', 'gray')\n .attr('opacity', '0')\n .on('mouseover', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity', '1')\n })\n .on('mouseout', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity', '0')\n })\n .on('click', function(){\n createPopup()\n })\n\n d3.select(parent.parentNode)\n .insert('text')\n .attr('class', 'drop-down_item_text')\n .attr('id', 'drop-down_item_text' + item_counter)\n .attr('x', (9 + nodeWidth/2+nodeHeight/2)+20)\n .attr('y', (6 + nodeHeight*item_counter))\n .style('font-size','14px')\n .style('fill','white')\n .style('stroke','none')\n .style('opacity', '0')\n .transition()\n .delay(300)\n .duration(200)\n .style('opacity', '1')\n \n d3.select(parent.parentNode)\n .select('#drop-down_item_text' + item_counter)\n .html(name)\n\n item_counter++\n }\n\n addDropdownItem(this, 'View diagrams')\n addDropdownItem(this, 'Explain entity')\n addDropdownItem(this, 'Explain relations')\n\n }else{\n hideDropdown() \n }\n\n })\n \n // CREATE SVG ARROW\n x = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('x'))\n y = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('y'))\n width = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('width'))\n points = (x + width/2) + ',' + (y + 5 + nodeHeight/2) + ' ' + (x + width/2) + ',' + (y - 5 + nodeHeight/2) + ' ' + (x + 5 + width/2) + ',' + (y + nodeHeight/2)\n \n d3.select(this)\n .append(\"polygon\")\n .attr('class', 'drop-down_arrow')\n .attr('points', points)\n .style('fill','#2c4c66')\n .style('stroke-width', '1px')\n .style('stroke', '#2c4c66')\n .style('pointer-events', 'none')\n })\n\n }\n\n function createPopup(){\n width = 80\n height = 90\n d3.select('body')\n .append('div')\n .attr('id', 'popup-background')\n .attr('class', 'popup')\n .style('width', '100%')\n .style('height', '100%')\n .style('opacity','0.3')\n .style('position', 'absolute')\n .style('background-color','black')\n \n d3.select('#popup-background')\n .on('click', function(){\n d3.selectAll('.popup')\n .remove()\n })\n\n d3.select('body')\n .append('div')\n .attr('id', 'popup-view')\n .attr('class','w3-light-gray w3-border w3-border-indigo popup')\n .style('position','absolute')\n .style('left', '50%')\n .style('bottom', '50%')\n .style('transform', 'translate(-50%,50%)')\n .style('width', width + \"%\")\n .style('height', height + \"%\")\n \n\n d3.select('#popup-view')\n .html(getPopup())\n\n var s = document.createElement('script')\n s.src = 'static/popup-graph.js'\n\n document.getElementById('popup-view').appendChild(s)\n\n d3.select('#close_popup')\n .on('click', function(){\n d3.selectAll('.popup')\n .remove()\n })\n }\n\n function getPopup(){\n string = \n \"<button class='w3-white w3-button w3-border-right roundedTopCorners' style='height:5%;float:left;font-size:13px'>Figure 3_10</button>\" +\n \"<button class='w3-button w3-light-grey w3-border-right roundedTopCorners' style='height:5%;background-color:#b8dced;float:left;font-size:13px'>Figure_3_4</button>\" +\n \"<button class='w3-button w3-light-grey w3-border-right roundedTopCorners' style='height:5%;background-color:#b8dced;float:left;font-size:13px'>Figure_3_2</button>\" +\n \"<button id='close_popup' class='w3-light-grey w3-button w3-text-indigo roundedTopCorners w3-border-right w3-border-top' style='height:5%;margin:0;float:right'><b>X</b></button>\" +\n \"<a href='popup-window.html' class='w3-button roundedTopCorners w3-border-right' target='_blank' style='height:5%;margin:0;float:right'>Open in new window</a>\" +\n \"<div class='w3-white w3-border-bottom' style='width:100%;height:5%;font-size:13px'></div> \" +\n \"<div id ='diagram_image_div' class='w3-white w3-border-right' style='width:65%;height:95%;float:left;position:relative'> \" +\n \" <svg id='diagram_image' height='100%' width='100%'></svg>\"+\n \"</div>\" +\n \"<div style='height:95%;padding-top:16px;padding-bottom:16px;'>\" +\n \"<div class='w3-container w3-light-gray' style='overflow-y:scroll;width:33.7%;height:95%;float:left;'>\" +\n \" <h2>View diagrams</h2>\" +\n \" <hr>\" +\n \" <h3>Figure 3.10: Class diagram of the system</h3>\" +\n \" <p>\" +\n \" The conceptual model of this project revolves around the cart concept, while all other system elements are there to provide the required information to the cart, as seen in the class diagram below (Figure 3.10). Products are related to carts as a list of product variants, forming line items. Variant is a concept to define the part of the product that contains the particular characteristics of it, such as color or size, even having sometimes a different price. Therefore every product has at least one variant, each one with different price or attributes. Similarly, a cart can be associated with one of the shipping methods available in the system, resulting in a shipping item, necessary to manage taxes. \" +\n \" </p>\" +\n \" <p>\" +\n \" Both products and shipping methods have a particular tax category, that can be variable for products and fixed in the case of shipping. When one of these elements are added to the cart, a tax rate is assigned to the item according to this tax category and the shipping address of the cart. As mentioned above carts can have a shipping address, but can have as well a billing address. \" +\n \" </p>\" +\n \" <p>\" +\n \" A cart can belong to a registered customer, otherwise it is considered to have an anonymous customer. Once the checkout is finished a cart becomes an order, with information about the current payment, shipping and order status. If the customer was not anonymous, this order will be associated with that customer, along with any of his previous orders. Every customer can also have a list of addresses comprising the address book.\" +\n \" </p>\" +\n \" <p>Products, addresses and shipping methods can change or disappear over time, but the orders associated with them must stay in the system for an indefinite period of time, having exactly 44 the original information. To solve this issue, cart is not related to the original instances, but to instances that were created exclusively for this particular cart as a snapshot of those original instances. </p>\" +\n \" <p>While the current cart may optionally have associated information, this information is mandatory in an order instance. For simplicity, the conceptual model only accepts product and shipping prices that do not include taxes. Allowing taxes in prices can be achieved by simply adding a boolean attribute indicating whether the price in question has taxes included or not. So assuming that taxes are not included, the net total price in the cart must be the sum of all the line item prices (i.e. the quantity in each line item multiplied by the corresponding variant price) associated with it, plus the price of the shipping method selected. In order to calculate the gross total price, taxes must be added up to this resulting net price. Taxes are calculated multiplying the price of each shipping or line item by its corresponding tax rate. </p>\" +\n \" <p>Lastly when the shipping address is set in the cart, all tax rates from shipping and line items are calculated. Only those products that include a tax category corresponding to the zone (e.g. state, country) of the shipping address can be part of the cart. Missing the tax category means that the price cannot be calculated, thus the product is not available in that zone.</p>\" +\n \"</div>\" +\n \"</div>\" +\n \"</div>\" \n return string\n }\n\n}", "function record_dependency(dependent, property, dependee)\n{\n if (!pending[dependee])\n \tpending[dependee] = [];\n \t\n pending[dependee].push({property: property, dependent: dependent});\n}", "function updateNetwork() {\n if (d3.event) {\n d3.event.stopPropagation();\n }\n node = node.data(graph.nodes, function (d) {\n return d.id;\n });\n node.exit().remove();\n node = node.enter().append(\"circle\").attr(\"fill\", function (d) {\n return color(d.group);\n })\n .attr(\"r\", function (d) {\n return 3 + (d.nodescore / maxNodeScore) * 4.5;\n })\n .merge(node);\n node.select(\"text\").remove();\n node.append(\"text\")\n .attr(\"dx\", 6)\n .attr(\"id\", function (d) {\n return d.id + \"-label\";\n })\n .text(function (d) {\n return d.id;\n });\n link = link.data(graph.links, function (d) {\n return d.source.id + \"-\" + d.target.id;\n });\n link.exit().remove();\n link = link.enter().append(\"line\").merge(link);\n simulation.nodes(graph.nodes)\n .force(\"link\").links(graph.links);\n simulation.alpha(0.3).restart();\n }", "async [_makeIdealGraph] (options) {\n /* Make sure that the ideal tree is build as the rest of\n * the algorithm depends on it.\n */\n const bitOpt = {\n ...options,\n complete: false,\n }\n await this.buildIdealTree(bitOpt)\n const idealTree = this.idealTree\n\n this.rootNode = {}\n const root = this.rootNode\n this.counter = 0\n\n // memoize to cache generating proxy Nodes\n this.externalProxyMemo = memoize(this.externalProxy.bind(this))\n this.workspaceProxyMemo = memoize(this.workspaceProxy.bind(this))\n\n root.external = []\n root.isProjectRoot = true\n root.localLocation = idealTree.location\n root.localPath = idealTree.path\n root.workspaces = await Promise.all(\n Array.from(idealTree.fsChildren.values(), this.workspaceProxyMemo))\n const processed = new Set()\n const queue = [idealTree, ...idealTree.fsChildren]\n while (queue.length !== 0) {\n const next = queue.pop()\n if (processed.has(next.location)) {\n continue\n }\n processed.add(next.location)\n next.edgesOut.forEach(e => {\n if (!e.to || (next.package.bundleDependencies || next.package.bundledDependencies || []).includes(e.to.name)) {\n return\n }\n queue.push(e.to)\n })\n if (!next.isProjectRoot && !next.isWorkspace) {\n root.external.push(await this.externalProxyMemo(next))\n }\n }\n\n await this.assignCommonProperties(idealTree, root)\n\n this.idealGraph = root\n }", "graph(options) {\n return this.appendChild(new Graph(options));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if the last error was set and throws it.
function throwLastError() { const er = in3w.ccall('in3_last_error', 'string', [], []); if (er) throw new Error(er + (in3w.sign_js.last_sign_error ? (' : ' + in3w.sign_js.last_sign_error) : '')) }
[ "function incrementoError()\n\t{\n\t\tif(presente === false)\n\t\t{\n\t\t\tmasUnError();//Instanciar la función que aumenta los fallos acumulados.\n\t\t}\n\t}", "function MultiError(errors)\n\t{\n\t\tmod_assertplus.array(errors, 'list of errors');\n\t\tmod_assertplus.ok(errors.length > 0, 'must be at least one error');\n\t\tthis.ase_errors = errors;\n\t\n\t\tVError.call(this, {\n\t\t 'cause': errors[0]\n\t\t}, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');\n\t}", "function error(err) {\n if (error.err) return;\n callback(error.err = err);\n }", "setError(error) {\n if (error === this.getError()) return\n const { form, path } = this.props\n if (form && path) return form.setError(path, error)\n else {\n this._error = error\n this.forceUpdate()\n }\n }", "error() {\n throw new Error('Invalid syntax');\n }", "function _authError() {\n next('Invalid User ID / Password');\n }", "logIfError() {\n if (!this.ok)\n console.error(this.error);\n return !this.ok;\n }", "error() {\n const isAbsolute = this.options.fail.indexOf('://') > -1;\n const url = isAbsolute ? this.options.fail : this.options.url + this.options.fail;\n\n this.request(url);\n }", "static getDerivedStateFromError(error) {\n // Update state so the next render will show the fallback UI. Setting this variable to true is required to know that children of errorBoundary component \n // are throwing error. \n return { hasError: true };\n }", "ensureTransactionErrors(transaction) {\n if (!transaction.results) {\n transaction.results = {};\n }\n if (!transaction.errors) {\n transaction.errors = [];\n }\n\n return transaction.errors;\n }", "error(errorCode) {\n throw new Error(errors[errorCode] || errorCode);\n }", "function errorManager(){\n if(fundamental_vars.retry == true){\n //Collect the domains still pending data. Collect all the domains bypassing what the cache says.\n fundamental_vars.bypass_cache_check = true;\n createRequests($('.tld-line.asked:has(.spinner)'));\n\n fundamental_vars.bypass_cache_check = false;\n fundamental_vars.retry = false;\n }else{\n //The requests failed again. Collect all the failed domains and apply to them a no connection error status.\n fundamental_vars.retry = true;\n fundamental_vars.run_errorCheck = false;\n\n var target = $('.tld-line.asked').filter(':has(.add-to-cart:visible)').filter(':has(.spinner)');\n\n target.find('.price').hide();\n target.find('.add-to-cart').hide();\n\n if(target.find('.errors').length < 1) {\n target.find('.actions').append(fundamental_vars.templates['error']).find('.errors span').text(dependencies['statuses'][dependencies['Status']['noconnection']]['locale'])\n }else{\n target.find('.actions .errors span').text(dependencies['statuses'][dependencies['Status']['noconnection']]['locale'])\n }\n }\n}", "function syncError() {\n app.syncState = 'Sync error';\n }", "handleExecutorError (error) {\n const priv = privs.get(this)\n if (priv.state === State.Done) return\n priv.state = State.Errored\n priv.error = error\n privm.wrapup.call(this)\n }", "_onError() {\n this.splice('notebooks', 0);\n this.message = 'Error retrieving Notebooks';\n }", "function focusMouseOnErrorElement(fieldname){\n\t\t\t\t//[ catchFirstError_element ] This would save after catching the first error element\n\t\t\t\tif( catchFirstError_element === undefined){\n\t\t\t\t\tcatchFirstError_element = fieldname;\n\t\t\t\t\t//We select form element by it's name attribute value\n\t\t\t\t\t$('[name=\"'+catchFirstError_element+'\"]').trigger('focus');\n\t\t\t\t}\n\t\t\t}", "isErrorState() {\r\n const gl = this.gl;\r\n return gl === null || gl.getError() !== gl.NO_ERROR;\r\n }", "ensureSuccessStatusCode() { \n if (!this.isSuccessStatusCode) {\n throw new Error(`Request didn't finished with success. Status code: ${this.statusCode}. Reason phrase: ${this.reasonPhrase}`);\n } \n }", "get isError() {\n return (this.flags & 4) /* NodeFlag.Error */ > 0\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
besetSelFormToObj() This is called by a couple of event handlers and decodes the currently selected BESet (in the dropdown form) and sets the cookieObj.besetName accordingly.
function besetSelFormToObj() { cookieObj.besetName = $j("#besetsel-sel").val(); }
[ "function bindSelectedToForm() {\n saveKPForm.find('#kp-id').val(selected.id);\n saveKPForm.find('#kp-number').val(selected.number);\n saveKPForm.find('#kp-name').val(selected.title);\n kpLevelList.val(selected.kLevel).trigger('change');\n saveKPForm.find('#kp-score').val(selected.score);\n saveKPForm.find('#kp-syllabus').text(syllabus.level + ' ' + syllabus.version);\n saveKPForm.find('#kp-chapter').text(chapter.title);\n\n }", "function setCurrMonth(today) {\n form.chooseMonth.selectedIndex = today.getMonth();\n }", "function setDate( dayControlName, monthControlName, date_str )\n{\n\tvar mon\t\t\t= date_str.substr(0,6);\n\tvar day\t\t\t= date_str.substr(6,2);\n\tvar day_elem\t= eval ('document.skylightsForm.' + dayControlName);\n\tvar mon_elem\t= eval ('document.skylightsForm.' + monthControlName);\n\n\tfor (var i=0; i < mon_elem.options.length; i++)\n\t{\n\t\tif ( mon_elem.options[i].value == mon )\n\t\t{\n\t\t\tmon_elem.options[i].selected = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (var i=0; i < day_elem.options.length; i++)\n\t{\n\t\tif ( day_elem.options[i].value == day )\n\t\t{\n\t\t\tday_elem.options[i].selected = true;\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function populateBranch()\n {\n var lstrDlrCode = document.forms[0].dealer.value;\n var lstrBlankFlag=arguments[0] ;\n // dealerBranch - a hidden combo\n comboDealerBranch = eval(document.forms[0].dealerBranch);\n comboBranch = eval(document.forms[0].branch);\n for(lintI=0; lintI < comboBranch.length; lintI++)\n {\n document.forms[0].branch.options[lintI] = null;\n lintI = -1;\n }\n\n //Enter default record\n if(lstrBlankFlag != null && lstrBlankFlag!=\"\" && lstrBlankFlag==\"YES\" ){\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(\" \", \"\");\n }else{\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(document.AppJsp.allLabel.value, \"\");\n }\n for(lintI=0; lintI < comboDealerBranch.length; lintI++)\n {\n var opt= document.forms[0].dealerBranch[lintI].text;\n var value= document.forms[0].dealerBranch[lintI].value;\n\n var lintPos = value.indexOf(\"~\");\n if (lintPos > -1)\n {\n var brcCode = value.substring(0, 2);\n var dlrCode = value.substring(3);\n if(dlrCode == lstrDlrCode || dlrCode == '')\n {\n with(document.forms[0].branch)\n {\n options[options.length] = new Option(opt, brcCode);\n }\n }\n }\n /*else\n {\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(document.AppJsp.allLabel.value, \"\");\n }*/\n }\n }", "function saveBasket(objBasket) {\n var str = JSON.stringify(objBasket);\n setCookie(cookieName, str);\n }", "function loadMarketoForm() {\r\n\t\tMktoForms2.loadForm(\r\n\t\t\t_self.defaultOptions.marketoAPIUrl,\r\n\t\t\t_self.defaultOptions.munchkinId,\r\n\t\t\t_self.defaultOptions.formid,\r\n\t\t\tfunction(form) {\r\n\t\t\t\t// create form function\r\n\t\t\t\t_self.form = form;\r\n\r\n\t\t\t\t// load all the select options if needed\r\n\t\t\t\tfor (var i = 0; i < _self.defaultOptions.fields.length; i++) {\r\n\t\t\t\t\tvar options = null;\r\n\t\t\t\t\tvar id = '#'\r\n\t\t\t\t\t\t\t+ _self.defaultOptions.fields[i].id;\r\n\t\t\t\t\tif (_self.defaultOptions.fields[i].type === \"select\") {\r\n\t\t\t\t\t\toptions = form.getFormElem().find(\r\n\t\t\t\t\t\t\t\tid + ' option');\r\n\r\n\t\t\t\t\t\tvar element = $(id);\r\n\t\t\t\t\t\tif (element && element.length > 0) {\r\n\t\t\t\t\t\t\tfor (var y = 0; y < options.length; y++) {\r\n\t\t\t\t\t\t\t\t$(options[y]).clone().appendTo(\r\n\t\t\t\t\t\t\t\t\t\telement);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t$(id).val($(id + 'option:first').val());\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t_self.defaultOptions.fields[i].options = [];\r\n\t\t\t\t\t\t\tfor (var opt = 0; opt < options.length; opt++) {\r\n\t\t\t\t\t\t\t\t_self.defaultOptions.fields[i].options\r\n\t\t\t\t\t\t\t\t\t\t.push($(options[opt])\r\n\t\t\t\t\t\t\t\t\t\t\t\t.text());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t // trigger the onready function when the form is ready for action\r\n\t\t\t\t_self.defaultOptions.onReady();\r\n\t\t\t\t\r\n\t\t\t\t/**\r\n\t\t\t\t * function to be triggered when a form is\r\n\t\t\t\t * successfully submitted\r\n\t\t\t\t */\r\n\t\t\t\t_self.form.onSuccess(function(obj) {\r\n\t\t\t\t\tvar response = true;\r\n\t\t\t\t\tvar redirect = _self.defaultOptions.onSuccess(obj);\r\n\t\t\t\t\tif(redirect === false)\r\n\t\t\t\t\t\tresponse = false;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\treturn response;\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t}", "function brand()\r\n{\r\n selBrand= def.options[def.selectedIndex].text;\r\n}", "function restoreSelectToOriginalValue(sel, win)\n{\n if(sel != null)\n {\n if (sel.type == \"select-one\" || sel.type == \"select-multiple\")\n {\n var valueWhenRendered = sel.getAttribute(\"valuewhenrendered\");\n if(valueWhenRendered != null && valueWhenRendered.length > 0)\n setSelectValue(sel, valueWhenRendered);\n }\n else if (isNLDropDown(sel))\n {\n getDropdown(sel, win).restoreToOriginalValue();\n }\n }\n}", "function selectPreset() {\n var preset = presets.get(presetsBox.value);\n if (preset) {\n if (preset['band']) {;\n var newBand = Bands[settings.region][preset['band']];\n if (newBand) {\n selectBand(newBand);\n }\n } else if (preset['mode']) {\n setMode(preset['mode']);\n }\n setFrequency(presetsBox.value, false);\n }\n }", "function restoreHtmlEditors( frm )\n{\n if ( typeof NetSuite == \"object\" && typeof NetSuite.RTEManager == \"object\" )\n {\n\t\tvar vfFunc = document.forms['main_form'] != null && document.forms['main_form'].elements.nlapiVF != null ? document.forms['main_form'].elements.nlapiVF.value : null;\n\t\ttry\n\t\t{\n\t\t\tif (vfFunc != null)\n\t\t\t\tdocument.forms['main_form'].elements.nlapiVF.value = '';\n NetSuite.RTEManager.getMap().eachKey(function (key, value) {\n var editor = value.obj;\n\t\t\t\tif (( frm == null || editor.hddn.form == frm ) && editor.getValue() != editor.hddn.value ) {\n editor.setValue( editor.hddn.value );\n }\n });\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tif (vfFunc != null)\n\t\t\t\tdocument.forms['main_form'].elements.nlapiVF.value = vfFunc;\n\t\t}\n\t}\n}", "function selectEventFormAutoChange() {\n\n var object = $(\"#eventFormSelect\");\n var value = object[0].value;\n var ajaxURL = \"../myPHP/classHandler.php?c=EmaileratorEvent&a=Read&MultiSelect=true&field=id&id=\" + value;\n var parentForm = $(\"#eventForm\");\n\n if (value == \"new\") {\n resetEventForm();\n }\n else { \n updateFormFromSelectAjax(ajaxURL, \"#eventForm\");\n updateLogDivAjax(\"#eventLogDiv\", \"EventID\", value);\n updateLogDivAjax(\"#generalLogDiv\");\n parentForm.find(\"#GoButton\").html(\"Update\");\n parentForm.find(\"#DeleteButton\").css(\"visibility\", \"visible\");\n }\n\n}", "function loadCookies() {\n document.getElementById('name').value = getCookie('name');\n document.getElementById('brand').selectedIndex = getCookie('brand');\n document.getElementById('Type').selectedIndex = getCookie('type');\n document.getElementById('target').selectedIndex = getCookie('target');\n document.getElementById('condition').selectedIndex = getCookie('condition');\n document.getElementById('location').selectedIndex = getCookie('location');\n}", "function setForm(target){ \n\t\tvar options = $.data(target, 'form').options; \n\t\tvar form = $(target); \n\t\tform.unbind('.form').bind('submit.form', function(){ \n\t\t\tajaxSubmit(target, options); \n\t\t\treturn false; \n\t\t}); \n\t}", "function selectNameFormAutoChange() {\n\n var object = $(\"#nameFormSelect\");\n var value = object[0].value;\n var ajaxURL = \"../myPHP/classHandler.php?c=EmaileratorUser&a=Read&field=id&id=\" + value;\n var parentForm = $(\"#nameForm\");\n\n if (value == \"new\") {\n resetNameForm();\n }\n else {\n updateFormFromSelectAjax(ajaxURL, \"#nameForm\");\n updateLogDivAjax(\"#nameLogDiv\", \"UserID\", value);\n updateLogDivAjax(\"#generalLogDiv\");\n parentForm.find(\"#GoButton\").html(\"Update\");\n parentForm.find(\"#DeleteButton\").css(\"visibility\", \"visible\");\n }\n\n}", "function saveCurrentSet() {\n if (!currentSet.name) {\n const inputValue = $headerElem.querySelector('.new-set-name').value;\n \n if (!validateSetNameInput(inputValue) || currentSet.ids.length === 0) {\n return;\n }\n\n currentSet.name = inputValue;\n }\n\n allSets[currentSet.name] = currentSet.ids;\n chrome.storage.sync.set({[setsStorageKey]: allSets}, () => {\n closeSetEditor();\n });\n }", "function buildBeerSelector(brewery, selectedBeer) {\n // Build out brewery if other\n if(brewery === 'Other'){\n $('#otherBrewery').val('')\n $('#otherBrewery').css('display', 'block')\n $('#beerSelector').empty()\n $('#beerSelector').append('<option>Other</option>')\n $('#otherBeer').css('display', 'block')\n displayBeerRating('Other', 'Other')\n return\n } else {\n $('#otherBrewery').css('display', 'none')\n $('#otherBeer').css('display', 'none')\n }\n\n $('#beerSelector').empty()\n var sortedBeers = []\n for (beer in result.beer[brewery]){\n sortedBeers.push(beer)\n }\n sortedBeers.sort()\n for (var i = 0; i < sortedBeers.length; i++){\n $('#beerSelector').append('<option>' + sortedBeers[i] + '</option>')\n }\n\n if (addOtherBeer) {\n $('#beerSelector').append('<option>Other</option>')\n }\n\n if (selectedBeer) {\n $('#beerSelector').val(selectedBeer)\n }\n\n // Display rating or tasting notes\n displayBeerRating($('#brewerySelector').val(), $('#beerSelector').val())\n\n refreshListeners()\n}", "function serializeSpecific(selector) {\r\n\t var obj = \"\";\r\n\t $(form).find(selector).each(function () { \r\n\t obj += \"&\";\r\n\t obj += $(this).attr(\"name\");\r\n\t obj += \"=\";\r\n\t obj += $(this).val(); \r\n\t });\r\n\t return obj;\r\n\t}", "function setSelectorFields() {\n // Clear existing selectors\n removeChildren(visualSelector);\n removeChildren(propertySelector);\n\n let propertyOpts = propertyOptions();\n propertyOpts.forEach(function (element) {\n var optK = document.createElement(\"option\")\n optK.value = element;\n optK.innerHTML = element;\n\n propertySelector.appendChild(optK);\n });\n\n propertySelector.value = selectedPropertyOption();\n\n // Add new visual options\n let visualSelectionOptions = visualisationOptions()\n\n visualSelectionOptions.forEach(function (element) {\n var optV = document.createElement('option');\n\n optV.value = element.value;\n optV.innerHTML = element.description;\n\n visualSelector.appendChild(optV);\n });\n}", "function newNode(obj,domOpt){\n \n// For loop to dynamically create select drop-down menu based on user slection. \nvar lNode = true;\nfor(i=0;i<obj.length;i++)\n {\n \n if(domOpt.value===obj.item(i).getElementsByTagName('name').item(0).firstChild.nodeValue) // extract data from data structure based on user selection.\n { \n lNode = false; //data node available to generate next level select statement\n \n // Store title, name value from selected object stored in xml. \n var title1 = obj.item(i).getElementsByTagName('title1').item(0).firstChild.nodeValue;\n var title = obj.item(i).getElementsByTagName('title').item(0).firstChild.nodeValue;\n var name = obj.item(i).getElementsByTagName('name').item(0).firstChild.nodeValue;\n var value = obj.item(i).getElementsByTagName('value');\n \n \n // Creation of new form node and setting its attribute\n var form = createEle(\"form\",\"class\",\"movie\");\n form.style.position = 'relative';\n form.style.left = \"-240px\";\n \n //creation of heading node and appending it to form element\n var head = createEle(\"h6\",\"class\",\"head2\");\n head.setAttribute(\"id\",title1);\n head.appendChild(document.createTextNode(title));\n form.appendChild(head);\n \n // Creation of Select Form element\n var slct = createEle(\"select\",\"class\",\"sel\");\n slct.setAttribute(\"name\",name);\n slct.setAttribute(\"title\",title);\n slct.onchange = function(){goDyna(this);}\n form.appendChild(slct);\n \n // below loop used for creation of Option elements in Select statement \n \n var flag = true; // used for creation of option title node in below loop. \n for(j=0;j<obj.item(i).getElementsByTagName('value').length;j++)\n {\n \n if(flag)\n {\n //Creation of Option elements in Select statement\n var option = createEle(\"option\",\"value\",\"none\");\n option.appendChild(document.createTextNode(title));\n slct.appendChild(option);\n flag = false;\n }\n \n var option1 = createEle(\"option\",\"value\",value.item(j).firstChild.nodeValue);\n option1.appendChild(document.createTextNode(value.item(j).firstChild.nodeValue));\n slct.appendChild(option1);\n //Appending all the option elements at the end of select statements.\n slct.appendChild(option1);\n \n } \n \n //Dynamic appending select statement.\n \n document.getElementById('container').appendChild(form);\n \n document.getElementById('container').appendChild(document.createTextNode(''));\n \n rotate(form,0); // Animation on newly created select menu.\n \n break;\n }\n }\n \n // If its last node in selection tree, display ouput to user.\n if(lNode===true)\n {\n quizNode(obj,quiz,domOpt);\n \n } \n}", "function select_innerHTML(objeto, innerHTML) {\n /******\n * select_innerHTML - corrige o bug do InnerHTML em selects no IE\n * Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228\n * Vers‹o: 2.1 - 04/09/2007\n * Autor: Micox - N‡iron Josˇ C. Guimar‹es - micoxjcg@yahoo.com.br\n * @objeto(tipo HTMLobject): o select a ser alterado\n * @innerHTML(tipo string): o novo valor do innerHTML\n *******/ \n objeto.innerHTML = \"\"\n var selTemp = document.createElement(\"micoxselect\")\n var opt;\n selTemp.id = \"micoxselect1\"\n document.body.appendChild(selTemp)\n selTemp = document.getElementById(\"micoxselect1\")\n selTemp.style.display = \"none\"\n if (innerHTML.toLowerCase().indexOf(\"<option\") < 0) {//se n‹o ˇ option eu converto\n innerHTML = \"<option>\" + innerHTML + \"</option>\"\n }\n innerHTML = innerHTML.toLowerCase().replace(/<option/g, \"<span\").replace(\n /<\\/option/g, \"</span\")\n selTemp.innerHTML = innerHTML\n\n for ( var i = 0; i < selTemp.childNodes.length; i++) {\n var spantemp = selTemp.childNodes[i];\n\n if (spantemp.tagName) {\n opt = document.createElement(\"OPTION\")\n\n if (document.all) { //IE\n objeto.add(opt)\n } else {\n objeto.appendChild(opt)\n }\n\n //getting attributes\n for ( var j = 0; j < spantemp.attributes.length; j++) {\n var attrName = spantemp.attributes[j].nodeName;\n var attrVal = spantemp.attributes[j].nodeValue;\n if (attrVal) {\n try {\n opt.setAttribute(attrName, attrVal);\n opt.setAttributeNode(spantemp.attributes[j]\n .cloneNode(true));\n } catch (e) {\n }\n }\n }\n //getting styles\n if (spantemp.style) {\n for ( var y in spantemp.style) {\n try {\n opt.style[y] = spantemp.style[y];\n } catch (e) {\n }\n }\n }\n //value and text\n opt.value = spantemp.getAttribute(\"value\")\n opt.text = spantemp.innerHTML\n //IE\n opt.selected = spantemp.getAttribute('selected');\n opt.className = spantemp.className;\n }\n }\n document.body.removeChild(selTemp)\n selTemp = null\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_readQuadPunctuation` reads punctuation after a quad
_readQuadPunctuation(token) { if (token.type !== '.') return this._error('Expected dot to follow quad', token); return this._readInTopContext; }
[ "function isPunctuation(input){\n\t\tvar lastChar = input.charAt(input.length-1);\n\t\tif((lastChar == ',') || (lastChar == '.') || (lastChar == ';')|| \n\t\t\t(lastChar == '!') || (lastChar == '?') || (lastChar == ':')){\n\t\t\treturn true;\t\t\n\t\t}\n\t\treturn false;\n\t}", "function has(w) {\n if (w.includes('\\'')) return ('\\'');\n if (w.includes(',')) return (',');\n if (w.includes('.')) return ('.');\n if (w.includes('?')) return ('?');\n if (w.includes('!')) return ('!');\n if (w.includes(';')) return (';');\n if (w.includes(',')) return (',');\n if (w.includes(':')) return (':');\n\n return \"\"; //no punctuation found\n}", "function setPunctuation(punct) {\n const punc = punct.toLowerCase();\n if (punc === \"true\") {\n punctuation = true;\n } else if (punc === \"false\") {\n punctuation = false;\n }\n }", "function isPolygram(word) {\n if (word.length % 2) return \"\";\n\n const half = word.slice(0, word.length / 2);\n \n if ([...half].every(w => w === half[0])) return \"\";\n \n return half;\n}", "function process_bracketed_text(words) {\n // If the first word (other than null) is not |, or if any other word is,\n // that's a problem.\n if (words[1] !== '|') {\n throw new Error(\"Sentences should begin with the start character ('|').\");\n }\n if (words.slice(2).indexOf('|') !== -1) {\n throw new Error(\"Sentences should only use '|' at the start.\");\n }\n // We create a sentence from the words.\n var sentence = new Sentence(words);\n // We do some logs for debugging purposes.\n console.log(JSON.stringify(sentence));\n console.log(JSON.stringify(sentence.words.join(' ')));\n // We declare sentence.indices_to_clause_regions as an empty dictionary.\n sentence.indices_to_clause_regions = {};\n // We declare words_and_indices as a dictionary containing the words and indices information.\n // slice is used to get rid of the first (null) entry.\n var words_and_indices = words.map(function (x, y) {return {'word': x, 'index': y}}).slice(1);\n // c is the result of process_bracketed_text_coordination.\n // It will be a list of the main clauses.\n var c = process_bracketed_text_coordination(sentence, words_and_indices);\n // We make all our main clauses main, and add a main clause tag to each of them.\n c.forEach(function (x) {\n x.make_clause(\"main clause\");\n x.add_tag(new SingleRegionTag(\"main clause\"))\n });\n // We return the sentence object.\n return sentence\n}", "function Phrase(options) {\r\n\r\n\tthis.lire = function () {\r\n\t\treturn this.corps;\r\n\t};\r\n\r\n\tthis.__assembler = function (texte) {\r\n\t\tvar resultat = texte.join(\" \");\r\n\t\tvar point = probaSwitch(Grimoire.recupererListe(\"PF\"), this.PROBA_POINT_FINAL);\r\n\t\tresultat = resultat.replace(/ \\,/g, \",\");\r\n\t\tresultat = resultat.replace(/' /g, \"'\");\r\n\t\tresultat = resultat.replace(/à les /g, \"aux \");\r\n\t\tresultat = resultat.replace(/à le /g, \"au \");\r\n\t\tresultat = resultat.replace(/ de ([aeiouhéèêàùäëïöü])/gi, \" d'$1\");\r\n\t\tresultat = resultat.replace(/ de les /g, \" des \");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([aeiouéèêàîïùyh])/gi, \" d'$2\");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([^aeiouéèêàîïùyh])/gi, \" de $2\");\r\n\t\tresultat = resultat.replace(/ de d'/g, \" d'\");\r\n\t\tresultat = resultat.replace(/ de (le|du) /g, \" du \");\r\n\t\tresultat = resultat.replace(/^(.*)je ([aeiouéèêàîïùyh])/i, \"$1j'$2\");\r\n\t\tresultat = resultat.replace(/£/g, \"h\").replace(/µ/g, \"Y\");\r\n\t\tresultat = resultat.substr(0, 1).toUpperCase() + resultat.substr(1) + point;\r\n\t\treturn resultat;\r\n\t};\r\n\r\n\toptions || (options = {});\r\n\tthis.PROBA_POINT_FINAL = [8, 1, 1];\r\n\r\n\tthis.structure = options.memeStr || Grimoire.genererStructure();\r\n\tthis.mots = [];\r\n\r\n\tvar posVerbe = -1, posVerbe2 = -1, posModal = -1, posDe = -1, posQue = -1, posPR = -1;\r\n\tvar personne = 0, temps = -1;\r\n\tvar premierGN = false, advPost = false, flagNoNeg = false;\r\n\r\n\t/* --- BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tfor (var i = 0, iMax = this.structure.length; i < iMax; ++i) {\r\n\t\tif (this.structure[i].substr(0, 1) == \"§\") {\r\n\t\t\tvar litteral = this.structure[i].substr(1);\r\n\t\t\tif (litteral.indexOf(\"/\") > -1) {\r\n\t\t\t\tlitteral = litteral.split(\"/\")[(de(2) - 1)];\r\n\t\t\t}\r\n\t\t\tthis.mots.push(litteral);\r\n\t\t\tif (litteral == \"sans\") {\r\n\t\t\t\tflagNoNeg = true;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvar mot;\r\n\t\t\tif (this.structure[i] == \"GN\") {\r\n\t\t\t\tif (options.sujetChoisi && !premierGN) {\r\n\t\t\t\t\tmot = options.sujetChoisi;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\t\tmot = Generateur.groupeNominal(premierGN);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpremierGN = true;\r\n\t\t\t} else if (this.structure[i] == \"CO\") {\r\n\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\tmot = Generateur.complementObjet(personne);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t}\r\n\t\t\tvar posPersonne = mot.indexOf(\"@\");\r\n\t\t\tif (posPersonne > -1) {\r\n\t\t\t\tpersonne = (personne > 0) ? personne : parseInt(mot.substr(posPersonne + 1), 10);\r\n\t\t\t\tmot = mot.substr(0, posPersonne);\r\n\t\t\t}\r\n\t\t\tthis.mots.push(mot);\r\n\t\t}\r\n\t\tvar verbesNonMod = [\"VT\", \"VN\", \"VOA\", \"VOD\", \"VOI\", \"VTL\", \"VAV\", \"VET\", \"VOS\"];\r\n\t\tvar verbesMod = [\"VM\", \"VD\", \"VA\"];\r\n\t\tif (verbesNonMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tif (posVerbe > -1) {\r\n\t\t\t\tif (posModal > -1) {\r\n\t\t\t\t\tposVerbe2 = i;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tposModal = posVerbe;\r\n\t\t\t\t\tposVerbe = i;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tposVerbe = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (verbesMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tposModal = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"§que\") {\r\n\t\t\tposQue = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"CT\") {\r\n\t\t\tvar posTemps = this.mots[i].indexOf(\"€\");\r\n\t\t\tif (posTemps > -1) {\r\n\t\t\t\ttemps = parseInt(this.mots[i].substr(posTemps + 1), 10);\r\n\t\t\t\tthis.mots[i] = this.mots[i].substr(0, posTemps);\r\n\t\t\t}\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"AF\")) {\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t\twhile (this.mots[i].indexOf(\"+\") > -1) {\r\n\t\t\t\tvar posPlus = this.mots[i].indexOf(\"+\");\r\n\t\t\t\tvar fem = this.mots[i].charAt(posPlus + 1) == \"F\";\r\n\r\n\t\t\t\tvar nom, ok;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tok = true;\r\n\t\t\t\t\tnom = Generateur.GN.nomsCommuns.puiser();\r\n\t\t\t\t\tif (nom.indexOf(\"_\") > -1) {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"_\");\r\n\t\t\t\t\t\tvar genre = nom.charAt(pos + 1);\r\n\t\t\t\t\t\tif (!fem && (genre == \"F\") || (fem && genre == \"H\")) {\r\n\t\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tnom = nom.split(\"_\")[0];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"%\");\r\n\t\t\t\t\t\tif (nom.substr(pos + 1).length == 1) {\r\n\t\t\t\t\t\t\tnom = nom.replace(/(.*)%e/, \"$1%$1e\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnom = nom.split(\"%\")[((fem) ? 1 : 0)];\r\n\t\t\t\t\t}\r\n\t\t\t\t} while ((!ok) || (nom === undefined));\r\n\t\t\t\tnom = Generateur.accordPluriel(nom, false);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\+[FH]/, nom);\r\n\t\t\t}\r\n\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"CT\") || (this.structure[i] == \"AF\")) {\r\n\t\t\tvar nombre;\r\n\t\t\twhile (this.mots[i].indexOf(\"&\") > -1) {\r\n\t\t\t\tnombre = de(10) + 1;\r\n\t\t\t\tif (this.mots[i].indexOf(\"&0\") > -1) {\r\n\t\t\t\t\tnombre = (nombre * 10) - 10;\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mots[i].indexOf(\"&00\") > -1) {\r\n\t\t\t\t\tnombre *= 10;\r\n\t\t\t\t}\r\n\t\t\t\tnombre = nombre.enLettres();\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/&(0){0,2}/, nombre);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.structure[i].split(\"_\")[0] == \"PR\") {\r\n\t\t\tposPR = i;\r\n\t\t}\r\n\t}\r\n\t/* --- FIN DE LA BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tif (temps == -1)\r\n\t\ttemps = (de(2) > 1) ? 2 : de(3);\r\n\r\n\tif (posQue > -1) {\r\n\t\tthis.mots[posQue] = (this.mots[posQue + 1].voyelle()) ? \"qu'\" : \"que\";\r\n\t}\r\n\tif (posPR > -1) {\r\n\t\tvar tPers = 2;\r\n\t\tif ((/^s(\\'|e )/).test(this.mots[posPR])) {\r\n\t\t\ttPers = [2, personne];\r\n\t\t}\r\n\t\tvar neg1 = \"\", neg2 = \"\";\r\n\t\tif ((!flagNoNeg) && (de(9) > 8)) {\r\n\t\t\tneg1 = (this.mots[posPR].voyelle()) ? \"n'\" : \"ne \";\r\n\t\t\tneg2 = \" \" + probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t}\r\n\t\tthis.mots[posPR] = \"en \" + neg1 + Grimoire.conjuguer(this.mots[posPR], 4, tPers) + neg2;\r\n\t}\r\n\r\n\tif (posModal > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posModal], temps, personne);\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posModal] = baseVerbe;\r\n\r\n\t\tif (this.mots[posVerbe].indexOf(\"#\") > -1) {\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].split(\"#\")[0];\r\n\t\t}\r\n\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe])) {\r\n\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\tif ((this.mots[posVerbe].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t}\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].replace(/s(\\'|e )/, pr);\r\n\t\t}\r\n\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tthis.mots[posVerbe] = \"ne \" + neg2 + \" \" + this.mots[posVerbe];\r\n\t\t}\r\n\t\tif (posVerbe2 > -1) {\r\n\t\t\tif (this.mots[posVerbe2].indexOf(\"#\") > -1) {\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].split(\"#\")[0];\r\n\t\t\t}\r\n\t\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe2])) {\r\n\t\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\t\tif ((this.mots[posVerbe2].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].replace(/s(\\'|e )/, pr);\r\n\t\t\t}\r\n\t\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\t\tthis.mots[posVerbe2] = \"ne \" + neg2 + \" \" + this.mots[posVerbe2];\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (posVerbe > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posVerbe], temps, personne);\r\n\t\tif (baseVerbe === undefined)\r\n\t\t\treturn new Phrase(options);// et sa copine\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posVerbe] = baseVerbe;\r\n\t}\r\n\r\n\tthis.corps = this.__assembler(this.mots);\r\n\treturn this;\r\n}", "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}", "phrase(phrase) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase))\n return map[phrase];\n return phrase;\n }", "function isCharacterPunctuation(asciiValue) {\n let isPunctuation = false;\n switch (asciiValue) {\n // Space\n case 32:\n isPunctuation = true;\n break;\n // Exclamation mark\n case 33:\n isPunctuation = true;\n break;\n // Quotation mark\n case 34:\n isPunctuation = true;\n break;\n // Apostrophe mark\n case 39:\n isPunctuation = true;\n break;\n // Open parentheses\n case 40:\n isPunctuation = true;\n break;\n // Close parentheses\n case 41:\n isPunctuation = true;\n break;\n // Comma\n case 44:\n isPunctuation = true;\n break;\n // Hyphen\n case 45:\n isPunctuation = true;\n break;\n // Period\n case 46:\n isPunctuation = true;\n break;\n // Forward slash\n case 47:\n isPunctuation = true;\n break;\n // Colon\n case 58:\n isPunctuation = true;\n break;\n // Semicolon\n case 59:\n isPunctuation = true;\n break;\n // Question markk\n case 63:\n isPunctuation = true;\n break;\n default:\n isPunctuation = false;\n break;\n }\n return isPunctuation;\n }", "function WordParser () {}", "_addQuad(s, p, o, g) {\n this.quads.push(N3.DataFactory.quad(s, p, o, g));\n }", "function writeWordsToReadingpad(){\n\n\t\t// put phonemes into div types\n\t\tvar word = words[0];\n\t\tconsole.log(word);\n\t\tvar numberOfPhonemes = word.phonemes.length;\n\t\tconsole.log(numberOfPhonemes);\n\t\t// for(var i=0; i < numberOfPhonemes; i++)\n\n\t\t// iterate over phonemes\n\t\t// if phoneme.phoneme.length <2 put it in a single letter div\n\t\t// if phoneme.phoneme.length === 2 put it in a digraph div\n\t\t// if phoneme.phoneme.length === 3 put it in a trigraph div\n\n\t\t// add the appropriate sound button to the div type\n\n\t\t// Connect the sound button to the appropriate phoneme sound\n\n\t\t// Position the div appropriately in relation to the reading pad\n\t\t\n\n\t\t\n\t\tvar i = 0;\n\t\tvar length = correctWord.length;\n\t\t// need logic to position word in the middle of the reading pad\n\t\t\n\t\t\t// if (length === 1){\n\t\t\t// \ti = 3;\n\t\t\t// }\n\n\t\t\t// // elsif (length === 2){\n\t\t\t// i = 2;\n\t\t\t// }\n\t\t\t// // elsif (length === 3){\n\t\t\t// i = 1;\n\t\t\t// }\n\n\t\t\t// // elsif (length === 4){\n\t\t\t// i = 1;\n\t\t\t// }\n\n\t\t//places each phoneme in on a reading pad block in ascending order\n\n\n\n\n\n\t\tfor (i; i<length; i++){\n\t\t\tvar p = i+1;\n\n\t\t\t$('#word-container-'+ p +'p').text(correctWord[i]);\t\n\t\t}\n\t}", "function setUpBetterPunctuation() {\n var els = document.querySelectorAll('h1, h2, h3, div')\n\n els.forEach(function(el) {\n var html = el.innerHTML\n\n if ((!el.querySelectorAll('*:not(br)').length) && \n (!el.classList.contains('no-smart-typography'))) {\n var html = el.innerHTML\n\n html = html.replace(/,/g, '<span class=\"comma\">\\'</span>')\n html = html.replace(/\\./g, '<span class=\"full-stop\">.</span>')\n html = html.replace(/…/g, '<span class=\"ellipsis\">...</span>')\n html = html.replace(/’/g, '\\'')\n\n el.innerHTML = html\n }\n })\n}", "function addPunctuations() {\n if (currentWordsList[0] !== undefined) {\n // Capitalize first word\n currentWordsList[0] =\n currentWordsList[0][0].toUpperCase() + currentWordsList[0].slice(1);\n\n // Add comma, fullstop, question mark, exclamation mark, semicolon. Capitalize the next word\n for (let i = 0; i < currentWordsList.length; i++) {\n const ran = Math.random();\n\n if (i < currentWordsList.length - 1) {\n if (ran < 0.03) {\n currentWordsList[i] += \",\";\n } else if (ran < 0.05) {\n currentWordsList[i] += \".\";\n\n currentWordsList[i + 1] =\n currentWordsList[i + 1][0].toUpperCase() +\n currentWordsList[i + 1].slice(1);\n } else if (ran < 0.06) {\n currentWordsList[i] += \"?\";\n\n currentWordsList[i + 1] =\n currentWordsList[i + 1][0].toUpperCase() +\n currentWordsList[i + 1].slice(1);\n } else if (ran < 0.07) {\n currentWordsList[i] += \"!\";\n\n currentWordsList[i + 1] =\n currentWordsList[i + 1][0].toUpperCase() +\n currentWordsList[i + 1].slice(1);\n } else if (ran < 0.08) {\n currentWordsList[i] += \";\";\n }\n }\n }\n currentWordsList[currentWordsList.length - 1] += \".\";\n }\n }", "phrase(phrase) {\n for (let map of this.facet(dist_EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase))\n return map[phrase];\n return phrase;\n }", "greek(s) {\n return (s.indexOf(\"ph\") > 0 || s.indexOf('y') > 0 && s.endsWith(\"nges\"));\n }", "function songDecoder(song) {\n\n //split input by WUB\n let words = song.split(\"WUB\");\n\n //store result in a string\n let result = '';\n\n //loop through array\n words.forEach(element => {\n\n //if element is not blank add to result with a space\n if (element !== '') {\n result += element + ' ';\n }\n\n });\n\n //we have to remove the extra space from the end of the string\n return result.trim(); //alternatives: str.substring(0, str.length - 1); or str.slice(0, -1);\n\n\n}", "function moveToNextPhrase() {\n currentPhraseIndex++;\n if (currentPhraseIndex < phrases.length) {\n document.getElementById('current-phrase').textContent = phrases[currentPhraseIndex];\n } else {\n document.getElementById('quiz-status').textContent = 'Quiz completed! Well done!';\n SpeechRecognitionService.stop();\n document.getElementById('stop-recording-btn').disabled = true;\n document.getElementById('start-recording-btn').disabled = true;\n }\n}", "function removePunctuation(str){\n return str.replace(/[.,!?;:()]/g,'')\n}", "function txtNoPunctuation (txt){\n let strA = txt.toLowerCase();\n let strB = strA.replace(/[+]/g, \" \");\n let strC = strB.replace(/[-]/g, \"\");\n let strD = strC.replace(/[:;.,!@#$%^&*()''\"\"]/g, \"\");\n return strD;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function applies the strategy you define in getstrategy(n): DON'T CHANGE
function applystrategy(hand, n) { var strat = getstrategy(n); return strat(hand); }
[ "function setStrategy(preferredStrategy) {\n strategy = preferredStrategy;\n }", "async strategies (obj, args, context, info) {\n let strategies = await WIKI.models.authentication.getStrategies(args.isEnabled)\n strategies = strategies.map(stg => {\n const strategyInfo = _.find(WIKI.data.authentication, ['key', stg.key]) || {}\n return {\n ...strategyInfo,\n ...stg,\n config: _.sortBy(_.transform(stg.config, (res, value, key) => {\n const configData = _.get(strategyInfo.props, key, false)\n if (configData) {\n res.push({\n key,\n value: JSON.stringify({\n ...configData,\n value\n })\n })\n }\n }, []), 'key')\n }\n })\n return strategies\n }", "function StrategyRunner(strategy) {\n // this.strategy = strategy;\n\n // NOTE: Any possible exception thrown by strategy must be catched and\n // saved under this.last_error\n // See VMStrategyRunner as example below\n}", "function getStrategyPositionTable() {\n /**\n * TODO: need to be tuned.\n */\n\n return {\n 'P': [\n 0, 0, 0, 0, 0, 0, 0, 0,\n 5, 10, 10,-25,-25, 10, 10, 5,\n 5, -5,-10, 0, 0,-10, -5, 5,\n 0, 0, 0, 25, 25, 0, 0, 0,\n 5, 5, 10, 27, 27, 10, 5, 5,\n 10, 10, 20, 30, 30, 20, 10, 10,\n 30, 30, 30, 40, 40, 30, 30, 30,\n 50, 50, 50, 50, 50, 50, 50, 50\n ],\n\n 'N': [\n -50,-40,-30,-30,-30,-30,-40,-50,\n -40,-20, 0, 5, 5, 0,-20,-40,\n -30, 5, 10, 15, 15, 10, 5,-30,\n -30, 0, 15, 20, 20, 15, 0,-30,\n -30, 5, 15, 20, 20, 15, 5,-30,\n -30, 0, 10, 15, 15, 10, 0,-30,\n -40,-20, 0, 0, 0, 0,-20,-40,\n -50,-40,-20,-30,-30,-20,-40,-50\n ],\n\n 'B': [\n -20,-10,-40,-10,-10,-40,-10,-20\n -10, 5, 0, 0, 0, 0, 5,-10,\n -10, 10, 10, 10, 10, 10, 10,-10,\n -10, 0, 10, 10, 10, 10, 0,-10,\n -10, 5, 5, 10, 10, 5, 5,-10,\n -10, 0, 5, 10, 10, 5, 0,-10,\n -10, 0, 0, 0, 0, 0, 0,-10,\n -20,-10,-10,-10,-10,-10,-10,-20\n ],\n\n 'R': [\n 20, 10, 10, 10, 10, 10, 10, 20,\n 20, 0, 0, 0, 0, 0, 0, 20,\n 20, 0, -5,-10,-10, -5, 0, 20,\n 10, 0,-10,-15,-15,-10, 0, 10,\n 10, 0,-10,-15,-15,-10, 0, 10,\n 10, 0, -5,-10,-10, -5, 0, 10,\n 20, 0, 0, 0, 0, 0, 0, 20,\n 20, 20, 10, 10, 10, 10, 20, 20\n ],\n\n 'Q': [\n 30, 20, 20, 50, 50, 20, 20, 30,\n 20, 20, 10, 5, 5, 10, 20, 20,\n 20, 10, -5,-10,-10, -5, 10, 20,\n 30, 0,-15,-20,-20,-15, 0, 30,\n 30, 0,-15,-20,-20,-15, 0, 30,\n 20, 0,-10,-50,-50,-20, 0, 20,\n 20, 20, 0, 0, 0, 0, 20, 20,\n 30, 20, 20, 40, 40, 20, 20, 30\n ],\n\n 'K': [\n 20, 30, 10, 0, 0, 10, 30, 20,\n 20, 20, 0, 0, 0, 0, 20, 20,\n -10, -20, -20, -20, -20, -20, -20, -10,\n -20, -30, -30, -40, -40, -30, -30, -20,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30\n ]\n };\n}", "function setupStrategy (board) {\n return [5, 4, 3, 3, 2].map(function (size) {\n while (1) {\n var blocks = randomBlocks(board, size);\n if (fits(board, blocks)) {\n placeBlocks(board, blocks);\n return blocks;\n }\n }\n });\n\n function randomBlocks (board, size) {\n var blocks = [[\n _.random(size-1, board.length-1),\n _.random(board[0].length-1)\n ]];\n while (--size) {\n blocks.unshift([blocks[0][0]-1, blocks[0][1]]);\n }\n if (_.random(1)) {\n blocks = blocks.map(function (b) {\n return [b[1], b[0]];\n });\n }\n return blocks;\n }\n \n function fits (board, blocks) {\n return blocks.every(function (b) {\n return !board[b[0]][b[1]];\n });\n }\n \n function placeBlocks (board, blocks) {\n blocks.forEach(function (b) {\n board[b[0]][b[1]] = 1;\n });\n }\n }", "function setTransform(func, n) {\n if (n === undefined) { n = 1; }\n _func = func;\n _n = n;\n _apply();\n }", "changeRuleType(event, selectorNum) {\n var rulesets = this.state.rulesets\n\n var selectorParameters = rulesets[this.state.currentRuleset][selectorNum].parameters\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].rule = event.target.value\n\n if (event.target.value == \"Total\") { // Matches to the total rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"condition\": \"\",\n \"amount\": null,\n \"category\": \"\",\n \"for\": \"\"\n }\n \n } else if (event.target.value == \"Repeats\") { // Matches to the repeats rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"amount\": null,\n \"category\": \"\"\n }\n } else { // Matches to the filter rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"type\": \"\",\n \"filter\": \"\"\n }\n }\n\n this.setState({rulesets: rulesets}, () => {\n this.updateData()\n })\n }", "applyTropism() {\n this.tendTo(this.currentParams.tropism, this.currentParams.elasticity);\n }", "function setRuleType(x, n){\n\t\n\tswitch (x) {\n\t\tcase 1:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 2:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 3:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 4:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 5:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 6:\n\t}\n\t\n}", "get positionStrategy() {\n if (this._positionStrategy) {\n return this._positionStrategy;\n }\n if (!this.position) {\n return undefined;\n }\n const positionList = [...this.position];\n const positionStrategy = this._positionStrategy = [];\n while (positionList.length) {\n const position = positionList.shift();\n if (!position) {\n continue;\n }\n const strategy = position.split('-');\n if (!strategy[1]) {\n const defaultAlign = DEFAULT_ALIGN.get(strategy[0]);\n if (!defaultAlign) {\n throw new Error(`ef-overlay: incorrect position provided: ${strategy[0]}`);\n }\n strategy.push(defaultAlign);\n }\n positionStrategy.push(strategy);\n }\n return positionStrategy;\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 priority(){\r\n\r\n turn = 2;\r\n \r\n if(array_attack_StringList.length != 0){\r\n \r\n if(search_in_array('1_king_',array_attack_StringList) == 1){\r\n decide_attack('1_king_');\r\n }\r\n else if(search_in_array('2_king_',array_defence_StringList) == 1){\r\n decide_defence('2_king_');\r\n }\r\n else if(search_in_array('1queenn',array_attack_StringList) == 1){\r\n decide_attack('1queenn');\r\n }\r\n else if(search_in_array('2queenn',array_defence_StringList) == 1){\r\n \r\n decide_defence('2queenn');\r\n }\r\n else if(search_in_array('1eleph1',array_attack_StringList) == 1){\r\n decide_attack('1eleph1');\r\n }\r\n else if(search_in_array('2eleph1',array_defence_StringList) == 1){\r\n decide_defence('2eleph1');\r\n }\r\n else if(search_in_array('1eleph2',array_attack_StringList) == 1){\r\n decide_attack('1eleph2');\r\n }\r\n else if(search_in_array('2eleph2',array_defence_StringList) == 1){\r\n decide_defence('2eleph2');\r\n }\r\n else if(search_in_array('1horse1',array_attack_StringList) == 1){\r\n decide_attack('1horse1');\r\n }\r\n else if(search_in_array('2horse1',array_defence_StringList) == 1){\r\n decide_defence('2horse1');\r\n }\r\n else if(search_in_array('1horse2',array_attack_StringList) == 1){\r\n decide_attack('1horse2');\r\n }\r\n else if(search_in_array('2horse2',array_defence_StringList) == 1){\r\n decide_defence('2horse2');\r\n }\r\n else if(search_in_array('1camel1',array_attack_StringList) == 1){\r\n \r\n decide_attack('1camel1');\r\n }\r\n else if(search_in_array('2camel1',array_defence_StringList) == 1){\r\n decide_defence('2camel1');\r\n }\r\n else if(search_in_array('1camel2',array_attack_StringList) == 1){\r\n decide_attack('1camel2');\r\n }\r\n else if(search_in_array('2camel2',array_defence_StringList) == 1){\r\n decide_defence('2camel2');\r\n }\r\n else if(search_in_array('1slave1',array_attack_StringList) == 1){\r\n \r\n decide_attack('1slave1');\r\n }\r\n else if(search_in_array('2slave1',array_defence_StringList) == 1){\r\n decide_defence('2slave1');\r\n }\r\n else if(search_in_array('1slave2',array_attack_StringList) == 1){\r\n decide_attack('1slave2');\r\n }\r\n else if(search_in_array('2slave2',array_defence_StringList) == 1){\r\n decide_defence('2slave2');\r\n }\r\n else if(search_in_array('1slave3',array_attack_StringList) == 1){\r\n decide_attack('1slave3');\r\n }\r\n else if(search_in_array('2slave3',array_defence_StringList) == 1){\r\n decide_defence('2slave3');\r\n }\r\n else if(search_in_array('1slave4',array_attack_StringList) == 1){\r\n decide_attack('1slave4');\r\n }\r\n else if(search_in_array('2slave4',array_defence_StringList) == 1){\r\n decide_defence('2slave4');\r\n }\r\n else if(search_in_array('1slave5',array_attack_StringList) == 1){\r\n decide_attack('1slave5');\r\n }\r\n else if(search_in_array('2slave5',array_defence_StringList) == 1){\r\n \r\n decide_defence('2slave5');\r\n }\r\n\r\n else if(search_in_array('1slave6',array_attack_StringList) == 1){\r\n decide_attack('1slave6');\r\n }\r\n else if(search_in_array('2slave6',array_defence_StringList) == 1){\r\n decide_defence('2slave6');\r\n }\r\n else if(search_in_array('1slave7',array_attack_StringList) == 1){\r\n \r\n decide_attack('1slave7');\r\n }\r\n else if(search_in_array('2slave7',array_defence_StringList) == 1){\r\n\r\n decide_defence('2slave7');\r\n }\r\n else if(search_in_array('1slave8',array_attack_StringList) == 1){\r\n decide_attack('1slave8');\r\n }\r\n else if(search_in_array('2slave8',array_defence_StringList) == 1){\r\n decide_defence('2slave8');\r\n }\r\n else{\r\n \r\n decide_else('_______');\r\n }\r\n }\r\n else{\r\n \r\n document.getElementById(\"won\").style.zIndex = 1;\r\n disable_all();\r\n }\r\n}", "function apply() {\n _apply();\n }", "switchAlgoMode(e){\n this.setState({algoMode: parseInt(e.target.value)});\n this.resetHull();\n }", "function Context(strategy) {\n this.strategy = strategy;\n }", "function adjustBet(hilo, baseBet, decks){\r\n var weight = decks >= 6? 2: 1;\r\n var weight = Math.floor(decks/2);\r\n if (this.runningBankroll>0){\r\n if (this.winScore()>=0){\r\n if (hilo >= 8*weight) this.hand.objHands[0].bet = 4*baseBet;\r\n else if (hilo >= 6*weight) this.hand.objHands[0].bet = 3*baseBet;\r\n else if (hilo >= 4*weight) this.hand.objHands[0].bet = 2*baseBet;\r\n //else if (hilo >=2) this.bet = 2*baseBet\r\n }\r\n } else this.bet = 0;\r\n //console.log(this.bet);\r\n}", "getViewStrategy(value: any): ViewStrategy {\n if (!value) {\n return null;\n }\n\n if (typeof value === 'object' && 'getViewStrategy' in value) {\n let origin = Origin.get(value.constructor);\n\n value = value.getViewStrategy();\n\n if (typeof value === 'string') {\n value = new RelativeViewStrategy(value);\n }\n\n viewStrategy.assert(value);\n\n if (origin.moduleId) {\n value.makeRelativeTo(origin.moduleId);\n }\n\n return value;\n }\n\n if (typeof value === 'string') {\n value = new RelativeViewStrategy(value);\n }\n\n if (viewStrategy.validate(value)) {\n return value;\n }\n\n if (typeof value !== 'function') {\n value = value.constructor;\n }\n\n let origin = Origin.get(value);\n let strategy = metadata.get(ViewLocator.viewStrategyMetadataKey, value);\n\n if (!strategy) {\n if (!origin.moduleId) {\n throw new Error('Cannot determine default view strategy for object.', value);\n }\n\n strategy = this.createFallbackViewStrategy(origin);\n } else if (origin.moduleId) {\n strategy.moduleId = origin.moduleId;\n }\n\n return strategy;\n }", "function findBestMode(endPoints,\n\t\t\t\t\t\t\t\t\t\t enabledModes,\n\t\t\t\t\t\t\t\t\t\t optimizationParameter,\n\t\t\t\t\t\t\t\t\t\t optimizationDirection,\n callback)\n{\n apis.getWalkingDirections(endPoints, function(walkingObject){\n console.log(\"Got walking directions...\");\n apis.getDrivingDirections(endPoints, function(drivingObject){\n console.log(\"Got driving directions...\");\n apis.getBikingDirections(endPoints, function(bikingObject){\n console.log(\"Got biking directions. Done.\");\n\n var modeResults = {};\n\n for(var i = 0; i < enabledModes.length; i++){\n var object = {};\n\n if(modes.modeList[enabledModes[i]].baseMode == 'walking') {\n object = JSON.parse(JSON.stringify(walkingObject));\n }\n else if(modes.modeList[enabledModes[i]].baseMode == 'driving') {\n object = JSON.parse(JSON.stringify(drivingObject));\n }else if(modes.modeList[enabledModes[i]].baseMode == 'biking'){\n object = JSON.parse(JSON.stringify(bikingObject));\n }else {\n\n\n object = {\"total_time\":enabledModes[i][\"time\"],\"total_energy\":enabledModes[i][\"energy\"],\"total_style\":enabledModes[i][\"stylepoints\"],\"directions\":enabledModes[i][\"steps_list\"]};\n }\n var result = modes.modeList[enabledModes[i]].eval(object);\n var modeName = modes.modeList[enabledModes[i]].displayName;\n modeResults[modeName] = result;\n }\n\n\t\t\t\tvar unsorted_parameters = [];\n\t\t\t\tvar unsorted_names = [];\n\t\t\t\tfor (x in modeResults) { //break modeResults into two parts\n\t\t\t\t unsorted_names.push(x);\n\t \t \t\tunsorted_parameters.push(modeResults[x][optimizationParameter]);\n\t\t\t\t}\n\n //sort the parameters\n\t\t\t\tvar sorted_parameters = JSON.parse(JSON.stringify(unsorted_parameters)).sort(function(a,b) { return a - b; });\n\t\t\t\tif (optimizationDirection === \"down\"){\n\t\t\t\t\tsorted_parameters.reverse();\n\t\t\t\t}\n\n\n\t\t\t\tvar sorted_names = [];\n\n //make sure the names are also sorted\n\t\t\t for(var i = 0; i < sorted_parameters.length; i++){\n\t\t\t\t\tfor(var j = 0; j < sorted_parameters.length; j++){\n\n\t\t\t\t\t\tif ((unsorted_parameters[j] === sorted_parameters[i]) && (sorted_names.indexOf(unsorted_names[j]) === -1)) {\n\t\t\t\t\t\t\tsorted_names.push(unsorted_names[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n //recombine sorted_names;\n\t\t\t\tvar newModeResults = {};\n\t\t\t\tfor(var i= 0; i < sorted_parameters.length; i++){\n\t\t\t\t\tnewModeResults[sorted_names[i]] = modeResults[sorted_names[i]];\n\t\t\t\t}\n\n callback(modeResults);\n });\n });\n });\n}", "function adjustTask( task, state, handicap, highesthandicap ) {\n //\n if( state.adjustments ) {\n return state.adjustments;\n }\n\n // Make a new array for it\n var newTask = state.adjustments = _clonedeep(task);\n\n // reduction amount (%ish)\n var maxhtaskLength = task.distance / (highesthandicap/100);\n var mytaskLength = maxhtaskLength * (handicap/100);\n var mydifference = task.distance - mytaskLength;\n var spread = 2*(newTask.legs.length-1)+2; // how many points we can spread over\n var amount = mydifference/spread;\n\n // how far we need to move the radius in to achieve this reduction\n var adjustment = Math.sqrt( 2*(amount*amount) );\n\n // Now copy over the points reducing all symmetric\n newTask.legs.slice(1,newTask.legs.length-1).forEach( (leg) => {\n if( leg.type == 'sector' && leg.direction == 'symmetrical') {\n leg.r2 += adjustment;\n }\n else {\n console.log( \"Invalid handicap distance task: \"+leg.toString() );\n }\n });\n\n // For scoring this handicap we need to adjust our task distance as well\n newTask.distance = mytaskLength;\n return newTask;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change target url of letsplaybtn to a url of the selected team
function selectteam(targeturl){ //get target from link in lets play button var target = document.getElementById("lets-play-btn").getAttribute("href"); //if team is not set already add it to target url if (target.indexOf("&team=") == -1){ document.getElementById("lets-play-btn").setAttribute("href", (target + "&team=" + targeturl)); } else { target = target.substring(0, target.indexOf("&team=")); //cut off unnecessary attributes document.getElementById("lets-play-btn").setAttribute("href", (target + "&team=" + targeturl)); } }
[ "function selectgame(targeturl){\n //Before selecting the game we need to know which teams are going to play it, and show them in the modal\n //get all teams from Database and make the right buttons out of them, eventually in the future different games need different teams\n db_call('get','all_teams',getteams);\n\n //while teambuttons are being created, change the targeturl of button\n //get current target from link in lets play button\n var target = document.getElementById(\"lets-play-btn\").getAttribute(\"href\");\n\n //if game is not set already add it to target url\n if (target.indexOf(\"?name=\") == -1){\n document.getElementById(\"lets-play-btn\").setAttribute(\"href\", (target + \"?name=\" + targeturl));\n }\n else\n {\n target = target.substring(0, target.indexOf(\"?name=\")); //cut off unnecessary attributes\n document.getElementById(\"lets-play-btn\").setAttribute(\"href\", (target + \"?name=\" + targeturl));\n }\n}", "function OnJoinTeamPressed() {\n // Get the team id asscociated with the team button that was pressed\n var teamId = $.GetContextPanel().GetAttributeInt(\"team_id\", -1);\n\n // Request to join the team of the button that was pressed\n Game.PlayerJoinTeam(teamId);\n}", "function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }", "previewTargetSet(event, data) {\n gamePreview.previewTarget = data.type;\n\n switch (data.type) {\n case 'deploy':\n const deployPath = join(projectInfo.location, 'deploy');\n // Make sure the deploy folder exists because attempting to host it.\n if (!existsSync(deployPath)) {\n dialog.showErrorBox(\n 'Deploy folder not found.',\n `Could not find a deploy folder in:\\n${projectInfo.location}`\n );\n return;\n }\n gamePreview.previewURL = `file://${deployPath}`;\n break;\n\n case 'url':\n if (data.url.indexOf('http:') === -1 && data.url.indexOf('https:') === -1) {\n data.url = `http://${data.url}`;\n }\n gamePreview.previewURL = data.url;\n break;\n }\n\n this.window.webContents.send(EVENTS.NAVIGATE, 'preview');\n }", "function updateTeamDevPlan(url) {\n updateTeam({id: tid, dev_plan: url}).then(function (data) {\n if (data.error) {\n oh.comm.alert('错误', data.error.friendly_message);\n } else {\n $('#projectPlanModal').modal('hide');\n $('#dev_plan_span').text('上传文件');\n $('#dev_plan_submit').text('确定');\n enableItems(['#dev_plan_input', '#dev_plan_btn', '#dev_plan_submit', '#dev_plan_cancel']);\n var p = $('#plan');\n p.attr({src: 'https://view.officeapps.live.com/op/embed.aspx?src=' +\n encodeURIComponent(url)}).removeClass('hide');\n oh.comm.alert(\"提示\", \"设置成功!\");\n }\n });\n }", "function showTeam(e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: e.target.id,\n success: (response) => {\n let teamObj = new Team(\n response.data.id,\n response.data.attributes.name,\n response.data.attributes.hq,\n response.data.attributes['image-url']\n )\n let newDiv = createNewDiv(\"team_page\")\n let template = Handlebars.compile(document.getElementById('team-show-template').innerHTML)\n let team = template(teamObj)\n newDiv.innerHTML += team\n loadTeamShowLinks();\n }\n });\n}", "function goToTeamPoints(){\n clientValuesFactory.setActiveWindow(windowViews.teamPoints);\n }", "function updateUrls(){\n\t\tchampionUrl = gifArray[championIndex];\n\t\tchallengerUrl = gifArray[challengerIndex];\n\t\t$('#championButton').attr('href', championUrl);\n\t\t$('#challengerButton').attr('href', challengerUrl);\n\t}", "function play_as_team(){\n var teamname = findGetParameter(\"team\"); //get parameter team\n team = teamname; //save teamname in global variable\n document.getElementById(\"team_name\").innerHTML = teamname;\n return team; //return team if needed later\n}", "function setRocketOnTeamPage(){\n\tlet rocketCurrentBlockTeamPage = document.querySelector(\"#teamChoice .rocket.current>:nth-child(2)\");\n\trocketCurrentBlockTeamPage.innerHTML=rocketCurrent.stringCurent(rocketCurrentBlockTeamPage);\n}", "function updateURL() {\n const URLelement = elements.get(\"title\").querySelector(\"a\");\n switch (URLelement) {\n case null:\n currentURL = undefined;\n break;\n default:\n const id = URLelement.href.replace(/[^0-9]/g, \"\");\n currentURL = `https://tidal.com/browse/track/${id}`;\n break;\n }\n}", "function checkingTeamMate() {\n if (globalURL.indexOf(\"team#t1\") > -1) {\n allTeamMates[0].scrollIntoView();\n } else if (globalURL.indexOf(\"team#t2\") > -1) {\n allTeamMates[1].scrollIntoView();\n } else if (globalURL.indexOf(\"team#t3\") > -1) {\n allTeamMates[2].scrollIntoView();\n }\n }", "function navigate(url) {\n $('#location').val(url);\n $('#frame').attr('src', url);\n }", "function updateBoards(selectedTarget) {\n let dropdown = document.querySelector('#target > .dropdown-menu');\n dropdown.innerHTML = '';\n for (let name in boards) {\n let board = boards[name];\n let item = document.createElement('a');\n item.textContent = board.humanName;\n item.classList.add('dropdown-item');\n if (name == selectedTarget) {\n item.classList.add('active');\n }\n item.setAttribute('href', '');\n item.dataset.name = name;\n dropdown.appendChild(item);\n }\n for (let item of document.querySelectorAll('#target > .dropdown-menu > .dropdown-item')) {\n item.addEventListener('click', (e) => {\n e.preventDefault();\n let boardConfig = boards[item.dataset.name];\n document.querySelector('#target > button').textContent = boardConfig.humanName;\n updateBoards(boardConfig.name);\n setTarget(boardConfig.name);\n });\n }\n}", "function selectTeam(team) {\n selectedTeam = team;\n team.classList.add(\"select\");\n\n const opponent = team == teamA ? teamB : teamA;\n if (opponent.classList.contains(\"select\")) {\n opponent.classList.remove(\"select\");\n }\n}", "_changeTarget() {\n this._targetPlanet =\n this._targetPlanet === this._redBigPlanet\n ? this._blueBigPlanet\n : this._redBigPlanet;\n }", "function _openYoutube(){\n Linking.openURL(songData.sections[2].youtubeurl.actions[0].uri);\n }", "urlForLeaving() {\n return `/settings/${Spark.teamsPrefix}/${this.leavingTeam.id}/members/${this.user.id}`;\n }", "function goProjects()\n\t{\n\t\tif (window.location == \"https://www.jasonbergland.com/projects\")\n\t\t{\n\t\t\tlet projectsY = document.getElementById('projects').offsetTop; // returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent node. \n\t\t\twindow.scrollTo(0, projectsY);\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accumulates without regard to direction, does not look for phased registration names. Same as `accumulateDirectDispatchesSingle` but without requiring that the `dispatchMarker` be the same as the dispatched ID.
function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } }
[ "function accumulator(xf) {\n function xformed(source, additional) {\n // Return a new accumulatable object who's accumulate method transforms the `next`\n // accumulating function.\n return accumulatable(function accumulateXform(next, initial) {\n // `next` is the accumulating function we are transforming. \n accumulate(source, function nextSource(accumulated, item) {\n // We are essentially wrapping next with `xf` provided the `item` is\n // not `end`.\n return item === end ? next(accumulated, item) :\n xf(additional, next, accumulated, item);\n }, initial);\n });\n }\n\n return xformed;\n}", "_dispatchEvents() {\n //todo: this doesnt let us specify order that events are disptached\n //so we will probably have to check each one\n //info here: https://stackoverflow.com/a/37694450/10232\n for (let handler of this._eventHandlers.values()) {\n handler.dispatch();\n }\n }", "_dispatch(event, ...args) {\n const handlers = this._handlers && this._handlers[event];\n if (!handlers) return;\n handlers.forEach(func => {\n func.call(null, ...args);\n });\n }", "function mapActionCreatorsToProps(dispatch) {\n return bindActionCreators({}, dispatch)\n}", "function redirecting_dispatch(dispatch, result)\n{\n\treturn (event) =>\n\t{\n\t\tswitch (event.type)\n\t\t{\n\t\t\t// In case of navigation from @preload()\n\t\t\tcase Preload:\n\t\t\t\t// `throw`s a special `Error` on server side\n\t\t\t\treturn result.redirect = location_url(event.location)\n\t\t\n\t\t\tdefault:\n\t\t\t\t// Proceed with the original\n\t\t\t\treturn dispatch(event)\n\t\t}\n\t}\n}", "findForcedReduction() {\n let { parser } = this.p,\n seen = []\n let explore = (state, depth) => {\n if (seen.includes(state)) return\n seen.push(state)\n return parser.allActions(state, (action) => {\n if (\n action &\n (262144 /* Action.StayFlag */ | 131072) /* Action.GotoFlag */\n );\n else if (action & 65536 /* Action.ReduceFlag */) {\n let rDepth = (action >> 19) /* Action.ReduceDepthShift */ - depth\n if (rDepth > 1) {\n let term = action & 65535 /* Action.ValueMask */,\n target = this.stack.length - rDepth * 3\n if (\n target >= 0 &&\n parser.getGoto(this.stack[target], term, false) >= 0\n )\n return (\n (rDepth << 19) /* Action.ReduceDepthShift */ |\n 65536 /* Action.ReduceFlag */ |\n term\n )\n }\n } else {\n let found = explore(action, depth + 1)\n if (found != null) return found\n }\n })\n }\n return explore(this.state, 0)\n }", "function incr(type, target) {\n results[type] = results[type] || {};\n results[type][target] = results[type][target] || 0;\n results[type][target]++;\n }", "function mappedReducer(reducer, child) {\n var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n _ref3$selectors = _ref3.selectors,\n selectors = _ref3$selectors === undefined ? {} : _ref3$selectors,\n _ref3$actions = _ref3.actions,\n actions = _ref3$actions === undefined ? {} : _ref3$actions;\n\n if (!(0, _lodash.isFunction)(reducer)) throw new Error('reslice.mappedReducer: expected reducer function, got: ' + (typeof reducer === 'undefined' ? 'undefined' : _typeof(reducer)));\n checkDistinctNames(selectors, actions);\n return { $$mapped: true, $$reducer: reducer, $$child: child, $$selectors: selectors, $$actions: actions };\n}", "function plus(){\n\tmemory[pointer]++;\n}", "dispatch(event) {\n for (let handler of this._handlers) {\n handler(event);\n }\n }", "dispatchJobs() {\n\t\tconst job = this.getJob(this.logKeys);\n\n\t\tif (!job) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.stat_collector) {\n\t\t\tthis.stat_collector.add(job.key)\n\t\t}\n\n\t\treturn job;\n\t}", "function traverse(uidPath, uid, memory, cls){\n\t\tcounter++;\n\t\tif(counter > 5000){\n\t\t\tconsole.log(uid);\n\t\t}\n\n\t\t//Get action object\n\t\tvar actionObj = tree.actions[uid];\n\n\t\t//evaluate each precondition for the action object\n\t\tvar trig = false;\n\t\tfor(var j = 0; j < actionObj.preconditions.length; j++){\n\t\t\tvar pre = actionObj.preconditions[j];\n\n\t\t\t//check to see if we get a false value\n\t\t\tif(!evaluatePrecondition(pre)){\n\t\t\t\ttrig = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t//If something doesn't pass, we return\n\t\tif(trig) return;\n\n\t\t//Now we can loop through each expression and evaluate them\n\t\tfor(var k = 0; k < actionObj.expressions.length; k++){\n\t\t\tvar exp = actionObj.expressions[k];\n\n\t\t\t//Evaluate the expression and write to the hypothetical memory\n\t\t\tevaluateExpression(exp, memory);\n\t\t}\n\n\t\t//We can assume now that we've succesfully passed the preconditions\n\t\t//This means we can add the action to the uid list\n\t\tuidPath.push(uid);\n\n\t\t//Now we have to see if there's a class for this action\n\t\t//If so, we add it to the list\n\t\tvar myClass = \"\";\n\t\tif(actionObj.cls != undefined && cls === \"\"){\n\t\t\tmyClass = actionObj.cls;\n\t\t} else {\n\t\t\tmyClass = cls;\n\t\t}\n\n\t\t//If the action is a leaf, push the uidPath on the available paths\n\t\t// and then push a new distance to conversation types on dists\n\t\tif(actionObj.isLeaf()){\n\t\t\tuids.push(uidPath);\n\n\t\t\tvar combineMem = Memory.prototype.combine(myCharacter.memBank.totalMemVec, memory, myCharacter.memBank.timeStep);\n\t\t\tvar normMem = combineMem.normalize();\n\t\t\t//Get the dot product\n\t\t\tvar dotproduct = normMem.dot(normalComposedMemory);\n\t\t\tvar dotproduct = Math.round(dotproduct * 1000) / 1000\n\t\t\t//Get the dist to the conversation type\n\t\t\tvar dist = Math.abs(that.conversationType - dotproduct);\n\n\t\t\tdists.push(dist);\n\n\t\t\tclasses.push(myClass);\n\n\t\t\treturn;\n\t\t}\n\n\t\t//Now we run the traversal algorithm for each child action\n\t\tfor(var i = 0; i < actionObj.children.length; i++){\n\t\t\tvar actionUID = actionObj.children[i];\n\t\t\tvar action = tree.actions[actionUID];\n\n\t\t\ttraverse(uidPath.slice(), actionUID, memory.copy(), myClass);\n\t\t}\n\t}", "function reductions(source, xf, initial) {\n var reduction = initial;\n\n return accumulatable(function accumulateReductions(next, initial) {\n // Define a `next` function for accumulation.\n function nextReduction(accumulated, item) {\n reduction = xf(reduction, item);\n\n return item === end ?\n next(accumulated, end) :\n // If item is not `end`, pass accumulated value to next along with\n // reduction created by `xf`.\n next(accumulated, reduction);\n }\n\n accumulate(source, nextReduction, initial);\n });\n}", "performReduction() {\n //console.log(\"called performReduction\");\n var reduced_expr = this.reduce();\n if (reduced_expr !== undefined && reduced_expr != this) { // Only swap if reduction returns something > null.\n\n console.warn('performReduction with ', this, reduced_expr);\n\n if (!this.stage) return Promise.reject();\n\n this.stage.saveState();\n Logger.log('state-save', this.stage.toString());\n\n // Log the reduction.\n let reduced_expr_str;\n if (reduced_expr === null)\n reduced_expr_str = '()';\n else if (Array.isArray(reduced_expr))\n reduced_expr_str = reduced_expr.reduce((prev,curr) => (prev + curr.toString() + ' '), '').trim();\n else reduced_expr_str = reduced_expr.toString();\n Logger.log('reduction', { 'before':this.toString(), 'after':reduced_expr_str });\n\n var parent = this.parent ? this.parent : this.stage;\n if (reduced_expr) reduced_expr.ignoreEvents = this.ignoreEvents; // the new expression should inherit whatever this expression was capable of as input\n parent.swap(this, reduced_expr);\n\n // Check if parent expression is now reducable.\n if (reduced_expr && reduced_expr.parent) {\n var try_reduce = reduced_expr.parent.reduceCompletely();\n if (try_reduce != reduced_expr.parent && try_reduce !== null) {\n Animate.blink(reduced_expr.parent, 400, [0,1,0], 1);\n }\n }\n\n if (reduced_expr)\n reduced_expr.update();\n\n return Promise.resolve(reduced_expr);\n }\n return Promise.resolve(this);\n }", "function decorateStoreWithCall(Store, call) {\n const names = Object.keys(call.actions).reduce((result, key) => {\n if (key === 'name') {\n return result;\n }\n // remove ACTION_CONSTANT variants generated by alt\n if (result.indexOf(key.toLowerCase()) === -1) {\n result.push(key);\n }\n return result;\n }, []);\n names.forEach(reducerName => {\n createStoreHandler(reducerName, Store, call);\n });\n}", "function onRecalculationPhase() {\n if (p.recalcQueued) {\n p.recalcPhase = 0;\n recalculateDimensions();\n } else if (p.recalcPhase == 1 && p.lastLocus) {\n p.recalcPhase = 2;\n p.flipper.moveTo(p.lastLocus, onRecalculationPhase, false);\n } else {\n Monocle.defer(afterRecalculate);\n }\n }", "function func(accumulator, currentValue, currentIndex, sourceArray) {\n return accumulator + currentValue;\n}", "function selectorFactory(dispatch, mapStateToProps, mapDispatchToProps) {\n //cache the DIRECT INPUT for the selector\n //the store state\n let state\n //the container's own props\n let ownProps\n\n //cache the itermediate results from mapping functions\n //the derived props from the state\n let stateProps\n //cache the derived props from the store.dispatch\n let dispatchProps\n\n //cache the output\n //the return merged props(stateProps + dispatchProps + ownProps) to be injected to wrappedComponent\n let mergedProps\n\n // the source selector is memorizable.\n return function selector(nextState, nextOwnProps) {\n //before running the actual mapping function, compare its arguments with the previous one\n const propsChanged = !shallowEqual(nextOwnProps, ownProps)\n const stateChanged = !strictEqual(nextState, state)\n\n state = nextState\n ownProps = nextOwnProps\n \n //calculate the return mergedProps based on different scenarios \n //to MINIMIZE the call to actual mapping functions\n //notice: the mapping function itself can be optimized by Reselect, but it is not the concern here\n \n //case 1: both state in redux and own props change\n if (propsChanged && stateChanged) {\n //derive new props based on state\n stateProps = mapStateToProps(state, ownProps)\n //since the ownProps change, update dispatch callback if it depends on props\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n //merge the props\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 2: only own props changes\n if (propsChanged) {\n //only update stateProps and dispatchProps if they rely on ownProps\n if (mapStateToProps.length !== 1) stateProps = mapStateToProps(state, ownProps) //it just call the mapping function\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 3: only store state changes\n // 1.since stateProps depends on state so must run mapStateToProps again\n // 2.for dispatch, since store.dispatch and ownProps remain the same, no need to update\n if (stateChanged) {\n const nextStateProps = mapStateToProps(state, ownProps)\n const statePropsChanged = !shallowEqual(nextStateProps, stateProps)\n stateProps = nextStateProps\n //if stateProps changed, update mergedProps by calling the mergeProps function\n if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 4: no change, return the cached result if no change in input\n return mergedProps;\n }\n}", "function accumulate(source, next, initial) {\n // If source is accumulatable, call accumulate method.\n isMethodAt(source, 'accumulate') ?\n source.accumulate(next, initial) :\n // ...otherwise, if source has a reduce method, fall back to accumulation\n // with reduce, then call `next` with `end` token and result of reduction.\n // Reducible sources are expected to return a value for `reduce`.\n isMethodAt(source, 'reduce') ?\n next(source.reduce(next, initial), end) :\n // ...otherwise, if source is nullish, end. `null` is considered to be\n // an empty source (akin to an empty array). This approach takes\n // inspiration from Lisp dialects, where `null` literally _is_ an empty\n // list. It also just makes sense: `null` is a non-value, and should\n // not accumulate.\n source == null ?\n next(initial, end) :\n // Otherwise, call `next` with value, then `end`. I.e, values without\n // a `reduce`/`accumulate` method are treated as sources containing\n // one item.\n next(next(initial, source), end);\n}", "function increment(event){\n if (isRunning){\n return;\n }\n var target = event.data.target;\n // Get the value of the target\n var value = parseInt(readInput(target));\n // Increment it\n value++;\n // Output incremented value back to target\n output(target, value);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if restore button shall appear or not
function checkRestoreButton(event){ fieldId = getFieldIdFromCurrentNode(event.target); backupFieldId = "#restore-field_" + fieldId; colorFieldId = "#color-field_" + fieldId; backupValue = getHexaColor(jQuery(backupFieldId).attr('value')); currentValue = jQuery(colorFieldId).attr('value'); if(backupValue != currentValue){ restoreButtonId = "#smartcolor_restore_button_" + fieldId; jQuery(restoreButtonId).css('display', 'inline'); } }
[ "function showBackBt() {\n if (_historyObj.length > 1) {\n return true;\n } else {\n return false;\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 }", "function restoreBlock() {\n if (blockStack.length > 0 && !currentBlock.isChildToggled()) {\n currentBlock.setIcon(true);\n currentBlock = blockStack.pop();\n currentBlock.setIcon(false);\n resizeCanvas(); // this redraws the screen\n return true;\n }\n return false;\n }", "ensureButtonsShown() {\n // TODO(fanlan1210)\n }", "buttonCheck(){\n this.visibility(document.getElementById(\"add-list-button\"), this.currentList == null);\n this.visibility(document.getElementById(\"undo-button\"), this.tps.hasTransactionToUndo());\n this.visibility(document.getElementById(\"redo-button\"), this.tps.hasTransactionToRedo());\n this.visibility(document.getElementById(\"delete-list-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"add-item-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"close-list-button\"), !(this.currentList == null));\n }", "hasButtonStateChanged( vButton ){\n if( VIRTUAL_BUTTONS_STATE[ vButton ] === VIRTUAL_BUTTONS_OLD_STATE[ vButton ] ) return false;\n else return true;\n }", "function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }", "function displayResetButton() {\n rollButton.style.display = 'none';\n resetButton.style.display = 'block';\n}", "function showReloadButton() {\n $('#reloadButton').removeClass('hidden');\n }", "function enableResetButton() {\n\t gameStartCheck = 2;\n\t}", "ensureButtonsHidden() {\n // TODO(fanlan1210)\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 backToWinMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"winScreen\");\n} // backToWinMenu", "function showPlayAgainButton() {\n\t$(\"#play-again\").show().css({opacity:0}).stop().animate({opacity:1},400);\n}", "function clickSettingsOkayBtn () {\n settingsWindow.close()\n writeOptions()\n\n return true\n}", "function validateSaved() {\n\t\t//Getting the save status\n\t\tvar status = productKey.getSaveStatus();\n\t\t//Visually displaying the save status\n\t\tVALIDATION_STATUS_HANDLE.innerHTML = status;\n\n\t\t//Toggling the save status\n\t\tif (productKey.isSaved()) {\n\t\t\t//Toggle the saved state from true to false\n\t\t\tproductKey.setSaved(false);\n\t\t} else {\n\t\t\t//Toggle the saved state from false to true\n\t\t\tproductKey.setSaved(true);\n\t\t}\n\n\t}", "function handleViewerClick_() {\n $('.viewer__prompt').removeClass('is-visible');\n localStorage.setItem('interacted', 'true');\n}", "function showOriginal() {\n const showOriginalBtn = document.querySelector('#show-original');\n if (originalImage.style.display == 'none') {\n originalImage.style.display = 'block';\n showOriginalBtn.style.color = '#CD343A';\n \n }\n else {\n originalImage.style.display = 'none';\n showOriginalBtn.style.color = '#ededed';\n } \n}", "function doNotShowInstructions(){ \n \n //Save the new false variable to local storage \n localStorage.setItem(\"disableInstructions\", false);\n \n props.hideMCInstructions()//close the pop up instructions \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace words with string in strings array
function replaceS() { strings[string.indexOf("words")] = "string"; }
[ "function SearchAndReplace(arr,oldWord,newWord) {\n var t = '';\n var text = arr.split(' ');\n for (let i = 0; i < text.length; i++) {\n if (text[i] == oldWord) {\n t = text[i].charAt(0);\n if (t == text[i].charAt(0).toUpperCase()) {\n t = newWord.charAt(0).toUpperCase()\n t += newWord.slice(1)\n }else{\n t = newWord.charAt(0).toLowerCase()\n t += newWord.slice(1)\n }\n text[i] = t\n }\n }\n return text.join(' ')\n}", "function replaceThe(str) {\n\tconst a = [];\n\tfor (let i = 0; i < str.split(\" \").length; i++) {\n\t\tif (str.split(\" \")[i] === \"the\" && /[aeiou]/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"an\");\n\t\t} else if (str.split(\" \")[i] === \"the\" && /([b-df-hj-np-tv-z])/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"a\");\n\t\t} else a.push(str.split(\" \")[i])\n\t}\n\treturn a.join(\" \");\n}", "function replaceArray(original, replacement, av)\n {\n\tfor (var i = 0; i < original.size(); i++)\n\t{\n\t\toriginal.value(i, replacement.value(i));\n\t\tif (replacement.isHighlight(i))\n\t\t{\n\t\t\toriginal.highlight(i);\n\t\t} else {\n\t\t\toriginal.unhighlight(i);\n\t\t}\n\t}\n }", "function jumbleWord(wordArr, mapArray) {\n var textArr = [];\n for (var i in wordArr) {\n textArr[i] = wordArr[mapArray[i]];\n }\n return textArr;\n}", "replaceSubstring(s1, s2, array){\n var result = Array();\n for (var el of array) {\n if(typeof el !== \"undefined\"){\n // Non solo la stringa deve essere contenuta, ma dato che si tratta di una sositutzione\n // dell'intero percorso fino a quella cartella mi assicuro che l'inclusione parta\n // dal primo carattere\n var eln = el;\n if(el.substring(0,s1.length).includes(s1)){\n eln = s2+el.substring(s1.length)\n }\n result.push(eln);\n }\n }\n return result;\n }", "function modifyStrings(strings, modify) {\n // YOUR CODE BELOW HERE //\n // I = array of strings and modify function\n // O = modified array\n // init empty array as modArray\n // use for loop to loop through entire array of strings\n // push strings into modArray array and into modify function\n var modArray = [ ];\n for (var i = 0; i < strings.length; i++) {\n modArray.push(modify(strings[i]));\n } \n \n return modArray;\n\n \n \n // YOUR CODE ABOVE HERE //\n}", "regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }", "function weave(strings) {\n let phrase = ('coding iz hard')\n let string = phrase.split('')\n let nth = 4;\n let replace = 'x';\n for (i = nth - 1; i < string.length; i += nth) {\n string[i] = replace;\n }\n return string.join('');\n}", "function str_replace(haystack, needle, replacement) {var temp = haystack.split(needle);return temp.join(replacement);}", "function removewords(text, words){\n if(isUndefined(words)){words = wordstoignore;}\n text = text.toLowerCase().split(\" \");\n for(var i=text.length-1; i>-1; i--){\n if(words.indexOf(text[i]) > -1){\n removeindex(text, i);\n }\n }\n text = removemultiples(text.join(\" \"), \" \", \" \");\n return text;\n}", "function swap(text) {\n let words = [];\n text.split(\" \").forEach(word => words.push(switchLetters(word)));\n console.log(words.join(\" \"));\n}", "function censorString(str, arr, char) {\n\treturn str.split(\" \").map(x => x.replace(new RegExp(arr.join('|'), 'g'), char.repeat(x.length))).join(\" \");\n}", "function charReplacer(array, oldChar, newChar) {\n for (let i = 0; i < array.length; i++) {\n array[i] = array[i].replace(oldChar, newChar);\n };\n}", "redact(parameters) {\n // Converted to a promise now\n let promise = this.$q((resolve, reject) => {\n // Setup and defaults\n let replacementChar = parameters.replacementChar || 'X';\n // Here is a little example of type checking variables and defaulting if it isn't as expected.\n let caseSensitive =\n typeof parameters.caseSensitive === typeof true\n ? parameters.caseSensitive\n : true;\n if (parameters.phrases === undefined || parameters.phrases.length === 0) {\n return parameters.inputText;\n }\n\n let phrases = parameters.phrases;\n let searchText = parameters.inputText;\n if (!caseSensitive) {\n phrases = parameters.phrases.map(p => p.toLowerCase());\n searchText = parameters.inputText.toLowerCase();\n }\n\n // loop through the phrases array\n let indicies = [];\n phrases.map(p => {\n // should just use for loop here now\n let pos = -1;\n do {\n pos = searchText.indexOf(p, pos + 1); // use the start index to reduce search time on subsequent searches\n if (pos === -1) break; // No more matches, abandon ship!\n // Track the starting index and length of the redacted area\n indicies.push({ index: pos, length: p.length });\n } while (pos != -1);\n });\n\n // Ok now go replace everything in the original text.\n // Overlapping phrases should be handled properly now.\n // we really need a splice method for strings\n // quick google search and guess what? There is an underscore string library ... neat! Now I don't have to write one.\n let redactedText = parameters.inputText;\n for (let i = 0, len = indicies.length; i < len; i++) {\n redactedText = _string.splice(\n redactedText,\n indicies[i].index,\n indicies[i].length,\n this.buildReplacement(replacementChar, indicies[i].length)\n );\n }\n\n // Go home strings, you're drunk\n resolve(redactedText);\n });\n return promise;\n }", "function makeHappy(arr){\n let result = arr.map(word => \"Happy \" + word)\n return result\n}", "function replaceInString(data, search, replace) {\n if (Array.isArray(search)) {\n for (var i=0; i<search.length; i++) {\n data = data.replaceAll(search[i], replace[i]);\n }\n return data;\n } else {\n return data.replaceAll(search, replace);\n }\n}", "function replaceAll(str, term, replacement) {\n return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);\n }", "function doReplace(str1, str2, str3){\n return str3.split(str1).join(str2)\n}", "function owofied(sentence) {\n\tconst a = sentence.replace(/i/g, \"wi\");\n\tconst b = a.replace(/e/g, \"we\");\n\treturn b + \" owo\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modifies an array of events in the following ways (operations are in order): clear the event's `end` convert the event to allDay add `dateDelta` to the start and end add `durationDelta` to the event's duration assign `miscProps` to the event Returns a function that can be called to undo all the operations. TODO: don't use so many closures. possible memory issues when lots of events with same ID.
function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) { var isAmbigTimezone = t.getIsAmbigTimezone(); var undoFunctions = []; // normalize zero-length deltas to be null if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; } if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; } $.each(events, function (i, event) { var oldProps; var newProps; // build an object holding all the old values, both date-related and misc. // for the undo function. oldProps = { start: event.start.clone(), end: event.end ? event.end.clone() : null, allDay: event.allDay }; $.each(miscProps, function (name) { oldProps[name] = event[name]; }); // new date-related properties. work off the original date snapshot. // ok to use references because they will be thrown away when backupEventDates is called. newProps = { start: event._start, end: event._end, allDay: allDay // normalize the dates in the same regard as the new properties }; normalizeEventRange(newProps); // massages start/end/allDay // strip or ensure the end date if (clearEnd) { newProps.end = null; } else if (durationDelta && !newProps.end) { // the duration translation requires an end date newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start); } if (dateDelta) { newProps.start.add(dateDelta); if (newProps.end) { newProps.end.add(dateDelta); } } if (durationDelta) { newProps.end.add(durationDelta); // end already ensured above } // if the dates have changed, and we know it is impossible to recompute the // timezone offsets, strip the zone. if ( isAmbigTimezone && !newProps.allDay && (dateDelta || durationDelta) ) { newProps.start.stripZone(); if (newProps.end) { newProps.end.stripZone(); } } $.extend(event, miscProps, newProps); // copy over misc props, then date-related props backupEventDates(event); // regenerate internal _start/_end/_allDay undoFunctions.push(function () { $.extend(event, oldProps); backupEventDates(event); // regenerate internal _start/_end/_allDay }); }); return function () { for (var i = 0; i < undoFunctions.length; i++) { undoFunctions[i](); } }; }
[ "getDanglingAudioEvents(millis, events){\n let num = 0;\n\n for(let event of this.audioEvents){\n if(event.millis < millis && event.endMillis > millis){\n event.playheadOffset = (millis - event.millis);\n event.time = this.startTime + event.millis - this.songStartMillis + event.playheadOffset;\n event.playheadOffset /= 1000;\n this.scheduledAudioEvents[event.id] = event;\n //console.log('getDanglingAudioEvents', event.id);\n events.push(event);\n num++;\n }else{\n event.playheadOffset = 0;\n }\n //console.log('playheadOffset', event.playheadOffset);\n }\n //console.log('getDanglingAudioEvents', num);\n return events;\n }", "function prepareEventsForStorage(events) {\n const prepared = events.map(event => {\n const { startObj, endObj, ...rest } = event;\n return rest;\n });\n\n return JSON.stringify(prepared);\n}", "function normaliseEvent(evt) {\n var duration = {};\n\n if (!evt.dtend) {\n if (evt.duration) {\n duration.original = evt.duration;\n duration.minutes = evt.duration.match(/^PT(\\d+)M$/)[1];\n evt.dtend = new Date();\n evt.dtend.setTime(\n evt.dtstart.getTime() + duration.minutes * 60000);\n } else {\n evt.dtend = evt.dtstart;\n duration.minutes = 0;\n }\n } else {\n duration.minutes = (evt.dtend.getTime() - evt.dtstart.getTime());\n duration.minutes /= 60000;\n }\n\n if (duration.minutes >= 60) {\n duration.hours = Math.floor(duration.minutes / 60);\n duration.minutes -= duration.hours * 60;\n } else {\n duration.hours = 0;\n }\n\n duration.str = pad(duration.hours) + pad(duration.minutes);\n evt.duration = duration;\n\n evt.dtstart.iso8601 = iso8601(evt.dtstart);\n evt.dtend.iso8601 = iso8601(evt.dtend);\n }", "function adjustDates(dates, arr, func) {\n if (!arr) {\n return dates;\n }\n var result = [];\n for (var i=0; i < dates.length; i++) {\n var d = dates[i];\n for (var j=0; j < arr.length; j++) {\n func(d, arr[j], result, j);\n }\n }\n return result;\n }", "function editEvent(){\n for(var i = 0; i < eventInput.length; i++){\n eventInput[i].addEventListener(\"change\", function(){\n this.previousElementSibling.lastElementChild.previousElementSibling.innerHTML = this.value;\n for(var i = 0; i < currentMonth.days.length; i++){\n if(clickedCell.firstChild.textContent === currentMonth.days[i].cell.firstChild.textContent){\n currentMonth.days[i].events.push(this.value);\n break;\n };\n }\n });\n }\n}", "async function addEventsList(id, eventsList) {\r\n eventsStore.update(state => {\r\n state[id] = eventsList;\r\n return state\r\n });\r\n // get the last element, which is the new event added\r\n var obj = eventsList.slice(-1)[0];\r\n await addEvent({...obj, timelineId: id});\r\n }", "updateFilteredEvents(events) {\n\n // Get New Events\n const currentEvents = this.state.filteredEvents.map(function(e) {return e.hash;});\n const isNotCurrentEvent = (e) => currentEvents.indexOf(e.hash) === -1;\n const newEvents = events.filter(isNotCurrentEvent);\n\n // Set New State\n if (newEvents.length > 0) {\n this.setState(prevState => ({filteredEvents: [...prevState.filteredEvents, ...newEvents]}));\n }\n }", "function rearrangeListOfVacationDates() {\n var startDate, vacationDuraionTotal, tagID;\n startDate = $('#startDateE').val();\n for (var i = 0; i < listOfVacation.length; i++) {\n vacationDuraionTotal += parseInt(listOfVacation[i].vacationStartDateE);\n listOfVacation[i].vacationStartDateE = startDate;\n listOfVacation[i].vacationEndDateE = addDays(startDate, listOfVacation[i].vacationDuration - 1);\n\n startDate = addDays(listOfVacation[i].vacationEndDateE, 1);\n\n tagID = '#' + listOfVacation[i].startDateETagID;\n $(tagID).text(listOfVacation[i].vacationStartDateE + ' م');\n tagID = '#' + listOfVacation[i].startDateTagID;\n $(tagID).text(moment(listOfVacation[i].vacationStartDateE, 'YYYY/MM/DD').format('iYYYY/iMM/iDD') + ' هـ');\n\n tagID = '#' + listOfVacation[i].endDateETagID;\n $(tagID).text(listOfVacation[i].vacationEndDateE + ' م');\n tagID = '#' + listOfVacation[i].endDateTagID;\n $(tagID).text(moment(listOfVacation[i].vacationEndDateE, 'YYYY/MM/DD').format('iYYYY/iMM/iDD') + ' هـ');\n }\n\n setEndAndBackDate();\n}", "mergeSequences () {\n let lastListElement;\n this.sequence.forEach((e, i) => {\n if (lastListElement && e.locationID === lastListElement.locationID && e.firstStart > lastListElement.lastEnd) {\n e.pushEvent(lastListElement.sequence);\n delete this.sequence[this.sequence.indexOf(lastListElement)];\n } else if(lastListElement && e.locationID === lastListElement.locationID) {\n lastListElement.createAlternativeSequence(e.sequence);\n delete this.sequence[this.sequence.indexOf(e)];\n e = lastListElement;\n }\n lastListElement = e;\n });\n this.updateTravelTime();\n }", "function toggleDate(timestamp, noCount)\n{\n\ttry {\n\n\t\tif(noCount)\n\t\t{\n\t\t\tvar noCountDateArray = getSubDates();\n\t\t\n\t\t\t//Secondary dates. Store many hooray\n\t\t\tvar sidx = noCountDateArray.indexOf(timestamp);\n\t\t\n\t\t\tif(sidx != -1)\n\t\t\t{\n\t\t\t\tnoCountDateArray.splice(sidx, 1); //Remove if found\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//...add if not found.\n\t\t\t\tnoCountDateArray.push(timestamp);\n\t\t\t}\n\t\t\t\n\t\t\tnoCountDateArray.sort();\n\t\t\t\n //trackEvent(\"Interaction\", \"Sub date changed\", timestamp);\n\t\t\t\n\t\t\t//This is the new solution!\n\t\t\tdates.subDateArray = noCountDateArray;\n\t\t\tpersistDatesToStorage(dates);\n\t\t\t\t\t\t\n\t\t\tlog(\"Sub date array changed\", noCountDateArray);\n\t\t\t\t\n\t\t\t\n\t\t}\n\t\telse //The main one. Store just that.\n\t\t{\n\t\t\tvar dateArray = getDates();\n\t\t\t\n\t\t\tvar idx = dateArray.indexOf(timestamp);\n\t\t\t\n\t\t\tif(idx != -1)\n\t\t\t{\n\t\t\t\tdateArray = []; // Clear out\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdateArray = [timestamp]; //Set\n\t\t\t}\n\t\t\t\n\t\t\t//This is the new solution!\n\t\t\tdates.mainDateArray = dateArray;\n\t\t\tpersistDatesToStorage(dates);\n\t\t\t\n\t\t\t\n\t\t\tlog(\"Date array changed\", dateArray); //Log it\t\n\t\t}\n\t\t\t\n\t}\n\tcatch(e)\n\t{\n\t\thandleError(\"Functions toggleDate\", e);\n\t}\n\t\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 }", "deleteItemsEventsEtc() {\n let items_buffer = getReferencesOfType('AGItem');\n items_buffer.forEach(function (buffer) {\n deleteItem(buffer);\n });\n let conditions_buffer = getReferencesOfType('AGCondition');\n conditions_buffer.forEach(function (buffer) {\n deleteCondition(buffer);\n });\n let glevents_buffer = getReferencesOfType('GlobalEvent');\n glevents_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeGlobalEventByID(parseInt(buffer));\n });\n let events_buffer = getReferencesOfType('Event');\n events_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeEventByID(parseInt(buffer));\n });\n\n this.listItems();\n this.listEvents();\n this.refreshItemSelect();\n this.listGlobalEvents();\n this.listConditions();\n }", "function setCalendarAppts() {\n\n var data = getCalendarData();\n var columnHeaders = getColumnHeaders();\n\n // column headers \n var isCompleteColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DONE);\n var taskColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_TASK);\n var dateColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DUEDATE);\n var googleCalColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_GOOGLECALENDARID); \n\n // find events with dates\n for (var i = 1; i < data.length; i++) {\n\n\n // if date but not google calendar entry, add it\n if (!data[i][isCompleteColumnId]) {\n var event;\n if (data[i][dateColumnId] && !data[i][googleCalColumnId]) {\n\n Logger.log('Add Task: ' + data[i][taskColumnId]);\n \n var eventDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'mm');\n\n // always add \"today\" if less than today\n var isOverdue = false;\n if (eventDate.getDate() < new Date().getDate()) {\n eventDate.setDate(new Date().getDate());\n isOverdue = true;\n }\n\n // create event\n event = CalendarApp.getDefaultCalendar().createAllDayEvent(\"TASK: \" + data[i][taskColumnId], eventDate);\n \n // if event is overdue\n if (isOverdue && CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n \n // WIP - set time if time exists in entry\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n \n // add the event ID to the spreadsheet\n SpreadsheetApp.openById(CONFIG_SHEETID).getSheetByName(CONFIG_SHEET_TODO).getRange(i + 1, googleCalColumnId + 1).setValue(event.getId());\n\n }\n else if (data[i][dateColumnId] && data[i][googleCalColumnId]) {\n\n Logger.log('Modify Task: ' + data[i][taskColumnId]);\n \n // fetch the event using the ID\n event = CalendarApp.getDefaultCalendar().getEventById(data[i][googleCalColumnId]);\n\n // update time if time is set in due date \n var eventSheetDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'mm');\n \n // auto-advance to today in CALENDAR (not sheet)\n if (eventSheetDate < new Date()) {\n event.setAllDayDate(new Date());\n \n // change color if event is overdue\n if (CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n\n }\n else\n {\n // update calendar date to revised sheet date\n event.setAllDayDate(eventSheetDate);\n }\n\n // update title\n event.setTitle(data[i][taskColumnId]);\n eventDate = event.getStartTime();\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n\n\n\n }\n\n }\n\n }\n\n}", "function pushAllEventsToCalendar() {\n console.log('Pushing all events to calendar');\n var dataRange = sheet.getDataRange();\n // Process the range.\n processRange(dataRange);\n console.log('Finished pushing all events');\n}", "function updateEvents(eventsNames) {\n\t\t\tfor (var i=0; i<events.length; i++) {\n\t\t if ( hasEvent(eventsNames, events[i].name)) {\n\t\t markEvent(i);\n\t\t }\n\t\t else {\n\t\t fadeEvent(i);\n\t\t }\n\t\t }\n\t\t}", "function populateCalPageEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 90; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : weeklyEvents[0].eventDesc, 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : weeklyEvents[2].eventDesc, 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : weeklyEvents[3].eventDesc, 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">REQUEST VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">BUY TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n \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 updateOrderAndDate() {\n let date = new Date();\n date.setHours(0, 0, 0, 0);\n let lastDate = new Date(playlist[playlist.length - 1]['date']);\n let offset = 1;\n let newList = playlist.slice();\n\n // All dates in playlist already passed\n if (lastDate < date) {\n lastDate = new Date();\n offset = 0;\n }\n\n for (let item of playlist) {\n if (date > new Date(item['date'])) {\n let putLast = newList.splice(0, 1)[0];\n lastDate.setDate(lastDate.getDate() + offset);\n putLast['date'] = lastDate.toISOString().substr(0, 10);\n newList.push(putLast);\n offset++;\n }\n }\n playlist = newList;\n logger.info('Updated date and order');\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 }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
:: > BOOLEAN Return TRUE if given value is an instance of YngwieView
static is(val) { return val instanceof YngwieView; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }", "function object (thing) {\n return typeof thing === 'object' && thing !== null && array(thing) === false && date(thing) === false;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === JavaAppLayer.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Bot.__pulumiType;\n }", "isLocation() {\n return this.truthObject.constructor.name == 'Location'\n }", "isText(value) {\n return isPlainObject(value) && typeof value.text === 'string';\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Key.__pulumiType;\n }", "get shouldRestoreView() {\n return this.view instanceof Map\n }", "function winActiveViewType() {\n\n var body = $('iframe#canvas_frame', parent.document).contents().find('div.nH.q0CeU.z');\n\n if (body.is(\"*\")) {\n return 'tl';\n } else {\n return 'na';\n }\n\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Record.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineScaleSetVM.__pulumiType;\n }", "function isViewed(display_frame_name) \n{ \n for (i = 0; i < active_displays_l.length; i++) \n { \n if (active_displays_l[i] == display_frame_name) \n { \n return true; \n } \n } \n return false; \n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Host.__pulumiType;\n }", "static init(yngwieElement) {\n switch (_Util_main_js__WEBPACK_IMPORTED_MODULE_1__.default.getType(yngwieElement)) {\n case \"YngwieElement\":\n case \"undefined\":\n return new YngwieView(yngwieElement);\n default:\n let elem = yngwie__WEBPACK_IMPORTED_MODULE_0__.Element.init.apply(null, arguments);\n return new YngwieView(elem);\n }\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Snapshot.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineResource.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DisasterRecoveryConfig.__pulumiType;\n }", "function convertible(value, ty) {\n if (ok(value, ty)) {\n return true;\n }\n if (isNull(value) || isUndefined(value)) {\n return false;\n }\n if (ty === tyNumber && isNaN(value)) {\n return false;\n }\n // TODO: refine\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is used to get drug names based on group selection.
function getDrugNamesOnGroup(groupName) { if (groupName != null && groupName != "") { $.ajax({ type : 'GET', url : 'getDrugNamesOnGroup', data : { groupName : groupName }, success : function(data) { var jsonDrugNames = $.parseJSON(JSON.stringify(data)); var select = $("#drugName"); if (onComplaint != null && onComplaint == 'yes') { select.empty().prepend("<option value='unknown' selected='selected'>Unknown</option>"); $(jsonDrugNames).each(function(index, drugName) { var option = $("<option/>").attr("value", drugName).text(drugName); select.append(option); }); } else { select.empty(); $(jsonDrugNames).each(function(index, drugName) { var option = $("<option/>").attr("value", drugName).text(drugName); select.append(option); }); // Populate Strength drop down if drug name drop down is // preselected. if ($("#drugName").val() != null || $("#drugName").val() != '') { getStrengthOnDrugName($("#drugName").val()); } } }, error : function(jqXHR, textStatus, errorThrown) { console.log(textStatus); }, }); } }
[ "function getDrugName(drugGroup, drugName) {\r\n\t\tvar groupName = drugGroup;\r\n\t\tif (groupName != null && groupName != \"\") {\r\n\t\t\t$.ajax({\r\n\t\t\t\ttype : 'GET',\r\n\t\t\t\turl : 'getDrugNamesOnGroup',\r\n\t\t\t\tdata : {\r\n\t\t\t\t\tgroupName : groupName\r\n\t\t\t\t},\r\n\t\t\t\tsuccess : function(data) {\r\n\t\t\t\t\tvar jsonDrugNames = $.parseJSON(JSON.stringify(data));\r\n\t\t\t\t\tvar select = $(\"#drugName\");\r\n\t\t\t\t\tif (onComplaint != null && onComplaint == 'yes') {\r\n\t\t\t\t\t\tif (drugName != null && drugName == 'unknown') {\r\n\t\t\t\t\t\t\tselect.empty().prepend(drugName);\r\n\t\t\t\t\t\t\t$(jsonDrugNames).each(function(index, drugName) {\r\n\t\t\t\t\t\t\t\tvar option = $(\"<option/>\").attr(\"value\", drugName).text(drugName);\r\n\r\n\t\t\t\t\t\t\t\tselect.append(option);\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\tselect.append(\"<option value='unknown' selected='selected'>Unknown</option>\");\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tselect.empty().prepend(drugName);\r\n\t\t\t\t\t\t\t$(jsonDrugNames).each(function(index, drugName) {\r\n\t\t\t\t\t\t\t\tvar option = $(\"<option/>\").attr(\"value\", drugName).text(drugName);\r\n\r\n\t\t\t\t\t\t\t\tselect.append(option);\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\tselect.append(\"<option value='unknown'>Unknown</option>\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tselect.empty().prepend(drugName);\r\n\t\t\t\t\t\t$(jsonDrugNames).each(function(index, drugName) {\r\n\t\t\t\t\t\t\tvar option = $(\"<option/>\").attr(\"value\", drugName).text(drugName);\r\n\r\n\t\t\t\t\t\t\tselect.append(option);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t},\r\n\t\t\t\terror : function(jqXHR, textStatus, errorThrown) {\r\n\t\t\t\t\tconsole.log(textStatus);\r\n\r\n\t\t\t\t},\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t}", "function getGroupNames(){\n var ret = [];\n for (var i = 0; i < this.groups.length; i++) {\n ret.push(this.groups[i].name);\n }\n return ret;\n}", "group (name) {\n var me = `${this.visualType}-${this.model.uid}`,\n group = this.visualParent.getPaperGroup(me);\n if (name && name !== this.visualType) return this.paper().childGroup(group, name);\n else return group;\n }", "function _getGroupDataSelector(item) {\n return item.group;\n }", "function showGroupName(){\n\tvar url = \"https://\"+CURRENT_IP+\"/cgi-bin/NFast_3-0/CGI/RESERVATIONMANAGER/FastConsoleCgi.py?action=getgroupnamelist&query={'QUERY':[{'username':'\"+globalUserName+\"'}]}\";\n\t\t$.ajax({\n\t\turl: url,\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData : false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\t\tconsole.log(\"getGROUP\",data)\n\t\t\t\tfor (var i = 0; i< json.data[0].row.length; i++ ){\n\t\t\t\t\tvar groupname = json.data[0].row[i].GroupName;\n\t\t\t\t\tvar hostname =\tjson.data[0].row[i].HostName;\n\t\t\t\t\tvar usermember = json.data[0].row[i].UserMember;\n\t\t\t\tstr += \"<li style='font-size:10px;list-style:none;cursor:pointer;text-align:left;margin-left:4px;' class='createdGroup'>\"+groupname+\"</li>\"\t\t\t\t\n\t\t\t\t}\n\t\t\t\t$('#grouplist').html(str);\n\t\t\t}\n\t});\n}", "function extGroup_getSelectParticipant(groupName)\n{\n return dw.getExtDataValue(groupName, \"groupParticipants\", \"selectParticipant\");\n}", "function commonGroup() {\nvar counter, counter2, commonTaxId;\n//var selectedList = [];\nvar allGroup = {};\nvar groupList = [\"genus\",\"family\",\"order\",\"phyl\"];\n//var refOrgs = $.extend(jsonOrgs[\"reforgs\"], jsonOrgs[\"queryorgs\"]); //how to handle if only query orgs remaining?\n // for each taxonomical level, see what group each active option in species selection belongs to\n for (var group in groupList) {\n var groupId = groupList[group]+\"id\";\n var groupName = groupList[group]+\"name\";\n // iterate through all selected options\n $(\"#specieslist > .picked\").each(function(){\n var currId = $(this).val();\n var currGroup = $(this).data(groupId);\n var currName = $(this).data(groupName)\n if (currGroup != \"N/A\" && currName != \"N/A\") {\n allGroup[currGroup] = currName; //stores current option's group ID and name in allGroup; overwrites respective entry if already present\n //console.log(allGroup);\n }\n /*for (counter=0; counter<refOrgs.length; counter++) {\n var refInfo = refOrgs[counter];\n if (currId == refInfo.id) {\n //selectedList.push(refInfo);\n var currGroup = refInfo[groupId];\n var currName = refInfo[groupName];\n if (currGroup != \"N/A\" && currName != \"N/A\") {\n allGroup[currGroup] = currName;\n console.log(allGroup);\n }\n }\n }*/\n });\n // if all options belong to the same group at the level currently examined, return examined level, NCBI group ID and name of group\n if (Object.keys(allGroup).length == 1) {\n commonTaxId = Object.keys(allGroup);\n var commonInfo = [groupList[group], commonTaxId[0], allGroup[commonTaxId[0]]];\n //console.log(commonInfo);\n return commonInfo;\n } else if (groupList[group] == \"phyl\" && Object.keys(allGroup).length > 1){ // if the check has been run down to phylum level without finding one single group to which all options belong, return level (phylum), as well as NCBI ids and names of all phyla represented\n commonTaxId = Object.keys(allGroup);\n var multiGroups = [];\n for (var idkey in commonTaxId) {\n multiGroups.push(allGroup[commonTaxId[idkey]]);\n }\n var commonInfo = [groupList[group], commonTaxId, multiGroups];\n //console.log(commonInfo);\n return commonInfo\n }\n // if neither of these conditions has been satisfied, empty allGroup and repeat check at next higher taxonomical level\n allGroup = {};\n}\n}", "function getGroup() {\n\n for(var i = 0; i < data.length; i++) {\n\n $('<option value=' + data[i].id + '>' + data[i].firstName + ' ' + data[i].surname + '</option>').appendTo(\"#friendPicker\");\n }\n\n }", "function dwscripts_getSBGroupNames(serverBehaviorName)\n{\n //get the group ids matcing that name\n var groupNames = dw.getExtGroups(serverBehaviorName,\"serverBehavior\");\n\n //walk the list of groupNames, and eliminate groups that do not\n // define any information for the current server model\n for (var i=groupNames.length-1; i >= 0; i--) //walk the list backward for removals\n {\n var hasData = false;\n var partNames = dw.getExtDataArray(groupNames[i],\"groupParticipants\");\n\n for (var j=0; j < partNames.length; j++)\n {\n if (dw.getExtDataValue(partNames[j], \"insertText\"))\n {\n hasData = true;\n break;\n }\n }\n if (!hasData)\n {\n groupNames.splice(i,1); // remove this item from the array\n }\n }\n\n return groupNames;\n}", "function extGroup_getParticipantNames(groupName, insertLocation)\n{\n var partNames = dw.getExtDataArray(groupName, \"groupParticipants\");\n var retPartNames = new Array();\n\n for (var i=0; i < partNames.length; i++)\n {\n if (!insertLocation || extPart.getLocation(partNames[i]).indexOf(insertLocation) == 0)\n {\n retPartNames.push(partNames[i]);\n }\n }\n return retPartNames;\n}", "async function getGroupName(group) {\n const result = await db.collection(\"Groups\")\n .findOne({ _id: ObjectId(group) }, { projection: { _id: 0, name: 1 } });\n\n if (result === null) {\n throw new RequestError('group does not exist');\n }\n\n return result.name;\n}", "function updateNames(selectedOption) {\n \t\t\t// Filter out data with the selection\n \t\t\tvar dataFilter = currentSelectedFaculty.map(function (d) {\n \t\t\t\treturn {\n \t\t\t\t\tAuthor: d.Author,\n \t\t\t\t\tAffiliation: d.Affiliation,\n \t\t\t\t\tKeyWords: d.KeyWords,\n \t\t\t\t\tCitations: d.Citations,\n \t\t\t\t\tURL: d.URL,\n \t\t\t\t\tRank: d.Rank,\n \t\t\t\t\tPictureURL: d.PictureURL\n \t\t\t\t};\n \t\t\t});\n\n \t\t\t// Track mousemove in show all name mode\n \t\t\tsvg.on(\"mousemove\", selectedOption\n \t\t\t? hideNames\n \t\t\t: () => {\n \t\t\t\t\t\n \t\t\t\t});\n\n \t\t\ttext.data(dataFilter).transition().duration(1000).attr(\"font_family\", \"sans-serif\").attr(\"font-size\", \"11px\").attr(\"fill\", \"black\").text(function (d) {\n \t\t\t\tif (selectedOption == true) {\n \t\t\t\t\treturn d.Author; // Font type\n \t\t\t\t\t// Font size\n \t\t\t\t\t// Font color\n \t\t\t\t} else {\n \t\t\t\t\treturn \"\";\n \t\t\t\t}\n \t\t\t});\n \t\t}", "function dwscripts_getUniqueSBGroupName(paramObj, serverBehaviorName)\n{\n var groupName = \"\";\n var groupNames = dwscripts.getSBGroupNames(serverBehaviorName);\n\n if (groupNames.length)\n {\n if (groupNames.length == 1)\n {\n groupName = groupNames[0];\n }\n else\n {\n //if subType or dataSource given, resolve ties by filtering using them\n if (paramObj)\n {\n var matchGroups = new Array();\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType or it matches, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n &&\n (\n (!paramObj.MM_subType && !dw.getExtDataValue(groupNames[i],\"subType\")) ||\n (paramObj.MM_subType && dw.getExtDataValue(groupNames[i],\"subType\") == paramObj.MM_subType)\n )\n )\n {\n matchGroups.push(groupNames[i]);\n }\n }\n\n if (!matchGroups.length && paramObj.MM_subType)\n {\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n && !dw.getExtDataValue(groupNames[i],\"subType\")\n )\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n if (!matchGroups.length && paramObj.MM_dataSource)\n {\n //if no dataSource, keep groupName\n for (var i=0; i<groupNames.length; i++)\n {\n if (!dw.getExtDataValue(groupNames[i],\"dataSource\"))\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n //if anything left after filtering, use that\n if (matchGroups.length)\n {\n groupName = matchGroups[0];\n }\n }\n }\n }\n\n return groupName;\n}", "selectModelsByGroup(groupName) {\n return this.filterAllByProperty('groupName', groupName)\n }", "function showGroup() {\n\tvar ps = document.querySelectorAll('p, nav, section, article');\n\tvar i = 0;\n\twhile(i < ps.length) {\n\t\tgroupLength = ps[i].childNodes.length;\n\t\tif(groupLength > 1) {\n\t\t\tvar groupChild = document.createElement('span');\n\t\t\tgroupChild.classList.add('vasilis-srm-group');\n\t\t\tgroupChild.innerHTML = \" Group \" + groupLength + \" items\";\n\t\t\tps[i].appendChild(groupChild);\n\t\t}\n\t\ti++;\n\t}\n}", "function getFullNames(runners) {\n /* CODE HERE */\n let name = [];\n runners.forEach((index) => {\n name.push(index.last_name + \", \" + index.first_name);\n })\n return name;\n}", "function drawGroups(){\nd3.select('div.viz')\n\t//.append('g').attr('id','recessions')\n\t.selectAll('div')\n\t.data(rec)\n\t.enter()\n\t.append('div')\n\t.attr('class','rBox');\t\n\t}//CLOSE drawGroups", "function extGroup_getDataSourceFileName(groupName)\n{\n return dw.getExtDataValue(groupName, \"dataSource\");\n}", "function getDataset(groupedData, currentGender, currentGroup) { \n var genderData = groupedData.filter(function(d) {\n return d.key == currentGender;\n })\n \n return genderData[0].values.filter(function(d) {\n return d.key == currentGroup;\n }) \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to Get region Tree BY searching Region name
function fnSearchRegions() { if ($.trim($('#txtSearchNode').val()) == '') { fnGetRegionTreeByRegion(currentRegionCode_g, "dvRegionTree", "dvFilteredNode"); } else { fnGetRegionsByRegionName($('#txtSearchNode').val(), "dvRegionTree", "dvFilteredNode"); } }
[ "async function getAllRegions() {\n const regions = {\n regions: [\n {\n name: \"blackrod\",\n parent: \"bolton\",\n },\n {\n name: \"bolton\",\n parent: \"manchester\",\n },\n {\n name: \"bury\",\n parent: \"manchester\",\n },\n {\n name: \"camden\",\n parent: \"central london\",\n },\n {\n name: \"camden town\",\n parent: \"camden\",\n },\n {\n name: \"central london\",\n parent: \"london\",\n },\n {\n name: \"covent garden\",\n parent: \"westminster\",\n },\n {\n name: \"croydon\",\n parent: \"south-west london\",\n },\n {\n name: \"east london\",\n parent: \"london\",\n },\n {\n name: \"farnworth\",\n parent: \"bolton\",\n },\n {\n name: \"hatton garden\",\n parent: \"camden\",\n },\n {\n name: \"heywood\",\n parent: \"rochdale\",\n },\n {\n name: \"holborn\",\n parent: \"camden\",\n },\n {\n name: \"kensington and chelsea\",\n parent: \"london\",\n },\n {\n name: \"kew\",\n parent: \"richmond upon thames\",\n },\n {\n name: \"kingston upon thames\",\n parent: \"south-west london\",\n },\n {\n name: \"london\",\n parent: \"\",\n },\n {\n name: \"manchester\",\n parent: \"\",\n },\n {\n name: \"middleton\",\n parent: \"rochdale\",\n },\n {\n name: \"north london\",\n parent: \"london\",\n },\n {\n name: \"oldham\",\n parent: \"manchester\",\n },\n {\n name: \"richmond upon thames\",\n parent: \"south-west london\",\n },\n {\n name: \"rochdale\",\n parent: \"manchester\",\n },\n {\n name: \"south london\",\n parent: \"london\",\n },\n {\n name: \"south-west london\",\n parent: \"london\",\n },\n {\n name: \"twickenham\",\n parent: \"richmond upon thames\",\n },\n {\n name: \"west london\",\n parent: \"london\",\n },\n {\n name: \"westminster\",\n parent: \"central london\",\n },\n {\n name: \"wimbledon\",\n parent: \"south-west london\",\n },\n ],\n };\n\n await waitFor(Math.random() * 1500);\n\n return regions;\n}", "findRegions(state) {\n let lang = state.facet(language)\n if (\n (lang === null || lang === void 0 ? void 0 : lang.data) == this.data\n )\n return [{ from: 0, to: state.doc.length }]\n if (!lang || !lang.allowsNesting) return []\n let result = []\n let explore = (tree, from) => {\n if (tree.prop(languageDataProp) == this.data) {\n result.push({ from, to: from + tree.length })\n return\n }\n let mount = tree.prop(dist_NodeProp.mounted)\n if (mount) {\n if (mount.tree.prop(languageDataProp) == this.data) {\n if (mount.overlay)\n for (let r of mount.overlay)\n result.push({ from: r.from + from, to: r.to + from })\n else result.push({ from: from, to: from + tree.length })\n return\n } else if (mount.overlay) {\n let size = result.length\n explore(mount.tree, mount.overlay[0].from + from)\n if (result.length > size) return\n }\n }\n for (let i = 0; i < tree.children.length; i++) {\n let ch = tree.children[i]\n if (ch instanceof dist_Tree) explore(ch, tree.positions[i] + from)\n }\n }\n explore(dist_syntaxTree(state), 0)\n return result\n }", "function fnLoadInitialRegionTree() {\n $('#dvFullTree').show();\n $('#dvLoadTree').hide();\n $('#dvLoadTree').attr(\"title\", \"Click here to show all Regions\");\n fnGetRegionTreeByRegion(currentRegionCode_g, \"dvRegionTree\", \"dvFilteredNode\");\n}", "function fnGetRegionTreeByRegionWithCheckBox(regionCode, treeId, filterId) {\n if (regionCode == \"\") {\n regionCode = currentRegionCode_g;\n }\n $('span').removeClass('childIcon');\n if (regionCode == currentRegionCode_g) {\n $('#dvPreviousNode').hide();\n }\n else {\n $('#dvPreviousNode').show();\n }\n $('#' + treeId).block({\n message: '<h3>Loading...</h3>',\n css: { border: '1px solid #ddd' }\n });\n $.ajax({\n type: \"POST\",\n url: 'Master/RegionTreeGenerationByRegionCode',\n data: \"regionCode=\" + regionCode + \"&includeOneLevelParent=NO\",\n success: function (jsData) {\n if (jsData != '') {\n $('#' + filterId).hide();\n $(\"#\" + treeId).show();\n $(\"#\" + treeId).html(' ');\n $('#' + treeId).dynatree('destroy');\n $('#' + treeId).empty();\n $(\"#\" + treeId).html(jsData);\n\n $(\"#\" + treeId).dynatree({\n checkbox: true,\n onActivate: function (node) {\n fnRegionTreeNodeClick(node);\n },\n onClick: function (node, event) {\n // Close menu on click\n //if ($(event.target).hasClass(\"parent\")) {\n // alert(\"You clicked \" + node + \", url=\" + node.url);\n //}\n if ($(\".contextMenu:visible\").length > 0) {\n $(\".contextMenu\").hide();\n }\n },\n onCreate: function (node, span) {\n bindRegionContextMenu(span);\n },\n onKeydown: function (node, event) {\n // Eat keyboard events, when a menu is open\n\n },\n onDeactivate: function (node) {\n },\n strings: {\n loading: \"Loading…\",\n loadError: \"Load error!\"\n },\n onSelect: function (select, node) {\n // Get a list of all selected nodes, and convert to a key array:\n fnRegionTreeSelect(select, node);\n if (!select) {\n node.visit(function (node) {\n node.select(true);\n });\n }\n else {\n node.visit(function (node) {\n node.select(false);\n });\n }\n },\n onDblClick: function (node, event) {\n node.select(true);\n try {\n inEventHandler = true;\n node.visit(function (childNode) {\n childNode.select(true);\n });\n } finally {\n inEventHandler = false;\n }\n // fnAddNode(node);\n fnBindRegionTreeWithCheckBox(node);\n },\n onPostInit: function (node, event) {\n fnRegionTreePostInit(node);\n }\n });\n\n // vacant user background-color change \n $(\"#\" + id).dynatree(\"getRoot\").visit(function (node) {\n //$(node.span.lastChild).addClass(\"tip\");\n if (node.data.title.split('-')[1] == \"NOT ASSIGNED\") {\n $(node.span).addClass('tree-node-assigned');\n }\n if (node.data.title.split('-')[1] == \"VACANT\") {\n $(node.span).addClass('tree-node-vacant');\n }\n if (node.data.title.split('-')[1] == \"TO BE VACANT\") {\n $(node.span).addClass('tree-node-tobevacant');\n }\n });\n\n $(\"#dvAjaxLoad\").hide();\n $(\"span.childIcon\").unbind(\"click\");\n $(\"span.childIcon\").bind(\"click\", function (e) {\n //alert(\"Edit \" + $.ui.dynatree.getNode(e.target));\n //fnShowChildNodes(e.target);\n e.preventDefault();\n fnAddRegionNode(e);\n return false;\n });\n }\n },\n error: function () {\n $('#' + treeId).unblock();\n },\n complete: function () {\n $('#' + treeId).unblock();\n }\n //}\n });\n}", "function selectTaxa(name, rdist){\n \n console.log(name + \"---\" + rdist);\n var rootIndex=-1;\n for(var i=0; i<taxaTree.length; i++){\n if((taxaTree[i][0]==rdist)&&(taxaTree[i][1]==name)){\n rootIndex=i;\n break;\n }\n }\n console.log(\"rootIndex=\"+rootIndex);\n /*\n var parentIndex=-1;\n for(var i=0; i<taxaTree.length; i++){\n if(taxaTree[i][3].indexOf(taxaTree[rootIndex][1])>-1){\n parentIndex=i;\n }\n }\n\n if(parentIndex<0){\n var searchOutput='<table border=\"3\"><tr><td>Parent</td><td> Undefined</td></tr><tr><td>Current</td><td>'+taxaTree[rootIndex][1]+\" (\"+taxaTree[rootIndex][2]+\")</td></tr><tr><td>Children </td><td>\";\n }else{\n var searchOutput='<table border=\"3\"><tr><td>Parent</td><td> <a href=\"#\" onclick=\"selectTaxa(\\''+taxaTree[parentIndex][1]+'\\','+taxaTree[parentIndex][0]+');\"><font color=\"yellow\" size=\"4\">'+taxaTree[parentIndex][1]+'</font></a> ('+taxaTree[parentIndex][2]+')</td></tr><tr><td>Current</td><td>'+taxaTree[rootIndex][1]+\" (\"+taxaTree[rootIndex][2]+\")</td></tr><tr><td>Children </td><td>\"; \n }\n\n for(var i=0; i<taxaTree[rootIndex][3].length; i++){\n var childNum;\n for(var j=0; j<taxaTree.length; j++){\n if(taxaTree[j][1]==taxaTree[rootIndex][3][i]){\n childNum=taxaTree[j][2];\n break;\n }\n }\n searchOutput+='<a href=\"#\" onclick=\"selectTaxa(\\''+taxaTree[rootIndex][3][i]+'\\','+String(taxaTree[rootIndex][0]+1)+');\"><font color=\"yellow\" size=\"4\">'+taxaTree[rootIndex][3][i]+'</font></a> ('+childNum+')';\n if(childNum>10){\n searchOutput+='&nbsp;<a href=\"load.html?mapid='+String(taxaTree[rootIndex][0]+1)+'_'+taxaTree[rootIndex][3][i]+'&specialmap=mtdna\"><font color=\"yellow\" size=\"4\">Zoom</font></a>';\n }\n searchOutput+='<br>';\n }\n searchOutput=searchOutput+\"</td></tr></table>\";\n document.getElementById(\"searchstatus\").innerHTML=searchOutput;\n */\n document.getElementById(\"tosearch\").value=taxaTree[rootIndex][1];\n startSearch();\n}", "getRegion(regionName) {\n var regions = this._regions || {};\n return regions[regionName];\n }", "getRegionValue(label, cityInfo1){\n let labelArr = label.split(\"/\");\n for (let y in cityInfo1) {\n if (labelArr[0] !== undefined && labelArr[0] === cityInfo1[y].label) {\n for (let z in cityInfo1[y].children) {\n if (labelArr[1] !== undefined && labelArr[1] === cityInfo1[y].children[z].label) {\n for (let i in cityInfo1[y].children[z].children) {\n if (labelArr[2] !== undefined && cityInfo1[y].children[z].children[i].label === labelArr[2]) {\n return [parseInt(cityInfo1[y].value), parseInt(cityInfo1[y].children[z].value), parseInt(cityInfo1[y].children[z].children[i].value)];\n }\n }\n }\n }\n }\n }\n }", "getSelectedRegions() {\r\n const regions = this.lookupSelectedRegions().map((region) => {\r\n return {\r\n id: region.ID,\r\n regionData: region.regionData,\r\n };\r\n });\r\n return regions;\r\n }", "getSelectedRegionsBounds() {\r\n const regions = this.lookupSelectedRegions().map((region) => {\r\n return {\r\n id: region.ID,\r\n x: region.x,\r\n y: region.y,\r\n width: region.boundRect.width,\r\n height: region.boundRect.height,\r\n };\r\n });\r\n return regions;\r\n }", "selectAllRegions() {\r\n let r = null;\r\n for (const region of this.regions) {\r\n r = region;\r\n r.select();\r\n if ((typeof this.callbacks.onRegionSelected) === \"function\") {\r\n this.callbacks.onRegionSelected(r.ID);\r\n }\r\n }\r\n if (r != null) {\r\n this.menu.showOnRegion(r);\r\n }\r\n }", "tree() {\n return trie;\n }", "lookupRegionByID(id) {\r\n let region = null;\r\n let i = 0;\r\n while (i < this.regions.length && region == null) {\r\n if (this.regions[i].ID === id) {\r\n region = this.regions[i];\r\n }\r\n i++;\r\n }\r\n return region;\r\n }", "function getRegionsStatByLevel() {\n return Region.aggregate([\n // Fields for selection. level - formed field of size of parents array, eg. region level\n // Introduced in 2.5.3 https://jira.mongodb.org/browse/SERVER-4899\n { $project: { _id: 0, level: { $size: '$parents' }, pointsnum: 1 } },\n // Calculate indicator for every level\n { $group: { _id: '$level', regionsCount: { $sum: 1 }, pointsCount: { $sum: '$pointsnum' } } },\n // Sort by parent ascending\n { $sort: { _id: 1 } },\n // Retain only the necessary fields\n { $project: { regionsCount: 1, pointsCount: 1, _id: 0 } },\n ]).exec();\n}", "function sortByRegion() {\n if (allNames !== null && allNames.length > 0) {\n allNames.sort((a, b) => {\n var valA = a.region.toLowerCase();\n var valB = b.region.toLowerCase();\n\n var secA = a.name.toLowerCase();\n var secB = b.name.toLowerCase();\n\n var terA = a.surname.toLowerCase();\n var terB = b.surname.toLowerCase();\n\n if (valA < valB) return -1;\n if (valA > valB) return 1;\n\n if (secA < secB) return -1;\n if (secA > secB) return 1;\n\n if (terA < terB) return -1;\n if (terA > terB) return 1;\n\n return 0;\n });\n search();\n }\n}", "lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }", "function extract_regions() {\n var options = {};\n\n for(var id = 0; id < tasks.length; id++) {\n options = {};\n options['id'] = id;\n options['start'] = tasks[id]['start'];\n options['end'] = tasks[id]['end'];\n options['color'] = color1;\n\n wavesurfer.addRegion(options);\n wavesurfer.regions.list[options['id']].editor = tasks[id]['editor'];\n wavesurfer.regions.list[options['id']].language = tasks[id]['language'];\n wavesurfer.regions.list[options['id']].speaker = tasks[id]['speaker'];\n }\n\n populate_segments();\n }", "findTheme(search) {\n if (typeof search== \"string\") search={id: search};\n if (!search) {\n return this.treeMum.getChild();\n }\n function innerFind(search, myTree) {\n if (!myTree) return;\n if (Object.entries(search).every(srch=>Object.entries(myTree.props).find(src=>srch[0]==src[0] && src[1]==srch[1]))) {\n return myTree;\n }\n for (const child of myTree.getRelationship(\"descendents\").children) {\n let result=innerFind(search, child);\n if (result) return result;\n }\n }\n return innerFind(search, this.treeMum.getChild());\n }", "function treeMap() {\n // Get rid of the SVG element, we're using divs here!\n d3.select(\"svg\").remove;\n\n scale = d3.scaleOrdinal() // nice little color map\n .range(d3.schemeCategory10);\n\n root = stratify(dset) // stratify our data, and sum up the total population\n .sum(function(d) { return d.population});\n\n treemap = d3.treemap() // build a treemap object\n .size([640,480])\n .padding(1)\n (root)\n\n d3.select(\"body\") // Nice, plain d3 selectAll().data().enter() syntax\n .selectAll(\".node\")\n .data(root.leaves())\n .enter().append(\"div\")\n .attr(\"class\", \"node\") // Next, set the size of the squares\n .style(\"left\", function(d) { return d.x0 + \"px\"; })\n .style(\"top\", function(d) { return d.y0 + \"px\"; })\n .style(\"width\", function(d) { return d.x1 - d.x0 + \"px\"; })\n .style(\"height\", function(d) { return d.y1 - d.y0 + \"px\"; })\n .style(\"background\", function(d){ while(d.depth > 1) d = d.parent; return scale(d.id);}) // Color based on province\n .append(\"div\")\n .attr(\"class\", \"node-label\") // Add city name\n .text(function(d) { return d.id})\n .append(\"div\")\n .attr(\"class\", \"node-value\") // Add city population\n .text(function(d) { return d.value});\n}", "function region(n) {\n if (n == regions[n]) return n;\n var r = region(regions[n])\n regions[n] = r\n return r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FizzBuzz is often one of the first programming puzzle people learn. Now undo it with reverse FizzBuzz! Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz. Notes: If the sequence can appear multiple times within FizzBuzz, return the numbers that generate the first instance of that sequence. All numbers in the sequence will be greater than zero. You will never receive an empty sequence. Examples reverse_fizzbuzz("1 2 Fizz 4 Buzz") > [1, 2, 3, 4, 5] reverse_fizzbuzz("Fizz 688 689 FizzBuzz") > [687, 688, 689, 690] reverse_fizzbuzz("Fizz Buzz") > [9, 10]
function reverseFizzBuzz(s) { let newS = s.split(' '); let firstNumberFound = []; let result = []; for(let i = 0; i < newS.length; i++){ if(parseInt(newS[i]) > 0){ firstNumberFound.push(i, newS[i]); break; }; }; if(firstNumberFound.length > 0){ let start = parseInt(firstNumberFound[1]) - firstNumberFound[0]; for(let i = start; i <= (start + newS.length) - 1; i++){ result.push(i); }; } else { if(s == 'FizzBuzz'){ result = [15]; } else if(s == 'Fizz Buzz'){ result = [9, 10]; } else if(s == 'Buzz Fizz'){ result = [5,6]; } else if(s == 'Fizz'){ result = [3]; } else if(s == 'Buzz'){ result = [5]; }; }; return result; }
[ "function fizzBuzzFactory(arr, arg) {\n let valueArr = [];\n let wordArr = [];\n\n arr.forEach((item) => {\n valueArr.push(item[0]);\n wordArr.push(item[1]);\n });\n\n let maxInd = valueArr.indexOf(Math.max(...valueArr));\n let minInd = valueArr.indexOf(Math.min(...valueArr));\n let midInd = 0;\n if (maxInd + minInd === 1) {\n midInd += 2;\n }\n if (maxInd + minInd === 2) {\n midInd += 1;\n }\n\n if (arg % Number(valueArr[maxInd]) === 0) {\n return wordArr[maxInd];\n }\n if (\n arg % Number(valueArr[midInd]) === 0 &&\n arg % Number(valueArr[maxInd]) !== 0\n ) {\n return wordArr[midInd];\n }\n if (\n arg % Number(valueArr[minInd]) === 0 &&\n arg % Number(valueArr[maxInd]) !== 0 &&\n arg % Number(valueArr[midInd]) !== 0\n ) {\n return wordArr[minInd];\n } else {\n return String(arg);\n }\n}", "function fizzBuzz(start, stop) {\n let res = '';\n let first = true;\n let fizz = false;\n\n for (let ix = start; ix <= stop; ix++) {\n if (start >= stop) {\n return 'start must be lower then stop';\n }\n if (first) {\n first = false;\n } else {\n res += ',';\n }\n if (ix % 3 === 0 || ix % 5 === 0) {\n if (ix % 3 === 0) {\n res += 'Fizz';\n fizz = true;\n }\n if (ix % 5 === 0) {\n if (fizz) {\n res += ' ';\n }\n res += 'Buzz';\n }\n fizz = false;\n } else {\n res += ix;\n }\n }\n return res;\n}", "function fizzBuzz(max){\n\n resulting_array2 = [];\n\n for (i = 1; i < max; i++) {\n\n if (((i % 3 === 0) ||(i % 5 === 0)) && (!(i % 15 === 0))) {\n resulting_array2.push(i);\n }\n\n }\n\n return resulting_array2;\n\n}", "function ListFizzBuzz(Value) {\n for (var i = 0; i < Value; i++) {\n if(i%3 != 0 && i%5 != 0){\n $(\"body\").append('<li>' + i + '</li>');\n };\n if(i%3 == 0) {\n $(\"body\").append('<li>' + \"fizz\" + '</li>');\n };\n if(i%5 == 0) {\n $(\"body\").append('<li>' + \"buzz\" + '</li>');\n };\n if(i%3 == 0 && i%5 == 0) {\n $(\"body\").append('<li>' + \"fizzbuzz\" + '</li>');\n };\n };\n }", "function doFizzBuzz(incomingNumber) {\n// find out if it's a multiple of 5\n\n\tif(incomingNumber % 5 === 0 ) {\n\t\tconsole.log(\"fizz\");\n\t}\n\t// find out if its a multiple of 3\n\telse(incomingNumber % 3 === 0) {\n\t\tconsole.log(\"buzz\");\n\t}\n}", "function invertirUnaPalabra(String){\r\n let alreves = \"\";\r\n let tamano = 3;\r\n let array = String.split(\"\");\r\n for(let i = tamano; i >= 0; i--){\r\n alreves+= array[i];\r\n }\r\n console.log(\"La palabra al reves es: \"+ alreves);\r\n return alreves;\r\n}", "function fizzBuzz() {\r\n for (let i = 0; i <= 100; i++) {\r\n if (i % 3 === 0 && i % 5 === 0) { // i % 15 === 0 will include both 3 & 5 multiples.\r\n console.log('FizzBuzz')\r\n } else if (i % 3 === 0) { // Using modular operator.\r\n console.log('Fizz');\r\n } else if (i % 5 === 0) {\r\n console.log('Buzz')\r\n } else {\r\n console.log(i);// console.log(i);// Prints all numbers from 0-100 in console.\r\n }\r\n }\r\n\r\n}", "function lookAndSaySequence(num) {\n let str = num.toString();\n let result = '';\n\n for (var i = 0; i < str.length; i++) {\n if (str[i] === str[i - 1]) {\n continue;\n };\n\n let count=1;\n while (str[i] === str[i+count]) {\n count++;\n };\n\n result += (count.toString() + str[i]);\n }\n\n return parseInt(result);\n}", "function fizzHandler(e) {\n e.preventDefault();\n var startVal = document.getElementById(\"number_start\").value;\n var endVal = document.getElementById(\"number_end\").value;\n fuzzBuzz.input(parseInt(startVal), parseInt(endVal));\n result = fuzzBuzz.output();\n renderHeading(startVal, endVal);\n renderList();\n}", "function fibonacciSequence(n) {\n let fibs = [1, 1];\n for (i = 2; i < n; i++) {\n fibs.push(fibs[fibs.length - 2] + fibs[fibs.length - 1] % 10)\n }\n return fibs;\n}", "function indexShuffler(input) {\n input = parseInt(input);\n if (Number.isInteger(input) === false) {\n // console.log(\"Index shuffler function failed. The input was \" + input);\n }\n else {\n var sourceValues = [];\n for (i = 0; i < input; i++) {\n sourceValues.push(i);\n } \n // console.log(\"The input was \" + input + \"and the source values generated were\" + sourceValues + \".\");\n }\n // destructively pull out values from sourceValues at random\n var shuffledValues = [];\n while (sourceValues.length > 0) {\n var pickAValue = Math.floor(Math.random() * sourceValues.length);\n var yankedValue = sourceValues.splice(pickAValue, 1);\n shuffledValues.push(yankedValue);\n }\n return shuffledValues;\n}", "function shuffleArray() {\r\n\r\n var startArray = []; // a temporary array with only this function scope to hold copy of input array\r\n\r\n var i = 0;\r\n var inValue = 0;\r\n\r\n\r\n // fill input array (for history and any possible displayInput calls) and our temp start array with input array values from page\r\n for (i = 0; i < 9; i++) {\r\n inValue = document.getElementById(\"input\" + i).value;\r\n\r\n G_inputArray[i] = inValue;\r\n startArray[i] = inValue;\r\n\r\n }// end for\r\n\r\n // empty the outputarray\r\n while (G_outputArray.length > 0) {\r\n G_outputArray.splice(0, G_outputArray.length); // clear old array\r\n }\r\n\r\n\r\n // now shuffle startArray and put values into output array\r\n\r\n while (startArray.length > 0) {\r\n let rnd = Math.floor(Math.random() * startArray.length);\r\n G_outputArray.push(startArray[rnd]); // add new one to the output array\r\n startArray.splice(rnd, 1); // remove it from temp start array\r\n }\r\n\r\n\r\n displayOutput(); // display results!\r\n\r\n} // end shuffle array", "function getWordSequence() {\n \n var wordseq = [];\n if (!debugging) {\n // sets the words assuming there are eight, with 24 reps each\n for (var i=0; i<192; i++) {\n wordseq[i] = i%8;\n }\n // puts in one of the words for them to recognise\n wordseq[192] = 999;\n wordseq[193] = 999;\n wordseq[194] = 999;\n wordseq[195] = 999;\n wordseq[196] = 999;\n wordseq = shuffleArrayNoRepeats(wordseq);\n } else {\n // when debugging only shows three words\n wordseq[0] = 3;\n wordseq[1] = 6;\n wordseq[2] = 999;\n wordseq[3] = 2;\n }\n return wordseq;\n}", "function solution(str) {\n let result = [];\n let copy = str.split('');\n\n while(copy.length > 0) {\n let pairs = copy.splice(0, 2);\n result.push(pairs.join(''));\n\n if(copy.length === 1) {\n let odd = copy.pop() + '_';\n result.push(odd);\n }\n }\n\n return result;\n}", "function fibbonacci(n) {\n var uitkomst = [];\n\n // the magic starts here...\n\n\n\n return uitkomst;\n}", "function obtenerRango(arreglo,casos)\n{\n for(i=1; i <= casos; i++)\n {\n inicial_final = arreglo[i].split(\" \");\n inicio = parseInt(inicial_final[0]);\n fin = parseInt(inicial_final[1]);\n buscarCuadrados(inicio,fin); //Buscar cuadrados perfectos dentro del rango\n }\n}", "getDisplayNumber(number) {\n\n let displayNumber = '';\n\n if (number % 3 === 0) { // multiple of 3\n displayNumber += 'Fizz';\n }\n\n if (number % 5 === 0) { // multiple of 5\n displayNumber += 'Buzz';\n }\n\n // If displayNumber has a value, return the string\n if (displayNumber) {\n return displayNumber;\n }\n\n // else, just return the number\n return number;\n\n }", "function genScramble(length) {\n var prevMove = -1, secPrevMove = -1, scramble = \"\";\n for (i = 0; i < length; i++) {\n var move = Math.floor((Math.random() * 6)),\n dir = Math.floor((Math.random() * 3));\n if (((prevMove == 0) && (secPrevMove != 1)) || ((prevMove == 1) && (secPrevMove != 0)) ||\n ((prevMove == 2) && (secPrevMove != 3)) || ((prevMove == 3) && (secPrevMove != 2)) ||\n ((prevMove == 4) && (secPrevMove != 5)) || ((prevMove == 5) && (secPrevMove != 4)))\n secPrevMove = -1;\n while ((move == prevMove) || (move == secPrevMove))\n move = Math.floor((Math.random() * 6));\n switch (move) {\n case 0: scramble = scramble.concat(\"U\"); break;\n case 1: scramble = scramble.concat(\"D\"); break;\n case 2: scramble = scramble.concat(\"L\"); break;\n case 3: scramble = scramble.concat(\"R\"); break;\n case 4: scramble = scramble.concat(\"F\"); break;\n case 5: scramble = scramble.concat(\"B\"); break;\n }\n switch (dir) {\n case 1: scramble = scramble.concat(\"'\"); break;\n case 2: scramble = scramble.concat(\"2\"); break;\n }\n secPrevMove = prevMove;\n prevMove = move;\n if (i < length - 1)\n scramble = scramble.concat(\" \");\n }\n return scramble;\n}", "function palindromize(number){\n let numStr = number.toString();\n let numStrRev = numStr.split('').reverse().join('');\n let ctr = 0;\n \n while(numStr != numStrRev){\n numStr = (+numStr + +numStrRev).toString();\n numStrRev = numStr.split('').reverse().join('');\n ctr++;\n };\n \n return ctr + ' ' + numStr;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uncomment when ready to test ~~~~BONUS Write a function that will print the id of each test and the name of the student who got the highest scores Example printBestStudent(students3) Test 0: Anthony Test 1: Pawandeep Test 2: Winnie
function printBestStudent(students) { //your code here... for (let i = 0; i < students.length; i++) { //iterates through students // console.log(students[i]["name"],students[i]["grades"] ); let student = students[i]; let grades = student.grades; // let bestGrade = grades[0].score; // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one //so we then need to compare all the grades in that array let sum = 0; for (let j = 0; j < grades.length; j++) { //iterates through grades sum += grades[j].score; } let avgScore = sum / grades.length; console.log("Test "+ student.id+": "+student.name); } }
[ "function printBestStudents(students) {\n var bestScores = {};\n\n for (var i = 0; i < students.length; i++) {\n var student = students[i];\n\n for(var j = 0; j < student.grades.length; j ++){\n var grade = student.grades[j];\n\n if(bestScores[grade.id] === undefined){\n bestScores[grade.id] = {name: student.name, score: grade.score};\n }\n else if (bestScores[grade.id].score < grade.score) {\n bestScores[grade.id] = {name: student.name, score: grade.score};\n }\n }\n }\n\n for(var id in bestScores){\n console.log(\"Test\", id, \":\", bestScores[id].name);\n }\n}", "function printBestGrade(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n let score = grades[j].score;\n //now check and see if bestGrade < score\n //if yes then bestGrade = score\n if (bestGrade < score) {\n bestGrade = score;\n }\n\n }\n console.log(student.name, bestGrade);\n }\n}", "function highestGrade() {\n let sortOrderArray = scores.sort(function(a, b) \n { return b - a});\n console.log(\"Highest Grade: \", sortOrderArray[0]);\n}", "function printStudents(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) {\n console.log(students[i][\"name\"]+ \" is student #\" + students[i][\"id\"]);\n // console.log(students[i].name);\n }\n}", "function testMax() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"max\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const numbers of parameters[0].values) {\n const functionCall = `max(${format(numbers)})`;\n const expected = staff.max(numbers);\n const actual = student.max(numbers);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`max -- passed ${pass} out of ${tc} test cases.`);\n}", "function printAverageGrades(students) {\n for (var i = 0; i < students.length; i++) {\n var student = students[i];\n var averageGrade = getAverageGrade(student.grades);\n\n console.log(student.name, averageGrade);\n }\n}", "function mostCommonGrade() {\n let currentGradeCount = 0;\n let mostCommonGrade;\n\n for (var prop in grades) {\n // checks if the value at the current property is less than the current grade counter. Then makes the counter equal the value of that property and assigns that property name (grade) to the variable mostCommonGrade. \n if (currentGradeCount < grades[prop]) {\n currentGradeCount = grades[prop];\n mostCommonGrade = prop;\n } \n // If the value is equal to the counter, then this appends the property name (grade) to the mostCommonGrade variable to keep a list of all the grades that have the same amount of scores when there is more than one. \n else if (currentGradeCount === grades[prop]) {\n currentGradeCount = grades[prop];\n mostCommonGrade += \", \" + prop;\n }\n\n }\n // This will output a list of the grade(s) with the most amount of scores and put the number of scores next to it. \n console.log('The most common grade(s): ', mostCommonGrade, \"-\", currentGradeCount)\n}", "function printAverageGrade(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n // let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n let sum = 0;\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n sum += grades[j].score;\n\n }\n let avgScore = sum / grades.length;\n console.log(student.name, avgScore);\n }\n}", "function list() { console.log(students); }", "function test_utility_logSortedData(studentData) {\n\n var formattedTestString = \"[\";\n for (var i = 0; i < studentData.length; ++i){\n formattedTestString += `{ \"_id\": \"${studentData[i].id}\", \"name\": \"${studentData[i].name}\", \"grade\": ${studentData[i].grade} } `\n\n if (i != studentData.length - 1) {\n formattedTestString += \", \"\n }\n\n }\n\n formattedTestString += \"]\"\n // console.log(studentData);\n console.log(formattedTestString);\n}", "function print(players) {\n\n\tvar scoreStack = new Array();\n\n\t// Simplified player object to ease sorting.\n\tfunction PlayerScore(name, playerObj) {\n\t\tthis.name = name;\n\t\tthis.playerObj = playerObj;\n\t\tthis.score = playerObj.totalScore();\n\t}\n\n\t// Convert the original player objects into something more workable.\n\tfor (var playersName in players) {\n\n\t\t// Grab the next element in the array.\n\t\tvar player = players[playersName];\n\n\t\t// Create the simplified PlayerScore object.\n\t\tvar scoreObj = new PlayerScore(playersName, player);\n\n\t\t// Add it on the stack to be sorted later.\n\t\tscoreStack.push(scoreObj);\n\t}\n\n\t// Sort the list of PlayerScore items into order of who score the most.\n\tvar sorted = new insertionSort('score', scoreStack);\n\n\t// Print out the scoreboard in the correct order.\n\tfor (var i = sorted.length -1; i >= 0 ; i--) {\n\n\t\t// Get next element in array.\n\t\tvar obj = sorted[i];\n\n\t\t// Build the string for the next line in the score board.\n\t\tvar score = 'Player: ' + obj.name + ' Scored: ' + obj.score;\n\n\t\t// Colour the text a specific colour depending on what row.\n\t\tvar text = ((i % 2) == 0) ? score.green : score.blue;\n\n\t\t// Print the row.\n\t\tconsole.log(text);\n\t}\n\n}", "displayTopEightMatchedRespondents() {\n console.log(\"\\nTop 8 matches- by matching scores:\");\n console.log(\"===================================\\n\");\n\n for (let i = 0; i < 8; i++) {\n const curr = this.results[this.results.length - 1 - i];\n console.log(i);\n console.log(\n `Name: ${curr.name.slice(0, 1).toUpperCase()}${curr.name.slice(\n 1\n )}`\n );\n console.log(\n `Distance to closest available city: ${curr.closestAvailableCity.distance}km`\n );\n console.log(`Matching Score: ${curr.score}`);\n console.log(\"-------------------------------\");\n }\n }", "function getStudentTopNotes(students) {\n\treturn students.map(x => Math.max(...x.notes, 0));\n}", "function matchUsers(studentList, coachList) {\n\tvar studentIndex = 0;\n\twhile (studentIndex < studentList.length) {\n\t\tvar i = 0;\n\t\tvar highestIndex = 0;\n\t\tvar highestQuotient = 0;\n\n\t\t// Iterate through list of coaches\n\t\twhile (i < coachList.length) {\n\t\t\tquotient = calculateQuotient(studentList[studentIndex], coachList[i]);\n\t\t\tif (quotient > highestQuotient) {\n\t\t\t\thighestQuotient = quotient;\n\t\t\t\thighestIndex = i;\n\t\t\t}\n\t\t\ti += 1;\n\t\t}\n\n\t\tif (highestQuotient > 0) {\n\t\t\tconsole.log(\"Student: \" + studentList.splice(studentIndex, 1)[0].name);\n\t\t\tconsole.log(\"Coach: \" + coachList.splice(highestIndex, 1)[0].name);\n\t\t\tconsole.log(\"Quotient: \" + highestQuotient);\n\t\t\tconsole.log('\\n');\n\t\t} else {\n\t\t\t// If no match found, proceed to the next student in the list\n\t\t\tstudentIndex += 1;\n\t\t}\n\t}\n}", "function lowestGrade() {\n let sortOrderArray = scores.sort(function(a, b) \n { return a - b});\n console.log(\"Lowest Grade: \", sortOrderArray[0]);\n}", "function displayScore()\n{\n\tconsole.log(\"Time taken: \" + Math.floor(timeTaken/60));\n\tconsole.log(\"Stars: \" + inventory[0][4] + \" picked up.\");\n\tconsole.log(\"Bombs: \" + inventory[1][4] + \" picked up, \" + inventory[1][5] + \" used.\");\n\tconsole.log(\"Lives: \" + inventory[3][4] + \" picked up, \" + inventory[3][5] + \" used.\");\n}", "function extractMax(table, studentArray, houseName) {\n let currentRank = table.getRank(houseName, studentArray[0]);\n let newRank = 0;\n // the highest rank \"bubbles\" to the end of the array\n for (let i = 0; i < studentArray.length - 1; i++) {\n newRank = table.getRank(houseName, studentArray[i + 1]);\n if (currentRank > newRank) {\n let temp = studentArray[i];\n studentArray[i] = studentArray[i + 1];\n studentArray[i + 1] = temp;\n } else {\n currentRank = newRank;\n }\n }\n let student = studentArray.pop();\n return student;\n}", "function generateCriteriaTable(studentRow, maxMarksRow) {\n\tvar result = [\n\t\t[\n\t\t\t{ text: 'Criterion', style: 'semibold', fillColor: '#eeeeee' },\n\t\t\t{ text: 'Available\\nmarks', style: 'semibold', fillColor: '#eeeeee' },\n\t\t\t{ text: 'Your mark', style: 'semibold', fillColor: '#eeeeee' },\n\t\t]\n\t];\n\n\tObject.keys(config.columns.criteriaSections).forEach(function(sectionTitle) {\n\t\t// Print a whole-row header for this criteria section\n\t\tresult.push([ { colSpan: 3, text: sectionTitle, style: 'semibold' } ]);\n\n\t\t// Then print a row for each criterion in this section\n\t\tObject.keys(config.columns.criteriaSections[sectionTitle]).forEach(function(criterion) {\n\t\t\tvar marksColumn = columnToIndex(config.columns.criteriaSections[sectionTitle][criterion]);\n\t\t\tvar marks = studentRow[marksColumn];\n\t\t\tvar maxMarks = maxMarksRow[marksColumn];\n\n\t\t\tresult.push([\n\t\t\t\t{ text: criterion, margin: [12, 0] },\n\t\t\t\tmaxMarks || '',\n\t\t\t\t{ text: marks, style: 'semibold', color: '#0011cc' }\n\t\t\t]);\n\t\t});\n\t});\n\n\tvar totalColumn = columnToIndex(config.columns.totalMarks);\n\tresult.push([\n\t\t{ text: 'Overall mark for ' + config.assignmentName, style: 'semibold', fillColor: '#eeeeee' },\n\t\t{ text: maxMarksRow[totalColumn], style: 'semibold', fillColor: '#eeeeee' },\n\t\t{ text: studentRow[totalColumn], color: '#0011cc', style: 'bold', fillColor: '#eeeeee' },\n\t]);\n\n\treturn result;\n}", "function mostFavorableGrid(){\r\n var bestGrid = 0;\r\n var index = 0;\r\n for(var i = 0; i < fitness.length; i++){\r\n if(fitness[i] > bestGrid){\r\n bestGrid = fitness[i];\r\n index = i;\r\n }\r\n }\r\n //console.log(\"Most favorable grid is grid:\" + index);\r\n\tdocument.getElementById(\"favGrid\").innerHTML = \"Grid #\" + index;\r\n return index;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2 arrays of integers a and b of the same length integer k output integer number of tiny pairs pairs (x, y) such that x is from a and y is from b iterating through array a from left to right iterating through b from right to left to be tiny, the concatenation xy is less than k solved; 30/30
function countTinyPairs(a, b, k) { let revB = b.reverse(); let tinyCount = 0; for (let index = 0; index < a.length; index++) { const elementA = a[index]; const elementB = revB[index]; let concat = elementA + "" + elementB; concat = parseInt(concat); if (concat < k){ tinyCount += 1; } } return tinyCount; }
[ "function polyvecPointWiseAccMontgomery(a, b, paramsK) {\r\n var r = polyBaseMulMontgomery(a[0], b[0]);\r\n var t;\r\n for (var i = 1; i < paramsK; i++) {\r\n t = polyBaseMulMontgomery(a[i], b[i]);\r\n r = polyAdd(r, t);\r\n }\r\n return polyReduce(r);\r\n}", "function merge(x, y, len_x) {\n // cnt is number of out of order triples\n // res is the new sorted array(each element is tri)\n // x and y are going to be combined\n // len_x is number of elements that have not been added to the new array\n // used_y is number of elements that have been added to the new array\n function helper(cnt, res, x, y, len_x, used_y) {\n if(is_empty_list(x) && is_empty_list(y)) {\n return pair(cnt, res);\n } else if(is_empty_list(x)) {\n const yy = head(y);\n const num_y = head(yy);\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n return helper(cnt, append(res, list(tri(num_y,\n lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n } else if(is_empty_list(y)) {\n const xx = head(x);\n const num_x = head(xx);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n const xx = head(x);\n const yy = head(y);\n const num_x = head(xx);\n const num_y = head(yy);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n if(num_x <= num_y) {\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n return helper(cnt + len_x * rt_y,\n append(res, list(tri(num_y,\n len_x + lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n }\n }\n }\n return helper(0, [], x, y, len_x, 0);\n }", "function divisibleSumPairs(n, k, ar) {\n\nvar cnt = 0, i = 0, j = 0;\nfor(i=0;i<ar.length-1;i++){\n for(j=i+1;j<ar.length;j++){\n if((ar[i]+ar[j])%k==0){\n cnt++;\n }\n }\n}\nreturn cnt;\n}", "function helper(cnt, res, x, y, len_x, used_y) {\n if(is_empty_list(x) && is_empty_list(y)) {\n return pair(cnt, res);\n } else if(is_empty_list(x)) {\n const yy = head(y);\n const num_y = head(yy);\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n return helper(cnt, append(res, list(tri(num_y,\n lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n } else if(is_empty_list(y)) {\n const xx = head(x);\n const num_x = head(xx);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n const xx = head(x);\n const yy = head(y);\n const num_x = head(xx);\n const num_y = head(yy);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n if(num_x <= num_y) {\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n return helper(cnt + len_x * rt_y,\n append(res, list(tri(num_y,\n len_x + lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n }\n }\n }", "function intertwineArrays(a, b) {\n var c = [];\n for (var i = 0; i < a.length; i++) {\n c[c.length] = a[i];\n c[c.length] = b[i];\n }\n return c;\n}", "function makeAnagrams(a, b) {\n // O(n*m) approach due to iterating through lengths of both inputs\n let count = 0;\n let arrA = a.split(\"\");\n let arrB = b.split(\"\");\n let totalLength = arrA.length + arrB.length;\n for (let i = 0; i < arrA.length; i++) {\n for (let j = 0; j < arrB.length; j++) {\n if (arrA[i] === arrB[j]) {\n arrB.splice(j, 1);\n count++;\n break;\n }\n }\n }\n return totalLength - count * 2;\n}", "function kgen(key) {\r\n\r\n let result = new Array()\r\n\r\n let t\r\n let u = new Array()\r\n\r\n t = Shuffle(key, p10)\r\n\r\n //console.log(\"key through p10 : \" + t)\r\n t = splitAt((t.length / 2))(t)\r\n //console.log(\"key through first split : \" + t[0] + \" and \" + t[1])\r\n t[0] = Shift(t[0], 1)\r\n t[1] = Shift(t[1], 1)\r\n //console.log(\"key fragments through shifts for k1 : \" + t[0] + \" and \" + t[1])\r\n //aqui no recuerdo si es un shift de -1 o de -2 sobre del anterior\r\n u[0] = Shift(t[0], 2)\r\n u[1] = Shift(t[1], 2)\r\n //console.log(\"key fragments through another shift for k2 : \" + u[0] + \" and \" + u[1])\r\n\r\n let k1\r\n let k2\r\n\r\n k1 = Stitch(t[0], t[1])\r\n k2 = Stitch(u[0], u[1])\r\n\r\n k1 = Shuffle(k1, p8)\r\n k2 = Shuffle(k2, p8)\r\n\r\n result[0] = k1\r\n result[1] = k2\r\n\r\n //k1 and k2 might return more elements than what we want\r\n return result\r\n}", "nCr_wo_repitition_3(n, r) {\r\n // ht tps://www.geeks forgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/\r\n // This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn2(n, r, index, tmp, i) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // When no more elements are there to put in tmp[]\r\n if (i >= n) return;\r\n\r\n // current is included, put next at next location\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn2(n, r, index + 1, tmp, i + 1);\r\n\r\n // current is excluded, replace it with next (Note that\r\n // i+1 is passed, but index is not changed)\r\n nCr_wo_reptn2(n, r, index, tmp, i + 1);\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn2(n, r, 0, tmp, 0);\r\n\r\n return res;\r\n }", "nCr_wo_repitition_2(n, r) {\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn(tmp, start, end, index, r) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // replace index with all possible elements. The condition\r\n // \"end-i+1 >= r-index\" makes sure that including one element\r\n // at index will make a combination with remaining elements\r\n // at remaining positions\r\n for (let i = start; i <= end && end - i + 1 >= r - index; i++) {\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn(tmp, i + 1, end, index + 1, r);\r\n }\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn(tmp, 0, n - 1, 0, r);\r\n\r\n return res;\r\n }", "function fpb(angka1, angka2) {\n // you can only write your code here!\n let subFactor1 = getSubFactor(angka1)\n let subFactor2 = getSubFactor(angka2)\n let result = []\n\n for (let i = 0; i < subFactor1.length; i++) {\n for (let j = 0; j < subFactor2.length; j++) {\n if (subFactor1[i] == subFactor2[j]) {\n result.push(subFactor1[i])\n }\n }\n }\n return result[result.length - 1]\n}", "function sol(nums, k) {\n const totalSum = nums.reduce((acc, val) => acc + val, 0);\n const targetSubsum = totalSum / k;\n\n if (k === 0 || totalSum % k !== 0) return false;\n\n // startIdx, array of booleans(indices of numbers that have been used), number of buckets, sum of current bucket\n return canPartition(0, Array(nums.length).fill(false), k, 0);\n\n function canPartition(start, used, k, inProgressBucketSum) {\n // Time Complexity: O(k ^ { N- k} k!) O(k\n // N−k\n // k!), where NN is the length of nums, and kk is as given.As we skip additional zeroes in groups, naively we will make O(k!)O(k!) calls to search, then an additional O(k ^ { N- k}) O(k\n // N−k\n // ) calls after every element of groups is nonzero.\n\n // Space Complexity: O(N)O(N), the space used by recursive calls to search in our call stack.\n\n // if all but the last bucket are filled with the correct sum, then the remaining bucket can definitely be filled correctly\n // nums = [4, 3, 2, 3, 5, 2, 1]\n // eg subsum = 5, [1,4], [2,3], [2,3], [...whatever is left in nums] === [5]\n if (k === 1) return true;\n\n // current bucket sum === target\n // move to next bucket\n if (inProgressBucketSum === targetSubsum) {\n return canPartition(0, used, k - 1, 0);\n }\n\n for (let i = start; i < nums.length; i++) {\n // if number not used\n if (!used[i]) {\n // CHOOSE THE NUMBER\n // select the num from the nums\n // and set corresponding idx in used arr to true\n used[i] = true;\n if (canPartition(i + 1, used, k, inProgressBucketSum + nums[i])) {\n return true;\n }\n // UNCHOOSE THE NUMBER\n used[i] = false;\n }\n }\n return false;\n }\n}", "function inner_product(a,b) {\n\tvar s = 0;\n\tif (typeof a ==='undefined' || typeof b ==='undefined'){\n\t\treturn undefined;\n\t}\n\telse {\n\t\tif (a.length != b.length){\n\t\t\treturn undefined;\n\t\t}\n\t\telse {\n\t\t\tfor (var i=0;i<a.length;i++){\n\t\t\t\t\n\t\t\t\ts = a[i]*b[i] + s;\n\t\t\t\t\n\t\t\t}\n\t\t\treturn s;\n\t\t}\t\n\t}\n}", "function minSwapForTogather(array, k) {\n //good means biger then given k\n\n let good = 0;\n for (let i in array) {\n if (array[i] <= k)\n good++;\n }\n\n // bad for element who's biger then k\n let bad = 0;\n for (let i = 0; i < good; i++) {\n if (array[i] > k)\n bad++;\n }\n\n let ans = bad;\n let i = 0;\n let j = good;\n while (j < array.length) {\n if (array[i] > k) {\n bad--;\n }\n if (array[j] > k) {\n bad++;\n }\n ans = min(ans, bad);\n i++;\n j++;\n }\n return ans;\n}", "function commonTwo(a, b) {\n let count = 0;\n let uniq = [];\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n if (a.length < b.length) {\n if (b.includes(a[i]) && !(uniq.includes(a[i]))) {\n count++;\n uniq.push(a[i]);\n }\n } else {\n if (a.includes(b[i]) && !(uniq.includes(b[i]))) {\n count++;\n uniq.push(b[i]);\n }\n }\n }\n return count;\n}", "function cal_kb(xy_points){\n\t/*\n\t// formula for k and b\n\tk =( n(x1y1+x2y2+...+xnyn)-(x1+...+x2)(y1+...+yn) ) / ( n(x1^2+x2^2+...+xn^2) - (x1+...+x2)^2 )\n\tb = (y1+...+yn)/n - k*(x1+...+x2)/n\n\t*/\n\tvar n = xy_points.length;\n\tvar xy_sum = 0,x2_sum = 0,y2_sum = 0;\n\tvar x_sum = 0,y_sum = 0;\n\t\n\tfor(var i=0;i<n;i++){\n\t\txy_sum += xy_points[i].x * xy_points[i].y;\n\t\tx2_sum += xy_points[i].x * xy_points[i].x;\n\t\ty2_sum += xy_points[i].y * xy_points[i].y;\n\t\t\n\t\tx_sum += xy_points[i].x;\n\t\ty_sum += xy_points[i].y;\n\t}\n\t\n\tvar k = (n*xy_sum - x_sum*y_sum)/(n*x2_sum - x_sum*x_sum);\n\tvar b = y_sum/n - k* x_sum/n;\n\treturn {k:k,b:b};\n}", "function multiPointer(arr){\n let i = 0;\n let j = arr.length - 1;\n while(i < j){\n if (arr[i] + arr[j] === 0){\n return [arr[i], arr[j]];\n } else {\n if (arr[i] + arr [j] < 0){\n i++;\n } else {\n j--;\n }\n }\n }\n console.log('no pair');\n return false;\n}", "function calculateBias_order(indexMap1,indexMap2){\n var bias=0;\n for(var i=0;i<len+1;i++){\n bias+=Math.abs(indexMap1[i]-indexMap2[i])\n }\n return bias;\n }", "function getSubPrimes(p, idx, k){\n\tdebug.log(5, \"!! getSubPrimes():\");\n\tdebug.log(7, arguments);\n\tgetPrimes(p, idx+2);\n\t\n\tvar sum = 0;\n\tvar mp = get_mp(p, 0, idx, Math.floor(p[idx]/k));\n\tvar i = mp - Math.floor(k/2) < 0 ? 0 : mp - Math.floor(k/2);\n\tfor (var j=i; j<i+k; j++){ sum += p[j];}\n\tdebug.log(6, \"i: \"+i+\", p[\"+idx+\"]: \"+p[idx]+\", sum: \"+sum);\n\tdebug.log(8, \"getSubPrimes(): p[\"+i+\"] (\"+p[i]+\") * \"+k+\n\t\t\" (\"+p[i]*k+\") < p[\"+idx+\"] (\"+p[idx]);\n\tdebug.log(8, \"getSubPrimes(): p[\"+(i+k-1)+\"] (\"+p[i+k-1]+\") * \"+k+\n\t\t\" (\"+p[i+k-1]*k+\") > p[\"+idx+\"] (\"+p[idx]);\n\n\tif (sum < p[idx]){\n\t\twhile (sum < p[idx] && i<=mp){\n\t\t\ti++;\n\t\t\tsum += p[i+k-1]-p[i-1];\n\t\t\tdebug.log(6, \"new i: \"+i+\", new sum: \"+sum);\n\t\t}\n\t} else if (sum > p[idx]){\n\t\twhile(sum > p[idx] && i>0 && i+k>mp){\n\t\t\ti--;\n\t\t\tsum -= p[i+k]-p[i];\n\t\t\tdebug.log(6, \"new i: \"+i+\", new sum: \"+sum);\n\t\t}\n\t}\n\n\tif (sum === p[idx]){return i;}\n\treturn -1; // else\n\n\twhile (p[i+k-1]*k < p[idx]) {i++;}\n\tdebug.log(4, \"getSubPrimes(): p[\"+(i+k-1)+\"] (\"+p[i+k-1]+\") * \"+k+\n\t\t\" (\"+p[i+k-1]*k+\") > p[\"+idx+\"] (\"+p[idx]);\n\twhile (p[i]*k < p[idx]){\n\t\tif (sum === 0){\n\t\t\tfor (var j=i; j<i+k; j++){ sum += p[j];}\n\t\t} else{\n\t\t\tsum += p[i+k]-p[i];\n\t\t}\n\t\tdebug.log(4, \"sum: \"+sum+\", i: \"+i);\n\t\tif (sum === p[idx]){\n\t\t\treturn i;\n\t\t}\n\t\ti++;\n\t}\n\treturn -1;\n}", "function timePlanner(a, b, duration) {\n let aCount = 0;\n let bCount = 0;\n \n while (aCount < a.length && bCount < b.length) {\n const start = Math.max(a[aCount][0], b[bCount][0]);\n const end = Math.min(a[aCount][1], b[bCount][1]);\n\n if (start + duration <= end) {\n return [start, start + duration];\n }\n \n if (a[aCount][1] < b[bCount][1]) {\n aCount++;\n } else {\n bCount++;\n }\n }\n \n return [];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isThereADoorToGoToRoom function Checks whether the player can access a room or not, based on the doors in the current room
function isThereADoorToGoToRoom (handlerInput, room){ const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); // get the doors in the currentRoom const currentRoomDoors = sessionAttributes.gamestate.currentRoom.elements.doors var canGo = false; // check if there is a door to go to the room if (Object.keys(currentRoomDoors).find(key => (currentRoomDoors[key].roomName === room.name))){ canGo = true; } return canGo; }
[ "function Room(origin, length, width, front_door, back_door, right_door, left_door) {\n this.front_door = front_door;\n this.back_door = back_door;\n this.right_door = right_door;\n this.left_door = left_door;\n this.length = length;\n this.width = width;\n\n this.isInDoorWay = function(x, y, z) {\n if (this.back_door) {\n if (z <= this.back_door.mesh.position.z + person_height && z >= this.back_door.mesh.position.z - person_height) {\n if (x <= this.back_door.mesh.position.x + this.back_door.length/2 && x >= this.back_door.mesh.position.x - this.back_door.length/2) {\n return 0;\n }\n } if (z > this.back_door.mesh.position.z - 1) {\n player.current_room = (this.back_door.rooms[0] == player.current_room) ? this.back_door.rooms[1] : this.back_door.rooms[0];\n return 0;\n }\n }\n if (this.front_door) {\n if (z <= this.front_door.mesh.position.z + person_height && z >= this.front_door.mesh.position.z - person_height) {\n if (x <= this.front_door.mesh.position.x + this.front_door.length/2 && x >= this.front_door.mesh.position.x - this.front_door.length/2) {\n return 1;\n }\n } if (z < this.front_door.mesh.position.z - 1) {\n player.current_room = player.current_room = (this.front_door.rooms[0] == player.current_room) ? this.front_door.rooms[1] : this.front_door.rooms[0];\n return 1;\n }\n }\n if (this.right_door) {\n if (x <= this.right_door.mesh.position.x + person_height && x >= this.right_door.mesh.position.x - 2*person_height) {\n if (z <= this.right_door.mesh.position.z + this.right_door.length/2 && z >= this.right_door.mesh.position.z - this.right_door.length/2) {\n return 2;\n }\n } if (x >= this.right_door.mesh.position.x - 1) {\n player.current_room = player.current_room = (this.right_door.rooms[0] == player.current_room) ? this.right_door.rooms[1] : this.right_door.rooms[0];\n return 2;\n }\n }\n if (this.left_door) {\n if (x <= this.left_door.mesh.position.x + 2*person_height && x >= this.left_door.mesh.position.x - person_height) {\n if (z <= this.left_door.mesh.position.z + this.left_door.length/2 && z >= this.left_door.mesh.position.z - this.left_door.length/2) {\n return 3;\n }\n } if (x <= this.left_door.mesh.position.x - 1) {\n player.current_room = player.current_room = (this.left_door.rooms[0] == player.current_room) ? this.left_door.rooms[1] : this.left_door.rooms[0];\n return 3;\n }\n }\n return -1;\n }\n\n this.isInDoorView = function(x,y,z, wall) {\n if (this.front_door && wall.mesh.position.z == this.front_door.mesh.position.z) {\n if (x <= this.front_door.mesh.position.x + this.front_door.length/2 && x >= this.front_door.mesh.position.x - this.front_door.length/2) {\n return true;\n }\n }\n if (this.back_door && wall.mesh.position.z == this.back_door.mesh.position.z) {\n if (x <= this.back_door.mesh.position.x + this.back_door.length/2 && x >= this.back_door.mesh.position.x - this.back_door.length/2) {\n return true;\n }\n }\n if (this.right_door && wall.mesh.position.x == this.right_door.mesh.position.x) {\n if (z <= this.right_door.mesh.position.z + this.right_door.length/2 && z >= this.right_door.mesh.position.z - this.right_door.length/2) {\n return true;\n }\n }\n if (this.left_door && wall.mesh.position.x == this.left_door.mesh.position.x) {\n if (z <= this.left_door.mesh.position.z + this.left_door.length/2 && z >= this.left_door.mesh.position.z - this.left_door.length/2) {\n return true;\n }\n }\n return false;\n }\n\n var wall_material = new THREE.MeshLambertMaterial({color:0x080A0A,wireframe:true});\n this.walls = createRoom(origin, length, width, wall_material);\n\n this.corners = new Array();\n this.corners[0] = new THREE.Vector3(origin.x - width/2, origin.y - person_height, origin.z+length/2); //back left bottom\n this.corners[1] = new THREE.Vector3(origin.x + width/2, origin.y - person_height, origin.z+length/2); // back right bottom\n this.corners[2] = new THREE.Vector3(origin.x - width/2, origin.y + length - person_height, origin.z + length/2); // back left top\n this.corners[3] = new THREE.Vector3(origin.x + width/2, origin.y + length - person_height, origin.z + length/2); // back right top\n this.corners[4] = new THREE.Vector3(origin.x - width/2, origin.y - person_height, origin.z - length/2); //front left bottom\n this.corners[5] = new THREE.Vector3(origin.x + width/2, origin.y - person_height, origin.z - length/2); // front right bottom\n this.corners[6] = new THREE.Vector3(origin.x - width/2, origin.y + length - person_height, origin.z - length/2); //front left top\n this.corners[7] = new THREE.Vector3(origin.x + width/2, origin.y + length - person_height, origin.z - length/2); //front right top\n}", "roomOrPossibleExists(position, rooms, possibles) {\n var result = false;\n for (var i = 0; i < rooms.length; i++) {\n if (rooms[i].position[0] === position[0] && rooms[i].position[1] === position[1]) {\n result = true;\n break;\n }\n }\n for (i = 0; i < possibles.length; i++) {\n if (possibles[i].position[0] === position[0] && possibles[i].position[1] === position[1]) {\n result = true;\n break;\n }\n }\n return result;\n }", "checkPortalCollision() {\n /*\n If the player steps in a portal:\n 1. Deactivate the player to prevent retriggering portal. \n 2. Trigger transitionRoom(target_room). \n 3. Emit the ROOM_TRANISITION event, passing the room to transition to. \n Note: (the following steps are handled by an event listener for the camera fade finish).\n 4. Jump the player to the specified spawn position. \n 5. Reactivate the player. \n */\n let room = this.scene.rooms[this.scene.curRoomKey];\n room.portalsArr.forEach((portal) => {\n if (Phaser.Geom.Rectangle.Overlaps(this.sprite.getBounds(), portal)) {\n // this.targetSpawn = portal.to_spawn;\n this.setActive(false);\n this.scene.transitionRoom(portal.to_room);\n this.to_spawn = portal.to_spawn;\n this.emitter.emit(events.ROOM_TRANSITION_START, portal.to_room);\n return;\n }\n });\n }", "async canPlayerJoin(client, playerId)\n {\n const inGame = this.players.some(x => x.id === playerId);\n return inGame || this.game.allowJoin;\n }", "is_facing_wall_or_portal() {\n switch(this.direction){ \n case KeyboardCodeKeys.left:\n return this.maze.has_left_wall(this.row, this.col)\n || (this.col == 0);\n case KeyboardCodeKeys.right:\n return this.maze.has_right_wall(this.row, this.col)\n || (this.col == this.maze.col_count-1);\n case KeyboardCodeKeys.up:\n return this.maze.has_top_wall(this.row, this.col)\n || (this.row == 0);\n case KeyboardCodeKeys.down:\n return this.maze.has_bot_wall(this.row, this.col)\n || (this.row == this.maze.row_count-1);\n }\n }", "actionDoor(sprite, door) {\n this.lastZoneMove = this.game.time.now;\n var nextRoomId = this.currentRoomJson.doors[door.name];\n var nextRoom;\n // Gets the next room based on the given door\n for (var i = 0; i < this.rooms.length; i++) {\n if (this.rooms[i].id == nextRoomId) {\n nextRoom = this.rooms[i];\n }\n }\n if (!nextRoom) {\n this.roomDisplay.setText(\"Error\")\n return;\n } \n\n // TODO: move key check into somewhere like room\n if (nextRoom.locked == true && this.player.inventory.includes(\"key-old\") == false ) {\n this.room.showText(\"Door is locked\");\n return;\n }\n\n if(this.room.locked){\n return;\n }\n\n this.currentRoomJson = nextRoom;\n this.setRoomText(this.currentRoomJson.name);\n this.roomObjects[this.room.id] = this.room;\n this.room.clearState();\n // Checks if room has already been loaded and just renders\n if(this.roomObjects[this.currentRoomJson.id]){\n console.log(\"Rendering already loaded room\");\n this.room = this.roomObjects[this.currentRoomJson.id];\n this.room.render(door.name);\n } else {\n this.room = new Room(this.game, this.currentRoomJson, this.player, door.name, this.playArea);\n }\n if(this.currentRoomJson.locked == true){\n this.room.showText(\"Unlocked room\", \"top\");\n }\n this.room.showText(this.currentRoomJson.name);\n\n if(this.currentRoomJson.name === 'Library'){\n var text = this.game.add.text(175, 500, \"You hear books talking to you...\", { font: \"18px Verdana\", fill: \"#ffffff\", align: \"center\" });\n text.anchor.set(0.15);\n\n // this.game.add.tween(text).to({y: 0}, 1500, Phaser.Easing.Linear.None, true); //this to move the text to the top and fades\n this.game.add.tween(text).to({alpha: 0}, 3500, Phaser.Easing.Linear.None, true);\n }\n\n if(this.currentRoomJson.name === 'Basement Exit'){\n var text = this.game.add.text(175, 500, \"Enter the chest if you dare...\", { font: \"18px Verdana\", fill: \"#ffffff\", align: \"center\" });\n text.anchor.set(0.15);\n\n // this.game.add.tween(text).to({y: 0}, 1500, Phaser.Easing.Linear.None, true); //this to move the text to the top and fades\n this.game.add.tween(text).to({alpha: 0}, 6000, Phaser.Easing.Linear.None, true);\n }\n }", "static hasRightToWrite(){\n var idProject = Router.current().params._id\n var project = Projects.findOne(idProject)\n if(!project){\n return false;\n }\n var username = Meteor.user().username\n var participant = $(project.participants).filter(function(i,p){\n return p.username == username && p.right == \"Write\"\n })\n if(project.owner == username || participant.length > 0){\n return true\n }else{\n return false\n }\n }", "function checkDoorOrShelf(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'dörren' || option === 'DÖRREN' || option === 'Dörren'){\n purpleRoom();\n\n }else if(option === 'bokhyllan' || option === 'BOKHYLLAN' || option === 'Bokhyllan'){\n story.innerHTML = 'Här fanns det bara massa tråkiga lexikon... Vill du gå igenom den andra dörren nu? (Ja eller Nej)';\n btn.onclick = outOrNot;\n\n /**\n * Function outOrNot sleected.\n * Options to go throught the other door or not.\n */\n function outOrNot(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n purpleRoom();\n \n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Hm... Det fanns inte så mycket mer att göra här.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n }\n }\n }\n }", "function whichRoom(){\n\n const option = user.value;\n user.value = '';\n /*\n * Switch statement with room options, that search for the users input in order to interact.\n * As user inputs option, function of the selected room is running. \n */\n switch(option){\n\n case 'grön':\n \n greenRoom();\n break;\n\n case 'lila':\n \n purpleRoom();\n break;\n\n case 'orange':\n \n orangeRoom();\n break; \n \n case 'blå':\n \n blueRoom();\n break;\n\n /* Error message! false user input*/\n default:\n story.innerHTML = 'Jag förstår inte vad du menar. Försök igen!';\n }\n}", "function joinRoom() {\n initSocket();\n initRoom();\n }", "canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}", "function ViewRooms() { }", "function orangeRoom(){\n room.style.backgroundColor = '#ff6d24'; /** Change of room color. */\n story.innerHTML = 'Du är nu i det oranga rummet, här finns det en till dörr och en bokhylla. Vilken vill du kolla? (Dörren eller Bokhyllan) ';\n btn.innerHTML = 'Svara';\n btn.onclick = checkDoorOrShelf;\n \n /**\n * Function checkDoorOrShelf seleted.\n * Options between the door or the bookshelf.\n */\n function checkDoorOrShelf(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'dörren' || option === 'DÖRREN' || option === 'Dörren'){\n purpleRoom();\n\n }else if(option === 'bokhyllan' || option === 'BOKHYLLAN' || option === 'Bokhyllan'){\n story.innerHTML = 'Här fanns det bara massa tråkiga lexikon... Vill du gå igenom den andra dörren nu? (Ja eller Nej)';\n btn.onclick = outOrNot;\n\n /**\n * Function outOrNot sleected.\n * Options to go throught the other door or not.\n */\n function outOrNot(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n purpleRoom();\n \n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Hm... Det fanns inte så mycket mer att göra här.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n }\n }\n }\n }\n}", "getCurrentRoom() {\n const map = this.game.maps.find(map => map.id === this.mapId);\n return map.rooms.find(room => room.id === this.roomId);\n }", "function check_room_winners(turn)\n{\n for(var room in room_winner)\n {\n //check for rooms that dont already have a winner\n if(room_winner[room]==0)\n {\n var lines_complete = 0; \n var temp_room = rooms[room];\n for(var key in temp_room)\n {\n if(temp_room[key]!=0)\n {\n lines_complete++;\n }\n else \n {\n break;\n }\n }\n if(lines_complete==4)\n {\n room_winner[room]=turn; \n if(turn==PLAYER_TURN)\n alert(\"You have conquered room \" + (Number(room)+1));\n else \n alert(\"I have conquered room \" + (Number(room)+1));\n }\n }\n } \n}", "_generateRoom() {\n let count = 0;\n while (count < this._roomAttempts) {\n count++;\n let room = _features_js__WEBPACK_IMPORTED_MODULE_1__[\"Room\"].createRandom(this._width, this._height, this._options);\n if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) {\n continue;\n }\n room.create(this._digCallback);\n this._rooms.push(room);\n return room;\n }\n /* no room was generated in a given number of attempts */\n return null;\n }", "get isHome () {\n return this.room.name === this._mem.rooms.home;\n }", "static needPlayers() {\n\t\talert('There\\'s not enough players in the room');\n\t}", "function roomNeedsWorker(room) {\n if (Game.time % RATE != 0) return;\n\n var controller = room.controller;\n if (!controller || !controller.my || controller.level >= 6) {\n setNeedsWorker(room, false);\n return;\n }\n\n var spawns = room.find(FIND_MY_SPAWNS).length;\n var underConstruction = room.find(FIND_CONSTRUCTION_SITES, {\n filter: (site) => site.structureType == STRUCTURE_SPAWN\n }).length;\n // don't send helpers to rooms without at least a spawn construction site\n if (!underConstruction && !spawns) {\n setNeedsWorker(room, false);\n return;\n }\n // how many creeps from higher leveled rooms are in this room\n var fatCreeps = room.find(FIND_MY_CREEPS, {\n filter: creep => creep.memory.cost > room.energyCapacityAvailable\n });\n setNeedsWorker(room, fatCreeps.length < optimize.getMaxCreeps(room.name));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
most useful when using specificType traverses the window until it comes across what you're looking for
getNearest(specificType = undefined) { return this.getSiteFromCandidates(Array.from(this.window.values()), false, specificType); }
[ "visitWindowing_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function recordsetDialog_searchByType(stype) {\r\n\tfor (ii = 0; ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (MM.rsTypes[ii].type == stype) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}", "function match(type, value) {\n}", "function winActiveViewType() {\n\n var body = $('iframe#canvas_frame', parent.document).contents().find('div.nH.q0CeU.z');\n\n if (body.is(\"*\")) {\n return 'tl';\n } else {\n return 'na';\n }\n\n }", "function recordsetDialog_searchDisplayableRecordset(SBRecordset,currentIndex) {\r\n\tvar cIdx = recordsetDialog.findPreferedType(SBRecordset);\r\n\tif (cIdx == -1) {\r\n\t\tcIdx = currentIndex;\r\n\t}\r\n\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[cIdx].serverModel) {\r\n\t\tif (recordsetDialog.canDialogDisplayRecordset(MM.rsTypes[cIdx].command, SBRecordset)) {\t\r\n\t\t\treturn cIdx;\r\n\t\t}\r\n\t}\r\n\tfor (ii = 0;ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (recordsetDialog.canDialogDisplayRecordset(MM.rsTypes[ii].command, SBRecordset)) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}", "function get_element_from_event (event, element_type) {\n\t\tvar target = $(event.target);\n\t\tvar element = null;\n\n\t\tif(target.is(element_type)) {\n\t\t\telement = target;\n\t\t} else if(target.parent(element_type).length) {\n\t\t\telement = target.parent(element_type+\":first\");\n\t\t}\n\n\t\treturn element;\n\t}", "function getItemsOfType(items, type) {\n return _.where(items, { 'type': type });\n }", "function changeType(type) {\n\tvar user = wialon.core.Session.getInstance().getCurrUser();\n\n\tvar flags = wialon.item.Item.dataFlag.base |\n\t\t\t\twialon.item.Item.dataFlag.image |\n\t\t\t\twialon.item.Item.dataFlag.customProps |\n\t\t\t\t0x20000;\n\n\tif (type === 'avl_resorce') {\n\t\tflags |= 0x00000100;\n\t\tflags |= 0x00008000;\n\t}\n\n\tsearchItems(\n\t\tqx.lang.Function.bind(function (items) {\n\t\t\tif (type == \"avl_unit\") {\n\t\t\t\t// count of units with settings\n\t\t\t\tvar okUnits = 0;\n\n\t\t\t\twialon.core.Remote.getInstance().startBatch(\"driveRankSettings\");\n\n\t\t\t\t// check if can exec report\n\t\t\t\twialon.core.Session.getInstance().searchItem(user.getAccountId(), 0x1, function(code, data) {\n\t\t\t\t\tif (code || !data || !(data.getUserAccess() & wialon.item.Resource.accessFlag.viewReports)) {\n\t\t\t\t\t\tLOCAL_STATE.canExec = false;\n\t\t\t\t\t\t$(\"#overlay-all\").html(\n\t\t\t\t\t\t\t'<div class=\"info\">' +\n\t\t\t\t\t\t\t$.localise.tr(\"You do not appear to have access \\\"View report templates\\\" to your account.\") +\n\t\t\t\t\t\t\t'</div>'\n\t\t\t\t\t\t).show();\n\t\t\t\t\t\t$(\"#add-unit\").empty();\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tfor (var u = 0; u < items.length; u++) {\n\t\t\t\t\titems[u].getDriveRankSettings(qx.lang.Function.bind(function (unit, code, data) {\n\t\t\t\t\t\tunit.driveRankSettings = false;\n\n\t\t\t\t\t\tif (code === 0 && hasDriveRankSettings(data)) {\n\t\t\t\t\t\t\t\tunit.driveRankSettings = true;\n\t\t\t\t\t\t\t\tokUnits++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}, this, items[u]));\n\t\t\t\t}\n\t\t\t\twialon.core.Remote.getInstance().finishBatch(function () {\n\t\t\t\t\t// sort by name\n\t\t\t\t\tsortListItems(items);\n\n\t\t\t\t\t// change phrases if no configured units\n\t\t\t\t\tif (okUnits === 0) {\n\t\t\t\t\t\t$(\"#add-unit\").html($.localise.tr(\"You have no units with adjusted driving criteria.\"));\n\t\t\t\t\t}\n\n\t\t\t\t\t$(\"#items .list\").html(fillListWithItems(true));\n\t\t\t\t\taddTab(\"tab_\"+LOCAL_STATE.tab_index++);\n\n\t\t\t\t\tif (LOCAL_STATE.canExec) {\n\t\t\t\t\t\tvar ids = getStorageItem(\"idrive\");\n\t\t\t\t\t\tif (typeof ids === \"undefined\"){\n\t\t\t\t\t\t\t// toDo: first start\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tids = ids ? ids.split(\",\") : [];\n\t\t\t\t\t\t\tfor (var i = 0; i < ids.length; i++) {\n\t\t\t\t\t\t\t\ttoggleUnit(ids[i], $(\".item_\"+ids[i]));\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}, \"driveRankSettings\");\n\t\t\t}\n\t\t}, this),\n\t\tflags\n\t);\n}", "function selectAncestor(elem, type) {\n type = type.toLowerCase();\n if (elem.parentNode === null) {\n console.log('No more parents');\n return undefined;\n }\n var tagName = elem.parentNode.tagName;\n\n if (tagName !== undefined && tagName.toLowerCase() === type) {\n return elem.parentNode;\n } else {\n return selectAncestor(elem.parentNode, type);\n }\n }", "function typeFilter(type, callback) {\n return function(event) {\n var obj = event.newValue || event.oldValue;\n\n console.log(\"Filtering event\", event, \"for type\", type, \"obj\", obj, obj['@type']);\n \n if(obj && obj['@type']) {\n var parts = obj['@type'].split('/');\n if(parts[parts.length - 1] == type) {\n callback(event);\n }\n }\n }\n }", "valueMatchesType(value) {\n return typeof value === this.valueType\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}", "visitWindowing_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function walkSelection() {\n //set the optionKey\n var optionKey = Menu.optionArray[Menu.optionSelected].optionKey;\n switch (optionKey) {\n case 'talkTo':\n var found = false;\n game.mapData.npcs.forEach(function(npc) {\n if (game.player.gridLocation.x - game.playerDirection.x === npc.x && game.player.gridLocation.y - game.playerDirection.y === npc.y) {\n //there is an NPC in the direction the player is facing\n found = true;\n //make the dialog panel\n game.dialogPanel.new({\n w: 800,\n h: 270,\n x: game.width / 2 - 400,\n y: game.height - 270 - 50,\n type: 'dialog',\n dialog: game.dialog[npc.nameKey]\n });\n }\n });\n if (!found) {\n //nobody there\n game.infoPanel.new({\n w: 400,\n h: 200,\n x: game.width / 2 - 200,\n y: 50,\n type: 'infoPanel',\n text: [\"There's nobody there!\"]\n });\n }\n break;\n case 'items':\n game.dialogPanel.new({\n w: 800,\n h: 450,\n x: game.width / 2 - 400,\n y: game.height / 2 - 300,\n type: 'itemPanel',\n callback: null\n });\n break;\n default:\n //temporary display for unfinished menus\n game.infoPanel.new({\n w: 400,\n h: 200,\n x: game.width / 2 - 200,\n y: 50,\n type: 'infoPanel',\n text: [\"That menu isn't finished yet!\", \"Stop clicking it.\", \"Please.\"]\n });\n // code\n }\n\n }", "function search(type, placeObject) {\r\n for (var i = 0; i < placeObject.length; i++) {\r\n if (placeObject[i].types[0] === type) {\r\n return placeObject[i].short_name;\r\n } else if (i === placeObject.length - 1) {\r\n return \"\";\r\n }\r\n }\r\n }", "function pageType(){\n types = ['section_id','page_id','group_id'];\n var match= false, pT = false;\n _.each(types, function(qv,qk){\n match = $.qs[qv] !== undefined ? $.qs[qv] : undefined;\n if(match) pT = {\"type\":qv,\"id\":match}\n });\n if(pT){ return pT; } else { return false }\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 typeOfFilms(data){\n var typeslinks = $('.list', data).children('tbody').children('tr').children('td').children('ul').children('li').children('a');\n typeslinks.each(function(i){\n if (i < 5){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchfirst').append(type + '</br>');\n }\n if (i > 5 && i < 11){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchsecond').append(type + '</br>');\n }\n if (i > 11 && i < 17){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchthird').append(type + '</br>');\n }\n });\n}", "function recordsetDialog_findPreferedType(SBRecordset) {\r\n\tfor (ii = 0; ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif ((SBRecordset.name) && (MM.rsTypes[ii].preferedName == SBRecordset.name.replace(/safe/i, ''))) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse SID and produces the correct URL
function parseSidUrl(baseUrl, urlExt) { var sidPos = baseUrl.indexOf('/?SID='); var sid = ''; urlExt = (urlExt != undefined) ? urlExt : ''; if(sidPos > -1) { sid = '?' + baseUrl.substring(sidPos + 2); baseUrl = baseUrl.substring(0, sidPos + 1); } return baseUrl+urlExt+sid; }
[ "function makeId(base, input) {\n // check if not falsy\n if(input) {\n // check for full id\n if(input.indexOf('http://') === 0 || input.indexOf('https://') === 0) {\n return input;\n }\n // else a short id\n else {\n return base + '/' + input;\n }\n }\n\n return base;\n}", "function GetDetailsUrlFromHref(href) {\n var pieces = /([0-9]+).+(JSS[^']*).+([0-9]+)/.exec(href);\n var docId = pieces[1];\n var rootUrl = \"https://ees.elsevier.com/jss/\";\n var url = rootUrl + \"EMDetails.aspx?docid=\" + pieces[1] + \"&ms_num=\" + pieces[2] + \"&sectionID=\" + pieces[3];\n return {\n url: url,\n docId: docId\n };\n}", "function parseUrl() {\n\tvar ResUrl = $(location).attr(\"hash\");\n\tvar access= ResUrl.split(/=|&/);\n\tlocalStorage.setItem('access_token', access[1]);\n\tlocalStorage.setItem('uid', access[5]);\n}", "function get_org_NAME_from_URL( escapedOrgName ){\n var thisURL = window.location.search;\n var org_name = thisURL.substring( thisURL.indexOf(\"org_name=\")+9);\n //console.info('get_org_NAME_from_URL: org_name step 1 = ' +org_name);\n org_name = unescape( org_name );\n //console.info('get_org_NAME_from_URL: org_name final = ' +org_name);\n return org_name;\n} // end get_org_NAME_from_URL", "function get_ScienceDirect(theURL) {\r\n var searchfor = \"piikey%3D\" \r\n var mypiiTMPi = theURL.indexOf(searchfor)\r\n var mypiiTMP = theURL.substring(mypiiTMPi+searchfor.length,theURL.length)\r\n var mypiiTMPi = mypiiTMP.indexOf(\"%26\")\r\n var mypii = mypiiTMP.substring(0,mypiiTMPi)\r\n var theNewURL = \"http://www.sciencedirect.com/science/article/pii/\" + mypii\r\n return theNewURL\r\n}", "function getServerFriendlyName(url){\n\trequest(url, function(error, response, body){\n\t parseString(body, function(err, result){\n\t\tconsole.log(result.root.device[0].friendlyName[0]);\n\t });\n\t});\n }", "parse(_stUrl) {\n Url.parse(_stUrl, true);\n }", "function shortenID(mid) {\n var id1 = parseInt(mid.substr(0,9), 16).toString(36)\n if (isNaN(id1)) { // conversion failed\n return mid; // return unchanged\n }\n\n // add padding if < 7 chars long\n while (id1.length < 7) id1 = '-' + id1\n\n var id2 = parseInt(mid.substr(9,9), 16).toString(36)\n if (isNaN(id2)) { // conversion failed\n return mid; // return unchanged\n }\n while (id2.length < 7) id2 = '-' + id2\n \n // add 'Z' which is the short link denoter\n return 'Z' + id1 + id2\n}", "function unsafelyGetOrgId(originalUrl) {\n const params = originalUrl.split('/');\n if (params.length === 0) {\n return null;\n }\n return params[1];\n}", "function cleanURL(path) {\n var cleanPath = path.replace(/\\/study\\/.+?(?=\\/|$)/, '/study'); // to strip study name (/study/leap to /study)\n return cleanPath.replace(/(\\/\\d+)/g, ''); // then to strip ids (/subject/1 to /subject)\n }", "function service2id(n)\n {\n return \"dummy_\"+n.replace(\" \",\"_\");\n }", "function getProductId(url){\n let id = url.match(/p-[0-9]+/g)\n let lastIndex = id.length -1\n return id[lastIndex].slice(2)\n}", "function getuid(opts) {\n\n\t\ttry { \n\t\t\treturn this.url(); \n\t\t} catch (e) { \n\t\t\treturn this.url || this.urlRoot || undefined;\n\t\t}\n\t}", "function identistring(state) {\n return re(state, /^([a-zA-Z_\\$][a-zA-Z0-9_\\$]*)(\\.[a-zA-Z_\\$][a-zA-Z0-9_\\$]*)*/);\n }", "function parse_uri()\n {\n if (this.myuri == \"..\") {\n var tt = window.location.href;\n var tarr = tt.split(\"?\", 2);\n this.myuri = tarr[0];\n if ((tarr.length > 1) && (this.myquery == \"..\")) {\n var myquery = {};\n this.myquery = myquery;\n var tarr = tarr[1].split(\"&\");\n for (var ndx in tarr) {\n var qp = tarr[ndx];\n if (qp.length > 0) {\n var qpa = qp.split(\"=\");\n if (qpa.length == 1) {\n myquery[qp] = \"\";\n }\n else {\n var pname = qpa.shift();\n myquery[pname] = qpa.join(\"=\");\n }\n }\n }\n }\n }\n }", "function decodeURL() {\n var url = document.location.pathname;\n \n if (url.lastIndexOf(\"/\") === url.length-1) {\n url = url.substring(0,url.lastIndexOf(\"/\"));\n }\n url = url.substring(url.lastIndexOf(\"/\") + 1);\n \n if (url !== \"\")\n console.log(url);\n else\n return;\n \n url = atob(url);\n \n // The beginning of the url is formatted <season><year>...\n // <season> is one character. <year> is 4.\n var svalue = url[0];\n url = url.substring(1);\n var yvalue = url.substring(0, 4);\n url = url.substring(4);\n \n console.log(\"Year: \" + yvalue);\n console.log(\"Season: \" + svalue);\n \n // Make sure the year is between 1999 (the first year with data) and next year (inclusive).\n if (parseInt(yvalue, 10) < 1999 || parseInt(yvalue, 10) > new Date().getFullYear()+1) {\n console.log(\"*** Year out of bounds.\");\n return;\n }\n \n // Make sure the season value is between 0 (Winter) and 3 (Fall) (inclusive).\n if (parseInt(svalue, 10) < 0 || parseInt(svalue, 10) > 3) {\n console.log(\"*** Season out of bounds.\");\n return;\n }\n \n // A class number is 4 characters long so check that the remaining url\n // length is a multiple of 4.\n if (url.length % 4 !== 0) {\n console.log(\"*** Bad URL length.\");\n return;\n }\n \n // Clear the schedule. There shouldn't be anything in it, but just in case\n SCHEDULE.length = 0;\n \n while (url.length >= 4) {\n var token = url.substring(0,4);\n url = url.substring(4);\n for (var i = 0; i < SECTIONS.length; i ++) {\n if (SECTIONS[i].class_no == token)\n SCHEDULE.push(SECTIONS[i]);\n }\n }\n \n analytics(\"share_link_schedule\");\n $(\"#switch_view\").click();\n}", "function getMemberDetailsURI(memberId) {\n return \"/snappy-api/services/memberdetails/\" + memberId;\n}", "function getEmployeeIdFromURL(){\n var query = document.location.search.substr(1).split('=') //e.g. takes \"employeeId=1\" & splits into [\"employeeId\", \"1\"]\n var employeeId = query[1];\n console.log(\"employeeId from employee js: \" + employeeId)\n return employeeId;\n}", "function constructAPIURL(urls) {\n\tvar ids = [];\n\tfor (let url of urls) {\n\t\tlet id;\n\t\tif (url.match(/\\.(io|com|org)\\/([a-z0-9]+)/)) {\n\t\t\tid = url.match(/\\.(?:io|com|org)\\/([a-z0-9]+)/)[1];\n\t\t}\n\t\tif (id) {\n\t\t\tids.push(\"https://api.osf.io/v2/preprints/\" + id + \"/?embed=contributors&embed=provider\");\n\t\t}\n\t}\n\treturn ids;\n}", "function getMatchIdFromUrl(url)\n{\n const URL_OBJ = new URL(url);\n return URL_OBJ.pathname.split('/')[2];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unsigned char ptr[x][y] = v
function h$writePtrPtrU8(ptr, ptr_off, v, x, y) { x = x || 0; y = y || 0; var arr = ptr.arr[ptr_off+ 4 * x]; arr[0].dv.setUint8(arr[1] + y, v); }
[ "function toU8Array(ptr, length) {\n return HEAPU8.subarray(ptr, ptr + length);\n }", "function set_board_pixel(board, x, y, value)\n{\n\tvar index = x + y * get_game_width();\n\tboard[index] = value;\n}", "set(x, y, value) {\n this.content[y * this.width + x] = value;\n }", "function create_arr(mem, pos, size) {\n\t\t\treserve_mem(mem, pos, 4 + size * 4);\n\n\t\t\tlet view = new DataView(mem.buffer);\n\n\t\t\t// write size\n\t\t\tview.setUint32(pos, size, true);\n\t\t\tpos += 4;\n\n\t\t\t// initialize to zero\n\t\t\tlet arr_pos = 0;\n\t\t\twhile (arr_pos < size) {\n\t\t\t\tview.setUint32(pos, 0, true);\n\t\t\t\tpos += 4;\n\t\t\t\t++arr_pos;\n\t\t\t}\n\t\t\treturn pos;\n\t\t}", "function buildAddrOfArray(obj)\n{\n let arr = [obj, obj];\n let tmp = {escapeVal: arr.length};\n arr[tmp.escapeVal] = floatMapObj;\n return arr; \n}", "set(x, y, value) {\n const index = this.linear(x, y);\n\n return new Matrix2D(this.xSize, this.ySize, [\n ...this.data.slice(0, index),\n value,\n ...this.data.slice(index + 1)\n ])\n }", "get(x, y) {\n return this.content[y * this.width + x];\n }", "set(x, y, value) {\n if(!this.grid[x]) {\n this.grid[x] = []\n }\n this.grid[x][y] = value\n }", "static array(v, dynamic) {\n throw new Error(\"not implemented yet\");\n return new Typed(_gaurd, \"array\", v, dynamic);\n }", "function sukeistiMasyvo2Elementus(x, y) {\n var z = prekiautojai[x];\n prekiautojai[x] = prekiautojai[y];\n prekiautojai[y] = z;\n\n}", "function sukeistiMasyvo2elementus(x, y) {\n let t = prekiautojai[x];\n prekiautojai[x] = prekiautojai[y];\n prekiautojai[y] = t;\n}", "setat(row,column,value)\n\t{\n\t\tif (row >= 0 && row < 4 && column >= 0 && column < 4 )\n\t\t\tthis._data[row][column] = value;\n\t}", "function TileXYToPixelXY( tileXY )\n\t{\n\t\treturn [ tileXY[0] * 256, tileXY[1] * 256 ];\n\t}", "function PixelXYToTileXY( pixelXY )\n\t{\n\t\treturn [ pixelXY[0] / 256, pixelXY[1] / 256 ];\n\t}", "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 }", "function pivot(buf)\r\n{\r\n var ans = malloc(0x400);\r\n var bak = read_ptr_at(fake_vtable+0x1d8);\r\n write_ptr_at(fake_vtable+0x1d8, saveall_addr);\r\n tarea.scrollLeft = 0;\r\n write_mem(ans, read_mem(fake_vt_ptr, 0x400));\r\n write_mem(fake_vt_ptr, read_mem(fake_vt_ptr_bak, 0x400));\r\n var bak = read_ptr_at(fake_vtable+0x1d8);\r\n write_ptr_at(fake_vtable+0x1d8, pivot_addr);\r\n write_ptr_at(fake_vt_ptr+0x38, buf);\r\n write_ptr_at(ans+0x38, read_ptr_at(ans+0x38)-16);\r\n write_ptr_at(buf, ans);\r\n tarea.scrollLeft = 0;\r\n write_mem(fake_vt_ptr, read_mem(fake_vt_ptr_bak, 0x400));\r\n}", "function createArray(len, value) {\n let tmpArray = [];\n for (let i = 0; i < len; i++) {\n tmpArray[i] = value;\n }\n return tmpArray;\n }", "static bytes2(v) { return b(v, 2); }", "placeAt(xx, yy, obj) {\r\n var xc = this.cw * xx + this.cw / 2;\r\n var yc = this.ch * yy + this.ch / 2;\r\n obj.x = xc;\r\n obj.y = yc;\r\n }", "function convert4x4(array) {\n currentIndex = 0;\n var newArray = [[null,null,null,null],[null,null,null,null],[null,null,null,null],[null,null,null,null]];\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 4; j++) {\n newArray[i][j] = array[currentIndex];\n currentIndex++;\n }\n }\n return newArray;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Video 'resized' event handler
function onVideoResized(vs, isPreview, size) { // notify the AVComponent that the video window size has changed pcAV.invoke('SetVideoWindowSize', vs._id(), vs.source.sink._videoWindow(), isPreview, size.width, size.height); }
[ "function videoResize() {\n if (window.innerWidth <= 600) {\n video.width = 320;\n video.height = 240;\n wallpaper.src=\"Images/whitney-houston-vertical-image.jpg\";\n } else {\n video.width = 640;\n video.height = 480;\n wallpaper.src=\"Images/whitney-houston-horizontal-image.jpg\"\n }\n}", "_thumbnailsBoxResized() {\n this._updateSize();\n this._redisplay();\n }", "function resizedw(){\n loadSlider(slider);\n }", "resizeEmbed() {\n Object.keys(this.videoEmbeds).forEach((key) => {\n const embed = this.videoEmbeds[key];\n\n fastdom.measure(() => {\n const newWidth = embed.floated ?\n embed.parent.offsetWidth :\n this.element.offsetWidth;\n fastdom.mutate(() => {\n embed.iframe.setAttribute(\n 'height',\n newWidth * embed.iframe.dataset.aspectRatio\n );\n embed.iframe.setAttribute('width', newWidth);\n });\n });\n });\n }", "function addResizeListener() {\n document.getElementById('large-btn').addEventListener('click', function(event){\n changeSize('large');\n });\n document.getElementById('normal-btn').addEventListener('click', function(event){\n changeSize('normal');\n });\n document.getElementById('small-btn').addEventListener('click', function(event){\n changeSize('small');\n });\n}", "onResize() {\n App.bus.trigger(TRIGGER_RESIZE, document.documentElement.clientWidth, document.documentElement.clientHeight);\n }", "resizePreview_() {\n this.scope_.$broadcast('resizePreview');\n }", "function listenWindowResize() {\n $(window).resize(_handleResize);\n }", "_handleResize(e) {\n this.resizeToolbar();\n }", "function video_height(){\r\n var _height = $('.gallery-image').height();\r\n $('.video-item').height(_height);\r\n }", "function popupPVAsWindow_onresize(e)\n{\n}", "function _resized() {\n\t\t\t\t_winHeight = $window.innerHeight + 'px';\n\n\t\t\t\tif (loading.active) {\n\t\t\t\t\t_$body.css({\n\t\t\t\t\t\theight: _winHeight,\n\t\t\t\t\t\toverflowY: 'hidden'\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}", "function detectSizeForStreaming()\n{\n\tvar sourceURL = VIDEO_SERVER_URI.value; \n\tif(/\\s*rtmp:\\/\\/([^\\/]+)\\/([^\\/]+\\/[^\\/]+)/i.test(sourceURL) && !((sourceURL.indexOf(\"*\") != -1) || (sourceURL.indexOf(\"?\") != -1) || (sourceURL.indexOf(\"<\") != -1) || (sourceURL.indexOf(\">\") != -1) || (sourceURL.indexOf(\"|\") != -1) || (sourceURL.indexOf(\"\\\"\") != -1)))\n\t{\n\t\tserverName=RegExp.$1;\n\t\tappName=RegExp.$2; \n\t}\n\telse\n\t{\n\t\talert(MSG_EnterValidServerURI);\n\t\treturn;\n\t}\n\tvar streamName = trimString(VIDEO_STREAM.value); \n\n\t//form the video URL from sourceURL + \"/\" + streamName\n\tif (sourceURL.length > 0)\n\t{\n\t\t\t//if the last character is not a slash then append \n\t\t\t//a slash to it\n\t\t if (sourceURL[sourceURL.length - 1] != '/')\n\t\t {\n\t\t\t\tsourceURL += \"/\";\n\t\t }\n\t}\n\n\t// Make sure that streamName does not have .flv at the end\n\tif (/\\.flv$/i.test(streamName) == true)\n\t{\n\t\tstreamName = streamName.replace(/\\.flv$/i, \"\");\n\t}\n\n\t//form the video URL from sourceURL + streamName\n\tvar videoURL = sourceURL + streamName;\n\tif((videoURL != null) && (videoURL.length > 0))\n\t{\n\t\t//load the video URL to get the auto detect the video dimension\n\t\tloadVideo(videoURL);\n\t\t//start the detect poll\n\t\t//we need the below flag to track when the auto detect from\n\t\t//swfloader extension is completed.\n\t\t//we loop 30 times x 500ms (1/2 second)15 seconds\n\t\tMM._LOOPCOUNTER = 0;\n\t\tMM.setBusyCursor();\n\n\t\tVIDEO_SIZE_BTN.setAttribute(\"disabled\",\"true\");\n\t\tVIDEO_TOTAL.innerHTML = MSG_Detecting;\n\n\t\t//first call back\n\t\tvar funCallBack = \"isDetectSizeDone()\";\n\t\ttimerID = setTimeout(funCallBack,500);\n\t}\n}", "function ResizeHandler() {\n setMaxWindowWidth((window.innerWidth - 800) / 2);\n setMaxWindowHeight((window.innerHeight - 700) / 2);\n }", "resize() {\n this.createCanvas();\n }", "function onFullScreenChange(){\n\t\t \n\t\tvar isFullscreen = g_functions.isFullScreen();\n\t\t var event = isFullscreen ? t.events.ENTER_FULLSCREEN:t.events.EXIT_FULLSCREEN; \n\t\t \n\t\t //add classes for the gallery\n\t\t if(isFullscreen){\n\t\t\t g_objWrapper.addClass(\"ug-fullscreen\");\n\t\t }else{\n\t\t\t g_objWrapper.removeClass(\"ug-fullscreen\");\n\t\t }\n\n\t\t g_objGallery.trigger(event);\n\t\t \n\t\t onGalleryResized();\n\t}", "function aspectScale() {\n $(\".media-container\").each(function () {\n var container = $(this);\n container.find(\"img, video\").each(function () {\n var dims = {\n w: this.naturalWidth || this.videoWidth || this.clientWidth,\n h: this.naturalHeight || this.videoHeight || this.clientHeight\n },\n space = {\n w: container.width(),\n h: container.height()\n };\n if (dims.w > space.w || dims.h > space.h) {\n $(this).css({width: \"\", height: \"\"}); // Let CSS handle the downscale\n } else {\n if (dims.w / dims.h > space.w / space.h) {\n $(this).css({width: \"100%\", height: \"auto\"});\n } else {\n $(this).css({width: \"auto\", height: \"100%\"});\n }\n }\n });\n });\n }", "setupEmbed() {\n Object.keys(this.videoEmbeds).forEach((key) => {\n const embed = this.videoEmbeds[key];\n\n embed.iframe.setAttribute(\n 'data-aspect-ratio',\n `${embed.iframe.height / embed.iframe.width}`\n );\n embed.iframe.removeAttribute('height');\n embed.iframe.removeAttribute('width');\n });\n\n this.resizeEmbed();\n window.addEventListener('resize', this.resizeEmbed);\n }", "actOnWindowResize() {\n self = this;\n window.addEventListener('resize', function () {\n clearTimeout(self.id);\n self.id = setTimeout(() => { self.manageHexagons() }, 100);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Put the group_id and the receiver_id in an array of objects called mass_requests
function sendGroupJoinRequests() { vm.usersToInvite.forEach(user => { massRequest.push({ group_id: vm.group.id, receiver_id: user.id}); }); const massRequestObj = { mass_requests: massRequest }; Request .sendMassRequest(massRequestObj) .$promise .then(data => { $uibModalInstance.close('Requests sent'); }) .catch(err => { console.log('Something went wrong with the mass request'); console.log('Error:', err); }); }
[ "_sendBatch() {\n if (_.isEmpty(this.events)) return;\n\n const events = Object.assign([], this.events);\n const body = JSON.stringify(events);\n const options = {\n url: `${this.endpoint}/${this.dataSet}`,\n headers: {\n 'X-Honeycomb-Team': this.writeKey,\n },\n body,\n };\n request.post(options, (err, response) => {\n if (err) {\n console.log(err);\n }\n\n if (response) {\n console.log(`Received status ${response.statusCode}`);\n }\n });\n }", "SendModeratorsListAndSubscribersListOfThisMailingListByEmail(domain, email, name) {\n let url = `/email/domain/${domain}/mailingList/${name}/sendListByEmail`;\n return this.client.request('POST', url, { email });\n }", "function bulkCreateActivityGroups() {\r\n var ss = SpreadsheetApp.getActiveSpreadsheet();\r\n var sheet = ss.getSheetByName(CREATE_ACTIVITY_GROUPS);\r\n\r\n // This represents ALL the data\r\n var range = sheet.getDataRange();\r\n var values = range.getValues();\r\n\r\n const profile_id = _fetchProfileId();\r\n const config_id = _fetchFloodlightConfigId();\r\n\r\n // build request body resources\r\n for (var i = 1; i < values.length; ++i) {\r\n var currentRow = i + 1;\r\n var currentPlacement = values[i];\r\n var activity_name = currentPlacement[0]; \r\n var activity_type = currentPlacement[1]; \r\n var resource = {\r\n \"name\": activity_name,\r\n \"type\" : activity_type,\r\n \"floodlightConfigurationId\": config_id\r\n };\r\n\r\n \r\n var newActivity = DoubleClickCampaigns.FloodlightActivityGroups\r\n .insert(resource, profile_id);\r\n \r\n sheet.getRange(\"C\" + currentRow)\r\n .setValue(newActivity.id).setBackground(AUTO_POP_CELL_COLOR);\r\n \r\n } \r\n }", "kickGroupUsers(bearerToken, groupId, userIds, options = {}) {\n if (groupId === null || groupId === void 0) {\n throw new Error(\"'groupId' is a required parameter but is null or undefined.\");\n }\n const urlPath = \"/v2/group/{groupId}/kick\".replace(\"{groupId}\", encodeURIComponent(String(groupId)));\n const queryParams = /* @__PURE__ */ new Map();\n queryParams.set(\"user_ids\", userIds);\n let bodyJson = \"\";\n const fullUrl = this.buildFullUrl(this.basePath, urlPath, queryParams);\n const fetchOptions = buildFetchOptions(\"POST\", options, bodyJson);\n if (bearerToken) {\n fetchOptions.headers[\"Authorization\"] = \"Bearer \" + bearerToken;\n }\n return Promise.race([\n fetch(fullUrl, fetchOptions).then((response) => {\n if (response.status == 204) {\n return response;\n } else if (response.status >= 200 && response.status < 300) {\n return response.json();\n } else {\n throw response;\n }\n }),\n new Promise(\n (_, reject) => setTimeout(reject, this.timeoutMs, \"Request timed out.\")\n )\n ]);\n }", "function getGroupInfo(){\n // Snorlax OP\n var groupInfoArray = []; // (Name, ID, Requests)\n // AJAX HERE\n $.ajax({\n url: \"https://hackforums.net/usercp.php?action=usergroups\",\n cache: false,\n success: function(response) {\n if (!$(response).find(\"Groups You Lead\")){\n window.alert(\"Group Management Links 2.0 FAILED!\\nGroup privledges not found!\");\n }\n else{\n $(response).find(\"a:contains('View Members')\").each(function() {\n groupInfoArray.push($(this).parent().prev().text()); // Group Name\n if(debug){console.log(groupInfoArray[0]);}\n groupInfoArray.push($(this).attr(\"href\").substr(20)); // Group ID\n if(debug){console.log(groupInfoArray[1]);}\n groupInfoArray.push($(this).parent().next().text().replace(/[^0-9]/g, '')); // Pending Requests\n if(debug){console.log(groupInfoArray[2]);}\n });\n GM_setValue(\"groupInfo\", groupInfoArray.join().toString());\n }\n prevInfo = GM_getValue(\"groupInfo\", false);\n setGroupInfo();\n }\n });\n}", "function sendPartyCM(data) {\n if (parent.party_list.length > 0) {\n for (let key in parent.party_list) {\n let member = parent.party_list[key];\n send_cm(member, data);\n }\n }\n}", "ListOfModerators(domain, name, email) {\n let url = `/email/domain/${domain}/mailingList/${name}/moderator?`;\n const queryParams = new query_params_1.default();\n if (email) {\n queryParams.set('email', email);\n }\n return this.client.request('GET', url + queryParams.toString());\n }", "function addTestRequest(req, res) {\n console.log('request adding')\n // Find a classroom matching the classroom_id in the request\n classroom.findOne({classroom_id: '311516886961'}, (err, doc) => {\n // Add the request and it's details to the request subdocument\n doc.requests.push({\n reward_name: 'A reward',\n reward_amount: 10,\n requester_id: '107965676074857006502',\n request_date: Date.now(),\n status: -1\n })\n // Save the document\n doc.save()\n })\n res.status(201).send()\n}", "static async getAllPrivateMessage(requestData, res) {\n const privateChatMessage = new PrivateChatMessage();\n const receiverUser = await User.findUserById(requestData['sender_user_id']);\n const result = await privateChatMessage.getChatMessages(requestData['sender_user_id'], requestData['receiver_user_id']);\n // reset counter for user and messages received from user with id receiver_user_id\n await receiverUser.changeMessageCount(requestData['receiver_user_id'], true);\n res.send(result);\n }", "promoteGroupUsers(bearerToken, groupId, userIds, options = {}) {\n if (groupId === null || groupId === void 0) {\n throw new Error(\"'groupId' is a required parameter but is null or undefined.\");\n }\n const urlPath = \"/v2/group/{groupId}/promote\".replace(\"{groupId}\", encodeURIComponent(String(groupId)));\n const queryParams = /* @__PURE__ */ new Map();\n queryParams.set(\"user_ids\", userIds);\n let bodyJson = \"\";\n const fullUrl = this.buildFullUrl(this.basePath, urlPath, queryParams);\n const fetchOptions = buildFetchOptions(\"POST\", options, bodyJson);\n if (bearerToken) {\n fetchOptions.headers[\"Authorization\"] = \"Bearer \" + bearerToken;\n }\n return Promise.race([\n fetch(fullUrl, fetchOptions).then((response) => {\n if (response.status == 204) {\n return response;\n } else if (response.status >= 200 && response.status < 300) {\n return response.json();\n } else {\n throw response;\n }\n }),\n new Promise(\n (_, reject) => setTimeout(reject, this.timeoutMs, \"Request timed out.\")\n )\n ]);\n }", "postResults() {\n const sendPromises = []\n\n this.failedSpecs.forEach((failedInfo) => {\n sendPromises.push(this._sendData(Object.assign({\n type: 'failedSpecs'\n }, failedInfo)))\n })\n\n return Promise.all(sendPromises)\n }", "async afterAddMembers ({ groupId, newUserIds, reactivatedUserIds }) {\n const zapierTriggers = await ZapierTrigger.forTypeAndGroups('new_member', groupId).fetchAll()\n\n const members = await User.query(q => q.whereIn('id', newUserIds.concat(reactivatedUserIds))).fetchAll()\n\n if (zapierTriggers && zapierTriggers.length > 0) {\n const group = await Group.find(groupId)\n for (const trigger of zapierTriggers) {\n const response = await fetch(trigger.get('target_url'), {\n method: 'post',\n body: JSON.stringify(members.map(m => ({\n id: m.id,\n avatarUrl: m.get('avatar_url'),\n bio: m.get('bio'),\n contactEmail: m.get('contact_email'),\n contactPhone: m.get('contact_phone'),\n facebookUrl: m.get('facebook_url'),\n linkedinUrl: m.get('linkedin_url'),\n location: m.get('location'),\n name: m.get('name'),\n profileUrl: Frontend.Route.profile(m, group),\n tagline: m.get('tagline'),\n twitterName: m.get('twitter_name'),\n url: m.get('url'),\n // Whether this user was previously in the group and is being reactivated\n reactivated: reactivatedUserIds.includes(m.id),\n // Which group were they added to, since the trigger can be for multiple groups\n group: { id: group.id, name: group.get('name'), url: Frontend.Route.group(group) }\n }))),\n headers: { 'Content-Type': 'application/json' }\n })\n // TODO: what to do with the response? check if succeeded or not?\n }\n }\n\n for (const member of members) {\n mixpanel.track(AnalyticsEvents.GROUP_NEW_MEMBER, {\n distinct_id: member.id,\n groupId: [groupId]\n })\n }\n }", "banGroupUsers(bearerToken, groupId, userIds, options = {}) {\n if (groupId === null || groupId === void 0) {\n throw new Error(\"'groupId' is a required parameter but is null or undefined.\");\n }\n const urlPath = \"/v2/group/{groupId}/ban\".replace(\"{groupId}\", encodeURIComponent(String(groupId)));\n const queryParams = /* @__PURE__ */ new Map();\n queryParams.set(\"user_ids\", userIds);\n let bodyJson = \"\";\n const fullUrl = this.buildFullUrl(this.basePath, urlPath, queryParams);\n const fetchOptions = buildFetchOptions(\"POST\", options, bodyJson);\n if (bearerToken) {\n fetchOptions.headers[\"Authorization\"] = \"Bearer \" + bearerToken;\n }\n return Promise.race([\n fetch(fullUrl, fetchOptions).then((response) => {\n if (response.status == 204) {\n return response;\n } else if (response.status >= 200 && response.status < 300) {\n return response.json();\n } else {\n throw response;\n }\n }),\n new Promise(\n (_, reject) => setTimeout(reject, this.timeoutMs, \"Request timed out.\")\n )\n ]);\n }", "function wrInsertContacts(results) {\n\n var wrContacts = results.map(function(ct) {\n return {\n \"SourceSystem\": sourceSystem, // TBMCircuiTree\n \"SourceID\": ct.entityid,\n \"CreateDate\": moment(ct.EnrollmentDate).format(\"YYYY-MM-DD HH:mm:ss\"),\n \"Email\": ct.EmailAddress\n ? ct.EmailAddress\n : '', // if EmailAddress is undefined, leave it blank\n \"FirstName\": ct.EntityFirstName,\n \"LastName\": ct.EntityLastName,\n \"City\": ct.HomeCity,\n \"State\": ct.HomeState,\n \"Country\": \"USA\"\n };\n });\n\n // splice into arrays of max length 1000\n // as per Wicked Reports limit\n var arrays = [],\n size = 1000;\n while (wrContacts.length > 0) {\n arrays.push(wrContacts.splice(0, size));\n }\n\n var promises = [];\n\n var options = {\n method: 'POST',\n url: 'https://api.wickedreports.com/contacts',\n headers: {\n 'Content-Type': 'application/json',\n 'apikey': wrApiKey\n },\n timeout: 5000000,\n body: '',\n json: true\n };\n\n // determined by NODE_ENV\n if (testMode) {\n options.headers.test = 1;\n }\n\n for (var i = 0; i < arrays.length; i++) {\n options.body = arrays[i];\n console.log(options.body[0]);\n promises.push(rp(options));\n }\n\n return promises;\n}", "async addMembers (usersOrIds, attrs = {}, { transacting } = {}) {\n const updatedAttribs = Object.assign(\n {},\n {\n active: true,\n role: GroupMembership.Role.DEFAULT,\n settings: {\n sendEmail: true,\n sendPushNotifications: true,\n showJoinForm: false\n }\n },\n pick(omitBy(attrs, isUndefined), GROUP_ATTR_UPDATE_WHITELIST)\n )\n\n const userIds = usersOrIds.map(x => x instanceof User ? x.id : x)\n const existingMemberships = await this.memberships(true)\n .query(q => q.whereIn('user_id', userIds)).fetch({ transacting })\n const reactivatedUserIds = existingMemberships.filter(m => !m.get('active')).map(m => m.get('user_id'))\n const existingUserIds = existingMemberships.pluck('user_id')\n const newUserIds = difference(userIds, existingUserIds)\n const updatedMemberships = await this.updateMembers(existingUserIds, updatedAttribs, { transacting })\n\n const newMemberships = []\n const defaultTagIds = (await GroupTag.defaults(this.id, transacting)).models.map(t => t.get('tag_id'))\n\n for (const id of newUserIds) {\n const membership = await this.memberships().create(\n Object.assign({}, updatedAttribs, {\n user_id: id,\n created_at: new Date()\n }), { transacting })\n newMemberships.push(membership)\n // Subscribe each user to the default tags in the group\n await User.followTags(id, this.id, defaultTagIds, transacting)\n }\n\n // Increment num_members\n // XXX: num_members is updated every 10 minutes via cron, we are doing this here too for the case that someone joins a group and moderator looks immediately at member count after that\n if (newUserIds.length > 0) {\n await this.save({ num_members: this.get('num_members') + newUserIds.length }, { transacting })\n }\n\n Queue.classMethod('Group', 'afterAddMembers', {\n groupId: this.id,\n newUserIds,\n reactivatedUserIds\n })\n\n return updatedMemberships.concat(newMemberships)\n }", "function updateRestList() {\n let currRanking = Object.keys(ranking).sort(function(a,b){return ranking[a]-ranking[b]});\n let restListToSend = [];\n for(i= 4; i >= 0; i--) {\n let id = currRanking[i];\n let restaurant = restaurants[id];\n restListToSend.push(restaurant);\n }\n allRests = restListToSend;\n sendRestUpdateMsg(restListToSend);\n}", "function batch(requests) {\n // if the batch contains only 1 request or batching is not enabled,\n // send the requests separately\n if (requests.length == 1 || !batcher || !maxBatchSize)\n return Task.wait(requests.map(ajax));\n return endpoint.batch(batcher, requests).then(function (results) {\n for (var _i = 0; _i < results.length; _i++) {\n var r = results[_i];\n Task.wait(r).then(repository.put);\n }\n return results;\n });\n }", "_sendRequestFromQueue () {\n while (this[ _requestQueue ].length > 0) {\n const request = this[ _requestQueue ].shift()\n this._sendRequest(request)\n }\n }", "function groupappend_response(req)\n{\n appending = false;\n if(req.status != 200 ) {\n pnshowajaxerror(req.responseText);\n return;\n }\n var json = pndejsonize(req.responseText);\n\n pnupdateauthids(json.authid);\n $('groupsauthid').value = json.authid;\n\n // copy new group li from permission_1.\n var newgroup = $('group_'+firstgroup).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newgroup.id = 'group_' + json.gid;\n $A(newgroup.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; node.value = ''; });\n $A(newgroup.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + json.gid; });\n\n // append new group to the group list\n $('grouplist').appendChild(newgroup);\n\n // set initial values in input, hidden and select\n $('name_' + json.gid).value = json.name;\n $('description_' + json.gid).value = json.description;\n $('editgroupnbumax_' + json.gid).value = json.nbumax;\n $('members_' + json.gid).href = json.membersurl;\n\n pnsetselectoption('state_' + json.gid, json.statelbl);\n pnsetselectoption('gtype_' + json.gid, json.gtypelbl);\n\n // hide cancel icon for new groups\n// Element.addClassName('groupeditcancel_' + json.gid, 'z-hide');\n // update delete icon to show cancel icon \n// Element.update('groupeditdelete_' + json.gid, canceliconhtml);\n\n // update some innerHTML\n Element.update('groupnbuser_' + json.gid, json.nbuser);\n Element.update('groupnbumax_' + json.gid, json.nbumax);\n Element.update('groupgid_' + json.gid, json.gid);\n Element.update('groupname_' + json.gid, json.name);\n Element.update('groupgtype_' + json.gid, json.gtypelbl);\n Element.update('groupdescription_' + json.gid, json.description) + '&nbsp;';\n Element.update('groupstate_' + json.gid, json.statelbl);\n //Element.update('members_' + json.gid, json.membersurl);\n\n // add events\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n Event.observe('groupeditsave_' + json.gid, 'click', function(){groupmodify(json.gid)}, false);\n Event.observe('groupeditdelete_' + json.gid, 'click', function(){groupdelete(json.gid)}, false);\n Event.observe('groupeditcancel_' + json.gid, 'click', function(){groupmodifycancel(json.gid)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + json.gid, 'z-hide');\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n\n // turn on edit mode\n enableeditfields(json.gid);\n\n // we are ready now, make it visible\n Element.removeClassName('group_' + json.gid, 'z-hide');\n new Effect.Highlight('group_' + json.gid, { startcolor: '#ffff99', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new group\n adding[json.gid] = 1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method validates the input and checks whether billAmount is NaN(Not a Number) or bilAmount is less than equal to zero or totalPerson equal to zero in this case show the alert of Invalid Input
validateInputs() { if(isNaN(this.billAmount) || this.billAmount <= 0 || this.totalPerson == 0) return false; return true; }
[ "function validateInputs(hotelToSave){\n\t\tvar valid = true;\n\t\tif(isNaN(hotelToSave.ratePerRoom)) {\n\t\t\thotel.validationMessages.rateShouldBeNumber = true;\n\t\t\tvalid = false;\n\t\t}\n\t\tif( hotelToSave.contact !== undefined) {\n\t\t\tif(isNaN(hotelToSave.contact.phone1)) {\n\t\t\t\thotel.validationMessages.phone1ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t\t\n\t\t\tif(isNaN(hotelToSave.contact.phone2)) {\n\t\t\t\thotel.validationMessages.phone2ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t}\n\t\treturn valid;\n\t}", "function requiredAT(objVal,strError, isZero){\n var objValue=document.getElementById(objVal); \n if(eval(objValue.value.trim().length) == 0 ){\n if(!strError || strError.length ==0){\n alert(objValue.name + \" : Required Field\"); objValue.focus(); \n return false; \n } \n alert(strError); objValue.focus(); \n return false; \n }\n if(isZero != null){\n if(isZero == 1){\n if(!numeric(objVal, \"Please enter Numeric Data only.\", 1))\n return false;\n if(!CheckForZeroAT(objValue))\n return false; \n }\n }\n return true; \n }", "function validateTaxableIncome() {\n var taxableIncome = document.TaxCalculator.taxableIncome.value;\n var regex = /[0-9]|\\./;\n \n if (taxableIncome === \"\" || taxableIncome === \"0.00\" || taxableIncome === \"0\") {\n errorMessage += \"Please Enter your Taxable Income. \\n\";\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"red\";\n return false;\n } else if (!regex.test(taxableIncome)) {\n errorMessage += \"Please Enter Only a Numberic Value As your Taxable Income. \\n\";\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"red\";\n return false;\n } else {\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"\";\n return true;\n }\n}", "function required(objVal,strError, isZero){\n var objValue=document.getElementById(objVal); \n if(eval(objValue.value.trim().length) == 0 ){\n if(!strError || strError.length ==0){\n alert(objValue.name + \" : Required Field\"); objValue.focus(); \n return false; \n } \n alert(strError); objValue.focus(); \n return false; \n }\n if(isZero != null){\n if(isZero == 1){\n if(!numeric(objVal, \"Please enter Numeric Data only.\", 1))\n return false;\n if(!CheckForZero(objValue))\n return false; \n }\n }\n return true; \n }", "function validateIntRate(errorMsg) {\n var tempIntRate = document.mortgage.intRate.value;\n tempIntRate = tempIntRate.trim();\n var tempIntRateLength = tempIntRate.length;\n var tempIntRateMsg = \"Please enter Interest Rate!\";\n\n if (tempIntRateLength == 0) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Field is empty <br />\" + tempIntRateMsg + \"</p>\";\n } else {\n if (isNaN(tempIntRate) == true) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Must be numeric <br />\" + tempIntRateMsg + \"</p>\";\n } else {\n if (parseFloat(tempIntRate) < 2.000 || parseFloat(tempIntRate) > 11.000) {\n errorMsg += \"<p><mark>Interest rate field: </mark>Must be values: 2.000 thru 11.000 inclusive <br />\" + tempIntRateMsg + \"</p>\";\n } \n }\n }\n return errorMsg;\n}", "function validateAmortization(errorMsg) {\n var tempAmortization = document.mortgage.amortization.value;\n tempAmortization = tempAmortization.trim();\n var tempAmortizationLength = tempAmortization.length;\n var tempAmortizationMsg = \"Please enter Amortization!\";\n\n if (tempAmortizationLength == 0) {\n errorMsg += \"<p><mark>No. of years field: </mark>Field is empty <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (isNaN(tempAmortization) == true) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be numeric <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (tempAmortization < 5 || tempAmortization > 20) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be values: 5 thru 20 inclusive <br />\" + tempAmortizationMsg + \"</p>\";\n }\n }\n }\n return errorMsg;\n}", "function isValidAmount(element){\n\t\n\t\t// user's amount\n\t\tvar amount = element.value;\t\n\t\t\n\t\t// parse amount as float\n\t\tamount = parseFloat(amount);\n\t\t\n\t\t// if amount is number, parse amount\n\t\tif(!isNaN(amount) && amount > 0.0 && amount < 100000){\n\t\t\n\t\t\t// test passed\n\t\t\treturn true;\n\t\t\t\n\t\t}else{\n\t\t\n\t\t\t// alert user of error\n\t\t\talert(\"Amount has to be in range: 0 to 100,000.\");\n\t\t\t\n\t\t\t// shift focus to failed webpage field\n\t\t\telement.focus();\n\t\t\t\n\t\t\t// test failed\n\t\t\treturn false;\n\t\t}\n\t}", "function validarDepNumCuenta() {\n var datosCorrectos;\n datosCorrectos = true;\n var error = \"\";\n var cd = document.getElementById('detalleNumId').value,\n cedulaFormato = /^[1-9]-?\\d{4}-?\\d{4}$/, expNumerica = /^[0-1000000]$/;\n var detMonto=document.getElementById('detalleMontoDep').value;\n \n \n // Valida si el campo de identificacion va vacio\n if (document.getElementById('detalleNumId').value == \"\") {\n error = \"\\n El campo de numero de identificacion de depositante está en blanco\";\n datosCorrectos = false;\n \n }\n // Valida si el formato ingresado en la cedula es correcto\n else if (!cedulaFormato.test(cd)) {\n error = \"\\n El numero de cédula: \" + cd + \" es incorrecto!\\nPor favor intente el formato\\n\\\n 100000000 (9 digitos)\";\n datosCorrectos = false;\n }\n \n // Valida que el campo ingresado en monto sea una expresion numerica\n else if (isNaN(detMonto) ) {\n error = \"\\n El valor ingresado en el campo monto de deposito no es una experesion numerica! \";\n datosCorrectos = false;\n }\n \n // Falso si el monto digitado es menor o igual a 0 se valida su error\n else if (detMonto <= 0){\n error = \"\\n El campo monto de deposito no puede ser menor o igual a 0\";\n datosCorrectos = false;\n console.log(\"VALIDA VALOR MONTO\");\n }\n \n // Valida que el monto ingresado para deposito sea una expresion numerica\n else if (detMonto.length >= 7 ){\n error = \"\\n La cifra excede el limite permitido para transferencia del sistema!\\n\\\n Por favor intente un valor menor a un millon! \";\n datosCorrectos = false;\n console.log(\"VALIDA MAX MONTO\");\n }\n\n// Si existen datos incorrecto entonces se realiza un alert con el error ocurrido al usuario\nif (!datosCorrectos) {\nalert('ERROR: ' + error);\n }\nreturn datosCorrectos;\n}", "function checkForNumber(min, max, avg) {\n if ((isNaN(min)) || (isNaN(max)) || (isNaN(avg))) {\n alert('You have entered a value that is not a number!');\n return false;\n } else if (min > max) {\n alert('Your minimum value is greater than your maximum value');\n return false;\n }\n}", "static enterBudget(inputVal, budget) {\r\n if(this.checkInput(inputVal.value, budgetWarning)) {\r\n throw new Error('Budget field cannot be empty');\r\n }\r\n else {\r\n budgetParams['budget'] = inputVal.value;\r\n budget.textContent = budgetParams['budget'];\r\n } \r\n }", "function validatePinAndAmount() {\n\tvar amount = '';\n\tvar pin = '';\n\tvar fundingSourceType = getVisibleCashFundingSource();/* Fetching the visible funding source */\n\t\n\tif ($('#cashPaymentOptionBox1').is(':visible')) {/* Evolve cash box is visible then proceed */\n\t\tamount = getFormatedNumber($(\"#amountOfCashEvolve\").val(), false);/* Get amount from the relevant cash div and formatted it */\n\t\tvar $inputFields = $('#pinSectionPreCash :input');/* Due to multiple input boxes gettting each of them through iterating */\n\t\t\t$inputFields.each(function() {\n\t\t\t\tpin += $(this).val();/* Getting pin number from the relevant 'Div' */\n\t\t\t});\n\t} else if ($('#cashPaymentOptionBox2').is(':visible')) {/* Reload it cash box is visible then proceed */\n\t\tamount = getFormatedNumber($(\"#amountOfCashReloadit\").val(), false);/* Get amount from the relevant cash div and formatted it */\n\t\tpin += $('#pinOfCashREloadit').val();/* Getting pin number from the relevant 'Div' */\n\t} else if ($('#cashPaymentOptionBox3').is(':visible')) {/* Vanilla cash box is visible then proceed */\n\t\tamount = getFormatedNumber($(\"#amountOfCashVanilla\").val(), false);/* Get amount from the relevant cash div and formatted it */\n\t\tvar $inputFields = $('#pinSectionInComm :input');/* Due to multiple input boxes gettting each of them through iterating */\n\t\t$inputFields.each(function() {\n\t\t\tpin += $(this).val();/* Getting pin number from the relevant 'Div' */\n\t\t});\n\t}\n\t\n\tif (jsonTypeConstant.BLACKHAWK == fundingSourceType) {/* Visible funding source is BLACKHAWK then proceed */\n\t\tvalidateCashFundingFields(pin, amount, 'saveBtnOfRelodit');\n\t} else if (jsonTypeConstant.INCOMM == fundingSourceType) {/* Visible funding source is INCOMM then proceed */\n\t\tvalidateCashFundingFields(pin, amount, 'saveBtnOfVanilla');\n\t} else if (jsonTypeConstant.PRECASH == fundingSourceType) {/* Visible funding source is PRECASH then proceed */\n\t\tif (pin.length < 16 && !amount) {/* Check for pin length must be 16 and amount not be empty */\n\t\t\t$(\"#saveBtnOfEvolve\").removeClass(\"bg_green\").addClass(\"bg_grey1\");\n\t\t\tdisableButton('saveBtnOfEvolve');\n\t\t\treturn false;\n\t\t} else if (!amount) {/* Amount should not be empty*/\n\t\t\t$(\"#saveBtnOfEvolve\").removeClass(\"bg_green\").addClass(\"bg_grey1\");\n\t\t\tdisableButton('saveBtnOfEvolve');\n\t\t\treturn false;\n\t\t} else if (pin.length < 16) {/* Pin should not be less than 16 for Evolve */\n\t\t\t$(\"#saveBtnOfEvolve\").removeClass(\"bg_green\").addClass(\"bg_grey1\");\n\t\t\tdisableButton('saveBtnOfEvolve');\n\t\t\treturn false;\n\t\t} else if(amount && validatePinLunh(pin)) {/* amount should not be empty and MOD10 check should satisfy */\n\t\t\t$(\"#pinOuterSection\").removeClass(\"error_red_border\");\n\t\t\t$(\"#blueBoxCnt1\").hide();\n\t\t\t$(\"#saveBtnOfEvolve\").removeClass(\"bg_grey1\").addClass(\"bg_green\");\n\t\t\tenableButton('saveBtnOfEvolve');\n\t\t\treturn false;\n\t\t}\n\t}\n}", "validateOccupancy(){\n if(this.occupancy ==''|| this.occupancy < 0 || this.occupancy > 180){\n return \"Occupancy cannot be empty, should not be negative and should not be morethan 180\";\n }\n else{\n return this.occupancy;\n }\n }", "function validateInput() {\n\tvar valid = false;\n\tvar maxPins = 0;\n\tif (!((pins==0)||(pins==\"1\")||(pins==2)||(pins==3)||(pins==4)||(pins==5)||(pins==6)||(pins==7)||(pins==8)||(pins==9)||(pins==10))) {\n\t\talert('The number of pins must be between 0 and 10.');\n\t\t$scope.pins = '';\n\t} else if ((ball == 1) && (frame != 9) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\t} else if ((ball == 1) && (frame == 9) && (parseInt(line[frame][0]) != 10) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\n\t} else {\n\t\tvalid = true;\n\t\tconsole.log('valid input');\n\t}\n\treturn valid;\n}", "function validateCashFundingFields(pin, amount, saveBtn) {\n\tif (!pin && !amount) {/* Pin and amount should not be empty */\n\t\t$(\"#\"+saveBtn).removeClass(\"bg_green\").addClass('bg_grey1');\n\t\tdisableButton(saveBtn);\n\t\treturn false;\n\t} else if (pin.length !== 10) {/* Pin length should not be less than 10 digit */\n\t\t$(\"#\"+saveBtn).removeClass(\"bg_green\").addClass('bg_grey1');\n\t\tdisableButton(saveBtn);\n\t\treturn false;\n\t\tif (!pin) {/* Pin should not be empty */\n\t\t\t$(\"#\"+saveBtn).removeClass(\"bg_green\").addClass('bg_grey1');\n\t\t\tdisableButton(saveBtn);\n\t\t\treturn false;\n\t\t}\n\t} else if (!amount) {/* amount should not be empty */\n\t\t$(\"#\"+saveBtn).removeClass(\"bg_green\").addClass('bg_grey1');\n\t\tdisableButton(saveBtn);\n\t\treturn false;\n\t} else if (amount && pin && pin.length === 10) {/* Pin and amount should not be empty and pin number should be 10 digit*/\n\t\t$(\"#\"+saveBtn).addClass(\"bg_green\").removeClass(\"bg_grey1\");\n\t\tenableButton(saveBtn);\n\t\treturn false;\n\t}\n}", "function _validate(salaryInfo)\n{\n if (!_validateText(salaryInfo.firstName))\n throw new Error('firstName is required');\n\n if (!_validateText(salaryInfo.lastName))\n throw new Error('lastName is required');\n\n if (!_validateText(salaryInfo.payPeriod))\n throw new Error('payPeriod is required');\n\n if (!_validateNumber(salaryInfo.annualSalary))\n throw new Error('annualSalary must be a number');\n\n if (!_validateNumber(salaryInfo.superRate))\n throw new Error('superRate must be a number');\n\n}", "function isExpenseValid(expense) {\n return expense &&\n expense.title !== '' &&\n expense.title.length < 55 &&\n wijmo.isNumber(expense.amount) &&\n wijmo.isDate(expense.date) &&\n expense.amount >= 0;\n }", "function checkInsert() {\n var insert_student_name = document.getElementById('insert_student_name').value;\n var insert_student_score = document.getElementById('insert_student_score').value;\n if (insert_student_name==null || insert_student_name=='') {\n alert('student name cannot be empty.')\n return false;\n }\n if (insert_student_score==null || insert_student_score=='') {\n alert('student score cannot be empty.')\n return false;\n }\n if (isNaN(parseFloat(insert_student_score))) {\n alert('invalid score.')\n return false;\n }\n return true;\n}", "function checkTotals(){\n var iconUrl= 'http://localhost/feemaster/assets/images/icons/warning.png';\n var grandsale = parseFloat($(\"#totalsaletxt\").val());\n console.log(\"total sale is: \"+grandsale);\n var cash = parseFloat($(\"#cashtxt\").val());\n \n if($.isNumeric(grandsale) && grandsale>0){\n if($.isNumeric(cash)){\n if(cash >= grandsale){\n Confirm.render('Execute Transaction?','execute_sale','cancel');\n }else{\n Alert.render(\"Cash issued is insufficient!\",\"Alert\",iconUrl);\n //$(\"#cashtxt\").focus();\n } \n }else{\n Alert.render(\"Enter a valid cash amount!\",\"Alert\",iconUrl);\n // $(\"#cashtxt\").focus();\n }\n \n }else{\n Alert.render('Add at least a single item to sell!',\"Notification\",iconUrl);\n $(\"#searchtxt\").focus();\n }\n}", "function check_input_fields() {\n var name = $('#student_name').val().replace(/\\s+/g, '');\n var course = $('#course_name').val().replace(/\\s+/g, '');\n var grade = parseFloat($('#student_grade').val());\n if (name == '' || course == '' || grade < 0 || grade > 100 || grade == '' || isNaN(grade) == true) {\n var message = 'All input fields must contain at least one non-space character. Grade must be a number between 0 and 100.';\n display(message);\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[0] Problem given a string of words, return an array of elements, each of which contains the number of vowels in the argument Input A string of ONE or MORE words Output An array, each element corresponds to the number of vowels in the argument word Algorithm Separate each word from the arguments string check how many vowels are in the individual word push the number of vowels to the resulting array when out of words, return resulting array
function vowelCount(stringOfWords) { let wordsArray = stringOfWords.split(' '); const VOWELS = 'aeiou'; if (stringOfWords.length === 0) return []; let vowelsArray = wordsArray.map(individualWord => { let vowelsInWord = 0; individualWord.split('').forEach(char => { if (VOWELS.includes(char.toLowerCase())) { vowelsInWord += 1; } }); return vowelsInWord; }); return vowelsArray; }
[ "function vowels(str) {\n\t// let vowelCount = {\n\t// \t'a': 0,\n\t// \t'e': 0,\n\t// \t'i': 0,\n\t// \t'o': 0,\n\t// \t'u': 0\n\t// }\n\n\t// for (let char of str) {\n\t// \tchar = char.toLowerCase();\n\t// \tif (vowelCount.hasOwnProperty(char)) {\n\t// \t\tvowelCount[char] = vowelCount[char] + 1;\n\t// \t}\n\t// }\n\n\t// let count = Object.values(vowelCount).reduce((a, b) => {\n\t// \treturn a + b;\n\t// });\n\n\t// return count;\n\tstr = str.toLowerCase();\n\treturn (str.match(/[aeiou]/g)) ? str.match(/[aeiou]/g).length : 0;\n}", "countBigWords(input) {\n // Set a counter equal to 0\n let counter = 0;\n // Split the input into words\n let temp = input.split(\" \");\n // Determine the length of each word by iterating over the array\n //If the word is greater than 6 letters, add 1 to a counter\n // If the word is less than or equal to 6 letters, go on to next word\n for(let i = 0; i < temp.length; i++) {\n if (temp[i].length > 6) {\n counter++;\n }\n }\n // Output the counter\n return counter;\n }", "function solve(arr){ \n let alpha = \"abcdefghijklmnopqrstuvwxyz\";\n return arr.map(a => a.split(\"\").filter((b,i) => b.toLowerCase() === alpha[i]).length )\n}", "function count_consonants(string){\n for(i=(string.length-1);i>=0;i--){\n \n for(j=0;j<10;j++){\n \n if (string[i] == vowels[j]){\n count++\n break;\n }\n if (string[i] == space){\n count++\n break;\n }\n }\n }\n \n console.log('Number of consonants : ',string.length-count)\n}", "function countConsonants(string) {\n var countConsonants = 0;\n var temp = [];\n //Adding characters in array\n for (var i = 0; i < string.length; i++) {\n temp.push(string[i]);\n }\n // console.log(temp);\n for (var i = 0; i < temp.length; i++) {\n var char = temp[i].toLowerCase();\n if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || char === ' ') {\n continue;\n }\n countConsonants++;\n // console.log(char);\n }\n console.log(\"Total consonants in '\" + string + \"' is: \", countConsonants);\n}", "function orderedVowelWords(str){\r\n var words = str.split(' ');\r\n\r\n return words.filter(function(word){\r\n return isOrderedVowelWord(word);\r\n }).join(' ');\r\n}", "function genVowelWordsHelper(word) {\n\tvar retSet = new Set(['']);\n\n\tfor (var i = 0; i < word.length; i++) {\n\t\tvar letter = word[i];\n\t\tif (isVowel(letter)) {\n\t\t\tvar tempSet = retSet.clone();\n\t\t\tretSet.clear();\n\t\t\tVOWELS.forEach(function(vowel) {\n\t\t\t\tvar aSet = addLettersToSet(vowel, tempSet);\n\t\t\t\tretSet.addEach(aSet);\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tretSet = addLettersToSetHelper(letter, 1, retSet);\n\t\t}\n\t};\n\treturn retSet;\n}", "function anagramCounter(arrayOfWords) {\n let sortedWords = arrayOfWords.map(word => word.split('').sort().join(''));\n let numberOfAnagrams = 0;\n\n sortedWords.forEach((word, theIndex) => {\n for (let i = theIndex + 1; i < sortedWords.length; i++) {\n if (word === sortedWords[i]) {\n numberOfAnagrams++\n }\n }\n })\n return numberOfAnagrams\n}", "function solve(s) {\n\tlet result = \"\";\n\tlet regex = /[aeiou]/;\n\tlet consonants = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn !regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tlet vowels = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tif (consonants.length > vowels.length) {\n\t\tfor (let i = 0; i < consonants.length; i++) {\n\t\t\tif (!vowels[i]) {\n\t\t\t\tresult += consonants[consonants.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += consonants[i];\n\t\t\tresult += vowels[i];\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < vowels.length; i++) {\n\t\t\tif (!consonants[i]) {\n\t\t\t\tresult += vowels[vowels.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += vowels[i];\n\t\t\tresult += consonants[i];\n\t\t}\n\t}\n\tif (result.length !== s.length) {\n\t\treturn \"failed\";\n\t} else {\n\t\treturn result;\n\t}\n}", "function calculateWords(textInput){\n let wordsArr = textInput.trim().split(' ')\n return wordsArr.length;\n }", "function aCounter(word) {\n let count = 0;\n let index = 0\n while (index < word.length) {\n let char = word[index];\n if (char === \"a\" || char === \"A\") {\n count += 1;\n }\n index++\n }\n return count;\n }", "function countAs(string) {\n var stringArray = string.split(\"\");\n var count = 0;\n stringArray.forEach(function(letter) {\n if (letter === \"a\") {\n count++;\n }\n });\n return count;\n}", "function vowelCount(myString){\r\n let vowelsMap = new Map();\r\n \r\n for (let char of myString){\r\n if (\"aeiou\".indexOf(myString)){\r\n if (vowelsMap.has(char)){\r\n vowelsMap.set(char,((vowelsMap.get(char))+1));\r\n }\r\n else{\r\n vowelsMap.set(char,1);\r\n \r\n }\r\n \t\t\t }\r\n }\r\n \r\n return vowelsMap;\r\n}", "function countYZ(word) {\n word = word.toLowerCase();\n var count = 0;\n //console.log(word[word.length - 1]);\n if (word[word.length - 1] == \"y\" || word[word.length - 1] == \"z\") {\n count += 1;\n }\n for (var i = 0; i < word.length; i++) {\n if(word[i] == \" \") {\n\n if(word[i-1] == \"y\") {\n count += 1;\n }else if(word[i-1] == \"z\"){\n count += 1;\n }\n }\n }\n return count;\n}", "function wordLengths(arr) {\n return arr.map(x => x.length);\n}", "function longestVowelSubsequence(s) {\n // Write your code here\n s=s.split('');\n let iIndex=j.findIndex(o=>o==='a');\n let startIndex=iIndex;\n let jIndex=0;\n let j=['a','e','i','o','u'];\n let i=0;\n iIndex++;\n while(iIndex<s.length){\n if(jIndex===5){\n endIndex=iIndex;\n iIndex=s.length;\n // 返回结果\n }\n if(jIndex===0){\n if(s[iIndex]===j[jIndex]){\n startIndex=iIndex;\n iIndex++;\n }else{\n jIndex++;\n }\n }else{\n if(s[iIndex]===j[jIndex]){\n iIndex++;\n jIndex++;\n }else{\n iIndex++;\n }\n }\n \n }\n if(jIndex!==5){\n return 0;\n }\n let result_str=s.slice(startIndex,endIndex);\n let mIndex=0,nIndex=0;\n while(mIndex<result_str.length){\n let curIndex=j.findIndex(o=>o===result_str[mIndex]);\n if(curIndex===nIndex){\n mIndex++;\n }else if(curIndex-nIndex===1){\n nIndex++;\n }else if(curIndex<nIndex){\n result_str.splice(mIndex,1)\n }else{\n mIndex++\n }\n }\n return result_str.length;\n}", "function construct_letter_array() {\n\tvar letter_array = [];\n\tfilter_letters.split(\"\").forEach( function( item ) {\n\t\tif ( letter_array[ item ] ) {\n\t\t\tletter_array[ item ] = letter_array[ item ] + 1;\n\t\t} else {\n\t\t\tletter_array[ item ] = 1;\n\t\t}\t\n\t}) ;\t\n\treturn letter_array;\n}", "function allSameVowels(input) {\n return input.every((string) => typeof(string) === \"string\" && string.match(/[aeiou]/g).every((vowel) => vowel === string.match(/[aeiou]/g)[0]))\n}", "function calculateUniqueWords(textInput) {\n\tvar inputWords = textInput.split(\" \");\n\tvar sortedWords = inputWords.sort();\n\tvar finalUniqueList = []\n\tfor (i = 0; i <= sortedWords.length; i++) {\n\t\tif (sortedWords[i] !== sortedWords[i+1]) {\n\t\t\tfinalUniqueList.push(sortedWords[i])\n\t\t}\n\t}\n\t//console.log(\"final uniqueWords list \" + finalUniqueList)\n\t//console.log(finalUniqueList.length);\n\treturn finalUniqueList.length;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
params : request with path, _query and _headers ; prettyJson which is enriched with links ; resList whose size is used as paginating condition.
function addPaginationLinks(request, prettyJson, resList, successFunctionName) { // adding "..." link for pagination : // NB. everything is already encoded if (!successFunctionName) { successFunctionName = 'null'; } var start = 0; var limit = dcConf.queryDefaultLimit; // from conf var query = ''; if (request._query) { // at least must get actual limit to know whether there might be more data // but it's easier to also get start and build query at the same time var splitQuery = request._query.split('&'); for (var critInd in splitQuery) { var criteria = splitQuery[critInd]; if (criteria.indexOf('start=') !== -1) { start = parseInt(criteria.substring(criteria.indexOf('=') + 1), 10); } else if (criteria.indexOf('limit=') !== -1) { limit = parseInt(criteria.substring(criteria.indexOf('=') + 1), 10); } else { query += '&' + criteria; } } } if (start !== 0) { var previousStart = Math.max(0, start - limit); var relativeUrl = request.path + '?start=' + previousStart + '&limit=' + limit + query; var headers = {}; for (var hInd in request._headers) { if (hInd === 'Accept' || hInd.indexOf('X-Datacore-') === 0) { headers[hInd] = request._headers[hInd]; // Accept for RDF, else 'X-Datacore-View'... } } prettyJson = '<a href="' + relativeUrl + '" class="dclink" onclick="' + 'javascript:return findDataByType($(this).attr(\'href\'), ' + successFunctionName + ', null, null, null, ' + stringifyForAttribute(headers) + ');' + '">...</a>' + lineBreak(0) + prettyJson; } if (!resList || typeof resList === 'string' // RDF case : always display || resList.length === limit) { var nextStart = start + limit; var relativeUrl = request.path + '?start=' + nextStart + '&limit=' + limit + query; var headers = {}; for (var hInd in request._headers) { if (hInd === 'Accept' || hInd.indexOf('X-Datacore-') === 0) { headers[hInd] = request._headers[hInd]; // Accept for RDF, else 'X-Datacore-View'... } } prettyJson += lineBreak(0) + '<a href="' + relativeUrl + '" class="dclink" onclick="' + 'javascript:return findDataByType($(this).attr(\'href\'), ' + successFunctionName + ', null, null, null, ' + stringifyForAttribute(headers) + ');' + '">...</a>'; } return prettyJson; }
[ "getAll(req, res, next) {\n\n var\n request = new Request(req),\n response = new Response(request, this.expandsURLMap),\n criteria = this._buildCriteria(request);\n\n this.Model.paginate(criteria, request.options, function(err, paginatedResults, pageCount, itemCount) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n response\n .setPaginationParams(pageCount, itemCount)\n .formatOutput(paginatedResults, function(err, output) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n res.json(output);\n });\n\n });\n }", "function setPaginationHeaders({ req, res, limit, offset, total }) {\n if (req == null || res == null || limit == null || offset == null || total == null) {\n return\n }\n function url(baseUrl, query, rel) {\n let url = baseUrl\n let index = 0\n _.forOwn(query, (value, key) => {\n url += `${(index == 0 ? \"?\" : \"&\")}${key}=${value}`\n index += 1\n })\n return `<${url}>; rel=\"${rel}\"`\n }\n // Set X-Total-Count header\n res.set(\"X-Total-Count\", total)\n let links = []\n let baseUrl = getBaseUrl(req, false) + req.path\n let query = _.cloneDeep(req.query)\n query.limit = limit\n // rel: first\n query.offset = 0\n links.push(url(baseUrl, query, \"first\"))\n // rel: prev\n if (offset > 0) {\n query.offset = Math.max(offset - limit, 0)\n links.push(url(baseUrl, query, \"prev\"))\n }\n // rel: next\n if (limit + offset < total) {\n query.offset = offset + limit\n links.push(url(baseUrl, query, \"next\"))\n }\n // rel: last\n let current = 0\n while (current + limit < total) {\n current += limit\n }\n query.offset = current\n links.push(url(baseUrl, query, \"last\"))\n // Set Link header\n res.set(\"Link\", links.join(\",\"))\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 }", "async QueryAssetsWithPagination(ctx, queryString, pageSize, bookmark) {\n\n const {iterator, metadata} = await ctx.stub.getQueryResultWithPagination(queryString, pageSize, bookmark);\n const results = await this.GetAllResults(iterator, false);\n\n results.ResponseMetadata = {\n RecordsCount: metadata.fetched_records_count,\n Bookmark: metadata.bookmark,\n };\n\n return JSON.stringify(results);\n }", "getPagingParams(req) {\n const limit = req.query.limit || 500;\n const pageNumber = req.query.pageNumber || 1;\n\n const offset = limit * (pageNumber - 1);\n return {\n offset,\n limit\n }\n }", "function getFullRequestPathWithoutPaging(div, sort, idlist, knownCount) {\n var request = getRequest(div), params = getUrlParamsForAllRecords(div);\n $.each(params, function (key, val) {\n if (typeof knownCount === 'undefined' || knownCount === true || key !== 'knownCount') {\n if (!idlist && key === 'idlist') {\n // skip the idlist param value as we want the whole map\n val = '';\n }\n request += '&' + key + '=' + encodeURIComponent(val);\n }\n });\n if (sort && div.settings.orderby !== null) {\n request += '&orderby=' + div.settings.orderby + '&sortdir=' + div.settings.sortdir;\n }\n return request;\n }", "function getAllJobs(req, res, next) {\n let nextPage = null; // will be used for cursor pagination\n\n const match = {\n job_status_id: 1, // will rep the initial state of job i.e accepting quotes\n };\n\n // TODO make modular\n const limit = parseInt(req.query.limit) || 100;\n\n if (req.query.industry) {\n match.industry_id = parseInt(req.query.industry);\n }\n\n if (req.query.jobStatus) {\n match.job_status_id = parseInt(req.query.jobStatus);\n }\n\n if (req.query.hr) {\n match.hiring_manager_id = parseInt(req.query.hr);\n }\n\n if (req.query.nextPage) {\n nextPage = req.query.nextPage;\n }\n\n JobService.getAllJobs(nextPage, match, limit)\n .then((jobs) => {\n return jobs ? res.json(jobs) : res.sendStatus(404);\n })\n .catch(next);\n}", "setPaginationData(data)\n {\n if (data.length) {\n var lastValue = data[data.length-1][this.model.key];\n }\n\n // The Response object takes care of this.\n this.request.pagination = {\n count: data.length,\n limit: this.limit,\n total: this.total,\n filter: this.filter,\n sort: this.querySort(),\n url: this.total > this.limit\n ? new Buffer(lastValue.toString()).toString('base64')\n : null\n }\n }", "async function listRecords(req, res) {\n let countQuery;\n let recordQuery;\n\n console.log(req.body);\n\n switch (req.body.queryType) {\n case \"keys\":\n countQuery = queries.keyCount;\n recordQuery = queries.keyRecords;\n break;\n case \"properties\":\n countQuery = queries.propCount;\n recordQuery = queries.propRecords;\n break;\n case \"people\":\n countQuery = queries.peopleCount;\n recordQuery = queries.peopleRecords;\n break;\n default:\n console.log(\"No query type passed to server.\");\n res.status(400).json({ error: \"No query type passed to server.\" });\n return;\n }\n\n //Build queries with WHERE clause, if request body includes an id and a value.\n if (req.body.filter.id && req.body.filter.value) {\n //People view. Requires alias for UNION ALL subselect.\n if (req.body.queryType === \"people\") {\n countQuery +=\n \"WHERE c.\" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE users.\" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n } else if (req.body.queryType === \"properties\") {\n //Properties and Keys views.\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n } else {\n //The key view has a special QR Code input, which will always take\n //a specially formatted string consisting of 4 values\n if (req.body.filter.id === \"qr\") {\n const filterArray = req.body.filter.value.split(\"*\");\n countQuery += `WHERE property_number LIKE ${filterArray[0]} AND\n office_location LIKE '${filterArray[1]}' AND key_type LIKE\n '${filterArray[2]}' AND key_number LIKE ${filterArray[3]} `;\n recordQuery += `WHERE property_number LIKE ${filterArray[0]} AND\n office_location LIKE '${filterArray[1]}' AND key_type LIKE\n '${filterArray[2]}' AND key_number LIKE ${filterArray[3]} `;\n } else if (req.body.filter.id === \"key_status\") {\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"' +\n req.body.filter.value +\n '%\" ';\n } else {\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n }\n }\n }\n\n //Build queries with ORDER BY clause, if request body includes an id\n if (req.body.sorted.length) {\n recordQuery += \"ORDER BY \" + req.body.sorted[0].id + \" \";\n if (req.body.sorted[0].desc) {\n recordQuery += \"DESC \";\n }\n }\n\n //Enable pagination\n let offset = req.body.page * req.body.pageSize;\n recordQuery += `LIMIT ${offset}, ${req.body.pageSize} `;\n\n console.log(recordQuery);\n\n //Query database and build response object\n try {\n const count = await db.dbQuery(countQuery);\n const rows = await db.dbQuery(recordQuery);\n let pageCount = Math.ceil(\n parseFloat(count[0].count) / parseFloat(req.body.pageSize)\n );\n const payload = {\n data: rows,\n pages: pageCount\n };\n res.status(200).json(payload);\n } catch (err) {\n console.log(err);\n res.status(404).json(err);\n }\n}", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'list', kparams);\n\t}", "async function listReviews (req, res) {\n const data = await ReviewService.listReviews(req.query)\n helper.setPaginationHeaders(req, res, data)\n}", "paginate({ unlimited = false } = {}) {\r\n const { page: qPage, limit: qLimit, skip: qskip } = this.queryObj;\r\n\r\n const page = qPage * 1 || 1;\r\n let limit = unlimited ? undefined : defaultRecordPerQuery;\r\n if (qLimit)\r\n limit = qLimit * 1 > maxRecordsPerQuery ? maxRecordsPerQuery : qLimit * 1;\r\n const skip = qskip\r\n ? qskip * 1\r\n : (page - 1) * (limit || defaultRecordPerQuery);\r\n\r\n this.query.skip = skip;\r\n this.query.take = limit;\r\n return this;\r\n }", "function parseListRequest(req){\n var reqObj = {};\n reqObj.originalUrl = req.originalUrl;\n reqObj.uid = req.params.guid;\n reqObj.env = req.params.environment;\n reqObj.domain = req.params.domain;\n return reqObj;\n}", "async listAllClientRequests(req, res) {\n try {\n const id_cliente = req.clientId.id;\n\n const requests = await Request.find({\n id_cliente,\n }).populate([\"produtos\", \"id_empresa\"]);\n\n const count = requests.length;\n\n if (count === 0)\n return res.status(404).send({ NOTFOUND: \"Nenhum pedido encontrado\" });\n\n return res.status(200).send({ TOTAL: count, requests });\n } catch (error) {\n return res.status(400).send({ error: error.message });\n }\n }", "function get_loads(req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n //Limit to three boat results per page\r\n var q = datastore.createQuery(LOAD).limit(5);\r\n\r\n var results = {};\r\n\r\n if(Object.keys(req.query).includes(\"cursor\")){\r\n q = q.start(req.query.cursor);\r\n }\r\n\r\n return datastore.runQuery(q).then( (entities) => {\r\n results.loads = entities[0].map(ds.fromDatastore);\r\n for (var object in results.loads)\r\n {\r\n if(results.loads[object].carrier.length === 1)\r\n {\r\n var bid = results.loads[object].carrier[0];\r\n var boatUrl = req.protocol + '://' + req.get('host') + '/boats/' + bid;\r\n results.loads[object].carrier = [];\r\n results.loads[object].carrier = {\"id\": bid, \"self\": boatUrl};\r\n }\r\n \r\n // Make sure self link does not have cursor in it\r\n if(Object.keys(req.query).includes(\"cursor\"))\r\n {\r\n results.loads[object].self = req.protocol + '://' + req.get('host') + results.loads[object].id;\r\n }\r\n else\r\n {\r\n results.loads[object].self = fullUrl +'/' + results.loads[object].id;\r\n }\r\n }\r\n if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS){\r\n results.next = req.protocol + \"://\" + req.get(\"host\") + req.baseUrl + \"?cursor=\" + encodeURIComponent(entities[1].endCursor);\r\n }\r\n }).then(() =>{\r\n return count_loads().then((number) => {\r\n results.total_count = number;\r\n return results; \r\n });\r\n });\r\n}", "getAllLists(req, res, next) {\n listsHelper.getAllLists(req.reqId).then((lists) => {\n res.json({\n success: 1,\n message: responseMessages.listsFetched.success,\n data: lists,\n });\n }).catch((error) => {\n next(error);\n });\n }", "constructor(collection, itemsPerPage) {\n\n let paginate = function paginate(arr, n) {\n if (arr.length === 0) return [];\n return [].concat([arr.slice(0, n)]).concat(paginate(arr.slice(n), n));\n };\n\n this.collection = collection;\n this.itemsPerPage = itemsPerPage;\n this.paginatedArray = paginate(collection, itemsPerPage);\n }", "async function list(req, res) {\n const { movieId } = req.params;\n\n if (movieId)\n {\n let results = await service.listWithCritic();\n const byResult = movieId\n ? (result) => result.movie_id == movieId\n : () => true;\n\n results = results.filter(byResult);\n\n const reduceReviewsAndCritics = reduceProperties(\"review_id\", {\n critic_id: [\"critic\", \"critic_id\"],\n preferred_name: [\"critic\", \"preferred_name\"],\n surname: [\"critic\", \"surname\"],\n organization_name: [\"critic\", \"organization_name\"],\n });\n \n\n const resultdata = reduceReviewsAndCritics(results);\n\n res.json({ data: resultdata });\n\n\n }\n else\n {\n let results = await service.list();\n res.json({ data: results });\n }\n\n\n}", "function getStarredSegments() {\n let pageCounter = 1;\n starredAPI();\n function starredAPI(){\n let url = 'https://www.strava.com/api/v3/segments/starred';\n const settings = {\n url: url,\n data: {\n access_token:STATE.access_token,\n per_page: 200,\n page: pageCounter\n },\n success: function(data) {\n STATE.temp = data;\n for (let i=0; i < data.length; i++) {\n let segmentData = {\n 'activity_type': data[i].activity_type,\n 'city': data[i].city,\n 'country': data[i].country,\n 'id': data[i].id,\n 'name': data[i].name,\n 'state': data[i].state\n };\n STATE.starred.push(segmentData);\n }\n pageCounter++;\n if(data.length === 200) {\n starredAPI();\n }\n },\n error: function(res) {\n console.log('Error! Status ',res.status);\n }\n };\n $.ajax(settings);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
opens window with choise of spell type
open() { document.querySelector(".spell-page").style.display = "block"; }
[ "chooseSpell(event) {\n this.kind = event.target.getAttribute(\"id\");\n document.querySelector(\".spell-page\").style.display = \"none\";\n document.querySelector(\".task-page\").style.display = \"block\";\n this.task = new _task__WEBPACK_IMPORTED_MODULE_0__[\"default\"]();\n this.task.generate();\n }", "function open_answers(page_template) {\n\t\tanswer_window = window.open(page_template, \"Antworten\", \"width=800,height=600,scrollbars=yes\");\n\t\tanswer_window.focus();\n\t}", "showWindow() {\n this.window.show();\n this.window.webContents.send('open-dictionary');\n }", "function OpenLattesWindow ()\n {\n \tif ( text == \"\" ) return;\n\n var left = screen.availWidth - 200;\n\n \tif ( wLattes && !wLattes.closed )\n \t{\n \t\twLattes.focus();\n \t\treturn;\n \t}\n \n wLattes = OpenWindow ( \"_Lattes\", 0, left, 200, 200, \"\" );\n \twLattes.document.open ();\n \twLattes.document.write ( text );\n \twLattes.document.close (); \n }", "function displaySpellbook() {\r\n\t\t// Hide other menus\r\n\t\taddClass($('#main_menu #shortcuts'), 'hide');\r\n\t\taddClass($('#main_menu #story'), 'hide');\r\n\t\taddClass($('#main_menu #stats'), 'hide');\r\n\t\taddClass($('#main_menu #settings'), 'hide');\r\n\r\n\t\t// Hide inside menu and show the main spellbook menu\r\n\t\taddClass($('#main_menu #spellbook #custom'), 'hide');\r\n\t\tremoveClass($('#main_menu #spellbook #spells'), 'hide');\t\t\r\n\r\n\t\tfor (x in game.mSpell.spells) {\r\n\t\t\tif (!isNaN(x)) {\r\n\t\t\t\tvar spell = game.mSpell.spells[x];\r\n\t\t\t\tvar img = '<img id=\"spell_'+x+'\" src=\"img/icon/spells/512x512/'+SpellConf.previewIcons[spell.icon]+'\"/>';\r\n\t\t\t\tvar div = $('#main_menu #spellbook #spells div#spell_'+x);\r\n\t\t\t\tdiv.innerHTML = img;\r\n\t\t\t\tdiv.setAttribute('data-hint', game.mSpell.spells[x].name);\r\n\t\t\t\taddClass(div, 'hint--top');\r\n\t\t\t\taddClass(div, 'hint--error');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Show spellbook screen\r\n\t\tremoveClass($('#main_menu #spellbook'), 'hide');\r\n\t}", "function OpenDialog(url, name, type)\n{\n\tWindowDef_1 = \"height=530, width= 530px, top=50, left=0\";\n\tWindowDef_2 = \"height=580, width= 850px, top=0, left=0\";\n\tWindowDef_3 = \"height=450, width= 300px, top=50, left=540\";\n\tWindowDef_4 = \"height=450, width= 550px, top=50, left=200\";\n\tWindowDef_5 = \"height=600, width= 800px, top=0, left=100\";\t\t\n\tvar WindowDef = eval(\"WindowDef_\" + type);\n\tvar attribs = \"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars,resizable,\" + WindowDef;\n\tvar DialogWindow = window.open(url,name,attribs);\n\treturn DialogWindow;\n}", "function openDisplayWindow() {\r\n var windowObjectReference;\r\n var strWindowFeatures = \"menubar=no,location=no,resizable=no, scrollbars=no, status=yes, width= 1920, height= 1080\";\r\n\r\n //Set Volume and play audio\r\n //This pauses the music in the login screen\r\n\r\n mySound.pause();\r\n\r\n // mySound.setVolume(0.5);\r\n // mySound.loop();\r\n\r\n //Opens new Window\r\n windowObjectReference = window.open(\"havehope.html\", \"Display for AllMyFriends Display\", strWindowFeatures);\r\n\r\n}", "function Window_ModTypeCommand() {\r\n this.initialize.apply(this, arguments);\r\n}", "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 launchWinWithOptions(name, url, options) {\r\n\r\n if (! windowExists(name)) {\r\n var winVar = window.open(url, name, options);\r\n windows[windows.length] = winVar;\r\n return winVar;\r\n }\r\n else{\r\n var theWin = getWindow(name);\r\n theWin.focus();\r\n }\r\n}", "open() {\n this.__revertContents = document.createElement(\"div\");\n this.__revertContents.appendChild(this.__selection.getRangeContents());\n this.__selectionContents = this.__selection.wrapOrGetTag(this.tag);\n this.__selection.addHighlight();\n this.updatePrompt();\n //make sure there is a unique id so that the prompt popover appears near the selection\n if (!this.__selectionContents.getAttribute(\"id\"))\n this.__selectionContents.setAttribute(\"id\", \"prompt\" + Date.now());\n this.__prompt.setTarget(this);\n this.dispatchEvent(new CustomEvent(\"select\", { detail: this }));\n }", "function openFlashWin(winFile,winName,myWidth,myHeight) {\r\n\tmyPopup = window.open(winFile,winName,'status=no,toolbar=no,scrollbars=no,width=' + myWidth + ',height=' + myHeight);\r\n}", "function ShowSurveyPopup(url, height, width)\n{\n\tnewWin=null;\n\tvar h = height;\n\tvar w = width;\n\tmyleft=(screen.width)?(screen.width-w)/2:100;\n\tmytop=(screen.height)?(screen.height-h)/2:100;\n\tsettings='width=' + w + ',height=' + h + ',top=' + mytop + ',left=' + myleft + ',scrollbars=1,toolbar=0,location=0,directories=0,status=1,menubar=0,resizable=1';\n\tnewWin=window.open(url,null,settings);\n\tif (newWin!=null)\n newWin.focus();\n}", "function onOpen(e) {\n DocumentApp.getUi().createAddonMenu()\n .addItem('Crypt It', 'doCrypt')\n .addItem('DeCrypt It', 'doDecrypt')\n .addToUi();\n}", "function open() {\n\t\t\t\tif ( !visible ) {\n\t\t\t\t\t// Call input method if cached value is stale\n\t\t\t\t\tif (\n\t\t\t\t\t\t$input.val() !== '' &&\n\t\t\t\t\t\t$input.val() !== cachedInput\n\t\t\t\t\t) {\n\t\t\t\t\t\tcachedInput = $input.val();\n\t\t\t\t\t\tonInput();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Show if there are suggestions.\n\t\t\t\t\t\tif ( $multiSuggest.children().length > 0 ) {\n\t\t\t\t\t\t\tvisible = true;\n\t\t\t\t\t\t\t$multiSuggest.show();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "function showMoodSelectionConfirmation()\n{\n // change the color of the checkmark to reflect the mood of the user\n colorCheckMark();\n // show the mood confirmation window\n switchScreens(activeWindow, document.getElementById(\"mood-logged-screen\"));\n}", "function doOpenTool(ev, title, url, width, height)\n{\n // ev.button appears to be undefined in trunk builds...\n // it comes out as 65535\n if(ev.ctrlKey) { // new tab\n doOpenTool_newTab(url);\n }\n else if(ev.shiftKey) { // open in current window\n getBrowser().loadURI(url);\n }\n else { // new window (default)\n doOpenTool_newWin(url, width, height);\n }\n}", "function fingerChoice() {\n choiceDialog(0, 0, ghostDialog, 14000);\n}", "function synthType(type) {\n selectedSound = type;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by the C++ internals when path validation is completed. This is a purely informational event that is emitted only when there is a listener present for the pathValidation event.
function onSessionPathValidation(res, local, remote) { const session = this[owner_symbol]; if (session) { process.nextTick( emit.bind( session, 'pathValidation', res === NGTCP2_PATH_VALIDATION_RESULT_FAILURE ? 'failure' : 'success', local, remote)); } }
[ "function OnPathComplete (newPath : Path) // the newly determined path is sent over as \"newPath\" type of Path\n{\n\tif (!newPath.error)//if the newPath does not have any errors\n\t{\n\t\tpath = newPath; //set the path to this new one\n\t\tcurrentWaypoint = 0;//now that we have a new path. make sure to start at the first waypoint\n\t\t\n\t}\n}", "function completedProcess(self) {\n\t//console.log('completedProcess called');\n\tself.emit('completedProcess', self.file, self.fileObjectList.getAll());\n\tconsole.log(\"FeedFileProcessor : Finished processing \", self.file);\n\t//console.log(\"Contents are \", self.fileObjectList.getAll());\n\n}", "function checkComplete() {\r\n if (sectionLoaderState.filesLoaded >= sectionLoaderState.filesToLoad.length) complete();\r\n}", "function dispatchingFilesFinished() {\n // NOTE: ignoring possible error because processOneFile never passes error to async\n if (this.errors.length > 0) {\n callback(this.errors);\n } else {\n callback(null, this.stats);\n }\n }", "function depthOperationsComplete() {\n operationsComplete();\n self.saveWebLinksAtDepth(depth + 1, operations, successfulOperations, failedOperations, operationsComplete);\n }", "function ValidationContext() {\n\t/**\n\t * The name of the constraint being validated, it may be useful for debugging and for the validator.\n\t * @member {string}\n\t */\n\tthis.constraintName = null;\n\t/**\n\t * A map from the model path to the results of validation for that path.\n\t * It contains all paths that have been validated.\n\t * <p>\n\t * The <code>_validity</code> properties map the constraint key to the actual {@linkcode ValidationResult}.\n\t * </p>\n\t *\n\t * @example\n\t * // for a model such as the following:\n\t * model = {\n\t * \tname: \"Nikos\",\n\t * \taddress: {\n\t * \t\tstreet: \"Alpha\",\n\t * \t\tnumber: 3\n\t * \t},\n\t * \tpets: [\n\t * \t\t{\n\t * \t\t\tname: 'Sylvester'\n\t * \t\t}\n\t * \t]\n\t * };\n\t * \n\t * // the result would look like:\n\t * result = {\n\t * \t_thisValid: true,\n\t * \t_childrenValid: false,\n\t * \t_validity: {\n\t * \t\t...\n\t * \t},\n\t * \t_children: {\n\t * \t\tname: {\n\t * \t\t\t_thisValid: true,\n\t * \t\t\t// NOTE: no _childrenValid member\n\t * \t\t\t_validity: {\n\t * \t\t\t\tlength: {...}, // a specific validator, e.g. for the string length\n\t * \t\t\t\tnospaces: {...} // another spacific validator, e.g. \"contains no spaces\"\n\t * \t\t\t},\n\t * \t\t\t_children: null\n\t * \t\t},\n\t * \t\taddress: {\n\t * \t\t\t_thisValid: true,\n\t * \t\t\t_childrenValid: false,\n\t * \t\t\t_validity: {\n\t * \t\t\t\t...\n\t * \t\t\t},\n\t * \t\t\t_children: { // NOTE: children is object\n\t * \t\t\t\tstreet: {\n\t * \t\t\t\t\t_thisValid: true,\n\t * \t\t\t\t\t_validity: {\n\t * \t\t\t\t\t\t...\n\t * \t\t\t\t\t},\n\t * \t\t\t\t\t_children: null\n\t * \t\t\t\t},\n\t * \t\t\t\tnumber: {\n\t * \t\t\t\t\t_thisValid: true,\n\t * \t\t\t\t\t_validity: {\n\t * \t\t\t\t\t\t...\n\t * \t\t\t\t\t},\n\t * \t\t\t\t\t_children: null\n\t * \t\t\t\t}\n\t * \t\t\t}\n\t * \t\t},\n\t * \t\tpets: {\n\t * \t\t\t_validity: {\n\t * \t\t\t\t...\n\t * \t\t\t},\n\t * \t\t\t_children: [ // NOTE: children is array\n\t * \t\t\t\t{ // index/key is 0 implicitly\n\t * \t\t\t\t\tname: {\n\t * \t\t\t\t\t\t...\n\t * \t\t\t\t\t}\n\t * \t\t\t\t}\n\t * \t\t\t]\n\t * \t\t}\n\t * \t}\n\t * };\n\t *\n\t * @member {Object}\n\t */\n\tthis.result = { _thisValid: true, _validity: null, _children: null };\n\t/**\n\t * The message related to the current result, usually a string but may be anything that makes sense to the underlying message display mechanism.\n\t * @member {string|any}\n\t */\n\tthis.message = null;\n\t/**\n\t * Message parameters related to the current result.\n\t * @member {object}\n\t */\n\tthis.messageParams = null;\n\t/**\n\t * Keep the path to the current property, so as to be able to return to the parent when <code>popPath()</code> is called.\n\t * @member {Object[]}\n\t */\n\tthis.path = [this.result];\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 teamDataSavedListener () {\n debug('match data saved, resolving state promise')\n module.exports.internal.teamDataSavedPromiseResolver()\n}", "startChanged () {\r\n this.$nextTick(() => {\r\n if (this.model.end) {\r\n this.$validator.validate('end')\r\n }\r\n })\r\n this.errors.remove('start')\r\n }", "function completed () {\n return this.resolved.length === this.chain.__expectations__.length;\n}", "function operationComplete() {\n if ((successfulOperations.length + failedOperations.length) >= totalOperations) {\n saveComplete();\n }\n }", "function validate(svg, saveto, validation) {\n expect(svg).to.not.be.undefined;\n expect(svg).to.not.be.null;\n expect(svg.length).to.be.above(100);\n\n // ensure we can parse the generated SVG and invoke callback with xpath\n var dom = require('xmldom').DOMParser;\n var selector = require('xpath');\n var xpath = selector.useNamespaces({'svg': 'http://www.w3.org/2000/svg'});\n\n var doc = new dom().parseFromString(svg);\n\n // save the snapshot for manual review if we have a 'output' dir\n if (saveto && fs.existsSync(output)) {\n fs.writeFileSync(output + saveto + '.svg', svg);\n }\n\n // make sure the root is an SVG document\n expect(xpath('/svg:svg', doc).length).to.equal(1);\n\n if (dl.isString(validation)) {\n // invoke the custom validation as an xpath if it is a string\n expect(xpath(validation, doc).length).to.equal(1);\n } else if (dl.isFunction(validation)) {\n // invoke the custom validation function\n validation(doc, xpath);\n }\n }", "function operationComplete() {\n completedOperationsCount++;\n if (completedOperationsCount >= depthOperationsCount) {\n depthOperationsComplete();\n }\n }", "function checkPath(){\n if(gamePath == null || path.length < 1) return;\n\n const index = path.length -1;\n if (index < gamePath.length){\n if(path[index].y !== gamePath[index].y || path[index].x !== gamePath[index].x){\n clearInterval(id)\n surrounded();\n transitionAnalysis();\n }\n }else{\n console.log(\"Congrats, you've made it to the end!\");\n clearInterval(id);\n transitionAnalysis();\n ctx.font = \"30px arial\"\n ctx.fillText(\"Congrats, you've made it to the end!\", 2 * cellWidth, 15 * cellWidth);\n }\n}", "function onFragmentPathChange() {\n // if the fragment was reset (i.e. the fragment path was deleted)\n if (!fragmentPath.value) {\n var canKeepConfig = elementsController.testStateForUpdate();\n if (canKeepConfig) {\n // There was no current configuration. We just need to disable fields.\n currentFragmentPath = fragmentPath.value;\n elementsController.disableFields();\n return;\n }\n // There was some current configuration. Show a confirmation dialog\n confirmFragmentChange(null, null, elementsController.disableFields, elementsController);\n // don't do anything else\n return;\n }\n\n elementsController.testGetHTML(editDialog.querySelector(SELECTOR_DISPLAY_MODE_CHECKED).value, function() {\n // check if we can keep the current configuration, in which case no confirmation dialog is necessary\n var canKeepConfig = elementsController.testStateForUpdate();\n if (canKeepConfig) {\n if (!currentFragmentPath) {\n elementsController.enableFields();\n }\n currentFragmentPath = fragmentPath.value;\n // its okay to save fetched state\n elementsController.saveFetchedState();\n return;\n }\n // else show a confirmation dialog\n confirmFragmentChange(elementsController.discardFetchedState, elementsController,\n elementsController.saveFetchedState, elementsController);\n });\n\n }", "function xpathListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}", "function validatePath(path) {\n if (path === \"\") {\n return validationError($('#file-chooser').parent().parent().children(\".error\"), i18n.EMPTY_PATH)\n } else if (!path.includes(\".specifz\")) {\n return validationError($('#file-chooser').parent().parent().children(\".error\"), i18n.NO_SPECIFZ_FILE)\n } else {\n return hideError($('#file-chooser').parent().parent().children(\".error\"))\n }\n }", "handleVPathChanged() {\n this.vPathState = this._inputDataStates.vpath.state;\n this.setProperVerticalArmedStates();\n\n if (this.vPathState === VPathState.ACTIVE) {\n this.currentVerticalActiveState = VerticalNavModeState.PATH;\n if (SimVar.GetSimVarValue(\"AUTOPILOT VS SLOT INDEX\", \"number\") != 2) {\n SimVar.SetSimVarValue(\"K:VS_SLOT_INDEX_SET\", \"number\", 2);\n }\n if (SimVar.GetSimVarValue(\"AUTOPILOT ALTITUDE SLOT INDEX\", \"number\") != 2) {\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 2);\n }\n if (!SimVar.GetSimVarValue(\"AUTOPILOT VERTICAL HOLD\", \"Boolean\")) {\n SimVar.SetSimVarValue(\"K:AP_PANEL_VS_HOLD\", \"number\", 1);\n }\n }\n\n if (this.currentLateralActiveState === LateralNavModeState.APPR) {\n switch (this.vPathState) {\n case VPathState.NONE:\n case VPathState.ARMED:\n case VPathState.UNABLEARMED:\n this.currentVerticalArmedStates = [VerticalNavModeState.GP];\n break;\n case VPathState.ACTIVE:\n this.currentVerticalArmedStates = [];\n this.currentVerticalActiveState = VerticalNavModeState.GP;\n break;\n }\n }\n }", "onScanCompleted_() {\n if (this.scanCancelled_) {\n return;\n }\n\n this.processNewEntriesQueue_.run(callback => {\n // Call callback first, so isScanning() returns false in the event\n // handlers.\n callback();\n dispatchSimpleEvent(this, 'scan-completed');\n });\n }", "function markGoalComplete() {\n\t\tprops.markGoalComplete(props.goalId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a flattened list of changed fields in `this`
function getChangedFields (instance) { var changeSet = getChangeSet(instance) || []; var props = changeSet.reduce(function (accum, change) { // Distill the ultimate path(s) from path + rhs if rhs is an object, or just path if not. // This clause handles array changes because typeof rhs is `undefined` if (typeof change.rhs !== 'object' || Object.keys(change.rhs).length === 0) { accum[change.path.join('.')] = 1; } // For object changes, we have to look at both right-hand and left-hand sides to get the changed paths else { Object.keys(flatten(change.rhs)).forEach(function (suffix) { accum[change.path.join('.') + '.' + suffix] = 1; }); if (typeof change.lhs === 'object' && Object.keys(change.lhs).length) { Object.keys(flatten(change.lhs)).forEach(function (suffix) { accum[change.path.join('.') + '.' + suffix] = 1; }); } } return accum; }, {}); // Let's filter any keys that are nested in another present key. // this happens specifically when items are removed from an array, // for example you might otherwise get something like `['foo.2', 'foo.3', foo]` // This transformation returns just `['foo']` in such a case. // Edits that don't shorten the array will still return indexed paths. props = Object.keys(props); return props.filter(function (prop, i) { return !utils.isNestedInSome(prop, props.filter(function (myprop) { return prop !== myprop; })); }); }
[ "track() {\n const snapShot = () => {\n return JSON.stringify(this.fields.reduce((obj, key) => {\n obj[key] = this.ctx[key];\n return obj;\n }, {}))\n }\n\n const changeListener = () => {\n this.hasFieldChanges = this.oldState !== snapShot();\n }\n\n this.oldState = snapShot();\n changeListener();\n observe(this.ctx, changeListener);\n }", "get fields() {\n return SPCollection(this, \"fields\");\n }", "getChangeFlags() {\n var _this$internalState2;\n\n return (_this$internalState2 = this.internalState) === null || _this$internalState2 === void 0 ? void 0 : _this$internalState2.changeFlags;\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 }", "get fields() {\n return tag.configure(SharePointQueryableCollection(this, \"fields\"), \"ct.fields\");\n }", "get listItemAllFields() {\n return SPInstance(this, \"listItemAllFields\");\n }", "function GetFormDirtyFields(executionContext) {\n try {\n //Get the form context\n var formContext = executionContext.getFormContext();\n var attributes = formContext.data.entity.attributes.get()\n for (var i in attributes) {\n var attribute = attributes[i];\n if (attribute.getIsDirty()) {\n Xrm.Utility.alertDialog(\"Attribute dirty: \" + attribute.getName());\n }\n }\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}", "getUnreleasedChanges() {\n return this._changes[constants_1.unreleased];\n }", "getTrackedElements() {\n const sourceTrackedKeys = Object.keys(this.getSourceMembers());\n return sourceTrackedKeys.map((key) => this.getTrackedElement(key));\n }", "get fieldValuesForEdit() {\n return SPInstance(this, \"FieldValuesForEdit\");\n }", "get lastCallArgumentValues() {\n return this.lastCallArgs.map(a => a.originalValue);\n }", "get relatedFields() {\n return SPQueryable(this, \"getRelatedFields\");\n }", "snapshot() {\n let changes = get(this, CHANGES);\n let errors = get(this, ERRORS);\n return {\n changes: keys(changes).reduce((newObj, key) => {\n newObj[key] = changes[key].value;\n return newObj;\n }, {}),\n errors: keys(errors).reduce((newObj, key) => {\n let e = errors[key];\n newObj[key] = { value: e.value, validation: e.validation };\n return newObj;\n }, {}),\n };\n }", "static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties.forEach((v, p) => {\n const attr = this._attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this._attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }", "static getVirtualFieldsList(names){\n\t}", "get cleanedData()\n {\n if (!this.isValid())\n {\n throw new Error(this.constructor.name + \" object has no attribute 'cleanedData'\");\n }\n var cleaned = [];\n for (var i = 0, l = this.forms.length; i < l; i++)\n {\n cleaned.push(this.forms[i].cleanedData);\n }\n return cleaned;\n }", "function getFormModifiedState (){\n\t\treturn formModified;\n\t}", "function isDirty(){\n return this.__isDirty__;\n}", "_clearChangeFlags() {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this.internalState.changeFlags = {\n dataChanged: false,\n propsChanged: false,\n updateTriggersChanged: false,\n viewportChanged: false,\n stateChanged: false,\n extensionsChanged: false,\n propsOrDataChanged: false,\n somethingChanged: false\n };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private function that traverses the nonbinary StoryTree Recursively goes through the tree and finds each available action ARGUMENTS: uidPath([int]) the uid array of the actions that have been traversed uid(int) the next uid to traverse to memory(Memory) the memory vector that we're setting up return void
function traverse(uidPath, uid, memory, cls){ counter++; if(counter > 5000){ console.log(uid); } //Get action object var actionObj = tree.actions[uid]; //evaluate each precondition for the action object var trig = false; for(var j = 0; j < actionObj.preconditions.length; j++){ var pre = actionObj.preconditions[j]; //check to see if we get a false value if(!evaluatePrecondition(pre)){ trig = true; break; } } //If something doesn't pass, we return if(trig) return; //Now we can loop through each expression and evaluate them for(var k = 0; k < actionObj.expressions.length; k++){ var exp = actionObj.expressions[k]; //Evaluate the expression and write to the hypothetical memory evaluateExpression(exp, memory); } //We can assume now that we've succesfully passed the preconditions //This means we can add the action to the uid list uidPath.push(uid); //Now we have to see if there's a class for this action //If so, we add it to the list var myClass = ""; if(actionObj.cls != undefined && cls === ""){ myClass = actionObj.cls; } else { myClass = cls; } //If the action is a leaf, push the uidPath on the available paths // and then push a new distance to conversation types on dists if(actionObj.isLeaf()){ uids.push(uidPath); var combineMem = Memory.prototype.combine(myCharacter.memBank.totalMemVec, memory, myCharacter.memBank.timeStep); var normMem = combineMem.normalize(); //Get the dot product var dotproduct = normMem.dot(normalComposedMemory); var dotproduct = Math.round(dotproduct * 1000) / 1000 //Get the dist to the conversation type var dist = Math.abs(that.conversationType - dotproduct); dists.push(dist); classes.push(myClass); return; } //Now we run the traversal algorithm for each child action for(var i = 0; i < actionObj.children.length; i++){ var actionUID = actionObj.children[i]; var action = tree.actions[actionUID]; traverse(uidPath.slice(), actionUID, memory.copy(), myClass); } }
[ "function i2uiManagePadTree(tablename, cellname, column, relatedtablenames, name, recurse, relatedroutine)\r\n{\r\n // allows related table to adjust to new width due to actions in current table\r\n if (recurse == null && relatedtablenames != null)\r\n {\r\n // only do this if not a leaf node\r\n var img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n if (img != null && img.src.indexOf(\"bullet\") == -1)\r\n i2uiShrinkScrollableTable(relatedtablenames);\r\n }\r\n\r\n //i2uitrace(1,\"manage cell=[\"+cellname+\"]\");\r\n\r\n var table;\r\n var savemasterscrolltop;\r\n var saveslavescrolltop;\r\n var loadondemand = false;\r\n\r\n //i2uitrace(1,\"tablename=[\"+tablename+\"]\");\r\n\r\n table = document.getElementById(tablename+\"_data\");\r\n if (table == null)\r\n {\r\n table = document.getElementById(tablename);\r\n }\r\n\r\n //i2uitrace(1,\"table=[\"+table+\"]\");\r\n\r\n if (table != null &&\r\n table.rows != null)\r\n {\r\n var masterscrolleritem = document.getElementById(relatedtablenames+\"_scroller\");\r\n var slavescrolleritem = document.getElementById(tablename+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n savemasterscrolltop = masterscrolleritem.scrollTop;\r\n saveslavescrolltop = slavescrolleritem.scrollTop;\r\n }\r\n\r\n var relatedtable = null;\r\n if (relatedtablenames != null &&\r\n relatedtablenames != 'undefined')\r\n {\r\n relatedtable = document.getElementById(relatedtablenames+\"_data\");\r\n }\r\n\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname));\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname).src);\r\n var img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n if (img.src.indexOf(\"bullet\") != -1)\r\n {\r\n return;\r\n }\r\n\r\n var i2action;\r\n if (img != null && img.src != null)\r\n {\r\n if (img.src.indexOf(\"_loadondemand\") != -1)\r\n {\r\n loadondemand = true;\r\n }\r\n else\r\n if (img.src.indexOf(\"minus\") == -1)\r\n {\r\n if (recurse == null)\r\n {\r\n img.src = i2uiImageDirectory+\"/minus_norgie.gif\";\r\n i2action = \"\";\r\n }\r\n else\r\n {\r\n i2action = \"none\";\r\n }\r\n //i2uitrace(1,\"now expand\");\r\n }\r\n else\r\n if (img.src.indexOf(\"plus\") == -1)\r\n {\r\n if (recurse == null)\r\n {\r\n img.src = i2uiImageDirectory+\"/plus_norgie.gif\";\r\n i2action = \"none\";\r\n }\r\n else\r\n {\r\n i2action = \"\";\r\n }\r\n //i2uitrace(1,\"now collapse\");\r\n }\r\n }\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname).src);\r\n\r\n // if collapsing, must collapse all children\r\n // if expanding, expand only immediate children\r\n\r\n var depth1 = cellname.split(\"_\").length;\r\n //i2uitrace(1,\"depth1=\"+depth1);\r\n var len = table.rows.length;\r\n //i2uitrace(1,\"len=\"+len);\r\n for (var i=1; i<len; i++)\r\n {\r\n //i2uitrace(1,\"id=\"+table.rows[i].cells[column].id);\r\n //i2uitrace(1,\"substr=\"+table.rows[i].cells[column].id.substr(0,cellname.length+10));\r\n //i2uitrace(1,\"test for [TREECELL_\"+cellname+\"_]\");\r\n\r\n if (table.rows[i].cells[column].id.substr(0,cellname.length+10) == \"TREECELL_\"+cellname+\"_\")\r\n {\r\n //i2uitrace(1,\"manage row \"+i);\r\n if (i2action == \"none\")\r\n {\r\n table.rows[i].style.display = i2action;\r\n if (relatedtable != null)\r\n {\r\n relatedtable.rows[i].style.display = i2action;\r\n }\r\n }\r\n else\r\n {\r\n var depth2 = table.rows[i].cells[column].id.split(\"_\").length;\r\n //i2uitrace(1,\"depth2=\"+depth2);\r\n if (depth2 == depth1 + 2)\r\n {\r\n table.rows[i].style.display = i2action;\r\n if (relatedtable != null)\r\n {\r\n relatedtable.rows[i].style.display = i2action;\r\n }\r\n\r\n var newcell = table.rows[i].cells[column].id.substr(9);\r\n //i2uitrace(1,newcell);\r\n i2uiManagePadTree(tablename,newcell,column,relatedtablenames,name,1);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // finally realign tables\r\n if (recurse == null)\r\n {\r\n if (relatedtablenames != null ||\r\n document.getElementById(tablename+\"_data\") != null)\r\n {\r\n // must scroll to top. can't use previous scroll position\r\n // since table height itself could have changed. as a result,\r\n // rows become misaligned.\r\n var masterscrolleritem = document.getElementById(relatedtablenames+\"_scroller\");\r\n var slavescrolleritem = document.getElementById(tablename+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n //i2uitrace(1,\"savedmasterscrolltop=\"+savemasterscrolltop);\r\n //i2uitrace(1,\"savedslavescrolltop=\"+saveslavescrolltop);\r\n masterscrolleritem.scrollTop = 0;\r\n slavescrolleritem.scrollTop = 0;\r\n //masterscrolleritem.scrollTop = savemasterscrolltop;\r\n //slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n }\r\n }\r\n\r\n // call a related routine to handle any follow-up actions\r\n // intended for internal use. external use should use the\r\n // callback mechanism\r\n //i2uitrace(0,\"managetreetable related=[\"+relatedroutine+\"]\");\r\n if (relatedroutine != null)\r\n {\r\n // must invoke the routine 'in the future' to allow browser\r\n // to settle down, that is, finish rendering the effects of\r\n // the tree element changing state\r\n setTimeout(relatedroutine,100);\r\n }\r\n\r\n // call a routine of the invoker's choosing to handle any realignment\r\n if (i2uiManageTreeTableUserFunction != null)\r\n {\r\n if (name == null)\r\n {\r\n name = 'undefined';\r\n }\r\n if (relatedtablenames != null)\r\n {\r\n eval(i2uiManageTreeTableUserFunction+\"('\"+tablename+\"','\"+relatedtablenames+\"','\"+i2action+\"',\"+savemasterscrolltop+\",'\"+name+\"',\"+loadondemand+\")\");\r\n }\r\n else\r\n {\r\n eval(i2uiManageTreeTableUserFunction+\"('\"+tablename+\"','undefined','\"+i2action+\"',null,'\"+name+\"',\"+loadondemand+\")\");\r\n }\r\n }\r\n }\r\n }\r\n}", "function i2uiManageTreeTable(tablename, cellname, column, relatedtablenames, name, recurse, relatedroutine, startat)\r\n{\r\n // allows related table to adjust to new width due to actions in current table\r\n if (recurse == null && relatedtablenames != null)\r\n {\r\n // only do this if not a leaf node\r\n var img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n if (img != null && img.src.indexOf(\"bullet\") == -1)\r\n i2uiShrinkScrollableTable(relatedtablenames);\r\n }\r\n\r\n //i2uitrace(1,\"manage cell=[\"+cellname+\"]\");\r\n\r\n var table;\r\n var savemasterscrolltop;\r\n var saveslavescrolltop;\r\n var loadondemand = false;\r\n\r\n //i2uitrace(1,\"tablename=[\"+tablename+\"]\");\r\n\r\n table = document.getElementById(tablename+\"_data\");\r\n if (table == null)\r\n {\r\n table = document.getElementById(tablename);\r\n }\r\n\r\n //i2uitrace(1,\"table=[\"+table+\"]\");\r\n\r\n if (table != null &&\r\n table.rows != null)\r\n {\r\n var masterscrolleritem = document.getElementById(relatedtablenames+\"_scroller\");\r\n var slavescrolleritem = document.getElementById(tablename+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n savemasterscrolltop = masterscrolleritem.scrollTop;\r\n saveslavescrolltop = slavescrolleritem.scrollTop;\r\n }\r\n\r\n var relatedtable = null;\r\n if (relatedtablenames != null &&\r\n relatedtablenames != 'undefined')\r\n {\r\n relatedtable = document.getElementById(relatedtablenames+\"_data\");\r\n }\r\n\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname));\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname).src);\r\n var img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n if (img != null && img.src != null && img.src.indexOf(\"bullet\") != -1)\r\n {\r\n return;\r\n }\r\n\r\n var i2action;\r\n var action2;\r\n if (img != null && img.src != null)\r\n {\r\n if (img.src.indexOf(\"_loadondemand\") != -1)\r\n {\r\n loadondemand = true;\r\n action2 = \"none\";\r\n }\r\n else\r\n if (img.src.indexOf(\"minus\") == -1)\r\n {\r\n action2 = \"expand\";\r\n if (recurse == null)\r\n {\r\n img.src = i2uiImageDirectory+\"/minus_norgie.gif\";\r\n i2action = \"\";\r\n }\r\n else\r\n {\r\n i2action = \"none\";\r\n }\r\n //i2uitrace(1,\"now expand\");\r\n }\r\n else\r\n if (img.src.indexOf(\"plus\") == -1)\r\n {\r\n action2 = \"collapse\";\r\n if (recurse == null)\r\n {\r\n img.src = i2uiImageDirectory+\"/plus_norgie.gif\";\r\n i2action = \"none\";\r\n }\r\n else\r\n {\r\n i2action = \"\";\r\n }\r\n //i2uitrace(1,\"now collapse\");\r\n }\r\n }\r\n //i2uitrace(1,document.getElementById(\"TREECELLIMAGE_\"+cellname).src);\r\n\r\n // if collapsing, must collapse all children\r\n // if expanding, expand only immediate children\r\n\r\n var depth1 = Math.floor(cellname);\r\n //i2uitrace(1,\"depth1=\"+depth1);\r\n var len = table.rows.length;\r\n //i2uitrace(1,\"len=\"+len);\r\n if (startat == null)\r\n startat = 0;\r\n\r\n //i2uitrace(1,\"**** startat=\"+startat+\" depth1=\"+depth1+\" cellname=\"+cellname);\r\n for (var i=startat; i<len; i++)\r\n {\r\n //i2uitrace(1,\"id=\"+table.rows[i].cells[column].id);\r\n //i2uitrace(1,\"test for [TREECELL_\"+cellname+\"]\");\r\n\r\n // locate desired row in table\r\n //if (table.rows[i].cells[column].getAttribute('id') == \"TREECELL_\"+cellname)\r\n\t if (table.rows[i].getElementsByTagName('td')[0].getAttribute('id') == 'TREECELL_' + cellname)\r\n {\r\n //i2uitrace(1,\"located key at row \"+i);\r\n\r\n // now process rest of table with respect to located\r\n for (var j=i+1; j<len; j++)\r\n {\r\n var newcell = table.rows[j].getElementsByTagName('td')[0].getAttribute('id').substr(9);\r\n var depth2 = Math.floor(newcell);\r\n //i2uitrace(1,\"row=\"+j+\" id=\"+table.rows[j].cells[column].id+\" newcell=\"+newcell+\" depth2=\"+depth2+\" depth1=\"+depth1+\" action2=\"+action2);\r\n if (((depth2 == depth1 + 10 || depth2 == depth1 + 15) && action2 == \"expand\") ||\r\n (depth2 > depth1 + 5 && action2 == \"collapse\"))\r\n {\r\n //i2uitrace(1,\"perform i2action [\"+i2action+\"] on row \"+j);\r\n table.rows[j].style.display = i2action;\r\n if (relatedtable != null)\r\n relatedtable.rows[j].style.display = i2action;\r\n\r\n // if expanding and not already recursing, then recurse\r\n if (depth2 == depth1 + 10 && action2 == \"expand\" && recurse == null)\r\n {\r\n //i2uitrace(0,\"recurse with \"+newcell+\" from row \"+j);\r\n i2uiManageTreeTable(tablename,newcell,column,relatedtablenames,name,1,null,j);\r\n }\r\n }\r\n if (depth2 <= depth1)\r\n {\r\n //i2uitrace(1,\"*** done with children\");\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // finally realign tables\r\n if (recurse == null)\r\n {\r\n if (relatedtablenames != null ||\r\n document.getElementById(tablename+\"_data\") != null)\r\n {\r\n // must scroll to top. can't use previous scroll position\r\n // since table height itself could have changed. as a result,\r\n // rows become misaligned.\r\n var masterscrolleritem = document.getElementById(relatedtablenames+\"_scroller\");\r\n var slavescrolleritem = document.getElementById(tablename+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n //i2uitrace(1,\"savedmasterscrolltop=\"+savemasterscrolltop);\r\n //i2uitrace(1,\"savedslavescrolltop=\"+saveslavescrolltop);\r\n masterscrolleritem.scrollTop = 0;\r\n slavescrolleritem.scrollTop = 0;\r\n //masterscrolleritem.scrollTop = savemasterscrolltop;\r\n //slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n }\r\n }\r\n\r\n // call a related routine to handle any follow-up actions\r\n // intended for internal use. external use should use the\r\n // callback mechanism\r\n //i2uitrace(0,\"managetreetable related=[\"+relatedroutine+\"]\");\r\n if (relatedroutine != null)\r\n {\r\n // must invoke the routine 'in the future' to allow browser\r\n // to settle down, that is, finish rendering the effects of\r\n // the tree element changing state\r\n setTimeout(relatedroutine,100);\r\n }\r\n\r\n // call a routine of the invoker's choosing to handle any realignment\r\n if (i2uiManageTreeTableUserFunction != null)\r\n {\r\n if (name == null)\r\n {\r\n name = 'undefined';\r\n }\r\n if (relatedtablenames != null)\r\n {\r\n eval(i2uiManageTreeTableUserFunction+\"('\"+tablename+\"','\"+relatedtablenames+\"','\"+i2action+\"',\"+savemasterscrolltop+\",'\"+name+\"',\"+loadondemand+\")\");\r\n }\r\n else\r\n {\r\n eval(i2uiManageTreeTableUserFunction+\"('\"+tablename+\"','undefined','\"+i2action+\"',null,'\"+name+\"',\"+loadondemand+\")\");\r\n }\r\n }\r\n }\r\n }\r\n}", "function DFSTraverse(tree, commands){\n let queue = [tree], node = {}, selectedNodes = [];\n\n while (queue.length){\n node = queue.shift();\n if (!node.cmdDepth) node.cmdDepth = 0;\n let { cmdDepth } = node,\n cmd = commands[Math.min(commands.length - 1, cmdDepth)]\n\n if (isValidMatch(cmd, node)) {\n cmdDepth++;\n if (cmdDepth >= commands.length) selectedNodes = selectedNodes.concat([node])\n }\n\n if (node.contentView) queue = queue.concat(node.contentView.subviews.map(node => Object.assign({}, node, {cmdDepth})))\n if (node.subviews) queue = queue.concat(node.subviews.map(node => Object.assign({}, node, {cmdDepth})))\n }\n return selectedNodes\n}", "function SplayTree() { }", "function i2uiCollapsePadTree(tablename, depth)\r\n{\r\n var column = 0;\r\n\r\n //i2uitrace(1,\"collapsepadtree depth=\"+depth);\r\n\r\n var table;\r\n var savemasterscrolltop;\r\n var saveslavescrolltop;\r\n\r\n //i2uitrace(1,\"tablename=[\"+tablename+\"]\");\r\n\r\n table = document.getElementById(tablename+\"_data\");\r\n if (table == null)\r\n {\r\n table = document.getElementById(tablename);\r\n }\r\n\r\n //i2uitrace(1,\"table=[\"+table+\"]\");\r\n\r\n if (table != null &&\r\n table.rows != null)\r\n {\r\n var len = table.rows.length;\r\n var rowdepth;\r\n var img;\r\n var cellname;\r\n var childkey;\r\n var childnode;\r\n //i2uitrace(1,\"#rows=\"+len);\r\n for (var i=0; i<len; i++)\r\n {\r\n rowdepth = table.rows[i].cells[column].id.split(\"_\").length - 2;\r\n //i2uitrace(1,\"rowdepth=\"+rowdepth);\r\n if (rowdepth <0)\r\n continue;\r\n\r\n cellname = table.rows[i].cells[column].id.substr(9);\r\n //i2uitrace(1,\"id=\"+table.rows[i].cells[column].id+\" cellname=\"+cellname);\r\n\r\n childkey = \"TREECELLIMAGE_\"+tablename+\"_\"+cellname + \"_1\";\r\n childnode = document.getElementById(childkey);\r\n //i2uitrace(1,\"childnode=\"+childnode+\" key=\"+childkey);\r\n\r\n img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n\r\n if (rowdepth == depth)\r\n {\r\n //i2uitrace(1,\"COLLAPSE ME id=\"+table.rows[i].cells[column].id);\r\n if (img != null)\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n else\r\n {\r\n img.src = i2uiImageDirectory+\"/plus_norgie.gif\";\r\n }\r\n }\r\n table.rows[i].style.display = \"\";\r\n }\r\n else\r\n {\r\n if (rowdepth > depth)\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img != null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n }\r\n //i2uitrace(1,\"HIDE ME id=\"+table.rows[i].cells[column].id);\r\n table.rows[i].style.display = \"none\";\r\n }\r\n else\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img != null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n }\r\n else\r\n {\r\n if (img != null)\r\n {\r\n img.src = i2uiImageDirectory+\"/minus_norgie.gif\";\r\n }\r\n }\r\n //i2uitrace(1,\"EXPAND ME id=\"+table.rows[i].cells[column].id);\r\n table.rows[i].style.display = \"\";\r\n }\r\n }\r\n }\r\n }\r\n}", "function processAllActions() {\r\n\t\r\n\tshowWriting();\r\n\t\r\n\tvar time = 500;\r\n\tvar na = botAction.next;\r\n\t\t\r\n\tvar fn = function(v,end){\r\n\t\treturn function(){\r\n\t\t\thideWriting();\r\n\t\t\tif(doAction(v)){\r\n\t\t\t\tshowWriting();\r\n\t\t\t} else {\r\n\t\t\t\tinputState(true);\r\n\t\t\t\tbotAction.last = botAction.next;\r\n\t\t\t\tbotAction.next = [];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar i = 0;\r\n\tfor (i=0;i<na.length;i++){\r\n\t\t\r\n\t\tvar b = (i == na.length-1)\r\n\t\t\r\n\t\ttime += na[i].text ? na[i].text.length*10 : 200;\r\n\t\tif (na[i].delay)\r\n\t\t\ttime += na[i].delay;\r\n\t\t\r\n\t\tsetTimeout(fn(i,b),time);\r\n\t}\r\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}", "visitAudit_direct_path(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "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 }", "autocomplete(start){\n // code here\n // We need to get to the end of our starting position ex: if we're passed \"CA\" we need to get down to the A node and search from there\n let runner = this.root;\n let word = \"\";\n let wordsArray = [];\n // For loop to check if the start is in the trie\n for(let letter = 0; letter < start.length; letter++){\n let idx = start[letter].toLowerCase().charCodeAt(0) - 97;\n if(runner.children[idx]){\n // if there is something there, head down\n word+=runner.children[idx].val;\n runner = runner.children[idx];\n console.log(`The word is currently ${word}`);\n } else {\n // If nothing is there, return the blank array because we never found anything\n console.log(\"We don't seem to have that route available, no words to show!\");\n return wordsArray;\n }\n }\n // If the place we stopped is a word, add it to the array\n if(runner.isWord){\n wordsArray.push(word);\n }\n // Call our recursive function\n for(let i = 0; i < runner.children.length; i++){\n this.autoHelper(runner.children[i], word, wordsArray);\n }\n return wordsArray;\n}", "function treeCallback (data) {\n\tconsole.log('>Motion at Tree');\n\tconsole.log(' event: ', data);\n\n\t//I wanted this to happen regardless so I commented out the motionActive \n\t//if (motionActive) {\n\t\tdoit('tree');\n\n\t\tif (toggleProp) {\n\t\t\tsetTimeout(doit,10000,'lamp');\n\t\t} else {\n\t\t\tsetTimeout(doit,10000,'ball');\n\t\t}\n\t\ttoggleProp = !toggleProp;\n\t\t//console.log(\"Event: \" + data);\n\t\t//motionWakeReset();\n\t//}\n}", "traverseLevelOrder() {\n const root = this._root;\n const queue = [];\n\n if (!root) {\n return;\n }\n queue.push(root);\n\n while (queue.length) {\n const temp = queue.shift();\n console.log(temp.value);\n if (temp.left) {\n queue.push(temp.left);\n }\n if (temp.right) {\n queue.push(temp.right);\n }\n }\n }", "*elements(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n for (var [node, path] of Node$1.nodes(root, options)) {\n if (Element$1.isElement(node)) {\n yield [node, path];\n }\n }\n }", "actions(board) {\r\n let actions = new Set(); //[];\r\n //let board_arr = [...board];\r\n\r\n for (let i = 0; i < 9; i++) {\r\n if (board[i] === null) actions.add(i); // changed from tuple to array\r\n }\r\n\r\n return [...actions]; // changed from a set\r\n }", "function printNode(ID) {\n var childArray = new Array(); // store all children of node with ID into childArray[]\n var thisNode; // \"this\"\n for (i=0; i< nodes.length;i++){ // finding all children whose parentID == ID\n if (nodes[i][5] == ID){\n childArray.push(nodes[i]);\n //console.log(ID);\n }\n else if (nodes[i][0] == ID){\n thisNode = nodes[i];\n }\n }\n var numChildren = childArray.length;\n console.log(\"Number of children: \" + numChildren);\n\n var url = \"/story/\" + ID; // this is the url that will link to the edit's unique webpage\n \n // printing the icon and associated up/down votes\n p.image(\"/static/img/icons/doc3.png\", x-(img/2), y-(img/2), img, img)\n .hover(\n function(){\n this.attr({src: \"/static/img/icons/doc3_hovered.png\"});\n },\n function(){\n this.attr({src: \"/static/img/icons/doc3.png\"});\n })\n .attr({cursor: \"pointer\", href: url});\n \n var upVote = thisNode[6];\n var downVote = thisNode[7];\n p.text(x-(img/2.5), y+(img/2.5), upVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#02820B\"});\n p.text(x+(img/2.5), y+(img/2.5), downVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#B71306\"});\n console.log(\"Printed icon\"); // finish printing icon\n \n // if thisNode only has one child, draw a straight line downward to the child node\n if (numChildren == 1){\n y += 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" L \" + x + \" \" + y;\n //path += \" l 0 200\";\n \n printNode(childArray[0][0]);\n y -= 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" M \" + x + \" \" + y;\n }\n\n // if thisNode has multiple children, draw lines at 45-degrees in both directions downward, and if numChildren > 2, spaced equally inward from these outer lines\n else if (numChildren > 1){\n for (i=0; i < numChildren;i++){\n var newI = i;\n var newNum = numChildren;\n var angle = (((newI / (newNum-1))*200)-100);\n x += angle;\n y += 100;\n path += \" L \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n console.log(childArray);\n \n printNode(childArray[i][0]);\n x -= angle;\n y -= 100;\n path += \" M \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n i = newI;\n }\n }\n \n else if (numChildren == 0){\n console.log(\"No children\");\n return;\n }\n console.log(\"Number of children: \" + numChildren);\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 iglooActions () {\n\t//we should have things like pageTitle, user and revid\n\t//here- and the current page\n}", "function i2uiToggleContent(item, nest, relatedroutine)\r\n{\r\n // find the owning table for the item which received the event.\r\n // in this case the item is the expand/collapse image\r\n // note: the table may be several levels above as indicated by 'nest'\r\n var owningtable = item;\r\n //i2uitrace(1,\"nest=\"+nest+\" item=\"+item+\" tagname=\"+item.tagName);\r\n if (item.tagName == \"A\")\r\n {\r\n item = item.childNodes[0];\r\n //i2uitrace(1,\"new item=\"+item+\" parent=\"+item.parentNode+\" type=\"+item.tagName);\r\n }\r\n\r\n while (owningtable != null && nest > 0)\r\n {\r\n if (owningtable.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentNode;\r\n }\r\n if (owningtable != null && owningtable.tagName == 'TABLE')\r\n {\r\n nest--;\r\n }\r\n }\r\n\r\n var ownerid = owningtable.id;\r\n\r\n // for tabbed container, the true owning table is higher.\r\n // continue traversal in order to get the container id.\r\n if (ownerid == \"\")\r\n {\r\n var superowner = owningtable;\r\n while (superowner != null && ownerid == \"\")\r\n {\r\n if (superowner.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentElement.tagName+\" level=\"+nest+\" id=\"+superowner.parentElement.id);\r\n superowner = superowner.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentNode.tagName+\" level=\"+nest+\" id=\"+superowner.parentNode.id);\r\n superowner = superowner.parentNode;\r\n }\r\n if (superowner != null && superowner.tagName == 'TABLE')\r\n {\r\n ownerid = superowner.id;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"final id=\"+ownerid);\r\n\r\n // if found table, find child TBODY with proper id\r\n if (owningtable != null)\r\n {\r\n var pretogglewidth = owningtable.offsetWidth;\r\n\r\n //i2uitrace(1,owningtable.innerHTML);\r\n\r\n // can not simply use getElementById since the container\r\n // may itself contain containers.\r\n\r\n // determine how many TBODY tags are within the table\r\n var len = owningtable.getElementsByTagName('TBODY').length;\r\n //i2uitrace(1,'#TBODY='+len);\r\n\r\n // now find proper TBODY that holds the content\r\n var contenttbody;\r\n for (var i=0; i<len; i++)\r\n {\r\n contenttbody = owningtable.getElementsByTagName('TBODY')[i];\r\n //i2uitrace(1,'TBODY '+i+' id='+contenttbody.id);\r\n if (contenttbody.id == '_containerBody' ||\r\n contenttbody.id == '_containerbody' ||\r\n contenttbody.id == 'containerBodyIndent' ||\r\n contenttbody.id == 'containerbody')\r\n {\r\n //i2uitrace(1,'picked TBODY #'+i);\r\n\r\n var delta = 0;\r\n\r\n if (contenttbody.style.display == \"none\")\r\n {\r\n contenttbody.style.display = \"table\";\r\n\t\t contenttbody.style.width = \"100%\";\r\n item.src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n delta = contenttbody.offsetHeight;\r\n }\r\n else\r\n {\r\n delta = 0 - contenttbody.offsetHeight;\r\n contenttbody.style.display = \"none\";\r\n item.src = i2uiImageDirectory+\"/container_expand.gif\";\r\n }\r\n if (i2uiToggleContentUserFunction != null)\r\n {\r\n\t\t eval(i2uiToggleContentUserFunction+\"('\"+ownerid+\"',\"+delta+\")\");\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // restore width of container\r\n if (pretogglewidth != owningtable.offsetWidth)\r\n {\r\n owningtable.style.width = pretogglewidth;\r\n owningtable.width = pretogglewidth;\r\n }\r\n\r\n // call a related routine to handle any follow-up actions\r\n // intended for internal use. external use should use the\r\n // callback mechanism\r\n //i2uitrace(0,\"togglecontent related=[\"+relatedroutine+\"]\");\r\n if (relatedroutine != null)\r\n {\r\n // must invoke the routine 'in the future' to allow browser\r\n // to settle down, that is, finish rendering the effects of\r\n // the tree element changing state\r\n setTimeout(relatedroutine,200);\r\n }\r\n }\r\n}", "function getActiveActions() {\n var actions = [];\n if (!self.histories || self.histories.length <= 0)\n return actions;\n\n self.histories.forEach(function(history) {\n if (!history.isTrue)\n return;\n\n if (history.script &&\n history.script.Value &&\n history.script.Value.Actions) {\n actions = actions.concat(history.script.Value.Actions);\n }\n });\n\n if (self.current &&\n self.current.Value &&\n self.current.Value.Actions &&\n self.current.Value.End) {\n actions = actions.concat(self.current.Value.Actions);\n }\n\n return actions;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This returns true if the image is decorative.
function isElementDecorative(element, elementData) { if ($(element).attr("aria-hidden") === "true") { return true; //TODO: this logic may need to change if screen readers support spec that says aria-label // should override role=presentation, thus making it not decorative } else { if (elementData.role === "presentation" || elementData.role === "none") { //role is presentation or none return true; } else if ($(element).is("img") && elementData.empty && elementData.empty.alt) { //<img> and empty alt return true; } } return false; }
[ "is_image() {\n if (\n this.file_type == \"jpg\" ||\n this.file_type == \"png\" ||\n this.file_type == \"gif\"\n ) {\n return true;\n }\n return false;\n }", "function canHandleTrPxMan() {\n\t\tvar c, s1, s2;\n\t\tc = document.createElement(\"canvas\");\n\t\tc.width = 2;\n\t\tc.height = 1;\n\t\tc = c.getContext('2d');\n\t\tc.fillStyle = \"rgba(10,20,30,0.5)\";\n\t\tc.fillRect(0,0,1,1);\n\t\ts1 = c.getImageData(0,0,1,1);\n\t\tc.putImageData(s1, 1, 0);\n\t\ts2 = c.getImageData(1,0,1,1);\n\t\treturn (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]);\n\t}", "function checkImageDimensions(thisContext, textEl, imageEl) {\n // Get height of image\n var imageH = imageEl.outerHeight();\n var wrapperH;\n\n // Make sure image height is not 0 (can happen when image is not loaded yet)\n if (imageH !== 0) {\n // Get height of text\n var textH = textEl.outerHeight();\n // If text is taller than image, display as background-image\n if (textH > imageH) {\n wrapperH = (textH - imageH) + imageH;\n thisContext.addClass('show-bg-image').css('height', wrapperH);\n return true;\n }\n else {\n thisContext.removeClass('show-bg-image').css('height', 'auto');\n return false;\n }\n }\n }", "shouldToggleByCornerOrButton() {\n if (this._animationInProgress)\n return false;\n if (this._inItemDrag || this._inWindowDrag)\n return false;\n if (!this._activationTime ||\n GLib.get_monotonic_time() / GLib.USEC_PER_SEC - this._activationTime > OVERVIEW_ACTIVATION_TIMEOUT)\n return true;\n return false;\n }", "function PrisonCharacterAppearanceAvailable (C, AppearanceName, AppearanceGroup) {\n\tfor (let I = 0; I < C.Appearance.length; I++)\n\t\tif ((C.Appearance[I].Asset.Name == AppearanceName) && (C.Appearance[I].Asset.Group.Name == AppearanceGroup))\n\t\t\treturn true;\n\treturn false;\n}", "function isOpenBefore( drawable ) {\n return drawable.previousDrawable !== null && !hasGapBetweenDrawables( drawable.previousDrawable, drawable );\n}", "function haveHat() {\n\tvar avatar=document.getElementById('avatar');\n\tif (avatar) {\n\t\treturn /Hat[^.]{0,14}\\.gif/.test(avatar.innerHTML);\n\t}\n\treturn false;\n}", "function isCanvas() {\n return !isHome();\n}", "get isOwning() {\n return !!(this.isManyToOne ||\n (this.isManyToMany && this.joinTable) ||\n (this.isOneToOne && this.joinColumn));\n }", "isIdentity() {\n if (this._isIdentityDirty) {\n this._isIdentityDirty = false;\n const m = this._m;\n this._isIdentity =\n m[0] === 1.0 &&\n m[1] === 0.0 &&\n m[2] === 0.0 &&\n m[3] === 0.0 &&\n m[4] === 0.0 &&\n m[5] === 1.0 &&\n m[6] === 0.0 &&\n m[7] === 0.0 &&\n m[8] === 0.0 &&\n m[9] === 0.0 &&\n m[10] === 1.0 &&\n m[11] === 0.0 &&\n m[12] === 0.0 &&\n m[13] === 0.0 &&\n m[14] === 0.0 &&\n m[15] === 1.0;\n }\n return this._isIdentity;\n }", "isVertical() {\r\n return !this.isHorizontal();\r\n }", "function isContrastCompliant(background, foreground, compliance) {\n if (compliance === void 0) { compliance = \"normal\"; }\n var ratio;\n switch (compliance) {\n case \"large\":\n ratio = exports.LARGE_TEXT_CONTRAST_RATIO;\n break;\n case \"normal\":\n ratio = exports.NORMAL_TEXT_CONTRAST_RATIO;\n break;\n case \"AAA\":\n ratio = exports.AAA_CONTRAST_RATIO;\n break;\n default:\n ratio = compliance;\n }\n return getContrastRatio_1.default(background, foreground) >= ratio;\n}", "function iconDisplay(profile){\n if (profile.isVegetarian === true && vegetarianCheck(props.ingredient) === true) {\n return false;\n } else if (profile.isVegan === true && veganCheck(props.ingredient) === true) {\n return false;\n } else if (profile.isGlutenFree === true && glutenFreeCheck(props.ingredient) === true) {\n return false;\n } else if (profile.hasNutAllergy === true && nutAllergyCheck(props.ingredient) === true) {\n return false;\n } else {\n return true;\n }\n }", "getCrosshairsClip() {\n if (this._crossHairs) {\n let [clipWidth, clipHeight] = this._crossHairs.getClip();\n return (clipWidth > 0 && clipHeight > 0);\n } else {\n return false;\n }\n }", "infoResponseIsInStore() {\n const responses = this.currentInfoResponses();\n if (responses.length === this.imageServiceIds().length) {\n return true;\n }\n return false;\n }", "hasAnnotationSupport() {\n\t\tif(this.props.annotationSupport != null) {\n\t\t\tif(this.props.annotationSupport.currentQuery || this.props.annotationSupport.singleItem) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "needsAnyAttention() {\n if (this.json_.hasOwnProperty(\"attention_set\")) {\n return Object.keys(this.json_.attention_set).length > 0;\n }\n return false\n }", "function PrisonCharacterAppearanceGroupAvailable (C, AppearanceGroup) {\n\tfor (let I = 0; I < C.Appearance.length; I++)\n\t\tif (C.Appearance[I].Asset.Group.Name == AppearanceGroup)\n\t\t\treturn true;\n\treturn false;\n}", "hasAnimationFlag() {\n let flag = false;\n Object.keys(this.args).forEach((key) => {\n if (this.args[key].anime) {\n flag = true;\n }\n });\n return flag;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
STAGE 4 RCL is 3, building up to RCL 4
function stage4() { // HARVESTERS if(harvesters.length < 1) { // if harvesters less than 2, make more spawn.run('harvester4'); } // BUILDERS else if(builders.length < 2) { // if harvesters less than 2, make more spawn.run('builder4'); } // UPGRADERS else if(upgraders.length < 4) { // if harvesters less than 2, make more spawn.run('upgrader4'); } // REPAIRERS else if(repairers.length < 2) { // if harvesters less than 2, make more spawn.run('repairer4'); } // PAVERS else if(pavers.length < 1) { // if harvesters less than 2, make more spawn.run('paver4'); } // DEFENDERS else if(defenders.length < 2) { // if harvesters less than 2, make more spawn.run('defender4'); } // TOWER tower(0); // function that runs the tower // MINER / HAULER checkPair(); /* if(checkSource(5) && Game.spawns['Spawn1'].room.energyAvailable >= 550){ // ensures that only big combos will be spawned spawnPair(5); }; */ //CONSTRUCTION //checkMaxEnergy(); // PROGRESSION CHECKER if(harvesters.length >= 1 && builders.length >= 2 && upgraders.length >= 4 && repairers.length >= 2 && pavers.length >= 1 && defenders.length >= 2 && Memory.stage == 4 && extensions.length >= 10 && Game.rooms[roomName].controller.level >= 4 && Memory.containersDone[1] && Memory.pairActive) { Memory.stage++; } else { if((Game.time%modTime)==1) { report(4,5); } } }
[ "BCS() { if (this.C) this.PC = this.checkBranch_(this.MP); }", "function C101_KinbakuClub_RopeGroup_Load() {\n\n\t// Load correct stage\n\t// After intro player has a choice each time she goes to the group, until a twin is released\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage > 100 && C101_KinbakuClub_RopeGroup_CurrentStage < 700) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 100;\n\t}\n\t\n\t// Player is pre bound/gagged or not\n\tif (Common_PlayerGagged || Common_PlayerRestrained) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 50;\n\t}\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 50 && !Common_PlayerGagged && !Common_PlayerRestrained) {\n\t\tif (C101_KinbakuClub_RopeGroup_IntroDone) C101_KinbakuClub_RopeGroup_CurrentStage = 100;\n\t\telse C101_KinbakuClub_RopeGroup_CurrentStage = 10;\n\t}\n\n\t// After Jenna frees you.\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 848 || C101_KinbakuClub_RopeGroup_CurrentStage == 849) C101_KinbakuClub_RopeGroup_CurrentStage = 100;\n\n\t// After Heather lets you go.\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 858) C101_KinbakuClub_RopeGroup_CurrentStage = 900;\n\t\n\t// Load the scene parameters\n\t// Load relevent actor\n\tC101_KinbakuClub_RopeGroup_NoActor()\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage < 100) C101_KinbakuClub_RopeGroup_LoadAmelia()\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 700) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\") ActorLoad(C101_KinbakuClub_RopeGroup_LeftTwin, \"ClubRoom1\");\n\t\telse ActorLoad(C101_KinbakuClub_RopeGroup_RightTwin, \"ClubRoom1\");\n\t}\n\tLoadInteractions();\n\tC101_KinbakuClub_RopeGroup_CalcParams();\n\t\n\n\t// Determine which twin is Lucy\n\tif (C101_KinbakuClub_RopeGroup_RightTwin == \"\") {\n\t\tC101_KinbakuClub_RopeGroup_Random = Math.floor(Math.random() * 2);\n\t\tif (C101_KinbakuClub_RopeGroup_Random == 0)\t{\n\t\t\tC101_KinbakuClub_RopeGroup_LeftTwin = \"Lucy\";\n\t\t\tC101_KinbakuClub_RopeGroup_RightTwin = \"Heather\";\n\t\t}\n\t\telse {\n\t\t\tC101_KinbakuClub_RopeGroup_LeftTwin = \"Heather\";\n\t\t\tC101_KinbakuClub_RopeGroup_RightTwin = \"Lucy\";\n\t\t}\n\t}\n}", "function doNextStage() {\r\n\r\n clearTip();\r\n\r\n var sO = CurStepObj;\r\n\r\n // The stage in current step\r\n //\r\n var stage = CurStepObj.stageInStep;\r\n\r\n // Templates scope supports only the very first step of grid creation\r\n //\r\n if (CurFuncObj.isTemplateScope) {\r\n stage = StageInStep.New;\r\n }\r\n\r\n CurHtmlGridId = AllHtmlGridIds[stage];\r\n\r\n if (stage <= StageInStep.New) { // we have not created any output grids\r\n\r\n\tdrawOutMenuTable(); // draw the menu to pick out grid\r\n\r\n } else if ((stage == StageInStep.ConfigDone) ||\r\n (stage == StageInStep.SrcSelectStarted)) {\r\n\r\n // we have added the output/src grid. Now, add src grid (more src grids)\r\n //\r\n var gridId = sO.allGridIds.length;\r\n CurHtmlGridId = AllHtmlGridIds[gridId];\r\n //\r\n sO.stageInStep = StageInStep.SrcSelectStarted;\r\n //\r\n drawSrcMenuTable(); // draw the menu to pick src grid\r\n\r\n /*\t \r\n\t// Since only an existing grid can be selected as a source, we \r\n\t// call the following function directly\r\n\t//\r\n\tselectExistingGrid();\r\n\t*/\r\n\r\n\r\n } else if (stage <= StageInStep.GridSelectDone) {\r\n\r\n // We have added all out/src grids (and add src menu is gone)\r\n\r\n // The grid selection is complete. Update program structure and\r\n // draw the code window with buttons\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n\r\n // Init and draw code window. \r\n // NOTE: initialization happens only once -- initCodeOfStep() checks\r\n // whether we have already initialized code of step\r\n //\r\n initCodeOfStep(CurStepObj); // init code of step\r\n drawCodeWindow(CurStepObj); // draw code window with buttons \r\n\r\n }\r\n\r\n}", "startGC() {\n this.currentParams.generalizedCylinder = true;\n //__params ->customId = popId();\n //__params ->customParentId = parentId;\n }", "function calcProdMinRackInit(){\n\ttry{\n\tif(DEVMODE_FUNCTION){ var trackingHandle = tracking.start(\"berater\",\"calcProdMinRackInit\"); }\n\t\tprodMinRackInit=explode(GM_getValue(COUNTRY+\"_\"+SERVER+\"_\"+USERNAME+\"_prodMinRackInit\"),\"calcProdMinRackInit/prodMinRackInit\",[[],{},{},{}]);\n\t\tif(!(prodMinRackInit instanceof Array)){ prodMinRackInit=[]; }\n\t\tfor(var type in prodName){\n\t\t\tif(!prodName.hasOwnProperty(type)){continue;}\n\t\t\tif(type==1){\n\t\t\t\tif((!prodMinRackInit[type])||(typeof prodMinRackInit[type]!=\"object\")||(prodMinRackInit[type] instanceof Array)){ prodMinRackInit[type]={}; } \n\t\t\t}else{\n\t\t\t\tif((!prodMinRackInit[type])||(!(prodMinRackInit[type] instanceof Array))){ prodMinRackInit[type]=[]; } \n\t\t\t}\n\t\t\tif(!valMinRackMan){ // detail-setting option (else see buildPreise)\n\t\t\t\tfor(var prod in prodName[type]){\n\t\t\t\t\t//GM_log(\"prodName type:\"+type+\" prod:\"+prod);\n\t\t\t\t\tif(!prodName[type].hasOwnProperty(prod)){continue;}\n\t\t\t\t\tif((!valMinRack[prodTyp[type][prod]])||(prodBlock[type][prod])){ // .match(/t/)\n\t\t\t\t\t\tprodMinRackInit[type][prod]=0;\n\t\t\t\t\t}else if(prodTyp[type][prod]==\"v\"){\n\t\t\t\t\t\tprodMinRackInit[type][prod]=valMinRack[prodTyp[type][prod]]/(valMinRackPlantsize?prodPlantSize[type][prod]:1);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tprodMinRackInit[type][prod]=valMinRack[prodTyp[type][prod]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// prodMinRackInit[type].sortObj();\n\t\t}\n\t\tGM_setValue2(COUNTRY+\"_\"+SERVER+\"_\"+USERNAME+\"_prodMinRackInit\",implode(prodMinRackInit,\"calcProdMinRackInit\\prodMinRackInit\"));\n\t\tunsafeData.prodMinRackInit=prodMinRackInit.clone();\n\t\tcalcProdMinRack();\n\tif(DEVMODE_FUNCTION){ tracking.end(\"berater\",trackingHandle); }\n\t}catch(err){ GM_logError(\"calcProdMinRackInit\\ntype=\"+type+\" prod=\"+prod+\"\\n\"+err); }\n}", "function drawPipeline() {\n var housesWidth = document.getElementById('houses').offsetWidth;\n var housesHeight = document.getElementById('houses').offsetHeight;\n\n // Pipeline outline\n outline = stage.rect(stage.getBounds().left, stage.getBounds().top + 50, housesWidth, housesHeight / 6).stroke('grey').fill(['darkgrey', 'lightgrey'], 60);\n\n // Pipeline sections and rivets\n var spacing = housesWidth / 6.29;\n for (var i = 0, rectOffset = spacing / 3; i < Math.floor(housesWidth / spacing); ++i, rectOffset += spacing) {\n var r = stage.rect(rectOffset, outline.getBounds().top - outline.getHeight() / 2, outline.getWidth() / 84.8, outline.getHeight() * 2).stroke('grey').fill(['darkgrey', 'lightgrey'], 15);\n var x = r.getBounds().left + r.getWidth() / 2;\n var y = r.getBounds().top + r.getHeight() / 3 / 2;\n var radius = r.getWidth() / 2 / 2;\n stage.circle(x, y, radius).stroke('grey').fill(['darkgrey', 'lightgrey'], 70);\n y += r.getHeight() / 3;\n stage.circle(x, y, radius).stroke('grey').fill(['darkgrey', 'lightgrey'], 70);\n y += r.getHeight() / 3;\n stage.circle(x, y, radius).stroke('grey').fill(['darkgrey', 'lightgrey'], 70);\n }\n // Set up craccs\n crack1 = stage.path();\n crack2 = stage.path();\n crack3 = stage.path();\n }", "function setFlags() {\n\n var WEBGL_VERSION = 2\n var WASM_HAS_SIMD_SUPPORT = false\n var WASM_HAS_MULTITHREAD_SUPPORT = false\n var WEBGL_CPU_FORWARD = true\n var WEBGL_PACK = true\n var WEBGL_FORCE_F16_TEXTURES = false\n var WEBGL_RENDER_FLOAT32_CAPABLE = true\n var WEBGL_FLUSH_THRESHOLD = -1\n var CHECK_COMPUTATION_FOR_ERRORS = false\n\n wasmFeatureDetect.simd().then(simdSupported => {\n if (simdSupported) {\n // alert(\"simd supported\")\n WASM_HAS_SIMD_SUPPORT = true\n } else {\n // alert(\"no simd\")\n }\n });\n wasmFeatureDetect.threads().then(threadsSupported => {\n if (threadsSupported) {\n // alert(\"multi thread supported\")\n WASM_HAS_MULTITHREAD_SUPPORT = true;\n } else {\n // alert(\"no multi thread\")\n }\n });\n switch (getOS()) {\n case 'Mac OS':\n // alert('Mac detected')\n WEBGL_VERSION = 1\n break;\n case 'Linux':\n // alert('linux detected')\n break;\n case 'iOS':\n // alert('ios detected')\n WEBGL_VERSION = 1\n WEBGL_FORCE_F16_TEXTURES = true //use float 16s on mobile just incase \n WEBGL_RENDER_FLOAT32_CAPABLE = false\n break;\n case 'Android':\n WEBGL_FORCE_F16_TEXTURES = true\n WEBGL_RENDER_FLOAT32_CAPABLE = false\n line_width = 3\n radius = 4\n // alert('android detected')\n break;\n default:\n // alert('windows detected')\n break;\n\n }\n\n var flagConfig = {\n WEBGL_VERSION: WEBGL_VERSION,\n WASM_HAS_SIMD_SUPPORT: WASM_HAS_SIMD_SUPPORT,\n WASM_HAS_MULTITHREAD_SUPPORT: WASM_HAS_MULTITHREAD_SUPPORT,\n WEBGL_CPU_FORWARD: WEBGL_CPU_FORWARD,\n WEBGL_PACK: WEBGL_PACK,\n WEBGL_FORCE_F16_TEXTURES: WEBGL_FORCE_F16_TEXTURES,\n WEBGL_RENDER_FLOAT32_CAPABLE: WEBGL_RENDER_FLOAT32_CAPABLE,\n WEBGL_FLUSH_THRESHOLD: WEBGL_FLUSH_THRESHOLD,\n CHECK_COMPUTATION_FOR_ERRORS: CHECK_COMPUTATION_FOR_ERRORS,\n }\n\n setEnvFlags(flagConfig)\n\n}", "function SCORMapi1_3(def, cmiobj, cmiint, cmicommentsuser, cmicommentslms, scormdebugging, scormauto, scormid, cfgwwwroot, sesskey, scoid, attempt, viewmode, cmid, currentorg, autocommit) {\n\n var prerequrl = cfgwwwroot + \"/mod/scorm/prereqs.php?a=\" + scormid + \"&scoid=\" + scoid + \"&attempt=\" + attempt + \"&mode=\" + viewmode + \"&currentorg=\" + currentorg + \"&sesskey=\" + sesskey;\n var datamodelurl = cfgwwwroot + \"/mod/scorm/datamodel.php\";\n var datamodelurlparams = \"id=\" + cmid + \"&a=\" + scormid + \"&sesskey=\" + sesskey + \"&attempt=\" + attempt + \"&scoid=\" + scoid;\n\n // Standard Data Type Definition\n\n // language key has to be checked for language dependent strings\n var validLanguages = {'aa':'aa', 'ab':'ab', 'ae':'ae', 'af':'af', 'ak':'ak', 'am':'am', 'an':'an', 'ar':'ar', 'as':'as', 'av':'av', 'ay':'ay', 'az':'az',\n 'ba':'ba', 'be':'be', 'bg':'bg', 'bh':'bh', 'bi':'bi', 'bm':'bm', 'bn':'bn', 'bo':'bo', 'br':'br', 'bs':'bs',\n 'ca':'ca', 'ce':'ce', 'ch':'ch', 'co':'co', 'cr':'cr', 'cs':'cs', 'cu':'cu', 'cv':'cv', 'cy':'cy',\n 'da':'da', 'de':'de', 'dv':'dv', 'dz':'dz', 'ee':'ee', 'el':'el', 'en':'en', 'eo':'eo', 'es':'es', 'et':'et', 'eu':'eu',\n 'fa':'fa', 'ff':'ff', 'fi':'fi', 'fj':'fj', 'fo':'fo', 'fr':'fr', 'fy':'fy', 'ga':'ga', 'gd':'gd', 'gl':'gl', 'gn':'gn', 'gu':'gu', 'gv':'gv',\n 'ha':'ha', 'he':'he', 'hi':'hi', 'ho':'ho', 'hr':'hr', 'ht':'ht', 'hu':'hu', 'hy':'hy', 'hz':'hz',\n 'ia':'ia', 'id':'id', 'ie':'ie', 'ig':'ig', 'ii':'ii', 'ik':'ik', 'io':'io', 'is':'is', 'it':'it', 'iu':'iu',\n 'ja':'ja', 'jv':'jv', 'ka':'ka', 'kg':'kg', 'ki':'ki', 'kj':'kj', 'kk':'kk', 'kl':'kl', 'km':'km', 'kn':'kn', 'ko':'ko', 'kr':'kr', 'ks':'ks', 'ku':'ku', 'kv':'kv', 'kw':'kw', 'ky':'ky',\n 'la':'la', 'lb':'lb', 'lg':'lg', 'li':'li', 'ln':'ln', 'lo':'lo', 'lt':'lt', 'lu':'lu', 'lv':'lv',\n 'mg':'mg', 'mh':'mh', 'mi':'mi', 'mk':'mk', 'ml':'ml', 'mn':'mn', 'mo':'mo', 'mr':'mr', 'ms':'ms', 'mt':'mt', 'my':'my',\n 'na':'na', 'nb':'nb', 'nd':'nd', 'ne':'ne', 'ng':'ng', 'nl':'nl', 'nn':'nn', 'no':'no', 'nr':'nr', 'nv':'nv', 'ny':'ny',\n 'oc':'oc', 'oj':'oj', 'om':'om', 'or':'or', 'os':'os', 'pa':'pa', 'pi':'pi', 'pl':'pl', 'ps':'ps', 'pt':'pt',\n 'qu':'qu', 'rm':'rm', 'rn':'rn', 'ro':'ro', 'ru':'ru', 'rw':'rw',\n 'sa':'sa', 'sc':'sc', 'sd':'sd', 'se':'se', 'sg':'sg', 'sh':'sh', 'si':'si', 'sk':'sk', 'sl':'sl', 'sm':'sm', 'sn':'sn', 'so':'so', 'sq':'sq', 'sr':'sr', 'ss':'ss', 'st':'st', 'su':'su', 'sv':'sv', 'sw':'sw',\n 'ta':'ta', 'te':'te', 'tg':'tg', 'th':'th', 'ti':'ti', 'tk':'tk', 'tl':'tl', 'tn':'tn', 'to':'to', 'tr':'tr', 'ts':'ts', 'tt':'tt', 'tw':'tw', 'ty':'ty',\n 'ug':'ug', 'uk':'uk', 'ur':'ur', 'uz':'uz', 've':'ve', 'vi':'vi', 'vo':'vo',\n 'wa':'wa', 'wo':'wo', 'xh':'xh', 'yi':'yi', 'yo':'yo', 'za':'za', 'zh':'zh', 'zu':'zu',\n 'aar':'aar', 'abk':'abk', 'ave':'ave', 'afr':'afr', 'aka':'aka', 'amh':'amh', 'arg':'arg', 'ara':'ara', 'asm':'asm', 'ava':'ava', 'aym':'aym', 'aze':'aze',\n 'bak':'bak', 'bel':'bel', 'bul':'bul', 'bih':'bih', 'bis':'bis', 'bam':'bam', 'ben':'ben', 'tib':'tib', 'bod':'bod', 'bre':'bre', 'bos':'bos',\n 'cat':'cat', 'che':'che', 'cha':'cha', 'cos':'cos', 'cre':'cre', 'cze':'cze', 'ces':'ces', 'chu':'chu', 'chv':'chv', 'wel':'wel', 'cym':'cym',\n 'dan':'dan', 'ger':'ger', 'deu':'deu', 'div':'div', 'dzo':'dzo', 'ewe':'ewe', 'gre':'gre', 'ell':'ell', 'eng':'eng', 'epo':'epo', 'spa':'spa', 'est':'est', 'baq':'baq', 'eus':'eus', 'per':'per',\n 'fas':'fas', 'ful':'ful', 'fin':'fin', 'fij':'fij', 'fao':'fao', 'fre':'fre', 'fra':'fra', 'fry':'fry', 'gle':'gle', 'gla':'gla', 'glg':'glg', 'grn':'grn', 'guj':'guj', 'glv':'glv',\n 'hau':'hau', 'heb':'heb', 'hin':'hin', 'hmo':'hmo', 'hrv':'hrv', 'hat':'hat', 'hun':'hun', 'arm':'arm', 'hye':'hye', 'her':'her',\n 'ina':'ina', 'ind':'ind', 'ile':'ile', 'ibo':'ibo', 'iii':'iii', 'ipk':'ipk', 'ido':'ido', 'ice':'ice', 'isl':'isl', 'ita':'ita', 'iku':'iku',\n 'jpn':'jpn', 'jav':'jav', 'geo':'geo', 'kat':'kat', 'kon':'kon', 'kik':'kik', 'kua':'kua', 'kaz':'kaz', 'kal':'kal', 'khm':'khm', 'kan':'kan', 'kor':'kor', 'kau':'kau', 'kas':'kas', 'kur':'kur', 'kom':'kom', 'cor':'cor', 'kir':'kir',\n 'lat':'lat', 'ltz':'ltz', 'lug':'lug', 'lim':'lim', 'lin':'lin', 'lao':'lao', 'lit':'lit', 'lub':'lub', 'lav':'lav',\n 'mlg':'mlg', 'mah':'mah', 'mao':'mao', 'mri':'mri', 'mac':'mac', 'mkd':'mkd', 'mal':'mal', 'mon':'mon', 'mol':'mol', 'mar':'mar', 'may':'may', 'msa':'msa', 'mlt':'mlt', 'bur':'bur', 'mya':'mya',\n 'nau':'nau', 'nob':'nob', 'nde':'nde', 'nep':'nep', 'ndo':'ndo', 'dut':'dut', 'nld':'nld', 'nno':'nno', 'nor':'nor', 'nbl':'nbl', 'nav':'nav', 'nya':'nya',\n 'oci':'oci', 'oji':'oji', 'orm':'orm', 'ori':'ori', 'oss':'oss', 'pan':'pan', 'pli':'pli', 'pol':'pol', 'pus':'pus', 'por':'por', 'que':'que',\n 'roh':'roh', 'run':'run', 'rum':'rum', 'ron':'ron', 'rus':'rus', 'kin':'kin', 'san':'san', 'srd':'srd', 'snd':'snd', 'sme':'sme', 'sag':'sag', 'slo':'slo', 'sin':'sin', 'slk':'slk', 'slv':'slv', 'smo':'smo', 'sna':'sna', 'som':'som', 'alb':'alb', 'sqi':'sqi', 'srp':'srp', 'ssw':'ssw', 'sot':'sot', 'sun':'sun', 'swe':'swe', 'swa':'swa',\n 'tam':'tam', 'tel':'tel', 'tgk':'tgk', 'tha':'tha', 'tir':'tir', 'tuk':'tuk', 'tgl':'tgl', 'tsn':'tsn', 'ton':'ton', 'tur':'tur', 'tso':'tso', 'tat':'tat', 'twi':'twi', 'tah':'tah',\n 'uig':'uig', 'ukr':'ukr', 'urd':'urd', 'uzb':'uzb', 'ven':'ven', 'vie':'vie', 'vol':'vol', 'wln':'wln', 'wol':'wol', 'xho':'xho', 'yid':'yid', 'yor':'yor', 'zha':'zha', 'chi':'chi', 'zho':'zho', 'zul':'zul'};\n\n var CMIString200 = '^[\\\\u0000-\\\\uFFFF]{0,200}$';\n var CMIString250 = '^[\\\\u0000-\\\\uFFFF]{0,250}$';\n var CMIString1000 = '^[\\\\u0000-\\\\uFFFF]{0,1000}$';\n var CMIString4000 = '^[\\\\u0000-\\\\uFFFF]{0,4000}$';\n var CMIString64000 = '^[\\\\u0000-\\\\uFFFF]{0,64000}$';\n var CMILang = '^([a-zA-Z]{2,3}|i|x)(\\-[a-zA-Z0-9\\-]{2,8})?$|^$';\n var CMILangString250 = '^(\\{lang=([a-zA-Z]{2,3}|i|x)(\\-[a-zA-Z0-9\\-]{2,8})?\\})?([^\\{].{0,250}$)?';\n var CMILangcr = '^((\\{lang=([a-zA-Z]{2,3}|i|x)?(\\-[a-zA-Z0-9\\-]{2,8})?\\}))(.*?)$';\n var CMILangString250cr = '^((\\{lang=([a-zA-Z]{2,3}|i|x)?(\\-[a-zA-Z0-9\\-]{2,8})?\\})?(.{0,250})?)?$';\n var CMILangString4000 = '^(\\{lang=([a-zA-Z]{2,3}|i|x)(\\-[a-zA-Z0-9\\-]{2,8})?\\})?([^\\{].{0,4000}$)?';\n var CMITime = '^(19[7-9]{1}[0-9]{1}|20[0-2]{1}[0-9]{1}|203[0-8]{1})((-(0[1-9]{1}|1[0-2]{1}))((-(0[1-9]{1}|[1-2]{1}[0-9]{1}|3[0-1]{1}))(T([0-1]{1}[0-9]{1}|2[0-3]{1})((:[0-5]{1}[0-9]{1})((:[0-5]{1}[0-9]{1})((\\\\.[0-9]{1,2})((Z|([+|-]([0-1]{1}[0-9]{1}|2[0-3]{1})))(:[0-5]{1}[0-9]{1})?)?)?)?)?)?)?)?$';\n var CMITimespan = '^P(\\\\d+Y)?(\\\\d+M)?(\\\\d+D)?(T(((\\\\d+H)(\\\\d+M)?(\\\\d+(\\.\\\\d{1,2})?S)?)|((\\\\d+M)(\\\\d+(\\.\\\\d{1,2})?S)?)|((\\\\d+(\\.\\\\d{1,2})?S))))?$';\n var CMIInteger = '^\\\\d+$';\n var CMISInteger = '^-?([0-9]+)$';\n var CMIDecimal = '^-?([0-9]{1,5})(\\\\.[0-9]{1,18})?$';\n var CMIIdentifier = '^\\\\S{1,250}[a-zA-Z0-9]$';\n var CMIShortIdentifier = '^[\\\\w\\.]{1,250}$';\n var CMILongIdentifier = '^(?:(?!urn:)\\\\S{1,4000}|urn:[A-Za-z0-9-]{1,31}:\\\\S{1,4000})$';\n var CMIFeedback = '^.*$'; // This must be redefined\n var CMIIndex = '[._](\\\\d+).';\n var CMIIndexStore = '.N(\\\\d+).';\n // Vocabulary Data Type Definition\n var CMICStatus = '^completed$|^incomplete$|^not attempted$|^unknown$';\n var CMISStatus = '^passed$|^failed$|^unknown$';\n var CMIExit = '^time-out$|^suspend$|^logout$|^normal$|^$';\n var CMIType = '^true-false$|^choice$|^(long-)?fill-in$|^matching$|^performance$|^sequencing$|^likert$|^numeric$|^other$';\n var CMIResult = '^correct$|^incorrect$|^unanticipated$|^neutral$|^-?([0-9]{1,4})(\\\\.[0-9]{1,18})?$';\n var NAVEvent = '^previous$|^continue$|^exit$|^exitAll$|^abandon$|^abandonAll$|^suspendAll$|^\\{target=\\\\S{0,200}[a-zA-Z0-9]\\}choice|jump$';\n var NAVBoolean = '^unknown$|^true$|^false$';\n var NAVTarget = '^previous$|^continue$|^choice.{target=\\\\S{0,200}[a-zA-Z0-9]}$'\n // Children lists\n var cmi_children = '_version,comments_from_learner,comments_from_lms,completion_status,credit,entry,exit,interactions,launch_data,learner_id,learner_name,learner_preference,location,max_time_allowed,mode,objectives,progress_measure,scaled_passing_score,score,session_time,success_status,suspend_data,time_limit_action,total_time';\n var comments_children = 'comment,timestamp,location';\n var score_children = 'max,raw,scaled,min';\n var objectives_children = 'progress_measure,completion_status,success_status,description,score,id';\n var correct_responses_children = 'pattern';\n var student_data_children = 'mastery_score,max_time_allowed,time_limit_action';\n var student_preference_children = 'audio_level,audio_captioning,delivery_speed,language';\n var interactions_children = 'id,type,objectives,timestamp,correct_responses,weighting,learner_response,result,latency,description';\n // Data ranges\n var scaled_range = '-1#1';\n var audio_range = '0#*';\n var speed_range = '0#*';\n var text_range = '-1#1';\n var progress_range = '0#1';\n var learner_response = {\n 'true-false':{'format':'^true$|^false$', 'max':1, 'delimiter':'', 'unique':false},\n 'choice':{'format':CMIShortIdentifier, 'max':36, 'delimiter':'[,]', 'unique':true},\n 'fill-in':{'format':CMILangString250, 'max':10, 'delimiter':'[,]', 'unique':false},\n 'long-fill-in':{'format':CMILangString4000, 'max':1, 'delimiter':'', 'unique':false},\n 'matching':{'format':CMIShortIdentifier, 'format2':CMIShortIdentifier, 'max':36, 'delimiter':'[,]', 'delimiter2':'[.]', 'unique':false},\n 'performance':{'format':'^$|' + CMIShortIdentifier, 'format2':CMIDecimal + '|^$|' + CMIShortIdentifier, 'max':250, 'delimiter':'[,]', 'delimiter2':'[.]', 'unique':false},\n 'sequencing':{'format':CMIShortIdentifier, 'max':36, 'delimiter':'[,]', 'unique':false},\n 'likert':{'format':CMIShortIdentifier, 'max':1, 'delimiter':'', 'unique':false},\n 'numeric':{'format':CMIDecimal, 'max':1, 'delimiter':'', 'unique':false},\n 'other':{'format':CMIString4000, 'max':1, 'delimiter':'', 'unique':false}\n }\n\n var correct_responses = {\n 'true-false':{'max':1, 'delimiter':'', 'unique':false, 'duplicate':false,\n 'format':'^true$|^false$',\n 'limit':1},\n 'choice':{'max':36, 'delimiter':'[,]', 'unique':true, 'duplicate':false,\n 'format':CMIShortIdentifier},\n 'fill-in':{'max':10, 'delimiter':'[,]', 'unique':false, 'duplicate':false,\n 'format':CMILangString250cr},\n 'long-fill-in':{'max':1, 'delimiter':'', 'unique':false, 'duplicate':true,\n 'format':CMILangString4000},\n 'matching':{'max':36, 'delimiter':'[,]', 'delimiter2':'[.]', 'unique':false, 'duplicate':false,\n 'format':CMIShortIdentifier, 'format2':CMIShortIdentifier},\n 'performance':{'max':250, 'delimiter':'[,]', 'delimiter2':'[.]', 'unique':false, 'duplicate':false,\n 'format':'^$|' + CMIShortIdentifier, 'format2':CMIDecimal + '|^$|' + CMIShortIdentifier},\n 'sequencing':{'max':36, 'delimiter':'[,]', 'unique':false, 'duplicate':false,\n 'format':CMIShortIdentifier},\n 'likert':{'max':1, 'delimiter':'', 'unique':false, 'duplicate':false,\n 'format':CMIShortIdentifier,\n 'limit':1},\n 'numeric':{'max':2, 'delimiter':'[:]', 'unique':false, 'duplicate':false,\n 'format':CMIDecimal,\n 'limit':1},\n 'other':{'max':1, 'delimiter':'', 'unique':false, 'duplicate':false,\n 'format':CMIString4000,\n 'limit':1}\n }\n\n // The SCORM 1.3 data model\n // Set up data model for each sco\n var datamodel = {};\n for(scoid in def){\n datamodel[scoid] = {\n 'cmi._children':{'defaultvalue':cmi_children, 'mod':'r'},\n 'cmi._version':{'defaultvalue':'1.0', 'mod':'r'},\n 'cmi.comments_from_learner._children':{'defaultvalue':comments_children, 'mod':'r'},\n 'cmi.comments_from_learner._count':{'mod':'r', 'defaultvalue':'0'},\n 'cmi.comments_from_learner.n.comment':{'format':CMILangString4000, 'mod':'rw'},\n 'cmi.comments_from_learner.n.location':{'format':CMIString250, 'mod':'rw'},\n 'cmi.comments_from_learner.n.timestamp':{'format':CMITime, 'mod':'rw'},\n 'cmi.comments_from_lms._children':{'defaultvalue':comments_children, 'mod':'r'},\n 'cmi.comments_from_lms._count':{'mod':'r', 'defaultvalue':'0'},\n 'cmi.comments_from_lms.n.comment':{'format':CMILangString4000, 'mod':'r'},\n 'cmi.comments_from_lms.n.location':{'format':CMIString250, 'mod':'r'},\n 'cmi.comments_from_lms.n.timestamp':{'format':CMITime, 'mod':'r'},\n 'cmi.completion_status':{'defaultvalue':def[scoid]['cmi.completion_status'], 'format':CMICStatus, 'mod':'rw'},\n 'cmi.completion_threshold':{'defaultvalue':def[scoid]['cmi.completion_threshold'], 'mod':'r'},\n 'cmi.credit':{'defaultvalue':def[scoid]['cmi.credit'], 'mod':'r'},\n 'cmi.entry':{'defaultvalue':def[scoid]['cmi.entry'], 'mod':'r'},\n 'cmi.exit':{'defaultvalue':def[scoid]['cmi.exit'], 'format':CMIExit, 'mod':'w'},\n 'cmi.interactions._children':{'defaultvalue':interactions_children, 'mod':'r'},\n 'cmi.interactions._count':{'mod':'r', 'defaultvalue':'0'},\n 'cmi.interactions.n.id':{'pattern':CMIIndex, 'format':CMILongIdentifier, 'mod':'rw'},\n 'cmi.interactions.n.type':{'pattern':CMIIndex, 'format':CMIType, 'mod':'rw'},\n 'cmi.interactions.n.objectives._count':{'pattern':CMIIndex, 'mod':'r', 'defaultvalue':'0'},\n 'cmi.interactions.n.objectives.n.id':{'pattern':CMIIndex, 'format':CMILongIdentifier, 'mod':'rw'},\n 'cmi.interactions.n.timestamp':{'pattern':CMIIndex, 'format':CMITime, 'mod':'rw'},\n 'cmi.interactions.n.correct_responses._count':{'defaultvalue':'0', 'pattern':CMIIndex, 'mod':'r'},\n 'cmi.interactions.n.correct_responses.n.pattern':{'pattern':CMIIndex, 'format':'CMIFeedback', 'mod':'rw'},\n 'cmi.interactions.n.weighting':{'pattern':CMIIndex, 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.interactions.n.learner_response':{'pattern':CMIIndex, 'format':'CMIFeedback', 'mod':'rw'},\n 'cmi.interactions.n.result':{'pattern':CMIIndex, 'format':CMIResult, 'mod':'rw'},\n 'cmi.interactions.n.latency':{'pattern':CMIIndex, 'format':CMITimespan, 'mod':'rw'},\n 'cmi.interactions.n.description':{'pattern':CMIIndex, 'format':CMILangString250, 'mod':'rw'},\n 'cmi.launch_data':{'defaultvalue':def[scoid]['cmi.launch_data'], 'mod':'r'},\n 'cmi.learner_id':{'defaultvalue':def[scoid]['cmi.learner_id'], 'mod':'r'},\n 'cmi.learner_name':{'defaultvalue':def[scoid]['cmi.learner_name'], 'mod':'r'},\n 'cmi.learner_preference._children':{'defaultvalue':student_preference_children, 'mod':'r'},\n 'cmi.learner_preference.audio_level':{'defaultvalue':def[scoid]['cmi.learner_preference.audio_level'], 'format':CMIDecimal, 'range':audio_range, 'mod':'rw'},\n 'cmi.learner_preference.language':{'defaultvalue':def[scoid]['cmi.learner_preference.language'], 'format':CMILang, 'mod':'rw'},\n 'cmi.learner_preference.delivery_speed':{'defaultvalue':def[scoid]['cmi.learner_preference.delivery_speed'], 'format':CMIDecimal, 'range':speed_range, 'mod':'rw'},\n 'cmi.learner_preference.audio_captioning':{'defaultvalue':def[scoid]['cmi.learner_preference.audio_captioning'], 'format':CMISInteger, 'range':text_range, 'mod':'rw'},\n 'cmi.location':{'defaultvalue':def[scoid]['cmi.location'], 'format':CMIString1000, 'mod':'rw'},\n 'cmi.max_time_allowed':{'defaultvalue':def[scoid]['cmi.max_time_allowed'], 'mod':'r'},\n 'cmi.mode':{'defaultvalue':def[scoid]['cmi.mode'], 'mod':'r'},\n 'cmi.objectives._children':{'defaultvalue':objectives_children, 'mod':'r'},\n 'cmi.objectives._count':{'mod':'r', 'defaultvalue':'0'},\n 'cmi.objectives.n.id':{'pattern':CMIIndex, 'format':CMILongIdentifier, 'mod':'rw'},\n 'cmi.objectives.n.score._children':{'defaultvalue':score_children, 'pattern':CMIIndex, 'mod':'r'},\n 'cmi.objectives.n.score.scaled':{'defaultvalue':null, 'pattern':CMIIndex, 'format':CMIDecimal, 'range':scaled_range, 'mod':'rw'},\n 'cmi.objectives.n.score.raw':{'defaultvalue':null, 'pattern':CMIIndex, 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.objectives.n.score.min':{'defaultvalue':null, 'pattern':CMIIndex, 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.objectives.n.score.max':{'defaultvalue':null, 'pattern':CMIIndex, 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.objectives.n.success_status':{'defaultvalue':'unknown', 'pattern':CMIIndex, 'format':CMISStatus, 'mod':'rw'},\n 'cmi.objectives.n.completion_status':{'defaultvalue':'unknown', 'pattern':CMIIndex, 'format':CMICStatus, 'mod':'rw'},\n 'cmi.objectives.n.progress_measure':{'defaultvalue':null, 'format':CMIDecimal, 'range':progress_range, 'mod':'rw'},\n 'cmi.objectives.n.description':{'pattern':CMIIndex, 'format':CMILangString250, 'mod':'rw'},\n 'cmi.progress_measure':{'defaultvalue':def[scoid]['cmi.progress_measure'], 'format':CMIDecimal, 'range':progress_range, 'mod':'rw'},\n 'cmi.scaled_passing_score':{'defaultvalue':def[scoid]['cmi.scaled_passing_score'], 'format':CMIDecimal, 'range':scaled_range, 'mod':'r'},\n 'cmi.score._children':{'defaultvalue':score_children, 'mod':'r'},\n 'cmi.score.scaled':{'defaultvalue':def[scoid]['cmi.score.scaled'], 'format':CMIDecimal, 'range':scaled_range, 'mod':'rw'},\n 'cmi.score.raw':{'defaultvalue':def[scoid]['cmi.score.raw'], 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.score.min':{'defaultvalue':def[scoid]['cmi.score.min'], 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.score.max':{'defaultvalue':def[scoid]['cmi.score.max'], 'format':CMIDecimal, 'mod':'rw'},\n 'cmi.session_time':{'format':CMITimespan, 'mod':'w', 'defaultvalue':'PT0H0M0S'},\n 'cmi.success_status':{'defaultvalue':def[scoid]['cmi.success_status'], 'format':CMISStatus, 'mod':'rw'},\n 'cmi.suspend_data':{'defaultvalue':def[scoid]['cmi.suspend_data'], 'format':CMIString64000, 'mod':'rw'},\n 'cmi.time_limit_action':{'defaultvalue':def[scoid]['cmi.time_limit_action'], 'mod':'r'},\n 'cmi.total_time':{'defaultvalue':def[scoid]['cmi.total_time'], 'mod':'r'},\n 'adl.nav.request':{'defaultvalue':'_none_', 'format':NAVEvent, 'mod':'rw'}\n };\n }\n\n var cmi, adl;\n function initdatamodel(scoid){\n\n prerequrl = cfgwwwroot + \"/mod/scorm/prereqs.php?a=\" + scormid + \"&scoid=\" + scoid + \"&attempt=\" + attempt + \"&mode=\" + viewmode + \"&currentorg=\" + currentorg + \"&sesskey=\" + sesskey;\n datamodelurlparams = \"id=\" + cmid + \"&a=\" + scormid + \"&sesskey=\" + sesskey + \"&attempt=\" + attempt + \"&scoid=\" + scoid;\n\n //\n // Datamodel inizialization\n //\n cmi = new Object();\n cmi.comments_from_learner = new Object();\n cmi.comments_from_learner._count = 0;\n cmi.comments_from_lms = new Object();\n cmi.comments_from_lms._count = 0;\n cmi.interactions = new Object();\n cmi.interactions._count = 0;\n cmi.learner_preference = new Object();\n cmi.objectives = new Object();\n cmi.objectives._count = 0;\n cmi.score = new Object();\n\n // Navigation Object\n adl = new Object();\n adl.nav = new Object();\n adl.nav.request_valid = new Array();\n\n for (element in datamodel[scoid]) {\n if (element.match(/\\.n\\./) == null) {\n if (typeof datamodel[scoid][element].defaultvalue != 'undefined') {\n eval(element + ' = datamodel[\"' + scoid + '\"][\"' + element + '\"].defaultvalue;');\n } else {\n eval(element + ' = \"\";');\n }\n }\n }\n\n eval(cmiobj[scoid]);\n eval(cmiint[scoid]);\n eval(cmicommentsuser[scoid]);\n eval(cmicommentslms[scoid]);\n\n if (cmi.completion_status == '') {\n cmi.completion_status = 'not attempted';\n }\n }\n\n //\n // API Methods definition\n //\n var Initialized = false;\n var Terminated = false;\n var diagnostic = \"\";\n var errorCode = \"0\";\n\n function Initialize (param) {\n scoid = scorm_current_node ? scorm_current_node.scoid : scoid;\n initdatamodel(scoid);\n\n errorCode = \"0\";\n if (param == \"\") {\n if ((!Initialized) && (!Terminated)) {\n Initialized = true;\n errorCode = \"0\";\n if (scormdebugging) {\n LogAPICall(\"Initialize\", param, \"\", errorCode);\n }\n return \"true\";\n } else {\n if (Initialized) {\n errorCode = \"103\";\n } else {\n errorCode = \"104\";\n }\n }\n } else {\n errorCode = \"201\";\n }\n if (scormdebugging) {\n LogAPICall(\"Initialize\", param, \"\", errorCode);\n }\n return \"false\";\n }\n\n function Terminate (param) {\n errorCode = \"0\";\n if (param == \"\") {\n if ((Initialized) && (!Terminated)) {\n var AJAXResult = StoreData(cmi,true);\n if (scormdebugging) {\n LogAPICall(\"Terminate\", \"AJAXResult\", AJAXResult, 0);\n }\n result = ('true' == AJAXResult) ? 'true' : 'false';\n errorCode = ('true' == result) ? '0' : '101'; // General exception for any AJAX fault.\n if (scormdebugging) {\n LogAPICall(\"Terminate\", \"result\", result, errorCode);\n }\n if ('true' == result) {\n Initialized = false;\n Terminated = true;\n if (adl.nav.request != '_none_') {\n switch (adl.nav.request) {\n case 'continue':\n setTimeout('mod_scorm_launch_next_sco();',500);\n break;\n case 'previous':\n setTimeout('mod_scorm_launch_prev_sco();',500);\n break;\n case 'choice':\n break;\n case 'exit':\n break;\n case 'exitAll':\n break;\n case 'abandon':\n break;\n case 'abandonAll':\n break;\n }\n } else {\n if (scormauto == 1) {\n setTimeout('mod_scorm_launch_next_sco();',500);\n }\n }\n // trigger TOC update\n var callback = M.mod_scorm.connectPrereqCallback;\n YUI().use('io-base', function(Y) {\n Y.on('io:complete', callback.success, Y);\n Y.io(prerequrl);\n });\n } else {\n diagnostic = \"Failure calling the Terminate remote callback: the server replied with HTTP Status \" + AJAXResult;\n }\n return result;\n } else {\n if (Terminated) {\n errorCode = \"113\";\n } else {\n errorCode = \"112\";\n }\n }\n } else {\n errorCode = \"201\";\n }\n if (scormdebugging) {\n LogAPICall(\"Terminate\", param, \"\", errorCode);\n }\n return \"false\";\n }\n\n function GetValue (element) {\n errorCode = \"0\";\n diagnostic = \"\";\n if ((Initialized) && (!Terminated)) {\n if (element != \"\") {\n var expression = new RegExp(CMIIndex,'g');\n var elementmodel = String(element).replace(expression,'.n.');\n if (typeof datamodel[scoid][elementmodel] != \"undefined\") {\n if (datamodel[scoid][elementmodel].mod != 'w') {\n\n element = String(element).replace(/\\.(\\d+)\\./, \".N$1.\");\n element = element.replace(/\\.(\\d+)\\./, \".N$1.\");\n\n var elementIndexes = element.split('.');\n var subelement = element.substr(0,3);\n var i = 1;\n while ((i < elementIndexes.length) && (typeof eval(subelement) != \"undefined\")) {\n subelement += '.' + elementIndexes[i++];\n }\n\n if (subelement == element) {\n\n if ((typeof eval(subelement) != \"undefined\") && (eval(subelement) != null)) {\n errorCode = \"0\";\n if (scormdebugging) {\n LogAPICall(\"GetValue\", element, eval(element), 0);\n }\n return eval(element);\n } else {\n errorCode = \"403\";\n }\n } else {\n errorCode = \"301\";\n }\n } else {\n //errorCode = eval('datamodel[\"' + scoid + '\"][\"' + elementmodel + '\"].readerror');\n errorCode = \"405\";\n }\n } else {\n var childrenstr = '._children';\n var countstr = '._count';\n var parentmodel = '';\n if (elementmodel.substr(elementmodel.length - childrenstr.length,elementmodel.length) == childrenstr) {\n parentmodel = elementmodel.substr(0,elementmodel.length - childrenstr.length);\n if (datamodel[scoid][parentmodel] != \"undefined\") {\n errorCode = \"301\";\n diagnostic = \"Data Model Element Does Not Have Children\";\n } else {\n errorCode = \"401\";\n }\n } else if (elementmodel.substr(elementmodel.length - countstr.length,elementmodel.length) == countstr) {\n parentmodel = elementmodel.substr(0,elementmodel.length - countstr.length);\n if (typeof datamodel[scoid][parentmodel] != \"undefined\") {\n errorCode = \"301\";\n diagnostic = \"Data Model Element Cannot Have Count\";\n } else {\n errorCode = \"401\";\n }\n } else {\n parentmodel = 'adl.nav.request_valid.';\n if (element.substr(0,parentmodel.length) == parentmodel) {\n if (element.substr(parentmodel.length).match(NAVTarget) == null) {\n errorCode = \"301\";\n } else {\n if (adl.nav.request == element.substr(parentmodel.length)) {\n return \"true\";\n } else if (adl.nav.request == '_none_') {\n return \"unknown\";\n } else {\n return \"false\";\n }\n }\n } else {\n errorCode = \"401\";\n }\n }\n }\n } else {\n errorCode = \"301\";\n }\n } else {\n if (Terminated) {\n errorCode = \"123\";\n } else {\n errorCode = \"122\";\n }\n }\n if (scormdebugging) {\n LogAPICall(\"GetValue\", element, \"\", errorCode);\n }\n return \"\";\n }\n\n function SetValue (element,value) {\n errorCode = \"0\";\n diagnostic = \"\";\n if ((Initialized) && (!Terminated)) {\n if (element != \"\") {\n var expression = new RegExp(CMIIndex,'g');\n var elementmodel = String(element).replace(expression,'.n.');\n if (typeof datamodel[scoid][elementmodel] != \"undefined\") {\n if (datamodel[scoid][elementmodel].mod != 'r') {\n if (datamodel[scoid][elementmodel].format != 'CMIFeedback') {\n expression = new RegExp(datamodel[scoid][elementmodel].format);\n } else {\n // cmi.interactions.n.type depending format accept everything at this stage\n expression = new RegExp(CMIFeedback);\n }\n value = value + '';\n var matches = value.match(expression);\n if ((matches != null) && ((matches.join('').length > 0) || (value.length == 0))) {\n // Value match dataelement format\n\n if (element != elementmodel) {\n //This is a dynamic datamodel element\n\n var elementIndexes = element.split('.');\n var subelement = 'cmi';\n var parentelement = 'cmi';\n for (var i = 1; (i < elementIndexes.length - 1) && (errorCode == \"0\"); i++) {\n var elementIndex = elementIndexes[i];\n if (elementIndexes[i + 1].match(/^\\d+$/)) {\n if ((parseInt(elementIndexes[i + 1]) > 0) && (elementIndexes[i + 1].charAt(0) == 0)) {\n // Index has a leading 0 (zero), this is not a number\n errorCode = \"351\";\n }\n parentelement = subelement + '.' + elementIndex;\n if ((typeof eval(parentelement) == \"undefined\") || (typeof eval(parentelement + '._count') == \"undefined\")) {\n errorCode = \"408\";\n } else {\n if (elementIndexes[i + 1] > eval(parentelement + '._count')) {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Collection Set Out Of Order\";\n }\n subelement = subelement.concat('.' + elementIndex + '.N' + elementIndexes[i + 1]);\n i++;\n\n if (((typeof eval(subelement)) == \"undefined\") && (i < elementIndexes.length - 2)) {\n errorCode = \"408\";\n }\n }\n } else {\n subelement = subelement.concat('.' + elementIndex);\n }\n }\n\n if (errorCode == \"0\") {\n // Till now it's a real datamodel element\n\n element = subelement.concat('.' + elementIndexes[elementIndexes.length - 1]);\n\n if ((typeof eval(subelement)) == \"undefined\") {\n switch (elementmodel) {\n case 'cmi.objectives.n.id':\n if (!duplicatedID(element,parentelement,value)) {\n if (elementIndexes[elementIndexes.length - 2] == eval(parentelement + '._count')) {\n eval(parentelement + '._count++;');\n eval(subelement + ' = new Object();');\n var subobject = eval(subelement);\n subobject.success_status = datamodel[scoid][\"cmi.objectives.n.success_status\"].defaultvalue;\n subobject.completion_status = datamodel[scoid][\"cmi.objectives.n.completion_status\"].defaultvalue;\n subobject.progress_measure = datamodel[scoid][\"cmi.objectives.n.progress_measure\"].defaultvalue;\n subobject.score = new Object();\n subobject.score._children = score_children;\n subobject.score.scaled = datamodel[scoid][\"cmi.objectives.n.score.scaled\"].defaultvalue;\n subobject.score.raw = datamodel[scoid][\"cmi.objectives.n.score.raw\"].defaultvalue;\n subobject.score.min = datamodel[scoid][\"cmi.objectives.n.score.min\"].defaultvalue;\n subobject.score.max = datamodel[scoid][\"cmi.objectives.n.score.max\"].defaultvalue;\n }\n } else {\n errorCode = \"351\";\n diagnostic = \"Data Model Element ID Already Exists\";\n }\n break;\n case 'cmi.interactions.n.id':\n if (elementIndexes[elementIndexes.length - 2] == eval(parentelement + '._count')) {\n eval(parentelement + '._count++;');\n eval(subelement + ' = new Object();');\n var subobject = eval(subelement);\n subobject.objectives = new Object();\n subobject.objectives._count = 0;\n }\n break;\n case 'cmi.interactions.n.objectives.n.id':\n if (typeof eval(parentelement) != \"undefined\") {\n if (!duplicatedID(element,parentelement,value)) {\n if (elementIndexes[elementIndexes.length - 2] == eval(parentelement + '._count')) {\n eval(parentelement + '._count++;');\n eval(subelement + ' = new Object();');\n }\n } else {\n errorCode = \"351\";\n diagnostic = \"Data Model Element ID Already Exists\";\n }\n } else {\n errorCode = \"408\";\n }\n break;\n case 'cmi.interactions.n.correct_responses.n.pattern':\n if (typeof eval(parentelement) != \"undefined\") {\n // Use cmi.interactions.n.type value to check the right dataelement format\n if (elementIndexes[elementIndexes.length - 2] == eval(parentelement + '._count')) {\n var interactiontype = eval(String(parentelement).replace('correct_responses','type'));\n var interactioncount = eval(parentelement + '._count');\n // trap duplicate values, which is not allowed for type choice\n if (interactiontype == 'choice') {\n for (var i = 0; (i < interactioncount) && (errorCode == \"0\"); i++) {\n if (eval(parentelement + '.N' + i + '.pattern') == value) {\n errorCode = \"351\";\n }\n }\n }\n if ((typeof correct_responses[interactiontype].limit == 'undefined') ||\n (eval(parentelement + '._count') < correct_responses[interactiontype].limit)) {\n var nodes = new Array();\n if (correct_responses[interactiontype].delimiter != '') {\n nodes = value.split(correct_responses[interactiontype].delimiter);\n } else {\n nodes[0] = value;\n }\n if ((nodes.length > 0) && (nodes.length <= correct_responses[interactiontype].max)) {\n errorCode = CRcheckValueNodes (element, interactiontype, nodes, value, errorCode);\n } else if (nodes.length > correct_responses[interactiontype].max) {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Pattern Too Long\";\n }\n if ((errorCode == \"0\") && ((correct_responses[interactiontype].duplicate == false) ||\n (!duplicatedPA(element,parentelement,value))) || (errorCode == \"0\" && value == \"\")) {\n eval(parentelement + '._count++;');\n eval(subelement + ' = new Object();');\n } else {\n if (errorCode == \"0\") {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Pattern Already Exists\";\n }\n }\n } else {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Collection Limit Reached\";\n }\n } else {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Collection Set Out Of Order\";\n }\n } else {\n errorCode = \"408\";\n }\n break;\n default:\n if ((parentelement != 'cmi.objectives') && (parentelement != 'cmi.interactions') && (typeof eval(parentelement) != \"undefined\")) {\n if (elementIndexes[elementIndexes.length - 2] == eval(parentelement + '._count')) {\n eval(parentelement + '._count++;');\n eval(subelement + ' = new Object();');\n } else {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Collection Set Out Of Order\";\n }\n } else {\n errorCode = \"408\";\n }\n break;\n }\n } else {\n switch (elementmodel) {\n case 'cmi.objectives.n.id':\n if (eval(element) != value) {\n errorCode = \"351\";\n diagnostic = \"Write Once Violation\";\n }\n break;\n case 'cmi.interactions.n.objectives.n.id':\n if (duplicatedID(element,parentelement,value)) {\n errorCode = \"351\";\n diagnostic = \"Data Model Element ID Already Exists\";\n }\n break;\n case 'cmi.interactions.n.type':\n var subobject = eval(subelement);\n subobject.correct_responses = new Object();\n subobject.correct_responses._count = 0;\n break;\n case 'cmi.interactions.n.learner_response':\n if (typeof eval(subelement + '.type') == \"undefined\") {\n errorCode = \"408\";\n } else {\n // Use cmi.interactions.n.type value to check the right dataelement format\n interactiontype = eval(subelement + '.type');\n var nodes = new Array();\n if (learner_response[interactiontype].delimiter != '') {\n nodes = value.split(learner_response[interactiontype].delimiter);\n } else {\n nodes[0] = value;\n }\n if ((nodes.length > 0) && (nodes.length <= learner_response[interactiontype].max)) {\n expression = new RegExp(learner_response[interactiontype].format);\n for (var i = 0; (i < nodes.length) && (errorCode == \"0\"); i++) {\n if (typeof learner_response[interactiontype].delimiter2 != 'undefined') {\n values = nodes[i].split(learner_response[interactiontype].delimiter2);\n if (values.length == 2) {\n matches = values[0].match(expression);\n if (matches == null) {\n errorCode = \"406\";\n } else {\n var expression2 = new RegExp(learner_response[interactiontype].format2);\n matches = values[1].match(expression2);\n if (matches == null) {\n errorCode = \"406\";\n }\n }\n } else {\n errorCode = \"406\";\n }\n } else {\n matches = nodes[i].match(expression);\n if (matches == null) {\n errorCode = \"406\";\n } else {\n if ((nodes[i] != '') && (learner_response[interactiontype].unique)) {\n for (var j = 0; (j < i) && (errorCode == \"0\"); j++) {\n if (nodes[i] == nodes[j]) {\n errorCode = \"406\";\n }\n }\n }\n }\n }\n }\n } else if (nodes.length > learner_response[interactiontype].max) {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Pattern Too Long\";\n }\n }\n break;\n case 'cmi.interactions.n.correct_responses.n.pattern':\n subel = subelement.split('.');\n subel1 = 'cmi.interactions.' + subel[2];\n\n if (typeof eval(subel1 + '.type') == \"undefined\") {\n errorCode = \"408\";\n } else {\n // Use cmi.interactions.n.type value to check the right //dataelement format\n var interactiontype = eval(subel1 + '.type');\n var interactioncount = eval(parentelement + '._count');\n // trap duplicate values, which is not allowed for type choice\n if (interactiontype == 'choice') {\n for (var i = 0; (i < interactioncount) && (errorCode == \"0\"); i++) {\n if (eval(parentelement + '.N' + i + '.pattern') == value) {\n errorCode = \"351\";\n }\n }\n }\n var nodes = new Array();\n if (correct_responses[interactiontype].delimiter != '') {\n nodes = value.split(correct_responses[interactiontype].delimiter);\n } else {\n nodes[0] = value;\n }\n\n if ((nodes.length > 0) && (nodes.length <= correct_responses[interactiontype].max)) {\n errorCode = CRcheckValueNodes (element, interactiontype, nodes, value, errorCode);\n } else if (nodes.length > correct_responses[interactiontype].max) {\n errorCode = \"351\";\n diagnostic = \"Data Model Element Pattern Too Long\";\n }\n }\n break;\n }\n }\n }\n }\n //Store data\n if (errorCode == \"0\") {\n if (autocommit && !(SCORMapi1_3.timeout)) {\n SCORMapi1_3.timeout = Y.later(60000, API_1484_11, 'Commit', [\"\"], false);\n }\n\n if (typeof datamodel[scoid][elementmodel].range != \"undefined\") {\n range = datamodel[scoid][elementmodel].range;\n ranges = range.split('#');\n value = value * 1.0;\n if (value >= ranges[0]) {\n if ((ranges[1] == '*') || (value <= ranges[1])) {\n eval(element + '=value;');\n errorCode = \"0\";\n if (scormdebugging) {\n LogAPICall(\"SetValue\", element, value, errorCode);\n }\n return \"true\";\n } else {\n errorCode = '407';\n }\n } else {\n errorCode = '407';\n }\n } else {\n eval(element + '=value;');\n errorCode = \"0\";\n if (scormdebugging) {\n LogAPICall(\"SetValue\", element, value, errorCode);\n }\n return \"true\";\n }\n }\n } else {\n errorCode = \"406\";\n }\n } else {\n errorCode = \"404\";\n }\n } else {\n errorCode = \"401\"\n }\n } else {\n errorCode = \"351\";\n }\n } else {\n if (Terminated) {\n errorCode = \"133\";\n } else {\n errorCode = \"132\";\n }\n }\n if (scormdebugging) {\n LogAPICall(\"SetValue\", element, value, errorCode);\n }\n return \"false\";\n }\n\n function CRremovePrefixes (node) {\n // check for prefixes lang, case, order\n // case and then order\n var seenOrder = false;\n var seenCase = false;\n var seenLang = false;\n var errorCode = \"0\";\n while (matches = node.match('^(\\{(lang|case_matters|order_matters)=([^\\}]+)\\})')) {\n switch (matches[2]) {\n case 'lang':\n // check for language prefix on each node\n langmatches = node.match(CMILangcr);\n if (langmatches != null) {\n lang = langmatches[3];\n // check that language string definition is valid\n if (lang.length > 0 && lang != undefined) {\n if (validLanguages[lang.toLowerCase()] == undefined) {\n errorCode = \"406\";\n }\n }\n }\n seenLang = true;\n break;\n\n case 'case_matters':\n // check for correct case answer\n if (! seenLang && ! seenOrder && ! seenCase) {\n if (matches[3] != 'true' && matches[3] != 'false') {\n errorCode = \"406\";\n }\n }\n seenCase = true;\n break;\n\n case 'order_matters':\n // check for correct case answer\n if (! seenCase && ! seenLang && ! seenOrder) {\n if (matches[3] != 'true' && matches[3] != 'false') {\n errorCode = \"406\";\n }\n }\n seenOrder = true;\n break;\n\n default:\n break;\n }\n node = node.substr(matches[1].length);\n }\n return {'errorCode': errorCode, 'node': node};\n }\n\n function CRcheckValueNodes(element, interactiontype, nodes, value, errorCode) {\n expression = new RegExp(correct_responses[interactiontype].format);\n for (var i = 0; (i < nodes.length) && (errorCode == \"0\"); i++) {\n if (interactiontype.match('^(fill-in|long-fill-in|matching|performance|sequencing)$')) {\n result = CRremovePrefixes(nodes[i]);\n errorCode = result.errorCode;\n nodes[i] = result.node;\n }\n\n if (correct_responses[interactiontype].delimiter2 != undefined) {\n values = nodes[i].split(correct_responses[interactiontype].delimiter2);\n if (values.length == 2) {\n matches = values[0].match(expression);\n if (matches == null) {\n errorCode = \"406\";\n } else {\n var expression2 = new RegExp(correct_responses[interactiontype].format2);\n matches = values[1].match(expression2);\n if (matches == null) {\n errorCode = \"406\";\n }\n }\n } else {\n errorCode = \"406\";\n }\n } else {\n matches = nodes[i].match(expression);\n //if ((matches == null) || (matches.join('').length == 0)) {\n if ((matches == null && value != \"\") || (matches == null && interactiontype == \"true-false\")){\n errorCode = \"406\";\n } else {\n // numeric range - left must be <= right\n if (interactiontype == 'numeric' && nodes.length > 1) {\n if (parseFloat(nodes[0]) > parseFloat(nodes[1])) {\n errorCode = \"406\";\n }\n } else {\n if ((nodes[i] != '') && (correct_responses[interactiontype].unique)) {\n for (var j = 0; (j < i) && (errorCode == \"0\"); j++) {\n if (nodes[i] == nodes[j]) {\n errorCode = \"406\";\n }\n }\n }\n }\n }\n }\n } // end of for each nodes\n return errorCode;\n }\n\n function Commit (param) {\n if (SCORMapi1_3.timeout) {\n SCORMapi1_3.timeout.cancel();\n SCORMapi1_3.timeout = null;\n }\n errorCode = \"0\";\n if (param == \"\") {\n if ((Initialized) && (!Terminated)) {\n var AJAXResult = StoreData(cmi,false);\n if (scormdebugging) {\n LogAPICall(\"Commit\", \"AJAXResult\", AJAXResult, 0);\n }\n var result = ('true' == AJAXResult) ? 'true' : 'false';\n errorCode = ('true' == result) ? '0' : '101'; // General exception for any AJAX fault\n if (scormdebugging) {\n LogAPICall(\"Commit\", \"result\", result, errorCode);\n }\n if ('false' == result) {\n diagnostic = \"Failure calling the Commit remote callback: the server replied with HTTP Status \" + AJAXResult;\n }\n return result;\n } else {\n if (Terminated) {\n errorCode = \"143\";\n } else {\n errorCode = \"142\";\n }\n }\n } else {\n errorCode = \"201\";\n }\n if (scormdebugging) {\n LogAPICall(\"Commit\", param, \"\", errorCode);\n }\n return \"false\";\n }\n\n function GetLastError () {\n if (scormdebugging) {\n LogAPICall(\"GetLastError\", \"\", \"\", errorCode);\n }\n return errorCode;\n }\n\n function GetErrorString (param) {\n if (param != \"\") {\n var errorString = \"\";\n switch(param) {\n case \"0\":\n errorString = \"No error\";\n break;\n case \"101\":\n errorString = \"General exception\";\n break;\n case \"102\":\n errorString = \"General Inizialization Failure\";\n break;\n case \"103\":\n errorString = \"Already Initialized\";\n break;\n case \"104\":\n errorString = \"Content Instance Terminated\";\n break;\n case \"111\":\n errorString = \"General Termination Failure\";\n break;\n case \"112\":\n errorString = \"Termination Before Inizialization\";\n break;\n case \"113\":\n errorString = \"Termination After Termination\";\n break;\n case \"122\":\n errorString = \"Retrieve Data Before Initialization\";\n break;\n case \"123\":\n errorString = \"Retrieve Data After Termination\";\n break;\n case \"132\":\n errorString = \"Store Data Before Inizialization\";\n break;\n case \"133\":\n errorString = \"Store Data After Termination\";\n break;\n case \"142\":\n errorString = \"Commit Before Inizialization\";\n break;\n case \"143\":\n errorString = \"Commit After Termination\";\n break;\n case \"201\":\n errorString = \"General Argument Error\";\n break;\n case \"301\":\n errorString = \"General Get Failure\";\n break;\n case \"351\":\n errorString = \"General Set Failure\";\n break;\n case \"391\":\n errorString = \"General Commit Failure\";\n break;\n case \"401\":\n errorString = \"Undefinited Data Model\";\n break;\n case \"402\":\n errorString = \"Unimplemented Data Model Element\";\n break;\n case \"403\":\n errorString = \"Data Model Element Value Not Initialized\";\n break;\n case \"404\":\n errorString = \"Data Model Element Is Read Only\";\n break;\n case \"405\":\n errorString = \"Data Model Element Is Write Only\";\n break;\n case \"406\":\n errorString = \"Data Model Element Type Mismatch\";\n break;\n case \"407\":\n errorString = \"Data Model Element Value Out Of Range\";\n break;\n case \"408\":\n errorString = \"Data Model Dependency Not Established\";\n break;\n }\n if (scormdebugging) {\n LogAPICall(\"GetErrorString\", param, errorString, 0);\n }\n return errorString;\n } else {\n if (scormdebugging) {\n LogAPICall(\"GetErrorString\", param, \"No error string found!\", 0);\n }\n return \"\";\n }\n }\n\n function GetDiagnostic (param) {\n if (diagnostic != \"\") {\n if (scormdebugging) {\n LogAPICall(\"GetDiagnostic\", param, diagnostic, 0);\n }\n return diagnostic;\n }\n if (scormdebugging) {\n LogAPICall(\"GetDiagnostic\", param, param, 0);\n }\n return param;\n }\n\n function duplicatedID (element, parent, value) {\n var found = false;\n var elements = eval(parent + '._count');\n for (var n = 0; (n < elements) && (!found); n++) {\n if ((parent + '.N' + n + '.id' != element) && (eval(parent + '.N' + n + '.id') == value)) {\n found = true;\n }\n }\n return found;\n }\n\n function duplicatedPA (element, parent, value) {\n var found = false;\n var elements = eval(parent + '._count');\n for (var n = 0; (n < elements) && (!found); n++) {\n if ((parent + '.N' + n + '.pattern' != element) && (eval(parent + '.N' + n + '.pattern') == value)) {\n found = true;\n }\n }\n return found;\n }\n\n function getElementModel(element) {\n if (typeof datamodel[scoid][element] != \"undefined\") {\n return element;\n } else {\n var expression = new RegExp(CMIIndex,'g');\n var elementmodel = String(element).replace(expression,'.n.');\n if (typeof datamodel[scoid][elementmodel] != \"undefined\") {\n return elementmodel;\n }\n }\n return false;\n }\n\n function AddTime (first, second) {\n var timestring = 'P';\n var matchexpr = /^P((\\d+)Y)?((\\d+)M)?((\\d+)D)?(T((\\d+)H)?((\\d+)M)?((\\d+(\\.\\d{1,2})?)S)?)?$/;\n var firstarray = first.match(matchexpr);\n var secondarray = second.match(matchexpr);\n if ((firstarray != null) && (secondarray != null)) {\n var firstsecs = 0;\n if(parseFloat(firstarray[13],10) > 0){ firstsecs = parseFloat(firstarray[13],10); }\n var secondsecs = 0;\n if(parseFloat(secondarray[13],10) > 0){ secondsecs = parseFloat(secondarray[13],10); }\n var secs = firstsecs + secondsecs; //Seconds\n var change = Math.floor(secs / 60);\n secs = Math.round((secs - (change * 60)) * 100) / 100;\n var firstmins = 0;\n if(parseInt(firstarray[11],10) > 0){ firstmins = parseInt(firstarray[11],10); }\n var secondmins = 0;\n if(parseInt(secondarray[11],10) > 0){ secondmins = parseInt(secondarray[11],10); }\n var mins = firstmins + secondmins + change; //Minutes\n change = Math.floor(mins / 60);\n mins = Math.round(mins - (change * 60));\n var firsthours = 0;\n if(parseInt(firstarray[9],10) > 0){ firsthours = parseInt(firstarray[9],10); }\n var secondhours = 0;\n if(parseInt(secondarray[9],10) > 0){ secondhours = parseInt(secondarray[9],10); }\n var hours = firsthours + secondhours + change; //Hours\n change = Math.floor(hours / 24);\n hours = Math.round(hours - (change * 24));\n var firstdays = 0;\n if(parseInt(firstarray[6],10) > 0){ firstdays = parseInt(firstarray[6],10); }\n var seconddays = 0;\n if(parseInt(secondarray[6],10) > 0){ firstdays = parseInt(secondarray[6],10); }\n var days = Math.round(firstdays + seconddays + change); // Days\n var firstmonths = 0;\n if(parseInt(firstarray[4],10) > 0){ firstmonths = parseInt(firstarray[4],10); }\n var secondmonths = 0;\n if(parseInt(secondarray[4],10) > 0){ secondmonths = parseInt(secondarray[4],10); }\n var months = Math.round(firstmonths + secondmonths);\n var firstyears = 0;\n if(parseInt(firstarray[2],10) > 0){ firstyears = parseInt(firstarray[2],10); }\n var secondyears = 0;\n if(parseInt(secondarray[2],10) > 0){ secondyears = parseInt(secondarray[2],10); }\n var years = Math.round(firstyears + secondyears);\n }\n if (years > 0) {\n timestring += years + 'Y';\n }\n if (months > 0) {\n timestring += months + 'M';\n }\n if (days > 0) {\n timestring += days + 'D';\n }\n if ((hours > 0) || (mins > 0) || (secs > 0)) {\n timestring += 'T';\n if (hours > 0) {\n timestring += hours + 'H';\n }\n if (mins > 0) {\n timestring += mins + 'M';\n }\n if (secs > 0) {\n timestring += secs + 'S';\n }\n }\n return timestring;\n }\n\n function TotalTime() {\n var total_time = AddTime(cmi.total_time, cmi.session_time);\n return '&' + underscore('cmi.total_time') + '=' + encodeURIComponent(total_time);\n }\n\n function CollectData(data,parent) {\n var datastring = '';\n for (property in data) {\n if (typeof data[property] == 'object') {\n datastring += CollectData(data[property],parent + '.' + property);\n } else {\n var element = parent + '.' + property;\n var expression = new RegExp(CMIIndexStore,'g');\n var elementmodel = String(element).replace(expression,'.n.');\n if (typeof datamodel[scoid][elementmodel] != \"undefined\") {\n if (datamodel[scoid][elementmodel].mod != 'r') {\n var elementstring = '&' + underscore(element) + '=' + encodeURIComponent(data[property]);\n if (typeof datamodel[scoid][elementmodel].defaultvalue != \"undefined\") {\n if (datamodel[scoid][elementmodel].defaultvalue != data[property] ||\n typeof datamodel[scoid][elementmodel].defaultvalue != typeof data[property]) {\n datastring += elementstring;\n }\n } else {\n datastring += elementstring;\n }\n }\n }\n }\n }\n return datastring;\n }\n\n function StoreData(data,storetotaltime) {\n var datastring = '';\n if (storetotaltime) {\n if (cmi.mode == 'normal') {\n if (cmi.credit == 'credit') {\n if ((cmi.completion_threshold) && (cmi.progress_measure)) {\n if (cmi.progress_measure >= cmi.completion_threshold) {\n cmi.completion_status = 'completed';\n } else {\n cmi.completion_status = 'incomplete';\n }\n }\n if ((cmi.scaled_passed_score != null) && (cmi.score.scaled != '')) {\n if (cmi.score.scaled >= cmi.scaled_passed_score) {\n cmi.success_status = 'passed';\n } else {\n cmi.success_status = 'failed';\n }\n }\n }\n }\n datastring += TotalTime();\n }\n datastring += CollectData(data,'cmi');\n var element = 'adl.nav.request';\n var navrequest = eval(element) != datamodel[scoid][element].defaultvalue ? '&' + underscore(element) + '=' + encodeURIComponent(eval(element)) : '';\n datastring += navrequest;\n\n var myRequest = NewHttpReq();\n result = DoRequest(myRequest, datamodelurl, datamodelurlparams + datastring);\n\n var results = String(result).split('\\n');\n if ((results.length > 2) && (navrequest != '')) {\n eval(results[2]);\n }\n errorCode = results[1];\n return results[0];\n }\n\n this.Initialize = Initialize;\n this.Terminate = Terminate;\n this.GetValue = GetValue;\n this.SetValue = SetValue;\n this.Commit = Commit;\n this.GetLastError = GetLastError;\n this.GetErrorString = GetErrorString;\n this.GetDiagnostic = GetDiagnostic;\n this.version = '1.0';\n}", "function createFireEngine( ) {\n createEngineBlock( );\n\n // piston\n piston = []; // reset the parts\n if ( $('#showPiston').prop('checked') ) {\n for ( let step = -0.1; step < 0.4; step += 0.1) {\n makeHorizontalCircle( piston, 0, 0, -engineSize*step, engineSize/4, 'green' );\n }\n }\n\n // piston rod\n pistonRod = [];\n if ( $('#showRod').prop('checked') ) {\n for ( let step = 0.1; step < rodFactor; step += 0.1) {\n makeHorizontalCircle( pistonRod, 0, 0, engineSize*step, engineSize/12, 'slateGrey' );\n }\n for ( let step = -0.1; step < 0.11; step += 0.05) {\n makeVerticalCircle( pistonRod, engineSize*step, 0, 0, engineSize/12, 'slateGrey' );\n makeVerticalCircle( pistonRod, engineSize*step, 0, rodFactor*engineSize, engineSize/12, 'slateGrey' );\n }\n }\n \n // crank shaft\n crankShaft = [];\n if ( $('#showShaft').prop('checked') ) {\n for ( let step = 0.1; step < 0.3; step += 0.1) {\n makeCounterWeight( crankShaft, engineSize*step, 0, 0, engineSize/3, 'slateGrey' );\n makeCounterWeight( crankShaft, -engineSize*step, 0, 0, engineSize/3, 'slateGrey' );\n }\n for ( let step = 0.2; step < 0.3; step += 0.05) {\n makeVerticalCircle( crankShaft, engineSize*step, 0, 0, engineSize/16, 'rgba(40,40,40,0.7)' );\n makeVerticalCircle( crankShaft, -engineSize*step, 0, 0, engineSize/16, 'rgba(40,40,40,0.7)' );\n }\n }\n\n // create a horizontal circle\n function makeHorizontalCircle( part, x, y, z, radius, color ) {\n const step = 5 / radius;\n const maxAngle = $('#showPartially').prop('value');\n\n for ( let angle = 0; angle < maxAngle; angle += step ) {\n let degree = angle * 360 / 8 / Math.PI;\n if ( angle > Math.PI ) degree = 360/4 - degree;\n color = 'hsla( ' + degree + ',100% ,50%, 0.6 )';\n addBall( part, x + radius*Math.cos( angle ), y + radius*Math.sin( angle ), z, color );\n }\n }\n\n // create a horizontal circle\n function makeVerticalCircle( part, x, y, z, radius, color ) { \n const step = 5 / radius;\n const maxAngle = $('#showPartially').prop('value');\n\n for ( let angle = 0; angle < maxAngle; angle += step ) {\n if ( radius > engineSize / 14 ) { // gradient only for big ones\n let degree = angle * 360 / 8 / Math.PI;\n if ( angle > Math.PI ) degree = 360/4 - degree;\n color = 'hsla( ' + degree + ',100% ,50%, 0.6 )';\n }\n addBall( part, x, y + radius*Math.cos( angle ), z + radius*Math.sin( angle ), color );\n }\n }\n\n // create a horizontal circle\n function makeCounterWeight( part, x, y, z, radius, color ) { \n const step = 5 / radius;\n const maxAngle = $('#showPartially').prop('value');\n\n for ( let angle = 0; angle < maxAngle; angle += step ) {\n if ( radius > engineSize / 14 ) { // gradient only for big ones\n let degree = angle * 360 / 8 / Math.PI;\n if ( angle > Math.PI ) degree = 360/4 - degree;\n color = 'hsla( ' + degree + ',100% ,50%, 0.6 )';\n }\n let pointZ = radius*Math.sin( angle );\n let pointY = radius*Math.cos( angle );\n if ( pointZ > 0 ) {\n if ( pointY > 0 ) addBall( part, x, y + (radius-pointZ), z + (radius-pointY), color );\n else addBall( part, x, y + (-radius+pointZ), z + (radius + pointY), color );\n }\n else addBall( part, x, y + pointY, z + pointZ, color );\n }\n }\n}", "initialize() {\n //console.log(`@@@ narrative.initialize():`);\n // canvas DOM-singularity, and webgl2-context\n canvas = document.getElementById(config.renderer.canvas_id);\n context = canvas.getContext('webgl2', { antialias: true });\n // topology\n _sg = config.topology._sg;\n _rm = config.topology._rm;\n _vr = config.topology._vr;\n _sgpost = config.topology._sgpost;\n _rmpost = config.topology._rmpost;\n topology = config.topology.topology; //topology=_sg + _rm*2 + _vr*4\n //console.log(`rendering topology type = ${topology}`);\n // canvas needed in camera.delta for vrcontrols and possibly others\n narrative['canvas'] = canvas;\n // displayed_scene needed in state/camera to add audioListener to \n // lens from displayed_scene\n narrative['audioListener'] = audioListener;\n displayed_scene = config.topology.displayed_scene;\n narrative['displayed_scene'] = displayed_scene; //'sg'|'rm'|'vr'\n //console.log(`n['displayed_scene'] = ${narrative['displayed_scene']}`);\n // create WebGLRenderer for all scenes\n renderer = create_renderer();\n //EXPT!\n renderer.setPixelRatio(dpr); // critically important for post!!\n //renderer.autoClear = false;\n //DataTexture filters\n dTexture.minFilter = THREE.NearestFilter;\n dTexture.magFilter = THREE.NearestFilter;\n //initial center (x,y) of DataTexture \n tVector.x = 0.0; //0.5*tw;\n tVector.y = 0.0; //0.5*th;\n //console.log(`dpr = ${dpr} tVector.x = ${tVector.x} tVector.y = ${tVector.y}`);\n // populate Narrative instance for use in state modules\n narrative['devclock'] = devclock;\n if (_sg) {\n narrative['sg'] = {};\n const nsg = narrative['sg'];\n sgscene = new THREE.Scene;\n nsg['scene'] = sgscene;\n nsg['lens'] = sglens;\n nsg['orbit'] = sgorbit;\n sgTargetNames = config.topology.sgTargetNames;\n }\n if (_rm) {\n narrative['rm'] = {};\n const nrm = narrative['rm'];\n rmscene = new THREE.Scene;\n nrm['scene'] = rmscene;\n //fixed rmlens \n const aspect = window.innerWidth / window.innerHeight;\n rmlens = new THREE.PerspectiveCamera(90, aspect, .01, 1000);\n rmlens.position.z = 1.0;\n rmlens.lookAt(new THREE.Vector3(0, 0, 0));\n nrm['lens'] = rmlens;\n rmTargetNames = config.topology.rmTargetNames;\n }\n if (_vr) {\n narrative['vr'] = {};\n const nvr = narrative['vr'];\n vrscene = new THREE.Scene;\n nvr['scene'] = vrscene;\n nvr['lens'] = vrlens;\n nvr['orbit'] = vrorbit;\n }\n // returns to bootstrap()\n }", "function robot_rrt_planner_init() {\n\n // form configuration from base location and joint angles\n q_start_config = [\n robot.origin.xyz[0],\n robot.origin.xyz[1],\n robot.origin.xyz[2],\n robot.origin.rpy[0],\n robot.origin.rpy[1],\n robot.origin.rpy[2]\n ];\n\n q_names = {}; // store mapping between joint names and q DOFs\n\n for (x in robot.joints) {\n q_names[x] = q_start_config.length;\n q_start_config = q_start_config.concat(robot.joints[x].angle);\n }\n\n // set goal configuration as the zero configuration\n var i; \n q_goal_config = new Array(q_start_config.length);\n for (i=0;i<q_goal_config.length;i++) q_goal_config[i] = 0;\n\n // CS148: add necessary RRT initialization here\n\n // make sure the rrt iterations are not running faster than animation update\n cur_time = Date.now();\n\n\n epsilon = 1;\n robot_path_traverse_idx = 0;\n rrt_iterate = true;\n tree1 = tree_init(vertex_init(q_start_config));\n tree2 = tree_init(vertex_init(q_goal_config));\n x_min = robot_boundary[0][0];\n x_max = robot_boundary[1][0];\n y_min = robot_boundary[0][2];\n y_max = robot_boundary[1][2];\n\n rrt_iter_count = 0;\n\n console.log(\"planner initialized\");\n}", "function qualrout_init()\n//\n// Input: none\n// Output: none\n// Purpose: initializes water quality concentrations in all nodes and links.\n//\n{\n let i, p, isWet;\n let c;\n\n for (i = 0; i < Nobjects[NODE]; i++)\n {\n isWet = ( Node[i].newDepth > FUDGE );\n for (p = 0; p < Nobjects[POLLUT]; p++)\n {\n c = 0.0;\n if ( isWet ) c = Pollut[p].initConcen;\n Node[i].oldQual[p] = c;\n Node[i].newQual[p] = c;\n }\n }\n\n for (i = 0; i < Nobjects[LINK]; i++)\n {\n isWet = ( Link[i].newDepth > FUDGE );\n for (p = 0; p < Nobjects[POLLUT]; p++)\n {\n c = 0.0;\n if ( isWet ) c = Pollut[p].initConcen;\n Link[i].oldQual[p] = c;\n Link[i].newQual[p] = c;\n }\n }\n}", "function initSCO() {\n lmsConnected = scorm.init();\n}", "function initFeatures() {\n\n features.push(function(s) { // v0 left knee\n var val = 0.8*(s.lk_ang + 0.25);\n return val;\n });\n\n features.push(function(s) { // v1 right knee\n var val = 0.8*(s.rk_ang + 0.25);\n return val;\n });\n\n features.push(function(s) { // v2 left hip\n var val = 0.5*(s.lh_ang + 1);\n return val;\n });\n\n features.push(function(s) { // v3 right hip\n var val = 0.5*(s.rh_ang + 1);\n return val;\n });\n\n features.push(function(s) { // v4 torso ang\n var val = 0.4*(1.25+max(-1.25,min(1.25,s.T_ang)));\n return val;\n });\n\n features.push(function(s) { // v5 feet heights\n var val = min(max(floor(s.LF_y/20),0),SQRTRES-1);\n val = (val*SQRTRES) + min(max(floor(s.RF_y/20),0),SQRTRES-1);\n return val/RESOLUTION;\n });\n}", "function loadRomFrame() {\n\n}", "levelMaker(floorCount, offsetArray, widthArray)\n { \n //Formula: firstPlat.XPos + firstPlat.width / 2 + 21 + secondPlat.width / 2 = secondPlat.XPos\n //Each floor is offset by 760 - 100 * floor number.\n let storeyHeight = 140;\n let floorY = 790;\n for(let i = 1; i <= floorCount; i++)\n {\n let floorPlans = widthArray[i - 1];\n let lastXPos = offsetArray[i - 1] + floorPlans[0] / 2;\n this.addPlatformConfiguration(lastXPos, floorY - storeyHeight * i, i, false, true, floorPlans[0] - this.PlatformOffset);\n for(let j = 1; j < floorPlans.length; j++)\n {\n //The ladder's position is determined from the gaps left in the floor.\n //Place the ladder 25 + firstPlat.XPos + firstPlat.width in x...\n //and 50 below the current floor's yPos. (in js, + 50)\n this.addLadderConfiguration(10 + lastXPos + floorPlans[j - 1] / 2, floorY - storeyHeight * i + 65, i - 1,j);\n\n lastXPos = lastXPos + floorPlans[j-1] / 2 + this.ladderWidth + floorPlans[j] / 2;\n this.addPlatformConfiguration(lastXPos, floorY - storeyHeight * i, i, false, true, floorPlans[j] - this.PlatformOffset);\n }\n }\n }", "function rActive (fm10ros) {\n return 3.34 * fm10ros\n}", "subdivision() {\n this.edges.forEach(edge => {\n if(this.bundled[edge.id]) {\n edge.controlpoints = this.subdivide(edge.cp, this.bundleStrength);\n edge.controlpoints = this.approximateBezier(edge.controlpoints, this.numApproximationPoints)\n }\n });\n }", "handle_redefines_in_parts(part) {\n this.syntaxReader.skip_newlines_blankspace();\n let redefine_name = this.syntaxReader.read_name();\n\n //This is for the first part of the parts of parts series where a subset exist\n if (part.subsets.length > 0) {\n for (var i = 0; i < part.subsets.length; i++) {\n for (var j = 0; j < part.subsets[i].parts.length; j++) {\n if (redefine_name === part.subsets[i].parts[j].name) {\n var copy_part = part.subsets[i].parts[j];//part.subsets[i].get_part_by_name(part.name);\n let block = this.active_package.get_block_by_name(copy_part.block);\n var redefine_part = new Part(copy_part.name, block, null, null);\n part.parts = redefine_part;\n redefine_part.redefines = copy_part;\n }\n }\n }\n }\n\n //This function runs as long as the redefines array have parts\n if (part.redefines.parts != undefined) {\n for (var i = 0; i < part.redefines.parts.length; i++) {\n if (redefine_name === part.redefines.parts[i].name) {\n var copy_part = part.redefines.parts[i];\n var redefine_part = new Part(copy_part.name, copy_part.block, null, null);\n part.parts = redefine_part;\n redefine_part.add_redefine(part.redefines.parts[i]);\n }\n\n }\n\n }\n\n if (part.block != undefined) {\n if (part.block.get_part_by_name(redefine_name)) {\n var copy_part_properties = part.block.get_part_by_name(redefine_name);\n var redefine_part = new Part(copy_part_properties.name, copy_part_properties.block, null, null);\n part.add_redefine(redefine_part);\n }\n }\n\n let amount = this.syntaxReader.read_amount();\n\n if (amount === undefined) {\n redefine_part.amount = 1;\n } else if (amount.length === 2) {\n redefine_part.amount = amount[0];\n redefine_part.upper_amount = amount[1];\n } else {\n redefine_part.amount = amount;\n }\n\n\n this.syntaxReader.skip_newlines_blankspace();\n let next_char = this.syntaxReader.read_next_char();\n\n if (next_char === \";\") {\n //done\n return\n } else if (next_char === \"{\") {\n this.handle_part_content(redefine_part);\n }\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion que desaparece los repetidos marcados con cero
function desaparecerRepetidos(){ sustituirCero(obtenerRepetidos()); }
[ "function operacionResta() {\r\n for (var j = 0; j < vecAuxiliar.length; j++) {\r\n var nu1 = vecAuxiliar[j].dato;\r\n var nu2 = vecTramaG[j].dato;\r\n var r = nu1 - nu2;\r\n if (r < 0) {\r\n agregar(1, 5);\r\n // vecresta += 1;\r\n } else {\r\n agregar(r, 5);\r\n //vecresta += r;\r\n }\r\n console.log(\"RESTA \" + vecresta[j].dato);\r\n } //FIN FOR\r\n vecAuxiliar = [];\r\n operacionAcomodar();\r\n } // FIN FUNCION OPERACION RESTAR ", "function sacar(){\n \n var nuevo=productosSeleccionados(); \n var actual= viejos;\n eliminar = [];\n insertar=[];\n for (var i = 0; i < actual.length; i++) {\n var igual=false;\n for (var j = 0; j < nuevo.length & !igual; j++) {\n if(actual[i].ID_PRO == nuevo[j].ID_PRO) \n igual=true;\n }\n if(!igual) {\n var item={}; \n item.ID_PRO=actual[i].ID_PRO;\n eliminar.push(item);\n } \n //else insertar.push(nuevo[j]);\n }\n\n for (var i = 0; i < nuevo.length; i++) {\n var igual=false;\n for (var j = 0; j < actual.length & !igual; j++) {\n if(nuevo[i].ID_PRO == actual[j].ID_PRO) \n igual=true;\n }\n if(!igual){\n var item={}; \n item.ID_PRO=nuevo[i].ID_PRO;\n insertar.push(item);\n } \n //else insertar.push(nuevo[j]);\n }\n\n eliminar=removeDuplicates(eliminar,\"ID_PRO\");\n insertar=removeDuplicates(insertar,\"ID_PRO\");\n\n console.log(\"array para eliminar \"+JSON.stringify(eliminar));\n console.log(\"array para insertar \"+JSON.stringify(insertar));\n\n}", "setItems(items){\n const currentFiller = this.numberLeftWithOddEnding()\n /**\n * Will return the indexes (from the old array) of items that were removed\n * @param oldArray\n * @param newArray\n */\n const removedIndexes = (oldArray, newArray) => {\n let rawArray = oldArray.map((oldItem, index) => {\n if(!newArray.some(newItem => newItem === oldItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n /**\n * Will return the indexes (from the new array) of items that were added\n * @param oldArray\n * @param newArray\n */\n const addedIndexes = (oldArray, newArray) => {\n let rawArray = newArray.map((newItem, index) => {\n if(!oldArray.some(oldItem => oldItem === newItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n this.previousItems = this.items.slice();\n this.items = items.slice();\n\n let indexesToRemove = removedIndexes(this.previousItems, this.items);\n let indexesToAdd = addedIndexes(this.previousItems, this.items);\n\n // console.log('add:', indexesToAdd, 'remove:', indexesToRemove)\n\n if(indexesToRemove.length > 0) {\n indexesToRemove.forEach(index => {\n this.removeLastItem(index);\n })\n }\n\n if(indexesToAdd.length > 0) {\n indexesToAdd.forEach(index => {\n this.addItemAtIndex(index);\n })\n }\n\n // When adding we have to update the index every time\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n realElements.forEach((element, index) => {\n let className = Array.from(element.classList).filter(_className => _className.match(new RegExp(`budgie-${this.budgieId}-\\\\d`)));\n if(className !== `budgie-${this.budgieId}-${index}`) {\n element.classList.remove(className);\n element.classList.add(`budgie-${this.budgieId}-${index}`);\n }\n })\n\n // remove duplicate elements\n const dupedElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}.budgie-item-${this.budgieId}--duplicate`));\n dupedElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // remove filler elements\n const fillerElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}--filler`));\n fillerElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // Insert duplicated elements anew, if this is an infinite scroll\n if(this.options.infiniteScroll) {\n this.prependStartingItems();\n this.appendEndingItems();\n }\n\n // Add filler items to the end if needed\n if(this.numberLeftWithOddEnding() > 0) {\n realElements[realElements.length - this.numberLeftWithOddEnding()]\n .insertAdjacentElement('beforebegin', BudgieDom.createBudgieFillerElement(this))\n\n realElements[realElements.length - 1]\n .insertAdjacentElement('afterend', BudgieDom.createBudgieFillerElement(this))\n }\n\n this.clearMeasurements();\n this.budgieAnimate();\n }", "function masUnAcierto(){\n\taciertosAcumulados++;\n\tdibujar();\n}", "function obtenerRango(arreglo,casos)\n{\n for(i=1; i <= casos; i++)\n {\n inicial_final = arreglo[i].split(\" \");\n inicio = parseInt(inicial_final[0]);\n fin = parseInt(inicial_final[1]);\n buscarCuadrados(inicio,fin); //Buscar cuadrados perfectos dentro del rango\n }\n}", "function borrarRegistro(){\n \n /*aId.splice(posicion,1);\n aDireccion.splice(posicion,1);\n aLatitud.splice(posicion,1);\n aLongitud.splice(posicion,1);\n */\n\n aContenedor.splice(posicion,1)\n contador--;\n\n\n posicion=0;\n mostrarRegistro(posicion);\n\n}", "function riunisci_nodi_sdoppiati() {\n\n for (a = 0; a < lista_adj.length; a++) {\n\n // nella lista delle adiacenze cerco i nodi replicati \n if (lista_adj[a].id.includes('_')) {\n\n // cerco il nodo da cui l'ho capiato\n for (b = 0; b < lista_adj.length; b++) {\n\n // il nodo da cui l'ho copiato sarà senza il trattino basso\n if (!(lista_adj[b].id.includes('_'))) {\n\n // devo capire se è il nodo che cercavo in questo modo:\n // il nodo principale sarà ad esempio => 1i\n // il nodo sdoppiato sarà => 1i_1\n // si può ben vedere come la prima parte della mia stringa\n // sia uguale per entrambi,\n // mentre cambia il trattino basso e il numero\n // nel nodo sdoppiato cerco la prima parte della stringa\n // che arrivi fino al trattino\n barra = lista_adj[a].id.indexOf('_');\n nodo = lista_adj[a].id.substr(0, barra);\n\n // se ho trovato il nodo\n if (lista_adj[b].id === nodo) {\n\n // inserisco come nodo collegato il nodo collegato\n // al nodo sdoppiato\n lista_adj[b].nodi_collegati.\n push(lista_adj[a].nodi_collegati[0]);\n\n // devo infine scegliere quale numero di archi assegnare\n // scelgo quindi il numero più grande\n if (lista_adj[a].num_archi_fino_a_qui >\n lista_adj[b].num_archi_fino_a_qui) {\n\n lista_adj[b].num_archi_fino_a_qui =\n lista_adj[a].num_archi_fino_a_qui;\n }\n }\n }\n }\n }\n }\n}", "function accionEliminar()\t{\n\t\tvar arr = new Array();\n\t\tarr = listado1.codSeleccionados();\n\t\teliminarFilas(arr,\"DTOEliminarMatricesDescuento\", mipgndo, 'resultadoOperacionMsgPersonalizado(datos)');\n\t}", "function effaceLesImages(){\n var p = document.getElementsByClassName(\"ImageBanque\");\n for(var i = p.length - 1; 0 <= i; i--) {\n p[i].remove();\n }\n }", "function NumerosSorteo(){\r\n\r\n let numant = 0;\r\n let numerosconcat = [];\r\n let numsrepetidos = [];\r\n let numerossinrep = [];\r\n let numeros = [];\r\n\r\n let numc = localStorage.getItem('nrocarton')\r\n\r\n for(let i=0; i<numc; i++){\r\n \r\n let nro = document.getElementById(\"c\"+i)\r\n if(nro!=null){\r\n for(let j=0; j<18; j++){\r\n let n = document.getElementById(i+\"\"+j)\r\n numerosconcat.push(parseInt(n.innerHTML));\r\n }\r\n }\r\n }\r\n //Los ordena\r\n numerosconcat.sort();\r\n //Crea un array con los numeros repetidos\r\n for(let j=0; j<numerosconcat.length; j++){\r\n if(numerosconcat[j]==numant){\r\n if(numsrepetidos.includes(numant)!=true){\r\n numsrepetidos.push(numant)\r\n }\r\n }\r\n numant = numerosconcat[j] \r\n }\r\n //Crea un array con los numeros no repetidos\r\n for(let i=1; i<91; i++){\r\n if(numsrepetidos.includes(i)!=true){\r\n numerossinrep.push(i);\r\n }\r\n }\r\n //Mezcla ambos arrays\r\n numsrepetidos = numsrepetidos.sort(function(){return Math.random()-0.5});\r\n numerossinrep = numerossinrep.sort(function(){return Math.random()-0.5});\r\n //Concatena poniendo primero los repetidos\r\n numeros = numsrepetidos.concat(numerossinrep);\r\n\r\n for(let i=0; i<90; i++){\r\n \r\n localStorage.setItem(i,numeros[i]) \r\n }\r\n \r\n}", "quitarValores(iteracion, maxIteracion, valoresPrevios, valoresMenosUno){\n let validar=false; //Esta variable va a ser la que indique si el valor que se quita permite una soluci[on [unica o no\n do {\n validar=false;\n const cuadrado = Math.floor(Math.random() * (9));\n const posicion = Math.floor(Math.random() * (9));\n if(this.valoresFinales[cuadrado][posicion] !=\"\"){\n this.valoresFinales[cuadrado][posicion] = \"\";\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n valoresMenosUno[i][j] = this.valoresFinales[i][j];\n }\n }\n this.solucionarSudoku();\n if (this.isTableroLleno()) {\n validar = true;\n } else {\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n this.valoresFinales[i][j] = valoresPrevios[i][j];\n }\n }\n }\n }\n } while (!validar);\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n this.valoresFinales[i][j] = valoresMenosUno[i][j];\n valoresPrevios[i][j] = valoresMenosUno[i][j];\n }\n }\n if(iteracion !== maxIteracion){\n iteracion++\n this.quitarValores(iteracion, maxIteracion, valoresPrevios, valoresMenosUno);\n }\n }", "function agregarPedidoRandom(){\n for (let i = 0; i < 3 ; i++){\n let productoRandom = generarProducto();\n let cantidadRandom = generarCantidad(productoRandom);\n let precio = calcularValor(productoRandom,cantidadRandom);\n let items = \n { \"producto\": productoRandom, \n \"cantidad\": cantidadRandom, \n \"precio\": precio}; \n agregarAlHeruku(items);\n } \n}", "function reset_risultati() {\n // resetto l'input testuale\n $('#message').val('');\n // nascondo il titolo della pagina\n $('.titolo-ricerca').removeClass('visible');\n // svuoto il contenitore dei risultati\n $('#results').empty();\n // $('#risultati .card').remove();\n // $('#risultati').html('');\n }", "function buscarCoincidencias(palabra) {\n\t elegidos=[];\n\t if (palabra == \"Todas las rutas\") {\n\t elegidos = rutas;\n\t }else {\n\t for (var i = 0; i < rutas.length; i++) {\n\t if (rutas[i].categoria.indexOf(palabra) !== -1) {\n\t elegidos.push(rutas[i]);\n\t }\n\t }\n\t }\n\t return elegidos;\n\t}", "function recess(){\n\tdataSets.forEach(function(d){\n\t\t\n\t\t})//CLOSE dataSets forEach\n\t}//CLOSE recess", "function removerEventos() {\n for (let i = 3; i < 8; i++) {\n div[i].removeEventListener('click', eventoClickDiv)\n }\n }", "cajasEnDestino() {\n for (var i = 0; i < this.cajas.length; i++) {\n const caja = this.cajas[i];\n if (\n Math.abs(caja.x - this.destinoCajas.x) <= caja.ancho / 2 &&\n caja.y + caja.alto / 2 == this.destinoCajas.y\n ) {\n reproducirEfecto(caja.deliver_sfx);\n this.stats.calcularScore(caja.puntos);\n this.cajas.splice(i, 1);\n this.espacio.eliminarCuerpoDinamico(caja);\n i = i - 1;\n }\n }\n }", "function animacionLinea(elementos) {\n for (var i = 0; i < elementos.length; i++) {\n $(elementos[i]).addClass(\"eliminado\");\n $('img.eliminado').effect('pulsate', 600);\n $('img.eliminado').animate({\n opacity: '0'\n }, {\n duration: 400\n })\n .animate({\n opacity: '0'\n }, {\n duration: 600,\n complete: function () {\n eliminarElemento()\n },\n queue: true\n });\n }\n}", "function getAppelloDaPrenotare(cdsId,adId){\n return new Promise(function(resolve, reject) {\n var appelliDaPrenotare=[];\n var rawData='';\n\n getSingoloAppelloDaPrenotare(cdsId,adId).then((body)=>{\n //controllo che body sia un array\n if (Array.isArray(body)){\n rawData=JSON.stringify(body);\n //console.log('\\n\\nQUESTO IL BODY ESAMI PRENOTABILI ' +rawData);\n //creo oggetto libretto\n for(var i=0; i<body.length; i++){\n //modifica del 16/05/2019 dopo cambio query\n appelliDaPrenotare[i]= new appello(body[i].aaCalId,body[i].adCod, body[i].adDes, body[i].adId,body[i].appId, body[i].cdsCod,\n body[i].cdsDes,body[i].cdsId,body[i].condId,body[i].dataFineIscr,body[i].dataInizioApp, body[i].dataInizioIscr, body[i].desApp,\n //aggiunto qui in data 16/05/2019\n body[i].note,body[i].numIscritti,body[i].numPubblicazioni,body[i].numVerbaliCar,body[i].numVerbaliGen,\n body[i].presidenteCognome,body[i].presidenteId,body[i].presidenteNome,body[i].riservatoFlg,body[i].stato,body[i].statoAperturaApp,body[i].statoDes,body[i].statoInsEsiti,body[i].statoLog,body[i].statoPubblEsiti,body[i].statoVerb,\n body[i].tipoDefAppCod,body[i].tipoDefAppDes,body[i].tipoEsaCod,body[i].tipoSceltaTurno, null);\n \n appelliDaPrenotare[i].log();\n \n/*\n appelliDaPrenotare[i]= new appello(null,null, null, null,null, null,\n null,null,null,null,body[i].dataInizioApp, null, null,\n \n null,null,null,null,null,\n null,null,null,null,null,null,null,null,null,null,null,\n null,null,null,null, null);\n console.log('PD PD PD data '+body[i].dataInizioApp);\n appelliDaPrenotare[i].log();*/\n\n }\n resolve(appelliDaPrenotare);\n }\n });\n });\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function changes the transparency of the optional layers if the layer is selected, otherwise ignore
function changeTranspOptionalLayers(selectedLayer, val, index, id_minus, id_plus, checkboxId) { var checkid = document.getElementById(checkboxId); if (checkid.checked == true)//check if the layer is selected { optionalArray[index] = optionalArray[index] + val; var optionOpacity = optionalArray[index];//locate which global opacity layer it is //Disables the buttons. if (optionOpacity < maxOpacity) { document.getElementById(id_minus).disabled = false; changeColor(document.getElementById(id_minus), 0);//Change color to enabled } else { document.getElementById(id_minus).disabled = true; changeColor(document.getElementById(id_minus), 3);//Change color to disabled } if (optionOpacity > minOpacity) { document.getElementById(id_plus).disabled = false; changeColor(document.getElementById(id_plus), 0);//Change color to enabled } else { document.getElementById(id_plus).disabled = true; changeColor(document.getElementById(id_plus), 3);//Change color to disabled } if (optionOpacity < .00001) { optionOpacity = 0; } selectedLayer.setOpacity(optionOpacity); } }
[ "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}", "function updateOverlayLayersOpacity(value) {\r\n\tgeojsonCCAA.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n\tgeojsonProvincias.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n\tgeojsonZonas.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n}", "function updateBaseLayersOpacity(value) {\r\n\tif (map.hasLayer(OpenStreetMap_Mapnik)) {\r\n\t\tOpenStreetMap_Mapnik.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(Stamen_Watercolor)) {\r\n\t\tStamen_Watercolor.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(OpenTopoMap)) {\r\n\t\tOpenTopoMap.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(BingAerial)) {\r\n\t\tBingAerial.setOpacity(value / 100);\r\n\t};\r\n}", "toggleLayersByType(layerType) {\n //Iterate over all tile layers\n this.allLayers\n //Filter for layers of the given type\n .filter(layer => layer instanceof layerType)\n .forEach(layer => {\n //Invert opacity\n let newOpacity = layer.getOpacity() < 1 ? 1 : 0;\n layer.setOpacity(newOpacity);\n });\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}", "function selectAlphaChannel() {\n // Work for shape layer\n var desc1 = new ActionDescriptor();\n var ref1 = new ActionReference();\n ref1.putProperty(charIDToTypeID(\"Chnl\"), charIDToTypeID(\"fsel\"));\n desc1.putReference(charIDToTypeID(\"null\"), ref1);\n var ref2 = new ActionReference();\n ref2.putEnumerated( charIDToTypeID(\"Path\"), charIDToTypeID(\"Path\"), stringIDToTypeID(\"vectorMask\"));\n desc1.putReference(charIDToTypeID(\"T \"), ref2 );\n executeAction(charIDToTypeID(\"setd\"), desc1, DialogModes.NO );\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 }", "function hideLayers(evt) {\r\n dialogLayer.style.display = \"none\";\r\n maskLayer.style.display = \"none\";\r\n }", "static set AllLayers(value) {}", "layer(name) {\n this._ensureIsInLayeredMode()\n\n return this.setCanvas(this.getLayer(name).getElement())\n }", "transparentMarker(){\n\t\tthis.moveableSprites.forEach(moveableFocus =>{\n\t\t\tmoveableFocus.alpha -= 0.7;\n\t\t})\n\t\tthis.hitmarker.forEach(hit =>{\n\t\t\thit.alpha -= 0.2;\n\t\t})\n\t}", "function applyDissolve(in_isLayerMask) {\r\n\tapp.activeDocument.suspendHistory(\"Simple Dissolve\", \"applyDissolveFilter(\"+in_isLayerMask+\")\" );\r\n\treturn gApplySuccessful;\r\n}", "function getMapLayers() {\n for (var i = 0; i < geeServerDefs.layers.length; i++) {\n var layer = geeServerDefs.layers[i];\n var layerId = layer.glm_id ?\n layer.glm_id + '-' + layer.id : '0-' + layer.id;\n var div = document.getElementById('LayerDiv');\n var checked = layer.initialState ? ' checked' : '';\n var imgPath =\n geeServerDefs.serverUrl + 'query?request=Icon&icon_path=' + layer.icon;\n div.innerHTML +=\n '<label>' +\n '<input type=\"checkbox\" onclick=\"toggleMapLayer(\\'' +\n layerId + '\\')\"' + 'id=\"' + layerId + '\" ' + checked + '/>' +\n '<img src=\"' + imgPath + '\" onerror=\"this.style.display=\\'none\\';\" >' +\n layer.label + '</label>';\n div.innerHTML +=\n '<input type=range id=opacity_' + i + ' min=0 value=100 max=100 step=10 ' +\n 'oninput=\"geeMap.setOpacity(\\'' + layerId + '\\', Number(value/100))\" ' +\n 'onchange=\"outputOpacityValue(\\'' + i + '\\', Number(value))\">';\n div.innerHTML += '<output id=opacity_out_' + i + '>100%</output>';\n\n }\n togglePolygonVisibility();\n}", "function hideAllLayers(layers) {\n\tlayers = layers || doc.layers;\n\tfor (var i = 0; i < layers.length; i++) {\n\t\tlayers[i].visible = false;\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 }", "onLayerHighlight() {}", "function hideOVLayer(name) {\t\t\n \tvar layer = getOVLayer(name);\t\t\n \tif (isNav4)\n \tlayer.visibility = \"hide\";\n \t//if (document.all)\n\telse\n \t layer.visibility = \"hidden\";\n\t //layer.display=\"block\";\n}", "function create_overlays() {\r\n // subtract value for each bit we know is set\r\n // colors must be set later\r\n add_blend_layer(\"overlay0\", 1, \"rgb(0, 0, 0)\", \"difference\");\r\n // colors must be set later\r\n add_blend_layer(\"overlay1\", 2, \"rgb(0, 0, 0)\", \"lighten\");\r\n // bg_color - test_color\r\n // results in zero of bg_color is smaller or equal to test_color\r\n add_blend_layer(\"overlay2\", 3, \"rgb(0, 0, 0)\", \"difference\");\r\n // if bg is not zero, set color to 255\r\n add_blend_layer(\"overlay3\", 4, \"rgb(255, 255, 255)\", \"color-dodge\");\r\n // bg is either 0 or 255. multiply with 10 (great test value)\r\n // result is either 10 or 0\r\n // colors must be set later\r\n add_blend_layer(\"overlay4\", 5, \"rgb(0, 0, 0)\", \"multiply\");\r\n\r\n var number_layers = number_layers_text_field.value;\r\n if(isNaN(number_layers)){\r\n alert(\"#layers must be numeric, please refresh.\");\r\n }\r\n // Fill the remaining stack with saturation blend layers as these will cause a strong side channel signal.\r\n for(var i = 6; i < number_layers; i++) {\r\n add_blend_layer(\"overlay\" + i, i+1, \"rgb(0, 255, 0)\", \"saturation\");\r\n }\r\n }", "filterSubLayer(context) {\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reports the collected statistics at the configured log level, and schedules a new report.
_report() { const msg = this.schedule.name + ' since ' + moment(this.lastRun).format('YYYY-MM-DD HH:mm') + ':\n' + this.reports.map(report => '\u2022 ' + report.name + ": " + (this.counts[report.name] || 0)).join('\n'); this.logger.log(this.schedule.level || 'info', msg); this.lastRun = Date.now(); this.counts = {}; this._schedule(); }
[ "function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\n\n }", "function reportStats() {\n const now = Date.now();\n console.log(`STATS Tweets: ${totalTweets}\\tErrors: ${totalErrors}\\tUptime: ${Math.round((now - startStatus)/1000)}s`);\n}", "_schedule() {\n setTimeout(() => this._report(), this._minimizeInterval(this.schedule.interval));\n }", "function startReportingActivity() {\n var id = Web.setInterval(function () {\n if (self.active()) {\n ucwa.send('POST', { rel: 'reportMyActivity' }, {\n nobatch: true\n }).catch(function (err) {\n // After a long period of inactivity, the connection with UCWA is usually lost.\n // While the connection is being restored, MePerson resends POST /makeMeAvailable.\n // However this periodic timer doesn't know about that logic and keeps sending\n // POST /reportMyActivity as usual. If the timer happens to wake up before the\n // /makeMeAvailable is completed, UCWA will reject this /reportMyActivity with a\n // 409.MakeMeAvailableRequired error.\n if (err && err.code == 'RequestFailed' && err.rsp.status == 409)\n return;\n debug.log('%c reportMyActivity stopped', 'color:red;font-weight:bold', err);\n Web.clearInterval(id);\n self.active(false, err);\n });\n }\n }, 3 * 60 * 1000);\n }", "function report(results) {\n // Add footer to results string.\n results += \"\\n\" + \"_\".repeat(45) + \"\\n\";\n // Print the results to the console.\n console.log(results);\n // Write the results to 'log.txt'. (Append to file. Don't erase the current contents.)\n // If 'log.txt' does not exist in this directory, it will be created.\n fs.appendFile(\"log.txt\", results, function(error) {\n // If an error was experienced log it.\n if (error) {\n console.log(\"There was an error writing the result to the log.\\n\" + error);\n }\n });\n}", "function reporting(area){\n var date = moment().startOf('week').toDate().toString().substring(0, 15);\n\n var district = Districts.findOne({ _id: area.district });\n var districtLeader = Areas.findOne({ _id: district.leader });\n var dlNumber = districtLeader.phone + \"@txt.att.net\";\n\n var progress = {};\n for (key in indicators){\n progress[key] = 0;\n }\n\n Kis.find({ areaId: area._id, date: date }).forEach(function(ki) {\n for (key in indicators){\n progress[key] += ki[key];\n }\n });\n\n //send area's numbers to district leader\n var subject = \"Weekly Actuals For \" + area.name;\n\n var message = \"\";\n for (key in progress){\n message = message + key + \":\" + progress[key] + \" \"\n }\n\n email(dlNumber, \"CFM OPPS <assistants@cfmopps.com>\", subject, message);\n}", "function _daily_report_(ListName,Destination)\n{\n var listId = _list_by_name_(ListName);\n if (!listId) {\n Logger.log(\"No such list\");\n return;\n }\n var now = new Date();\n var lookBack2 = (now.getDay() == 1) ? -4 : -2;\n var later = _days_away_(1);\n var before = _days_away_(-1);\n var before2 = _days_away_(lookBack2);\n var i, n, c, t, tasks, items;\n var message = {\n to: Destination,\n subject: \"Daily Task Status: \"+ListName,\n name: \"Happy Tasks Robot\",\n htmlBody: \"<div STYLE=\\\"background-color:#88ffff;\\\"><table>\\n\",\n body: \"Task report for \"+now+\":\\n\"\n };\n //Logger.log(before.toISOString());\n // past week\n tasks = Tasks.Tasks.list(listId, {'showCompleted':true, 'dueMin':before.toISOString(), 'dueMax': now.toISOString()});\n items = tasks.getItems();\n message = _add_to_message_(message,items,\"Today's Scheduled Tasks\");\n tasks = Tasks.Tasks.list(listId, {'showCompleted':true, 'dueMin':before2.toISOString(), 'dueMax': before.toISOString()});\n items = tasks.getItems();\n message = _add_to_message_(message,items,\"Yesterday's Schedule\");\n message['htmlBody'] += _footer_text_();\n message['htmlBody'] += \"</table>\\n\";\n message['htmlBody'] += \"</div>\";\n //\n MailApp.sendEmail(message);\n Logger.log('Sent email:\\n'+message['body']);\n Logger.log('Sent email:\\n'+message['htmlBody']);\n}", "function saveDataCreateReport() {\n console.log('Writing data to JSON...');\n const jsonFile = fileName(client,'results/','json');\n fs.writeFileSync(jsonFile, JSON.stringify(AllResults));\n console.log(`Created ${jsonFile}`);\n\n console.log('Creating A11y report...');\n var data = mapReportData(AllResults);\n var report = reportHTML(data, tests, client, runner, standard);\n var dateStamp = dateStamp();\n var name = `${client} Accessibility Audit ${dateStamp}`;\n\n console.log('Writing report to HTML...');\n const htmlFile = fileName(client,'reports/','html');\n fs.writeFileSync(htmlFile, report);\n console.log(`Created ${htmlFile}`);\n\n console.log('Creating Google Doc...');\n googleAPI.createGoogleDoc(name, report);\n }", "function monthlyReport() {\n\n}", "dispatchJobs() {\n\t\tconst job = this.getJob(this.logKeys);\n\n\t\tif (!job) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.stat_collector) {\n\t\t\tthis.stat_collector.add(job.key)\n\t\t}\n\n\t\treturn job;\n\t}", "function 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}", "consumeLogs () {\n try {\n this.tail = new Tail(this.logPath)\n } catch (err) {\n console.log('Error while opening log file.', err)\n return\n }\n\n console.log(`Ready to consume new logs from ${this.logPath} file.`)\n\n this.tail.on('line', (line) => {\n console.log('New log:', line)\n this.update(line)\n })\n\n this.tail.on('error', (error) => {\n console.log('Error during log parsing', error)\n })\n\n // Summary of most hit section, runs every 10 seconds\n setInterval(() => {\n this.summarizeTraffic()\n }, this.SUMMARY_INTERVAL * 1000)\n }", "function generateRoverReport(){\n\t$('div#roverReport').empty();\n\t$('div#roverReport').append(\"<h2>Rover Report:</h2>\");\n\n\tallRoversObjArray.forEach(function(rover) {\n\t\tvar reportWrapper = document.createElement(\"div\");\n\t\treportWrapper.className = 'reportWrapper alert alert-primary col-md-12 col-sm-4';\n\n\t\tvar roverNameHTML = '<h3> Rover Name: ' + rover.name +'</h3>';\n\t\tvar locationHTML = 'Currently Located at ' + rover.x + ',' + rover.y + ' and facing ' + rover.getFacingDirection();\n\n\t\t$('div#roverReport').append(reportWrapper);\n\n\t\t$('div.reportWrapper:last').append(roverNameHTML).append(locationHTML);\n\n\t});\n\n}", "function gotNewReport(report) {\n // if the map has been destroyed, do nothing\n if (!self.map || !self.$element.length || !$.contains(document, self.$element[0])) {\n return;\n }\n\n // successful request, so set timeout for next API call\n nextReqTimer = setTimeout(refreshVisits, config.liveRefreshAfterMs);\n\n // hide loading indicator\n $('.realTimeMap_overlay img').hide();\n $('.realTimeMap_overlay .loading_data').hide();\n\n // store current timestamp\n now = forceNowValue || (new Date().getTime() / 1000);\n\n if (firstRun) { // if we run this the first time, we initialiize the map symbols\n visitSymbols = map.addSymbols({\n data: [],\n type: $K.Bubble,\n /*title: function(d) {\n return visitRadius(d) > 15 && d.actions > 1 ? d.actions : '';\n },\n labelattrs: {\n fill: '#fff',\n 'font-weight': 'bold',\n 'font-size': 11,\n stroke: false,\n cursor: 'pointer'\n },*/\n sortBy: function (r) { return r.lastActionTimestamp; },\n radius: visitRadius,\n location: function (r) { return [r.longitude, r.latitude]; },\n attrs: visitSymbolAttrs,\n tooltip: visitTooltip,\n mouseenter: highlightVisit,\n mouseleave: unhighlightVisit,\n click: function (visit, mapPath, evt) {\n evt.stopPropagation();\n self.$element.trigger('mapClick', [visit, mapPath]);\n }\n });\n\n // clear existing report\n lastVisits = [];\n }\n\n if (report.length) {\n // filter results without location\n report = $.grep(report, function (r) {\n return r.latitude !== null;\n });\n }\n\n // check wether we got any geolocated visits left\n if (!report.length) {\n $('.realTimeMap_overlay .showing_visits_of').hide();\n $('.realTimeMap_overlay .no_data').show();\n return;\n } else {\n $('.realTimeMap_overlay .showing_visits_of').show();\n $('.realTimeMap_overlay .no_data').hide();\n\n if (yesterday === false) {\n yesterday = report[0].lastActionTimestamp - 24 * 60 * 60;\n }\n\n lastVisits = [].concat(report).concat(lastVisits).slice(0, maxVisits);\n oldest = Math.max(lastVisits[lastVisits.length - 1].lastActionTimestamp, yesterday);\n\n // let's try a different strategy\n // remove symbols that are too old\n var _removed = 0;\n if (removeOldVisits) {\n visitSymbols.remove(function (r) {\n if (r.lastActionTimestamp < oldest) _removed++;\n return r.lastActionTimestamp < oldest;\n });\n }\n\n // update symbols that remain\n visitSymbols.update({\n radius: function (d) { return visitSymbolAttrs(d).r; },\n attrs: visitSymbolAttrs\n }, true);\n\n // add new symbols\n var newSymbols = [];\n $.each(report, function (i, r) {\n newSymbols.push(visitSymbols.add(r));\n });\n\n visitSymbols.layout().render();\n\n if (enableAnimation) {\n $.each(newSymbols, function (i, s) {\n if (i > 10) return false;\n\n s.path.hide(); // hide new symbol at first\n var t = setTimeout(function () { animateSymbol(s); },\n 1000 * (s.data.lastActionTimestamp - now) + config.liveRefreshAfterMs);\n symbolFadeInTimer.push(t);\n });\n }\n\n lastTimestamp = report[0].lastActionTimestamp;\n\n // show\n var dur = lastTimestamp - oldest, d;\n if (dur < 60) d = dur + ' ' + _.seconds;\n else if (dur < 3600) d = Math.ceil(dur / 60) + ' ' + _.minutes;\n else d = Math.ceil(dur / 3600) + ' ' + _.hours;\n $('.realTimeMap_timeSpan').html(d);\n\n }\n firstRun = false;\n }", "send(events, metrics) {\n\t\t\t// This is where we connect EmPerfSender with our persistent metrics adapter, in this case, trackPerf\n\t\t\t// is our instance of a Weppy interface\n\t\t\ttrackPerf.trackPerf({\n\t\t\t\tmodule: metrics.klass.split('.')[0].toLowerCase(),\n\t\t\t\tname: metrics.klass,\n\t\t\t\ttype: 'timer',\n\t\t\t\tvalue: metrics.duration\n\t\t\t});\n\t\t}", "compressStats() {\n if (this.totalMins > 0) {\n this.history.push({\n date: this.sessionStartDateTime,\n distractionCount: this.distractionList.length,\n timeSpent: this.totalMins,\n });\n localStorage.setItem('statsHistory', JSON.stringify(this.history));\n }\n\n const event = new CustomEvent('reset-timer', {\n });\n this.dispatchEvent(event);\n }", "function process_Pdh_Frame_Hop_History_Data_Stats(record)\n{\n\tvar myId;\t\t\n\tvar subelement = LOOKUP.get(record.monitoredObjectPointer); \n\t\n\tif(subelement == null)\n\t{\n\t\tlogP5Msg(\"process_Pdh_Frame_Hop_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Hop_History_Data_Stats\", \"Skipping 0 rid for --> \"+ record.monitoredObjectPointer);\n\t\treturn;\n\t}\n\tmyId = subelement.id;\n logP4Msg(\"process_Pdh_Frame_Hop_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Hop_History_Data_Stats\", \"ENTERING for --> \"+ record.monitoredObjectPointer + \" with id == \" + myId);\n \n\tfor(var i in PdhFrameHopHistoryDataStats15MinMetrics)\n\t{\n\t var value = parseInt(record[PdhFrameHopHistoryDataStats15MinMetrics[i]]);\t\n\t if (!(value == null || isNaN(value))) {\n\t\t CreateSimpleMetricObject(myId, record, \"AP~Specific~Alcatel~5620 SAM~Bulk~radioequipment~PdhFrameHopHistoryDataStats15Min~\", PdhFrameHopHistoryDataStats15MinMetrics[i]); \n }\n\t}\n\tlogP4Msg(\"process_Pdh_Frame_Hop_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Hop_History_Data_Stats\", \"LEAVING\");\n}", "function addSingleReportToTable(statsTable, singleReport) {\n if (!singleReport || !singleReport.values || singleReport.values.length == 0)\n return;\n\n var date = Date(singleReport.timestamp);\n updateStatsTableRow(statsTable, 'timestamp', date.toLocaleString());\n for (var i = 0; i < singleReport.values.length - 1; i = i + 2) {\n updateStatsTableRow(statsTable, singleReport.values[i],\n singleReport.values[i + 1]);\n }\n}", "function GenerateBuildReport()\r\n{\r\n if (!g_AlreadyCompleted && !PrivateData.objConfig.Options.fRestart)\r\n {\r\n var strTitle;\r\n var strMsg;\r\n var strDuplicated = \"\";\r\n var strElapsed = GetElapsedReport();\r\n\r\n if (!PrivateData.fIsStandalone)\r\n strDuplicated = GetDuplicateReport();\r\n\r\n strTitle = 'Build complete.';\r\n strMsg = PrivateData.objEnviron.LongName + \" \" + PrivateData.objEnviron.Description + ' completed.\\n\\n\\n';\r\n strMsg += strElapsed + '\\n\\n';\r\n strMsg += strDuplicated;\r\n\r\n SendErrorMail(strTitle, strMsg);\r\n g_AlreadyCompleted = true;\r\n }\r\n// <Config xmlns=\"x-schema:config_schema.xml\">\r\n// <LongName>Win64 Check</LongName>\r\n// <Description>Sync and win64 check build, with all post-build options and test-signing</Description>\r\n\r\n\r\n// <Environment xmlns=\"x-schema:enviro_schema.xml\">\r\n// <LongName>AXP64 Checked</LongName>\r\n// <Description>Build on AXP64Chk, NTAXP03, NTAXP04, NTAXP05 AND NTAXP06</Description>\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the API url stored in the component state
function get_url(){ return this.state.api_url; }
[ "apiUrl() {\n const url = this.globalConfigService.getData().apiUrl;\n return url || Remote_1.RemoteConfig.uri;\n }", "baseURL () {\n return config.api.baseUrl;\n }", "function getAPIURL() {\n return (\n `${baseRemoteURL}?${jQuery('#filters :input[value!=\\'all\\']').serialize()}`\n );\n}", "get url() {\n return this._serverRequest.url;\n }", "function init_url( url ) {\n\treturn api_url + url;\n}", "getUrl() {\n return process.env.ENVIRONMENT === \"DEV\" ? \"http://localhost:3001\" : \"prod\";\n }", "setURL() {\n let forecastApiKey = 'f051a3a6eaeb0d3041fa073c40a73a0c';\n let forecastApiURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${this.lat}&lon=${this.lon}&units=metric&APPID=${forecastApiKey}`;\n return forecastApiURL;\n }", "componentDidMount() {\n fetch(\"/backendapiroute\")\n .then(rsp => rsp.json())\n .then(rsp => {\n window.apiHost = rsp.apiHost;\n this.setState({ apiHost: rsp.apiHost });\n })\n .catch(e => console.error(\"failed to get the api host\", e));\n }", "getApi(){\n if (!this.props.api){\n return {};\n }\n return this.props.api;\n }", "getStatusUrl() {\n\t\t\tthrow new Error('This function must be overridden!');\n\t\t}", "function getUxUrl() {\r\n try {\r\n let content = fs.readFileSync(path.join(__dirname, '../../config.json'))\r\n uxUrl = JSON.parse(content).UXURI\r\n logger.silly('uxUrl:', uxUrl)\r\n }\r\n catch (err) {\r\n uxUrl = DEBUG_URL\r\n logger.error('Error loading config.json, using DEBUG_URL:', DEBUG_URL)\r\n }\r\n }", "getServiceBaseHostURL() {\n let routeInfo = this.store.peekRecord('nges-core/engine-route-information', 1);\n\n //if(!routeInfo) routeInfo = this.store.peekRecord('nges-core/engine-route-information', 2);\n let hostUrl = 'http://' + routeInfo.appCode + '.' + routeInfo.appModuleCode + config.NGES_SERVICE_HOSTS.APP_SERVICE_POST_HOST;\n return hostUrl;\n }", "get imageURL() {\n this._logger.debug(\"imageURL[get]\");\n return this._imageURL;\n }", "function apiUrl({ withTenant, apiBaseUrl, apiDomain, tenant, withFeed, feed }) {\n let result = withTenant\n ? `https://${tenant || 'www'}.${apiDomain}`\n : apiBaseUrl\n if (withFeed) {\n result += `/F/${feed}/api/v3`\n }\n return result\n}", "static buildApiUrl(opts) {\n if (!opts.apiKey) {\n return null;\n }\n const urlBase = 'https://maps.googleapis.com/maps/api/js';\n const params = {\n key: opts.apiKey,\n callback: opts.callback,\n libraries: (opts.libraries || ['places']).join(','),\n client: opts.client,\n v: opts.version || '3.27',\n channel: null,\n language: null,\n region: null,\n };\n const urlParams = _.reduce(params, (result, value, key) => {\n if (value) result.push(`${key}=${value}`);\n return result;\n }, []).join('&');\n\n return `${urlBase}?${urlParams}`;\n }", "function computeURL() {\n var url = settings.url;\n if (typeof settings.url == 'function') {\n url = settings.url.call();\n }\n return url;\n }", "getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }", "get imageUrl() {\n return this._imageUrl\n }", "function videoURL(state=\"\", action){\n if(action.type === \"SET_VIDEO_URL\"){\n return action.value;\n }\n return state;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the highlighted autocomplete entry
function acHighlightedText() { return Selector(".autocomplete-item.highlighted").textContent; }
[ "onFocusAutosuggest(event) {\n event.target.select();\n }", "function highlightActiveLineGutter() {\n return activeLineGutterHighlighter\n }", "function handleAutoCompleteEntryClick(tag) {\n\t\t// Get all tag entries\n\t\tconst tags = ref.current.value.split(/\\s/);\n\t\t// Set the input text to the clicked tag name.\n\t\tref.current.value = [\n\t\t\t// Get the text content of the input, excluding the last word.\n\t\t\t...tags.slice(0, -1),\n\t\t\t// Append the tag name to the list of tags.\n\t\t\t(tags[tags.length - 1].match(/[^a-z0-9]/gi)?.[0] ?? \"\") + tag.name,\n\t\t\t// And a little spacey.\n\t\t\t\"\"\n\t\t].join(\" \");\n\n\t\t// Clear the auto complete entries.\n\t\tsetAutoCompleteEntries([]);\n\n\t\t// Wait for the next frame because JavaScript is shitting through the screen.\n\t\tsetImmediate(() => {\n\t\t\t// Set the selection index to the end of the list.\n\t\t\tref.current.selectionStart =\n\t\t\t\tref.current.selectionEnd = ref.current.value.length;\n\n\t\t\t// Focus the input field element.\n\t\t\tref.current.focus();\n\t\t});\n\t}", "function getClickedWord(selRange, node) {\n var nodeText = document.createRange();\n nodeText.selectNode(node);\n\n var str = nodeText.toString();\n var loc = selRange.focusOffset;\n\n return isolateWord(str,loc);\n}", "function getCurrentMultiSelectUserInputValue (inputField)\n{\n var selectionStartPos = getSelectedTextRange(inputField)[0];\n var subStrBefore = inputField.value.substr(0, selectionStartPos);\n var startPos = Math.max(subStrBefore.lastIndexOf('\\n'), subStrBefore.lastIndexOf('\\r')) + 1;\n var endPos = inputField.value.substr(selectionStartPos).search(/\\n|\\r/);\n endPos = endPos == -1? inputField.value.length : selectionStartPos + endPos;\n return inputField.value.substring(startPos, endPos);\n}", "asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.primary]);\n }", "asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.primary]);\n }", "_selectCurrentActiveItem() {\n const currentActive = this._getActiveListItemElement();\n const suggestionId =\n currentActive && currentActive.getAttribute('data-suggestion-id');\n const selection = this.state.list.filter(item => {\n return item.__suggestionId === suggestionId;\n })[0];\n\n if (selection) {\n this.options.onSelect(selection);\n this._filterAndToggleVisibility();\n this.setState({\n activeId: null,\n });\n }\n }", "function getStartColor() {\n var editor = atom.workspace.getActiveTextEditor();\n var selection = editor.getSelectedText();\n\n if (selection.length === 7) {\n selection = selection.slice(1);\n }\n\n if (selection.length === 6) {\n return isValidColor(selection) ? [ '-startColor', selection ] : undefined;\n }\n}", "function _getRange() {\n\t\t// sel: a selection object representing the range of text selected by the user\n\t\tvar sel = win.getSelection();\n\t\t// Return a range object representing the current selection or false\n\t\treturn (sel.rangeCount) ? sel.getRangeAt(0) : false;\n\t}", "asSingle() {\n return this.ranges.length == 1\n ? this\n : new EditorSelection([this.main], 0)\n }", "function selectPhrase(editArea)\r\n{\r\n var startPos = editArea.selectionStart;\r\n var endPos = editArea.selectionEnd;\r\n var selPhrase = editArea.value.substring(startPos, endPos);\r\n var _phrase = document.getElementById('phrase');\r\n if (_phrase)\r\n {\r\n _phrase.value = selPhrase;\r\n } \r\n}", "getSuggestionFor(target) {\n return target && this.suggestionMap.get(target);\n }", "renderSuggestions() {\n const { value, matched, showList, selectedIndex } = this.state;\n\n if (!showList || matched.length < 1) {\n return null; // Nothing to render\n }\n\n return (\n <ul className=\"suggestions\">\n {matched.map((item, index) => (\n <li\n key={`item-${item}-${index}`}\n className={index === selectedIndex ? 'selected' : ''}\n dangerouslySetInnerHTML={{ __html: this.renderHighlightedText(item, value) }}\n onClick={this.handleOnItemClick}\n />\n ))}\n </ul>\n );\n }", "highlightSearchSyntax() {\n console.log('highlightRegexSyntax');\n if (this._highlightSyntax) {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n this.regexField.setBgHtml(this.parseRegex(this.regexField.getTextarea().value));\n } else {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n }\n }", "function changeSuggest() {\r\n var suggest = \"\";\r\n if(listIndex == -1) {\r\n suggest = curPattern;\r\n } else {\r\n var acList = document.getElementById(\"ac-list\");\r\n if(acList && acList.childNodes.length > listIndex) suggest = acList.childNodes[listIndex].textContent;\r\n }\r\n inputBox.focus();\r\n inputBox.value = inputBox.value.substring(0, inputBox.value.lastIndexOf(\"#\") + 1) + suggest;\r\n inputBox.setSelectionRange(inputBox.value.length, inputBox.value.length);\r\n }", "function getAutocompleteUrl(){\n\tvar baseUrl = \"http://www.bennettl.com/inspyr/author/autocomplete/\";\n\tvar searchStr = $(\"[name='author']\").val();\n\treturn baseUrl + searchStr;\n}", "function OneWordHelper_highlight(word, mainID) {\n this.p_currentWord = word\n\n this.locs = chlonnik.mainIndex.getNumbers(this.p_currentWord)\n for(var i = 0; i < this.locs.length; i++) {\n utl.id( 'w-'+this.locs[i] ).className = 'highlight'\n } // for i in this.locs\n\n this.showBar(mainID)\n} // _highlight function", "async getFocusedValue() {\n const focusedInput = await this.getFocusedInput();\n if (focusedInput) {\n return focusedInput.getValue();\n }\n return undefined;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Company filter for comments
function addCompanyCommentsFilter(ev,companyFilter){ var companyFilterId = (companyFilter.company__id); var companyFilterName = (companyFilter.company__name); vm.showCompany = companyFilterName; //vm.showCompanyIdForDialog = ''; vm.showCompanyNameForFilter = companyFilterName; vm.showCompanyIdForFilterDialog = companyFilterId; }
[ "function createFilter(companies) {\n const searchFilter = document.querySelector('#companySearch');\n searchFilter.addEventListener('change', function() {\n const matches = findMatches(searchFilter.value, companies);\n htmlCompanyList.innerHTML = \"\";\n setCompanyList(matches);\n });\n }", "filterReviewers(filter) {\n var codeReviewLabel = this.json_.labels['Code-Review'];\n return ((codeReviewLabel && codeReviewLabel.all) || [])\n .filter(function(reviewer) {\n return !!reviewer._account_id && filter(reviewer);\n });\n }", "function createCompanyList(companies) {\n document.querySelector('#companyLoadingAnimation').style.display = 'none';\n\n document.querySelector('#clearButton').addEventListener('click', () => {\n document.querySelector('#companySearch').value = \"\";\n htmlCompanyList.innerHTML = \"\";\n setCompanyList(companies);\n });\n setCompanyList(companies);\n createFilter(companies);\n }", "getComments(q = null) {\n if (q === null) {\n // no query, get all comments of the type\n return this.comments;\n } else {\n // comments for a specific post...filter by name\n return this.comments.filter(el => el.name === q);\n }\n }", "function getCompanyName(companyKey, arr){\n\n\t\t//filter data for the company names\n\t\t//var compNames=Object.keys(filtered).map(i=> filtered[i]);\n\t\tObject.values(companyKey).map(i=> \n\t\t\t{Object.entries(dataByCompanies).forEach(([key, value]) => {\n\t\t\t\tif (i == key&& !arr.includes(value[0].company)){\n\t \t\t\t\tarr.push(value[0].company);\n\t \t\t\t}\t\t\t\n\n\t \t})}\n\t\t); //end Object.values(companyKey).map()\n\n\t} //end getCompanyName()", "function ApplyFilter(bezl) {\n if (bezl.data.Accounts) { // Avoid throwing errors if the account data hasn't been returned yet\n for (var i = 0; i < bezl.data.Accounts.length; i++) {\n if (bezl.vars.filterString) { // Make sure we have something to filter on\n if (bezl.data.Accounts[i].ID.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Name.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Territory.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Address.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1) {\n bezl.data.Accounts[i].show = true;\n } else {\n bezl.data.Accounts[i].show = false;\n }\n } else {\n bezl.data.Accounts[i].show = true;\n }\n };\n }\n}", "function renderCompanies() {\n\tdbCom.orderBy('name').onSnapshot((snapshot) => {\n\t\trenderCompanies(snapshot.docs)\n\t})\n\n\t// Get where HTML div tag to render\n\tconst companiesList = document.querySelector('.card-company')\n\n\t// Render\n\tconst renderCompanies = (data) => {\n\n\t\tdata.forEach(doc => {\n\t\t\tconst detail = doc.data();\n\t\t\tconst li = `\n<div class=\"cards column is-one-fifth \" id=\"${doc.id}\" >\n\t<div class=\"cards-item\">\n\t\t<header class=\"card-header\">\n \t<p class=\"card-header-title is-centered\" id=\"${doc.id}\" onclick=\"people(this.id)\">\n \t${detail.name}\n\t\t\t</p>\n\t\t\t<span class=\"icon has-text-danger\" id=\"${doc.id}\" onclick=\"deleteCardCompany(this.id)\">\n \t<i class=\"fas fa-lg fa-ban\"></i>\n </span>\n\t\t</header>\n </div>\n</div>`;\n\n\t\t\t// Temp all render items\n\t\t\thtml += li\n\n\t\t});\n\n\t\t// Push all render items to replace\n\t\tcompaniesList.innerHTML = html;\n\n\t}\n}", "function addFilterFunctionality() {\n var bubble,\n form,\n input,\n submit;\n\n // filter is available only for logged in users\n if ( !Site.remoteUser ) {\n return;\n }\n\n bubble = $('#lj_controlstrip_new .w-cs-filter-inner');\n\n // exit if filter content is not currently on the page\n if ( bubble.length === 0 ) {\n return;\n }\n\n form = $('#sortByPoster');\n input = form.find('[name=poster]');\n submit = form.find('[type=image]');\n\n bubble.bubble({\n target: '#lj_controlstrip_new .w-cs-filter-icon',\n showOn: 'click',\n closeControl: false\n });\n\n input.input(function () {\n if( this.value.length ) {\n submit.css('opacity', 1)\n .prop('disabled', false);\n } else {\n submit.css('opacity', 0)\n .prop('disabled', true);\n }\n });\n\n form.on('submit', function (e) {\n if( !input.val().length ) {\n e.preventDefault();\n }\n });\n }", "function applyFilter() {\n var cqlFilterBase = \"seq = '\" + sequence + \"'\";\n\n for (var j = 0; j < layersWithCql.length; j++) {\n // Check for related layer config\n for (lc in currentLayers) {\n if ((layersWithCql[j] == currentLayers[lc].title)) {\n\n var cqlFilter = cqlFilterBase;\n if (currentLayers[lc].custom_cql_filter) {\n cqlFilter = cqlFilter + \" and \" + currentLayers[lc].custom_cql_filter;\n }\n\n var ly = app.mapPanel.map.getLayersByName(layersWithCql[j])[0];\n \n if (ly && ly.mergeNewParams) {\n ly.mergeNewParams({ cql_filter: cqlFilter });\n }\n\n break;\n }\n }\n }\n}", "function CompanyList()\n{\n\tHandleList.call(this, \"CompanyList\");\n}", "function requireCom() {\n return this.feedbackType === 'comment';\n}", "loadCompaniesList(cityName) {\n return this.findListByCondition(this.customers, \"City\", cityName, \"CompanyName\").sort();\n }", "parseComments(comments) {\n\t\tconst newComments = [];\n\t\tcomments.forEach((c) => {\n\t\t\tconst tagRegex = /\\[tag=([a-zA-Z ]+)\\]/gi;\n\t\t\tconst userRegex = /\\[to=([a-zA-Z ]+)\\]/gi;\n\t\t\tconst newComment = { ...c };\n\t\t\tnewComment.body = newComment.body.replace(tagRegex, '<b>#$1</b>');\n\t\t\tnewComment.body = newComment.body.replace(userRegex, '<i><b>$1</b></i>')\n\t\t\tnewComments.push(newComment);\n\t\t});\n\t\treturn newComments;\n\t}", "function urlCustomshipments(companyId, Type){\n\treturn '#search/customshipments/type=' + Type + '&id=' + companyId;\n}", "function Comment(github, item, data) {\n this.github = github;\n this.item = item;\n this.data = data;\n }", "function filtrando(text){\n setListagemComFiltro(\n listagens.filter((item) =>\n {\n return item.nome.toLowerCase().includes(text.toLowerCase());\n })\n );\n setNomefiltro(text)\n }", "addNewContact ({ commit, state }, data) {\n commit('saveNewContact', data)\n const letters = getLettersForFilter(state.contacts)\n commit('updateFilterLetters', letters)\n }", "function idFilter() {\n }", "function showCompanyForm(mode, callback) {\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a single query parameter `name[=value]`
parseQueryParam(params) { const key = matchQueryParams(this.remaining); if (!key) { return; } this.capture(key); let value = ''; if (this.consumeOptional('=')) { const valueMatch = matchUrlQueryParamValue(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } const decodedKey = decodeQuery(key); const decodedVal = decodeQuery(value); if (params.hasOwnProperty(decodedKey)) { // Append to existing values let currentVal = params[decodedKey]; if (!Array.isArray(currentVal)) { currentVal = [currentVal]; params[decodedKey] = currentVal; } currentVal.push(decodedVal); } else { // Create a new value params[decodedKey] = decodedVal; } }
[ "function parse_query(query_string){\n\t\tvar vars = [],\n\t\t\t\tpairs = query_string.split('&');\n\t\t\n\t\tfor ( i = 0; i < pairs.length; i++ ) {\n\t\t\tvar tmp = pairs[i].split('=');\n\t\t\tvars[tmp[0]] = tmp[1];\n\t\t}\n\t\t\n\t\treturn vars;\n\t}", "function parseQueryParams(loc) {\n\tvar params = loc.search.substring(1);\n\tparams = params.split(\"&\");\n\tfor (var i = 0; i < params.length; i++) {\n\t\tvar parts = params[i].split(\"=\");\n\t\tmyApp.config[parts[0]] = parts[1];\n\t}\n}", "function getQueryValue(name) {\n var query = window.location.search.substring(1);\n var vars = query.split('&');\n\n for (var i = 0; i < vars.length; i++) {\n var pair = vars[i].split('=');\n if (pair[0] == name) return pair[1];\n }\n\n return '';\n}", "function ampGetQueryParams(qs) {\n qs = qs.split(\"+\").join(\" \");\n\n var params = {}, tokens,\n re = /\\butm_([^=]+)=([^&]+)/g;\n\n while (tokens = re.exec(qs)) {\n params[decodeURIComponent(tokens[1])]\n = decodeURIComponent(tokens[2]);\n }\n\n return params;\n }", "function getArgs() \n{\n var args = new Object(); \n var query = location.search.substring(1); // Get query string \n var pairs = query.split(\"&\"); // Break at ampersand \n\n for (var i = 0; i < pairs.length; i++) { \n var pos = pairs[i].indexOf('='); // Look for \"name=value\" \n\n if (pos == -1)\n continue; // If not found, skip \n\n var argname = pairs[i].substring(0,pos); // Extract the name \n var value = pairs[i].substring(pos+1); // Extract the value \n value = decodeURIComponent(value); // Decode it, if needed \n args[argname] = value; // Store as a property \n } \n return args; // Return the object \n}", "function deparam( params, coerce ) {\n var obj = {},\n coerce_types = { 'true': !0, 'false': !1, 'null': null };\n\n // Iterate over all name=value pairs.\n $.each( params.replace( /\\+/g, ' ' ).split( '&' ), function(j,v){\n var param = v.split( '=' ),\n key = decodeURIComponent( param[0] ),\n val,\n cur = obj,\n i = 0,\n\n // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it\n // into its component parts.\n keys = key.split( '][' ),\n keys_last = keys.length - 1;\n\n // If the first keys part contains [ and the last ends with ], then []\n // are correctly balanced.\n if ( /\\[/.test( keys[0] ) && /\\]$/.test( keys[ keys_last ] ) ) {\n // Remove the trailing ] from the last keys part.\n keys[ keys_last ] = keys[ keys_last ].replace( /\\]$/, '' );\n\n // Split first keys part into two parts on the [ and add them back onto\n // the beginning of the keys array.\n keys = keys.shift().split('[').concat( keys );\n\n keys_last = keys.length - 1;\n } else {\n // Basic 'foo' style key.\n keys_last = 0;\n }\n\n // Are we dealing with a name=value pair, or just a name?\n if ( param.length === 2 ) {\n val = decodeURIComponent( param[1] );\n\n // Coerce values.\n if ( coerce ) {\n val = val && !isNaN(val) ? +val // number\n : val === 'undefined' ? undefined // undefined\n : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null\n : val; // string\n }\n\n if ( keys_last ) {\n // Complex key, build deep object structure based on a few rules:\n // * The 'cur' pointer starts at the object top-level.\n // * [] = array push (n is set to array length), [n] = array if n is\n // numeric, otherwise object.\n // * If at the last keys part, set the value.\n // * For each keys part, if the current level is undefined create an\n // object or array based on the type of the next keys part.\n // * Move the 'cur' pointer to the next level.\n // * Rinse & repeat.\n for ( ; i <= keys_last; i++ ) {\n key = keys[i] === '' ? cur.length : keys[i];\n cur = cur[key] = i < keys_last ? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] ) : val;\n }\n\n } else {\n // Simple key, even simpler rules, since only scalars and shallow\n // arrays are allowed.\n\n if ( $.isArray( obj[key] ) ) {\n // val is already an array, so push on the next value.\n obj[key].push( val );\n\n } else if ( obj[key] !== undefined ) {\n // val isn't an array, but since a second value has been specified,\n // convert val into an array.\n obj[key] = [ obj[key], val ];\n\n } else {\n // val is a scalar.\n obj[key] = val;\n }\n }\n\n } else if ( key ) {\n // No value was defined, so set something meaningful.\n obj[key] = coerce ? undefined : '';\n }\n });\n\n return obj;\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 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 getArgs()\n{\n let args = new Object();\n\n if (location.search.length > 1)\n { // examine the search string\n let query = location.search.substring(1);\n let pairs = query.split(\"&\");\n for(let i = 0; i < pairs.length; i++)\n { // loop through all parameters\n let pos = pairs[i].indexOf('=');\n if (pos == -1)\n continue;\n var argname = pairs[i].substring(0, pos);\n var value = pairs[i].substring(pos + 1);\n value = decodeURIComponent(value);\n value = value.replace(/\\+/g, \" \");\n args[argname] = value;\n } // loop through all parameters\n } // examine the search string\n return args;\n} // function getArgs", "get params() {\n return this._parsed.params || {};\n }", "function URLParamatersToArray(url) {\n\tvar request = [];\n\tvar pairs = url.substring(url.indexOf('?') + 1).split('&');\n\tfor (var i = 0; i < pairs.length; i++) {\n\t\tif(!pairs[i])\n\t\t\tcontinue;\n\t\tvar pair = pairs[i].split('=');\n\t\trequest.push(decodeURIComponent(pair[0]));\n\t}\n\treturn request;\n}", "function parseFuncParam() {\n var params = [];\n var id;\n var valtype;\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = token.value;\n eatToken();\n }\n\n if (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: id,\n valtype: valtype\n });\n /**\n * Shorthand notation for multiple anonymous parameters\n * @see https://webassembly.github.io/spec/core/text/types.html#function-types\n * @see https://github.com/xtuc/webassemblyjs/issues/6\n */\n\n if (id === undefined) {\n while (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: undefined,\n valtype: valtype\n });\n }\n }\n } else {// ignore\n }\n\n return params;\n }", "function baynote_getUrlParamValue(paramName) {\n var url = window.location.href;\n var regex = new RegExp(\"[\\\\?&\\/]\"+paramName+\"=([^&#\\/]*)\");\n var match = regex.exec(url);\n\n if (!match){ return \"\";}\n else{ return match[1];}\n}", "function parseFromURL(){\n var uri = new URI(window.location.href);\n uri = new URI(uri.filename() + uri.fragment());\n if(uri.search(true).hasOwnProperty('q')){\n parse(uri.search(true).q);\n $('#input').val(uri.search(true).q);\n } else{\n $('#input').focus();\n }\n}", "function parse_url_fragment() {\n let params = new Map();\n let fragment = window.location.hash;\n if (fragment.startsWith('#')) {\n for (let kv of fragment.slice(1).split(',')) {\n let delim = kv.indexOf('=');\n if (delim == -1) {\n params.set(kv.trim(), null);\n } else {\n params.set(kv.slice(0, delim).trim(), kv.slice(delim + 1).trim());\n }\n }\n }\n return params;\n}", "getCurrentQuery() {\n const e = window.location.search;\n if (!e)\n return {};\n let t = {};\n return e.substring(1).split(\"&\").forEach((r) => {\n const n = decodeURIComponent(r).split(\"=\");\n let i = n[0];\n if (!fp(i, \"]\")) {\n t[i] = n[1];\n return;\n }\n const s = i.split(\"[\"), a = s[1].substring(0, s[1].length - 1);\n parseInt(a) == a ? (i = s[0], M(t[i]) || (t[i] = []), t[i].push(n[1])) : t[i] = n[1];\n }), t;\n }", "function getParams(parts) {\n return parts.split(';').reduce((acc, attribute) => {\n let [key, value] = attribute.trim().split('=');\n key = key.trim();\n\n if (value === undefined || key === 'rel') {\n return acc;\n }\n\n acc[key] = value\n .trim()\n .replace(/(^\"|\"$)/g, '')\n .trim();\n\n return acc;\n }, {});\n}", "function transformQuery(query) {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)){\n if (Array.isArray(value)) {\n for (const val of value){\n params.append(name, val);\n }\n } else if (typeof value !== 'undefined') {\n params.append(name, value);\n }\n }\n return params;\n}", "function parse_uri()\n {\n if (this.myuri == \"..\") {\n var tt = window.location.href;\n var tarr = tt.split(\"?\", 2);\n this.myuri = tarr[0];\n if ((tarr.length > 1) && (this.myquery == \"..\")) {\n var myquery = {};\n this.myquery = myquery;\n var tarr = tarr[1].split(\"&\");\n for (var ndx in tarr) {\n var qp = tarr[ndx];\n if (qp.length > 0) {\n var qpa = qp.split(\"=\");\n if (qpa.length == 1) {\n myquery[qp] = \"\";\n }\n else {\n var pname = qpa.shift();\n myquery[pname] = qpa.join(\"=\");\n }\n }\n }\n }\n }\n }", "function getQueryVal(query){\n var url = new URLSearchParams(window.location.search);\n var param = url.get(query);\n return param;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the file title and ID using Google Properties Service This will persist through file save/loads until a new component file is associated with the document.
function setHDFile(docID,title) { var documentProperties = PropertiesService.getDocumentProperties(); documentProperties.setProperties({'hdID': docID, 'hdTitle': title}); onOpen(); }
[ "function refreshHDFile() {\n var documentProperties = PropertiesService.getDocumentProperties();\n var hdID = documentProperties.getProperty('hdID');\n var hdTitle = documentProperties.getProperty('hdTitle');\n \n loadHDFileIntoSheet(hdID,hdTitle);\n}", "updateManifest(documentId, props) {\n let state = {}\n return this.getBuffer(documentId).then((buffer) => {\n state.buffer = buffer\n return buffer.readFile('stencila-manifest.json', 'application/json')\n }).then((manifest) => {\n manifest = JSON.parse(manifest)\n Object.assign(manifest, props)\n state.buffer.writeFile(\n 'stencila-manifest.json',\n 'application/json',\n JSON.stringify(manifest, null, ' ')\n ).then(() => {\n return this._setLibraryRecord(documentId, manifest)\n })\n })\n }", "function saveChangesInFile() {\n var fileId = $(this).attr(\"data-id\");\n var editedText = $(\"textarea.editFile\").val();\n var fileAndParent = fileSystem.findElementAndParentById(fileId);\n var file = fileAndParent.element;\n file.content = editedText;\n var parent = fileAndParent.parent;\n if (parent != null) {\n showFolderOrFileContentById(parent.id);\n }\n }", "updatePersistedMetadata() {\n this.addon.sourceURI = this.sourceURI.spec;\n\n if (this.releaseNotesURI) {\n this.addon.releaseNotesURI = this.releaseNotesURI.spec;\n }\n\n if (this.installTelemetryInfo) {\n this.addon.installTelemetryInfo = this.installTelemetryInfo;\n }\n }", "function saveDoc() {\n const currDoc = appData.currDoc();\n if (currDoc.filePath) {\n saveToFile(currDoc.filePath);\n return;\n }\n saveDocAs();\n}", "function loadHDFileIntoSheet(docID, title) {\n spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\n var componentsRoot = getComponents(docID);\n try {\n var sheet = spreadsheet.insertSheet(title);\n } catch (e) {\n var sheet = spreadsheet.getSheetByName(title);\n sheet.clear();\n }\n \n var components = componentsRoot.getChildren();\n sheet.appendRow(['Component Type','Name','Prompt','Title']);\n sheet.setFrozenRows(1);\n for (var i=0; i<components.length; i++) {\n var x = getComponentAttributes(components[i]);\n var a = [x['type'],x['name'], x['prompt'], x['title']];\n sheet.appendRow(a);\n } \n}", "async function saveDocData(name, desc, pathname, mimetype, userid, projid, replaces) {\n //use g_data later to get document related data like Notes, Supersedes, etc...\n\n if (!currentDBYear) { //If currentDBYear isn't set, retrieve it from database\n currentDBYear = get_db_year.get().Year;\n }\n if (currentDBYear != currentDate.getFullYear()) { //if no records exist or most recent is dated with other than current year\n currentDBYear = currentDate.getFullYear() //set currentDBYear to current year\n nextSerial = 0 //reset nextSerial to 0\n }\n\n if (!nextSerial) { //db year matches current but nextSerial not set\n nextSerial = get_last_Serial.get(currentDBYear).Serial; //get most recent Serial for current year\n }\n nextSerial++ //increment to next available ID\n\n //null values to be replaced by Description, Supersedes, and SupersededBy respectively \n docid = insert_doc.run(currentDBYear, nextSerial, name, desc, pathname, mimetype, userid, projid, currentDate.toString(), replaces, null).lastInsertRowid\n return [docid, currentDBYear, nextSerial]\n}", "function saveLib(){\n chrome.storage.local.set({'library': raw_notes}, function(){\n console.log(\"Library successfully saved.\");\n });\n}", "function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}", "save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }", "function saveNotificationService(notificationService, filename) {\n console.log();\n notificationService.save(filename);\n}", "function saveCurrentCoScriptLocally(){\r\n\tif (!currentProcedure || !currentCoScript) return;\r\n\tvar u = components.utils()\r\n\tif (!currentCoScript.getUUID()) debug(\"saveCurrentCoScriptLocally: currentCoScript has no UUID\")\r\n\tvar uuid = currentCoScript.getUUID()\r\n\t//debug(\"saveCurrentCoScriptLocally. UUID is \" + currentCoScript.getUUID())\r\n\t//ToDo: delete any unused scrapbook files if a script is unloaded and not saved\r\n\t\r\n\t// Populate the currentCoScript object prior to saving it to file\r\n\tcurrentCoScript.procedure = currentProcedure\r\n\t//debug(\"contextP is \" + contextP())\r\n\t//if (contextP()) fillInStepList()\t// reinstate this once JSON.stringify is working\r\n\t\r\n\tvar title = currentProcedure.scriptjson.title\r\n\tif (!title) title = \"no title\"\r\n\t//var titleJSON = nativeJSON.encode(title)\r\n\t\r\n\t// Save to file\r\n\ttry {\r\n\t\t//debug(\"saveCurrentCoScriptLocally: \" + uuid.slice(uuid.length-4, uuid.length))\r\n\t\tcleanCurrentCoScriptForLocalSave()\r\n\t\tvar coScriptJSON = \"\"\r\n\t\t// Use JSON.stringify instead of nativeJSON.encode once FFox's the filter bug is fixed: \r\n\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=509184\r\n\t\t//coScriptJSON = JSON.stringify(currentCoScript, filterOutFunctionsAndComponentsProperty)\r\n\t\tcoScriptJSON = nativeJSON.encode(currentCoScript)\r\n\t} catch (e) {\r\n\t\tdebug(\"local-save: saveCurrentCoScriptLocally: Error encoding currentCoScript: \" + e)\r\n\t}\r\n\t\r\n\tvar coScriptFile = coScriptFolder.clone()\r\n\tcoScriptFile.append(\"coscript\" + currentCoScript.getUUID())\r\n\tfScriptStream.init(coScriptFile, 0x02 | 0x08 | 0x20, 0664, 0)\r\n\tfScriptStream.write(title, title.length)\r\n\tfScriptStream.write(coScriptJSON, coScriptJSON.length)\r\n\tfScriptStream.close()\r\n\t//debug(\"saveCurrentCoScriptLocally: done\")\r\n\t\r\n\t// If the procedure has an id (ie it has been saved on koalescence)\r\n\t//add this coscript to the idUuidPairs file\r\n\tvar id = currentProcedure.getId()\r\n\tif (id && uuid) {\r\n\t\t//debug(\"saveCurrentCoScriptLocally: adding id and uuid to pairs list: \" + id + \", \" + uuid)\r\n\t\taddIdUuidPair(id, uuid)\r\n\t}\r\n}\t// end of saveCurrentCoScriptLocally", "function saveProps(domain, props, callback) {\n chrome.storage.local.get(null, function(data) {\n if (data.sites[domain]) {\n $.extend(data.sites[domain], props);\n if (props.libs && props.libs.length != 0) {\n $.extend(data.sites[domain]['libs'], props.libs);\n }\n } else {\n data.sites[domain] = props;\n }\n chrome.storage.local.set(data, function() {\n if (callback) {\n callback();\n }\n });\n });\n}", "function processMetadataForm(theForm) {\n var props=PropertiesService.getDocumentProperties()\n //Process each form element\n var description = \"{\";\n for (var item in theForm) {\n props.setProperty(item,theForm[item]);\n description += \"\\\"\" + item + \"\\\":\\\"\" + theForm[item] + \"\\\",\";\n Logger.log(item+':::'+theForm[item]);\n }\n var size = description.length;\n description = description.substring(0,size-1);\n description += \"}\";\n var id = DocumentApp.getActiveDocument().getId();\n DriveApp.getFileById(id).setDescription(description);\n\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 }", "async function saveEditing() {\n // Gets the files contents from #fileEditor\n const selectedFileContent = document.getElementById(\"fileEditor\").innerText;\n let type;\n\n if (selectedFile.substr(0, 3) === '/pa') {\n type = 'pages';\n } else if (selectedFile.substr(0, 3) === '/st') {\n type = 'styles';\n } else if (selectedFile.substr(0, 3) === '/sc') {\n type = 'scripts';\n }\n\n // Asks for confirmation of current action\n if (window.confirm(\"Are you sure you want to save the changes made to \" + selectedFile + \" ? \" + \"These changes could cause knock on effects to other pages and files being used on live displays.\")) {\n\n // The selectedFileContent will be saved to the selectedFile\n await fetch('/api/' + type + '/' + selectedFileName, {\n method: 'PUT',\n headers: { 'Content-Type' : 'application/json' },\n body: JSON.stringify({\n file: {\n content: selectedFileContent\n }\n })\n });\n // The page will be reloaded\n reloadPage();\n }\n}", "async setBookingFile(event) {\n if (!(bookingTempStore.bookingFile === 'booking/' + event.target.id)) {\n bookingTempStore.bookingFile = 'booking/' + event.target.id;\n bookingTempStore.bookingFileHasChanged = true;\n bookingTempStore.save();\n }\n }", "function getCoScriptFileTitle(iFile){\r\n\tvar fstream = CC[\"@mozilla.org/network/file-input-stream;1\"]\r\n\t\t\t\t\t\t\t.createInstance(CI.nsIFileInputStream)\r\n\tvar sstream = CC[\"@mozilla.org/scriptableinputstream;1\"]\r\n\t\t\t\t\t\t\t.createInstance(CI.nsIScriptableInputStream)\r\n\tfstream.init(iFile, -1, 0, 0)\r\n\tsstream.init(fstream)\r\n\tvar str = sstream.read(200)\r\n\tsstream.close()\r\n\tfstream.close()\r\n\t\r\n\tvar savedPVal = null\r\n\tvar savedPStartIndex = str.indexOf('savedP')\r\n\tif(savedPStartIndex != -1) savedPVal = str.substring(savedPStartIndex+8, savedPStartIndex+13)\r\n\t//debug(\"getCoScriptFileTitle has savedPVal of \" + savedPVal)\r\n\tif(savedPVal == \"false\") return null\r\n\t\r\n\tvar titleEndIndex = str.indexOf(\"{\")\r\n\tvar title = str.substring(0, titleEndIndex)\r\n\treturn title\r\n}", "_persist() {\n\t\tstorage.set(STORAGE_KEY, this.events);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update a education by for a resume id
update(req, res) { return Education .find({ where: { id: req.params.educationId, resumeId: req.params.resumeId, }, }) .then(education => { if (!education) { return res.status(404).send({ message: 'education Not Found', }); } return education .update(req.body, { fields: Object.keys(req.body) }) .then(updatedEducation => res.status(200).send(updatedEducation)) .catch(error => res.status(400).send(error)); }) .catch(error => res.status(400).send(error)); }
[ "async updateResearchPaper(id,researchPaper){\n const bearer = 'Bearer ' + localStorage.getItem('userToken');\n return await fetch(RESEARCH_PAPER_API_BASE_URI+\"/\"+id,{\n method:'PUT',\n headers:{\n 'content-Type':\"application/json\",\n 'Authorization': bearer\n },\n body:JSON.stringify(researchPaper)\n }).then(response =>{\n return response;\n }).catch(reason => {\n return reason;\n })\n }", "async function updateByQueryFirstApproach(id){\n const course=await Course.findById({_id:id})\n if(!course)\n console.log(\"No course found with published Status: \"+id);\n else{\n // course.author=\"Ali\"\n // course.isPublished=true;\n \n course.set({\n author:\"Ali\",\n isPublished:true\n });\n\n const result=await course.save();\n console.log(result);\n\n }\n}", "function promoteToTeacher(id)\r\n{\r\n //Find the participant in the database\r\n participant = getParticipantByID(id);\r\n if(participant != null)\r\n {\r\n if(participant.status == 'Student')\r\n {\r\n participant.status = 'Teacher';\r\n }\r\n }\r\n}", "function editLibraryMethod(req, res, libraryEncontrado, body) {\n updateLibrary(libraryEncontrado.id, body)\n .then((libraryUpdated) => {\n libraryUpdated ? RESPONSE.success(req, res, libraryUpdated, 200) : RESPONSE.error(req, res, 'No se puede modificar este libro.', 404);\n })\n .catch((err) => {\n console.log(err);\n return RESPONSE.error(req, res, 'Error Interno', 500);\n });\n}", "function updateEmployee(employee,id,callback)\n{\n db.run(\"UPDATE Employees SET firstname=?,lastname=?,salary=?,role=? WHERE rowid=?\",\n [employee.firstname, employee.lastname, employee.salary, employee.role, id],\n function(err) { callback(); });\n}", "async update ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n const dados = request.only([\"descricao\", \"titulo\", \"status\"]);\n \n tarefa.fill({\n id : tarefa.id,\n ...dados\n });\n \n await tarefa.save();\n }", "async update(req,res){\n try {\n\n let params = req.allParams();\n let attr = {};\n if(params.name){\n attr.name = params.name;\n }\n if(params.description){\n attr.description = params.description;\n }\n \n const departmentById = await Department.update({\n id: req.params.department_id\n }, attr);\n return res.ok(departmentById);\n\n } catch (error) {\n return res.serverError(error);\n }\n }", "function editStudentInfo(studentInFireBaseRef){\n var newName = capitalizeFirstLetter($(\"#modal-edit-name\").val());\n var newGrade = parseFloat($(\"#modal-edit-grade\").val());\n var newCourse = capitalizeFirstLetter($(\"#modal-edit-course\").val());\n studentInFireBaseRef.update({\n name: newName,\n grade: newGrade,\n course: newCourse\n });\n }", "function updateAccess(req, res) {\n\n db.get(\"SELECT * FROM tool WHERE user = ? AND id =?\", req.signedCookies.user_id, req.body.toolId,\n function(err, row) {\n if (err) {\n res.status(500).send({ error: \"Error when updating access authority for tool: \" + req.body.toolId });\n } else {\n if(row) {\n db.run(\"UPDATE access SET authority=? WHERE userId=? AND toolId=?\", //auth_token is saltseed for the user\n [ req.body.authority, req.body.userId, req.body.toolId ], function(err){\n if(err) {\n res.status(500).send({ error: \"update access failed for tool:\"+ req.body.toolId });\n } else {\n res.json({ success: \"access authority is successfully updated.\" }); \n }\n }); \n } else {\n res.status(500).send({ error: \"Havn't enough authority to update access authority for tool: \" + req.body.toolId });\n }\n }\n });\n }", "async update ({ params, request, response, auth }) {\n const establishment = await Establishment.findOrFail(params.id)\n\n if (establishment.user_id !== auth.user.id) {\n return response.status(401).send({ error: 'Not authorized' })\n }\n\n const data = request.only([\n 'title',\n 'state',\n 'city',\n 'country',\n 'description',\n 'classification',\n 'facebook',\n 'twitter',\n 'instagram',\n 'telephone',\n 'website',\n 'category',\n ])\n\n establishment.merge(data)\n\n await establishment.save()\n\n return establishment\n }", "function updateLanguage(personReferenceKey, languageProficiencyReferenceKey) {\n $scope.lang.CanRead = ($scope.lang.CanRead == true ? 1 : 0);\n $scope.lang.CanWrite = ($scope.lang.CanWrite == true ? 1 : 0);\n $scope.lang.CanSpeak = ($scope.lang.CanSpeak == true ? 1 : 0);\n $scope.lang.personReferenceKey = personReferenceKey;\n personLanguageProficiencyLogic.updateLanguage($scope.lang, personReferenceKey, languageProficiencyReferenceKey).then(function (response) {\n\n appLogger.alert($scope.alertMessageLabels.languageUpdated);\n getLangProfList(personReferenceKey);\n $scope.lang = {};\n $scope.languageForm.$setPristine();\n $scope.languageForm.$setUntouched();\n\n }, function (err) {\n appLogger.error('ERR', err);\n });\n }", "function updateStudentGrade (studnetId,assignmentId,studentScore,gradebookData){\n gradebookData[studnetId].grades[assignmentId] = studentScore;\n\n}", "static async edit(id, titulo, descripcion, avatar, color) {\n // comprobar que ese elemento exista en la BD\n const trackTemp = await this.findById(id);\n if (!trackTemp) throw new Error(\"El track solicitado no existe!\");\n\n // crear un DTO> es un objeto de trancicion\n const modificador = {\n titulo,\n descripcion,\n avatar,\n color\n };\n // findOneAndUpdate > actualizara en base a un criterio\n const result = await this.findOneAndUpdate(\n {\n _id: id\n },\n {\n $set: modificador\n }\n );\n // retornar un resultado\n return result;\n }", "function updateArticle(articleId, title, body, permission) {\n var time = firebase.firestore.FieldValue.serverTimestamp();\n firebase.firestore().collection('articles').doc(articleId).update({\n title: title,\n body: body,\n permission: permission,\n editedAt: time,\n }).then(function() {\n showAlert('Successfully saved article');\n loadArticles();\n }).catch(function(error) {\n showAlert(error.toString());\n });\n}", "async editarOProjeto(dadosDoProjetoEditadoComIdDoProjeto){\n return axios.put(API_URL + \"projetoid\", dadosDoProjetoEditadoComIdDoProjeto).then(response => response.data)\n }", "static async apiUpdatePostit(req, res, next) {\n try {\n const postitId = req.body._id;\n const title = req.body.title;\n const content = req.body.content;\n const deadline = req.body.deadline;\n const date = new Date();\n\n const postitEditRes = await PostitsDAO.editPostit(\n postitId,\n title,\n content,\n deadline,\n date,\n );\n \n var {error} = postitEditRes;\n if(error){\n res.status(400).json({error});\n }\n res.json({ status: \"Postit updated successfully !\" });\n } catch (e) {\n res.status(500).json({ error: e.message });\n }\n }", "function saveEducation(userEducation) {\r\n return new Promise((resolve, reject) => {\r\n dashboardModel.saveEducation(userEducation).then((data) => {\r\n resolve({ code: code.OK, message: '', data: data })\r\n }).catch((err) => {\r\n if (err.message === message.INTERNAL_SERVER_ERROR)\r\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\r\n else\r\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\r\n })\r\n })\r\n}", "updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }", "function updateEsRecord(data) {\n esClient.search({\n index: 'products',\n body: {\n query : {\n term: { \"id\" : data.id }\n }\n }\n }).then(found => {\n \n console.log('Found item: ', found.hits.hits[0]._id);\n\n if(found){\n esClient.update({\n index: 'products',\n id: found.hits.hits[0]._id,\n body: {\n doc: {\n id: data.id,\n title: data.title,\n description: data.description\n }\n }\n })\n .then(response => {\n console.log('Updated successfully.');\n })\n .catch(err => {\n console.log('Update error: ' +err);\n })\n }\n })\n .catch(err => {\n console.log('Not found Error: '+ err);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns data from start of the month (up to 31 items)
listMonthly() { const today = new Date(); return this.trafficRepository.getMonthlyData(dateService.getYearStart(today), dateService.getYearEnd(today)) .then(data => { data = this.mapRepositoryData(data); const range = numberService.getSequentialRange(1, 12); const valuesToAdd = range.filter(x => !data.find(item => item.group === x)); return data.concat(this.mapEmptyEntries(valuesToAdd)); }); }
[ "populateDaysInMonth() {\n var daysInMonth = [];\n //first day of this.state.monthNumber\n var date = new Date(this.state.year, this.state.monthNumber);\n while (date.getMonth() === this.state.monthNumber) {\n daysInMonth.push(new Date(date));\n //Increment to next day\n date.setDate(date.getDate() + 1)\n }\n return daysInMonth\n }", "function getIncomeHistoryIndex (index)\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var indexMonth = date.getMonth()- index;\r\n while(indexMonth <0)\r\n {\r\n var currentYear = date.getYear()-1;\r\n indexMonth += 11;\r\n }\r\n\r\n var temp = Income.filter(getAssetByMonth);\r\n}", "function getExpenditureHistoryIndex (index)\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var indexMonth = date.getMonth() - index;\r\n while (indexMonth < 0) {\r\n var currentYear = date.getYear() - 1;\r\n indexMonth += 11;\r\n }\r\n\r\n var temp = Expenditure.filter(getAssetByMonth);\r\n}", "function getExpenditureHistory ()\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var currentMonth = date.getMonth();\r\n var currentYear = date.getYear();\r\n\r\n return Expenditure.filter(getAssetByMonth);\r\n}", "getDomLimit(year, month) {\r\n\t\tvar date = new Date(year, month + 1, 0)\r\n\t\treturn date.getDate()\r\n\t}", "function buildMonth(start, month){\n var done = false, date = start.clone(), monthIndex = date.month(), count = 0;\n monthArray = [];\n $scope.month = moment().month(start.month() +1).format('MMMM');\n var viewedMonth = moment().month(start.month() +1);\n $scope.viewedMonth = viewedMonth.month();\n while (!done) {\n monthArray.push({ days: buildWeek(date.clone(), month, viewedMonth) });\n date.add(1, \"w\");\n done = count++ > 2 && monthIndex !== date.month();\n monthIndex = date.month();\n }\n var filterForBadWeek = [];\n filterForBadWeek = _.filter(monthArray[0].days, {'number': 1 })\n\n if (filterForBadWeek.length == 0){\n monthArray.shift();\n }\n $scope.monthArray = monthArray;\n\n console.log('Currently viewed month Array', $scope.monthArray);\n\n }", "function getIncomeHistory ()\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var currentMonth = date.getMonth();\r\n var currentYear = date.getYear();\r\n\r\n return Income.filter(getAssetByMonth);\r\n}", "function nextStartMonth() {\n var thisMonth = new Date().getMonth();\n var nextMonth = 'Jan';\n\n if (0 <= thisMonth && thisMonth < 4) {\n nextMonth = 'May';\n } else if (4 <= thisMonth && thisMonth < 8) {\n nextMonth = 'Sep';\n }\n\n return nextMonth;\n }", "getFoodMonth(){\n let temp = [];\n let total = 0;\n let today= new Date();\n for(var i = 0; i< this.foodLog.length; i++){\n let then = this.foodLog[i].date;\n if(then.getFullYear() == today.getFullYear() && then.getMonth() == today.getMonth()){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }", "function getMonthList() {\n var today = new Date();\n var aMonth = today.getMonth();\n var i;\n var matrixMnthList = $(\".div-lpc-wrapper #matrixMonthList\");\n for (i = 0; i < 12; i++) {\n var monthRow = '<th class=\"label-month-lpc-wrapper\" id=\\\"' + i + '\\\">' + monthArray[aMonth] + '</th>';\n if ($(matrixMnthList)) {\n $(matrixMnthList).append(monthRow);\n }\n aMonth++;\n if (aMonth > 11) {\n aMonth = 0;\n }\n }\n}", "function month_links(start) { \n var startAr = start.split('-');\n var start_year = startAr[0];\n var start_month = startAr[1];\n var monthAr = [];\n var month,this_month,month_date, month_name, m, year;\n var this_m = parseInt(start_month, 10);\n var start_m = (12 + (this_m - 3)) % 12;\n var year = start_year;\n if(this_m - 3 < 0) year--;\n \n for(var i=start_m;i<12+start_m;i++) {\n if(i==12) year++; \n m = i%12;\n if(this_m == m+1) {\n month_name = g_months[m];\n month = '<b>' + month_name + '</b>';\n } else {\n month_name = g_monthsShort[m]; \n month_date = year + \"-\" + zero_pad(m+1) + \"-01\";\n month = '<a href=\"?start=' + month_date +'\" class=\"cal_nav start\" data-value=\"' + month_date + '\">' + month_name + '</a>';\n }\n monthAr.push(month);\n }\n return monthAr.join(' ');\n}", "function getValidMonth(){\r\n\treturn 3;\r\n}", "function dates_within_this_month() {\n days = moment().daysInMonth();\n today = new Date()\n month = String(today.getMonth() + 1)\n year = String(today.getFullYear())\n date_string = year + \"-\" + month + \"-01\"\n start_time = moment(date_string)\n hours_list = []\n for (i = 0; i < days; i++) {\n next_time = start_time.clone()\n next_time.add(i, 'day')\n hours_list.push(next_time)\n\n }\n return hours_list\n}", "function getMonthPickerStart(selector) {\n jQuery(selector).monthpicker({\n showOn: \"both\",\n dateFormat: 'M yy',\n yearRange: 'c-5:c+10'\n });\n}", "function previousMonth(){\n if(data.calendar.month != 11 || data.calendar.year == 2019){\n data.calendar.month--;\n }\n if(data.calendar.month <= -1){\n data.calendar.month = 11;\n data.calendar.year--;\n }\n fillInCalendar();\n}", "function buildWeek(date, month, viewedMonth){\n var days = [];\n for (var i = 0; i < 7; i++) {\n days.push({\n name: date.format(\"dd\").substring(0, 2),\n number: date.date(),\n isCurrentMonth: date.month() === month.month(),\n isViewedMonth: date.month() === viewedMonth.month(),\n isToday: date.isSame(new Date(), \"day\"),\n date: moment(date, \"MM-DD-YYYY\"),\n transactions: applyTransactions(date),\n endOfDay: Math.round((calculateEndOfDay(date, viewedMonth) + 0.00001) * 100) / 100\n });\n\n if (date._d.toString() == moment().endOf('month').startOf('day')._d.toString() && date.month() == viewedMonth.month()){\n console.log('last day of the current month', days[days.length -1]);\n applyNextTotal(days[days.length -1])\n }\n\n date = date.clone();\n date.add(1, \"d\");\n }\n return days;\n }", "static filterMonth(items) {\n const month = document.getElementById(\"month-select\").value;\n\n return items.filter((item) => item.date.split(\"-\")[1] == month);\n }", "function getDaysInMonth()\n{\n var daysArray = new Array(12);\n \n for (var i = 1; i <= 12; i++)\n {\n daysArray[i] = 31;\n\tif (i==4 || i==6 || i==9 || i==11)\n {\n daysArray[i] = 30;\n }\n\tif (i==2)\n {\n daysArray[i] = 29;\n }\n }\n return daysArray;\n}", "function nextMo() {\n showingMonth++;\n if (showingMonth > 11) {\n showingMonth = 0;\n showingYear++;\n }\n update();\n closeDropDown();\n //console.log(\"SHOWING MONTH: \" + showingMonth);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the "$" character from our cash values
function cleanCashString(str) { return str.replace("$", ""); }
[ "function prefixPoundSign(el){\n el.val(function (i, v) {\n return '£' + v.replace('£', '');\n }); \n }", "function removeCurrencySignAndPadding(value, selection) {\n var newValue = value;\n if (newValue.charAt(0) === config.currencySymbol) {\n newValue = newValue.substring(1); // Remove sign\n }\n selection.start --;\n selection.end --;\n var lastPadChar = -1;\n for (var i = 0; i < newValue.length; i++) {\n if (newValue.charAt(i) === config.padChar) {\n\tlastPadChar = i;\n } else {\n\tbreak;\n }\n }\n newValue = newValue.substring(lastPadChar + 1);\n selection.start -= (lastPadChar + 1);\n selection.end -= (lastPadChar + 1);\n if (selection.start < 0) selection.start = 0;\n if (selection.end < 0) selection.end = 0;\n return newValue;\n }", "function extractCurrencyValue(s) {\n return +s.slice(1);\n}", "static amountPriceParser(amount) {\n //delete decimals\n let amountWithoutDecimals = parseInt(amount);\n let amountString = amountWithoutDecimals.toString();\n const regx = /(\\d+)(\\d{3})/;\n while (regx.test(amountString)) {\n amountString = amountString.replace(regx, `$1.$2`);\n }\n return amountString;\n }", "removeTrailingZeros(amount) {\r\n amount = amount.toString();\r\n //console.log(\"Actual amount=>> \", amount);\r\n let regEx1 = /^[0]+/; // remove zeros from start.\r\n let regEx2 = /[0]+$/; // to check zeros after decimal point\r\n let regEx3 = /[.]$/; // remove decimal point.\r\n if (amount.indexOf(\".\") > -1) {\r\n amount = amount.replace(regEx2, \"\"); // Remove trailing 0's\r\n amount = amount.replace(regEx3, \"\");\r\n //console.log(\"Remove trailings=>> \", amount);\r\n }\r\n return parseFloat(amount).toFixed(2);\r\n }", "function currencyFormat(x) {\n return x.toString().replace(/\\B(?<!\\.\\d*)(?=(\\d{3})+(?!\\d))/g, \".\");\n}", "function toUsd(number) {\n number = number.toFixed(2); //to limit the number to two decimal places\n number = number.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ','); //to add commas to seperate the thousands\n //console.log('to US Dollar:', '$' + number);\n return '$' + number; //adds the $\n}", "function removeExtraStuff(state) {\n if (config.currency) {\n state.value = removeCurrencySignAndPadding(state.value, state.selection);\n state.value = removeCommas(state.value, state.selection);\n }\n state.posFromEnd = state.value.length - state.selection.end;\n state.sign = false;\n var dotPos = -1;\n if (config.allowNegative) {\n state.sign = getSign(state.value);\n state.value = clearSign(state.value);\n }\n if (config.currency) {\n state.value = removeDot(state.value, state.selection);\n }\n }", "function getDollarAmount(amount) {\r\n return Math.round(amount).toString();\r\n}", "function getPriceOnly(text) {\n\tif (text.indexOf(\"stop loss\") > -1) {\n\t\ttext = text.substring(0, text.indexOf(\"stop loss\"));\n\t}\n\treturn text.replace(/[^0-9.]/g, \"\");\n}", "function insertDol() {\n var insertedMoney = parseFloat(($(\"#moneyDisplayBox\").text().substring(1)));\n insertedMoney += 1;\n $(\"#moneyDisplayBox\").text(\"$\" + insertedMoney.toFixed(2));\n}", "function getMoneyFormatted(val){\n return val.toFixed(2);\n }", "_formatBalance(balance) {\n return parseFloat(balance, 10).toFixed(0).toString();\n }", "function updateExpressWidget() {\nvar grandTotalSum = $('.grand-total-sum').text();\n console.log(\"Updating express widget. Grandtotal=\", grandTotalSum);\n grandTotalSum = grandTotalSum.replace(/\\$/g, '');\n var currency = $('#afterpay-widget-currency').val();\n if (\"afterpayWidget\" in window) {\n afterpayWidget.update({\n amount: { amount: grandTotalSum, currency: currency },\n });\n\n $('#afterpay-widget-amount').val(grandTotalSum);\n $('#afterpay-widget-currency').val(currency);\n }\n}", "calculateCashOnCash() { return parseFloat((this.calculateCashFlow() / this.calculateTotalCapitalRequired()).toFixed(3)) }", "function get_currency_name(str) {\n return str.replace(` (${get_currency_code(str)})`, '');\n}", "function cleanFx() {\n // Remove entries without a currency code present\n fxData.fx = fxData.fx.filter(fx =>\n fx.currency\n && (typeof fx.currency === \"string\")\n && fx.currency.trim() !== \"\"\n && fx.currency.trim() !== \"XXX\"\n );\n}", "priceFormatter(cell, row) {\n\t\treturn `$${cell}`;\n\t}", "function getAmountandSetBlank(){\n var amount = Math.round($('#amount').val() * 100)/100;\n $('#amount').val('');\n return amount;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for roman/cyrl text insert 'a' after all consonants that are not followed by virama, dependent vowel or 'a' cyrillic mapping extracted from TODO capitalize cyrl too
function insert_a(text, script) { const a = (script == Script.CYRL) ? '\u0430' : 'a'; // roman a or cyrl a text = text.replace(new RegExp(`([ක-ෆ])([^\u0DCF-\u0DDF\u0DCA${a}])`, 'g'), `$1${a}$2`); text = text.replace(new RegExp(`([ක-ෆ])([^\u0DCF-\u0DDF\u0DCA${a}])`, 'g'), `$1${a}$2`); return text.replace(/([ක-ෆ])$/g, `$1${a}`); // conso at the end of string not matched by regex above }
[ "function encodeConsonantWord(word) {\n\n \n word = word.toLowerCase();\n let firstletter = word[0];\n let cons_phrase = \"-\";\n \n\n while\n (firstletter !== \"a\" || \n firstletter !== \"e\" || \n firstletter !== \"i\" || \n firstletter !== \"o\" || \n firstletter !== \"u\")\n {\n \n cons_phrase += word[0];\n word = word.slice(1);\n firstletter = word[0];\n \n\n if(firstletter == \"a\" || \n firstletter == \"e\" || \n firstletter == \"i\" || \n firstletter == \"o\" || \n firstletter == \"u\" ){\n\n return word + cons_phrase + \"ay\";\n\n\n }\n\n \n }\n\n return word; // replace this!\n}", "function replaceInsensitive(chr) {\n\n\t\tvar lower = chr.toLowerCase(),\n\t\t upper = chr.toUpperCase();\n\n\t\tif (lower == upper) {\n\t\t\treturn chr;\n\t\t}\n\n\t\treturn '[' + lower + upper + (baseDiacriticsMap[chr]||'') + ']';\n\t}", "function alternatingCaps(s) {\n\treturn s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]());\n}", "function a(word) {\n if (word === 'undefined' || word === 'null') return word;\n return `${('aeiou').includes(word[0]) ? 'an' : 'a'} ${word}`;\n}", "function cyrillic_adjustments(graphemes) {\n\n cyr_graphemes = cyrillic_adjust_doubleVowel(graphemes)\n\n var au_for_capitals = {\n \"\\u0430\":\"\\u042F\", // CYRILLIC SMALL LETTER A to CAPITAL LETTER YA\n \"\\u0443\":\"\\u042E\", // CYRILLIC SMALL LETTER U to CAPITAL LETTER YU\n \n \"\\u0430\\u0304\":\"\\u042F\\u0304\", // CYRILLIC SMALL LETTER A with MACRON to CAPITAL LETTER YA with MACRON\n \"\\u04EF\":\"\\u042E\\u0304\", // CYRILLIC SMALL LETTER U with MACRON to CAPITAL LETTER YU with MACRON\n }\n\n var shortAU = {\n \"\\u0430\":\"\\u044F\", // CYRILLIC SMALL LETTER A to SMALL LETTER YA\n \"\\u0443\":\"\\u044E\", // CYRILLIC SMALL LETTER U to SMALL LETTER YU\n\n \"\\u0430\\u0301\":\"\\u044F\\u0301\", // CYRILLIC SMALL LETTER A with ACUTE ACCENT to SMALL LETTER YA with ACUTE ACCENT\n \"\\u0443\\u0301\":\"\\u044E\\u0301\", // CYRILLIC SMALL LETTER U with ACUTE ACCENT to SMALL LETTER YU with ACUTE ACCENT\n\n \"\\u0430\\u0302\":\"\\u044F\\u0302\", // CYRILLIC SMALL LETTER A with CIRCUMFLEX to SMALL LETTER YA with CIRCUMFLEX\n \"\\u0443\\u0302\":\"\\u044E\\u0302\", // CYRILLIC SMALL LETTER U with CIRCUMFLEX to SMALL LETTER YU with CIRCUMFLEX\n }\n\n var longAU = {\n \"\\u0430\\u0304\":\"\\u044F\\u0304\", // CYRILLIC SMALL LETTER A with MACRON to SMALL LETTER YA with MACRON\n \"\\u04EF\":\"\\u044E\\u0304\", // CYRILLIC SMALL LETTER U with MACRON to SMALL LETTER YU with MACRON\n\n \"\\u0430\\u0304\\u0301\":\"\\u044F\\u0304\\u0301\", // A with MACRON and ACUTE to YA with MACRON and ACUTE\n \"\\u04EF\\u0301\":\"\\u044E\\u0304\\u0301\", // U with MACRON and ACUTE to YU with MACRON and ACUTE\n\n \"\\u0430\\u0304\\u0302\":\"\\u044F\\u0304\\u0302\", // A with MACRON and CIRCUMFLEX to YA with MACRON and CIRCUMFLEX\n \"\\u04EF\\u0302\":\"\\u044E\\u0304\\u0302\", // U with MACRON and CIRCUMFLEX to YU with MACRON and CIRCUMFLEX\n }\n\n var vowels = { \n \"\\u0438\":\"i\", // CYRILLIC SMALL LETTER I \n \"\\u0430\":\"a\", // CYRILLIC SMALL LETTER A\n \"\\u0443\":\"u\", // CYRILLIC SMALL LETTER U\n \"\\u044B\":\"e\", // CYRILLIC SMALL LETTER YERU\n \"\\u04E3\":\"ii\", // CYRILLIC SMALL LETTER I with MACRON\n \"\\u0430\\u0304\":\"aa\", // CYRILLIC SMALL LETTER A with MACRON\n \"\\u04EF\":\"uu\", // CYRILLIC SMALL LETTER U with MACRON\n } \n\n var lzlls = {\n \"\\u043B\":\"l\", // CYRILLIC SMALL LETTER EL\n \"\\u0437\":\"z\", // CYRILLIC SMALL LETTER ZE\n \"\\u043B\\u044C\":\"ll\", // CYRILLIC SMALL LETTER EL and SMALL LETTER SOFT SIGN\n \"\\u0441\":\"s\", // CYRILLIC SMALL LETTER ES\n\n \"\\u041B\":\"L\", // CYRILLIC CAPITAL LETTER EL\n \"\\u0417\":\"Z\", // CYRILLIC CAPITAL LETTER ZE\n \"\\u0421\":\"S\", // CYRILLIC CAPITAL LETTER ES\n \"\\u041B\\u044C\":\"Ll\", // CYRILLIC CAPITAL LETTER EL and SMALL LETTER SOFT SIGN\n } \n\n // Swaps position of the labialization symbol, i.e. Small Letter U with Dieresis\n var labialC = {\n \"\\u043A\\u04F1\":\"\\u04F1\\u043A\", // CYRILLIC SMALL LETTER KA and SMALL LETTER U with DIERESIS\n \"\\u049B\\u04F1\":\"\\u04F1\\u049B\", // CYRILLIC SMALL LETTER KA with DESCENDER and SMALL LETTER U with DIERESIS \n \"\\u04F7\\u04F1\":\"\\u04F1\\u04F7\", // CYRILLIC SMALL LETTER GHE with DESCENDER and SMALL LETTER U with DIERESIS \n \"\\u0445\\u04F1\":\"\\u04F1\\u0445\", // CYRILLIC SMALL LETTER HA and SMALL LETTER U with DIERESIS\n \"\\u04B3\\u04F1\":\"\\u04F1\\u04B3\", // CYRILLIC SMALL LETTER HA with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u04A3\\u04F1\":\"\\u04F1\\u04A3\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u04A3\\u044C\\u04F1\":\"\\u04F1\\u04A3\\u044C\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN\n // & SMALL LETTER U with DIERESIS\n }\n\n var voicelessC = {\n // Stops \n \"\\u043F\":\"p\", // CYRILLIC SMALL LETTER PE\n \"\\u0442\":\"t\", // CYRILLIC SMALL LETTER TE\n \"\\u043A\":\"k\", // CYRILLIC SMALL LETTER KA\n \"\\u043A\\u04F1\":\"kw\", // CYRILLIC SMALL LETTER KA and SMALL LETTER U with DIERESIS\n \"\\u049B\":\"q\", // CYRILLIC SMALL LETTER KA with DESCENDER\n \"\\u049B\\u04F1\":\"qw\", // CYRILLIC SMALL LETTER KA with DESCENDER and SMALL LETTER U with DIERESIS \n\n // Voiceless fricatives \n \"\\u0444\":\"ff\", // CYRILLIC SMALL LETTER EF\n \"\\u043B\\u044C\":\"ll\", // CYRILLIC SMALL LETTER EL and SMALL LETTER SOFT SIGN\n \"\\u0441\":\"s\", // CYRILLIC SMALL LETTER ES\n \"\\u0448\":\"rr\", // CYRILLIC SMALL LETTER SHA\n \"\\u0445\":\"gg\", // CYRILLIC SMALL LETTER HA\n \"\\u0445\\u04F1\":\"wh\", // CYRILLIC SMALL LETTER HA and SMALL LETTER U with DIERESIS\n \"\\u04B3\":\"ghh\", // CYRILLIC SMALL LETTER HA with DESCENDER\n \"\\u04B3\\u04F1\":\"ghhw\", // CYRILLIC SMALL LETTER HA with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u0433\":\"h\", // CYRILLIC SMALL LETTER GHE\n\n // Voiceless nasals \n \"\\u043C\\u044C\":\"mm\", // CYRILLIC SMALL LETTER EM and SMALL LETTER SOFT SIGN\n \"\\u043D\\u044C\":\"nn\", // CYRILLIC SMALL LETTER EN and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\":\"ngng\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\\u04F1\":\"ngngw\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN & SMALL LETTER U with DIERESIS\n }\n \n // Removes devoicing sign, i.e. Small Letter Soft Sign\n var voicelessNasals = {\n \"\\u043C\\u044C\":\"\\u043C\", // CYRILLIC SMALL LETTER EM and SMALL LETTER SOFT SIGN\n \"\\u043D\\u044C\":\"\\u043D\", // CYRILLIC SMALL LETTER EN and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\":\"\\u04A3\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\\u04F1\":\"\\u04A3\\u04F1\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN\n } // & SMALL LETTER U with DIERESIS\n\n var result = []\n\n for (var i = 0; i < cyr_graphemes.length; i++) {\n var grapheme = cyr_graphemes[i]\n\n // ADJUSTMENT 1: The Cyrillic pairings of 'y-a', 'y-u', 'y-aa', 'y-uu'are rewritten\n // into Cyrillic YA, YU, YA WITH MACRON, YU with MACRON respectively\n // First checks if grapheme is Cyrillic 'y'\n if (grapheme == \"\\u04E4\" && (i < cyr_graphemes.length - 1)) {\n after_for_capitals = cyr_graphemes[i+1]\n\n if (after_for_capitals in au_for_capitals) {\n result.push(au_for_capitals[after_for_capitals])\n i++\n } else {\n result.push(grapheme)\n }\n } else if (grapheme == \"\\u04E5\" && (i < cyr_graphemes.length - 1)) { \n after = cyr_graphemes[i+1]\n\n if (after in shortAU) {\n // ADJUSTMENT 2: If 'ya' or 'yu' follow a consonant, insert a Cyrillic soft sign between\n if (i > 0 && isAlpha(cyr_graphemes[i-1]) && !(cyr_graphemes[i-1] in vowels)) {\n result.push(\"\\u044C\")\n }\n result.push(shortAU[after])\n i++\n } else if (after in longAU) {\n result.push(longAU[after])\n i++\n } else {\n result.push(grapheme)\n }\n } \n\n // ADJUSTMENT 3: The 'a', 'u' Cyrillic representations are rewritten \n // if they follow the Cyrillic representations of 'l', 'z', 'll', 's'\n else if (i > 0 && grapheme in shortAU && cyr_graphemes[i-1] in lzlls) {\n result.push(shortAU[grapheme])\n }\n \n // ADJUSTMENT - Labialization symbol can appear either before or after\n // the consonant it labializes. It moves to appear next to a vowel \n else if (i > 0 && grapheme in labialC && cyr_graphemes[i-1] in vowels) {\n result.push(labialC[grapheme])\n }\n\n // ADJUSTMENT - Cyrillic representation of 'e' deletes before a voiceless\n // consonant cluster\n else if (grapheme == \"\\u042B\" && (i < cyr_graphemes.length - 2) &&\n cyr_graphemes[i+1] in voicelessC && cyr_graphemes[i+2] in voicelessC) {\n result.push(\"\")\n result.push(cyr_graphemes[i+1].toUpperCase())\n i++\n } else if (grapheme == \"\\u044B\" && (i < cyr_graphemes.length - 2) &&\n cyr_graphemes[i+1] in voicelessC && cyr_graphemes[i+2] in voicelessC) {\n result.push(\"\") \n }\n\n // ADJUSTMENT - Devoicing sign is omitted for a voiceless nasal if it\n // appears after a voiceless consonant\n else if (i > 0 && grapheme in voicelessNasals && cyr_graphemes[i-1] in voicelessC) {\n result.push(voicelessNasals[grapheme])\n }\n\n // No adjustments applicable\n else {\n result.push(grapheme)\n }\n\n } // End 'for' Loop\n\n return result\n}", "function replaceThe(str) {\n\tconst a = [];\n\tfor (let i = 0; i < str.split(\" \").length; i++) {\n\t\tif (str.split(\" \")[i] === \"the\" && /[aeiou]/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"an\");\n\t\t} else if (str.split(\" \")[i] === \"the\" && /([b-df-hj-np-tv-z])/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"a\");\n\t\t} else a.push(str.split(\" \")[i])\n\t}\n\treturn a.join(\" \");\n}", "function acronym(phrase) {\n let acr = phrase\n .split(\" \")\n .reduce((a, b) => a + b.charAt(0).toUpperCase(), \"\");\n return acr;\n}", "function translatePigLatin(str) {\n var tab = str.split('');\n if (tab[0] == 'a' || tab[0] =='e' || tab[0] =='o' || tab[0] == 'i' || tab[0] =='u' || tab[0] == 'y') {\n var endOfWord = 'way';\n tab.push(endOfWord);\n return tab.join('');\n } else {\n var firstOfWord = '';\n do {\n firstOfWord += tab.shift();\n }\n while (tab[0] != 'a' && tab[0] !='e' && tab[0] !='o' && tab[0] != 'i' && tab[0] !='u' && tab[0] != 'y');\n var endClassic = 'ay';\n tab.push(firstOfWord,endClassic);\n return tab.join('');\n }\n}", "function replaceApici(text,charToSubst)\n{\n\t/*if (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"\\\"\");*/\n\t\t\n\tif (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"''\");\n\t\n\n\t\t\n\t\t\n}", "function alphabet_az() {\n\tvar sequence = '';\n\t// Ne rien modifier au dessus de ce commentaire\n\n\t// Ne rien modifier au dessous de ce commentaire\n\treturn sequence;\n}", "function ipa_adjust_doubleVowel(graphemes) {\n\n var doubleVowel = {\n \"\\u0069\":\"\\u0069\\u02D0\", // LATIN SMALL LETTER I to I with IPA COLON\n \"\\u0251\":\"\\u0251\\u02D0\", // LATIN SMALL LETTER ALPHA to ALPHA with IPA COLON\n \"\\u0075\":\"\\u0075\\u02D0\", // LATIN SMALL LETTER U to U with IPA COLON\n\n \"\\u0069\\u0301\":\"\\u0069\\u0301\\u02D0\", // LATIN SMALL LETTER I with ACUTE ACCENT to I with IPA COLON and ACUTE ACCENT \n \"\\u0251\\u0301\":\"\\u0251\\u0301\\u02D0\", // LATIN SMALL LETTER ALPHA with ACUTE ACCENT to ALPHA with IPA COLON and ACUTE ACCENT\n \"\\u0075\\u0301\":\"\\u0075\\u0301\\u02D0\", // LATIN SMALL LETTER U with ACUTE ACCENT to U with IPA COLON and ACUTE ACCENT \n \n \"\\u0069\\u0302\":\"\\u0069\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER I with CIRCUMFLEX ACCENT to I with TWO IPA COLONS and ACUTE ACCENT \n \"\\u0251\\u0302\":\"\\u0251\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER ALPHA with CIRCUMFLEX ACCENT to ALPHA with TWO IPA COLONS and ACUTE ACCENT \n \"\\u0075\\u0302\":\"\\u0075\\u0301\\u02D0\\u02D0\", // LATIN SMALL LETTER U with CIRCUMFLEX ACCENT to U with TWO IPA COLONS and ACUTE ACCENT \n }\n\n var stressedVowel = new Set(['\\u0069\\u0301', '\\u0251\\u0301', '\\u0075\\u0301', '\\u0069\\u0302', '\\u0251\\u0302', '\\u0075\\u0302'])\n\n var result = []\n\n for (var i = 0; i < graphemes.length; i++) {\n var grapheme = graphemes[i]\n\n if (grapheme in doubleVowel && grapheme == graphemes[i+1]) {\n result.push(doubleVowel[grapheme])\n i++\n } else if (stressedVowel.has(grapheme)) {\n if (graphemes[i-1] in doubleVowel) {\n result[result.length - 1] = doubleVowel[grapheme]\n } else {\n result.push(grapheme)\n }\n } else if (grapheme in doubleVowel && stressedVowel.has(grapheme)) {\n result.push(doubleVowel[grapheme])\n i++\n } else {\n result.push(grapheme)\n }\n }\n\t\n return result\n}", "function leetspeak(text) {\n regularText = text;\n\n //The global modifier is used to change more than just the first occurence\n regularText = regularText.toUpperCase();\n regularText = regularText.replace(/A/g, '4');\n regularText = regularText.replace(/E/g, '3');\n regularText = regularText.replace(/G/g, '6');\n regularText = regularText.replace(/I/g, '1');\n regularText = regularText.replace(/O/g, '0');\n regularText = regularText.replace(/S/g, '5');\n regularText = regularText.replace(/T/g, '7');\n\n console.log(regularText);\n\n}", "function reOrdering(text) {\n let s = text.split(' '), i = s.findIndex(a => a[0] === a[0].toUpperCase());\n return [s[i], ...s.slice(0, i), ...s.slice(i + 1)].join(' ');\n}", "static cleanText (inputText) {\r\n let cleanText = inputText.toLowerCase().trim();\r\n\r\n cleanText = cleanText.replaceAll(\"à\",\"a\");\r\n cleanText = cleanText.replaceAll(\"â\",\"a\");\r\n cleanText = cleanText.replaceAll(\"è\",\"e\");\r\n cleanText = cleanText.replaceAll(\"é\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ê\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ë\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ç\",\"c\");\r\n cleanText = cleanText.replaceAll(\"ï\",\"i\");\r\n cleanText = cleanText.replaceAll(/ {2,}/g,\" \");\r\n \r\n return cleanText;\r\n }", "function translate (phrase) {\n var newPhrase = \" \";\n for (var count = 0; count < phrase.length; count++) {\n var letter = phrase[count];\n if (cleanerIsVowel(letter) || letter === \" \") {\n newPhrase += letter;\n } else {\n newPhrase += letter + \"o\" + letter;\n }\n return newPhrase;\n}\n\n translate(\"these are some words\");\n}", "capitalizer(str) {\n\t\treturn str.replace(/[aeiou]/g, char => char.toUpperCase());\n\t}", "function ak2uy ( akstr )\n{\n var tstr = \"\" ;\n for ( i = 0 ; i < akstr.length ; i++ ) {\n code = akstr.charCodeAt(i) ;\n if ( code < BPAD || code >= BPAD + akmap.length ) {\n tstr = tstr + akstr.charAt(i) ; \n continue ;\n }\n\n code = code - BPAD ; \n\n if ( code < akmap.length && akmap[code] != 0 ) {\n tstr = tstr + String.fromCharCode ( akmap[code] ) ;\n } else {\n tstr = tstr + akstr.charAt(i) ; \n }\n }\n\n return tstr ;\n}", "textChangeHandler(event) {\n let newConvertedText = \"\"\n let buffer = \"\";\n\n for (let i = 0; i < event.target.value.length; i++) {\n let targetChar = event.target.value.charAt(i);\n\n if (JAPANESE_CHARACTER_REGEX.test(targetChar)) {\n newConvertedText += buffer + targetChar;\n buffer = \"\";\n continue;\n }\n\n buffer += targetChar;\n\n if (buffer in hiragana) {\n newConvertedText += hiragana[buffer];\n buffer = \"\";\n }\n }\n\n newConvertedText += buffer;\n\n this.setState({\n convertedText: newConvertedText,\n isValid: true,\n helperText: \"\"\n });\n }", "function acronym(words) {\n return words.reduce(function (acc, currentVal) {\n return acc + currentVal.slice(0,1)\n }, '')\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode text using `decodeURIComponent`. Returns the original text if it fails.
function decode(text) { try { return decodeURIComponent('' + text); } catch (err) { ( true) && warn(`Error decoding "${text}". Using original value`); } return '' + text; }
[ "function decode(content, encoding, decoder = \"text\") {\n if (encoding) {\n content = Buffer.from(content, encoding).toString();\n }\n switch (decoder) {\n case \"json\":\n try {\n return JSON.parse(content);\n } catch (e) {\n return undefined;\n }\n default:\n return content;\n }\n}", "function getMessageDecoding( msg )\n{\n\tlet dec = new TextDecoder();\n\treturn dec.decode( msg );\n}", "function encodeDecode(text, mode) {\n if (text == null)\n return text;\n\n var textEncoded = '';\n for (var count = 0; count < text.length; count++) {\n var index = ALPHABET.indexOf(text.charAt(count));\n if ( index != -1) {\n textEncoded = textEncoded + ALPHABET.charAt((((index+(OFFSET*mode))+ALPHABET.length) % ALPHABET.length));\n } else {\n textEncoded = textEncoded + text.charAt(count);\n }\n }\n return textEncoded;\n}", "function decode(queryStr, shouldTypecast) {\n\tvar queryArr = (queryStr || '').replace('?', '').split('&'),\n\t n = queryArr.length,\n\t obj = {},\n\t item, val;\n\twhile (n--) {\n\t item = queryArr[n].split('=');\n\t val = shouldTypecast === false? item[1] : typecast(item[1]);\n\t obj[item[0]] = isString(val)? decodeURIComponent(val) : val;\n\t}\n\treturn obj;\n }", "function _hexDecode(data) {\n var j\n , hexes = data.match(/.{1,4}/g) || []\n , back = \"\"\n ;\n\n for (j = 0; j < hexes.length; j++) {\n back += String.fromCharCode(parseInt(hexes[j], 16));\n }\n\n return back;\n }", "function decodeUtf8ToString(bytes) {\n // XXX do documentation\n return encodeCodePointsToString(decodeUtf8ToCodePoints(bytes));\n }", "function decode1251 (str) {\n\tvar i, result = '', l = str.length, cc;\n\n\tfor (i = 0; i < l; i++) {\n\t\tcc = str.charCodeAt(i);\n\n\t\tif ('\\r' == str[i]) continue;\n\n\t\tif (cc < 192) {\n\t\t\tif (168 == cc)\n\t\t\t\tresult += 'Ё';\n\t\t\telse if (184 == cc)\n\t\t\t\tresult += 'ё';\n\t\t\telse\n\t\t\t\tresult += String.fromCharCode(cc);\n\t\t}\n\t\telse\n\t\t\tresult += String.fromCharCode(cc + 848);\n\t}\n\n\treturn result;\n}", "function TagDecode(str){\r\n\tvar temp;\r\n\ttemp = str.replace(/&quot;/gi,\"\\\"\")\r\n\ttemp = temp.replace(/&#39;/gi,\"\\'\")\r\n\ttemp = temp.replace(/&lt;/gi,\"<\")\r\n\ttemp = temp.replace(/&gt;/gi,\">\")\r\n\ttemp = temp.replace(/<br>/gi,\"\\n\")\r\n\ttemp = temp.replace(/&amp;/gi,\"&\")\r\n\treturn temp;\r\n}", "function decode (string) {\n\n var body = Buffer.from(string, 'base64').toString('utf8')\n return JSON.parse(body)\n}", "function songDecoder (str){\n return str.replace(/(WUB)+/g, ' ').trim();\n}", "function decode(message){\n var normAlph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; \n var backAlph = normAlph.slice().reverse();\n var massive = message.split(\"\");\n \n return massive.map(function(item){\n var ind = normAlph.indexOf(item);\n\n if (item != ' ')\n {return backAlph[ind]}\n else {return item}\n }).join(\"\");\n }", "function getdec(hexencoded) {\n\tif (hexencoded.length == 3) {\n\t\tif (hexencoded.charAt(0) == \"%\") {\n\t\t\tif (hexchars.indexOf(hexencoded.charAt(1)) != -1 && hexchars.indexOf(hexencoded.charAt(2)) != -1) {\n\t\t\t\treturn parseInt(hexencoded.substr(1, 2), 16);\n\t\t\t}\n\t\t}\n\t}\n\treturn 256;\n}", "function decode (csv) {\n return iconv.decode(csv, 'windows-1250')\n}", "function unescape(object) {\n return transform(object, _.unescape)\n}", "function decodeDescription(description) {\n return $(\"<span>\").html(description).text();\n }", "function encode(text)\n{\n return encodeURIComponent(text);\n}", "function ConvertToUTF8(text) {\r\n var t = text;\r\n t = ReplaceAll(t, \"è\", \"\\u00e8\");\r\n t = ReplaceAll(t, \"à\", \"\\u00e0\");\r\n t = ReplaceAll(t, \"ù\", \"\\u00f9\");\r\n return t;\r\n}", "function parsestr (c, s) {\n var encodeUtf8 = function (s) {\n return unescape(encodeURIComponent(s));\n };\n var decodeUtf8 = function (s) {\n return decodeURIComponent(escape(s));\n };\n var decodeEscape = function (s, quote) {\n var d3;\n var d2;\n var d1;\n var d0;\n var c;\n var i;\n var len = s.length;\n var ret = \"\";\n for (i = 0; i < len; ++i) {\n c = s.charAt(i);\n if (c === \"\\\\\") {\n ++i;\n c = s.charAt(i);\n if (c === \"n\") {\n ret += \"\\n\";\n }\n else if (c === \"\\\\\") {\n ret += \"\\\\\";\n }\n else if (c === \"t\") {\n ret += \"\\t\";\n }\n else if (c === \"r\") {\n ret += \"\\r\";\n }\n else if (c === \"b\") {\n ret += \"\\b\";\n }\n else if (c === \"f\") {\n ret += \"\\f\";\n }\n else if (c === \"v\") {\n ret += \"\\v\";\n }\n else if (c === \"0\") {\n ret += \"\\0\";\n }\n else if (c === '\"') {\n ret += '\"';\n }\n else if (c === '\\'') {\n ret += '\\'';\n }\n else if (c === \"\\n\") /* escaped newline, join lines */ {\n }\n else if (c === \"x\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16));\n }\n else if (c === \"u\" || c === \"U\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n d2 = s.charAt(++i);\n d3 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16), parseInt(d2 + d3, 16));\n }\n else {\n // Leave it alone\n ret += \"\\\\\" + c;\n // goog.asserts.fail(\"unhandled escape: '\" + c.charCodeAt(0) + \"'\");\n }\n }\n else {\n ret += c;\n }\n }\n return ret;\n };\n\n //print(\"parsestr\", s);\n\n var quote = s.charAt(0);\n var rawmode = false;\n var unicode = false;\n\n // treats every sequence as unicodes even if they are not treated with uU prefix\n // kinda hacking though working for most purposes\n if((c.c_flags & Parser.CO_FUTURE_UNICODE_LITERALS || Sk.python3 === true)) {\n unicode = true;\n }\n\n if (quote === \"u\" || quote === \"U\") {\n s = s.substr(1);\n quote = s.charAt(0);\n unicode = true;\n }\n else if (quote === \"r\" || quote === \"R\") {\n s = s.substr(1);\n quote = s.charAt(0);\n rawmode = true;\n }\n goog.asserts.assert(quote !== \"b\" && quote !== \"B\", \"todo; haven't done b'' strings yet\");\n\n goog.asserts.assert(quote === \"'\" || quote === '\"' && s.charAt(s.length - 1) === quote);\n s = s.substr(1, s.length - 2);\n if (unicode) {\n s = encodeUtf8(s);\n }\n\n if (s.length >= 4 && s.charAt(0) === quote && s.charAt(1) === quote) {\n goog.asserts.assert(s.charAt(s.length - 1) === quote && s.charAt(s.length - 2) === quote);\n s = s.substr(2, s.length - 4);\n }\n\n if (rawmode || s.indexOf(\"\\\\\") === -1) {\n return strobj(decodeUtf8(s));\n }\n return strobj(decodeEscape(s, quote));\n}", "function stripText(text) {\n return text.replace(/<[^>]+>|[!.?,;:'\"-]/g, ' ').replace(/\\r?\\n|\\r|\\s+|\\t/g, ' ').trim()\n }", "function getTranslatedUrl(text){\n return serverUrl + \"?\" + \"text=\" + text; \n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves new settings to storage, and calls f if it exists
function saveNewSettings(settings, f=null){ for(let key of Object.keys(settings)){ let obj = {[key]: settings[key]}; chrome.storage.sync.set(obj, function(e){console.log(e);}); } if(f) f(); }
[ "apply() {\n localStorage.setItem(SETTINGS_KEY, this.export());\n const event = new SettingsEvent();\n event.fire();\n }", "function saveSettings() {\n // Update the sources variable.\n $('.js-social-media-source', modal).each(function () {\n var source = $(this).val();\n\n if (sources.hasOwnProperty(source)) {\n sources[source] = $(this).is(':checked');\n }\n });\n\n // Save settings in cookie.\n if (Drupal.eu_cookie_compliance.hasAgreed()) {\n cookieSaveSettings();\n }\n\n // Apply new settings.\n $('.js-social-media-wrapper').each(function () {\n applySettings($(this));\n });\n }", "function persistSettingsToStorage(tmpSettings) {\n\t\n\ttry {\n\t\tif(tmpSettings.popup)\n\t\t{\n\t\t\tdataStore.set({\"settings\": tmpSettings}, function(items){\n\t\t\t\n\t\t\t\tlogger(\"info\", \"Settings\", \"Settings has been written to storage\");\n\t\t\n\t\t\t});\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t\thandleError(\"persistSettingsToStorage\", e);\n\t}\n}", "loadExistingSettings() {\n // Load from local storage.\n let savedSettings;\n try {\n savedSettings = localStorage.getItem(SETTINGS_KEY);\n if (!savedSettings) {\n return;\n }\n savedSettings = JSON.parse(savedSettings);\n } catch (e) {\n return;\n }\n // Iterate over saved settings and merge into defaults.\n for (let key in savedSettings) {\n const setting = new Setting(key, savedSettings[key]);\n const defaultSetting = super.get(setting.getName());\n if (!defaultSetting) {\n continue;\n }\n // Merge saved setting into default.\n defaultSetting.merge(setting);\n }\n }", "function saveSettings(newSettings) {\n if (newSettings != null) {\n ctrl.settings = angular.copy(newSettings);\n }\n\n const isNewDomain = ctrl.settings.createDate == null;\n const items = {};\n\n if (isNewDomain) {\n ctrl.settings.createDate = new Date().getTime();\n }\n\n items[ctrl.activeDomain] = ctrl.settings;\n chrome.storage.local.set(items, function () {\n // TODO: handle errors\n // If it's a new domain, reset the rules for which icon to show\n if (isNewDomain) {\n hwRules.resetRules();\n }\n });\n }", "function saveSettings(){\n localStorage[\"pweGameServerStatus\"] = gameselection;\n //console.log('saved: ' + gameselection);\n}", "function saveSettings() {\n\n var projectRoot = ProjectManager.getProjectRoot().fullPath;\n var file = FileSystem.getFileForPath(projectRoot + '.ftpsync_settings');\n\n function replacePwd(key, value) {\n if (key === \"pwd\") return undefined;\n return value;\n }\n // if save password is checked, no need to remove pwd from settings\n if (ftpSettings.savepwd === 'checked')\n FileUtils.writeText(file, JSON.stringify(ftpSettings));\n else\n FileUtils.writeText(file, JSON.stringify(ftpSettings, replacePwd));\n }", "function updateSettings(k,v) {\n\t\tuserSettings[k] = v;\n\t\twindow.localStorage.setItem(settingsName, JSON.stringify(userSettings));\n\t}", "function storePref () {\n localStorage.setItem('pref', JSON.stringify(pref));\n}", "function save() {\n\twriteFile(config, CONFIG_NAME);\n\tglobal.store.dispatch({\n\t\ttype: StateActions.UPDATE_CONFIGURATION,\n\t\tpayload: {\n\t\t\t...config\n\t\t}\n\t})\n}", "function saveSettingsAndUpdatePopup(){\n\tvar settings = {};\n settings.on = document.getElementById(\"onoff\").innerText.toLowerCase().includes(\"on\"); // Sorry about this line\n\tsettings.fast_mode = document.getElementById(\"fast_mode\").checked;\n\tsettings.run_at = document.getElementById(\"run_at\").value;\n\n\tsaveNewSettings(settings);\n\n\t/* Update the UI in the popup depending on the settings */\n\tdocument.getElementById(\"onoff\").style.backgroundColor = settings.on ?\n\t\tON_COLOR : OFF_COLOR;\n\n\t/* Update whitelist display */\n\tredrawWhitelists();\n\tredrawIcon(settings.on);\n\n\treturn settings;\n}", "function kh_loadedSetting(setting) {\n loadedSettings.add(setting);\n\n if (loadedSettings.size >= Object.keys(SETTINGS_KEYS).length) {\n waitingForSettings.forEach(function(callback) {\n callback();\n });\n waitingForSettings = [];\n kh_updateWatchers({ settings: true });\n }\n}", "function save () {\n\n\tvar title = postTitle.value;\n\tvar content = postContent.value;\n\tvar savedPost = { \"title\": title, \"content\": content };\n\n\tsaving = setInterval( saveItemToLocalStorage, 5000, savedPost, 'savedPost' );\n\n}", "function writeOptions () {\n needsToSave = false\n fs.writeFile('options.json', JSON.stringify(settings, null, 2), 'utf8')\n}", "function saveState(){\n writeToFile(userFile, users);\n writeToFile(campusFile, campus);\n}", "function setSetting(setting, value) {\n console.log(\"save \" + setting + \" \" + value);\n // setting: string representing the setting name (eg: “username”)\n // value: string representing the value of the setting (eg: “myUsername”)\n var db = getDatabase();\n var res = \"\";\n db.transaction(function(tx) {\n var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);\n if (rs.rowsAffected > 0) {\n res = \"OK\";\n } else {\n res = \"Error\";\n }\n });\n // The function returns “OK” if it was successful, or “Error” if it wasn't\n return res;\n}", "save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }", "function saveLib(){\n chrome.storage.local.set({'library': raw_notes}, function(){\n console.log(\"Library successfully saved.\");\n });\n}", "save() {\n console.log(state)\n localStorage.setItem('state', JSON.stringify(state))\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create our path from the places array
makePath(places) { let path = places.map( x => ({lat: Number(x.latitude), lng: Number(x.longitude)}) ); if (places.length > 0) { path.push({lat: Number(places[0].latitude), lng: Number(places[0].longitude)}); } return path; }
[ "constructPath(cameFrom, goal) {\n let path = this.board.getNeighborTiles(goal[0], goal[1]);\n let pos = goal;\n while (pos !== null) {\n path.unshift(pos);\n pos = cameFrom[pos]; // set the pos to prev pos\n }\n\n return path;\n }", "function genPathways(waypoints) \n{\n\t// Define a dashed line symbol using SVG path notation, with an opacity of 1.\n\tvar lineSymbol = {path: \"M 0,-1 0,1\", strokeOpacity: 1, scale: 2}\n\n\tvar pathColors = [\"#ff6600\", \"#f40696\", \"#FF0000\", \"#d39898\", \"#00FF00\", \"#FFA500\", \"#0000FF\"];\n\tvar pcSize = pathColors.length \n\n\tJSbldPathways(waypoints, pathways);\n\n\tvar nx = 0;\t// Index for path names in array\n\tvar px = 0;\t// Color index\n\n\tfor (pw in pathways)\n\t{\n\t\tif(LOG_PW == true)\n\t\t{\n\t\t\tconsole.log(pathways[pw]);\n\t\t}\n\t\n\t\tnewPath = new google.maps.Polyline({\n\t\t\tpath: pathways[pw],\n\t\t\tgeodesic: true,\n\t\t\tstrokeColor: pathColors[px++],\n\t\t\tstrokeOpacity: 0,\n\t\t\ticons: [{icon: lineSymbol,offset: '0',repeat: '10px'}],\n\t\t\tstrokeWeight: 1});\n\t\t\n\t\tnewPath.setMap(map);\n\t\tptNames[nx++] = newPath;\n\n\t\tpx = (px >= pcSize ? 0 : px);\n\t}\n}", "function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}", "function pointsToPath(points) {\r\n return points.map(function(point, iPoint) {\r\n return (iPoint>0?'L':'M') + point[0] + ' ' + point[1];\r\n }).join(' ')+'Z';\r\n }", "function genWayPoints()\n{\n\tvar ix = 0;\n\n\tvar numWayPoints = waypoints.length\n\tvar bounds = new google.maps.LatLngBounds();\n\tvar iw = new google.maps.InfoWindow();\n\tvar totDistance = 0;\t\t// Total distance for trip\n\tvar aryPrevWpt;\n\tconsole.log(\"Starting new Waypoints:\");\n\t\n\tfor (var kx in waypoints)\n\t{ \n\t\tif(++ix >= 26) ix = 0 // 26 letters in the alphabet\n\t\tvar thisCode = String.fromCharCode(65 + ix) + \".png\"\t// Create the waypoint alphabetic label\n\t\tvar thisPath = \"icons/markers/\";\n\t\n\t\t// Assume a normal marker\n\t\tvar wptColor = thisPath + \"green_Marker\" + thisCode \n\t\n\t\t// If there was a tag associated with this, make it BLUE, unless it was queued\n\t\tif(waypoints[kx][\"tag\"] != \"0\") wptColor = thisPath + \"blue_Marker\" + thisCode\n\n\t\t// If it was queued, we lose the BLUE tag - / Indicates queued/deferred item\n\t\tif(waypoints[kx][\"flg\"] == \"1\") wptColor = thisPath + \"red_Marker\" + thisCode\n\n\t\t // Indicates first after queued/deferred items, use Yellow\n\t\t if(waypoints[kx][\"flg\"] == \"3\") wptColor = thisPath + \"yellow_Marker\" + thisCode \n\t \n\t\t // Generate the WayPoint\n\t\t var latlng = {lat: Number(waypoints[kx][\"gpslat\"]), lng: Number(waypoints[kx][\"gpslng\"])};\n\t\t bounds.extend(latlng)\n\t \n\t\t var latlngA = waypoints[kx][\"gpslat\"] + \", \" + waypoints[kx][\"gpslng\"];\n\n\t\t var wpt = new google.maps.Marker({icon: wptColor, \n\t\t\t\t\t\t\t\t\t\t position: latlng, \n\t\t\t\t\t\t\t\t\t\t title: latlngA}) \n\t\t wpt.setMap(map);\t\t// Display the waypoint\t\t \n\t\t markers.push(wpt);\t\t// Save the Waypoint\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now make sure we have the Cell Tower\n\t\t genCellTower(waypoints[kx][\"cid\"], kx);\n\t \n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now generate the info for this point\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\t\t// Get distance to cell tower and between waypoints\n\t\tvar arycel = {lat: Number(waypoints[kx][\"gsmlat\"]) , lng: Number(waypoints[kx][\"gsmlng\"])}\n\t\tvar distToCell = distCalc(latlng, arycel)\n\t\n\t\tvar thisDist = (aryPrevWpt == null ? 0 : distance(Number(waypoints[kx][\"gpslat\"]), Number(waypoints[kx][\"gpslng\"]), Number(aryPrevWpt[\"lat\"]), Number(aryPrevWpt[\"lng\"]), \"M\"))\n\n\t\ttotDistance += thisDist\n\t\taryPrevWpt = latlng\n\t\n\t\tif(LOG_DS == true)\n\t\t{\n\t\t\tconsole.log(\"thisDist \",thisDist);\n\t\t\tconsole.log(\"totDist \",totDistance);\n\t\t}\n\t\n\t\t// This is a function type called \"closure\" - no idea how it works, but it does\n\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\taryInfoVars[\"iv\" + kx] = \n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"&deg</b></p>\" +\n\t\t\t\t\"</div></div>\"\n\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.setContent(aryInfoVars[\"iv\" + kx]);\n\n\t\t\t// Generate the Listener\n\t\t\twpt.addListener('click', function() {iw.open(map, wpt)})\n\t\t})(kx, wpt);\n\t\t//\n\t\t/*\n\t\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\tgoogle.maps.event.addListener(wpt, 'click',\n\t\t\t\tfunction() {\n\t\t\t\t\tvar iw = \n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"&deg</b></p>\" +\n\t\t\t\t\t\"</div></div>\"\n\t\t\t\t});\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.open(map, wpt);\n\t\t\tbacs0 ----})(kx, wpt);\n\t\t*/\n\t}\t// End of For Loop\n\n\t// Now adjust the map to fit our waypoints\n\tmap.fitBounds(bounds);\n\n\t// Generate the pathways to the cell towers\n\tgenPathways(waypoints);\n\n}", "createRunPathPolyline(map, waypoints, runPath) {\n var runPathPolyLine;\n\n for (var i = 0; i < waypoints.length - 1; i++) {\n\n // Move along the path and compute the distance between each point\n var dx = parseFloat(waypoints[i].lat) -\n parseFloat(waypoints[i + 1].lat);\n\n var dy = parseFloat(waypoints[i].lon) -\n parseFloat(waypoints[i + 1].lon);\n\n var dist = Math.sqrt(dx * dx + dy * dy) * 1000;\n\n // Since datapoints are evenly spaced, we can use distance to\n // imply the speed between each point pair\n\n // Multiply the distance to give a constant we can use in colour\n // generation\n dist *= 600;\n\n if ( dist > 230 ) {\n dist = 230;\n }\n if ( dist < 20 ) {\n dist = 20;\n }\n\n // Generate the colour for this line segment\n var r, g, b;\n r = parseInt((255 - dist));\n g = parseInt((dist));\n b = 20;\n\n // Create a new line segment between the given points,\n // with our computed colour\n runPathPolyLine = new google.maps.Polyline({\n path: [runPath[i], runPath[i + 1]],\n geodesic: true,\n strokeColor: 'rgba(' + r + ', ' + g + ', ' + b + ', 1)',\n strokeOpacity: 1.0,\n strokeWeight: 3\n });\n\n // Apply to map\n runPathPolyLine.setMap(map);\n }\n }", "function createPathString(data) {\n\t\t\t\n\t\t\t var points = data.charts[data.current].points;\n\t\t\t\n\t\t\t \n\t\t\t\tvar path = 'M 25 291 L ' + data.xOffset + ' ' + (data.yOffset - points[0].value);\n\t\t\t\tvar prevY = data.yOffset - points[0].value;\n\t\t\t\n\t\t\t\tfor (var i = 1, length = points.length; i < length; i++) {\n\t\t\t\t\tpath += ' L ';\n\t\t\t\t\tpath += data.xOffset + (i * data.xDelta) + ' ';\n\t\t\t\t\tpath += (data.yOffset - points[i].value);\n\t\t\t\n\t\t\t\t\tprevY = data.yOffset - points[i].value;\n\t\t\t\t}\n\t\t\t\t//path += ' L 989 291 Z';\n\t\t\t\tpath += ' L 2200 291 Z';\n\t\t\t\treturn path;\n\t\t\t}", "constructor(pathList){\n\t\tthis.pointPath = pathList;\n\t}", "boxPath(sideLength = 7) {\n let path = \"\";\n const choices = [\"E\", \"N\", \"W\", \"S\"];\n while (choices.length) {\n const dir = choices.shift();\n for (var j = 0; j < sideLength; j++) {\n path = path.concat(dir);\n }\n }\n return path;\n }", "function PlacesVisited() {\n this.places = []\n\n}", "function build_path(p_orig, p_dest){\n var res = new Array();\n\n if(p_orig.x == p_dest.x){\n if(p_orig.y < p_dest.y){\n // Vertical path, going downwards.\n for(var y = p_orig.y + 1; y <= p_dest.y; y++){\n res.push({x: p_orig.x, y: y});\n }\n } else {\n // Vertical path, going upwards.\n for(var y = p_orig.y - 1; y >= p_dest.y; y--){\n res.push({x: p_orig.x, y: y});\n }\n }\n } else if(p_orig.y == p_dest.y){\n if(p_orig.x < p_dest.x){\n // Horizontal path, going to the right.\n for(var x = p_orig.x + 1; x <= p_dest.x; x++){\n res.push({x: x, y: p_orig.y});\n }\n } else {\n // Horizontal path, going to the left.\n for(var x = p_orig.x - 1; x >= p_dest.x; x--){\n res.push({x: x, y: p_orig.y});\n }\n }\n } else {\n res.push(p_dest); // TODO properly handle diagonal paths.\n }\n\n return res;\n}", "function generatePath(actor, parents, movies) {\n\tparents = mapDocuments(parents);\n\tmovies = mapDocuments(movies);\n\n\tlet currActor = { actor };\n\tconst pathToBacon = [];\n\n\tactor.parents.forEach(([ nconst, tconst ]) => {\n\t\tconst movie = movies[tconst];\n\n\t\tdelete currActor.parents;\n\t\tdelete movie._id;\n\n\t\tcurrActor.movie = movie;\n\t\tpathToBacon.push(currActor);\n\t\tcurrActor = { actor: parents[nconst] };\n\t});\n\n\t// Now currActor is Kevin Bacon, who has no parent thus no movie linking to his parent\n\tcurrActor.movie = null;\n\tpathToBacon.push(currActor);\n\n\treturn pathToBacon;\n}", "updateItineraryAndMapByArray(places){\n let newMarkerPositions = [];\n this.setState({placesForItinerary: places});\n places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));\n this.setState({markerPositions: newMarkerPositions});\n this.setState({reverseGeocodedMarkerPositions: []});\n }", "function _getSVGPath(coord, options) {\n let path\n , subpath\n , x\n , y\n , i\n , j\n ;\n\n path = '';\n for (i = 0; i < coord.length; i++) {\n subpath = '';\n for (j = 0; j < coord[i].length; j++) {\n [x, y] = _transform(coord[i][j], options);\n if (subpath === '') {\n subpath = `M${x},${y}`;\n } else {\n subpath += `L${x},${y}`;\n }\n }\n subpath += 'z';\n path += subpath;\n }\n return path;\n }", "function parseWaypoints(waypoints){\n var wpArray=[]\n \twaypoints.forEach(function(WP){\n \t\twpArray.push({\n \t\t\tlocation: \"\" + WP.location.A + \" \" + WP.location.F\n \t\t})\n \t})\n return wpArray;\n }", "function addRouteMarkers() {\n\n // Add start location\n map.addMarker({\n lat: startLocation[0],\n lng: startLocation[1],\n title: \"Start Location: \" + startLocation[2],\n icon: \"images/start.png\"\n });\n\n // Add end location\n if (endLocation != startLocation) {\n map.addMarker({\n lat: endLocation[0],\n lng: endLocation[1],\n title: \"End Location: \" + endLocation[2],\n icon: \"images/end.png\"\n });\n }\n\n // Add all path markers\n for (var i = 0; i < path.length; i++) {\n map.addMarker({\n lat: path[i][0],\n lng: path[i][1],\n title: path[i][2],\n icon: markers[i],\n infoWindow: {\n content: \"<p>\" + path[i][2] + \"</p><p><input onclick='search([\" + path[i][0] + \",\" + path[i][1] + \"], \\\"\\\")'\" + \" type='button' value='Search Nearby'></p>\" + \n \"<span id='marker' class='delete' onclick='cancelStopMarker(\\\"\" + path[i][2] + \"\\\")'><img src='images/cancel.png' alt='cancel' /></span>\"\n }\n });\n }\n\n fitMap();\n}", "function addPointsToPath(point){\r\n path.push(point);\r\n $('#coordinates-container').html('');\r\n \r\n for(var i = 0; i < path.length; i++){\r\n $('#coordinates-container').html($('#coordinates-container').html() + 'x: ' + path[i].x + ' y: ' + path[i].y + '<br/>');\r\n }\r\n}", "function trianglePath(triangles){\n var path = \"M \" + xScale(triangles[0].x) + \",\" + yScale(triangles[0].y);\n path += \" L \" + xScale(triangles[1].x) + \",\" + yScale(triangles[1].y);\n path += \" L \" + xScale(triangles[2].x) + \",\" + yScale(triangles[2].y) + \" Z\";\n\n return path;\n}", "function placeList () {\n return `<div class='placelist'> ${places.map(p => placeData(p)).join(' ')} </div>`;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predicts tooltip top position based on the trigger element
function predictTooltipTop(el) { var top = el.offsetTop; var height = 40; // asumes ~40px tooltip height while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; } return (top - height) - (window.pageYOffset); }
[ "function _setTooltipPosition() {\n // eslint-disable-next-line no-new\n new PopperJs($element, _tooltip, {\n placement: lumx.position || 'top',\n modifiers: {\n arrow: {\n // eslint-disable-next-line id-blacklist\n element: `.${CSS_PREFIX}-tooltip__arrow`,\n enabled: true,\n },\n },\n });\n }", "function calculateOffsetTop(r){\n return absolute_offset(r,\"offsetTop\")\n}", "function tooltipXposition(d){\n\t\t\treturn x(d)+leftOffset(\"stage_wrapper\")+\"px\";\n\t\t}", "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}", "function tooltip_placement(context, source) {\n\t\tvar $source = $(source);\n\t\tvar $parent = $source.closest('table')\n\t\tvar off1 = $parent.offset();\n\t\tvar w1 = $parent.width();\n\n\t\tvar off2 = $source.offset();\n\t\t//var w2 = $source.width();\n\n\t\tif( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';\n\t\treturn 'left';\n\t}", "function positionTip(evt) {\r\n\tif (!tipFollowMouse) {\r\n\t\tmouseX = (ns4||ns5)? evt.pageX: window.event.clientX + document.documentElement.scrollLeft;\r\n\t\tmouseY = (ns4||ns5)? evt.pageY: window.event.clientY + document.documentElement.scrollTop;\r\n\t}\r\n\t// tooltip width and height\r\n\tvar tpWd = (ns4)? tooltip.width: (ie4||ie5)? tooltip.clientWidth: tooltip.offsetWidth;\r\n\tvar tpHt = (ns4)? tooltip.height: (ie4||ie5)? tooltip.clientHeight: tooltip.offsetHeight;\r\n\t// document area in view (subtract scrollbar width for ns)\r\n\tvar winWd = (ns4||ns5)? window.innerWidth-20+window.pageXOffset: document.body.clientWidth+document.body.scrollLeft;\r\n\tvar winHt = (ns4||ns5)? window.innerHeight-20+window.pageYOffset: document.body.clientHeight+document.body.scrollTop;\r\n\t// check mouse position against tip and window dimensions\r\n\t// and position the tooltip \r\n\r\n\tif ((mouseX+offX+tpWd)>winWd)\r\n\t{\r\n\t\ttipcss.left = (ns4)? mouseX-(tpWd+offX): mouseX-(tpWd+offX)+\"px\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttipcss.left = (ns4)? mouseX+offX: mouseX+offX+\"px\";\r\n\t}\r\n\tif ((mouseY+offY+tpHt)>winHt)\r\n\t{\r\n\t\ttipcss.top = (ns4)? winHt-(tpHt+offY): winHt-(tpHt+offY)+\"px\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttipcss.top = (ns4)? mouseY+offY: mouseY+offY+\"px\";\r\n\t}\r\n\r\n\tif (!tipFollowMouse) t1=setTimeout(\"tipcss.visibility='visible'\",100);\r\n}", "function calculatePosition(triggerBounding, ContentBounding, position, arrow, offset) {\n const margin = arrow ? 8 : 0;\n const MarginX = margin + offset.offsetX;\n const MarginY = margin + offset.offsetY;\n const args = position.split(\" \"); // the step N 1 : center the popup content => ok\n\n const CenterTop = triggerBounding.top + triggerBounding.height / 2;\n const CenterLeft = triggerBounding.left + triggerBounding.width / 2;\n const {\n height,\n width\n } = ContentBounding;\n let top = CenterTop - height / 2;\n let left = CenterLeft - width / 2;\n let transform = \"\";\n let arrowTop = \"0%\";\n let arrowLeft = \"0%\"; // the step N 2 : => ok\n\n switch (args[0]) {\n case \"top\":\n top -= height / 2 + triggerBounding.height / 2 + MarginY;\n transform = `rotate(45deg)`;\n arrowTop = \"100%\";\n arrowLeft = \"50%\";\n break;\n\n case \"bottom\":\n top += height / 2 + triggerBounding.height / 2 + MarginY;\n transform = `rotate(225deg)`;\n arrowLeft = \"50%\";\n break;\n\n case \"left\":\n left -= width / 2 + triggerBounding.width / 2 + MarginX;\n transform = ` rotate(-45deg)`;\n arrowLeft = \"100%\";\n arrowTop = \"50%\";\n break;\n\n case \"right\":\n left += width / 2 + triggerBounding.width / 2 + MarginX;\n transform = `rotate(135deg)`;\n arrowTop = \"50%\";\n break;\n }\n\n switch (args[1]) {\n case \"top\":\n top = triggerBounding.top;\n arrowTop = triggerBounding.height / 2 + \"px\";\n break;\n\n case \"bottom\":\n top = triggerBounding.top - height + triggerBounding.height;\n arrowTop = height - triggerBounding.height / 2 + \"px\";\n break;\n\n case \"left\":\n left = triggerBounding.left;\n arrowLeft = triggerBounding.width / 2 + \"px\";\n break;\n\n case \"right\":\n left = triggerBounding.left - width + triggerBounding.width;\n arrowLeft = width - triggerBounding.width / 2 + \"px\";\n break;\n }\n\n return {\n top,\n left,\n transform,\n arrowLeft,\n arrowTop\n };\n}", "function getTitlePosition() {\n var center = this.center, chart = this.chart, titleOptions = this.options.title;\n return {\n x: chart.plotLeft + center[0] + (titleOptions.x || 0),\n y: (chart.plotTop +\n center[1] -\n ({\n high: 0.5,\n middle: 0.25,\n low: 0\n }[titleOptions.align] *\n center[2]) +\n (titleOptions.y || 0))\n };\n }", "function top(index) {\n var y;\n if (!theight) {\n //This is the first time we are guaranteed to have a template available to measure\n updateDimensions();\n }\n y = index * theight + vpheight / 2 - theight / 2;\n return y;\n }", "function tableToolTip(){\n\tsetPopoverAttributes();\n\t$('#button7-5').popover({\n\t\thtml: true,\n\t\ttrigger: 'manual',\n\t\tcontent: \"<p>\" + tablePopoverContent + \"</p>\" ,\n\t\ttitle: \"<h4>\" + tablePopoverTitle + \"</h4>\",\n\t\tplacement: 'top'\n\t});\n\tsetTimeout(function(){\n\t\t$('#main-table').expose();\n\t}, 300);\n\tsetTimeout(function(){\n\t\t$('#button7-5').popover('show');\n\t\t$('.popover').css('z-index', '9999999');\n\t}, 320);\n\t\n}", "function wordsListToolTip(){\n\t$('#wordsList').popover();\n\tsetTimeout(function(){\n\t\t$('#list-div').expose();\n\t}, 100);\n\tsetTimeout(function(){\n\t\t$('#wordsList').popover('show');\n\t\t$('.popover').css('z-index', '9999999');\n\t}, 200);\n\t\n}", "function getOffsets() {\n // Set a static position before getting the offsets\n $articleHeading.css('position', 'static');\n $articleHeading.each(function (idx) {\n articleHeadingOffset[idx] = $(this).offset().top;\n })\n // Clear style attr\n $articleHeading.attr('style', '');\n }", "_calculateErrorMsgTooltipPosition(inputElement, errorMsgHolder) {\n const bodyRect = document.body.getBoundingClientRect(),\n elemRect = inputElement.getBoundingClientRect(),\n offsetTop = elemRect.top - bodyRect.top;\n\n errorMsgHolder.style.top = offsetTop + elemRect.height + 'px';\n errorMsgHolder.style.left = elemRect.left + 'px';\n }", "function setTooltipListeners() {\n\t\t\td3.selectAll(\"path.trend-area\").filter(function(d) {return !d3.select(this).classed(\"null\");}).tooltip(function(d, i) {\n\t\t\t\tvar content = '<div><p>';\n\t\t\t\tcontent += '<strong>Income Poverty:</strong> ' + (trends[d.id].Einkommen_Arm*100).toFixed(2) + '% &rarr; ' + (trends[d.id].Einkommen_Arm_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\t//content += '<strong>Erwachsenen Armut:</strong> ' + (trends[d.id].Erwa_Arm*100).toFixed(2) + '%<br/>';\n\t\t\t\t//content += '<strong>Altersarmut:</strong> ' + (trends[d.id].Alter_Arm*100).toFixed(2) + '%';\n\t\t\t\tcontent += '<hr/>';\n\t\t\t\tcontent += '<strong>Rent Price:</strong> ' + (trends[d.id].Mietpreise*1).toFixed(2) + '€ &rarr; ' + (trends[d.id].Mietpreise_t2*1).toFixed(2) +'€<br/>';\n\t\t\t\tcontent += '<strong>Condominiums:</strong> ' + (trends[d.id].Anteil_ETW*100).toFixed(2) + '% &rarr; ' + (trends[d.id].Anteil_ETW_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\tcontent += '<strong>Affordable Flats:</strong> ' + (trends[d.id].Anteil_KDU*100).toFixed(2) + '% &rarr; ' + (trends[d.id].Anteil_KDU_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\tcontent += '</p></div>';\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"popover\",\n\t\t\t\t\ttitle: '<strong style=\"font-size:1.5em;\">' + trends[d.id].Stadtteil + '</strong><br/>' + trends[d.id].Bezirk,\n\t\t\t\t\tcontent: content,\n\t\t\t\t\tdetection: \"shape\",\n\t\t\t\t\tplacement: \"mouse\",\n\t\t\t\t\tgravity: 'up',\n\t\t\t\t\tposition: path.centroid(_.where(topojson.feature(dataset, dataset.objects.immoscout).features, {id: d.id})[0]),\n\t\t\t\t\tdisplacement: [10, 10],\n\t\t\t\t\tmousemove: false,\n\t\t\t };\n\t\t\t});\n\t\t}", "function SetText(tooltipText : String, position : Vector2)\n{\n if (text != null && !String.IsNullOrEmpty(tooltipText))\n {\n mTargetAlpha = 1f;\n text.text = tooltipText;\n\n if (tooltipType == TooltipTypeEnum.TOOLTIP_HOVER)\n {\n mPos = position;\n Adjust();\n }\n }\n else\n mTargetAlpha = 0f;\n}", "function wordLablelToolTip(){\n\t$('#wordLabel').popover();\n\tsetTimeout(function(){\n\t\t$('.label-div').expose();\n\t}, 300);\n\tsetTimeout(function(){\n\t\t$('#wordLabel').popover('show');\n\t\t$('.popover').css('z-index', '9999999');\n\t}, 400);\n}", "function arrowToTopFun() {\n\tif(supportAndMaintance[0].getClientRects()[0].top < 0){\n\t\tarrowToTop[0].style.opacity = '0.5';\n\t}else{\n\t\tarrowToTop[0].style.opacity = '0';\n\t}\n}", "function ToolTips(){\n\t\n\t// connector divs\n\tthis.createConnectors();\n\t\n\t// over lap of connector and trigger \n\tthis.overlapH = 10;\n\tthis.overlapV = -5;\n\n\t// time delay\n\tthis.showDelay = 500; // milliseconds\n\t\n\t// current showing tip\n\tthis.currentShowingEl = 0;\n}", "function bindEventsOverlapTooltip(result,tooltipContainer,chartOptions) {\n var page = 1;\n var perPage = result['perPage'];\n var pagestr = \"\";\n var data = [];\n result['perPage'] = perPage;\n data = $.extend(true,[],result['content']);\n result['content'] = result['content'].slice(0,perPage);\n if(result['perPage'] > 1)\n result['pagestr'] = 1 +\" - \"+result['content'].length +\" of \"+data.length;\n else if(result['perPage'] == 1)\n result['pagestr'] = 1 +\" / \"+data.length;\n $(tooltipContainer).find('div.enabledPointer').parent().html(formatLblValueMultiTooltip(result));\n $(tooltipContainer).find('div.left-arrow').on('click',function(e){\n result['button'] = 'left';\n handleLeftRightBtnClick(result,tooltipContainer);\n });\n $(tooltipContainer).find('div.right-arrow').on('click',function(e){\n result['button'] = 'right';\n handleLeftRightBtnClick(result,tooltipContainer);\n });\n $(tooltipContainer).find('div.tooltip-wrapper').find('div.chart-tooltip').on('click',function(e){\n bubbleDrillDown($(this).find('div.chart-tooltip-title').find('p').text(),result['nodeMap']);\n });\n $(tooltipContainer).find('div.enabledPointer').on('mouseover',function(e){\n hoveredOnTooltip = true;\n });\n $(tooltipContainer).find('div.enabledPointer').on('mouseleave',function(e){\n hoveredOnTooltip = false;\n nv.tooltip.cleanup();\n });\n $(tooltipContainer).find('button.close').on('click',function(e){\n hoveredOnTooltip = false;\n nv.tooltip.cleanup();\n });\n function handleLeftRightBtnClick(result,tooltipContainer) {\n var content = [];\n var leftPos = 'auto',rightPos = 'auto';\n if(result['button'] == 'left') {\n if($(tooltipContainer).css('left') == 'auto') {\n leftPos = $(tooltipContainer).position()['left'];\n $(tooltipContainer).css('left',leftPos);\n $(tooltipContainer).css('right','auto');\n }\n if(page == 1)\n return;\n page = page-1;\n if(result['perPage'] > 1)\n pagestr = (page - 1) * perPage+1 +\" - \"+ (page) * perPage;\n else if(result['perPage'] == 1)\n pagestr = (page - 1) * perPage+1;\n if(page <= 1) {\n if(result['perPage'] > 1)\n pagestr = 1 +\" - \"+ (page) * perPage;\n else if(result['perPage'] == 1)\n pagestr = 1;\n }\n content = data.slice((page-1) * perPage,page * perPage);\n } else if (result['button'] == 'right') {\n if($(tooltipContainer).css('right') == 'auto') {\n leftPos = $(tooltipContainer).position()['left'];\n rightPos = $(tooltipContainer).offsetParent().width() - $(tooltipContainer).outerWidth() - leftPos;\n $(tooltipContainer).css('right', rightPos);\n $(tooltipContainer).css('left','auto');\n }\n if(Math.ceil(data.length/perPage) == page)\n return;\n page += 1;\n if(result['perPage'] > 1)\n pagestr = (page - 1) * perPage+1 +\" - \"+ (page) * perPage;\n else if(result['perPage'] == 1)\n pagestr = (page - 1) * perPage+1;\n content = data.slice((page-1) * perPage,page * perPage);\n if(data.length <= page * perPage) {\n if(result['perPage'] > 1)\n pagestr = (data.length-perPage)+1 +\" - \"+ data.length;\n else if(result['perPage'] == 1)\n pagestr = (data.length-perPage)+1;\n content = data.slice((data.length - perPage),data.length);\n }\n }\n leftPos = $(tooltipContainer).position()['left'];\n rightPos = $(tooltipContainer).offsetParent().width() - $(tooltipContainer).outerWidth() - leftPos;\n result['content'] = content;\n if(result['perPage'] > 1)\n pagestr += \" of \"+data.length;\n else if(result['perPage'] == 1)\n pagestr += \" / \"+data.length;\n result['perPage'] = perPage;\n $(tooltipContainer).css('left',0);\n $(tooltipContainer).css('right','auto');\n $(tooltipContainer).find('div.tooltip-wrapper').html(\"\");\n for(var i = 0;i<result['content'].length ; i++) {\n $(tooltipContainer).find('div.tooltip-wrapper').append(formatLblValueTooltip(result['content'][i]));\n }\n $(tooltipContainer).find('div.pagecount span').html(pagestr);\n if(result['button'] == 'left') {\n //Incase the tooltip doesnot accomodate in the right space available\n if($(tooltipContainer).outerWidth() > ($(tooltipContainer).offsetParent().width() - leftPos)){\n $(tooltipContainer).css('right',0);\n $(tooltipContainer).css('left','auto');\n } else {\n $(tooltipContainer).css('left',leftPos);\n }\n } else if(result['button'] == 'right') {\n //Incase the tooltip doesnot accomodate in the left space available\n if($(tooltipContainer).outerWidth() > ($(tooltipContainer).offsetParent().width() - rightPos)){\n $(tooltipContainer).css('left',0);\n } else {\n $(tooltipContainer).css('right',rightPos);\n $(tooltipContainer).css('left','auto');\n }\n }\n //binding the click on tooltip for bubble drill down\n $(tooltipContainer).find('div.tooltip-wrapper').find('div.chart-tooltip').on('click',function(e){\n bubbleDrillDown($(this).find('div.chart-tooltip-title').find('p').text(),result['nodeMap']);\n });\n }\n function bubbleDrillDown(nodeName,nodeMap) {\n var e = nodeMap[nodeName];\n if(typeof(chartOptions['clickFn']) == 'function')\n chartOptions['clickFn'](e['point']);\n else\n processDrillDownForNodes(e);\n }\n $(window).off('resize.multiTooltip');\n $(window).on('resize.multiTooltip',function(e){\n nv.tooltip.cleanup();\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loadGame: Called by button handler Gets gameStateObject from local storage and puts into appropriate game data structures.
function loadGame() { // temp gameStateObject var gameStateObject = null; var tempString = ""; // get state object from local storage tempString = localStorage.getItem("GoblinKingGameData"); console.log("Loaded gamedata: " + tempString); gameStateObject = JSON.parse(tempString); console.log("Gamestate Object after parse: " + gameStateObject); // now get data from state object mapLocation = gameStateObject.mapLocation; console.log("mapLocation: " + gameStateObject.mapLocation); itemsInWorld = gameStateObject.itemsInWorld; console.log("itemsInWorld: " + gameStateObject.itemsInWorld); itemLocations = gameStateObject.itemLocations; console.log("itemLocations: " + gameStateObject.itemLocations); backpack = gameStateObject.backpack; console.log("backpack: " + gameStateObject.backpack); // now redisplay game renderGame(); }// end loadGame
[ "loadGame(game) {\n if (game) {\n this.initialize();\n this.restore(game);\n } else {\n this.newGame();\n }\n }", "function loadState()\n{\n if( savedStateExists() )\n {\n console.log(\"Found a saved state to load.\");\n\n // pause game\n bPauseGame = true;\n\n // load into a holding area\n var tempload = JSON.parse(localStorage.getItem(savedStateKey));\n\n // load data into real state\n state = tempload;\n\n // re-set things that have functions attached\n state.world.time = new Timestamp(tempload.world.time.totalSeconds);\n\n // unpause\n bPauseGame = false;\n\n // re-draw // TODO do this differently\n state.player.inventory.updateDisplay();\n state.player.updateMoneyDisplay();\n\n console.info(\"Loaded!\");\n }\n else\n {\n console.warn(\"No saved state with key\" + savedStateKey + \" exists.\");\n }\n}", "function onScreenLoad(){\n\tstate = parent.newGameState(JSON.parse(localStorage[\"save\"]));\n\tstate.bugs = 9;\n\tscreen1.bugCount = $(\"#bugCount\");\n\tgenerateBreederList(state.breeders);\n\tdisplayTotal();\n\tparent.removeCover();\n}", "load() {\n log.debug('Entities - load()', this.game.renderer);\n this.game.app.sendStatus('Lots of monsters ahead...');\n\n if (!this.sprites) {\n log.debug('Entities - load() - no sprites loaded yet', this.game.renderer);\n this.sprites = new Sprites(this.game.renderer);\n\n this.sprites.onLoadedSprites(() => {\n log.debug('Entities - load() - sprites done loading, loading cursors');\n this.game.input.loadCursors();\n this.game.postLoad();\n this.game.start();\n });\n }\n\n this.game.app.sendStatus('Yes, you are also a monster...');\n\n if (!this.grids) {\n log.debug('Entities - load() - no grids loaded yet');\n this.grids = new Grids(this.game.map);\n }\n }", "function loadGamePage(lvl) {\n\n //Update the level number in global variable\n level = lvl;\n\n //The level is going to start now so initialise the correct items to zero\n itemCorrect = 0;\n\n //Create the game content\n var gameContent = createGamePage();\n\n //If game content is not created the display level not ready message\n if(gameContent === undefined) {\n updateTeddyDialogueMessage(teddyDialogues.gameLevelNotExists);\n level = 0;\n return;\n } else {\n //Clear the page\n document.body.innerHTML = \"\";\n //Append the game page to the main page\n document.body.appendChild(gameContent);\n }\n}", "function load() {\n _data_id = m_data.load(FIRST_SCENE, load_cb, preloader_cb);\n}", "function loadState(state) {\n // Clear everything first\n reservePile.hiddenStack.splice(0, reservePile.hiddenLength());\n reservePile.stack.splice(0, reservePile.getLength());\n stacks.forEach(stack => stack.stack.splice(0, stack.getLength()));\n piles.forEach(pile => pile.stack.splice(0, pile.getLength()));\n\n const unserialisedSections = decodeStateString(state);\n unserialisedSections.forEach((section, sectIndex) => {\n section.forEach((nestedSect, nestedIndex) => {\n nestedSect.forEach((card, index) => {\n const cardObject = getCardById(card.id);\n switch (sectIndex) {\n case 0:\n forcePutCard({ type: 'reserve', reference: reservePile, index: index + 100 }, cardObject);\n break;\n case 1:\n forcePutCard({ type: 'reserve', reference: reservePile, index: index }, cardObject);\n break;\n case 2:\n forcePutCard({ type: 'stack', reference: stacks[nestedIndex], index: index }, cardObject);\n break;\n case 3:\n forcePutCard({ type: 'pile', reference: piles[nestedIndex], index: index }, cardObject);\n break;\n }\n if (cardObject.revealed != card.revealed) {\n cardObject.setRevealedAnim(card.revealed);\n }\n });\n }); \n });\n}", "function loadContent(){\n pole = game.instantiate(new Pole(Settings.pole.size));\n pole.setColor(Settings.pole.color);\n pole.setPosition(Settings.canvasWidth /2 , Settings.canvasHeight /2);\n\n shield = game.instantiate(new Shield(pole));\n shield.getBody().immovable = true;\n shield.setColor(Settings.shield.color);\n\n player = game.instantiate(new Player(\"\"));\n player.setPole(pole);\n player.setShield(shield);\n pole.setPlayer(player);\n\n //Player labels, name is set once again when the user has filled in his/her name\n scoreLabel = game.instantiate(new ScoreLabel(player, \"Score: 0\"));\n scoreLabel.setPosition(Settings.label.score);\n\n nameLabel = game.instantiate(new Label(\"Unknown Player\"));\n nameLabel.setPosition(Settings.label.name);\n\n highscoreLabel = game.instantiate(new Label(\"Highscore: 0\"));\n highscoreLabel.setPosition(Settings.label.highscore);\n\n createTempImage();\n setTimeout(deleteTempImage, 3000);\n\n //Hide the canvas for the player until a username is filled in and accepted\n var gameElem = document.getElementById(\"gameCanvas\");\n gameElem.style.display=\"none\";\n}", "function setGameState(newGameState) {\n gameState = newGameState;\n}", "load() {\n let jsonState = localStorage.getItem('state')\n if (jsonState) {\n let parsedState = JSON.parse(jsonState)\n // Do this so we add in the defaults for any new state objects which are missing.\n if (parsedState.version !== stateVersion) {\n state = defaultState()\n } else {\n state = Object.assign(defaultState(), parsedState)\n }\n } else {\n state = defaultState()\n }\n }", "restore(game) {\n this.kingSlots.forEach((s, index) => s.load(game.kingSlots[index]));\n this.slots.forEach((s, index) => s.load(game.slots[index]));\n this.stub.load(game.stub);\n }", "function loadNewGames() \n{\n\n\tdoClassLoading('checkGameLoad2');\n\tloadList('@ADMINURI@/doloadgames.json', 'loadGames', \n\t\tfunction(resp) { loadGamesSuccessInner(resp, 0, 'loadGames'); },\n\t\tfunction(err) { loadError(err, 'loadGames'); });\n}", "LoadScene()\n {\n\n if ( this.__loaded )\n {\n console.error( \"Unable to load scene, already loaded \" )\n return;\n }\n\n this.LocalSceneObjects.forEach( element => {\n\n let _constructor = element[0];\n let _serializedCallback = element[1];\n \n let obj = this.Create( _constructor, GameObject.COMPONENT_INIT_MODES.NO_SYNC );\n _serializedCallback( obj );\n\n } );\n\n this.__loaded = true;\n }", "_initializeGameValues() {\n this.currentFPS = GameConfig.STARTING_FPS;\n this.scoreBoard.resetScore();\n\n this.player = new Player(this.gameView.getPlayerName(), \"white\");\n this.food = new Food(this.boardView.getRandomCoordinate(this.player.segments), \"lightgreen\");\n this.gameView.hideChangeNameButton();\n }", "gameInit() {\n\t\tthis.curGameData = new gameData.GameData(this.genome.length);\n\t\tthis.playHist = [];\n\t\tfor (let i = 0; i < this.hist.length; i++) {\n\t\t\tthis.playHist.push(this.hist[i]);\n\t\t}\n\t}", "function readState(data) {\n\n gamestate = data.val();\n\n}", "function loadLevel(){\n\n\t\t//saveChar(n, r, ge, go, l, t, a);\n\t\tnewLevel++;\n // Next we get to change the background\n //var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\tvar BG = PIXI.Texture.fromImage(currentArea.name + \".png\");\n\t doorOut.tint = 0x999966;\n\n\t\tconsole.log(\"\t\" + newLevel + \" \" + currentArea.name);\n\n\t\t// Gotta reset those chests, jsut gonna make new ones for now, will 'reset' them later.\n \t for(var i = 0; i < 5; i++){\n\n \t chests[i] = new chest(INDEX, i);\n\t chests[i].sprite.position.x = 650; //20 + (90 * i);\n \t chests[i].sprite.position.y = 42 + (80 * i); //50;\n \t stage.addChild(chests[i].sprite);\n \t }\n\t\t\n\t\t// Next we get to change the background\n \t//var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\t//areaBackground.setTexture(BG);\n\t\tareaBackground.texture = BG;\n //stage.addChild(areaBackground);\n\t}", "function GameState (state) {\n // Storage class that is passed to all players at end of turn\n this.Players = [] ;//Ordered array of players in game\n this.Name = \"\" ;// Game name\n this.id = \"\";\n this.Started = false\n this.GameOwner = 0; //Index into players array of player that owns game\n this.CurrentPlayer = 0; //Index into players array of current player\n // History is array of TurnStates keeping a detailed history of each turn.\n // Note first TurnState is only interesting in terms of initial bag state and each\n //player's tray state\n this.History = [];\n if (state) {\n this.Players = state.Players\n this.Name = state.Name\n this.id = state.id\n this.Started = state.Started \n if (state.GameOwner) this.GameOwner = state.GameOwner;\n if (state.CurrentPlayer) this.CurrentPlayer = state.CurrentPlayer;\n if (state.History ){\n var history = []\n for(var i=0;i<state.History.length;i++){\n var bag = new Bag(true, state.History[i].Bag.letters)\n var boardState = new BoardState(state.History[i].BoardState.letters)\n var turn = null;\n if (state.History[i].Turn) {\n turn = new Turn(state.History[i].Turn.Type, state.History[i].Turn.LettersIn, state.History[i].Turn.LettersOut, \n state.History[i].Turn.TurnNumber, state.History[i].Turn.Player, state.History[i].Turn.NextPlayer)\n }\n var trayStates = [];\n for(var j=0;j<state.History[i].TrayStates.length;j++){ \n trayStates.push( new TrayState(state.History[i].TrayStates[j].player, state.History[i].TrayStates[j].letters, state.History[i].TrayStates[j].score));\n }\n history.push( new TurnState(bag, boardState, trayStates, state.History[i].End, turn))\n }\n this.History = history ;\n }\n }\n this.GetNextPlayer = function() {\n var next = this.CurrentPlayer +1;\n if (next >= this.Players.length){\n next =0;\n }\n return next;\n }\n this.GetPlayers = function(){\n return this.Players;\n }\n this.GetCurrentPlayerIndex = function(){\n return this.CurrentPlayer\n }\n this.GetNumberOfPlayers = function(){\n return this.Players.length;\n }\n this.IsPlayer = function(playerName){\n for (var i=0;i<Players.length;i++){\n if (playerName == Players[i]) return true;\n }\n return false;\n }\n this.GetBoardState = function(){\n var boardState = null;\n var lastTurn = this.GetLastTurn();\n if (lastTurn){\n boardState = lastTurn.GetBoardState();\n }\n return boardState;\n }\n this.CloneLastTurnState =function(){\n var last = this.GetLastTurnState();\n return last.Clone();\n }\n this.GetLastTurnState = function(){\n var lastTurnState = null;\n if (this.History.length >0 ) {\n lastTurnState = this.History[this.History.length-1]\n }\n return lastTurnState;\n }\n this.HasGameEnded = function(){\n var ended = false;\n var lastTurnState = this.GetLastTurnState();\n if (lastTurnState){\n ended = lastTurnState.End;\n }\n return ended;\n }\n \n this.GetLastTurn = function(){\n //Actually only gets last proper turn because there is no turn object in first turnState\n var lastTurn = null;\n if (this.History.length >=1 ) {\n lastTurn = this.History[this.History.length-1].Turn;\n }\n return lastTurn;\n }\n this.GetMyTrayState =function (playerName) {\n var trayState = null;\n if (this.History.length >=1 ) {\n var trays = this.History[this.History.length-1].GetTrayStates();\n if (trays) {\n for (var i=0;i<trays.length;i++){\n if (trays[i].GetPlayer() == playerName){\n trayState = trays[i]\n break;\n }\n }\n }\n }\n return trayState;\n }\n this.AddTurnState = function(turnState){\n this.History.push(turnState);\n }\n this.HasScores = function(){\n return (this.History.length > 0);\n }\n this.GetBagSize = function(){\n var count = 0;\n if (this.History.length >=1 )\n {\n count = this.History[this.History.length-1].GetBagSize();\n }\n return count;\n }\n this.GetPlayerScore = function (playerName){\n var lastTurnState = this.History[this.History.length-1];\n return lastTurnState.GetPlayerScore(playerName);\n }\n this.GetGameOwner = function(){\n return this.Players[ this.GameOwner];\n }\n this.RemoveLastState = function(){\n var lastTurnState = this.History.pop();\n var newLastTurn = this.GetLastTurn();\n if (newLastTurn){\n this.CurrentPlayer = newLastTurn.NextPlayer;\n }else{\n //This is same code at start game first player is first tray state\n this.SetCurrentPlayerByName(lastTurnState.GetTrayState(0).GetPlayer());\n }\n }\n this.SetCurrentPlayerByName = function(playerName){\n this.CurrentPlayer = 0\n for (var i=0;i<this.Players.length;i++){\n if (this.Players[i] == playerName){\n this.CurrentPlayer = i;\n break;\n }\n }\n }\n this.SetCurrentPlayer = function(index){\n this.CurrentPlayer = index; \n }\n this.GetCurrentPlayer = function(){\n var player = \"\";\n if (this.CurrentPlayer <= (this.Players.length -1) ){\n player = this.Players[this.CurrentPlayer];\n }\n return player\n }\n}", "static loadGames() {\n let gameList = [];\n let dataFile = fs.readFileSync('./data/currentGames.json', 'utf8');\n if (dataFile === '') return gameList;\n\n let gameData = JSON.parse(dataFile);\n if (!Array.isArray(gameData)) {\n gameData = [gameData];\n }\n gameData.forEach((element) => {\n gameList.push(\n new Game(\n element.Name,\n element.Creator,\n element.CreatedOn,\n element.Players\n )\n );\n });\n\n return gameList;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if a specified element is a top level DOM element
function isTopLevelEl(el) { if (!el) { return false; } var tn = propAttr(el, 'tagName'); tn = tn ? tn.toLowerCase() : null; return tn === 'html' || tn === 'head'; }
[ "function isDescendantOf(element, tagName) {\n const tagNameTarget = tagName.toUpperCase();\n\n for (let node = element; node && node != document; node = node.parentNode) {\n if (node.tagName.toUpperCase() === tagNameTarget) return true;\n }\n\n return false;\n}", "function inDOM() {\n var closestBody = $that.closest(body),\n isInDOM = !!closestBody.length;\n return isInDOM;\n }", "function hasSomeParentTheClass(element, classname) {\n element = element.target;\n if (element.className.split(' ').indexOf(classname)>=0) return true;\n return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);\n}", "function singleChildContentTagExists(element)\n{\n // Define a list of alloed tags for the inner content tag. There should be one and only one of these tags as element child\n var allowedContentTags = [\"blockquote\", \"dd\", \"div\", \"form\", \"center\", \"table\", \"span\", \"input\", \"textarea\", \"select\", \"img\"];\n\n\tif(element == undefined || element == null)\n\t\treturn false;\n\n\tif(element.hasChildNodes())\n\t{\n\t\tvar childCnt = element.childNodes.length;\n\t\tvar eltCount = 0;\n\n\t\tfor(var i=0; i<childCnt; i++)\n\t\t{\n\t\t\tvar potChildCurr = element.childNodes[i];\n\t\t\tvar nodeType = potChildCurr.nodeType;\n\t\t\tif(nodeType == 1) // element node\n\t\t\t{\n\t\t\t\ttagNameStr = potChildCurr.tagName.toLowerCase();\n if(dwscripts.findInArray(allowedContentTags, tagNameStr) == -1)\n\t\t\t\t\treturn false;\n\n\t\t\t\tif(eltCount == 0)\n\t\t\t\t\teltCount++\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse if(nodeType == 3) // Node.TEXT_NODE\n\t\t\t{\n\t\t\t\tif(potChildCurr.data.search(/\\S/) >= 0) // there is a non whitespace character available\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif(eltCount==1)\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}", "function isElementOfType(element, Component) {\n var _element$props;\n\n if (element == null || ! /*#__PURE__*/React.isValidElement(element) || typeof element.type === 'string') {\n return false;\n }\n\n const {\n type: defaultType\n } = element; // Type override allows components to bypass default wrapping behavior. Ex: Stack, ResourceList...\n // See https://github.com/Shopify/app-extension-libs/issues/996#issuecomment-710437088\n\n const overrideType = (_element$props = element.props) == null ? void 0 : _element$props.__type__;\n const type = overrideType || defaultType;\n const Components = Array.isArray(Component) ? Component : [Component];\n return Components.some(AComponent => typeof type !== 'string' && isComponent(AComponent, type));\n} // Returns all children that are valid elements as an array. Can optionally be", "isAncestor(value) {\n return isPlainObject(value) && Node$1.isNodeList(value.children);\n }", "isInsideAList(element) {\n let parent = element.parentNode;\n while (parent !== null) {\n if (parent.nodeName === 'UL' || parent.nodeName === 'OL') {\n return true;\n }\n parent = parent.parentNode;\n }\n return false;\n }", "function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }", "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}", "exists(el)\n {\n if(typeof(el) != 'undefined' && el != null) { return true; } // If not undefined or null, then exists.\n return false;\n }", "function _elementIsChildOfMapView(element) {\n\t if (element.className.indexOf('fm-mapview') >= 0) {\n\t return true;\n\t }\n\t return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false;\n\t }", "function ancestorHasId(el, id) {\n var outcome = (el.id === id);\n while (el.parentElement && !outcome) {\n el = el.parentElement;\n outcome = (el.id === id);\n }\n return outcome;\n}", "function is_ancestor(node, target)\r\n{\r\n while (target.parentNode) {\r\n target = target.parentNode;\r\n if (node == target)\r\n return true;\r\n }\r\n return false;\r\n}", "function get_parent(el, class_name) {\n var elem = el.parentElement;\n while (!elem.classList.contains(class_name)) {\n if (elem.classList.contains(\"main\")) {\n return null;\n }\n elem = elem.parentElement;\n }\n return elem;\n}", "_isHeading(elem) {\n return elem.tagName.toLowerCase() === 'howto-accordion-heading';\n }", "_hasScrolledAncestor(el, deltaX, deltaY) {\n if (el === this.scrollTarget || el === this.scrollTarget.getRootNode().host) {\n return false;\n } else if (\n this._canScroll(el, deltaX, deltaY) &&\n ['auto', 'scroll'].indexOf(getComputedStyle(el).overflow) !== -1\n ) {\n return true;\n } else if (el !== this && el.parentElement) {\n return this._hasScrolledAncestor(el.parentElement, deltaX, deltaY);\n }\n }", "function extUtils_isAContainerTag(theTagName)\n{\n if ( !theTagName )\n return false;\n\n var tag = \" \" + theTagName.toUpperCase() + \" \";\n var containerTags = \" P H1 H2 H3 H4 H5 H6 LI LAYER DIV TD TABLE FORM PRE BLOCKQUOTE OL UL PRE BODY \";\n\n return ( containerTags.indexOf(tag) != -1);\n}", "function findNearestNodeEl(el) {\n while (el !== document.body && !el.classList.contains('blocks-node')) {\n el = el.parentNode;\n }\n return el === document.body? null : el;\n}", "findNodeFromEl(el) {\n if(el) {\n let match = el.id.match(/block-node-(.*)/);\n return match && (match.length > 1) && this.ast.getNodeById(match[1]);\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
action for the Eval & start Job menu item on Jobs menu.
static start_job_menu_item_action() { let full_src = Editor.get_javascript() let selected_src = Editor.get_javascript(true) let sel_start_pos = Editor.selection_start() let sel_end_pos = Editor.selection_end() let start_of_job_maybe = Editor.find_backwards(full_src, sel_start_pos, "new Job") let start_of_job_pos let end_of_job_pos let job_src = null //if this is not null, we've got a valid job surrounds (or is) the selection. let sel_is_instructions = false if(start_of_job_maybe !== null){ [start_of_job_pos, end_of_job_pos] = Editor.select_call(full_src, start_of_job_maybe) } if(end_of_job_pos && (end_of_job_pos > sel_start_pos)){ //sel is within a job, but we don't know if its //instruction selection or just within the job yet. job_src = full_src.substring(start_of_job_pos, end_of_job_pos) let do_list_start_pos = full_src.indexOf("do_list:", start_of_job_pos) if((do_list_start_pos === -1) || (do_list_start_pos > end_of_job_pos)) {} //weird, looks like Job has no do_list, //but ok, we just have the whole Job to execute. else if (do_list_start_pos < sel_start_pos) { //our selected_src should be instructions in the do_list sel_is_instructions = true } } if (job_src === null) { //no job def so we're going to make our own. //warning("There's no Job definition surrounding the cursor.") var selection = Editor.get_javascript(true).trim() if (selection.endsWith(",")) { selection = selection.substring(0, selection.length - 1) } if (selection.length > 0){ //if (selection.startsWith("[") && selection.endsWith("]")) {} //perhaps user selected the whole do_list. but //bue we can also have a single instr that can be an array. //since it's ok for a job to have an extra set of parens wrapped around its do_list, //just go ahead and do it. //else { //plus selection = "[" + selection + "]" sel_start_pos = sel_start_pos - 1 //} var eval2_result = eval_js_part2(selection) if (eval2_result.error_type) {} //got an error but error message should be displayed in output pane automatmically else if (Array.isArray(eval2_result.value)){ //got an array, but is it a do_list of multiple instructions? let do_list if(!Instruction.is_instructions_array(eval2_result.value)){ //might never hit, but its an precaution do_list = [eval2_result.value] } if (Job.j0 && Job.j0.is_active()) { Job.j0.stop_for_reason("interrupted", "Start Job menu action stopped job.") setTimeout(function() { Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos, do_list, selection)}, (Job.j0.inter_do_item_dur * 1000 * 2) + 10) //convert from seconds to milliseconds } else { Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos, eval2_result.value, selection) } } else { shouldnt("Selection for Start job menu item action wasn't an array, even after wrapping [].") } } else { warning("When choosing the Eval&Start Job menu item<br/>" + "with no surrounding Job definition,<br/>" + "you must select exactly those instructions you want to run.") } } //we have a job. else { const eval2_result = eval_js_part2(job_src) if (eval2_result.error_type) { } //got an error but error message should be displayed in Output pane automatically else { let job_instance = eval2_result.value if(!sel_is_instructions){ job_instance.start() } else if (selected_src.length > 0){ //sel is instructions let do_list_result = eval_js_part2("[" + selected_src + "]") //even if we only have one instr, this is still correct, esp if that one starts with "function(). //if this wraps an extra layer of array around the selected_src, that will still work pretty well. if (do_list_result.error_type) { } //got an error but error message should already be displayed else { job_instance.start({do_list: do_list_result.value}) } } else { //no selection, so just start job at do_list item where the cursor is. const [pc, ending_pc] = job_instance.init_show_instructions(sel_start_pos, sel_end_pos, start_of_job_pos, job_src) job_instance.start({show_instructions: true, inter_do_item_dur: 0.5, program_counter: pc, ending_program_counter: ending_pc}) } } } }
[ "function show_job(page, process_name) {\n // Save info of the opened tab\n msg_or_job = 'Job';\n ProcessJobUpdate(page, process_name, true);\n}", "function showJobSelect(){\r\n showSelect(appendJobSelect, jobMoveDrop, empMoveCancel, showMoveEmp, \"jobSelected\", \"jobsArray\", \"jobs\", showFullEmpMoveMenu, hideFullEmpMoveMenu);\r\n}", "function goToJob() {\r\n\tvar exitURL = $relocateApplyURL;\r\n\r\n\t// Modifies the apply URL when an apply ID is available.\r\n\tif ( typeof j2w.applyID === 'number' ) {\r\n\t\texitURL += j2w.applyID + '/';\r\n\r\n\t\t// Pass the social source along, if defined.\r\n\t\tif ( attributes.socialsrc ) {\r\n\t\t\tswitch ( attributes.socialsrc ) {\r\n\t\t\t\tcase 'li':\r\n\t\t\t\t\texitURL += '?type=linkedin';\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 'fb':\r\n\t\t\t\t\texitURL += '?type=facebook';\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif ( typeof $myApplyURL == 'string' && $myApplyURL.length ) {\r\n\t\t// Determine the final redirection URL and make sure we don't count the apply twice\r\n\t\tvar targetURL = exitURL;\r\n\r\n\t\t// Redirects to the ATS for the job, in a new window, if the site setup is so configured.\r\n\t\tif ( window.$popApply ) {\r\n\t\t\tvar winSizeFactor = 0.9;\r\n\r\n\t\t\t// Calculate window width and X position\r\n\t\t\tvar bodyWidth = $('body').width();\r\n\t\t\tvar myWinWidth = bodyWidth * winSizeFactor;\r\n\t\t\tvar myXPosition = (bodyWidth - myWinWidth)/2;\r\n\r\n\t\t\t// Calculate window height and Y position\r\n\t\t\tvar bodyHeight = $('body').height();\r\n\t\t\tvar myWinHeight = bodyHeight * winSizeFactor;\r\n\t\t\tvar myYPosition = (bodyHeight - myWinHeight)/2;\r\n\r\n\t\t\t// Try to open the new window\r\n\t\t\tvar myWindowOpenString = windowOpener(targetURL,'jobwindow','width='+ myWinWidth + ',height=' + myWinHeight + ',screenX=' + myXPosition + ',screenY=' + myYPosition + ',left=' + myXPosition + ',top=' + myYPosition + ',location=yes,status=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes') ;\r\n\r\n\t\t\t// If the ATS window opens, redirect from our Talent Community apply page to the job page, otherwise, show a pop-up blocker message.\r\n\t\t\tif ( myWindowOpenString ) {\r\n\t\t\t\tdefaultPleaseWait();\r\n\r\n\t\t\t\t// Return to the job page the user applied on, if available, or the home page, if not.\r\n\t\t\t\tattributes.tcReturnURL.length ? document.location.href = attributes.tcReturnURL : document.location.href = '/';\r\n\t\t\t} else {\r\n\t\t\t\t// Make sure to add the pop-up blocker message div only once\r\n\t\t\t\tif ( $('#popupblocker').length === 0 ) {\r\n\t\t\t\t\t$('body').append('<div id=\"popupblocker\"></div>');\r\n\r\n\t\t\t\t\t$('#popupblocker')\r\n\t\t\t\t\t\t.dialog({\r\n\t\t\t\t\t\t\tautoOpen:true,\r\n\t\t\t\t\t\t\theight: 160,\r\n\t\t\t\t\t\t\twidth: 500,\r\n\t\t\t\t\t\t\tmodal: true,\r\n\t\t\t\t\t\t\tcloseOnEscape: false,\r\n\t\t\t\t\t\t\ttitle: jsStr.tcpopupblockerdetected,\r\n\t\t\t\t\t\t\tdraggable: true,\r\n\t\t\t\t\t\t\tresizable: false\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.html('<p>Your browser blocked opening the job application in a new window.</p><p>Please allow pop-up windows for this site and <a id=\"tryagain\" href=\"javascript://\">try again</a>.</p>');\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$('#popupblocker').dialog('open');\r\n\t\t\t\t}\r\n\r\n\t\t\t\t$('#tryagain').live('click',function(){\r\n\t\t\t\t\t$('#popupblocker').dialog('close');\r\n\t\t\t\t\tnextEnable();\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Open the job in the normal window\r\n\t\t\tdocument.location.href = exitURL;\r\n\t\t}\r\n\t}\r\n}", "function performActions() {\n\n // prepare event data\n event_data = $.integrate( entry_data, event_data );\n event_data.content = content_elem;\n event_data.entry = entry_elem;\n delete event_data.actions;\n\n // perform menu entry actions\n if ( entry_data.actions )\n if ( typeof ( entry_data.actions ) === 'function' )\n entry_data.actions( $.clone( event_data ), self );\n else\n entry_data.actions.forEach( action => $.action( action ) );\n\n // perform callback for clicked menu entry\n self.onclick && $.action( [ self.onclick, $.clone( event_data ), self ] );\n\n }", "function getAction() {\r\n\r\n return( action );\r\n\r\n }", "saveJob(item) {\n this.props.sendJobToRedux(item);\n alert('Posting added to your Saved Jobs!')\n }", "function onOpen() {\r\n var sheet = SpreadsheetApp.getActiveSpreadsheet();\r\n var entries = [{\r\n name : \"SendOneEntry\",\r\n functionName : \"failedFormSubmit\"\r\n }];\r\n sheet.addMenu(\"GBSP\", entries);\r\n}", "static onSelect() {\n const node = Navigator.byItem.currentNode;\n if (MenuManager.isMenuOpen() || node.actions.length <= 1 ||\n !node.location) {\n node.doDefaultAction();\n return;\n }\n\n ActionManager.instance.menuStack_ = [];\n ActionManager.instance.menuStack_.push(MenuType.MAIN_MENU);\n ActionManager.instance.actionNode_ = node;\n ActionManager.instance.openCurrentMenu_();\n }", "function performSelectedAction(){\r\n\tswitch(selectedAction){\r\n\tcase GameScreenActionType.mainmenu:\r\n\t\tperformQuit();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.hints:\t\r\n\t\ttoggleHints();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.difficulty:\r\n\t\tperformDifficultyAction();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.gamestate:\r\n\t\t\r\n\t\tbreak;\r\n\t}\r\n}", "function onEntryAction(evt) {\n if ($(this).hasClass(\"edit\")) {\n zdPage.navigate(\"edit/existing/\" + $(this).data(\"entry-id\"));\n //window.open(\"/\" + zdPage.getLang() + \"/edit/existing/\" + $(this).data(\"entry-id\"));\n }\n }", "function startJob(jobid,onstarted)\n{\n var req = new XMLHttpRequest();\n req.onreadystatechange = function() {\n if (req.readyState == 4 && req.status == 200)\n {\n if (onstarted != null)\n {\n onstarted(jobid);\n }\n }\n }\n req.open(\"GET\",\"/api/solve-background?token=\"+jobid,true);\n req.send();\n}", "function jumpToURL(formName,menuName) {\r\n\t var obj = eval(\"document.\" + formName + \".\" + menuName);\r\n\t var index = obj.selectedIndex;\r\n\t var url = eval(menuName + \"_URLs[\" + index + \"]\");\r\n\t if (url != \"\") {\r\n\t location.href=url;\r\n\t }\r\n\t}", "function menuHandler(){\n if(command.getChecked()){\n command.setChecked(false);\n prefs.set('enabled',false);\n return;\n }\n command.setChecked(true); \n prefs.set('enabled',true);\n var st = startTabEx();\n }", "function DoEditSCWorkItem_clicked(newitemid) {\n ModalWorkItem = new C_WorkLog(null);\n ModalNewWorkItem = newitemid === -1;\n if (newitemid !== -1) {\n ModalWorkItem = BackendHelper.FindWorkItem(newitemid);\n }\n else {\n ModalWorkItem.UserId = OurUser.id;\n ModalWorkItem.Date = C_YMD.Now();\n }\n\n // build a dropdown of users to select from\n let vol = BackendHelper.FindAllVolunteers();\n vol.sort(function (a, b) {\n return a.Name.localeCompare(b.Name);\n });\n\n let usersChoices = [];\n vol.forEach(function (u) {\n let c = { \"text\": u.Name, \"item\" : u.id.toString() };\n usersChoices.push(c);\n });\n\n let userselitem = ModalWorkItem.UserId.toString();\n\n let usersOptions = {\n \"choices\": usersChoices,\n \"selitem\" : userselitem,\n \"dropdownid\" : \"vitasa_dropdown_users\",\n \"buttonid\" : \"vitasa_button_selectuser\"\n };\n usersDropDown = new C_DropdownHelper(usersOptions); // this must be in the global space\n usersDropDown.SetHelper(\"usersDropDown\");\n usersDropDown.CreateDropdown();\n\n BackendHelper.Filter.CalendarDate = ModalWorkItem.Date;\n $('#vitasa_scvolhours_edit_date_i')[0].value = ModalWorkItem.Date.toStringFormat(\"mmm dd, yyyy\");\n $('#vitasa_workitem_hours')[0].value = ModalWorkItem.Hours.toString();\n $('#vitasa_modal_scvolhours_sitename')[0].innerText = OurSite.Name;\n $('#vitasa_modal_title').innerText = \"Work Item\";\n\n DrawSCVolHoursCalendar();\n\n $('#vitasa_modal_scworkitem').modal({});\n\n BackendHelper.SaveFilter()\n .catch(function (error) {\n console.log(error);\n })\n}", "function ExpandedTabUpdate(process_name, msg_or_job, inside_page) {\n $(\"#\" + process_name).addClass(\"table_row_selected\");\n if (msg_or_job == 'Msg') {\n ProcessMsgUpdate(inside_page, process_name);\n }\n else { \n ProcessJobUpdate(inside_page, process_name);\n }\n}", "function empEndJob() {\n\t// Set control variable\n\temployeeIsWorking = false;\n\t\n\t// Hide all employee images\n\tempHideAll();\n\n\t// Show employee image getting the job\n\tif (powerUp) {\n\t\t$(\"#emp_up_2\").show();\n\t}\n\telse {\n\t\t$(\"#emp_stress_2\").show();\n\t}\n\n\t// Set timer to give up the ended job\n\tsetTimeout(\"empNoJob()\", 300);\n}", "function onOpen() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(),\n menuItems = [{name: \"Item1\", functionName: \"function1\"}, \n {name: \"Item2\", functionName: \"function2\"}];\n ss.addMenu(\"My Menu\", menuItems);\n}", "function checkCurrentJob() {\n if (isCurrentJobApplied()) {\n let params = getURLParams()\n let currentJobId = params.get('currentJobId')\n\n let newAppliedJobs = getAppliedJobs()\n if (!newAppliedJobs.includes(currentJobId)) {\n console.info(`[Helper] Adding new job ${currentJobId} to applied list`)\n\n newAppliedJobs.push(currentJobId)\n setAppliedJobs(newAppliedJobs)\n }\n }\n}", "function onRequest(cmdContext) {\n\t// we first run the workflow rule and then\n\t// hide the request button and change the move status to Requested\n\tvar form = cmdContext.command.getParentPanel();\n\tvar mo_id = form.getFieldValue('mo.mo_id');\n\n try {\n var result = Workflow.callMethod('AbMoveManagement-MoveService-requestIndividualMove', mo_id);\n\t\tform.refresh();\n } catch (e) {\n Workflow.handleError(e);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The "watch" function is called at the DOM's animation frame rate continously
watch() { if (this.shouldUpdate()) { this.trigger('change', this.rect); } if(!this.shouldStop){ window.requestAnimationFrame(() => this.watch()); } }
[ "notify_speed_update() {\n this.speed_update = true;\n }", "function animate() {\n requestAnimationFrame(animate);\n // Insert animation frame to update here.\n }", "refresh(timeNow, enableAnimation) {\n }", "stopWatchIntervalHandler() {\n if (this.frames < 60) {\n this.frames++;\n if (this.handle) {\n this.clearInterval();\n }\n this.lastFrame = Date.now();\n this.handle = requestAnimationFrame(this.stopWatchIntervalHandler.bind(this));\n return;\n }\n this.frames = 0;\n this.running() ? this.decrementSeconds() : this.clearInterval();\n this.onTimeFormatChangedHanders.forEach(handler => {\n handler(this, this.time);\n });\n if (this.handle) {\n this.clearInterval();\n }\n this.lastFrame = Date.now();\n this.handle = requestAnimationFrame(this.stopWatchIntervalHandler.bind(this));\n }", "watch (fileChanged) {\n setTimeout(() => {\n fileChanged({\n change: \"modified\",\n path: \"file2.txt\",\n source: this.file2Source\n });\n }, 100);\n }", "resetWatch() {\n this.reset();\n this.print();\n }", "function watch(sync, e, events, channel) {\n for (var i = 0; i < events.length; ++i) {\n addEventListener(e, events[i], function () {\n channel.ready = true;\n sync.update();\n });\n }\n }", "function _initWatchers()\n {\n var lasth = null, fn; // previous body height value\n\n function childSend() \n {\n var h = height(), l = childs.length, i = 0;\n\n if (!l || lasth === h) {\n return;\n }\n\n lasth = h;\n\n for (; i < l; i += 1) {\n childs[i].sendHeight();\n }\n } \n\n function parentSend() \n {\n var l = parents.length, i = 0, parent;\n\n if (!l) {\n return;\n }\n\n for (; i < l; i += 1) {\n parent = parents[i];\n parent.sendMessage('position', offset.encode(offset(parent.iframe)));\n }\n } \n\n fn = throttle(parentSend, 16);\n\n on('resize', fn);\n on('scroll', fn);\n\n setInterval(childSend, 16);\n }", "function watchFiles() {\n watch('source/*.*', build);\n}", "run() {\n this.pid = setInterval(animate, 200, this);\n //let pathInterval = null;\n //animates the visit portion of the animation then passes on to path\n function animate(animation) {\n //if no more steps\n if(!animation.steps) {\n clearInterval(animation.id);\n return;\n }\n const cur = animation.popStep();\n cur.run();\n }\n }", "function loop(){\n requestAnimationFrame(loop);\n //Get waveform values in order to draw it.\n var waveformValues = waveform.analyse();\n drawWaveform(waveformValues);\n }", "function watchScreenFrame() {\n\t\tif (screenFrameSizeTimeoutId !== undefined) {\n\t\t\treturn\n\t\t}\n\t\tconst checkScreenFrame = () => {\n\t\t\tconst frameSize = getCurrentScreenFrame()\n\t\t\tif (isFrameSizeNull(frameSize)) {\n\t\t\t\tscreenFrameSizeTimeoutId = setTimeout(\n\t\t\t\t\tcheckScreenFrame,\n\t\t\t\t\tscreenFrameCheckInterval,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tscreenFrameBackup = frameSize\n\t\t\t\tscreenFrameSizeTimeoutId = undefined\n\t\t\t}\n\t\t}\n\t\tcheckScreenFrame()\n\t}", "function watchTask() {\n // watch(\n // [files.cssPath, files.jsPath, files.imgPath],\n // parallel(cssTask, jsTask, imgSquash)\n // );\n watch([files.cssPath, files.jsPath], parallel(cssTask, jsTask));\n}", "function updateClock(){\n document.getElementById(\"app\").innerHTML = currentTime();\n\n updateStopWatches();\n}", "function setBufferChecker() {\n bufferChecker = window.setInterval(function() {\n var allBuffered = true;\n\n var currTime = getCurrentTime(masterVideoId);\n\n for (var i = 0; i < videoIds.length; ++i) {\n var bufferedTimeRange = getBufferTimeRange(videoIds[i]);\n if (bufferedTimeRange) {\n var duration = getDuration(videoIds[i]);\n var currTimePlusBuffer = getCurrentTime(videoIds[i]) + bufferInterval;\n var buffered = false;\n for (j = 0;\n (j < bufferedTimeRange.length) && !buffered; ++j) {\n currTimePlusBuffer = (currTimePlusBuffer >= duration) ? duration : currTimePlusBuffer;\n if (isInInterval(currTimePlusBuffer, bufferedTimeRange.start(j), bufferedTimeRange.end(j))) {\n buffered = true;\n }\n }\n allBuffered = allBuffered && buffered;\n } else {\n // Do something?\n }\n }\n\n if (!allBuffered) {\n playWhenBuffered = true;\n ignoreNextPause = true;\n for (var i = 0; i < videoIds.length; ++i) {\n pause(videoIds[i]);\n }\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:buffering\", []);\n } else if (playWhenBuffered && !hitPauseWhileBuffering) {\n playWhenBuffered = false;\n play(masterVideoId);\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:bufferedAndAutoplaying\", []);\n } else if (playWhenBuffered) {\n playWhenBuffered = false;\n $(document).trigger(\"sjs:bufferedButNotAutoplaying\", []);\n }\n }, checkBufferInterval);\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 }", "observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }", "_startAnimationLoop() {\n\t\t\tconst xTermMaterials = Array.from(this._xTermLayerMap.values());\n\t\t\tconst timeUniforms = this._shaderPasses.filter(pass => {\n\t\t\t\treturn pass.getFullscreenMaterial().uniforms.time !== undefined;\n\t\t\t}).map(pass => {\n\t\t\t\treturn pass.getFullscreenMaterial().uniforms.time;\n\t\t\t});\n\n\t\t\tconst xTermMaterialsLength = xTermMaterials.length;\n\t\t\tconst timeUniformsLength = timeUniforms.length;\n\n\t\t\tconst that = this;\n\n\t\t\t(function render() {\n\t\t\t\tthat._animationId = window.requestAnimationFrame(render);\n\n\t\t\t\tfor (let i = 0; i < timeUniformsLength; i++) {\n\t\t\t\t\ttimeUniforms.value = that._clock.getElapsedTime();\n\t\t\t\t}\n\n\t\t\t\tfor (let i = 0; i < xTermMaterialsLength; i++) {\n\t\t\t\t\txTermMaterials[i].map.needsUpdate = true;\n\t\t\t\t}\n\n\t\t\t\tthat._composer.render(that._clock.getDelta());\n\t\t\t})();\n\t\t}", "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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether the underlying truth is a location
isLocation() { return this.truthObject.constructor.name == 'Location' }
[ "isLocation(value) {\n return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value);\n }", "function locationStatus(location, grid) {\n var gridWidth = grid.length;\n var gridHeight = grid[0].length;\n var x = location.x;\n var y = location.y;\n\n if (location.x < 0 ||\n location.x >= gridWidth ||\n location.y < 0 ||\n location.y >= gridHeight) {\n\n // location is not on the grid--return false\n return 'Invalid';\n } else if (grid[x][y] === 'Goal') {\n return 'Goal';\n } else if (grid[x][y] !== 'Empty') {\n // location is either an obstacle or has been visited\n return 'Blocked';\n } else {\n return 'Valid';\n }\n }", "function is_unit_visible(punit)\n{\n if (punit == null || punit['tile'] == null) return;\n\n var u_tile = index_to_tile(punit['tile']);\n var r = map_to_gui_pos(u_tile['x'], u_tile['y']);\n var unit_gui_x = r['gui_dx'];\n var unit_gui_y = r['gui_dy'];\n\n if (unit_gui_x < mapview['gui_x0'] || unit_gui_y < mapview['gui_y0']\n || unit_gui_x > mapview['gui_x0'] + mapview['width'] \n || unit_gui_y > mapview['gui_y0'] + mapview['height']) {\n return false;\n } else {\n return true;\n }\n\n}", "function getValidLocation( reading ) {\n\n if ( reading['x'].length > 0 && reading['y'].length > 0 ) {\n return 'X:' + reading['x'][0] + ' and Y:' + reading['y'][0];\n }\n else { return false; }\n //Logic for determining if tripped sensors can result in a valid x,y plotting\n\n //Get all groups of consecutive trips for X\n //If there is more than one group return false\n\n //Get all groups of consecutive trips for Y\n //If there is more than one group return false\n\n //If exactly 1 group consecutive trips for X and Y, get midpoint for both X and Y\n // If odd number of consective trips, set coord to middle one\n // If even number of consecutive trips, set coord to midpoint of the two middle ones\n\n //If X and Y coord set return true\n //Else return false\n\n}", "function isFree(aLocation) {\n //for (var liste in locations) {\n // for (var i in liste) {\n // if (i.x == aLocation.x && i.y == aLocation.y) {\n // return false;\n // }\n // }\n //}\n return true;\n}", "function isAt(x, y){\n for(var i = 0; i < tileArray.length; i++){\n if(tileArray[i]._x == x && tileArray[i]._y == y){\n return true;\n }\n }\n return false;\n }", "function canPlace() {\r\n var pos = getLocation(parameters.openLocations[parameters.choice]);\r\n for (length = 0; length < parameters.word.length; length++) {\r\n if (alphabetSoup[pos.row][pos.col] !== 0 && alphabetSoup[pos.row][pos.col] !== parameters.word[length]) {\r\n parameters.openLocations.splice(parameters.choice, 1);\r\n return false;\r\n }\r\n pos = nextLocation(pos.row, pos.col);\r\n }\r\n return true;\r\n }", "function didPlayerMove (loc) {\n\t\t\tvar lastMove = game.prevMoveId;\n\t\t\tif (typeof loc === 'string') {\n\t\t\t\treturn loc === lastMove;\n\t\t\t} else {\n\t\t\t\tfor (var key in loc) {\n\t\t\t\t\tif (loc[key] === lastMove) {\n\t\t\t\t\t\tconsole.log('from didPlayerMove : ' + loc[key]);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}", "function isOpenPos(x, y) {\n\tif (x < 0 && x >= canvasWidth / pieceSize) {\n\t\treturn false;\n\t}\n\tif (y < 0 && y >= canvasHeight / pieceSize) {\n\t\treturn false;\n\t}\n\n\tswitch(board[y][x]) {\n\t\tcase 3: // Wall\n\t\t\treturn false;\n\t\tcase 2: // Monster\n\t\t\treturn false;\n\t\tcase 1: // Player\n\t\t\treturn false;\n\t\tcase 0: // Empty\n\t\t\treturn true;\n\t}\n}", "canMove(tile) {\r\n if (abs(tile.mapX - this.mapX) <= this.info.movement &&\r\n abs(tile.mapY - this.mapY) <= this.info.movement) {\r\n if (tile.unit) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "checkPosition (y, x) {\n\t\t// Checks position of coordinates\n\t\treturn this.grid[y][x] === 0;\n\t}", "function checkLocation(){\r\n\tif (guylocation.value == null || guylocation.value == \"\"){\r\n\t\temptyFieldsArray.push(\" Location\");\r\n\t\tborderRed(guylocation);\r\n\t\treturn true;\r\n\t}\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}", "isStart(editor, point, at) {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false;\n }\n\n var start = Editor.start(editor, at);\n return Point.equals(point, start);\n }", "function isLocationInBox(location, cornerA, cornerB) {\n return (location.x >= cornerA.x && location.y >= cornerA.y && location.z >= cornerA.z &&\n location.x <= cornerB.x && location.y <= cornerB.y && location.z <= cornerB.z);\n }", "checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }", "isInsideMap(pos) {\n if(pos.x < this.map.length && pos.x >= 0 && pos.y < this.map[0].length && pos.y >= 0) {\n return true;\n }\n return false;\n }", "function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}", "hasBlockAt(position) {\n\t\tconst xVals = this.blocks.get(position.y);\n\t\treturn (xVals && xVals.has(position.x)) || false;\n\t}", "isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if version is >= minimum
function compareSemVer(version, minimum) { version = parseSemVer(version); minimum = parseSemVer(minimum); var versionNum = version.major * 10000 * 10000 + version.minor * 10000 + version.patch; var minimumNum = minimum.major * 10000 * 10000 + minimum.minor * 10000 + minimum.patch; return versionNum >= minimumNum; }
[ "function validSemanticVersion (version, minimum) {\n version = parseSemVer(version)\n minimum = parseSemVer(minimum)\n\n var versionNum = (version.major * 100000 * 100000) +\n (version.minor * 100000) +\n version.patch\n var minimumNum = (minimum.major * 100000 * 100000) +\n (minimum.minor * 100000) +\n minimum.patch\n\n return versionNum >= minimumNum\n }", "function checkMinVersion() {\n const majorVersion = Number(process.version.replace(/v/, '').split('.')[0]);\n if (majorVersion < NODE_MIN_VERSION) {\n $$.util.log('Please run Subscribe with Google with node.js version ' +\n `${NODE_MIN_VERSION} or newer.`);\n $$.util.log('Your version is', process.version);\n process.exit(1);\n }\n}", "function filterFromVersion(file) {\n if (fromVersion) { \n if (direction == 'down') {\n return fromVersion;\n } else {\n return semver.gt(file.version, fromVersion);\n }\n }\n else { return true; }\n }", "function versionIsRange(version) {\n return version.includes('-');\n}", "function filterToVersion(file) {\n if (toVersion) {\n if (direction !== null && direction =='down') {\n return semver.gte(file.version, toVersion);\n } else {\n return semver.lte(file.version, toVersion);\n }\n }\n else {\n return true;\n }\n }", "function isMajorSemverDiff(diff) {\n return diff.includes(SemverReleaseTypes.Major);\n}", "function requires(version) {\n\tvar s = version.split(\".\");\n\tassert(s.length >= 1);\n\t\n\tvar reqmajor = parseInt(s[0]);\n\tvar reqminor = (s.length >= 2) ? parseInt(s[1]) : 0;\n\tvar reqbuild = (s.length >= 3) ? parseInt(s[2]) : 0;\n\t\n\tvar id = GPSystem.getSystemID();\n\tvar s = id.toString(OID).split(\".\");\n\n\tvar major = parseInt(s[s.length - 4]);\n\tvar minor = parseInt(s[s.length - 3]);\n\tvar build = parseInt(s[s.length - 2]);\n\t\n\tif ((major < reqmajor) ||\n\t ((major == reqmajor) && (minor < reqminor)) ||\n\t ((major == reqmajor) && (minor == reqminor) && (build < reqbuild))) {\n\t\tprint(\"This script uses features only available in version \" + version + \" or later.\");\n\t\tprint(\"It may not run as expected, please update to a more current version.\");\n\t\tGPSystem.wait(1500);\n\t}\n}", "function satisfiesWithPrereleases(version, range, loose = false) {\n let semverRange;\n\n try {\n semverRange = new semver_1.default.Range(range, loose);\n } catch (err) {\n return false;\n }\n\n if (!version) return false;\n let semverVersion;\n\n try {\n semverVersion = new semver_1.default.SemVer(version, semverRange.loose);\n\n if (semverVersion.prerelease) {\n semverVersion.prerelease = [];\n }\n } catch (err) {\n return false;\n } // A range has multiple sets of comparators. A version must satisfy all\n // comparators in a set and at least one set to satisfy the range.\n\n\n return semverRange.set.some(comparatorSet => {\n for (const comparator of comparatorSet) if (comparator.semver.prerelease) comparator.semver.prerelease = [];\n\n return comparatorSet.every(comparator => {\n return comparator.test(semverVersion);\n });\n });\n}", "isReleasedVersion() {\n return !/\\w{7}/.test(this.getVersion()); // Check if the release is a 7-character SHA prefix\n }", "function compareVersions(a, b) {\r\n\r\n var ap = Utils.semverReg.exec(a);\r\n var bp = Utils.semverReg.exec(b);\r\n\r\n if (!ap || !bp) return 0;\r\n if (!ap) return 1;\r\n if (!bp) return -1;\r\n\r\n var ret = 0;\r\n for (var i = 1; i < 4; i++) {\r\n if (ap[i] === bp[i]) continue;\r\n ret = (Number(ap[i]) > Number(bp[i])) ? 1 : -1;\r\n break;\r\n }\r\n\r\n return ret;\r\n}", "function hasValidVersionField(manifest) {\n return semver_utils_1.isValidSemver(manifest[ManifestFieldNames.Version]);\n}", "requestedSalaryIsLessThanMin(application) {\n return application.posted_salary_min && \n application.requested_salary && \n application.posted_salary_min > application.requested_salary;\n }", "function IsEarlier(less, more)\n{\n\tif (less.getFullYear() > more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\tif (less.getMonth() > more.getMonth() && less.getFullYear() == more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\tif (less.getDate() > more.getDate() && less.getMonth() == more.getMonth() && less.getFullYear() == more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}", "function isValidSemver(value) {\n var _a;\n if (typeof value !== 'string') {\n return false;\n }\n return ((_a = parse_1.default(value, { loose: false })) === null || _a === void 0 ? void 0 : _a.version) === value;\n}", "function checkIfVersionExists(modulename, version) {\n var moduleObject = require(modulename);\n var classname = \"v\" + version;\n if (moduleObject[classname]) {\n return true;\n }\n else {\n return false;\n }\n}", "local_compatible() {\n if (this.sources.local !== undefined) {\n return this.satisfying(\"^\" + this.sources.local.version);\n } else {\n return this.newest();\n }\n }", "function versionsAreCompatible(versions) {\n return isSubtreeOf(currentVersions, versions, (a, b) => {\n // Technically already handled by isSubtreeOf, but doesn't hurt.\n if (a === b) {\n return true;\n }\n\n if (! a || ! b) {\n return false;\n }\n\n const aType = typeof a;\n const bType = typeof b;\n\n if (aType !== bType) {\n return false;\n }\n\n if (aType === \"string\") {\n const aVer = parse(a);\n const bVer = parse(b);\n return aVer && bVer &&\n aVer.major === bVer.major &&\n aVer.minor === bVer.minor;\n }\n });\n}", "function getTargetVersion(currentVersion, release) {\n if (['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'].includes(release)) {\n return semver.inc(currentVersion, release);\n } else {\n return semver.valid(release);\n }\n}", "function lessThanNumber(number) {\n if (base > number) {\n return true;\n } else {\n return false;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies the summary display text into the clipboard
copySummaryToClipboard() { copyToClipboard(this.summaryListContent()); }
[ "function handleDescriptionCopy() {\n var copyText = document.getElementById(\"part-descriptions\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }", "function copyToClipboard() {\n var el = document.createElement('textarea');\n el.value = loremIpsumText.textContent;\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}", "function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }", "function copyTextToClipboard() {\n const textarea = document.createElement(\"textarea\");\n textarea.innerHTML = Key;\n textarea.style.display = \"hidden\";\n document.body.appendChild(textarea);\n textarea.focus();\n textarea.select();\n try {\n document.execCommand(\"copy\");\n document.body.removeChild(textarea);\n generatePopUp(\"Key Copied\")\n } catch (err) {\n generatePopUp(`some error happened: ${err}`);\n }\n\n /*other way for copying in clipboard -->\n\n navigator.clipboard\n .writeText(text)\n .then(() => {\n generatePopUp(\"Key Copied\")\n })\n .catch((err) => generatePopUp(`some error happened: ${err}`)); */\n}", "function copy(list){\n\t//Empty the background page, add a textarea\n\t$('body').html(\"<textarea></textarea>\");\n\t//For each item in the list, add it to the textarea\n\tfor (var i = 0; i < list.length; i++){\n\t\t$('textarea').append(list[i]);\n\t}\n\t//Select the content to be copied\n\t$('textarea').select();\n\ttry{\n\t\t//Try to cut the data\n\t\tvar success = document.execCommand('cut');\n\t\tif (success){\n\t\t\t//Notify successful cut!\n\t\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Requisitions Copied','message':'Your Halo 5 requisition list has been copied to your clipboard.'});\n\t\t}else{\n\t\t\t//Didn't work, throw an error for the failed message\n\t\t\tthrow 404;\n\t\t}\n\t} catch(err) { \n\t\t//Notify that it failed\n\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Error','message':'Unable to copy the requisition list to your clipboard.'}); \n\t} \n}", "function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}", "function gui_toClipBoard(text) {\n\tif (typeof text == 'undefined') {text = document.getElementById('html_container').value;}\n\ttry {\n\t\tif (window.clipboardData) {\n\t\t\t// IE send-to-clipboard method.\n\t\t\twindow.clipboardData.setData('Text', text);\n\t\t}\n\t\telse if (typeof air == 'object') {\n\t\t\tair.Clipboard.generalClipboard.clear();\n\t\t\tair.Clipboard.generalClipboard.setData(\"air:text\", text, false);\n\t\t}\n\t}\n\tcatch (err) {\n\t\tmyimgmap.log(\"Unable to set clipboard data\", 1);\n\t}\n}", "function dc_copy_to_clipboard(div) {\n let copyText = document.getElementById(div).innerText;\n //console.log(copyText);\n /* Copy the text inside the text field */\n navigator.clipboard.writeText(copyText);\n}", "function selectTextAndCopy(containerId) {\n if (wasLastCopied(containerId)) {\n return;\n }\n\n try {\n if (highlightContent(containerId)) {\n if (document.queryCommandSupported(\"copy\")) {\n document.execCommand(\"copy\") && showCurrentCopyAlert(containerId);\n }\n } \n } catch (e) {}\n}", "updateSummary() {\n const summary = this.details.drupalGetSummary();\n this.detailsSummaryDescription.html(summary);\n this.summary.html(summary);\n }", "copyToClipboard(e){\n e.preventDefault();\n var copyTextarea = document.getElementById('post');\n copyTextarea.select();\n try{\n document.execCommand('copy');\n console.log(\"Post copied succesfully.\");\n }\n catch(err){\n console.log(\"Unable to copy the post. Please, do it manually selecting the text and pressing Crtl + C keys.\");\n console.log(err)\n }\n }", "unsuccessfulCopy () {\n this.labelTarget.innerHTML = 'Press Ctrl+C to copy!';\n }", "copyActiveDataToClipboard() {\n const { activeData } = this.state;\n const cleanData = encounterDataUtils.formatEncounterData(activeData);\n NotificationManager.info('Copied Current Data', undefined, 1000);\n copyToClipboard(JSON.stringify(cleanData));\n }", "handleCopyCut(event) {\n event.stopPropagation();\n let activeNode = this.getActiveNode();\n if(!activeNode) return;\n\n // If nothing is selected, say \"nothing selected\" for cut\n // or copy the clipboard to the text of the active node\n if(this.selectedNodes.size === 0) {\n if(event.type == 'cut') {\n this.say(\"Nothing selected\");\n return;\n } else if(event.type == 'copy') {\n this.clipboard = this.cm.getRange(activeNode.from, activeNode.to);\n }\n // Otherwise copy the contents of selection to the buffer, first-to-last\n } else {\n let sel = [...this.selectedNodes].sort((a, b) => poscmp(a.from, b.from));\n this.clipboard = sel.reduce((s,n) => s + this.cm.getRange(n.from, n.to)+\" \",\"\");\n }\n\n this.say((event.type == 'cut'? 'cut ' : 'copied ') + this.clipboard);\n this.buffer.value = this.clipboard;\n this.buffer.select();\n try {\n document.execCommand && document.execCommand(event.type);\n } catch (e) {\n console.error(\"execCommand doesn't work in this browser :(\", e);\n }\n // if we cut selected nodes, clear them\n if (event.type == 'cut') { this.deleteSelectedNodes(); } // delete all those nodes if we're cutting\n else { activeNode.el.focus(); } // just restore the focus if we're copying\n }", "function copyToClipboard(info) {\n\t// Get the selected text\n\tvar result = searchOracle(info.selectionText);\n\t// If something was found\n\tif (result != null) {\n\t\t // Copy result to clipboard\n\t\t toClipboard(result);\n // If nothing was returned\n\t} else {\n\t\t// Show error\n\t\talert(\"GIF Not Found\");\n\t}\n}", "function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}", "function parse_summary() {\n\n var desc_elms = $('iframe#bookDesc_iframe').contents();\n var desc_text_elms = $(desc_elms).find('div#iframeContent').contents();\n var desc_text = $(desc_text_elms).map(function(i, e) {\n if (this.nodeType === 3) { return $(this).text(); }\n else { return $(this).prop('outerHTML'); }\n }).toArray().join('');\n\n return desc_text;\n}", "function copy()\n{\n var params = arguments;\n var paramsLength = arguments.length;\n var e = params[0];\n var c = params[paramsLength-1];\n if($(e).length < 1)\n {\n var uniqueid = unique_id();\n var textareaId = \"__temp_textarea__\"+uniqueid;\n var element = $(\"<textarea id='\"+textareaId+\"'></textarea>\");\n element.appendTo('body')\n .each(function(){\n $(this).val(e)\n $(this).select()\n })\n }else\n {\n $(e).select();\n }\n\n try {\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n console.log('Copying text was ' + msg);\n if($(e).length < 1)\n {\n $(this).remove();\n }\n if(typeof c == 'function')\n {\n c()\n }\n } catch (err) {\n console.error('Oops, unable to copy');\n }\n}", "writeFindText(text) {\n clipboard.writeFindText(text);\n }", "copyDataListToClipboard() {\n const { dataList } = this.state;\n const cleanList = encounterDataUtils.formatEncounterList(dataList);\n NotificationManager.info('Copied All Data', undefined, 1000);\n copyToClipboard(JSON.stringify(cleanList));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build debugger panel for wrist.
buildWristDebugger() { // If not in headset, put the panel in view. let panelPosition = AFRAME.utils.device.checkHeadsetConnected() ? `position="0.1 0.1 0.1" rotation="-85 0 0"` : `position="0.0 ${this.playerHeight} -0.5"`; let debuggerPanelWrist = ``; // if ( window.location.hostname !== 'localhost') { // if ( window.location.hostname === 'localhost' || AFRAME.utils.device.checkHeadsetConnected() || !AFRAME.utils.device.checkHeadsetConnected()) { debuggerPanelWrist = ` <a-box id="debugger-log-vr-bkg" height="0.2" width="0.2" depth="0.005" ${panelPosition} material="side: back; color: #f44242; transparent: true; opacity: 0.7" > <a-entity id="debugger-log-vr-label" material="side: double; color: #ffffff; transparent: true; opacity: 0.7" text="value: MESSAGES; anchor: center; letterSpacing: 10; baseline: top; width: 0.2; font: https://cdn.aframe.io/fonts/Roboto-msdf.json; height: 0.05; xOffset: 0.001; yOffset: 0.001; zOffset: 0.001; wrap-pixels: 700; color: #ffffff" position="0 0.07 0" ></a-entity> <a-entity id="debugger-log-vr" text="value: ; anchor: center; baseline: center; width: 0.2; height: 0.10; xOffset: 0.001; yOffset: 0.001; zOffset: 0.001; wrap-pixels: 750; color: #eeeeee" ></a-entity> </a-box>`; // } debuggerPanelWrist = ``; // Disabled return { debuggerPanelWrist: debuggerPanelWrist } }
[ "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 setupDebug(){\n debug = new DEBUGTOOL(false,null,[8,8,16]);\n}", "function buildUI(thisObj){\n\n\t\t\t// ----- Main Window -----\n\t\t\tvar w = (thisObj instanceof Panel) ? thisObj : new Window(\"palette\", scriptName);\n\t\t\t\tw.alignChildren = ['fill', 'fill'];\n\n\t\t\t\tw.add(\"statictext\", undefined, \"Use the + button to add a project, or use the ? button to access the settings window and import a previous list.\", {multiline: true});\n\n\t\t\t\t// group for panel buttons\n\t\t\t\tvar panelBtns = w.add(\"group\");\n\n\t\t\t\t\t//panel buttons\n\t\t\t\t\tvar addProjBtn = panelBtns.add(\"button\", undefined, \"+\");\n\t\t\t\t\tvar remProjBtn = panelBtns.add(\"button\", undefined, \"-\");\n\t\t\t\t\tvar settingsBtn = panelBtns.add(\"button\", undefined, \"?\");\n\n\t\t\t\t\taddProjBtn.preferredSize = \n\t\t\t\t\tremProjBtn.preferredSize = \n\t\t\t\t\tsettingsBtn.preferredSize = [80, 30] \n\n\t\t\t\t// group for list of projects\n\t\t\t\tvar projsListGroup = w.add(\"group\");\n\t\t\t\t\tprojsListGroup.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// project list\n\t\t\t\t\tvar projList = projsListGroup.add(\"listbox\", undefined, theProjectNames, {scrollable: true});\n\t\t\t\t\t\tprojList.preferredSize = ['', 250]\n\n\t\t\t\t// group for system buttons\n\t\t\t\tvar systemBtns = w.add(\"group\");\n\n\t\t\t\t\t// system buttons\n\t\t\t\t\tvar importBtn = systemBtns.add(\"button\", undefined, \"Import\")\n\t\t\t\t\tvar openBtn = systemBtns.add(\"button\", undefined, \"Open\");\n\t\t\t\t\tvar cancelBtn = systemBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t\timportBtn.preferredSize =\n\t\t\t\t\topenBtn.preferredSize =\n\t\t\t\t\tcancelBtn.preferredSize = [80, 30]\n\n\t\t\t\t\t// ----- Main Window Functionality -----\n\t\t\t\taddProjBtn.onClick = function(){\n\t\t\t\t\taddProject();\n\t\t\t\t}\n\n\t\t\t\tremProjBtn.onClick = function(){\n\n\t\t\t\t\tdelete theList[projList.selection];\n\t\t\t\t\tupdateProjList(getProjectNames(theList));\t\t\t\t\n\n\t\t\t\t}\n\n\t\t\t\tsettingsBtn.onClick = function(){\n\t\t\t\t\tmakeSettingsWindow();\n\t\t\t\t}\n\n\t\t\t\timportBtn.onClick = function(){\n\n\t\t\t\t\tapp.project.importFile(new ImportOptions(File(theList[projList.selection])));\n\t\t\t\t}\n\n\t\t\t\topenBtn.onClick = function(){\n\t\t\t\t\tapp.open(File(theList[projList.selection]));\n\t\t\t\t}\n\n\t\t\t\tcancelBtn.onClick = function(){\n\n\t\t\t\t\tw.close();\n\t\t\t\t}\n\n\t\t\t\tw.onClose = function(){\n\t\t\t\t\tif (checkObjectForEmpty(theList) == false){\n\t\t\t\t\t\twriteListFile(theList); // save the list when closing the panel.\n\t\t\t\t\t } else {\n\t\t\t\t\t\twriteListFile(new Object ())\n\t\t\t\t\t }\t\n\t\t\t\t}\n\n\t\t\t\t// ----- End Main Window Functionality -----\n\n\t\t\t// ----- End Main Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Add Project Window -----\n\n\t\t\tfunction addProject(){\n\n\t\t\t\tvar addProjWindow = new Window(\"palette\", \"Add Project\");\n\n\t\t\t\t// group for custom project\n\t\t\t\tvar customProjGroup = addProjWindow.add(\"group\");\n\t\t\t\t\tcustomProjGroup.orientation = \"column\";\n\t\t\t\t\tcustomProjGroup.alignChildren = ['left', 'fill']\n\n\t\t\t\t\t// Project name group\n\t\t\t\t\tvar projNameGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojNameGroup.add(\"statictext\", undefined, \"Project Name:\")\n\t\t\t\t\t\t// Project Name\n\t\t\t\t\t\tvar projName = projNameGroup.add(\"edittext\", undefined, \"Project Name\");\n\t\t\t\t\t\t\tprojName.characters = 32;\n\n\t\t\t\t\t// Project location group\n\t\t\t\t\tvar projLocGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojLocGroup.add(\"statictext\", undefined, \"Project Location:\")\n\n\t\t\t\t\t\t// Project Location\n\t\t\t\t\t\tvar projLoc = projLocGroup.add(\"edittext\", undefined, \"Project Location\");\n\t\t\t\t\t\t\tprojLoc.characters = 24;\n\n\t\t\t\t\t\tvar getProjLoc = projLocGroup.add(\"button\", undefined, \"...\");\n\t\t\t\t\t\t\tgetProjLoc.preferredSize = [31, 20];\n\n\t\t\t\t// group for buttons\n\t\t\t\tvar addProjBtns = addProjWindow.add(\"group\");\n\n\t\t\t\t\t// button for current project\n\t\t\t\t\tvar setCurProjBtn = addProjBtns.add(\"button\", undefined, \"Set Current\");\n\n\t\t\t\t\t// button to add the project\n\t\t\t\t\tvar addProjBtn = addProjBtns.add(\"button\", undefined, \"Add Project\");\n\t\t\t\t\t\n\t\t\t\t\t// button to cancel\n\t\t\t\t\tvar cancelAddBtn = addProjBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- SHOW WINDOW -----\n\t\t\t\taddProjWindow.show();\n\t\t\t\t\n\t\t\t\t// ----- Add Project Window Functionality -----\n\t\t\t\tgetProjLoc.onClick = function(){\n\t\t\t\t\tvar getAEP = File.openDialog(\"Please select the location of an AEP.\");\n\t\t\t\t\tif (getAEP != null){\n\n\t\t\t\t\t\tif (getAEP.fsName.split(\".\").pop() == \"aep\"){\n\n\t\t\t\t\t\t\tprojName.text = getAEP.fsName.split(\"/\").pop();\n\t\t\t\t\t\t\tprojLoc.text = getAEP.fsName;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(getAEP.name.split(\".\")[0] + \" is a \" + getAEP.fsName.split(\".\").pop() + \" file. Please select an AEP!\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open file. Please make sure you selected something!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsetCurProjBtn.onClick = function(){\n\n\t\t\t\t\tif (app.project){\n\n\t\t\t\t\t\tprojName.text = String(app.project.file).split(\"/\").pop();\n\t\t\t\t\t\tprojLoc.text = app.project.file;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Please open a Project!\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\taddProjBtn.onClick = function(){\n\n\t\t\t\t\tif (new File(projLoc.text).exists){\n\t\t\t\t\t\tif(projName.text.length > 0 && projName.text != \"Project Name\"){\n\t\t\t\t\t\t\ttheList[projName.text] = projLoc.text;\n\t\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(\"The name \\'\" + projName.text + \"\\' is not valid. Please choose a better name.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"File at \" + projLoc.text + \" does not exist. Please double check that you've selected the correct file.\")\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcancelAddBtn.onClick = function(){\n\n\t\t\t\t\treturn addProjWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Add Project Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Settings Window -----\n\n\t\t\tfunction makeSettingsWindow(){\n\n\t\t\t\tvar settingsWindow = new Window(\"palette\", \"Settings\");\n\t\t\t\t\tsettingsWindow.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// group for text (about, etc)\n\t\t\t\t\tvar aboutGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\taboutGroup.add(\"statictext\", undefined, aboutText, {multiline: true});\n\n\t\t\t\t\t// group for importing and exporting lists\n\t\t\t\t\tvar importExportListGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// import list\n\t\t\t\t\t\tvar importListBtn = importExportListGroup.add(\"button\", undefined, \"Import List\");\n\t\t\t\t\t\tvar exportListBtn = importExportListGroup.add(\"button\", undefined, \"Export List\");\n\n\t\t\t\t\t// group for settings buttons (OK)\n\t\t\t\t\tvar settingsBtns = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// button to close the window\n\t\t\t\t\t\tvar closeSettings = settingsBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- Show Window -----\n\t\t\t\tsettingsWindow.show();\n\n\t\t\t\t// ----- Settings Window FUNCTIONALITY -----\n\t\t\t\timportListBtn.onClick = function(){\n\t\t\t\t\tvar theNewList = File.openDialog(\"Please select a JSON file created by this script.\");\n\t\t\t\t\tif (theNewList != null){\n\t\t\t\t\t\ttheList = readJSONFile(theNewList);\n\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open JSON file. Please try again and ensure a JSON file is selected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\texportListBtn.onClick = function(){\n\t\t\t\t\tvar saveLoc = Folder.selectDialog(\"Please select a location to save your .JSON file.\");\n\t\t\t\t\tif (saveLoc != null){\n\t\t\t\t\t\texportList(theList, saveLoc);\n\t\t\t\t\t} \n\t\t\t\t}\n\n\t\t\t\tcloseSettings.onClick = function(){\t\t\t\t\n\t\t\t\t\treturn settingsWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Make Settings Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- HELPER FUNCTIONS -----\n\t\t\t\n\t\t\tfunction updateProjList(newArrayOfItems){\n\t\t\t\tvar newList = projsListGroup.add(\"listbox\", projList.bounds, newArrayOfItems, {scrolling: true});\n\t\t\t\tprojsListGroup.remove(projList);\n\n\t\t\t\tprojList = newList;\n\t\t\t}\n\n\n\n\n\n\n\n\n\n\n\t\t\t\n\t\t\t// Return window.\n\t\t\tw.layout.layout(true);\n\t\t\treturn w;\n\n\n\t\t} // ----- End Build UI -----", "static init()\n {\n let aeDbg = Component.getElementsByClass(document, PCx86.APPCLASS, \"debugger\");\n for (let iDbg = 0; iDbg < aeDbg.length; iDbg++) {\n let eDbg = aeDbg[iDbg];\n let parmsDbg = Component.getComponentParms(eDbg);\n let dbg = new DebuggerX86(parmsDbg);\n Component.bindComponentControls(dbg, eDbg, PCx86.APPCLASS);\n }\n }", "function openDebugger(options = {}) {\n if (!options.tab) {\n options.tab = gBrowser.selectedTab;\n }\n\n let deferred = promise.defer();\n\n let target = TargetFactory.forTab(options.tab);\n let toolbox = gDevTools.getToolbox(target);\n let dbgPanelAlreadyOpen = toolbox && toolbox.getPanel(\"jsdebugger\");\n\n gDevTools.showToolbox(target, \"jsdebugger\").then(function onSuccess(tool) {\n let panel = tool.getCurrentPanel();\n let panelWin = panel.panelWin;\n\n panel._view.Variables.lazyEmpty = false;\n\n let resolveObject = {\n target: target,\n toolbox: tool,\n panel: panel,\n panelWin: panelWin,\n };\n\n if (dbgPanelAlreadyOpen) {\n deferred.resolve(resolveObject);\n } else {\n panelWin.DebuggerController.waitForSourcesLoaded().then(() => {\n deferred.resolve(resolveObject);\n });\n }\n }, function onFailure(reason) {\n console.debug(\"failed to open the toolbox for 'jsdebugger'\", reason);\n deferred.reject(reason);\n });\n\n return deferred.promise;\n}", "function createPanel( pw, ph, director ){\n\t\tdashBG = new CAAT.Foundation.ActorContainer().\n\t\t\t\t\tsetPreferredSize( pw, ph ).\n\t\t\t\t\tsetBounds( 0, 0, pw, ph ).\n\t\t\t\t\tsetClip(false);\n\n \n\t\t//create bottom panel\n\t\tfor(var i=0;i<dashBoardEle.length;i++){\n\t\t\tvar oActor = game.__addImageOnScene( game._director.getImage(dashBoardEle[i][0]), 1, 1 );\n\t\t\toActor.\t\t\t\n\t\t\t\tsetLocation(dashBoardEle[i][1], dashBoardEle[i][2]);\n\t\t\t\n\t\t\tdashBG.addChild(oActor);\t\t\t\n\t\t}\t\t\t\n\t\t\n\t\t__createDashBoardTxt();\n\t\t__createDashBoardButton();\t\n\t\t__createIncDecButton();\n\t\treturn dashBG;\n\t}", "function _addLauncherPanel(io) {\n\n\n var programs = null;\n\n function displayLauncher(launcher) {\n\n // TODO: this text node could be made into\n // a table row.\n //\n launcher.runCountText.data = launcher.runCount.toString();\n\n launcher.numRunningText.data = launcher.numRunning.toString();\n }\n\n function createPrograms() {\n var contestPanel = _getContestPanel();\n\n if(programs) {\n // remove the old list\n assert(programs.div, \"\");\n while(programs.div.firstChild)\n programs.div.removeChild(launcher.firstChild);\n delete programs.div; // Is this delete needed??\n delete programs;\n }\n\n programs = {};\n var div = programs.div = document.createElement('div');\n\n div.className = 'launcher';\n return div;\n }\n\n\n io.Emit('getLauncherPrograms');\n\n io.On('receiveLauncherPrograms', function(programs_in) {\n\n var programNames = Object.keys(programs_in);\n\n if(programNames.length < 1) {\n console.log('got NO receiveLauncherPrograms');\n return;\n }\n\n var contestPanel = _getContestPanel();\n\n // TODO: This html could be prettied up a lot.\n //\n\n if(programs) {\n // remove the old list\n assert(programs.div, \"\");\n while(programs.div.firstChild)\n programs.div.removeChild(launcher.firstChild);\n delete programs.div; // Is this delete needed??\n delete programs;\n }\n\n var div = createPrograms();\n\n div.className = 'launcher';\n\n let table = document.createElement('table');\n table.className = 'launcher';\n\n let tr = document.createElement('tr');\n tr.className = 'launcher';\n\n\n let th = document.createElement('th');\n th.className = 'launcher';\n th.appendChild(document.createTextNode('program'));\n tr.appendChild(th);\n\n th = document.createElement('th');\n th.className = 'launcher';\n th.appendChild(document.createTextNode('run with arguments'));\n tr.appendChild(th);\n\n th = document.createElement('th');\n th.className = 'launcher';\n th.appendChild(document.createTextNode('number running'));\n tr.appendChild(th);\n\n th = document.createElement('th');\n th.className = 'launcher';\n th.appendChild(document.createTextNode('run count'));\n tr.appendChild(th);\n\n table.appendChild(tr);\n\n\n programNames.forEach(function(key) {\n\n var path = key;\n var program = programs_in[key];\n\n assert(path === programs_in[key].path, \"program != path\");\n\n var tr = document.createElement('tr');\n tr.className = 'launcher';\n\n // All paths will start with '/' so they will not conflict\n // with objects keys in programs that do not start with '/'.\n //\n var launcher = programs[path] = { path: path};\n Object.keys(program).forEach(function(key) {\n launcher[key] = program[key];\n });\n\n\n var argsInput = document.createElement('input');\n argsInput.type = 'text';\n argsInput.value = '';\n\n\n var td = document.createElement('td');\n td.className = 'launcher';\n td.appendChild(document.createTextNode(path));\n tr.appendChild(td);\n td.onclick = function() {\n console.log(\"launch program=\" + path + ' ' +\n argsInput.value);\n io.Emit('launch', path, argsInput.value);\n };\n\n td = document.createElement('td');\n td.className = 'args';\n td.appendChild(argsInput);\n tr.appendChild(td);\n\n td = document.createElement('td');\n td.className = 'numRunning';\n launcher.numRunningText = document.createTextNode('');\n td.appendChild(launcher.numRunningText);\n tr.appendChild(td);\n\n td = document.createElement('td');\n td.className = 'runCount';\n launcher.runCountText = document.createTextNode('');\n td.appendChild(launcher.runCountText);\n tr.appendChild(td);\n\n table.appendChild(tr);\n displayLauncher(launcher);\n });\n\n\n div.appendChild(table);\n contestPanel.appendChild(div);\n // Make this a show/hide clickable thing.\n makeShowHide(div, { header: 'launch' });\n });\n\n io.On('programTally', function(path, program) {\n\n // This updates the table of programs giving a count\n // of the number of launched programs and the number\n // of running programs.\n\n if(undefined === programs[path]) return;\n var launcher = programs[path];\n Object.keys(program).forEach(function(key) {\n launcher[key] = program[key];\n });\n\n displayLauncher(launcher);\n });\n}", "function buildSouthPane(p_data) {\n var l_html = \"<div class=\\\"ui-layout-south\\\">\" +\n \"<div id=\\\"south_title\\\" class=\\\"header ui-widget-header\\\"></div>\" +\n \"<div id=\\\"south_file\\\" class=\\\"file\\\"></div>\" +\n \"</div>\";\n\n jQuery(l_html).appendTo('body');\n }", "function setHtmlPanel(){\n\t\t\n\t\t//add panel wrapper\n\t\tg_objWrapper.append(\"<div class='ug-grid-panel'></div>\");\n\t\t\n\t\tg_objPanel = g_objWrapper.children('.ug-grid-panel');\n\t\t\n\t\t//add arrows:\n\t\tif(g_temp.isHorType){\n\t\t\t\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left-hortype\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right-hortype\");\n\t\t}\n\t\telse if(g_options.gridpanel_vertical_scroll == false){\t\t//horizonatl arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right\");\n\t\t\t\n\t\t}else{\t\t//vertical arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-up ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-down ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-up\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-down\");\n\t\t}\n\t\t\n\t\tg_panelBase.setHtml(g_objPanel);\n\t\t\n\t\t//hide the arrows\n\t\tg_objArrowPrev.fadeTo(0,0);\n\t\tg_objArrowNext.fadeTo(0,0);\n\t\t\n\t\t//init the grid panel\n\t\tg_options.parent_container = g_objPanel;\n\t\tg_gallery.initThumbsPanel(\"grid\", g_options);\n\t\t\n\t\t//get the grid object\n\t\tvar objects = g_gallery.getObjects();\n\t\tg_objGrid = objects.g_objThumbs;\n\t\t\n\t\tsetHtmlProperties();\n\t}", "function KSDpanel(guiAction){\n EAction.call(this, guiAction);\n}", "function DebugWindow(domDivId_debugMessagesOutputDiv) {\n this.domDivId_debugMessagesOutputDiv = domDivId_debugMessagesOutputDiv;\n this.RowClasses = [];\n this.FirstColumnClasses = [];\n this.LastColumnClasses = [];\n}", "function addKnPanel(){\n\tvar zIndex = getMaxZIndex() + 10;\n\tvar panel = $(\"<div kn-panel class=kn-panel></div>\");\n\tpanel.css(\"z-index\", zIndex);\n\tpanel.click(function(){\n\t\tstopKeynapse();\n\t})\n\t$(\"body\").append(panel);\n}", "function ganttDiagnostics() {\r\n var log;\r\n if (console && console.log) {\r\n log = console.log;\r\n } else {\r\n if (!window.ganttDebugWin) {\r\n window.ganttDebugWin = new Ext.Window({\r\n height:400,\r\n width: 500,\r\n bodyStyle:'padding:10px',\r\n closeAction : 'hide',\r\n autoScroll:true\r\n });\r\n }\r\n window.ganttDebugWin.show();\r\n window.ganttDebugWin.update('');\r\n log = function(text){ window.ganttDebugWin.update((window.ganttDebugWin.body.dom.innerHTML || '') + text + '<br/>');};\r\n }\r\n\r\n var els = Ext.select('.sch-ganttpanel');\r\n \r\n if (els.getCount() === 0) {\r\n log('No gantt component found');\r\n return;\r\n }\r\n \r\n var gantt = Ext.getCmp(els.elements[0].id),\r\n ts = gantt.store,\r\n ds = gantt.dependencyStore;\r\n log('Gantt initial config:');\r\n log(gantt.initialConfig);\r\n log(gantt.el.select('*').getCount() + ' DOM elements in the gant component');\r\n log('Gantt view start: ' + gantt.getStart() + ', end: ' + gantt.getEnd());\r\n \r\n if (!ts) { log('No task store configured'); return; }\r\n if (!ds) {log('No dependency store configured'); }\r\n \r\n log(ts.getCount() + ' records in the resource store'); \r\n log(ds.getCount() + ' records in the dependency store'); \r\n log(Ext.select(gantt.eventSelector).getCount() + ' events present in the DOM'); \r\n \r\n if (ts.getCount() > 0) {\r\n if (!ts.getAt(0).get('StartDate') || !(ts.getAt(0).get('StartDate') instanceof Date)) {\r\n log ('The store reader is misconfigured - The StartDate field is not setup correctly, please investigate');\r\n return;\r\n }\r\n \r\n if (!ts.getAt(0).get('EndDate') || !(ts.getAt(0).get('EndDate') instanceof Date)) {\r\n log('The store reader is misconfigured - The EndDate field is not setup correctly, please investigate');\r\n return;\r\n }\r\n \r\n if (!ts.fields.get('Id')) {\r\n log('The store reader is misconfigured - The Id field is not present');\r\n return;\r\n }\r\n \r\n log('Records in the task store:');\r\n ts.each(function(r, i) {\r\n log((i + 1) + '. Start:' + r.get('StartDate') + ', End:' + r.get('EndDate') + ', Id:' + r.get('Id'));\r\n });\r\n } else {\r\n log('Event store has no data.');\r\n }\r\n \r\n if (ds && ds.getCount() > 0) {\r\n log('Records in the dependency store:');\r\n ds.each(function(r) {\r\n log('From:' + r.get('From') + ', To:' + r.get('To') + ', Type:' + r.get('Type'));\r\n return;\r\n });\r\n }\r\n \r\n log('Everything seems to be setup ok!');\r\n}", "function DOMDisplay(parent, level) {\n\tthis.wrap = parent.appendChild(elMaker(\"div\", \"game\"));\n\tthis.level = level;\n\n\tthis.wrap.appendChild(this.drawBackground());\n\tthis.activeLayer = null;\n\tthis.drawFrame();\n}", "function debugControls() {\n\tvar div = document.getElementById(\"dbgCtrls\");\n\n\tvar diffLabel = document.createElement(\"p\");\n\tdiffLabel.textContent = \"DIFFICULTY OVERRIDE\";\n\tdiv.appendChild(diffLabel);\n\tvar diffEntry = document.createElement(\"input\");\n\tdiffEntry.min = 1;\n\tdiffEntry.max = 10;\n\tdiffEntry.id = `${div.id}_controlDifficulty`;\n\tdiffEntry.onchange = function() {\n\t\tDIFFICULTY_OVERRIDE = Number.parseFloat(diffEntry.value);\n\t\tupdateDifficulty();\n\t\tconsole.log(`DEBUG CONTROLS: Set difficulty to ${DIFFICULTY_OVERRIDE}`);\n\t}\n\tdiv.appendChild(diffEntry);\n\n\t// #region Octree Controls\n\t{\n\t\tlet ctrlDiv = document.createElement(\"div\"); \n\t\tctrlDiv.id = \"dbgOctreeControls\";\n\t\t\n\t\tvar hdrTxt = document.createElement(\"h4\");\n\t\thdrTxt.innerText = \"OCTREE CONTROLS:\";\n\t\tctrlDiv.appendChild(hdrTxt);\n\n\t\tvar toggleDrawBtn = document.createElement(\"button\");\n\t\ttoggleDrawBtn.id = `${ctrlDiv.id}_toggleDraw`;\n\t\tctrlDiv.appendChild(toggleDrawBtn);\n\t\ttoggleDrawBtn.innerText = `TOGGLE DRAW`;\n\t\ttoggleDrawBtn.onclick = function() {\n\t\t\tDEBUG_DRAW_OCTREE = !DEBUG_DRAW_OCTREE;\n\t\t\tconsole.debug(`DEBUG CONTROLS: Toggle DEBUG_DRAW_OCTREE to ${DEBUG_DRAW_OCTREE}`);\n\n\t\t\tif (DEBUG_DRAW_OCTREE == false) {\n\t\t\t\tdbgDrawablesPersist[\"OCTREE\"] = [];\n\t\t\t}\n\t\t}\n\n\t\tdiv.appendChild(ctrlDiv);\n\t}\n\t// #endregion Octree Controls\n\n\t// spawnRandomAsteroid\n\tif (false)\n\t{\n\t\tvar ctrlDiv = document.createElement(\"div\"); \n\t\tctrlDiv.id = \"spawnRandomAsteroid\";\n\t\t{\n\t\t\tvar hdrTxt = document.createElement(\"h4\");\n\t\t\thdrTxt.innerText = \"SPAWN DISPLACED ASTEROID:\";\n\t\t\tctrlDiv.appendChild(hdrTxt);\n\n\t\t\tvar locTxt = document.createElement(\"p\");\n\t\t\tlocTxt.innerText = `Location (\"x, y, z\"):`;\n\t\t\tctrlDiv.appendChild(locTxt);\n\t\t\tvar locInp = document.createElement(\"input\");\n\t\t\tlocInp.id = `${ctrlDiv.id}.locInp`;\n\t\t\tlocInp.value = \"0, 0, 0\";\n\t\t\tctrlDiv.appendChild(locInp);\n\n\t\t\tvar scaleTxt = document.createElement(\"p\");\n\t\t\tscaleTxt.innerText = `Scale (universal x,y, and z):`;\n\t\t\tctrlDiv.appendChild(scaleTxt);\n\t\t\tvar scaleInp = document.createElement(\"input\");\n\t\t\tscaleInp.id = `${ctrlDiv.id}.scaleInp`;\n\t\t\tscaleInp.value = \"1\";\n\t\t\tctrlDiv.appendChild(scaleInp);\n\n\t\t\tvar noiseSizeTxt = document.createElement(\"p\");\n\t\t\tnoiseSizeTxt.innerText = `Noise Size (0.001-50):`;\n\t\t\tctrlDiv.appendChild(noiseSizeTxt);\n\t\t\tvar noiseSizeInp = document.createElement(\"input\");\n\t\t\tnoiseSizeInp.id = `${ctrlDiv.id}.noiseSizeInp`;\n\t\t\tnoiseSizeInp.value = \"10\";\n\t\t\tctrlDiv.appendChild(noiseSizeInp);\n\t\t\t\n\t\t\tvar noiseImpactTxt = document.createElement(\"p\");\n\t\t\tnoiseImpactTxt.innerText = `Noise Impact (0.001-1):`;\n\t\t\tctrlDiv.appendChild(noiseImpactTxt);\n\t\t\tvar noiseImpactInp = document.createElement(\"input\");\n\t\t\tnoiseImpactInp.id = `${ctrlDiv.id}.noiseImpactInp`;\n\t\t\tnoiseImpactInp.value = \"0.02\";\n\t\t\tctrlDiv.appendChild(noiseImpactInp);\n\n\t\t\tvar wireframeColTxt = document.createElement(\"p\");\n\t\t\twireframeColTxt.innerText = `Wireframe Color [r,g,b] [0-1]:`;\n\t\t\tctrlDiv.appendChild(wireframeColTxt);\n\t\t\tvar wireframeColInp = document.createElement(\"input\");\n\t\t\twireframeColInp.id = `${ctrlDiv.id}.wireframeColInp`;\n\t\t\twireframeColInp.value = \"1, 1, 1\";\n\t\t\tctrlDiv.appendChild(wireframeColInp);\n\n\t\t\tvar wireframeThicknessTxt = document.createElement(\"p\");\n\t\t\twireframeThicknessTxt.innerText = `Wireframe Thickness [0-1]:`;\n\t\t\tctrlDiv.appendChild(wireframeThicknessTxt);\n\t\t\tvar wireframeThicknessInp = document.createElement(\"input\");\n\t\t\twireframeThicknessInp.id = `${ctrlDiv.id}.wireframeThicknessInp`;\n\t\t\twireframeThicknessInp.value = \"0.02\";\n\t\t\tctrlDiv.appendChild(wireframeThicknessInp);\n\n\t\t\tvar submit = document.createElement(\"button\");\n\t\t\tsubmit.id = `${ctrlDiv.id}.submit`;\n\t\t\tsubmit.innerText = `CREATE 'ROID`;\n\t\t\tsubmit.onclick = function() {\n\t\t\t\tvar locSplit = locInp.value.split(\",\");\n\t\t\t\tvar loc = vec3.fromValues(Number.parseFloat(locSplit[0]), Number.parseFloat(locSplit[1]), Number.parseFloat(locSplit[2]));\n\n\t\t\t\tvar scale = Number.parseFloat(scaleInp.value);\n\n\t\t\t\tvar noiseSize = Number.parseFloat(noiseSizeInp.value);\n\t\t\t\tvar noiseImpact = Number.parseFloat(noiseImpactInp.value);\n\n\t\t\t\tvar wColSplit = wireframeColInp.value.split(\",\");\n\t\t\t\tASTEROID_WIREFRAME_COLOR = [Number.parseFloat(wColSplit[0]), Number.parseFloat(wColSplit[1]), Number.parseFloat(wColSplit[2])];\n\t\t\t\tASTEROID_WIREFRAME_THICKNESS = Number.parseFloat(wireframeThicknessInp.value);\n\n\t\t\t\tconsole.log(`Create asteroid with pos=${loc}, size=${noiseSize}, imp=${noiseImpact}, wC=${ASTEROID_WIREFRAME_COLOR}, wT=${ASTEROID_WIREFRAME_THICKNESS}`);\n\n\n\t\t\t\tvar roid = generateNoisedRoid(loc, noiseSize, noiseImpact);\n\t\t\t\troid.transform.scaleVec3 = vec3.fromValues(scale, scale, scale);\n\t\t\t}\n\t\t\tctrlDiv.appendChild(submit);\n\t\t}\n\t\tdiv.appendChild(ctrlDiv);\n\t}\n\t// spawnRandomAsteroid\n} // debugControls", "function createInterface(diy, editor) {\n let nameField = textField();\n diy.nameField = nameField;\n\n // The bindings object links the controls in the component\n // to the setting names we have selected for them: when the\n // user changes a control, the setting is updated; when the\n // component is opened, the state of the settings is copied\n // to the controls.\n let bindings = new Bindings(editor, diy);\n\n // Background panel\n let bkgPanel = new Grid('', '[min:pref][0:pref,grow,fill][0:pref][0:pref]', '');\n bkgPanel.setTitle(@tal_content);\n bkgPanel.place(@tal_title, '', nameField, 'growx, span, wrap');\n\n let alignmentCombo = createAlignmentCombo();\n bindings.add('Alignment', alignmentCombo, [0]);\n\n let startCombo = createStartCombo();\n bindings.add('Start', startCombo, [0]);\n\n bkgPanel.place(@tal_start, '', startCombo, 'width pref+16lp, growx', @tal_alignment, 'gap unrel', alignmentCombo, 'width pref+16lp, wrap');\n\n // Character base\n let baseCombo = createBaseCombo();\n bkgPanel.place(@tal_char_base, '', baseCombo, 'width pref+16lp, wrap para');\n bindings.add('Base', baseCombo, [0]);\n\n // Statistics panel\n // Create a grid that will be centered within the panel overall,\n // and controls in each of the four columns will be centered in the column\n let statsPanel = new Grid('center, fillx, insets 0', '[center][center][center][center]');\n statsPanel.place(\n noteLabel(@tal_strength), 'gap unrel', noteLabel(@tal_craft), 'gap unrel',\n noteLabel(@tal_life), 'gap unrel', noteLabel(@tal_fate), 'gap unrel, wrap 1px'\n );\n // the $Settings to store the stats in\n let statSettings = ['Strength', 'Craft', 'Life', 'Fate'];\n // the range of possible values for each stat\n let statItems = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '-'];\n for (let i = 0; i < 4; ++i) {\n let combo = comboBox(statItems);\n statsPanel.place(combo, 'growx, width pref+16lp, gap unrel' + (i == 3 ? ', wrap' : ''));\n bindings.add(statSettings[i], combo, [0]);\n }\n // add the --- Stats --- divider and panel\n bkgPanel.place(separator(), 'span, split 3, growx', @tal_stats, 'span, split 2', separator(), 'growx, wrap rel');\n bkgPanel.place(statsPanel, 'span, growx, wrap rel');\n bkgPanel.place(separator(), 'span, growx, wrap para');\n\n // Special Abilities\n let specialTextField = textArea('', 17, 15, true);\n bkgPanel.place(@tal_abilities, 'span, wrap');\n bkgPanel.place(specialTextField, 'span, gap para, growx, wrap');\n bindings.add('SpecialText', specialTextField, [0]);\n\n bkgPanel.addToEditor(editor, @tal_content, null, null, 0);\n bindings.bind();\n\n // Set up custom clip stencil for the portrait panels:\n // The portrait clip stencil is what defines the shape\n // of the portrait area in the portrait panel. It is an\n // image the same size as the portrait's clip region,\n // and the opacity (alpha) of its pixels determines where\n // in the clip region the portrait shows through and where\n // it is covered by other content. The default system \n // assumes that the card template has a hole in it for\n // the portrait, and that you draw the portrait and then\n // draw the template over it. If you do something different\n // then you may need to customize the clip stencil. In this\n // case, we are using the portrait clip stencil to define\n // the ideal size for portraits, but we allow the portrait\n // to escape from this area (i.e. portrait clipping is\n // disabled). In addition, the portraits are transparent\n // so the card background shows through them. To account for\n // this we need to do two things:\n //\n // 1. Change the size of the clip stencil region. By default,\n // this is the same as the portrait clip region. Since we\n // don't clip to that region, we need to set the clip stencil\n // region to the area that we *do* clip to. Otherwise, the\n // area where the portrait shows through in the portrait panel\n // will be the wrong size.\n // 2. In the case of the main portrait, we need to use a different\n // clip stencil. The default clip stencil is created by taking\n // the portion of the template image that fits within the\n // portrait clip region (or the custom clip stencil region if\n // we set one). In our case, the template image does not have\n // a transparent area where the portrait is, because the portrait\n // gets drawn overtop of it. Instead, we need to use the\n // 'front overlay' image, which does have a hole for the portrait\n // and which gets stamped overtop of the portrait so that the\n // portrait can't cover up certain decorations.\n //\n // There is a function defined in the Talisman named object for\n // customizing a component's portraits, and we call that below.\n // However, the function is a bit hard to follow because it handles\n // multiple cases, so I have also included a straightforward translation\n // for each call just below that line\n //\n\n // customize the main portrait stencil to use the front overlay and true clip\n Talisman.customizePortraitStencil(diy, ImageUtils.get($char_front_overlay), R('portrait-true-clip'));\n /*\n // Equivalent code:\n let stencil = ImageUtils.get( $char_front_overlay );\n let region = R('portrait-true-clip');\n stencil = AbstractPortrait.createStencil( stencil, region );\n diy.setPortraitClipStencil( stencil );\n diy.setPortraitClipStencilRegion( region );\n */\n\n // customize the marker portrait to use the true clip\n // (see also the paintMarker function, below)\n Talisman.customizePortraitStencil(diy, null, R('marker-true-clip'), true);\n\n /*\n // Equivalent code:\n diy.setMarkerClipStencilRegion( R('marker-true-clip') );\n */\n}", "function buildPanel(panelName) {\n return {\n name: panelName,\n entry: `./dashboard/${panelName}/src/index.ts`,\n output: {\n filename: 'script.js',\n path: `${path.resolve(__dirname)}/dashboard/${panelName}/js/`\n },\n\n ...rootConfig\n }\n}", "function runProject(){\r\n run = getDefaultWindow(\"project_runner_window\",800,500);\r\n run.setText(\"Gurski Browser [\"+current_project+\"]\");\r\n run.progressOn();\r\n run.center(); \r\n\r\n preview_toolbar = run.attachToolbar();\r\n preview_toolbar.setSkin(\"dhx_blue\");\r\n preview_toolbar.addButton(\"back\", 0,null, \"../images/back.png\", null);\r\n preview_toolbar.addButton(\"next\", 1,null, \"../images/next.png\", null);\r\n preview_toolbar.addText(\"labelURL\",2,\"URL:\");\r\n var path = \"../projects/\".concat(current_project.toString(), \"/\", current_project_index_file.toString());\r\n preview_toolbar.addInput(\"url\", 3,path,400);\r\n preview_toolbar.addButton(\"run\", 4,null, \"../images/run.jpg\", null);\r\n preview_toolbar.addInput(\"time\", 5,\"30\",40);\r\n preview_toolbar.addButton(\"clock\", 6,null, \"../images/clock.png\",\"../images/clockdis.png\");\r\n preview_toolbar.addButton(\"stop\", 7,null, \"../images/stop.png\", \"../images/stopdis.png\");\r\n preview_toolbar.disableItem(\"stop\");\r\n preview_toolbar.attachEvent(\"onClick\", function(id){\r\n if(id === \"run\"){\r\n run.progressOn();\r\n historyArray.push(preview_toolbar.getValue(\"url\").toString());\r\n historyNumber++;\r\n run.attachURL(preview_toolbar.getValue(\"url\").toString());\r\n setTimeout(\"run.progressOff()\",2000);\r\n }else if(id === \"next\"){\r\n historyNumber++;\r\n preview_toolbar.setValue(\"url\",historyArray[historyNumber].toString() );\r\n run.attachURL( historyArray[historyNumber].toString() );\r\n }else if(id === \"back\"){\r\n if(historyNumber > 0){\r\n historyNumber--;\r\n preview_toolbar.setValue(\"url\",historyArray[historyNumber].toString() );\r\n run.attachURL( historyArray[historyNumber].toString() );\r\n }\r\n }else if(id === \"clock\"){ \r\n interval = setInterval(\"run.attachURL('\"+preview_toolbar.getValue(\"url\").toString()+\"');\",preview_toolbar.getValue(\"time\")*1000);\r\n preview_toolbar.enableItem(\"stop\");\r\n preview_toolbar.disableItem(\"clock\");\r\n }else if(id === \"stop\"){\r\n clearInterval(interval);\r\n preview_toolbar.enableItem(\"clock\");\r\n preview_toolbar.disableItem(\"stop\");\r\n }\r\n });\r\n \r\n preview_toolbar.attachEvent(\"onEnter\", function(id){\r\n if(id === \"url\"){\r\n run.progressOn();\r\n historyArray.push(preview_toolbar.getValue(\"url\").toString());\r\n historyNumber++;\r\n run.attachURL(preview_toolbar.getValue(\"url\").toString());\r\n setTimeout(\"run.progressOff()\",2000);\r\n this.clearInterval(interval);\r\n }\r\n });\r\n\r\n\r\n run.attachURL(\"../src/Linker.class.php?action=run_project&project=\"+current_project+\"\");\r\n historyArray.push(\"../src/Linker.class.php?action=run_project&project=\"+current_project+\"\");\r\n setTimeout(\"run.progressOff()\",1500);\r\n}", "function setupShowOpt() {\n queries.showoptbody = $(\">div#showoptbody\", queries.fcnlist);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
comprobarPremioMinimo solo verificamos que es un objeto del tipo que toca y que tiene ID se usa en borrados
function comprobarPremioMinimo(premio) { // debe ser un objecto var comprobado = 'object' === typeof premio; // propiedades no nulas comprobado = (comprobado && premio.hasOwnProperty('idPremio')); return comprobado; }
[ "function Zidovi(sirina, boja) {\n//function napravi_zidove(sirina, boja) {\n// ova funkcija ucrtava zidove u igracki prostor i postavlja njihovo polje/parametre. sirina definira\n// sirinu zidova u pikselima, boja je css string koji govori o njihovoj boji. Ako zelis/ne zelis zid na donjem bridu\n// moras u ovoj funkciji ukljuciti/iskljuciti pripadajuci prekidac\n \n var sir = parseInt($('div#prostor').css('width'));\n var vis = parseInt($('div#prostor').css('height'));\n \n console.log('sirina/visina igrackog polja je ' + sir + ' / ' + vis);\n \n //lijevi zid\n var centarx = Math.floor(sirina/2);\n var centary = Math.floor(vis/2);\n this.lijevi = sirina;\n console.log('centar je ' + centarx + ' / ' + centary);\n nacrtaj_pravokutnik(centarx, centary, sirina, vis, boja, 0);\n \n //gornji zid\n centarx = Math.floor(sir/2);\n centary = Math.floor(sirina/2);\n this.gornji = sirina;\n console.log('centar je ' + centarx + ' / ' + centary);\n nacrtaj_pravokutnik(centarx, centary, sir, sirina, boja, 0);\n \n //desni zid\n centarx = Math.floor(sir - sirina/2);\n centary = Math.floor(vis/2);\n this.desni = sir - sirina;\n console.log('centar je ' + centarx + ' / ' + centary);\n nacrtaj_pravokutnik(centarx, centary, sirina, vis, boja, 0);\n \n this.donji = -1;\n if (false) { // za true crta donji zid\n centarx = Math.floor(sir/2);\n centary = Math.floor(vis - sirina/2);\n this.donji = vis - sirina;\n console.log('centar je ' + centarx + ' / ' + centary);\n nacrtaj_pravokutnik(centarx, centary, sir, sirina, boja, 0);\n }\n}", "async obterPorId(pessoaId) {\n const pessoa = await PessoaRepository.findById(pessoaId).exec();\n return pessoa;\n }", "function User_Insert_Type_de_couche_Type_de_couches0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 4\n\nId dans le tab: 96;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 97;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 98;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 99;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typecouche\";\n var CleMaitre = TAB_COMPO_PPTES[93].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tc_nom=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom))\n \treturn -1;\n var note=GetValAt(97);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[97],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[97],note))\n \treturn -1;\n var couleur=GetValAt(98);\n if (!ValiderChampsObligatoire(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur))\n \treturn -1;\n var tc_sansilots=GetValAt(99);\n if (!ValiderChampsObligatoire(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tc_nom,note,couleur,tc_sansilots\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tc_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_nom)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\",\"+(couleur==null ? \"null\" : \"'\"+ValiderChaine(couleur)+\"'\" )+\",\"+(tc_sansilots==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_sansilots)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "async criar() {\n this.validar(true);\n const resultado = await TabelaProduto.inserir({\n titulo : this.titulo,\n preco: this.preco,\n estoque : this.estoque,\n fornecedor : this.fornecedor\n });\n this.id = resultado.id;\n this.dataCriacao = resultado.dataCriacao;\n this.dataAtualizacao = resultado.dataAtualizacao;\n this.versao = resultado.versao\n }", "function calcularProm(filas)\n{\n let promedio = document.getElementById('promedio');\n let max = document.getElementById('precioMaximo');\n let min = document.getElementById('precioMinimo');\n if(filas.length != 0 )\n {\n let celdas = traerColumna(filas,'name','CELDAPRECIO').map((e)=>parseInt(precioDeServer(e.textContent)));\n let precioFinal = celdas.reduce((a,b)=> a + b) / celdas.length;\n let precioMaximo = celdas.reduce((a,b)=> a>=b ? a : b);\n let precioMinimo = celdas.reduce((a,b)=> a>=b ? b : a);\n promedio.value = precioDeForm(precioFinal);\n max.value = precioDeForm(precioMaximo);\n min.value = precioDeForm(precioMinimo);\n }\n else{\n promedio.value = precioDeForm(0);\n max.value = precioDeForm(0);\n min.value = precioDeForm(0);\n }\n porcentajeVacunados(filas);\n}", "function cargarPlantilla(){\n\tif(objeto()!= 0)\n\t\tconexionPHP('formulario.php','Plantilla',objeto())\t\t\n\telse\n\t\talert(\"Debe Seleccionar un tipo de Objeto\");\n}", "function getDataRiferimento(objData,tipo)\n{\n\tvar dataInput;\n\tvar dataOutput;\n\tvar giorno;\n\tvar mese;\n\tvar anno;\n \n // objData e' una stringa che rappresenta una data\n if (typeof(objData)==\"string\")\n {\n \tdata=getDateFromText(objData);\n }\n // objData e' un campo INPUT\n else if (objData.tagName!=undefined)\n {\n \tdata=getDateFromText(objData.value);\t\t\t\t\n }\n // objData e' un oggetto Date\n else\n {\n \tdata=new Date(objData.getFullYear(),objData.getMonth(),objData.getDate(),0,0,0,0);\n }\n\t\n\tanno=data.getFullYear();\n\t\n\tswitch (tipo)\n\t{\n\t\t// Torna data INIZIO ANNO\n\t\tcase \"IA\":\n\t\t\tgiorno=1;\n\t\t\tmese=1;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data FINE ANNO\n\t\tcase \"FA\":\n\t\t\tgiorno=31;\n\t\t\tmese=12;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data INIZIO MESE\n\t\tcase \"IM\":\n\t\t\tgiorno=1;\n\t\t\tmese=data.getMonth()+1;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data FINE MESE\n\t\tcase \"FM\":\n\t\t\tmese=data.getMonth()+1;\n\t\t\tswitch (mese)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\tcase 3:\n\t\t\t\tcase 5:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 10:\n\t\t\t\tcase 12:\n\t\t\t\t\tgiorno=31;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\tcase 6:\n\t\t\t\tcase 9:\n\t\t\t\tcase 11:\n\t\t\t\t\tgiorno=30;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tif (anno%4!=0 || (anno%100==0 && anno%400!=0))\n\t \t\tgiorno=28;\n\t\t\t else\n\t\t\t \tgiorno=29;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t// Stringa vuota\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n\t\n\t// Normalizzazione giorno/mese\n\tif (giorno<10)\n\t\tgiorno=\"0\"+giorno;\n\t\n\tif (mese<10)\n\t\tmese=\"0\"+mese;\n\t\t\n\t// Data in formato GG/MM/AAAA\n\treturn giorno+\"/\"+mese+\"/\"+anno;\n\n}", "function subirObjetosNegocio(claves, valores, actualizacionFlag) {\n if (utils_isComuServidorWeb()){\n\t\t\t//Si utilizamos el servidor Web\n\t\t\tvar mensaje=\"\";\n\t\t\t// EL formato serà clave1=*=valor1*+*clave2=*=valor2 ...\n\t\t\tvar j=0;\n\t\t\tfor(var i=0;i<claves.length;i++)\n\t\t\t{\n\t\t\t\tif (j>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmensaje = mensaje + \"+*+\";\n\t\t\t\t\t}\n\t\t\t\t\tmensaje = mensaje + claves[i] + \"=*=\" + valores[i]\n\t\t\t\t\tj++;\n\t\t\t}\n\t\t\tmensaje=mensaje.replace(/&/g,\"%26\");\n\t\t\tif(typeof(actualizacionFlag)!=\"undefined\"&&!actualizacionFlag){\n\t\t\t\t//mensaje = \"CTE_XSNACTUALIZADO=*=false+*+\"+mensaje;\n\t\t\t\tutils_servidorWeb_enviaPlano(\"CTE_SUBIDA_OBJETOS_NEGOCIO_SIN_FLAG\"+mensaje,\"true\");\n\t\t\t}else{\n\t\t\t\tutils_servidorWeb_enviaPlano(\"CTE_SUBIDA_OBJETOS_NEGOCIO\"+mensaje,\"true\");\n\t\t\t}\t\t\n\t\t}else if (isNavegadorEmbebido()){\n\t\t\t//Si no utilizamos el servidor Web pero utilizamos el PlugIn\n\t\tvar mensaje=\"\";\n\t\t// EL formato serà clave1=*=valor1*+*clave2=*=valor2 ...\n\t\tfor(var i=0;i<claves.length;i++)\n\t\t{\n\t\t\tif (i>0)\n\t\t\t{\n\t\t\t\tmensaje = mensaje + \"+*+\";\n\t\t\t}\n\t\t\tmensaje = mensaje + claves[i] + \"=*=\" + valores[i]\n\t\t}\n\t\tmensaje=mensaje.replace(/&/g,\"%26\");\n\t\t// Usamos el conector de comunicaciones para transmitir la peticion\n\t\tif(typeof(actualizacionFlag)!=\"undefined\"&&!actualizacionFlag){\n\t\t\tPlugIn.enviaPlano(\"CTE_SUBIDA_OBJETOS_NEGOCIO_SIN_FLAG\"+mensaje);\n\t\t}else{\n\t PlugIn.enviaPlano(\"CTE_SUBIDA_OBJETOS_NEGOCIO\"+mensaje);\n\t\t}\n\t}\n\telse\n\t{\n\t var isATPI=false;\n\n\t //Se comprueba que se realiza la ejecución sobre el portal ATPI o ATPN\n\t try{\n isATPI=window.top.isEjecucionSobrePortal;\n\n }catch (err){\n \n try{\n // Estamos en la ventana contenedora\n isATPI=isEjecucionSobrePortal; \n }\n catch(err){\n // Estamos en el contenedor\n isATPI=parent.isEjecucionSobrePortal;\n }\n \n }\n\n\t //Se comprueba si se está ejecutando sobre el portal ATPN o sobre ATPI\n\t\tif (isATPI==true){\n \t\t //Estamos en ATPI\n \t\t try{\n top.atpn_gt_subirObjetosNegocio(claves, valores);\n }\n catch(err){\n \n try{\n // Estamos en la venata contenedora\n atpn_gt_subirObjetosNegocioCD(claves, valores);\n }\n catch(err){\n // Estamos en el contenedor\n parent.atpn_gt_subirObjetosNegocioCD(claves, valores);\n }\n \n }\n \t}else{\n\t\t //Estamos sobre ATPN\n\t\t \n\t\t var isObjetoNegocio = false;\n\t\t try{\n isObjetoNegocio = window.top.Fprincipal.objetoNegocio;\n }\n catch(err){\n try{\n // Estamos en la ventana contenedora\n isObjetoNegocio = Fprincipal_objetoNegocio;\n }\n catch(err){\n // Estamos en el contenedor\n isObjetoNegocio = parent.Fprincipal_objetoNegocio;\n }\n }\n \n if(isObjetoNegocio == true){\n try{\n window.top.Fprincipal.subidaObjetoLigero(claves, valores);\n }\n catch(err){\n try{\n // Estamos en la ventana contenedora\n Fprincipal_subidaObjetoLigeroCD(claves, valores);\n }\n catch(err){\n // Estamos en el contenedor\n parent.Fprincipal_subidaObjetoLigeroCD(claves, valores);\n }\n }\n }\n \n }\n\t}\n}", "async pegarPorId(id) {\n const encontrado = await ModeloTabelaFornecedor.findOne({\n where : {id},\n raw : true\n });\n if(!encontrado) {\n throw new NaoEncontrado(`Fornecedor de id ${id}`);\n } \n return encontrado;\n }", "function crearMetodoDePago(metodo) {\n return new Promise(async (resolve, reject) => {\n try {\n if (!metodo) {\n return reject(new Error(\"faltan datos\"));\n }\n const id = await store.crearMetodoDePago(metodo);\n return resolve(id);\n } catch (error) {\n return reject(error);\n }\n });\n}", "function buscarPorNombre(nombre, idPartida, tipo){\n\tif (tipo == 'aliado'){\n\t\tfor (i in personajes[idPartida]){\n\t\t\tif (personajes[idPartida][i].nombre == nombre){\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\t\n\t} else {\n\t\tfor (i in enemigos[idPartida]){\n\t\t\tif (enemigos[idPartida][i].nombre == nombre){\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\t\t\n}", "function CurrentTransaction(objname, id, postaja, ime_postaje, tip, datumz, datumk) {\n this.getClass = function() { return \"CurrentTransaction\" }; \n this.name = objname.toLowerCase(); \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// klima|padavine|sonce\n this.id = id; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// id stevilka objekta: 0,1,2,...\n this.action; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// check|insert; check=preverjanje, insert=vnos v bazo; privzeto=check\n this.postaja = postaja; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// klimataoloska stevilka postaje\n this.tip = tip; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// tip postaje (klima=2|3, padavine=1, sonce=14)\n this.ime_postaje = ime_postaje; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ime postaje \n this.datumz = datumz;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// zacetek intervala\n this.datumk = datumk; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// konec intervala\n this.getFirst = getFirst; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// prvi element glede na interval\n this.getLast = getLast; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// zadnji element glede na interval\n this.postaje = generatePostaje(this.postaja, this.tip, this.datumz, this.datumk); \t\t\t// veljavni idmm-ji za to klimatolosko postajo v danem intervalu\n this.parametri = generateParametri(this.postaja, this.tip, this.datumz, this.datumk); \t// parametri, ki se merijo na posameznem idmm glede na this.postaje\n this.setFirstEditDate = setFirstEditDate; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dolocanje prvi dan, v katerem se lahko editirajo podatki (odvisno od vloge uporabnika)\n this.getFirstEditDate = getFirstEditDate; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// prvi dan, v katerem se lahko editirajo podatki (odvisno od vloge uporabnika) \n this.generateKlimaPadavineSonce = generateKlimaPadavineSonce; \t\t\t\t\t\t\t\t\t\t\t\t\t// generiranje podatkov: iz baze(status=0) in prazni(status=1)\n this.generateKlimaPadavineSonce(objname);\t \n this.addFirstKlimaPadavine = addFirstKlimaPadavine; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dodajanje prvega elementa, ÄŤe ni idmm; status=2\n this.addFirstKlimaPadavine(objname); \n this.toXml = obj2xml; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// transformacija objektov v xml - podatki \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\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 this.toEXml = obj2errorXml;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// transformacija objektov v xml - napake\n this.getPrev = getPrev; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// predhodni element\n this.getPrevByDate = getPrevByDate; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// predhodni element glede na datum\n this.getNext = getNext; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// naslednji element\n this.hasPrev = hasPrev; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali obstaja predhodni element\n this.hasNext = hasNext; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali obstaja naslednji element\n this.lastDate = getLastDate; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// zadnji dan, ki se vsebuje podatke\n this.insert = insertObj; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// vnos podatkov v bazo\n this.correct = correctObj; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// uskladitev podatkov ob vnosu v bazo (val = nval)\n this.validate = validateObj; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// preverjanje podatkov \n this.clearErrorsWarnings = clearErrorsWarningsObj;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// brisanje napak in opozoril\n this.numerrs; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//stevilo napak\n this.numwarns;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stevilo opozoril \n this.setOldVal = setOldValueObj;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//shranjevanje vrednosti v formi (oval = nval)\n}", "function marcaReprovados(aluno) {\n aluno.reprovado = false;\n if (aluno.nota < 5) {\n aluno.reprovado = true;\n }\n}", "function cargarPedido(nuevoPedido, IDnuevoPedido) {\n // Recibe la direccion de la tabla y crea una fila siempre al final\n \n let tabla = document.getElementById(\"tablaPedido\");\n let fila = tabla.insertRow(-1);\n\n /// El td del producto\n let producto = document.createElement(\"td\");\n producto.textContent =nuevoPedido.producto; // el textContent del td es el producto\n fila.appendChild(producto);\n // El td del cantidad\n let cantidad = document.createElement(\"td\");\n cantidad.textContent =nuevoPedido.cantidad ; // el textContent del td es el cantidad\n fila.appendChild(cantidad);\n // El td del precio\n let precio = document.createElement(\"td\");\n precio.textContent =nuevoPedido.precio; // el textContent del td es el precio\n fila.appendChild(precio);\n \n //Crea el boton de editar, le asigna las propiedades\n let btnEditar = document.createElement(\"button\");\n btnEditar.innerHTML = \"Editar\";\n btnEditar.type = \"button\";\n btnEditar.addEventListener('click', function(){editarPedido(fila, IDnuevoPedido);});\n fila.appendChild(btnEditar);\n //Crea el boton de borrar, le asigna las propiedades\n let btnBorrar = document.createElement(\"button\");\n btnBorrar.innerHTML = \"Borrar\";\n btnBorrar.type = \"button\";\n btnBorrar.addEventListener('click', function(){borrarPedido(fila, IDnuevoPedido);});\n fila.appendChild(btnBorrar);\n // Finalmente agregamos la fila al cuerpo de la tabla\n tabla.appendChild(fila);\n // modifica el atributo \"border\" de la tabla y lo fija a \"2\";\n tabla.setAttribute(\"border\", \"2\"); \n}", "function inserirElementoExecutado(objeto){\n\tfilaProntos[filaProntos.length] = objeto;\n\t//Inserindo elemento no HTML:\n\taddTAGs(\"executado\", \"li\", objeto.id, \"bordar espera negrito\", 1, null);\n}", "function getIdMesero(){\n\treturn idMeseroGlobal;\n}", "function ArticoloSelezioneGuidata() {\r\n this.BaseCodice = null;\r\n this.Gruppo = null;\r\n this.ArticoloCodice = [];\r\n}", "ajouter(data){\n var nouNoeud = new Noeud(data)\n if(this.racine === null){\n this.racine = nouNoeud\n }else{\n this.ajouterNoeud(this.racine,nouNoeud)\n }\n }", "function obj2xml() {//sonce, padavine, klima\n var xmlstr = new java.lang.StringBuffer(\"\");\n xmlstr.append(\"<\" + this.name + \" action=''\" + \" interval='false' id='\" + this.id + \"' postaja='\" + \n\t\t\t\t\t\t\t\tformatNumber(this.postaja) + \"' tip='\" + formatNumber(this.tip) + \"' ime_postaje='\" + \n\t\t\t\t\t\t\t\tthis.ime_postaje + \"' user='\" + user + \"'>\"); // za izpis postaje z vodilnimi niÄŤlami\n var obj = this.getFirst();\n if (obj) {\n while (1) {\n xmlstr.append(obj.toXml());\n if (obj.hasNext()) obj = obj.getNext();\n\t\t\telse break;\n }\n }\n xmlstr.append(\"</\" + this.name + \">\");\n return toXml(xmlstr.toString());\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Noti / Returns an array of all notifications by trip_id
getNotifications(url, trip_id) { return axios.get(`${url}notify/${trip_id}`).then(res => { return res.data; }); }
[ "async all() {\n const subscriptions = await this.db.subscriptions.toArray();\n return Promise.all(\n subscriptions.map(async (s) => ({\n ...s,\n new: await this.db.notifications.where({ subscriptionId: s.id, new: 1 }).count(),\n }))\n );\n }", "static async getRecentTrips() {\n const tripResult = await db.query(\n `SELECT id AS \"tripId\",\n trip_name AS \"tripName\",\n distance,\n trip_rating AS \"tripRating\"\n FROM trips\n JOIN user_trips\n ON trips.id = user_trips.trip_id\n ORDER BY trip_id DESC\n LIMIT 20`\n );\n let trips = tripResult.rows;\n if (!trips[0]) {\n return trips;\n };\n\n /** Gets array of locations for each trip retrieved above */\n for (let trip of trips) {\n const locationResults = await db.query(\n `SELECT location_id AS \"locationId\",\n location_position AS \"locationPosition\",\n locations.title AS \"locationName\"\n FROM trips\n JOIN trip_locations\n ON trips.id = trip_locations.trip_id\n JOIN locations\n ON trip_locations.location_id = locations.id\n WHERE trips.id = $1\n ORDER BY location_position`,\n [trip.tripId]\n );\n trip.locations = locationResults.rows;\n };\n \n return trips;\n }", "crotonTrips(state) {\n var trips = [];\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n var crotonTrip = {\n id: state.recordsList[i].key,\n angler: state.recordsList[i].angler,\n comment: state.recordsList[i].comment,\n reservoir: state.recordsList[i].reservoir,\n species: state.recordsList[i].species,\n timestamp: state.recordsList[i].timestamp,\n weight: state.recordsList[i].weight,\n };\n trips.push(crotonTrip);\n }\n }\n return trips;\n }", "function getTripInfo(departureId, arrivalId) {\n\tvar tripInfo = [];\n\tif (typeof(departureId) !== \"undefined\" && typeof(arrivalId) !== \"undefined\") {\n\t\tvar timesCursor = Times.find({\n\t\t$or: [\n\t\t\t{\"stop_id\": departureId},\n\t\t\t{\"stop_id\": arrivalId}\n\t\t]\n\t\t}, {\n\t\t\tfields: {\n\t\t\t\t\"trip_id\": 1,\n\t\t\t\t\"stop_id\": 1,\n\t\t\t\t\"departure_time\": 1\n\t\t\t}\n\t\t});\n\n\t\ttripInfo = timesCursor.fetch();\n\t\treturn tripInfo;\n\t}else {\n\t\treturn tripInfo;\n\t}\t\n}", "function getNotifications() {\n $.ajax({\n url: \"files/notification.json\",\n dataType: 'json',\n success: function(data) {\n var notice =\"\";\n var noticelist = []; //Array to store list of notifications from JSON file\n\n $.each(data, function(key, value) { // Execute for each set of data\n // If statement to filter notification list according to current logged in userid. Only notifications for current user is retrieved.\n if (value.userkey === parseInt(userid)) {\n // Nested if else to render notifications according to \"new\" or \"read\" status\n if (value.noticestatus === \"new\") {\n notice = `<div class=\"notice new\"><span class=\"noticeSubject\">${value.noticesubject}</span><span class=\"noticeStatus\">${value.noticestatus}</span>\n <i class=\"bi bi-pin-angle-fill\"></i><br/><span class=\"noticeContent\">${value.noticecontent}</span><span class=\"noticeTime\">${value.noticetime}</span><br/>\n <span class=\"noticeDate\">${value.noticedate}</span></div>`;\n noticelist.push(notice);\n } else {\n notice = `<div class=\"notice read\"><span class=\"noticeSubject\">${value.noticesubject}</span><span class=\"noticeStatus\">${value.noticestatus}</span><br/>\n <span class=\"noticeContent\">${value.noticecontent}</span><span class=\"noticeTime\">${value.noticetime}</span><br/>\n <span class=\"noticeDate\">${value.noticedate}</span></div>`;\n noticelist.push(notice);\n }\n }\n });\n // For loop to render all notification messages on division noticeContainer\n for (i = 0; i < noticelist.length; i++) {\n $(\".noticeContainer\").append(noticelist[i]);\n } \n },\n error(xhr, status, error) { // Function for error message and error handling\n console.log(error);\n }\n })\n }", "function getNotifications() {\n\t\ttrace(\"Get notifications of logged in user\");\n\t\t\n\t\tset_ready();\n\t\t\n\t\tFB.api({\n\t\t\t\tmethod: 'notifications.get'\n\t\t\t}, function(result) {\n\t\t\t\ttrace(_s.NOTIFICATIONS_GET);\n\n\t\t\t\ttrace(result);\n\t\t\t\tinspect(result);\n\n\t\t\t\tdispatchEvent(_s.NOTIFICATIONS_GET, result);\n\t\t});\n\t}", "allNotions () {\n return _.flatten(this.notions.map(c => c.entities))\n }", "storeTrip() {\n this.tripsArray.push(this.currentTrip);\n this.currentTrip = new Trip();\n return this.tripsArray;\n }", "function delete_all() {\n return apiWithAuth.delete(`/notifications/delete_all`);\n}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'get', kparams);\n\t}", "_runNotificationsPendingActivation() {\n if (!this._notificationsPendingActivation.length) {\n return;\n }\n\n let pendingNotifications = this._notificationsPendingActivation;\n this._notificationsPendingActivation = [];\n for (let notif of pendingNotifications) {\n notif.call(this);\n }\n }", "function getNoteByID(id) {\n let db = note.notes\n for (let i = 0; i < db.length; i++) {\n let nte = db[i]\n if (nte._id == id) {\n return nte\n }\n }\n}", "static async getAll(lessonId) {\n const result = await db.query(\n `SELECT * FROM notes WHERE lesson_id = $1`, [lessonId]);\n if (result.rows.length === 0) {\n throw new ExpressError(`No notes`, 404);\n };\n return result.rows.map(n => new Note(n.id, n.lesson_id, n.note));\n }", "function getTriagers(project_id){\n\n}", "static getClientNotification(entryId, type){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('notification', 'getClientNotification', kparams);\n\t}", "function loadNotifications() {\n notificator.getAllNotifications(1, 10, true).then(data => {\n if (!data) return;\n if (data.is_success) {\n $.each(data.result.notifications, (i, notification) => {\n notificator.addNewNotificationToContainer(notification);\n });\n const loaderClassString = 'notification-loader';\n const loaderClass = `.${loaderClassString}`;\n $('#notificationList').find(loaderClass).fadeOut();\n setTimeout(function () { $('#notificationList').find(loaderClass).remove(); }, 400);\n }\n });\n }", "function getNotification(){\n\tvar data = {\n\t\t\"session\" : localStorage.sessionId\n\t}\n\tperformPostRequest(\"get-notifications.php\", data, function(data){\n\t\tswitch(data.status) {\n\t\t\tcase 470:\n\t\t\t\tlogOut();\n\t\t\t\tbreak;\n\t\t\tcase 200:\n\t\t\t\tgetGameInvitation(data);\n\t\t\t\tbreak;\n\t\t\tcase 201:\n\t\t\t\tlocalStorage.setItem(\"gameAreaClickCounter\", 1);\n\t\t\t\tlocalStorage.setItem(\"gameTurn\", 1);\n\t\t\t\tlocalStorage.setItem(\"currentGameNum\", data.gameNum);\n\t\t\t\tbeginGame(data.creatorName);\n\t\t\t\tbreak;\n\t\t}\n\t});\n}", "async getCommentReplies({ commit }, commentId) {\n try {\n commit('getCommentRepliesRequest');\n let res = await axios.get(`/reply/comment-id/${commentId}`);\n const replies = res.data.replies;\n commit('getCommentRepliesInfo', replies);\n return res;\n } catch(err) {\n commit('getCommentRepliesError', err);\n }\n }", "function fetchNotifications() {\n\t// Update Progress bar value\n\tsetTimeout(function() {\n\t\tupdateProgressBar(\"Finishing....\", \"100%\");\n\t\tsetTimeout(function() {\n\t\t\ttoggleProgressBar();\n\t\t\tresetProgressBar();\n\n\t\t}, 5000);\n\n\t}, 10000);\n\n\tsetInterval(function() {\n\n\t\t$.ajax({\n\t\t\turl : \"MessageService\",\n\t\t\ttype : \"GET\",\n\t\t\tdata : {\n\t\t\t\trequest : 'getMessages'\n\t\t\t},\n\t\t\tsuccess : function(data) {\n\t\t\t\tparsePushMessagJSON(JSON.parse(data));\n\t\t\t}\n\t\t});\n\t}, 60000); // <-------Interval Is Set To 2 Minute\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user params to generate and set the converted src
updateconvertedurl() { // src is only actually required property if (this.src) { const params = { height: this.height, width: this.width, quality: this.quality, src: this.src, rotate: this.rotate, fit: this.fit, watermark: this.watermark, wmspot: this.wmspot, format: this.format, }; this.srcconverted = MicroFrontendRegistry.url( "@core/imgManipulate", params ); } }
[ "function addURLParam(element,newParam){var originalSrc=element.getAttribute('src');element.setAttribute('src',originalSrc+getUrlParamSign(originalSrc)+newParam);}", "set src(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.src[set]\");\n this._src = aValue;\n }", "function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}", "function setImageSrc(image, location) {\n image.src = location + '-640_medium.webp';\n}", "updateSrcSet(newSrc) {\n if (this.srcValues.length > 0) {\n this.srcValues.forEach(function (src) {\n if (src.name === newSrc.name) {\n src.url = newSrc.url;\n }\n }.bind(this));\n }\n\n this.saveSrcSet();\n this.fredCropper.el.dataset.crop = 'true';\n this.fredCropper.pluginTools.fredConfig.setPluginsData('fredcropper'+this.fredCropper.el.fredEl.elId, 'activated', 'true');\n }", "function setPicture(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\telement.find('source').each(function(){\n\n\t\t\t\t\tvar media, path, num;\n\t\t\t\t\tmedia = $(this).attr('media');\n\t\t\t\t\tpath = $(this).attr('src');\n\n\t\t\t\t\tif(media)\n\t\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\t\t\t\t\telse\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" style=\"' + element.attr('style') + '\" alt=\"' + element.attr('alt') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\t\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}", "saveSrcSet() {\n let i = 0;\n this.srcSet = '';\n if(this.srcValues.length > 0) {\n this.srcValues.forEach(function(src) {\n if(src.url.length > 0) {\n i++;\n this.srcSet += src.url + ' ' + src.width + 'w';\n if (i <= this.srcCount) {\n this.srcSet += ', ';\n }\n }\n }.bind(this));\n // Save the srcset value to the element attribute\n this.fredCropper.setStateAttribute('srcset',this.srcSet);\n }\n this.srcCount++;\n //console.log(this.srcSet);\n }", "_createSourceOptions(srcOptions) {\n var self = this;\n srcOptions = super._createSourceOptions(srcOptions);\n srcOptions.tileUrlFunction = function(tileCoord) {\n return self.tileUrlFunction(\n tileCoord,\n srcOptions.baseUrl,\n srcOptions.layer,\n srcOptions.format\n );\n };\n if(\n angular.isUndefined(srcOptions.tileGrid) &&\n angular.isDefined(srcOptions.extent)\n ) {\n var w = getWidth(srcOptions.extent);\n var h = getHeight(srcOptions.extent);\n var minRes = Math.max(w / srcOptions.tileSize[0], h / srcOptions.tileSize[1]);\n srcOptions.tileGrid = new TileGrid({\n origin: getBottomLeft(srcOptions.extent),\n resolutions: self._createResolutions(\n minRes,\n srcOptions.levels\n )\n });\n }\n return srcOptions;\n }", "function mapSource(src) {\n if (types.isPlainObject(src)) {\n return utils.pick(src, [\"content\", \"path\"]);\n }\n\n if (types.isString(src)) {\n return src;\n }\n\n throw new Error(\"Invalid format for input file to bundle.\");\n }", "copyTexImage2D(ctx, funcName, args) {\n const [target, level, internalFormat, x, y, width, height, border] = args;\n const info = getTextureInfo(target);\n updateMipLevel(info, target, level, internalFormat, width, height, 1, UNSIGNED_BYTE);\n }", "_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst t = editor.t;\n\t\tconst conversion = editor.conversion;\n\t\tconst imageUtils = editor.plugins.get( 'ImageUtils' );\n\n\t\tconversion.for( 'dataDowncast' )\n\t\t\t.elementToElement( {\n\t\t\t\tmodel: 'imageBlock',\n\t\t\t\tview: ( modelElement, { writer } ) => createImageViewElement( writer, 'imageBlock' )\n\t\t\t} );\n\n\t\tconversion.for( 'editingDowncast' )\n\t\t\t.elementToElement( {\n\t\t\t\tmodel: 'imageBlock',\n\t\t\t\tview: ( modelElement, { writer } ) => imageUtils.toImageWidget(\n\t\t\t\t\tcreateImageViewElement( writer, 'imageBlock' ), writer, t( 'image widget' )\n\t\t\t\t)\n\t\t\t} );\n\n\t\tconversion.for( 'downcast' )\n\t\t\t.add( downcastImageAttribute( imageUtils, 'imageBlock', 'src' ) )\n\t\t\t.add( downcastImageAttribute( imageUtils, 'imageBlock', 'alt' ) )\n\t\t\t.add( downcastSrcsetAttribute( imageUtils, 'imageBlock' ) );\n\n\t\t// More image related upcasts are in 'ImageEditing' plugin.\n\t\tconversion.for( 'upcast' )\n\t\t\t.elementToElement( {\n\t\t\t\tview: getImgViewElementMatcher( editor, 'imageBlock' ),\n\t\t\t\tmodel: ( viewImage, { writer } ) => writer.createElement( 'imageBlock', { src: viewImage.getAttribute( 'src' ) } )\n\t\t\t} )\n\t\t\t.add( upcastImageFigure( imageUtils ) );\n\t}", "async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }", "function setElementSrc ( id, value )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt && typeof(value) == \"string\" ) elt.src = value;\n }", "setTransSourceUrl(value: string) {\n this.transSourceUrl = value;\n }", "_applyCustomConfig() {\n\n this._backupSPFXConfig();\n\n // Copy custom gulp file to\n this.fs.copy(\n this.templatePath('gulpfile.js'),\n this.destinationPath('gulpfile.js')\n );\n\n // Add configuration for static assets.\n this.fs.copy(\n this.templatePath('config/copy-static-assets.json'),\n this.destinationPath('config/copy-static-assets.json')\n );\n\n }", "changeSrc(e, source) {\n e.preventDefault();\n const src = e.target.elements.source.value || source;\n if (src.includes('www.youtube.com')) {\n this.player.src({type: 'video/youtube', src: src});\n }\n else {\n this.player.src({src: src});\n }\n this.reset();\n }", "loadSrcSet() {\n if(this.fredCropper.el.attributes.srcset.value === \"null\") {\n console.log('correctly null');\n return false;\n }\n let srcset = this.fredCropper.el.attributes.srcset.value.split(',');\n\n srcset.forEach(function(t){\n let width = t.substr(t.lastIndexOf(\" \") + 1);\n let url = t.substr(0, t.lastIndexOf(\" \"));\n\n if(this.srcValues.length > 0) {\n this.srcValues.forEach((src) => {\n if (parseInt(src.width) === parseInt(width)) {\n src.url = url;\n }\n });\n }\n }.bind(this));\n\n let count = 0;\n this.srcValues.forEach(function(src) {\n if(src.url.length > 0) {\n count++;\n }\n });\n this.srcCount = count;\n //console.log(this.srcValues);\n }", "async function build(){\n\n let imgSrc = './dev/assets/img/*.+(png|jpg|gif|svg)',\n imgDst = './build/assets/img',\n jscopy = gulp.src(['./dev/assets/js/**/*.js']).pipe(uglify()).pipe(gulp.dest('./build/assets/js')),\n csscopy = gulp.src(['./dev/assets/css/**/*.css']).pipe(cleanCSS()).pipe(gulp.dest('./build/assets/css')),\n htmlcopy = gulp.src(['./dev/*.html']).pipe(gulp.dest('./build')),\n optimages = gulp.src(imgSrc).pipe(changed(imgDst)).pipe(imagemin()).pipe(gulp.dest(imgDst));\n\n}", "function setSpecialSettings(src, dst) {\n\t if (src.backgroundColor !== undefined) {\n\t setBackgroundColor(src.backgroundColor, dst);\n\t }\n\n\t setDataColor(src.dataColor, dst);\n\t setStyle(src.style, dst);\n\t setShowLegend(src.showLegend, dst);\n\t setCameraPosition(src.cameraPosition, dst);\n\n\t // As special fields go, this is an easy one; just a translation of the name.\n\t // Can't use this.tooltip directly, because that field exists internally\n\t if (src.tooltip !== undefined) {\n\t dst.showTooltip = src.tooltip;\n\t }\n\t }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
look for empty cell 16, then choose what cell move based on the keypressed
function lookForWhatToMove(key) { var coord = ""; for(var r = 0; r < dim_max; r++) { for(var c = 0; c < dim_max; c++) { if(m[r][c] == 16) { //console.log(key); switch(key) { //a, left case 65: case 37: if(validate(r, c+1)) coord = r+";"+c +"$"+ r+";"+(c+1); break; //w, up case 87: case 38: if(validate(r+1, c)) coord = r+";"+c +"$"+ (r+1)+";"+c; break; //d, right case 68: case 39: if(validate(r, c-1)) coord = r+";"+c +"$"+ r+";"+(c-1); break; //s, down case 83: case 40: if(validate(r-1, c)) coord = r+";"+c +"$"+ (r-1)+";"+c; break; } } } } //what is coord? //coord = "emptyCellRow;emptyCellCol$foundCellRow;foundCellCol" return coord; }
[ "function keyPress(evt) {\n if (current_cell == null)\n return;\n var key, key1;\n if (evt) {\n // firefox or chrome\n key = evt.key;\n key1 = evt.keyCode;\n }\n else {\n // IE\n key = String.fromCharCode(event.keyCode);\n }\n if (key1 == 8 || key1 == 46) {\n VerificarBorrar();\n current_cell.innerHTML = '';\n }\n\n else if (key1 >= 49 && key1 <= 57) {\n scoreT++;\n VerificarFila(key);\n VerificarColumna(key);\n VerificarSubTabla(key);\n current_cell.innerHTML = key;\n document.getElementById(\"score\").innerHTML = scoreT;\n }\n else if (key1 == 67) {\n borrarTodo();\n }\n\n\n}", "function navigateCells(e) {\n if($(\"div.griderEditor[style*=block]\").length > 0)\n return false;\n\n var $td = $table.find('.' + defaults.selectedCellClass);\n var col = $td.attr(\"col\");\n switch(e.keyCode) {\n case $.ui.keyCode.DOWN:\n //console.log($td);\n setSelectedCell($td.parent(\"tr:first\").next().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.UP:\n setSelectedCell($td.parent(\"tr\").previous().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.LEFT:\n //console.log(\"left\");\n break;\n case $.ui.keyCode.RIGHT:\n //console.log(\"right\");\n break;\n }\n }", "function cellClicked(cell) {\n if (gameOver == false && cell.innerText == \"\") {\n // decrease # of empty cells by 1\n empty--;\n\n /* set content according to players mark and changes current player. In the end tells weather there is a winner or not */\n cell.innerHTML = player;\n checkWin();\n player = (player === \"X\") ? \"O\" : \"X\";\n document.getElementById(\"player\").innerHTML = player;\n }\n}", "function moveNumberCellToEmpty(cell, playingOrShuffling) {\n // Checks if selected cell has number\n if (cell.className != \"empty\") {\n // Tries to get empty adjacent cell\n let emptyCell = getEmptyAdjacentCellIfExists(cell);\n \n if (emptyCell) {\n if (playingOrShuffling === 1) {\n // noOfMoves++;\n // document.getElementById(\"counter\").innerText = noOfMoves;\n // new Audio(\"../sound/fire_bow_sound-mike-koenig.mp3\").play();\n }\n // There is empty adjacent cell..\n // styling and id of the number cell\n let tempCell = { style: cell.style.cssText, id: cell.id };\n \n // Exchanges id and style values\n cell.style.cssText = emptyCell.style.cssText;\n cell.id = emptyCell.id;\n emptyCell.style.cssText = tempCell.style;\n emptyCell.id = tempCell.id;\n \n if (state == 1) {\n // Checks the order of numbers\n checkSolvedState();\n }\n }\n }\n }", "function handleKeyDownEvent(){\n if(d3.event.keyCode == 49){\n // Number 1: Set start point\n } else if(d3.event.keyCode == 50){\n // Number 2: Set end point\n } else if(d3.event.keyCode == 83){\n // Character S: Start search\n startSearch();\n } else if(d3.event.keyCode == 82){\n // Character R: Reset search\n resetSearch();\n } else if(d3.event.keyCode == 67){\n // Character C: Clear walls\n clearWalls();\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 nextCellAvailable() {\n\t\t\t\tvar cellAvailable = true;\n\t\t\t\tvar newSnakeCellX = newSnakeCell().x;\n\t\t\t\tvar newSnakeCellY = newSnakeCell().y;\n\n\t\t\t\t/* Check if there is no border on X-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellX / ($scope.options.cellWidth + $scope.options.cellMargin)) === $scope.maxAvailabeCells.x || newSnakeCellX < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Check if there is no border on Y-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellY / ($scope.options.cellHeight + $scope.options.cellMargin)) === $scope.maxAvailabeCells.y || newSnakeCellY < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Walking thru all snake's cells. If next cell is busy by existing one it means that snake hits its own tail. */\n\t\t\t\tangular.forEach($scope.snake, function (cell) {\n\t\t\t\t\tif (cell.x === newSnakeCellX && cell.y === newSnakeCellY) {\n\t\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn cellAvailable;\n\t\t\t}", "function startGame() {\n allCells.forEach((cell) => {\n cell.classList.remove(xMarker);\n cell.classList.remove(oMarker);\n cell.removeEventListener(\"click\", handleClick);\n cell.addEventListener(\"click\", handleClick, { once: true });\n });\n}", "function selectKnCell(e){\n\tvar knCell = keynapse.currentKnCell;\n\tstopKeynapse();\n\n\tif(knCell.type == 'text'){\n\t\t$(knCell).focus();\t\t\n\t} else {\n\t\t$(knCell).focus();\n\t\t$(knCell).trigger(\"click\");\n\t}\n}", "function keyPressed() {\n if(keyCode === 37 && currentCardIndex > 0) {\n pressedLeft = true;\n }\n\n if(keyCode === 39 && currentCardIndex < amountOfCards - 1) {\n pressedRight = true;\n }\n redraw();\n}", "function nextKnCell(e){\n\tvar previousKnCell = keynapse.currentKnCell;\n\tpreviousKnCell.knCellHint.removeClass('kn-cell-hint-current');\n\n\tvar currentKnCell;\n\tif (keynapse.currentKnCellIndex == keynapse.knCells.length - 1 ){\n\t\tkeynapse.currentKnCellIndex = 0;\n\t\tkeynapse.currentKnCell = keynapse.knCells[keynapse.currentKnCellIndex];\n\t\tcurrentKnCell = keynapse.currentKnCell;\n\t} else {\n\t\tkeynapse.currentKnCell = keynapse.knCells[++keynapse.currentKnCellIndex];\n\t\tcurrentKnCell = keynapse.currentKnCell;\n\t}\n\t\n\tcurrentKnCell.knCellHint.addClass('kn-cell-hint-current');\n}", "function spacebar(e) {\n if (e.keyCode === 32) {\n jumping()\n }\n}", "function showCell (evt) {\n evt.target.className = evt.target.className.replace(\"hidden\", \"\");\n if (evt.target.classList.contains(\"mine\")) {\n showAllMines();\n playBomb();\n reset();\n return;\n }\n showSurrounding(evt.target);\n checkForWin();\n}", "onKeyPress(str, key) {\n switch (key.name) {\n case wordsearchConstants.KEY_UP:\n if (this.cursorPos.row > 0) {\n this.cursorPos.row--;\n } else {\n return;\n }\n break;\n case wordsearchConstants.KEY_DOWN:\n if (this.cursorPos.row < this.gridSize - 1) {\n this.cursorPos.row++;\n } else {\n return;\n }\n break;\n case wordsearchConstants.KEY_LEFT:\n if (this.cursorPos.col > 0) {\n this.cursorPos.col -= 2;\n } else {\n return;\n }\n break;\n case wordsearchConstants.KEY_RIGHT:\n if (this.cursorPos.col < (this.gridSize - 1) * 2) {\n this.cursorPos.col += 2;\n } else {\n return;\n }\n break;\n case wordsearchConstants.KEY_SPACE: {\n this.onSpaceKeyPressed();\n break;\n }\n default:\n // if user enters any other key they will be writing over the grid so we need to redraw it\n if (!(key.ctrl && key.name === 'c')) {\n this.drawGrid();\n }\n }\n\n this.setCursorPos();\n }", "function gridClickListener(event) {\n const ctx = canvas.getContext('2d');\n\n let [row, col] = translateClickPosition(event);\n\n console.log(\"clicked [\",row ,\"][\",col, \"]\");\n\n // start the timer once a grid cell is clicked (if it hasn't been started already)\n if (!timer) setTimer();\n\n if (event.ctrlKey) {\n // mark a cell with a question mark\n minesweeper.toggleQuestion(row, col);\n } else if (event.shiftKey) {\n // flag a cell\n minesweeper.toggleFlag(row, col);\n } else {\n // cell was left clicked, reveal the cell\n minesweeper.revealCell(row, col);\n }\n\n // check if game is won or lost\n if (minesweeper.isGameWon()) {\n renderGameWon(ctx);\n } else if (minesweeper.isGameLost()) {\n renderGameLost(ctx);\n } else {\n // game is not over, so render the grid state\n renderGrid(ctx);\n mineCounter.innerText = minesweeper.remainingFlags().toString(10).padStart(3, \"0\");\n }\n\n}", "function cellClick(id) {\n\n\tplayerMove = id.split(\",\");\n\tif (playerMove[0] == currentCell[0] && playerMove[1] == currentCell[1]) {\n\n\t\tvar cellClicked = document.getElementById(id);\n\t\tcellClicked.style.backgroundColor = getRandomColor();\n\t\tscoreCounter++;\n\t\tmoveMade = true;\n\t\t$(cellClicked).text(scoreCounter);\n\t\tsetTimeout(function() {\n\t\t\t$(cellClicked).text(\"\");\n\t\t}, 1000);\n\n\t} else {\n\t\tgameOver = true;\n\n\t\tvar lastClicked = document.getElementById(id);\n\n\t\tvar lastColor = $(lastClicked).css(\"background-color\");\n\n\t\tfor (var row = 1; row <= tableHeight; row++) {\n\t\t\tfor (var col = 1; col <= tableWidth; col++) {\n\t\t\t\tdocument.getElementById(row + \",\" + col).style.backgroundColor = lastColor;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\t\n}", "function checkMovement(){\n if(keyIsDown(65)){\n player.position.x -=setMode(mode);\n }\n if(keyIsDown(68)){\n player.position.x +=setMode(mode);\n }\n if(keyIsDown(87)){\n player.position.y -=setMode(mode);\n }\n if(keyIsDown(83)){\n player.position.y +=setMode(mode);\n }\n}", "function check_unclicked_cell(cell) {\n\tif ((!cell.hasClass(\"clicked\"))&&(!cell.hasClass(\"flag\"))){\n\t\tvar cell_adjacent = get_adjacent(cell);\n\t\t/* If a cell with mine is left-clicked and it is not marked as mine, the user lose\n\t\tthe game */\n\t\tif (cell.hasClass(\"mine\")) {\n\t\t\tlose_game();\n\t\t\tcell.css(\"background-color\", \"red\");\n\t\t\t$(\"#minefield\").addClass(\"lose\");\n\t\t}\n\t\telse {\n\t\t\t/* If a cell without mine is left-clicked, clear the cell and if the cell \n\t\t\thasn't any adjacent mine, clear its adjacent cell */\n\t\t\tif (cell.attr(\"value\") == 0) {\n\t\t\t\tcell.addClass(\"clicked\");\n\t\t\t\tcell_adjacent.forEach(function(entry) {\n\t\t\t\t\tcheck_unclicked_cell(entry);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcell.html(cell.attr(\"value\"));\n\t\t\t\tcell.addClass(\"clicked\");\n\t\t\t}\n\t\t}\n\t}\n}", "handleEraseClick() {\n const history = this.state.history.slice(0, this.state.currStep + 1);\n const currBoard = this.state.history[this.state.currStep].board.slice();\n const currNotes = JSON.parse(JSON.stringify(this.state.history[this.state.currStep].notes.slice()));\n const startingBoard = this.state.history[0].board;\n\n if (this.state.selectedCell && !startingBoard[this.state.selectedCell] && (!this.checkNotesEmpty(currNotes[this.state.selectedCell]) || currBoard[this.state.selectedCell])) {\n currBoard[this.state.selectedCell] = null;\n for (let i = 0; i < 9; i++) {\n currNotes[this.state.selectedCell][i] = false;\n }\n\n let numCount = this.countNums(currBoard);\n this.setState({\n history: history.concat([{\n board: currBoard,\n notes: currNotes,\n }]),\n currStep: this.state.currStep + 1,\n numCount: numCount,\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
spotifyClientCredentialsFlow_relatedArtists Authorize Spotify with client credentials flow Guide on this authorization flow: Create Spotify app at
async function spotifyClientCredentialsFlow_playlist(context) { let { relatedArtists } = context; /** * Get the access token for your Spotify App * Authorization type: Basic * Input: client_id, client_secret, grant_type * Output: access token * @function getAccessToken * */ async function getAccessToken() { let myHeaders = new Headers(); myHeaders.append("Authorization", "Basic NDg3MmM3MDU1NzVhNDU5M2EyMjRkZjhlY2RlOGNmZjY6MzM1MjA1ZmJkNzU0NDlmMTg1MTQxZGI4NDU2OGM4MGQ="); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); myHeaders.append("Cookie", "__Host-device_id=AQCRGraHLh7exU3bLCTNZeXoxf5C5tdKL4vFbN4MYhpGZTwnMUisw35CBX0b6zvzrNzPHdFA25GqXO3NdX12SFcuCocGxmtGPA0"); let urlencoded = new URLSearchParams(); urlencoded.append("grant_type", "client_credentials"); let requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded, redirect: 'follow' }; return fetch("https://accounts.spotify.com/api/token", requestOptions) .then(response => response.json()) .then(result => result) .catch(error => console.log('error', error)); }; // getAccessToken /** * Get the Spotify ID for the artist. That's needed to search related artists later on * API Guide on general searches: https://developer.spotify.com/console/search/ * Authorization type: Bearer access token * Input: bearer access token, artist name * Output: object including artist id * @function getArtistId * */ async function getSongs(bearerAccessToken, relatedArtists) { let relatedArtistIds = relatedArtists.map(relatedArtist => relatedArtist.id); let theirTopTracks = await relatedArtistIds.map(artistId => { let myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer " + bearerAccessToken); let requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; return fetch(`https://api.spotify.com/v1/artists/${artistId}/top-tracks?market=US`, requestOptions) .then(response => response.json()) .then(result => result) .catch(error => console.log('error', error)); }); // If we are limited to a number of songs in the playlist, then if an user picks X number of artists // then have each artist contribute similar amount of songs let limitSongs = 30; // combine all songs from selected artists up to 15 songs total let limitArtists = relatedArtists.length; let limitSongsPerArtist = limitSongs / limitArtists; let tracks = []; /** * @array artists * All their artists with their top tracks * * */ return Promise.all(theirTopTracks).then(artists => { /** * * @object topTracks * An artist's top tracks * where topTracks.track[i] includes name and external_urls.spotify * */ console.group("Distributing artists among the playlist"); console.info("Should count up to some number, then restart counting to the same number or less (if artist has less songs listed in their top tracks). It will cycle the number of times there are artists."); artists.forEach(artistTopTracks => { let topTracks = artistTopTracks.tracks; topTracks.forEach((track, i) => { if (i < limitSongsPerArtist) { console.log(i); tracks.push({ songTitle: track.name, url: track.external_urls.spotify }); } else { return false; } }) }); tracks = tracks.slice(0, limitSongs); console.groupEnd(); return tracks; }); } // getSongs /** * @expect {"access_token":"<Temporary Bearer Access Token>","token_type":"Bearer","expires_in":3600,"scope":""} */ let accessTokenObject = await getAccessToken(); let bearerAccessToken = accessTokenObject.access_token; console.group("Spotify API"); console.dir({ accessTokenObject }) console.groupEnd(); let songs = await getSongs(bearerAccessToken, relatedArtists); // debugger; // let songs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20]; // Mock data songs = songs.sort(function(a, b) { return 0.5 - Math.random() }); console.group("Spotify API"); console.dir({ songs }) console.groupEnd(); return songs; } // spotifyClientCredentialsFlow_playlist
[ "async function requestAccessToken() {\n\n/**\n * Function to get base64 encoded data from private spotify values.\n * @param {string} clientID - private spotify client id\n * @param {string} secret - private spotify secret key\n */\n async function getEncodedKey(clientID, secret) {\n const encodedVal = btoa(clientID + \":\" + secret);\n return encodedVal;\n };\n\n const key = await getEncodedKey(CLIENT_ID, CLIENT_SECRET)\n const config = {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': `Basic ${key}`\n }\n };\n const params = new URLSearchParams();\n params.append('grant_type', 'client_credentials');\n const {data} = await axios.post(ACCESS_TOKEN_URL, params, config);\n return data.access_token;\n}", "function authorize(credentials, callback) {\n const { clientSecret, clientId, redirectUris } = credentials.installed;\n const oAuth2Client = new google.auth.OAuth2(\n clientId, clientSecret, redirectUris[0],\n );\n\n /**\n * Get and store new token after prompting for user authorization, and then\n * execute the given callback with the authorized OAuth2 client.\n * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.\n * @param {getEventsCallback} callback The callback for the authorized client.\n */\n function getAccessToken() {\n const authUrl = oAuth2Client.generateAuthUrl({\n access_type: 'offline',\n scope: SCOPES,\n });\n console.log('Authorize this app by visiting this url:', authUrl);\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question('Enter the code from that page here: ', (code) => {\n rl.close();\n oAuth2Client.getToken(code, (err, token) => {\n if (err) return console.error('Error retrieving access token', err);\n oAuth2Client.setCredentials(token);\n // Store the token to disk for later program executions\n fs.writeFile(TOKEN_PATH, JSON.stringify(token), () => {\n if (err) return console.error(err);\n console.log('Token stored to', TOKEN_PATH);\n return true;\n });\n return callback(oAuth2Client);\n });\n });\n }\n\n // Check if we have previously stored a token.\n fs.readFile(TOKEN_PATH, (err, token) => {\n if (err) return getAccessToken(oAuth2Client, callback);\n oAuth2Client.setCredentials(JSON.parse(token));\n return callback(oAuth2Client);\n });\n }", "generateAuthTokens(clientName) {\n var self = this;\n self.getClientConfig(clientName).then(function (clientConfig) {\n const courseraCodeURI = util.format(\n COURSERA_CODE_URI,\n clientConfig.scope,\n COURSERA_CALLBACK_URI + clientConfig.clientId,\n clientConfig.clientId);\n startServerCallbackListener();\n (async () => {\n await open(courseraCodeURI);\n })();\n }).catch(function (error) {\n console.log(error);\n });\n }", "async bestEffortAppleCtx(ctx) {\n if (ctx.hasAppleCtx()) {\n // skip prompts if already have apple ctx\n return;\n }\n\n if (ctx.nonInteractive) {\n return;\n }\n\n const confirm = await (0, _prompts().confirmAsync)({\n message: `Do you have access to the Apple account that will be used for submitting this app to the App Store?`\n });\n\n if (confirm) {\n return await ctx.ensureAppleCtx();\n } else {\n _log().default.log(_chalk().default.green('No problem! 👌 \\nWe can’t auto-generate credentials if you don’t have access to the main Apple account. \\nBut we can still set it up if you upload your credentials.'));\n }\n }", "function newFavoriteArtist() { // essentially the main method of this script.\n \n var relatedArtists = getRelatedArtists(\"4yvcSjfu4PC0CYQyLy4wSq\"); // test example: artist related to __tame impala__\n var focusArtist = pickRandomArtist(relatedArtists);\n \n // collect info about the spotlight artist @ this spot.\n \n var httpResponse = makePlaylist(focusArtist);\n var uris = getValues(httpResponse, \"uri\");\n var playlistId = \"\";\n for (var i = 0; i < uris.length; i++) {\n if (uris[i].includes(\"playlist\")) playlistId = (uris[i]).substring(17);\n }\n \n var focusAlbum = getBestAlbum(focusArtist);\n //Logger.log(focusAlbum);\n var tracksInAlbum = getAlbumTracks(focusAlbum); \n //Logger.log(tracksInAlbum);\n fillPlaylist(playlistId, tracksInAlbum); //TODO: Randomize order, mix in other things of artist.\n \n}", "function startApp() {\n inquirer.prompt([\n\n {\n type: \"list\",\n name: \"userCommandChoices\",\n message: \"What would you like to do?\",\n choices: [\"View Products for Sale\", \"View Low Inventory\", \"Add to Inventory\", \"Add New Product\"]\n }\n\n ]).then(function (answer) {\n\n // This could probably be made into a switch/case statement but I'm not as experiences with those yet\n if (answer.userCommandChoices === \"View Products for Sale\") {\n viewProducts();\n\n } else if (answer.userCommandChoices === \"View Low Inventory\") {\n viewLowInventory();\n\n } else if (answer.userCommandChoices === \"Add to Inventory\") {\n addToInventory();\n\n } else if (answer.userCommandChoices === \"Add New Product\") {\n addNewProduct();\n }\n });\n}", "getToken() {\n const basicAuth = new Buffer(`${this.spotifyClientId}:${this.spotifyClientSecret}`).toString('base64')\n const options = {\n method: 'POST',\n uri: this.tokenUri,\n headers: {\n 'Authorization': `Basic ${basicAuth}`,\n },\n form: {\n grant_type: 'client_credentials',\n },\n json: true,\n }\n console.log(`Will make request for Spotify token with options ${JSON.stringify(options)}`);\n\n return request(options)\n .then(tokenResponse => tokenResponse.access_token)\n .catch(err => {\n console.log(err);\n throw new Error(`Spotify error ${JSON.stringify(err)}`)\n })\n }", "async getRecommendedTracksAndCreatePlaylist() {\n await spotifyApi.setAccessToken(this.options.access_token);\n\n let usersTopIds = await this.getUsersTopIds();\n let recommendedTracks = [];\n\n if (usersTopIds.seed_artists && usersTopIds.seed_artists.length > 0) {\n const recommendedTracksFromCall = await this.getRecommendedTracks(\n usersTopIds.seed_artists, 'seed_artists');\n recommendedTracks = recommendedTracks.concat(recommendedTracksFromCall);\n }\n\n if (usersTopIds.seed_tracks && usersTopIds.seed_tracks.length > 0) {\n const recommendedTracksFromCall = await this.getRecommendedTracks(\n usersTopIds.seed_tracks, 'seed_tracks');\n recommendedTracks = recommendedTracks.concat(recommendedTracksFromCall);\n }\n\n const recommendedPlaylist = await this.createPlaylist(recommendedTracks);\n return {\n recommendedList: recommendedPlaylist,\n playListId: this.playListId\n }\n }", "function authorize(credentials, callback) {\n const {client_secret, client_id, redirect_uris} = credentials.installed;\n const oAuth2Client = new google.auth.OAuth2(\n client_id, client_secret, redirect_uris[0]);\n\n // Check if we have previously stored a token.\n if (!config.get('oauthToken')) {\n setup.getAccessToken(oAuth2Client, callback);\n } else {\n oAuth2Client.setCredentials(config.get('oauthToken'));\n callback(oAuth2Client);\n }\n}", "async ensureAppCredentials(appLookupParams) {\n var _this$credentials2, _this$credentials2$ac, _this$credentials2$ac2;\n\n const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);\n const {\n accountName\n } = appLookupParams;\n\n if (this.isPrefetched[accountName] || (_this$credentials2 = this.credentials) !== null && _this$credentials2 !== void 0 && (_this$credentials2$ac = _this$credentials2[accountName]) !== null && _this$credentials2$ac !== void 0 && (_this$credentials2$ac2 = _this$credentials2$ac.appCredentials) !== null && _this$credentials2$ac2 !== void 0 && _this$credentials2$ac2[appCredentialsIndex]) {\n return;\n }\n\n await this.refetchAppCredentials(appLookupParams);\n }", "function createApp() {\n // GET rel=anonUser returns both links\n var r = name ?\n repository.get('anonApplications')[0] :\n repository.get('applications')[0];\n // if the server doesn't support forking an application, the client\n // falls back to the regular POST /applications request that creates\n // a new endpoint or resumes an existing one with the given id\n var v = (instanceId && r.revision >= 2) ? 2 : 1;\n tm && tm.record('create_application_started');\n return Task.run(function () {\n // Guess the xframe URL only in the p2p anon auth.\n // This could be done unconditionally, but there may\n // be troubles with the private OAuth2 flow in which\n // the xframe.src value is changed to get the token\n if (!name)\n return;\n var _user = new URI(xframe.src());\n var _apps = new URI(r.href);\n // in the p2p anon flow rel=anonApplications and rel=anonUser\n // are on different domains, but GET rel=anonUser doesn't return\n // a new xframe; the workaround is to guess the new xframe URL\n if (_user.host() != _apps.host())\n return xframe.src.set(_apps.path('/xframe') + '');\n }).then(function () {\n return endpoint.ajax({\n type: 'POST',\n url: r.href,\n version: v,\n data: {\n AnonymousDisplayName: name,\n UserAgent: version,\n Culture: culture,\n EndpointId: endpointId,\n InstanceId: v == 2 ? instanceId : void 0\n }\n });\n }).then(function (app) {\n repository.put(app);\n return app;\n });\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 LoginSpotify(props) {\n const location = useLocation();\n\n const state = generateRandomString(16);\n\n const opts = {\n client_id: process.env.REACT_APP_SPOTIFY_CLIENT_ID,\n redirect_uri: location.origin + location.pathname,\n scope: `user-read-private \n user-read-email \n user-follow-read \n user-library-read \n user-follow-modify \n user-library-modify`,\n state: state,\n show_dialog: false,\n }\n\n const onSubmit = (e) => {\n e.preventDefault();\n props.onSubmit(state);\n window.location = temporaryUserAuthorization(opts);\n }\n\n return (\n <Form onSubmit={onSubmit} className=\"d-flex flex-column justify-content-center align-content-center\">\n <Button variant=\"primary\" type=\"submit\">Continue</Button>\n </Form>\n )\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}", "async function getRelatedArtists(bearerAccessToken, artistId) {\n var myHeaders = new Headers();\n myHeaders.append(\"Authorization\", \"Bearer \" + bearerAccessToken);\n\n var requestOptions = {\n method: 'GET',\n headers: myHeaders,\n redirect: 'follow'\n };\n\n return fetch(\"https://api.spotify.com/v1/artists/\" + artistId + \"/related-artists\", requestOptions)\n .then(response => response.json())\n .then(result => result)\n .catch(error => console.log('error', error));\n }", "async function getArtistId(bearerAccessToken, artistName) {\n var myHeaders = new Headers();\n myHeaders.append(\"Authorization\", \"Bearer \" + bearerAccessToken);\n\n var requestOptions = {\n method: 'GET',\n headers: myHeaders,\n redirect: 'follow'\n };\n\n return fetch(\"https://api.spotify.com/v1/search?q=artist:\" + artistName + \"&type=artist\", requestOptions)\n .then(response => response.json())\n .then(result => result)\n .catch(error => console.log('error', error));\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 getArtistId(bearerAccessToken, artistName) {\n let myHeaders = new Headers();\n myHeaders.append(\"Authorization\", \"Bearer \" + bearerAccessToken);\n\n let requestOptions = {\n method: 'GET',\n headers: myHeaders,\n redirect: 'follow'\n };\n\n return fetch(\"https://api.spotify.com/v1/search?q=artist:\" + artistName + \"&type=artist\", requestOptions)\n .then(response => response.json())\n .then(result => result)\n .catch(error => console.log('error', error));\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read the actual content for the page
contentFor(page) { let reader = this.readers[page.extension]; let pathToFile = this.pathToPageContent(page); let content = ''; if (typeof reader.readFile !== 'undefined') { content = reader.readFile(pathToFile); } else { content = fs.readFileSync(pathToFile, 'utf8'); } if (!reader) { throw new Error(`No reader for file extension '${page.extension}'`) } else if (typeof reader.read !== 'function') { throw new Error(`Reader for file extension '${page.extension}' has no read method`); } return reader.read(content); }
[ "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}", "function readData()\r{\r var pages = docData.selectedDocument.pages;\r $.writeln('# of pages: ' + pages.length);\r for (var x = 0; x < pages.length; x++){\r page = pages.item(x); \r pageName = page.name;\r $.writeln(\"Page: \" + pageName);\r pageTagToAdd = addPage(pageName);\r readPage(pageTagToAdd,page);\r exportGraphicLinks(pageTagToAdd,page);\r }\r}", "function getHtmlContent(){\n \n }", "function loadContent()\n {\n xhrContent = new XMLHttpRequest();\n xhrContent.open(\"GET\",\"Scripts/paragraphs.json\",true);\n xhrContent.send(null);\n xhrContent.addEventListener(\"readystatechange\",readParagraphs);\n }", "async getContent() {\n return await this.spider.getContent()\n }", "function loadContent(page) {\n\t// Builds an XMLHttpRequest if supported otherwise defaults to an\n\t// ActiveXObject.\n\tvar xmlhttp;\n\tif (window.XMLHttpRequest)\n\t\txmlhttp = new XMLHttpRequest();\n\telse\n\t\txmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\n\t// Sets a callback that shows the response inside the content section.\n\txmlhttp.onreadystatechange = function() {\n\t\tif ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))\n\t\t\tdocument.getElementById(\"content\").innerHTML = xmlhttp.responseText;\n\t}\n\n\t// Builds the destination URL and sends the AJAX request.\n\tvar page = \"content/\" + page + \".html\";\n\txmlhttp.open(\"GET\", page, true);\n\txmlhttp.send();\n}", "function readParagraphs() \n{\n if ((xhrContent.readyState === 4) && (xhrContent.status === 200)) \n {\n let MyContent = JSON.parse(xhrContent.responseText);\n let paragraphs = MyContent.paragraphs;\n paragraphs.forEach(function (paragraph) \n {\n let paragraphElements = document.getElementById(paragraph.id);\n //Searches element ids and aligns them with suitable paragraphs in the html\n if(paragraphElements) \n {\n paragraphElements.innerHTML = paragraph.content;\n } \n }, this);\n }\n}", "function loadPage() {\n pageNumber++; // Increment the page number\n const options = {\n method: 'GET',\n uri: `https://doctor.webmd.com/results?so=&zip=${ZIP_CODE}&ln=Family%20Medicine&pagenumber=${pageNumber}`,\n headers: {\n 'User-Agent': 'Request-Promise',\n 'Authorization': 'Basic QWxhZGRpbjpPcGVuU2VzYW1l'\n },\n transform: body => {\n return cheerio.load(body);\n }\n };\n request(options)\n .then(async $ => {\n let results = await fetchResults($);\n return results;\n })\n .catch(err => console.error(err.message));\n }", "collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }", "function process_contents() {\n process_histories(issue, (err) => {\n if (err) log.warn('Error processing history for ' + issue.key, err);\n process_comments(issue, (err) => {\n if (err) log.warn('Error processing comments for ' + issue.key, err);\n cb();\n });\n });\n }", "function fun( error , response , data ){\n // current directory => homepage.html , => html file of webpage\n parseData(data);\n}", "function loadPage (slug) {\n\tvar pagedata = fm(cat(PAGE_DIR+slug+'.md'));\n\treturn pagedata;\n}", "function GetBody() {\n const context = React.useContext(SinglepostContext)\n if (context) {\n return context.data.body.map(bodyString => {\n\n if (bodyString.includes(\"(CODE)\")) {\n const splitBodyString = bodyString.split(\"(CODE)\");\n return <Page language={splitBodyString[0]} code={cleanString(splitBodyString[1])}/>\n } \n else if (bodyString.includes(\"</Header>\")) {\n const header = bodyString.match(new RegExp(\"<Header>(.*)</Header>\"))[1]\n return <h3 className=\"body-header\"> {header}</h3>\n }\n else if (bodyString.includes(\"</Link>\")) {\n const href = bodyString.match(new RegExp(\"href='(.*)'\"))[1]\n const linkText = bodyString.match(new RegExp(\">(.*)</Link>\"))[1]\n return <a className=\"body-link\" href={href}> {linkText} </a>\n }\n else if (bodyString.includes(\"/images/\")) return <img alt=\"body\" className=\"body-image\" src={bodyString}/>\n else if (bodyString !== \"\") return <p> {cleanString(bodyString)}</p>\n return null\n })\n }\n return <h2> There was a problem</h2>\n }", "function read(){\n\n }", "function readBookIssueRecords() {\n $.get(\"ajax/BooksIssue/readRecords.php\", {}, function (data, status) {\n $(\".records_content\").html(data);\n });\n}", "function getStory() {\n\txhttp = new XMLHttpRequest(); // <-- create request\n\tchangeSong(); // <-- load first song\n\n\t// Each time the request-state changes...\n\txhttp.onreadystatechange = function() {\n\n\t\t// readyState(4) = Operation complete, status(200) = request succesfull\n\t\tif (this.readyState == 4 && this.status == 200) {\n\n\t\t\tstrStory = xhttp.responseText; // <-- retrieve text from query\n\t\t\tstoryParts = strStory.split(\"<END>\"); // <-- break string into array by '<END>' delimeter (was written into .txt file)\n\t\t\tstoryParts.unshift(intro); // <-- add intro portion\n\n\t\t\t// for each string element in array...\n\t\t\tfor (var i = 0; i < storyParts.length; i++) {\n\t\t\t\tstoryParts[i] = storyParts[i].trim(); // <-- trim any leading/trailing white-spaces\n\t\t\t}\n\t\t\ttextAreaEl.value = storyParts[0]; // <-- set opening window to first string (Intro)\n\t\t}\n\t}\n\txhttp.open(\"GET\", \"pupProcess.php?name=\" + storyName, true); // <-- Open .php file, passing 'name' parameter to open file\n\txhttp.send(); // <-- sent request\n}", "async getDownloadedContent() {\n this.setState({ isLoading: true });\n var content = await DbQueries.queryVersions(\n this.props.language,\n this.props.versionCode,\n this.props.bookId,\n this.props.currentVisibleChapter\n );\n if (content != null) {\n this.setState({\n chapterHeader:\n content[0].chapters[this.state.currentVisibleChapter - 1]\n .chapterHeading,\n downloadedBook: content[0].chapters,\n chapterContent:\n content[0].chapters[this.state.currentVisibleChapter - 1].verses,\n isLoading: false,\n error: null,\n previousContent: null,\n nextContent: null,\n });\n } else {\n this.setState({\n chapterContent: [],\n unAvailableContent: true,\n isLoading: false,\n });\n }\n }", "async function getPages() {\n const url = '/api/pages';\n const response = await fetch(url);\n const pageFiles = await response.json();\n\n console.log(\"HUB: Page files have been recieved\");\n generateFileList(\"pagesList\", \"delPagesList\", pageFiles);\n}", "getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a query property into a knex `raw` instance.
function queryPropToKnexRaw(queryProp, builder) { if (!queryProp) { return queryProp; } if (queryProp.isObjectionQueryBuilderBase) { return buildObjectionQueryBuilder(queryProp, builder); } else if (isKnexRawConvertable(queryProp)) { return buildKnexRawConvertable(queryProp, builder); } else { return queryProp; } }
[ "function convertExistingQueryProps(json, builder) {\n const keys = Object.keys(json);\n\n for (let i = 0, l = keys.length; i < l; ++i) {\n const key = keys[i];\n const value = json[key];\n\n if (isQueryProp(value)) {\n json[key] = queryPropToKnexRaw(value, builder);\n }\n }\n\n return json;\n}", "toString() {\n var statement = this._statement;\n this._applyHas();\n this._applyLimit();\n\n var parts = {\n fields: statement.data('fields').slice(),\n joins: statement.data('joins').slice(),\n where: statement.data('where').slice(),\n limit: statement.data('limit')\n };\n\n var noFields = !statement.data('fields');\n if (noFields) {\n statement.fields({ [this.alias()]: ['*'] });\n }\n var sql = statement.toString(this._schemas, this._aliases);\n\n for (var name in parts) {\n statement.data(name, parts[name]);\n }\n this._aliasCounter = {};\n this._aliases = {};\n this.alias('', this.schema());\n return sql;\n }", "function generateQuery (type) {\n const query = new rdf.Query()\n const rowVar = kb.variable(keyVariable.slice(1)) // don't pass '?'\n\n addSelectToQuery(query, type)\n addWhereToQuery(query, rowVar, type)\n addColumnsToQuery(query, rowVar, type)\n\n return query\n }", "queryRaw(data, path) {\n path = path || \"/\"; // default path literal key\n if (typeof data !== 'string') {\n data = data.toString('hex');\n }\n return this.client.abciQuery({path, data});\n }", "_query(connection, obj) {\n if (!obj || typeof obj === 'string') obj = {sql: obj}\n return new Promise(function(resolver, rejecter) {\n let { sql } = obj\n if (!sql) return resolver()\n if (obj.options) sql = assign({sql}, obj.options)\n connection.query(sql, obj.bindings, function(err, rows, fields) {\n if (err) return rejecter(err)\n obj.response = [rows, fields]\n resolver(obj)\n })\n })\n }", "get query() {\n return this._parsed.query || {};\n }", "function convertValueToEscapedSqlLiteral (value) {\n if (_.isNumber(value)) {\n return value;\n } else if (value === null) {\n return \"NULL\";\n } else if (_.isBoolean(value)) {\n return value ? \"TRUE\" : \"FALSE\";\n } else if (isDateTimeString(value)) {\n return dateTimeStringToSqlValue(value);\n } else {\n return \"'\" + sanitizeSqlString(value).replace(\"'\", \"''\") + \"'\";\n }\n}", "function getGraphQLValue(value) {\n if (\"string\" === typeof value) {\n value = JSON.stringify(value);\n } else if (Array.isArray(value)) {\n value = value.map(function (item) {\n return getGraphQLValue(item);\n }).join();\n value = \"[\" + value + \"]\";\n } else if (value instanceof Date) {\n value = JSON.stringify(value);\n } else if (value !== null & \"object\" === (typeof value === \"undefined\" ? \"undefined\" : _typeof(value))) {\n /*if (value.toSource)\n value = value.toSource().slice(2,-2);\n else*/\n value = objectToString(value);\n //console.error(\"No toSource!!\",value);\n }\n return value;\n}", "get rawValues() {\n var ret = {};\n Object.keys(propertyInformation).forEach(function (key) {\n ret[key] = _get(key);\n });\n return ret;\n }", "static __query() {\n // Ensure model is registered before creating query\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return a newly constructed DbQuery given `this` and internal DB API\n return new DbQuery(this, this.__db);\n }", "_getQueryBy(callback) {\r\n var query = new Query(); // Create a new instance for nested scope.\r\n callback.call(query, query);\r\n query.sql = query.getSelectSQL();\r\n return query; // Generate SQL statement.\r\n }", "async viewProperty(ctx, propertyId){\r\n\r\n\t\tconst propertyKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.property',[propertyId]);\r\n\t\tlet propertyBuffer = await ctx.stub.getState(propertyKey).catch(err => console.log(err));\r\n\r\n\t\tif(propertyBuffer.length === 0){\r\n\t\t\tthrow new Error(\"Property doesn't exist\");\r\n\t\t}\r\n\r\n\t\tlet propertyObject = JSON.parse(propertyBuffer.toString());\r\n\r\n\t\treturn propertyObject;\r\n\r\n\t }", "function NamedQuery(props) {\n return __assign({ Type: 'AWS::Athena::NamedQuery' }, props);\n }", "async getRecord(path, idProp = \"id\") {\n try {\n const snap = await this.getSnapshot(path);\n let object = snap.val();\n if (typeof object !== \"object\") {\n object = { value: snap.val() };\n }\n return Object.assign(Object.assign({}, object), { [idProp]: snap.key });\n }\n catch (e) {\n throw new AbstractedProxyError(e);\n }\n }", "prepareEntity(entity) {\n if (entity.__prepared) {\n return entity;\n }\n const meta = this.metadata.get(entity.constructor.name);\n const root = Utils_1.Utils.getRootEntity(this.metadata, meta);\n const ret = {};\n if (meta.discriminatorValue) {\n ret[root.discriminatorColumn] = meta.discriminatorValue;\n }\n // copy all props, ignore collections and references, process custom types\n Object.values(meta.properties).forEach(prop => {\n if (this.shouldIgnoreProperty(entity, prop, root)) {\n return;\n }\n if (prop.reference === enums_1.ReferenceType.EMBEDDED) {\n return Object.values(meta.properties).filter(p => { var _a; return ((_a = p.embedded) === null || _a === void 0 ? void 0 : _a[0]) === prop.name; }).forEach(childProp => {\n ret[childProp.name] = entity[prop.name][childProp.embedded[1]];\n });\n }\n if (Utils_1.Utils.isEntity(entity[prop.name], true)) {\n ret[prop.name] = Utils_1.Utils.getPrimaryKeyValues(entity[prop.name], this.metadata.find(prop.type).primaryKeys, true);\n if (prop.customType) {\n return ret[prop.name] = prop.customType.convertToDatabaseValue(ret[prop.name], this.platform);\n }\n return;\n }\n if (prop.customType) {\n return ret[prop.name] = prop.customType.convertToDatabaseValue(entity[prop.name], this.platform);\n }\n if (Array.isArray(entity[prop.name]) || Utils_1.Utils.isObject(entity[prop.name])) {\n return ret[prop.name] = Utils_1.Utils.copy(entity[prop.name]);\n }\n ret[prop.name] = entity[prop.name];\n });\n Object.defineProperty(ret, '__prepared', { value: true });\n return ret;\n }", "function compile(sql) {\n // Text holds the query string.\n var text = '';\n // Values hold the JavaScript values that are represented in the query\n // string by placeholders. They are eager because they were provided before\n // compile time.\n var values = [];\n // When we come accross a symbol in our identifier, we create a unique\n // alias for it that shouldn’t be in the users schema. This helps maintain\n // sanity when constructing large Sql queries with many aliases.\n var nextSymbolId = 0;\n var symbolToIdentifier = new Map();\n for (var _i = 0, _a = Array.isArray(sql) ? sql : [sql]; _i < _a.length; _i++) {\n var item = _a[_i];\n switch (item.type) {\n case 'RAW':\n text += item.text;\n break;\n // TODO: Identifier escaping? I know `pg-promise` does some of this.\n // Most of the time identifiers are trusted, but this could be a source\n // of Sql injection. Replacing double quotes (\") is the minimal\n // implementation.\n case 'IDENTIFIER':\n if (item.names.length === 0)\n throw new Error('Identifier must have a name');\n text += item.names.map(function (name) {\n if (typeof name === 'string')\n return escapeSqlIdentifier(name);\n // Get the correct identifier string for this symbol.\n var identifier = symbolToIdentifier.get(name);\n // If there is no identifier, create one and set it.\n if (!identifier) {\n identifier = \"__local_\" + nextSymbolId++ + \"__\";\n symbolToIdentifier.set(name, identifier);\n }\n // Return the identifier. Since we create it, we won’t have to\n // escape it because we know all of the characters are fine.\n return identifier;\n }).join('.');\n break;\n case 'VALUE':\n values.push(item.value);\n text += \"$\" + values.length;\n break;\n default:\n throw new Error(\"Unexpected Sql item type '\" + item['type'] + \"'.\");\n }\n }\n // Finally, minify our query text.\n text = minify(text);\n return {\n text: text,\n values: values,\n };\n }", "async queryRecord(store, type, query) {\n let upstreamQuery = Ember.assign({}, query);\n upstreamQuery.page = { size: 1 };\n let response = await this._super(store, type, upstreamQuery);\n if (!response.data || !Array.isArray(response.data) || response.data.length < 1) {\n throw new DS.AdapterError([ { code: 404, title: 'Not Found', detail: 'branch-adapter queryRecord got less than one record back' } ]);\n }\n let returnValue = {\n data: response.data[0],\n };\n if (response.meta){\n returnValue.meta = response.meta;\n }\n return returnValue;\n }", "function searchByProperty(queriesObject) {\n const entries = Object.entries(queriesObject);\n if (!entries.find(([, value]) => !!value)) return list();\n\n let whereQuery = \"\";\n for (let i = 0; i < entries.length; i++) {\n const [name, value] = entries[i];\n whereQuery += `${name}::text ilike '%${value}%'`;\n if (i !== entries.length - 1) whereQuery += \" AND \";\n }\n\n return db(tableName)\n .select(\"*\")\n .where(db.raw(whereQuery))\n .orderBy(\"reservation_date\", \"DESC\");\n}", "buildQuerry (query){\n var ecodedQuery = encodeURIComponent(query);\n return ecodedQuery;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }