query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Fonction qui permet de mettre les audio en pause
function pauseAudio() { audioHelp.pause(); audioGood.pause(); audioBad.pause(); audioPlay.pause(); }
[ "function audioPause() {\n\t\t$(\"#audio-player\")[0].pause();\n if(audioInterval != null) {\n window.clearInterval(audioInterval);\n audioInterval = null;\n }\n changeWaveLength();\n //css knoppen\n\t\t$(\"#playbutton\").css(\"display\", \"block\");\n\t\t$(\"#pausebutton\").css(\"display\", \"none\");\n\t\tstatus = 0;\n}", "pause(){\n console.debug(\"Pausing\", this.id);\n this.playing = false;\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if(typeof this.mediaSourceListeners[i].pause === 'function')this.mediaSourceListeners[i].pause(this);\n }\n }", "pauseSong() {\n this.paused = true;\n pauseSpin();\n currAudio.pause();\n }", "pauseMusic() {\n var musicLevel = Math.floor((this.currentLevel + 1) / 2)\n sounds[`level${musicLevel}.mp3`].pause();\n }", "function pauseTrack() {\n if (current_track_id !== null) {\n audioTracks[current_track_id].pause();\n }\n}", "function stopAudio() {\n for (var key in audioSrcList) {\n if (audioSrcList.hasOwnProperty(key)) {\n audioSrcList[key][0].pause();\n audioSrcList[key][0].currentTime = 0;\n }\n }\n}", "function pause(alias) {\n var soundInstance = getSoundByAlias(alias);\n soundInstance.pauseSound();\n }", "function pauseAllSounds() {\n var that = this;\n for (var s in soundsLookup) {\n if (soundsLookup.hasOwnProperty(s)) {\n that.pause(s);\n }\n }\n }", "$mediaplayerPause() {\n this._setState(\"Paused\")\n }", "function pause() {\r\n\t\t\tpauseFunction(countDown, \"pause\");\r\n\t\t}", "function hindiAudio() {\n\n\tif (mute == 0) {\n\t\tmute = 1;\n\t\t$('#muteButton').text('Unmute Audio');\n\t\tresponsiveVoice.cancel();\n\n\t}\n\telse {\n\t\tmute = 0;\n\t\t$('#muteButton').text('Mute Audio');\n\t}\n\n\n\tvar t = Math.round(player.getCurrentTime());\n\twhile (subtitles[subindex].start < t) {\n\t\tsubindex++;\n\t}\n}", "function pause() {\n try {\n\t pl[(arguments[0]-1)].message(\"pause\");\n\t }\n catch(err) {\n post(\"bw.playlister: pause() requires a postive integer between 1 and \" + String(play_num) + \"\\n\");\n } \n}", "function toggleMusicPause() {\n\tif (musicPaused) {\n\t\t// toggle the flag\n\t\tmusicPaused = false;\n\t\t// play the music\n\t\tmusicAudio.play();\n\t\t// debug message\n\t\tif (debugging) {\n\t\t\tconsole.log(\"Playing music.\");\n\t\t}\n\t} else { // toggle the flag\n\t\tmusicPaused = true;\n\t\t// pause the music\n\t\tmusicAudio.pause();\n\t\t// debug message\n\t\tif (debugging) {\n\t\t\tconsole.log(\"Paused music.\");\n\t\t}\n\t}\n}", "function pausing()\n{\n //enableScroll();\n var btn = document.getElementById('playBtn');\n var $audio = document.getElementById('poemAudio');\n $audio.pause();\n btn.src = \"image/play.svg\";\n}", "function privatePause(){\n\t\tconfig.active_song.pause();\n\t\t\n\t\tif( config.active_metadata.live ){\n\t\t\tprivateDisconnectStream();\n\t\t}\n\t}", "function addSongNameClickEvent()\n {\n var song=$('audio');\n if (document.getElementById(\"player\").paused==true){\n song[0].play();\n $('.icon').removeClass('fa fa-play-circle');//chaining\n $(\".icon\").addClass(\"fa fa-pause-circle\");//chaining\n //$(\".fa-pause-circle\").addClass(\"iconshow\");\n console.log(\"changed play\");\n }\n else{\n song[0].pause();\n //$(\".fa-play-circle\").addClass(\"iconshow\");\n $('.icon').removeClass('fa fa-pause-circle')//chaining\n $('.icon').addClass('fa fa-play-circle');//chaining\n console.log(\"changed pause\");\n }\n }", "playPauseAndUpdate(song = player.currentlyPlaying) {\n player.playPause(song);\n $('#time-control .total-time').text( player.getDuration );\n }", "function playsound() {\r\n audio1.play();\r\n }", "function stopMusic() {\n music_audio.play();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds some more CSS and tries to center both front and back in the container
function _addCssPositioning(options) { for (const card of options.domObjects.cardList) { // Set container relative card.container.style.position = "relative"; // Get dimensions from front/back let frontBounds = card.front.getBoundingClientRect(); let backBounds = card.back.getBoundingClientRect(); // Check max width/height and set container accordingly let width = Math.max(frontBounds.width, backBounds.width); let height = Math.max(frontBounds.height, backBounds.height); card.container.style.width = width + "px"; card.container.style.height = height + "px"; // Position front and back in container card.front.style.position = "absolute"; card.front.style.top = "50%"; card.front.style.left = "50%"; card.front.style.transformOrigin = "left center"; Helper.updateTransformProperty(card.front, "translate(-50%, -50%)"); card.back.style.position = "absolute"; card.back.style.top = "50%"; card.back.style.left = "50%"; card.back.style.transformOrigin = "left center"; Helper.updateTransformProperty(card.back, "translate(-50%, -50%)"); } }
[ "center() {\n if (this._fromFront) {\n this._updatePositionAndTarget(this._front, this._back);\n } else {\n this._updatePositionAndTarget(this._back, this._front);\n }\n\n this._updateMatrices();\n this._updateDirections();\n }", "function centerField() {\n $(\"#container\").css(\"width\", $(\"#container\").width()*1.1); // prevents shifting of container when text size changes.\n $(\"#container\").css(\"margin-left\", -$(\"#container\").width()/2);\n $(\"#container\").css(\"margin-top\", -$(\"#container\").height()/2);\n }", "function centerContent() {\r\n $('.container').css({\r\n position:'absolute',\r\n left: ($(window).width() - $('.container').outerWidth())/2,\r\n top: ($(window).height() - $('.container').outerHeight())/2\r\n });\r\n }", "centerInParent() {\n this._x = (100 - this._width) / 2;\n this._y = (100 - this._height) / 2;\n }", "function PopUp_Center() {\n if (_popUp) {\n _popUp.css({ \"left\": ($(\"html\").outerWidth() / 2) - (_popUp.outerWidth() / 2), \"top\": ($(\"html\").outerHeight() / 2) - (_popUp.outerHeight() / 2) });\n }\n\n return false;\n }", "static center(scene, camera, controls, axis, caf, inverse) {\n let BbMaxx = -Infinity;\n let BbMaxy = -Infinity;\n let BbMaxz = -Infinity;\n let BbMinx = Infinity;\n let BbMiny = Infinity;\n let BbMinz = Infinity;\n for (let i = 0; i < scene.children.length; i++) {\n if (scene.children[i] instanceof Camera ||\n scene.children[i] instanceof Light)\n continue;\n let bhelper = new BoxHelper(scene.children[i], 0xff0000);\n bhelper.geometry.computeBoundingBox();\n let WRSmin = bhelper.localToWorld(bhelper.geometry.boundingBox.min);\n let WRSmax = bhelper.localToWorld(bhelper.geometry.boundingBox.max);\n if (WRSmin.x < BbMinx) {\n BbMinx = WRSmin.x;\n }\n if (WRSmin.y < BbMiny) {\n BbMiny = WRSmin.y;\n }\n if (WRSmin.z < BbMinz) {\n BbMinz = WRSmin.z;\n }\n if (WRSmax.x > BbMaxx) {\n BbMaxx = WRSmax.x;\n }\n if (WRSmax.y > BbMaxy) {\n BbMaxy = WRSmax.y;\n }\n if (WRSmax.z > BbMaxz) {\n BbMaxz = WRSmax.z;\n }\n }\n if (BbMinx === Infinity) {\n BbMaxx = -10;\n BbMaxy = -10;\n BbMaxz = -10;\n BbMinx = 10;\n BbMiny = 10;\n BbMinz = 10;\n }\n\n var length = new Vector3(BbMaxx - BbMinx,\n BbMaxy - BbMiny,\n BbMaxz - BbMinz);\n\n var center = new Vector3(BbMinx + (length.x / 2),\n BbMiny + (length.y / 2),\n BbMinz + (length.z / 2));\n\n if (camera.type === CAMERA_TYPE.OrthographicCamera) {\n\n let lengthX = 0;\n let lengthY = 0;\n switch (axis) {\n case 0:\n lengthX = length.z;\n lengthY = length.y;\n break;\n case 1:\n lengthX = length.z;\n lengthY = length.x;\n break;\n case 2:\n lengthX = length.x;\n lengthY = length.y;\n break;\n default:\n break;\n }\n let aspectWidth = window.innerWidth / lengthX;\n let aspectHeight = window.innerHeight / lengthY;\n let maxIsWidth = aspectWidth < aspectHeight;\n if (!maxIsWidth) {\n let aspect = window.innerWidth / window.innerHeight;\n camera.left = lengthY * aspect * caf / -2;\n camera.right = lengthY * aspect * caf / 2;\n camera.top = lengthY * caf / 2;\n camera.bottom = lengthY * caf / -2;\n camera.position.set(0, 0, 0).setComponent(axis, center.getComponent(axis) + (lengthY * caf * inverse));\n\n } else {\n let aspect = window.innerHeight / window.innerWidth;\n camera.left = lengthX * caf / -2;\n camera.right = lengthX * caf / 2;\n camera.top = lengthX * aspect * caf / 2;\n camera.bottom = lengthX * aspect * caf / -2;\n camera.position.set(0, 0, 0).setComponent(axis, center.getComponent(axis) + (lengthX * caf * inverse));\n }\n\n\n } else {\n var maxLenght = Math.max(length.x, length.z);\n let dist = (maxLenght * caf) / 2 / Math.tan(Math.PI * camera.fov / 360);\n camera.position.set(center.x, center.y, center.z + (maxLenght * caf));\n if (controls) {\n controls.target = new Vector3(0, center.y, 0);\n }\n }\n camera.updateProjectionMatrix();\n }", "function center( $item ) {\n\t\t$item.css({\n\t\t\tleft: ( winWidth() - $item.width() ) / 2,\n\t\t\ttop: ( winHeight() - $item.height() ) / 2\n\t\t});\n\t}", "function setSelfPosition() {\r\n var s = $self[0].style;\r\n\r\n // reset CSS so width is re-calculated for margin-left CSS\r\n $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1, zIndex: (opts.zIndex + 3) });\r\n\r\n\r\n /* we have to get a little fancy when dealing with height, because lightbox_me\r\n is just so fancy.\r\n */\r\n\r\n // if the height of $self is bigger than the window and self isn't already position absolute\r\n if (($self.height() + 80 >= $(window).height()) && ($self.css('position') != 'absolute')) {\r\n\r\n // we are going to make it positioned where the user can see it, but they can still scroll\r\n // so the top offset is based on the user's scroll position.\r\n var topOffset = $(document).scrollTop() + 40;\r\n $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})\r\n } else if ($self.height()+ 80 < $(window).height()) {\r\n //if the height is less than the window height, then we're gonna make this thing position: fixed.\r\n if (opts.centered) {\r\n $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})\r\n } else {\r\n $self.css({ position: 'fixed'}).css(opts.modalCSS);\r\n }\r\n if (opts.preventScroll) {\r\n $('body').css('overflow', 'hidden');\r\n }\r\n }\r\n }", "static Center(value1, value2) {\n const center = Vector3.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }", "function setContainer() {\n zwiperContainer = document.getElementsByClassName(zwiperSettings.container)[0];\n zwiperContainer.style.overflow = 'hidden';\n zwiperContainer.style.position = 'relative';\n }", "refreshCenter()\n {\n let { x, y } = this.editing == \"start\"? { x: this.rect.x1, y: this.rect.y1 }: { x: this.rect.x2, y: this.rect.y2 };\n x *= this.width;\n y *= this.height;\n this._handle.querySelector(\".crosshair\").setAttribute(\"transform\", `translate(${x} ${y})`);\n }", "function inclButtonCenter(spec) {\n /******************\n * parent function\n */\n var that = inclHideButton(spec);\n\n that.buttonVerticalCenter = function () {\n that._next.css('top', that.currentHeight / 2 - (that._next.height() / 2));\n that._prev.css('top', that.currentHeight / 2 - (that._prev.height() / 2));\n };\n\n return that;\n\n }", "reCenter(clipSize) {\n let [groupWidth, groupHeight] = this._actor.get_size();\n let leftLength = this._horizLeftHair.get_width();\n let topLength = this._vertTopHair.get_height();\n let thickness = this._horizLeftHair.get_height();\n\n // Deal with clip rectangle.\n if (clipSize)\n this._clipSize = clipSize;\n let clipWidth = this._clipSize[0];\n let clipHeight = this._clipSize[1];\n\n // Note that clip, if present, is not centred on the cross hair\n // intersection, but biased towards the top left.\n let left = groupWidth / 2 - clipWidth * 0.25 - leftLength;\n let right = groupWidth / 2 + clipWidth * 0.75;\n let top = groupHeight / 2 - clipHeight * 0.25 - topLength - thickness / 2;\n let bottom = groupHeight / 2 + clipHeight * 0.75 + thickness / 2;\n this._horizLeftHair.set_position(left, (groupHeight - thickness) / 2);\n this._horizRightHair.set_position(right, (groupHeight - thickness) / 2);\n this._vertTopHair.set_position((groupWidth - thickness) / 2, top);\n this._vertBottomHair.set_position((groupWidth - thickness) / 2, bottom);\n }", "function centerTextInNavs(){\r\n\t\twelcomeNavCentering = ((($(\"#header-text\").height() - 50) - ($(\"#welcome\").height() + $(\"#welcome-text\").height() - 10)) / 2);\r\n\t\taboutNavCentering = ((($(\"#about-section\").height() - 50) - ($(\"#about\").height() + $(\"#about-text\").height() - 10)) / 2);\r\n\t\tcontactNavCentering = ((($(\"#contact-section\").height() - 50) - ($(\"#contact\").height() + $(\"#contact-text\").height() - 10)) / 2);\r\n\r\n\t\t$(\"#welcome\").css({\r\n\t\t\t\t\"padding-top\": welcomeNavCentering + \"px\",\r\n\t\t\t\t\"font-size\": \"200%\"\r\n\t\t});\r\n\t\t\t$(\"#about\").css({\r\n\t\t\t\t\"padding-top\": aboutNavCentering + \"px\",\r\n\t\t\t\t\"font-size\": \"200%\"\r\n\t\t});\r\n\t\t\t$(\"#contact\").css({\r\n\t\t\t\t\"padding-top\": contactNavCentering + \"px\",\r\n\t\t\t\t\"font-size\": \"200%\"\r\n\t\t});\r\n\t}", "static Center(value1, value2) {\n const center = Vector2.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }", "static Center(value1, value2) {\n const center = Vector4.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }", "function PositionButtons(nContainerWidth, nContainerHeight, bFullScreen)\n{\n var nTotalMaxGaps1 = 0;\n var nTotalMinGaps1 = 0;\n var nTotalButtonWidth1 = 0;\n\n for (i=0; i<g_nButtonsOnRow1; i++)\n {\n nIndex = g_FlexLayoutRow1[i][0];\n nTotalButtonWidth1 += bFullScreen?g_nButPosFull[nIndex][2]:g_nButPos[nIndex][2];\n nTotalMinGaps1 += g_FlexLayoutRow1[i][1];\n nTotalMaxGaps1 += g_FlexLayoutRow1[i][2];\n }\n\n var nTotalMinGaps2 = 0;\n var nTotalMaxGaps2 = 0;\n var nTotalButtonWidth2 = 0;\n\n for (i=0; i<g_nButtonsOnRow2; i++)\n {\n nIndex = g_FlexLayoutRow2[i][0];\n nTotalButtonWidth2 += bFullScreen?g_nButPosFull[nIndex][2]:g_nButPos[nIndex][2];\n nTotalMinGaps2 += g_FlexLayoutRow2[i][1];\n nTotalMaxGaps2 += g_FlexLayoutRow2[i][2];\n }\n\n // the control area includes the buttons and the spaces in between,\n // but not include the margin of the container on the two sides.\n\n // the maximum control area width is pre-defined, but it should not be\n // wider than the maximum stretched size of the control area\n\n var nMaxControlAreaWidth = Math.min(nTotalButtonWidth1 + nTotalMaxGaps1,\n nTotalButtonWidth2 + nTotalMaxGaps2);\n\n if (nMaxControlAreaWidth > g_nMaxControlAreaWidth)\n {\n nMaxControlAreaWidth > g_nMaxControlAreaWidth;\n }\n\n // the minimum control area width is pre-defined, but it should not be\n // narrower than the minimum compressed size of the control area\n\n var nMinControlAreaWidth = Math.max(nTotalButtonWidth1 + nTotalMinGaps1,\n nTotalButtonWidth2 + nTotalMinGaps2);\n\n if (nMinControlAreaWidth < g_nMaxControlAreaWidth)\n {\n nMinControlAreaWidth = g_nMinControlAreaWidth;\n }\n\n var nMargin = g_nMinMargin;\n var nControlAreaWidth = nContainerWidth - nMargin*2;\n\n if (nControlAreaWidth < nMinControlAreaWidth)\n {\n // not enough room for control area, we will keep the default margin on\n // the left side as well as the control spacing, but allow the controls \n // to go beyond the right-side edge\n\n nControlAreaWidth = nMinControlAreaWidth;\n }\n else if(nControlAreaWidth > nMaxControlAreaWidth)\n {\n // two much room for the control area, we will fix the control spacing\n // at the maximum, but make the margin wider\n\n nControlAreaWidth = nMaxControlAreaWidth;\n nMargin = (nContainerWidth - nControlAreaWidth)/2;\n }\n\n // the control area width is within the flexible range of spacing,\n // we will distribute the space between the controls.\n // first row\n\n var nVariableWidth = nControlAreaWidth - nTotalButtonWidth1 - nTotalMinGaps1;\n var nTotalDelta = nTotalMaxGaps1 - nTotalMinGaps1;\n var xOffset = nMargin;\n\n for (i=0; i<g_nButtonsOnRow1; i++)\n {\n nDelta = g_FlexLayoutRow1[i][2] - g_FlexLayoutRow1[i][1];\n nGap = g_FlexLayoutRow1[i][1] + Math.round(nVariableWidth*nDelta*1.0/nTotalDelta);\n xOffset += nGap; // advance by the gap width in front of control\n\n nIndex = g_FlexLayoutRow1[i][0];\n g_nButPos[nIndex][0] = xOffset;\n xOffset += bFullScreen?g_nButPosFull[nIndex][2]:g_nButPos[nIndex][2]; // advance by the control width\n }\n\n // same thing for second row\n\n nVariableWidth = nControlAreaWidth - nTotalButtonWidth2 - nTotalMinGaps2;\n nTotalDelta = nTotalMaxGaps2 - nTotalMinGaps2;\n xOffset = nMargin;\n\n for (i=0; i<g_nButtonsOnRow2; i++)\n {\n nDelta = g_FlexLayoutRow2[i][2] - g_FlexLayoutRow2[i][1];\n nGap = g_FlexLayoutRow2[i][1] + Math.round(nVariableWidth*nDelta*1.0/nTotalDelta);\n xOffset += nGap; // advance by the gap width in front of control\n\n nIndex = g_FlexLayoutRow2[i][0];\n g_nButPos[nIndex][0] = xOffset;\n xOffset += bFullScreen?g_nButPosFull[nIndex][2]:g_nButPos[nIndex][2]; // advance by the control width\n }\n\n // move other overlaping controls\n\n g_nButPos[g_nIndexStop][0] = g_nButPos[g_nIndexPause][0];\n g_nButPos[g_nIndexDiCC][0] = g_nButPos[g_nIndexEnCC][0];\n g_nButPos[g_nIndexResume][0] = g_nButPos[g_nIndexMenu][0];\n g_nButPos[g_nIndexUp][0] = g_nButPos[g_nIndexEnter][0];\n g_nButPos[g_nIndexDown][0] = g_nButPos[g_nIndexEnter][0];\n g_nButPos[g_nIndexShrink][0] = g_nButPos[g_nIndexExpand][0];\n g_nButPos[g_nIndexSound][0] = g_nButPos[g_nIndexMute][0];\n}", "function setMixInformationPosition(){\n informationMix.infromationMixPosition = $(\".container-fruits\").offset().left;\n informationMix.infromationMixWidth = $(\".information-mix\").width();\n\n strawLeft.documentWidth = $(window).width();\n strawLeft.glassPosition = $(\".glass\").offset().left;\n strawLeft.glassWidth = $(\".glass\").width();\n\n strawLeft.strawLeftPosition = strawLeft.documentWidth - parseInt(strawLeft.glassPosition) + strawLeft.glassWidth;\n $(\".straw\").css(\"left\", strawLeft.strawLeftPosition);\n informationMix.infromationMixLeft = informationMix.infromationMixPosition + parseInt(informationMix.infromationMixWidth);\n $(\".container-fruits\").find('.information-mix').css(\"left\", -informationMix.infromationMixLeft);\n }", "function centerImage() {\n let container = document.getElementById(\"sliderImages\");\n const containerHeight = parseInt(window.getComputedStyle(container,null).getPropertyValue(\"height\"), 10);\n const topPos = (imageContainer.height - containerHeight)/2;\n if(topPos > 0) {\n imageContainer.style.top = `-${topPos}px`;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prettierignore Validates block range
function validateBlockNumbers(fromBlock, toBlock, currentBlock) { if (fromBlock > currentBlock || fromBlock < 0) { throw new Error('Invalid fromBlock. It must be less than the currentBlock || it cannot be negative'); } if (fromBlock > toBlock) { throw new Error('Invalid blockRange. fromBlock must be less than toBlock'); } if (toBlock > currentBlock) { throw new Error('Invalid toBlock. It must be less than or equal to the currentblock'); } }
[ "changedRange(blockToCompare) {\n let startIndex = 0;\n let differencesFound = false;\n while (startIndex < this.tokens.length &&\n startIndex < blockToCompare.tokens.length) {\n if (!this.tokens[startIndex].contentEquals(\n blockToCompare.tokens[startIndex])) {\n differencesFound = true;\n break;\n }\n ++startIndex;\n }\n if (!differencesFound) {\n if (this.tokens.length !== blockToCompare.tokens.length) {\n return [startIndex, this.tokens.length,\n startIndex, blockToCompare.tokens.length];\n }\n return null;\n }\n let endOffset = 0;\n while (this.tokens[this.tokens.length - endOffset - 1].contentEquals(\n blockToCompare.tokens[blockToCompare.tokens.length - endOffset - 1])) {\n if (endOffset === this.tokens.length - 1 ||\n endOffset === blockToCompare.tokens.length - 1) {\n break;\n }\n ++endOffset;\n }\n if (this.tokens.length - endOffset <= startIndex ||\n blockToCompare.tokens.length - endOffset <= startIndex) {\n endOffset = Math.min(this.tokens.length - startIndex - 1,\n blockToCompare.tokens.length - startIndex - 1);\n }\n return [startIndex, this.tokens.length - endOffset,\n startIndex, blockToCompare.tokens.length - endOffset];\n }", "function produceDrivingRange(blockRange) {\n return function blockRangeCalculator(firstBlock, secondBlock) {\n let blockDifference = parseInt(secondBlock) - parseInt(firstBlock);\n if ( blockDifference > blockRange ) {\n var rangeDifference = blockDifference - blockRange\n return `${rangeDifference} blocks out of range`\n } else {\n var rangeDifference = blockDifference - blockRange\n return `within range by ${blockDifference}`;\n }\n }\n}", "function produceDrivingRange(blockRange) {\n return function(startBlock, endBlock) {\n const start = parseInt(startBlock);\n const end = parseInt(endBlock);\n let result;\n start > end ? result = Math.abs(start - end) : result = Math.abs(end - start);\n let difference;\n if (result > blockRange) {\n difference = Math.abs(result - blockRange);\n return `${difference} blocks out of range`;\n } else {\n difference = Math.abs(blockRange - result);\n return `within range by ${difference}`;\n };\n };\n}", "range(start, end) {\n return new vscode.Range(start, end);\n }", "inRangeIdea (num, start, end) {\n let startRange\n let endRange\n if (!end) {\n startRange = 0\n endRange = start\n } else if (start > end) {\n startRange = end\n endRange = start\n } else {\n startRange = start\n endRange = end\n }\n return this.checkRangeIdea(num, startRange, endRange)\n }", "function Range() {\n\tthis.minCells = 2 // Can operate on a minimum of 2 cells\n\tthis.maxCells = 4 // Can operate on a maximum of 4 cells\n\tthis.symbol = 'range'\n}", "function range(event, from, to) {\n result = allowChars('0-9');\n if (result)\n return (event.currentTarget.value >= from && event.currentTarget.value <= to);\n else\n return result;\n}", "function versionIsRange(version) {\n return version.includes('-');\n}", "isRangeCommented(state, range) {\n let textBefore = state.sliceDoc(range.from - SearchMargin, range.from);\n let textAfter = state.sliceDoc(range.to, range.to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - this.open.length, beforeOff) == this.open &&\n textAfter.slice(spaceAfter, spaceAfter + this.close.length) == this.close) {\n return { open: { pos: range.from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: range.to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (range.to - range.from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(range.from, range.to);\n }\n else {\n startText = state.sliceDoc(range.from, range.from + SearchMargin);\n endText = state.sliceDoc(range.to - SearchMargin, range.to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - this.close.length;\n if (startText.slice(startSpace, startSpace + this.open.length) == this.open &&\n endText.slice(endOff, endOff + this.close.length) == this.close) {\n return { open: { pos: range.from + startSpace + this.open.length,\n margin: /\\s/.test(startText.charAt(startSpace + this.open.length)) ? 1 : 0 },\n close: { pos: range.to - endSpace - this.close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n }", "_validateYRange() {\n return this.currentYRange[1] >= this.currentYRange[0];\n }", "isRangeCommented(state, range) {\n let textBefore = state.sliceDoc(range.from - SearchMargin, range.from);\n let textAfter = state.sliceDoc(range.to, range.to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - this.open.length, beforeOff) == this.open &&\n textAfter.slice(spaceAfter, spaceAfter + this.close.length) == this.close) {\n return { open: { pos: range.from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: range.to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (range.to - range.from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(range.from, range.to);\n }\n else {\n startText = state.sliceDoc(range.from, range.from + SearchMargin);\n endText = state.sliceDoc(range.to - SearchMargin, range.to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - this.close.length;\n if (startText.slice(startSpace, startSpace + this.open.length) == this.open &&\n endText.slice(endOff, endOff + this.close.length) == this.close) {\n return { open: { pos: range.from + startSpace + this.open.length,\n margin: /\\s/.test(startText.charAt(startSpace + this.open.length)) ? 1 : 0 },\n close: { pos: range.to - endSpace - this.close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n }", "*positions(editor) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n at = editor.selection,\n unit = 'offset',\n reverse: reverse$1 = false\n } = options;\n\n if (!at) {\n return;\n }\n\n var range = Editor.range(editor, at);\n var [start, end] = Range.edges(range);\n var first = reverse$1 ? end : start;\n var string = '';\n var available = 0;\n var offset = 0;\n var distance = null;\n var isNewBlock = false;\n\n var advance = () => {\n if (distance == null) {\n if (unit === 'character') {\n distance = getCharacterDistance(string);\n } else if (unit === 'word') {\n distance = getWordDistance(string);\n } else if (unit === 'line' || unit === 'block') {\n distance = string.length;\n } else {\n distance = 1;\n }\n\n string = string.slice(distance);\n } // Add or substract the offset.\n\n\n offset = reverse$1 ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.\n\n available = available - distance; // If the available had room to spare, reset the distance so that it will\n // advance again next time. Otherwise, set it to the overflow amount.\n\n distance = available >= 0 ? null : 0 - available;\n };\n\n for (var [node, path] of Editor.nodes(editor, {\n at,\n reverse: reverse$1\n })) {\n if (Element.isElement(node)) {\n // Void nodes are a special case, since we don't want to iterate over\n // their content. We instead always just yield their first point.\n if (editor.isVoid(node)) {\n yield Editor.start(editor, path);\n continue;\n }\n\n if (editor.isInline(node)) {\n continue;\n }\n\n if (Editor.hasInlines(editor, node)) {\n var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);\n var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);\n var text = Editor.string(editor, {\n anchor: s,\n focus: e\n });\n string = reverse$1 ? esrever.reverse(text) : text;\n isNewBlock = true;\n }\n }\n\n if (Text.isText(node)) {\n var isFirst = Path.equals(path, first.path);\n available = node.text.length;\n offset = reverse$1 ? available : 0;\n\n if (isFirst) {\n available = reverse$1 ? first.offset : available - first.offset;\n offset = first.offset;\n }\n\n if (isFirst || isNewBlock || unit === 'offset') {\n yield {\n path,\n offset\n };\n }\n\n while (true) {\n // If there's no more string, continue to the next block.\n if (string === '') {\n break;\n } else {\n advance();\n } // If the available space hasn't overflow, we have another point to\n // yield in the current text node.\n\n\n if (available >= 0) {\n yield {\n path,\n offset\n };\n } else {\n break;\n }\n }\n\n isNewBlock = false;\n }\n }\n }", "function createRangeDescription() {\n if((!dual || single) && incrementTop === 1) {\n return `(range: ${topStart} to ${topEnd})`;\n } else if((!dual || single) && incrementTop !== 1) {\n return `(range: ${topStart} to ${topEnd}(step ${incrementTop}))`;\n } else if((topStart === bottomStart && topEnd === bottomEnd)) {\n return `(range: ${topStart} to ${topEnd}(top step ${incrementTop}, bottom step ${incrementBottom}))`;\n } else if(incrementTop === incrementBottom && (incrementTop !== 1 || incrementBottom !== 1)) {\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementTop}))`;\n } else if(incrementTop === incrementBottom){\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom))`;\n } else {\n return `(ranges: ${topStart} to ${topEnd}(top) (step ${incrementTop}) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementBottom}))`;\n }\n }", "static replace(spec) {\n let block = !!spec.block;\n let { start, end } = getInclusive(spec);\n let startSide = block ? -200000000 /* BigBlock */ * (start ? 2 : 1) : 100000000 /* BigInline */ * (start ? -1 : 1);\n let endSide = block ? 200000000 /* BigBlock */ * (end ? 2 : 1) : 100000000 /* BigInline */ * (end ? 1 : -1);\n return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);\n }", "function CheckBadNumberRange(str, min, max, defMsg, msg, isQuite)\n{\n var result = false;\n var num = parseInt(str);\n if (!((num >= min && num <= max) && (IsNumeric(str))))\n {\n if (isQuite != true)\n {\n if (msg == null)\n {\n alert(GL(\"verr_bad_num\",\n { 1 : defMsg, 2 : min, 3 : max }));\n }\n else\n {\n alert(msg);\n }\n }\n result = true;\n }\n return result;\n}", "function rangeAdjust (luckySign, luckModifier) {\n var adjust = 0;\n if (luckySign.luckySign != undefined && (luckySign.luckySign === \"Harsh winter\" || luckySign.luckySign === \"Fortunate date\")){\n adjust = luckModifier;\n }\n\treturn adjust;\n}", "static validateReadingGreaterThanOrEqualLowerRange(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //Lower range value exists\n if (libThis.evalIsLowerRange(dict) && !libThis.evalLowerRangeIsEmpty(dict)) {\n //New reading >= lower range\n if (libThis.evalReadingGreaterThanEqualToLowerRange(pageClientAPI, dict)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [dict.LowerRange];\n let messageText = pageClientAPI.localizeText('validation_reading_below_lower_range_of',dynamicParams);\n let captionText = pageClientAPI.localizeText('validation_warning_x', [dict.Point]);\n let okButtonText = pageClientAPI.localizeText('continue_text');\n let cancelButtonText = pageClientAPI.localizeText('cancel');\n\n return libCom.showWarningDialog(pageClientAPI, messageText, captionText, okButtonText, cancelButtonText);\n }\n }\n return Promise.resolve(false);\n }", "function parseRange(range)\n {\n let parts = range.split(\"=\");\n if (parts[0] === \"bytes\")\n {\n parts = parts[1].split(\"-\");\n return [parseInt(parts[0], 10), parseInt(parts[1] || \"-1\", 10)];\n }\n else\n {\n return [];\n }\n }", "function range_ques_(exception_info) /* (exception-info : exception-info) -> bool */ {\n return (exception_info._tag === _tag_Range);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return available lang files as options with selected one
DropdownOptionsLANG() { let html = ''; let sel = ''; let fileListData = spx.getJSONFileList('./locales/'); fileListData.files.forEach((element,i) => { sel = ''; if (element.name == config.general.langfile) { sel = 'selected'; } html += '<option value="' + element.name + '" ' + sel + '>' + element.name.replace('.json', '') + '</option>'; }); return html }
[ "function availableLanguage (site) {\n // Read the language files available\n var locales = fs.readdirSync(__dirname + '/../sites/' + site + '/locales');\n var html = '';\n // See all file and create the html\n for (var i = 0; i < locales.length; i++) {\n html += '<li><a href=\"/locales/' + locales[i].split('.')[0] + '\">' + locales[i].split('.')[0] + '</a></li>';\n } \n return html;\n}", "function GenerateOptionsandList() {\n var optn = '';\n var li = '';\n try {\n if (MasterPlainLanguages.length > 0) {\n for (var i = 0; i < MasterPlainLanguages.length; i++) {\n optn = optn + '<option value=\"' + MasterPlainLanguages[i].PlainLanguageName + '\">' + MasterPlainLanguages[i].PlainLanguageName + '</option>';\n li = li + '<li class=\"list-group-item\"><a>' + MasterPlainLanguages[i].PlainLanguageName + '</a></li>';\n }\n } else {\n throw \"Plain Languages Not Available\";\n }\n } catch (err) {\n console.log(err);\n }\n $(\"#selectplainlang\").append(optn);\n $('.plainlanglist').append(li);\n $(\"#selectplainlang\").customselect();\n return;\n }", "function getLang(){\n fetch(\"https://api.cognitive.microsofttranslator.com/languages?api-version=3.0\", {\n method: \"GET\",\n })\n.then((response) => {\n return response.json();\n})\n.then((response) => {\n var languages = response.translation\n for(var prop in languages){\n var createOption = document.createElement('option');\n\n createOption.textContent = languages[prop].name\n createOption.setAttribute(\"id\", prop)\n \n dropDown.appendChild(createOption);\n };\n }\n)\n.catch((err) => {\n console.error(err);\n});\n}", "function createLangs() {\n var languages = [];\n /*Get languages from checkboxes */\n var github_request = document.getElementById('github_request');\n var i;\n for (i = 0; i < github_request.lang.length; i++) {\n if (github_request.lang[i].checked) {\n languages.push(github_request.lang[i].value);\n }\n }\n return languages;\n}", "function handleLangSelect ( event ) {\r\n\t\t\r\n\t\t// prevent going to #\r\n\t\tevent.preventDefault()\r\n\r\n\t\tlet selectElement = event.srcElement\r\n\t\t// to be shown as placeholder\r\n\t\tlet buttonElement = selectElement.parentElement.previousElementSibling\r\n\t\t// element in with data to be saved of selected language\r\n\t\tlet dataElement = buttonElement.parentElement\r\n\r\n\t\t// save the selected info\r\n\t\tlet selectedInfo = {\r\n\t\t\tvalue: selectElement.getAttribute(\"data-val\"),\r\n\t\t\ttext: selectElement.innerHTML\r\n\t\t}\r\n\r\n\t\t// toogle data b/w selected element and \r\n\t\t// placeholder element\r\n\t\tselectElement.innerHTML = buttonElement.innerHTML\r\n\t\tselectElement.setAttribute(\"data-val\", dataElement.getAttribute(\"data-val\"))\r\n\t\tdataElement.setAttribute(\"data-val\", selectedInfo.value)\r\n\t\tbuttonElement.innerHTML = selectedInfo.text\r\n\t\t\r\n\t\tif ( DEBUG.Log ) {\r\n\t\t\tconsole.log(event)\r\n\t\t}\r\n\t}", "function setLangByUrl() {\n var url = document.URL;\n var id = url.substring(url.lastIndexOf('#') + 1);\n getLang(id);\n\n // update #lang-select based on url segment\n var rightOption = \"lang-\" + id;\n $(\"#lang-select option\").filter(function(){\n return this.id == rightOption;\n }).prop('selected', true);\n}", "function fetchOptions() {\n\n var urlList = ['assets/word_list_pt.txt', 'assets/word_list_se.txt', 'assets/word_list_fr.txt', 'assets/word_list_de.txt'];\n var url = 0;\n\n if (mode === \"Portuguese\") {\n url = urlList[0];\n } else if (mode === \"Swedish\") {\n url = urlList[1];\n } else if (mode === \"French\") {\n url = urlList[2];\n } else if (mode === \"German\") {\n url = urlList[3];\n } else if (mode === \"Random\") {\n url = urlList[numr2];\n }\n\n return fetch(url)\n .then(response => response.text().then(text => text.split(\"\\n\")))\n .then(data => {\n word1 = data[num1];\n word2 = data[num2];\n word3 = data[num3];\n word4 = data[num4];\n\n document.getElementById(\"option1\").innerHTML = word1;\n document.getElementById(\"option2\").innerHTML = word2;\n document.getElementById(\"option3\").innerHTML = word3;\n document.getElementById(\"option4\").innerHTML = word4;\n });\n}", "function loadOptionsFromStorage() {\n chrome.storage.sync.get([\n 'yiiShortcut',\n 'yiiDocsVersion',\n 'laravelShortcut',\n 'laravelDocsVersion'\n ], function (props) {\n var data = Object.assign({}, defaultOptions, props || {});\n\n yiiShortcutSelect.value = data.yiiShortcut;\n laravelShortcutSelect.value = data.laravelShortcut;\n laravelDocsVersionSelect.value = data.laravelDocsVersion;\n });\n }", "async getInstalledLanguages() {\n const results = await SPCollection(this, \"installedlanguages\")();\n return results.Items;\n }", "function getLanguageTypes() {\n personLanguageProficiencyLogic.getLanguageTypes().then(function (response) {\n $scope.languageList = response;\n }, function (err) {\n appLogger.log(err);\n appLogger.error('ERR', err);\n\n });\n\n }", "function setDomainOpts(){\r\n\tvar split1 = location.href.split('ikariam.');\r\n\tvar split2 = split1[1].split('/');\r\n\tvar ext = split2[0];\r\n\tvar opts = new Array();\r\n\topts['ext'] = ext;\r\n\tif ( ext == 'fr' ){\r\n\t\topts['lvl'] = ' Niveau';\r\n\t\topts['inactives'] = 'Inactifs';\t\r\n\t}\r\n\telse if ( ext == 'de' ){\r\n\t\topts['lvl'] = ' Stufe';\r\n\t\topts['inactives'] = 'Inaktívak';\t\r\n\t}\r\n\telse if ( ext == 'com' ){\r\n\t\topts['lvl'] = ' Level';\t\r\n\t\topts['inactives'] = 'Inaltívak';\r\n\t}\r\n\telse if ( ext == 'es' ){\r\n\t\topts['lvl'] = ' Nivel';\r\n\t\topts['inactives'] = 'Inaktívak';\r\n\t}\r\n\telse if ( ext == 'gr' ){\r\n\t\topts['lvl'] = 'ÎľĎ�ÎŻĎ�ξδο';\r\n\t\topts['inactives'] = 'Inactives';\r\n\t}\r\n\telse if ( ext == 'hu' ){\r\n\t\topts['lvl'] = 'ÎľĎ�ÎŻĎ�ξδο';\r\n\t\topts['inactives'] = 'Inaktívak';\r\n\t}\r\n\telse {\r\n\t\topts['lvl'] = ' Level';\t\r\n\t\topts['inactives'] = 'Inactives';\t\r\n\t}\t\t\r\n\treturn opts;\r\n}", "function languageISO(list, name){\n\tvar result= list.find(language => language.name ===name);\n\tif (typeof result === \"undefined\"){return \"\"}else{return result[\"1\"]};\n}", "_renderSelectedLanguage(tmp = false) {\n Array.from(\n this._parentElement.querySelectorAll('.window .body button')\n ).forEach(\n languageButton => {\n if (\n tmp && languageButton.dataset.languageAcronym === this._tmpSelectedLanguage ||\n !tmp && languageButton.dataset.languageAcronym === helpers.getSelectedItem(this._data).acronym\n ) {\n languageButton.classList.add('selected');\n } else {\n languageButton.classList.remove('selected');\n }\n }\n );\n }", "selectedList(state) {\n const selectedDirectories = state.directories.filter((directory) =>\n state.selected.directories.includes(directory.path)\n );\n\n const selectedFiles = state.files.filter((file) => state.selected.files.includes(file.path));\n\n return selectedDirectories.concat(selectedFiles);\n }", "function generateProgramList(selectedName) {\n removeAllChildren(loadSelector);\n\n var option=document.createElement(\"option\");\n if (selectedName==\"\") {\n\toption.selected=true;\n }\n loadSelector.appendChild(option);\n for (i=0;i<window.localStorage.length;i++) {\n\tvar key=window.localStorage.key(i);\n\tif (!key.startsWith(\"program.\")) {\n\t continue;\n\t}\n\tvar programName=key.substring(8,key.lastIndexOf(\".\"));\n\tvar suffix=key.substring(key.lastIndexOf(\".\"))\n\tif (suffix!=\".html\") {\n\t /* There are multiple keys per program; skip all but\n\t * one. */\n\t continue;\n\t}\n\toption=document.createElement(\"option\");\n\toption.value=programName;\n\toption.innerText=programName;\n\tif (selectedName==programName) {\n\t option.selected=true;\n\t}\n\tloadSelector.appendChild(option);\n }\n}", "function updateLanguage(select_language, select_dialect) {\n var list = langs[select_language.selectedIndex];\n select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';\n localStorage['dialect'] = select_dialect.selectedIndex; \n document.getElementById('voiceBtn').setAttribute('lang', list[select_dialect.selectedIndex + 1][0]);\n}", "function initLangMenu() {\n\t\n\tvar linkFr = document.getElementById(\"link-fr\");\n\tvar linkEn = document.getElementById(\"link-en\");\n\t\n\tif (currentCriteriaListName) {\n\t\tlinkFr.setAttribute('href', './?lang=fr&list=' + currentCriteriaListName);\n\t\tlinkEn.setAttribute('href', './?lang=en&list=' + currentCriteriaListName);\n\t} else {\n\t\tlinkFr.setAttribute('href', './?lang=fr');\n\t\tlinkEn.setAttribute('href', './?lang=en');\n\t}\n\t\n\tif (globalLang === \"fr\") {\n\t\tlinkFr.setAttribute('aria-current', true);\t\n\t\tlinkFr.classList.add(\"active\");\n\t\t\n\t\tlinkEn.removeAttribute('aria-current');\n\t\tlinkEn.classList.remove(\"active\");\n\t\t\n\t} else {\n\t\tlinkEn.setAttribute('aria-current', true);\n\t\tlinkEn.classList.add(\"active\");\n\t\t\n\t\tlinkFr.removeAttribute('aria-current');\n\t\tlinkFr.classList.remove(\"active\");\n\t}\n}", "function FillLanguagesCallBack(data, request) {\n FillDropDowns(\"Language\", data);\n}", "function setLanguage() {\n const queryParams = new URLSearchParams(window.location.search);\n const language = (queryParams.get(\"language\") || localStorage.getItem(\"language\") || \"\").toLowerCase();\n const languages = new Map();\n const codeTabs = document.querySelectorAll(\".multitab-code:not(.dependencies) li\") || [];\n Array.from(codeTabs).forEach(it => {\n languages.set(it.textContent.toLowerCase(), it.getAttribute(\"data-tab\")); // language and index\n });\n if (languages.get(language) !== undefined) {\n codeTabs[0].parentElement.querySelector(`[data-tab='${languages.get(language)}']`).click();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
indiviual log in validation document.getElementById('IndivisualLog').addEventListener('submit',
function IndivisualLog() { var inFieldU = document.getElementById("in-userf"); var inFieldP = document.getElementById("in-passf"); var inLabelU = document.getElementById("in-user"); var inLabelP = document.getElementById("in-pass"); usernameRegex .exec(inFieldU);//regular expression const vaild=!!usernameRegex; if(!vaild){ alert("user name is invaild"); return false } //if already shown from previous submit to hide it if (inLabelU.style.display === "inline" || inLabelP.style.display === "inline" ) { inLabelU.style.display = "none"; inLabelP.style.display = "none"; } if( inFieldU.value[0].match(RegexFirstchar) != null ){ inLabelU.innerHTML="user name should not start with number or Literal Characters"; inLabelU.style.display="inline" return false } }
[ "function handleLogInSubmit() {\n $('body').on(\"submit\", \"#form-log-in\", (event) => {\n event.preventDefault();\n const credentials = {\n username: $('#username-txt').val(),\n password: $('#password-txt').val()\n }\n doUserLogIn({\n credentials,\n onSuccess: getAndDisplayIdeas,\n onError: err => {\n alert('Incorrect username or password. Please try again.');\n }\n });\n });\n}", "function areTheyLogged(form)\n{\n if(!validatelogin(form)) return false;\n\n return true;\n}", "function validateAccount() {\n let uName = document.getElementById('username').value;\n let pword = document.getElementById('password').value;\n testAccount(uName, pword);\n}", "function event_login(e) {\n ajax_login($('#email').val());\n e.preventDefault();\n }", "async function onFormSubmit(event) {\n event.preventDefault();\n await signIn();\n }", "function fn_validaInicioSesion() {\n \n $('#hfrmInicioSesion').bootstrapValidator({\n message: 'El valor es inválido.',\n feedbackIcons: {\n valid: 'fa fa-check-circle icono-verde',\n invalid: 'fa fa-times-circle icono-rojo',\n validating: 'glyphicon glyphicon-refresh'\n },\n live: 'enabled',\n fields: {\n txtLogin: {\n validators: {\n //vacio\n notEmpty: {\n message: \"Favor de ingresar un Usuario\"\n },\n //caracteres y formato\n regexp: {\n regexp: /^[0-9a-zA-Z._-]+$/i,\n message: 'Formato Invalido.'\n }\n }\n },\n txtPassword: {\n validators: {\n //vacio\n notEmpty: {\n message: \"Favor de ingresar un ID de Tarjeta\"\n }\n }\n }\n }\n }).on('success.form.bv', function (e) {\n e.preventDefault();\n //se llama funcion de iniciar sesion\n fn_inicioSesionSistema();\n });\n}", "function onClickSubmit() {\n let key = document.getElementById(\"educator-validation\").value;\n checkInput(key);\n if (validKey == true) {\n // Display success message\n $(\"#feedback\").html(\"Success! Please wait...\");\n $(\"#feedback\").css({\n color: \"green\"\n });\n $(feedback).show(0);\n $(feedback).fadeOut(1000);\n setTimeout(function () {\n // Store record of a valid key entry event\n sessionStorage.setItem(\"keyStatus\", JSON.stringify({ \"key\": \"valid\" }));\n // Hide key-input DOM elements and display the Firebase login widget\n $(\"#input-container\").css({ display: \"none\" });\n $(\"#feedback-placeholder\").css({ display: \"none\" });\n $(\"#card-button-container-1\").css({ display: \"none\" });\n $(\"#firebaseui-auth-container\").css({ display: \"\" });\n }, 1000);\n }\n}", "function check() {\r\n\r\n // stored data from the register-form\r\n let storedID = localStorage.getItem('id_no1');\r\n let storedName = localStorage.getItem('name1');\r\n let storedPw = localStorage.getItem('psw1');\r\n\r\n // entered data from the login-form\r\n let userID = document.getElementById('id_no');\r\n let userName = document.getElementById('name');\r\n var userPw = document.getElementById('psw');\r\n\r\n // check if stored data from register-form is equal to data from login form\r\n if(userID.value == storedID && userName == storedName && userPw.value == storedPw) {\r\n alert('Error already hav an account');\r\n }else {\r\n alert('You Logged in.');\r\n }\r\n}", "function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}", "function signIn()\n {\n var email = document.getElementById(\"email\");\n var password = document.getElementById(\"password\");\n const promise = auth.signInWithEmailAndPassword(email.value, password.value);\n promise.catch(e => alert(e.message));\n \n if (auth.signInWithEmailAndPassword(email.value, password.value))\n {\n window.location.href=\"MainPage.html\"\n }\n else\n {\n alert(\"Wrong infromation, please try again.\")\n }\n\n }", "function validatePassLogin(){\n\n\n\tif (logInUserForm.users_Password.value === \"\" || logInUserForm.users_Password.value === null) {\n\n\t\tlogInUserForm.users_Password.style.borderColor = \"red\";\n\t\ttheUserLoginPassErr.innerHTML = \"Password is required\";\n\t}else{\n\n\t\tlogInUserForm.users_Password.style.borderColor = \"green\";\n\t\ttheUserLoginPassErr.innerHTML = \"\";\n\n\t}\n}", "function validateForm() {\n var emailInput = document.getElementById('email');\n var submitButton = document.getElementById('button-submit');\n var email = emailInput.value;\n var re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n // check if email format is invalid\n if (email == \"\" || !re.test(email)) {\n document.querySelector('.invlalid-feedback').innerHTML = \"電子郵件空白或格式不符\";\n emailInput.classList.add('is-invalid');\n return false;\n } else {\n // if email format if valid\n if (emailInput.classList.contains('is-invalid')) {\n // remove 'is-invalid' class if previous submission triggered invalid\n emailInput.classList.remove('is-invalid');\n }\n // Set input group to 'is-valid' status\n emailInput.classList.add('is-valid');\n document.querySelector('.invlalid-feedback').innerHTML = \"\";\n // change button status after successful update\n submitButton.innerHTML = \"完成!\"\n submitButton.setAttribute(\"style\", \"background: linear-gradient(to right, #5ead07 0%, #5ead07 50%, #5ead07 100%); cursor: default;\");\n submitButton.disabled = 'disabled';\n // update user's email to SD param and redirect to finish page\n exportFile();\n api.exports.requestAsync({name: \"data email\"}).then( function(response) {\n // console.log(response);\n window.location.href = \"finish-post-config.html\";\n }\n );\n }\n}", "function loginClickHandler() {\n var values = this.getLoginForm().getValues();\n var e = new ExtJSCodeSample.event.SessionEvent(values.username, values.password, this.getRememberMeCheckBox().getValue());\n this.application.fireEvent(ExtJSCodeSample.event.SessionEvent.LOGIN, e);\n }", "function onLoginError( evt )\n{\n\talert(\"Login Error!\");\n}", "function validate() {\n var errorMessage = document.querySelector(\".ui.error.message\");\n var ipAddress = document.getElementById('loggerIpAddress');\n var portNumber = document.getElementById('loggerPortNumber');\n var ipExp =\n /^(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))$/;\n var hostExp =\n /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$/;\n errorMessage.style.display = 'none';\n var ip = false;\n var hostname = false;\n var port = false;\n var time = false;\n var i = 0;\n errorMessage.innerHTML = '';\n if (ipAddress.value === '' || ipAddress.value === undefined || ipAddress.value === null) {\n errorMessage.innerHTML = \"Please enter IP Address/Hostname\";\n errorMessage.style.display = 'block';\n return false;\n }\n if (portNumber.value === '' || portNumber.value === undefined || portNumber.value ===\n null) {\n errorMessage.innerHTML = \"Please enter Port Number\";\n errorMessage.style.display = 'block';\n return false;\n }\n if (ipAddress.value !== undefined && ipAddress.value !== null && ipAddress.value !== \"0.0.0.0\" && ipAddress.value !==\n \"255.255.255.255\" && ipExp.test(ipAddress.value) && ipAddress.value.length <= 127 && hostExp.test(ipAddress.value) &&\n ipAddress.value.length <= 127) {\n ip = true;\n errorMessage.style.display = 'none';\n } else {\n errorMessage.innerHTML = \"Please enter valid IP Address/Hostname\";\n errorMessage.style.display = 'block';\n return false;\n }\n if (portNumber.value !== null && (!isNaN(portNumber.value) && (portNumber.value >= 1025 &&\n portNumber.value < 65536))) {\n port = true;\n errorMessage.style.display = 'none';\n } else {\n errorMessage.innerHTML = \"Please enter valid Port Number\";\n errorMessage.style.display = 'block';\n return false;\n }\n if ((ip || hostname) && port) {\n errorMessage.style.display = 'none';\n updateLoggerInfo();\n }\n }", "handleSubmit(event) \n { \n // Call the signIn function with the values from the form input\n this.signIn(this.state.email, this.state.password);\n\n // Prevent default action\n event.preventDefault();\n }", "function checkValid() {\n\tif(!document.getElementById(\"email\").value.match(/\\S+@\\S+\\.\\S+/)){\n\t\tif (document.getElementById(\"email\").value != \"\") {\n\t\t\talert(\"Email Format is wrong!\")\n\t\t\treturn false;\n\t\t} \n\t}\n\tif (!document.getElementById(\"phone_number\").value.match(\"^\\\\d{3}-\\\\d{3}-\\\\d{4}$\")) {\n\t\tif (document.getElementById(\"phone_number\").value != \"\") {\n\t\t\talert(\"Phone Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (!document.getElementById(\"zipcode\").value.match(\"^\\\\d{5}$\")) {\n\t\tif (document.getElementById(\"zipcode\").value != \"\") {\n\t\t\talert(\"Zipcode Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tvar password = document.getElementById(\"password\")\n\tvar password2 = document.getElementById(\"password2\")\n\tif (password.value == \"\" && password2.value != \"\") {\n\t\talert(\"Password is empty !\")\n\t\treturn false;\n\t} else if (password2.value == \"\" && password.value != \"\"){\n\t\talert(\"Confirmation Password is empty !\")\n\t\treturn false;\n\t}\n\treturn true;\n}", "function verifyUser(e)\n{\n e.preventDefault();\n\n user.email = email.value;\n user.password = password.value;\n \n //check if user is valid\n checkUser(user);\n}", "onLogin() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the start to the first suitable text node.
function moveStart(rng) { var container = rng.startContainer, offset = rng.startOffset, isAtEndOfText, walker, node, nodes, tmpNode; // Convert text node into index if possible if (container.nodeType == 3 && offset >= container.nodeValue.length) { // Get the parent container location and walk from there offset = nodeIndex(container); container = container.parentNode; isAtEndOfText = true; } // Move startContainer/startOffset in to a suitable node if (container.nodeType == 1) { nodes = container.childNodes; container = nodes[Math.min(offset, nodes.length - 1)]; walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); // If offset is at end of the parent node walk to the next one if (offset > nodes.length - 1 || isAtEndOfText) { walker.next(); } for (node = walker.current(); node; node = walker.next()) { if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { // IE has a "neat" feature where it moves the start node into the closest element // we can avoid this by inserting an element before it and then remove it after we set the selection tmpNode = dom.create('a', null, INVISIBLE_CHAR); node.parentNode.insertBefore(tmpNode, node); // Set selection and remove tmpNode rng.setStart(node, 0); selection.setRng(rng); dom.remove(tmpNode); return; } } } }
[ "function findFirstTextNode(element, startIndex) {\n var index = null;\n startIndex = startIndex || 0;\n\n if (startIndex < textNodes.length) {\n for (var i = startIndex; i < textNodes.length; i++) {\n if ($.contains(element, textNodes[i])) {\n index = i;\n break;\n }\n }\n }\n\n return index;\n}", "function emitTagAndPreviousTextNode() {\n var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);\n if (textBeforeTag) {\n // the html tag was the first element in the html string, or two\n // tags next to each other, in which case we should not emit a text\n // node\n onText(textBeforeTag, currentDataIdx);\n }\n if (currentTag.type === 'comment') {\n onComment(currentTag.idx);\n }\n else if (currentTag.type === 'doctype') {\n onDoctype(currentTag.idx);\n }\n else {\n if (currentTag.isOpening) {\n onOpenTag(currentTag.name, currentTag.idx);\n }\n if (currentTag.isClosing) {\n // note: self-closing tags will emit both opening and closing\n onCloseTag(currentTag.name, currentTag.idx);\n }\n }\n // Since we just emitted a tag, reset to the data state for the next char\n resetToDataState();\n currentDataIdx = charIdx + 1;\n }", "tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.start, to: this.pos,\n text: this.state.sliceDoc(token.start, this.pos),\n type: token.type } : null;\n }", "function StartTextAnimation(i) {\n if (i < dataText[i].length) {\n // text exists! start typewriter animation\n typeWriter(dataText[i], 0, function () {\n // after callback (and whole text has been animated), start next text\n StartTextAnimation(i + 1);\n });\n }\n }", "function nextConspiricy() {\n index++;\n textBox.innerHTML = textGenerator.next();\n}", "tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }", "function firstSlide()\n{\n var h;\n\n h = document.body.firstChild;\n while (h && !isStartOfSlide(h)) h = h.nextSibling;\n\n if (h != null) makeCurrent(h);\n}", "moveStartPoint(to) {\n this._edgeSegment.moveStartPoint(to);\n }", "onPreviousParagraphRequested() {}", "function moveToCaretPosition(root) {\n\t\t\t\tvar walker, node, rng, lastNode = root, tempElm;\n\n\t\t\t\trng = dom.createRng();\n\n\t\t\t\tif (root.hasChildNodes()) {\n\t\t\t\t\twalker = new TreeWalker(root, root);\n\n\t\t\t\t\twhile ((node = walker.current())) {\n\t\t\t\t\t\tif (node.nodeType == 3) {\n\t\t\t\t\t\t\trng.setStart(node, 0);\n\t\t\t\t\t\t\trng.setEnd(node, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (nonEmptyElementsMap[node.nodeName.toLowerCase()]) {\n\t\t\t\t\t\t\trng.setStartBefore(node);\n\t\t\t\t\t\t\trng.setEndBefore(node);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlastNode = node;\n\t\t\t\t\t\tnode = walker.next();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!node) {\n\t\t\t\t\t\trng.setStart(lastNode, 0);\n\t\t\t\t\t\trng.setEnd(lastNode, 0);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (root.nodeName == 'BR') {\n\t\t\t\t\t\tif (root.nextSibling && dom.isBlock(root.nextSibling)) {\n\t\t\t\t\t\t\t// Trick on older IE versions to render the caret before the BR between two lists\n\t\t\t\t\t\t\tif (!documentMode || documentMode < 9) {\n\t\t\t\t\t\t\t\ttempElm = dom.create('br');\n\t\t\t\t\t\t\t\troot.parentNode.insertBefore(tempElm, root);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\trng.setStartBefore(root);\n\t\t\t\t\t\t\trng.setEndBefore(root);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trng.setStartAfter(root);\n\t\t\t\t\t\t\trng.setEndAfter(root);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\trng.setStart(root, 0);\n\t\t\t\t\t\trng.setEnd(root, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tselection.setRng(rng);\n\n\t\t\t\t// Remove tempElm created for old IE:s\n\t\t\t\tdom.remove(tempElm);\n\t\t\t\tselection.scrollIntoView(root);\n\t\t\t}", "function nextWord() {\n\n //Agrega la siguiente palabra en un string, seguido por un espacio\n text.text = text.text.concat(line[wordIndex] + \" \");\n\n //Avanza el indice de la palabra\n wordIndex++;\n\n //Si es la ultima palabra...\n if (wordIndex === line.length)\n {\n //Agrega un salto de linea\n text.text = text.text.concat(\"\\n\");\n\n //Obtiene la siguiente linea \n game.time.events.add(lineDelay, nextLine, this);\n }\n\n }", "textAfterPos(pos) {\n var _a, _b;\n let sim = (_a = this.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;\n if (pos == sim && ((_b = this.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak))\n return \"\";\n return this.state.sliceDoc(pos, Math.min(pos + 100, sim != null && sim > pos ? sim : 1e9, this.state.doc.lineAt(pos).to));\n }", "TreeAdvanceToLabelPos()\n {\n let g = this.guictx;\n g.CurrentWindow.DC.CursorPos.x += this.GetTreeNodeToLabelSpacing();\n }", "startAutoScroll() {\n this.selectNextSibling();\n this.setAutoScroll();\n }", "function dnd_moveText() {\r\n\tvar dragndropTextElement = $('dnd_mouseText');\r\n\tif (dragndropTextElement != null) {\r\n\t\tdragndropTextElement.style.left = (dnd_mouseX + 15) + \"px\";\r\n\t\tdragndropTextElement.style.top = (dnd_mouseY + 5) + \"px\";\r\n\t}\r\n}", "setFocusToFirstItem() {\n if (this.interactiveChildElements.length) {\n this.interactiveChildElements[0].focus();\n }\n }", "function nextLeft(v){var children=v.children;return children?children[0]:v.t;} // This function works analogously to nextLeft.", "function moveLeft(){\n gMeme.currText.x -= 15;\n}", "function helperSkipToNextWord() {\n\n // Loop to next periode / space etc\n while (ch = searchString.charAt(currentPosition)) {\n\n if (ch === ' ' || ch === '.') {\n break;\n }\n\n currentPosition += 1;\n\n }\n\n //currentPosition = searchString.indexOf(' ', currentPosition + 1);\n if (ch !== '') {\n\n // Loop through any additional spaces / periods\n while (ch = searchString.charAt(currentPosition)) {\n\n if (ch !== ' ' && ch !== '.') {\n break;\n }\n\n currentPosition += 1;\n\n }\n\n if (ch !== '') {\n helperStartWord();\n return;\n }\n\n }\n\n if (ch === '') {\n // End of text\n cb(null, returnData);\n return;\n }\n\n }", "firstChild() {\n return this.enterChild(1, 0, 4 /* Side.DontCare */)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POKEMON OBJECT Update pokemon object
function updatePokemonObject(pokemonData) { PokemonObject.name = pokemonData.name; PokemonObject.height = pokemonData.height; PokemonObject.weight = pokemonData.weight; PokemonObject.frontImgSrc = pokemonData.sprites.front_default; PokemonObject.backImgSrc = pokemonData.sprites.back_default; PokemonObject.typeList = []; PokemonObject.namesRelatedToTypesUrls = []; for (let type of pokemonData.types){ PokemonObject.typeList.push(type.type.name); PokemonObject.namesRelatedToTypesUrls.push(type.type.url); } }
[ "constructor(pokemonObj) {\n this.pokPokemonId = pokemonObj.pokPokemonId;\n this.pokName = pokemonObj.pokName;\n this.pokHeight = pokemonObj.pokHeight;\n this.pokWeight = pokemonObj.pokWeight;\n this.pokAbilities = pokemonObj.pokAbilities;\n this.pokGender = pokemonObj.pokGender;\n if (pokemonObj.pokFavorite) this.pokFavorite = pokemonObj.pokFavorite;\n if (pokemonObj.pokTypes) this.pokTypes = _.cloneDeep(pokemonObj.pokTypes);\n }", "updatePokemon(pokemon) {\n // destructure the necessary values\n const { name } = pokemon;\n const { front_default: sprite } = pokemon.sprites;\n\n // update the state to the accrued values\n // additionally toggle the boolean to show the input instead of result\n this.setState({\n pokemon: {\n name,\n sprite\n },\n result: false\n });\n\n // select the header showing the answer and the image showing the pokemon\n const heading = document.querySelector('.AppOutput h2');\n const image = document.querySelector('.AppOutput img');\n\n // after a specified timeout, show the label describing pokemon and show the image in which the sprite is used\n const timeoutID = setTimeout(() => {\n heading.textContent = 'Pokemon';\n heading.style.opacity = 1;\n image.parentElement.style.transform = 'scale(1)';\n clearTimeout(timeoutID);\n }, 750);\n }", "function changePokemonData()\n{\n\t// Dereference the value of the Pokemon Search Bar\n\tlet pokemon = document.getElementById('pokemon').value;\n\t\n\t// Name_lookup: Function from /util/search.js\n\t// Check to see if the value of the search bar matches \n\t// the name of a Pokemon\n\t\n\tlet lookup = name_lookup(pokemon,document.pokedex);\n\t\n\t// If the search bar matches a Pokemon\n\tif (lookup)\n\t{\n\t\t// Load the Pokemon's data into memory\n\t\tloadPokemonData(lookup);\n\t}\n\telse // If it does not match a Pokemon\n\t{\n\t\t// Do nothing\n\t}\n}", "function refresh_pokemon_layer() {\n // Prepare new layer\n var pokemon_layer = get_pokemon_layer_from_map_items(map_manager.map_items);\n\n // Remove old layer\n map_manager.map.layers.clear();\n\n // Add new layer\n map_manager.map.layers.insert(pokemon_layer);\n}", "function createPokemon(_id, name, classification, type1, type2, hp, attack, defense, speed, sp_attack, sp_defense){\n return {\n \"_id\": _id,\n \"name\": name,\n \"classification\": classification,\n \"type1\": type1,\n \"type2\": type2,\n \"stats\": {\n \"hp\": hp,\n \"attack\": attack,\n \"defense\": defense,\n \"speed\": speed,\n \"sp_attack\": sp_attack,\n \"sp_defense\": sp_defense\n }\n }\n\n}", "function selectPokemon(){\n var choosePokemon = prompt(\"Choose a Pokemon: BULBASAUR, CHARMANDER, SQUIRTLE, PIKACHU, DRATINI, EEVEE, MEOWTH, or RATTATA?\").toLowerCase();\n if (choosePokemon === \"bulbasaur\") {myPokemon = new Bulbasaur();}\n else if (choosePokemon === \"charmander\") {myPokemon = new Charmander();}\n else if (choosePokemon === \"squirtle\") {myPokemon = new Squirtle();}\n else if (choosePokemon === \"dratini\") {myPokemon = new Dratini();}\n else if (choosePokemon === \"eevee\") {myPokemon = new Eevee();}\n else if (choosePokemon === \"meowth\") {myPokemon = new Meowth();}\n else if (choosePokemon === \"rattata\") {myPokemon = new Rattata();}\n else {myPokemon = new Pikachu();} //default option if you fail to make a proper choice. (you can also choose it)\n myPokemon.inventory += 1; //will allow the user to heal twice\n //give user the option to choose a nickname\n var chooseNickname = confirm(\"Do you want to give your \" + choosePokemon + \" a nickname? Click 'OK' for yes, and 'CANCEL' for no\");\n if (chooseNickname === true) {var pokeNickname = prompt(\"What will you name your \" + choosePokemon + \"?\"); myPokemon.name = pokeNickname;}\n console.log(\"I choose you, \" + myPokemon.name + \"!!!\");\n\n //select the computer's pokemon:\n var botChoose = Math.floor(Math.random() * (8 - 1 + 1)) + 1; //random number from 1-8 represents number of pokemon\n if (botChoose === 1) {botPokemon = new Bulbasaur();}\n else if (botChoose === 2) {botPokemon = new Charmander();}\n else if (botChoose === 3) {botPokemon = new Squirtle();}\n else if (botChoose === 4) {botPokemon = new Dratini();}\n else if (botChoose === 5) {botPokemon = new Eevee();}\n else if (botChoose === 6) {botPokemon = new Meowth();}\n else if (botChoose === 7) {botPokemon = new Rattata();}\n else {botPokemon = new Pikachu();}\n console.log(\"The computer chose \" + botPokemon.name);\n //if the computer & user choose the same pokemon, prefix computer pokemon's name with \"enemy\" to differentiate it:\n if (myPokemon.name === botPokemon.name) {botPokemon.name = \"Enemy \" + botPokemon.name;}\n\nbattle(myPokemon, botPokemon);\n} //end selectPokemon function", "updateWeaponPlayerInfo() {\n let playerWeaponInfoImg = $(\"#\"+this.name+\"-weapon-img\");\n let playerWeaponInfoValue = $(\"#\"+this.name+\"-weapon-value\");\n $('#'+playerWeaponInfoImg.attr('id')).removeClass(\"player-infos__\"+this.previousWeapon).addClass(\"player-infos__\"+this.weapon.weapon);\n $('#'+playerWeaponInfoValue.attr('id')).text(this.weapon.name);\n }", "updateProjectiles() {\r\n //remvoe projectiles\r\n for (let [index, projectile] of this.projectileList.entries()) {\r\n if (projectile.toDelete) this.projectileList.splice(index, 1);\r\n }\r\n\r\n //update projectiles\r\n for (let projectile of this.projectileList) {\r\n projectile.update();\r\n }\r\n }", "party__update(party){\n this.digimons = party.digimons;\n for(const index in party.configuration){\n this.digimons[party.configuration[index].id].start_time = this.elapsed;\n this.digimons[party.configuration[index].id].background = party.configuration[index].bkg;\n this.digimons[party.configuration[index].id].bond_count = 0;\n this.digimons[party.configuration[index].id].light = party.configuration[index].light;\n }\n /* recebe digimons e adiciona o basico necessario relativo a pendulum, bkg, light, time, etc */\n}", "function addPoo( quantity ) { _playerState[\"Statistics\"][\"TotalPooCollect\"] += quantity; }", "function update() {\n\tchangeSpeed(game_object);\n\tchangeLivesOfPlayer(game_object);\n\thackPlayerScore(game_object);\n}", "lvlUp() {\n this.lvl ++;\n console.log(\"Su pokémon ha subido de nivel, el nivel es: \" + this.lvl);\n\n // Sube alguno de sus stats dependiendo de la naturaleza del pokemon\n switch (this.naturaleza) {\n case 'Audaz':\n this.stats[\"ataque\"] ++;\n console.log(\"Tu nivel de ataque es: \" + this.stats[\"ataque\"]);\n break;\n case 'Osada':\n this.stats[\"defensa\"] ++;\n console.log(\"Tu nivel de defensa es: \" + this.stats[\"defensa\"]);\n break;\n case 'Cauta':\n this.stats[\"vida\"] ++;\n console.log(\"Tu nivel de vida es: \" + this.stats[\"vida\"]);\n break;\n case 'Alegre':\n this.stats[\"velocidad\"] ++;\n console.log(\"Tu nivel de velocidad es: \" + this.stats[\"velocidad\"]);\n break;\n default:\n console.log(\"Esto es raro, tu pokémon tiene un naturaleza que no había visto antes, no sé que hacer\")\n }\n if (this.lvl === 100) {\n console.log(\"Tu pokemon ha llegado al nivel 100\");\n }\n }", "function updateTipEventCount(tipObj){\n\t\n\t\t\tconsole.log(tipObj);\n\t\t\tconsole.log(tipObj._id + \" : \" + tipObj.isEvent);\n\t\t\t\n\t\t\tvar placeObj = {};\n\t\t\t\n\t\t\t\n\t\t\t//Get Current Tip Count\n\t\t\tvar promise = Kinvey.DataStore.find('places', tipObj._id , {\n\t\t\t\tsuccess: function(response) {\n\t\t\t\t\t\n\t\t\t\t\tconsole.log(response);\n\t\t\t\t\t\tplaceObj = response;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(tipObj.isEvent == \"true\"){\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Event Count : \" + placeObj.eventCount++);\n\t\t\t\t\t\t\n\t\t\t\t\t\tplaceObj.eventCount = placeObj.eventCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Tip Count : \" + placeObj.tipCount++);\n\t\t\t\t\t\tplaceObj.tipCount = placeObj.tipCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\n\tKinvey.DataStore.save('places', placeObj).then(function() {\n\t\t\tconsole.log(\"place event tip count updated\");\n\t\t\tconsole.log(placeObj);\n \t}, function(error) {\n \t\t doc.trigger('error', error);\n \t}).then(function() {\n\t\t \n\t\t \n\t\t});\t\n}", "function updatePlaceResultObject(tobeupdated,update){\n\ttobeupdated.geometry= update.geometry;\n\ttobeupdated.icon=update.icon;\n\ttobeupdated.name=update.name;\n\ttobeupdated.vicinity=update.vicinity;\n\t}", "getPokeDetails() {\n let pokeData = this.state;\n return {\n name: pokeData.name,\n imgData: this.getPokeImgs(pokeData.sprites),\n type: this.getPokeType(pokeData.types),\n hp: pokeData.base_experience,\n weight: pokeData.weight,\n height: pokeData.height,\n stats: this.getPokeStats(pokeData.stats),\n moves: this.getPokeMoves(pokeData.moves)\n }\n }", "function updateField(f)\n{\n\t// Dereference active Pokemon\n\tlet active = window.active;\n\t\n\t// Dereference active Pokemon base stats\n\tlet bs = active.baseStats;\n\t\n\t// Integer contained in the webpage maximum EV input field for the field\n\tmax_ev = parseInt(document.getElementById(f + '-max').value);\n\t\n\t// Integer contained in the webpage minimum EV input field for the field\n\tmin_ev = parseInt(document.getElementById(f + '-min').value);\n\t\n\t// Integer contained in the webpage level input field\n\tlevel = parseInt(document.getElementById('level').value);\n\t\n\t// Integer contained in the webpage IV input field for the field\n\tiv = parseInt(document.getElementById(f + '-iv').value);\n\t\n\t// Best and worst possible stat given inputs\n\tvar best,worst;\n\t\n\t// If given stat is 'hp'\n\tif(f == 'hp')\n\t{\n\t\t// Use hp algorithm\n\t\tbest = hp(bs[f],iv,max_ev,level);\n\t\tworst = hp(bs[f],iv,min_ev,level);\n\t}\n\t// Non-HP stat\n\telse\n\t{\n\t\t// Use normal algorithm\n\t\tbest = stat(bs[f],iv,max_ev,level,window.nature[f]);\n\t\tworst = stat(bs[f],iv,min_ev,level,window.nature[f]);\n\t}\n\t\n\t// Update the page elements with the new minimum and maximum stats\n\tdocument.getElementById(f + '-stat-max').innerHTML = 'Max: ' + best;\n\tdocument.getElementById(f + '-stat-min').innerHTML = 'Min: ' + worst;\n\t\n\t// Update the computational complexity of the algorithm\n\tcomplexity();\n}", "function increaseYakuzaVote(value)\n {\n setGame(\"yakuza\");\n setVotes(true);\n }", "async updatePlayerPunchcard(numNewPlayers) {\n // get date, utc hour, and utc day\n const now = new Date();\n const time = now.getTime();\n const hour = now.getUTCHours();\n const day = now.getUTCDay();\n const month = now.getUTCMonth();\n const year = now.getUTCFullYear();\n\n // find the punchcard\n const card = await this.stores.status.findOne({\n type: 'punchcard',\n kind: 'playerCount',\n month, year,\n });\n\n // create a new punchcard if one does not exist for this month\n if (!card) {\n const punchcard = createPunchcard();\n punchcard[day][hour] = numNewPlayers;\n // insert it\n await this.stores.status.insert({\n type: 'punchcard',\n kind: 'playerCount',\n created: time,\n updated: time,\n month, year,\n punchcard,\n });\n\n // if the card exists, check if it was already updated this hour\n } else {\n // add the players to this slot\n card.punchcard[day][hour] += numNewPlayers;\n // update the punchcard\n await this.stores.status.update({ _id: card._id }, {\n $set: {\n punchcard: card.punchcard,\n updated: time,\n },\n });\n }\n }", "function pokemonImage(pokemon){\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParsernew_column_name.
visitNew_column_name(ctx) { return this.visitChildren(ctx); }
[ "visitColumn_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXml_column_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitRename_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitParen_column_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_mv_log_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDrop_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubstitutable_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModify_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXml_table_column(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_modify_drop_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModify_mv_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitVirtual_column_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModel_column(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function column1(machine)\n {\n token = machine.popToken();\n switch( token.type )\n {\n case \"identifier\": machine.pushToken( new identifierColumn( \"\", token.identifier, token.identifier ) ); break;\n case \"expression\": machine.pushToken( new expressionColumn( token.expression, \"\" ) ); break;\n case \"*\": machine.pushToken( new everythingColumn() ); break;\n\n default : machine.error(\"there is an unexpected error with a column1 production\");\n }\n }", "visitColumn_or_attribute(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function setState of maxPrice to price selected on MaxPrice Dropdown Menu
maxHandleChange(event, index, maxPrice) { this.setState({ maxPrice }); }
[ "useMaxQty(event) {\n this.props.useMaxQty(event.target.checked);\n }", "minHandleChange(event, index, minPrice) {\n this.setState({ minPrice });\n }", "function updateMaxQty(maxQty, upgradePurchased, cost, currency) {\r\n if(currency >= cost) {\r\n maxQty += upgradePurchased;\r\n currency -= cost;\r\n\r\n updatePbFill(beans, beansMax, 'pbBeansFill');\r\n document.getElementById('beans').innerHTML = \"Beans: \" + beans + \"/\" + beansMax;\r\n }\r\n}", "function handleDecrease() {\n if (selectedAmount > 1) setSelectedAmount(selectedAmount - 1);\n }", "function setPriceRange(list) {\n let min = Infinity;\n let max = -Infinity;\n list.forEach(hotel => {\n const price = parseFloat(hotel.price);\n if (price > max) max = price;\n if (price < min) min = price;\n });\n\n //Set minimum and maximum prices in slider\n const price = document.querySelector(\"#price\");\n price.setAttribute(\"min\", min);\n price.setAttribute(\"max\", max);\n price.setAttribute(\"value\", max);\n document.querySelector(\"#forPrice\").innerHTML = `<span id=\"labelPrice\">Price\n </span><span class=\"tab\">Max: $${max}</span>`;\n }", "function updateMaxWeeks() {\n var weekSelect = document.getElementById('week');\n if(state.medium === 'coco'){\n weekSelect.setAttribute('max', '13');\n } else {\n weekSelect.setAttribute('max', '12');\n }\n}", "verifyValueMax() {\n this.discount.value = discountHandler.getFixedValue(this.discount.value, this.discount.type);\n }", "function getpsPrice(product) {\n\n let $prod = $(product);\n let qty = $prod.find(\"option:selected\").data(\"qty\");\n let pprice_to = Number($prod.find(\"option:selected\").data(\"pprice\"));\n let pprice = pprice_to.toFixed(2);\n\n let sprice_to = Number($prod.find(\"option:selected\").data(\"sprice\"));\n let sprice = sprice_to.toFixed(2);\n if (pprice === \"\" || sprice === \"\" || pprice === \"0.00\" || sprice === \"0.00\") {\n\n $('input[name=\"u_price\"]').val(\"\");\n $('input[name=\"s_price\"]').val(\"\");\n } else {\n $('input[name=\"u_price\"]').val(pprice);\n $('input[name=\"s_price\"]').val(sprice);\n $('input[name=\"pquantity\"]').val(1);\n $('input[name=\"discount\"]').val(0);\n\n }\n // For Show Quantity of Purchase Goods\n if ($(\"#product\").val() === \"\")\n {\n $(\"#qa\").html(\"\");\n }\n else {\n\n\n $(\"#qa\").html(\"{<b> \" + qty + \" </b>}\");\n $(\"#quantity\").prop(\"max\", qty);\n\n\n }\n}", "function onSelectionChange(){\n if (ui.amountBox.value > 0 && ui.icosBox.selectedIndex != 0 && ui.roundBox.selectedIndex != 0 && ui.currencyBox != 0) {\n onCalculateClick();\n }\n }", "set price(value) {\n this._price = 80;\n }", "onCompanyChange(e) {\n const companyId = e.target.value;\n getCompanyCostsById(companyId)\n .then(response => {\n this.setState({\n selectedCompanyCost: response.totalCosts,\n });\n });\n }", "function setDataInputMax(x)\n{\n\tdataInputMax = x;\n}", "updateMaxHeightState() {\n this.setState(() => ({\n maxHeight: this._refMainContainer.clientHeight - this.state.mainContainerRestHeight,\n }));\n }", "getMinMaxPrice(ticketData) {\n const price = [];\n\n // get the totalprices\n ticketData.map(ticket => {\n price.push(ticket.price);\n });\n\n // get price minimum and maximum\n const min = Math.min(...price);\n const max = Math.max(...price);\n\n let minMax;\n max === min\n ? (minMax = `₦ ${max.toLocaleString()}`)\n : (minMax = `₦ ${min.toLocaleString()} - ₦ ${max.toLocaleString()}`);\n return minMax;\n }", "SET_MESSAGE_PRICE(state, price){\n state.messagePrice = price;\n }", "changeStockPrices(state) {\n state.stocks.forEach(stock => {\n stock.price = Math.round(stock.price * (1 + Math.random() - 0.5));\n });\n }", "function setDataMax(x)\n{\n\tdataMax = x;\n}", "function MDEC_SelectLevelChange(el_select) {\n console.log(\"===== MDEC_SelectLevelChange =====\");\n\n mod_MEX_dict.lvlbase_pk = (el_select.value && Number(el_select.value)) ? Number(el_select.value) : null;\n MDEC_enable_btn_save();\n\n }", "setProductPerPageSelectionEventListener() {\n var selectSection = document.getElementById('select-page-limit');\n selectSection.addEventListener('change', this.setPageLimit.bind(this));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adding an observer to this.observers
addObserver(observer){ this.observers.push(observer) }
[ "function addObserver(chain, observer) {\n let tail = chain.tail;\n if (tail) {\n observer.prev = tail;\n tail.next = observer;\n chain.tail = observer;\n } else {\n chain.head = observer;\n chain.tail = observer;\n }\n}", "function runObserver (observer) {\n currentObserver = observer;\n observer();\n}", "_observeEntries() {\n this.items.forEach((item) => {\n item.elementsList.forEach((element) => {\n this.observer.observe(element);\n });\n });\n }", "function addMutationObserver() {\n const config = {\n childList: true,\n attributes: true,\n subtree: true,\n };\n observer.observe(document, config);\n}", "function Subject() {\n this.observers = new ObserverList();\n}", "notifyObservers() {\n if (this.observers != null) {\n\n this.observers.forEach((observer, index) => {\n \n var newroute = window.location.pathname;\n observer(newroute);\n });\n }\n }", "observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }", "function Subject() {\n this._observerList = [];\n}", "function addChangesetsObserver() {\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (mutation.type == 'attributes') {\n return;\n }\n searchChangesets();\n });\n });\n\n var config = { attributes: true, childList: true, characterData: true };\n var changesets = document.querySelector('#sidebar_content div.changesets');\n observer.observe(changesets, config);\n}", "addContact(contact){\n this.contactList.push(contact);\n super.notifyObservers(\"addContact\",contact);\n }", "setEventListeners() {\n this.on('edit',this.onEdit.bind(this));\n this.on('panelObjectAdded',this.onPanelObjectAdded.bind(this));\n this.on('panelObjectRemoved',this.onPanelObjectRemoved.bind(this));\n }", "function queueObserver (observer) {\n if (queuedObservers.size === 0) {\n Promise.resolve().then(runObservers);\n }\n queuedObservers.add(observer);\n}", "function Subject() {\n // create an Observers list instance, passing all methods on\n this.observers = new ObserverList()\n}", "function notifyServerConnected(func) {\n this.observersNotifyServerConnected.push(func);\n }", "function attachTracklistModificationListeners(onTracklistModifiedByExternalSource) {\n let onEvent = (event) => {\n if(!currentlyModifyingAnyTracklist)\n onTracklistModifiedByExternalSource()\n }\n\n for(trackList of getTracklistNodes()) {\n trackList.addEventListener('DOMNodeInserted', onEvent)\n trackList.addEventListener('DOMNodeRemoved', onEvent)\n }\n}", "function _observe(observer, obj, patches) {\r\n if (Object.observe) {\r\n Object.observe(obj, observer);\r\n }\r\n for (var key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n var v = obj[key];\r\n if (v && typeof (v) === \"object\") {\r\n _observe(observer, v, patches);\r\n }\r\n }\r\n }\r\n return observer;\r\n }", "initIntersectionObserver() {\n if (this.observer) return;\n // Start loading the image 10px before it appears on screen\n const rootMargin = '10px';\n this.observer = new IntersectionObserver(this.observerCallback, { rootMargin });\n this.observer.observe(this);\n }", "_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }", "constructor() {\n this.model = new TimerModel();\n this.view = new TimerView(this.model);\n\n this.model.registerObserver(this.view);\n\n this.subsribeToEvents();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disableOtherElement() : Disables all other operations during the levelup, win all levels, lost because of time, lost because of score scenarios makes the buttons in game header 'back' and 'i will learn' disabled makes the input field to enter the name of current item disabled reduces the opacity of the right and left panel to appear faded
function disableOtherElement() { //Back, home page, learn and speaker icons are disabled document.getElementsByClassName('backContainer')[0].setAttribute('disabled', 'true'); document.getElementsByClassName('homePageContainer')[0].setAttribute( 'disabled','true'); document.getElementsByClassName('learnContainer')[0].setAttribute('disabled', 'true'); document.getElementById('speaker').setAttribute('disabled','true'); //Decrease the opacity of header elements document.getElementsByClassName('levelHeader')[0].style.opacity = 0.5; var images = document.getElementsByClassName( 'levelHeader')[0].getElementsByTagName('img'); //Also remove the pointer for header icons for(var i=0;i<images.length;i++) { images[i].style.cursor = 'default'; } //Deacrease opacity for all elements document.getElementsByClassName('leftPanelContainer')[0].style.opacity = 0.5; document.getElementsByClassName('questionElement')[0].style.opacity = 0.5; document.getElementById('answerInputElement').setAttribute('disabled','true'); document.getElementById('item_'+currentItem.itemId).setAttribute('draggable', 'false'); }
[ "function disableInput() {\n if (turn === \"player 1\") {\n document.getElementById(\"ci1a\").disabled = false;\n document.getElementById(\"ci1b\").disabled = false;\n document.getElementById(\"ci1c\").disabled = false;\n document.getElementById(\"ci1d\").disabled = false;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n } else {\n document.getElementById(\"ci2a\").disabled = false;\n document.getElementById(\"ci2b\").disabled = false;\n document.getElementById(\"ci2c\").disabled = false;\n document.getElementById(\"ci2d\").disabled = false;\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n }\n }", "function disable(div_name, title){\n div_name.disabled = true;\n add_class(div_name,'disabled');\n add_class(title,'disabled-light');\n /*var nodes = div_name.getElementsByTagName('*');\n for(var i = 0; i < nodes.length; i++){\n nodes[i].disabled = true;\n }*/\n }", "function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}", "function byeGuardian() {\n document.getElementById(\"guardianButton\").disabled = true\n}", "function easySettings() {\n document.getElementById(\"ezybtn\").disabled = true; // Turns off easy button\n document.getElementById(\"hrdbtn\").disabled = true; // Turns off hard button\n COUNTDOWN = 30; // Sets the spawnrate to 30\n start = 1; // Sets our game state to 1 (meaning the game will turn on and run)\n}", "function disableControls() {\n $(\"button.play\").attr('disabled', true);\n $(\"select\").attr('disabled', true);\n $(\"button.stop\").attr('disabled', false);\n }", "function setButtons() {\n hitButton.disabled = false;\n standButton.disabled = false;\n continueButton.disabled = true;\n }", "function disable_button() {\n allow_add = false;\n}", "function DisableTranspOptionalLayers(index, id_minus, id_plus, checkboxId)\n{\n\n\tvar checkid = document.getElementById(checkboxId);\n\n\n\tif (checkid.checked == true)//check if the layer is selected\n\t{\n\t\tvar optionOpacity = optionalArray[index];//localte which global opacity layer it is\n\n\t\t//Disables the buttons.\n\t\tif (optionOpacity < maxOpacity) {\n\t\t\tdocument.getElementById(id_minus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_minus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_minus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity > minOpacity) {\n\t\t\tdocument.getElementById(id_plus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_plus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_plus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\t\t}\n\t}\n\telse\n\t{\n\t\t//Disables the buttons.\n\t\tdocument.getElementById(id_minus).disabled = true;\n\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\n\t\tdocument.getElementById(id_plus).disabled = true;\n\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\n\t}\n\n}", "function isGameOver() {\n for (let cat of all_category_ids) {\n let x = document.getElementById(cat + '-score-value').disabled;\n if (x === false) {//category is not disabled\n return false;\n }\n }\n return true;\n}", "function checkWinner() {\n if (player1Score === 20) {\n setMessage(\"player 1 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n } else if (player2Score === 20) {\n setMessage(\"player 2 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n }\n }", "function MEXQ_validate_and_disable() {\n console.log(\" ----- MEXQ_validate_and_disable ----\")\n //console.log(\"mod_MEX_dict\", mod_MEX_dict)\n\n let disable_save_btn = false;\n\n const is_locked = mod_MEX_dict.is_locked;\n const no_subject = !mod_MEX_dict.subject_pk;\n // no_level is only true when vsbo and no level\n const no_level = (setting_dict.sel_dep_level_req && !mod_MEX_dict.lvlbase_pk);\n // when has_partex: show el_MEXQ_input_scalelength, otherwise: show amount\n const show_input_scalelength = (mod_MEX_dict.has_partex);\n let multiple_exams_found = false;\n// --- disable save_btn when is_locked or no subject\n if (is_locked || no_subject) {\n disable_save_btn = true;\n\n// --- disable save_btn when amount has no value, only when not has_partex\n // because of secret exams you can save exam without questions PR2022-05-16\n } else if (!mod_MEX_dict.amount && !mod_MEX_dict.has_partex) {\n //disable_save_btn = true;\n\n// --- disable save_btn when level has no value - only when level required\n } else if(no_level){\n disable_save_btn = true;\n\n } else {\n// --- check if there are multiple exams of this subject and this level\n\n // skip when there are no other exams yet\n for (const data_dict of Object.values(ete_exam_dicts)) {\n // loop through exams\n // skip the current exam\n if(data_dict.map_id !== mod_MEX_dict.map_id){\n // skip other levels - only when level required\n if(!!columns_hidden.lvl_abbrev || data_dict.lvlbase_pk !== mod_MEX_dict.lvlbase_pk){\n multiple_exams_found = true;\n }}}};\n if (multiple_exams_found){\n// --- disable save_btn when multiple exams are found and version has no value\n // TODO give message, it doesnt work yet\n disable_save_btn = !el_MEXQ_input_version.value;\n };\n\n// --- disable level_select when no subject or when not add_new\n if (el_MEXQ_select_level){\n el_MEXQ_select_level.disabled = (is_locked || no_subject || !mod_MEX_dict.is_addnew);\n };\n if (el_MEXQ_input_version){\n el_MEXQ_input_version.disabled = (is_locked || no_subject || no_level);\n };\n// --- disable partex checkbox when no subject or no level\n if (el_MEXQ_input_version){\n el_MEXQ_input_version.disabled = (is_locked || no_subject || no_level);\n };\n if (el_MEXQ_input_amount){\n el_MEXQ_input_amount.disabled = (is_locked || no_subject || no_level);\n };\n if (el_MEXQ_input_scalelength){\n el_MEXQ_input_scalelength.disabled = (is_locked || no_subject || no_level);\n };\n const msg_txt = (mod_MEX_dict.has_partex) ? loc.Awp_calculates_amount : loc.err_list.amount_mustbe_between_1_and_100;\n add_or_remove_class(el_MEX_err_amount, \"text-danger\", false, \"text-muted\" );\n\n //if (el_MEX_err_amount){\n el_MEX_err_amount.innerHTML = msg_txt;\n //};\n add_or_remove_attr(el_MEXQ_input_amount, \"readOnly\", mod_MEX_dict.has_partex, true);\n\n// --- disable save button on error\n if (el_MEXQ_btn_save){\n el_MEXQ_btn_save.disabled = disable_save_btn;\n };\n// --- disable tab buttons\n if (el_MEX_btn_tab_container){\n const btns = el_MEX_btn_tab_container.children;\n for (let i = 0, btn; btn = btns[i]; i++) {\n const data_btn = get_attr_from_el(btn, \"data-btn\");\n if ([\"tab_assign\", \"tab_minscore\", \"tab_keys\"].includes(data_btn)){\n //add_or_remove_attr(btn, \"disabled\", disable_save_btn);\n };\n };\n };\n }", "onDisabled() {\n this.updateInvalid();\n }", "function OnEnable () { \n gameObject.transform.root.gameObject.GetComponent(FPSInputController).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(MouseLook).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(CharacterMotor).enabled = false;\n transform.root.FindChild(playerCameraPrefab).gameObject.SetActive(false);\n \n}", "function plusDisabled() {\r\n minusbtn.removeAttribute(\"disabled\");\r\n if (temp.innerHTML == tempMax - 1) {\r\n plusbtn.setAttribute(\"disabled\", \"true\");\r\n }\r\n }", "function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }", "function disableButtons() {\n let buttons = document.getElementsByTagName(\"button\");\n for (let i = 0; i < buttons.length; i++) {\n if (buttons[i].id !== \"power-button\") buttons[i].disabled = true;\n }\n}", "function disableAllButtons() {\n disableOrEnableButtons(false);\n }", "function buttonDisable(){\r\n\t\tswitch (currentLoc){\r\n\t\t//South off\r\n\t\t\tcase 0: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go SOUTH...\"\r\n\t\t\t\tbreak;\r\n\t\t//South West off\r\n\t\t\tcase 1: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go SOUTH or WEST...\"\r\n\t\t\t\tbreak;\r\n\t\t//South East off\r\n\t\t\tcase 2: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go SOUTH or EAST...\"\r\n\t\t\t\tbreak;\r\n\t\t//East off\r\n\t\t\tcase 5: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go EAST...\"\r\n\t\t\t\tbreak;\r\n\t\t//West off\r\n\t\t\tcase 3: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go WEST...\"\r\n\t\t\t\tbreak;\r\n\t\t//East West North off\r\n\t\t\tcase 9: document.getElementById(\"btnN\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go NORTH, EAST, or WEST...\"\r\n\t\t\t\tbreak;\r\n\t\t//West North off\r\n\t\t\tcase 6: document.getElementById(\"btnN\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go NORTH or WEST...\"\r\n\t\t\t\tbreak;\r\n\t\t//East North off\r\n\t\t\tcase 8: document.getElementById(\"btnN\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"navError\").innerHTML = \"WARNING: You've reached the edge of the island. Don't try to go NORTH, EAST, or WEST...\"\r\n\t\t\t\tbreak;\r\n\t\t\tcase 1000: document.getElementById(\"btnN\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnTake\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnInventory\").disabled = true;\r\n\t\t\t\t\tdocument.getElementById(\"btnGo\").disabled = true;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault: document.getElementById(\"btnN\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnS\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnE\").disabled = false;\r\n\t\t\t\t\tdocument.getElementById(\"btnW\").disabled = false;\r\n\t\t}\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return its head. For example, Given linked list: 1 > 2 > 3 > 4 > 5, and n = 2. After removing the second node from the end, the linked list becomes 1 > 2 > 3 > 5. Note: Given n will always be valid. Try to do this in one pass.
function removeNthFromEnd(head, n) { let current = head; let previous = head; let ahead = head; let count = 0; while (count < n && ahead) { ahead = ahead.next; count++; } while (ahead) { ahead = ahead.next; previous = current; current = current.next } if (previous == current) { return head.next } else if (!head) { return null; } else { previous.next = current.next; return head; } return head; }
[ "removeFromFront() {\n\n if(this.isEmpty()) return null;\n\n var nodeToRemove = this.head;\n\n this.head = this.head.next;\n nodeToRemove.next = null;\n this.counter--;\n return nodeToRemove;\n }", "function removeKthNodeFromEnd(head, k) {\n let firstPointer = head;\n let secondPointer = head;\n while (k >= 1) {\n secondPointer = secondPointer.next;\n k--;\n }\n if (secondPointer === null) {\n head.value = head.next.value;\n head.next = head.next.next;\n //Below is the alternate solution if you wanted to return the head of the\n //Linked List that removed the kth node.\n // let solution = head.next\n // return solution\n }\n while (secondPointer.next !== null) {\n firstPointer = firstPointer.next;\n secondPointer = secondPointer.next;\n }\n firstPointer.next = firstPointer.next.next;\n //Return head if you need it\n //return head\n}", "shift() {\n if (!this.head) return undefined;\n let removed = this.head;\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = removed.next;\n this.head.prev = null;\n removed.next = null;\n }\n\n // removed.next = null;\n this.length--;\n return removed;\n }", "deleteAtHead() {\n \n try {\n \n //check if there is a head \n if (!this.head) {\n return false;\n } else {\n \n //1-2-3-4 and we want to delete 1 and then return list which has 2-3-4\n const item = this.head.value;\n this.head = this.head.next;\n return item;\n }\n \n } catch (err) {\n \n return false;\n \n }\n }", "_getNode(idx) {\n let currentNode = this.head;\n let count = 0;\n\n while (currentNode !== null && count !== idx) {\n currentNode = currentNode.next;\n count++;\n }\n return currentNode;\n }", "getNodeAtIndex(index) {\n //if index is not within list return null\n if (index >= this.length || index < 0) return null;\n //iterate through nodes until finding the one at index\n let currentNode = this.head;\n let currentIndex = 0;\n while (currentIndex !== index) {\n currentNode = currentNode.next;\n currentIndex++;\n }\n return currentNode;\n }", "addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }", "getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }", "insert() {\n let newNode = new Node(1);\n newNode.npx = XOR(this.head, null);\n // logic to update the next pointer of the previous element once the next element is being set.\n\n // (null ^ 1)^ null will nullify null and the output will be 1\n if(this.head !== null) {\n let next = XOR(this.head.npx, null);\n this.head.npx = XOR(newNode, next)\n }\n\n // change the head node to the last node\n this.head = newNode;\n }", "function drop(xs, n) /* forall<a> (xs : list<a>, n : int) -> list<a> */ { tailcall: while(1)\n{\n if ($std_core._int_le(n,0)) {\n return xs;\n }\n else {\n if (xs == null) {\n return Nil;\n }\n else {\n {\n // tail call\n var _x17 = $std_core._int_sub(n,1);\n xs = xs.tail;\n n = _x17;\n continue tailcall;\n }\n }\n }\n}}", "removeLast(){\n if(this.isEmpty()) return new Error(\"The linked list is empty.\");\n let newTail = this.tail.prev;\n newTail.next = null;\n this.tail.prev = null, this.tail.data = null, this.tail = null;\n this.tail = newTail;\n this.size--;\n }", "function kthToLastIterative(head, k) {\n let p1 = head,\n p2 = head\n\n for (let i = 0; i < k; i++) {\n if (!p2) return null //k > size of linked list\n p2 = p2.next\n }\n\n while (p2) {\n p1 = p1.next\n p2 = p2.next\n }\n\n return p1\n}", "getFirstNum() {\n if(this.numList.length > 0){\n return this.numList.dequeue();\n } else {\n return undefined;\n }\n }", "removeTail() {\n // what we're really doing here is removing the last value\n // which would be the least recently used value\n\n const leastUsed = this.tail.prev;\n this.removeNode(leastUsed);\n return leastUsed.key;\n }", "setupLoop(n) {\n const loopTo = this.kToLast2(n);\n if(loopTo === null){\n return loopTo;\n }\n let current = loopTo;\n while(current && current.next){\n current = current.next;\n }\n if(current === loopTo){\n return null;\n }\n current.next = loopTo;\n return this;\n\n }", "addNode(n) {\n if (!this.getNode(n)) {\n const tempNode = node.create({ name: n });\n const clone = this.nodes.slice(0);\n clone.push(tempNode);\n this.nodes = clone;\n\n return tempNode;\n }\n\n return null;\n }", "function moveMinToFront (sList) {\n let current = sList.head; // initialize current and previous for traversal\n let previous = null;\n let min = sList.head; // init min with current so all comparisons are from list (starting w/ 0 could create a bug potentially)\n let minPrev = null;\n if (current === null) { // for empty list, take no action and return null\n return null;\n }\n while (current) { // traversing while 'current' because using 'current.next' means we won't compare last node\n if (current.value < min.value) { // update min and minPrev if current value is smaller\n min = current;\n minPrev = previous;\n }\n previous = current; // continue traversing\n current = current.next;\n }\n if (minPrev !== null) { // if minPrev is null, that means the minimum value was already at start of list, so do nothing\n minPrev.next = min.next; // remove min from the list by pointing its previous node to its next node\n min.next = sList.head; // insert min in list at front by point min's next node to current head\n sList.head = min; // then point head to min\n }\n return sList\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 }", "function getLastSibling(node) {\n let sibling = node;\n\n while (sibling && sibling.next) {\n sibling = sibling.next;\n }\n\n return sibling;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses align mode from direction if specified with hyphen, defaulting to middle if not e.g. 'leftstart' is mode 'start' and 'left' would be the default of 'middle'
function parseAlignMode(direction) { var directionArray = direction.split('-'); if (directionArray.length > 1) { return directionArray[1]; } return 'middle'; }
[ "function positionMode() {\n var attachment = ($attrs.mdPositionMode || 'target').split(' ');\n\n // If attachment is a single item, duplicate it for our second value.\n // ie. 'target' -> 'target target'\n if (attachment.length == 1) {\n attachment.push(attachment[0]);\n }\n\n return {\n left: attachment[0],\n top: attachment[1]\n };\n }", "function alignment(val) {\n\n // check if date\n var parsedDate = Date.parse(val);\n if (isNaN(val) && (!isNaN(parsedDate))) {\n return \"center\";\n }\n\n // check if numeric (remove $ and , and then check if numeric)\n var possibleNum = val.replace(\"$\", \"\");\n possibleNum = possibleNum.replace(\",\", \"\");\n if (isNaN(possibleNum)) {\n return \"left\";\n }\n return \"right\"; // it's a number\n\n }", "function convert_align_middle_to_center(code)\n{\n\tr = /(\\salign=\"middle\")/gi;\n\tr1 = /(\\salign=middle)/gi;\n\tcode = code.replace(r,\" align=\\\"center\\\"\");\n\tcode = code.replace(r1,\" align=center\");\n\treturn code;\n}", "function _isValidAlignment(align) {\n\tif (ratify.isEmpty(align))\n\t\treturn false;\n\n\t//\n\t// dia1 : Diagonal 1\n\t// dia2 : Diagonal 2\n\t// ttb : top to bottom\n\t// btt : bottom to top\n\t// ltr : left to right\n\t// rtl : right to left\n\t//\n\tif (['dia1', 'dia2', 'ttb', 'btt', 'ltr', 'rtl'].indexOf(align.toLowerCase()) > -1)\n\t\treturn true;\n\n\treturn false;\n}", "align(text, length, alignment, filler) {\n if (!filler) filler = SPACE;\n if (!alignment)\n ArgumentNullException(\"alignment\");\n switch (alignment) {\n case \"c\":\n case \"center\":\n return S.center(text, length, filler);\n case \"l\":\n case \"left\":\n return S.ljust(text, length, filler);\n break;\n case \"r\":\n case \"right\":\n return S.rjust(text, length, filler);\n default:\n ArgumentException(\"alignment: \" + alignment);\n }\n }", "function parseMeasureMode(x)\n{\n\tswitch (x)\n\t{\n\t\tcase PRECISE_MEASURE_ID:\n\t\tmyMeasureMode = PRECISE_MEASURE;\n\t\treturn NO_ERROR;\n\t\tbreak;\n\t\t\n\t\tcase IMPRECISE_MEASURE_ID:\n\t\tmyMeasureMode = IMPRECISE_MEASURE;\n\t\treturn NO_ERROR;\n\t\tbreak;\n\t\t\n\t\tdefault:\n\t\treturn WRONG_MEASURE_MODE;\n\t\tbreak;\n\t}\n}", "function validateHorizontalAlignment(align) {\n var ALIGNMENTS = ['left', 'center', 'right'];\n var DEFAULT = acf.get('rtl') ? 'right' : 'left';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function validateMatrixAlignment(align) {\n var DEFAULT = 'center center';\n\n if (align) {\n var _align$split = align.split(' '),\n _align$split2 = _slicedToArray(_align$split, 2),\n y = _align$split2[0],\n x = _align$split2[1];\n\n return validateVerticalAlignment(y) + ' ' + validateHorizontalAlignment(x);\n }\n\n return DEFAULT;\n } // Dependencies.", "_guessWidgetAlignment(priceElement) {\n if (!priceElement) return 'left'; // default\n const textAlignment = window.getComputedStyle(priceElement).textAlign;\n /* Start is a CSS3 value for textAlign to accommodate for other languages which may be\n\t\t * RTL (right to left) for instance Arabic. Since the sites we are adding the widgets to are mostly,\n\t\t * if not all in English, it will be LTR (left to right), which implies that 'start' and 'justify' would mean 'left'\n\t\t */\n if (textAlignment === 'start' || textAlignment === 'justify') return 'left';\n /*\n\t\t * end is a CSS3 value for textAlign to accommodate for other languages which may be RTL (right to left), for instance Arabic\n\t\t * Since the sites we are adding to are mostly, if not all in English, it will be LTR (left to right), hence 'right' at the end\n\t\t */\n return textAlignment === 'end' ? 'right' : textAlignment;\n }", "function parseAnchor(anchor, isRtl) {\n let [side, align] = anchor.split(' ');\n if (!align) {\n align = includes(block, side) ? 'start' : includes(inline, side) ? 'top' : 'center';\n }\n return {\n side: toPhysical(side, isRtl),\n align: toPhysical(align, isRtl)\n };\n}", "function validateVerticalAlignment(align) {\n var ALIGNMENTS = ['top', 'center', 'bottom'];\n var DEFAULT = 'top';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function tabAlign(currTblDOM){ \r\n //Changing paragraphs above space\r\n var alignParas = currTblDOM.evaluateXPathExpression(\"//p[@data-align]\");\r\n var alignParasLen = alignParas.length;\r\n for (var x = 0; x < alignParasLen; x++){\r\n var currAlignPara = alignParas[x].xmlAttributes.itemByName(\"data-align\").value;\r\n if (!(currAlignPara == '')){\r\n var charAlignOn = alignParas[x].xmlAttributes.itemByName(\"data-align\").value;\r\n var charAlignAt = alignParas[x].xmlAttributes.itemByName(\"data-align-left-width\").value;\r\n try{\r\n if(charAlignOn == '.'){\r\n alignParas[x].paragraphs[0].tabStops.add({alignment:TabStopAlignment.CHARACTER_ALIGN, alignmentCharacter:charAlignOn, position:charAlignAt});\r\n //alignParas[x].paragraphs[0].leftIndent = 0;\r\n alignParas[x].paragraphs[0].firstLineIndent = 0;\r\n alignParas[x].paragraphs[0].rightIndent = 0; \r\n }\r\n else if(charAlignOn == ','){\r\n //alignParas[x].paragraphs[0].justification = Justification.RIGHT_ALIGN;\r\n alignParas[x].paragraphs[0].tabStops.add({alignment:TabStopAlignment.CHARACTER_ALIGN, alignmentCharacter:charAlignOn, position:charAlignAt});\r\n alignParas[x].paragraphs[0].leftIndent = 0;\r\n alignParas[x].paragraphs[0].firstLineIndent = 0;\r\n alignParas[x].paragraphs[0].rightIndent = parseInt(alignParas[x].xmlAttributes.itemByName(\"data-align-right-width\").value); \r\n }\r\n else if(charAlignOn == '('){\r\n alignParas[x].paragraphs[0].tabStops.add({alignment:TabStopAlignment.CHARACTER_ALIGN, alignmentCharacter:charAlignOn, position:charAlignAt});\r\n //alignParas[x].paragraphs[0].leftIndent = 0;\r\n alignParas[x].paragraphs[0].firstLineIndent = 0;\r\n alignParas[x].paragraphs[0].rightIndent = 0; \r\n }\r\n else if(charAlignOn == '±' || charAlignOn == '&#x00B1;' || charAlignOn == 'prm'){\r\n charAlignOn = '±';\r\n //below is the temp solution for p/m align\r\n var tcha = alignParas[x].paragraphs[0].characters;\r\n var tchaLen = tcha.length;\r\n if (tchaLen > 0){\r\n var plsMinusCharPosition = 0;\r\n for (var a = 0; a < tchaLen; a ++){\r\n if (tcha[a].contents == '±'){\r\n plsMinusCharPosition = a;\r\n break;\r\n }\r\n }\r\n var startCharOffset = tcha[0].horizontalOffset;\r\n var lastCharBeforePlusRMinusOffset = tcha[plsMinusCharPosition - 1].endHorizontalOffset;\r\n var diff = lastCharBeforePlusRMinusOffset - startCharOffset;\r\n alignParas[x].paragraphs[0].leftIndent = charAlignAt - diff; \r\n }\r\n//~ alignParas[x].paragraphs[0].recompose();\r\n//~ alignParas[x].paragraphs[0].tabStops.add({alignmentCharacter:'±', alignment:TabStopAlignment.CHARACTER_ALIGN, position:charAlignAt});\r\n//~ alignParas[x].paragraphs[0].firstLineIndent = 0;\r\n//~ alignParas[x].paragraphs[0].rightIndent = 0; \r\n }\r\n } catch (e){}\r\n }\r\n }\r\n }", "find_initial_direction() {\n switch (maze.start_dir) {\n case ActorDirection.left:\n this.direction = KeyboardCodeKeys.left;\n break;\n case ActorDirection.right:\n this.direction = KeyboardCodeKeys.right;\n break;\n case ActorDirection.up:\n this.direction = KeyboardCodeKeys.up;\n break;\n case ActorDirection.down:\n this.direction = KeyboardCodeKeys.down;\n break;\n }\n }", "setDirection (dir, lengths) {\n this[dir.prop] = {\n ...lengths[0] && { before: lengths[0] },\n ...lengths[1] && { size: lengths[1] },\n ...lengths[2] && { after: lengths[2] }\n }\n }", "find_initial_direction() {\n this.direction = maze.start_dir;\n }", "defineDirection() {\n var posRoad = this.road[this.partRoad];\n if (Number(this.pos.getx()) == Number(posRoad.getx())) {\n if (Number(this.pos.gety()) < Number(posRoad.gety())) {\n return SOUTH;\n } else {\n return NORTH;\n }\n }\n if (Number(this.pos.gety()) == Number(posRoad.gety())) {\n if (Number(this.pos.getx()) < Number(posRoad.getx())) {\n return EAST;\n } else {\n return WEST;\n }\n }\n return -1;\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 offsets() {\n var offsets = ($attrs.mdOffset || '0 0').split(' ').map(parseFloat);\n if (offsets.length == 2) {\n return {\n left: offsets[0],\n top: offsets[1]\n };\n } else if (offsets.length == 1) {\n return {\n top: offsets[0],\n left: offsets[0]\n };\n } else {\n throw Error('Invalid offsets specified. Please follow format <x, y> or <n>');\n }\n }", "function determineOrientation (event, tabsetIndex) {\n var key = event.keyCode;\n var vertical = tablist[tabsetIndex].getAttribute('aria-orientation') == 'vertical';\n var proceed = false;\n\n if (vertical) {\n if (key === keys.up || key === keys.down) {\n event.preventDefault();\n proceed = true;\n }\n }\n else {\n if (key === keys.left || key === keys.right) {\n proceed = true;\n }\n }\n\n if (proceed) {\n switchTabOnArrowPress(event, tabsetIndex);\n }\n }", "function handleTranspose(mode) {\r\n console.log(\"Transpose: \"+mode)\r\n let modeOption\r\n if (mode=='up') {\r\n modeOption = 1\r\n }\r\n else if(mode=='down'){\r\n modeOption = -1\r\n }\r\n //walk through words and checking type chord\r\n for (let i = 0; i < words.length; i++) {\r\n let sharpFlatNote = 1\r\n \r\n if (words[i].type===\"chord\"){\r\n \r\n //console.log(\"Before: \" + words[i].word)\r\n if(words[i].word.includes(\"#\") || words[i].word.includes(\"b\")){\r\n sharpFlatNote = 2\r\n }\r\n\r\n if(words[i].word.includes(\"/\")){\r\n for(let j =0;j<semitones.length;j++){\r\n\r\n if (words[i].word.substring(words[i].word.indexOf(\"/\")+1,words[i].word.length)==semitones[j].chord) {\r\n words[i].word = words[i].word.replace(semitones[j].chord,semitones[((j+modeOption)+12)%12].chord)\r\n break\r\n }\r\n }\r\n }\r\n\r\n for (let k =0; k<semitones.length;k++) {\r\n //console.log(words[i].word)\r\n if (words[i].word.substring(0,sharpFlatNote)==semitones[k].chord) {\r\n words[i].word = words[i].word.replace(semitones[k].chord, semitones[((k+modeOption)+12)%12].chord)\r\n break\r\n }\r\n else if (words[i].word.substring(0,sharpFlatNote)==semitones[k].flat) {\r\n words[i].word = words[i].word.replace(semitones[k].flat,semitones[((k+modeOption)+12)%12].chord)\r\n break\r\n }\r\n //console.log(\"after replace: \"+words[i].word)\r\n }\r\n } \r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FYI The extra complexity in this method is due to the fact that for the block API you are sending the full list rather than individual items you want to unblock / unblock and that gets interesting if you kick off a subsequent request while a previous is still pending and, for example, the previous may fail whereas the subsequent (which includes the block/unblock from the previous) may succeed.
function blockUnblock(_block, peerIds) { if (typeof _block !== 'boolean') { throw new Error('Please provide _block as a boolean.'); } if (!isMultihash(peerIds) && !Array.isArray(peerIds)) { throw new Error('Either provide a single peerId as a multihash or an array of peerId ' + 'multihashes.'); } if (Array.isArray(peerIds)) { peerIds.forEach(peerId => { if (!isMultihash(peerId)) { throw new Error('If providing an array of peerIds, each item must be a multihash.'); } }); } checkAppSettings(); let peerIdList = typeof peerIds === 'string' ? [peerIds] : peerIds; if (_block && app.profile && peerIdList.includes(app.profile.id)) { throw new Error('You cannot block your own node.'); } // de-dupe peerId list peerIdList = Array.from(new Set(peerIdList)); let blockedNodes; // if _block is false, semantically this means unblockedNodes if (_block) { blockedNodes = [ ...( latestSettingsSave && latestSettingsSave.state() === 'pending' ? lastSentBlockedNodes : app.settings.get('blockedNodes') ), ...peerIdList, ]; pendingBlocks = [...pendingBlocks, ...peerIdList]; pendingUnblocks = pendingUnblocks.filter(peerId => !peerIdList.includes(peerId)); } else { const filterList = latestSettingsSave && latestSettingsSave.state() === 'pending' ? lastSentBlockedNodes : app.settings.get('blockedNodes'); blockedNodes = filterList.filter(peerId => !peerIdList.includes(peerId)); pendingUnblocks = [...pendingUnblocks, ...peerIdList]; pendingBlocks = pendingBlocks.filter(peerId => !peerIdList.includes(peerId)); } lastSentBlockedNodes = [...blockedNodes]; latestSettingsSave = $.ajax({ type: 'PATCH', url: app.getServerUrl('ob/settings/'), data: JSON.stringify({ blockedNodes }), dataType: 'json', }).done(() => { app.settings.set('blockedNodes', blockedNodes); const blocked = []; const unblocked = []; pendingBlocks = pendingBlocks.filter(peerId => { if (blockedNodes.includes(peerId)) { blocked.push(peerId); return false; } return true; }); pendingUnblocks = pendingUnblocks.filter(peerId => { if (!blockedNodes.includes(peerId)) { unblocked.push(peerId); return false; } return true; }); if (blocked.length) { events.trigger('blocked', { peerIds: blocked }); } if (unblocked.length) { events.trigger('unblocked', { peerIds: unblocked }); } }).fail(xhr => { if (latestSettingsSave && latestSettingsSave.state() === 'pending') return; const reason = xhr.responseJSON && xhr.responseJSON.reason || ''; const bn = app.settings.get('blockedNodes'); const failedBlocks = pendingBlocks.filter(peerId => !bn.includes(peerId)); const failedUnblocks = pendingUnblocks.filter(peerId => bn.includes(peerId)); pendingBlocks = []; pendingUnblocks = []; if (failedBlocks.length) { events.trigger('blockFail', { peerIds: failedBlocks, reason, }); } if (failedUnblocks.length) { events.trigger('unblockFail', { peerIds: failedUnblocks, reason, }); } if (failedBlocks.length || failedUnblocks.length) { let title; let body; if (failedBlocks.length && failedUnblocks.length) { title = app.polyglot.t('block.errorModal.titleUnableToBlockUnblock'); body = `${app.polyglot.t('block.errorModal.blockFailedListHeading')}<br /><br />` + `<div class="txCtr">${failedBlocks.join('<br />')}</div><br />` + `${app.polyglot.t('block.errorModal.unblockFailedListHeading')}<br /><br />` + `<div class="txCtr">${failedUnblocks.join('<br />')}</div>`; } else if (failedUnblocks.length) { title = app.polyglot.t('block.errorModal.titleUnableToUnblock'); body = `${app.polyglot.t('block.errorModal.unblockFailedListHeading')}<br /><br />` + `<div class="txCtr">${failedUnblocks.join('<br />')}</div>`; } else { title = app.polyglot.t('block.errorModal.titleUnableToBlock'); body = `${app.polyglot.t('block.errorModal.blockFailedListHeading')}<br /><br />` + `<div class="txCtr">${failedBlocks.join('<br />')}</div>`; } if (reason) { body += `<br />${app.polyglot.t('block.errorModal.reason', { reason })}`; } openSimpleMessage(title, '', { messageHtml: body }); } }); events.trigger(_block ? 'blocking' : 'unblocking', { peerIds: peerIdList }); }
[ "function showBlockList () {\r\n $(\"#blocklist\").children().remove();\r\n var i=1;\r\n $.each(BLOCKER.getBlockedSites(), function (index, value) {\r\n\t\t\t\t\r\n\t\t$(\"#blocklist\").append(\"<li id='site-\"+i+\"'> <input type='button' class='pure-button button-remove' id='unblock-\"+i+\"' value='unblock' /> \" + index + \"</li>\");\r\n\t\t$(\"#unblock-\"+i).click(function () {\r\n\t\t\tBLOCKER.removeBlockedSite(index);\r\n\t\t\tshowBlockList();\r\n\t\t});\r\n\t\ti++;\r\n });\r\n}", "async unblockUser(user, userToUnblock) {\n const userId = extractUserId(user);\n const userIdToUnblock = extractUserId(userToUnblock);\n await this._client.callApi({\n url: `users/${userId}/blocks/${userIdToUnblock}`,\n method: 'DELETE',\n scope: 'user_blocks_edit'\n });\n }", "unfreeze() {\n //call api to unfreeze listing\n api.get(`/listing/unfreeze/${this.props.Item.listing_id}`)\n .then(function (result) {\n console.log(result);\n window.history.go(0);\n });\n\n }", "async function loopBlocks(headBlockNumber){\n try {\n let blockList = [];\n let delay = 50;\n for (let callNumber = 0; callNumber <= 10; callNumber++){\n //uses helper function to time out each endpoint call. without helper function, endpoint returns overload error\n await setAsyncTimeout(() => {\n //calls single instance of getBlock with (headblocknumber - # of calls made so far)\n getBlock(headBlockNumber - callNumber).then(function(currentBlock){\n //currentBlock is equal to a single block returned at the current block number\n blockList.push(currentBlock);\n })\n }, delay * callNumber);\n }\n //returning block list which is what we return to the UI\n return await blockList;\n } catch(err){\n let errorMessage = `Controller Error: ${err.message}`;\n return errorMessage;\n } \n}", "static update(request, data, block) {\n if (Server.offline) {\n Pending.dbget((pending) => {\n if (request === \"comment\") {\n pending.comment = pending.comment || {};\n pending.comment[data.attach] = data.comment;\n Server.pending.comments[data.attach] = data.comment\n } else if (request === \"approve\") {\n // update list of offline requests\n if (data.request.includes(\"approve\")) {\n pending.approve = pending.approve || {};\n pending.approve[data.attach] = data.request\n } else if (data.request.includes(\"flag\")) {\n pending.flag = pending.flag || {};\n pending.flag[data.attach] = data.request\n };\n\n // apply request locally\n if (data.request === \"approve\") {\n let index = Server.pending.unapproved.indexOf(Server.pending.attach);\n if (index !== -1) Server.pending.unapproved.splice(index, 1);\n\n if (!Server.pending.approved.includes(data.attach)) {\n Server.pending.approved.push(data.attach)\n }\n } else if (data.request === \"unapprove\") {\n let index = Server.pending.approved.indexOf(data.attach);\n if (index !== -1) Server.pending.approved.splice(index, 1);\n\n if (!Server.pending.unapproved.includes(data.attach)) {\n Server.pending.unapproved.push(data.attach)\n }\n } else if (data.request === \"flag\") {\n let index = Server.pending.unflagged.indexOf(Server.pending.attach);\n if (index !== -1) Server.pending.unflagged.splice(index, 1);\n\n if (!Server.pending.flagged.includes(data.attach)) {\n Server.pending.flagged.push(data.attach)\n }\n } else if (data.request === \"unflag\") {\n let index = Server.pending.flagged.indexOf(data.attach);\n if (index !== -1) Server.pending.flagged.splice(index, 1);\n\n if (!Server.pending.unflagged.includes(data.attach)) {\n Server.pending.unflagged.push(data.attach)\n }\n }\n };\n\n // store offline requests\n Pending.dbput(pending);\n\n // inform caller, other tabs\n if (block) {\n block(Server.pending);\n Events.broadcast({type: \"pending\", value: Server.pending})\n }\n })\n } else {\n post(request, data, (pending) => {\n block(pending);\n Pending.load(pending)\n })\n }\n }", "receiveBlock(Block){\n \n // need to handle the JSON file better // TODO\n // need to rehash the block to make sure the hash is valid\n if( this.ValidateBlock(Block)){\n this.list.push(Block);\n console.log('received Block is valid and added to the Blockchain')\n return true;\n }\n return false;\n\n }", "updateListForBlock(block, pW) {\n // ignore if not a list block\n if (!block.isList()) {\n return;\n }\n // the node representing the parent block\n const parentNode = this.nodeFromElement(block.id);\n // get the focused list for this block\n const focusedOptionId = this.focusedOptions[block.id];\n // get only the options that are enabled for this block\n const enabled = Object.keys(block.options).filter(opt => block.options[opt]);\n // if block list is empty add a single placeholder block\n if (enabled.length === 0) {\n const node = this.emptyListBlockFactory(block.id, parentNode);\n node.set({\n bounds: new Box2D(0, kT.blockH + 1, pW, kT.optionH),\n fill: this.fillColor(block.id),\n updateReference: this.updateReference,\n listParentBlock: block,\n listParentNode: parentNode,\n hidden: block.isHidden(),\n });\n } else {\n // find the index of the focused list option, or default the first one\n let focusedIndex = enabled.findIndex(blockId => focusedOptionId === blockId);\n if (focusedIndex < 0) {\n focusedIndex = 0;\n }\n enabled.forEach((blockId, index) => {\n // ensure we have a hash of list nodes for this block.\n let nodes = this.listNodes[block.id];\n if (!nodes) {\n nodes = this.listNodes[block.id] = {};\n }\n // get the block in the list\n const listBlock = this.getListBlock(blockId);\n\n // create node as necessary for this block\n let listNode = nodes[blockId];\n if (!listNode) {\n listNode = nodes[blockId] = this.listBlockFactory();\n parentNode.appendChild(listNode);\n }\n // update position and other visual attributes of list part\n listNode.set({\n bounds: new Box2D(0, kT.blockH + 1 + index * kT.optionH, pW, kT.optionH),\n text: listBlock.metadata.name,\n fill: this.fillColor(block.id),\n color: this.fontColor(block.id),\n updateReference: this.updateReference,\n listParentBlock: block,\n listParentNode: this.nodeFromElement(block.id),\n listBlock,\n optionSelected: index === focusedIndex,\n hidden: block.isHidden(),\n });\n });\n }\n }", "removeValidationRequest(address){\r\n //removes item in index reference array and mempool array\r\n let indexToFind = this.walletList[address];\r\n delete this.walletList[address];\r\n delete this.mempool[indexToFind];\r\n\r\n //clear timeouts\r\n clearTimeout(this.timeoutRequests[address]);\r\n delete this.timeoutRequests[address]\r\n }", "update(wasActive: boolean) : void {\n // The time to subtract is calculated as the time since the last update, if applicable.\n const totalTimeToSubtract : number = this.lastTimeUpdate ? Date.now() - this.lastTimeUpdate : 0;\n\n // Subtract from the unblock interrupt times, if applicable.\n let unblockTimeSubtracted : number = 0;\n if (wasActive)\n {\n for (let i=0; i<this.timesUntilUnblockDisruptions.length; ++i)\n {\n const initial = this.timesUntilUnblockDisruptions[i];\n const subtracted = initial > totalTimeToSubtract ? totalTimeToSubtract : initial;\n\n this.timesUntilUnblockDisruptions[i] -= subtracted;\n\n unblockTimeSubtracted = Math.max(unblockTimeSubtracted, subtracted);\n }\n }\n\n // Use the remaining time differfence to subtract from the lockdown time.\n const lockdownSubtractTime = Math.min(totalTimeToSubtract - unblockTimeSubtracted, this.lockdownRemainingTime);\n if (this.lockdownRemainingTime > 0)\n this.lockdownRemainingTime -= lockdownSubtractTime;\n\n\n // Finally, update the last update time to now\n this.lastTimeUpdate = new Date();\n\n }", "getBlockchain(lastBlock = undefined) {\n console.log('getBlockchain');\n if(this.blockchainState != 'init' && this.blockchainState != \"stop\") return;\n console.log(this.blockchainState);\n for(var address of Object.keys(this.nodeRoom)) {\n var socket = this.nodeRoom[address].socket;\n socket.emit('getLastBlockID');\n }\n setTimeout(() => {\n if(this.lastBlockIDArray && this.lastBlockIDArray.length) {\n this.blockchainState = 'processing';\n console.log(this.blockchainState);\n this.lastBlockIDArray.sort((a, b) => Number(b.id) - Number(a.id));\n console.log('last block: ' + this.lastBlockIDArray[0].id)\n this.lastBlockIDArray[0].socket.emit('getBlockchain', lastBlock);\n delete this.lastBlockIDArray;\n this.blockchain_receive_timer = setTimeout(() => {\n console.log('getBlockchain again');\n this.blockchainState = 'stop';\n this.getBlockchain(lastBlock);\n }, config.timegap_for_send_blocks * 10);\n }\n else {\n this.getBlockchain(lastBlock);\n }\n }, 1000);\n }", "function refreshTable() {\n deleteAllRowsExceptFirst();\n chrome.storage.sync.get(['blocklist'], function(result) {\n blocklist = result.blocklist;\n if (typeof blocklist !== 'undefined') {\n if (Object.keys(blocklist).length == 0) {\n $('h3').text('The block list is empty!');\n return;\n }\n $('h3').text('Block List');\n for (var id in blocklist) {\n user = blocklist[id];\n lastRow = $('div.mp-blocklist > table > tr:last');\n $('div.mp-blocklist table tr:last')\n .after(`<tr>` +\n `<td>${user.id}</td>` +\n `<td>${user.screenName}</td>` +\n `<td><button class=\"unblock\" id=\"unblock-${user.id}\">Unblock</button></td>` +\n `</tr>`);\n }\n addButtonHandlers();\n } else {\n $('h3').text('There is no blocklist yet!');\n }\n });\n}", "function updateBlockMedia(message){\n\tif(\"blockMedia\" in message){\n\t\tconsole.log(\"blocking\");\n\t\tblocked =1;\n\t}else if(\"unblockMedia\" in message){\n\t\tconsole.log(\"not blocking\");\n\t\tblocked =0;\n\t}\n}", "deSelectBlocks() {\n this.getNavigableBlocks().setEach('isSelected', false);\n }", "async function mineAndSubmitBlock(){\n //PROCESS DATA\n let obj = dataPool.pop()\n const encryptedData = await encryptData(pubKey, obj.data)\n const d = await new Data(encryptedData, address, obj.meta)\n \n //MINE NEW BLOCK\n let lastBlock = await storage.getItem(nonce.toString());\n newBlockHash = await hash(lastBlock.blockHash + d.encryptedData + nonce)\n const b = await new Block(d, newBlockHash.toString(), lastBlock.blockHash)\n const myBlockchain = await addBlock(b)\n let storedBlock = await storage.getItem(nonce.toString());\n let blockNum = storedBlock.nonce + 1 \n console.log(\"block number \"+ blockNum +\" block hash is \" + JSON.stringify(storedBlock.blockHash))\n\n //SUBMIT NEW BLOCK TO ROOTCHAIN\n let newBlock = `0x${storedBlock.blockHash}`\n plasmaContract.methods.submitBlock(newBlock).send({from: operatorAddr}, function(error, transactionHash){\n console.log(\"blockhash submitted to rootchain with hash:\" + transactionHash)\n });\n}", "function removeCodeblock() {\r\n\r\n // Disable the codeblock buttons so they can't be hit multiple times.\r\n changeCodeblockButtons(false);\r\n jQuery('#codeblock_remove').button('option', 'label', 'Removing...');\r\n\r\n // Request the server removes the codeblock. This will also remove any\r\n // timeslots that use this codeblock.\r\n jQuery.post(ajaxurl, {\r\n action : 'tw-ajax-codeblock-remove',\r\n block_id : current_block_id\r\n }, function(response) {\r\n\r\n // Re-enable the codeblock buttons upon response\r\n changeCodeblockButtons(true);\r\n jQuery('#codeblock_remove').button('option', 'label', 'Remove');\r\n\r\n // Only update the array if the request was successful.\r\n if (response.removed) {\r\n // Remove the entry from the codeblock array\r\n delete codeblocks[response.block_id];\r\n\r\n // Select the tab that comes before this one in the sequence (this\r\n // will cause the form to be updated with information from a new\r\n // codeblock)\r\n jQuery('#codeblock_tabs').tabs(\"select\",\r\n \"#codeblock_tab_\" + response.prev_id);\r\n\r\n // Remove the current tab as well.\r\n jQuery('#codeblock_tabs').tabs(\"remove\",\r\n \"#codeblock_tab_\" + response.block_id);\r\n\r\n current_block_id = response.prev_id;\r\n\r\n // Refresh the calendar, in case any timeslots have\r\n // been removed.\r\n jQuery('#calendar').weekCalendar('refresh');\r\n }\r\n });\r\n}", "handleUnstakingEvents() {\n // Updating locked gold balances if the locking time has elapsed.\n if (this.unstakingEvents.has(this.chainLength)) {\n let q = this.unstakingEvents.get(this.chainLength);\n q.forEach(({clientID, amount}) => {\n let totalStaked = this.stakeBalances.get(clientID);\n console.log(`Unstaking ${totalStaked} for ${clientID}`);\n this.stakeBalances.set(clientID, totalStaked - amount);\n });\n\n // No longer need to track these locking events.\n this.unstakingEvents.delete(this.chainLength);\n }\n }", "function getExpiredDealsAndUpdateRewards() {\n\n var body = {};\n nouvoController.getExpiredDeals(function (error, response) {\n if (error) {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n } else {\n var stakeCalculated = [];\n response.body.responseData = functions.decryptData(response.body.responseData);\n if (response != null && response.body != null && response.body.responseData != null) {\n \n if (response.body.responseData.length > 0) {\n each(response.body.responseData,\n function (deal, next) {\n\n var params = [deal.merchantId, deal.startDate, deal.endDate];\n var query = 'call GetStakeOfAllUsersForMerchant(?,?,?)';\n\n var stakeForMerchant = {};\n stakeForMerchant.merchantId = deal.merchantId;\n stakeForMerchant.endDate = deal.endDate;\n stakeForMerchant.id = deal.id;\n con.query(query, params, function (err, result) {\n if (err) {\n setNextScheduledBatchInterval();\n }\n else {\n if (result[0].length > 0) {\n stakeForMerchant.stake = result[0];\n stakeCalculated.push(stakeForMerchant);\n next(err);\n }\n else {\n stakeForMerchant.stake = [];\n stakeCalculated.push(stakeForMerchant);\n next(err);\n }\n \n }\n });\n // next(err);\n },\n function (err) {\n if (!err) {\n // stakeCalculated\n // setNextScheduledBatchInterval();\n nouvoController.distributeRewards(stakeCalculated, function (error, response) {\n if (error) {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n } else {\n setNextScheduledBatchInterval();\n }\n });\n }\n })\n }\n else {\n setNextScheduledBatchInterval();\n }\n\n }\n else {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n }\n }\n })\n}", "is_blocker() {\n return false;\n }", "function stopReqs(req){\n switch(req){\n case 'pp': $.each(reqs['bp'],function(k,v){\n v.abort();\n delete reqs['bp']['#'+k];\n // $('#'+k).data('loading',true);\n\n });\n $.each(reqs['pd'],function(k,v){\n v.abort();\n delete reqs['pd']['#'+k];\n // $('#'+k).data('loading',true);\n\n });\n break;\n case 'bp': $.each(reqs['pp'],function(k,v){\n v.abort();\n delete reqs['pp']['#'+k];\n // $('#'+k).data('loading',true);\n\n });\n $.each(reqs['pd'],function(k,v){\n v.abort();\n delete reqs['pd']['#'+k];\n // $('#'+k).data('loading',true);\n\n });\n break;\n case 'pd': $.each(reqs['bp'],function(k,v){\n v.abort();\n delete reqs['bp']['#'+k];\n // $('#'+k).data('loading',true);\n\n });\n $.each(reqs['pp'],function(k,v){\n v.abort();\n delete reqs['pp']['#'+k];\n // $('#'+k).data('loading',true);\n });\n break;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create virtual table of cells with all cells, including span cells.
function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } }
[ "function generateTable() {\n emptyTable();\n generateRows();\n generateHead();\n generateColumns();\n borderWidth();\n}", "generateCells(){\n for(let row = 0; row<this.rows; row++){\n this.cells[row] = []\n for(let column = 0; column<this.columns; column++){\n this.cells[row][column] = new Cell({column, row, height: this.cellSize, width: this.cellSize})\n this.cells[row][column].showBlocked()\n }\n }\n }", "function buildTable() {\n var table = document.getElementById(\"propertiesTable\");\n for (var i = 0; i < Properties.size; i++) {\n var eth = 1000000000000000000;\n var row = table.insertRow(i+1);\n var cell0 = row.insertCell(0);\n var cell1 = row.insertCell(1);\n var cell2 = row.insertCell(2);\n var cell3 = row.insertCell(3);\n cell0.innerHTML = \"<b><font size=\\\"4\\\"><i class=\\\"ni ni-building\\\"></i>&nbsp;&nbsp;&nbsp;\" + Properties.get(i)[0] + \"</b></font>\";\n cell1.innerHTML = Properties.get(i)[1];\n var boughtTokens = Properties.get(i)[1] - Properties.get(i)[3];;\n cell2.innerHTML = boughtTokens;\n cell3.innerHTML = boughtTokens * Properties.get(i)[2].toNumber()/eth;\n\n }\n}", "function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }", "function write(width, height, table) {\n w = width;\n h = height;\n for (var k = 0; k < h; k++) {\n createElement('tr', table);\n for (var l = 0; l < w; l++)\n createElement('td', table.children[k]);\n }\n}", "function sizeTable() {\n\t\tvar emulator = $('.emulator'),\n\t\t\t\ttable = emulator.find('.grid'),\n\t\t\t\tdimensions = disco.controller.getDimensions(),\n\t\t\t\txMax = dimensions.x,\n\t\t\t\tyMax = dimensions.y,\n\t\t\t\tstyles = [],\n\t\t\t\theight, width, cellWidth, cellHeight;\n\n\t\ttable.css({\n\t\t\t'height': '100%',\n\t\t\t'width': '100%',\n\t\t});\n\n\t\tif (xMax < yMax) {\n\t\t\ttable.css('width', table.outerHeight()/yMax);\n\t\t}\n\t\telse if (xMax > yMax) {\n\t\t\ttable.css('height', table.outerWidth()/xMax);\n\t\t}\n\n\t\t// height = emulator.height();\n\t\t// width = emulator.width();\n\n\t\t// // Determine the cell height to keep each cell square\n\t\t// cellWidth = width / dimensions.x;\n\t\t// cellHeight = height / dimensions.y;\n\t\t// if (cellWidth < cellHeight) {\n\t\t// \tcellHeight = cellWidth;\n\t\t// } else {\n\t\t// \tcellWidth = cellHeight;\n\t\t// }\n\n\t\t// // Set styles\n\t\t// $('#grid-dimensions').html('table.grid td { width: '+ cellWidth +'px; height: '+ cellHeight +'px }');\n\t}", "createRangeBySelectedCells() {\n const sq = this.wwe.getEditor();\n const range = sq.getSelection().cloneRange();\n const selectedCells = this.getSelectedCells();\n const [firstSelectedCell] = selectedCells;\n const lastSelectedCell = selectedCells[selectedCells.length - 1];\n\n if (selectedCells.length && this.wwe.isInTable(range)) {\n range.setStart(firstSelectedCell, 0);\n range.setEnd(lastSelectedCell, lastSelectedCell.childNodes.length);\n sq.setSelection(range);\n }\n }", "function drawTable(){\n var wrapper = document.getElementById(\"table-wrapper\");\n var table = document.createElement(\"TABLE\");\n\n table.id = \"game-table\";\n wrapper.appendChild(table);\n\n var t = document.getElementById(\"game-table\");\n\n for(var x=0;x<colorArray.length;x++){\n var tr = document.createElement(\"TR\");\n tr.id = \"row\" + x;\n t.appendChild(tr);\n for(var y=0;y<colorArray.length;y++){\n var r = document.getElementById(\"row\" + x);\n var node = colorArray[x][y].print(\"cell\"+x+\"-\"+y);\n r.appendChild(node);\n }\n }\n }", "function createTable() {\n var main = $('#region-main');\n var table = $('<table></table>');\n table.attr('id', 'local-barcode-table');\n table.addClass('generaltable');\n table.addClass('local-barcode-table');\n\n var thead = table.append('<thead></thead>');\n var header = thead.append('<tr></tr>');\n header.html('<th colspan=\"8\" class=\"local-barcode-th-left local-barcode-sm-hide\">' + strings[1] +\n ' - (<span id=\"local_barcode_id_count\">' +\n '0</span> ' + strings[6] + ')</th>' +\n '<th colspan=\"17\" class=\"local-barcode-th-center\">' + strings[0] + '</th>' +\n '<th colspan=\"5\" class=\"local-barcode-th-right\">' + strings[8] +\n '(<span id=\"local_barcode_id_submit_count\">0</span>)</th>');\n table.append('<tbody id=\"tbody\"></tbody>');\n\n main.append(table);\n }", "function buildHtmlTable() {\n\tvar columns = addAllColumnHeaders(myList);\n\n\tfor ( var i = 0; i < myList.length; i++) {\n\t\tvar row$ = $('<tr/>');\n\t\tfor ( var colIndex = 0; colIndex < columns.length; colIndex++) {\n\t\t\tvar cellValue = myList[i][columns[colIndex]];\n\n\t\t\tif (cellValue == null) {\n\t\t\t\tcellValue = \"\";\n\t\t\t}\n\n\t\t\trow$.append($('<td/>').html(cellValue));\n\t\t}\n\t\t$(\"#excelDataTable\").append(row$);\n\t}\n}", "function tableFromTreeWithColspan(tree) {\n var tableArray = [];\n var colspanMatrix = [];\n\n while(true){\n var row = [];\n var colspanRow = [];\n var offspring = [];\n\n if (tree.length == 0) {\n break\n }\n\n for (var i = 0; i < tree.length; i++) {\n branch = [];\n colspanBranch = [];\n\n for (var j = 0; j < tree[i].length; j++) {\n branch.push(tree[i][j]['name']);\n colspanBranch.push(calculateColspan([tree[i][j]],0));\n\n if (!!tree[i][j]['children']){\n offspring.push(tree[i][j]['children']);\n }\n else {\n offspring.push([]);\n }\n }\n row.push(branch);\n colspanRow.push(colspanBranch);\n }\n tableArray.push(row);\n colspanMatrix.push(colspanRow);\n tree = offspring;\n }\n\n return [tableArray,colspanMatrix]\n}", "function makeGrid() {\n\tlet cellSize = 0;\n\tif ($(window).width() < $(window).height()) {\n\t\tcellSize = $(window).width()*0.8*(1/(level + 0.5));\n\t} else {\n\t\tcellSize = $(window).height()*0.8*(1/(level + 0.5));\n\t}\n\tmakeRows(cellSize);\n\tfillRows(cellSize);\n}", "function CellRange() {\r\n this.p0 = new Vec2d();\r\n this.p1 = new Vec2d();\r\n this.reset();\r\n}", "tabulate(\n headers,\n rows,\n options) {\n if (!_.isArray(headers))\n TypeException(\"headers\", \"array\")\n if (!rows)\n TypeException(\"rows\", \"array\")\n if (_.any(rows, x => { return !_.isArray(x); }))\n TypeException(\"rows child\", \"array\")\n var o = _.extend({}, KingTableTextBuilder.options, options || {});\n var headersAlignment = o.headersAlignment,\n rowsAlignment = o.rowsAlignment,\n padding = o.padding,\n cornerChar = o.cornerChar,\n headerLineSeparator = o.headerLineSeparator,\n cellVerticalLine = o.cellVerticalLine,\n cellHorizontalLine = o.cellHorizontalLine,\n minCellWidth = o.minCellWidth,\n headerCornerChar = o.headerCornerChar;\n if (padding < 0)\n OutOfRangeException(\"padding\", 0)\n var self = this;\n // validate the length of headers and of each row: it must be the same\n var headersLength = headers.length;\n if (!headersLength)\n ArgumentException(\"headers must contain at least one item\")\n if (_.any(rows, x => { x.length != headersLength; }))\n ArgumentException(\"each row must contain the same number of items\")\n\n var s = \"\"\n\n // sanitize all values\n _.reach(headers, x => {\n return this.checkValue(x);\n })\n _.reach(rows, x => {\n return this.checkValue(x);\n })\n\n var valueLeftPadding = S.ofLength(SPACE, padding)\n padding = padding * 2;\n // for each column, get the cell width\n var cols = _.cols([headers].concat(rows)),\n colsLength = _.map(cols, x => {\n return Math.max(_.max(x, y => { return y.length; }), minCellWidth) + padding;\n });\n // does the table contains a caption?\n var totalRowLength;\n var caption = o.caption, checkLength = 0;\n if (caption) {\n checkLength = padding + caption.length + 2;\n }\n\n // does option contains information about the pagination?\n var paginationInfo = self.paginationInfo(o);\n if (paginationInfo) {\n // is the pagination info bigger than whole row length?\n var pageInfoLength = padding + paginationInfo.length + 2;\n checkLength = Math.max(checkLength, pageInfoLength);\n }\n\n // check if the last column length should be adapted to the header length\n if (checkLength > 0) {\n totalRowLength = _.sum(colsLength) + (colsLength.length) + 1;\n if (checkLength > totalRowLength) {\n var fix = checkLength - totalRowLength;\n colsLength[colsLength.length - 1] += fix;\n totalRowLength = checkLength;\n }\n }\n\n if (caption) {\n s += cellVerticalLine + valueLeftPadding + caption + S.ofLength(SPACE, totalRowLength - caption.length - 3) + cellVerticalLine + RN;\n }\n if (paginationInfo) {\n s += cellVerticalLine + valueLeftPadding + paginationInfo + S.ofLength(SPACE, totalRowLength - paginationInfo.length - 3) + cellVerticalLine + RN;\n }\n\n var headCellsSeps = _.map(colsLength, l => {\n return S.ofLength(headerLineSeparator, l);\n }),\n cellsSeps = _.map(colsLength, l => {\n return S.ofLength(cellHorizontalLine, l);\n });\n\n var headerLineSep = \"\";\n // add the first line\n _.each(headers, (x, i) => {\n headerLineSep += headerCornerChar + headCellsSeps[i];\n });\n // add last vertical separator\n headerLineSep += headerCornerChar + RN;\n\n if (paginationInfo || caption) {\n s = headerLineSep + s;\n }\n s += headerLineSep;\n\n // add headers\n _.each(headers, (x, i) => {\n s += cellVerticalLine + self.align(valueLeftPadding + x, colsLength[i], headersAlignment);\n });\n\n // add last vertical singleLineSeparator\n s += cellVerticalLine + RN;\n\n // add header separator\n s += headerLineSep;\n\n // build line separator\n var lineSep = \"\", i;\n for (i = 0; i < headersLength; i++)\n lineSep += cornerChar + cellsSeps[i];\n lineSep += cornerChar;\n\n // build rows\n var rowsLength = rows.length, j, row, value;\n for (i = 0; i < rowsLength; i++) {\n row = rows[i];\n for (j = 0; j < headersLength; j++) {\n value = row[j];\n s += cellVerticalLine + self.align(valueLeftPadding + value, colsLength[j], rowsAlignment);\n }\n s += cellVerticalLine + RN;\n s += lineSep + RN;\n }\n return s;\n }", "static create(value: Value, cell: Block): TablePosition {\n const row = value.document.getParent(cell.key);\n const table = value.document.getParent(row.key);\n\n return new TablePosition({\n table,\n row,\n cell\n });\n }", "function createTable() {\n\tdocument.getElementById('output').innerHTML = \"Creating Table...\";\n\n\tlet keys = [\"Index\", \"SS58\", \"Owner\", \"Deposit\", \"Permanent?\"];\n\n\tlet table = document.getElementById('indices-table');\n\n\t// Clear table\n\twhile (table.firstChild) {\n\t\ttable.removeChild(table.firstChild);\n\t}\n\n\tlet thead = document.createElement('thead');\n\tlet tbody = document.createElement('tbody');\n\n\tlet tr = document.createElement('tr');\n\tfor (key of keys) {\n\t\tlet th = document.createElement('th');\n\t\tth.innerText = key;\n\t\ttr.appendChild(th);\n\t}\n\n\tfor (index of Object.keys(global.indices)) {\n\t\tlet tr2 = document.createElement('tr');\n\n\t\tfor (key in keys) {\n\t\t\tlet td = document.createElement('td');\n\t\t\ttd.innerText = global.indices[index][key];\n\t\t\ttr2.appendChild(td);\n\t\t}\n\t\ttbody.appendChild(tr2);\n\t}\n\n\tthead.appendChild(tr);\n\ttable.appendChild(thead);\n\ttable.appendChild(tbody);\n\n\tdocument.getElementById('output').innerHTML = \"Done.\";\n}", "createTable(x, y, z) {\n\t\t'use strict';\n\t\tvar table = new Table(x, y, z);\n\n\t\ttable.createTableLeg(-35, 30, -50);\n\t\ttable.createTableLeg(-35, 30, 50);\n\t\ttable.createTableLeg(35, 30, -50);\n\t\ttable.createTableLeg(35, 30, 50);\n\t\ttable.createTableTop();\n\t\tthis.scene.add(table);\n\t\treturn table;\n\t}", "wipeAndRecreateNodes() {\n const el = this.el;\n TableViewer.removeChildren(el);\n let styleNode = document.createElement('style');\n styleNode.type = \"text/css\";\n el.appendChild(styleNode);\n let seekNodeObj;\n if (this.rowSource.isTableRowSource()) {\n seekNodeObj = TableViewer.createSeekNode();\n el.appendChild(seekNodeObj.div);\n const input = seekNodeObj.input;\n seekNodeObj.form.onsubmit = (event) => {\n this.seek(input.value);\n };\n }\n else {\n seekNodeObj = null;\n }\n let rowScroller = document.createElement('div');\n rowScroller.className = TableViewer.className + ' table_viewer_scroller';\n el.appendChild(rowScroller);\n let columnHeaders = document.createElement('table');\n columnHeaders.className = TableViewer.className + ' table_viewer_headers';\n rowScroller.appendChild(columnHeaders);\n let rowHolder = document.createElement('table');\n rowHolder.className = 'table_viewer_holder';\n rowScroller.appendChild(rowHolder);\n rowScroller.onscroll = event => { this.scrolled(event); };\n return { styleNode, seekNodeObj, rowScroller, columnHeaders, rowHolder };\n }", "_renderBodyCellsContent(renderer, cells) {\n if (!cells || !renderer) {\n return;\n }\n\n this.__renderCellsContent(renderer, cells);\n }", "function Table(canvas, col, row) {\n return Object.create({\n init: function () {\n game.col += 2;\n game.row += 2;\n\n var args = { table: this },\n windowWidth = $(w).width(),\n windowHeight = $(w).height() - 50,\n newSquareHeight = windowHeight / game.row,\n newSquareWidth = newSquareHeight;\n\n game.squareWidth = newSquareWidth;\n game.squareHeight = newSquareHeight;\n\n for (var i = 0; i < game.col + 2; i++) {\n this.grid[i] = [];\n for (var j = 0; j < game.row + 2; j++) {\n this.add(i, j);\n }\n }\n\n // remove all events from canvas element\n this.canvas.off('.minesweeper');\n\n // attach all events to our canvas\n this.canvas\n .on('contextmenu.minesweeper', args, function (e) {\n args.table.click(e);\n e.preventDefault();\n })\n .on('click.minesweeper', args, function (e) {\n args.table.click(e);\n })\n .on('mouseup.minesweeper', args, function (e) {\n args.table.mouseup(e);\n })\n .on('mousedown.minesweeper', args, function (e) {\n args.table.mousedown(e);\n });\n\n this.canvas.attr({ width: newSquareWidth * (game.col - 2), height: newSquareHeight * (game.row - 2) })\n .parent().css({ width: newSquareWidth * (game.col - 2), height: newSquareHeight * (game.row - 2) });\n\n this.placeMines();\n this.calculate();\n },\n // adds a square to the matrix\n add: function (i, j) {\n this.grid[i][j] = new Square(this, i, j);\n },\n // draw the minesweeper table(board)\n draw: function () {\n var arr = [], item = null;\n for (var i = 1; i < game.col - 1; i++) {\n for (var j = 1; j < game.row - 1; j++) {\n this.grid[i][j].draw();\n }\n }\n },\n // mousedown\n mousedown: function (e) {\n e.preventDefault();\n },\n // mouseup\n mouseup: function (e) {\n e.preventDefault();\n },\n // click handler on the table\n click: function (e) {\n \n // get clicked square\n var square = this.getSelected(e);\n\n if (square.x === 0 || square.y === 0 || square.x === game.col + 1 || square.y === game.row + 1) { \n return;\n }\n\n if (e.which == 1) {\n this.leftClick(square, e);\n } else if (e.which == 3) {\n this.rightClick(square, e);\n }\n },\n // left click handler on a square\n leftClick: function (square, e) {\n square.click(e);\n },\n // right click handler on a square\n rightClick: function (square, e) {\n square.rightClick(e);\n },\n // calculate the selected square with mouse coordinates\n getSelected: function (e) {\n var offset = this.coordinates(e),\n squarex = Math.floor(offset.x / game.squareWidth) + 1,\n squarey = Math.floor(offset.y / game.squareHeight) + 1,\n selectedSquar = this.grid[squarex][squarey];\n\n return selectedSquar;\n },\n // place mines \n placeMines: function () {\n var randomx = 0,\n randomy = 0;\n\n for (var i = 0; i < game.mines; i++) {\n randomx = Math.floor(Math.random() * (game.col - 2)) + 1;\n randomy = Math.floor(Math.random() * (game.row - 2)) + 1;\n\n this.grid[randomx][randomy].hasMine = true;\n }\n },\n // calculate square numbers according to number of mines surrounding them\n calculate: function () {\n for (var i = 1; i < game.col + 1; i++) {\n for (var j = 1; j < game.row + 1; j++) {\n this.grid[i][j].mines = this.getMinesCount(i, j);\n }\n }\n },\n // helper to the function above\n getMinesCount: function (i, j) {\n var count = 0;\n for (var k = -1; k < 2; k++) {\n if (this.grid[i - 1][j + k].hasMine === true) {\n count++;\n }\n }\n for (var k = -1; k < 2; k++) {\n if (this.grid[i + 1][j + k].hasMine === true) {\n count++;\n }\n }\n if (this.grid[i][j - 1].hasMine === true) {\n count++;\n }\n if (this.grid[i][j + 1].hasMine === true) {\n count++;\n }\n return count;\n },\n // open empty square until you reach mines, with recursion\n explore: function (i, j) {\n var current = this.grid[i][j];\n if (current.open || current.hasMine) {\n return;\n }\n if (i <= 0 || j <= 0 || i >= game.col - 1 || j >= game.row - 1) {\n return;\n }\n\n this.revealSquare(current);\n\n if (current.mines > 0) {\n return;\n }\n\n this.explore(i - 1, j - 1);\n this.explore(i - 1, j);\n this.explore(i - 1, j + 1);\n this.explore(i, j - 1);\n this.explore(i, j + 1);\n this.explore(i + 1, j - 1);\n this.explore(i + 1, j);\n this.explore(i + 1, j + 1);\n },\n // open all squares & draws them\n reveal: function () {\n for (var i = 1; i < game.col + 1; i++) {\n for (var j = 1; j < game.row + 1; j++) {\n this.grid[i][j].open = true;\n this.grid[i][j].draw();\n }\n }\n },\n // open a single square & draw it\n revealSquare: function (square) {\n square.open = true;\n square.draw();\n\n this.squareReveal--;\n\n // win game, no more squares to reveal\n if (this.squareReveal === 0) {\n this.smiley(true);\n }\n },\n // draw smiley (happy/sad)\n smiley: function (flag) { \n var x = $canvas.width() / 2,\n y = $canvas.height() / 2,\n start = 90,\n end = 270;\n\n // happy / sad ?\n if (!flag) {\n start = 270;\n end = 90;\n }\n\n this.canvas.drawArc({\n fillStyle: \"#ffff66\",\n strokeStyle: \"#ffff66\",\n strokeWidth: 5,\n x: x, y: y,\n radius: 200,\n start: 0, end: 360\n });\n\n this.canvas.drawArc({ fillStyle: \"#000\", strokeStyle: \"#000\", strokeWidth: 5, x: x - 50, y: y - 40, radius: 20, start: 0, end: 360 });\n this.canvas.drawArc({ fillStyle: \"#000\", strokeStyle: \"#000\", strokeWidth: 5, x: x + 50, y: y - 40, radius: 20, start: 0, end: 360 });\n this.canvas.drawArc({ fillStyle: \"#000\", strokeStyle: \"#000\", strokeWidth: 5, x: x, y: y + 100, radius: 40, start: start, end: end });\n },\n // display all squares with mines\n revealMines: function () {\n for (var i = 1; i < game.col + 1; i++) {\n for (var j = 1; j < game.row + 1; j++) {\n if (this.grid[i][j].hasMine) {\n this.grid[i][j].open = true;\n this.grid[i][j].draw();\n }\n }\n }\n },\n // get x & y coordinates of the mouse in the current canvas\n coordinates: function (e) {\n return { x: e.pageX - canvas.offset().left, y: e.pageY - canvas.offset().top };\n }\n },\n {\n // reference to canvas element\n canvas: { value: canvas, writable: true },\n // matrix of square objects [x,y]\n grid: { value: [], writable: true }, \n // number of revealed squares \n squareReveal: { value: game.col * game.row - game.mines, writable: true }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: hash with /id (cardDetail/id) I have startswith() method to grab the hash and have access to the hash on the controller
function cardDetail() { $('.image').click((event) => { let id = event.target.id; window.location.hash = '#cardDetail/' + id; }); }
[ "handleHashChange() {\n const authorId = window.location.hash.substr(1);\n if (authorId && authorId.length > 0) {\n // save the history!\n this.saveState();\n this.createFeedRequest(`&id=${authorId}`);\n }\n else {\n // mostly like a back button..\n this.loadFromState();\n }\n }", "getBlockByHash() {\n this.app.get(\"/stars/hash::hash\", async (req, res) => {\n let hash = req.params.hash;\n console.log(`GET /stars/hash:${hash}`);\n let block = await this.blockChain.getBlockByHash(hash);\n if (undefined === block || null === block) {\n res.status(404)\n res.send(`Error Block #${hash} not found`);\n } else {\n block = this.decodeStory(block); // block.body.star.storyDecoded = hex2ascii(block.body.star.story);\n res.json(block);\n }\n });\n }", "function loadBoardByHash()\n{\n let hash = location.hash;\n let page = hash ? hash.slice(1) : 'home';\n\n loadBoard(page);\n}", "function updateHash($accordion) {\n\n // get id of accordion which contains unique accordion name\n var hashVal = $.trim($accordion.attr('id'));\n\n if(history.replaceState) {\n history.replaceState(null, null, '#' + hashVal);\n }\n else {\n // warning: for older browsers, this causes the accordion to be scrolled to\n location.hash = hashVal;\n }\n\n }", "function editCard(card_id) {\n // console.log(\"id received\" + card_id);\n loadValues(card_id);\n}", "getBlockByHash() {\n this.server.route({\n method: 'GET',\n path: '/stars/hash:{hash}',\n handler: (request, h) => {\n return this.blockchain.getBlockByHash(request.params.hash).then((block) => {\n if (block == null) {\n throw Boom.badRequest('No block found for hash');\n }\n block.body.star.storyDecoded = new Buffer(block.body.star.story, 'hex').toString('ascii');\n return block;\n })\n .catch((err) => {\n throw Boom.badRequest(err);\n });\n }\n });\n }", "_onHashChanged() {\n const hash = RB.getLocationHash();\n let selector = null;\n\n if (hash !== '') {\n if (hash.includes('comment')) {\n selector = `a[name=${hash}]`;\n } else {\n selector = `#${hash}`;\n }\n }\n\n if (!selector) {\n return;\n }\n\n /*\n * If trying to link to some anchor in some entry, we'll expand the\n * first entry containing that anchor.\n */\n for (let i = 0; i < this._entryViews.length; i++) {\n const entryView = this._entryViews[i];\n const $anchor = entryView.$(selector);\n\n if ($anchor.length > 0) {\n /*\n * We found the entry containing the specified anchor.\n * Expand it and stop searching the rest of the entries.\n */\n entryView.expand();\n\n /*\n * Scroll down to the particular anchor, now that the entry\n * is expanded.\n */\n RB.scrollManager.scrollToElement($anchor);\n break;\n }\n }\n }", "getStarBlockByHash() {\n this.app.get(\"/stars/hash::index\", (req, res) => {\n let hash = req.params.index;\n blockchain.getBlockByHash(hash).then((block) => {\n res.status(200).send(block);\n }).catch(() => {\n res.status(404).send({ error: { message: 'Block #' + index + ' not found' } });\n });\n });\n }", "updateHash(slug) {\n window.location.hash = slug;\n }", "function get_details(id){\n console.log(\"You clicked Game ID: \" + id);\n fetch_by_id(id);\n}", "goToCardIntake() {\n let url;\n if (Auth.get(this).user.role === 'corporate-admin') {\n url = 'main.corporate.customer.intake-revised';\n } else {\n url = 'main.employee.customer.intake-revised';\n }\n if (this.displayData.rejectionTotal) {\n url = url + '.denials';\n }\n state.get(this).go(url, {customerId: this.displayData.selectedCustomer._id});\n }", "function getChapterHash($chapter) {\n var $link = $chapter.children(\"a\"),\n hash = $link.attr(\"href\").split(\"#\")[1];\n\n if (hash) hash = \"#\" + hash;\n return !!hash ? hash : \"\";\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}", "function getHashPageId() {\n const hash = decodeURIComponent(location.hash.substring(1));\n return `${hash.replace(/\\s+/g, '') || 'main-page'}`;\n}", "get hashId()\n\t{\n\t\t//this.id;\n\t\t//this.recurrenceId;\n\t\t//this.calendar;\n\t\treturn this._calEvent.hashId;\n\n/*\t\t this._hashId = [encodeURIComponent(this.id),\n\t\t\tthis.recurrenceId ? this.recurrenceId.getInTimezone(exchGlobalFunctions.ecUTC()).icalString : \"\",\n\t\t\tthis.calendar ? encodeURIComponent(this.calendar.id) : \"\"].join(\"#\");\n\n\t\t//dump(\"get hashId: title:\"+this.title+\", value:\"+this._hashId);\n\t\treturn this._hashId;*/\n\t}", "function fnOpenOrderHistoryDetailView(id) {\n $.mobile.changePage(\"/HiDoctor_Activity/OTC/OrderHistoryDetailView?orderID=\" + id.split('_')[0] + \"&from=\" + id.split('_')[1], {\n type: \"post\",\n reverse: false,\n changeHash: false\n });\n}", "function internCard(internObj) {\n var name = internObj.getName();\n var id = internObj.getID();\n var email = internObj.getEmail();\n var school = internObj.getSchool();\n var role = internObj.getRole();\n\n var html = `<div class=\"card\">\n <h4 class=\"card-header\" id=\"name\">`+ name + `</h4>\n <h4 class=\"card-header\" id=\"name\">`+ `<i class=\"fas fa-user-graduate\"></i>` + role + `</h4>\n <div class=\"card-body\">\n <p class=\"card-text\">ID : `+ id + `</p>\n <p class=\"card-text\">Email : <a href=\"mailto:`+email+`\">`+ email +`</a></p>\n <p class=\"card-text\">School : `+ school + `</p>\n </div>\n </div>`;\n return html;\n}", "hashChangeListener () {\n let teamNameRegEx = /teams\\/([\\w+|\\x25|\\s]+)\\W/\n let urlSpaceEncodingRegEx = /\\x25\\d{2}/g\n let foundTeamNameRegExGroup = document.URL.match(teamNameRegEx)\n let foundTeamName = foundTeamNameRegExGroup !== null ? String(foundTeamNameRegExGroup[1]) : null\n if (foundTeamName === null) { return }\n let cleanedTeamName = foundTeamName.replace(urlSpaceEncodingRegEx, ' ')\n if (this.state.viewedTeamObjects.hasOwnProperty(cleanedTeamName) === true) {\n this.setState(this.state.viewedTeamObjects[cleanedTeamName])\n } else if (this.state.viewedTeamObjects.hasOwnProperty(cleanedTeamName) !== true && this.state.viewedTeams.indexOf(cleanedTeamName) === -1) {\n this.fetchTeamInfo(cleanedTeamName)\n }\n scrollToTop()\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user has many addresses
static associate(models) { this.hasMany(models.Address, { foreignKey: "user_id", // coluna da tabela addresses que faz o relacionamento as: "addresses" }) this.belongsToMany(models.Tech, { foreignKey: "user_id", through: "user_techs", as: "techs" // quais são as techs desse usuário }) }
[ "static async getAddressId(user_id){\n const res = await db.query(`SELECT \n user_id, street_address, address_number, city, state, zip_code, country \n FROM user_address \n WHERE user_id=$1`, [user_id])\n const a = res.rows[0]\n if(a) {\n return new Address(a.user_id, a.street_address, a.address_number, a.city, a.state, a.zip_code, a.country)\n }\n throw new ExpressError('User not found.', 404)\n }", "getAddressByUserIdAddressId(userId, addressId) {\n return http.get(`/address/${userId}/${addressId}`);\n }", "function showAddresses(addresses) {\n console.log('Address:')\n for (let address of addresses) {\n console.log(address);\n }\n}", "getRecipients() {\n return new Promise((resolve, reject) => {\n Action.find().distinct('toAddress', (error, address) => {\n if(error) { reject; return; }\n resolve(address)\n })\n })\n }", "function appendAddress(address)\n{\n\tvar div = d3.select(this);\n\tif (address && address.id())\n\t{\n\t\taddress.promiseData()\n\t\t\t.then(function()\n\t\t\t{\n\t\t\t\tvar streets = address.streets();\n\t\t\t\tvar city = address.city();\n\t\t\t\tvar state = address.state();\n\t\t\t\tvar zip = address.zipCode();\n\t\t\t\tif (streets)\n\t\t\t\t\t$(streets).each(function() {\n\t\t\t\t\t\tif (this.text() && this.text().length > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdiv.append('div')\n\t\t\t\t\t\t\t\t.classed('address-line', true)\n\t\t\t\t\t\t\t\t.text(this.text());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tline = \"\";\n\t\t\t\tif (city && city.length)\n\t\t\t\t\tline += city;\n\t\t\t\tif (state)\n\t\t\t\t\tline += \", \" + state;\n\t\t\t\tif (zip && zip.length)\n\t\t\t\t\tline += \" \" + zip;\n\t\t\t\tif (line.trim())\n\t\t\t\t\tdiv.append('div')\n\t\t\t\t\t\t.classed('address-line', true)\n\t\t\t\t\t\t.text(line.trim());\n\t\t\t});\n\t}\n}", "async processUserAddress(stepContext) {\n const userProfile = await this.userProfileAccessor.get(stepContext.context);\n userProfile.in.address = stepContext.context.activity.text;\n await this.userProfileAccessor.set(stepContext.context, userProfile);\n return await stepContext.replaceDialog(MAIN_DIALOG);\n }", "addUser(person) {\r\n this.#userList.set(person.getPersonId(), person);\r\n }", "function addUser(user) {\n\tif (user) {\n\t\tlet friends = []\n\t\tu.forEach((person) => {\n\t\t\tif (person !== user) {\n\t\t\t\tfriends.push(person)\n\t\t\t}\n\t\t})\n\t\tlet newUser = new User()\n\t\tnewUser.facebook.name = user\n\t\tnewUser.password = '123'\n\n\t\tnewUser.facebook.friends = friends\n\t\tnewUser.save()\n\t}\n}", "function get_reputation_rows_for_users(users, callback){\n async.concat(\n\n users,\n\n function(user, done){\n\n get_reputation_rows_for_user(user, function(reputation_rows){\n\n var reputation = {};\n reputation[user] = reputation_rows;\n\n done(null, reputation);\n\n });\n\n }, async_concat_callback(callback));\n}", "constructor(userProfileObj){\n this._user = userProfileObj.user || userProfileObj._user || {};\n this._userConnections = userProfileObj.userConnections || userProfileObj._userConnections || []; \n }", "function AddAssignee(supplierAddress, multi, address, callback) {\n var transactionhash = '';\n var signedDate = Math.floor(Date.now() / 1000);\n var status = props.status_pending;\n multi.addAssignee.sendTransaction(supplierAddress, false, signedDate, status, '', {\n from: address,\n gas: 3000000\n }, function(err, contract) {\n transactionhash = contract;\n });\n callback(null, transactionhash);\n}", "drawAdditionalAddresses (address, link, parcel) {\n let _display = `<section class='drop-area additional-addresses'>`;\n\n // Skip first address\n for (let i = 1; i < address.length; i++) {\n if(typeof address[i] == 'object') address[i] = address[i].streetAddress;\n let parcelNumber = '';\n if(typeof parcel[i] != undefined){\n parcelNumber = typeof parcel[i] == 'object' ? ` - ${parcel[i].parcelNumber}` : ` - ${parcel[i]}`;\n }\n \n _display += `\n <a class='address-link' href='${link[i]}' target='_blank' title=\"Find address on DART\">\n <span class='address'>${address[i]}</span><span class='parcel'>${parcelNumber}</span>\n </a>`;\n if (i != address.length - 1) {\n _display += `<br>`;\n }\n }\n _display += `</section>`;\n return _display;\n }", "function getMyEmailAddresses(){\n var myaddy = GmailApp.getAliases() || [],\n x;\n if ((x = Session.getEffectiveUser().getEmail()) && myaddy.indexOf(x) === -1){\n myaddy.push(x);\n }\n return myaddy;\n}", "function addUser( domain, user, callback ) {\n\tgetBlockList( domain, function( list ) {\n\t\tvar index = list.indexOf( user );\n\n\t\tif( index == -1 ) {\n\t\t\tlist.push( user );\n\t\t\tsetBlockList( domain, list, function(){} );\n\t\t}\n\n\t\tcallback( list );\n\t} );\n}", "function getUserManagerRelationshipView(user_id) {\n var user = getUser(user_id, ['manager']);\n return user.manager;\n}", "function clearAddress() {\n address = [];\n}", "function setupPledgeAddressAutocomplete(root) {\n pledgeAddressElement = root.find('input[name=\"address\"]');\n\n pledgeAddressAutocomplete = new google.maps.places.Autocomplete(pledgeAddressElement[0], {types: ['geocode']});\n pledgeAddressAutocomplete.addListener('place_changed', updatePlaceDataFromAddress);\n\n // try to determine user's location to bound results\n pledgeAddressElement.bind('focus', function () {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(function (position) {\n var geolocation = {\n lat: position.coords.latitude,\n lng: position.coords.longitude\n };\n var circle = new google.maps.Circle({\n center: geolocation,\n radius: position.coords.accuracy\n });\n pledgeAddressAutocomplete.setBounds(circle.getBounds());\n });\n }\n });\n }", "hideFromUser(user1,user2){\n this.users[user1].friendsDontShow.push({name: this.users[user2].name, id: user2});\n return true;\n }", "function addUserToOUByPath(node, path, user){\n if(node.data['path'] === path){\n node.data['users'].push(user);\n return;\n }\n else{\n if(node['children'] === undefined)\n return;\n var children = node['children'];\n for(var ou of children){\n if(path.includes(ou.data['path'])){\n addUserToOUByPath(ou, path, user);\n }\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force reload the image
function reloadImage(img) { const src = img.attr('src'); img.removeAttr('src'); setTimeout(() => { img.attr('src', src); }, 500); }
[ "function Refresh_Image(the_id)\n{\n var data = {\n action: 'x2_get_image',\n id: the_id\n };\n\t\t\n jQuery.get(ajaxurl, data, function(response)\n\t\t{\n\n if(response.success === true)\n\t\t\t{\n jQuery('#x2-preview-image').replaceWith( response.data.image );\n }\n });\n}", "function gifRefresh() {\n window.location.reload();\n}", "function _refreshCaptcha() {\n $.getJSON(config.captchaRefreshURL, {}, function(json) {\n $captcha_image[0].src = json.image_url;\n $captcha_image.next()[0].value= json.key;\n });\n\n return false;\n }", "function ReLoadImages() {\n $('img[data-lazysrc]').each(function() {\n $(this).attr('src', $(this).attr('data-lazysrc'));\n });\n}", "load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }", "function resetThumbnailImg() {\n $('img.edit_thumbnail').attr('src', emptyImageUrl);\n currentThumbnailId = 0;\n}", "_cancelLoadImage(){\n if(this.image){\n this.image.onload = null;\n this.image.onerror = null;\n this.image = null;\n }\n }", "function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }", "function updateSlimemanImage() {\n document.getElementById(\"SlimemanImage\").src = \"assets/images/face\" + (maxTries - remainingGuesses) + \".png\";\n}", "function cambiarImagenLleno(){\n $(\"#miImagen\").attr(\"src\",\"media/cestaLlena.png\");\n }", "async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }", "imageLoaded(){}", "function url_force_reload(url) { \n var date_now = new Date();\n return url + '?v=' + date_now.getTime(); \n}", "reloadTexture(){\n this.blochDiagram.loadTexture('qbloch');\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 updateImageReader() {\r\n var newImageUrl = document.getElementById('image-search').value;\r\n\r\n clearImageSelection();\r\n\r\n if (mode == READ_MODE) {\r\n refreshAnnotations(newImageUrl, document.getElementById('textUrl').value);\r\n } else {\r\n document.getElementById('image-input').src = \"/alignment/imageReader.html?ui=embed&editable=true&url=\" + encodeURIComponent(newImageUrl);\r\n document.getElementById('imageUrl').value = newImageUrl;\r\n }\r\n }", "async function attemptReload() {\n await fetch(''); // Check the server really is back\n location.reload();\n }", "resetFileThumb() {\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n fileThumb.src = require(\"../static/images/file-128x128.png\");\n }", "function replay() {\n\tlocation.reload();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for a Garden containing different animals, plants, and other objects. All the arguments for the constructor are optional and will be initialized as an empty array if they are missing
constructor(animals=[], plants=[], randomObjects=[]) { this.animals = animals; this.plants = plants; this.randomObjects = randomObjects; }
[ "function Animal(object){\n this.name = object.keyword;\n this.image = object.image_url;\n this.description = object.description;\n this.hornCount = object.horns;\n this.title = object.title;\n\n animalArray.push(this);\n}", "constructor(size) {\r\n this.birds = [];\r\n this.size = size;\r\n this.actualBird = 0; //kind of an index for the population\r\n for (let i = 0; i < size; i++) {\r\n this.birds.push(new bird());\r\n }\r\n this.generation = 0;\r\n this.melhor = this.birds[0];\r\n this.lastmelhor = 0;\r\n }", "initializeDogs(canvasW, canvasH) {\n this.petDogs = {\n dog: [],\n location: [],\n }\n\n for (let i = 0; i < MAX_DOGS; i += 1) {\n this.petDogs.dog.push(new Dog())\n this.petDogs.location.push({\n x: calcDogX(0, canvasW),\n y: calcDogY(canvasH * (2 / 3), canvasH),\n })\n }\n }", "function Dog(name, color) {\n this.name = name;\n this.color = color;\n this.numLegs = 4; \n}", "constructor(name, weight, eyeColor){\n//Assigns it to this instance\n// this is the object that is instantiated (created) \nthis.name = name //assigns value to this specific instance of a gorilla\nthis.weight = weight\nthis.isAlive = true // a default can also be set\nthis.eyeColor = eyeColor\nthis.bananasEaten = 0\nconsole.log(('you built a gorilla'));\n\n}", "function Drink(teaType, toppingsList, milkOption){\n \"use strict\";\n \n this.teaType = teaType;\n this.toppingsList = toppingsList.slice();\n this.milkOption = milkOption;\n}", "function addAnimal()\n{\n animalArray.push(new Animal());\n console.log(\"God creates a new animal, and it was good\");\n}", "function generateRandomAnimal() {\n // random index to choose animal type\n var animalIndex = generateRandomIndex(animals.length);\n // get a random animal\n var animal = animals[animalIndex];\n // identify and create animal\n if (animal instanceof PolarBear) return new PolarBear(generateRandomName(), generateRandomAge());\n else if (animal instanceof Lion) return new Lion(generateRandomName(), generateRandomAge());\n else return new Rabbit(generateRandomName(), generateRandomAge());\n}", "function Duck(){\n\tthis.speciesName = 'duck';\n}", "function AnimalType() {\n this.single = '';\n this.plural = '';\n this.health = 10;\n this.healthGrowth = 1;\n this.speed = 10;\n this.speedGrowth = 0;\n this.armor = 0;\n this.armorGrowth = 0;\n this.carry = 1;\n this.carryGrowth = 0;\n this.damage = 1;\n this.damageGrowth = 0;\n //these tags are used for matching modifier abilities like\n //\"increase the armor of all 'birds'\"\n this.tags = [];\n this.spriteIndex = 0;\n this.numberOfFrames = 6;\n}", "function Bird() {\n this.name = \"Albert\";\n this.color = \"blue\";\n this.numLegs = 2;\n // \"this\" inside the constructor always refers to the object being created\n}", "static init(diagnoses = []) {\n const self = new DoctorRegistrar();\n self.diagnoses = diagnoses; // diagnoses.forEach(diagnosis => self.diagnoses.push(diagnosis));\n }", "function Pet(petName,age,adopted,markings,breed){\n this.petName = petName;\n this.age = age;\n this.adopted = adopted;\n this.markings = markings;\n this.breed = breed;\n}", "constructor() {\n // An array for data which are taken api\n this.foodsArray = []\n // An array for favourite meals\n this.favouriteFoods = []\n this.renderApp()\n }", "function Pizza(toppings, size){\n this.toppings = [];\n this.size = size;\n}", "constructor() {\n this.name = \"yourself\"\n this.worn = []\n }", "function createNewAliens() {\n aliens.push(\n new Alien(width * random(0.05, 0.12), 150),\n new Alien(width * random(0.2, 0.3), 150),\n new Alien(width * random(0.35, 0.45), 150),\n new Alien(width * random(0.5, 0.6), 150),\n new Alien(width * random(0.7, 0.9), 150)\n );\n}", "function _postrocessConstruction() {\n this.$.model.animals = [];\n for (let playerId of this.$.model.actors) {\n const pl = playerProxy.get(playerId);\n this.$.model.animals.concat(pl.animals.list());\n }\n}", "function EarthBuildings(earth){\n var resources = earth.resources;\n this.mill = new Building(\"Mill\", resources.food, 1, 0);\n this.quarry = new Building(\"Quarry\", resources.stone, 1, 0);\n this.lumbermill = new Building(\"Lumbermill\", resources.wood, 1, 0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get streetView, Zomato info (by ajax)
function getStreetView(data, status) { var resId = marker.id; var result = { rating: "", averageCostForTwo: "", currency: "", errMsg: "" }; // Use ajax to get the Zomato restaurant info $.ajax ({ url: "https://developers.zomato.com/api/v2.1/restaurant?", data: { 'res_id': resId }, headers: { 'user-key': "8efa773100b432e426e7816bfeaef2af" }, dataType: "json", success: function(re) { result.rating = (re.user_rating.aggregate_rating == "0")? re.user_rating.rating_text : re.user_rating.aggregate_rating; result.averageCostForTwo = re.average_cost_for_two; result.currency = re.currency; }, error: function() { result.errMsg = "Can't find Zomato info."; }, complete: function() { var content = ""; if (status == google.maps.StreetViewStatus.OK) { content = '<div>' + marker.title + '</div><div id="pano"></div>'; content = checkZomatoInfo(result, content); infoWindow.setContent(content); var nearLocation = data.location.latLng; var heading = google.maps.geometry.spherical.computeHeading(nearLocation, marker.position); var panoramaOptions = { position: nearLocation, pov: { heading: heading, pitch: 30 } }; // Id: #pano will be added automaticely within each infoWindow when click the marker var panorama = new google.maps.StreetViewPanorama($('#pano')[0], panoramaOptions); } else { content = '<div>' + marker.title + '</div>' + '<div>No Street View Found</div>'; content = checkZomatoInfo(result, content); infoWindow.setContent(content); } } }); //End of $.ajax } // End of function getStreetView
[ "function makeZomatoRequest(){\n\n\tvar zomatoURL = \"https://developers.zomato.com/api/v2.1/search?entity_id=57&entity_type=city&cuisines=148\";\n\n console.log(\"About to make the Ajax request to Zomato\");\n $.ajax({\n url: zomatoURL,\n type: \"GET\",\n headers: {\n 'user-key':'128179da0e7972547e1938fdae65a31d'\n },\n dataType: \"json\",\n error: function(err){\n console.log(err);\n },\n success: function(result){\n console.log(\"Success!\");\n console.log(result);\n\n\n var theRestaurants = result.restaurants; //the array of restaurant objects. \n\n //the lines below should also make it show up \n\n makeHTML(theRestaurants);\n\n // for (var i=0; i<theRestaurants.length; i++){\n // // $('#.a').append(htmlString);\n // console.log(theRestaurants[i].restaurant.name);\n // }\n }\n });\n}", "getLocation() {\n // using fetch API to get AJAX calls you can use XHP also\n fetch(\"https://geoip-db.com/json/\")\n .then(res => res.json())\n .then(result => {\n name.innerHTML += `${res.city}, ${res.state}`;\n });\n }", "function infoWindowContents(index, data) {\n\tvar restaurant = data.restaurants[index];\n\tvar mymap = data.restaurants[index].mymap;\n\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/home/info_window',\n\t\tdata: {\n\t\t\tid: \t\t\t\trestaurant.id,\n\t\t\tmymap_id: \tmymap.id\n\t\t}\n\t});\n}", "function getRestaurantInfo(cityID){\n var zomatoURL = \"https://developers.zomato.com/api/v2.1/location_details?entity_id=\" + cityID + \"&entity_type=city\"\n var settingsZomatoLocationDetails = {\n async: true,\n crossDomain: true,\n url: zomatoURL,\n beforeSend: function(xhr) {\n xhr.setRequestHeader(\"user-key\", \"9f4de5189fa76ba5e2e854c84b47b2e3\")\n },\n method: \"GET\",\n }\n $.ajax(settingsZomatoLocationDetails).then(function (response) {\n console.log(\"Zomato Location Details: \");\n console.log(response);\n for(var i = 0; i < 5; i++){\n //Conditional set above possible range for time being\n if(response.best_rated_restaurant[i].restaurant.price_range < 5){\n $(\"#Food_\" +(i+1)).find(\".title\").text(response.best_rated_restaurant[i].restaurant.name);\n $(\"#Food_\" +(i+1)).find(\".restaurant-url\").attr(\"href\", response.best_rated_restaurant[i].restaurant.url);\n $(\"#Food_\" +(i+1)).find(\".cuisine-type\").text(\"Cuisine type: \" + response.best_rated_restaurant[i].restaurant.cuisines);\n $(\"#Food_\" +(i+1)).find(\".address\").text(\"Address: \" + response.best_rated_restaurant[i].restaurant.location.address);\n $(\"#Food_\" +(i+1)).find(\".menu\").attr(\"href\", response.best_rated_restaurant[i].restaurant.menu_url);\n $(\"#Food_\" +(i+1)).find(\"img\").attr(\"src\", response.best_rated_restaurant[i].restaurant.featured_image);\n }\n }\n })\n }", "function displayRestaurantInfo(place) {\n $('#review-window').show();\n $('#add-review-button').show();\n restaurantInfoContainer.show();\n $('#name').text(place.name);\n $('#address').text(place.vicinity);\n $('#telephone').text(place.formatted_phone_number);\n\n var reviewsDiv = $('#reviews');\n var reviewHTML = '';\n reviewsDiv.html(reviewHTML);\n if (place.reviews) {\n if (place.reviews.length > 0) {\n for (var i = 0; i < place.reviews.length; i += 1) {\n var review = place.reviews[i];\n var avatar;\n if (place.reviews[i].profile_photo_url) {\n avatar = place.reviews[i].profile_photo_url;\n } else {\n avatar = 'img/avatar.svg';\n }\n reviewHTML += `<div class=\"restaurant-reviews\">\n <h3 class=\"review-title\">\n <span class=\"user-avatar\" style=\"background-image: url('${avatar}')\"></span>`;\n if (place.rating) {\n reviewHTML += `<span id=\"review-rating\" class=\"rating\">${placeRating(review)}</span>`;\n }\n reviewHTML += ` <h3>${place.reviews[i].author_name}</h3>\n </h3>\n <p> ${place.reviews[i].text} </p>\n </div>`;\n reviewsDiv.html(reviewHTML);\n }\n }\n }\n\n /********** Street view using Google API **********/\n\n /*** Add Street View ***/\n var streetView = new google.maps.StreetViewService();\n streetView.getPanorama({\n location: place.geometry.location,\n radius: 50\n }, processStreetViewData);\n\n var streetViewWindow = $('#street-view-window');\n var photoContainer = $('#photo');\n var photoWindow = $('#see-photo');\n var seeStreetView = $('#see-street-view');\n photoContainer.empty();\n photoContainer.append('<img class=\"place-api-photo\" ' + 'src=\"' + createPhoto(place) + '\"/>');\n\n streetViewWindow.show();\n if (photo) {\n photoWindow.show();\n } else {\n photoWindow.hide();\n }\n\n function processStreetViewData(data, status) {\n if (status === 'OK') {\n var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'));\n panorama.setPano(data.location.pano);\n panorama.setPov({\n heading: 440,\n pitch: 0\n });\n panorama.setVisible(true);\n\n } else {\n photoWindow.hide();\n streetViewWindow.hide();\n photoContainer.show();\n }\n }\n }", "function getCity() {\n var zomatoURL = \"https://developers.zomato.com/api/v2.1/cities?q=\" + city;\n $.ajax({\n url: zomatoURL,\n dataType: \"json\",\n async: true,\n beforeSend: function (xhr) { xhr.setRequestHeader(\"user-key\", zAPIkey); },\n success: function (response) {\n if (response.location_suggestions.length > 1) {\n $(\"#cityMessage\").empty();\n var message = $(\"<p>\").appendTo($(\"#cityMessage\"));\n message.text(\"We found a few matches for that city name. Please click on the best match.\")\n for (var i = 0; i < response.location_suggestions.length; i++) {\n var cityOption = response.location_suggestions[i].name;\n var cityBtn = $(\"<button>\");\n cityBtn.text(cityOption);\n cityBtn.addClass(\"cityBtn\");\n cityBtn.addClass(\"hollow button\");\n cityBtn.attr(\"id\", response.location_suggestions[i].id);\n $(\"#cityMessage\").append(cityBtn);\n }\n } else if (response.location_suggestions.length === 0) {\n $(\"#cityMessage\").empty();\n var errorMessage = $(\"<p>\").text(\"Sorry, we couldn't find that city! Please try again.\");\n $(\"#cityMessage\").append(errorMessage);\n } else {\n cityID = response.location_suggestions[0].id;\n $(\"#cityMessage\").empty();\n $(\"#restaurant-list\").addClass(\"grid-x grid-margin-x small-up-2 medium-up-3\");\n getRestaurants();\n }\n }\n });\n}", "function showAllInfo(data) {\n $(\".info_section\").empty();\n if (verifyTeleportDataNotEmpty(data)) {\n const firstCity = data._embedded[`city:search-results`][0];\n showTeleportCityInfo(firstCity);\n showWikipediaInfo(firstCity[`matching_full_name`]);\n } \n else {\n displayNoSearchResults();\n }\n }", "function requestTomTom(query) {\n $.ajax({\n // Rotta response\n 'url': 'http://localhost:8000/search',\n 'dataType': 'json',\n 'headers': {'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')},\n 'method': 'POST',\n 'data':{\n // le coordinate da mandare al back-end\n 'query_lat': query.lat,\n 'query__long': query.lon,\n 'radius': $('#search_radius').val(),\n\n 'services': checkboxCheck(),\n 'rooms': $('#rooms').val(),\n 'beds': $('#beds').val(),\n 'baths': $('#baths').val(),\n 'mq': $('#mq').val(),\n },\n 'success': function (data) {\n\n // data contiene la ns risposta. gli appartamenti!\n renderApartment_premium(data['premium']);\n renderApartment_free(data['free']);\n },\n 'error':function(){\n console.log('errore!');\n }\n });\n}", "function getCityName() {\n 'use strict';\n\n var keyGoogle = 'AIzaSyBmCk28nEs1OWXgwS0VQ1752o_cYwrkxHs',\n url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=',\n location = latitude + ',' + longitude;\n\n $.ajax({\n url: url + location,\n type: 'GET',\n dataType: 'json',\n data: {\n //location_type: 'GEOMETRIC_CENTER',\n key: keyGoogle\n }\n }).done(function (googleResponse) {\n $city.text(googleResponse.results[0].formatted_address);\n }).fail(function (googleResponse) {\n Materialize.toast('Cannot get City Name from google', 600);\n });\n}", "function searchUV(lat, lon){\n var apiKey=\"fb387ced59c1ebda042a0c8fd0dabefe\";\n var settings = {\n \"async\": true,\n \"crossDomain\": true,\n \"url\": \"http://api.openweathermap.org/data/2.5/uvi?lat=\"+lat+\"&lon=\"+lon+\"&appid=\"+apiKey,\n \"method\": \"GET\"\n } \n $.ajax(settings).done(function (response) {\n displayUVData(response);\n });\n}", "function getTideData(pos, errorFunction, successFunction) {\n $.ajax({\n url: 'https://www.worldtides.info/api?heights&key=a9b7587f-73a5-4b34-b643-18a493c7c3e3&lat=' + pos.lat + '&lon=' + pos.lng,\n dataType: 'json',\n type: 'GET',\n crossDomain: true,\n error: function (msg) {\n errorFunction(msg);\n },\n success: function (data) {\n successFunction(data);\n }\n });\n}", "function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}", "function getBaiduData(location) {\n jQuery.ajax({\n url: 'https://api.map.baidu.com/place/v2/search',\n type: 'GET',\n dataType: 'jsonp',\n data: {\n // query for only attractions\n 'q': '旅游景点',\n 'scope': '2',\n // sort by raiting\n 'filter': 'sort_name:好评|sort_rule:0',\n 'region': location,\n 'output': 'json',\n // ak = acess key\n 'ak': 'oXmLrK2EjxWxZm1qab51f1fmRLm4I4kF',\n // max page_size is 20\n 'page_size': '20',\n 'page_num': '0'\n }\n })\n .done(function(data, textStatus, jqXHR) {\n //store results in locations array\n locations = data.results;\n //create markers for locations returned by Baidu\n createMarkers(locations);\n })\n .fail(function(jqXHR, textStatus, errorThrown) {\n console.log('HTTP Request Failed');\n alert('Baidu search results could not load properly. Please try again in a few minutes.');\n });\n }", "function findStreetViews(pointsArray){\n var paLength = pointsArray.length;\n var currentIteration = 0;\n var panoArray = [];\n for (var i = 0; i < (paLength > LIMIT ? LIMIT : paLength); i++){\n findPanorama(pointsArray[i], i, paLength, panoArray, currentIteration);\n }\n\n //findPanorama()\n //==============\n //Find a single panoramic image at a point, and puts it into the specified index.\n //If no result is found, it puts null into the array.\n function findPanorama(point, index, paLength, panoArray){\n webService.getPanoramaByLocation(point, RADIUS, function(result, status){\n console.log('index', index);\n currentIteration++;\n panoArray[index] = result;\n\n //Conditional to check if we move on can only be done in here\n //by incrementing currentIteration until it matches\n //the limit, or the length of routes[0].overview_path\n //If we're on the last iteration, parse the entire array\n if (currentIteration == (paLength > LIMIT ? LIMIT : paLength)){\n parsePanoramaArray(panoArray);\n }\n });\n }\n }", "function search(){\n\t\tvar xhttp = new XMLHttpRequest();\n\t\tvar response;\n\t\tvar address = document.getElementById(\"address\").value;\n\t\tconsole.log(address);\n\t\t\n\t\tif(address != undefined || address != \"\"){\n\t\t\tconsole.log(address);\n\t\t\txhttp.onreadystatechange = function() {\n\t\t\t\tif (this.readyState == 4 && this.status == 200) {\n\t\t\t\t\tresponse = this.responseText;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\txhttp.open(\"GET\", \"http://localhost:3000/address/?address=\"+address, false);\n\t\t\txhttp.send();\n\n\t\t\tprintWeather(response);\n\t\t}\n\t}", "function foursquareSearch(food, longitudeLatitude) { // first ajax call\n var queryURL = \"https://api.foursquare.com/v2/venues/search\";\n $.ajax({\n url: queryURL,\n data: {\n client_id: \"UYCPKGBHUK5DSQSOGFBATS2015CFIZM1CELCN4AIYPT1LEBH\",\n client_secret: \"EBLDOOVW2FIZBGC0PH3M2NATAUCABKHWRVIC3YFRW1SOTKKF\",\n ll: longitudeLatitude,\n query: food,\n v: \"20180206\",\n limit: 3\n },\n cache: false,\n type: \"GET\",\n success: function(response) {\n console.log(response);\n getImages(response);\n appendFourSquare(response);\n },\n error: function(xhr) {\n console.log(xhr);\n }\n });\n}", "function fetchrestaurants() {\n var data;\n $.ajax({\n url: 'https://api.foursquare.com/v2/venues/search',\n dataType: 'json',\n data: 'client_id=LEX5UAPSLDFGAG0CAARCTPRC4KUQ0LZ1GZSB4JE0GSSGQW3A&client_secret=0QUGSWLF4DJG5TM2KO3YCUXUB2IJUCHDNSZC0FUUA3PKV0MY&v=20170101&ll=28.613939,77.209021&query=restaurant',\n async: true,\n }).done(function (response) {\n data = response.response.venues;\n data.forEach(function (restaurant) {\n var foursquare = new Foursquare(restaurant, map);\n self.restaurantList.push(foursquare);\n });\n self.restaurantList().forEach(function (restaurant) {\n if (restaurant.map_location()) {\n google.maps.event.addListener(restaurant.marker, 'click', function () {\n self.selectrestaurant(restaurant);\n });\n }\n });\n }).fail(function (response, status, error) {\n\t\t\tself.queryResult('restaurant\\'s could not load...');\n });\n }", "getPlaceInfo(pos) {\n\t\tlet venueID = '';\n\t\tlet lat = pos.lat, lng = pos.lng;\t\t\n\n\t\t//this fetch's purpose is to find the venueID of the given position\n\t\treturn fetch(`https://api.foursquare.com/v2/venues/search?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&v=${VERSION}&ll=${lat},${lng}`)\n\t\t .then(data => data.json())\n\t\t .then(data => {\n\t\t \tvenueID = data.response.venues[0].id;\n\t\t \treturn this.getPlaceTip(venueID);\n\t\t })\n\t\t .catch(function(e) {\n\t\t console.log(e);\n\t\t return null;\n\t\t });\t \n\t}", "function getLocationsData() {\n middle = getMiddle();\n setPointOnMap(middle.lat, middle.long, key);\n var radiusInMeters = radius * 1609.34;\n\n $('.poweredBy').fadeIn();\n\n // create accessor\n var accessor = {\n consumerSecret: auth.consumerSecret,\n tokenSecret: auth.accessTokenSecret\n };\n\n // push params\n var parameters = [];\n parameters.push(['category_filter', category]);\n parameters.push(['sort', 1]);\n parameters.push(['limit', 10]);\n parameters.push(['radius_filter', radiusInMeters]);\n parameters.push(['ll', middle.lat + ',' + middle.long]);\n parameters.push(['oauth_consumer_key', auth.consumerKey]);\n parameters.push(['oauth_consumer_secret', auth.consumerSecret]);\n parameters.push(['oauth_token', auth.accessToken]);\n parameters.push(['oauth_signature_method', 'HMAC-SHA1']);\n\n var message = {\n 'action': 'http://api.yelp.com/v2/search',\n 'method': 'GET',\n 'parameters': parameters\n };\n\n OAuth.setTimestampAndNonce(message);\n OAuth.SignatureMethod.sign(message, accessor);\n\n var parameterMap = OAuth.getParameterMap(message.parameters);\n parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature);\n\n var qs = '';\n\n for (var p in parameterMap) {\n qs += p + '=' + parameterMap[p] + '&';\n }\n\n var url = message.action + '?' + qs;\n\n\n WinJS.xhr({\n url: url\n }).then(success, failure);\n\n $('#searching').show(); // hide progress\n\n // handles a succesful yelp response\n function success(result) {\n\n var response = window.JSON.parse(result.responseText);\n\n $('#searching').hide(); // hide progress\n\n if (response.businesses.length == 0) { // handle no results error\n $('.error').show();\n\n if (radius == 25) {\n $('.error .noresultsLargest').show();\n }\n else {\n $('.error .noresults').show();\n }\n\n }\n\n var businesses = response.businesses;\n\n var list = new WinJS.Binding.List(); // create a new list to hold items\n\n response.businesses.forEach(function (item) {\n\n var cleaned = [];\n cleaned['name'] = item.name;\n\n var imgurl = item.image_url;\n\n if (imgurl == null || imgurl == '') {\n imgurl = '/images/no-image.png';\n }\n\n cleaned['image_url'] = imgurl;\n\n var address = '';\n var url_address = '';\n\n for (var x = 0; x < item.location.display_address.length; x++) {\n if (x > 0) {\n address += '<br>';\n url_address += ' ';\n }\n address = address + item.location.display_address[x];\n url_address = url_address + item.location.display_address[x];\n }\n\n cleaned['display_address'] = address;\n cleaned['url_address'] = encodeURIComponent(url_address);\n cleaned['city'] = item.location.city;\n cleaned['state'] = item.location.state_code;\n cleaned['city_state'] = item.location.city + ', ' + item.location.state_code;\n cleaned['cross_streets'] = item.location.cross_streets;\n cleaned['latitude'] = item.location.coordinate.latitude;\n cleaned['longitude'] = item.location.coordinate.longitude;\n cleaned['rating_img_url'] = item.rating_img_url;\n cleaned['display_phone'] = item.display_phone;\n cleaned['review_count'] = item.review_count;\n cleaned['url'] = item.url;\n cleaned['distance'] = (item.distance / 1609.34).toFixed(2) + ' miles away from the middle';\n\n list.push(cleaned);\n });\n\n // Set up the ListView\n var listView = el.querySelector(\".itemlist\").winControl;\n ui.setOptions(listView, {\n itemDataSource: list.dataSource,\n itemTemplate: el.querySelector(\".itemtemplate\"),\n layout: new ui.ListLayout(),\n oniteminvoked: itemInvoked\n });\n\n\n function itemInvoked(e) {\n\n var i = e.detail.itemIndex;\n\n // win-item\n var item = $(listView.element).find('.win-item')[i];\n\n var latitude = $(item).find('.lat').val();\n var longitude = $(item).find('.long').val();\n var title = $(item).find('.title').val();\n var address = jQuery.trim($(item).find('.address').val());\n var city_state = jQuery.trim($(item).find('.city_state').val());\n var url_address = jQuery.trim($(item).find('.url_address').val());\n var url = $(item).find('.url').val();\n var photo = $(item).find('.photo').val();\n var ratingimage = $(item).find('.ratingimage').val();\n var reviews = $(item).find('.reviews').val();\n var phone = $(item).find('.phone').val();\n\n current = {\n latitude: latitude,\n longitude: longitude,\n title: title,\n address: address,\n url_address: url_address,\n city_state: city_state,\n url: url,\n photo: photo,\n ratingimage: ratingimage,\n reviews: reviews,\n phone: phone,\n key: key\n };\n\n showCurrentInfoBox();\n }\n\n }\n\n // handles a failed yelp response\n function failure(result) {\n debug(result.responseText);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns LContext associated with a target passed as an argument. Throws if a given target doesn't have associated LContext.
function loadContext(target) { var context = getContext(target); if (!context) { throw new Error(ngDevMode ? "Unable to find context associated with " + stringify$1(target) : 'Invalid ng target'); } return context; }
[ "getContextById(context) {\n if (typeof context === 'string' || context instanceof String) {\n return this.contexts[context];\n }\n return context; // might already be a context object\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}", "function checkEntityContext(cmdTarget)\n{\n\t// If the entity array for this room exists:\n\tif ((roomArray[currentRoom].entities !== undefined) && (roomArray[currentRoom].entities.length > 0)) {\n\t\t// For each entity in the entity array:\n\t\tfor (var obj in roomArray[currentRoom].entities)\n\t\t{\n\t\t\t// If that entity belongs to the array and not the prototype:\n\t\t\tif (roomArray[currentRoom].entities.hasOwnProperty(obj))\n\t\t\t{\n\t\t\t\t// If the command matches the entity's name, this is the correct entity; return as much.\n\t\t\t\tif (cmdTarget == roomArray[currentRoom].entities[obj].ident) { return obj; }\n\t\t\t\t// Otherwise, check if the command matches any of that entity's aliases; if so, return that entity.\n\t\t\t\telse {\n\t\t\t\t\tfor (var objAlias in roomArray[currentRoom].entities[obj].alias) {\n\t\t\t\t\t\tif (cmdTarget == roomArray[currentRoom].entities[obj].alias[objAlias]) { return obj; }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// If none of these things matched, move on to the next entity in the loop.\n\t\t\t}\n\t\t}\n\t}\n\t// If the command failed to find any entity to match the command against, return -1 to indicate as much.\n\treturn -1;\n}", "function createGLContext() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n opts = Object.assign({}, contextDefaults, opts);\n var _opts = opts,\n canvas = _opts.canvas,\n width = _opts.width,\n height = _opts.height,\n throwOnError = _opts.throwOnError,\n manageState = _opts.manageState,\n debug = _opts.debug; // Error reporting function, enables exceptions to be disabled\n\n function onError(message) {\n if (throwOnError) {\n throw new Error(message);\n } // log.log(0, message)();\n\n\n return null;\n }\n\n var gl;\n\n if (_utils.isBrowser) {\n // Get or create a canvas\n var targetCanvas = (0, _createCanvas.getCanvas)({\n canvas: canvas,\n width: width,\n height: height,\n onError: onError\n }); // Create a WebGL context in the canvas\n\n gl = (0, _createBrowserContext.createBrowserContext)({\n canvas: targetCanvas,\n opts: opts\n });\n } else {\n // Create a headless-gl context under Node.js\n gl = (0, _createHeadlessContext.createHeadlessContext)({\n width: width,\n height: height,\n opts: opts,\n onError: onError\n });\n }\n\n if (!gl) {\n return null;\n } // Install context state tracking\n\n\n if (manageState) {\n (0, _trackContextState.default)(gl, {\n copyState: false,\n log: function log() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _utils.log.log.apply(_utils.log, [1].concat(args))();\n }\n });\n } // Add debug instrumentation to the context\n\n\n if (_utils.isBrowser && debug) {\n gl = (0, _debugContext.makeDebugContext)(gl, {\n debug: debug\n }); // Debug forces log level to at least 1\n\n _utils.log.priority = Math.max(_utils.log.priority, 1); // Log some debug info about the context\n } // Log context information\n\n\n logInfo(gl); // Add to seer integration\n\n return gl;\n}", "get target() {\n\t\treturn this.#target;\n\t}", "function getCachedMountContext(blockchain_or_datastore_id, full_app_name) {\n\n var userData = getUserData();\n assert(userData);\n\n assert(blockchain_or_datastore_id, 'No blockchain ID given');\n assert(full_app_name, 'No app name given');\n\n var cache_key = blockchain_or_datastore_id + '/' + full_app_name;\n\n if (!userData.datastore_contexts) {\n console.log(\"No datastore contexts defined\");\n return null;\n }\n\n if (!userData.datastore_contexts[cache_key]) {\n console.log('No datastore contexts for ' + blockchain_or_datastore_id + ' in ' + full_app_name);\n return null;\n }\n\n var ctx = userData.datastore_contexts[cache_key];\n if (!ctx) {\n console.log('Null datastore context for ' + blockchain_or_datastore_id + ' in ' + full_app_name);\n return null;\n }\n\n return ctx;\n}", "getTargetNode(props: PropsT) {\n const { children, targetRef, targetSelector } = props\n if (children) {\n return ReactDOM.findDOMNode(this._target)\n }\n if (targetRef) {\n return ReactDOM.findDOMNode(targetRef)\n }\n if (targetSelector) {\n return document.querySelector(targetSelector)\n }\n return null\n }", "getApplicationContext() {\n let context = \"\";\n // figure out the context we need to apply for where the editing creds\n // and API might come from\n // beaker is a unique scenario\n if (typeof DatArchive !== typeof undefined) {\n context = \"beaker\"; // implies usage of BeakerBrowser, an experimental browser for decentralization\n } else {\n switch (window.HAXCMSContext) {\n case \"published\": // implies this is to behave as if it is completely static\n case \"nodejs\": // implies nodejs based backend, tho no diff from\n case \"php\": // implies php backend\n case \"11ty\": // implies 11ty static site generator\n case \"demo\": // demo / local development\n case \"desktop\": // implies electron\n case \"local\": // implies ability to use local file system\n case \"userfs\": // implies hax.cloud stylee usage pattern\n context = window.HAXCMSContext;\n break;\n default:\n // we don't have one so assume it's php for now\n // @notice change this in the future\n context = \"php\";\n break;\n }\n }\n return context;\n }", "getSuggestionFor(target) {\n return target && this.suggestionMap.get(target);\n }", "function get_elem(target) {\n return document.querySelector(target);\n }", "function ExprContext(node, opt_position, opt_nodelist, opt_parent,\n opt_caseInsensitive, opt_ignoreAttributesWithoutValue,\n opt_returnOnFirstMatch)\n{\n this.node = node;\n this.position = opt_position || 0;\n this.nodelist = opt_nodelist || [ node ];\n this.variables = {};\n this.parent = opt_parent || null;\n this.caseInsensitive = opt_caseInsensitive || false;\n this.ignoreAttributesWithoutValue = opt_ignoreAttributesWithoutValue || false;\n this.returnOnFirstMatch = opt_returnOnFirstMatch || false;\n if (opt_parent) {\n this.root = opt_parent.root;\n } else if (this.node.nodeType == DOM_DOCUMENT_NODE) {\n // NOTE(mesch): DOM Spec stipulates that the ownerDocument of a\n // document is null. Our root, however is the document that we are\n // processing, so the initial context is created from its document\n // node, which case we must handle here explcitly.\n this.root = node;\n } else {\n this.root = node.ownerDocument;\n }\n}", "function checkInvContext(cmdTarget)\n{\n\t// If the inventory exists:\n\tif ((inventory !== undefined) && (inventory.length > 0)) {\n\t\t// For each item in the inventory:\n\t\tfor (var obj in inventory)\n\t\t{\n\t\t\t// If that item belongs to the array and not the prototype:\n\t\t\tif (inventory.hasOwnProperty(obj))\n\t\t\t{\n\t\t\t\t// If the command matches the item's name, this is the correct item; return as much.\n\t\t\t\tif (cmdTarget == inventory[obj].ident) { return obj; }\n\t\t\t\t// Otherwise, check if the command matches any of that item's aliases; if so, return this item.\n\t\t\t\telse {\n\t\t\t\t\tfor (var objAlias in inventory[obj].alias) {\n\t\t\t\t\t\tif (cmdTarget == inventory[obj].alias[objAlias]) { return obj; }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// If none of these things matched, move on to the next item in the loop.\n\t\t\t}\n\t\t}\n\t}\n\t// If the command failed to find any item to match the command against, return -1 to indicate as much.\n\treturn -1;\n}", "function getOffset(target) {\n\t\tif (target instanceof Array) {\n\t\t\treturn Rect(target[0], target[1], target[2] || target[0], target[3] || target[1]);\n\t\t}\n\n\t\tif (typeof target === 'string') {\n\t\t\t//`100, 200` - coords relative to offsetParent\n\t\t\tvar coords = target.split(/\\s*,\\s*/).length;\n\t\t\tif (coords === 2) {\n\t\t\t\treturn Rect(parseInt(coords[0]), parseInt(coords[1]));\n\t\t\t}\n\t\t}\n\n\t\tif (!target) {\n\t\t\treturn Rect();\n\t\t}\n\n\t\t//`.selector` - calc selected target coords relative to offset parent\n\t\treturn offset(target);\n\t}", "function getFileContext(contentPath){\n\tvar contextPath = getContextFilePath(contentPath),\n\t\t\tparent = '';\n\n\ttry {\n\t\tif (!_.isUndefined(siteContext.files[contextPath])) {\n\t\t\treturn siteContext.files[contextPath].context;\n\t\t} else if (useNearestContext){\n\t\t\t//TODO: try to find the nearest matching context up the tree\n\t\t\t//doc this option for the grunt file\n\t\t\tparent = util.getDirectoryPath(contentPath)+'/'+util.getParentDirectory(contentPath);\n\t\t\tgrunt.log.debug(parent);\n\t\t\tif (parent !== '.'){\n\t\t\t\treturn getFileContext(parent);\n\t\t\t} else {\n\t\t\t\tgrunt.log.debug('ran out of parents');\n\t\t\t\treturn {};\n\t\t\t}\n\t\t}\n\t} catch(error){\n\t\tgrunt.log.error(error);\n\t\treturn {};\n\t}\n}", "getChildContext() {\n return { translator };\n }", "function findHighlightTarget(start) {\n let target = start;\n\n while (target.nodeName === 'tspan') target = target.parentNode;\n\n if (target.nodeName === 'text') target = target.parentNode;\n\n if (target.nodeName === 'g' || target.nodeName === 'a') {\n let children = target.getElementsByTagName('rect');\n if (children.length === 0) {\n children = target.getElementsByTagName('path');\n }\n\n if (children.length === 0) return undefined;\n\n target = children.item(0);\n }\n\n return (\n target.nodeName === 'rect' ||\n target.nodeName === 'path' ||\n target.nodeName === 'circle' ||\n target.nodeName === 'ellipse') ? target : undefined;\n}", "function getParent(feature, fm) {\n\tfor (var i=0; i < fm.edges.length; i++) {\n\t\tvar edge = fm.edges[i];\n\t\tif (edge.source == feature) {\n\t\t\treturn edge.target;\n\t\t}\n\t}\n\n\treturn null;\n}", "function getParent(eventTarget) {\n return isNode(eventTarget) ? eventTarget.parentNode : null;\n }", "function CLC_Content_FindLabelText(target){\r\n var logicalLineage = CLC_GetLogicalLineage(target);\r\n var labelText = \"\";\r\n for (var i=0; i < logicalLineage.length; i++){\r\n if (logicalLineage[i].tagName && (logicalLineage[i].tagName.toLowerCase() == \"label\")){\r\n labelText = labelText + \" \" + logicalLineage[i].textContent;\r\n }\r\n }\r\n return labelText;\r\n }", "function localCompletionSource(context) {\n let inner = dist_syntaxTree(context.state).resolveInner(context.pos, -1)\n if (dontComplete.indexOf(inner.name) > -1) return null\n let isWord =\n inner.name == 'VariableName' ||\n (inner.to - inner.from < 20 &&\n Identifier.test(context.state.sliceDoc(inner.from, inner.to)))\n if (!isWord && !context.explicit) return null\n let options = []\n for (let pos = inner; pos; pos = pos.parent) {\n if (ScopeNodes.has(pos.name))\n options = options.concat(getScope(context.state.doc, pos))\n }\n return {\n options,\n from: isWord ? inner.from : context.pos,\n validFor: Identifier\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function draw// function drawArcade
function drawArcade(x, y) { if(back1){ push(); translate(arcadeVX, 0) scale(arcadeSC) var arcadeX = 0 fill(255, 165, 0) rect(arcadeX, 0, 500, 500) for (i = 0; i < 5; i++) { fill(0); //body rect(arcadeX, 100, 100, 300) fill(255); //header rect(arcadeX + 10, 110, 80, 30) fill(250, 128, 114) rect(arcadeX + 15, 115, 70, 20, 5) fill(random(100, 150)); //screen rect(arcadeX + 10, 170, 80, 80) fill(128); //remote rect(arcadeX + 18, 230, 2, 20) fill(128, 0, 0) ellipse(arcadeX + 20, 235, 10) rect(arcadeX + 40, 248, 10, 2) rect(arcadeX + 55, 248, 10, 2) rect(arcadeX + 70, 248, 10, 2) fill(0, 0, 205); //body detail rect(arcadeX + 10, 280, 80, 100) fill(255); //balls ellipse(arcadeX + 30, 320, 10) ellipse(arcadeX + 50, 320, 10) ellipse(arcadeX + 70, 320, 10) fill(255, 215, 0) //pacman arc(arcadeX + 30, 320, 30, 30, PI/4, 7*PI/4, PIE) arcadeX+=100 } pop(); } }
[ "function draw()\r\n\t{\r\n\t\tvar canvas = document.getElementById('canvas');\r\n\t\tif(canvas.getContext)\r\n\t\t{\r\n\t\t\tvar context = canvas.getContext('2d');\r\n\t\t\t// draw body\r\n\t\t\tif(this.state == playerStates.respawning) context.fillStyle= \"rgba(0,200,0,0.4)\"; // set fillStyle to dark green\r\n\t\t\telse context.fillStyle= \"rgb(0,200,0)\"; // set fillStyle to dark green\r\n\t\t\t\t\r\n\t\t\tcontext.fillRect(this.rect.pos.x,this.rect.pos.y,this.rect.dim.width,this.rect.dim.height);\r\n\t\t\t\r\n\t\t\t// left arm\r\n\t\t\tcontext.fillRect(this.arms.leftArm.pos.x,this.arms.leftArm.pos.y,this.arms.leftArm.dim.width,this.arms.leftArm.dim.height);\r\n\t\t\t// right arm\r\n\t\t\tcontext.fillRect(this.arms.rightArm.pos.x,this.arms.rightArm.pos.y,this.arms.rightArm.dim.width,this.arms.rightArm.dim.height);\r\n\t\t\t// left leg\r\n\t\t\tcontext.fillRect(this.legs.leftLeg.pos.x,this.legs.leftLeg.pos.y,this.legs.leftLeg.dim.width,this.legs.leftLeg.dim.height);\r\n\t\t\t//right leg\r\n\t\t\tcontext.fillRect(this.legs.rightLeg.pos.x,this.legs.rightLeg.pos.y,this.legs.rightLeg.dim.width,this.legs.rightLeg.dim.height);\r\n\t\t\t\r\n\t\t\t// switch to black for eyes\r\n\t\t\tcontext.fillStyle= \"rgb(0,0,0)\"; // set fillStyle to black\r\n\t\t\t// left eye\r\n\t\t\tcontext.fillRect(this.eyes.left.pos.x,this.eyes.left.pos.y,this.eyes.left.dim.width,this.eyes.left.dim.height);\r\n\t\t\t//right eye\r\n\t\t\tcontext.fillRect(this.eyes.right.pos.x,this.eyes.right.pos.y,this.eyes.right.dim.width,this.eyes.right.dim.height);\r\n\t\t\t\r\n\t\t\tif(this.drawJumpZone)\r\n\t\t\t{\r\n\t\t\t\t// draw jumpzone\r\n\t\t\t\tif(this.jumpZone.inZone)\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(0,255,0)\"; // set fillStyle to green\r\n\t\t\t\telse\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(255,0,0)\"; // set fillStyle to red\r\n\t\t\t\t\r\n\t\t\t\tcontext.lineWidth = 2;\r\n\t\t\t\tcontext.strokeRect(this.jumpZone.rect.pos.x, this.jumpZone.rect.pos.y, this.jumpZone.rect.dim.width, this.jumpZone.rect.dim.height);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// draw lives\r\n\t\t\tthis.lifeBar.draw();\r\n\t\t}\r\n\t}", "function draw() {\n background(bg);\n \n drawBall();\n drawLPaddle();\n drawRPaddle();\n ballCollision();\n rPaddleCollision();\n lPaddleCollision();\n drawScore();\n resetBallPosition();\n \n}", "function draw() {\r\n if (currentScene === 1) {\r\n drawTitleScreen();\r\n drawPlayButton();\r\n drawPractiseButton();\r\n drawRules();\r\n hint.draw();\r\n hint.update();\r\n goalSign();\r\n }\r\n if (currentScene === 2) { // zoals je kan zien wordt dit getekent bij scene 2\r\n drawPongTheGame();\r\n drawScoreBoard();\r\n drawBatjeA();\r\n drawBatjeB();\r\n batjesUpdate();\r\n goalSign();\r\n }\r\n if (currentScene === 3) { // en onderstaande wordt getekent bij scene 3\r\n drawPractiseRoom();\r\n drawBackButton();\r\n drawScoreBoardPractise();\r\n drawBatjeB();\r\n batjesUpdate();\r\n }\r\n if (currentScene === 10) { // dit wordt getekent bij scene 10\r\n drawTitleScreenExtreme();\r\n drawTitleAnimation();\r\n drawPlayExtremeButton();\r\n drawPractiseExtremeButton();\r\n drawRulesExtreme();\r\n PowerUpNr = 0;\r\n speeding = 1*resize;\r\n }\r\n if (currentScene === 11){ // dit wordt getekent bij scene 11\r\n drawPongExtreme();\r\n drawBatjeAExtreme();\r\n drawBatjeBExtreme();\r\n drawScoreBoardExtreme();\r\n batjesUpdate();\r\n drawPowerUps();\r\n goalSign();\r\n }\r\n if(currentScene === 12){ // dit wordt getekent bij scene 12\r\n drawRulesScreenExtreme();\r\n drawBackButton();\r\n drawTitleAnimation();\r\n \r\n \r\n }\r\n if(surpriseBart === true){ // dit wordt getekent wanneer de B toets wordt ingedrukt\r\n bSurprise();\r\n }\r\n}", "function draw() \n{\n\tif (screenChanger == 0)\n\t{\n\t\tscreenDecision1();\n\t}\n \n\telse if (screenChanger == 1)\n\t{\n\t\tscreenWelcome();\n\t}\n \n\telse if (screenChanger == 4)\n\t{\n\t\tscreenFail();\n\t}\n \n\telse if (screenChanger == 5)\n\t{\n\t\tscreenCongrats();\n\t}\n\t\n else if (screenChanger == 6)\n {\n screenCircles();\n }\n\t \n else if (screenChanger == 7)\n {\n\t\tscreenRectangles();\n }\n\t \n else if (screenChanger == 8)\n {\n screenTriangles();\n }\n}", "function draw() {\n\n // Cases to handle Game over.\n if (player.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n else if (enemy.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n \n // check for player commands\n playerAction();\n\n // Multiple IF to check if it is players turn or Enemy, also if Projectile exist or not.\n if (Game.projectile != null) {\n Game.projectile.draw();\n }\n if (Game.playerTurn == true && Game.projectile != null) {\n if (Game.checkCollision(Game.projectile, enemy)) {\n Game.hit(enemy)\n Game.playerTurn = false;\n }\n }\n if (Game.playerTurn == false) {\n enemy.enemyTurn(player);\n if (Game.checkCollision(Game.projectile, player)) {\n Game.hit(player)\n Game.playerTurn = true;\n }\n }\n if (Game.projectile != null && !Game.checkCollision(Game.projectile, game) && player.firearm == 0) {\n Game.miss();\n }\n for (var i = 0; i < Game.map.length; i++) {\n if (Game.checkCollision(Game.projectile, Game.map[i])) {\n Game.projectile.clear();\n \n staticTexture.clear(Game.map[i])\n Game.map[i] = null;\n Game.miss();\n\n }\n }\n player.draw();\n enemy.draw();\n // If game over, stop callback.\n if (Game.over == false) {\n window.requestAnimationFrame(draw);\n }\n }", "function draw() {\n background(\"black\");\n scenery();\n\n //Loop over length of menagerie and call appropriate methods\n for (let i = 0; i < menagerie.length; i++) {\n menagerie[i].display();\n menagerie[i].update();\n menagerie[i].move();\n\n if (mouseIsPressed) {\n fill(\"white\");\n triangle(mouseX, mouseY, mouseX + 5, mouseY - 30, mouseX + 10, mouseY);\n arc(mouseX, mouseY, 30, 10, 0, 90);\n }\n }\n\n}", "function drawIntro(){\n\t\n}", "draw()\n {\n var canvas = document.getElementById(\"CANVAS\");\n var ctx = canvas.getContext(\"2d\");\n var cVehicles = this.getVehicleCount();\n\n ctx.save();\n ctx.scale(def.scale, def.scale);\n\n this._drawRoute(ctx);\n for (let iVehicle = 0; iVehicle < cVehicles; iVehicle ++)\n this._drawVehicle(ctx, route.getVehicle(iVehicle));\n\n ctx.restore();\n }", "function draw() {\n // Clear the background to black\n background(0);\n\n // Handle input for the tiger\n tiger.handleInput();\n lion.handleInput();\n // Move all the \"animals\"\n tiger.move();\n lion.move();\n antelope.move();\n zebra.move();\n bee.move();\n\n // Handle the tiger eating any of the prey\n tiger.handleEating(antelope);\n tiger.handleEating(zebra);\n tiger.handleEating(bee);\n\n lion.handleEating(antelope);\n lion.handleEating(zebra);\n lion.handleEating(bee);\n\n // Display all the \"animals\"\n tiger.display();\n lion.display();\n antelope.display();\n zebra.display();\n bee.display();\n}", "function draw_s() {\n ctx.beginPath()\n canvas_arrow(ctx, passthroughCoords.x - 2, passthroughCoords.y - 2, refractedCoords.x + 2, refractedCoords.y + 2)\n ctx.stroke()\n }", "show() {\n var pos = this.body.position;\n var angle = this.body.angle;\n\n push();\n translate(pos.x, pos.y);\n rotate(angle);\n rectMode(CENTER);\n\n drawSprite(this.birdspr);\n /* strokeWeight(1);\n stroke(255);\n fill(127);\n ellipse(0, 0, this.r * 2);\n line(0, 0, this.r, 0);*/\n pop();\n }", "function draw(){\n\n mCanvas.background(255);\n drawBirdsGraphics();\n\n push();\n\n if(soundWater.isPlaying()){\n drawWaterGraphics();\n push(); \n }\n\n if(soundBell.isPlaying()){\n drawBellGraphics();\n push();\n }\n\n if(soundGlass.isPlaying()){\n drawGlassGraphics();\n push();\n }\n\n if(soundSeller.isPlaying()){\n drawSellerGraphics();\n push();\n }\n\n if(soundGong.isPlaying()){\n drawGongGraphics();\n push();\n }\n\n if(soundGuitar.isPlaying()){\n drawGuitarGraphics();\n push();\n }\n\n if(soundTrafficLight.isPlaying()){\n drawTrafficlightGraphics();\n push();\n }\n\n}", "draw() {\r\n context.strokeStyle = \"#fafafa\";\r\n context.fillStyle = \"#10e831\";\r\n if (this.status == \"infected\") context.fillStyle = \"#e60202\";\r\n context.beginPath();\r\n // Calls the 'arc' method and inputs the x and y coordinates, radius, 0 and PI*2 = 360 degrees\r\n context.arc(this.x,this.y,this.r,0,Math.PI*2);\r\n // Calls the 'fill' method\r\n context.fill();\r\n // Calls the 'stroke' method\r\n context.stroke();\r\n }", "function draw() {\n background('#01633d');\n\n // will call your state machine function\n drawFunction();\n}", "function mainMenuDraw() {\r\n\tif (showCredits) {\r\n\t\tdrawFullScreenImage(creditsScreen);\r\n\t\tseeMainMenuButtons(false);\r\n\t} else {\r\n\t\tdrawFullScreenImage(mainMenu);\r\n\t}\r\n}", "function draw() {\n background (50, 255, 50);\n\n//shape outline\n noStroke()\n\n//kermit image\n imageMode(CENTER);\n image(kermitImage, mouseX, mouseY);\n\n\n // covid 19 movement\n covid19.x = covid19.x + covid19.vx;\n covid19.y = covid19.y + covid19.vy;\n\n if (covid19.x > width) {\n covid19.x = 0;\n covid19.y = random(0,height);\n }\n\n //covid 19 growth\n if (covid19.x < width/1.002){\n covid19.size = covid19.size + 3;\n }\n else {\n covid19.size = 100;\n }\n\n // covid 20 movement\n covid20.x = covid20.x + covid20.vx;\n covid20.y = covid20.y + covid20.vy;\n\n if (covid20.x > width) {\n covid20.x = 0;\n covid20.y = random(0,height);\n }\n\n //covid 20 growth\n if (covid20.x < width/1.002){\n covid20.size = covid20.size + 1;\n }\n else {\n covid20.size = 100;\n }\n\n //user movement\n user.x = mouseX;\n user.y = mouseY;\n\n // check for bumping covid19\n let d = dist(user.x,user.y,covid19.x,covid19.y);\n if (d < covid19.size/2 + user.size/2) {\n noLoop();\n }\n\n // display covid 19\n fill(covid19.fill.r, covid19.fill.g, covid19.fill.b);\n ellipse(covid19.x, covid19.y, covid19.size);\n\n // display covid 20\n fill(covid20.fill.r, covid20.fill.g, covid20.fill.b);\n ellipse(covid20.x, covid20.y, covid20.size);\n\n // display user\n fill(user.fill);\n square(user.x, user.y, user.size);\n\n}", "function dieDraw2(ctx,reverse) {\n\n reverse = typeof(reverse) != 'undefined' ? reverse : false;\n\n var dot_x;\n var dot_y;\n\n ctx.beginPath();\n dot_x = dicex + 3 * dotrad;\n dot_y = reverse ? dicey + diceh - 3 * dotrad : dicey + 3 * dotrad;\n ctx.arc( dot_x, dot_y, dotrad, 0, Math.PI * 2);//, true );\n\n dot_x = dicex + dicew - 3 * dotrad;\n dot_y = reverse ? dicey + 3 * dotrad : dicey + diceh - 3 * dotrad;\n ctx.arc( dot_x, dot_y, dotrad, 0, Math.PI * 2);//, true );\n\n ctx.closePath();\n ctx.fill();\n\n}", "drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }", "update() {\r\n\t\tthis.flock();\r\n\t\tthis.drawBoid();\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
w1 ^ w2 :: Word > Word > BigNat
function h$ghcjsbn_pow_ww(w1, w2) { h$ghcjsbn_assertValid_s(w1, "pow_ww w1"); h$ghcjsbn_assertValid_s(w2, "pow_ww w2"); var b = h$ghcjsbn_tmp_2a; h$ghcjsbn_toBigNat_w(b, w1); var t = h$ghcjsbn_pow_bw(b, w2); h$ghcjsbn_assertValid_b(t, "pow_ww result"); return t; }
[ "function XOR() {\n for (var _len15 = arguments.length, values = Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {\n values[_key15] = arguments[_key15];\n }\n\n return !!(FLATTEN(values).reduce(function (a, b) {\n if (b) {\n return a + 1;\n }\n return a;\n }, 0) & 1);\n}", "function diff(idx1, idx2) {\n if (word1[idx1-1] === word2[idx2-1]) {\n return 0;\n }\n return 1;\n }", "function hammingDistance(codewordOne, codewordTwo) {\n // compute the bitwise Boolean EXCLUSIVE OR of the two codewords\n var bitwiseXORResult = (parseInt(codewordOne, 2) ^ parseInt(codewordTwo, 2)).toString(2);\n // count the number of one bits in the result \n let result = 0;\n for (char of bitwiseXORResult) {\n if (char === '1') result += 1; \n }\n console.log('For %s and %s the Hamming distance is %s.', codewordOne, codewordTwo, result);\n return result;\n}", "function xor_strings(a, b) {\n //xor is only carried out if the two strings have the same length\n if(a.length != b.length) {\n alert(\"Error calculating XOR\");\n return;\n }\n var output = \"\";\n for (var i=0; i<a.length; i ++) {\n output+=XOR(a[i],b[i]);\n }\n return output;\n}", "function simple_xor2(b) {\n switch (b) {\n case 1: return 0;\n case 0: return 1;\n default: return \"invalid\"\n }\n}", "function xor(a, b) {\n assert.equal(a.length, b.length);\n\n var length = a.length,\n result = new Buffer(length);\n\n for (var i = 0; i < length; i++) {\n result[i] = a[i] ^ b[i];\n }\n\n return result;\n}", "function xor(a, b) {\n\n if (!!a ^ !!b == 1) {\n return true;\n }\n}", "function G_SetXOR(list1, list2) {\n var list1Map = {};\n var list2Map = {};\n var output1 = [];\n var output2 = [];\n\n for (var i = 0; i < list1.length; i++) {\n list1Map[list1[i]] = true;\n }\n\n for (var i = 0; i < list2.length; i++) {\n list2Map[list2[i]] = true;\n }\n\n for (var key in list1Map) {\n if (!(list2Map[key])) {\n output1.push(key);\n }\n }\n\n for (var key in list2Map) {\n if (!(list1Map[key])) {\n output2.push(key);\n }\n }\n\n return {\n xor: Array.concat(output1, output2),\n left: output1, \n right: output2\n };\n}", "[symbols.ne](other)\n\t{\n\t\treturn !this[symbols.eq](other);\n\t}", "function canMatchLength(word1, word2) {\n \t\t\tif(word1.length == word2.length) {\n \t\t\t\treturn true;\n \t\t\t}\n \t\t\tlet shorter = word1.length > word2.length ? word2 : word1;\n \t\t\tlet longer = shorter == word1 ? word2 : word1;\n \t\t\treturn shorter.length + totalWC(shorter) * 3 >= longer.length - totalWC(longer);\n \t\t}", "function VxEuclideanRythm ()\n{\n\tthis.k = 4;\n\tthis.N = 16;\n\tthis.R = 0;\n\tthis.algorithm = 'bjorklund';\n\tthis.integermode = 0;\n}", "visitXor_expr(ctx) {\r\n console.log(\"visitXor_expr\");\r\n let length = ctx.getChildCount();\r\n let value = this.visit(ctx.and_expr(0));\r\n for (var i = 1; i * 2 < length; i = i + 1) {\r\n if (ctx.getChild(i * 2 - 1).getText() === \"^\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"^\",\r\n left: value,\r\n right: this.visit(ctx.and_expr(i)),\r\n };\r\n }\r\n }\r\n return value;\r\n }", "function hs_wordToWord64(low) {\n return [0, low];\n}", "function inWord(bit) {\n return Math.floor((bit | 0) / 32);\n }", "function isReal(w1, w2){\n\n let real = false;\n\n for(let i=0; i<w2.length; i++){\n let current = w2[i];\n let currentNext = w2[i+1];\n let combinedTwo = current+currentNext;\n let combinedThree = current+currentNext+w2[i+2];\n\n //Vowel-Consonent (or) consonent-Vowel\n if( ( (vowelsSet.has(current) && consonentsSet.has(currentNext)) || (consonentsSet.has(current) && vowelsSet.has(currentNext)) ) ||\n (rulesSet.has(combinedTwo) || rulesSet.has(combinedTwo) || //If the Two or three are present in rulesset\n (consonentsSet.has(current) && consonentsSet.has(currentNext)) //if two consonents repeat NN or ZZ\n ) //Rules are present in ruleset\n ){\n real = true;\n }\n }\n return real;\n}", "function Logical (type, ax, bx) {\n var result = {value: null, // the result of the Logical operation\n diff : 0, // number of bits that are different between ax and bx\n change : 0, // estimate of the number of bits that need to be changed to get to eaither ax or bx from .value\n length : null, // size in terms of the number of bits\n up : 0, // number of bits rounded up\n down : 0, // number of bits rounded down\n type : type}; // type of operation\n if(ax.length != bx.length) {\n var resized = resize(ax, bx);\n ax = resized.ax;\n bx = resized.bx;\n }\n if (ax.length > 1 || bx.length > 1) {\n var msb = Logical(type, [ax[0]], [bx[0]]);\n var rem = Logical(type, ax.slice(1, ax.length), bx.slice(1, bx.length));\n // concatinate the msb with all the remaining bits\n result.value = [].concat(msb.value, rem.value);\n result.diff = msb.diff + rem.diff;\n result.change = msb.change + rem.change;\n result.length = msb.length + rem.length;\n result.up = msb.up + rem.up;\n result.down = msb.down + rem.down;\n return result;\n } \n else {\n if(ax[0] != bx[0] && (ax[0] != null && bx[0] != null)) {\n result.diff = 1;\n }\n switch (type) {\n case \"xor\": // xor means that things are totally different\n if (ax[0] != bx[0]) { \n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 1 || bx[0] == 1) ? 1 : ax[0] > bx[0] ? ax[0] : bx[0]; // or maybe have the value be whatever value is larger or non zero\n result.length = 1;\n if(ax[0] != null && bx[0] != null){\n result.change = .5; \n result.up = .5; \n }\n return result;\n } \n else { //(ax[0] == bx[0]) - with a corner case of null\n result.value = (ax[0] == null) ? null : 0; // TODO maybe both 0\n result.length = 1;\n if(ax[0] != 0 && ax[0] != null){\n result.down = 1; // TODO: maybe should be a % 3 and 3 for example\n result.change = 1; // both are 1 or both are the same value // maybe should be\n } \n }\n return result;\n break;\n case \"or\": // or means that things are similar or the same (similar to a round up only)\n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 0 && bx[0] == 0) ? 0 : ax[0] > bx[0] ? ax[0] : bx[0];\n if(result.value != null && result.value != 0){\n result.up = .5; \n result.change = .5; // TODO: check for null case maybe also check for case for result.down where ax or bx > 1 or a non 1 number\n }\n result.length = 1;\n return result;\n break;\n case \"and\": // and means that things are identical (similar to a round down only)\n if (ax[0] == bx[0]) {\n result.value = ax[0];\n result.change = 0;\n result.length = 1;\n return result;\n } \n else {\n result.value = (ax[0] == null || bx[0] == null) ? null : 0; // TODO: add these into the same function\n if(ax[0] != 0 && bx[0] != 0 && ax[0] != null && bx[0] != null){\n result.change = 1; // maybe 2\n result.down = 1; // maybe do a %%\n } else { // one is 1 the other is 0\n if(ax[0] != null && bx[0] != null) {\n result.change = .5;\n result.up = .5; // TODO maybe add the ammount up...\n } \n }\n result.length = 1;\n return result;\n }\n return result; \n break;\n default: // nand\n if(ax[0] == bx[0] && ax[0] != 0) {\n result.value = (ax[0] == null) ? null : 0; \n result.change = (ax[0] == null) ? 0 : 1;\n result.length = 1;\n result.down = (ax[0] == null) ? 0 : 1;\n return result;\n }\n else {\n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 0 && bx[0] == 0) ? 1 : ax[0] == 0 ? bx[0] : bx[0] == 0 ? ax[0] : ax[0] < bx[0] ? ax[0] : bx[0]; // TODO: sepcial case we do less (maybe change)\n if(ax[0] == 0 && bx[0] == 0) {\n result.change = 1;\n result.up = 1;\n } else {\n if(ax[0] != null && bx[0] != null){\n result.change = .5;\n result.up = .5; // TODO: Check this case maybe do Math.abs()\n }\n return result;\n }\n }\n return result;\n }\n }\n return result;\n}", "function dotProduct(vec1, vec2) {\n return vec1[0]*vec2[0] + vec1[1]*vec2[1];\n}", "function findLevenshteinDistance(word_a, word_b) {\n\tlet distMatrix = [];\n\n\tfor (var i = 0; i < (word_b.length + 2); i++) {\n\t\tdistMatrix[i] = [];\n\n\t\tfor (var j = 0; j < (word_a.length + 2); j++) {\n\t\t\tdistMatrix[i][j] = '0';\n\t\t}\t\n\t}\n\n\tdistMatrix[0][0] = '-'; //free.\n\tdistMatrix[0][1] = ' '; //setting empty word.\n\tdistMatrix[1][0] = ' '; //setting empty word.\n\n\tlet wa = word_a.split('');\n\tlet wb = word_b.split('');\n\n\t//consuming word_a.\n\tfor (var j = 2; j < (wa.length + 2); j++) {\n\t\tdistMatrix[0][j] = wa[(j - 2)];\n\t\tdistMatrix[1][j] = (j - 1).toString();\n\t}\n\n\t//consuming word_b.\n\tfor (var i = 2; i < (wb.length + 2); i++) {\n\t\tdistMatrix[i][0] = wb[(i - 2)];\n\t\tdistMatrix[i][1] = (i - 1).toString();\n\t}\n\n\t//Calculating edit distances.\n\tfor (var i = 2; i < (wb.length + 2); i++) {\n\t\tfor (var j = 2; j < (wa.length + 2); j++) {\n\t\t\tlet collumnIndex = j;\n\t\t\tlet lineIndex = i;\n\n\t\t\twhile(distMatrix[0][collumnIndex] == distMatrix[lineIndex][0] && collumnIndex > 2 && lineIndex > 2) {\n\t\t\t\tlineIndex--;\n\t\t\t\tcollumnIndex--;\n\t\t\t}\n\n\t\t\t// console.log(\"lineIndex: \", lineIndex);\n\t\t\t// console.log(\"collumnIndex: \", collumnIndex);\n\n\t\t\tif (collumnIndex > 2 || lineIndex > 2) {\n\t\t\t\tlet deleteCost = parseInt(distMatrix[lineIndex][(collumnIndex - 1)]);\n\t\t\t\tlet replaceCost = parseInt(distMatrix[(lineIndex - 1)][(collumnIndex - 1)]);\n\t\t\t\tlet insertCost = parseInt(distMatrix[(lineIndex - 1)][collumnIndex]);\n\n\t\t\t\tlet helper = deleteCost < replaceCost ? deleteCost : replaceCost;\n\t\t\t\tlet smallestCost = insertCost < helper ? insertCost : helper;\n\n\t\t\t\tdistMatrix[i][j] = (smallestCost + 1).toString();\n\t\t\t} else {\n\t\t\t\tdistMatrix[i][j] = '0';\n\t\t\t}\n\t\t}\n\t}\n\n\tlet dif = (parseInt(distMatrix[word_b.length + 1][word_a.length + 1]) * 100) / word_b.length;\n\n\tconsole.log('\\n_________________________________');\n\tconsole.log(\"\\nWord A: \", word_a);\n\tconsole.log(\"Word B: \", word_b);\n\tconsole.log(\"\\nLevenshtein distance: \", distMatrix[word_b.length + 1][word_a.length + 1]);\n\tconsole.log(\"Structural difference: \", dif);\n\tconsole.log('_________________________________');\n\n\treturn parseInt(distMatrix[word_b.length + 1][word_a.length + 1]);\n}", "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 getSum(a, b) { \n return b == 0 ? a : getSum(a ^ b, (a & b) << 1)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a Wheat is destroyed, decrement the wheat count
onDestroy() { STATE.cows--; }
[ "function countHandTowelHwfMinus() {\n\t\t\tif(instantObj.noOfHandTowelHWF > 0) {\n\t\t\t\tinstantObj.noOfHandTowelHWF = instantObj.noOfHandTowelHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countShirtWwiMinus() {\n\t\t\tif(instantObj.noOfShirtWWI > 0) {\n\t\t\t\tinstantObj.noOfShirtWWI = instantObj.noOfShirtWWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countShirtWwfMinus() {\n\t\t\tif(instantObj.noOfShirtWWF > 0) {\n\t\t\t\tinstantObj.noOfShirtWWF = instantObj.noOfShirtWWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countHcoverHwfMinus() {\n\t\t\tif(instantObj.noOfHcoverHWF > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countHcoverHwiMinus() {\n\t\t\tif(instantObj.noOfHcoverHWI > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function upkeep() {\n\t\tif (state.food > 0) {\n\t\t\tstate.food--;\n\t\t} else {\n\t\t\tstate.health--;\n\t\t}\n\t}", "function countTowelHwfMinus() {\n\t\t\tif(instantObj.noOfTowelHWF > 0) {\n\t\t\t\tinstantObj.noOfTowelHWF = instantObj.noOfTowelHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countSweatshirtrJacketWwfMinus() {\n\t\t\tif(instantObj.noOfSweatshirtJacketWWF > 0) {\n\t\t\t\tinstantObj.noOfSweatshirtJacketWWF = instantObj.noOfSweatshirtJacketWWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countTshirtWwiMinus() {\n\t\t\tif(instantObj.noOfTshirtWWI > 0) {\n\t\t\t\tinstantObj.noOfTshirtWWI = instantObj.noOfTshirtWWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function decrementCount(key) {\n if (counts[key] < 2) {\n delete counts[key];\n } else {\n counts[key] -= 1;\n }\n }", "function countTshirtWwfMinus() {\n\t\t\tif(instantObj.noOfTshirtWWF > 0) {\n\t\t\t\tinstantObj.noOfTshirtWWF = instantObj.noOfTshirtWWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function whacked() {\n\tif (timeLeft > 0) {\n\t\tthis.classList.remove(\"mole\");\n\t\tthis.removeEventListener(\"click\", giveMePoints, true);\n\t\tthis.classList.add(\"whacked\");\n\t\tsetTimeout(resetWhacked, 250);\n\t}\n}", "function countLungiDhotiMwfMinus() {\n\t\t\tif(instantObj.noOfLungiDhotiMWF > 0) {\n\t\t\t\tinstantObj.noOfLungiDhotiMWF = instantObj.noOfLungiDhotiMWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countCarpetHwfMinus() {\n\t\t\tif(instantObj.noOfCarpetHWF > 0) {\n\t\t\t\tinstantObj.noOfCarpetHWF = instantObj.noOfCarpetHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countSweatshirtJacketMwfMinus() {\n\t\t\tif(instantObj.noOfSweatshirtJacketMWF > 0) {\n\t\t\t\tinstantObj.noOfSweatshirtJacketMWF = instantObj.noOfSweatshirtJacketMWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "die() {\n this.dieSfx.play('die');\n this.scene.time.delayedCall(6000, (sounds)=> {\n sounds.forEach( (sound) => {\n sound.destroy();\n })\n }, [[this.dieSfx, this.takeDamageSfx, this.dealDamageSfx, this.shoutSfx]]);\n for(let i = this.minCoins; i < Math.random() * this.maxCoins + this.minCoins; i++) {\n let coin = new GameCoin({scene:this.scene, x:this.x, y:this.y});\n coin.body.setVelocityX(Math.random() * 100 - 50);\n coin.body.setVelocityY(Math.random() * 100 - 50);\n }\n if(this.nextMoveEvent) {\n this.nextMoveEvent.destroy();\n }\n if(this.senseEvents) {\n this.senseEvents.forEach( (event)=> {\n event.destroy();\n });\n }\n dataManager.emitter.emit(\"enemyDied\");\n this.destroy();\n }", "_destroy() {\n\t\tthis.workspaces_settings.disconnect(this.workspaces_names_changed);\n\t\tWM.disconnect(this._ws_number_changed);\n\t\tglobal.display.disconnect(this._restacked);\n\t\tglobal.display.disconnect(this._window_left_monitor);\n\t\tthis.ws_bar.destroy();\n\t\tsuper.destroy();\n\t}", "function countSareeWwfMinus() {\n\t\t\tif(instantObj.noOfSareeWWF > 0) {\n\t\t\t\tinstantObj.noOfSareeWWF = instantObj.noOfSareeWWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countShirtMwfMinus() {\n\t\t\tif(instantObj.noOfShirtMWF > 0) {\n\t\t\t\tinstantObj.noOfShirtMWF = instantObj.noOfShirtMWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle tab or enter keypress for new notebooks TODO: add a minimum character limit for new notebooks
keyPress(e) { // If enter or tab key pressed on new notebook input if (e.keyCode === 13 || e.keyCode === 9) { this.addNotebook(e); } }
[ "onKeyPressHandler(event) {\n if(event.key === \"Enter\") {\n this.addToNotes();\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 enterobs(e){\n if(e.which == 13 && !e.shiftKey){\n $('#pubob').click();\n e.preventDefault();\n }\n}", "function renameEnter(self) {\n\tif (window.event.keyCode == 13) { // 13 = enter key\n\t renameBlurred(self);\n\t}\n }", "function bindKeyboardShortcutsForTabs() {\n $( document ).keydown(function (event) {\n if($(document.activeElement).is('textarea,input,select')) { return; }\n switch (event.which) {\n case $.ui.keyCode.DOWN:\n event.preventDefault();\n nextTab();\n break;\n case $.ui.keyCode.UP:\n event.preventDefault();\n previousTab();\n break;\n default: return;\n }\n });\n}", "function extendedOnKeyPress() {\r\n this._handleEscapeToHome()\r\n originalOnKeyPress()\r\n }", "handleHolderKeyPress(event) {\n // If the key code is ENTER (13), select the time\n if ((event.keyCode ? event.keyCode : event.which) == 13) {\n event.preventDefault();\n this.deployContract();\n }\n }", "function addOnKeyPressedListener(interpreter) {\n $(document).keypress(function(event){\n if (interpreter.keyPressedListenerActive) {\n event.preventDefault();\n if (event.keyCode == ENTER_KEY_CODE) {\n interpreter.keyPressedListenerActive = false;\n return;\n }\n // alert(String.fromCharCode(event.which));\n interpreter.commands = interpreter.commands + String.fromCharCode(event.which);\n interpreter.nextCommand(RunningMethodEnum.VISUALIZE);\n }\n });\n}", "function spacebar(e) {\n if (e.keyCode === 32) {\n jumping()\n }\n}", "function KeyPaste(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n Paste();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}", "function ODBInlineEditKeydown(event, p, path, bracket) {\n var keyCode = ('which' in event) ? event.which : event.keyCode;\n\n if (keyCode == 27) {\n /* cancel editing */\n p.ODBsent = true;\n p.inEdit = false;\n mie_back_to_link(p, path, bracket);\n return false;\n }\n\n if (keyCode == 13) {\n ODBFinishInlineEdit(p, path, bracket);\n return false;\n }\n\n return true;\n}", "function addTitleListener() {\n\n $('#current-note-title').blur(function() {\n saveTitle();\n });\n\n document.getElementById('current-note-title').addEventListener('keydown' ,function(event) {\n var targetElement = event.target || event.srcElement;\n if (event.key == \"Enter\") {\n targetElement.blur();\n }\n else if (targetElement.textContent.length > 31 && event.key != \"Backspace\" && event.key != \"ArrowLeft\" && event.key != \"ArrowRight\") {\n event.preventDefault();\n }\n });\n\n}", "function pressKey(event) {\n if (event.which == 13) {\n bot();\n questionNum++\t\t\t\t\t\t\t\t\t\t\t\t\t// increase questionNum count by 1\n }\n}", "function KeyCreateFolder(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n CreateFolder();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}", "function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}", "function KeyCut(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n Cut();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}", "function submitOnEnter(event){\n\tif (event.keyCode == 13 && !event.shiftKey) {\n\t\tevent.preventDefault();\n\t\tnewMessage();\n\t}\n}", "function enterAction(event, button) {\n\tevent.preventDefault();\n\tif (event.keyCode === 13) { \n\t\tdocument.activeElement.blur();\n\t\tbutton.click();\n\t}\n}", "function disableEnterButton()\n{\n\t$('html').on('keypress', function(e)\n\t{\n\t\tif (e.keyCode == 13)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
class Particle extends Object
function Particle() { }
[ "function Particle(initialPosition, initialVelocity) {\n this.position = initialPosition;\n this.velocity = initialVelocity;\n this.bestPosition = null;\n this.bestFitness = null;\n this.fitness = 0;\n this.dispersion = 0;\n}", "function ParticleCollection(data) {\n this._data = _.map(data, function (p) {\n return Object.freeze(new Particle(p));\n });\n}", "function BoxParticleEmitter(){/**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */this.direction1=new BABYLON.Vector3(0,1.0,0);/**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */this.direction2=new BABYLON.Vector3(0,1.0,0);/**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */this.minEmitBox=new BABYLON.Vector3(-0.5,-0.5,-0.5);/**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */this.maxEmitBox=new BABYLON.Vector3(0.5,0.5,0.5);}", "function Path(){\n\tthis.particles = [];\n\tthis.hue = random(100);\n}", "constructor(){\r\n this.points = []\r\n this.numpoints = 100\r\n this.gravity = 0.1;\r\n }", "function SubEmitter(/**\n * the particle system to be used by the sub emitter\n */particleSystem){this.particleSystem=particleSystem;/**\n * Type of the submitter (Default: END)\n */this.type=SubEmitterType.END;/**\n * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)\n * Note: This only is supported when using an emitter of type Mesh\n */this.inheritDirection=false;/**\n * How much of the attached particles speed should be added to the sub emitted particle (default: 0)\n */this.inheritedVelocityAmount=0;// Create mesh as emitter to support rotation\nif(!particleSystem.emitter||!particleSystem.emitter.dispose){particleSystem.emitter=new BABYLON.AbstractMesh(\"SubemitterSystemEmitter\",particleSystem.getScene());}// Automatically dispose of subemitter when system is disposed\nparticleSystem.onDisposeObservable.add(function(){if(particleSystem.emitter&&particleSystem.emitter.dispose){particleSystem.emitter.dispose();}});}", "function point(xx,yy){\nthis.x = xx;\nthis.y = yy;\n}", "constructor(settings) { \r\n\t\tsettings = settings || {};\r\n\t\tsettings.sprites = settings.sprites || [];\r\n\t\tsettings.lifetime = settings.lifetime || 1;\r\n\t\tsettings.speed = settings.speed || 1;\r\n\t\tsettings.fadeout = settings.fadeout || 1;\r\n\t\tsettings.transformation = settings.transformation || Transformation.create();\r\n\t\tsettings.spread = settings.spread || Range.create(0, Math.PI * 2);\r\n\t\tsettings.spawnDelay = settings.spawnDelay || Range.create();\r\n\r\n\t\tthis.settings = settings;\r\n\r\n\t\tthis.particles = [];\r\n\t\tthis.nextSpawnTime = 0;\r\n\t}", "function Shape() {\n Vector.apply( this, arguments ); // call Vector's constructor\n this.age = 0\n this.maxAge = 450\n this.size = 0\n this.color = \"#00FFFF\";\n}", "function TestEntity1() {\n this.sprite = new Sprite(0,0,20, \"blue\");\n}", "function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {\n this.idx = 0; // particle global index\n this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color\n this.position = BABYLON.Vector3.Zero(); // position\n this.rotation = BABYLON.Vector3.Zero(); // rotation\n this.scaling = BABYLON.Vector3.One(); // scaling\n this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs\n this.velocity = BABYLON.Vector3.Zero(); // velocity\n this.alive = true; // alive\n this.isVisible = true; // visibility\n this._pos = 0; // index of this particle in the global \"positions\" array\n this.shapeId = 0; // model shape id\n this.idxInShape = 0; // index of the particle in its shape id\n this.idx = particleIndex;\n this._pos = positionIndex;\n this._model = model;\n this.shapeId = shapeId;\n this.idxInShape = idxInShape;\n this._sps = sps;\n if (modelBoundingInfo) {\n this._modelBoundingInfo = modelBoundingInfo;\n this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);\n }\n }", "function Player(){\n Paddle.call(this);\n \n this.x = 20;\n}", "gravityAdd(particle,factor)\n{\n return particle.dy += factor*0.5;\n}", "function mousePressed(){\r\n particlesBg.push(new ParticleBg());\r\n}", "constructor(args) {\n super();\n var { noodle: noodle, objMeta: meta, container: container, core: core, pos: pos } = args;\n meta = meta || {};\n meta.container = meta.container || new Container({ noodle: noodle });\n this.core = core = core || {};\n core.resetFuncs = core.resetFuncs || [];\n //core.outPorts = core.outPorts || [];\n\n this.pos = new Pos(pos || { x: 0, y: 0 });\n\n this.addMeta({ meta: meta }); //TODO: this.constructor.addMeta?\n this.meta.id = noodle.ids.firstFree()\n\n this.in = { ports: core.inPorts || [] };\n this.out = { ports: core.outPorts || [] };\n this.label = core.name;\n this.parNode = this;\n this.startPos = new Pos();\n\n var ports = this.ports.all;\n for (var i in ports) {\n var port = ports[i];\n port.meta.parNode = this;\n }\n\n }", "function initPoses() {\n let num = 0;\n this.joints = {\n // wrist\n Wrist: new _JointObject.JointObject(\"wrist\", num++, this),\n // thumb\n T_Metacarpal: new _JointObject.JointObject(\"thumb-metacarpal\", num++, this),\n T_Proximal: new _JointObject.JointObject(\"thumb-phalanx-proximal\", num++, this),\n T_Distal: new _JointObject.JointObject(\"thumb-phalanx-distal\", num++, this),\n T_Tip: new _JointObject.JointObject(\"thumb-tip\", num++, this),\n // index\n I_Metacarpal: new _JointObject.JointObject(\"index-finger-metacarpal\", num++, this),\n I_Proximal: new _JointObject.JointObject(\"index-finger-phalanx-proximal\", num++, this),\n I_Intermediate: new _JointObject.JointObject(\"index-finger-phalanx-intermediate\", num++, this),\n I_Distal: new _JointObject.JointObject(\"index-finger-phalanx-distal\", num++, this),\n I_Tip: new _JointObject.JointObject(\"index-finger-tip\", num++, this),\n // middle\n M_Metacarpal: new _JointObject.JointObject(\"middle-finger-metacarpal\", num++, this),\n M_Proximal: new _JointObject.JointObject(\"middle-finger-phalanx-proximal\", num++, this),\n M_Intermediate: new _JointObject.JointObject(\"middle-finger-phalanx-intermediate\", num++, this),\n M_Distal: new _JointObject.JointObject(\"middle-finger-phalanx-distal\", num++, this),\n M_Tip: new _JointObject.JointObject(\"middle-finger-tip\", num++, this),\n // ring\n R_Metacarpal: new _JointObject.JointObject(\"ring-finger-metacarpal\", num++, this),\n R_Proximal: new _JointObject.JointObject(\"ring-finger-phalanx-proximal\", num++, this),\n R_Intermediate: new _JointObject.JointObject(\"ring-finger-phalanx-intermediate\", num++, this),\n R_Distal: new _JointObject.JointObject(\"ring-finger-phalanx-distal\", num++, this),\n R_Tip: new _JointObject.JointObject(\"ring-finger-tip\", num++, this),\n // little\n L_Metacarpal: new _JointObject.JointObject(\"pinky-finger-metacarpal\", num++, this),\n L_Proximal: new _JointObject.JointObject(\"pinky-finger-phalanx-proximal\", num++, this),\n L_Intermediate: new _JointObject.JointObject(\"pinky-finger-phalanx-intermediate\", num++, this),\n L_Distal: new _JointObject.JointObject(\"pinky-finger-phalanx-distal\", num++, this),\n L_Tip: new _JointObject.JointObject(\"pinky-finger-tip\", num++, this)\n };\n }", "function mousePressed(){\r\n count-=1;\r\n if(gameState===\"PLAY\" && count>0){\r\n particle=new Particle(mouseX,10,10);\r\n }\r\n}", "createParticleBg() {\r\n noStroke();\r\n var r = random(255); // r is a random number between 0 - 255\r\n var g = random(100,200); // g is a random number betwen 100 - 200\r\n var b = random(100); // b is a random number between 0 - 100\r\n var a = random(200,255); // a is a random number between 200 - 255\r\n fill(r, g, b, a);\r\n //noFill();\r\n circle(this.x,this.y,this.r);\r\n }", "function Pet(petName,age,adopted,markings,breed){\n this.petName = petName;\n this.age = age;\n this.adopted = adopted;\n this.markings = markings;\n this.breed = breed;\n}", "dead() {\n let x = this.x;\n let y = this.y;\n new Explosion(this.scene, x, y);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Comprueba si el usuario esta bloqueado.
function checKBloq(typeUs) { try { var userId = getUserId(); if (typeUs == 'u') { //Si el usuario es individual //Comprueba bloqueo. Devuelve true si está bloqueado y false si no lo está. var bloqueo = database.getData("Usuarios/" + userId + "/Bloqueo"); if (bloqueo == 0) { //si no está bloqueado. //Comprueba el número de peticiones. var petitions = getPetitions(); if (petitions[0] >= petitions[1]) { //Si ha superado el número de peticiones. bloqUser(); return true; } else { return false; } } else { return true; } } else if (typeUs == 'd') { //Si el usuario es dominio. //Comprueba bloqueo. Devuelve true si está bloqueado y false si no lo está. var dominio = replaceIdDomain(domain[1]), bloqueo = database.getData("dominios/" + dominio + "/Bloqueo"); if (bloqueo == 0) { //si no está bloqueado. //Comprueba el número de peticiones. var petitions = getPetitions(); if (petitions[0] >= petitions[1]) { //Si ha superado el número de peticiones. bloqDomain(); return true; } else { return false; } } else { return true; } } else { return false; } } catch (e) { return; } }
[ "function isUserStillWaiting(request) {\n\treturn false; //Allow user to return the pool for selection.\n}", "async blockUserInClass(userId,classId){\n let userInClass = await UserClass.findOne({\n where:{\n userId:userId,\n classId:classId,\n status:'active'\n }\n });\n userInClass.status='block';\n await userInClass.save();\n return 'Block User successfully';\n }", "function empenhoEstaBloqueado(empenho) {\n var empenhoBloqueado = false; \n //procura o empenho na lista dos bloqueados e retorna 'true' se encontrar\n for (var cont = 0; cont < empenhosBloqueados.length; cont++) {\n if (empenhosBloqueados[cont].trim() != \"\") {\n if (empenho == empenhosBloqueados[cont]) {\n empenhoBloqueado = true;\n }\n }\n }\n return empenhoBloqueado;\n}", "is_blocker() {\n return true;\n }", "is_blocker() {\n return false;\n }", "hasRemainingUsers() {\n return this.remainingUsers !== 0\n }", "get busy() {\n\t\treturn this.state == Constants.STATE.BUSY;\n\t}", "function blockUser( user_id )\n{\n\tshowDialogMsg( \n\t\t\t\t\t\"Block User\", \n\t\t\t\t\t\"Page will refresh to apply settings.\", \n\t\t\t\t\t0,\n\t\t\t\t\t{\n\t\t\t\t\t buttons: [\n\t\t\t\t {\n\t\t\t\t text: \"Block\",\n\t\t\t\t click: function(){\n\t\t\t\t \tjQuery.ajax(\n\t\t \t\t \t{\n\t\t \t\t url: \"/\" + PROJECT_NAME + \"profile/block-user\",\n\t\t \t\t type: \"POST\",\n\t\t \t\t dataType: \"json\",\n\t\t \t\t data: { \"user_to_be_blocked_id\":user_id },\n\t\t \t\t success: function(jsonData) \n\t\t \t\t {\n\t\t \t\t \tif( jsonData == 1 )\n\t\t \t\t \t{\t\n\t\t \t\t \t\tlocation.reload();\n\t\t \t\t \t}\n\t\t \t\t }\n\t\t \t\t \t});\n\t\t\t\t }\n\t\t\t\t },\n\t\t\t\t {\n\t\t\t\t \ttext: \"Cancel\",\n\t\t\t\t \tclass: 'only_text', \n\t\t\t\t \tclick: function(){\n\t\t\t\t \t\t$(this).dialog(\"close\");\n\t\t\t\t \t}\n\t\t\t\t }\n\t\t\t\t ],\n\t\t\t\t show: {\n\t\t\t\t effect: \"fade\"\n\t\t\t\t },\n\t\t\t\t hide: {\n\t\t\t\t effect: \"fade\"\n\t\t\t\t },\n\t\t\t\t dialogClass: \"general_dialog_message shortProfileViewDialogs\",\n\t\t\t\t height: 150,\n\t\t\t\t width: 300\n\t\t\t\t}\n\t\t\t);\n}", "function handleBpBillerCorpCredsOnSuccess(isMsg) {\n\t/* show the div */ \n $('#billerFormData').show();\n $('#addOrEditSaveBtnDiv').show();\n $('#addBil_billerType').show();\n $('#addBil_postingCategoryLanguage').show();\n $('#addBil_instruction2').show();\n $('#addBil_rightSection').show(); \n \n printBillerData();\n createTableNew();\n \n hideShowCreateAccountForGuestUser();\n if (isMsg) {\n \tshowGeneralErrorMsg(msgType);\n }\n}", "function solicitacaoEstaBloqueada(solicitacao) {\n var solicitacaoBloqueada = false;\n var idSolicitacao = \"\";\n\n //procura a sollicitacao na lista e retorna 'true' se encontrar\n for (var cont = 0; cont < solicitacoesBloqueadas.length; cont++) {\n idSolicitacao = solicitacoesBloqueadas[cont].split(\"/\")[0];\n\n if (solicitacao == idSolicitacao) {\n solicitacaoBloqueada = true;\n }\n }\n return solicitacaoBloqueada;\n}", "function userAtBottom() {\n const element = $('#message-box')[0];\n return element.scrollHeight - element.scrollTop - 45 === element.clientHeight;\n }", "checkUnlock() {\n if (clickNumber >= this.cost && this.isUnlocked == false) {\n this.isUnlocked = true;\n document.getElementById(this.id).className += \" reveal\";\n }\n }", "function isBusy(busyBlocks, time) {\n var i;\n\n for (i = 0; i < busyBlocks.length; i++) {\n if (busyBlocks[i].isBusy(time)) {\n return true;\n }\n }\n\n return false;\n}", "function isnotsu() {\nif(msguser !== superuserid ) {\nconst plaintext = \"<:warn_3:498277726604754946> Sorry, you don't have permissions to use this!\"\nconst embed = new RichEmbed() \n//.setTitle('Title') \n.setColor(0xCC0000) \n.setDescription('only ' + superuser + ' may use this command')\n//.setAuthor(\"Header\")\n.setFooter(\"@\" + msgauthor)\n//.addField(\"Field\");\nmessage.channel.send(plaintext, embed);\n\n\t/*\nreturn message.reply(\"Sorry, you don't have permissions to use this!\")\n*/\nreturn true\n}\nelse\nreturn false;\n}", "function checkLogedInUser() {\n\n}", "async isBusy() {\n return new Promise((resolve, reject) => {\n this.rpc.stdin.write('busy' + os.EOL);\n this.rpc.stdout.once('data', (data) => {\n data = data.toString().trim();\n if ((typeof data == 'boolean' && data) || data == \"true\") {\n resolve(true)\n } else {\n resolve(false)\n }\n });\n });\n\n }", "isPermitted(user_id) {\n if (!user_id) return false;\n for(var permitted in this.permitted) {\n if ( permitted == user_id ) return this.permitted[permitted] != null;\n if ( botStuff.userHasRole(this.server_id, user_id, permitted)) return this.permitted[permitted] != null;\n }\n return false;\n }", "function fGuardar(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }", "isBusy() {\n return this.totalTasks() >= this.options.maxPoolSize;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch additional photos based on page scroll get Friends
function getFriends() { var query = "SELECT uid, name FROM user WHERE uid IN (Select uid2 from friend where uid1 =me())"; FB.api( { method: 'fql.query', query: query }, function(response) { console.log(response); var html = ""; var friend = new Array(); for (var i=0; i < response.length; i++) { console.log("There were this many responses " + response.length + " and they are " + response[i]); var name = response[i].name; var fuid = response[i].uid; fbPhoto.insert({username: name, uid: fuid, selected: 0}); friend[i] = fuid; console.log(name + " is your friend and their id is " + fuid); //html += "<a href='"+big+"' target='_blank'><img src='"+src+"' /></a>"; } console.log("you hit me with ONE " + fbPhoto.find().count() ); //getLatestPhotos(friend); //var container = document.getElementById("container"); //container.innerHTML = html; console.log('done'); } ); }
[ "function friendsLoad() {\n\tsendReq('friends.search',{count: 5, fields: 'photo_50'}, function (data){\n\t\tshowFriends(data.response);\n\t});\n}", "function infiniScroll(pageNumber) {\n \n $.ajax({\n url: \"rest/getMoreImages/\"+pageNumber+\"/\"+uploadCount,\n type:'GET',\n success: function(imageJSON){\n \n var imageResults = $.parseJSON(imageJSON);\n for(var i=0;i<6;i++) { \n if(imageResults.images[i].userID !== \"\") {\n \n getGPlusName(imageResults.images[i].userID);\n \n $(\"#contentList\").append(\n '<li class=\"polaroid\">'+\n '<a href=\"javascript:void(0)\" title=\"'+plusName+'\">'+\n '<img src=\"uploads/'+imageResults.images[i].filename+'\" alt=\"'+plusName+'\" />'+\n '</a>'+\n '</li>');\n } else {\n streamOK = false;\n }\n }\n \n }\n });\n}", "function getPhoto(direction) {\n var i = currentPhotoIndex;\n switch (direction) {\n case \"next\":\n if (i + 1 < profile['photos'].length) { // Check that photo is not out-of-bounds\n retrievePhoto(i + 1);\n };\n break;\n case \"previous\":\n if (i - 1 >= 0) { // Check that photo is not out-of-bounds\n retrievePhoto(i - 1);\n }; \n break;\n }\n}", "function getPhotos(callback) {\n $.ajax({\n type: \"GET\",\n dataType: 'json',\n url: Routes.cms_photos,\n data: {\n 'page': window.current_page + 1\n }\n })\n .done(function (response) {\n var photosObj = $.parseJSON(response.photos);\n\n\n window.current_page = photosObj.current_page;\n\n // hide the [load more] button when all pages are loaded\n if (window.current_page == photosObj.last_page) {\n $('#load-more-photos').remove();\n }\n\n callback(photosObj);\n })\n .fail(function (response) {\n console.log(\"Error: \" + response);\n });\n\n }", "function moreImages(){\n \n $('#more').click(event =>{\n let search = $('#search_input').val();\n getPhoto(search,++page,true);\n });\n}", "function checkEndOfPage(firstFill){\r\n\tfirstFill = firstFill || 0;\r\n\tvar endOfPage = document.getElementById('photoGallery').clientHeight;\r\n var lastDiv = document.querySelector(\"#photoBlock > div:last-child\");\r\n var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;\r\n var pageOffset = window.pageYOffset + window.innerHeight;\r\n if(firstFill == 0){\t\r\n\t \tif(Math.round(pageOffset) >= endOfPage){\r\n\t \t\tshowLoading();\r\n\t \t\tgetPhotos(per_page = 5, page = 1, function(data){createNewPhotoBlock(data)});\r\n\t \t}\r\n }\r\n \telse if(lastDivOffset < window.innerHeight){\r\n \tpage++;\r\n\t \tshowLoading();\r\n \t\tgetPhotos(per_page = 5, page, function(data){ createNewPhotoBlock(data, firstFill = 1) });\r\n \t}\r\n\t// \"page++\" variable page here makes the scroll down shows older images, with \"page = 1\" in the function getPhotos, \r\n\t// scroll down shows the newest images in flickr. \r\n\t//The method \"getRecents\" dont verify if the images are duplicated\r\n}", "function friend_ajax(){\n\t\t\tfriend=friend+1;\n\t\t\tif(friend==1){\n\t\t\tvar url=\"https://graph.facebook.com/me?fields=family{picture.height(400),name}&&access_token=\";\n\t\t\turl=url+at;\n\t\t\t$.ajax(url,{\n\n\t\t\t type:'GET',\n\t\t\t success : function(response){\n\t\t\t console.log(url);\n\t\t\t setFriends(response);\n\t\t\t \t\tsetFriendHeight();\n\t\t\t },\n\t\t\t error : function(request,errorType,errorMessage){\n\t\t\t console.log(request);\n\t\t\t console.log(errorType);\n\t\t\t },\n\t\t\t timeout:3000\n\t\t\t }//end argument list s\n\t\t);\n\t\t}\n\t\t}", "function handleFlickrPhotoSearch(rsp) {\n if (rsp.stat === 'fail') {\n // display error message to user\n var _load_mess_div = document.getElementById('loading-mess-div');\n var err_mess = document.createElement('p');\n err_mess.className = \"error-message\";\n err_mess.innerHTML = \"I'm sorry, there was a problem searching for elephants from flickr: \" + rsp.message;\n _load_mess_div.appendChild(err_mess);\n }\n var load_mess_div = document.getElementById('loading-mess-div');\n var load_mess = document.getElementById('loading-mess');\n load_mess_div.removeChild(load_mess);\n var photos = rsp.photos.photo;\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = photos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var photo = _step.value;\n\n var size_url = \"https://api.flickr.com/services/rest/?method=flickr.photos.getSizes\" + \"&api_key=27cfab5e654f8de0d4f0c85859984b5b&photo_id=\" + photo.id + \"&format=json&jsoncallback=handleFlickrSizes\";\n var script = document.createElement(\"script\");\n script.async = true;\n script.src = size_url;\n document.body.appendChild(script);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n }", "function getMoreImages() {\n\t\t// Return 0 if fetched all images, 1 if enough to fill screen and >1 otherwise\n\t\tvar uncovered_px = $box.height()+$box.offset().top - ($(document).scrollTop()+window.innerHeight),\n\t\t\tuncovered_rows = uncovered_px / settings.row_height;\n\n\t\tif (unloaded) {\n\t\t\t// Don't load more than if not all have loaded (think: slow connections!)\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (!fetched_all) {\n\t\t\tif (uncovered_rows < 2) {\n\t\t\t\tif (!loading_images && settings.getImages) {\n\t\t\t\t\tloading_images = true;\n\t\t\t\t\tsettings.getImages(addNew);\n\t\t\t\t}\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}", "function fetchPhotos(query, callback) {\n\t\tvar flickr, cached;\n\t\t\n\t\tcached = getCached(query);\n\t\t\n\t\tif(cached) {\n\t\t\tcallback(cached.photos.photo);\n\t\t} else {\n\t\t\t\n\t\t\tflickr = new Flickr('b04fabc8322a5f5f45f5b172c9c176fd');\n\t\t\t\n\t\t\tflickr.makeRequest(\n\t\t\t\t'flickr.photos.search', \n\n\t\t\t\t{text:query, extras:'url_z,owner_name', license:5, per_page:50}, \n\n\t\t\t\tfunction(data) {\n\t\t\t\t\tcallback(data.photos.photo);\n\t\t\t\t\t\n\t\t\t\t\t//set the cache after the callback, so that\n\t\t\t\t\t//it happens after any UI updates that may be needed\n\t\t\t\t\tsetCache(query, data);\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\t\n\t}", "function getPhotosAPI(){\n\n\tvar fb_user_id;\n\n\t// // get user's facebook user id\n\tFB.api(\n\t\t'/me/',\n\t\t'GET',\n\t\t{\"fields\":\"id\"},\n\t\tfunction(response) {\n\t\t\tfb_user_id = response.id;\n\t\t}\n\t);\n\n\t// console.log(\"my fb_user_id: \", fb_user_id);\n\n\t// currently limiting to 50 photos...too much data won't send successfully to my server\n\t// apparently 100 is too many for a single request\n\t// only getting type=uploaded to make sure the user owns those photos\n\tFB.api(\n\t\t'/me/photos',\n\t\t'GET',\n\t\t{\"fields\":\"album,created_time,id,images,place,tags,picture\",\"type\":\"uploaded\",\"limit\":\"50\"}, \n\t\tfunction (response) {\n\t \tif (response && !response.error){\n\t \t\tconsole.log(\"response data: \", response);\n\t \t\t// clean up the data before I send it to my server\n\t \t\tvar photoDataArray = [];\n\t \t\tfor (var i = 0; i < response.data.length; i++){\n\t \t\t\tvar thisImage = response.data[i];\n\t \t\t\t// if can_delete is set to false, do not save photo\n\t \t\t\t// because photo does not belong to this person\n\t \t\t\tvar lastImageUrlPlace = thisImage.images.length - 1 ;\n\t \t\t\tconsole.log(\"lastImageUrlPlace: \", lastImageUrlPlace);\n\n\t \t\t\tif (thisImage.can_delete === false){\n\t \t\t\t\t// do nothing\n\t \t\t\t\tconsole.log(\"skipping an image\");\n\t \t\t\t} else {\n\t \t\t\t\tvar photoDataObject = {\n\t \t\t\t\t\tfb_user_id : fb_user_id,\n\t \t\t\t\t\tfb_photo_id : thisImage.id,\n\t \t\t\t\t\tfb_photo_created_time : thisImage.created_time,\n\t \t\t\t\t\tfb_photo_album : thisImage.album,\n\t \t\t\t\t\tfb_photo_url_full_size : thisImage.images[0].source,\n\t \t\t\t\t\tfb_photo_thumbnail : thisImage.picture, \t\t\t// 100px version\n\t \t\t\t\t\tfb_photo_url_mid_size: thisImage.images[lastImageUrlPlace].source, // choose whatever is last image array of image data\n\t \t\t\t\t\tfb_photo_place : thisImage.place,\n\t \t\t\t\t\tfb_photo_tags : thisImage.tags\n\t \t\t\t\t};\n\t \t\t\t\tphotoDataArray.push(photoDataObject);\n\t \t\t\t}\n\t \t\t}\n\t \t\tconsole.log(\"data i'm sending to my server: \", photoDataArray);\n\t \t\t// send the data to my server\n\t \t\tsendFbUserData(photoDataArray);\n\n// note - this is asynchronous\n// if there is an issue with this, I could create an Angular service\n// see https://developers.facebook.com/docs/javascript/howto/angularjs for more info\n\n\t \t} else {\n\t \t\tconsole.log(\"problem getting facebook photo data: \", response.error);\n\t \t\t// switch button view\n\t\t\tredirectToFbLanding();\n\t \t}\n\t});\n}", "function getInstagram() {\n\tquery = \"feed/instagram.php?lat=\" + pictureLocation.lat() + \"&lng=\" + pictureLocation.lng() + \"&range=\" + pictureRange;\n\tjx.load(query, function(data) {\n\t\tprocessInstagramData(data);\n\t}, \"json\");\n}", "function loadimages(params){\n\tvar url = \"http://api.flickr.com/services/rest/?method=flickr.photos.search&\" +\n\t\t\t\t\t\t\t \"api_key=a2282a6e140e07e7689570dd1463330a&\" +\n\t\t\t\t\t\t\t \"text=\"+encodeURIComponent(params)+\"&\" +\n\t\t\t\t\t\t\t \"safe_search=1&\" + // 1 is \"safe\"\n\t\t\t\t\t\t\t \"content_type=1&\" + // 1 is \"photos only\"\n\t\t\t\t\t\t\t \"sort=relevance&\" + // another good one is \"interestingness-desc\"\n\t\t\t\t\t\t\t \"per_page=5&\" +\n\t\t\t\t\t\t\t\t\t \"page=1\";\n\t\t\t\t\t\t\t\t\t var photos;\n\t\t\t\t\t\t\t\t\t $.ajax({type: \"GET\",url: url,dataType: \"html\",\n\t\t\t\t\t \tsuccess: function (xml) {\n\t\t\t\t\t //console.log(xml);\n\t\t\t\t\t photos = $(xml).find('photo');\n\t\t\t\t\t console.log(photos);\n\t\t\t\t\t \t\t\t\t$.each(photos, function() {\n\t\t\t\t\t var imgsrc = \"http://farm\" + this.getAttribute(\"farm\") +\n\t\t\t\t\t\t\t\t\t \".static.flickr.com/\" + this.getAttribute(\"server\") +\n\t\t\t\t\t\t\t\t\t \"/\" + this.getAttribute(\"id\") +\n\t\t\t\t\t\t\t\t\t \"_\" + this.getAttribute(\"secret\") +\n\t\t\t\t\t\t\t\t\t \"_m.jpg\";\n\t\t\t\t\t\t\t\t\t console.log(imgsrc);\n\t\t\t\t\t\t\t\t\t $(\".alert\").alert(\"Successfully loaded some images..\");\n\t\t\t\t\t\t\t\t\t $(\"#loader\").hide();\n\t\t\t\t\t\t\t\t\t $(\"#subbutton\").button('reset');\n\t\t\t\t\t\t\t\t\t $(\"#container\").show();\n\t\t\t\t\t $(\"#container\").append( '<img src=\"'+imgsrc+'\" alt=\"Lawl\" class=\"img-thumbnail\">' );\t\t\t\t\t \n\t\t\t\t\t \t });\n\t\t\t\t\t }\n\t\t\t\t\t \t});\n\n}", "function addUsersToGallery() {\n addUsersToDatabase();\n \n let galleryProfiles = document.getElementsByClassName('profiles');\n let profileInfo = document.getElementsByClassName('profileInfo');\n\n let user;\n let profileChildern;\n \n for (let i = 0; i<galleryProfiles.length; i++) {\n profileChildern = profileInfo[i].children;\n user = userDatabase.users[i];\n profileInfo[i].title = user.email;\n profileInfo[i].children[0].title = user.email;\n profileInfo[i].children[0].href = \"profil.html\";\n profileInfo[i].children[0].style.cursor = \"pointer\";\n galleryProfiles[i].children[0].src = user.profilePic;\n profileChildern[0].textContent = user.firstName;\n profileChildern[1].textContent = \"Ålder: \"+getAge(user.birthday);\n \n }\n goToProfile(profileInfo);\n}", "function getMyPictures(req, res, next) {\n let query = Picture.find({\"user\": req.params.id});\n query.exec(function (err, pictures) {\n if (err) {\n next(err);\n }\n req.picture = pictures;\n next();\n });\n}", "function doLazyLoadImages() {\n DomUtil.doLoadLazyImages( self.$scroller, self.$pugs.find( \"pug\" ) );\n }", "function showPhoto() {\n $(\"#main-section\").empty();\n\n var showPhotoContainer = $(\"<div>\");\n showPhotoContainer.attr(\"class\", \"row\");\n showPhotoContainer.attr(\"id\", \"show-photo-container\");\n\n var showPhotoDiv = $(\"<div>\");\n showPhotoDiv.attr(\"id\", \"show-photo-div\");\n showPhotoDiv.attr(\"class\", \"col-xs-6 offset-xs-3 col-xl-6 offset-xl-3\");\n\n var foodImagesContainer = $(\"<div>\");\n foodImagesContainer.attr(\"id\", \"food-images\");\n foodImagesContainer.attr(\"class\", \"row well well-lg\");\n\n var foodImagesDiv = $(\"<div>\");\n foodImagesDiv.attr(\"id\", \"food-images-div\");\n foodImagesDiv.attr(\"class\", \"col-xs-8 offset-xs-2 col-xl-8 offset-xl-2\");\n\n var foodImage = $(\"<img>\");\n foodImage.attr(\"id\", \"food-img\");\n // foodImage.attr(\"class\", \"well well-lg\");\n foodImage.attr(\"src\", businessInfo.businessImages[imageCount]);\n foodImagesDiv.append(foodImage);\n foodImagesContainer.append(foodImagesDiv);\n showPhotoDiv.append(foodImagesContainer);\n\n console.log(businessInfo.businessAddress[imageCount]);\n\n // Adding Yelp logo/link to Yelp to image in order to comply with Yelp API display requirements\n var yelpLink = $(\"<a>\");\n yelpLink.attr(\"href\", \"https://www.yelp.com\");\n yelpLink.attr(\"target\", \"_blank\");\n var yelpLogo = $(\"<img>\");\n yelpLogo.attr(\"id\", \"yelp-logo\");\n yelpLogo.attr(\"src\", \"assets/images/Yelp_trademark_RGB_outline.png\");\n yelpLogo.attr(\"alt\", \"Yelp Logo\");\n yelpLink.append(yelpLogo);\n foodImagesDiv.append(yelpLink);\n\n // Creating like/dislike \"buttons\" as images with Bootstrap img-rounded class\n // Need to add on-click event listener and cursor hover event\n var buttonsContainer = $(\"<div>\");\n buttonsContainer.attr(\"class\" ,\"row\");\n\n\n // Creating like & dislike \"buttons\" as images with Bootstrap img-rounded class\n // **Need to add on-click event listener for both buttons**\n var buttonsDiv = $(\"<div>\");\n buttonsDiv.attr(\"class\", \"col-xs-10 offset-xs-2 col-xl-10 offset-xl-2\");\n buttonsDiv.attr(\"id\", \"like-buttons-div\");\n\n var dislikeButton = $(\"<img>\");\n dislikeButton.addClass(\"img-rounded\");\n dislikeButton.attr(\"id\", \"dislike-btn\");\n dislikeButton.attr(\"src\", \"assets/images/dislike-button3.png\");\n buttonsDiv.append(dislikeButton);\n\n var likeButton = $(\"<img>\");\n likeButton.addClass(\"img-rounded\");\n likeButton.attr(\"id\", \"like-btn\");\n likeButton.attr(\"src\", \"assets/images/like-button2.png\");\n buttonsDiv.append(likeButton);\n\n buttonsContainer.append(buttonsDiv);\n showPhotoDiv.append(buttonsContainer);\n\n\n showPhotoContainer.append(showPhotoDiv);\n $(\"#main-section\").append(showPhotoContainer);\n}", "function getMoreUserInfo(){\n let curPage = parseInt(localStorage.getItem('curPage'));\n $.ajax({\n url:'https://api.github.com/users?since='+(curPage+1).toString(),\n type: 'GET',\n success: function (response) {\n $(\"#users-list\").append(\n response.reduce(function(previousValue, currentValue){\n return previousValue+`\n <div class=\"card user-info\">\n <div class=\"card-body user-info-detail\">\n <img src=${currentValue.avatar_url} class=\"avatar-display\">\n <span class=\"login-display\">User: ${currentValue.login}</span>\n </div>\n <span class=\"followers-btn\">followers</span>\n <div class=\"user-repos\"></div>\n <div class=\"user-followers\"></div>\n </div>\n `\n }\n ,``)\n );\n localStorage.setItem('curPage',curPage+1);\n userData = userData.concat(response);\n }\n })\n}", "function bindNameAndImagesToProfile(){\n var userPics = document.getElementsByClassName(\"userImage\");\n var userPseudoName = document.getElementsByClassName(\"pseudoName\");\n\n for(var x = 0; x < userPics.length; x++){\n // update the image of the user\n userPics[x].src = \"services/getAvatar.php?userId=\" + userPics[x].dataset.user + \"&size=small\"\n + \"&random=\"+new Date().getTime();\n // add event listener for click\n userPics[x].addEventListener(\"click\", showOtherUser);\n }\n\n for(var x = 0; x < userPseudoName.length; x++){\n userPseudoName[x].addEventListener(\"click\", showOtherUser);\n }\n unbindShowProfileUserShowOptions(); // unbind the click on the author in choise list\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disable or enable all inline stylesheets.
function toggleInlineStylesheets(toggle) { $("*").each(function () { if (toggle) { if (this.style.cssText != "") { // this tag has an inline style this.style[property] = this.style.cssText; this.style.cssText = ""; } } else { if (this.style[property]) { this.style.cssText = this.style[property]; delete this.style[property]; } } }); }
[ "function toggleEmbeddedStylesheets(toggle) {\n $(\"style\").each(function () {\n if (this.sheet) { // may be null if the browser ignored its inner text\n toggleStylesheet(this.sheet, toggle);\n }\n });\n}", "function toggleStylesheet(stylesheet, toggle) {\n stylesheet.disabled = toggle;\n stylesheet.disabled = toggle; // force the browser to action right now\n}", "disable_style() {\n this.enabledStyles.pop();\n }", "function setStylesheet() {\n try {\n const s = document.createElement('style');\n s.setAttribute('type', 'text/css');\n s.setAttribute('id', 'salf');\n s.appendChild(document.createTextNode(\n float_mode.enabled ? style_float() : style_classic\n ));\n document.head.appendChild(s);\n } catch (error) {\n console.debug(error);\n }\n}", "function initStyleSwitcher() {\n var isInitialzed = false;\n var sessionStorageKey = 'activeStylesheetHref';\n var titlePrefix = 'style::';\n\n function handleSwitch(activeTitle) {\n var activeElm = document.querySelector('link[title=\"' + activeTitle +'\"]');\n setActiveLink(activeElm);\n }\n\n function setActiveLink(activeElm) {\n var activeHref = activeElm.getAttribute('href');\n var activeTitle = activeElm.getAttribute('title');\n var inactiveElms = document.querySelectorAll(\n 'link[title^=\"' + titlePrefix + '\"]:not([href*=\"' + activeHref +'\"]):not([title=\"' + activeTitle +'\"])');\n\n // CUSTOM OVERRIDE to allow all Simple Dark titled CSS to be activated together\n // so now all CSS tag with same activeTitle will all be activated together in group\n var activeElms = document.querySelectorAll('link[title=\"' + activeTitle +'\"]');\n activeElms.forEach(function(activeElm){\n // Remove \"alternate\" keyword\n activeElm.setAttribute('rel', (activeElm.rel || '').replace(/\\s*alternate/g, '').trim());\n\n // Force enable stylesheet (required for some browsers)\n activeElm.disabled = true;\n activeElm.disabled = false;\n })\n\n // Store active style sheet\n sessionStorage.setItem(sessionStorageKey, activeTitle);\n\n // Disable other elms\n inactiveElms.forEach(function(elm){\n elm.disabled = true;\n\n // Fix for browsersync and alternate stylesheet updates. Will\n // cause FOUC when switching stylesheets during development, but\n // required to properly apply style updates when alternate\n // stylesheets are enabled.\n if (window.browsersyncObserver) {\n var linkRel = elm.getAttribute('rel') || '';\n var linkRelAlt = linkRel.indexOf('alternate') > -1 ? linkRel : (linkRel + ' alternate').trim();\n\n elm.setAttribute('rel', linkRelAlt);\n }\n });\n\n // CSS custom property ponyfil\n if ((window.$docsify || {}).themeable) {\n window.$docsify.themeable.util.cssVars();\n }\n }\n\n // Event listeners\n if (!isInitialzed) {\n isInitialzed = true;\n\n // Restore active stylesheet\n document.addEventListener('DOMContentLoaded', function() {\n var activeTitle = sessionStorage.getItem(sessionStorageKey);\n\n if (activeTitle) {\n handleSwitch(activeTitle);\n }\n });\n\n // Update active stylesheet\n /** \n * @OPTIMIZE: this will add event listener on all click\n */\n document.addEventListener('click', function(evt) {\n var dataTitle = evt.target.getAttribute('title');\n if(!dataTitle){ return 0; }\n var dataTitleIncludePrefix = dataTitle.toLowerCase().includes(titlePrefix);\n if(!dataTitleIncludePrefix){ return 0; }\n\n dataTitle = dataTitle\n || evt.target.textContent\n || '_' + Math.random().toString(36).substr(2, 9); // UID\n\n handleSwitch(dataTitle);\n evt.preventDefault();\n });\n }\n }", "reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }", "function defineDocumentStyles() {\r\n for (var i = 0; i < document.styleSheets.length; i++) {\r\n var mysheet = document.styleSheets[i],\r\n myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;\r\n config.documentStyles.push(myrules);\r\n }\r\n }", "function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }", "function addStyles() {\n\t styles.use();\n\t stylesInUse++;\n\t}", "function disableAllButtons() {\n disableOrEnableButtons(false);\n }", "function enableControls() {\n $(\"button.play\").attr('disabled', false);\n $(\"select\").attr('disabled', false);\n $(\"button.stop\").attr('disabled', true);\n }", "function updatePageStyles(sheetIndex, styleRules, restorePlace) {\n return changingStylesheet(function () {\n p.stylesheets[sheetIndex] = styleRules;\n if (typeof styleRules.join == \"function\") {\n styleRules = styleRules.join(\"\\n\");\n }\n\n var i = 0, cmpt = null;\n while (cmpt = p.reader.dom.find('component', i++)) {\n var doc = cmpt.contentDocument;\n var styleTag = doc.getElementById('monStylesheet'+sheetIndex);\n if (!styleTag) {\n console.warn('No such stylesheet: ' + sheetIndex);\n return;\n }\n if (styleTag.styleSheet) {\n styleTag.styleSheet.cssText = styleRules;\n } else {\n styleTag.replaceChild(\n doc.createTextNode(styleRules),\n styleTag.firstChild\n );\n }\n }\n }, restorePlace);\n }", "function changeCodeblockButtons(enabled) {\r\n if (enabled) {\r\n jQuery(\"#codeblock_add\").button(\"enable\");\r\n jQuery(\"#codeblock_save\").button(\"enable\");\r\n jQuery(\"#codeblock_remove\").button(\"enable\");\r\n jQuery(\"#codeblock_reset\").button(\"enable\");\r\n } else {\r\n jQuery(\"#codeblock_add\").button(\"disable\");\r\n jQuery(\"#codeblock_save\").button(\"disable\");\r\n jQuery(\"#codeblock_remove\").button(\"disable\");\r\n jQuery(\"#codeblock_reset\").button(\"disable\");\r\n }\r\n}", "function setCSS(styles, elements) {\n if (elements.length > 1) {\n for (var i = 0; i < elements.length; i++) {\n Object.assign(elements[i].style, styles);\n }\n } else {\n Object.assign(elements.style, styles);\n }\n} // Set CSS before elements appear", "function changeCSS(oldCss,newCss){\n //changeCSS(\"main.css\",\"main2.css\");\n\n var oldLink = $('link[rel=stylesheet][href*=\"'+oldCss+'\"]');\n if(oldLink.length < 1){\n console.log(\"computer said nnnoooo\");\n return;\n }\n //get path of old css\n var path = oldLink.attr(\"href\");\n var pathArray = path.split('/');\n var filename = pathArray.pop();\n path = pathArray.join(\"/\")+\"/\";\n\n //remove old css\n $('link[rel=stylesheet][href=\"'+path+oldCss+'\"]').remove();\n\n //add new css\n var script_tag = document.createElement('link');\n script_tag.setAttribute(\"href\",path+newCss);\n script_tag.setAttribute(\"type\",\"text/css\");\n script_tag.setAttribute(\"rel\",\"stylesheet\");\n\n var headElement = (document.getElementsByTagName(\"head\")[0] || document.documentElement);\n headElement.appendChild(script_tag);\n\n}", "function disableControls() {\n $(\"button.play\").attr('disabled', true);\n $(\"select\").attr('disabled', true);\n $(\"button.stop\").attr('disabled', false);\n }", "function update_style() {\n\tvar style = get_style();\n\tif (style !== null) {\n\t\tvar cssName = \"chroma_\" + style + \".css\";\n\t\tvar cssPath = \"inc/css/\" + cssName;\n\t\tvar elem = document.getElementById(\"chroma_style\");\n\t\telem.href = cssPath;\n\t}\n}", "function BAAppendReviseCSS() {\n\tfor (var i in BA.css.revise) {\n\t\tvar ua = i.split('.')[0];\n\t\tvar os = i.split('.')[1];\n\t\tif (os && BA.ua['is' + os] && BA.ua['is' + ua] || !os && BA.ua['is' + ua]) {\n\t\t\tBAAppendCSS(BA.url.cssDir + BA.css.revise[i], BA.css.reviseTitle);\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function importStyles()\r{\r var myDocumentsFolder = Folder.myDocuments.fullName;\r var stylesFilePath = myDocumentsFolder + \"/BIP/lessonStyles.indd\";\r $.writeln(\"loading styles from: \" + stylesFilePath);\r docData.xmlDocument.importStyles(ImportFormat.textStylesFormat, File(stylesFilePath), GlobalClashResolutionStrategy.loadAllWithOverwrite);\r}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if invoking `Benchmarkrun` with asynchronous cycles.
function isAsync(object) { // Avoid using `instanceof` here because of IE memory leak issues with host objects. var async = args[0] && args[0].async; return name == 'run' && (object instanceof Benchmark) && ((async == null ? object.options.async : async) && support.timeout || object.defer); }
[ "isCompletedRunCurrent () {\n return this.runCurrent?.RunDigest && Mdf.isRunCompleted(this.runCurrent)\n }", "function runAsync(func) {\n window.setTimeout(func, 0);\n}", "function krnCheckExecution()\n{\n return _Scheduler.processEnqueued;\n}", "isBusy() {\n return this.totalTasks() >= this.options.maxPoolSize;\n }", "hasCallback() {}", "function assertOps(fn) {\n return async function asyncOpSanitizer() {\n const pre = metrics();\n await fn();\n // Defer until next event loop turn - that way timeouts and intervals\n // cleared can actually be removed from resource table, otherwise\n // false positives may occur (https://github.com/denoland/deno/issues/4591)\n await delay(0);\n const post = metrics();\n // We're checking diff because one might spawn HTTP server in the background\n // that will be a pending async op before test starts.\n const dispatchedDiff = post.opsDispatchedAsync - pre.opsDispatchedAsync;\n const completedDiff = post.opsCompletedAsync - pre.opsCompletedAsync;\n assert(\n dispatchedDiff === completedDiff,\n `Test case is leaking async ops.\nBefore:\n - dispatched: ${pre.opsDispatchedAsync}\n - completed: ${pre.opsCompletedAsync}\nAfter:\n - dispatched: ${post.opsDispatchedAsync}\n - completed: ${post.opsCompletedAsync}\n\nMake sure to await all promises returned from Deno APIs before\nfinishing test case.`,\n );\n };\n }", "function checkLoops() {\n\t\tfor (var i = 0, il = this.loops.length; i < il; ++i) {\n\t\t\tvar loop = this.loops[i];\n\t\t\t\n\t\t\tif (loop._current !== loop.iterations && this._currentTime >= loop.stopTime) {\n\t\t\t\tthis._currentTime = loop.startTime;\n\t\t\t\tloop._current++;\n\t\t\t}\n\t\t}\n\t}", "function onCycle() {\n var bench = this,\n cycles = bench.cycles;\n if (!bench.aborted) {\n setStatus(bench.name + ' &times; ' + formatNumber(bench.count) + ' (' +\n cycles + ' cycle' + (cycles == 1 ? '' : 's') + ')');\n }\n }", "async isBusy() {\n return new Promise((resolve, reject) => {\n this.rpc.stdin.write('busy' + os.EOL);\n this.rpc.stdout.once('data', (data) => {\n data = data.toString().trim();\n if ((typeof data == 'boolean' && data) || data == \"true\") {\n resolve(true)\n } else {\n resolve(false)\n }\n });\n });\n\n }", "function completeCycleIfNecessary() {\n if (stateManager.getAccountsWithStatus(Statuses.NOT_STARTED).length == 0 &&\n stateManager.getStatus() != Statuses.COMPLETE) {\n stateManager.setStatus(Statuses.COMPLETE);\n stateManager.saveState();\n processFinalResults(stateManager.getResults());\n }\n }", "_checkGeneratorIsAlive() {\n this._log('Checking generator is alive...');\n this._client.existsAsync(LAST_GENERATOR_TIME).then((reply) => {\n if (reply === 0) {\n this._client.watch(LAST_GENERATOR_TIME);\n const multiQuery = this._client.multi()\n .set(LAST_GENERATOR_TIME, 1)\n .expire(LAST_GENERATOR_TIME, 10);\n return multiQuery.execAsync()\n } else {\n Promise.resolve(null);\n }\n }).then((reply) => {\n if (reply == null) {\n this._getMessages();\n } else {\n this._isGenerator = true;\n this._generateMessage();\n }\n }).catch((err) => { throw err });\n }", "doBenchmarks() {\n if (!this.state.isBenching) {\n const bench = Benchmark.benchInfo();\n const benchResults = this.state.benchResults;\n this.setState({ isBenching: true });\n if (this.state.benchQueue.length > 0) {\n const tmp = this.state.benchQueue;\n const functionToBench = tmp.shift();\n // const functionFromString = window[Benchmark];\n const benchResult = Benchmark.bench(functionToBench);\n if (!(\"error\" in benchResult)) {\n benchResults[functionToBench] = benchResult;\n this.changeData(\n functionToBench,\n format.formatTime(\n benchResult.time,\n bench.unit.time,\n format.adaptedTimeSymbol(benchResult.time)\n ),\n format.formatSize(\n benchResult.size,\n bench.unit.size,\n format.adaptedSizeSymbol(benchResult.size)\n ),\n this.popUp(benchResult.data)\n );\n if (tmp !== null) this.changeData(tmp[0], clockSpinner, clockSpinner);\n // if (typeof functionFromString === \"function\") functionFromString();\n this.setState({ benchQueue: tmp });\n } else {\n if (tmp !== null) this.changeData(tmp[0], clockSpinner, clockSpinner);\n console.error(benchResult.error);\n this.setState({ benchQueue: tmp });\n }\n }\n this.setState({\n isBenching: false,\n benchInfo: bench,\n benchResults: benchResults,\n });\n }\n }", "function asynchronity() {\n //setTimeout is used, which is an asynchronous function.\n let result = new Promise((resolve, reject) => {\n setTimeout(() => resolve('I am complete!'), 1000);\n });\n\n /*Because of setTimeout, result isn't evaluated yet. Because of JavaScript's\n asynchronity, result is still logged. */\n console.log(result); //Logs Promise { <pending> }\n\n /*JavaScript contains many asynchronous functions, such as setInterval,\n requestAnimationFrame, XMLHttpRequest, WebSocket, Worker, some APIs, and more. */\n}", "function do_a(){\n // simulate a time consuming function\n setTimeout(function(){\n console.log( \"'do_a': this takes longer than 'do_b'\");\n }, 1000);\n}", "async function isSimulatorAppRunningAsync() {\n try {\n const zeroMeansNo = (await osascript.execAsync('tell app \"System Events\" to count processes whose name is \"Simulator\"')).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n }\n catch (error) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n return true;\n}", "function expectedEventsDispatched()/* : Boolean*/\n {\n for (var i/*:uint*/ = 0; i < this._expectedEventTypes$_LKQ.length; ++i )\n {\n var expectedEvent/* : String*/ = this._expectedEventTypes$_LKQ[i];\n \tif ( this.expectedEventDispatched( expectedEvent ) == false )\n \t\treturn false;\n }\n return true;\n }", "get hasCalls() {\n return this.calls.length > 0;\n }", "function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }", "function exodustimeout_sync(command) {\n\n logevent('exodustimeout_sync:geventhandler.done:' + geventhandler.done)\n\n //if another event handler is already running then defer execution for 100ms\n if (gblockevents) {\n window.setTimeout('exodustimeout_sync(\"' + command + '\")', 100)\n return\n }\n\n //the async function should run to completion\n // even if it pauses for multiple async operations on the way.\n //command MUST be prefixed with \"yield *\" and return a generator\n var generator = eval(command);\n exodusneweventhandler(generator, 'exodustimeout_sync() ' + command)//yielding code\n //not interested in result\n}", "function checkAsynRequestCount(){\n if(asyncRequestCount === 0){\n chrome.tabs.reload();\n document.getElementById('loader').style.display = \"none\";\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restrict access to editors only, redirecting and returning false if user is not an editor
function restrictedToEditors(lesson,req,res){ if ( lesson.editors.includes(req.user.id) ) return false; res.status(401).json({message: "Access Denied"}); return true; }
[ "ableToEdit() {\n const accountIdForEdit = sessionStorage.getItem(\"accountIdForEdit\");\n if (accountIdForEdit !== null) {\n sessionStorage.setItem(\"accountId\", accountIdForEdit);\n return true;\n } else {\n return false;\n }\n }", "isEditor(value) {\n if (!isPlainObject(value)) return false;\n var cachedIsEditor = IS_EDITOR_CACHE.get(value);\n\n if (cachedIsEditor !== undefined) {\n return cachedIsEditor;\n }\n\n var isEditor = typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && typeof value.deleteForward === 'function' && typeof value.deleteFragment === 'function' && typeof value.insertBreak === 'function' && typeof value.insertFragment === 'function' && typeof value.insertNode === 'function' && typeof value.insertText === 'function' && typeof value.isInline === 'function' && typeof value.isVoid === 'function' && typeof value.normalizeNode === 'function' && typeof value.onChange === 'function' && typeof value.removeMark === 'function' && (value.marks === null || isPlainObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && Node$1.isNodeList(value.children) && Operation.isOperationList(value.operations);\n IS_EDITOR_CACHE.set(value, isEditor);\n return isEditor;\n }", "function canEdit() {\n return Jupyter.narrative.uiModeIs('edit');\n }", "function check_block_editor(doc, elem) {\n if (doc.editor != phila.editor.editor_id) {\n elem.find('input').prop('disabled', true);\n elem.find('textarea').prop('disabled', true);\n elem.find(':not(.block-edit)').fadeTo(0, 0.75);\n elem.find(':not(.block-edit)').addClass('disabled');\n }\n else {\n elem.find('input').removeProp('disabled');\n elem.find('textarea').removeProp('disabled');\n elem.find('*').removeClass('disabled');\n elem.find('*').fadeTo(0, 1);\n }\n}", "function openUserEditor(){\n\n\t$('.content-panel').hide();\n\n\t$('#editUserPanel').show();\n\n}", "function isModerator(user){\r\n return user.mod;\r\n}", "function usingHTMLEditor(){\n\tif(typeof(FCKeditorAPI) != \"undefined\" && (fckEditor = FCKeditorAPI.GetInstance(\"html_body\"))) {\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}", "isEditing() {\n return Template.instance().uiState.get(\"editing\");\n }", "function EditPost() {\n if (post.user._id === \"60af83bbbe9b150015506e18\") {\n setEdited(!edited);\n } else {\n alert(\"You can't Edit someone's post!!!\");\n }\n }", "function unNewsEditLinkChecker() {\n\tif( wgPageName != 'UnNews:Main_Page' || wgIsLogin ) {\n\t\treturn;\n\t}\n\n\teditlinks = document.getElementsByTagName( 'span' );\n\tfor( i = 0; i < editlinks.length; i++ ) {\n\t\tif( editlinks[i].className != 'editor' ) {\n\t\t\tcontinue;\n\t\t}\n\t\teditlinks[i].parentNode.removeChild( editlinks[i] );\n\t}\n}", "function evaluateCmsContentAccess() {\n \tvar isProtected = $(\"#content\").attr(\"data-protected\");\n\n if(isProtected != undefined && isProtected != null){\n\n // Evaluate existence of cookie\n\t\t\tvar SSOCodeFromCookie = getSSOCookie();\n if(SSOCodeFromCookie == null){\n // Show login prompt\n\t\t\t\tvar hashPath = window.location.hash;\n //console.log(\"hashPath \" + hashPath);\n if(!hashPath.includes(\"userAction=Login\")) {\n\n var width = $(window).width();\n var element;\n \n if(width <= 767) {\n element = $(\"#ocp-widget a.userProfile_icon\");\n } else {\n element = $('a[ng-click=\"showtriangle(\\'login\\')\"]');\n }\n if(element != null){\n setTimeout(function() {\n //console.log(element);\n element.triggerHandler('click');\n }, 1000);\n } \n } \n\n\n\t\t\t\t// Wait for signin success\n $( document ).on( \"userSignedIn\", function( event ) {\n //console.log(\"Received login complete notification\");\n loadCmsContent(getExternalizedCurrPage() + \".content.html\");\n });\n } else {\n loadCmsContent(getExternalizedCurrPage() + \".content.html\");\n }\n } \n }", "toggle() {\n let editorEl = h.getEditorEl(),\n toggleEl = h.getEditorToggleEl(),\n mainNav = h.getMainNavEl();\n\n // Clear menus and load edit panel\n editor.clearMenus();\n editor.currentPost = view.currentPost;\n editor.currentPostType = view.currentPost.type;\n editor.currentMenu = 'edit';\n\n // Toggle editor and nav hidden classes\n editorEl.classList.toggle('hidden');\n toggleEl.classList.toggle('hidden');\n // Toggle whether view nav is disabled\n mainNav.classList.toggle('inactive');\n\n // Take specific actions if opening or closing editor\n if (toggleEl.classList.contains('hidden') === false) {\n // If opening editor\n var navTitleLink = h.getEditorNavTitleLink();\n editor.showEditPanel();\n navTitleLink.addEventListener('click', editor.listenSecondaryNavTitle, false);\n view.listenDisableMainNavLinks();\n } else {\n // If closing editor\n if (view.currentPost.type === 'posts') {\n router.updateHash('blog/' + view.currentPost.slug);\n } else {\n if (editor.currentPost.slug === '_new') {\n // If closing a new post editor\n router.updateHash('blog');\n router.setCurrentPost();\n } else {\n router.updateHash(view.currentPost.slug);\n }\n }\n view.listenMainNavLinksUpdatePage();\n }\n }", "function isTutor(req, res, next) {\n var user = req.user;\n if (user.roles.indexOf('tutor') > -1) {\n next();\n } else {\n res.status(403).end();\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 disableEditLink() {\n if ( mw.config.get('wgNamespaceNumber') !== 110 && mw.config.get('wgNamespaceNumber') % 2 !== 1 ) { return; }\n var skin = mw.config.get('skin');\n if ( ( skin !== 'oasis' && skin !== 'monaco' && skin !== 'monobook' ) || // might be unnecessary, other skins haven't been checked\n $.inArray( 'sysop', mw.config.get('wgUserGroups') ) > -1 || // disable completely for admins\n typeof enableOldForumEdit !== 'undefined' ||\n !$('#archived-edit-link')[0] ) { return; }\n\n var editLink = ( skin === 'oasis' || skin === 'monaco' ) ? $('#ca-edit') : $('#ca-edit a');\n if ( !editLink[0] ) { return; }\n\n editLink.html('Archived').removeAttr('href').removeAttr('title').css({'color':'gray','cursor':'auto'});\n\n $('span.editsection-upper').remove();\n\n}", "function verifyPermission() {\n let user = JSON.parse(localStorage.getItem(USER_KEY));\n if (user == \"\")\n {\n // Should be denied access\n document.getElementsByTagName(\"body\")[0].innerText = \"Access Denied\";\n }\n\n else\n {\n var url = window.location.pathname;\n var permissionsLst = ACCESSIBLE_PAGES[user.permission];\n if (!permissionsLst.includes(url)){\n // Should be denied access\n document\n .getElementsByTagName(\"body\")[0]\n .innerText = \"Access Denied\";\n }\n }\n}", "function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}", "function checkReviewer(req, res, next) {\n // Find the user in charge of course\n Course.findById(req.params.courseId)\n .exec(function(err, course) {\n if(err) return next(err);\n // Check that the current authenticated user is not the same as the user\n // in charge of the course\n if (req.user._id.equals(course.user._id)) {\n var err = new Error('You cannot review your own course.');\n err.status = 401;\n return next(err);\n } else {\n return next();\n }\n });\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables user to add a new expense item & stores that data
function addExpense() { console.log('Adding expense'); var expense = {}; expense.amount = document.querySelector('#amount').value; expense.date = new Date(document.querySelector('#date').value); expense.date = expense.date.toDateString(); console.log(expense.date); expense.category = document.querySelector('#category').value; expense.notes = document.querySelector('#notes').value; if (user.expenses[expense.date]) { console.log('expenses exist'); } else { console.log("expenses don't exist"); user.expenses[expense.date] = []; } console.log(expense.date.length); user.expenses[expense.date].push(expense); users[currentUser] = user; localStorage.setItem('users', JSON.stringify(users)); location.href = 'expenses.html'; }
[ "function addExpense(){\n var Addexpen = document.getElementById(\"AddExpen\").value\n \n if(Addexpen > 0 ){\n\n setExpense( Addexpen)\n setExpenId( expenId + 1)\n\n }\n }", "function addExpanse(context) {\n if(addAmount.value === \"\" || addDate.value === \"\") {\n return false;\n }\n\n if(localStorage.getItem(\"expanseIndex\") === null){\n localStorage.setItem(\"expanseIndex\",\"1\");\n }\n\n let index = parseInt(localStorage.getItem(\"expanseIndex\"));\n\n var expanse = new Expanse(addAmount.value, addCategory.value, addDate.value, addDescription.value);\n addAmount.value = \"\";\n addCategory.value = \"\";\n addDate.value = \"\";\n addDescription.value = \"\";\n localStorage.setItem(`expanse${index}`,JSON.stringify(expanse));\n\n index++;\n localStorage.setItem(\"expanseIndex\", index);\n refreshExpanses();\n\n\n\n}", "function Expense(id, desc, value) {\n this.id = id;\n this.desc = desc;\n this.value = value;\n }", "addExpense(expenseObj, expenseOut) {\r\n budgetParams['expenses'] += parseInt(expenseObj.amount); \r\n expenseOut.textContent = budgetParams['expenses'];\r\n }", "function addInventory() {\n\n\t//Lets manager identify which item to credit\n\tinquirer\n\t\t.prompt ({\n\t\t\tname: \"restock_product\",\n\t\t\ttype: \"input\",\n\t\t\tmessage: \"Type the Id of the product you want to re-stock:\"\n\t\t})\n\t\t//Initiates database credit process\n\t\t.then(function(answer) {\n\n\t\t\t//Queries database and increases quantity by +5\n\t\t\tconnection.query(\"UPDATE products SET quantity = quantity + 5 WHERE id =\"+answer.restock_product, function(err, res) {\n\t\t\tif (err) throw err;\n\n\t\t\t//Returns the updated inventory table\n\t\t\tallInventory();\n\t\t\t})\n\t\t}\n\t)\n}", "function createNewExpense(args){\n\n args = Joi.attempt(\n args,\n schemaCreateNewExpense,\n \"Failed to validate arguments\"\n );\n\n const\n employee = args.for_employee,\n expense_type = args.of_type,\n valide_attributes = args.with_parameters;\n\n const\n date_start = moment.utc(),\n expense_amount = parseFloat(valide_attributes.expense_amount) || 0;\n\n // Check that expense amount is greater than zero\n if ( expense_amount <= 0 ) {\n Exception.throwUserError({\n user_error : \"Amount should be greater than zero\",\n system_error : `Failed to add new Expense for user ${ employee.id } `\n `because amount is not greater than zero`,\n });\n }\n\n const comment = valide_attributes.reason,\n companyId = employee.companyId;\n\n // Make sure that booking to be created is not going to ovelap with\n // any existing bookings\n return Promise\n\n .try(() => employee.promise_boss())\n .then(main_supervisor => {\n\n const new_expense_status = employee.is_auto_approve()\n ? Models.Expense.status_approved()\n : Models.Expense.status_new();\n\n // Following statement creates in memory only expense object\n // it is not in database until .save() method is called\n return Promise.resolve(Models.Expense.build({\n userId : employee.id,\n status : new_expense_status,\n approverId : main_supervisor.id,\n employee_comment : valide_attributes.reason,\n\n date_start : date_start.format('YYYY-MM-DD'),\n expense_type : expense_type,\n expense_amount : expense_amount,\n }));\n })\n\n .then(expense_to_create =>\n expense_to_create.save()\n )\n .then(expense => commentExpenseIfNeeded({expense,comment,companyId}).then(() => expense))\n .then(expense => Promise.resolve(expense));\n}", "function addExercise() {\n // Grab ui inputs\n let name = document.querySelector(el.exerciseInput);\n let weight = document.querySelector(el.weightInput);\n\n // Add exercise to DS\n exercise.addExercise(name.value, weight.value);\n\n // Get recently added exercise\n let current = exercise.getCurrentExercise();\n\n // Display new exercise from data state to ui\n ui.addExercise(current.id, current.name, current.weight);\n\n // Clear input values\n name.value = \"\";\n weight.value = \"\";\n }", "function addToInventory() {\n\t// Querying the Database\n\tconnection.query(\"SELECT * FROM products\", function (err, res) {\n\n\t\tif (err) throw err;\n \n // Setting up our results in the console.table NPM\n consoleTable(\"\\nCurrent Inventory Data\", res);\n \n\t\t// Inquirer asking Manager to select ID of the item they wish to add Inventory of\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\tname: \"id\",\n\t\t\t\tmessage: \"Input the item ID to increase inventory on.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0 && value <= res.length) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"amount\",\n\t\t\t\tmessage: \"Input the amount to increase inventory by.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t]).then(function(answer) {\n\n\t\t\tvar itemQty;\n\n\t\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\t\tif (parseInt(answer.id) === res[i].item_id) {\n\t\t\t\t\titemQty = res[i].stock_quantity;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Call the function to Increase the Quantity with the Parameters needed\n\t\t\tincreaseQty(answer.id, itemQty, answer.amount);\n\t\t});\n\t});\n}", "function addToInventory() {\n\tconnection.query('SELECT * FROM products', function(err,res) {\n\t\tif(err) throw err;\n\t\tconsole.log(res);\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\ttype: 'input',\n\t\t\t\tmessage: 'enter the Item Id you would like to add more to.',\n\t\t\t\tname: 'addInvId'\n\t\t\t}\n\t\t]).then(function(inquireResponse) {\n\t\t\t\n\t\t\tvar id = inquireResponse.addInvId;\n\t\t\tidValidCheck(id);\n\n\t\t});\n\n\t});\n\t\n}", "async addOfferingToInvestmentMethod(req, res, next) {\n try {\n const {\n body,\n models: { Investments },\n } = req;\n var { offering, investment } = body;\n var inv = await Investments.findById(investment);\n if (!inv) {\n throw Error('Couldnt find this investment');\n }\n inv.offering = offering;\n if (!inv.completed.includes('Offering')) {\n inv.completed.push('Offering');\n }\n await inv.save();\n return successResponse(\n res,\n 'Offering detail added successfully',\n 200,\n inv\n );\n } catch (error) {\n return errorHandler(error, req, res, next);\n }\n }", "function addItem(req, res, next) {\n var userId = req.userId,\n offerId = req.body.offerId; // the id in the postgres table\n\n console.log(JSON.stringify(req.body));\n\n db.query('SELECT offerId FROM wallet WHERE userId=$1 AND offerId=$2', [userId, offerId], true)\n .then(function(offer) {\n if (offer) {\n return res.send(400, 'This offer is already in your wallet');\n }\n db.query('INSERT INTO wallet (userId, offerId) VALUES ($1, $2)', [userId, offerId], true)\n .then(function () {\n return res.send('ok');\n })\n .fail(function(err) {\n return next(err);\n });\n })\n .catch(next);\n}", "fillIncomeForm(item) {\n // Change to edit form\n this.changeIncomeForm(\"edit\", item.id);\n\n // Set edit item value to income form\n this.incomeDateInput.value = item.date;\n this.incomeTitleInput.value = item.title;\n this.incomeCostInput.value = item.cost.split(\",\").join(\"\");\n }", "function addItem() {\n const title = document.getElementById('title').value;\n const description = document.getElementById('description').value;\n const image = document.getElementById('image').value;\n const price = document.getElementById('price').value;\n const status = document.getElementById('status').value;\n const username = document.getElementById('usernameItemSection').value;\n\n const dataToSend = JSON.stringify({\n title: title,\n description: description,\n image: image,\n price: price,\n status: status,\n username: username\n });\n const url = `${URL_BASE}/add/item/${username}`;\n const request = new XMLHttpRequest();\n request.open('POST', url);\n request.send(dataToSend);\n}", "function salvarItemEstoque() {\n if ($scope.novoItemEstoque.Id > 0) {\n atualizarItemEstoque();\n }\n }", "addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }", "addExpense(expense) {\n const div = document.createElement('div')\n div.classList.add('expense')\n div.innerHTML = `\n <div class=\"expense-item d-flex justify-content-between align-items-baseline\">\n <h6 class=\"expense-title mb-0 text-uppercase list-item\">${expense.title}</h6><h5 class=\"expense-amount mb-0 list-item\">${expense.amount}</h5>\n <div class=\"expense-icons list-item\">\n <a href=\"#\" class=\"edit-icon mx-2\" data-id=\"${expense.id}\">\n <i class=\"fas fa-edit\"></i>\n </a>\n <a href=\"#\" class=\"delete-icon mx-2\" data-id=\"${expense.id}\">\n <i class=\"fas fa-trash\"></i>\n </a>\n </div>\n</div>\n`\nthis.expenseList.appendChild(div)\n}", "static createInvoiceItem(invoice_id, user_id, role, advanced_price=0) {\n return axios.post(\n liabilities_url + 'invoice_items/',\n {\n invoice_id: invoice_id,\n user_id: user_id,\n role: role,\n advanced_price: advanced_price,\n }\n );\n }", "addValue() {\n const newItemName = document.querySelector('#item-name').value;\n const newItemPrice = document.querySelector('#item-price').value;\n const newOutStock = document.querySelector('#out-stock').value;\n const newItemType = document.querySelector('#item-type').value;\n const newItemDesc = document.querySelector('#item-desc').value;\n\n this.setState ({ newItemName, newItemPrice, newOutStock , newItemType, newItemDesc })\n }", "function add() {\n\t\t\tvm.enquiry.enquiries.push(\n\t\t\t\t{\n\t\t\t\t\titineries: '',\n\t\t\t\t\tplan: '',\n\t\t\t\t\tschool_contact_person: '',\n\t\t\t\t\tschool_class: '',\n\t\t\t\t\ttransport: [],\n\t\t\t\t\tfood: [],\n\t\t\t\t\tsharing: [],\n\t\t\t\t\tpackage_type: [],\n\t\t\t\t\taccomodation: [],\n\t\t\t\t\tquotations: [],\n\t\t\t\t\textras: [],\n\t\t\t\t\tentry: [],\n\t\t\t\t\tremarks: '',\n\t\t\t\t\tno_of_students: 0,\n\t\t\t\t\tno_of_teachers: 0\n\t\t\t\t}\n\t\t\t);\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the pageName from the given Url String. By default, this is the part of the url without the host (domain) and without query parameters. You can register a custom extraction function to be used.
function getPageNameFromUrl(urlString) { var urlObject = _url.default.parse(urlString); if ((0, _isFunction.default)(customExtractionFunction)) { return customExtractionFunction(urlObject); } else if (!isValidUrlObject(urlObject)) { return urlString; } else { return buildDefaultPageName(urlObject); } }
[ "function findPageNameFromHref( href ) {\n\t\tvar m = pageRE.exec( href );\n\t\treturn m ? decodeURIComponent(\n\t\t\t( m[1] || m[2] ).replace( /\\+/g, '%20' )\n\t\t).replace( / /g, '_' ) : null;\n\t}", "function domainName(url){\n// if url begins with s: followed by wwww\n if (url.includes(\"s:\\//www\")) {\nreturn url.slice(12).split('.')[0]; \n } else if (url.includes(\"p:\\//www\")) {\nreturn url.slice(11).split('.')[0];\n } else if (url.includes(\"ps:\")) {\nreturn url.slice(8).split('.')[0];\n } else if (url.includes(\"ttp:\")) {\nreturn url.slice(7).split('.')[0];\n } else if (url.includes(\"www.\")) {\nreturn url.slice(4).split('.')[0];\n } else {\n \treturn url.slice(0).split('.')[0];\n }\n}", "function giveFriendlyUrl(url){\n\t\tvar splitElements = url.split(\"../index.html\");\n\t\treturn splitElements[splitElements.length-2];\n\t}", "function getDomainByUrl(url) {\n\n\t// returns the domain by the full url\n\treturn URI(url).hostname();\n\n}", "function generateCampaignName() {\n var splitURL = window.location.href.split('/');\n return splitURL[3];\n}", "function extractHostname(t) {\n return (t.indexOf(\"//\") > -1 ? t.split(\"/\")[2] : t.split(\"/\")[0]).split(\":\")[0].split(\"?\")[0]\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 GetPage() {\n return [location.href.split(\"/\")[4], location.href.split(\"/\")[5], location.href.split(\"/\")[6], location.href.split(\"/\")[7]].map(function (L) {\n if (typeof L === \"undefined\") {\n return \"\";\n } else {\n return L.split(\"?\")[0].split(\"#\")[0];\n }\n });\n}", "function getIndexPage(numberString) {\n\tvar number = numberString.split(\"/\");\n\treturn number[0];\n}", "function PT_getSubdomain() {\n var PT_regexParse = new RegExp('[a-z\\-0-9]{2,63}\\.[a-z\\.]{2,5}$');\n var PT_urlParts = PT_regexParse.exec(window.location.hostname);\n\n return window.location.hostname.replace(PT_urlParts[0], '').slice(0, -1);\n}", "function parseBreadcrumbTitle(pageUrl) {\n var titleObject = $(_options.titleElement);\n var crumbTitle;\n\n if (titleObject.length > 0 && titleObject.attr(\"title\")) {\n crumbTitle = titleObject.attr(\"title\");\n }\n else {\n // Strip out the first part of the url\n crumbTitle = pageUrl.replace(/^.*\\/|\\.[^.]*$/g, '');\n\n // Strip out the query string\n if (crumbTitle.indexOf(\"?\") > 0)\n crumbTitle = crumbTitle.split('?')[0];\n\n // If we still have a question mark, this is probably the landing page, so just set to document title\n if (crumbTitle.indexOf(\"?\") == 0) {\n crumbTitle = document.title;\n }\n\n // Check to see if it's a GUID or an int. In MVC, this indicates an edit, so we don't want to display\n // a GUID in the crumb. If we get either, display the previous View name (so, SecurityManager/User/EditUser/64918c0d-b024-4225-8607-d5b822cf52be\n // would become \"Edit User\" instead of \"64918c0d-b024-4225-8607-d5b822cf52be\"\n if (isGuid(crumbTitle) || isInt(crumbTitle)) {\n // split the url on the /, take the second to last entry\n var viewTitle = pageUrl.split('/');\n crumbTitle = viewTitle[viewTitle.length - 2];\n }\n }\n\n // Add spaces between capital letters to make it look purdy\n return crumbTitle.replace(/([a-z])([A-Z])/g, '$1 $2');\n }", "function urlMatch(url) {\n return url.match(/etter=([A-Z])/)[1];\n}", "function language_segment_from_url() {\n var path = window.location.pathname;\n var language_regexp = '/((?:' + Object.keys( all_languages ).join( \"|\" ) + ')/)'\n var match = path.match( language_regexp );\n if ( match !== null )\n return match[ 1 ];\n return '';\n }", "function getMatchIdFromUrl(url)\n{\n const URL_OBJ = new URL(url);\n return URL_OBJ.pathname.split('/')[2];\n}", "function slugifyUrl(url) {\n\t\t\treturn Util.parseUrl(url).path\n\t\t\t\t.replace(/^[^\\w]+|[^\\w]+$/g, '')\n\t\t\t\t.replace(/[^\\w]+/g, '-')\n\t\t\t\t.toLocaleLowerCase();\n\t\t}", "function extract(url) {\n var index = url.lastIndexOf(\"category\");\n var cat = '';\n for(index+=9;index < url.length && url[index] != '/';index++) {\n cat += url[index];\n }\n return cat;\n }", "function getWordFromURL(url) {\n // get query param\n var a = url.split(\"q=\");\n if (a.length != 2) {\n return \"\"\n } \n\n // sanitize search query string:\n // remove trailing parameters\n // un URL encode\n // replace \"+\" with spaces\n var searchQueryStringRaw = a[1].split(\"&\")[0];\n var searchQueryString = decodeURIComponent(searchQueryStringRaw).replace(\"+\", \" \");\n\n console.log(searchQueryStringRaw);\n\n // if search query was of format \"define: [word]\", return word\n var terms = searchQueryString.split(\":\");\n if (terms.length == 2 && terms[0] == \"define\") {\n var definitionTarget = terms[1];\n \n // trim starting space, if necessary\n if (definitionTarget[0] == \" \" && definitionTarget.length > 1) {\n definitionTarget = definitionTarget.substring(1, definitionTarget.length);\n }\n return definitionTarget;\n }\n return \"\";\n}", "getBookId(url) {\n // match a url like:\n // https://www.safaribooksonline.com/library/view/startup-opportunities-2nd/9781119378181/\n // https://www.safaribooksonline.com/library/view/startup-growth-engines/77961SEM00001/\n let match = url.match(/\\/library\\/view\\/[^\\/]+\\/(\\w+)\\//)\n let bookId = match && match[1]\n\n if (!bookId) {\n throw new Error('could not extract book id from url')\n }\n\n return bookId\n }", "function getRelativeConverter(pageUrl) {\n return (src) => {\n const isAbsoluteUrl = /^(\\/\\/|\\w+:\\/\\/)/.exec(src);\n if (isAbsoluteUrl) {\n return src;\n } else {\n const parsed = url.parse(pageUrl);\n const base = path.basename(parsed.pathname);\n return parsed.protocol + '//' + parsed.host +\n (base ? base + '/' : '') + src;\n }\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add click functions to "play" and "reset" buttons when clicked, buttons call functions ready() and wipeGameBoard() and wipeGameTimer
function makeReady() { console.log("play ready!"); document.getElementById("play").onclick = function() { //"play" button disabled while game is in play document.getElementById("play").disabled = true; //delays the function that re-enables play button until game timer = 0 setTimeout(enablePlay, 14000); ready(); }; // console.log("reset ready!"); // document.getElementById("reset").onclick = function() { // wipeGameTimer(); // wipeGameBoard(); // }; makeGameboard(); }
[ "function buildGameButton(){\n\tbuttonStart.cursor = \"pointer\";\n\tbuttonStart.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('tutorial');\n\t});\n\t\n\tbuttonGotIt.cursor = \"pointer\";\n\tbuttonGotIt.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('game');\n\t});\n\t\n\tfor(n=0;n<pots_arr.length;n++){\n\t\t$.buttons[n+'_cook'].cursor = \"pointer\";\n\t\t$.buttons[n+'_cook'].id = n;\n\t\t$.buttons[n+'_cook'].addEventListener(\"click\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tstartCook(evt.target.id);\n\t\t});\n\t\t\n\t\t$.buttons[n+'_burn'].cursor = \"pointer\";\n\t\t$.buttons[n+'_burn'].id = n;\n\t\t$.buttons[n+'_burn'].addEventListener(\"mousedown\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tpots_arr[evt.target.id].heatUp = true;\n\t\t\tplaySound('soundBurn');\n\t\t});\n\t\t\n\t\t$.buttons[n+'_burn'].addEventListener(\"pressup\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tpots_arr[evt.target.id].heatUp = false;\n\t\t});\n\t}\n\t\n\tbuttonReplay.cursor = \"pointer\";\n\tbuttonReplay.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('tutorial');\n\t});\n\t\n\ticonFacebook.cursor = \"pointer\";\n\ticonFacebook.addEventListener(\"click\", function(evt) {\n\t\tshare('facebook');\n\t});\n\ticonTwitter.cursor = \"pointer\";\n\ticonTwitter.addEventListener(\"click\", function(evt) {\n\t\tshare('twitter');\n\t});\n\ticonGoogle.cursor = \"pointer\";\n\ticonGoogle.addEventListener(\"click\", function(evt) {\n\t\tshare('google');\n\t});\n}", "function createPlayAgainEvents()\n {\n yesButton();\n\n noButton();\n\n function yesButton()\n {\n canvasObjs[1] = new CanvasObject(250, DEFAULT_CANVAS_SIZE - 75, 0, 0, CHIP_RADIUS);\n canvasObjs[1].clickCallback = function()\n {\n Game.counter = 0;\n resetArray();\n Game.lastTimedEvent = 0;\n resetHand(Game.CPUHand);\n resetHand(Game.userHand);\n }\n canvasObjs[1].hoverCallback = function()\n {\n drawChip(250, DEFAULT_CANVAS_SIZE - 75, 'YES', '#0000AA');\n }\n }\n\n function noButton()\n {\n canvasObjs[2] = new CanvasObject(375, DEFAULT_CANVAS_SIZE - 75, 0, 0, CHIP_RADIUS);\n canvasObjs[2].clickCallback = function()\n {\n Game.context = 'TitleScreen';\n resetArray();\n Game.lastTimedEvent = 0;\n resetHand(Game.CPUHand);\n resetHand(Game.userHand);\n Game.prevCounter = null;\n }\n canvasObjs[2].hoverCallback = function()\n {\n drawChip(375, DEFAULT_CANVAS_SIZE - 75, 'NO', '#0000AA');\n }\n }\n }", "function playerClicks () {\n\n\t\tvar playButtons = document.getElementsByClassName('play-icon');\n\t\tvar pauseButtons = document.getElementsByClassName('pause-icon');\n\t\tvar playerBarName = document.getElementById('player-bar-name');\n\t\tvar closePlayer = document.getElementById('close-player');\n\t\tvar ffButton = document.getElementById('ff-icon');\n\t\tvar rewButton = document.getElementById('rew-icon');\n\t\tvar clearUpNext = document.getElementById('clear-up-next');\n\n\t\tfor (var i = 0, lenOne = pauseButtons.length; i < lenOne; i++) {\n\t\t\tpauseButtons[i].addEventListener('click', Player.pause);\n\t\t}\n\n\t\tfor (var j = 0, lenTwo = playButtons.length; j < lenTwo; j++) {\n\t\t\tplayButtons[j].addEventListener('click', Player.play);\n\t\t}\n\n\t\tplayerBarName.addEventListener('click', Views.showPlayer);\n\t\tclosePlayer.addEventListener('click', Views.hidePlayer);\n\t\tffButton.addEventListener('click', Player.next);\n\t\trewButton.addEventListener('click', Player.previous);\n\n\t\tclearUpNext.addEventListener('click', function () {\n\n\t\t\tPlayer.clear();\n\t\t\tViews.clearSongs();\n\n\t\t});\n\n\t}", "function playAgain(){\n document.querySelector('button').setAttribute('id', 'button-hide'); //remove play again button\n resetSelectionState();\n resetGameBoardState();\n addElementListener(document.getElementsByTagName('div')); //reapply board event listeners\n addElementListener(document.getElementsByTagName('button')); //apply replay button event listener\n\n var gameBoard = document.getElementById('game-board'); //remove game board\n gameBoard.removeAttribute('id');\n gameBoard.setAttribute('id', 'board-hide');\n\n isGameOver = false;\n}", "function startGame() {\n createButtons();\n createCards();\n displayCards();\n}", "function startSetUpBoard() {\n $('#menu').remove();\n\n // add buttons here\n createOppoBoard();\n createMyBoard();\n $('#status').text('Pick 15 locations on your board to place your ships');\n isSettingUp = true;\n}", "function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }", "function play(){\n removeClassName('no-display');\n addClassName('img', 'no-display');\n addClassName('play-btn', 'no-display')\n showDisplay('player-score');\n showDisplay('computer-score');\n showDisplay('results');\n }", "function playAgainClick()\n{\n\tnumTurns = settings.numTurns; \n\t$('#endOfGame').css('display', 'none');\n\tresetInputs();\n\tdocument.getElementById('gotItButton').disabled = false;\n document.getElementById('nextButton').disabled = false;\t\n\t$('#guessedSwatches').html('');\t\n\tfinalScore = 0;\n\tscore = 0;\n\trandomColor();\t\n\tobj.Start();\n\tobj.Restart();\n}", "playButtonPressed() {\n this.setPropertyInputVisibility(false);\n this.playButton.visible = false;\n this.game.multiplayerHandler.sendStartMessage();\n }", "function buttonClickPlayerTwo() {\n if($(this).hasClass(\"correct\")){\n $(\".correct\").css(\"background-color\", \"#00FF00\");\n correctAudio.play();\n p2Score = p2Score + 10;\n $(\"#score2\").html(\"Score: \" + p2Score);\n }\n else if ($(this).hasClass(\"incorrect\")) {\n $(this).css(\"background-color\", \"#FF0000\");\n incorrectAudio.play();\n }\n $(answerBtns2).off(\"click\");\n }", "function createButtons() {\n document.getElementById('start-game').classList.add('invisible');\n document.getElementById('shuffle').classList.remove('invisible');\n document.getElementById('show-hide').classList.remove('invisible');\n}", "function start() {\n generalTime = new Date();\n createTextArray();\n document.getElementById(\"playButton\").addEventListener('click', buttonControl, false);\n\n}//end function start", "function initUI() {\n // Detach Stop and Stop Replay\n $stopButton.detach();\n $stopReplayButton.detach();\n // Append start and start replay\n $buttonContainer.append($startButton);\n $buttonContainer.append($startReplayButton);\n}", "processStartButton() {\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t\tthis.game.switchScreens('play');\n\t}", "function replayGame() {\n resetGame();\n togglePopup();\n }", "function init() {\n squares.forEach((q) => {\n q.innerText = \"\";\n q.addEventListener(\"click\", handleTurn);\n })\n win = null;\n moveCount = 0;\n render();\n}", "function init(){\n setupSquares();\n setupModeButtons();\n\n reset();\n}", "function init() {\n document\n .getElementById(\"game-photo-1\")\n .addEventListener(\"click\", playSound1);\n document\n .getElementById(\"game-photo-2\")\n .addEventListener(\"click\", playSound2);\n document\n .getElementById(\"game-photo-3\")\n .addEventListener(\"click\", playSound3);\n document\n .getElementById(\"game-photo-4\")\n .addEventListener(\"click\", playSound4);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by KotlinParserexplicitDelegation.
enterExplicitDelegation(ctx) { }
[ "enterParenthesizedType(ctx) {\n\t}", "enterOrdinaryCompilation(ctx) {\n\t}", "function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }", "enterExplicitConstructorInvocation(ctx) {\n\t}", "enterTypeArgumentList(ctx) {\n\t}", "enterNormalClassDeclaration(ctx) {\n\t}", "enterClassMemberDeclaration(ctx) {\n\t}", "function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}", "_generate(ast) {}", "_connectNodes() {\n // Connect start\n let startAstNode = this.#jp;\n if (startAstNode.instanceOf(\"function\")) {\n startAstNode = startAstNode.body;\n }\n\n if (!startAstNode.instanceOf(\"statement\")) {\n throw new Error(\n \"Not defined how to connect the Start node to an AST node of type \" +\n this.#jp.joinPointType\n );\n }\n\n let afterNode = this.#nodes.get(startAstNode.astId);\n\n // Add edge\n this.#addEdge(this.#startNode, afterNode, CfgEdgeType.UNCONDITIONAL);\n\n for (const astId of this.#nodes.keys()) {\n const node = this.#nodes.get(astId);\n\n // Only add connections for astIds of leader statements\n if (node.data().nodeStmt.astId !== astId) continue;\n\n const nodeType = node.data().type;\n\n if (nodeType === undefined) {\n throw new Error(\"Node type is undefined: \");\n //continue;\n }\n\n switch (nodeType) {\n case CfgNodeType.IF:\n this.#connectIfNode(node);\n break;\n case CfgNodeType.LOOP:\n this.#connectLoopNode(node);\n break;\n case CfgNodeType.COND:\n this.#connectCondNode(node);\n break;\n case CfgNodeType.BREAK:\n this.#connectBreakNode(node);\n break;\n case CfgNodeType.CONTINUE:\n this.#connectContinueNode(node);\n break;\n case CfgNodeType.SWITCH:\n this.#connectSwitchNode(node);\n break;\n case CfgNodeType.CASE:\n this.#connectCaseNode(node);\n break;\n case CfgNodeType.INIT:\n this.#connectInitNode(node);\n break;\n case CfgNodeType.STEP:\n this.#connectStepNode(node);\n break;\n case CfgNodeType.INST_LIST:\n this.#connectInstListNode(node);\n break;\n case CfgNodeType.RETURN:\n this.#connectReturnNode(node);\n break;\n case CfgNodeType.SCOPE:\n case CfgNodeType.THEN:\n case CfgNodeType.ELSE:\n this.#connectScopeNode(node);\n break;\n }\n }\n }", "enterConstructorDelegationCall(ctx) {\n\t}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }", "function isNodeEntering(state, interpreter) {\n var updateNeeded = false;\n\n function isSupportedFunctionCall(state) {\n // won't show stepping into and out of member methods (e.g array.slice)\n // because these are built-ins with black-boxed code.\n // User functions may also be object properties, but I am not considering\n // this for this exercise.\n return state.node.type === 'CallExpression' && !state.doneCallee_ && !(state.node.callee && state.node.callee.type === 'MemberExpression');\n }\n\n if (isSupportedFunctionCall(state)) {\n\n var enterNode = {\n name: state.node.callee.name || state.node.callee.id.name,\n parentNode: (0, _lodash.last)(scopeChain) || null,\n paramNames: [],\n interpreterComputedArgs: [],\n // variable information and warnings\n // populated once the interpreter\n // generates scope\n variablesDeclaredInScope: null,\n warningsInScope: new Set(),\n type: 'function',\n status: 'normal'\n };\n\n // set up string tokens for display text\n enterNode.recursion = enterNode.parentNode && enterNode.name === enterNode.parentNode.name;\n enterNode.displayTokens = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].getInitialDisplayTokens(enterNode.name, state.node.arguments, enterNode.parentNode, interpreter);\n enterNode.displayName = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].joinAndFormatDisplayTokens(enterNode.displayTokens, enterNode.recursion);\n\n // the root node carries through information to d3 about overall progress.\n if (nodes.length === 0) {\n enterNode.type = 'root';\n enterNode.errorCount = 0;\n enterNode.status = ''; //d3 manually assigns color to rootNode\n rootNode = enterNode;\n }\n\n // add nodes and links to d3\n nodes.push(enterNode);\n var callLink = getCallLink(enterNode.parentNode, enterNode, 'calling');\n if (callLink) {\n links.push(callLink);\n }\n\n /* Tracking by scope reference allows for\n displaying nested functions and recursion */\n scopeChain.push(enterNode);\n updateNeeded = true;\n }\n return updateNeeded;\n }", "generate_abstract_syntax_tree(cst) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Generating Abstract Syntax Tree...`));\n // Make new ast\n this._current_ast = new NightingaleCompiler.AbstractSyntaxTree();\n // Store scope tree in AST\n this._current_ast.scope_tree = this._current_scope_tree;\n // Get program number from CST\n this._current_ast.program = cst.program;\n // Begin adding nodes to the ast from the cst, filtering for the key elements\n this.add_subtree_to_ast(cst.root.children_nodes[0]);\n }", "enterAnnotationTypeMemberDeclaration(ctx) {\n\t}", "function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}", "enterTypeAlias(ctx) {\n\t}", "enterInheritanceModifier(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When you click down on the measurement handler
function measurement_handler(event){ pointer_select_handler(event); }
[ "mDown(e){\n this.xMouseStart=e.offsetX;\n this.yMouseStart=e.offsetY;\n if(this.insideButton){\n Button.shape=this.name;\n }\n }", "function onMouseDownEvent()\n{\n let clickedTime = calculateClickedTime();\n let minute = (30 * clock.indicators.m.angle) / (Math.PI + 15);\n let hour = (6 * clock.indicators.h.angle) / (Math.PI + 3);\n let threshold = 0.25;\n\n if((clickedTime[0] < minute + threshold) && (clickedTime[0] > minute - threshold))\n {\n clock.minuteTimeChanger.highlightIndicator('red'); // threshold makes it easier to click on hand \n return;\n } \n if((clickedTime[1] < hour + threshold) && (clickedTime[1] > hour - threshold)) \n clock.hourTimeChanger.highlightIndicator('red'); \n}", "function privateVolumeDownClickHandle(){\n\t\t/*\n\t\t\tThe volume range is from 0 to 1 for an audio element. We make this\n\t\t\ta base of 100 for ease of working with.\n\n\t\t\tIf the new value is less than 0, we use the new calculated\n\t\t\tvalue which gets converted to the proper unit for the audio element.\n\n\t\t\tIf the new value is greater than 0, we set the volume to 0 which\n\t\t\tis the min for the audio element.\n\t\t*/\n\t\tif( ( ( config.volume * 100 ) - config.volume_decrement ) > 0 ){\n\t\t\tconfig.volume = config.volume - ( config.volume_decrement / 100 );\n\t\t}else{\n\t\t\tconfig.volume = 0;\n\t\t}\n\t\t/*\n\t\t\tCalls the core function to set the volume to the computed value\n\t\t\tbased on the user's intent.\n\t\t*/\n\t\tprivateSetVolume( config.volume * 100 );\n\n\t\t/*\n\t\t\tSyncs the volume sliders so the visuals align up with the functionality.\n\t\t\tIf the volume is at 0, then the sliders should represent that so the user\n\t\t\thas the right starting point.\n\t\t*/\n\t\tprivateSyncVolumeSliders();\n\t}", "function autoClick () {\n calcWattsRate()\n\n watts += wattsPerSec\n draw()\n}", "_onTap(x,y){\n console.log('tap!', x, y)\n //save screen coordinates normalized to -1..1 (0,0 is at center and 1,1 is at top right)\n this._tapEventData = [\n x / window.innerWidth,\n y / window.innerHeight\n ]\n }", "function setDown() {\n mouseDown = true;\n}", "function klik(evt) { // mousedown on svg\n function x2time(x, line) {\n\n function isBigEnough(element) {\n return element >= x;\n }\n\n // Get the sfaff measure number from an X-value;\n var measure = bars[line].xs.findIndex(isBigEnough) - 1;\n var measure_width = bars[line].xs[measure + 1] - bars[line].xs[measure];\n\n console.log(\"X: \" + x + \" , \" + \"measure: \" + measure + \" width: \" + measure_width);\n\n }\n\n evt.preventDefault();\n evt.stopPropagation();\n var line = msc_svgs.get().indexOf(this); // index of the clicked svg\n var x = evt.clientX; // position click relative to page\n x -= $(this).position().left; // minus (position left edge if svg relative to page)\n x2time(x, line);\n}", "_onDayDblTap() {\n this.execute();\n }", "function mouseDown(e) {\n // Here we changing isMoving from false to true, and depicting that now we are moving the mouse over the wheel\n setMoving(true);\n }", "viewWasClicked (view) {\n\t\t\n\t}", "function clickOnPoint() {\n var x = 58,\n y = 275;\n _DygraphOps[\"default\"].dispatchMouseDown_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseMove_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseUp_Point(g, x, y);\n }", "function jsDblClick() {\n if (!clicked) {\n clicked = true;\n return true;\n }\n else {\n return false;\n }\n }", "function pressMod() {\n\thandleMulDivMod(MOD);\n}", "function volumeBarClickedDown(changeVolume) {\n volumeBarInterval = setInterval(changeVolume, 100);\n}", "function sketchpad_mouseDown() {\n mouseDown=1;\n drawDot(ctx,mouseX,mouseY,pencilThickness, currentColor);\n}", "function OnTimeMouseDown(){\n\n \tg_bTimeUpdate = false;\n}", "function pressDiv() {\n\thandleMulDivMod(DIV);\n}", "function pressMult() {\n\thandleMulDivMod(TIMES);\t\n}", "clickListener(e) {\n if (this.selectedMapCube !== null && this.selectedMapCube != this.selectedCube) {\n this.enhancedCubes = [];\n this.scaffoldingCubesCords = null;\n this.selectedCube = this.selectedMapCube;\n let directions = this.ref.methods.getDirections(this.selectedMapCube);\n // this.ref.updateRoom(this.selectedMapCube, directions);\n this.ref.room.navigateToRoom(this.selectedMapCube, directions, true);\n this.repaintMapCube(ref.cubes, \"\", [], null, false, this.selectedMapCube);\n //this.repaintMapCube(hoverCubeArr, this.selectedMapCube.label);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the detected facial feature points on the image
function drawFeaturePoints(img, featurePoints) { var contxt = $('#face_video_canvas')[0].getContext('2d'); var hRatio = contxt.canvas.width / img.width; var vRatio = contxt.canvas.height / img.height; var ratio = Math.min(hRatio, vRatio); contxt.strokeStyle = "#FFFFFF"; for (var id in featurePoints) { contxt.beginPath(); contxt.arc(featurePoints[id].x, featurePoints[id].y, 2, 0, 2 * Math.PI); contxt.stroke(); } }
[ "function drawFeaturePoints(canvas, img, face) {\n // Obtain a 2D context object to draw on the canvas\n var ctx = canvas.getContext('2d');\n \n ctx.fillStyle = '#13FC00';\n \n // Loop over each feature point in the face\n let ii = 0;\n ctx.font = '8px serif';\n for (var id in face.featurePoints) {\n ii++;\n var fp = face.featurePoints[id];\n ctx.fillText(ii, fp.x, fp.y);\n \n\t// ctx.beginPath();\n\t// ctx.arc(fp.x,fp.y,2,0,2*Math.PI);\n\t// ctx.stroke();\n }\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}", "function drawGlasses() {\n\tcopyCanvas();\n\tcomp = detectFaces();\n \n for (var i = 0; i < comp.length; i++) {\n con.drawImage(glasses, comp[i].x, comp[i].y,comp[i].width, comp[i].height);\n }\n}", "function fillFromPoint(canvas, p1, rI, gI, bI){\n console.log(canvas);\n var frontier = [];\n var width = canvas.width;\n var height = canvas.height;\n var context = canvas.getContext('2d');\n var imgData = context.getImageData(0, 0, width, height);\n var pos = (p1.y * width + p1.x) * 4;\n\n frontier.push(p1);\n\n var r = imgData.data[pos];\n var g = imgData.data[pos + 1];\n var b = imgData.data[pos + 2];\n\n if (rI == r && g == gI && b == bI){\n return;\n }\n\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n\n while (frontier.length){\n var point, left, right;\n point = frontier.pop();\n\n pos = (point.y * width + point.x) * 4;\n\n for (var i=0; i < neigh.length; i++){\n\n var tPosX = point.x + neigh[i][0];\n var tPosY = point.y + neigh[i][1];\n\n if (tPosX >= 0 && tPosX < width && tPosY >= 0 && tPosY < height){\n var tPos = ((tPosY * width + tPosX) * 4);\n\n if (imgData.data[tPos] == r && imgData.data[tPos + 1] == g && imgData.data[tPos + 2] == b){\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n frontier.push(new Point(tPosX, tPosY));\n }\n }\n }\n }\n context.putImageData(imgData,0,0 );\n}", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "drawFacing(context, actor){\n\t\tcontext.fillStyle = 'rgba('+(255-actor.cd)+',0,0,1)';\n\t\tcontext.beginPath(); \n\t\tcontext.arc(actor.fx + actor.x, actor.fy + actor.y, actor.r / 3, 0, 2 * Math.PI, false); \n\t\tcontext.fill(); \n\t}", "function display() {\r\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\r\n\r\n var eye = vec3(a * Math.sin(theta) * Math.cos(phi), //used for mouse rotation\r\n b * Math.sin(theta) * Math.sin(phi),\r\n c * Math.cos(theta));\r\n\r\n\tviewMatrixLoc = gl.getUniformLocation( programId, \"viewMatrix\" );\r\n\tviewMatrix = mult(transCamera, lookAt(eye, at, up));\r\n\tgl.uniformMatrix4fv( viewMatrixLoc, false, flatten(viewMatrix) );\r\n\t\r\n\t/////////////////////////////////////////////\r\n // TODO: Draw the superquadric, implement perspective projection\r\n /////////////////////////////////////////////\r\n\r\n\tgl.uniform4fv(color, flatten(getWireframeColor()));\r\n\t\r\n\tgl.drawArrays( gl.LINE_STRIP, 0, points.length);\r\n}", "function FunnyFace(x,y){\n stroke(300,300,0,200);\n fill(30,10,200,255);\n strokeWeight(5);\n rect(x, y, 20, 60);\n rect(x, y, 10, 30);\n\n strokeWeight(5);\n rect(x+20, y+0, 20, 20);\n rect(x+29, y+9, 2, 2);\n rect(x+8.5, y+42, 3, 8);\n ellipse(x+35,y+45, 30, 30);\n ellipse(x+35,y+45, 10, 10);\n}", "display() {\n this.draw(this.points.length);\n }", "function face() {\n noFill();\n stroke('white'); strokeWeight(10);\n var face = triangle(300, 100, 100, 500, 500, 500);\n var cheekl = ellipse(150, 400, 50, 10);\n var cheek2 = ellipse(450, 400, 50, 10);\n}", "function getfloodfill(e){ \r\n let coords = getMousePosition(canvas, e); \r\n col_num = parseInt(coords[1]);\r\n row_num = parseInt(coords[0]);\r\n var new_color = {r: 0x0, g: 0x0, b: 0x0, a: 0xff};\r\n var baseColor = getColorAtPixel(imageData,row_num,col_num);\r\n Stack.push([row_num, col_num]);\r\n while(Stack.length){\r\n floodfill(baseColor, new_color, row_num, col_num, numRows, numCols);\r\n let newPos = Stack.pop();\r\n row_num = newPos[0];\r\n col_num = newPos[1];\r\n }\r\n c.putImageData(imageData, 0, 0);\r\n \r\n}", "function drawFlakes()\n\t{\n\t\tctx.clearRect(0, 0, W, H);\n\t\tctx.fillStyle = \"white\";\n\t\tctx.beginPath();\n\t\tfor(var i = 0; i < mf; i++)\n\t\t{\n\t\t\tvar f = flakes[i];\n\t\t\tctx.moveTo(f.x, f.y);\n\t\t\tctx.arc(f.x, f.y, f.r, 0, Math.PI*2, true);\n\t\t}\n\t\tctx.fill();\n\t\tmoveFlakes();\n\t}", "function detectFeatures(frame, features, width, height) {\n // detect features for frame\n const tempFeatures = [];\n for (let i = 0; i < width * height; i++) {\n tempFeatures[i] = new jsfeat.keypoint_t();\n }\n const count = jsfeat.fast_corners.detect(frame.data[0], tempFeatures, 3);\n\n // add detected features to array\n for (let i = 0; i < count; i++) {\n features.push(tempFeatures[i].x);\n features.push(tempFeatures[i].y);\n }\n\n return count;\n}", "function render(){\n gl.clear( gl.COLOR_BUFFER_BIT );\n gl.drawArrays( gl.TRIANGLES, 0, points.length );\n}", "function draw_detector() {\n ctx.beginPath()\n ctx.strokeStyle = 'black'\n ctx.setLineDash([0, 0])\n ctx.rect(DIFF_PATTERN.x, DIFF_PATTERN.y, DIFF_PATTERN.width, DIFF_PATTERN.height)\n ctx.stroke()\n\n ctx.beginPath()\n ctx.arc(DIFF_PATTERN.x + (DIFF_PATTERN.width / 2), SECOND_XRAY_Y, 3, 0, 2 * Math.PI)\n ctx.fill()\n\n deltaPos = {\n x: passthroughCoords.x - refractedCoords.x,\n y: passthroughCoords.y - refractedCoords.y\n }\n\n ctx.beginPath()\n ctx.arc(DIFF_PATTERN.x + (DIFF_PATTERN.width / 2) - deltaPos.x, SECOND_XRAY_Y - deltaPos.y, 3, 0, 2 * Math.PI)\n\n //Arrow between origin spot and diffracted spot\n //canvas_arrow(ctx,DETECTOR_POSITION + (DETECTOR_WIDTH/2) - 2, SECOND_XRAY_Y - 2 , DETECTOR_POSITION + (DETECTOR_WIDTH/2) - deltaPos.x + 5, SECOND_XRAY_Y - deltaPos.y + 5)\n \n ctx.stroke()\n\n ctx.font = \"bold 16px Verdana\"\n ctx.fillText(\"Diffraction Pattern\", DIFF_PATTERN.x + (0.5 * DIFF_PATTERN.width) - 90, 50)\n \n }", "function getFacesFromLocations(img, rects, faceSize = 150) {\r\n const shapes = rects.map(rect => faceLandmarkPredictor.predict(img, rect))\r\n return fr.extractImageChips(img, fr.getFaceChipDetails(shapes, faceSize))\r\n }", "_renderFeauture(coordinates){\n _logger.info(_self._fileName, '_renderFeauture() coordinates()',{'coordinates':coordinates});\n try{\n if(_self.options.visited_spots_layer){\n if(typeof ol==\"undefined\" || !ol) return false;\n let newFeature = new ol.Feature(),\n featureGeom = null;\n if(geom_colors.visited_spots_shape===\"square\"){\n featureGeom = new ol.style.RegularShape({\n fill: new ol.style.Fill({color: geom_colors.visited_spots_fill_color}),\n stroke: new ol.style.Stroke({\n color: geom_colors.visited_spots_stroke_color,\n width: 1\n }),\n points: 4,\n radius: geom_colors.visited_spot_radius,\n angle: Math.PI / 4\n });\n }else{\n featureGeom = new ol.style.Circle({\n radius: geom_colors.visited_spot_radius,\n fill: new ol.style.Fill({color: geom_colors.visited_spots_fill_color}),\n stroke: new ol.style.Stroke({\n color: geom_colors.visited_spots_stroke_color,\n width: 1\n })\n });\n }\n\n newFeature.setStyle(new ol.style.Style({\n image: featureGeom\n })\n );\n newFeature.setGeometry(new ol.geom.Point(coordinates));\n if(offlineVisitSpotsSource){\n offlineVisitSpotsSource.addFeature(newFeature);\n }\n }\n return true;\n }catch(e){\n _logger.error(_self._fileName, '_renderFeauture()',e);\n return false;\n }\n }", "function Face() {\n\n // these are state variables for a face\n // (your variables may be different\n\n this.eyelid = 0;\n this.lipheight = 0;\n this.blackeye = 0;\n this.redeye = 0;\n this.wrinkles = 0;\n this.chin = 20;\n this.hairX = 0;\n this.hairY = 0;\n this.hairColour = [\"#090806\", \"#D6C4C2\", \"#E6CEA8\", \"#B55239\", \"#3B3024\", \"#A7856A\"];\n\n // Draw a face with position lists that include:\n // chin, right_eye, left_eye, right_eyebrow, left_eyebrow\n // bottom_lip, top_lip, nose_tip, nose_bridge, \n\nthis.draw = function(positions) {\n \n //average of eye points\n let pos_left = average_point(positions.left_eye)\n let pos_right = average_point(positions.right_eye)\n\n //face\n let pos_c1 = positions.chin[3];\n let pos_c2 = positions.chin[8];\n let pos_c3 = positions.chin[13];\n let pos_c4 = positions.chin[8];\n \n //face points\n let pos_p1 = positions.chin[0];\n let pos_p2 = positions.chin[16];\n let pos_p3 = positions.chin[11];\n let pos_p4 = positions.chin[5];\n\n //mouth curves\n let mouth_leftc = positions.top_lip[0];\n let mouth_topc = positions.top_lip[3];\n let mouth_rightc = positions.top_lip[6];\n let mouth_botc = positions.bottom_lip[9];\n\n //mouth points\n let mouth_left = positions.top_lip[0];\n let mouth_bot = positions.top_lip[3];\n let mouth_right = positions.top_lip[6];\n let mouth_top = positions.bottom_lip[9];\n\n //nose points\n let nose_top = positions.nose_bridge[0];\n let nose_mid = positions.nose_bridge[2];\n let nose_tip = positions.nose_tip[2];\n let nose_bot1 = positions.nose_tip[4];\n let nose_bot2 = positions.nose_tip[0];\n let nostril1 = positions.nose_tip[3];\n let nostril2 = positions.nose_tip[1];\n\n let nose_side = positions.nose_bridge[3];\n\n //cheekbones\n let cheekbones1 = positions.chin[1];\n let cheekbones2 = positions.chin[2];\n let cheekbones3 = positions.chin[3];\n\n let cheekbones4 = positions.chin[15];\n let cheekbones5 = positions.chin[14];\n let cheekbones6 = positions.chin[13];\n\n //forehead wrinkles\n let forehead1 = positions.left_eyebrow[0];\n let forehead2 = positions.left_eyebrow[2];\n let forehead3 = positions.nose_bridge[0];\n let forehead4 = positions.right_eyebrow[2];\n let forehead5 = positions.right_eyebrow[4];\n\n\n //face\n stroke(240);\n strokeWeight(.05);\n fill(240);\n\n //forehead\n curve(pos_c1[0], pos_c1[1]+15, pos_p1[0], pos_p1[1], pos_p2[0], pos_p2[1], pos_c2[0], pos_c2[1]+15);\n //cheeks\n curve(pos_c2[0]-2, pos_c2[1]-5, pos_p2[0], pos_p2[1], pos_p3[0], pos_p3[1], pos_c3[0]-2, pos_c3[1]+5);\n curve(pos_c4[0]+2, pos_c4[1]+5, pos_p4[0], pos_p4[1], pos_p1[0], pos_p1[1], pos_c1[0]+2, pos_c1[1]-5);\n //chin\n curve(pos_c3[0], pos_c3[1]-this.chin/2, pos_p3[0], pos_p3[1], pos_p4[0], pos_p4[1], pos_c4[0], pos_c4[1]-this.chin/2);\n\n //inner face\n fill(240);\n // strokeWeight(.03);\n // stroke(240);\n noStroke();\n beginShape();\n vertex(pos_p1[0]+0.03,pos_p1[1]-0.03);\n vertex(pos_p2[0]+0.03,pos_p2[1]-0.03);\n vertex(pos_p3[0]+0.03,pos_p3[1]+0.03);\n vertex(pos_p4[0]-0.03,pos_p4[1]+0.03);\n vertex(pos_p1[0]-0.03,pos_p1[1]+0.03);\n endShape();\n\n //cheekbones\n //doesn't draw them if the face is turned too far one way or the other\n stroke(190); \n strokeWeight(.05);\n noFill();\n\n if (nose_side[0] < 0.1 && -0.1) {\n\n beginShape();\n curveVertex(cheekbones1[0]+this.cb1, cheekbones1[1]);\n curveVertex(cheekbones1[0]+this.cb1, cheekbones1[1]);\n curveVertex(cheekbones2[0]+this.cb2, cheekbones2[1]);\n curveVertex(cheekbones3[0]+this.cb2, cheekbones3[1]);\n curveVertex(cheekbones3[0]+this.cb2, cheekbones3[1]);\n endShape();\n\n beginShape();\n curveVertex(cheekbones4[0]-this.cb1, cheekbones4[1]);\n curveVertex(cheekbones4[0]-this.cb1, cheekbones4[1]);\n curveVertex(cheekbones5[0]-this.cb2, cheekbones5[1]);\n curveVertex(cheekbones6[0]-this.cb2, cheekbones6[1]);\n curveVertex(cheekbones6[0]-this.cb2, cheekbones6[1]);\n endShape();\n }\n\n else if (nose_side[0] > 0.2) {\n\n beginShape();\n curveVertex(cheekbones1[0]+this.cb1, cheekbones1[1]);\n curveVertex(cheekbones1[0]+this.cb1, cheekbones1[1]);\n curveVertex(cheekbones2[0]+this.cb2, cheekbones2[1]);\n curveVertex(cheekbones3[0]+this.cb2, cheekbones3[1]);\n curveVertex(cheekbones3[0]+this.cb2, cheekbones3[1]);\n endShape();\n }\n\n else if (nose_side[0] > -0.2) {\n\n beginShape();\n curveVertex(cheekbones4[0]-this.cb1, cheekbones4[1]);\n curveVertex(cheekbones4[0]-this.cb1, cheekbones4[1]);\n curveVertex(cheekbones5[0]-this.cb2, cheekbones5[1]);\n curveVertex(cheekbones6[0]-this.cb2, cheekbones6[1]);\n curveVertex(cheekbones6[0]-this.cb2, cheekbones6[1]);\n endShape();\n }\n\n //mouth\n fill(255,190,190);\n //i can't remember why this stroke is 0,0 but it does something that fixes the mouth\n stroke(0,0);\n strokeWeight(25);\n curve(mouth_leftc[0], mouth_leftc[1]-this.lipheight/2, mouth_left[0], mouth_left[1], mouth_top[0], mouth_top[1], mouth_topc[0], mouth_topc[1]-this.lipheight/2);\n curve(mouth_topc[0], mouth_topc[1]-this.lipheight/2, mouth_top[0], mouth_top[1], mouth_right[0], mouth_right[1], mouth_rightc[0], mouth_rightc[1]-this.lipheight/2);\n curve(mouth_rightc[0], mouth_rightc[1]+this.lipheight, mouth_right[0], mouth_right[1], mouth_bot[0], mouth_bot[1], mouth_botc[0], mouth_botc[1]+this.lipheight);\n curve(mouth_botc[0], mouth_botc[1]+this.lipheight, mouth_bot[0], mouth_bot[1], mouth_left[0], mouth_left[1], mouth_leftc[0], mouth_leftc[1]+this.lipheight);\n\n //inner mouth\n fill(255,190,190);\n beginShape();\n vertex(mouth_left[0],mouth_left[1]);\n vertex(mouth_top[0],mouth_top[1]);\n vertex(mouth_right[0],mouth_right[1]);\n vertex(mouth_bot[0],mouth_bot[1]);\n endShape();\n\n //mouth hole\n fill(0);\n beginShape();\n vertex(mouth_left[0],mouth_left[1]);\n vertex(mouth_top[0],mouth_top[1]);\n vertex(mouth_right[0],mouth_right[1]);\n vertex(mouth_bot[0],mouth_bot[1]);\n endShape();\n\n //nose\n //moves the nose tip left or right depending on the nose position\n fill(240);\n stroke(0);\n strokeWeight(.08);\n\n if (nose_side[0] < 0) {\n beginShape();\n curveVertex(nose_top[0], nose_top[1]);\n curveVertex(nose_top[0], nose_top[1]);\n curveVertex(nose_mid[0], nose_mid[1]);\n curveVertex(nose_tip[0], nose_tip[1]);\n curveVertex(nose_bot1[0], nose_bot1[1]);\n curveVertex(nose_bot1[0], nose_bot1[1]);\n endShape();\n }\n\n else if (nose_side[0] > 0) {\n beginShape();\n curveVertex(nose_top[0], nose_top[1]);\n curveVertex(nose_top[0], nose_top[1]);\n curveVertex(nose_mid[0], nose_mid[1]);\n curveVertex(nose_tip[0], nose_tip[1]);\n curveVertex(nose_bot2[0], nose_bot2[1]);\n curveVertex(nose_bot2[0], nose_bot2[1]);\n endShape();\n }\n\n // eyes outer\n fill(0);\n noStroke();\n ellipse(pos_left[0], pos_left[1], 1*this.blackeye, 1*this.blackeye);\n ellipse(pos_right[0],pos_right[1], 1*this.blackeye, 1*this.blackeye);\n //eyes inner\n fill(255);\n ellipse(pos_left[0], pos_left[1], .70, .70);\n ellipse(pos_right[0],pos_right[1], .70, .70);\n\n //pupils\n fill(255,0,0);\n noStroke();\n ellipse(pos_left[0], pos_left[1], .15*this.redeye, .15*this.redeye);\n ellipse(pos_right[0],pos_right[1], .15*this.redeye, .15*this.redeye);\n\n\n //eyelids bottom\n if (this.eyelid == 0) {\n fill(100);\n stroke(100);\n strokeWeight(0.01);\n arc(pos_left[0], pos_left[1], .70, .70, 15, 165, CHORD);\n arc(pos_right[0],pos_right[1], .70, .70, 15, 165, CHORD);\n }\n\n //eyelids top\n else if (this.eyelid == 1) {\n fill(100);\n stroke(100);\n strokeWeight(0.01);\n arc(pos_left[0], pos_left[1], .70, .70, 200, -15, CHORD);\n arc(pos_right[0],pos_right[1], .70, .70, 200, -15, CHORD);\n }\n\n //hair\n push();\n fill(this.hairColour[this.hairColour_choice]);\n noStroke();\n scale(0.1,0.1);\n translate(this.hairX,this.hairY);\n push();\n translate(5,-15);\n\n //left hair\n beginShape();\n vertex(-6.5, -11);\n quadraticVertex(-0, -17 , -10, -19);\n quadraticVertex(-13, -20 , -16, -17);\n quadraticVertex(-20, -12 , -22, -17);\n quadraticVertex(-23, -6 , -12, -8);\n endShape();\n pop();\n\n //right hair\n push();\n translate(-5,-15);\n beginShape();\n vertex(6.5, -11 );\n quadraticVertex(0, -17 , 10, -19);\n quadraticVertex(13, -20 , 16, -17);\n quadraticVertex(21, -12 , 22, -17);\n quadraticVertex(23, -6 , 12, -8);\n \n endShape();\n pop();\n pop();\n\n //forehead line\n stroke(190); \n strokeWeight(.05);\n noFill();\n\n beginShape();\n curveVertex(forehead1[0], forehead1[1]-.4);\n curveVertex(forehead1[0], forehead1[1]-.4);\n curveVertex(forehead2[0], forehead2[1]-this.wrinkles);\n curveVertex(forehead3[0], forehead3[1]-.5);\n curveVertex(forehead3[0], forehead3[1]-.5);\n endShape();\n\n beginShape();\n curveVertex(forehead3[0], forehead3[1]-.5);\n curveVertex(forehead3[0], forehead3[1]-.5);\n curveVertex(forehead4[0], forehead4[1]-this.wrinkles);\n curveVertex(forehead5[0], forehead5[1]-.4);\n curveVertex(forehead5[0], forehead5[1]-.4);\n endShape();\n\n}\n\n /* set internal properties based on list numbers 0-100 */\n this.setProperties = function(settings) {\n\n this.eyelid = Math.floor(map(settings[0], 0, 100, 0, 1));\n this.lipheight = map(settings[1], 0, 100, .1, 3);\n this.blackeye = map(settings[2], 0, 100, 1, 1.5);\n this.redeye = map(settings[3], 0, 100, 1, 2);\n this.wrinkles = map(settings[4], 0, 100, 0.01, 0.7);\n this.chin = map(settings[5], 0, 100, 10, 30);\n this.hairX = map(settings[6], 0, 100, 0.5, -2);\n this.hairY = map(settings[7], 0, 100, 0.5, 8);\n this.cb1 = map(settings[8], 0, 100, 0, 0.5);\n this.cb2 = map(settings[9], 0, 100, .3, 0.6);\n this.hairColour_choice = Math.floor(map(settings[10],0,100,0,5));\n }\n\n /* get internal properties as list of numbers 0-100 */\n this.getProperties = function() {\n let settings = new Array(1);\n\n settings[0] = map(this.eyelid, 0, 1, 0, 100);\n settings[1] = map(this.lipheight, .1, 3, 0, 100);\n settings[2] = map(this.blackeye, 1, 1.5, 0, 100);\n settings[3] = map(this.redeye, 1, 2, 0, 100);\n settings[4] = map(this.wrinkles, 0.01, 0.7, 0, 100);\n settings[5] = map(this.chin, 10, 30, 0, 100);\n settings[6] = map(this.hairX, 0.5, -2, 0, 100);\n settings[7] = map(this.hairY, 0.5, 8, 0, 100);\n settings[8] = map(this.cb1, 0, 0.5, 0, 100);\n settings[9] = map(this.cb2, .3, 0.6, 0, 100);\n settings[10] = map(this.hairColour_choice,0,5,0,100);\n\n return settings;\n }\n}", "function drawEmoji(canvas, img, face) {\n // Obtain a 2D context object to draw on the canvas\n var ctx = canvas.getContext('2d');\n let fp_0 = face.featurePoints[0];\t\n let em = face.emojis.dominantEmoji;\n \n ctx.font = '48px serif';\n ctx.fillText(em, fp_0.x-70, fp_0.y);\n}", "function detectFaces(img, faceSize = 150) {\r\n return getFacesFromLocations(img, locateFaces(img).map(mmodRect => mmodRect.rect), faceSize)\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw Health Concerns Popup
function drawHealthConcernsPopup(panelId, risk, color, meaning, map_size) { var healthConcernsWrapper = document.getElementById('health_concerns_wrapper_' + panelId); var healthConcerns = document.querySelector('#health_concerns_wrapper_' + panelId + '>div'); var healthConcernsColor = document.querySelector('#health_concerns_wrapper_' + panelId + '>div>span>span.color'); var healthRisk = document.getElementById('health_risk_' + panelId); healthConcernsWrapper.style.display = 'block'; healthConcernsColor.style.backgroundColor = color; healthRisk.innerHTML = risk; }
[ "drawExtraUI() {\n // draw the button for canceling ability if an ability is being used if it has not been used partly\n if (this.situation === \"ability\") {\n if (currentAbility.currentStep === 1) {\n push();\n rectMode(CENTER);\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver === \"cancel\") {\n fill(0);\n } else {\n fill(255,50,0);\n }\n rect(width-width/10, height/2, width/10, height/15);\n // if moused over, it is highlighted\n if (mouseOver === \"cancel\") {\n fill(255, 0, 0);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/120+height/120);\n text(\"Cancel Ability\", width-width/10, height/2);\n pop();\n }\n }\n // draw the button to go to the fight mode\n if (this.situation === \"choose\") {\n push();\n rectMode(CENTER);\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver === \"fight\") {\n fill(0);\n } else {\n fill(255,255,0);\n }\n rect(width-width/10, height/2, width/10, height/15);\n // if moused over, it is highlighted\n if (mouseOver === \"fight\") {\n fill(255, 255, 0);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/80+height/50);\n text(\"Fight!\", width-width/10, height/2);\n pop();\n }\n }", "drawHealth() {\n document.querySelector(\".monster-health__remain\").style.width =\n (this.health / this.startHealth) * 100 + \"%\";\n document.querySelector(\n \".monster-health__remain\"\n ).innerHTML = this.health;\n }", "function showAssessmentsPopup( aLength) {\n \n\t\t\tself.selectedAnotations([]);\n\t\t\t//$('.popup').ojPopup('close');\n\t\t\t// Popup1 or popup2 if there are any assessments\n\t\t\t\n \n\t\t\t\t\tdocument.getElementById('popup1').style.display = 'flex';\n document.getElementById('selection-context').style.display = 'block';\n\t\t\t\t\n \n\t\t\t}", "drawPopUpTexts(){\n\t\tlet popUpshortInfoText = new InfoText(\"popup\", \"pageDescriptionPopup\", infoTextsNamespace.shortPageDescription.popupInfo);\n\t\tpopUpshortInfoText.appendThisCharToPage();\n\t\tpopUpshortInfoText.drawInfoText();\n\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.popupPage;\n\t}", "function CtrlStatisticPopup() {\n clickedElement = event.target;\n clickedElementId = clickedElement.id;\n\n //if one of the statistic paragraphs are clicked ,inside of the StatistikPopup, is clicked then we open the FillRandomlyPopup\n if(clickedElement.classList.contains(DOMStrings.statisticButton)) {\n UICtrl.closePopup();\n setTimeout(function(){ UICtrl.openFillRandomlyPopup();}, 200); //you need to wait till the previous popup is closed.\n }\n }", "function createLockLevelPopUp(){\n\t\t\t\t\t\t\tvar levelChoose=new lib.levelChooseBoard();\n\t\t\t\t\t\t\tlevelChoose.x=myStage/2-levelChoose.nominalBounds.width/2;\n\t\t\t\t\t\t\tlevelChoose.y=myStage/2-levelChoose.nominalBounds.height/2;\n\t\t\t\t\t\t\tstage.addChild(levelChoose);\n\t\t\t\t\t\t}", "function drawPausePopup(){\n ctx.fillStyle = menu.background.color;\n ctx.fillRect(gameWindow.x,gameWindow.y,200,70);\n\n ctx.strokeStyle = menu.borderColor;\n ctx.lineWidth = menu.borderWidth;\n ctx.strokeRect(gameWindow.x,gameWindow.y,200,70);\n\n var pauseText = new Text(gameWindow.x+20,gameWindow.y+50,\"Paused\",-1,\"black\",50);\n pauseText.paint();\n}", "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 showHealth(player, el) {\n\tvar percent = (player.health * 10) + \"%\"\n\t$(el).children(\".health-bar\").css(\"width\", percent);\n\tconsole.log(\"Health has been updated\");\n}", "decribe() {\n return .innerText = `Shape Name: ${targetName}`;\n shapePanel.innerText = `Width: ${targetWidth}`;\n shapePanel.innerText = `Height: ${targetHeight}`;\n shapePanel.innerText = `Radius: ${targetRadius}`;\n shapePanel.innerText = `Area: ${targetRadius}`;\n shapePanel.innerText = `Perimeter: ${targetPerimeter}`;\n shapePanel.style.color = \"black\";\n //Makes the container visible\n shapePanel.innerText.style.visibility = \"visible\";\n }", "function displayHeartRate(hr)\n{\n document.getElementById(\"mood-hr-main\").text = \" \" + hr + \"hr \";\n}", "drawBoss() {\n ctx.drawImage(this.boss,\n 0, 0, this.boss.width, this.boss.height,\n this.x_boss_pos, this.y_icon_pos,\n icon_width, icon_height);\n \n // Health outer\n ctx.strokeStyle = \"black\";\n ctx.strokeRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, icon_width + 100, 25);\n\n // Health drawing\n ctx.fillStyle = \"red\";\n ctx.fillRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, this.health, 25);\n\n ctx.fillStyle = \"black\";\n ctx.font = '20px Arial';\n ctx.fillText(\"Health: \" + this.health, this.x_boss_pos - 150 - 100, this.y_icon_pos + icon_height + 25);\n }", "checkBetLinesShow () {\n if (this.getService(\"LinesService\").getWinLines().length > 0){\n linesManager.disableMouseOverForLabels();\n } else {\n linesManager.enableMouseOverForLabels();\n }\n }", "function drawTrafficFlowPopup(panelId) {\n document.getElementById('traffic_table_' + panelId).style.display = 'block';\n}", "function showMoodLevel() {\n\t\tvar positiveOrNegative = moodLevel > 0 ? 1 : -1;\n\t\tvar startingColor = 242;\n\t\tvar blueStep = 242 / 100;\n\t\tvar redStep = moodLevel > 0 ? 242 / 100 : 142 / 100;\n\t\tvar greenStep = moodLevel < 0 ? 242 / 100 : 142 / 100;\n\n\t\tvar newRed = startingColor - redStep * moodLevel * positiveOrNegative;\n\t\tvar newGreen = startingColor - greenStep * moodLevel * positiveOrNegative;\n\t\tvar newBlue = startingColor - blueStep * moodLevel * positiveOrNegative;\n\n\t\ttextField.style.background = \"rgb(\" + newRed + \", \" + newGreen + \", \" + newBlue + \")\";\n\t}", "drawPlayerMenu() {\n if (currentChar != \"none\") {\n push();\n // 2 supporting skills\n for (let i = 0; i < currentChar.abilities[0].length; i++) {\n strokeWeight(3);\n stroke(0);\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(0);\n } else {\n fill(255);\n }\n rectMode(CORNER);\n rect(width/7+(i*width/3.5), height-height/4.5, width/4, height/6);\n // name, cost and ability\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(255);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/80+height/80);\n text(currentChar.abilities[0][i].name, width/3.75+(i*width/3.5), height-height/6);\n let abilityCostText = \"Cost: \" + currentChar.abilities[0][i].cost + \" Energy\";\n text(abilityCostText, width/3.75+(i*width/3.5), height-height/8);\n textSize(width/150+height/150);\n text(currentChar.abilities[0][i].description, width/3.75+(i*width/3.5), height-height/12);\n // if this is an ultimate, then let the player know\n if (currentChar.abilities[0][i].ultimate === true) {\n textSize(width/100+height/100);\n if (currentChar.ultCharge === 100) {\n fill(0, 255, 0);\n text(\"Ultimate Ready!\", width/3.75+(i*width/3.5), height-height/5);\n } else {\n fill(255, 0, 0);\n text(\"Ultimate Charging\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n // if this non-ultimate ability has been used this turn and cannot be used again\n if (currentChar.abilities[0][i].used === true && currentChar.abilities[0][i].ultimate === false) {\n textSize(width/100+height/100);\n fill(255, 0, 0);\n text(\"Used This Turn\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n pop();\n }\n }", "function drawToolbar(wcoef, hcoef) {\n \"use strict\";\n \n var concept = sys.concepts[sys.c_index];\n var p = sys.p;\n \n // Toolbar bounding box\n concept.toolbar.toolbar_rect.attr(\"x\", -2);\n concept.toolbar.toolbar_rect.attr(\"y\", -2);\n concept.toolbar.toolbar_rect.attr(\"width\", document.getElementById(\"conceptor-layer\").offsetWidth / 5);\n concept.toolbar.toolbar_rect.attr(\"height\", window.innerHeight - 146);\n concept.toolbar.toolbar_rect.attr(\"stroke-width\", 2);\n \n // Help tool\n concept.toolbar.helptool.ht_circle.attr(\"cx\", 30 * wcoef);\n concept.toolbar.helptool.ht_circle.attr(\"cy\", 30 * hcoef);\n concept.toolbar.helptool.ht_circle.attr(\"rx\", 15 * wcoef);\n concept.toolbar.helptool.ht_circle.attr(\"ry\", 15 * hcoef);\n concept.toolbar.helptool.ht_circle.attr(\"stroke-width\", 2);\n concept.toolbar.helptool.ht_dot.attr(\"cx\", 30 * wcoef);\n concept.toolbar.helptool.ht_dot.attr(\"cy\", 40 * hcoef);\n concept.toolbar.helptool.ht_dot.attr(\"r\", 1);\n concept.toolbar.helptool.ht_dot.attr(\"stroke-width\", 4);\n concept.toolbar.helptool.ht_qmark.attr(\"path\", \"M\" + (30 * wcoef) + \",\" + (30 * hcoef + 5 * wcoef) + \"l0,-\" + (5 * hcoef) + \"S\" + (30 * wcoef) + \",\" + (30 * hcoef) + \",\" + (32 * wcoef) + \",\" + (30 * hcoef) + \"c\" + (10 * wcoef) + \",0,\" + (10 * wcoef) + \",-\" + (10 * hcoef) + \",-\" + (5 * wcoef) + \",-\" + (10 * hcoef));\n concept.toolbar.helptool.ht_qmark.attr(\"stroke-width\", 2);\n if (concept.toolbar.helptool.hover || concept.toolbar.helptool.chosen) {\n concept.toolbar.helptool.ht_circle.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.helptool.ht_circle.attr(\"fill\", \"white\");\n }\n \n \n // Tool selector\n concept.toolbar.tools.bbox.attr(\"x\", 2 * wcoef);\n concept.toolbar.tools.bbox.attr(\"y\", 50 * hcoef);\n concept.toolbar.tools.bbox.attr(\"height\", 250 * hcoef);\n concept.toolbar.tools.bbox.attr(\"width\", 195 * wcoef);\n concept.toolbar.tools.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.tools.bbox.attr(\"r\", 2);\n concept.toolbar.tools.bbox.attr(\"fill\", \"white\");\n \n // Tool selector drop down list options\n var x = 0;\n for (x; x < 5; x += 1) {\n concept.toolbar.tools.options[x].opbox.attr(\"x\", 2 * wcoef);\n concept.toolbar.tools.options[x].opbox.attr(\"y\", (50 + x * 50) * hcoef);\n concept.toolbar.tools.options[x].opbox.attr(\"width\", 195 * wcoef);\n concept.toolbar.tools.options[x].opbox.attr(\"height\", 50 * hcoef);\n concept.toolbar.tools.options[x].opbox.attr(\"fill\", \"grey\");\n if (concept.toolbar.tools.options[x].chosen || concept.toolbar.tools.options[x].hover) {\n concept.toolbar.tools.options[x].opbox.attr(\"fill-opacity\", 0.25);\n } else {\n concept.toolbar.tools.options[x].opbox.attr(\"fill-opacity\", 0);\n }\n \n concept.toolbar.tools.options[x].optext.attr(\"x\", 122 * wcoef);\n concept.toolbar.tools.options[x].optext.attr(\"y\", (75 + x * 50) * hcoef);\n concept.toolbar.tools.options[x].optext.attr(\"font-size\", 12);\n concept.toolbar.tools.options[x].icon.attr(\"stroke-width\", 2);\n }\n \n // Make icons and texts\n concept.toolbar.tools.options[0].icon.attr(\"path\", \"M\" + (27 * wcoef) + \",\" + (60 * hcoef) + \"c\" + (-20 * wcoef) + \",0,\" + (-20 * wcoef) + \",\" + (30 * hcoef) + \",\" + (-5 * wcoef) + \",\" + (30 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (-4 * hcoef) + \"m\" + (3 * wcoef) + \",\" + (4 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (3 * hcoef) + \"m\" + (3 * wcoef) + \",\" + (-3 * hcoef) + \"m\" + (5 * wcoef) + \",0c\" + (20 * wcoef) + \",0,\" + (20 * wcoef) + \",\" + (-30 * hcoef) + \",\" + (5 * wcoef) + \",\" + (-30 * hcoef) + \"l\" + (3 * wcoef) + \",\" + (4 * hcoef) + \"m\" + (-3 * wcoef) + \",\" + (-4 * hcoef) + \"l\" + (4 * wcoef) + \",\" + (-2 * hcoef));\n concept.toolbar.tools.options[0].optext.attr(\"text\", \"Rotate:\\npress 'r' then\\n't' or 'e'\");\n \n concept.toolbar.tools.options[1].icon.attr(\"path\", \"M\" + (12 * wcoef) + \",\" + (140 * hcoef) + \"l0,\" + (-30 * hcoef) + \"l\" + (3 * wcoef) + \",\" + (3 * hcoef) + \"m\" + (-3 * wcoef) + \",\" + (-3 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (3 * hcoef) + \"M\" + (12 * wcoef) + \",\" + (140 * hcoef) + \"l\" + (30 * wcoef) + \",0l\" + (-3 * wcoef) + \",\" + (-3 * hcoef) + \"m\" + (3 * wcoef) + \",\" + (3 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (3 * hcoef));\n concept.toolbar.tools.options[1].optext.attr(\"text\", \"Resize:\\npress '=' or '-'\\n(+ is =)\");\n \n concept.toolbar.tools.options[2].icon.attr(\"path\", \"M\" + (12 + wcoef) + \",\" + (190 * hcoef) + \"l\" + (5 * wcoef) + \",0l0,\" + (-30 * hcoef) + \"l\" + (-5 * wcoef) + \",0m\" + (5 * wcoef) + \",\" + (15 * hcoef) + \"l\" + (20 * wcoef) + \",0m\" + (5 * wcoef) + \",\" + (15 * hcoef) + \"l\" + (-5 * wcoef) + \",0l0,\" + (-30 * hcoef) + \"l\" + (5 * wcoef) + \",0\");\n concept.toolbar.tools.options[2].optext.attr(\"text\", \"Link:\\nclick two\\nobjects\");\n \n concept.toolbar.tools.options[3].icon.attr(\"path\", \"M\" + (25 * wcoef) + \",\" + (225 * hcoef) + \"l\" + (-15 * wcoef) + \",\" + (-15 * hcoef) + \"l\" + (5 * wcoef) + \",0m\" + (-5 * wcoef) + \",0l0,\" + (5 * hcoef) + \"M\" + (25 * wcoef) + \",\" + (225 * hcoef) + \"l\" + (-15 * wcoef) + \",\" + (15 * hcoef) + \"l\" + (5 * wcoef) + \",0m\" + (-5 * wcoef) + \",0l0,\" + (-5 * hcoef) + \"M\" + (25 * wcoef) + \",\" + (225 * hcoef) + \"l\" + (15 * wcoef) + \",\" + (-15 * hcoef) + \"l\" + (-5 * wcoef) + \",0m\" + (5 * wcoef) + \",0l0,\" + (5 * hcoef) + \"M\" + (25 * wcoef) + \",\" + (225 * hcoef) + \"l\" + (15 * wcoef) + \",\" + (15 * hcoef) + \"l\" + (-5 * wcoef) + \",0m\" + (5 * wcoef) + \",0l0,\" + (-5 * hcoef));\n concept.toolbar.tools.options[3].optext.attr(\"text\", \"Zoom:\\nuse mouse\\nwheel\");\n \n concept.toolbar.tools.options[4].icon.attr(\"path\", \"M\" + (20 * wcoef) + \",\" + (275 * hcoef) + \"m\" + (-10 * wcoef) + \",0l\" + (10 * wcoef) + \",0l\" + (-3 * wcoef) + \",\" + (-3 * hcoef) + \"m0,\" + (6 * hcoef) + \"l\" + (3 * wcoef) + \",\" + (-3 * hcoef) + \"c0,\" + (15 * hcoef) + \",\" + (20 * wcoef) + \",\" + (15 * hcoef) + \",\" + (20 * wcoef) + \",0c0,\" + (-15 * hcoef) + \",\" + (-20 * wcoef) + \",\" + (-15 * hcoef) + \",\" + (-20 * wcoef) + \",0z\");\n concept.toolbar.tools.options[4].icon.attr(\"fill\", concept.toolbar.color_sltr.color);\n concept.toolbar.tools.options[4].optext.attr(\"text\", \"Recolor:\\nchoose new \\ncolor first\");\n \n // Color Selector\n concept.toolbar.color_sltr.bbox.attr(\"x\", 90 * wcoef);\n concept.toolbar.color_sltr.bbox.attr(\"y\", 15 * hcoef);\n concept.toolbar.color_sltr.bbox.attr(\"width\", 80 * wcoef);\n concept.toolbar.color_sltr.bbox.attr(\"height\", 30 * hcoef);\n concept.toolbar.color_sltr.bbox.attr(\"r\", 2);\n concept.toolbar.color_sltr.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.color_sltr.bbox.attr(\"fill\", concept.toolbar.color_sltr.color);\n concept.toolbar.color_sltr.dropbox.attr(\"x\", 154 * wcoef);\n concept.toolbar.color_sltr.dropbox.attr(\"y\", 15 * hcoef);\n concept.toolbar.color_sltr.dropbox.attr(\"width\", 16 * wcoef);\n concept.toolbar.color_sltr.dropbox.attr(\"height\", 30 * hcoef);\n concept.toolbar.color_sltr.dropbox.attr(\"r\", 2);\n concept.toolbar.color_sltr.dropbox.attr(\"stroke-width\", 2);\n if (concept.toolbar.color_sltr.hover) {\n concept.toolbar.color_sltr.dropbox.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.color_sltr.dropbox.attr(\"fill\", \"white\");\n }\n concept.toolbar.color_sltr.arrow.attr(\"path\", \"M\" + (156 * wcoef) + \",\" + (26 * hcoef) + \"l\" + (12 * wcoef) + \",0l\" + (-6 * wcoef) + \",\" + (12 * hcoef) + \"l\" + (-6 * wcoef) + \",\" + (-12 * hcoef) + \"z\");\n concept.toolbar.color_sltr.arrow.attr(\"fill\", \"black\");\n \n concept.toolbar.color_sltr.droplist.attr(\"x\", 0);\n concept.toolbar.color_sltr.droplist.attr(\"y\", 40 * hcoef);\n concept.toolbar.color_sltr.droplist.attr(\"width\", 200 * wcoef);\n concept.toolbar.color_sltr.droplist.attr(\"height\", 80 * hcoef);\n concept.toolbar.color_sltr.droplist.attr(\"fill-opacity\", 0);\n concept.toolbar.color_sltr.droplist.attr(\"stroke-opacity\", 0);\n \n concept.toolbar.color_sltr.droplistbkg.attr(\"x\", 2 * wcoef);\n concept.toolbar.color_sltr.droplistbkg.attr(\"y\", 45 * hcoef);\n concept.toolbar.color_sltr.droplistbkg.attr(\"width\", 194 * wcoef);\n concept.toolbar.color_sltr.droplistbkg.attr(\"height\", 70 * hcoef);\n concept.toolbar.color_sltr.droplistbkg.attr(\"r\", 2);\n concept.toolbar.color_sltr.droplistbkg.attr(\"stroke-width\", 2);\n concept.toolbar.color_sltr.droplistbkg.attr(\"fill\", \"black\");\n \n // Make color boxes\n x = 0;\n for (x; x < 6; x += 1) {\n concept.toolbar.color_sltr.options[x].opbox.attr(\"x\", (2 + x * 32) * wcoef);\n concept.toolbar.color_sltr.options[x].opbox.attr(\"y\", 45 * hcoef);\n concept.toolbar.color_sltr.options[x].opbox.attr(\"width\", 32 * wcoef);\n concept.toolbar.color_sltr.options[x].opbox.attr(\"height\", 70 * hcoef);\n concept.toolbar.color_sltr.options[x].opbox.attr(\"stroke-width\", 2);\n concept.toolbar.color_sltr.options[x].opbox.attr(\"fill\", concept.toolbar.color_sltr.options[x].color);\n if (concept.toolbar.color_sltr.options[x].chosen || concept.toolbar.color_sltr.options[x].hover) {\n concept.toolbar.color_sltr.options[x].opbox.attr(\"fill-opacity\", 0.5);\n } else {\n concept.toolbar.color_sltr.options[x].opbox.attr(\"fill-opacity\", 1);\n }\n }\n \n // If color selector window is open\n if (concept.toolbar.color_sltr.open) {\n concept.toolbar.color_sltr.opset.show();\n } else {\n concept.toolbar.color_sltr.opset.hide();\n }\n \n // Draw Text Tool\n if (!concept.toolbar.text.chosen) {\n concept.toolbar.text.bbox.attr(\"x\", 17 * wcoef);\n concept.toolbar.text.bbox.attr(\"y\", 320 * hcoef);\n concept.toolbar.text.bbox.attr(\"width\", 164 * wcoef);\n concept.toolbar.text.bbox.attr(\"height\", 40 * hcoef);\n concept.toolbar.text.bbox.attr(\"r\", 2);\n concept.toolbar.text.bbox.attr(\"stroke\", concept.toolbar.color_sltr.color);\n concept.toolbar.text.text.attr(\"x\", 99 * wcoef);\n concept.toolbar.text.text.attr(\"y\", 340 * hcoef);\n concept.toolbar.text.text.attr(\"text\", \"Write your custom\\ntext here\");\n concept.toolbar.text.text.attr(\"font-size\", 26 * wcoef * hcoef * 0.5);\n concept.toolbar.text.text.attr(\"font-weight\", 1);\n concept.toolbar.text.bbox.attr(\"fill\", \"white\");\n }\n \n \n // Draw Object Tabs\n // Draw bboxes first because they are similar\n concept.toolbar.obj_sltr.objecttab.bbox.attr(\"path\", \"M\" + (wcoef) + \",\" + (380 * hcoef) + \"l\" + (44 * wcoef) + \",0l0,\" + (15 * hcoef) + \"l\" + (150 * wcoef) + \",0l0,\" + (200 * hcoef) + \"l\" + (-194 * wcoef) + \",0l0,\" + (-215 * hcoef));\n concept.toolbar.obj_sltr.objecttab.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.obj_sltr.objecttab.bbox.attr(\"fill\", \"white\");\n concept.toolbar.obj_sltr.objecttab.bbox.attr(\"title\", \"Object\");\n concept.toolbar.obj_sltr.picstab.bbox.attr(\"path\", \"M\" + (51 * wcoef) + \",\" + (380 * hcoef) + \"l\" + (44 * wcoef) + \",0l0,\" + (15 * hcoef) + \"l\" + (100 * wcoef) + \",0l0,\" + (200 * hcoef) + \"l\" + (-194 * wcoef) + \",0l0,\" + (-200 * hcoef) + \"l\" + (50 * wcoef) + \",0l0,\" + (-15 * hcoef));\n concept.toolbar.obj_sltr.picstab.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.obj_sltr.picstab.bbox.attr(\"fill\", \"white\");\n concept.toolbar.obj_sltr.picstab.bbox.attr(\"title\", \"Picture\");\n concept.toolbar.obj_sltr.containertab.bbox.attr(\"path\", \"M\" + (101 * wcoef) + \",\" + (380 * hcoef) + \"l\" + (44 * wcoef) + \",0l0,\" + (15 * hcoef) + \"l\" + (50 * wcoef) + \",0l0,\" + (200 * hcoef) + \"l\" + (-194 * wcoef) + \",0l0,\" + (-200 * hcoef) + \"l\" + (100 * wcoef) + \",0l0,\" + (-15 * hcoef));\n concept.toolbar.obj_sltr.containertab.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.obj_sltr.containertab.bbox.attr(\"fill\", \"white\");\n concept.toolbar.obj_sltr.containertab.bbox.attr(\"title\", \"Container\");\n concept.toolbar.obj_sltr.viewtab.bbox.attr(\"path\", \"M\" + (151 * wcoef) + \",\" + (380 * hcoef) + \"l\" + (44 * wcoef) + \",0l0,\" + (15 * hcoef) + \"l0,\" + (200 * hcoef) + \"l\" + (-194 * wcoef) + \",0l0,\" + (-200 * hcoef) + \"l\" + (150 * wcoef) + \",0l0,\" + (-15 * hcoef));\n concept.toolbar.obj_sltr.viewtab.bbox.attr(\"stroke-width\", 2);\n concept.toolbar.obj_sltr.viewtab.bbox.attr(\"fill\", \"white\");\n concept.toolbar.obj_sltr.viewtab.bbox.attr(\"title\", \"View\");\n \n // Draw the Text\n concept.toolbar.obj_sltr.objecttab.text.attr(\"text\", \"Obj\");\n concept.toolbar.obj_sltr.objecttab.text.attr(\"font-size\", 12);\n concept.toolbar.obj_sltr.objecttab.text.attr(\"x\", 23 * wcoef);\n concept.toolbar.obj_sltr.objecttab.text.attr(\"y\", 387 * hcoef);\n concept.toolbar.obj_sltr.objecttab.text.attr(\"title\", \"Object\");\n if (concept.toolbar.obj_sltr.objecttab.hover) {\n concept.toolbar.obj_sltr.objecttab.text.attr(\"font-weight\", 2);\n } else {\n concept.toolbar.obj_sltr.objecttab.text.attr(\"font-weight\", 1);\n }\n concept.toolbar.obj_sltr.picstab.text.attr(\"text\", \"Pic\");\n concept.toolbar.obj_sltr.picstab.text.attr(\"font-size\", 12);\n concept.toolbar.obj_sltr.picstab.text.attr(\"x\", 73 * wcoef);\n concept.toolbar.obj_sltr.picstab.text.attr(\"y\", 387 * hcoef);\n concept.toolbar.obj_sltr.picstab.text.attr(\"title\", \"Picture\");\n if (concept.toolbar.obj_sltr.picstab.hover) {\n concept.toolbar.obj_sltr.pictab.text.attr(\"font-weight\", 2);\n } else {\n concept.toolbar.obj_sltr.picstab.text.attr(\"font-weight\", 1);\n }\n concept.toolbar.obj_sltr.containertab.text.attr(\"text\", \"Cont\");\n concept.toolbar.obj_sltr.containertab.text.attr(\"font-size\", 12);\n concept.toolbar.obj_sltr.containertab.text.attr(\"x\", 123 * wcoef);\n concept.toolbar.obj_sltr.containertab.text.attr(\"y\", 387 * hcoef);\n concept.toolbar.obj_sltr.containertab.text.attr(\"title\", \"Container\");\n if (concept.toolbar.obj_sltr.containertab.hover) {\n concept.toolbar.obj_sltr.containertab.text.attr(\"font-weight\", 2);\n } else {\n concept.toolbar.obj_sltr.containertab.text.attr(\"font-weight\", 1);\n }\n concept.toolbar.obj_sltr.viewtab.text.attr(\"text\", \"View\");\n concept.toolbar.obj_sltr.viewtab.text.attr(\"font-size\", 12);\n concept.toolbar.obj_sltr.viewtab.text.attr(\"x\", 173 * wcoef);\n concept.toolbar.obj_sltr.viewtab.text.attr(\"y\", 387 * hcoef);\n concept.toolbar.obj_sltr.viewtab.text.attr(\"title\", \"View\");\n if (concept.toolbar.obj_sltr.viewtab.hover) {\n concept.toolbar.obj_sltr.viewtab.text.attr(\"font-weight\", 2);\n } else {\n concept.toolbar.obj_sltr.viewtab.text.attr(\"font-weight\", 1);\n }\n \n // Draw the Scrollbar\n var scroll_arr = [concept.toolbar.obj_sltr.objecttab.scrollbar, concept.toolbar.obj_sltr.picstab.scrollbar, concept.toolbar.obj_sltr.containertab.scrollbar, concept.toolbar.obj_sltr.viewtab.scrollbar];\n for (x = 0; x < 4; x += 1) {\n scroll_arr[x].bbox.attr(\"x\", 185 * wcoef);\n scroll_arr[x].bbox.attr(\"y\", 400 * hcoef);\n scroll_arr[x].bbox.attr(\"width\", 10 * wcoef);\n scroll_arr[x].bbox.attr(\"height\", 190 * hcoef);\n scroll_arr[x].bbox.attr(\"r\", 1);\n \n scroll_arr[x].upbox.attr(\"x\", 185 * wcoef);\n scroll_arr[x].upbox.attr(\"y\", 400 * hcoef);\n scroll_arr[x].upbox.attr(\"width\", 10 * wcoef);\n scroll_arr[x].upbox.attr(\"height\", 15 * hcoef);\n scroll_arr[x].upbox.attr(\"r\", 1);\n if (scroll_arr[x].updarken) {\n scroll_arr[x].upbox.attr(\"fill\", \"grey\");\n } else {\n scroll_arr[x].upbox.attr(\"fill\", \"white\");\n }\n \n scroll_arr[x].downbox.attr(\"x\", 185 * wcoef);\n scroll_arr[x].downbox.attr(\"y\", 575 * hcoef);\n scroll_arr[x].downbox.attr(\"width\", 10 * wcoef);\n scroll_arr[x].downbox.attr(\"height\", 15 * hcoef);\n scroll_arr[x].downbox.attr(\"r\", 1);\n if (scroll_arr[x].downdarken) {\n scroll_arr[x].downbox.attr(\"fill\", \"grey\");\n } else {\n scroll_arr[x].downbox.attr(\"fill\", \"white\");\n }\n \n scroll_arr[x].uparrow.attr(\"path\", \"M\" + (190 * wcoef) + \",\" + (413 * hcoef) + \"l0,\" + (-10 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (3 * hcoef) + \"m\" + (6 * wcoef) + \",0l\" + (-3 * wcoef) + \",\" + (-3 * hcoef));\n scroll_arr[x].uparrow.attr(\"stroke-width\", 2);\n \n scroll_arr[x].downarrow.attr(\"path\", \"M\" + (190 * wcoef) + \",\" + (577 * hcoef) + \"l0,\" + (10 * hcoef) + \"l\" + (-3 * wcoef) + \",\" + (-3 * hcoef) + \"m\" + (6 * wcoef) + \",0l\" + (-3 * wcoef) + \",\" + (3 * hcoef));\n scroll_arr[x].downarrow.attr(\"stroke-width\", 2);\n \n scroll_arr[x].bar.attr(\"x\", 185 * wcoef);\n scroll_arr[x].bar.attr(\"y\", (415 + scroll_arr[x].position) * hcoef);\n scroll_arr[x].bar.attr(\"width\", 10 * wcoef);\n scroll_arr[x].bar.attr(\"height\", 50 * hcoef);\n scroll_arr[x].bar.attr(\"r\", 2);\n if (scroll_arr[x].bardarken) {\n scroll_arr[x].bar.attr(\"fill\", \"grey\");\n } else {\n scroll_arr[x].bar.attr(\"fill\", \"white\");\n }\n \n scroll_arr[x].lines.attr(\"path\", \"M\" + (187 * wcoef) + \",\" + ((435 + scroll_arr[x].position) * hcoef) + \"l\" + (6 * wcoef) + \",0m0,\" + (5 * hcoef) + \"l\" + (-6 * wcoef) + \",0m0,\" + (5 * hcoef) + \"l\" + (6 * wcoef) + \",0\");\n }\n \n \n \n \n \n if (concept.toolbar.color_sltr.color === \"white\") {\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"stroke\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"stroke\", concept.toolbar.color_sltr.color);\n }\n if (concept.toolbar.obj_sltr.objecttab.options[0].hover && !concept.toolbar.obj_sltr.objecttab.options[0].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"fill\", \"white\");\n }\n // Draw Default Objects: Object\n if (!concept.toolbar.obj_sltr.objecttab.options[0].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"x\", 8 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"y\", 410 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"width\", 80 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"height\", 50 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[0].obj.attr(\"stroke-width\", 2);\n }\n if (concept.toolbar.color_sltr.color === \"white\") {\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"stroke\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"stroke\", concept.toolbar.color_sltr.color);\n }\n if (concept.toolbar.obj_sltr.objecttab.options[1].hover && !concept.toolbar.obj_sltr.objecttab.options[1].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"fill\", \"white\");\n }\n if (!concept.toolbar.obj_sltr.objecttab.options[1].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"x\", 97 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"y\", 410 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"width\", 80 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"height\", 50 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"stroke-width\", 2);\n concept.toolbar.obj_sltr.objecttab.options[1].obj.attr(\"r\", 10);\n }\n if (concept.toolbar.obj_sltr.objecttab.options[2].hover && !concept.toolbar.obj_sltr.objecttab.options[2].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"fill\", \"white\");\n }\n if (concept.toolbar.color_sltr.color === \"white\") {\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"stroke\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"stroke\", concept.toolbar.color_sltr.color);\n }\n if (!concept.toolbar.obj_sltr.objecttab.options[2].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"cx\", 48 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"cy\", 515 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"r\", 30 * hcoef * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[2].obj.attr(\"stroke-width\", 2);\n }\n if (concept.toolbar.obj_sltr.objecttab.options[3].hover && !concept.toolbar.obj_sltr.objecttab.options[3].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"fill\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"fill\", \"white\");\n }\n if (concept.toolbar.color_sltr.color === \"white\") {\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"stroke\", \"grey\");\n } else {\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"stroke\", concept.toolbar.color_sltr.color);\n }\n if (!concept.toolbar.obj_sltr.objecttab.options[3].chosen) {\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"cx\", 133 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"cy\", 515 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"rx\", 45 * wcoef);\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"ry\", 25 * hcoef);\n concept.toolbar.obj_sltr.objecttab.options[3].obj.attr(\"stroke-width\", 2);\n }\n //triangle\n \n //speech bubble\n \n //pics\n //container\n //view\n \n \n \n \n \n //object hide/show based on scroll\n \n \n if (concept.toolbar.obj_sltr.chosen === \"obj\") {\n concept.toolbar.obj_sltr.objectset.toFront();\n }\n if (concept.toolbar.obj_sltr.chosen === \"pics\") {\n concept.toolbar.obj_sltr.picsset.toFront();\n }\n if (concept.toolbar.obj_sltr.chosen === \"cont\") {\n concept.toolbar.obj_sltr.containerset.toFront();\n }\n if (concept.toolbar.obj_sltr.chosen === \"view\") {\n concept.toolbar.obj_sltr.viewset.toFront();\n }\n}", "function writeUI () {\n player.wherePlayer();\n health.writeThirst();\n}", "function happycol_presentation_beginShow(args){\n\t//check for preshow\n\thappycol_enable_controls(args);\n\tif( \n\t\t\n\t\t//list of conditions for a preshow\n\t\targs.lightingDesigner == true \n\t\t\n\t\t){\n\t\thappycol_presentation_preshow(args);\n\t}else{\n\t\thappycol_presentation_theShow(args);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Rectangle and adds it to canvas
createRect(){ let rect = Rect.createRect(this.activeColor); this.canvas.add(rect); this.notifyCanvasChange(rect.id, "added"); }
[ "function drawRectParams() {\n new_shape = new Rectangle(startX, startY, currentX, currentY, getColor());\n drawRectShape(new_shape)\n}", "function Rectangle(width, height, color) {\n var _this = _super.call(this) || this;\n _this.width = width;\n _this.height = height;\n _this.color = color;\n // Set default position.\n _this.setPosition(0, 0);\n return _this;\n }", "function drawRectangle(x,y,w,h, fillC, strokeC, lw, fill, stroke ){\r\n ctx.beginPath();\r\n ctx.rect(x,y,w,h);\r\n if(fill == true){\r\n ctx.fillStyle = fillC;\r\n ctx.fill();\r\n }\r\n if(stroke == true){\r\n ctx.lineWidth = lw;\r\n ctx.strokeStyle = strokeC;\r\n ctx.stroke();\r\n }\r\n\r\n}", "function drawRectangle() {\n let height = Number(prompt(\"Height: \"));\n let width = Number(prompt(\"Width: \"));\n let x = Number(prompt(\"X\"));\n let y = Number(prompt(\"Y\"));\n const canvas = document.getElementById('canvas2');\n const context = canvas.getContext('2d');\n context.clearRect(0, 0, canvas.width, canvas.height);\n if(height<1){\n alert(\"Your height is too small.\")\n }else if (width<1){\n alert(\"Your width is too small.\")\n }else if (x<5){\n alert(\"Your x-coordinate is too small.\")\n }else if (y<5){\n alert(\"Your y-coordinate is too small.\")\n }else if(height>canvas.height-y || width>canvas.width-x){\n alert(\"The rectangle will not fit on the canvas.\")\n }else if(height/1!=height || width/1!=width || x/1!=x || y/1!=y){\n alert(\"Please enter a number.\")\n }else{\n context.strokeStyle=\"black\";\n context.rect(x, y, width, height);\n context.stroke();\n }\n\n}", "function RectangleExtended(pos, id, angle, news) {\n var w = 20;\n var h = 20;\n this.fabricRect = new fabric.Rect({\n left: Math.round(pos.x - w/2),\n top: Math.round(pos.y - h/2),\n width: w,\n height: h,\n angle: angle,\n fill: '#e0e0e0',\n opacity: 0.8,\n strokeWidth: 1,\n stroke: '#004d40',\n selectable: true,\n hasControls: false,\n hasBorders: false,\n lockMovementX: true,\n lockMovementY: true\n });\n this.news=news;\n this.id = id;\n}", "function drawRect(rectObj, id){\n\t\n\tvar rect = rectObj;\n\t\n\t// If no rectangle object was passed in create a new one\n\tif(!rectObj){\n\t\trectObj = new Rect();\t \n\t}\n\n\tvar x = rectObj.x;\n\tvar y = rectObj.y;\n\tvar w = rectObj.w;\n\tvar h = rectObj.h;\n\tvar color = rectObj.color;\n\n\tconsole.log(\"Drawing rectangle with x y w h color : \" + \n x + \",\" + y + \",\" + w + \",\" + h + \",\" + color);\n \n\n\t// If we are just updating a rectange dont create an element\n\tvar rectElem = document.getElementById(id);\n\n\t// if no rect element by that id already exists create and append.\n\tif(!rectElem){ \n\t\trectElem = document.createElement(\"div\");\n\t\trectElem.id = id;\n\t\tdocument.body.appendChild(rectElem); // bug: document body may not exist\n\t} \t\n\n rectElem.innerHTML = \"\";\n rectElem.style.backgroundColor = color;\n rectElem.style.position =\"absolute\";\n rectElem.style.left = x + \"px\";\n rectElem.style.width = w + \"px\";\n rectElem.style.top = y + \"px\";\n rectElem.style.height = h + \"px\";\n\n return rectElem;\n\n}", "function rect( x,y,w,h, color){\n\t\n var x = x;\n var y = y;\n var w = w;\n var h = h;\n var color = color;\n\n \t//defaults\n if(x == undefined) x = 0;\n if(y == undefined) y = 0;\n if(w == undefined) w = 100;\n if(h == undefined) h = 100;\n if(color == undefined) color = \"lightgrey\";\t\n\n\trectElem = document.createElement(\"div\");\n\t// rectElem.id = id;\n\n rectElem.innerHTML = \"\";\n rectElem.style.backgroundColor = color;\n rectElem.style.position =\"absolute\";\n rectElem.style.left = x + \"px\";\n rectElem.style.width = w + \"px\";\n rectElem.style.top = y + \"px\";\n rectElem.style.height = h + \"px\";\n \n //temp\n // rectElem.style.border = \"1px solid blue\";\n\n return rectElem;\n\n}", "function Rect(width,height) {\n\tthis.width = width;\n\tthis.height = height;\n}", "setupCanvas(width, height, rectMargin, rulerSize) {\n\t\tthis.canvas.width = width\n\t\tthis.canvas.height = height\n\t\tthis.rectMargin = rectMargin\n\t\tthis.rulerSize = rulerSize\n\t\tthis.rectArea = {\n\t\t\t'width':this.canvas.width - rulerSize - rectMargin,\n\t\t\t'height':this.canvas.height - rulerSize - rectMargin\n\t\t}\n\t}", "setRect(x, y, width, height){\n\t\tthis.x = x\n\t\tthis.y = y\n\t\tthis.width = width\n\t\tthis.height = height\n\t}", "function createSquare(x, y) {\ngameAreaContext.fillStyle = \"#568000\";\ngameAreaContext.fillRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth)\n}", "createRectangle(options) {\n return this._zone.runOutsideAngular(() => {\n return this._map.then(map => {\n options.map = map;\n return new google.maps.Rectangle(options);\n });\n });\n }", "function definePlane() {\n game.addObject({\n type : 'rect',\n x : 0,\n y : 350,\n width : 800,\n height : 125,\n color : '#333'\n });\n game.draw();\n }", "drawBallReleaseBar() {\n const canvas = document.getElementById(\"myCanvas\");\n const ctx = canvas.getContext(\"2d\");\n ctx.beginPath();\n // ctx.rect(releaseBarX, releaseBarY, canvas.width-releaseBarWidth, releaseBarHeight, releaseBarWidth);\n ctx.strokeRect(381, 560, 280, 500);\n // ctx.fillStyle = \"#000000\";\n // ctx.fill();\n ctx.closePath();\n ctx.stroke();\n }", "function Rect(_x, _y, _width, _height) {\n\tthis.x = _x;\n\tthis.y = _y;\n\tthis.width = _width;\n\tthis.height = _height;\n\n\t//Here are the new variables that track rotation \n\t//and color respectively, and their default values.\n\tthis.rotation = 0;\n\tthis.color = \"red\";\n}", "function drawRectCard (rect) {\n let offset = 3\n let color = '#f54263'\n let w = rect.w\n let h = rect.h\n let cx = rect.cx - offset\n let cy = rect.cy - offset\n\n ctx.beginPath()\n ctx.strokeStyle = color\n ctx.lineWidth = 2\n ctx.strokeRect(cx, cy, w, h)\n ctx.closePath()\n\n }", "function addRectGuides($canvas, parent) {\n\tvar guideProps, guide;\n\tguideProps = $.extend({}, parent.guide, {\n\t\tlayer: true,\n\t\tdraggable: false,\n\t\ttype: 'rectangle',\n\t\thandle: null\n\t});\n\t$canvas.addLayer(guideProps);\n\tguide = $canvas.getLayer(-1);\n\tparent._guide = guide;\n\t$canvas.moveLayer(guide, -parent._handles.length - 1);\n\tupdateRectGuides(parent);\n}", "static buildRectangle(dims, cTypes, offset = new Point()) {\n return new CollisionShape([\n new Point(-dims.x / 2, -dims.y / 2),\n new Point(dims.x / 2, -dims.y / 2),\n new Point(dims.x / 2, dims.y / 2),\n new Point(-dims.x / 2, dims.y / 2),\n ], cTypes, Physics.Shape.Rectangle, offset);\n }", "function addRectHandle($canvas, parent, px, py) {\n\tvar handle, cursor;\n\n\t// Determine cursor to use depending on handle's placement\n\tif ((px === -1 && py === -1) || (px === 1 && py === 1)) {\n\t\tcursor = 'nwse-resize';\n\t} else if (px === 0 && (py === -1 || py === 1)) {\n\t\tcursor = 'ns-resize';\n\t} else if ((px === -1 || px === 1) && py === 0) {\n\t\tcursor = 'ew-resize';\n\t} else if ((px === 1 && py === -1) || (px === -1 && py === 1)) {\n\t\tcursor = 'nesw-resize';\n\t}\n\n\thandle = $.extend({\n\t\t// Set cursors for handle\n\t\tcursors: {\n\t\t\tmouseover: cursor\n\t\t}\n\t}, parent.handle, {\n\t\t// Define constant properties for handle\n\t\tlayer: true,\n\t\tdraggable: true,\n\t\tx: parent.x + ((px * parent.width / 2) + ((parent.fromCenter) ? 0 : parent.width / 2)),\n\t\ty: parent.y + ((py * parent.height / 2) + ((parent.fromCenter) ? 0 : parent.height / 2)),\n\t\t_parent: parent,\n\t\t_px: px,\n\t\t_py: py,\n\t\tfromCenter: true,\n\t\tdragstart: function (layer) {\n\t\t\t$(this).triggerLayerEvent(layer._parent, 'handlestart');\n\t\t},\n\t\t// Resize rectangle when dragging a handle\n\t\tdrag: function (layer) {\n\t\t\tvar parent = layer._parent;\n\n\t\t\tif (parent.width + (layer.dx * layer._px) < parent.minWidth) {\n\t\t\t\tparent.width = parent.minWidth;\n\t\t\t\tlayer.dx = 0;\n\t\t\t}\n\t\t\tif (parent.height + (layer.dy * layer._py) < parent.minHeight) {\n\t\t\t\tparent.height = parent.minHeight;\n\t\t\t\tlayer.dy = 0;\n\t\t\t}\n\n\t\t\tif (!parent.resizeFromCenter) {\n\t\t\t\t// Optionally constrain proportions\n\t\t\t\tif (parent.constrainProportions) {\n\t\t\t\t\tif (layer._py === 0) {\n\t\t\t\t\t\t// Manage handles whose y is at layer's center\n\t\t\t\t\t\tparent.height = parent.width / parent.aspectRatio;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Manage every other handle\n\t\t\t\t\t\tparent.width = parent.height * parent.aspectRatio;\n\t\t\t\t\t\tlayer.dx = layer.dy * parent.aspectRatio * layer._py * layer._px;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Optionally resize rectangle from corner\n\t\t\t\tif (parent.fromCenter) {\n\t\t\t\t\tparent.width += layer.dx * layer._px;\n\t\t\t\t\tparent.height += layer.dy * layer._py;\n\t\t\t\t} else {\n\t\t\t\t\t// This is simplified version based on math. Also you can write this using an if statement for each handle\n\t\t\t\t\tparent.width += layer.dx * layer._px;\n\t\t\t\t\tif (layer._px !== 0) {\n\t\t\t\t\t\tparent.x += layer.dx * ((1 - layer._px) && (1 - layer._px) / Math.abs((1 - layer._px)));\n\t\t\t\t\t}\n\t\t\t\t\tparent.height += layer.dy * layer._py;\n\t\t\t\t\tif (layer._py !== 0) {\n\t\t\t\t\t\tparent.y += layer.dy * ((1 - layer._py) && (1 - layer._py) / Math.abs((1 - layer._py)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Ensure diagonal handle does not move\n\t\t\t\tif (parent.fromCenter) {\n\t\t\t\t\tif (layer._px !== 0) {\n\t\t\t\t\t\tparent.x += layer.dx / 2;\n\t\t\t\t\t}\n\t\t\t\t\tif (layer._py !== 0) {\n\t\t\t\t\t\tparent.y += layer.dy / 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Otherwise, resize rectangle from center\n\t\t\t\tparent.width += layer.dx * layer._px * 2;\n\t\t\t\tparent.height += layer.dy * layer._py * 2;\n\t\t\t\t// Optionally constrain proportions\n\t\t\t\tif (parent.constrainProportions) {\n\t\t\t\t\tif (layer._py === 0) {\n\t\t\t\t\t\t// Manage handles whose y is at layer's center\n\t\t\t\t\t\tparent.height = parent.width / parent.aspectRatio;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Manage every other handle\n\t\t\t\t\t\tparent.width = parent.height * parent.aspectRatio;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tupdateRectHandles(parent);\n\t\t\t$(this).triggerLayerEvent(parent, 'handlemove');\n\t\t},\n\t\tdragstop: function (layer) {\n\t\t\tvar parent = layer._parent;\n\t\t\t$(this).triggerLayerEvent(parent, 'handlestop');\n\t\t},\n\t\tdragcancel: function (layer) {\n\t\t\tvar parent = layer._parent;\n\t\t\t$(this).triggerLayerEvent(parent, 'handlecancel');\n\t\t}\n\t});\n\t$canvas.draw(handle);\n\t// Add handle to parent layer's list of handles\n\tparent._handles.push($canvas.getLayer(-1));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : rouletteArrPusher AUTHOR : Mark Anthony Elbambo DATE : March 12, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : for pushing objects used in the roulette PARAMETERS : devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype
function rouletteArrPusher(devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype){ if(window['variable' + dynamicGreenRouletteArr[pageCanvas]].length > 0){ var ctr=0; for(var a=0; a < window['variable' + dynamicGreenRouletteArr[pageCanvas]].length; a++){ var roultArr = window['variable' + dynamicGreenRouletteArr[pageCanvas]][a]; if(roultArr.model == model && roultArr.manufac == manufac && roultArr.ostyp == ostyp && roultArr.prdfmly == prdfmly && roultArr.ipadd==ipadd && roultArr.prot == prot && roultArr.hostnme == hostnme && roultArr.devtype == devtype){ ctr++; a = window['variable' + dynamicGreenRouletteArr[pageCanvas]].length; }else if(roultArr.model == model && manufac == undefined && ostyp == undefined && prdfmly == undefined && ipadd== undefined && prot == undefined && hostnme && hostnme == undefined){ ctr++; a = window['variable' + dynamicGreenRouletteArr[pageCanvas]].length; } } if(ctr == 0){ window['variable' + dynamicGreenRouletteArr[pageCanvas]].push({"devPath":devPath,"model":model,"imageObj":imageObj,"manufac":manufac,"ostyp":ostyp,"prdfmly":prdfmly,"ipadd":ipadd,"prot":prot,"hostnme":hostnme,"devtype":devtype}); greenRoulette2(); } }else{ window['variable' + dynamicGreenRouletteArr[pageCanvas]].push({"devPath":devPath,"model":model,"imageObj":imageObj,"manufac":manufac,"ostyp":ostyp,"prdfmly":prdfmly,"ipadd":ipadd,"prot":prot,"hostnme":hostnme,"devtype":devtype}); greenRoulette2(); } }
[ "jsonParser(photos){\n let farmIds = [];\n let serverIds = [];\n let ids = [];\n let secretIds = [];\n\n photos.forEach(element => {\n farmIds.push(element.farm);\n serverIds.push(element.server);\n ids.push(element.id);\n secretIds.push(element.secret);\n});\n this.imageLinkBuilder(farmIds,serverIds,ids,secretIds);\n }", "buildPipePair() {\n const topHeight = Phaser.Math.RND.between(\n 1,\n globals.tilesTall - globals.pipeGapSize - 1\n );\n const bottomHeight = globals.tilesTall - globals.pipeGapSize - topHeight;\n\n this.buildPipe(topHeight, false);\n this.buildPipe(bottomHeight, true);\n }", "function populate_market(traders_spec, traders, shuffle, verbose){\n\n function trader_type(robottype, name){\n if (robottype === 'GVWY'){\n return new Trader_Giveaway('GVWY', name, 0.00, 0);\n }else if (robottype === 'ZIC'){\n return new Trader_ZIC('ZIC', name, 0.00, 0);\n }else if (robottype === 'SHVR'){\n return new Trader_Shaver('SHVR', name, 0.00, 0);\n }else if (robottype === 'SNPR'){\n return new Trader_Sniper('SNPR', name, 0.00, 0);\n }else if (robottype === 'ZIP'){\n return new Trader_ZIP('ZIP', name, 0.00, 0);\n }else{\n// sys.exit('FATAL: don\\'t know robot type %s\\n' % robottype)\n }\n\t}\n\n function shuffle_traders(ttype_char, n, traders){\n for (var swap=0; swap<n; swap+=1){\n var t1 = (n - 1) - swap;\n var t2 = int(random(0, t1));\n var t1name = ttype_char+t1;\n var t2name = ttype_char+t2;\n traders[t1name].tid = t2name;\n traders[t2name].tid = t1name;\n var temp = traders[t1name];\n traders[t1name] = traders[t2name];\n traders[t2name] = temp;\n }\n\t}\n\n var n_buyers = 0\n for (var bsIndex=0; bsIndex<Object.keys(traders_spec['buyers']).length; bsIndex+=1){\n var ttype = Object.keys(traders_spec['buyers'])[bsIndex];\n for (var b=0; b<traders_spec['buyers'][ttype]; b+=1){\n var tname = 'B' + n_buyers; // buyer i.d. string\n traders[tname] = trader_type(ttype, tname);\n n_buyers = n_buyers + 1;\n }\n\t}\n\n if (n_buyers < 1){\n// sys.exit('FATAL: no buyers specified\\n')\n }\n\n if (shuffle){ shuffle_traders('B', n_buyers, traders);}\n\n var n_sellers = 0\n for (var ssIndex=0; ssIndex<Object.keys(traders_spec['sellers']).length; ssIndex+=1){\n var ttype = Object.keys(traders_spec['sellers'])[ssIndex];\n for (var s=0; s<traders_spec['sellers'][ttype]; s+=1){\n var tname = 'S' + n_sellers; // buyer i.d. string\n traders[tname] = trader_type(ttype, tname);\n n_sellers = n_sellers + 1;\n }\n\t}\n\n if (n_sellers < 1){\n// sys.exit('FATAL: no buyers specified\\n')\n }\n\n if (shuffle){ shuffle_traders('S', n_sellers, traders);}\n\n if (verbose){\n for (var t=0; t<n_buyers; t+=1){\n var bname = 'B' + t;\n }\n for (var t=0; t<n_sellers; t+=1){\n var bname = 'S' + t;\n }\n }\n\n\n return [{'n_buyers':n_buyers, 'n_sellers':n_sellers},traders];\n\n}", "updateRocketLauncher() {\n // mache für alle Rakten im rockets Array das Folgende:\n for (let i = 0; i < this.rockets.length; i++) { // this.rockets.length ist die Anzahl der Raketen in dem Array rockets\n if (this.rockets[i].endOfLife) { // frage, ob Rakete am Ende ihres Lebens ist\n this.rockets.splice(i, 1); // a) wenn ja, entferne Rakete aus rockets array\n // (.splice entfernt ein element aus einem array an einer bestimmten Stelle, der Array wird kleiner)\n }\n else { // b) wenn noch nicht am Ende des Lebens:\n // Rakete anweisen die Explosion zu zeichnen und zu überprüfen, ob sie jetzt am Ende ihres Lebens ist\n this.rockets[i].updateRocket();\n }\n }\n }", "function bufferLikers(){\r\n\t\tvar temp = new Array();\r\n\t\tfor(var i = 0; i< that.likers.length; i++){\r\n\t\t\tif(that.likers[i].refs === undefined){\r\n\t\t\t\tthat.likers[i].refs = null;\r\n\t\t\t\ttemp.push(that.likers[i].FbId);\r\n\t\t\t\t//R.request('getVideoRefs',{FromFbId:that.likers[i].FbId,Type:\"findWhoLikedMe\"});\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(temp.length > 0)\r\n\t\t\tR.request('getVideoRefs',{FromFbId:temp,Type:\"findWhoLikedMe\"});\r\n\t}", "function change_num_to_brick(){\n for (let z = 0; z < arr.length; z++) {\n arr1.push([]);\n brick_pos_x = 69.5; //69.5\n brick_pos_y = 69.5; //69.5\n count = 0;\n for (let x = 0; x < arr[z].length; x++) {\n arr1[z].push([]);\n for (let y = 0; y < arr[z][x].length; y++) {\n count++;\n if (arr[z][x][y] == 1) {\n brick_count++;\n arr1[z][x][y] = new bricks(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 2) {\n brick_count++;\n arr1[z][x][y] = new golden_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 0) {\n arr1[z][x][y] = new no_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;//101\n }\n if (count % 5 == 0) {\n brick_pos_y += 33;\n brick_pos_x = 69.5; //69.5\n }\n } \n } \n arr_len.push(brick_count);\n brick_count = 0\n }\n}", "function bucketVisitor(obj) {\n console.log(\"bucket visitor \" + obj.id);\n var section_ids = DATA.experiments[obj.id].section_ids;\n obj.sections = [];\n obj.bucket = [];\n for (var i = 0; i < section_ids.length; i++) {\n var sid = section_ids[i];\n obj.sections.push(DATA.sections[sid].variation_ids);\n var r = Math.floor((Math.random() * DATA.sections[sid].variation_ids.length));\n obj.bucket.push(DATA.sections[sid].variation_ids[r]);\n }\n }", "function givepts(target, context) {\r\n\r\n var viewer = context.username;\r\n //console.log(viewer);\r\n var pts = Math.floor((Math.random()+1 ) * 10);\r\n\r\n var i = 0;\r\n while (i <= viewerObj.length) {\r\n if (viewerObj[i] == viewer) {\r\n ptsObj[i] += pts;\r\n console.log(viewer + \" is already in array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n else if (i == viewerObj.length) {\r\n viewerObj.push(viewer);\r\n ptsObj.push(pts);\r\n coinObj.push(0);\r\n console.log(viewer + \" has been added to array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n i++;\r\n }\r\n\r\n sendMessage(target, context, context.username + ' got ' + pts + ' points. YAY!');\r\n}", "function buildocrPayload (filesArr) {\n let labels = getLabels();\n var JSONBody = {\n \"template\":{\n \"labels\": labels\n },\n \"pdffiles\": {\n \"files\": filesArr\n }\n };\n console.log('payload: ' +JSON.stringify(JSONBody))\n return JSONBody;\n \n }", "function pushAndRun(tark, argArr, callbackIndex) {\n Qtark.push({\n arg: argArr,\n func: tark,\n callbackIndex: callbackIndex\n });\n\n if (!tarking && Qtark.length == 1) {\n processQtark();\n }\n }", "movePipes() {\n this.eachPipe(function (pipe) {\n pipe.topPipe.left -= CONSTANTS.PIPE_SPEED;\n pipe.topPipe.right -= CONSTANTS.PIPE_SPEED;\n pipe.bottomPipe.left -= CONSTANTS.PIPE_SPEED;\n pipe.bottomPipe.right -= CONSTANTS.PIPE_SPEED;\n });\n\n /*\n Whenever a pipe completely passes out of the dimensions of the canvas\n it should be shifted from the array and a new, randomly generated pair\n of pipes should be pushed into the array. Unfortunately, JS does not\n have #first and #last methods for array indices. \n */\n if (this.pipes[0].topPipe.right <= 0) {\n this.pipes.shift();\n /*\n This constant is assigned the extra distance in which the new pipe must be created\n away from the last pipe in order to retain consistent spacing\n */\n const newXOffset = this.pipes[1].topPipe.left + CONSTANTS.HORIZONTAL_PIPE_SPACING;\n this.pipes.push(this.randomPipe(newXOffset));\n }\n }", "function recivedShot(UID){\n //tank have\n if(UID==GameObjs.Player.UID){\n createShot(0,0,GameObjs.Player,GameObjs.Player.shotColor);\n return ;\n }\n for (var i = GameObjs.TANKs.length - 1; i >= 0; i--) {\n if(UID==GameObjs.TANKs[i].UID){\n createShot(0,0,GameObjs.TANKs[i],GameObjs.TANKs[i].shotColor);\n break;\n }\n }\n \n \n}", "function fillBucket() {\n \n // Old method - kept for bug checking\n //for (var i=1;i<=numOfAvailableFeeders;i++) {\n // availableFeeders.push(i);\n //}\n\n for (var i=0; i <= currentStage.feederArrangement.length; i++) {\n if (currentStage.feederArrangement[i] == true) {\n availableFeeders.push(i+1);\n }\n }\n numOfAvailableFeeders = availableFeeders.length;\n }", "function createRoverObj(name, x, y, state, facingDirection) {\n\tvar newRover = new roverObject(name, x, y, state, facingDirection);\n\tallRoversObjArray.push(newRover);\n}", "makeThenRenderAGObject(obj_type, obj_left, obj_top) {\n let obj_buffer;\n let obj_buffer_ID;\n switch (obj_type) {\n case 'enemy':\n obj_buffer = new AGObject(\"AGgegner\", new Vector3((obj_left / this._scale), 1, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"ENEMY\";\n getReferenceById(obj_buffer_ID).setSpeedSkalar(0);\n break;\n case 'wall':\n obj_buffer = new AGObject(\"Structure\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"WALL\";\n break;\n case 'portal':\n obj_buffer = new AGPortal(\"Portal\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'exit':\n obj_buffer = new AGRoomExit(\"Exit\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'generic':\n obj_buffer = new AGObject(\"Generic\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).collidable = false;\n getReferenceById(obj_buffer_ID).tag = \"GENERIC\";\n }\n getReferenceById(this._AGroomID).add(obj_buffer_ID);\n this.renderAGObject(obj_buffer_ID);\n\n this.refreshObjectSelect();\n this.listItems();\n this.listConditions();\n\n return obj_buffer_ID;\n }", "async function snipe(msg,args){ \n let base_url = 'https://api.hypixel.net/skyblock/auctions?key=' + api_key + '&page='; //add page num at the end\n /*\n \"Implosion\": 76000000,\n \"Wither Shield\": 75600000,\n \"Shadow Warp\": 75600000,\n \"Necron's Handle\": 342000000,\n */\n //\"Implosion\",\"Wither Shield\",\"Shadow Warp\",\"Necron's Handle\",\n let watchList = [ \"Wither Chestplate 5star\", \"Aspect of the Dragons 3star\", \"Zombie Commander Chestplate 1star\"];\n //watchList supports ✪\n let max_price = {\n \"Wither Chestplate 5star\": 200000000, //for max price, do not include the ✪\n \"Aspect of the Dragons 3star\": 10000000,\n \"Zombie Commander Chestplate 1star\": 4000000\n };\n //additionally check to make sure it's looking at EVERYTHING in the AH\n while(true){\n let initialResponse = await fetch(base_url + \"1\");\n if(initialResponse.ok){\n const json = await initialResponse.json();\n let totalPages = json.totalPages\n for(let i = 0;i<totalPages;i++){\n let currPage = base_url + i;\n const response = await fetch(currPage);\n if(response.ok){\n let pageData = await response.json();\n totalPages = pageData.totalPages;\n processSnipeArray(max_price,pageData.auctions,watchList,msg,args); //Called on each page of the auction house\n }\n console.log(i);\n }\n }\n await new Promise(r => setTimeout(r, 35000));\n } \n}", "createMeetUp(state, payload) {\n state.loadedMeetUps.push(payload);\n }", "function push() {\n var lastState = newState(),\n i;\n copyModelState(lastState);\n list[listState.index + 1] = lastState; // Drop the oldest state if we went over the max list size\n\n if (list.length > listState.maxSize) {\n list.splice(0, 1);\n listState.startCounter++;\n } else {\n listState.index++;\n }\n\n listState.counter = listState.index + listState.startCounter; // Send push request to external objects defining TickHistoryCompatible Interface.\n\n for (i = 0; i < externalObjects.length; i++) {\n externalObjects[i].push();\n }\n\n invalidateFollowingState();\n listState.length = list.length;\n }", "function serialize(robot_command) {\n var num_packet = 10;\n var buffer = new ArrayBuffer(num_packet);\n var uint8View = new Uint8Array(buffer);\n\n var binarized_command = new Object();\n binarized_command = scalingToBinary(robot_command);\n\n uint8View[0] = 0xFF;\n uint8View[1] = 0xC3;\n\n uint8View[2] = binarized_command.id;\n\n uint8View[3] = binarized_command.vel_norm;\n uint8View[4] = binarized_command.vel_theta;\n uint8View[5] = binarized_command.omega;\n\n uint8View[6] = 0x00;\n if (binarized_command.dribble_power > 0) {\n uint8View[6] |= 0x80;\n }\n uint8View[6] = 0x20;\n if (binarized_command.kick_power > 0) {\n uint8View[6] |= 0x10;\n }\n if (binarized_command.kick_type == \"CHIP\") {\n uint8View[6] |= 0x08;\n }\n uint8View[6] |= 0x04;\n if (binarized_command.charge_enable == true) {\n uint8View[6] |= 0x02;\n }\n\n // TODO : ErrFlag\n\n\n // TODO : Overflow err expression\n uint8View[7] = 0x00;\n uint8View[7] += binarized_command.dribble_power;\n uint8View[7] <<= 4;\n uint8View[7] += binarized_command.kick_power;\n\n // Make checksum\n uint8View[8] = 0x00;\n for (var i=2; i<8; i++) {\n uint8View[8] ^= uint8View[i];\n }\n uint8View[9] = uint8View[8] ^ 0xFF;\n\n return buffer;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collapse the main header search and do some cleanup.
function collapseHeaderSearch() { // Collapse the div $("#header-search").collapse("hide"); // Clear out the input $("input#global-search").val(""); // Clear out the query suggestions $("#header-search table#search_suggest").children().remove(); }
[ "function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}", "function setupHeaderClickHandling()/*:void*/ {var this$=this;\n this.subPanels$v95j.forEach(function (panel/*:Panel*/)/*:void*/ {\n var header/*:Element*/ = panel.header.getEl();\n\n if (header) {\n header.setStyle(\"cursor\", \"pointer\");\n\n // Single click should expand/collapse the panel, but only if\n // the single click is not part of a double click. Therefore\n // we use a DelayedTask that executes the expand/collapse\n // only if no other click happens within the next 350ms.\n this$.mon(header, \"click\", function ()/*:void*/ {\n if (!this$.clickActionRequested$v95j) {\n this$.clickActionRequested$v95j = true;\n var executeSingleClickActionLater/*:DelayedTask*/ = new Ext.util.DelayedTask(function ()/*:void*/ {\n if (this$.clickActionRequested$v95j) {\n this$.clickActionRequested$v95j = false;\n if (panel.getCollapsed()) {\n panel.expand(false);\n } else {\n panel.collapse();\n }\n }\n });\n executeSingleClickActionLater.delay(350);\n }\n });\n\n // Double clicks should expand the panel and collapse all other\n // panels.\n this$.mon(header, \"dblclick\", function ()/*:void*/ {\n this$.clickActionRequested$v95j = false;\n this$.subPanels$v95j.forEach(function (subPanel/*:Panel*/)/*:void*/ {\n if (subPanel !== panel) {\n subPanel.collapse();\n }\n });\n panel.expand(false);\n });\n }\n });\n }", "function hsCollapseParents(header) {\n hsCollapse(header);\n header.parents('.hsExpanded').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}", "_collapseHeading(heading) {\n heading.expanded = false;\n }", "function getSubHeaders(header,subHeaderObj,applicationObj)\n{\n var subHeaders =[];\n if(header=='flat_products')\n {\n\n /*var subHeader =new SubHeader('Processes');\n subHeader.subHeaderArray.push(new SubHeader('Coil Thermal','/coilthermal/'),new SubHeader('Plate Stretch','/platestretch/'),\n new SubHeader('Hot Rolling Mill','/rollingmill/hot/'),new SubHeader('Cold Rolling Mill','/rollingmill/cold/'),new SubHeader('Continuous Furnace','/furnace/'),\n new SubHeader('Continuous Quench','/continuousquench/'),new SubHeader('Batch Furnace','/batchfurnace/')\n );*/\n subHeaders.push(new SubHeader('Linked Process','/linkage/'));\n //subHeaders.push(new SubHeader('linkage','/linkage/'));\n\n subHeaders.push(new SubHeader('Coil Thermal','/coilthermal/'));\n subHeaders.push(new SubHeader('Plate Stretch','/platestretch/'));\n\n var subHeader =new SubHeader('Rolling Mill');\n var subHeaderContinuousQuench =new SubHeader('Continuous Quench');\n var subHeaderContinuousFurnace =new SubHeader('Continuous Furnace');\n var subHeaderBatchFurnace =new SubHeader('Batch Furnace');\n var subHeaderBatchQuench =new SubHeader('Batch Quench');\n\n subHeader.subHeaderArray.push(new SubHeader('Hot Rolling Mill','/rollingmill/hot/'),new SubHeader('Cold Rolling Mill','/rollingmill/cold/'),new SubHeader('Hot Reversing Mill','/hotreversingmill/'));\n // hot reversing mill has been separated for nov migration\n // subHeader.subHeaderArray.push(new SubHeader('Hot Rolling Mill','/rollingmill/hot/'),new SubHeader('Cold Rolling Mill','/rollingmill/cold/'));\n subHeaderContinuousQuench.subHeaderArray.push(new SubHeader('Continuous Quench Sheet/Plate Rec/Rcx','/continuousquench/'),new SubHeader('Continuous Quench HHT Plate C-Curve','/continuousquenchplate/'),new SubHeader('Continuous Quench Sheet/Plate C-Curve','/continuousquenchccurve/'));\n subHeaderContinuousFurnace.subHeaderArray.push(new SubHeader('Continuous Furnace Convective Rec/Rcx','/furnace/'),new SubHeader('Continuous Furnace Pusher','/furnacepusher/'),new SubHeader('Continuous Furnace Paintline','/continuousfurnacepaintline/'),new SubHeader('Continuous Furnace Convective Equiv Aging Time','/continuousfurnaceconvectiveequivagingtime/'),new SubHeader('Continuous Furnace Infrared Rec/Rcx','/continuousfurnaceinfrared/'),new SubHeader('Continuous Furnace Convective Prec/Diss','/continuousfurnaceprecdiss/'));\n // subHeaderContinuousFurnace.subHeaderArray.push(new SubHeader('Continuous Furnace Convective Rec/Rcx','/furnace/'),new SubHeader('Continuous Furnace Pusher','/furnacepusher/'),new SubHeader('Continuous Furnace Paintline','/continuousfurnacepaintline/'),new SubHeader('Continuous Furnace Convective Equiv Aging Time','/continuousfurnaceconvectiveequivagingtime/'),new SubHeader('Continuous Furnace Infrared Rec/Rcx','/continuousfurnaceinfrared/'));\n // subHeaderContinuousFurnace.subHeaderArray.push(new SubHeader('Continuous Furnace Convective Rec/Rcx','/furnace/'),new SubHeader('Continuous Furnace Pusher','/furnacepusher/'),new SubHeader('Continuous Furnace Paintline','/continuousfurnacepaintline/'));\n subHeaderBatchFurnace.subHeaderArray.push(new SubHeader('Batch Furnace Coil Rec/Rcx','/batchfurnace/'),new SubHeader('Batch Furnace Sheet/Plate Equiv Aging Time','/batchfurnacesheetplate/'),new SubHeader('Batch Furnace Specified T vs t Prec/Diss','/batchfurnacespecifiedtvst/'),new SubHeader('Batch Furnace Ingot and Thermal','/batchfurnaceingot/'));\n\n subHeaderBatchQuench.subHeaderArray.push(new SubHeader('Batch Quench Sheet/Plate C-Curve','/batchquench/'),new SubHeader('Batch Quench SheetPlate Rec/Rcx','/batchquenchsheetplate/'));\n subHeaders.push(subHeader);\n subHeaders.push(subHeaderContinuousQuench);\n subHeaders.push(subHeaderContinuousFurnace);\n subHeaders.push(subHeaderBatchFurnace);\n subHeaders.push(subHeaderBatchQuench);\n // subHeaders.push(new SubHeader('Continuous Furnace','/furnace/'));\n //subHeaders.push(new SubHeader('Continuous Quench','/continuousquench/'));\n // subHeaders.push(new SubHeader('Batch Furnace','/batchfurnace/'));\n // subHeaders.push(new SubHeader('Batch Quench','/batchquench/'));\n subHeaders.push(new SubHeader('Slab Thermal','/slabthermal/'));\n subHeaders.push(new SubHeader('Leveler Work Hardening','/leveler/'));\n subHeaders.push(new SubHeader('Coil Stress','/coilstress/'));\n subHeaders.push(new SubHeader('Caster2D','/caster/'));\n subHeaders.push(new SubHeader('Trim,Scalp,Shear-Mass Balance','/trimscalpshearmass/'));\n\n\n if(currentApp == 'rollingmill'){\n if(applicationObj() == 'Cold Rolling Mill'){\n subHeader.selectedApplication(pageMapping[currentApp].application1);\n subHeader.selectedLink(pageMapping[currentApp].application1);\n }\n else if(applicationObj() == 'Hot Rolling Mill'){\n subHeader.selectedApplication(pageMapping[currentApp].application2);\n subHeader.selectedLink(pageMapping[currentApp].application2);\n }\n else if(applicationObj() == 'Hot Reversing Mill'){\n subHeader.selectedApplication(pageMapping[currentApp].application3);\n subHeader.selectedLink(pageMapping[currentApp].application3);\n }\n }\n if(currentApp == 'continuousquench'){\n if(applicationObj() == 'Continuous Quench Sheet/Plate Rec/Rcx'){\n subHeaderContinuousQuench.selectedApplication(pageMapping[currentApp].application1);\n subHeaderContinuousQuench.selectedLink(pageMapping[currentApp].application1);\n }\n else if(applicationObj() == 'Continuous Quench HHT Plate C-Curve'){\n subHeaderContinuousQuench.selectedApplication(pageMapping[currentApp].application2);\n subHeaderContinuousQuench.selectedLink(pageMapping[currentApp].application2);\n }\n else if(applicationObj() == 'Continuous Quench Sheet/Plate C-Curve'){\n subHeaderContinuousQuench.selectedApplication(pageMapping[currentApp].application3);\n subHeaderContinuousQuench.selectedLink(pageMapping[currentApp].application3);\n }\n }\n if(currentApp == 'furnace'){\n if(applicationObj() == 'Continuous Furnace'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application1);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application1);\n }\n else if(applicationObj() == 'Continuous Furnace Pusher'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application2);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application2);\n }\n else if(applicationObj() == 'Continuous Furnace Paintline'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application3);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application3);\n }\n else if(applicationObj() == 'Continuous Furnace Convective Equiv Aging Time'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application4);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application4);\n }\n else if(applicationObj() == 'Continuous Furnace Infrared Rec/Rcx'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application5);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application5);\n }\n else if(applicationObj() == 'Continuous Furnace convective prec/diss'){\n subHeaderContinuousFurnace.selectedApplication(pageMapping[currentApp].application6);\n subHeaderContinuousFurnace.selectedLink(pageMapping[currentApp].application6);\n }\n }\n if(currentApp == 'batchfurnace'){\n if(applicationObj() == 'Batch Furnace Coil Rec/Rcx'){\n subHeaderBatchFurnace.selectedApplication(pageMapping[currentApp].application1);\n subHeaderBatchFurnace.selectedLink(pageMapping[currentApp].application1);\n }\n else if(applicationObj() == 'Batch Furnace Sheet/Plate Equiv Aging Time'){\n subHeaderBatchFurnace.selectedApplication(pageMapping[currentApp].application2);\n subHeaderBatchFurnace.selectedLink(pageMapping[currentApp].application2);\n }\n else if(applicationObj() == 'Batch Furnace Specified T vs t Prec/Diss'){\n subHeaderBatchFurnace.selectedApplication(pageMapping[currentApp].application2);\n subHeaderBatchFurnace.selectedLink(pageMapping[currentApp].application2);\n }\n else if(applicationObj() == 'Batch Furnace Ingot and Thermal'){\n subHeaderBatchFurnace.selectedApplication(pageMapping[currentApp].application2);\n subHeaderBatchFurnace.selectedLink(pageMapping[currentApp].application2);\n }\n }\n else{\n /*if(pageMapping[currentApp].application)\n {\n subHeader.selectedApplication(pageMapping[currentApp].application);\n subHeader.selectedLink(pageMapping[currentApp].application);\n }*/\n /*else\n {\n if(pageMapping[currentApp].subHeader!='Linkage') {\n /!*subHeader.selectedApplication('Coil Thermal');\n subHeader.selectedLink('/coilthermal/');*!/\n subHeader.selectedApplication('Processes');\n subHeader.selectedLink('/flatrolled/');\n }\n else\n {\n subHeader.selectedApplication('Processes');\n subHeader.selectedLink('/flatrolled/');\n\n }\n }*/\n }\n /*if(pageMapping[currentApp].application)\n {\n subHeader.selectedApplication(pageMapping[currentApp].application);\n subHeader.selectedLink(pageMapping[currentApp].application);\n }\n else\n {\n if(pageMapping[currentApp].subHeader!='Linkage') {\n subHeader.selectedApplication('Coil Thermal');\n subHeader.selectedLink('/coilthermal/');\n }\n else\n {\n subHeader.selectedApplication('Processes');\n subHeader.selectedLink('/coilthermal/');\n }\n }*/\n\n //subHeaders.push(subHeader);\n\n\n if(!subHeaderObj())\n {\n /*subHeaderObj('Processes');\n //applicationObj('Coil Thermal');\n applicationObj('Processes');*/\n }\n\n }\n else if(header=='castings')\n {\n\n subHeaders.push(new SubHeader('Linked Process','/linkageCasting/'));\n subHeaders.push(new SubHeader('A622 Fluxing', '/fluxing/'),new SubHeader('Trough-2D', '/troughcasting/'));\n if (!subHeaderObj()) {\n if(currentApp=='fluxing') {\n subHeaderObj('A622 Fluxing');\n }\n else if(currentApp=='Trough'){\n subHeaderObj('Trough-2D');\n }\n }\n }\n\n else if(header=='toolbox')\n {\n subHeaders.push(new SubHeader('Spray ToolBox','/spraydesign/')\n ,new SubHeader('AlShape','/alshape/')\n ,new SubHeader('Automotive Heat Treat','/autoht/')\n ,new SubHeader('XPA','/xpa/'),\n new SubHeader('Trough','/troughv1/'));\n if(!subHeaderObj())\n {\n subHeaderObj('Spray ToolBox');\n }\n\n }\n\n return subHeaders;\n}", "function markUnSelectedLevelHeader(headerid) {\n if (tcga.util.hasClass(document.getElementById(headerid), \"selected\")) {\n tcga.util.removeClass(document.getElementById(headerid), \"selected\");\n centerParent = headerid.split(\"_l\")[0] + \"_\";\n platformParent = headerid.split(\"_c\")[0] + \"_\";\n\n if (selectedColHeaderChildren[centerParent] == document.getElementById(centerParent).colSpan) {\n tcga.util.removeClass(document.getElementById(centerParent), \"selected\");\n }\n if (selectedColHeaderChildren[platformParent] == document.getElementById(platformParent).colSpan) {\n tcga.util.removeClass(document.getElementById(platformParent), \"selected\");\n }\n\n selectedColHeaderChildren[centerParent]--;\n selectedColHeaderChildren[platformParent]--;\n }\n}", "function hsExpandParents(header) {\n hsExpand(header);\n header.parents('.hsCollapsed').each(function() {\n hsExpand($(this).children(':header'));\n });\n}", "function hideSearch() {\n\tstate.search = !state.search\n\t$(\"header, #results, #trees\").removeClass(\"search\")\n}", "function actionCollapseAll() {\n $('tr[name=action_entry_referer_header]').hide();\n $('tr[name=action_entry_referer]').hide();\n $('tr[name=action_entry_edit_header]').hide();\n $('tr[name=action_entry_edit]').hide();\n}", "function mainHeaderContent() {\n var winHeight = $(window).innerHeight();\n\n // @screen width => 992px\n if ($(window).width() >= 992) {\n var mainHeaderContentMargin = -($('.main-header-content').height() / 2);\n\n $('.main-header-content').css('margin-top', mainHeaderContentMargin);\n }\n\n \t// @screen width => 768px and <= 991px\n \telse if ($(window).width() >= 768 && $(window).width() <= 991) {\n var headerContainerHeight = $('.main-header > .container').height();\n\n if ((winHeight - 100) <= headerContainerHeight) {\n $('.main-header > .container').css('margin', '110px 0 60px');\n }\n\n else {\n var headerContainerMargin = (50 + ((winHeight - 100) - headerContainerHeight)) / 2;\n\n $('.main-header > .container').css('margin-top', headerContainerMargin);\n }\n \t}\n\n \t// @screen width <= 767px\n \telse {\n var headerContainerHeight = $('.main-header > .container').height();\n\n if ((winHeight - 50) <= headerContainerHeight) {\n\n }\n\n else {\n var headerContainerMargin = (50 + (winHeight - headerContainerHeight)) / 2;\n\n $('.main-header > .container').css('margin-top', headerContainerMargin);\n }\n \t};\n }", "function\nstickTableHeader()\n{\n var reportBody = $(currentPane + \" #report-body\")[0];\n if (!reportBody) return;\n var areaTable = $(currentPane + \" #area-table-content\")[0];\n if (!areaTable) return;\n var panel = reportBody.getBoundingClientRect();\n var table = areaTable.getBoundingClientRect();\n var rowWidth = 0.0;\n var tableWidth = table.width;\n var systemRow;\n\n var tableHeader = $(currentPane + ' #table-header').filter(function () {\n if ($(this).is(\":visible\")) return true;\n return false;\n });\n\n systemRow = $(currentPane + ' #first-row')\n .filter(function () {\n if ($(this).is(\":visible\")) return true;\n return false;\n });\n\n tableHeader.css(\"position\", \"absolute\")\n .css(\"top\", (panel.top - table.top))\n .css(\"left\", 0);\n\n tableHeader.find('th').each(function (i) {\n var itemWidth = (systemRow.find('td').eq(i))[0].getBoundingClientRect().width;\n if (i === 0) {\n // This column contains the expand/collapse all button. Check if need to resize button\n if (itemWidth < $('#collapseAll').outerWidth() || itemWidth < 116) {\n $('#collapseAll').outerWidth(itemWidth);\n $('#expandAll').outerWidth(itemWidth);\n } else {\n $('#collapseAll').outerWidth(116);\n $('#expandAll').outerWidth(116);\n }\n }\n rowWidth += itemWidth;\n\n $(this).css('min-width', itemWidth);\n });\n\n // Set the Spacer row height equal to current tableHeader height\n systemRow.css(\"height\", tableHeader.outerHeight());\n\n // if we just hid the selected row, unselect it and clear details pane\n if (view.clickDown && view.clickDown.offsetParent === null) {\n unsetClick();\n }\n}", "exitImportHeader(ctx) {\n\t}", "function removeShrink(){\n\t\tvar rows = $b42s_header.find( '.fl-row-content-wrap' ),\n\t\t\tmodules = $b42s_header.find( '.fl-module-content' );\n\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-bottom' );\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-top' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-bottom' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-top' );\n\t\t$b42s_header.removeClass( 'fl-theme-builder-header-shrink' );\n\t}", "function coheUpdateMessageHeaders()\n {\n // Remove the height attr so that it redraws correctly. Works around a\n // problem that attachment-splitter causes if it's moved high enough to\n // affect the header box:\n document.getElementById('msgHeaderView').removeAttribute('height');\n\n // iterate over each header we received and see if we have a matching entry\n // in each header view table...\n for (var headerName in currentHeaderData)\n {\n var headerField = currentHeaderData[headerName];\n var headerEntry = null;\n\n if (gCoheCollapsedHeaderViewMode && !gCoheBuiltCollapsedView)\n {\n if (headerName == \"cc\" || headerName == \"to\" || headerName == \"bcc\")\n headerEntry = gCoheCollapsedHeaderView[\"toCcBcc\"];\n else if (headerName in gCoheCollapsedHeaderView)\n headerEntry = gCoheCollapsedHeaderView[headerName];\n }\n\n if (headerEntry) {\n headerEntry.outputFunction(headerEntry, headerField.headerValue);\n headerEntry.valid = true;\n }\n }\n\n if (gCoheCollapsedHeaderViewMode)\n gCoheBuiltCollapsedView = true;\n\n // now update the view to make sure the right elements are visible\n coheUpdateHeaderView();\n }", "function setHeadingCollapse(cell, collapsing, notebook) {\n const which = findIndex(notebook.widgets, (possibleCell, index) => {\n return cell.model.id === possibleCell.model.id;\n });\n if (which === -1) {\n return -1;\n }\n if (!notebook.widgets.length) {\n return which + 1;\n }\n let selectedHeadingInfo = NotebookActions.getHeadingInfo(cell);\n if (cell.isHidden ||\n !(cell instanceof MarkdownCell) ||\n !selectedHeadingInfo.isHeading) {\n // otherwise collapsing and uncollapsing already hidden stuff can\n // cause some funny looking bugs.\n return which + 1;\n }\n let localCollapsed = false;\n let localCollapsedLevel = 0;\n // iterate through all cells after the active cell.\n let cellNum;\n for (cellNum = which + 1; cellNum < notebook.widgets.length; cellNum++) {\n let subCell = notebook.widgets[cellNum];\n let subCellHeadingInfo = NotebookActions.getHeadingInfo(subCell);\n if (subCellHeadingInfo.isHeading &&\n subCellHeadingInfo.headingLevel <= selectedHeadingInfo.headingLevel) {\n // then reached an equivalent or higher heading level than the\n // original the end of the collapse.\n cellNum -= 1;\n break;\n }\n if (localCollapsed &&\n subCellHeadingInfo.isHeading &&\n subCellHeadingInfo.headingLevel <= localCollapsedLevel) {\n // then reached the end of the local collapsed, so unset NotebookActions.\n localCollapsed = false;\n }\n if (collapsing || localCollapsed) {\n // then no extra handling is needed for further locally collapsed\n // headings.\n subCell.setHidden(true);\n continue;\n }\n if (subCellHeadingInfo.collapsed && subCellHeadingInfo.isHeading) {\n localCollapsed = true;\n localCollapsedLevel = subCellHeadingInfo.headingLevel;\n // but don't collapse the locally collapsed heading, so continue to\n // expand the heading. This will get noticed in the next round.\n }\n subCell.setHidden(false);\n }\n if (cellNum === notebook.widgets.length) {\n cell.numberChildNodes = cellNum - which - 1;\n }\n else {\n cell.numberChildNodes = cellNum - which;\n }\n NotebookActions.setCellCollapse(cell, collapsing);\n return cellNum + 1;\n }", "function selectHeader(headerid) {\n var cellDomLocations = new Array();\n var headerIndex = headerid;\n\n if (headerid.indexOf(\"column\") > -1) {\n //mark selected header and update header relationships\n markSelectedLevelHeader(headerid);\n\n headerIndex = parseInt(headerid.split(\"column\")[1].split(\"_\")[0]);\n\n if (cellHeaders[headerIndex + \"\"] != null) {\n cellDomLocations = cellHeaders[headerIndex].replace(\"undefined\", \"\").split(\",\");\n for (var l = 0; l < cellDomLocations.length - 1; l++) {\n levelHeaders[headerIndex].push(document.getElementById(cellDomLocations[l]));\n }\n cellHeaders[headerIndex + \"\"] = null;\n }\n if (levelHeaders[headerIndex] != undefined) {\n for (var k = 0; k < levelHeaders[headerIndex].length; k++) {\n cell = levelHeaders[headerIndex][k];\n cellid = cell.id;\n cellIdParts = cellid.split(\"column\");\n columnNum = cellIdParts[1].split(\"_\")[0];\n selectCellNum = cellid.split(\"_cellID_\")[1];\n selectedSampleID = cellIdParts[0];\n levelHeaders[columnNum].length > 0 ? totalSelectableCol = levelHeaders[columnNum].length : totalSelectableCol = cellHeaders[columnNum].split(\",\").length - 1;\n if (selectedCells[selectCellNum] == null) {\n selectCell(cell, \"headerCol\", selectCellNum, selectedSampleID, columnNum, totalSelectableCol, cellHeaders[selectedSampleID].split(\",\").length);\n }\n }\n }\n\n } else if (cellHeaders[headerIndex] != undefined) {\n //the string is likely to lead with undefined if first batch had no 'availables'\n var idString = cellHeaders[headerIndex].replace(\"undefined,\", \"\");\n\n if (idString.length > 0) {\n var idArray = idString.split(\",\");\n\n if (headerIndex.indexOf(\"_sample\") == -1 && headerIndex.indexOf(\"column\") == -1) {\n //if its batch header clicked, recursively apply to each sample id\n for (var j = 0; j < idArray.length; j++) {\n selectHeader(idArray[j]);\n }\n\n } else {\n for (var i = 0; i < idArray.length; i++) {\n cellid = idArray[i];\n cell = document.getElementById(cellid);\n cellIdParts = cellid.split(\"column\");\n columnNum = cellIdParts[1].split(\"_\")[0];\n selectCellNum = cellid.split(\"_cellID_\")[1];\n selectedSampleID = cellIdParts[0];\n levelHeaders[columnNum].length > 0 ? totalSelectableCol = levelHeaders[columnNum].length : totalSelectableCol = cellHeaders[columnNum].split(\",\").length - 1;\n\n if (selectedCells[selectCellNum] == null) {\n selectCell(cell, \"header\", selectCellNum, selectedSampleID, columnNum, totalSelectableCol, cellHeaders[selectedSampleID].split(\",\").length);\n }\n }\n }\n } else if (!tcga.util.hasClass(document.getElementById(headerIndex), \"selected\")) {\n markSelectedSampleHeader(headerIndex);\n }\n }\n}", "function hideAll() {\n for(let bio in allBios) {\n if(!allBios[bio].hasClass('hidden-heading')) {\n allBios[bio].addClass('hidden-heading');\n }\n }\n }", "_expandHeading(heading) {\n heading.expanded = true;\n }", "appendCurrentHeader(header) {\n this.currentSectionContent += header + \"\\n\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update Firebase high scores
function updateHighScore(path, data) { var leaderRef = firebase.database().ref().child("highscores"); leaderRef.child(path).update(data); }
[ "updateScore() {\n this.serverComm.updateScore(this.userId, this);\n }", "getHighScores() {\n\t\tvar ref = this.database.ref(this.tableName);\n\t\tvar db = this;\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\t(function(db){\n\t\t\t\tref.on(\"value\", function(snapshot) {\n\t\t\t\t\tdb.highScores = snapshot.val();\n\t\t\t\t\tdb.setHighScoreInformation();\n\t\t\t\t\tresolve (snapshot.val());\n\t\t\t\t}, function (errorObject) {\n\t\t\t\t\tconsole.log(\"The read failed: \" + errorObject.code);\n\t\t\t\t\treject (-1);\n\t\t\t\t});\n\t\t\t}(db));\n\t\t});\n\t}", "function addScore() {\n\tvar ref = database.ref('rank');\n\tvar data = {\n\t\tname: userName,\n\t\tvalue: score\n\t}\n\tref.push(data);\n}", "function updateScore() {\n\n}", "set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }", "function addHighScore(){\n var highScore = getHighScore();\n var score = currentScore;\n highScore.splice(0, 0, score);\n localStorage.setItem('highScore', JSON.stringify(highScore)); \n displayHighScore(); \n }", "set score(val) {\n this._score = val;\n console.log('score updated');\n emitter.emit(G.SCORE_UPDATED);\n }", "updatePoints() {\n \n if (this.props.format === 'stroke') {\n // *** no points to be calculated ***\n return\n }\n \n if (this.props.format === 'match') {\n /**************************************************************\n * Assigns point to player with lowest score\n * If multiple value of lowest score, no points are assigned\n **************************************************************/\n const scores = Object.values(this.props.scores);\n \n const playerObjects = Object.entries(this.props.scores).map((entry => ({\n player_id: entry[0], score: entry[1], points: 0\n })));\n\n const min = Math.min(...scores);\n const minIndex = scores.indexOf(min);\n playerObjects[minIndex].points = 1;\n scores.splice(minIndex, 1);\n\n\n for (let i = 0; i < scores.length; i++) {\n if (scores[i] === min) {\n playerObjects[minIndex].points = 0;\n }\n }\n\n playerObjects.map(player => \n this.props.firebase.db.ref(`matches/${this.props.match_id}/points/${player.player_id}/`).update({[this.props.hole_id]: player.points})\n )\n }\n }", "updateCount(count){\r\n //playerCount refers to the database counts whereas count refers to make a change to the original playerCount\r\n database.ref(\"/\").update({playerCount:count});\r\n }", "function updateScore() {\n\t\t\t// Score rule: pass level n in t seconds get ((100 * n) + (180 - t)) points \n\tlevelScore = (levelTime + 100) + Math.floor(levelTime * (currentLevel-1));\n\t// Set original \"levelScore\" to extraLevelScore for testing purpose\n\tfinalScore += levelScore + extraLevelScore;\t\t\n\t// Add finalTime\n\tfinalTime += startLevelTime - levelTime;\n}", "function loadLeaderBoard() {\n var leaderRef = firebase.database().ref().child(\"highscores\");\n leaderRef.child(\"p0\").child('name').on('value', snap => {\n $(\"#p0\").text(snap.val());\n leaderName0 = snap.val();\n });\n leaderRef.child(\"p0\").child('score').on('value', snap => {\n $(\"#p0score\").text(snap.val());\n leaderScore0 = parseInt(snap.val());\n });\n leaderRef.child(\"p1\").child('name').on('value', snap => {\n $(\"#p1\").text(snap.val());\n leaderName1 = snap.val();\n });\n leaderRef.child(\"p1\").child('score').on('value', snap => {\n $(\"#p1score\").text(snap.val());\n leaderScore1 = parseInt(snap.val());\n });\n leaderRef.child(\"p2\").child('name').on('value', snap => {\n $(\"#p2\").text(snap.val());\n leaderName2 = snap.val();\n });\n leaderRef.child(\"p2\").child('score').on('value', snap => {\n $(\"#p2score\").text(snap.val());\n leaderScore2 = parseInt(snap.val());\n });\n }", "async function CompareHighScores(client)\r\n{\r\n console.log(\"Checking high scores\");\r\n\r\n // load list of leaderboards\t\r\n\tvar leaderboardList = await steam.GetLeaderboardList(bot.config.steam_appid);\r\n\r\n // put leaderboard scores into map and check for changes\r\n var highScores = new Map();\r\n var leaderboardCount = leaderboardList.leaderboard.length;\r\n for (var leaderboardIdx = 0; leaderboardIdx < leaderboardCount; ++leaderboardIdx)\r\n {\r\n var curLeaderboard = leaderboardList.leaderboard[leaderboardIdx];\r\n\r\n var leaderboardXml = await rp(curLeaderboard.url + '&start=1&end=1');\r\n\t\tif (!leaderboardXml)\r\n\t\t{\r\n\t\t\tconsole.log(\"Failed to get leaderboard xml for \" + curLeaderboard.display_name);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t\r\n var leaderboard = await xml2js(leaderboardXml, {explicitArray : false, async: false})\r\n\t\tif (!leaderboard || !leaderboard.response || !leaderboard.response.entries || !leaderboard.response.entries.entry)\r\n\t\t{\r\n\t\t\tconsole.log(\"Unexpected leaderboard js for \" + curLeaderboard.display_name);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n var newEntry = leaderboard.response.entries.entry;\r\n\t if (newEntry)\r\n {\r\n var newScore = newEntry.score;\r\n var oldScore = bot.highScores.get(curLeaderboard.lbid);\r\n var messageNewScore = false;\r\n\r\n if (oldScore != undefined)\r\n {\r\n if (oldScore != newScore) // note that we dont test greater than to make this agnostic to sort mode\r\n {\r\n console.log(\"New high score of \" + newScore + \" for leaderboard \" + curLeaderboard.display_name);\r\n bot.highScores.set(curLeaderboard.lbid, newScore);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (!bot.config.steam_leaderboard_tracking_blacklist.includes(curLeaderboard.lbid))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessageNewScore = true;\r\n\t\t\t\t\t}\r\n }\r\n }\r\n else\r\n {\r\n //console.log(\"Tracking initial high score of \" + newScore + \" for leaderboard \" + curLeaderboard.display_name);\r\n bot.highScores.set(curLeaderboard.lbid, newScore);\r\n }\r\n\r\n if (messageNewScore)\r\n {\r\n var channel = client.channels.get(bot.config.steam_channel);\r\n if (channel)\r\n {\r\n // query info about new high score hoder\r\n var usersUrl = 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=' + bot.secret.steam_api_key + '&format=json&steamids=' + newEntry.steamid;\r\n var usersJson = await rp(usersUrl);\r\n var users = JSON.parse(usersJson);\r\n\t\t\t\t\r\n // process the data\r\n var nameData = \"\";\r\n var iconUrl = \"\";\r\n\r\n var player = users.response.players.find(x => x.steamid == newEntry.steamid);\r\n if (player)\r\n {\r\n nameData = player.personaname;;\r\n iconUrl = player.avatar;\r\n }\r\n else\r\n {\r\n // unexpected failure to find steamid in results\r\n nameData += newEntry.steamid + \"\\n\";\r\n }\r\n\r\n // shore the results\r\n channel.send({embed: {\r\n color: 0xFFFFFF,\r\n title: curLeaderboard.display_name,\r\n url: \"http://steamcommunity.com/stats/\" + bot.config.steam_appid + \"/leaderboards/\" + curLeaderboard.lbid + \"/\",\r\n description: \"New high score of \" + parseInt(newScore).toLocaleString() + \" by \" + nameData + \"!\",\r\n thumbnail: { url: iconUrl },\r\n }});\r\n }\r\n }\r\n }\r\n }\r\n}", "function updateScore(){\n scoreText.setText(\"Score: \"+score);\n }", "function updateUserPqScoreToLatest(userAnalyticsMap, user, analyticsTillDate, pqScoreTillDate){\n var last7DayPQScores = (Array.isArray(user.get(\"last_7_day_pq_scores\"))) ? (user.get(\"last_7_day_pq_scores\")).slice() : [0],\n last7DayPqGain = 0;\n user.set(\"pq_score\", last7DayPQScores[0]); // sets pq score to user's last analytics record score\n\n if(userAnalyticsMap[user.id]) {\n var endDate = new Date(pqScoreTillDate),\n startDate = new Date(analyticsTillDate);\n startDate.setDate(startDate.getDate() + 1);\n\n // check if user has attemptest any quiz after last analytics date and then update pq score\n while (startDate.getTime() <= endDate.getTime()) {\n if (userAnalyticsMap[user.id].data[startDate.getTime()]) {\n user.set(\"pq_score\", userAnalyticsMap[user.id].data[startDate.getTime()].pq)\n }\n last7DayPqGain = user.get(\"pq_score\") - last7DayPQScores[last7DayPQScores.length - 1];\n last7DayPQScores.unshift(user.get(\"pq_score\")); // adds current day pq score\n last7DayPQScores = last7DayPQScores.slice(0, 7); // removes the 8th day pq score\n startDate.setDate(startDate.getDate() + 1);\n }\n if(last7DayPqGain) {\n user.set(\"last_7_day_pq_gain\", last7DayPqGain)\n }\n\n }\n }", "setScore() {\n this.#gameScore += this.#rules[this.#gameLevel - 1].score\n document.dispatchEvent(this.#gameScoreEvent)\n }", "function updateScore() {\n humanScoreSpan.innerHTML = humanScore;\n computerScoreSpan.innerHTML = computerScore;\n return;\n }", "async function addNewScore(e) {\n e.preventDefault();\n const response = await fetch(\"/scoreboard\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(gatherInputData()),\n });\n const data = await response.json();\n console.log(data);\n getAllScores();\n clearInputFields();\n}", "function updateGameDatabaseforPlayer1() {\n console.log(\"im in updateGameDatabaseeforPlayer1\");\n gameRef.update({\n player1ChoiceMade: player1ChoiceMade,\n player1Choice: player1Choice\n });\n\n}", "function updateScoreOverlay() {\n let one = playerNetscore(team.getT1());\n write(t1Players, one);\n one = team.getT1();\n write(t1Score, one.points);\n\n let two = playerNetscore(team.getT2());\n write(t2Players, two);\n two = team.getT2();\n write(t2Score, two.points);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SFVFS[] Set Freedom Vector From Stack 0x0B
function SFVFS(state) { var stack = state.stack; var y = stack.pop(); var x = stack.pop(); if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } state.fv = getUnitVector(x, y); }
[ "getVariable(index) {\n const depth = this.getLocalDepth(index); // depth of the local in the stack.\n const memoryOffset = this.getMemoryOffset(depth); // actual depth in BF memory.\n const size = this.sizeOfVal(index); // how many byes to copy.\n const type = this.typeOfVal(index);\n\n for (let i = 0; i < size; i++) {\n this.copyByte(memoryOffset, true);\n }\n\n this.stack.push(StackEntry(type, size));\n }", "static FromFloatArray(array, offset) {\n return Vector3.FromArray(array, offset);\n }", "static FromFloatArrayToRef(array, offset, result) {\n Vector4.FromArrayToRef(array, offset, result);\n }", "static FromFloatArrayToRef(array, offset, result) {\n return Vector3.FromArrayToRef(array, offset, result);\n }", "get f32() { return new Float32Array(module.memory.buffer, this.ptr, this.len); }", "setVariable(index) {\n // how far down the value is, in the compile time stack.\n const slot = this.getLocalDepth(index);\n // how far down the first byte of the variable will be in BF memory-tape\n const memoryOffset = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(index);\n\n let stackTopSize = this.sizeOfVal(this.stack.length - 1);\n if (size != stackTopSize) {\n this.error(\n `Cannot assign value of size ${size} to value of size ${stackTopSize}`\n );\n }\n\n for (let i = 0; i < size; i++) {\n this.setByte(memoryOffset - size + 1);\n }\n this.stack.pop();\n }", "static shiftFamilyImmutably(family, vector)\n {\n const newFam = [];\n let draft;\n for(let i = 0; i < family.length; i++)\n {\n draft = Person.cloneFromOther(family[i]);\n draft.locationInTreeX += vector.x;\n draft.locationInTreeY += vector.y;\n newFam.push(draft);\n }\n return newFam;\n }", "function getRomFrame(addr){\n\n}", "save_stack(s){\n var v = [];\n for(var i=0; i<s; i++){\n v[i] = this.stack[i];\n }\n return { stack: v, last_refer: this.last_refer, call_stack: [...this.call_stack], tco_counter: [...this.tco_counter] };\n }", "function restoreBSPArray(bspString) {\n\t//console.log(\"restoring \" +bspString);\n\tvar bspArray = bspString.split(\"&&\");\n\t//console.log(bspArray);\n\tfor (var i=0; i < bspArray.length; i++) {\n\t\tvar split1 = bspArray[i].split('=');\n\t\tshell.branchStartPages.BSPArray[split1[0]] = new Array();\n\t\tshell.branchStartPages.BSPInitArray[split1[0]] = true;\n\t\tvar newArray = new Array();\n\t\tvar branchArray = split1[1].split('!!');\n\t\tfor (var j=0, k=branchArray.length; j<k; j++) {\n\t\t\tvar split2 = branchArray[j].split(\",\");\n\t\t\tvar currBranch = new Object();\n\t\t\tcurrBranch.bsp = split1[1];\n\t\t\tcurrBranch.id = split2[0];\n\t\t\tcurrBranch.trigger = split2[1];\n\t\t\tcurrBranch.isComplete = split2[2];\n\t\t\tnewArray[newArray.length] = currBranch;\n\t\t}\n\t\tshell.branchStartPages.BSPArray[split1[0]] = newArray;\n\t}\n\t//console.log(shell.branchStartPages.BSPArray);\n}", "[createFunctionName('set', collection, false)](object) {\n return setObjectToArray(object, self[collection], findField)\n }", "function saveState () {\n stack.splice(stackPointer);\n var cs = slots.slice(0);\n var ci =[];\n cs.forEach(function(s) {\n ci.push(s.slice(0));\n });\n stack[stackPointer] = [cs, ci];\n }", "function declaracionArrayCTV(ele, mod, ambi) {\n var encontreError = false;\n //BUSCANDO VECTOR EN LOS AMBITOS SI NO ESTA SE REALIZA DECLARACION\n if (!buscarVariable(ele.identificador)) {\n //VERIFICAR EXPRESIONES\n var v = [];\n //console.log(ele);\n //VERIFICANDO TAMAñO DE VECTOR DE VALORES PARA SABER SI ES NECESARIO ASIGNAR VALORES\n if (ele.valor.length > 0) {\n //console.log(\"traigo valores\");\n //AGREGANDO VALORES\n for (var e of ele.valor) {\n var exp = leerExp(e);\n if (e.tipo != \"Error Semantico\") {\n if (ele.tipoDato == exp.tipo) {\n v.push(exp.valor);\n } else {\n encontreError = true;\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error:\n \"Problema al insertar valores que no coinciden con tipo de vector \" +\n exp.valor,\n Fila: ele.fila,\n Columna: 0,\n });\n break;\n }\n } else {\n encontreError = true;\n errorSemantico.push(exp);\n break;\n }\n }\n //SI NO SE ENCONTRO UN ERROR SE HACE LA CREACION DE LA VARIABLE\n if (encontreError == false) {\n insertarAmbito({\n tipo: ele.tipo,\n ambito: rNomAmbito(),\n modificador: mod,\n identificador: ele.identificador,\n tipoDato: ele.tipoDato,\n valor: v,\n fila: ele.fila,\n });\n } else {\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error:\n \"Problema al declarar vector con valores no validos -> \" +\n ele.identificador,\n Fila: ele.fila,\n Columna: 0,\n });\n }\n } else {\n //SI NO ES NECESARIO AGREGAR VALORES\n //console.log(\"no traigo valores\");\n insertarAmbito({\n tipo: ele.tipo,\n ambito: rNomAmbito(),\n modificador: mod,\n identificador: ele.identificador,\n tipoDato: ele.tipoDato,\n valor: v,\n fila: ele.fila,\n });\n }\n } else {\n //SI HAY UNA VARIABLE DECLARADA CON EL MISMO NOMBRE SE REPORTA ERROR\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error: \"variable ya declarada -> \" + ele.identificador,\n Fila: ele.fila,\n Columna: 0,\n });\n }\n}", "restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter];\n return s;\n }", "setFreeSpinsReelsData ( freeSpinReelsData = {}){\n this.getService(\"LinesService\").updateHistory();\n\n this.memory.set(this.getName(\"freespins_ReelsData\"), freeSpinReelsData);\n }", "set(vec) {\n for (var i = 0; i < this.size; i++)\n this.v[i] = vec[i];\n return this;\n }", "function Start () {\n\t//xpoints = new Array(12.0);\n\t//zpoints = new Array(-1.0);\n}", "function editFVSSL()\n{\n //get the original code\n var dom = dw.getDocumentDOM();\n var theObj = dom.getSelectedNode();\n var objectCode = theObj.outerHTML;\n\n //set the variables to be the default for Flash Video\n MM.CalledFromFVSSLPI = true;\n dw.runCommand(\"FlashVideo\");\n MM.CalledFromFVSSLPI = false;\n}", "static flipVector(vec){\n\t\treturn [vec[0] * -1, vec[1] * -1];\n\t}", "stackPush(byte) {\n this.writeRam({ address: 0x0100 + this.cpu.sp, value: byte });\n this.decrementRegister('sp');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
autocomplete div from search bar uses artist.name and artist.images
function createAutoCompleteDiv(artist) { if (!artist) { return; } var val = "<div class='autocomplete-item'>" + "<div class='artist-icon-container'>" + "<img src=" + getSuitableImage(artist.images) + " class='circular artist-icon' />" + "<div class='artist-label'>" + artist.name + "</div>" + "</div>" + "</div>"; return val; }
[ "function searchArtists() {\n\tvar textbox = document.getElementById(\"searchbox-textbox\");\n\tvar listbox = document.getElementById(\"list-box\");\n\n\tvar nameSearched = textbox.value;\n\n\tfor (var i = 0; i < artistNames.length; i++) {\n\t\tif (!artistNames[i].includes(nameSearched)) {\n\t\t\tvar listItem = document.getElementById(artistNames[i]);\n\t\t\tlistItem.style.display = \"none\";\n\t\t}\n\t}\n}", "function displayArtistName(artistName) {\n $(\"#searched-artist\").empty();\n $('#js-error-message').empty();\n $(\"#searched-artist\").append(artistName);\n}", "function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}", "function makeAnyMediaLabelAutocomplete(valueControl,typeControl) { \r\n\t$('#'+valueControl).autocomplete({\r\n\t\tsource: function (request, response) { \r\n\t\t\tvar media_label_val = $('#'+typeControl).val();\r\n\t\t\t$.ajax({\r\n\t\t\t\turl: \"/media/component/search.cfc\",\r\n\t\t\t\tdata: { \r\n\t\t\t\t\tterm: request.term, \r\n\t\t\t\t\tmedia_label: media_label_val, \r\n\t\t\t\t\tmethod: 'getMediaLabelAutocomplete' \r\n\t\t\t\t},\r\n\t\t\t\tdataType: 'json',\r\n\t\t\t\tsuccess : function (data) { response(data); },\r\n\t\t\t\terror : function (jqXHR, status, error) {\r\n\t\t\t\t\tvar message = \"\";\r\n\t\t\t\t\tif (error == 'timeout') { \r\n\t\t\t\t\t\tmessage = ' Server took too long to respond.';\r\n\t\t\t\t\t} else { \r\n\t\t\t\t\t\tmessage = jqXHR.responseText;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmessageDialog('Error:' + message ,'Error: ' + error);\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t},\r\n\t\tselect: function (event, result) {\r\n\t\t\t// on select, set prefix the value with an equals for exact match\r\n\t\t\tevent.preventDefault();\r\n\t\t\t$('#'+valueControl).val(\"=\" + result.item.value);\r\n\t\t},\r\n minLength: 3\r\n\t}).autocomplete(\"instance\")._renderItem = function(ul,item) { \r\n\t\t// override to display meta \"collection name * (description)\" instead of value in picklist.\r\n\t\treturn $(\"<li>\").append(\"<span>\" + item.meta + \"</span>\").appendTo(ul);\r\n\t};\r\n}", "function makeMediaLabelAutocomplete(valueControl,media_label) { \r\n\t$('#'+valueControl).autocomplete({\r\n\t\tsource: function (request, response) { \r\n\t\t\t$.ajax({\r\n\t\t\t\turl: \"/media/component/search.cfc\",\r\n\t\t\t\tdata: { \r\n\t\t\t\t\tterm: request.term, \r\n\t\t\t\t\tmedia_label: media_label, \r\n\t\t\t\t\tmethod: 'getMediaLabelAutocomplete' \r\n\t\t\t\t},\r\n\t\t\t\tdataType: 'json',\r\n\t\t\t\tsuccess : function (data) { response(data); },\r\n\t\t\t\terror : function (jqXHR, status, error) {\r\n\t\t\t\t\tvar message = \"\";\r\n\t\t\t\t\tif (error == 'timeout') { \r\n\t\t\t\t\t\tmessage = ' Server took too long to respond.';\r\n\t\t\t\t\t} else { \r\n\t\t\t\t\t\tmessage = jqXHR.responseText;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmessageDialog('Error:' + message ,'Error: ' + error);\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t},\r\n\t\tselect: function (event, result) {\r\n\t\t\t// on select, set prefix the value with an equals for exact match\r\n\t\t\tevent.preventDefault();\r\n\t\t\t$('#'+valueControl).val(\"=\" + result.item.value);\r\n\t\t},\r\n minLength: 3\r\n\t}).autocomplete(\"instance\")._renderItem = function(ul,item) { \r\n\t\t// override to display meta \"collection name * (description)\" instead of value in picklist.\r\n\t\treturn $(\"<li>\").append(\"<span>\" + item.meta + \"</span>\").appendTo(ul);\r\n\t};\r\n}", "function handleSearchArtistResult(resultData) {\n\t\n\tresultData = jQuery.parseJSON(resultData);\n\t\n\t // Populate the search results\n let searchResultsElement = jQuery(\"#search-results\");\n searchResultsElement.empty();\n \n if(resultData == null || resultData.length == 0)\n \tsearchResultsElement.append(\"<h2>0 Search Results</h2><br><br>\");\n else\n \tsearchResultsElement.append(\"<h2>\" + resultData.length + \" Search Results</h2><br><br>\");\n \n let searchContentElement = $(\"#search-content\");\n searchContentElement.empty();\n searchContentElement.append(\"<thead><tr><th></th><th></th><th></th></tr></thead><tbody>\");\n\n // Iterate through resultData\n for (let i = 0; i < resultData.length; i++) {\n\n // Concatenate the html tags with resultData jsonObject\n let rowHTML = \"\";\n rowHTML += \"<tr>\";\n rowHTML +=\n \"<td>\" +\n '<img src=\"img/band-pic/' + resultData[i][\"id\"] + '.jpg\" class=\"artist-pic\"></td><td>'\n +\n // Add a link to band.html with id passed with GET url parameter\n '<a href=\"artist.html?id=' + resultData[i]['id'] + '\">'\n + resultData[i][\"name\"] + // display star_name for the link text\n '</a>' +\n \"</td>\";\n //rowHTML += \"<td>\" + resultData[i][\"origin\"] + \"</td>\";\n rowHTML += \"</tr>\";\n\n // Append the row created to the table body, which will refresh the page\n searchContentElement.append(rowHTML);\n }\n \n}", "function discog(artist) {\n var apiKey = \"523537\";\n var queryURL =\n \"https://theaudiodb.com/api/v1/json/\" +\n apiKey +\n \"/searchalbum.php?s=\" +\n artist;\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (discResponse) {\n // this for loop iterates through information provided with each album in the discography\n for (i = 0; i < 8; i++) {\n // make variable for album art, year, title, and description\n var albumArt = discResponse.album[i].strAlbumThumb;\n var albumTitle = discResponse.album[i].strAlbum;\n var albumYear = discResponse.album[i].intYearReleased;\n var albumDescription = discResponse.album[i].strDescriptionEN;\n\n var artID = $(\"#coverart\" + i);\n var nameID = $(\"#disc-title\" + i);\n var yearID = $(\"#disc-year\" + i);\n var descriptionID = $(\"#disc-desc\" + i);\n var artID = $(\"#coverart\" + i);\n\n artID.attr(\"src\", albumArt);\n nameID.html(albumTitle);\n yearID.html(albumYear);\n descriptionID.html(albumDescription);\n }\n });\n }", "function tenorCallback_search(responsetext)\n{\n // parse the json response\n var response_objects = JSON.parse(responsetext);\n\n top_10_gifs = response_objects[\"results\"];\n\n // load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)\n\n //document.getElementById(\"preview_gif\").src = top_10_gifs[0][\"media\"][0][\"nanogif\"][\"url\"];\n\n document.getElementById(\"gif\").src = top_10_gifs[0][\"media\"][0][\"tinygif\"][\"url\"];\n\n return;\n\n}", "function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}", "function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}", "chooseArtistImage(data) {\n \tvar imgSrc;\n \tif (data.images.length > 3) {\n imgSrc = data.images[2].url;\n } else if (data.images.length > 1) {\n imgSrc = data.images[0].url;\n } else {\n imgSrc = 'http://placehold.it/45x45';\n };\n return imgSrc;\n }", "function load() {\n var artistsSearched = JSON.parse(localStorage.getItem(\"searches\"));\n // only run if a local storage object is found\n if (artistsSearched) {\n // empty the container before we append\n $(\"#search-items\").empty();\n\n $.each(artistsSearched, function (i) {\n var artist = artistsSearched[i];\n var newP = $(\"<p>\");\n newP.text(artist);\n $(\"#search-items\").append(newP);\n });\n }\n }", "function artistInfo(artist) {\n var artist;\n var apiKey = \"f02edefb391a21cbdfb37796f1e48351\";\n var queryURL =\n \"https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=\" +\n artist +\n \"&api_key=\" +\n apiKey +\n \"&format=json\";\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n $(\"#artist-name\").text(response.artist.name);\n // use split method to trim the response value a bit\n var biography = response.artist.bio.summary.split(\"<\")[0];\n $(\"#artist-bio\").text(biography);\n var similar = response.artist.similar.artist;\n $(\"#lfm-playcount\").text(response.artist.stats.playcount);\n $(\"#lfm-listeners\").text(response.artist.stats.listeners);\n\n // empty the container so we can append\n $(\"#similar-artists\").empty();\n\n // For loop that iterates through artist object to append similar artists\n $.each(similar, function (i) {\n var similarArtist = response.artist.similar.artist[i].name;\n var newLi = $(\"<li>\");\n newLi.addClass(\"sim-artist\");\n newLi.text(similarArtist);\n $(\"#similar-artists\").append(newLi);\n });\n });\n }", "function displayAutocomplete(data) {\t\n\tconst pages = data.query.pages;\n\t\n\t//Create a datalist option for each search item found.\n\tconst searchResultHtml = Object.keys(pages).map( function(key){\n\t\tconst { title } = pages[key];\n\t\treturn html = ` <option value=\"${title}\">${title}</option> `;\n\t});\t\n\t//Put all datalist option search result item in input datalist.\t\n\tsearchDatalist.innerHTML = searchResultHtml.join(\"\");\n}", "function runSearch(){\n filteredObjects = [];\n let names = [];\n const searchValue = document.getElementById('search-input').value;\n for (let i = 0;i<objects.length;i++){\n let name = `${objects[i].name.first} ${objects[i].name.last}`\n name = name.toLowerCase();\n names.push(name);\n }\n\n for(let i = 0; i < names.length; i++){\n if(names[i].includes(searchValue)){\n filteredObjects.push(objects[i])\n }\n }\n \n generateGallery(filteredObjects);\n}", "function renderImagesByKeyword(searchValue) {\n var elImagesContainer = document.querySelector('.images-container');\n var strHtml = '';\n if (gState.renderMode === 'hexagons') {\n strHtml += '<ul id=\"hexGrid\">';\n } else if (gState.renderMode === 'list') {\n strHtml += '<ul class=\"list-images\">';\n }\n var imagesWithKeyword = gImages.filter(function (image) {\n return image.keywords.some(function (keyword) {\n return keyword === searchValue;\n });\n });\n\n imagesWithKeyword.forEach(function (image, imageIndex) {\n\n if (gState.renderMode === 'hexagons') {\n strHtml += '<li class= \"hex\" onclick=\"openMemeEditor(' + image.id +\n ')\"><div class=\"hexIn\"><a class=\"hexLink\" href=\"#\"><img src=\"' +\n image.url + '\" alt=\"\" /><h1>Click</h1><p>To open Editor</p></a></div></li>';\n } else if (gState.renderMode === 'list') {\n strHtml += '<li class=\"list-image\" onclick=\"openMemeEditor(' + image.id + ')\"><img style=\"width:30;height:35px;\" src=\"' + image.url + '\" alt=\"\" /><span>Click on the image to open the meme editor</span></li>';\n }\n });\n\n if (imagesWithKeyword.length == 0) {\n elImagesContainer.innerHTML = '<h4>Sorry but no images were found</h4>';\n } else {\n strHtml +='</ul>';\n elImagesContainer.innerHTML = strHtml;\n }\n}", "function BrowseByName() \n{\n HideListingCriteria();\n $(\"#Language\").attr('selectedIndex', 0);\n $(\"#Genre\").attr('selectedIndex', 0);\n var movieNameToSearch = $(\"#txtName\").val();\n movieCriteria = \"Name\"\n movieCriteriaValue = movieNameToSearch;\n var uri = MOVIE_BY_NAME_URI.replace(\"*name*\", movieNameToSearch);\n BuildMoviesCache(uri)\n startPage = 0;\n FetchTitles(startPage)\n}", "function populateSearchResultsInvite(results, container) \r\n{\r\n\tvar output = '';\r\n\t\r\n\tif (results.length < 1) {\r\n\t\t// No results\r\n\t\toutput += \"<div class='header-search-result dark-back medium'>No results found</div>\";\r\n\t} else {\r\n\t\t// Results found\r\n\t\tvar limit = (results.length > 5 ? 5 : results.length);\r\n\t\tvar src, classy;\r\n\t\t\r\n\t\tif (container.is('#create-userName-results-container')) {\r\n\t\t\t// Add player to reserve list or invite list\r\n\t\t\tclassy = 'create-userName-result';\r\n\t\t} else if (container.is('#invite-alert-results')) {\r\n\t\t\tclassy = 'profile-invite-result';\r\n\t\t}\r\n\t\t\r\n\t\tfor (i = 0; i < limit; i++) {\r\n\t\t\t\t\t\r\n\t\t\toutput += \"<div class='clear \" + classy + \" userName-search-result pointer animate-darker' userID='\" + results[i]['id'] + \"' username = '\" + results[i]['name'] + \"'>\\\r\n\t\t\t\t\t\t\t<img src='/images/users/profile/pic/small/\" + results[i]['id'] + \".jpg' onerror=\\\"this.src='/images/users/profile/pic/small/default.jpg'\\\" class='left' />\\\r\n\t\t\t\t\t\t\t<div class='larger-indent left'>\\\r\n\t\t\t\t\t\t\t\t<p class='larger-text left darkest heavy'>\" + results[i]['name'] + \"</p>\\\r\n\t\t\t\t\t\t\t\t<p class='clear light'>\" + results[i]['city'] + \"</p>\\\r\n\t\t\t\t\t\t\t</div>\\\r\n\t\t\t\t\t\t</div>\";\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tcontainer.html(output);\r\n\t\r\n\tif ($('#inviteSearchBar').is(':focus') && $('#inviteSearchBar').val().length >= 3) {\r\n\t\t// Search bar has focus and val is greater than 2 (protect against accidently overfire due to ajax delay\r\n\t\tcontainer.show();\r\n\t}\r\n\t\r\n\t\r\n}", "function showSuggestions() {\n var v = getNeedle();\n\n if (v.length == 0) {\n box.css('display', 'none');\n return;\n }\n\n suggestions = 0;\n\n box.empty();\n\n options.filters.each(function(i, f) {\n if (suggestions == options.size) {\n return;\n }\n\n list.every(function(o) {\n if (f(options.get(o).toLowerCase(), v)) {\n var li = suggestions++;\n\n box.append($('<div \\>', {\n 'events': {\n 'mousemove': function() { // don't use mouseover since that will bug when the user has the mouse below the input box while typing\n if (!hiding) {\n hover = li;\n showHover();\n }\n }\n }\n }).append(options.render(o)).store('val', o));\n\n if (suggestions == options.size) {\n return false;\n }\n }\n\n return true;\n });\n });\n\n updatePosition();\n\n // If no suggestions, no need to show the box\n if (suggestions > 0) {\n box.css('display', 'block');\n } else {\n box.css('display', 'none');\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects collision between player and different objects that has hitbox.
detectCollisions() { const sources = this.gameObjects.filter(go => go instanceof Player); const targets = this.gameObjects.filter(go => go.options.hasHitbox); for (const source of sources) { for (const target of targets) { /* Skip source itself and if source or target is destroyed. */ if ( source.uuid === target.uuid || source.isDestroyed || target.isDestroyed ) continue; this.checkCollision(source, target); } } }
[ "hitBox(collision){\n\t\tswitch(collision.closestEdge(this.pos.minus(new vec2(this.vel.x, 0)))){\n\t\t\tcase 't': this.hitGround(collision.top()); break;\n\t\t\tcase 'l': this.hitRWall(collision.left()); break;\n\t\t\tcase 'r': this.hitLWall(collision.right()); break;\n\t\t\tcase 'b': this.hitCeiling(collision.bottom()); break;\n\t\t}\n\t}", "function detect_collision(obj1, obj2) {\r\n\tif ((obj1.x + obj1.width > obj2.x) &&\r\n\t\t(obj1.x < obj2.x + obj2.width) &&\r\n\t\t(obj1.y + obj1.height > obj2.y) &&\r\n\t\t(obj1.y < obj2.y + obj2.height)) {\r\n\t\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}", "_setupCollision () {\n this.PhysicsManager.getEventHandler().on(this.PhysicsManager.getEngine(), 'collisionStart', (e) => {\n\n for (let pair of e.pairs) {\n let bodyA = pair.bodyA\n let bodyB = pair.bodyB\n\n if (bodyB === this.body) {\n this.onCollisionWith(bodyA)\n }\n }\n })\n }", "function checkCollisions() {\n\t// check lTraffic\n\tvar numObs = lTraffic.length;\n\tvar i = 0;\n\tfor (i = 0; i < numObs; i++){\n\t\tif (rectOverlap(userCar, lTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check rTraffic\n\tnumObs = rTraffic.length;\n\tfor (i = 0; i < numObs; i++) {\n\t\tif (rectOverlap(userCar, rTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check bottom peds\n\t// TODO check top peds\n}", "isColliding() {\n this.getCorners();\n return Line.isColliding(this.hitboxLines, sceneHitboxLines.filter(line => this.hitboxLines.indexOf(line) === -1));\n }", "checkCollisions() {\n console.log(\n \"Collisions not defined for Agent at x=\"\n + this.pos.x + \", y=\" + this.pos.y);\n }", "function checkCollisions() {\n if (this.collisionWorker != null) {\n collisionWorker.postMessage(JSON.stringify(collideableObjs));\n }\n}", "function checkCollisions() {\n\tvar returner = [];\n\tvar counter=0;\n\tfor (i=0;i<COLLIDABLE_OBJECTS.length;i++) {\n\t\tvar currentObj = COLLIDABLE_OBJECTS[i];\n\t\tif (\t\thero.x+hero.size>currentObj.x && \n\t\t\t\t\thero.x-hero.size<currentObj.x+currentObj.width &&\n\t\t\t\t\thero.y+hero.size>currentObj.y &&\n\t\t\t\t\thero.y-hero.size<currentObj.y+currentObj.height){\n\t\t\treturner[counter]=COLLIDABLE_OBJECTS[i];\n\t\t\tcounter++;\n\t\t}\n\t}\n\treturn returner;\n}", "function collides(obj, obstacles){\n for (var idx in obstacles){\n if (mayCollide(obj, obstacles[idx])) // algoritmo veloce ma soggetto a falsi positivi\n if (reallyCollides(obj, obstacles[idx])) // algoritmo lento ma preciso\n return idx; // collisione!\n }\n // Nessuna collisione\n return -1;\n}", "collide(rect) {\n return (this.left < rect.right && this.right > rect.left &&\n this.top < rect.bottom && this.bottom > rect.top);\n }", "function checkEnergyCollision() {\r\n energies.forEach(function (e) {\r\n if ((player.X < e.x + energyRadius) &&\r\n (player.X + player.width > e.x) &&\r\n (player.Y < e.y + energyRadius) &&\r\n (player.Y + player.height > e.y)) {\r\n e.onCollide();\r\n //startSound();\r\n }\r\n })\r\n}", "function collide(a, b) {\n\n // Find the distance between the balls\n let dx = b.x - a.x;\n let dy = b.y - a.y;\n let distance = Math.sqrt(dx * dx + dy * dy);\n\n // Check for a collision\n if (distance < a.size + b.size) {\n\n // Find the unit vectors \n let ux = dx / distance;\n let uy = dy / distance;\n\n // Multiply the collided balls' velocities by \n // the unit vector and repulsion factor\n a.vx -= ux * REPULSION;\n a.vy -= uy * REPULSION;\n b.vx += ux * REPULSION;\n b.vy += uy * REPULSION;\n }\n} // end collide", "isCollide(potato) {\n\n\n // Helper Function to see if objects overlap\n const overLap = (objectOne, objectTwo) => {\n\n // Check X-axis if they dont overlap\n if (objectOne.left > objectTwo.right || objectOne.right < objectTwo.left) {\n return false;\n }\n // Check y-axis if they dont overlap\n // 100 \n // 200 ObjectTwo Bottom\n // 300 ObjectOne Top\n if (objectOne.top > objectTwo.bottom || objectOne.bottom < objectTwo.top) {\n return false;\n }\n return true;\n }\n\n let collision = false;\n\n this.eachObject((object) => {\n if (overLap(object, potato)) {\n collision = true\n }\n\n });\n\n return collision\n\n\n }", "checkCollision(lookupID, category){\n //find the hitbox\n var hitbox = this.getHitbox(lookupID)\n\n //compare against category\n return hitbox.checkCollision(this.hitboxCategories[category]);\n }", "function updateCollisions() {\n GeometrySplit.game.physics.arcade.collide(players, blockedLayer);\n GeometrySplit.game.physics.arcade.collide(players, moveableLayer1);\n GeometrySplit.game.physics.arcade.collide(players, moveableLayer2);\n GeometrySplit.game.physics.arcade.collide(players, players, (p1, p2) => {\n if(p1 === p2) {\n return;\n }\n if(Math.abs(p1.width - p2.width) < 1 && Math.abs(p1.y - p2.y) < 1){\n merge(p1, p2);\n } else if(currentPlayer === p1 || currentPlayer === p2) {\n setLocks(p1, p2);\n }\n });\n players.forEach(function (p){\n \thazards.forEach(function (h){\n \t\tif (p.overlap(h))\n \t\t{\n \t\t\tif (p.right > h.left)\n \t\t\t{\n \t\t\t\tif(p.bottom > h.top)\n \t\t\t\t{\n \t\t\t\t\tGeometrySplit.game.state.restart();\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t});\n });\n // maybe remove this part once spawning is improved?\n GeometrySplit.game.physics.arcade.overlap(players, players, (p1, p2) => {\n if(p1 === p2 || !(p1.body.touching.right || p1.body.touching.left)) {\n return;\n }\n if(p1.body.x < p2.body.x) {\n p2.body.x = p1.body.x + p1.width + 1;\n } else {\n p1.body.x = p2.body.x + p2.width + 1;\n }\n });\n}", "collide(other) {\n // Don't collide if inactive\n if (!this.active || !other.active) {\n return false;\n }\n\n // Standard rectangular overlap check\n if (this.x + this.width > other.x && this.x < other.x + other.width) {\n if (this.y + this.height > other.y && this.y < other.y + other.height) {\n return true;\n }\n }\n return false;\n }", "function playerShipAndEnemyCollisionDetection(elapsedTime){\r\n\t\tvar xDiff = myShip.getSpecs().center.x - enemyShip.getSpecs().center.x;\r\n\t\tvar yDiff = myShip.getSpecs().center.y - enemyShip.getSpecs().center.y;\r\n\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff));\r\n\r\n\t\tif(distance < myShip.getSpecs().radius + enemyShip.getSpecs().radius){\r\n\t\t\t\r\n\t\t\tparticleGenerator.createShipExplosions(elapsedTime,myShip.getSpecs().center);\r\n\r\n\t\t\tmyShip.getSpecs().hit = true;\r\n\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t}\r\n\t}", "function checkCollision(n1, n2){\r\n p1 = getPlayer(n1);\r\n p2 = getPlayer(n2);\r\n if(n1 != n2)\r\n var d0 = Math.sqrt( ((p1.cx - p2.cx)*(p1.cx - p2.cx)) +\r\n ((p1.cy - p2.cy)*(p1.cy - p2.cy)))\r\n\r\n var len = p1.trail.length;\r\n if(n1 === n2) len = len-10;\r\n for(var i = 0; i < len; i++){\r\n var pos = p1.trail[i];\r\n var d = Math.sqrt( ((pos.cx - p2.cx)*(pos.cx - p2.cx)) +\r\n ((pos.cy - p2.cy)*(pos.cy - p2.cy)))\r\n\r\n if(d < 5 || d0 < 5 && p2.dead === false){\r\n\r\n if(p2.dead === false && p2.number < 5) endingSoundEffects[selectedplayers[n2-1]].play();\r\n if(p2.dead === false && p2.number === 5) endingSoundEffects[selectedplayers[0]].play();\r\n p2.halt();\r\n p2.dead = true;\r\n console.log(\"Player \" + n2 + \" hit player \" + n1 + \"'s trail!\");\r\n\r\n }\r\n\r\n }\r\n\r\n}", "function cannonBallsHitEdgeOfCanvas(cannonBall){\n let hadCollision = false;\n if(cannonBall.x - cannonBall.radius < stageX){\n //Left edge collision\n cannonBall.x = stageX + cannonBall.radius;\n cannonBall.vx *= -1;\n hadCollision = true;\n }else if(cannonBall.x + cannonBall.radius > stageX + stageWidth){\n //Right edge collision\n cannonBall.x = (stageX + stageWidth) - cannonBall.radius;\n cannonBall.vx *= -1;\n hadCollision = true;\n }else if(cannonBall.y - cannonBall.radius < stageY){\n //Top edge collision\n cannonBall.y = stageY + cannonBall.radius;\n cannonBall.vy *= -1;\n hadCollision = true;\n }else if(cannonBall.y + cannonBall.radius > stageY + stageHeight){\n //Bottom edge collision\n cannonBall.y = (stageY + stageHeight) - cannonBall.radius;\n cannonBall.vy *= -1;\n hadCollision = true;\n }\n\n if(hadCollision){\n if(!gamePaused && new Date() - lastClink > 50){\n playAudio(clinkSFX, 0.3);\n lastClink = new Date();\n } \n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show/hide all fields needed for not modifying a module
function disableeditfields(moduleid) { Element.addClassName('editmodulenavtype_' + moduleid, 'z-hide'); Element.addClassName('editmoduleenablelang_' + moduleid, 'z-hide'); Element.addClassName('editmoduleaction_' + moduleid, 'z-hide'); Element.addClassName('editmoduleexempt_' + moduleid, 'z-hide'); Element.removeClassName('modulenavtype_' + moduleid, 'z-hide'); Element.removeClassName('moduleenablelang_' + moduleid, 'z-hide'); Element.removeClassName('moduleaction_' + moduleid, 'z-hide'); Element.removeClassName('moduleexempt_' + moduleid, 'z-hide'); if(allownameedit[moduleid] == true) { Element.addClassName('editmodulename_' + moduleid, 'z-hide'); Element.removeClassName('modulename_' + moduleid, 'z-hide'); } }
[ "function enableeditfields(moduleid)\n{\n Element.addClassName('modulenavtype_' + moduleid, 'z-hide');\n Element.addClassName('moduleenablelang_' + moduleid, 'z-hide');\n Element.addClassName('moduleaction_' + moduleid, 'z-hide');\n Element.addClassName('moduleexempt_' + moduleid, 'z-hide');\n Element.removeClassName('editmodulenavtype_' + moduleid, 'z-hide');\n Element.removeClassName('editmoduleenablelang_' + moduleid, 'z-hide');\n Element.removeClassName('editmoduleaction_' + moduleid, 'z-hide');\n Element.removeClassName('editmoduleexempt_' + moduleid, 'z-hide');\n if(allownameedit[moduleid] == true) {\n Element.addClassName('modulename_' + moduleid, 'z-hide');\n Element.removeClassName('editmodulename_' + moduleid, 'z-hide');\n }\n}", "function citruscartHideBillingFields() {\n\t$('billingToggle_show').set('class', 'hidden');\n\n\t$('field-toggle').addEvent('change', function() {\n\t\t///$$('#billingDefaultAddress', '#billingToggle_show', '#billingToggle_hide').toggleClass('hidden');\n\t\tdocument.getElementById('billingDefaultAddress').toggleClass('hidden');\n\t\tdocument.getElementById('billingToggle_show').toggleClass('hidden');\n\t\tdocument.getElementById('billingToggle_hide').toggleClass('hidden');\n\t\t\n\t});\n}", "function showinfo(moduleid, infotext)\n{\n if(moduleid) {\n var moduleinfo = 'moduleinfo_' + moduleid;\n var module = 'modulecontent_' + moduleid;\n if(!Element.hasClassName(moduleinfo, 'z-hide')) {\n Element.update(moduleinfo, '&nbsp;');\n Element.addClassName(moduleinfo, 'z-hide');\n Element.removeClassName(module, 'z-hide');\n } else {\n Element.update(moduleinfo, infotext);\n Element.addClassName(module, 'z-hide');\n Element.removeClassName(moduleinfo, 'z-hide');\n }\n } else {\n $A(document.getElementsByClassName('z-moduleinfo')).each(function(moduleinfo){\n Element.update(moduleinfo, '&nbsp;');\n Element.addClassName(moduleinfo, 'z-hide');\n });\n $A(document.getElementsByClassName('modulecontent')).each(function(modulecontent){\n Element.removeClassName(modulecontent, 'z-hide');\n });\n }\n}", "function disableEditing() {\n disableForm(true);\n}", "function hidePaymentOptions() {\n // loop through paymentOptions object and set display to none\n for (prop in paymentOptions)\n toggleView(paymentOptions[prop], false);\n }", "function enableFieldsForSubmit(theform) {\r\n var elems = theform.elements;\r\n\r\n for (var i = 0; i < elems.length; i++) {\r\n if (elems[i].disabled) {\r\n elems[i].style.visibility = \"hidden\";\r\n elems[i].disabled = false;\r\n }\r\n }\r\n}", "displayAdmin() {\n let add_form = document.getElementById(\"add_form\");\n add_form.classList.toggle(\"hidden\");\n \n let delete_btns = document.querySelectorAll(\".delete_btn\");\n delete_btns.forEach(function(item){\n item.classList.toggle(\"hidden\");\n })\n\n let edit_btns = document.querySelectorAll(\".edit_btn\");\n edit_btns.forEach(function(item){\n item.classList.toggle(\"hidden\");\n }) \n //disable sort function when inside admin, to avoid bugg.\n this.sort_btn.disabled = !this.sort_btn.disabled; \n }", "_hideFormElements()\r\n {\r\n $(this.el).find('#filter-inputs div input').val('');\r\n $(this.el).find('#filter-inputs div select').val('');\r\n $(this.el).find('#filter-inputs').children().hide();\r\n }", "function show_hide_partner(obj,show_section)\n{\n}", "function showProperties() {\r\n document.getElementById(\"simulationView\").style.display = \"none\";\r\n document.getElementById(\"propertiesInput\").style.display = \"block\";\r\n}", "function IsHidden(){\n\treturn !_showGizmo;\n}//IsHidden", "function disableEditingOptionViewForStudentID(id) {\n\n // Hide edit links\n $(`#${uniqueIDPrefix}options${id} .on-edit-show div`)\n .removeAttr('class', 'is-editable')\n .attr('class', 'edit-content-hidden');\n\n // Show the options button\n $(`#${uniqueIDPrefix}options${id} .on-hover-show button`).removeAttr('class', 'edit-content-hidden');\n $(`#${uniqueIDPrefix}options${id} .on-hover-show div.edit-content-hidden`).attr('class', 'dropdown-content');\n\n\n}", "function hideModule() {\n\t\t// Setting common.naclModule.style.display = \"None\" doesn't work; the\n\t\t// module will no longer be able to receive postMessages.\n\t\tcommon.naclModule.style.height = '0';\n\t}", "function disableEditingNameViewForStudentID(id) {\n\n // Show the specific table cell\n $(`#${uniqueIDPrefix}name${id} span`).removeAttr('class', 'edit-content-hidden');\n\n // Access and destroy the input\n $(`#${uniqueIDPrefix}input-name${id}`).remove();\n\n}", "function showLoginInfo (){\n var LoginBtn = $(\"#firstLoginBtn\");\n LoginBtn.hide();\n\n // var SignUp = $(\"#Sign-upBtn\");\n // SignUp.hide();\n\n loginField.show();\n}", "function hideKeyElements() {\n $(\"#input-container\").css({ display: \"none\" });\n $(\"#feedback-placeholder\").css({ display: \"none\" });\n $(\"#card-button-container-1\").css({ display: \"none\" });\n $(\"#firebaseui-auth-container\").css({ display: \"\" });\n}", "function formDisplayStatus () {\n $(\".js-resource_field\").each(function () {\n if (($(this).val().length >= 1) || ($(this).text().length >= 1)) {\n $(this).closest(\".js-resource_form_section\").find(\".js-title_right\").hide();\n $(this).closest(\".js-resource_form_section\").find(\".js-success_display\").show();\n } else {\n $(this).closest(\".js-resource_form_section\").find(\".js-title_right\").show();\n $(this).closest(\".js-resource_form_section\").find(\".js-success_display\").hide();\n }\n });\n }", "function hideInputs() {\n var selectedDistribution = jQuery(\"#distribution\").val();\n for (inputName in fEnableObj) {\n var inputField = jQuery(`input[name='${inputName}']`);\n if (fEnableObj[inputName] === selectedDistribution)\n inputField.parent(\"label\").removeClass(\"hidden\");\n else\n inputField.parent(\"label\").addClass(\"hidden\");\n }\n if (selectedDistribution === \"parcel\") {\n jQuery(\"#geometry-box\").prop(\"checked\", true);\n jQuery(\"select#geometry\").attr(\"disabled\", true);\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n } else {\n jQuery(\"select#geometry\").attr(\"disabled\", false)\n if (jQuery(\"#geometry\").val() == \"box\") {\n jQuery(\".inputfield.maxsize\").removeClass(\"hidden\");\n } else {\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n }\n }\n}", "function showhidehelp() {\n\tif (showhelp == false) {\n\t\tshowhelp = true;\n\t\tdocument.getElementById('helpinfo').style.display = 'block';\n\t} else {\n\t\tshowhelp = false;\n\t\tdocument.getElementById('helpinfo').style.display = 'none';\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Minimizar la ventana actual
function minimizar() { var win = remote.getCurrentWindow() win.minimize(); }
[ "actualizarCuota () {\n this.interesMensual = this.interes / 1200;\n this.factorFunc();\n this.cuotaFunc();\n }", "function actualizarVentanaMesero(){\n\tswitch(navegarMesero){\n\t\tcase 1: //Se en cuentra en la ventana 1\n\t\t\tnavegar(1);\n\t\tbreak;\n\t\tcase 3:\n\t\t\tnavegar(3);\n\t\tbreak;\n\t}\n}", "function bajarPlanta() {\n if (pisoActual > pisoMin) {\n removeFloors(pisoActual);\n removeMeasuresLayer();\n pisoActual--;\n addMeasuresLayer(pisoActual);\n addFloors(pisoActual);\n floors.addTo(map);\n }\n}", "function restartuj() {\n\n\t\tnivo = -1; //nivo se vraca na pocetak\n\t\t$('.trenutno').removeClass('trenutno'); //elementu koji u datom momentu ima klasu 'trenutno' uklonjena je ta klasa\n\t\t$('.skala li:last').addClass('trenutno'); //klasa trenutno se postavlja na posljednji element u skali\n\t\tiznos = '0 KM'; //iznos se vraca na pocetak\n\t\t$('.osvojeno').text(iznos); //osvojeni iznos se vraca na pocetak\n\t\tiducePitanje(); //poziva se funkcija koja postavlja iduce pitanje\n\t\trestartOkvir.hide(); //okvir za restartovanje se uklanja sa ekrana\n\t\t//dugmadima za jokere se uklanja klasa iskoristeno i ponovno im se postavlja event-handler\n\t\tpolaPola.removeClass('iskoristeno');\n\t\tpolaPola.on('click', polaPolaFunkcija);\n\t\tpublika.removeClass('iskoristeno');\n\t\tpublika.on('click', publikaFunkcija);\n\n\t}", "function minimizeDailyReward(){\r\n var startup, daily_reward_minimized = false, town_window = false;\r\n startup = new MutationObserver(function(mutations) {\r\n mutations.forEach(function(mutation) {\r\n if(mutation.addedNodes[0]){\r\n if($('#new_daily_reward').get(0) && !uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_SHOW_ON_LOGIN).isMinimized()){\r\n uw.GPWindowMgr.getOpenFirst(uw.Layout.wnd.TYPE_SHOW_ON_LOGIN).minimize();\r\n }\r\n }\r\n }); \r\n });\r\n startup.observe($('body').get(0), { attributes: false, childList: true, characterData: false});\r\n \r\n setTimeout(function(){ startup.disconnect();}, 3000);\r\n}", "function calcular_si_mueve(element, partes) {\n switch (puzzleElegido){\ncase \"south_park\": comprovarGanado(partes, array_south_park); break;\ncase \"peter\": comprovarGanado(partes, array_peter_partido); break;\ncase \"homer\": comprovarGanado(partes, array_homer_partido); break;\ncase \"stan \": comprovarGanado(partes, erased_value_stan); break;\n }\n \n var valor_element = element.getBoundingClientRect();\n var vacio = document.getElementById(\"vacio\");\n\n\n var valor_vacio = vacio.getBoundingClientRect();\n\n if (\n seTocanAbajo(valor_element, valor_vacio, element, vacio) ||\n seTocanArriba(valor_element, valor_vacio, element, vacio) ||\n seTocanDerechaNormal(valor_element, valor_vacio, element, vacio) ||\n seTocanIzquierda(valor_element, valor_vacio, element, vacio)\n ) {\n\n var valor_anterior = Number(document.getElementById(\"mov\").innerHTML);\n document.getElementById(\"mov\").innerHTML = valor_anterior + 1;\n\n } else {\n\n flash(element.getAttribute(\"name\"))\n\n }\n\n\n}", "function ksfHelp_mainTourBegin()\n{\n\tif(ksfHelp_mainTour.ended())\n\t{\n\t\tksfHelp_mainTour.restart();\n\t}\n\tksfHelp_mainTourResize();\n}", "function actualizar_gal_a(gal,id_ruta,id_depto,id_solicitud,restante,resto,motivo){\n \n\n var actual=resto - gal;\n\n if (actual < 0) {\n \n\n alert('No tiene suficiente galones disponibles, Debe colocar cantidad galones a 0 para actualizar valor de galonaje disponible.');\n \n }else{\n ///////////////////////////////////\n $.ajax({\n url: \"../../operativo/models/solicitud_cantgalones.php\",\n type:\"POST\",\n dataType:'html',\n data:{gal:gal,id_ruta:id_ruta,id_depto:id_depto,id_solicitud:id_solicitud},\n success: function(data){\n solicitud_editable(id_solicitud); \n }\n })\n ///////////////////////////////\n document.getElementById('aviso').style.display='none'\n \n }\n \n }", "function movimentaBolinha(){\n xbolinha += velocidadeXbolinha;\n ybolinha += velocidadeYbolinha;\n}", "function siguienteMes(){\n if (numeroMes !== 11){\n numeroMes++;\n }else{\n numeroMes=0;\n anioCorriente++;\n }\n\n setearFechaNueva();\n}", "function animacionGmOver() {\n\tconsole.log(\"Perdiste AMEEEEO!!\");\n}", "function masUnAcierto(){\n\taciertosAcumulados++;\n\tdibujar();\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 pintar(simulacion){\r\n\r\n\t\tlimpiar();\r\n\t\tpintarAgua(simulacion);\r\n\t\tpintarAlcantarillado(simulacion);\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n}", "function ultimaPagina(){\n\tif(pagina_actual!=paginas_totales){\n\t\tpagina_actual=paginas_totales;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\t\n\t\tlet pagina = paginas_totales-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}", "mine(creep){\n var clossestSource = this.getClosestEnergySource(creep);\n if(creep.carry.energy < creep.carryCapacity) {\n if(creep.harvest(clossestSource) == ERR_NOT_IN_RANGE) {\n if (creep.memory.Mining){\n creep.memory.Mining = false;\n }\n creep.moveTo(clossestSource, {visualizePathStyle: {stroke: '#ffaa00'}});\n\n }else{\n if (!creep.memory.Mining && creep.harvest(clossestSource) == OK){\n creep.memory.Mining = true;\n console.log(\"plus\"+creep);\n Memory[clossestSource.id].currentHarvesters += 1;\n }\n } \n return 0; \n } else{\n if(creep.memory.Mining){\n creep.memory.Mining = false;\n console.log(\"minus\"+ creep);\n Memory[clossestSource.id].currentHarvesters -= 1;\n\n }\n return 1;\n }\n\n }", "function ksfHelp_mainTourResize()\n{\n\tif(ksfHelp_mainTour.ended() == false)\n\t{\n\t\tvar browserWidth = $(window).width();\n\t\tvar currentStep = ksfHelp_mainTour.getCurrentStep();\n\t\tif(browserWidth <= LAYOUT_WIDTH_THRESHOLD)\n\t\t{\n\t\t\tif((currentStep % 2) == 0)\n\t\t\t{\n\t\t\t\tcurrentStep += 1;\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif((currentStep % 2) == 1)\n\t\t\t{\n\t\t\t\tcurrentStep -= 1;\n\t\t\t}\n\t\t}\n\t\tksfHelp_mainTour.setCurrentStep(currentStep);\n\t\tksfHelp_mainTour.goTo(currentStep);\n\t}\n}", "function cicloPrincipal(){\r\n\t\tpasado=actual;\r\n\t\tactual=new Date().getTime()/1000;\r\n\t\t//Se actualiza cada segundo (temporal)\r\n\t\tif( Math.floor(actual-tiempo)%300===0 && Math.floor(actual-tiempo) !== 0){\r\n\t\t\tincrementarRacha();\r\n\t\t}\r\n\t\tactualizarDinero();\r\n\t\tgetID(\"tiempo\").innerHTML = \"Tiempo de juego: \" + time(tiempo);\r\n\t\tcpsActual = cps*racha.toFixed(1);\r\n\t\tdineroTotal += cpsActual;\r\n\t\tdineroActual += cpsActual;\r\n\t\tpasado = new Date().getTime()/1000;\r\n\r\n\t\tif( jugadorActivo() === false ){ \r\n\r\n\t\t\tvar resp = confirm(\"Jugador inactivo\");\r\n\r\n\t\t\tif(resp || !resp){\r\n\t\t\t\treinicio();\r\n\t\t\t}\r\n\t\t\t//reiniciar juegoS\r\n\t\t}\r\n\t\t//alert(Math.floor(actual-tiempo));\r\n\r\n\t\tsetTimeout(cicloPrincipal,1000);\r\n\t}", "function primeraPagina(){\n\tif(pagina_actual!=1){\n\t\t\n\t\tpagina_actual = 1;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\tlet pagina = pagina_actual-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
details: reset all hold modal state to default
function resetHoldModalState() { setConfirm(false) setHold(false) setHoldReason(null) }
[ "function handleDetailReset(){\n cnDetailForm.reset()\n returnBtn()\n}", "function f_resetAll(){\n fdoc.find('.spEdit').removeAttr('contenteditable').removeClass('spEdit');\n fdoc.find('.targetOutline').removeAttr('contenteditable').removeClass('targetOutline');\n fdoc.find('#ipkMenu').hide();\n fdoc.find('.ipkMenuCopyAnime').removeClass('ipkMenuCopyAnime');\n $('.sp-show-edit-only-place').css('opacity','0.2');\n f_resetHiddenBox();\n }", "function resetAllEvents(){\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.gotoAndStop(0);\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t\tev.choosen = false; \n\t\t\t});\n\t\t\t// update instructions\n\t\t\tself.instructions.gotoAndStop(0);\n\t\t\t// update side box\n\t\t\tself.sideBox.gotoAndStop(0);\n\t\t}", "reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}", "function resetModal() {\n tipo.value = '';\n nombre.value = '';\n dueno.value = '';\n indiceOculto.value = '';\n botonGuardar.innerHTML = 'Crear'\n}", "function resetReportModal(){\n\t\n\ttoggleErrorMessage(\"#report_filter_criteria\", true, \"\");\n\t\n\t$('#account_created_period_error_text').attr('style', \"display: none;\");\n\t$('#account_created_range_error_text').attr('style', \"display: none;\");\n\t$('#report_format_error_text').attr('style', \"display: none;\");\n\t\n\t//Unchecking the account created radio button period\n\ttoggleIcheckBox('#accountCreatedPeriodRadio', false);\n\t\n\t//Setting the default select\n\tresetSelect(\"#selectRange1Value\");\n\tdisableField(\"#selectRange1Value\");\n\t\n\t//Unchecking the account created radio button range\n\ttoggleIcheckBox('#accountCreatedRangeRadio', false);\n\t\n\t//Reset Datepicker\n\tresetDatePicker(\"#date-picker-start\");\n\tresetDatePicker(\"#date-picker-end\");\n\tdisableField(\"#date-picker-start\");\n\tdisableField(\"#date-picker-end\");\n\t\n\t//Unchecking the no account information and no category description\n\ttoggleIcheckBox('#noAccountInformation', false);\n\ttoggleIcheckBox('#noCatagoryDescription', false);\n\n\t//Setting the default select\n\tresetSelect(\"#managerReportFormatSelect\");\n}", "function resetAlert() {\n alertify.set({\n labels : {\n ok : \"OK\",\n cancel : \"Cancel\"\n },\n delay : 5000,\n buttonReverse : false,\n buttonFocus : \"ok\"\n });\n }", "function initializeModal()\n{\n\t_gel('searchableMetadata').value= \"\";\n\t_gel('meetingHeader').value= \"\";\n\t_gel('participantsInOffice').value= \"\";\n\t_gel('participantsOverCall').value= \"\";\n\t_gel('agenda').value= \"\";\n\t_gel('notes').innerHTML= \"\";\n\t_gel('urgentActionItems').innerHTML= \"\";\n\t_gel('taskAllocations').innerHTML= \"\";\n\t_gel('timelineOfDeliverables').innerHTML= \"\";\n}", "function resetPopup() {\n\tnewEventNameInput.value = \"\";\n\thrSelect.value = \"hr\";\n\tminSelect.value = \"min\";\n\tampmSelect.value = \"am\";\n\tcategorySelect.value = \"none\";\n\tcreateEventBtn.style.display = \"inline-block\";\n\teditEventBtn.style.display = \"none\";\n\tdeleteEventBtn.style.display = \"none\";\n\tshareEventInput.value = \"\";\n\tshareEventInput.style.display = \"none\";\n\tshareEventBtn.style.display = \"none\";\n\terrormessage.textContent = \"[error message]\";\n\terrormessage.style.display = \"none\";\n}", "function onClickReset() {\r\n cleanInputs();\r\n resetFieldsUi();\r\n}", "function bringToStatic() {\n modalState = \"static\";\n // hide form elements\n ingredientsForm.style.display = \"none\";\n preparationForm.style.display = \"none\";\n // show modal elements\n ingredients.style.display = \"block\";\n preparation.style.display = \"block\";\n // reset btn text\n editBtn.textContent = \"Edit\";\n}", "function _resetIssuesUI() {\n var $noIssues = $issuesWrapper.find(\".no-issues\"),\n $noGithub = $issuesWrapper.find(\".no-github\"),\n $errors = $issuesWrapper.find(\".errors\"),\n $state = $issuesPanel.find(\".issue-state\"),\n $assignee = $issuesPanel.find(\".issue-assignee\");\n \n $issuesWrapper.removeClass(\"loading\");\n $noIssues.addClass(\"hide\");\n $noGithub.addClass(\"hide\");\n $errors.addClass(\"hide\");\n $state.addClass(\"disabled\");\n $assignee.addClass(\"disabled\");\n \n $issuesList.empty();\n }", "function guessClearResetButtonsOff() {\n guessButton.disabled = false;\n clearButton.disabled = false;\n resetButton.disabled = false;\n }", "function resetForm() {\n $leaveComment\n .attr('rows', '1')\n .val('');\n $cancelComment\n .closest('.create-comment')\n .removeClass('focused');\n }", "function resetForms(){\r\n $('.user-col form').attr('data-mode', 'working');\r\n // $('.user-col fieldset, .user-col textarea').addClass('untouched');\r\n $('.pairwise-decision, .pairwise-guidelines').addClass('untouched');\r\n // $('.pairwise-reasoning').removeClass('untouched')\r\n $('.user-col input').prop('checked', false);\r\n $('.user-col textarea').val('');\r\n}", "hideAcceptGameModal() {\n // Hide modal\n this.setState({ showAcceptModal: false })\n }", "closeDetails() {\n this.setDetailsView(0);\n }", "function resetForm() {\n setInputs(initial);\n }", "function resetEditedNote() {\n vm.isEditingNote = false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply constraints to a point. These constraints are both physical along an axis, and an elastic factor that determines how much to constrain the point by if it does lie outside the defined parameters.
function applyConstraints(point, _a, elastic) { var min = _a.min, max = _a.max; if (min !== undefined && point < min) { // If we have a min point defined, and this is outside of that, constrain point = elastic ? (0,popmotion__WEBPACK_IMPORTED_MODULE_0__.mix)(min, point, elastic.min) : Math.max(point, min); } else if (max !== undefined && point > max) { // If we have a max point defined, and this is outside of that, constrain point = elastic ? (0,popmotion__WEBPACK_IMPORTED_MODULE_0__.mix)(max, point, elastic.max) : Math.min(point, max); } return point; }
[ "function biasedPoint(point, normal, bias) {\n return vec3.add(vec3.create(), point, vec3.scale(vec3.create(), normal, bias));\n}", "_applyScale(point) {\n let scale = this.getScale()\n return {\n x: point.x * scale,\n y: point.y * scale,\n z: point.z * scale,\n }\n }", "applyFriction(){\n\t\tthis.vel.x *= ((0.8 - 1) * dt) + 1;\n\t}", "function applyMinimapGravity(pointWorld, pointVisual, planets, w, h, scale, cameraPos) {\n let visual = { x: pointVisual.x, y: pointVisual.y };\n\n let gravityDominator = planets[0];\n let gravity = null;\n\n for (let k = planets.length - 1; k >= 0; k--) {\n let g = applyGravity(planets[k], pointWorld);\n let gMag = V.magnitude(g);\n if (gravity === null || gravity < gMag) {\n gravityDominator = planets[k];\n gravity = gMag;\n }\n visual.x += g.x * MINIMAP_G_FACTOR;\n visual.y += g.y * MINIMAP_G_FACTOR;\n }\n\n let visualWorldPoint = makeWorldPoint(visual, w, h, scale, cameraPos);\n return limitGravityLine(pointWorld, visualWorldPoint, gravityDominator);\n}", "enactPhysics(physObj)\r\n {\r\n if(!physObj.ignoreGravity) {\r\n let dV = Vector2.scale(this.deltaTime, this.physics.gravity);\r\n physObj.velocity = Vector2.sum(dV, physObj.velocity);\r\n }\r\n\r\n let dP = Vector2.scale(this.deltaTime, physObj.velocity);\r\n physObj.position = Vector2.sum(dP, physObj.position);\r\n }", "function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}", "function b2ManifoldPoint()\n{\n\tthis.localPoint = new b2Vec2();\t\t///< usage depends on manifold type\n\tthis.normalImpulse = 0;\t\t\t\t///< the non-penetration impulse\n\tthis.tangentImpulse = 0;\t\t\t///< the friction impulse\n\tthis.id = new b2ContactID();\t\t///< uniquely identifies a contact point between two shapes\n}", "applyConstraints(props) {\n // Ensure zoom is within specified range\n const {\n maxZoom,\n minZoom,\n zoom\n } = props;\n props.zoom = Object(_math_gl_core__WEBPACK_IMPORTED_MODULE_0__[\"clamp\"])(zoom, minZoom, maxZoom);\n const {\n longitude,\n latitude\n } = props;\n\n if (longitude < -180 || longitude > 180) {\n props.longitude = Object(_utils_math_utils__WEBPACK_IMPORTED_MODULE_3__[\"mod\"])(longitude + 180, 360) - 180;\n }\n\n props.latitude = Object(_math_gl_core__WEBPACK_IMPORTED_MODULE_0__[\"clamp\"])(latitude, -89, 89);\n return props;\n }", "function createConstraint()\n\t\t{\n\t\t\tconstraint.css({\n\t\t\t\tleft : -(map.width()) + viewport.width(),\n\t\t\t\ttop : -(map.height()) + viewport.height(),\n\t\t\t\twidth : 2 * map.width() - viewport.width(),\n\t\t\t\theight : 2 * map.height() - viewport.height()\n\t\t\t});\n\t\t\t// Check if map is currently out of bounds, revert to closest position if so\n\t\t\tif(map.position().left < constraint.position().left) map.css('left',constraint.position().left);\n\t\t\tif(map.position().top < constraint.position().top) map.css('top',constraint.position().top);\n\t\t}", "set useFriction(value) {}", "function projectPointOntoSegment(px, py, vx, vy, wx, wy) {\n var l2 = dist2(vx, vy, wx, wy);\n if (l2 === 0) return new Point(vx, vy);\n \n var t = ((px - vx) * (wx - vx) + (py - vy) * (wy - vy)) / l2;\n if (t < 0) return new Point(vx, vy);\n if (t > 1) return new Point(wx, wy);\n return new Point( vx + t * (wx - vx),\n vy + t * (wy - vy));\n}", "function left_wall_force(pos_x, radius, elastic_constant=constant.elastic) {\r\n let edge_at = pos_x - radius\r\n if (edge_at < 0) {\r\n return Math.abs(edge_at) * elastic_constant\r\n }\r\n return 0\r\n}", "function Constraint(vtx1, vtx2)\n{\n this.vtx1 = vtx1;\n this.vtx2 = vtx2;\n this.length = VERTEX_MARGIN;\n}", "update(x,y){\n\n if (x > 0 & x < width){\n if(y > 0 & y < height/2){\n //if(!this.nearWall()){\n this.pos.x= x;\n this.pos.y= y;\n for (var i = 0; i < this.rays.length;i++) {\n this.rays[i].update(this.pos)\n let rmagold = Infinity;\n for(let bound of bounds){\n let rmag = bound.intersect(this.rays[i].pos,this.rays[i].dir);\n if(rmag < rmagold) rmagold = rmag;\n }\n this.rays[i].mag = rmagold;\n }\n //}\n }\n }\n }", "centreOn() {\r\n let mx, my;\r\n if (typeof arguments[0] === \"number\" && typeof arguments[1] === \"number\") {\r\n mx = constrain(arguments[0], 0, this.SIZE - 1);\r\n my = constrain(arguments[1], 0, this.SIZE - 1);;\r\n } else if (typeof arguments[0] === \"string\") {\r\n if ((arguments[0].toLowerCase() === 'center') || (arguments[0].toLowerCase() === 'centre')) {\r\n mx = (this.SIZE - 1) / 2;\r\n my = (this.SIZE - 1) / 2;\r\n }\r\n } else {\r\n throw new Error(\"Unexpected Input\");\r\n }\r\n let x, y;\r\n x = width / 2 - this.TILE_SIZE * constrain(mx, 0, this.SIZE - 1);\r\n y = height / 2 - this.TILE_SIZE * constrain(my, 0, this.SIZE - 1);\r\n this.offset.set(createVector(x, y));\r\n }", "function applybox(context, phys, platformLevel, platformRadius)\n{\n\tvar objectradius = 135*0.4;\n\tvar restitution = 0.8;\n\t\n\t// bounce on platform\n\tonPlatform = (Math.pow(phys.x - phys.x0, 2) < platformRadius*platformRadius) && (phys.y <= platformLevel+50) ;\n\t\n\tif (phys.y>platformLevel && onPlatform)\n\t\tphys.vy = phys.v0;\n\t\n\t// bounce on all borders of the canvas\n\tif (phys.x < objectradius && phys.vx < 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\n\tif (phys.x > context.canvas.width - objectradius && phys.vx > 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\t\n\tif (phys.y > context.canvas.height - objectradius && phys.vy > 0)\n\t{\n\t\tphys.vx = phys.vx * restitution;\n\t\tphys.vy = -phys.vy * restitution;\n\t}\n\t\n\t// if falling off the platform, add rotation\n\tvar v = Math.sqrt(phys.vx*phys.vx + phys.vy*phys.vy);\n\tvar vr = v/500;\n\tif (!onPlatform)\n\t{\n\t\tif (phys.x > phys.x0)\n\t\t\tphys.vr = vr;\n\t\telse\n\t\t\tphys.vr = -vr;\n\t}\n\t\n\treturn onPlatform;\n}", "function makeVisualPoint(point, w, h, scale, cameraPos) {\n return {\n x: point.x + ((w * scale) / 2) - cameraPos.x,\n y: point.y + ((h * scale) / 2) - cameraPos.y\n };\n}", "function updateKB_ByPoint(point_fs){\n\tvar r = default_radius;\n\tvar points_in_radius = getPointsInRadius_3Level(point_fs,r);\n\tvar result = calKB(points_in_radius);\n\tsetKB(result);\n}", "gravityAdd(particle,factor)\n{\n return particle.dy += factor*0.5;\n}", "point(param) {\n return this._edgeSegment.point(param);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function renumbers the IDs of the given circuit so that there are no collisions. This should be called any time a circuit is loaded to avoid collisions. It returns the circuit.
function renumber (circuit) { const clone = { ...circuit } let maxId = currentId const calcNewId = (id) => currentId < (Number.MAX_SAFE_INTEGER - id) ? id + currentId : (id - Number.MAX_SAFE_INTEGER) + currentId const updateId = (object) => { const clone = { ...object, id: calcNewId(object.id) } if (clone.id > maxId) { maxId = clone.id } if (clone.connections) { clone.connections = clone.connections.map(calcNewId) } return clone } clone.gates = clone.gates.map((gate) => { const r = updateId(gate) r.inputs = r.inputs.map(updateId) r.outputs = r.outputs.map(updateId) return r }) currentId = maxId + 1 return clone }
[ "function StickyIdMaker() {\n this.highId = 0;\n this.spare = [];\n}", "arrangeId() {\n const rootNode = this.parent.contentDom.documentElement;\n let id = SlideSet.MIN_ID;\n for (let { slideId } of this.selfElement.items()) {\n const oriId = slideId.id;\n const relElements = rootNode.xpathSelect(`.//*[local-name(.)='sldId' and @id='${oriId}']`);\n for (let relIdx in relElements) {\n relElements[relIdx].setAttribute(\"id\", id);\n }\n id++;\n }\n this[$slideAvalidID] = id;\n }", "function makeId (){\n function s4() {\n //generate random number to create a unique id for every item sent to the checkout page\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n }\n //return a random long random number generated above\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +\n s4() + '-' + s4() + s4() + s4();\n}", "getNewId() {\n var id = -1;\n\n this.meanlines.leafletLayer.getLayers().forEach((layer) => {\n if (layer.feature.id >= id) {\n id = layer.feature.id + 1;\n }\n });\n\n return id;\n }", "function addCircuitsToWorkouts(workoutsArr, circuitsArr) {\n workoutsArr.forEach(w => w.circuits = []);\n for (let c in circuitsArr) {\n let workoutIDForThisCircuit = circuitsArr[c].workoutID \n for (let w in workoutsArr) {\n if (workoutsArr[w].workoutID === workoutIDForThisCircuit) {\n workoutsArr[w].circuits.push(circuitsArr[c])\n }\n }\n }\nreturn workoutsArr\n}", "IDStrands(type=\"pd\"){\n\t\t//type can be \"pd\" or \"alexander\"\n\t\t\n\t\ttype = type.toLowerCase();\n\t\tif(type !== \"pd\" && type !== \"alexander\"){\n\t\t\tthrow new Error(\"Can't IDStrands, type argument (\"+type+\") is not 'pd' or 'alexander'\");\n\t\t}\n\t\t\n\t\tlet cur_id = type===\"pd\"? 1 : 0;\n\t\tlet strand_indices = Array.from(Array(this.strands.length).keys()); //gets an array [0,1,2,3, ...]\n\t\t//this array is used to track what strands remain to be ID-ed. Strands w/ an ID get removed. The entry in the\n\t\t//array refers to the strand's index in this.strands\n\t\t\n\t\tthis.ordered_strands = []; //clear it\n\t\t\n\t\t//sort this.strands so that strands w/ under-crossings at p0 come first, since we always need to start ID-ing each component\n\t\t//at a strand that just came out from under a crossing\n\t\tthis.strands.sort(function(a,b){\n\t\t\tif(a.p0.isCrossing() && !b.p0.isCrossing()){return -1;}\n\t\t\telse if(b.p0.isCrossing() && !a.p0.isCrossing()){return 1;}\n\t\t\telse if(a.p0_over == false && b.p0_over == true){return -1;}\n\t\t\telse if (b.p0_over == false && a.p0_over == true){return 1}\n\t\t\telse {return 0;}\n\t\t});\n\t\t\n\t\t//clear old IDs\n\t\tfor(let i=0; i<this.strands.length; i++){\n\t\t\tthis.strands[i].id = undefined;\n\t\t}\n\t\t\n\t\twhile(strand_indices.length > 0){ //loop for going through multiple components\n\t\t\tlet i = strand_indices[0]; //current strand index\n\t\t\tlet first_strand = this.strands[i];\n\t\t\tlet next_strand; //declared in this scope so the do-while loop's condition can read it\n\t\t\t\n\t\t\tdo {\n\t\t\t\tthis.strands[i].id = cur_id;\n\t\t\t\tstrand_indices.splice(strand_indices.indexOf(i), 1)[0];\n\t\t\t\tthis.ordered_strands.push(this.strands[i]);\n\t\t\t\t\n\t\t\t\t//change id if we should\n\t\t\t\tif(this.strands[i].p1.endpoint){\n\t\t\t\t\tcur_id++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(this.strands[i].p1.isCrossing()){\n\t\t\t\t\tif(type === \"pd\"){\n\t\t\t\t\t\tcur_id++;\n\t\t\t\t\t}\n\t\t\t\t\telse if(type === \"alexander\" && this.strands[i].p1_over === false){\n\t\t\t\t\t\tcur_id++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tnext_strand = this.strands[i].getNextStrand();\n\t\t\t\tif(next_strand == false){\n\t\t\t\t\tthrow new Error(\"Couldn't get next strand in IDStrands()\");\n\t\t\t\t}\n\t\t\t\ti = this.strands.indexOf(next_strand);\n\t\t\t\t\n\t\t\t} while (next_strand != first_strand && strand_indices.length > 0)\n\t\t}\n\t}", "function uniqueId() {\n return id++;\n }", "function resetComponentInstances() {\n Blockly.ComponentInstances = {};\n\n Blockly.ComponentInstances.addInstance = function(name, uid) {\n if (DEBUG) console.log(\"RAM ComponentInstances.addInstance \" + name);\n Blockly.ComponentInstances[name] = {};\n Blockly.ComponentInstances[name].uid = uid;\n Blockly.ComponentInstances[name].blocks = [];\n }\n\n Blockly.ComponentInstances.haveInstance = function(name, uid) {\n return Blockly.ComponentInstances[name] != undefined\n && Blockly.ComponentInstances[name].uid == uid;\n }\n\n Blockly.ComponentInstances.addBlockName = function(name, blockName) {\n Blockly.ComponentInstances[name].blocks.push(blockName);\n }\n\n}", "#nextId() {\n const nextId = \"id_\" + this.#currentId;\n this.#currentId++;\n return nextId;\n }", "async getChainId(network){}", "function InterCrack(parentChipId, id, parentCrack_1, parentCrack_2) {\n \n this.parentChipId = parentChipId;\n \n this.id = id;\n \n this.parentCrack_1 = parentCrack_1;\n \n this.parentCrack_2 = parentCrack_2;\n \n this.distanceFromCenter = Math.floor(Math.random() * Math.max(WIDTH, HEIGHT)) + 10;\n \n var parentChip = chips[this.parentChipId];\n \n var parentCrack_1 = parentChip.cracks[parentCrack_1];\n \n var parentCrack_2 = parentChip.cracks[parentCrack_2];\n \n this.x = parentChip.x + Math.cos(degToRad(parentCrack_1.dir)) * this.distanceFromCenter;\n \n this.y = parentChip.y + Math.sin(degToRad(parentCrack_1.dir)) * this.distanceFromCenter;\n \n this.endX = parentChip.x + Math.cos(degToRad(parentCrack_2.dir)) * this.distanceFromCenter;\n \n this.endY = parentChip.y + Math.sin(degToRad(parentCrack_2.dir)) * this.distanceFromCenter;\n \n this.draw();\n \n }", "removeminer(id) {\n\t\tconst idx = this.minerids.indexOf(id);\n\t\tif(idx == -1) return;\n\t\tthis.minerids.splice(idx, 1);\n\t\tif(this.minerpool[id]) delete this.minerpool[id];\n\t}", "function updateNetworkId() {\n gsnStore.getStore().then(function (rst) {\n if (service.store != rst) {\n var baseNetworkId;\n\n if (rst) {\n baseNetworkId = '/' + rst.City + '-' + rst.StateName + '-' + rst.PostalCode + '-' + rst.StoreId;\n baseNetworkId = baseNetworkId.replace(/(undefined)+/gi, '').replace(/\\s+/gi, '');\n }\n Gsn.Advertising.gsnNetworkStore = baseNetworkId;\n }\n });\n }", "function checkWireRep(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showWireItem('repetitive');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkWireRep", "function generateCardIDs() {\n //for each card add its id to cardids list\n cards.forEach(card => {\n cardIDs.push(card.cardID);\n });\n}", "function refNoGenerator() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = Math.random() * 16 | 0,\n v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}", "function addIdPrefix(component, prefix) {\n if (component.attr(\"id\") != undefined) {\n component.attr(\"id\", prefix + component.attr(\"id\"));\n }\n component.find('*').each(function () {\n if (jQuery(this).attr(\"id\") != undefined) {\n jQuery(this).attr(\"id\", prefix + jQuery(this).attr(\"id\"))\n }\n });\n return component;\n}", "function deleteCurrentCircuit(scopeId = globalScope.id) {\n const scope = scopeList[scopeId];\n if (Object.keys(scopeList).length <= 1) {\n showError('At least 2 circuits need to be there in order to delete a circuit.');\n return;\n }\n let dependencies = '';\n for (id in scopeList) {\n if (id != scope.id && scopeList[id].checkDependency(scope.id)) {\n if (dependencies === '') {\n dependencies = scopeList[id].name;\n } else {\n dependencies += `, ${scopeList[id].name}`;\n }\n }\n }\n if (dependencies) {\n dependencies = `\\nThe following circuits are depending on '${scope.name}': ${dependencies}\\nDelete subcircuits of ${scope.name} before trying to delete ${scope.name}`;\n alert(dependencies);\n return;\n }\n\n const confirmation = confirm(`Are you sure want to close: ${scope.name}\\nThis cannot be undone.`);\n if (confirmation) {\n if (scope.verilogMetadata.isVerilogCircuit) {\n scope.initialize();\n for (var id in scope.verilogMetadata.subCircuitScopeIds)\n delete scopeList[id];\n }\n $(`#${scope.id}`).remove();\n delete scopeList[scope.id];\n switchCircuit(Object.keys(scopeList)[0]);\n showMessage('Circuit was successfully closed');\n } else { showMessage('Circuit was not closed'); }\n}", "function _makeChangeId() {\n var arr = 'a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9'.split(',');\n var rnd = '';\n for (var i = 0; i < 40; i++) {\n rnd += arr[Math.floor(Math.random() * arr.length)];\n }\n\n return rnd;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function open message lightbox
function openMessage(message) { // var $container = window.parent.$('.container-message-lightbox'); var $container = $('.container-message-lightbox'); $container.find(".js-message").text(message); $container.fadeIn(); //hide fncybox close parent.$("#fancybox-close").css("display", "none !important"); }
[ "function display_message_box(){\r\n\t$(\"#new_msg\").click(function(){\r\n\t\t$(\"#popout\").fadeIn(\"slow\");\r\n\t});\r\n}", "function popup (message) {\n $('.pop').show().css('display', 'flex')\n $('.message').html(message)\n }", "function modalBox(msg) {\n\t\tvar boxCSS = \"position:absolute;width:300px;height:150px;padding:10px;background-color:#000000;color:#ffffff;z-index:30;font-family:'Arial';font-size:12px;display:none;\";\n\t\t$(\"#aspnetForm\").parent().append(\"<div id='SPServices_msgBox' style=\" + boxCSS + \">\" + msg);\n\t\tvar height = $(\"#SPServices_msgBox\").height();\n\t\tvar width = $(\"#SPServices_msgBox\").width();\n\t\tvar leftVal = ($(window).width() / 2) - (width / 2) + \"px\";\n\t\tvar topVal = ($(window).height() / 2) - (height / 2) - 100 + \"px\";\n\t\t$(\"#SPServices_msgBox\").css({border:'5px #C02000 solid', left:leftVal, top:topVal}).show().fadeTo(\"slow\", 0.75).click(function () {\n\t\t\t$(this).fadeOut(\"3000\", function () {\n\t\t\t\t$(this).remove();\n\t\t\t});\n\t\t});\n\t} // End of function modalBox", "function open_chat_box() {\n\n if(window.key_follow==false){\n var camera_chat = '<a href=\"camera\" class=\"com com_camera\" reason=\"camera\"><i class=\"mdi-notification-voice-chat\"></i></a>';\n var attach_file = '<a href=\"file\" class=\"com com_file\" reason=\"file\"> <i class=\"mdi-editor-attach-file\"></i></a>';\n }else{\n var camera_chat = '';\n var attach_file = '';\n }\n\n \n // var follow = '<a href=\"follow\" class=\"com\" reason=\"follow\"> <i class=\"following mdi-social-share\"></i></a>';\n var minimize = '<a class=\"\" style=\"color:#FFF;cursor:pointer;\" > <i class=\"mdi-content-remove\"></i></a>';\n var close = '<a href=\"close\" class=\"com\" reason=\"close_box\"> <i class=\"mdi-navigation-close\"></i></a>';\n\n \n $(\"#chat_div\").chatbox({id : \"chat_div\",\n title : '<span class=\"name_box truncate\"></span><span class=\"title_box_style\"><span class=\"ui-chatbox-icon\">'+camera_chat+attach_file+minimize+close+'</span></span>',\n user : \"can be anything\",\n hidden: false, // show or hide the chatbox\n offset:0,\n width: 230, // width of the chatbox\n messageSent: function(id,user,msg){ \n \n $(\"#chat_div\").chatbox(\"option\", \"boxManager\").addMsg(window.username, msg);//on écrit son message en local\n\n socket.emit('send_message',{'sender_name':window.username,'sender_num':window.user_number,'sender_msg':msg,'interloc_num':window.interloc_num});\n\n }\n });\n \n window.open_chat = true;\n }", "function showpopup(msg_id, process_name, top_value) {\n GetFullDetailMessage(msg_id, process_name);\n}", "function showok(message){\n\t$.messager.show({\n\t\ttitle:'消息',\n\t\tmsg:message == null ? '操作成功!' : message,\n\t\tshowType:'show',\n\t\ttimeout:3000,\n\t\tstyle:{\n\t\t\tright:'',\n\t\t\ttop:document.body.scrollTop + document.documentElement.scrollTop,\n\t\t\tbottom:''\n\t\t}\n\t});\n}", "function opensmoothboxurl(openURLsmoothbox){\n openSmoothBoxInUrl(openURLsmoothbox);\n\treturn false;\n}", "function imwindow(imtype, userid, width, height)\n{\n\treturn openWindow(\"sendmessage.php?\" + SESSIONURL + \"do=im&type=\" + imtype + \"&userid=\" + userid, width, height);\n}", "function initLightbox() {\n\tjQuery('a.lightbox, a[rel*=\"lightbox\"]').each(function(){\n\t\tvar link = jQuery(this);\n /* added (15th Oct 2014) */\n // when clicking on a lightbox class element that opens a fancybox modal, determine if option modal is true or false\n // this prevents the user of closing the modal without selecting any options that will close it\n modalOption = false;\n if (link.attr('data-fancybox-modal') === \"true\"){\n modalOption = true;\n }\n /* End: added (15th Oct 2014) */\n\t\tlink.fancybox({\n\t\t\tpadding: 0,\n\t\t\tcyclic: false,\n\t\t\toverlayShow: true,\n\t\t\thideOnOverlayClick: false,\n\t\t\toverlayOpacity: 0.65,\n\t\t\toverlayColor: '#000000',\n\t\t\ttitlePosition: 'inside',\n modal: modalOption, /* added (15th Oct 2014): */\n\t\t\tonStart: function(box) {\n hrefValue = link.attr('href');\n\n if (hrefValue == '#beats-terms-of-use-popup') {\n // Load the popup content.\n jQuery(\"#beats-terms-of-use-popup-content\").load(\"/beats_popup_load.jq?p=beats-terms-of-use-popup\");\n\t\t\t\t}\n else if (hrefValue == '#beats-privacy-policy-popup') {\n // Load the popup content.\n jQuery(\"#beats-privacy-policy-popup-content\").load(\"/beats_popup_load.jq?p=beats-privacy-policy-popup\");\n\t\t\t\t}\n else if (hrefValue == '#ebook-terms-of-use-popup') {\n // Load the popup content.\n jQuery(\"#ebook-terms-of-use-popup-content\").load(\"/ebook_popup_load.jq?p=ebook-terms-of-use-popup\");\n\t\t\t\t}\n else if (hrefValue == '#ebook-privacy-policy-popup') {\n // Load the popup content.\n jQuery(\"#ebook-privacy-policy-popup-content\").load(\"/ebook_popup_load.jq?p=ebook-privacy-policy-popup\");\n\t\t\t\t}\n else if (hrefValue == '#popup-registration-login') {\n // Hide any error messages.\n jQuery('#popup-registration-login #errorMsgExc1, #popup-registration-login #errorMsgExc2, #popup-registration-login #errorMsgMisc').hide();\n\t\t\t\t}\n else if (hrefValue == '#ebooks-email-popup') {\n if (link.hasClass('ebooks-register')) {\n jQuery('#ebooks-email-popup .ebooks-newsletter-signup').hide();\n jQuery('#ebooks-email-popup .ebooks-end-of-book').hide();\n jQuery('#ebooks-email-popup .ebooks-register').show();\n }\n else if (link.hasClass('ebooks-newsletter-signup')) {\n jQuery('#ebooks-email-popup .ebooks-register').hide();\n jQuery('#ebooks-email-popup .ebooks-end-of-book').hide();\n jQuery('#ebooks-email-popup .ebooks-newsletter-signup').show();\n }\n else if (link.hasClass('ebooks-end-of-book')) {\n jQuery('#ebooks-email-popup .ebooks-register').hide();\n jQuery('#ebooks-email-popup .ebooks-newsletter-signup').hide();\n jQuery('#ebooks-email-popup .ebooks-end-of-book').show();\n }\n\t\t\t\t}\n\t\t\t},\n\t\t\tonComplete: function(box) {\n hrefValue = link.attr('href');\n\n\t\t\t\tif (hrefValue.indexOf('#') === 0) {\n\t\t\t\t\tjQuery('#fancybox-content').find('a.close, button.close').unbind('click.fb').bind('click.fb', function(e){\n\t\t\t\t\t\tjQuery.fancybox.close();\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t});\n\t\t\t\t}\n\n /* added (15th Oct 2014) */\n /* Special processing for popups on music page. The following\n assumes that #beats-terms-of-use-popup and #beats-privacy-policy-popup\n are called only from other certain popups.\n */\n if (hrefValue == '#popup-registration-user' || hrefValue == '#popup-registration-login' || hrefValue == '#popup-registration-forced') {\n // Remember which popup is being displayed.\n beats.popupLink = hrefValue;\n }\n else if (hrefValue == '#beats-terms-of-use-popup' || hrefValue == '#beats-privacy-policy-popup') {\n // Set the href values of the close links to the\n // previous popup that was displayed.\n jQuery('.beats-agreement-popup a.close-link').attr('href', beats.popupLink);\n }\n /* End: added (15th Oct 2014) */\n\n // If there is a user-defined callback function, call it.\n if (typeof lightbox_complete_callback == 'function') {\n lightbox_complete_callback(hrefValue);\n }\n\t\t\t},\n/*\n\t\t\tonCleanup: function(box) {\n\t\t\t},\n\t\t\tonCancel: function(box) {\n\t\t\t},\n*/\n\t\t\tonClosed: function(box) {\n hrefValue = link.attr('href');\n\n // If there is a user-defined callback function, call it.\n if (typeof lightbox_closed_callback == 'function') {\n lightbox_closed_callback(hrefValue);\n }\n\t\t\t},\n\t\t});\n\t});\n}", "function openMessageFrame(contactElement){\n\n\t\t\t//get a reference to the view object\n\t\t\tvar msgView = document.getElementById(\"message_view\");\n\n\t\t\tif(activeContact.trim() !== \"\"){\n\t\t\t\t\n\t\t\t\t//Change the color of the current active contact to black\n\t\t\t\tvar currentActiveContact = document.getElementById (activeContact);\n\t\t\t\tcurrentActiveContact.style.color = \"black\";\n\t\t\t\tconsole.log(\"Switch from \"+ activeContact );\n\t\t\t}//if Ends \n\n\t\t\t//remove current user's message content and replace them with that of the new user.\n\t\t\tactiveContact = contactElement.textContent; \n\n\t\t\tmsgView.textContent = \"\";\n\n\t\t\tcontactElement.style.color = \"blue\";\n\n\t\t\tconsole.log(\"Active contact: \"+activeContact);\n\n\t\t\t//TODO:Let the sender know that receiver has view the message that was sent.\n\t\t\t//clear the message notication status count to indicate that user has view the message. \n\t\t document.getElementById(activeContact+\"_msg_notice\").textContent = \"\";\n\t\t}", "function callMessageDialog(title, messageContent){\n\t\t$(\"#messageDialog\").find(\"#messageContent\").text(messageContent);\n\t\t$(\"#messageDialog\").dialog({\n\t\t\tshow:{\n\t\t\t\teffect:\"slide\",\n\t\t\t\tduration: 300\n\t\t\t},\n\t\t\ttitle: title,\n\t\t\theight: 200,\n\t\t\twidth: 350,\n\t\t\thide: {\n\t\t\t\teffect: \"slide\",\n\t\t\t\tduration: 300\n\t\t\t},\n\t\t\tbuttons:{\n\t\t\t\t\"OK\": function(){\n\t\t\t\t\t$(this).dialog(\"close\");\n\t\t\t\t\tloadData();\n\t\t\t\t\tloadFactoryData();\n\t\t\t\t}\n\t\t\t}\n\t\t}).prev(\".ui-widget-header\").css(\"color\",\"#333\");\n\t}", "function show_message(page, process_name) {\n // Save info of the opened tab\n msg_or_job = 'Msg';\n ProcessMsgUpdate(page, process_name, true);\n}", "function fadeInMsg(msg) {\n\t//fade in message with Jquery action\t\n\t$(\"#preview p:first\").css(\"opacity\", 0);\n\t$(\"#preview p:first\").delay(400);\n \t$(\"#preview p:first\").html(msg);\n \t$(\"#preview p:first\").animate({\n \t\topacity: 1\n \t\t\t}, 400);\t\n \t$(\"#directions\").hide();\n \t\t\t\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 ShowAlert()\n{\n var a = document.createElement('a');\n a.href='/enUS/search-editor/default.html?mode=newalert&' + $j('#search_state').val();\n a.setAttribute('rel','popup 700 750');\n showpopup(a);\n}", "function buildBox() {\n var innerContent = getInnerContent();\n var buttons = '';\n if(curOpt.ok){\n buttons = '<div class=\\'pm-popup-buttons\\'> <button class=\\'button\\'>OK</button></div>';\n }\n var boxHtml = '<div id=\\'pm_'+curOpt.id+'\\' class=\\'pm_popup\\'><div class=\\'pm-popup-inner\\'> '+innerContent + buttons+'</div></div>';\n var thisPopup = $(boxHtml).appendTo('body');\n if (curOpt.ok) {\n //attach events\n thisPopup.find('.button').click(function() {\n $(window).scrollTop(0);\n hide();\n curOpt.ok();\n });\n }\n }", "function pmRmMsgFlash (message) {\r\n var client_id = message[0];\r\n var room_id = message[1];\r\n var url = message[2];\r\n var comment = message[3];\r\n var x = userFind(client_id);\r\n\r\n if (x < 0) {\r\n printPlus(\"text_div\", '<span class=\"cln_err\">RM_MSG_FLASH from '+client_id+'</span>');\r\n return 0;\r\n }\r\n\r\n g_user_msg_v[x] = url;\r\n\r\n if ((my_client_id == client_id) || (g_user_admin[x] == 1)) {\r\n mboxView('media_div');\r\n output = '';\r\n output += '<object width=\"100%\" height=\"100%\">';\r\n output += ' <param name=\"movie\" value=\"'+url+'\"></param>';\r\n output += ' <param name=\"allowFullScreen\" value=\"true\"></param>';\r\n output += ' <param name=\"allowscriptaccess\" value=\"always\"></param>';\r\n output += ' <embed src=\"'+url+'&autoplay=1\"';\r\n output += ' type=\"application/x-shockwave-flash\"';\r\n output += ' allowscriptaccess=\"always\"';\r\n output += ' allowfullscreen=\"true\"';\r\n output += ' autoplay=\"true\"';\r\n output += ' width=\"100%\"';\r\n output += ' height=\"100%\">';\r\n output += ' </embed>';\r\n output += '</object>';\r\n print(\"media_div\", output);\r\n } else {\r\n output = '<span class=\"media\">';\r\n output += g_user_name[x]+\" Loaded: \";\r\n output += \"<a href=\\\"#\\\" onclick=\\\"document.getElementById('input_box').value='/flash \"+url+\"';clientInput();\\\">Video (\"+comment+\")</a></span><br />\";\r\n printPlus(\"text_div\", output);\r\n }\r\n return 1;\r\n}", "function ntv_huy_theo_doi() {\n\tvar url = '/ajax/ntv_quan_tri_theo_doi_tin_tuyen_dung/popup_huy_theo_doi/';\n\tshow_box_popup('', 420, 250);\n\tAjaxAction('_box_popup', url);\n\n}", "function _notify(msg) {\n let html=document.getElementById('notify-container');\n html.innerHTML=msg;\n $('#modalnotify').modal('show');\n setTimeout(function() {$('#modalnotify').modal('hide')}, 3000);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the users last search to localStorage
function storeLastSearch() { let userSearch = $("#userSearch").val(); localStorage.setItem("lastSearch", JSON.stringify(userSearch)); }
[ "function storeSearchHistory() {\nlocalStorage.setItem(\"searchHistory\", JSON.stringify(userSearchArray))\n}", "function checkSavedSearches() {\n var checkStorage = JSON.parse(localStorage.getItem(\"saved\"));\n if (checkStorage !== null) {\n searchStorage = checkStorage;\n }\n }", "function storeSearches() {\n localStorage.setItem(\"storedSearches\", JSON.stringify(storedSearches));\n}", "function setSearchHistory (searchHistory) {\n\n localStorage.setItem(\"searchHistory\", JSON.stringify(searchHistory));\n\n}", "function addStoredSearch(search){\n var storedSearchesArray = getStoredSearches(); //get stored searches from localStorage\n //push new item to local array\n storedSearchesArray.push(search);\n //set localStorage to updated array\n localStorage.setItem(\"storedSearches\", JSON.stringify(storedSearchesArray));\n //now add button to search history\n var storedSearch = $(document.createElement(\"button\"));\n storedSearch.text(search);\n storedSearch.addClass('btn btn-info btn-block history-button');\n storedSearch.on('click', function(){\n getBreweryData(this.innerHTML);\n getWikiPage(this.innerHTML);\n });\n $('#search').append(storedSearch);\n}", "function saveDate() {\n let lastDate = new Date();\n localStorage.lastDate = lastDate;\n}", "function loadStoredResults() {\n //conditional statement to check if load is needed\n if (loadFromLocalStorage(\"reloadResults\") == true) {\n //initialize variable and store loaded results in it\n let searchResults = loadFromLocalStorage(\"latestSearchResults\");\n //display the results that have been loaded\n displaySearchResults(searchResults, loadFromLocalStorage(\"backToResultsPageToLoad\"));\n //clear data under backToResultsPageToLoad tag in local storage\n saveToLocalStorage(\"\", \"backToResultsPageToLoad\");\n //disable load results instruction to stop the results being loaded again if user navigates away and back to page\n disableLoadStoredResults();\n }\n}", "saveQueryState() {\n this.localStorageObj.put('queryState', {\n pageSize: this.state.pageSize,\n currentPage: this.state.currentPage,\n sort: this.state.sort,\n searchTerm: this.state.searchTerm,\n filterType: this.state.filterType\n });\n }", "function previousCity(city) {\n \n var history = JSON.parse(localStorage.getItem(\"history\")) || [];\n\n if (history.indexOf(city) === -1) {\n history.push(city);\n window.localStorage.setItem(\"history\", JSON.stringify(history));\n // Adds previously searched cities to search bar card \n let cityListItem = $(\"<li>\").addClass(\"list-group-item\").text(city);\n $(\".list\").prepend(cityListItem);\n \n }\n }", "function goToStoreList(e) {\n var confirmedValue = currentValue;\n\n // Set confirmed value to local storage so other page can access it\n localStorage.setItem(\"userSearchFor\", confirmedValue);\n\n // Checks if the local storage is updated\n console.log(localStorage.getItem(\"userSearchFor\"));\n\n // Send user from this screen to store list\n window.location.replace(\"store-list.html\");\n}", "function renderStoredSearch() {\n // console.log(\"Im in render stored search locations func\");\n //creating a variable to hold the items in local storage parsed into JSON\n var searchArray = JSON.parse(localStorage.getItem(\"searchLocations\"));\n //if there are items in local storage\n if (searchArray != null) {\n // console.log(\"searchArray\", searchArray);\n //do this for loop for the entire length of the new array\n for (var i = 0; i < searchArray.length; i++) {\n //run the add search function above add the previously searched items to the ul as lis\n addSearch(searchArray[i].searchLocation);\n }\n }\n }", "function saveUsers() {\n localStorage.setItem(\"trivia-users\", JSON.stringify(users));\n}", "function saveUsersName(text) {\n localStorage.setItem(USERS_LS, text);\n}", "function renderLocalSearch () {\n //checks local storage for localScores item\n if(JSON.parse(localStorage.getItem(\"localCity\")) === null) {\n return;\n }\n // if localScores is in local storage, parses string to highScoreStore array.\n storedSearches = JSON.parse(localStorage.getItem(\"localCity\"));\n}", "function getLastViewed() {\n return sessionStorage.getItem('lastviewed');\n}", "function renderLast() {\n //create a variable to hold the local storage item holding the last searched location\n var location = localStorage.getItem(\"lastLocation\", location);\n //run the function to display the weather\n getLatLong(location);\n }", "function saveName() {\n\tlocalStorage.setItem('receivedName', userName)\n}", "async doSaveCacheHistory() {\n\t\tlet theUnsaved = this.historyCache.getUnSaved();\n\t\tif (!$.isEmptyObject(theUnsaved)) { await this.doAddToDB('searching', 'history', Object.values(theUnsaved)); }\n\t}", "function storeCount() {\n if (localStorage.getItem(userInput) !== null){\n let counter = parseInt(localStorage.getItem(userInput)) + 1;\n localStorage.setItem(userInput, counter);\n } else {\n localStorage.setItem(userInput, 1);\n }\n let currentCount = 0;\n let currentSybol;\n for (let [key, value] of Object.entries(localStorage)) {\n if (parseInt(value) > currentCount) {\n currentCount = value;\n currentSymbol = key;\n }\n }\n updateFavorite(currentSymbol, currentCount);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shall be used to parse output of the custom `Ptypes` gdb command
consoleParsePtypes(input) { return Parser.parse(input, { startRule: 'PTYPES' }); }
[ "consoleParseTypes(input) { return Parser.parse(input, { startRule: 'TYPES' }); }", "function show(type) { console.log(type.schema({exportAttrs: true})); }", "commandType() {\n const { 0: com } = __classPrivateFieldGet(this, __command);\n // console.log(\"com\", com);\n const type = __classPrivateFieldGet(this, _cType).get(com);\n // if (!type) throw new Error(\"Syntax Error\");\n return type;\n }", "function queryCommandTypes() {\n server.getCommandTypes().then(function(res) {\n vm.commandTypes = res.data.commandTypes;\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }", "parseMIoutput(input) { return Parser.parse(input, { startRule: 'GDBMI_OUTPUT' }); }", "visitType_procedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parseType() {\n var id;\n var params = [];\n var result = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = identifierFromToken(token);\n eatToken();\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) {\n eatToken(); // (\n\n eatToken(); // func\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken(); // function with an empty signature, we can abort here\n\n return t.typeInstruction(id, t.signature([], []));\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) {\n eatToken(); // (\n\n eatToken(); // param\n\n params = parseFuncParam();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) {\n eatToken(); // (\n\n eatToken(); // result\n\n result = parseFuncResult();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.typeInstruction(id, t.signature(params, result));\n }", "visitTypedargslist(ctx) {\r\n console.log(\"visitTypedargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }", "function printResolver(type) {\n if (type === 'i') {\n emit(`invokevirtual java/io/PrintStream/print(I)V \\n`, -2);\n } else if (type === 's') {\n emit(`invokevirtual java/io/PrintStream/print(Ljava/lang/String;)V \\n`, -2);\n } else if (type === 'a') {\n emit(`invokevirtual Array/string()Ljava/lang/String;`, 0);\n emit(`invokevirtual java/io/PrintStream/print(Ljava/lang/String;)V \\n`, -2);\n } else {\n console.error(`ERROR: check printResolver`);\n process.exit(1);\n }\n }", "function convertToPyret(programs, pinfo){\n _pinfo = pinfo;\n return { name: \"program\"\n , kids: [ {name: \"prelude\"\n , kids: [/* TBD */]\n , pos: blankLoc}\n , {name: \"block\"\n , kids: programs.map(function(p){return {name:\"stmt\", kids:[p.toPyret()], pos: p.location};})\n , pos: programs.location}]\n , pos: programs.location};\n }", "function parseTypeExpressionList() {\n var elements = [];\n elements.push(parseTop());\n\n while (token === Token.COMMA) {\n consume(Token.COMMA);\n elements.push(parseTop());\n }\n\n return elements;\n } // TypeName :=", "function getTypeIdentifier(Repr) {\n\t return Repr[$$type] || Repr.name || 'Anonymous';\n\t }", "typesList(types) {\n this.snippet.appendText(\" [\");\n this.textOrPlaceholder(types, \"<Type>\");\n this.snippet.appendText(\"]\");\n }", "visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getNextPacketType(){\n\t\tif(this.buffer.length < 4)return null;\n\t\treturn this.buffer.slice(0,4).toString();\n\t}", "static parseTypesFromDexPage(html, typeList) {\n const typeImgs = html.find('.dexdetails>li>img');\n const typeUrls = typeImgs.map((idx, img) => {\n return img.src;\n });\n let types = typeUrls.map((idx, url) =>\n url.substring(url.indexOf('types/')+'types/'.length,\n url.indexOf('.png')));\n types = types.map((idx, type) => type.charAt(0).toUpperCase() + type.substring(1));\n types = types.map((idx, type) => typeList.indexOf(type)); // GLOBALS.TYPE_LIST.indexOf(type));\n return types.toArray();\n }", "checkXrefType() {\n // check for xref .... trailer occurrences in file\n const xrefTableMatch = /[^start]xref(.*?)(?=trailer)/gs\n this.xrefTables = this.docString.match(xrefTableMatch)\n\n // check for /XRef dictionary entries\n const xrefStreamMatch = /\\/XRef/gms\n this.xrefStreams = this.docString.match(xrefStreamMatch)\n }", "parseMIrecord(input) { return Parser.parse(input, { startRule: 'GDBMI_RECORD' }); }", "visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create target ul list
function createTarget(t){ var tUl= document.createElement('ul'); var imgSufix='.png'; tUl.id = 'drag2share-targets'; $.each(t.split(','), function(index, value) { var tLi = document.createElement('li'); tLi.id = value; tLi.style.background = 'url('+options.icons+'/'+value+imgSufix+') no-repeat 0 0'; $(tUl).append(tLi); }); $(document.body).prepend(tUl); tUlH=($(tUl).height()); tUl.style.top = '-'+parseInt(tUlH+20)+'px'; }
[ "function createLiElement() {\n const fragment = document.createDocumentFragment();\n sections.forEach((section) => {\n const navListElement = document.createElement('li');\n navListElement.classList.add('nav-list__item');\n const idSection = section.id;\n const linkElement = document.createElement('a');\n linkElement.href = `#${idSection}`;\n linkElement.textContent = idSection;\n linkElement.classList.add('nav-list__link');\n navListElement.appendChild(linkElement)\n fragment.appendChild(navListElement)\n })\n ulList.appendChild(fragment)\n\n }", "function buildItem(heading, currentLevel, maxLevel) {\n if (currentLevel > maxLevel) { return; }\n\n const item = $('<li class=\"usa-sidenav__item\"></li>');\n const link = $(`<a href=\"#${heading.attr(\"id\")}\">${heading.text()}</a>`);\n item.append(link);\n\n if (!(currentLevel + 1 > maxLevel)) {\n const sublist = buildSublist(heading, currentLevel, maxLevel);\n item.append(sublist);\n }\n\n return item;\n }", "function createList(scene) {\n id += 1;\n var html='';\n var c = scene.children;\n if (scene.name == '' && c.length <= 1) {\n if (c.length == 1) {\n html = createList(c[0]);\n }\n }\n else if (c.length == 0) {\n html+='<li data-sceneid='+id+'>'+scene.name+'</li>';\n scenes[id]=scene; \n }\n else {\n if (scene.name == '') {\n scene.name = 'All' // just a placeholder...\n }\n html+='<li data-sceneid='+id+'>'+scene.name+'<ul>';\n scenes[id]=scene;\n for (var i=0; i<c.length; i++) {\n html+=createList(c[i]);\n }\n html += '</ul>';\n }\n return html;\n}", "function createListHTML(list, container) {\n container.innerHTML = \"\"; //first, clean up any existing LI elements\n for (var i = 0; i < 6; i++) {\n container.innerHTML = container.innerHTML + \"<li data-index='\" + list[i][\"index\"] + \"'>\" + \"<span>\" + list[i][\"text\"] + \"</span>\" + \"</li>\";\n //OR shorter version: container.innerHTML += \"<li data-index='\" + list[i][\"index\"] + \"'>\" + list[i][\"text\"] + \"</li>\";\n }\n }", "function sf_list_up(){\n\t\n\tjQuery( 'body' ).find( '.studio-container .menu-item' ).each( function( ind ){\n\t\tjQuery( this ).get( 0 ).style.setProperty( '--animation-order', ind.toString() ); // studio container (big list)\n\t});\n\t\n\tjQuery( 'body' ).find( '.list-entry' ).each( function( ind ){\n\t\tjQuery( this ).get( 0 ).style.setProperty( '--animation-order', ind.toString() ); // list entries (normal list)\n\t});\t\n\t\n}", "function buildSublist(parentHeading, currentLevel, maxLevel) {\n const subheadings = parentHeading.nextUntil(`h${currentLevel}`, `h${currentLevel + 1}`)\n if (subheadings.length === 0) { return; }\n\n const sublist = $('<ul class=\"usa-sidenav__sublist\"></ul>');\n\n subheadings.each(function () {\n const item = buildItem($(this), currentLevel + 1, maxLevel);\n sublist.append(item);\n });\n\n return sublist;\n }", "function createWebsiteTree() {\n let finalListUI = '';\n websiteList.reverse().forEach(website => {\n if(website.url.length > 40)\n website.displayURL = website.url.substring(0, 40) + \"....\";\n else\n website.displayURL = website.url;\n const listItem = `\n <div class=\"list__item\">\n <h3>${website.displayURL}</h3>\n <svg id=\"${hashCode(website.url)}\" width=\"14\" height=\"18\" viewBox=\"0 0 14 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M1 16C1 17.1 1.9 18 3 18H11C12.1 18 13 17.1 13 16V4H1V16ZM3 6H11V16H3V6ZM10.5 1L9.5 0H4.5L3.5 1H0V3H14V1H10.5Z\" fill=\"#C18888\"/>\n </svg>\n </div>`;\n finalListUI += listItem\n });\n websiteListUI.innerHTML = finalListUI;\n websiteList.forEach(website => {\n getElement('#' + hashCode(website.url)+'').addEventListener('click', () => removeFromList(website.url));\n })\n }", "function list() {\r\n var x = document.getElementsByTagName(\"li\")[9];\r\n x.setAttribute(\"id\", \"list\");\r\n }", "function addChildToListView(parentUl, childCcn) {\n var childLi = $(\"<li/>\");\n var cpd = currentFrameworkCompetencyData.competencyPacketDataMap[childCcn.id];\n var compNode = cpd.cassNodePacket.getNodeList()[0]; //TODO: What if there are multiple nodes in the same packet?\n if (childCcn.children && childCcn.children.length > 0) childLi.addClass(\"collapsed\");\n childLi.attr(\"id\", buildIDableString(getStringVal(compNode.getName()).trim()) + \"_lvi\");\n var hasChildren = childCcn.children && childCcn.children.length > 0;\n childLi.html(generateCompetencyLineItemHtmlForListView(cpd, compNode, hasChildren));\n if (hasChildren) {\n childCcn.children.sort(function (a, b) {\n return a.name.localeCompare(b.name);\n });\n var childsChildUl = $(\"<ul/>\");\n childsChildUl.attr(\"class\", \"fa-ul\");\n childsChildUl.attr(\"style\", \"display:none\");\n $(childCcn.children).each(function (i, cc) {\n addChildToListView(childsChildUl, cc);\n });\n childLi.append(childsChildUl);\n }\n parentUl.append(childLi);\n}", "function buildListReposAndFollowers(data,list,sign)\n{\n for (let i=0; i <data.length;i++)\n {\n const a = document.createElement(\"a\");\n const newItem = document.createElement(\"li\");\n if(sign === 'REPOS')\n a.innerHTML = data[i].name;\n else\n a.innerHTML = data[i].login;\n a.href = data[i].html_url;\n newItem.appendChild(a);\n list.appendChild(newItem);\n }\n\n}", "function buildUlTree(tree)\n{\n\tvar unordered_list = '';\n\tfor (node in tree)\n\t{\n\t\tnode = tree[node];\n\t\t\n\t\tunordered_list += '<ul style=\"margin-bottom: 0\">';\n\t\tunordered_list += println(node['title']);\n\t\tif(node['children'])\n\t\t{\n\t\t\tunordered_list += buildUlTree(node['children']);\n\t\t}\n\t\tunordered_list += '</ul>';\n\t}\n\treturn unordered_list;\n}", "function buildLi(elem){\n var a = document.createElement('a');\n a.href = '#' + elem.id\n a.rel = 'internal';\n a.textContent = elem.textContent;\n\n var li = document.createElement('li');\n li.appendChild(a);\n return li;\n}", "function itemClicked(){\n $(\".listing-container li > div\").off().on(\"click\",function(){ \n if ($(this).children(\"i:first-child\").hasClass(\"permision_ok\") ){\n ulelment=$(\"[path='\"+$(this).parent(\"li\").attr(\"path\")+\"']\").find(\"ul\") \n //ajaxGetChildren($(\"#\"+$(this).parent(\"li\").attr(\"id\")+\"_ul\"),$(this).parent(\"li\").attr(\"path\"),1,0)\n if ($(this).parent(\"li\").attr(\"ftype\")===\"file\"){\n $(\".listing-container ul,li div.bg-primary\").removeClass(\"bg-primary\");\n $(this).addClass(\"bg-primary\"); \n }\n else if (ulelment.is(':visible')){\n $(\"[path='\"+$(this).parent(\"li\").attr(\"path\")+\"'] > ul\").hide()\n }\n else {\n $(\".listing-container ul,li div.bg-primary\").removeClass(\"bg-primary\");\n $(this).addClass(\"bg-primary\");\n $(this).parent(\"li\").find(\"ul\").remove()\n $(\".loader\").show()\n $(this).parent(\"li\").append(\"<ul level='\"+$(this).parent(\"li\").attr(\"level\")+\"_ul' ></ul>\")\n ajaxGetChildren($(\"[path='\"+$(this).parent(\"li\").attr(\"path\")+\"'] > ul\"),$(this).parent(\"li\").attr(\"path\"),parseInt($(this).parent(\"li\").attr(\"level\").match(/(\\d+)$/)[0])+1,parseInt($(this).parent(\"li\").attr(\"level\").match(/(\\d+)$/)[0]))\n $(\"[path='\"+$(this).parent(\"li\").attr(\"path\")+\"'] > ul\").show() \n }\n itemClicked()\n \n }\n\n //console.log(this.parentElement.find(\"ul\"))\n //this.parent().find(\"ul\").slideToggle()\n });\n }", "function if_addLinks() {\n\n $( 'ul.imageflow-list' ).each(function(i,musiclist) {\n\n if ( $('li',musiclist).length > 1 ) {\n\n var wrap = $( '<div></div>' );\n var link = $( '<a></a>' )\n .html( 'ImageFlow' )\n .addClass( 'toggler' )\n .attr( 'href', 'javascript:;' )\n .click(function(){\n var imageflow = $( '#imageflow' );\n if ( imageflow.length > 0 ) {\n $.each(imageflow,function(){\n $(this).remove();\n });\n }\n else if_createImageFlow( wrap );\n $( this )\n .blur()\n .toggleClass( 'togglerHide' );\n });\n\n var newDiv = $( '<div></div>' )\n .addClass( 'imageflow_toggler' )\n .append( link )\n .append( wrap )\n\n newDiv.insertBefore( musiclist );\n\n }\n\n });\n\n }", "function addListToHtml(ul) {\n fetchYaml().then(function(yamlData) {\n for (i in yamlData) {\n // LOCAL VARIABLES\n let label = document.createElement(\"label\");\n let input = document.createElement(\"input\");\n let span = document.createElement(\"span\");\n let img = document.createElement(\"img\");\n let li = document.createElement(\"li\");\n\n // SET ATTRIBUTES\n label.htmlFor = i // <label for={yamlData.pkgName}>\n span.className = \"package-list__label-text\"\n label.className = \"package-list__label\";\n label.title = yamlData[i].description;\n\n input.type = \"checkbox\";\n input.name = \"package-item\";\n input.className = \"label__checkbox\";\n input.value = i\n input.id = i\n img.src = iconSrc + yamlData[i].icoUrl;\n img.className = \"icoImg\";\n span.innerHTML = `<b>${yamlData[i].name}</b> - ${yamlData[i].description}`;\n\n\n li.className = \"package-list__item\";\n\n // WRITE ELEMENTS\n label.appendChild(input); // <div><label><input> <=\n label.appendChild(img);\n label.appendChild(span); // write yamlData.name after checkbox\n li.appendChild(label); // <div><label> <=\n ul.appendChild(li); // li --> label --> input, img\n\n }\n })\n}", "function trailList(mtbInfoArr) {\n $(\".mtbList\").empty();\n for (var i = 0; i < mtbInfoArr.length; i++) {\n var trailName = mtbInfoArr[i].name;\n var trailID = mtbInfoArr[i].ID;\n var trailIndex = mtbInfoArr[i].dataIndex;\n var trailItem = $(\"<li>\");\n var trailLink = $(\"<a href='#!'></a>\");\n trailLink.attr(\"data-ID\", trailID);\n trailLink.attr(\"data-index\", trailIndex);\n trailLink.addClass('listData');\n trailLink.text(trailName);\n trailItem.append(trailLink);\n $(\".mtbList\").append(trailItem);\n }\n}", "_addToLists(list) {\n const listObj = {\n index: this.lists.length,\n name: list.getAttribute('name'),\n element: list,\n editable: this.isEditable(list),\n };\n if(this.lists.length === 0) this.activeList = listObj;\n this.lists.push(listObj);\n }", "function newList() {\n let article = gen(\"article\");\n let titleInput = gen(\"input\");\n let taskInput = gen(\"input\");\n let ul = gen(\"ul\");\n\n article.classList.add(\"list\");\n\n titleInput.type = \"text\";\n titleInput.placeholder = \"Title\";\n titleInput.classList.add(\"title-in\");\n article.appendChild(titleInput);\n titleInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTitle(titleInput);\n }\n });\n\n taskInput.type = \"text\";\n taskInput.placeholder = \"+ New task\";\n taskInput.classList.add(\"task-in\");\n article.appendChild(taskInput);\n article.appendChild(ul);\n taskInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTask(taskInput);\n }\n });\n\n qs(\"section\").insertBefore(article, id(\"add\"));\n\n article.addEventListener(\"dblclick\", removeObj);\n }", "function buildNode(id, name, parent){\n\t\tvar element = $(\"<li><a>\" + name + \"</i></a></li>\");\n\t\t\n\t\t$('a', element).attr('data-remote','true');\n\t\t$('a', element).attr('data-tagname', name);\n\t\t$('a', element).attr('href', window.location.href + '/?tag=' + name);\n\t\tparent.append(element); \n\t\treturn element;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run Syncs options and build path, Also prompts user for required info before deploying.
run(config, compilerOptions) { let Uploader = this; // Set output to compiler output object. this.output = compilerOptions.output; // If options are passed, sync with class options. if (config.options) { this._syncOptions(config.options); } if (!this.options.autoRun && !argv.deploy) { return; } // Sync build path: this._syncBuildPath(); // Display Header for Deployer this.log('', 'HEADER'); // Check aws config this._checkEnvironmentConfig(config.environments, (error, env) => { if (error) { this.log(error, 'ERROR'); process.exit(0); } // Display environment they are deploying to: this.log(`You are deploying to the ${env} environment`); // If deploying, prompt for a deploy message. promptly.prompt( '[Deployer]: What is this deploy about? ', {'default': 'No deploy message specified.'}, (error, value) => { this.deployMessage = '[' + this.env + '] ' + value; this._createDeployFile(); this._createRobotsFile(); this._initializeDeploy(config); } ); }); }
[ "function upload(options, git_data) {\n\tvar rsync = new Rsync();\n\n\t// glob files\n\tglob(package_files, {\n\t\tabsolute: true\n\t}, function(error, files) {\n\t\tvar dest, path;\n\n\t\tif (error) throw error;\n\n\t\tconsole.log(chalk.green('Uploading ' + files.length + ' packages to ' + options.host + '...'));\n\n\t\tpath = options.path + '/' + options.package_name + '/' + git_data.branch + '/' + git_data.tag;\n\t\tdest = (options.user ? options.user + '@' : '') +\n\t\t\toptions.host + ':' + path;\n\n\t\trsync\n\t\t\t.flags('z')\n\t\t\t.set('rsync-path', 'mkdir -p ' + path + ' && rsync')\n\t\t\t.source(files)\n\t\t\t.destination(dest);\n\n\t\trsync.execute(function(error, code, cmd) {\n\t\t\tif (error) {\n\t\t\t\tconsole.error('Rsync error: ' + error.message + ' ' + cmd);\n\t\t\t\tprocess.exit(code);\n\t\t\t}\n\t\t});\n\t});\n}", "function runPublishScript() {\n\n const script = [];\n\n // merge dev -> master\n script.push(\n \"git checkout dev\",\n \"git pull\",\n \"git checkout master\",\n \"git pull\",\n \"git merge dev\",\n \"npm install\");\n\n // version here to all subsequent actions have the new version available in package.json\n script.push(\"npm version patch\");\n\n // push the updates to master (version info)\n script.push(\"git push\");\n\n // package and publish to npm\n script.push(\"gulp publish:packages\");\n\n // merge master back to dev for updated version #\n script.push(\n \"git checkout master\",\n \"git pull\",\n \"git checkout dev\",\n \"git pull\",\n \"git merge master\",\n \"git push\");\n\n // always leave things on the dev branch\n script.push(\"git checkout dev\");\n\n return chainCommands(script);\n}", "function startBrowserSync() {\n var options = {\n server: {\n baseDir: project.destinations.build,\n routes: {\n \"/bower_components\": \"bower_components\",\n \"/src/app\": project.sources.main\n },\n directory: false\n },\n ghostMode: false,\n logFileChanges: true,\n notify: true,\n reloadDelay: 0\n };\n\n browserSync(options);\n}", "function setupDistBuild(cb) {\n context.dev = false;\n context.destPath = j('dist', context.assetPath);\n del.sync('dist');\n cb();\n}", "function main_runNode_BuildFileDiff(mysql_connection, callback) {\n console.log('Files Modified in Development, not reflected in Production: ');\n /*runNode(\"BuildFileDiff.js\", function () {\n callback();\n }, nodeCB);*/\n \n if(runOption_migrate_files_prod){\n BuildFileDiff.moveFiles(BuildFileDiff.getChanges(), true, callback);\n }else{\n BuildFileDiff.displayFileChanges(BuildFileDiff.getChanges(), callback);\n }\n}", "async function migrate() {\n\n github.authenticate({\n type: \"token\",\n token: settings.github.token\n });\n\n //\n // Sequentially transfer repo things\n //\n\n // transfer GitLab milestones to GitHub\n if (program.milestone) {\n await transferMilestones(settings.gitlab.projectId);\n }\n\n // transfer GitLab labels to GitHub\n if (program.label) {\n await transferLabels(settings.gitlab.projectId, true, settings.conversion.useLowerCaseLabels);\n }\n\n // Transfer issues with their comments; do this before transferring the merge requests\n if (program.issue) {\n await transferIssues(settings.github.owner, settings.github.repo, settings.gitlab.projectId);\n }\n\n if (program.mergerequest) {\n if (settings.mergeRequests.log) {\n // log merge requests\n await logMergeRequests(settings.gitlab.projectId, settings.mergeRequests.logFile);\n } else {\n await transferMergeRequests(settings.github.owner, settings.github.repo, settings.gitlab.projectId);\n }\n }\n\n console.log(\"\\n\\nTransfer complete!\\n\\n\");\n}", "_initializeDeploy(config) {\n\n // Configure and instantiate S3\n this._initializeS3(this.s3Config, (error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n // Get last character of build path\n let lastCharOfPath = this.buildPath.slice(-1);\n\n /**\n * If buildpath does not have a trailing slash, add it.\n */\n if (lastCharOfPath !== '/') {\n this.buildPath += '/';\n }\n\n // Grab the files, then go to the _uploadFiles method\n glob(this.options.pathGlob, {cwd: this.buildPath}, (error, files) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log('Deployer is now running.', 'SUCCESS');\n\n // Set the version variables for the files.\n this._setVersionVars((error, hash) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log(`Setting deployment to version: ${this.version}`);\n\n // Upload files to S3\n this._uploadFiles(files, (done, fileNum) => {\n\n if (done) {\n\n // Change cloudfront root object\n this._cloudfrontInvalidateEntryHtml((error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log(`Deployment finished successfully. ${fileNum} files uploaded.`, 'SUCCESS');\n\n // Check for slack notifs:\n this._configureSlack(config.options.slack, (success) => {\n\n if (success) {\n this.log('Slack has been notified.', 'SUCCESS');\n }\n });\n });\n }\n });\n });\n });\n });\n }", "async function run() {\n const commands = [addRepo, installPlugins, deploy]\n\n try {\n await status(\"pending\");\n\n process.env.XDG_DATA_HOME = \"/root/.helm/\"\n process.env.XDG_CACHE_HOME = \"/root/.helm/\"\n process.env.XDG_CONFIG_HOME = \"/root/.helm/\"\n \n // Setup necessary files.\n if (process.env.KUBECONFIG_FILE) {\n process.env.KUBECONFIG = \"./kubeconfig.yml\";\n await writeFile(process.env.KUBECONFIG, process.env.KUBECONFIG_FILE);\n }\n \n const helm = getInput(\"helm\") || \"helm3\";\n core.debug(`param: helm = \"${helm}\"`);\n\n for(const command of commands) {\n await command(helm);\n }\n\n await status(\"success\");\n } catch (error) {\n core.error(error);\n core.setFailed(error.message);\n await status(\"failure\");\n }\n}", "async installProject() {\n // git clone\n await this.gitClone();\n\n // run hook\n await this.install();\n }", "function deployDirectory() {\n console.log(chalk.bold('Deploying to BitBucket'));\n _command('npm run deploy-demo', (result) => {\n console.log(chalk.bold('Deployed!'));\n console.log('Site will be visible on ' + chalk.cyan(opts.demoUrl) + ' shortly.');\n\n done();\n });\n }", "function configure() {\n\n var rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n // Grab the user's API keys for Stormpath and FullContact, then store them in\n // the configuration file.\n async.waterfall([\n function(cb) {\n mkdirp(CONFIG_DIR, function(err, made) {\n if (err) {\n cb(new Error(\"ERROR: Can't create configuration directory:\", CONFIG_DIR));\n }\n cb();\n });\n },\n function(cb) {\n rl.question(\"Enter your Stormpath API Key ID: \", function(id) {\n cb(null, id.trim());\n });\n },\n function(id, cb) {\n rl.question(\"Enter your Stormpath API Key Secret: \", function(secret) {\n cb(null, id, secret.trim());\n });\n },\n function(id, secret, cb) {\n rl.question(\"Enter your Mailchimp API Key: \", function(key) {\n cb(null, id, secret, key.trim());\n });\n },\n function(id, secret, key, cb) {\n fs.writeFile(CONFIG_FILE, JSON.stringify({\n stormpath_api_key_id: id,\n stormpath_api_key_secret: secret,\n mailchimp_api_key: key,\n }, null, 2), function(err) {\n if (err) {\n console.log(\"ERROR: Can't write configuration file:\", CONFIG_FILE);\n cb(err);\n }\n cb();\n });\n },\n ], function(err) {\n rl.close();\n });\n\n}", "_createDeployFile() {\n\n if (this.options.generateDeployFile) {\n\n // Write the deploy message to the deploy.txt\n fs.writeFile(`${this.buildPath}/deploy.txt`, this.deployMessage, (error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n this.log(`deploy.txt was unable to be created.`, 'ERROR');\n process.exit(0);\n }\n\n this.log('deploy.txt was created.');\n });\n }\n }", "function generateServeTask(overrides) {\n var options = utils.merge(OPTIONS, overrides);\n\n var task = function serve(done) {\n browserSync.init({\n ghostMode: false,\n open: false,\n server: {\n baseDir: 'dist'\n }\n }, done);\n };\n task.displayName = options.name;\n task.description = 'Start development server.';\n task.options = options;\n\n return task;\n}", "_promptLoop() {\n // If there are still projects, ask about the next one\n if (this._sortedProjectList.length) {\n return this._askQuestions(this._sortedProjectList.pop())\n .then((answers) => {\n if (answers) {\n // Save the info into the changefile\n let changeFile = this._changeFileData.get(answers.packageName);\n if (!changeFile) {\n changeFile = {\n changes: [],\n packageName: answers.packageName,\n email: undefined\n };\n this._changeFileData.set(answers.packageName, changeFile);\n }\n changeFile.changes.push(answers);\n }\n // Continue to loop\n return this._promptLoop();\n });\n }\n else {\n this._warnUncommittedChanges();\n // We are done, collect their email\n return this._detectOrAskForEmail().then((email) => {\n this._changeFileData.forEach((changeFile) => {\n changeFile.email = email;\n });\n this._writeChangeFiles();\n });\n }\n }", "function deploy(cb) {\n console.log(\"deploying with the role name 'assigner' in metadata ...\");\n var req = {\n fcn: \"init\",\n args: [],\n metadata: new Buffer(\"assigner\")\n };\n if (devMode) {\n req.chaincodeName = chaincodeName;\n } else {\n req.chaincodePath = \"github.com/asset_management_with_roles/\";\n }\n var tx = deployer.deploy(req);\n tx.on('submitted', function (results) {\n console.log(\"deploy submitted: %j\", results);\n });\n tx.on('complete', function (results) {\n console.log(\"deploy complete: %j\", results);\n chaincodeID = results.chaincodeID;\n console.log(\"chaincodeID:\" + chaincodeID);\n return cb();\n });\n tx.on('error', function (err) {\n console.log(\"deploy error: %j\", err.toString());\n return cb(err);\n });\n}", "function buildSite (cb, options, environment = 'development') {\n const args = options ? hugoArgsDefault.concat(options) : hugoArgsDefault\n\n process.env.NODE_ENV = environment\n\n return spawn(hugoBin, args, {stdio: 'inherit'}).on('close', (code) => {\n if (code === 0) {\n browserSync.reload()\n cb()\n } else {\n browserSync.notify('Hugo build failed :(')\n cb(new Error('Hugo build failed'))\n }\n })\n}", "function deployChaincode() {\n\t// Construct the deploy request\n\tvar deployRequest = {\n\t\t// Path (under $GOPATH/src) required for deploy in network mode\n\t\tchaincodePath: \"crowd_fund_chaincode\",\n\t\t// Function to trigger\n\t\tfcn: \"init\",\n\t\t// Arguments to the initializing function\n\t\targs: [\"key1\", \"key_value_1\"],\n\t};\n\n\t// Trigger the deploy transaction\n\tvar deployTx = app_user.deploy(deployRequest);\n\n\t// Print the successfull deploy results\n\tdeployTx.on('complete', function (results) {\n\t\t// Set the chaincodeID for subsequent tests\n\t\tchaincodeID = results.chaincodeID;\n\t\tconsole.log(util.format(\"Successfully deployed chaincode: request=%j, \" +\n\t\t\t\"response=%j\" + \"\\n\", deployRequest, results));\n\t\t// The chaincode is successfully deployed, start the listener port\n\t\tstartListener();\n\t});\n\tdeployTx.on('error', function (err) {\n\t\t// Deploy request failed\n\t\tconsole.log(util.format(\"ERROR: Failed to deploy chaincode: request=%j, \" +\n\t\t\t\"error=%j\", deployRequest, err));\n\t\tprocess.exit(1);\n\t});\n}", "function snap(bplateName, projectDir, options) {\n // find the boilerplate\n const bplate = path.join(os.homedir(), '.snap', bplateName);\n if (!fs.pathExistsSync(bplate)) {\n console.log(`\\n${chalk.red('Error:')} ${chalk.yellow(bplateName)} does not exist.\\n`);\n return;\n }\n\n const projectPath = path.resolve(projectDir);\n // check if the project directory is already taken\n if (fs.pathExistsSync(projectPath)) {\n console.log(`\\n${chalk.red('Error:')} ${chalk.cyan(projectPath)} already exists.\\n`);\n return;\n }\n\n // copy the boilerplate\n console.log('\\nCopying...');\n fs.copySync(bplate, projectPath);\n\n if (options.install) {\n console.log(`Running '${chalk.yellow('npm install')}'...`);\n shell.exec(`cd ${projectDir} && npm install`);\n }\n\n console.log(chalk.green('\\nSuccess! \(^O^)/'));\n console.log(`You can now ${chalk.yellow(`cd ${projectDir}`)}\\n`);\n}", "function executeCommand(cmd, root){\n cmd = root ? 'sudo ' + cmd : cmd;\n grunt.verbose.writeln('Executing: ' + cmd);\n\n exec(cmd, function(error, stdout, stderr){\n if(stderr.indexOf('have write permissions') !== -1){\n grunt.log.errorlns('It seems that you don\\'t have write permissions for this directory. Executing as root, you may be required to type your root password below:');\n return executeCommand(cmd, true);\n } else if(stderr.indexOf('multipart-post (~> 1.2.0)') !== -1){\n grunt.log.errorlns('An error occured with a Ruby dependency, trying to resolve the issue');\n return exec('gem install multipart-post -v 1.2.0', function(error, stdout, stderr){\n if(!error){\n return executeCommand(cmd, true);\n }\n });\n } else if(error !== null){\n return deferred.reject(stderr, 'fatal');\n }\n \n // Next step here ...\n deferred.resolve(stdout);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pop a byte from the stack.
popByte() { const value = this.readByte(this.regs.sp); this.regs.sp = inc16(this.regs.sp); return value; }
[ "pop() {\n if(this.stack.length == 0) {return null\n }\n\n return this.stack[this.top--];\n }", "pop() {\r\n return this._msgStack.pop()\r\n }", "popWord() {\n const lowByte = this.popByte();\n const highByte = this.popByte();\n return word(highByte, lowByte);\n }", "popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }", "pop_interrupt() {\n return this.interrupts.pop();\n }", "pop(){\n\t\tif(this.q1.length == 0)\n\t\t\treturn null;\n\t\tthis.size--;\n\t\treturn q1.shift()\n\t}", "function jsonPop(key) {\n\n\tvar type = Object.prototype.toString.call(this).slice(8, -1);\n\t\t\t\t\t\t\n\tif ( type === 'Object' ) {\n\tfor ( var k in this ) {\n\t\tif ( k === key ) { \n\n\t\t\tvar val = this[k];\n\t\t\t\t\n\t\t\t\tdelete this[key]\n\t\t\t\treturn val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse return undefined\n\t}", "minus() {\n this._lastX = this.pop();\n let first = this.pop();\n this._stack.push(first - this._lastX);\n }", "stackPush(byte) {\n this.writeRam({ address: 0x0100 + this.cpu.sp, value: byte });\n this.decrementRegister('sp');\n }", "popActive() {\n\t\t\tif(!this._activeStack.length) throw new Error(\"Active stack for \"+this.name+\" is empty and requested pop.\");\n\t\t\tthis._activeStack.pop().becomeActive();\n\t\t}", "pushByte(value) {\n this.write(\">\" + \"+\".repeat(value));\n this.stack.push(StackEntry(DataType.Byte, 1));\n }", "dequeue() {\n if(this.stack2.length === 0 ){\n if(this.stack1.length===0){return'cannot dequeue stack is empty'}\n while(this.stack1.length>0){\n let p = this.stack1.pop();\n this.stack2.push(p);\n }\n }\n return this.stack2.pop();\n}", "function popFront(arr){\n return removeAt(arr,0);\n}", "popBack() {\n const last = this.length - 1;\n const value = this.get(last);\n this._vec.remove(last);\n this._changed.emit({\n type: 'remove',\n oldIndex: this.length,\n newIndex: -1,\n oldValues: [value],\n newValues: []\n });\n return value;\n }", "function knockOffSym(aObj){\r\n\taObj.pop();\r\n}", "copyByte(depth, silent = false) {\n // push an empty value on top of the stack. [...a, 0]\n // ^\n if (silent) {\n this.write(\">\");\n } else {\n this.pushByte(0);\n }\n\n this.write(\"<\".repeat(depth + 1)); // go to the variable's slot\n this.write(\"[\"); // repeat until the slot is 0.\n this.write(\">\".repeat(depth + 1)); // go to top of stack\n this.write(\"+\"); // increment the value at the top.\n this.write(\">+\"); // go one step forward, and increment that value too.\n this.write(\"<\".repeat(depth + 2)); // go back to slot\n this.write(\"-\"); // decrement.\n this.write(\"]\" + \">\".repeat(depth + 2)); // exit when the variable slot is zero.\n\n // after the move, our stack is : [0, ... a, a]\n // ^\n\n // now we want to copy the topmost a back into the original slot.\n this.write(\"[\"); // start loop, stop when the data ptr is 0\n this.write(\"<\".repeat(depth + 2)); // go to the original slot which is now 0.\n this.write(\"+\"); // increment it.\n this.write(\">\".repeat(depth + 2)); // come back to the copy\n this.write(\"-\"); // decrement.\n this.write(\"]<\"); // repeat until copy is 0. and then pop it.\n }", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "peek(){\n\n if(!this.top){\n return 'Stack is empty.';\n\n }\n try{\n return this.top.value;\n } \n catch(err){\n return 'Stack is empty.';\n }\n }", "function cachePop(direction, id, value) {\n var pushStack, popStack\n cacheMapping[id] = value\n\n if (direction === 'forward') {\n pushStack = cacheBackStack\n popStack = cacheForwardStack\n } else {\n pushStack = cacheForwardStack\n popStack = cacheBackStack\n }\n\n pushStack.push(id)\n id = popStack.pop()\n if (id) delete cacheMapping[id]\n\n // Trim whichever stack we just pushed to to max cache length.\n trimCacheStack(pushStack, pjax.defaults.maxCacheLength)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for postV3UserKeys
postV3UserKeys(incomingOptions, cb) { const Gitlab = require('./dist'); let defaultClient = Gitlab.ApiClient.instance; // Configure API key authorization: private_token_header let private_token_header = defaultClient.authentications['private_token_header']; private_token_header.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //private_token_header.apiKeyPrefix = 'Token'; // Configure API key authorization: private_token_query let private_token_query = defaultClient.authentications['private_token_query']; private_token_query.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //private_token_query.apiKeyPrefix = 'Token'; let apiInstance = new Gitlab.UserApi() /*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | apiInstance.postV3UserKeys(incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => { if (error) { cb(error, null) } else { cb(null, data) } }); }
[ "postV3UsersIdKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.UsersApi()\n/*let id = 56;*/ // Number | The ID of the use\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3UsersIdKeys(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "static add(userEntry){\n\t\tlet kparams = {};\n\t\tkparams.userEntry = userEntry;\n\t\treturn new kaltura.RequestBuilder('userentry', 'add', kparams);\n\t}", "function signUser(req,res,next){\n //first param is the payload, second param is the privatekey\n //async - this token will be valid for 3h\n jwt.sign({user:res.locals[\"userData\"]}, secretKey, {expiresIn: '3h' }, (err, token) => {\n if(err) throw err;\n var userToSend = res.locals[\"userData\"]\n userToSend.token = token\n res.send(userToSend);\n });\n}", "async createApiKey (obj, args, context) {\n try {\n return {\n key: await WIKI.models.apiKeys.createNewKey(args),\n responseResult: graphHelper.generateSuccess('API Key created successfully')\n }\n } catch (err) {\n return graphHelper.generateError(err)\n }\n }", "function addKeysToDb(uid, keys){\r\n var dataref = database.ref('issuer/' + uid + '/keys');\r\n dataref.set(keys);\r\n}", "putV3UsersIdBlock(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.UsersApi()\n/*let id = 56;*/ // Number | The ID of the user\napiInstance.putV3UsersIdBlock(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "getV3UsersIdKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.UsersApi()\n/*let id = 56;*/ // Number | The ID of the user\napiInstance.getV3UsersIdKeys(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "dbSaveUser(user) {\n let userInfo = {\n email: user.email ? user.email : null,\n displayName: user.displayName ? user.displayName : null\n };\n // Overrides any key data given, which is cool for us\n firebase.database().ref('users/' + user.uid).update(userInfo);\n }", "post(data, callback) {\n // Check fro required field(s)\n const phone =\n typeof data.payload.phone === 'string'\n && data.payload.phone.trim().length === 10\n ? data.payload.phone.trim()\n : false;\n\n const password =\n typeof data.payload.password === 'string'\n && data.payload.password.trim().length\n ? data.payload.password.trim()\n : false;\n\n if(phone && password) {\n // Lookup matching user\n _data.read('users', phone, (err, userData) => {\n if(!err && userData) {\n // Hash the sent password\n const hashedPassword = helpers.hash(password);\n if(hashedPassword === userData.hashedPassword) {\n // If valid create a new random token, set expiration 1 hour in the future\n const id = helpers.createRandomString(20);\n const expires = Date.now() + 1000 * 60 * 60;\n const tokenObject = {\n phone,\n id,\n expires\n };\n\n // Store the token\n _data.create('tokens', id, tokenObject, err => {\n if(!err) {\n callback(200, tokenObject);\n }\n else {\n callback(500, { Error: 'Couldn\\'t create new token' });\n }\n })\n }\n else {\n callback(400, { Error: 'Incorrect password' });\n }\n }\n else {\n callback(400, { Error: 'Couldn\\'t find user' });\n }\n })\n }\n else {\n callback(400, { Error: 'Missing required fields' });\n }\n }", "postV3UsersIdEmails(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.UsersApi()\n/*let id = 56;*/ // Number | The ID of the use\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3UsersIdEmails(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function addUserToSharePointGroup(groupID, key) {\n\n\n console.log(groupID + ' : ' + key);\n\n \n\n var siteUrl = '/asaalt/hqdag8/quad';\n\n var clientContext = new SP.ClientContext(siteUrl);\n var collGroup = clientContext.get_web().get_siteGroups();\n var oGroup = collGroup.getById(groupID);\n var userCreationInfo = new SP.UserCreationInformation();\n //userCreationInfo.set_email('david.m.lewandowsky.ctr@mail.mil');\n userCreationInfo.set_loginName(key);\n //userCreationInfo.set_title('MAINTENANCE TEST PILOT');\n this.oUser = oGroup.get_users().add(userCreationInfo);\n \n clientContext.load(oUser);\n clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));\n \n\n}", "function createUser(userid){\n users[userid] = { \"userid\": userid.toString(), \"inventory\": [\"laptop\"], \"roomid\": \"strong-hall\"};\n saveState();\n}", "putV3UsersIdUnblock(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.UsersApi()\n/*let id = 56;*/ // Number | The ID of the user\napiInstance.putV3UsersIdUnblock(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "function createToken(user) {\n var token = jsonwebtoken.sign({\n firstname: user.firstname,\n lastname: user.lastname,\n username: user.username,\n usertype: user.usertype,\n email: user.email\n }, secretKey);\n return token;\n}", "function finishedCreatingCallback(err, usersForCloudFormation, IAMuserPassword, groupName) {\n if(err) {\n cloudformationsender.sendResponse(theEvent, theContext, \"FAILED\", {});\n\t}\n\telse {\t\n\t cloudformationsender.sendResponse(theEvent, theContext, \"SUCCESS\", {\n \"IamPassword\": IAMuserPassword,\n \"Users\": usersForCloudFormation,\n \"IamGroup\": groupName \n });\n }\n}", "hashedCacheKey(address, username, callbackHash) {\n return JSON.stringify([address, username, callbackHash]);\n }", "function put() {\n let data = {\n name: userInfo.elements.name.value,\n firstname: userInfo.elements.firstname.value,\n lastname: userInfo.elements.lastname.value,\n email: userInfo.elements.email.value,\n password: userInfo.elements.password.value\n };\n\n let postData = JSON.stringify(data);\n\n fetch(`https://smackfly-2fd1.restdb.io/rest/users-fly-smacker/${id}`, {\n method: \"put\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"x-apikey\": \"5de40f274658275ac9dc2152\",\n \"cache-control\": \"no-cache\"\n },\n body: postData\n }\n)\n.then(d => d.json())\n.then( updatedUser => {\n userInfo.elements.name.value=updatedUser.name,\n userInfo.elements.firstname.value=updatedUser.firstname;\n userInfo.elements.lastname.value=updatedUser.lastname;\n userInfo.elements.email.value=updatedUser.email;\n userInfo.elements.password.value=updatedUser.password;\n\n updateUserBtn.textContent = \"Success!\";\n updateUserBtn.style.backgroundColor = \"#fca91f\";\n});\n}", "function saveAndPublishUserData(resp) {\n user.name = resp.data.name;\n user.email = resp.data.email;\n user.id = resp.data._id;\n localStorage.setItem('user', JSON.stringify(user)); \n}", "function KTouchUserXApiSync(kTouchUser) {\n\tthis.kTouchUser = kTouchUser;\n\n\tthis.statements = [];\n\tthis.statementIndex = 0;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the CommandLineStringParameter with the specified long name.
getStringParameter(parameterLongName) { return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.String); }
[ "getFlagParameter(parameterLongName) {\n return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Flag);\n }", "getChoiceParameter(parameterLongName) {\n return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Choice);\n }", "getStringListParameter(parameterLongName) {\n return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.StringList);\n }", "getIntegerParameter(parameterLongName) {\n return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Integer);\n }", "function ServerBehavior_getParameter(name)\n{\n var paramVal = null;\n var undefined; // Use to compare against 'undefined' type\n \n // Note: be careful about when we use the old parameter value. We only want do this\n // if the new version of the parameter is undefined. We may have assigned the\n // new version of the parameter to null, so we must check for '!== undefined'.\n if (this.bInEditMode && this.applyParameters && this.applyParameters[name] !== undefined)\n {\n paramVal = this.applyParameters[name];\n }\n else if (this.parameters[name] !== undefined)\n {\n paramVal = this.parameters[name];\n }\n return paramVal;\n}", "get arg1() {\n const { 1: first } = __classPrivateFieldGet(this, __command);\n return first;\n }", "function getParam( name, defaultValue ) {\r\n\r\n if ( ng.isUndefined( defaultValue ) ) {\r\n\r\n defaultValue = null;\r\n\r\n }\r\n\r\n return( params[ name ] || defaultValue );\r\n\r\n }", "function ParameterKliVidnost(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0,1,2,3,4,5,6,7,8,9];\n}", "function ParameterKliRelVlaga(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.min = new Number(0);\n this.max = 100;\n}", "function getFlagValueFromArgv(name) {\n for (let i = 0; i < process.argv.length; i++) {\n let list = process.argv[i].split(\"=\");\n if (list[0] === `--${name}`)\n return list[1];\n }\n\n return undefined;\n}", "function extPart_getNodeParamName(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\", \"nodeParamName\");\n}", "function ParameterKliStanjeTal(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0,1,2,3,4,5,6,7,8,9];\n}", "function parameterDefine(num = 10, name = \"snn\", nullVal = \"***\") {\n console.log(\"1.\" + num); //return 10\n console.log(\"2.\" + name); //return coskun\n console.log(\"3.\" + nullVal); //return null \n}", "get arg2() {\n const { 2: sec } = __classPrivateFieldGet(this, __command);\n return Number(sec);\n }", "function ParameterKliSmerVetra(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32];\n}", "function ServerBehavior_setParameter(name, value)\n{\n if (this.bInEditMode)\n {\n this.applyParameters[name] = value;\n }\n else\n {\n this.parameters[name] = value; \n }\n}", "name() {\n return this._command.name;\n }", "function getParameterIdFromParameterType(layer, parameterType, id_name, cb) {\n try {\n _self.emit(\"log\", \"visits.js\", \"getParameterIdFromParameterType(\" + layer + \",\" + parameterType + \")\", \"info\");\n\n var dataToSend = {};\n dataToSend.layer = layer;\n dataToSend.parameterType = parameterType;\n dataToSend.id_name = id_name;\n dataToSend.token = _token;\n dataToSend.what = 'GET_PARAMETER_ID_FOR_PARAMETER_ID';\n dataToSend.expected_api_version = _expected_api_version;\n axios.post(_baseHref + '/ajax.sewernet.php', dataToSend).then(function (response) {\n _self.emit(\"log\", \"visits.js\", \"getParameterIdFromParameterType\", \"success\", response.data.message);\n\n if (response.data.status === \"Accepted\") {\n cb(null, response.data.message.parameter_id_options);\n } else {\n cb(response.data.message, false);\n }\n })[\"catch\"](function (error) {\n _self.emit(\"log\", \"visits.js\", \"getParameterIdFromParameterType error\", \"error\", error);\n\n cb(error, false);\n });\n } catch (e) {\n _self.emit(\"log\", \"visits.js\", \"getParameterIdFromParameterType error\", \"error\", e);\n\n cb(e, false);\n }\n }", "function longSpecType( )\n{\n var stype = \"Onbekend\";\n\n if(respecConfig.specType != null) \n {\n var stype = respecParams.validSpecTypes[respecConfig.specType].txt;\n }\n console.log(\"\\t\\tLong SpecType is [\" + stype + \"]\");\n return( stype );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method: checks if there is another shape with the desired prefix, and different suffixes for the various states. In this demo, it looks for faceInitial, faceSecond and faceFinal on the th iteration.
function hasNextShape () { shapeIndex++; startShapeId = startShapePrefix + shapeIndex + startShapeSuffix; intermediateShapeId = intermediateShapePrefix + shapeIndex + intermediateShapeSuffix; endShapeId = endShapePrefix + shapeIndex + endShapeSuffix; startShape = Y.one("#" + startShapeId); endShape = Y.one("#" + endShapeId); intermediateShape = Y.one("#" + intermediateShapeId); if (intermediateShape === null) { Y.log('intermediate shape ' + intermediateShapeId + ' is null'); } return startShape !== null && endShape !== null && intermediateShape !== null; }
[ "function checkCube() {\n//===============================\n var check = false;\n\n // Check each color\n for(face in colorMap) {\n // Check each sticker from that color\n $(\".color-\"+colorMap[face]).each(function() {\n\n // If the sticker isn't on the right face for its color\n // Then the cube hasn't been solved yet\n check = $(this).hasClass(\"pyramid-\"+face);\n return check;\n });\n\n if(!check) break;\n }\n\n return check;\n}", "function anyMiddlesCanBeSolved(cube) {\n if (middlesCanBeSolved(cube)) return true;\n\n U(cube);\n if (middlesCanBeSolved(cube)){\n Ui(cube);\n return true;\n }\n\n U(cube);\n if (middlesCanBeSolved(cube)){\n Ui(cube); Ui(cube);\n return true;\n }\n\n U(cube);\n if (middlesCanBeSolved(cube)){\n Ui(cube); Ui(cube); Ui(cube);\n return true;\n }\n\n Ui(cube); Ui(cube); Ui(cube);\n return false;\n} //anyMiddlesCanBeSolved", "function renderShapeGrammar(iterations) {\n // ground\n // TODO: replace with real ground, and roads, etc\n var mat = new THREE.MeshLambertMaterial({color: new THREE.Color(0.67, 0.70, 0.75)});\n var mesh = new THREE.Mesh(new THREE.PlaneGeometry(200,200), mat);\n mesh.rotation.x = Math.PI / 2;\n mesh.material.side = THREE.DoubleSide;\n mesh.position.set(20,-0.1,20);\n mesh.receiveShadow = shadowsOn;\n mesh.castShadow = shadowsOn;\n scene.add(mesh);\n\n var set = initRender ? shapeGrammar.doIterations(iterations) : shapeGrammar.shapeSet;\n set.forEach((node) => {\n var geo = Geometry[node.shape].obj.clone();\n\n geo.rotation.set(node.rotation.x, node.rotation.y, node.rotation.z);\n geo.scale.set(node.scale.x, node.scale.y, node.scale.z);\n geo.position.set(node.position.x, node.position.y, node.position.z);\n\n var color = Geometry[node.shape].obj.material.color;\n \n geo.material = new THREE.MeshPhongMaterial(Geometry[node.shape].obj.material);\n geo.material.color = new THREE.Color(color.r, color.g, color.b)\n geo.material.color.addScalar(node.colorOffset);\n\n geo.traverse(function(child) {\n if (child instanceof THREE.Mesh) {\n child.material = geo.material;\n child.castShadow = shadowsOn;\n child.receiveShadow = shadowsOn;\n }\n });\n \n if (node.iteration <= iterations) {\n scene.add(geo);\n }\n rendered = true;\n });\n}", "function middlesCanBeSolved(cube) {\n if ( ((cube[front][1][0] == 'B') && (cube[up][1][2] == 'R')) || ((cube[front][1][0] == 'B') && (cube[up][1][2] == 'O')) || ((cube[left][1][0] == 'O') && (cube[up][0][1] == 'B')) || ((cube[left][1][0] == 'O') && (cube[up][0][1] == 'G')) || ((cube[back][1][0] == 'G') && (cube[up][1][0] == 'O')) || ((cube[back][1][0] == 'G') && (cube[up][1][0] == 'R')) || ((cube[right][1][0] == 'R') && (cube[up][2][1] == 'G')) || ((cube[right][1][0] == 'R') && (cube[up][2][1] == 'B')) ) {\n return true;\n }\n else return false;\n}", "function filterShape(aliens) {\n return aliens.shape == $shapeInput.value.trim().toLowerCase();\n}", "function middleEdgesSolved(cube) {\n if ((cube[front][2][1] == 'B') && (cube[front][0][1] == 'B') && (cube[right][2][1] == 'R') && (cube[right][0][1] == 'R') && (cube[back][2][1] == 'G') && (cube[back][0][1] == 'G') && (cube[left][2][1] == 'O') && (cube[left][0][1] == 'O')) return true;\n else return false;\n}", "function solveAvailableMiddles(cube) {\n while(middlesCanBeSolved(cube) == true){\n if ((cube[front][1][0] == 'B') && (cube[up][1][2] == 'R')) solveBlueRed(cube);\n if ((cube[front][1][0] == 'B') && (cube[up][1][2] == 'O')) solveBlueOrange(cube);\n if ((cube[left][1][0] == 'O') && (cube[up][0][1] == 'B')) solveOrangeBlue(cube);\n if ((cube[left][1][0] == 'O') && (cube[up][0][1] == 'G')) solveOrangeGreen(cube);\n if ((cube[back][1][0] == 'G') && (cube[up][1][0] == 'O')) solveGreenOrange(cube);\n if ((cube[back][1][0] == 'G') && (cube[up][1][0] == 'R')) solveGreenRed(cube);\n if ((cube[right][1][0] == 'R') && (cube[up][2][1] == 'G')) solveRedGreen(cube);\n if ((cube[right][1][0] == 'R') && (cube[up][2][1] == 'B')) solveRedBlue(cube);\n }\n}", "function extUtils_isDependentNodeSegment(nodeSeg, countFamilyAsOne)\n{\n var retVal = false;\n\n var num = 0; family = '';\n var sbList = dw.serverBehaviorInspector.getServerBehaviors();\n var sbPartList = null; // SBParticipant list\n\n for (var i=0; !retVal && i < sbList.length; i++) //search all ServerBehaviors\n {\n if (sbList[i].getParticipants)\n {\n sbPartList = sbList[i].getParticipants();\n for (j=0; !retVal && j < sbPartList.length; j++) //scan SB participantNames\n {\n var ns = sbPartList[j].getNodeSegment();\n if (ns.equals(nodeSeg))\n {\n if (countFamilyAsOne && num > 0)\n {\n if (!sbList[i].getFamily() || sbList[i].getFamily() != family)\n {\n num++;\n }\n }\n else\n {\n num++;\n if (countFamilyAsOne && sbList[i].getFamily())\n {\n family = sbList[i].getFamily();\n }\n }\n if (num > 1)\n {\n retVal = true;\n }\n break; //only count one reference per ServerBehavior\n }\n }\n }\n else\n { // Handle UD1 and UD4 Server Behavior objects\n var parts = sbList[i].participants;\n for (j=0; !retVal && j < parts.length; j++) { //scan ssRec participantNames\n if (parts[j] == nodeSeg.node) {\n if (countFamilyAsOne && num > 0) {\n if (!sbList[i].family || sbList[i].family != family) {\n num++;\n }\n } else {\n num++;\n if (countFamilyAsOne && sbList[i].family) {\n family = sbList[i].family;\n }\n }\n if (num > 1) {\n retVal = true;\n }\n break; //only count one reference per ssRec\n }\n }\n }\n }\n\n return retVal;\n}", "moveFace() {\n if (this.raycaster.ray.intersectPlane(this.plane, this.intersection)) {\n if (this.selected_face == this.group.getObjectById(this.closet_faces_ids[3])) { //If the selected face is the right one\n\n var rightFacePosition = this.intersection.x - this.offset + this.selected_face.position.x; //Position of the right closet face\n\n if (this.closet_slots_faces_ids.length == 0) { //If there are no slots\n this.selected_face.position.x = rightFacePosition;\n this.closet.changeClosetWidth(rightFacePosition);\n this.updateClosetGV();\n\n } else {\n var rightSlotPosition = this.group.getObjectById(this.closet_slots_faces_ids[this.closet_slots_faces_ids.length - 1]).position.x; //Position of the last (more to the right) slot \n\n if (rightFacePosition - rightSlotPosition > rightSlotPosition) { //Checks if right face doesn't intersect the slot\n this.selected_face.position.x = rightFacePosition;\n this.closet.changeClosetWidth(rightFacePosition);\n this.updateClosetGV();\n }\n }\n } else if (this.selected_face == this.group.getObjectById(this.closet_faces_ids[2])) { //If the selected face is the left one\n\n var leftFacePosition = -this.intersection.x - this.offset - this.selected_face.position.x; //Position of the left closet face\n\n if (this.closet_slots_faces_ids.length == 0) { //If there are no slots\n this.selected_face.position.x = leftFacePosition;\n this.closet.changeClosetWidth(leftFacePosition);\n this.updateClosetGV();\n } else {\n var leftSlotPosition = -this.group.getObjectById(this.closet_slots_faces_ids[0]).position.x; //Position of the first (more to the left) slot\n\n if (leftFacePosition - leftSlotPosition > leftSlotPosition) { //Checks if left face doesn't intersect the slot\n this.selected_face.position.x = leftFacePosition;\n this.closet.changeClosetWidth(leftFacePosition);\n this.updateClosetGV();\n }\n }\n }\n }\n }", "function hasNewShapeType(proceed) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n return this.series.chart.is3d() ?\n this.graphic && this.graphic.element.nodeName !== 'g' :\n proceed.apply(this, args);\n}", "function isPrefix(word, prefix) {\n\treturn word.startsWith(prefix.slice(0, -1));\n}", "function gotSomethingDifferent(){\n if (prevDetections.length != detections.length){\n return true;\n }\n var prev = getCountedObjects(prevDetections);\n var curr = getCountedObjects(detections);\n for (var k in curr){\n if (curr[k] !== prev[k]){\n return true;\n }\n }\n for (var k in prev){\n if (prev[k] !== curr[k]){\n return true;\n }\n }\n return false;\n}", "function checkIndex(imageIndexCheck,previousIndex)\n{\n for(let x=0;x<3;x++){\n \n if(imageIndexCheck==previousImages[previousIndex][x]){\n \n return true;}\n else {\n continue;}\n\n \n }\nreturn false;\n}", "function checkMeshConnectivity({points, delaunator: {triangles, halfedges}}) {\n // 1. make sure each side's opposite is back to itself\n // 2. make sure region-circulating starting from each side works\n let r_ghost = points.length - 1, s_out = [];\n for (let s0 = 0; s0 < triangles.length; s0++) {\n if (halfedges[halfedges[s0]] !== s0) {\n console.log(`FAIL _halfedges[_halfedges[${s0}]] !== ${s0}`);\n }\n let s = s0, count = 0;\n s_out.length = 0;\n do {\n count++; s_out.push(s);\n s = TriangleMesh.s_next_s(halfedges[s]);\n if (count > 100 && triangles[s0] !== r_ghost) {\n console.log(`FAIL to circulate around region with start side=${s0} from region ${triangles[s0]} to ${triangles[TriangleMesh.s_next_s(s0)]}, out_s=${s_out}`);\n break;\n }\n } while (s !== s0);\n }\n}", "function isPrefix(trie, word){ \n for(let temp_word of trie){\n if( temp_word.substr(0, word.length) == word){\n return true;\n }\n }\n return false; \n}", "function checkCorner3(cube) {\n if( ((cube[up][0][0] == 'G') && (cube[back][2][0] == 'W') && (cube[left][0][0] == 'O')) || ((cube[up][0][0] == 'W') && (cube[back][2][0] == 'O') && (cube[left][0][0] == 'G')) || ((cube[up][0][0] == 'O') && (cube[back][2][0] == 'G') && (cube[left][0][0] == 'W')) ) return true;\n else return false;\n}", "function extUtils_onlyFamilyReferences(nodeSegment, familyName, ignoreOtherFamilies)\n{\n var retVal = false;\n var family = '';\n var onlyFamRefs = true;\n var sbList = dw.serverBehaviorInspector.getServerBehaviors();\n var sbPartList = null; //SBParticipant list\n\n for (var i=0; onlyFamRefs && i < sbList.length; i++) //search all ServerBehaviors\n {\n if (sbList[i].getParticipants)\n {\n sbPartList = sbList[i].getParticipants();\n for (j=0; onlyFamRefs && j < sbPartList.length; j++) //scan SB participantNames\n {\n var ns = sbPartList[j].getNodeSegment();\n if (ns.equals(nodeSegment))\n {\n if (!sbList[i].getFamily())\n {\n //no family, return false\n onlyFamRefs = false;\n break;\n }\n else if (!family)\n {\n family = sbList[i].getFamily();\n }\n else if (sbList[i].getFamily() != family)\n {\n onlyFamRefs = false;\n break;\n }\n }\n }\n }\n else\n { // Handle UD1 and UD4 Server Behavior objects\n var parts = sbList[i].participants;\n for (j=0; onlyFamRefs && j < parts.length; j++) { //scan ssRec participantNames\n if (parts[j] == nodeSegment.node) {\n if (!sbList[i].family) {\n //no family, return false\n onlyFamRefs = false;\n break;\n } else if (!family) {\n family = sbList[i].family;\n } else if (sbList[i].family != family) {\n onlyFamRefs = false;\n break;\n }\n }\n }\n }\n }\n\n //return true if onlyFamRefs is true, and a family value has been set\n retVal = (onlyFamRefs && family && (!familyName || familyName == family));\n\n if (retVal)\n {\n\t//if in the ignore other families list , ignore them\n\tif (family && family.length)\n\t{\n\t\tif (ignoreOtherFamilies && ignoreOtherFamilies.length && (family.indexOf(ignoreOtherFamilies) != -1))\n\t\t{\n\t\t\tretVal = false;\n\t\t}\n\t}\n }\n\n return retVal;\n}", "equals(face) {\n\n // Throw an error if face is not a Face\n validate({ face }, 'Face');\n\n // Check that the faces equal the same value\n return (this.toString() === face.toString());\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 }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a placeholder function to install as a global in place of a function that may be available after snapshot load, at runtime. Uses the current state of globalFunctionTrampoline to either call the real function or throw an appropriate error for improper use.
function makeGlobalPlaceholder(globalFunctionName) { return function() { if (globalFunctionTrampoline === null) { throw new Error(`Attempt to call ${globalFunctionName} during snapshot generation or before snapshotResult.setGlobals()`) } else if (globalFunctionTrampoline[globalFunctionName] === undefined) { throw new ReferenceError(`Global method ${globalFunctionName} was still not defined after the snapshot was loaded`) } else if (new.target === undefined) { // Not called as a constructor return globalFunctionTrampoline[globalFunctionName](...arguments) } else { // Called as a constructor return new globalFunctionTrampoline[globalFunctionName](...arguments) } } }
[ "function wrapFunction(fun, contentGlobal) {\n return function () {\n let result = fun.apply(this, arguments);\n if (typeof result === 'object') {\n if (('then' in result) && (typeof result.then === 'function')) {\n // fun returned a promise.\n return createPromiseInPage((resolve, reject) => result.then(resolve, reject), contentGlobal);\n }\n return Components.utils.cloneInto(result, contentGlobal);\n }\n return result;\n }\n}", "function LocalCache( fn, initCalls, timeout ) {\n\n var cachedFunction = function() {\n return cachedFunction.this( this || cachedFunction._this ).apply( argumentsToArray( arguments ) )\n }\n\n cachedFunction.__proto__ = LocalCache.prototype;\n\n cachedFunction.fn = fn;\n cachedFunction.calls = initCalls || {};\n cachedFunction.timeout = timeout || -1;\n cachedFunction._this = null;\n cachedFunction.forceNext = false;\n\n return cachedFunction;\n\n}", "function createFunction() {\n\tlet hello = \"hello\";\n\tfunction holla() {\n\t\tconsole.log(hello);\n\t}\n\treturn holla;\n}", "function myFunc1(param) {\n\tconsole.log('I am the new myFunc - I have replaced the original version even tho I am declared after the call to me in the code. This is because all function declarations are loaded, including overloaded function decs, before any code is executed. I recieved '+param);\n}", "function addNewFuncExpr() {\r\n\r\n // if any grid is currently highlighted, remove that highlight first\r\n // This is important if the user replaces a grid expression with an\r\n // operator\r\n //\r\n removeGridHighlight();\r\n\r\n\r\n // Get the new function name from the user and check for duplicate names\r\n // TODO: Check among grid names of function and let names of the step\r\n //\r\n var isdup = true;\r\n\r\n do {\r\n var fname = prompt(\"Name of new function\", DefFuncName);\r\n\r\n // If user pressed cancel, just return\r\n //\r\n if (!fname)\r\n return;\r\n\r\n isdup = isExistingFuncName(CurModObj, fname);\r\n\r\n if (isdup) {\r\n alert(\"Function name \" + fname + \" already exists!\");\r\n }\r\n\r\n } while (isdup);\r\n\r\n\r\n // main root expression for the function\r\n //\r\n var funcExpr = new ExprObj(false, ExprType.FuncCall, fname);\r\n\r\n // Create a new func obj and record in the current module\r\n //\r\n var fO = new FuncObj();\r\n fO.funcCallExpr = funcExpr; // set reference to func expr\r\n\r\n CurModObj.allFuncs.push(fO); // add function to current module\r\n\r\n assert((fO.argsAdded < 0), \"Can't have any args yet\");\r\n\r\n // STEP A: -------------------------------------------------- \r\n //\r\n // Add return value (scalar grid).\r\n // NOTE: Return value is always a scalar. \r\n //\r\n // Create a scalar grid and add it to the Function Grids/Header\r\n //\r\n var newGId = fO.allGrids.length;\r\n //\r\n var newgO = new GridObj(newGId, DefRetValName, 1, 1,\r\n\t\t\t 1, 1, false, false, false, false);\r\n newgO.isRetVal = true;\r\n //\t\r\n // Record this grid in function header\r\n // Note: We add return value as the very first grid to function.\r\n // This is necessary for having a unique grid ID for each \r\n // Grid (return value is a grid). This is useful in showing\r\n // return *data* value. Also, user can directly assign to this.\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.allSteps[FuncHeaderStepId].allGridIds.push(newGId);\r\n //\r\n fO.argsAdded = 0; // indicates return value added\r\n\r\n // Add the data type to the arg grid. Return value is always integer\r\n //\r\n newgO.dataTypes.push(DataTypes.Integer);\r\n assert((newgO.dataTypes.length == 1), \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n // Redraw step to reflect the addition of the function\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n replaceOrAppendExpr(funcExpr);\r\n drawCodeWindow(CurStepObj); // redraw code window\r\n}", "function cacheFn(fn) {\n var cache = {};\n return function(arg) {\n if (cache[arg]) {\n return cache[arg];\n } else {\n cache[arg] = fn(arg);\n return cache[arg];\n }\n };\n}", "wrapToFunction(template, ...localVariables) {\n const args = ['template', 'state', 'ctx'].concat(localVariables);\n return new Function('', `return function template (${args.join(',')}) { ${template} }`)();\n }", "function set_target_function(exp, fake_object, function_ptr) {\n\t// RPC_MESSAGE -> RpcInterfaceInformation -> InterpreterInfo -> DispatchTable\n\tvar rpc_interface = exp.read_ptr(fake_object.add(0x28));\n\tvar midl_server_info = exp.read_ptr(rpc_interface.add(0x50));\n\tvar function_table = exp.read_ptr(midl_server_info.add(8));\n\texp.write_ptr(function_table.add(0), function_ptr); // Target\n}", "function insertLibFunc() {\r\n\r\n var pO = CurProgObj;\r\n\r\n var sel1 = document.getElementById('selWin');\r\n var libind = sel1.selectedIndex;\r\n\r\n var sel2 = document.getElementById('selWin2');\r\n var funcind = sel2.selectedIndex;\r\n\r\n // alert(\"TODO: Lib ind:\" + libind + \" funcind:\" + funcind);\r\n\r\n displayAtLastGrid(\"\");\r\n\r\n // Create a function call expression and insert it\r\n //\r\n removeGridHighlight();\r\n\r\n\r\n\r\n // main root expression for the function\r\n //\r\n var libM = pO.libModules[libind];\r\n var libF = libM.allFuncs[funcind];\r\n var libFexpr = libF.funcCallExpr;\r\n var fname = libM.name + \".\" + libFexpr.str;\r\n var funcExpr = new ExprObj(false, ExprType.LibFuncCall, fname);\r\n\r\n // Insert the dummy args so that user knows the number/type of args\r\n // required\r\n //\r\n for (var i = 0; i < libFexpr.exprArr.length; i++) {\r\n\r\n var argE = new ExprObj(true,\r\n libFexpr.exprArr[i].type,\r\n libFexpr.exprArr[i].str);\r\n funcExpr.addSubExpr(argE);\r\n }\r\n\r\n replaceOrAppendExpr(funcExpr);\r\n drawCodeWindow(CurStepObj); // redraw code window\r\n}", "function insertFuncArg(fcallexpr, arg) {\r\n\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind]; // change CurFuncObj\r\n var sO = CurStepObj;\r\n\r\n assert((arg < fcallexpr.exprArr.length), \"invalid arg position \" +\r\n arg);\r\n\r\n // Particular argument expr in the function *call*\r\n //\r\n var argexpr = fcallexpr.exprArr[arg];\r\n assert(argexpr, \"ERROR: argexpr cannot be null\");\r\n\r\n // arg pos in the header. We add 1 because the first expr is the return\r\n // expression\r\n //\r\n var arggrid = arg + 1;\r\n\r\n // Point the default functionCallExpr in function to this function call\r\n // because updateOtherFuncCalls() depend on this \r\n //\r\n fO.funcCallExpr = fcallexpr;\r\n\r\n // STEP:\r\n //\r\n // Process arg expr in the func *call* and add the corresponding grid\r\n // to function grids (and header step) \r\n //\r\n if (argexpr.isScalarExpr() || argexpr.isGridCell() || argexpr.isLetName()) {\r\n\r\n // SCALAR args\r\n // if this is a number. Create a scalar grid and add push\r\n // to arg list\r\n //\r\n var newGId = fO.allGrids.length; // grid id at the end\r\n\r\n var newgO = new GridObj(newGId, \"param\" + arg, 1, 1,\r\n 1, 1, false, false, false, false);\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // incoming arg const by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n // If this is a grid cell AND user needs a reference (Don't know\r\n // how to detect this yet), create an *additional* reference\r\n // grid object and record it in newgO (scalar grid). \r\n // We do this to enable an arg to be used as either a scalar\r\n // value or a reference\r\n //\r\n if (0 && argexpr.isGridCell()) { // <--- NOTE 0 \r\n\r\n alert(\"TODO: Handle this case if necessary\");\r\n\r\n /*\r\n\t // TODO: Currently we don't use this 'hidden' reference\r\n\t // grid. Allow switching to this.\r\n\r\n\t // If we pass a grid cell as a *reference* \r\n\t // (not as a sclar val)\r\n\t // it is similar to passing a whole grid reference plus\r\n\t // a set of indices to point to the correct cell\r\n\t // So, this case is similar to isGridRef case.\r\n\t //\r\n\t // NOTE: We use the same 'newGId' as the scalar because\r\n\t // this represents the same grid as scalar arg\r\n\t //\r\n\t var refgO = new cloneGridObj(newGId, argexpr.gO);\r\n\t refgO.caption = \"param\" + arg; // same name as salar\r\n\r\n\r\n\t // This is a grid cell reference. Which will indicate to \r\n\t // draw index values in the arg like Src[arg1,arg2,arg3]\r\n\t //\r\n\t refgO.isGridCellRef = true;\r\n\t \r\n\t // record this reference grid obj in the scalar grid\r\n\t //\r\n\t newgO.refgO = refgO;\r\n\r\n\t // Add the global data type to newgO\r\n\t //\r\n\t newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\t */\r\n\r\n } else if (argexpr.isGridCell()) {\r\n\r\n // scalar grid cell (passed by value)\r\n //\r\n newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\r\n } else if (argexpr.isLetName()) {\r\n\r\n // alert(\"ARGUMENT IS LET\");\r\n // Here do what needs to be done w.r.t. finding type of new grid\r\n\r\n var letType = findLetType(argexpr, CurModObj);\r\n newgO.dataTypes.push(letType);\r\n\r\n } else {\r\n\r\n // Add the global data type to newgO\r\n // NOTE: For all scalar types (even for a Number), we add type \r\n // integer. For a number, updateFuncArgType() is called\r\n // just after this so it's type will be updated correctly\r\n // \r\n newgO.dataTypes.push(DataTypes.Integer);\r\n }\r\n\r\n // Mark that scalar grid arg has globla data type\r\n //\r\n assert((newgO.dataTypes.length == 1),\r\n \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n\r\n } else if (argexpr.isGridRef()) {\r\n\r\n // This is a grid reference. So, make a cloned grid \r\n // and insert it to arg list and step\r\n // NOTE: When we genrate code for this new function, the caller\r\n // generates something like func( _out), where \r\n // _out = out.data. So, on the caller side, just introduce\r\n // an argumnet called argX. JavaScript will make\r\n // argX = _out = out.data automatically. There is nothing\r\n // more to do. Within the argument, we can refer to \r\n // the grid cells as argX[i][j] and it will point to \r\n // proper caller's data[]. \r\n //\r\n var newGId = fO.allGrids.length;\r\n var newgO = new cloneGridObj(newGId, argexpr.gO);\r\n newgO.caption = \"param\" + arg;\r\n newgO.isGridRef = true; // mark this as a ref arg\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // a ref grid is constat by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n } else {\r\n\r\n alert(\"TODO: Create grid for other ... arg\");\r\n }\r\n\r\n // if there are any other function call expressions that call the same\r\n // function update them -- i.e., insert a NeedUpdate argument, or \r\n // replace corresponding arg with a NeedUpdate arg\r\n //\r\n updateOtherFuncCalls(fO, arg, false);\r\n\r\n}", "function whatWasTheLocal() {\n var captured = \"local variable\";\n\n return function() {\n return \"Here is the \" + captured;\n }\n}", "function createFunctionWithInput(input){\n const x = input;\n function returnInput(){\n return x;\n }\n return returnInput;\n}", "inFunction(context, keyword) {\n doCheck(\n context.currentFunction !== null,\n `${keyword} can only be used in a function`\n );\n }", "function myFunctionToCallAnotherFunction() {\n myFunctionWithParam(\"called from inside a function!\");\n}", "function installFunction(end_point, functionName, callback, xsrf_token) {\n ajax_server[functionName] = function(opt_arg) {\n var type = xsrf_token ? 'POST' : 'GET';\n var async = (callback != null);\n\n var data = {};\n data.action = functionName;\n if (xsrf_token) {\n data.xsrf_token = xsrf_token;\n }\n data.time = new Date().getTime();\n if (opt_arg) {\n $.extend(data, opt_arg);\n }\n $.ajax(end_point, {\n type: type,\n async: async,\n data: data,\n dataType:\"text\",\n success: function(data){\n json_data = parseAjaxResponse(data);\n callback(json_data);\n },\n error: function (request, status, error) {\n console.log(status);\n console.log(error);\n }\n });\n };\n}", "function liftf(binaryFunction){\n\treturn function (x){\n\t\treturn function(y){\n\t\t\treturn binaryFunction(x, y)\n\t\t};\n\t}\n}", "function lookupExistingFunctionId(func) {\n var tokens = Object.keys(storedFunctionArguments);\n for (var i = 0, l = tokens.length; i < l; ++i) {\n var token = tokens[i];\n var functions = storedFunctionArguments[token];\n var functionIds = Object.keys(functions);\n for (var j = 0, k = functionIds.length; j < k; ++j) {\n var functionId = functionIds[j];\n if (functions[functionId] == func) return functionId;\n }\n }\n }", "function factory () {\n // Just forwards the call to the resolver by setting itself as context.\n function fn (value) {\n return resolver.call(fn, value);\n }\n\n created += 1;\n fn.id = created;\n\n // The state is attached to the function object so it's available to the\n // state-less functions when running under `this.`.\n fn.locks = 0;\n fn.chain = null;\n fn.resolved = [];\n fn.filters = [];\n fn.forks = [];\n\n // Expose the behaviour in the functor\n fn.pause = pause;\n fn.resume = resume;\n fn.filter = filter;\n fn.fork = fork;\n fn.merge = merge;\n fn.completed = completed;\n\n return fn;\n}", "function replaceFuncArg(fcallexpr, pos, newExpr) {\r\n\r\n // find the function object of this function call\r\n //\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind];\r\n //\r\n // find the gridObj corresponding to 'pos' in function header\r\n //\r\n var gidHead = fO.allSteps[FuncHeaderStepId].allGridIds[pos + 1];\r\n var gOhead = fO.allGrids[gidHead];\r\n\r\n // We ALWAYS check whether the newExpr and the grid in the function \r\n // prototype matches, when we do a replace.\r\n //\r\n if (newExpr.isScalarOrGridCell()) { // newExpr is scalar\r\n\r\n\r\n\tif (newExpr.isLetName()) {\r\n\r\n\t // if the new expression is a LetName, just check whether func arg\r\n\t // is scalar (because let is always sclar value)\r\n\t //\r\n\t if (gOhead.numDims > 0) {\r\n\t\talert(\"Existing argument in function header is not scalar\");\r\n\t\treturn false;\r\n\t }\r\n\t \r\n } else if (gOhead.numDims > 0) {\r\n\r\n // The function header has a non-scalar (i.e., a gridRef) arg\r\n //\r\n alert(\"Existing argument in function header is not scalar\");\r\n return false;\r\n\r\n } else if (gOhead.dataTypes[0] != findDataTypeOfScalarExpr(newExpr)) {\r\n\r\n // For a scalar grid, the data types must match. If not, the user\r\n // can change the function header (or use a different arg)\r\n //\r\n alert(\r\n \"Data Type mismatch. Use correct type arg OR change the \" +\r\n \" data type in function header\");\r\n\r\n return false;\r\n }\r\n\r\n } else { // newExpr is not scalar\r\n\r\n if (gOhead.numDims < 1) {\r\n\r\n alert(\"Existing argument in function header is scalar\");\r\n return false;\r\n }\r\n\r\n // TODO: Do other type checks here and return if not compatible.\r\n // E.g., (1) check \r\n\r\n\r\n\r\n }\r\n\r\n // We are here because the argument in function header and the newExr\r\n // match. So, we can safely replace the argument in the function call.\r\n // NO updates to the function header is made.\r\n //\r\n fcallexpr.exprArr.splice(pos, 1, newExpr);\r\n\r\n}", "function setup_environment() {\n const primitive_function_names =\n map(f => head(f), primitive_functions);\n const primitive_function_values =\n map(f => make_primitive_function(head(tail(f))),\n primitive_functions);\n const primitive_constant_names =\n map(f => head(f), primitive_constants);\n const primitive_constant_values =\n map(f => head(tail(f)),\n primitive_constants);\n return extend_environment(\n append(primitive_function_names,\n primitive_constant_names),\n append(primitive_function_values,\n primitive_constant_values),\n the_empty_environment);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
chooses theme on load checks for local storage first else uses local time
function modeOnLoad() { const themeUser = localStorage.getItem("themeSave"); //checks for saved theme key if (themeUser === "dark") { switcher(false); } else if (themeUser === "light") { switcher(true); } else { //no saved theme so determines via current time const now = new Date(); console.log(now.getHours()); if (now.getHours() > 18 || now.getHours < 8) { switcher(false); data.doms.toggleSwitch.checked = true; } else { switcher(true); } } }
[ "function RetroTheme() {\n if (localStorage.getItem('theme') === 'theme-dark') {\n setTheme('theme-retro');\n } else if (localStorage.getItem('theme') === 'theme-light') {\n setTheme('theme-retro');\n } else {\n setTheme('theme-light');\n }\n}", "function getStoredTheme() {\r\n let theme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;\r\n\r\n // check for user system preference\r\n if (theme == null) {\r\n if (!window.matchMedia) {\r\n theme = null;\r\n } else if (window.matchMedia(\"(prefers-color-scheme: dark)\").matches) {\r\n theme = 'dark';\r\n } else if (window.matchMedia(\"(prefers-color-scheme: light)\").matches) {\r\n theme = 'light';\r\n }\r\n }\r\n return theme;\r\n}", "function setTheam(){\n if (localStorage.getItem(\"theam\") !== null) {\n if (localStorage.getItem('theam')==1) {\n dark();\n } else if (localStorage.getItem('theam')==0) {\n light();\n }\n } \n}", "function themeSwitcher(){\n // this makes the LightWeightThemeManager resource available.\n // we need it to change the LightWeightThemes, also known as Personas.\n var {Cu} = require('chrome');\n var sslStatus = require('./sslHandler').SSLHandler.SSL_STATUS;\n var PrefListener = require('./prefListener').PrefListener;\n var simpleStorage = require('sdk/simple-storage');\n var simplePrefs = require('sdk/simple-prefs');\n var data = require('sdk/self').data;\n var cleanupReasons = {\n standardActive : 'standardActive'\n };\n\n // these Ids are going to be cleaned up whenever we switch to the default theme.\n // the reason is that we don't want them to appear in the extensions list.\n var sslPersonasThemeIds = ['ev','sv','http','https','sslp_standard'];\n var self = this;\n\n var themeChangedListener = new PrefListener(\n \"lightweightThemes.\",\n function(branch, name) {\n switch (name) {\n case \"lightweight-theme-changed\":\n case \"persisted.headerURL\":\n case \"isThemeSelected\":\n self.ensureCustomTheme();\n break;\n case \"lightweight-theme-change-requested\":\n break;\n case \"usedThemes\":\n break;\n default:\n break;\n }\n }\n );\n\n\n // Implitctly declared: var LightWeightThemeManger\n Cu.import('resource://gre/modules/LightweightThemeManager.jsm');\n\n\n /**\n * Constants for available themes.\n */\n this.theme = {};\n this.theme.defaultTheme = simpleStorage.storage.userTheme || new Theme();\n this.theme[sslStatus.extendedValidation] = new Theme('ev','Extended Validation Certificate Theme', data.url('img/themes/extendedValidation.png'));\n this.theme[sslStatus.standardValidation] = new Theme('sv','Standard Validation Certificate Theme', data.url('img/themes/standardValidation.png'));\n\n // we need to allow people to deactivate the red theme because a lot of users complained about seeing red all the time.\n resetInsecureConnectionTheme();\n\n this.theme[sslStatus.brokenCertificate] = new Theme('https','Broken Certificate Theme', data.url('img/themes/brokenCertificate.png'));\n this.theme[sslStatus.otherProtocol] = simpleStorage.storage.userTheme || new Theme();\n\n\n /**\n * Wrapper for the LightweightThemeManager's themeChanged method.\n * Only thing we do is make sure to clean up the SSLPersonas themes\n * if we switch to the default theme.\n * @param theme object of type {id:?,name:?,headerURL:?}\n */\n this.switchToTheme = function(theme){\n if(theme && typeof theme != 'undefined'){\n LightweightThemeManager.themeChanged(theme);\n // it doesn't happen that often, to switch to the\n // default theme.\n // let's use this opportunity to quickly clean up\n // after our add on.\n if(theme.id == this.theme.defaultTheme.id){\n this.cleanUpSSLPersonasThemes(cleanupReasons.standardActive);\n }\n }\n };\n\n\n\n /**\n * we do not want to leave any traces.\n * That's why we tell the theme manager\n * to forget all our themes.\n * This might be called onUninstall or even onClose.\n */\n this.cleanUpSSLPersonasThemes = function(reason){\n // console.log(\"Cleanup \"+reason);\n\n // on each clean up we restore the default theme\n // is restoring the default theme.\n // don't do this with this.switchToTheme, because this might\n // lead to recursion!\n if(typeof reason == 'undefined' || reason != cleanupReasons.standardActive){\n try{\n LightweightThemeManager.themeChanged(simpleStorage.storage.userTheme);\n }\n catch(e){ // pokemon!\n // gotta catch 'em all.\n }\n }\n\n\n\n // iterate over all themes that are stored\n // in this.theme\n // do not remove: defaultTheme, otherProtool\n for(var i=0;i<sslPersonasThemeIds.length;i++){\n (function(id){\n if(typeof id != 'undefined'){\n try{\n LightweightThemeManager.forgetUsedTheme(id);\n }\n catch(e){\n console.warn(\"SSLPersonas could not clean up properly because there was an error with forgetUsedTheme\");\n }\n\n }\n })(sslPersonasThemeIds[i]);\n }\n };\n\n\n\n\n /**\n * this maintains the user selected theme when SSLPersonas is installed or activated.\n */\n this.ensureCustomTheme = function(){\n var previousTheme = LightweightThemeManager.currentTheme;\n\n // there was an active theme that was not the default theme\n if(previousTheme != null && typeof previousTheme != 'undefined'){\n\n if(previousTheme.id == self.theme.defaultTheme.id){\n // we already are using the custom theme.\n // getting here results most likely from another\n // callback to the themeChangeListener\n return;\n }\n\n // let's see if the theme is one of our own:\n if(sslPersonasThemeIds.indexOf(previousTheme.id) == -1){\n // if we get here, we know that the user has chosen her own theme.\n // let's try to preserve it. We're going to activate it when none\n // of our statuses are needed.\n simpleStorage.storage.userTheme = previousTheme;\n self.theme.defaultTheme = previousTheme;\n self.theme[sslStatus.otherProtocol] = previousTheme;\n // console.log('Trying to use theme ' + previousTheme.name + ' by ' + previousTheme.author);\n }\n else{\n // last theme was an SSLPersonas theme. We don't persist anything.\n }\n }\n // the previous theme is Null in case the user chooses not to use\n // any custom theme, i.e. deactivates themes.\n // in that case, we want to use the standard theme again.\n else{\n delete simpleStorage.storage.userTheme;\n self.theme.defaultTheme = new Theme();\n self.theme[sslStatus.otherProtocol] = new Theme();\n }\n };\n\n /**\n * An Object wrapper for a lightweight theme.\n * @param id a randomly chosen string that will not be shown to the user\n * @param name a name for the theme that will appear in the theme selection.\n * @param headerURL a path or URL to an image that's large enough to span the entire chrome.\n */\n function Theme(id,name,headerURL){\n var additionalInfo = 'SSLPersonas';\n this.id = id || 'sslp_standard';\n this.name = additionalInfo + \": \" + (name || 'Standard Theme');\n\n // if headerURL is null, the LightWeightThemeManager\n // reverts to Firefox's default theme!\n this.headerURL = headerURL;\n this.footerURL = headerURL; // for people who actually use the footer.\n this.author = additionalInfo;\n }\n\n function resetInsecureConnectionTheme(){\n switch (simplePrefs.prefs.insecureTheme){\n case 'white':\n self.theme[sslStatus.insecureConnection] = new Theme('http',\n 'Insecure Connection Theme',\n data.url('img/themes/insecureConnection_white.png'));\n break;\n case 'red':\n self.theme[sslStatus.insecureConnection] = new Theme('http',\n 'Insecure Connection Theme',\n data.url('img/themes/insecureConnection_red.png'));\n break;\n default:\n self.theme[sslStatus.insecureConnection] = simpleStorage.storage.userTheme || new Theme();\n break;\n\n }\n }\n\n\n //this.ensureCustomTheme();\n // we want to be notified in case the user changes the theme.\n themeChangedListener.register(true);\n\n simplePrefs.on(\"insecureTheme\", function(preferenceName){\n resetInsecureConnectionTheme();\n });\n\n}", "function save_theme(e) {\n var theme = e.target.id;\n chrome.storage.sync.set({\"theme\": theme}, function() {\n document.location.reload();\n });\n}", "function switchThemes(){\n var entirePage = document.getElementById( 'document-body' );\n if( entirePage.classList.contains( 'lightTheme' ) ){\n entirePage.classList.remove( 'lightTheme' );\n entirePage.classList.add( 'darkTheme' );\n document.cookie = \"theme=darkTheme;path=/\";\n }\n else if( entirePage.classList.contains( 'darkTheme' ) ){\n entirePage.classList.remove( 'darkTheme' );\n entirePage.classList.add( 'lightTheme' );\n document.cookie = \"theme=lightTheme;path=/\";\n }\n}", "function initWeather() {\n var storedWeather = JSON.parse(localStorage.getItem('currentCity'));\n\n if (storedWeather !== null) {\n cityname = storedWeather;\n\n displayWeather();\n displayFiveDayForecast();\n }\n}", "function applyTheme(themeName) {\n document.body.classList = '';\n document.body.classList.add(themeName);\n document.cookie = 'theme=' + themeName;\n }", "function initLocalStorage() {\n if (typeof (Storage) !== \"undefined\") {\n // restore the localStorage, if storage is empty, will init new one\n allObjects.forEach((item) => {\n if (getItem(clickMap, item.title) != \"buttonGreen\") {\n setItem(clickMap, item.title, \"buttonGrey\");\n }\n })\n } else {\n allObjects.forEach((item) => {\n setItem(clickMap, item.title, \"buttonGrey\");\n })\n }\n}", "function displayTabContentLoader() {\r\n var $el = $(\"#tab-content-loader\");\r\n var nextUpdate, currentTime = new Date().getTime();\r\n var currentTab = getSettingsBackgroundTabId();\r\n if (currentTab == 0) {\r\n nextUpdate = localStorage.getItem(\"flixel-themes-data-next-update\");\r\n if (!nextUpdate || nextUpdate < currentTime)\r\n if (!$el.is(\":visible\")) $el.show();\r\n }\r\n else if (currentTab == 1) {\r\n nextUpdate = localStorage.getItem(\"available-themes-data-next-update\");\r\n if (!nextUpdate || nextUpdate < currentTime)\r\n if (!$el.is(\":visible\")) $el.show();\r\n }\r\n}", "get themeData() {\n if (this.manifest) {\n var themeData = {};\n // this is required so better be...\n if (varExists(this.manifest, \"metadata.theme\")) {\n themeData = this.manifest.metadata.theme;\n } else {\n // fallback juuuuust to be safe...\n themeData = {\n \"haxcms-basic-theme\": {\n element: \"haxcms-basic-theme\",\n path: \"@lrnwebcomponents/haxcms-elements/lib/core/themes/haxcms-basic-theme.js\",\n name: \"Basic theme\",\n variables: {\n image: \"assets/banner.jpg\",\n icon: \"icons:record-voice-over\",\n hexCode: \"#da004e\",\n cssVariable: \"pink\",\n },\n },\n };\n }\n // ooo you sneaky devil you...\n if (this.activeItem && varExists(this.activeItem, \"metadata.theme\")) {\n return this.activeItem.metadata.theme;\n }\n return themeData;\n }\n }", "function setTheme(event, obj){\n function save(theme){\n storage.set({ 'devtools-theme': theme.value },\n function(){ panel.currentTheme = theme.text; });\n }\n if (event && event.type === 'change'){\n $themeTitle.style.display = 'none';\n var el = event.target || event.srcElement;\n var option = el.options[el.selectedIndex];\n save(option);\n $('.alert')[0].style.display = 'block';\n } else if (event === null && obj){\n save(obj);\n }\n }", "_onThemeChanged() {\n this._changeStylesheet();\n if (!this._disableRedisplay)\n this._updateAppearancePreferences();\n }", "getCurrentTheme() {\n return this.isDarkTheme ? 'dark' : 'light';\n }", "function initLocalStorage(){\n if (!localStorage.hasOwnProperty('closeLoginWarning')){\n localStorage['closeLoginWarning'] = false;\n }\n \n if (!localStorage.hasOwnProperty('list')){\n localStorage['list'] = JSON.stringify([DEFAULT_ITEM]);\n }\n \n if (!localStorage.hasOwnProperty('loginStatus')){\n localStorage['loginStatus'] = false;\n }\n}", "async addTheme(){\n //If there is no page styling already\n if(!document.querySelector('.eggy-theme') && this.options.styles){\n //Create the style tag\n let styles = document.createElement('style');\n //Add a class\n styles.classList.add('eggy-theme');\n //Populate it\n styles.innerHTML = '{{CSS_THEME}}';\n //Add to the head\n document.querySelector('head').appendChild(styles);\n }\n //Resolve\n return;\n }", "function init() {\n var storedUsers = JSON.parse(localStorage.getItem(\"Users\"));\n if (storedUsers !== null) {\n users = storedUsers;\n //renderUsers();\n }\n}", "function updateThemeField() {\n\tvar linkTypeValue = settings.linkType;\n\tvar themePref, themeDef;\n\t\n\t//Get the correct theme preference and default.\n\tif (linkTypeValue == REMOTE) {\n\t\tthemePref = REMOTE_THEME;\n\t\tthemeDef = jQMThemeSource;\n\t} else {\n\t\tvar libPath = getTrueConfigurationPath() + assetDir;\n\t\tthemeDef = libPath + localThemeCSS;\n\t\tthemePref = PREF_CSS_FILE;\n\t}\n\t\n\t//Pre-populate select menu with CSS files.\n\tvar cssOpts = dw.getPreferenceString(PREF_SECTION, themePref, themeDef);\n\tsettings.themeInput.value = cssOpts;\n}", "function loadWishList(){\n\t\t\t\twishlist = JSON.parse(localStorage.getItem(\"myWishlist\"));\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns 1 if car is not in array, and returns the index of array where it was found if car was found
function checkIfVehicleExists(vehicle, array) { for (var i = 0; i < array.length; i++) { if (vehicle.shortIdentifier == array[i].shortIdentifier) { return i; } } return -1; }
[ "function inArray(value, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] == value) return i;\n }\n return -1;\n}", "function findCard(arr, card){\n for (let i = 0; i < arr.length; i++){\n if(cards[i] == card) return i;\n }\n return -1;\n}", "function search_in_array(element,array){\r\n\r\n var found = 0;\r\n \r\n for(i=0;i<array.length;i++)\r\n {\r\n if(array[i] == element)\r\n {\r\n found = 1;\r\n return 1;\r\n }\r\n }\r\n\r\n if(found == 0){\r\n return 0;\r\n }\r\n\r\n}", "function searchLinear(array, target){\n\tfor(let i = 0;i<array.length;i++){\n\t\tif(target == array[i]){\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1\n}", "function linearSearch(searchObj, searchArr){\n\n for(let index = 0; index < searchArr.length; index++){\n if(searchArr[index] === searchObj){\n return index\n }\n }\n return undefined\n}", "function arrayContains(arr, obj){\n \tfor (var i=0; i < arr.length; i++){\n \t\tif (arr[i] == obj){\n \t\t\treturn i;\n \t\t}\n \t}\n \treturn false;\n }", "function findIndexOfItem(array, item){\r\n for (var x = 0; x < array.length; x++) {\r\n if (array[x][1] == item[1]) {\r\n return x;\r\n }\r\n}\r\n }", "function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}", "function getMatchingIndex(arr, key, value) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i][key] === value)\n return i;\n }\n return null;\n}", "function checkExistance(arrayOfNames, name){\n\tvar result = -1;\n\t\n\tfor(var i=0; i<arrayOfNames.length; i++){\n\t\tif(arrayOfNames[i] == name){\n\t\t\treturn i;\n\t\t}\n\t}\n\t\n\treturn result;\n}", "function indice(lat, lon, array){\n\tvar n = array.length;\n\tindex = -1;\n\tfor (var i = 0 ; i < n; i++) {\n\t\tif (Number(array[i][0]) == lat && Number(array[i][1]) == lon){\n\t\t\tindex = i;\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn index;\t\n\t\t\n}", "function getCutoffIndex(array, value) {\n for (var index = 0; index < array.length; ++index) {\n if (array[index] === value) {\n return index + 1;\n }\n }\n\n return 0;\n }", "function search(arr, val) {\n\n let sortedArr = arr.sort((a, b) => a - b)\n\n for (let i = 0; i < sortedArr.length; i++) {\n if (sortedArr[i] === val) {\n return i;\n }\n }\n return 'value not found'\n}", "function indexOfElement(arrayContainer, element){\n\t//loop thru elements of container\n\tvar index = 0;\n\tfor( ; index < arrayContainer.length; index++ ){\n\t\t//compare currently iterated array entry to the given element\n\t\tif( arrayContainer[index] == element ){\n\t\t\t//if found, return index\n\t\t\treturn index;\n\t\t}\n\t}\n\t//not found, return -1\n\treturn -1;\n}", "findBookIndex(book) {\n let bookIndex = this.allBooks.indexOf(book);\n if (bookIndex == -1) {\n console.error(\"Book does not exist in allBooks array\")\n return false\n } else {\n return bookIndex;\n }\n\n }", "function getIndices(arr, el) {\n\tconst a = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] === el) {\n\t\t\ta.push(i)\n\t\t}\n\t}\n\treturn a;\n}", "function getDrumComboId(inputArray){\n if (inputArray.length == 0) return 0; \n\n inputArray.sort(); \n for (let i = 0; i < DRUM_COMBOS.length; i++){\n if (DRUM_COMBOS[i].length == inputArray.length && \n DRUM_COMBOS[i].every((val, index) => val === inputArray[index]))\n return i + 1; // 0 is for empty\n }\n console.error(\"Something wrong with drum id\", inputArray);\n return -1; // error\n}", "function findInArray(array, attr) {\n for ( let i = 0; i < array.length; i++ ) {\n if ( array[i].Name == attr.toString() ) {\n return i;\n }\n }\n }", "function findTruckWithID (truckID) {\n\tif(isArrayEmpty(localTruckArray)) return -2; // aey - if no trucks\n\tfor(let i = 0; i < localTruckArray.length; i++) {\n\t\tif(localTruckArray[i].id == truckID) return i; // aey - id was found, return where it was found\n\t}\n\treturn -1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get past meeting details.
getPastMeeting(uuid) { const response = jwtHelper.getApi('past_meetings/' + uuid); return response; }
[ "get meetingTimeZone()\n\t{\n\t\treturn this._meetingTimeZone;\n\t}", "function listUpcomingEvents() {\n const calendarId = 'primary';\n // Add query parameters in optionalArgs\n const optionalArgs = {\n timeMin: (new Date()).toISOString(),\n showDeleted: false,\n singleEvents: true,\n maxResults: 10,\n orderBy: 'startTime'\n // use other optional query parameter here as needed.\n };\n try {\n // call Events.list method to list the calendar events using calendarId optional query parameter\n const response = Calendar.Events.list(calendarId, optionalArgs);\n const events = response.items;\n if (events.length === 0) {\n console.log('No upcoming events found');\n return;\n }\n // Print the calendar events\n for (const event of events) {\n let when = event.start.dateTime;\n if (!when) {\n when = event.start.date;\n }\n console.log('%s (%s)', event.summary, when);\n }\n } catch (err) {\n // TODO (developer) - Handle exception from Calendar API\n console.log('Failed with error %s', err.message);\n }\n}", "pastAppointmentsMap(appointment, index) {\n if (this.findTimeDifference(appointment.time) > 0) {\n return (\n <div key={index} className=\"appointment\">\n <div>Time: {appointment.time}</div>\n <div>Purpose: {appointment.purpose}</div>\n </div>\n );\n }\n }", "function getRunningMeeting() {\n Safety_doAjax(runningMeetingURL, 'POST', { MeetingStatusType: 'Started' }, 'application/json', 'json', '', function (err, runningMeetingList) {\n if (err) {\n }\n else {\n //console.log(runningMeetingList);\n if (runningMeetingList.length > 0) {\n runningMeeting = runningMeetingList[0];\n hideMeetingBtn(true);\n //console.log(runningMeeting);\n }\n else {\n hideMeetingBtn(false);\n }\n }\n });\n}", "function getNextMeetupV2() {\n return new Promise((resolve, reject) => {\n const meetingCache = cache.get('nextMeeting');\n if (meetingCache) {\n resolve(meetingCache[0]);\n } else {\n fetch('https://api.meetup.com/2/events?&sign=true&group_id=10250862&page=20&key=' + process.env.meetupapi_key).then(response => {\n return response.json();\n }).then(json => {\n const meetingArray = json.results;\n setTimeToNewYork(meetingArray);\n cache.put('nextMeeting', meetingArray, 3600000);\n resolve(meetingArray[0]);\n }).catch(err => {\n reject(err);\n });\n }\n });\n}", "async function getNextMeetupV3() {\n const meetingCache = cache.get('nextMeeting');\n if (meetingCache) {\n return meetingCache[0];\n } else {\n const response = await fetch('https://api.meetup.com/2/events?&sign=true&group_id=10250862&page=20&key=' + process.env.meetupapi_key);\n const json = await response.json();\n const meetingArray = json.results;\n setTimeToNewYork(meetingArray);\n cache.put('nextMeeting', meetingArray, 3600000);\n return meetingArray[0]; \n }\n}", "function _grabTodayAvailability() {\n vm.timeSlotInfo.scheduleType = false;\n vm.timeSlotInfo.queryDate = vm.dateToday;\n vm.timeSlotInfo.queryDay = _getDayOfWeekFromDate(new Date(vm.dateToday));\n //Later will need Team Id As well as Website Id to enter into the ASAP TIME SLOT if none exists.\n console.log(\"ASAP GET TIME SLOT Payload: \", vm.timeSlotInfo);\n vm.$jobScheduleService.getTimeSlotByDate(vm.timeSlotInfo, _grabTodayAvailabilitySuccess, _grabTodayAvailabilityError);\n }", "get isMeeting()\n\t{\n\t\treturn this._isMeeting;\n\t}", "function handleUpcomingMatch() {\n var today = new Date();\n var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+ (\"0\" + today.getDate()).slice(-2)+'T'+today.getHours()+\":\"+today.getMinutes();\n handleUpcoming(date);\n}", "function getProtoEligibles(event) {\r\n var date = event.data.date;\r\n var $scheduleClicked = $(\".fc-event-clicked\");\r\n // Ensure a day has been clicked and no schedule currently clicked\r\n if (date && !$scheduleClicked.length) {\r\n var startTime = $(\"#start-timepicker\").val();\r\n var endTime = $(\"#end-timepicker\").val();\r\n $.get(\"get_proto_schedule_info\",\r\n {add_date: date, department: calDepartment, start_time: startTime, end_time: endTime},\r\n displayProtoEligables);\r\n }\r\n }", "async function getNextMeetupV4() {\n return nextmeeting[0];\n}", "get employmentDate() {\n return this._employmentDate;\n }", "getBy(meetingId) {\n const response = jwtHelper.getApi('meetings/' + meetingId);\n\n return response;\n }", "function setNextMeeting() {\n var today = new Date();\n console.log('Today is ' + today + '.');\n\n // Get date of meeting from this month.\n var date = getMeetingOfYearMonth(today.getFullYear(), today.getMonth());\n console.log('Meeting this month is ' + date + '.');\n\n // If meeting this month is over, take the one from the next month.\n if (date.getTime() < today.getTime()) {\n console.log('Meeting this month is over.');\n date = getMeetingOfYearMonth(today.getFullYear(), today.getMonth() + 1);\n }\n\n console.log('Next meeting is: ' + date + '.');\n document.getElementById('nextMeeting').innerHTML = date;\n}", "function getRecentListings(req, res, next) {\n\t//find all listings, sorts (-1 sorts descending) & returns most recent date\n\tListing.find().sort({date: -1}).limit(8).exec(function(err,listings){\n\t\tif(err){\n\t\t\tconsole.log(\"Error in finding highest hits\");\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tres.locals.recentListings = listings;\n\t\tnext();\n\t});\n}", "function handleReadUpcomingNoEdits(date){\n var query = firebase.database().ref(\"Games\").orderByKey();\n query.once(\"value\").then(function(snapshot) {\n // Iterate over every game schedule entry\n snapshot.forEach(function(childSnapshot) {\n var gameType = childSnapshot.child(\"gameType\").val();\n var them = childSnapshot.child(\"them\").val();\n var location = childSnapshot.child(\"location\").val();\n var datetime = childSnapshot.child(\"datetime\").val();\n var status = childSnapshot.child(\"status\").val();\n var display = false;\n \n // Compare entry date to current date\n for(var i = 0; i < 16; i++) {\n // current date is earlier than entry date\n if(date.charCodeAt(i) < datetime.charCodeAt(i)){\n // It's a date in the future, display it.\n display = true;\n break;\n }\n\n // current date is later than entry date\n if(date.charCodeAt(i) > datetime.charCodeAt(i)){\n // It's a date in the past, don't display it.\n break;\n }\n }\n\n if(display == true){\n var tmpl = document.getElementById('previousGame').content.cloneNode(true);\n tmpl.querySelector('.datetime').innerText = datetime;\n tmpl.querySelector('.gLocation').innerText = location;\n tmpl.querySelector('.matchUp').innerText = \"My Team vs \" + them;\n tmpl.querySelector('.gameType').innerHTML = status + \" : \" + gameType;\n tmpl.querySelector('#viewMatchStatsButton').value = datetime;\n tmpl.querySelector('#editScheduleButton').style.display = 'none';\n document.querySelector('#viewPrevious').appendChild(tmpl); \n }\n }); \n });\n}", "function fetchOpeningTimes () {\n\t\tParkingService.getTimesForOne (ParkingService.data.selectedParking.id).then(function(response) {\n\t\t\t\n\t\t\t// save result to model\n\t\t\tParkingService.data.selectedParking.openingtimes = response;\n\t\t\t\n\t\t\t// hide table if no opening time data:\n\t\t\tif (response == false){ \n\t\t\t\tconsole.log ('no times available');\n\t\t\t\tParkingService.data.selectedParking.noTimesFlag = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t}", "function getPastTimes()\n{\n //get current UNIX time\n let currTime = Math.round((new Date()).getTime() / 1000)\n let dayInSeconds = 24*60*60 //24 hrs * 60 min * 60 sec\n let pastTimes = []\n\n //get past 5 days from now in UNIX times\n for (let i = 1; i <= 5; i++)\n {\n pastTimes.push(currTime - dayInSeconds*i)\n }\n\n return pastTimes;\n}", "getissueDate(){\n\t\treturn this.dataArray[6];\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function used as an initial value for watchers. because it's unique we can easily tell it apart from other values
function initWatchVal() {}
[ "function Watcher(watchVar, ChangeTest, Callback) {\n\tthis.watchVar = watchVar;\n\tthis.ChangeTest = ChangeTest;\n\tthis.Callback = Callback;\n\n\tthis.GetValue = function() {\n\t\treturn this.watchVar;\n\t}\n\n\tthis.SetValue = function(val) {\n\t\tthis.watchVar = val;\n\t\tdebugLog('Set value: ' + this.watchVar);\n\t\tif (this.ChangeTest(this.watchVar)) {\n\t\t\tdebugLog(WATCHER_DEBUG, 'Doing callback');\n\t\t\tthis.Callback();\n\t\t}\n\t}\n}", "switchAfterZero(val) {\n /*\n Override by component\n */\n return val\n }", "hasWatchers() {\n return this.watchers.length > 0;\n }", "function LiveFunc(data){\n\t\tvar self = this;\n\n\t\tthis.internal = {\n\t\t\tname: data.name,\n\t\t\tvalue: data.value, // this is the function that is being used.\n\t\t\tinitArgs: data.initArgs || null,\n\t\t\tliveFunc: data.liveFunc,\n\t\t\tinitContext: data.initContext || window,\n\t\t\tasdfWrapperFunc: null\n\t\t};\n\n\t\tObject.defineProperty(this, 'name', {\n\t\t\tget: function(){\n\t\t\t\t// console.log('getting name');\n\t\t\t},\n\t\t\tset: function(val){\t\n\t\t\t\t// console.log('setting name: ');\n\t\t\t\tconsole.dir(val);\n\t\t\t}\n\t\t});\n\n\t\tObject.defineProperty(this, 'value', {\n\t\t\tget: function(){\n\t\t\t\t// console.log('getting value');\n\n\t\t\t\treturn self.internal.asdfWrapperFunc;\n\t\t\t},\n\t\t\tset: function(val){\n\t\t\t\t// console.log('setting value');\n\t\t\t\tconsole.dir(val);\n\t\t\t}\n\t\t});\n\n\t\tthis.internal.asdfWrapperFunc = this.createWrapperFunction();\n\n\t\t// evaluate the initFunc to get a starting value, then set it to the \n\t\t// internal.value prop.\n\t\tlpoi.monitoringLiveThings = true;\n\t\tthis.internal.value = this.internal.liveFunc.apply(self.internal.initContext, self.internal.initArgs);\n\t\tlpoi.monitoringLiveThings = false;\n\t\t\n\t\t// subscribe to all \n\t\tfor (var i = 0; i < lpoi.monitoringLiveThingsArr.length; i++) {\n\t\t\tvar v = lpoi.monitoringLiveThingsArr[i];\n\n\t\t\tps.subscribe(v.internal.name, self.updateLiveFunc.bind(self));\n\t\t};\n\n\t\tlpoi.monitoringLiveThingsArr = [];\n\n\t}", "resetWatch() {\n this.reset();\n this.print();\n }", "_onTriggerInternalHelperDefaults(triggerHelper) {\n this.currentFunction = '_onTriggerInternalHelperDefaults';\n super._onTriggerInternalHelperDefaults(triggerHelper);\n }", "watch() {\n if (this.shouldUpdate()) {\n this.trigger('change', this.rect);\n }\n\n if(!this.shouldStop){\n window.requestAnimationFrame(() => this.watch());\n }\n }", "function OffsetDummyListener()\r\n{\r\n this.offset = undefined;\r\n this.matches = new Map();\r\n this.orderedSet = undefined;\r\n}", "handleNoChangeEvent() {\n \n }", "watchNewCustomerCreation() {\n scope.get(this).$watch(() => state.get(this).current.name, newVal => {\n // Displaying customers\n this.newCustomer = ['main.employee.customer', 'main.corporate.customer'].indexOf(newVal) === -1;\n // Retrieve customer details if landing on a state displaying customer details\n if (/main.(employee|corporate).customer.(details|edit|intake)/.test(newVal)) {\n // Make sure we don't get the selected customer more than once\n if (this.displayData.selectedCustomer && this.displayData.selectedCustomer._id === state.get(this).params.customerId) {\n return;\n }\n this.getCustomer(state.get(this).params.customerId);\n }\n });\n }", "set_voltageAtStartUp(newval)\n {\n this.liveFunc.set_voltageAtStartUp(newval);\n return this._yapi.SUCCESS;\n }", "function setSourceFrequencyFn(scope) {\n\tsource_frequency = scope.source_frequency_value; /**Frequency of sound will be slider's current value */\n}", "function setDetectorVelocityFn(scope) {\n\tdetector_velocity = scope.detector_velocity_value;\n\tif ( detector_velocity > 0 ) { \n\t\tdetector_speed = (detector_velocity/1200)*3;/** Setting the detector speed based on the slider value */\n\t}\n\telse {\n\t\tdetector_speed = 0;\n\t\tdetector_container.x = detector_container.y = 0;\n\t}\n}", "function setSourceVelocityFn(scope) {\n\tsource_velocity = scope.source_velocity_value; /** Setting the source speed based on the slider value */\n\tcircle_centre = 100; /**Resetting the circle radius while changing the slider */\n}", "registerAutoWorker(){\r\n var functionPtr = Fatusjs.autoWorker;\r\n if(!this.autoInterval) {\r\n this.autoInterval = setInterval(\r\n functionPtr,\r\n 30000\r\n );\r\n }\r\n }", "_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }", "get takesValue() {\n return this._memoize('takesValue', () => {\n return this.takesValueFormattedTag !== null\n })\n }", "registerOnValidatorChange(fn) {\n this._onValidatorChange = fn;\n }", "_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }", "function initAll(handler){\r\n let overrideProxy=new Proxy({},{\r\n has:function(target,prop){\r\n return true\r\n },\r\n get:function(target,prop){\r\n return newElementHolderProxy()[prop](handler)\r\n }\r\n }\r\n )\r\n return newElementHolderProxy(undefined,overrideProxy)\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when user clicks the back button in the categories section, displays the original edit and create buttons
function catGoBack() { altCatDivPt1.style.display = "block"; altCatDivPt2.style.display = "none"; altCatDivPt3.style.display = "none"; catBackBtn.style.display = "none"; editCatErrorMessage.textContent = "[error message]"; editCatErrorMessage.style.visibility = "hidden"; }
[ "function display_CategoryView(parentDiv) {\n\t$('.button').removeClass(\"ActiveCategory\");//remove 'active' class on previous parent\n\tvar newParent = $('#categoryView');\n\t\n\tif (newParent.children()[0].id !== 'itemView') {\n\t\tvar parentCategory = newParent.children()[0].id;\n\t\tvar end = parentCategory.indexOf(\"-\");\n\t\tparentCategory = parentCategory.substring(0,end);\n\t\tnewParent.find('*').css('display','none');\n\t\tnewParent.find('*').not('#itemView').clone(true).appendTo($('#'+parentCategory));\n\t};\n\tnewParent.find('*').not('#itemView').remove();\n\n\t//clone(true) takes all attached handlers too, see docs\n\tparentDiv.children().clone(true).prependTo(newParent);\n\tparentDiv.children().remove();\n\t\n if(newParent.children('.subbutton').css('display') ==='none'){\n\t\t\tnewParent.children('.subbutton').toggle();};\n\t\t\t\n\tparentDiv.addClass(\"ActiveCategory\");\n}", "function showBackBt() {\n if (_historyObj.length > 1) {\n return true;\n } else {\n return false;\n }\n }", "backButtonClicked(){\n // get back to the previous page on the app-main navigator stack\n $('#app-main-navigator').get(0).popPage();\n }", "function previousClicked() {\n if (currentFeed && currentItemIndex > 0) {\n currentItemIndex--;\n displayCurrentItem();\n }\n }", "function createMainCategory() {\r\n var id = document.getElementById(\"main-category\");\r\n id.innerHTML = \"\";\r\n for (var i = 0; i < dict.mainCategory.length; i++) {\r\n id.appendChild(createMainCategoryButton(dict.mainCategory[i]));\r\n }\r\n id.firstChild.classList.add(\"menu-first-category-box\");\r\n updateViewMainCategory();\r\n}", "function restoreCupcakeList() {\r\n $(\"h2\").text(\"Add Cupcake\");\r\n $(\".update\").hide();\r\n $(\"#add\").show();\r\n $(\"a\").show();\r\n $(\".edit_btn\").show();\r\n $(\".cupcake_side\").css(\"width\", \"800px\");\r\n $(\"#flavor_input\").val(\"\");\r\n $(\"#size_input\").val(\"\");\r\n $(\"#image_input\").val(\"\");\r\n $(\"#rating_input\").val(\"\");\r\n }", "goBack(){\n BusinessActions.goBack();\n }", "function goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}", "scrollCategoriesToCurrent() {\n let currCat = this.category || localStorage.getItem('category');\n if (!currCat) return;\n\n const converter = {\n raw_food: 'Liv',\n restaurants: 'All',\n 'restaurants,bars,food': 'All',\n newamerican: 'Ame',\n tradamerican: 'Ame',\n hotdogs: 'Fas',\n bbq: 'Bar',\n hkcafe: 'Hon',\n };\n\n if (currCat in converter) currCat = converter[currCat];\n location.href = '#';\n location.href = `#${currCat[0].toUpperCase()}${currCat.substr(1, 2)}`;\n const $scrl3 = $('#scrl3');\n // move scrolled category a little lower for better visibility.\n const sT = $scrl3.scrollTop();\n if (sT >= 50) $scrl3.scrollTop(sT - 50);\n else $scrl3.scrollTop(0);\n\n FormFunctsObj.focusBlur();\n }", "handleBreadcrumbDelete() {\n let emptyCategory = this.state.category;\n emptyCategory.itemCategory.name = null;\n emptyCategory.breadcrumb = [];\n this.setState({\n category: emptyCategory\n });\n\n this.getDropdownCategories();\n }", "function makebuttoncategory(cattitle) {\n $('#toolbox') // Find the toolbox\n .append('\\n<div class=\"category\">'+cattitle+'</div>') // Add the header button\n .append('<div class=\"panel\"></div>'); // Make a blank panel container\n}", "createCatListItem(cat) {\n let catListItem = document.createElement(\"li\");\n\n catListItem.textContent = cat.name;\n document.getElementById(\"cats-list\").appendChild(catListItem);\n catListItem.addEventListener(\"click\", () => {\n catApp.setCurrentCat(cat);\n catApp.setAdminSettings(false);\n });\n }", "function caadpButton(){\n\t\tvar content = $('.node-type-programmes .caadp-term-class').clone();\n\t\t$('.node-type-programmes .caadp-term-class').remove();\n\t\t$('.node-type-programmes ul.quicktabs-tabs>li.last').after(content);\n\t\t}", "function showHistory() {\n\n\t}", "handleBreadcrumbClick(event, data) {\n let categoryId;\n let categoryName = data.content;\n let breadcrumb = this.state.category.breadcrumb;\n //get selected category id\n for (let i = 0; i < breadcrumb.length - 1; i++) {\n if (breadcrumb[i].name === categoryName) {\n categoryId = breadcrumb[i].id;\n break;\n }\n }\n\n this.setNewCategory(categoryId, categoryName);\n }", "function _backButtonStackHandler() {\n var backButtonStack = JSON.parse(localStorage.getItem('backButtonStack'));\n\n if (backButtonStack === null || backButtonStack.length < 1) {\n return;\n } else {\n var pageModel = backButtonStack.pop(),\n previousUrl = pageModel.url,\n pageModelData = pageModel.data;\n\n localStorage.setItem('pageModelData', JSON.stringify(pageModelData));\n\n if (backButtonStack.length < 1) {\n localStorage.removeItem('backButtonStack');\n } else {\n localStorage.setItem('backButtonStack', JSON.stringify(backButtonStack));\n }\n\n if (previousUrl === window.location.href) {\n window.location.reload();\n } else {\n window.location.href = previousUrl;\n }\n }\n }", "function back_button(){\n\t//back to home button's clicks and interaction\n\t\tvar back_button = $(\"<button type='button'>Back to Home</button>\")\n\t\tback_button.addClass(\"btn btn-secondary\")\n\t\t$('#back-to-home').append(back_button)\n\t\t\tback_button.click(function(){\n\t\t\twindow.location.href = \"/\"\n\t\t})\n}", "function showPreviousPreview()\r\n {\r\n if ($label == null)\r\n return;\r\n\r\n log(\"Preview.showPreviousPreview()\");\r\n\r\n // get current label\r\n var prevIndex = $previews.index($label) - 1;\r\n if (prevIndex >= 0)\r\n showPreview(prevIndex);\r\n }", "function goBack() {\n pop();\n\n if(typeof last() === 'undefined') {\n return;\n }\n var previousView = last();\n $state.go(previousView);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
stacks look like [[y1, y2], [y1, y2] ...] colorFunc is optional; if null it draws increasingly dark gray bands
function drawStack(ctx, stack, x, w, colorFunc) { var gray = void 0; stack.forEach(function (y, i) { if (!colorFunc) { gray = (0, _utils.randomInRange)(0.55, 0.85); ctx.fillStyle = 'rgba(0, 0, 0,' + (i + 1) * gray / stack.length + ')'; } else { ctx.fillStyle = colorFunc(ctx, w, y[1] - y[0]); } ctx.beginPath(); ctx.rect(x, y[0], x + w, y[1] - y[0]); ctx.closePath(); ctx.fill(); }); }
[ "function drawGlass(data, color) {\n // sort the array of data from biggest to smallest value\n // consider only the first 5 observations\n const sortedData = data.sort((a, b) => ((a.value > b.value) ? -1 : 1)).slice(0, 5);\n // compute the total for the linear scale\n const total = sortedData.reduce((acc, curr) => acc + curr.value, 0);\n\n // build an array to emulate a stack, adding an origin property based on the values of the previous observation\n // 0 for the first\n const stackData = [];\n for (let i = 0; i < sortedData.length; i += 1) {\n if (i !== 0) {\n stackData.push(Object.assign(sortedData[i], { origin: sortedData[i - 1].value + sortedData[i - 1].origin }));\n } else {\n stackData.push(Object.assign(sortedData[i], { origin: 0 }));\n }\n }\n\n // linear scale\n const yScale = d3\n .scaleLinear()\n .domain([0, total])\n .range([0, height]);\n\n // divide the update (read: existing elements) from the enter (read: new elements) selection\n const update = containerFrame\n .selectAll('rect');\n\n const enter = update\n .data(stackData)\n .enter();\n\n // when drawing the elements introduce them as a flowing from the top\n enter\n .append('rect')\n .attr('x', 0)\n .attr('y', d => yScale(d.origin))\n .attr('width', width)\n .transition()\n .duration(100)\n .delay((d, i) => i * 100)\n .ease(d3.easeLinear)\n .attr('height', d => yScale(d.value))\n .attr('fill', `#${color}`)\n .attr('opacity', (d, i) => {\n // first one opacity 1, then in decrements according to the number of observations\n const { length } = stackData;\n return 1 - (1 / length) * i;\n });\n\n // when updating the visualization, transition the properties which change with the same pattern\n update\n .transition()\n .duration(100)\n .delay((d, i) => i * 100)\n .ease(d3.easeLinear)\n .attr('y', d => yScale(d.origin))\n .attr('height', d => yScale(d.value))\n .attr('fill', `#${color}`)\n .attr('opacity', (d, i) => {\n const { length } = stackData;\n return 1 - (1 / length) * i;\n });\n\n // select all rectangle elements and show connected information in the tooltip\n d3.selectAll('rect')\n .on('mouseenter', (d) => {\n const format = d3.format(',');\n tooltip\n .append('p')\n .text(`Country: ${d.country}`);\n\n tooltip\n .append('p')\n .text(`Quantity Produced: ${format(d.value)}L`);\n\n tooltip\n .style('opacity', 1)\n .style('left', `${d3.event.pageX}px`)\n .style('top', `${d3.event.pageY}px`);\n })\n .on('mouseout', () => {\n tooltip\n .style('opacity', 0)\n .selectAll('p')\n .remove();\n });\n}", "function SVGStackedRowChart() {\n}", "function checkStacks(){\n if (stacked || (ending == 0 && beginning == 0)) {\n g.each(function (d, i) {\n d.forEach(function (datum, index) {\n \n // create y mapping for stacked graph\n if (stacked && Object.keys(yAxisMapping).indexOf(index) == -1) {\n yAxisMapping[index] = maxStack;\n maxStack++;\n }\n \n // always look for beginning and ending times of all timelines\n datum.times.forEach(function (time, i) {\n if (time.starting_time < minTime || minTime == 0)\n minTime = time.starting_time;\n if (time.ending_time > maxTime)\n maxTime = time.ending_time;\n });\n });\n });\n beginning = minTime;\n ending = maxTime;\n }\n }", "function triggerStackedAreaChart() {\r\n\t$(\"#map\"+app.m).html(\"\");\r\n\r\n\tvar zm = 1;\r\n\tif (!isAllzIntervalsEqual()) return;\r\n\t\r\n\tvar dataGlobal = [];\r\n\tfor (var i=0; i<app.m; i++) {\r\n\t\tvar mapN = \"map\" + i;\r\n\t\t//var row = {date: new Date(app.years[i], 1, 1)};\r\n\t\tvar row = {mapId: (i+1)}; // map number (1, 2, ...)\r\n\t\tif (app[mapN].gPolygonbyClass[0] == // skip if all are No Data\r\n\t\t\tapp[mapN].gPolygonbyClass[app[mapN].gPolygonbyClass.length-1]) continue; \r\n\t\t//console.log(mapN, 0, app[mapN].gPolygonbyClass[0], app[mapN].gPolygonbyClass.length, app[mapN].gPolygonbyClass[app[mapN].gPolygonbyClass.length-1],app[mapN].gPolygonbyClass);\r\n\t\tfor (var j=1; j<app[mapN].gPolygonbyClass.length; j++) {\r\n\t\t\tvar c = \"class\" + j;\r\n\t\t\trow[c] = app[mapN].gPolygonbyClass[j];\r\n\t\t}\r\n\t\tdataGlobal.push(row);\r\n\t\t//console.log(dataGlobal);\r\n\t}\r\n\tdataGlobal[\"columns\"] = [\"date\"];\r\n\tfor (var j=1; j<app[\"maps\"].gPolygonbyClass.length; j++) {\r\n\t\tvar c = \"class\" + j;\r\n\t\tdataGlobal[\"columns\"].push(c);\r\n\t}\r\n\t//console.log(dataGlobal);\t\t\r\n\r\n\tvar dataLocal = [];\r\n\tfor (var i=0; i<app.m; i++) {\r\n\t\tvar mapN = \"map\" + i;\r\n\t\t//var row = {date: new Date(app.years[i], 1, 1)};\r\n\t\tvar row = {mapId: (i+1)}; // map number (1, 2, ...)\r\n\t\tif (app[mapN].nPolygonbyClass[0] == // skip if all are No Data\r\n\t\t\tapp[mapN].nPolygonbyClass[app[mapN].nPolygonbyClass.length-1]) continue; \r\n\t\t//console.log(mapN, 0, app[mapN].nPolygonbyClass[0], app[mapN].nPolygonbyClass.length, app[mapN].nPolygonbyClass[app[mapN].nPolygonbyClass.length-1],app[mapN].nPolygonbyClass);\r\n\t\tfor (var j=1; j<app[mapN].nPolygonbyClass.length; j++) {\r\n\t\t\tvar c = \"class\" + j;\r\n\t\t\trow[c] = app[mapN].nPolygonbyClass[j];\r\n\t\t}\r\n\t\tdataLocal.push(row);\r\n\t\t//console.log(dataLocal);\r\n\t}\r\n\tdataLocal[\"columns\"] = [\"date\"];\r\n\tfor (var j=1; j<app[\"maps\"].nPolygonbyClass.length; j++) {\r\n\t\tvar c = \"class\" + j;\r\n\t\tdataLocal[\"columns\"].push(c);\r\n\t}\r\n\t//console.log(dataLocal);\t\t\r\n\t\r\n\t// ChartWidth: 500px, ChartHeight: 500px -> cWidth: 470, cHeight: 240\r\n\tvar ChartWidth = app.ChartWidth .replace('px','');\r\n\tvar ChartHeight = app.ChartHeight.replace('px','');\r\n\tvar cWidth = ChartWidth - 30;\r\n\tvar cHeight = Math.floor((ChartHeight - 20) / 2);\r\n\t//console.log(\"Chart: (\"+ChartWidth+\",\"+ChartHeight+\") -> chart: (\"+cWidth+\",\"+cHeight+\")\");\r\n\tvar html = '';\r\n\t//html += '<div style=\"text-align:center;\">The percentage of polygons belonging to each class</div>';\r\n\thtml += '<div style=\"text-align:right; margin-top:25px;\">';\r\n\thtml += '\t<div style=\"text-align:left; padding-left:70px; font-size:80%; font-style:normal;\">Global</div>';\r\n\thtml += '\t<svg id=\"globalStackedAreaChart\" width=\"' + cWidth + '\" height=\"' + cHeight + '\"></svg>';\r\n\thtml += '</div>';\r\n\thtml += '<div style=\"text-align:right; margin-top:10px;\">';\r\n\thtml += '\t<div style=\"text-align:left; padding-left:70px; font-size:80%; font-style:normal;\">Local</div>';\r\n\thtml += '\t<svg id=\"localStackedAreaChart\" width=\"' + cWidth + '\" height=\"' + cHeight + '\"></svg>';\r\n\thtml += '</div>';\r\n\t$(\"#map\"+app.m).html(html);\r\n\tdrawStackedAreaChart(\"globalStackedAreaChart\", dataGlobal, app.colorGradient19[0]);\r\n\tdrawStackedAreaChart(\"localStackedAreaChart\", dataLocal, app.colorGradient19[1]);\r\n}", "function drawGradeFStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Grade\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Pre-school\", 15, 151],\n [\"Primary school\", 8, 80],\n [\"Middle school\", 20, 19],\n [\"Highschool\", 15, 151]\n ]);\n\n var options = {\n \"title\": \"Figure 11: Mode of Transportation to School by Grade\",\n chartArea: {width: \"50%\"},\n \"isStacked\": true,\n\t\tcolors: ['#C52026','#ADADAD'],\n\t\t\"width\": 800,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"Grade\"\n }\n };\n\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div12\"));\n chart.draw(data, options);\n }", "function drawGrade2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Grade\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Pre-school\", 15, 151],\n [\"Primary school\", 8, 80],\n [\"Middle school\", 20, 19],\n [\"Highschool\", 15, 151]\n ]);\n\n var options = {\n \"title\": \"Figure 10: Mode of Transportation to School by Grade\",\n chartArea: {width: \"50%\"},\n \"isStacked\": true,\n\t\tcolors: ['#C52026','#ADADAD'],\n\t\t\"width\": 800,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"Grade\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div11\"));\n chart.draw(data, options);\n }", "function createStackedBarChart(jsonObj) {\r\n\r\n\t// create new svg\r\n\tvar svg = d3.select(\"svg\"),\r\n margin = {top: 20, right: 20, bottom: 30, left: 40},\r\n width = +svg.attr(\"width\") - margin.left - margin.right,\r\n height = +svg.attr(\"height\") - margin.top - margin.bottom,\r\n g = svg.append(\"g\").attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\r\n\tvar x = d3.scaleBand()\r\n\t .rangeRound([0, width])\r\n\t .padding(0.1)\r\n\t .align(0.1);\r\n\r\n\tvar y = d3.scaleLinear()\r\n \t.rangeRound([height, 0]);\r\n\r\n\tvar z = d3.scaleOrdinal()\r\n\t .range([\"#98abc5\", \"#8a89a6\"]);\r\n\r\n\tvar stack = d3.stack();\r\n\tvar data = jsonObj;\r\n\r\n\tz.domain(d3.keys(data[0]).filter(function(key) { return key !== \"jahr\"; }));\r\n\r\n\tdata.forEach(function(d) {\r\n\t var y0 = 0;\r\n\t d.jahre = z.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });\r\n\t d.total = d.jahre[d.jahre.length - 1].y1;\r\n \t});\r\n\r\n\tx.domain(data.map(function(d) { return d.jahr; }));\r\n\ty.domain([0, d3.max(data, function(d) { return d.total; })]);\r\n\r\n \tg.selectAll(\".serie\")\r\n \t.data(stack.keys([\"patienten_entlassen\", \"patienten_gestorben\"])(data))\r\n \t.enter().append(\"g\")\r\n \t.attr(\"class\", \"serie\")\r\n \t.attr(\"fill\", function(d) { return z(d.key); })\r\n \t.selectAll(\"rect\")\r\n\t .data(function(d) { return d; })\r\n\t .enter().append(\"rect\")\t \r\n\t .attr('jahr', function(d) {return d.data.jahr;}) \r\n\t .attr('data-togle', 'tooltip')\r\n\t .attr('data-placement', 'right')\r\n\t .attr('title', function(d) {\r\n\t \tvar patienten_gestorben = parseFloat(d.data.patienten_gestorben);\r\n\t \tvar patienten_entlassen = parseFloat(d.data.patienten_entlassen);\r\n\t \tvar gestorbenProzent = (patienten_gestorben / (patienten_gestorben + patienten_entlassen)) * 100; \r\n\t \tgestorbenProzent = gestorbenProzent.toFixed(4);\r\n\t \tgestorbenProzent = germanizeDecimal(gestorbenProzent);\r\n\t \tvar gestorben = humanizeNumber(patienten_gestorben);\r\n\t \tvar entlassen = humanizeNumber(patienten_entlassen);\r\n\t\t \tvar text = \"Entlassen: \" + entlassen + \"<br />Gestorben: \" + gestorben + \"<br />Gestorben %: \" + gestorbenProzent; \r\n\t \treturn text;\r\n\t \t})\r\n\t .attr(\"x\", function(d) { return x(d.data.jahr); })\r\n\t .attr(\"y\", function(d) { return y(d[1]); })\r\n\t .attr(\"height\", function(d) { return y(d[0]) - y(d[1]); })\r\n\t .attr(\"width\", x.bandwidth());\r\n\r\n\tg.append(\"g\")\r\n\t .attr(\"class\", \"axis axis--x\")\r\n\t .attr(\"transform\", \"translate(0,\" + height + \")\")\r\n\t .call(d3.axisBottom(x));\r\n\r\n\tg.append(\"g\")\r\n\t .attr(\"class\", \"axis axis--y\")\r\n\t .call(d3.axisLeft(y).ticks(10, \"s\"))\r\n\t .append(\"text\")\r\n\t .attr(\"x\", 2)\r\n\t .attr(\"y\", y(y.ticks(10).pop()))\r\n\t .attr(\"dy\", \"0.35em\")\r\n\t .attr(\"text-anchor\", \"start\")\r\n\t .attr(\"fill\", \"#000\")\r\n\t .text(\"Patienten\");\r\n\r\n\t/*\r\n \tvar legend = g.selectAll(\".legend\")\r\n \t.data(data.slice(2,4))\r\n \t.enter().append(\"g\")\r\n .attr(\"class\", \"legend\")\r\n .attr(\"transform\", function(d, i) { return \"translate(0,\" + i * 20 + \")\"; })\r\n .style(\"font\", \"10px sans-serif\");\r\n\r\n\tlegend.append(\"rect\")\r\n\t .attr(\"x\", width - 18)\r\n\t .attr(\"width\", 18)\r\n\t .attr(\"height\", 18)\r\n\t .attr(\"fill\", z);\r\n\r\n\tlegend.append(\"text\")\r\n\t .attr(\"x\", width - 24)\r\n\t .attr(\"y\", 9)\r\n\t .attr(\"dy\", \".35em\")\r\n\t .attr(\"text-anchor\", \"end\")\r\n\t .text(function(d) { return d; });\r\n\t*/\r\n\r\n}", "function 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 }", "function renderBarChart() {\n var i, j, p, a, x, y, w, h, len;\n\n if (opts.orient === \"horiz\") {\n rotate();\n }\n\n drawAxis();\n\n ctx.lineWidth = opts.stroke || 1;\n ctx.lineJoin = \"miter\";\n\n len = sets[0].length;\n\n // TODO fix right pad\n for (i = 0; i < sets.length; i++) {\n for (j = 0; j < len; j++) {\n p = 1;\n a = rotated ? height : width;\n w = ((a / len) / sets.length) - ((p / sets.length) * i) - 1;\n x = (p / 2) + getXForIndex(j, len + 1) + (w * i) + 1;\n y = getYForValue(sets[i][j]);\n h = y - getYForValue(0) || 1;\n\n if (isStacked()) {\n // TODO account for negative and positive values in same stack\n w = (a / len) - 2;\n x = getXForIndex(j, len + 1);\n y = getYForValue(sumY(sets.slice(0, i + 1), j));\n }\n\n drawRect(x, y, w, h, getColorForIndex(i));\n }\n }\n }", "function drawSchoolFStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 31, 102],\n [\"MGHS\", 24, 73],\n [\"IHoMCS\",11, 11],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n title: \"Figure 9: Mode of Transportation from School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n\t\tcolors: ['#C52026','#ADADAD'],\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div10\"));\n chart.draw(data, options);\n }", "function drawTopConcernsNotAllowStacked() {\n var data = google.visualization.arrayToDataTable([\n\t\t[\"Issues\", \"Very important & Somewhat important\", \"Not at all important\", \"Neutral\"],\n [\"Amount of traffic along route\", 156, 14, 3],\n [\"Speed of traffic along route\", 153, 16, 3],\n\t\t[\"Weather\", 145, 24, 3],\n [\"Age of children\", 143, 25, 3],\n [\"Sidewalks or pathways\", 142, 23, 6],\n\t\t[\"Distance from home to school\", 132, 38, 4],\n\t\t[\"Crossing guards\", 131, 31, 10],\n [\"Family schedule\", 129, 35, 8],\n [\"Convenience/Inconvenience of driving\", 114, 47 , 11],\t\n\t\t[\"Child's before or after school activities\", 113, 49, 9],\n\t\t[\"Adults to walk or bike with\", 106, 52, 16],\n [\"Violence or crime\", 92, 71, 10]\n ]);\n\n\n var options = {\n title: \"Figure 16: How important were the follwing issues for you when you decided NOT to allow your child to walk or bike to and from school\",\n\t\theight: 400,\n chartArea: { width: \"50%\", height: 300 },\n isStacked: true,\n\t\tcolors: ['#C52026','#DD847E','#ADADAD'],\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div17\"));\n chart.draw(data, options);\n}", "function interpolateColors(_type='fill',_colors,_step = 1){\n if (_type =='fill'){\n // If there is only one color in the layer:\n if (!Array.isArray(_step)){\n var steps = [1,_step];\n } else {\n var steps = _step;\n }\n // If there is only one color in the layer:\n if (!Array.isArray(_colors)){\n var colors = [_colors];\n } else {\n var colors = _colors;\n }\n // Create the color ramp.\n var color = d3.scaleLinear()\n .domain(steps)\n .range(colors)\n .interpolate(d3.interpolateRgb);\n } else{\n var color = d3.scaleLinear()\n .domain([0,_step/3,_step*(2/3),_step])\n .range(['#67a9cf','#5fe265','#ef8a62','#b21818'])\n .interpolate(d3.interpolateRgb);\n }\n return color;\n\n}", "function createPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches.push(new ColorSwatch(\t((i*colorSwatchRadius)+colorSwatchRadius/2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t colorArray[i]));\n\t}\n\tfillIcon = new FillIcon(canvasWidth-frameThickness*.75, canvasWidth/40, canvasWidth/20);\n}", "function drawFlat(spectrum){\n colorMode(HSB, bands);\n var w = width / (bands * 1.5);\n var maxF = Math.max(spectrum);\n for (var i = 0; i < spectrum.length; i++) {\n var amp = spectrum[i];\n var y = map(amp, 0, 255, height, 10);\n fill(i,255,255);\n rect(width/2 + i*w,y,w-2,height-y);\n rect(width/2 - i*w,y,w-2,height-y);\n }\n}", "function highlight_heatmap(frames) {\r\n\r\n // Make highlighter_container visible\r\n document.querySelector('#highlighter_container').style.display = \"block\";\r\n\r\n // Find original node\r\n node = $('.highlighter')[0];\r\n\r\n for(i = 0; i<frames.length; i++) {\r\n\r\n // Duplicate highlighter node\r\n copy = node.cloneNode(true);\r\n node.parentNode.insertBefore(copy, node);\r\n\r\n // Make highlighter visible\r\n node.style.display = \"block\";\r\n\r\n start = frames[i][0];\r\n width = frames[i][1];\r\n\r\n node.style.marginLeft = (gridWidth * start) + \"px\";\r\n node.style.width = (gridWidth * width) + \"px\";\r\n\r\n node = copy;\r\n }\r\n}", "function drawSchool2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 28, 105],\n [\"MGHS\", 13, 84],\n [\"IHoMCS\", 10, 12],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n \"title\": \"Figure 8: Mode of Transportation to School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n\t\tcolors: ['#C52026','#ADADAD'],\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div9\"));\n chart.draw(data, options);\n }", "function drawDistanceFSStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Distance\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Less than 1/4\", 30, 11],\n [\"1/4 - 1/2\", 16, 21],\n [\"1/2 -1\", 16, 34],\n [\"1 - 2\", 11, 50],\n [\"More than 2\", 1, 86]\n ]);\n\n var options = {\n title: \"Figure 11: Mode of Trasnportation from School by Distance\",\n chartArea: {width: \"50%\"},\n isStacked: true,\n\t\tcolors: ['#C52026','#ADADAD'],\n\t\t\"width\": 600,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"Distance (miles)\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div19\"));\n chart.draw(data, options);\n}", "function drawDistance2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Distance\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Less than 1/4\", 29, 12],\n [\"1/4 - 1/2\", 13, 24],\n [\"1/2 -1\", 11, 39],\n [\"1 - 2\", 6, 55],\n [\"More than 2\", 1, 66]\n ]);\n\n var options = {\n title: \"Figure 10: Mode of Transportation to School by Distance\",\n chartArea: {width: \"50%\"},\n isStacked: true,\n\t\tcolors: ['#C52026','#ADADAD'],\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n\t\t\"width\": 600,\n vAxis: {\n title: \"Distance (miles)\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div13\"));\n chart.draw(data, options);\n}", "function zcolor(col, dimension) {\n var z = zscore(_(col).pluck(dimension).map(parseFloat));\n // console.log(z);\n return function(d) {\n return zcolorscale(z(d[dimension]))\n }\n }", "function plotlyDefaultColor(index){\n index = index%10;\n return plotlyColors[index];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a user decides to select a preuploaded picture, then the form for inserting a URL will be disabled.
function checker() { var thisSrc = displayPic.src; if (thisSrc.indexOf("#") >= 0) { uploadURL.disabled = false; localURL.disabled = false; } else { upload.style.color = "Grey"; uploadURL.disabled = true; uploadURL.placeholder = ""; localURL.disabled = true; localURL.style.color = "Grey"; localURL.value = ""; localURL.placeholder = ""; } }
[ "function imageUploaded(error, result) {\n $('#recipe-upload-image').prop(\"src\", result[0].secure_url);\n $('#image_upload_url').val(result[0].secure_url);\n}", "function setThumbnail(url){\r\n\tvar imgUrl = \"\";\r\n\tif(url.match(/youtube/) != null){\r\n\t\timgUrl = \"http://img.youtube.com/vi/\" + getKey(url) + \"/0.jpg\";\r\n\t}\r\n\tif(imgUrl != \"\"){\r\n\t\t$(\"#formDialog img\").show();\r\n\t\t$(\"#formDialog img\").attr(\"src\", imgUrl);\r\n\t} else {\r\n\t\t$(\"#formDialog img\").hide();\r\n\t}\r\n}", "function show_image_upload_form() {\n let profile_upload = document.getElementById(\"profile-image-upload-form\");\n profile_upload.style.display = \"\";\n let profile_info = document.getElementById(\"profile-info-form\");\n profile_info.style.display = \"none\";\n}", "function showPictureToDelete()\n{\n\tif (document.forms[1].deletePics.value == \"\")\n\t{\n\t\t$('#showPicture').empty();\n\t}\n\telse\n\t{\n\t\t$('#showPicture').empty();\n\t\tvar picture = document.forms[1].deletePics.value;\n\t\tvar pictureScript = '<p><img src=\"../mainPictures/' + picture + '\"width=\"50\" height=\"76\" />';\n\t\t$('#showPicture').append(pictureScript);\n\t}\n}", "function setSelectedImage(objectUrl) {\r\n var image_iframe = document.getElementById('image-input'); \r\n image_iframe.contentWindow.setSelectedImage(objectUrl);\r\n }", "function validateImage() {\n var img = document.getElementById(\"image\").value;\n if (img == \"\" || img == null) {\n alert(\"Image link must be filled\");\n return false;\n }\n else {\n resultView();\n }\n}", "function addGrayListUrl(form){\n\tlet clientId=$('#clientId').val();\n\tlet platformId=$('#typeId').val();\n\tlet url =$('#url').val().trim();\n\tif(clientId === \"0\"){\n\t\talert('Please select a Client ');\n\t}else if(platformId === \"0\"){\n\t\talert('Please select Platform type');\n\t}else if(url === \"\"){\n\t\talert('Please add a URL');\n\t}else{\n\t\tform.action=\"glist\";\n\t\tform.method=\"post\";\n\t}\n}", "function freeFormOn() {\n console.log('freeform');\n disableRatios();\n document.getElementById('freeform').checked = true;\n jcrop_api.setOptions({ aspectRatio: 0 });\n}", "function resetImgForm() {\n $('#local-opt, #library-opt, #link-opt').removeClass('selected');\n $('#local-upload, #library-upload, #link-upload').addClass('hidden');\n}", "function removePhoto(){\n\tdocument.getElementById(\"PhotoField\").disabled = true;\n\t$(\"#PhotoField\").val(\"\");\n\t$(\"#PhotoParentDiv\").hide();\n\t$(\"#imageIcon\").css('color',\"#9ba1a7\");\n\t// for edit page\n\tdocument.getElementById(\"fileRemovedStatus\").disabled = false;\n}", "function correctImageUrl(event)\n{\n event.stopPropagation();\n let form = this.form;\n let imageLine = document.getElementById(\"ImageButton\");\n let imageUrl = '';\n let nextSibling;\n for(var child = imageLine.firstChild;\n child;\n child = nextSibling)\n {\n if (child.nodeType == 1 &&\n child.nodeName == 'INPUT' &&\n child.name == 'Image')\n { // <input name='Image' ...\n imageUrl = child.value;\n } // <input name='Image' ...\n nextSibling = child.nextSibling;\n imageLine.removeChild(child);\n } // loop through children of imageLine\n\n // create new label and <input type='text'>\n imageLine.appendChild(\n document.createTextNode(\"Enter URL of Census Image:\"));\n let inputTag = document.createElement(\"INPUT\");\n inputTag.type = 'text';\n inputTag.size = '64';\n inputTag.maxlength = '128';\n inputTag.name = 'Image';\n inputTag.value = imageUrl;\n inputTag.className = 'black white leftnc';\n imageLine.appendChild(inputTag);\n}", "function cancelUploadedImg() {\n // Close Upload Box\n $(\"#uploadImgContainer\").removeClass('open-upload');\n\n $(\"#uploadImgContainer\").parent('.popup-container').removeClass('show');\n\n // Reset the Default Preview Image\n $('#uploadingPreview').attr('src', $('#uploadingPreview').attr('data-default'));\n\n // Reset Image Title\n $('#imagUploadingTitle').html($('#imagUploadingTitle').attr('data-text'));\n\n // Reset Uploaded Image\n $(\"#chatUploadInput\").val('');\n }", "function handleFormChange(evt) {\n showUrlOrFile(evt.currentTarget); // currentTarget is the form\n }", "function onAddUrl(ev) {\n ev.preventDefault();\n\n var lastField = this.select('urlListSelector').find('[name=\"websites[]\"]').last();\n\n if (lastField.val() === '') {\n lastField.focus();\n } else {\n this.select('urlListSelector').append(metadataEditUrlListTemplate.render({\n metadataPrefix: this.attr.metadataPrefix,\n fontPrefix: this.attr.fontPrefix\n }));\n this.select('urlListSelector').find('[name=\"websites[]\"]').last().focus();\n }\n}", "function onImagePickerOptionChange(pickerOption) {\r\n $('#projectImagePreview').attr('src', $(pickerOption.option[0]).data('img-src'));\r\n}", "function editPictures()\n{\n var\tform\t\t = this.form;\n var\tpicIdType\t = form.PicIdType.value;\n var\tidlr;\n\n if (form.idlr && form.idlr.value > 0)\n {\t\t// idlr present in form\n\t\tidlr\t\t = form.idlr.value;\n\t\tvar iframe\t = window.frameElement;\n\t\tvar childFrameClass\t\t= 'right';\n\t\tif (iframe)\n\t\t{\n\t\t if (iframe.className == 'right')\n\t\t\t childFrameClass\t\t= 'left';\n\t\t}\n var lang = 'en';\n if ('lang' in args)\n lang = args.lang;\n\t\topenFrame(\"pictures\",\n\t\t\t \"editPictures.php?idlr=\" + idlr +\n \"&idtype=\" + picIdType +\n \"&lang=\" + lang, \n\t\t\t childFrameClass);\n }\t\t// idlr present in form\n else\n {\t\t// unable to identify record to associate with\n\t\tpopupAlert(\"Location.js: editPictures: \" +\n\t\t\t \"Unable to identify record to associate pictures with\",\n\t\t\t\t this);\n }\t\t// unable to identify record to associate with\n return true;\n}", "function handleFormSubmit(evt) {\n const form = evt.currentTarget;\n const fileInput = form.elements.namedItem('file');\n if (fileInput.hidden) {\n fileInput.value = '';\n }\n }", "function addWhiteListUrl(form){\n\tlet clientId=$('#clientId').val();\n\tlet platformId=$('#typeId').val();\n\tlet url =$('#url').val().trim();\n\tif(clientId === \"0\"){\n\t\talert('Please select a Client ');\n\t}else if(platformId === \"0\"){\n\t\talert('Please select Platform type');\n\t}else if(url === \"\"){\n\t\talert('Please add a URL');\n\t}else{\n\t\tif(platformId === \"in\"){\n\t\t\tform.action=\"addwlist\";\n\t\t\tform.method=\"post\";\n\t\t}else if(platformId === \"fb\" || platformId === \"tw\" ){\n\t\t\tform.action=\"addwlist2\";\n\t\t\tform.method=\"post\";\n\t\t}else if(platformId === \"insta\"){\n\t\t\tform.action=\"wInsta\";\n\t\t\tform.method=\"post\";\n\t\t}else if(platformId === \"yt\"){\n\t\t\tform.action=\"wYT\";\n\t\t\tform.method=\"post\";\n\t\t}else if( platformId === \"dm\"){\n\t\t\tif(url.indexOf(DAILYMOTION)> -1){\n\t\t\t\tlet sub=url.substring(DAILYMOTION.length,url.length);\n\t\t\t\tif(sub.length>0){\n\t\t\t\t\tform.action=\"addwlist2\";\n\t\t\t\t\tform.method=\"post\";\n\t\t\t\t}else{\n\t\t\t\t\talert('Uploader details missing');\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('This is not a proper dailymotion link');\n\t\t\t}\n\t\t}else if(platformId === \"pin\"){\n\t\t\tif(url.indexOf(PINTEREST)> -1){\n\t\t\t\tlet sub=url.substring(PINTEREST.length,url.length);\n\t\t\t\tif(sub.length>0){\n\t\t\t\t\tform.action=\"addwlist2\";\n\t\t\t\t\tform.method=\"post\";\n\t\t\t\t}else{\n\t\t\t\t\talert('Uploader details missing');\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('This is not a proper Pinterest link');\n\t\t\t}\n\t\t}else if(platformId === \"re\"){\n\t\t\tif(url.indexOf(REDDIT)> -1){\n\t\t\t\tlet sub=url.substring(REDDIT.length,url.length);\n\t\t\t\tif(sub.length>0){\n\t\t\t\t\tform.action=\"addwlist2\";\n\t\t\t\t\tform.method=\"post\";\n\t\t\t\t}else{\n\t\t\t\t\talert('Uploader details missing');\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('This is not a proper REDDIT link');\n\t\t\t}\n\t\t}else if(platformId === \"ti\"){\n\t\t\tif(url.indexOf(TIKTOK)> -1){\n\t\t\t\tlet sub=url.substring(TIKTOK.length,url.length);\n\t\t\t\tif(sub.length>0){\n\t\t\t\t\tif(sub[0]!== '@'){\n\t\t\t\t\t\talert('Uploader details missing.It must be start with @');\n\t\t\t\t\t}else{\n\t\t\t\t\tform.action=\"addwlist2\";\n\t\t\t\t\tform.method=\"post\";\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\talert('Uploader details missing');\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('This is not a proper TIKTOK link');\n\t\t\t}\n\t\t}else if(platformId === \"vi\"){\n\t\t\tif(url.indexOf(VIMEO)> -1){\n\t\t\t\tlet sub=url.substring(VIMEO.length,url.length);\n\t\t\t\tif(sub.length>0){\n\t\t\t\t\tform.action=\"addwlist2\";\n\t\t\t\t\tform.method=\"post\";\n\t\t\t\t}else{\n\t\t\t\t\talert('Uploader details missing');\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('This is not a proper VIMEO link');\n\t\t\t}\n\t\t}\n\t}\n}", "function setObjectUrl(objectUrl) {\r\n document.getElementById('objectUrl').value = objectUrl;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: LookupOASCapableSucceeded This is the AJAX callback function for success. Asks if user wants to leave the test pfratus, 4/7/2010
function LookupOASCapableSucceeded(result, context) { var action='', msf='', oldZipcode='', question=''; if (context!=null && context!='') { var qs = context.split('|') action = qs[0]; msf = qs[1]; oldZipcode = qs[2]; question = qs[3]; } if (result.d) { gs('', action, msf); } else { var leaveTestAnswer = confirm(question); if (leaveTestAnswer) { gs('', action, msf); } else { document.getElementById('zip_code').value = oldZipcode; } } }
[ "function LookupOASCapableOnHomePageFailed(result, context) {\n var oldZipcode='', question='', controlName='';\n if (context!=null && context!='') {\n\t var qs = context.split('|')\n oldZipcode = qs[0];\n controlName = qs[2];\n }\n document.getElementById(controlName).value = oldZipcode;\n\n alert('LookupOASCapableOnHomePage Failed: ' + result.status + ' ' + result.statusText);\n //there needs to be more than an alert\n return false;\n}", "function LookupOASCapableOnHomePage(oldZipcode, question, controlName) {\n if (oldZipcode == document.getElementById(controlName).value) \n {\n return true;\n }\n else\n {\n var ret = true;\n var context = oldZipcode + \"|\" + question + \"|\" + controlName;\n\t \n $j.ajax({\n async: false,\n type: \"POST\",\n url: \"/data/LookupOASCapable.aspx/IsOASCapable\",\n data: \"{'zipCode': '\" + document.getElementById(controlName).value + \"'}\",\n context: context,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n timeout: 3000,\n success: function(msg) {\n ret = LookupOASCapableOnHomePageSucceeded(msg, this.context); \n },\n error: function(msg) {\n ret = LookupOASCapableOnHomePageFailed(msg, this.context); \n } \n });\t\n return ret;\n }\n}", "function LookupOASCapableFailed(result, context) {\n var action='', msf='', oldZipcode='', question='';\n if (context!=null && context!='') {\n\t var qs = context.split('|')\n oldZipcode = qs[2];\n }\n document.getElementById('zip_code').value = oldZipcode;\n\n alert('LookupOASCapable Failed: ' + result.status + ' ' + result.statusText);\n //there needs to be more than an alert\n}", "function LookupOASCapable(oldZipcode, newZipcode, action, msf, question) \n{\n if (oldZipcode == newZipcode) \n {\n\t gs('', action, msf);\n }\n else\n {\n var context = action + \"|\" + msf + \"|\" + oldZipcode + \"|\" + question;\n\t \n $j.ajax({\n type: \"POST\",\n url: \"/data/LookupOASCapable.aspx/IsOASCapable\",\n data: \"{'zipCode': '\" + newZipcode + \"'}\",\n context: context,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(msg) {\n LookupOASCapableSucceeded(msg, this.context); \n },\n error: function(msg) {\n LookupOASCapableFailed(msg, this.context); \n }\n });\t \n }\n}", "function aRegPingTestFinished(aTest) {\n if (aTest.serverObj.ping < lowestPingRegServer.ping) {\n lowestPingRegServer = aTest.serverObj;\n }\n //remove from conn list, check if all are done\n var tmp = pingTestCons.indexOf(aTest);\n if (-1 != tmp) {\n pingTestCons.splice(tmp, 1);\n }\n if (pingTestCons.length == 0) {\n //test done!\n //console.log(\"pingtest: all finished\");\n if (slowTimeout) clearTimeout(slowTimeout);\n quickestConnectRegionFound();\n }\n}", "function APIOK() {\n\treturn (g_objAPI != null)\n}", "function doesNotWantExternalActivity () {\n alert(\"Student does not want the external activity\") ;\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=NO\");\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector,\n processNextProblemResult)\n}", "function LMSFinish()\n{\n\tvar strResult = strCMIFalse\n\tif (objAPI != null){\n\t\tstrResult = objAPI.LMSFinish(strEmptyString)\n\t\tif(strResult == strCMITrue){\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\thandleSCORMError();\n\t\t\treturn false;\n\t\t}\n\t}\n\telse{\n\t\thandleSCORMError();\n\t\treturn false;\n\t}\n}", "function handleAllOfficesChangeOfficeData(allOfficesResponseData) {\r\n\t\r\n\tvar allOfficesJsonData = jQuery.parseJSON(allOfficesResponseData);\r\n\t\r\n\tif(allOfficesJsonData.result_available) { // We got some offices\r\n\t\t$(\"#noChangeOfficeMsg\").hide();\r\n\t\tvar officesJsonArray = allOfficesJsonData.offices;\r\n\t\tif(officesJsonArray != undefined && officesJsonArray != null)\r\n\t\t\tparseOfficesJsonArrayForChangeOffice(officesJsonArray);\r\n\t\t\r\n\t} else { // We did not get any result for filter criteria\r\n\t\t$(\"#noChangeOfficeMsg\").show();\r\n\t\t$(\"#noChangeOfficeMsg\").text(\"No offices.\");\r\n\t}\r\n\t\r\n}", "function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }", "function wantsExternalActivity () {\n alert(\"Student wants the external activity\") ;\n // send an InputResponse to the server with YES. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=YES\");\n}", "function checkIfResult() {\n if (isFinalResult) {\n isFinalResult = false;\n displayContent = \"\";\n }\n}", "function MASE_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASE_SetInfoboxesAndBtns =====\") ;\n\n const step = mod_MASE_dict.step;\n const is_response = (!!response);\n\n console.log(\"......................step\", step) ;\n console.log(\"is_response\", is_response) ;\n console.log(\"test_is_ok\", mod_MASE_dict.test_is_ok) ;\n console.log(\"saved_is_ok\", mod_MASE_dict.saved_is_ok) ;\n console.log(\"is_approve_mode\", mod_MASE_dict.is_approve_mode) ;\n console.log(\"verification_is_ok\", mod_MASE_dict.verification_is_ok) ;\n\n // step 0: opening modal\n // step 1 + response : return after check\n // step 1 without response: save clicked approve or request verifcode\n // step 2 + response : return after approve or after email sent\n // step 2 without response: submit Exform wit hverifcode\n // step 3 + response: return from submit Exform\n\n // TODO is_reset\n const is_reset = mod_MASE_dict.is_reset;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false;\n let show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.approve_msg_html) {\n mod_MASE_dict.msg_html = response.approve_msg_html;\n };\n\n console.log(\" >> step:\", step);\n\n if (step === 0) {\n // step 0: when form opens and request to check is sent to server\n // tekst: 'The subjects of the candidates are checked'\n msg_info_txt = loc.MASE_info.checking_exams;\n show_loader = true;\n } else {\n if(mod_MASE_dict.is_approve_mode){\n // --- is approve\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = mod_MASE_dict.has_already_approved;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.MASE_info.Approve_exams;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n msg_info_txt = (is_reset) ? loc.MASE_info.removing_approval_exams : loc.MASE_info.approving_exams;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else {\n // --- is submit\n if (step === 1) {\n // response with checked subjects\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.Request_verifcode;\n };\n } else if (step === 2) {\n // clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MASE_info.sending_verifcode;\n show_loader = true;\n } else if (step === 3) {\n // response 'email sent'\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n show_input_verifcode = true;\n disable_save_btn = !el_MASE_input_verifcode.value;\n save_btn_txt = loc.Publish_exams;\n } else if (step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n show_loader = true;\n } else if (step === 5) {\n // response 'Exform submittes'\n // msg_info_txt is in response\n }\n } // if(mod_MASE_dict.is_approve_mode)\n } // if (step === 0)\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n\n if (msg_info_txt){\n mod_MASE_dict.msg_html = \"<div class='pt-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \" ...</p></div>\";\n }\n\n const hide_info_container = (!msg_info_txt || show_loader)\n add_or_remove_class(el_MASE_info_container, cls_hide, hide_info_container)\n\n el_MASE_msg_container.innerHTML = mod_MASE_dict.msg_html;\n add_or_remove_class(el_MASE_msg_container, cls_hide, !mod_MASE_dict.msg_html)\n\n add_or_remove_class(el_MASE_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASE_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n add_or_remove_class(el_MASE_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n\n if (el_MASE_info_request_msg1){\n el_MASE_info_request_msg1.innerText = loc.MASE_info.need_verifcode +\n ((permit_dict.requsr_role_admin) ? loc.MASE_info.to_publish_exams : \"\");\n };\n\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASE_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASE_btn_delete, cls_hide, !show_delete_btn);\n\n console.log(\"save_btn_txt\", save_btn_txt) ;\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASE_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASE_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MASE_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASE_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n } // MASE_SetInfoboxesAndBtns", "function sendInterventionDialogYesNoConfirmInputResponse (event, fn, userInput) {\n\n incrementTimers(globals);\n servletFormPost(event, \"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector + \"&userInput=\"+userInput,\n fn) ;\n}", "function finishRegistration() {\n if(!addressChosen) {\n alert(\"Please unlock your Ethereum address\");\n return;\n }\n\n if(state != 1) {\n alert(\"Please wait until Registration Phase\");\n return;\n }\n\n if(myvotingAddr.totalregistered() < 3) {\n alert(\"Election cannot begin until there is 3 or more registered voters\");\n return;\n }\n\n\n web3.personal.unlockAccount(addr,password);\n\n res = myvotingAddr.finishRegistrationPhase.sendTransaction({from:web3.eth.accounts[accountindex], gas: 4200000});\n document.getElementById(\"finishRegistration\").innerHTML = \"Waiting for Ethereum to confirm that Registration has finished\";\n\n //txlist(\"Finish Registration Phase: \" + res);\n}", "function Active_DeactiveCampaign(record) {\n debugger;\n var Enabled = record.Enabled;\n var message = \"\";\n if (Enabled == \"False\") {\n message = confirm('Are you sure you want to activate this item?');\n }\n else {\n message = confirm('Are you sure you want to de-activate this item?');\n }\n\n if (message != 0) {\n return true;\n }\n else {\n return false;\n }\n\n\n}", "function submitPage() {\n GetLookupChanges();\n Page_ClientValidate();\n if (!Page_IsValid) {\n return false;\n }\n if (getPageChanges()) {\n if (ifgEquipmentInformation.Submit() == false || _RowValidationFails) {\n return false;\n }\n return UpdateEquipmentInformation();\n }\n else {\n showInfoMessage('No Changes to Save');\n }\n return true;\n}", "function newgameOK(response) {\n if (response.indexOf(\"<!doctype html>\") !== -1) { // User has timed out.\n window.location = \"access-denied.html\";\n } else if (response === \"nobox\") {\n $(\"#bi_error\").text('Invalid Game Box ID.').show(); \n $(\"#boxid\") .trigger('focus');\n } else if (response === \"dupname\") {\n $(\"#sn_error\").text('Duplicate Game Name is not allowed.').show(); \n $(\"#sessionname\") .trigger('focus');\n } else if (response.indexOf(\"noplayer\") !== -1) { \n // Response contains \"noplayer\".\n var plerr = 'Player #' + response.substr(9) + ' does not exist';\n $(\"#pc_error\").text(plerr).show(); \n $(\"#player1\") .trigger('focus');\n } else if (response === \"success\") {\n $('#newgame .error').hide();\n $('#newgame :text').val('');\n // Send an email notification to each player in the game.\n var cString;\n BD18.mailError = false;\n for (var i = 0; i < BD18.playerCount; i++) {\n cString = 'game=' + BD18.name + '&login=' + BD18.player[i];\n $.post(\"php/emailPlayerAdd.php\", cString, emailPlayerResult);\n }\n delayGoToMain();\n } else if (response === \"fail\") {\n var ferrmsg ='New game was not created due to an error.\\n';\n ferrmsg += 'Please contact the BOARD18 webmaster.';\n alert(ferrmsg);\n } else { // Something is definitly wrong in the code.\n var nerrmsg ='Invalid return code from createGame.php.\\n';\n nerrmsg += response + '\\nPlease contact the BOARD18 webmaster.';\n alert(nerrmsg);\n }\n}", "function endCallback() {\n endIANA(session);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Monitor GPRS 3000 7 huboVentas(mes, anio): que indica si hubo ventas en un mes determinado.
function huboVentas (mes, anio) { return ventasMes(mes, anio) > 0; }
[ "function siguienteMes(){\n if (numeroMes !== 11){\n numeroMes++;\n }else{\n numeroMes=0;\n anioCorriente++;\n }\n\n setearFechaNueva();\n}", "async scan() {\n try {\n let that = this\n await waitUntil(() => {\n return (that.state === 'poweredOn')\n }, 20000)\n console.log('Starting to scan...')\n return await waitUntil(() => {\n noble.stopScanning()\n if(that.peripherals.length <= 0) {\n console.log('Scanning...')\n noble.startScanning()\n } else {\n console.log('Found ' + that.peripherals.length + ' devices.')\n return that.peripherals\n }\n }, 20000, 4000)\n } catch (err) {\n throw new Error(err)\n }\n }", "function process_message_from_monitor(mtype,mvalue){\n if (mtype==\"connected\"){\n console.log(\"Monitor connected\");\n } else if(mtype==\"start_experiment\"){\n var tiempo = new Date().getTime();\n insertRecord_js(\"timeMarks\",\"timeStamp, name\",` '${tiempo}', 'start_exp' `);\n } else if(mtype==\"time_marks\"){\n var tiempo_server = new Date().getTime();\n insertRecord_js(\"timeMarks\",\"timeStamp,timeStampLocal, name\",` '${tiempo_server}', '${mvalue}', 'stamp' `);\n } else if(mtype==\"update_game_vars\"){\n console.log(\"updating_game_vars\");\n load_game_parameters();\n } else {\n console.log(\"Type of Messsage from Monitor not recognised: \" + mtype);\n }\n}", "function check_potentiometer(reading) {\n\t\tpotentiometer_check = Math.floor(reading.value * 100);\n\t\tif (potentiometer_reading != potentiometer_check\n\t\t\t\t\t\t\t\t && !isNaN(potentiometer_check)){\n\t\t\tpotentiometer_reading = potentiometer_check;\n\t\t\tsocket.emit(\"potentiometer\", potentiometer_check);\n\t\t}\n\t}", "async startMonitor() {\n this.monitor = true\n this.fill()\n this.node.swarm.db.events.subscribe(() => {\n //update the data on swarm update if monitoring is On\n this.fill()\n })\n }", "async listen() {\n const contract = await this.getContract();\n contract.on('Claimed', async (vendor, phone, amount) => {\n try {\n const otp = Math.floor(1000 + Math.random() * 9000);\n const data = await this.setHashToChain(contract, vendor, phone.toString(), otp.toString());\n\n const message = `A vendor is requesting ${amount} token from your account. If you agree, please provide this OTP to vendor: ${otp}`;\n // eslint-disable-next-line global-require\n const sms = require(`./plugins/sms/${config.get('plugins.sms.service')}`);\n\n // call SMS function from plugins to send SMS to beneficiary\n sms(phone.toString(), message);\n } catch (e) {\n console.log(e);\n }\n });\n console.log('--- Listening to Blockchain Events ----');\n }", "function wlansChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = listWLANs;\n pushstream.addChannel('wlans');\n pushstream.connect();\n $.ajax({\n url: '/command/?cmd=wifiscan',\n cache: false\n });\n}", "async function periodicRefresh(){\n try {\n tsLogger('Refreshing monitor data, monitor data, and missed events...');\n\n //Get daily usage data\n let today = new Date();\n let todayMidnight = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);\n dailyUsageData = await mySense.getDailyUsage(moment.utc(todayMidnight).format());\n\n //Get monitor stats\n let monitor = await mySense.getMonitorInfo()\n monitorData = monitor;\n updateMonitorInfo();\n refreshDeviceList();\n getMissedEvents();\n } catch (error) {\n tsLogger(`Error in periodicRefresh: ${error.message}`)\n }\n}", "function start_monitoring()\n {\n browser.idle.onStateChanged.addListener(on_idle_state_change);\n }", "carMessageHandler(err,msg) {\n var carjo=msg.body;\n console.log(JSON.stringify(carjo));\n var sv=simulatorVerticle;\n switch (carjo.type) {\n case 'servodirect':\n if (carjo.position) {\n // the position can be between -100 and 100\n var pos=parseFloat(carjo.position);\n // we need a value between -1 and +1\n sv.remoteControl.steer=pos/100;\n }\n break;\n case 'servo':\n switch (carjo.position) {\n case 'left':\n sv.remoteControl.steer-=0.01;\n break;\n case 'right':\n sv.remoteControl.steer+=0.01;\n break;\n case 'center':\n sv.remoteControl.steer=0;\n break;\n }\n break;\n case 'motor':\n switch (carjo.speed) {\n case 'up':\n sv.remoteControl.gas+=0.01;\n break;\n case 'down':\n sv.remoteControl.gas-=0.01;\n break;\n case 'brake':\n sv.remoteControl.break+=0.01;\n break;\n case 'stop':\n sv.remoteControl.gas=0;\n sv.remoteControl.break=1;\n break;\n }\n break;\n }\n }", "function onDiscover(sensorTag) {\n DiscoveringSensorTag = false;\n console.log('discovered: ' + sensorTag.uuid + ', type = ' + sensorTag.type);\n // Connect the the SensorTag\n sensorTag.connectAndSetUp(function (error) {\n if (error) {\n console.log('ConnectAndSetup Error:' + error);\n SensorTagConnected = false;\n } else {\n // SensorTag connected and setup\n SensorTagConnected = true;\n\n // Set \"disconnect\" callback\n sensorTag.on('disconnect', function () {\n console.log('Sensortag disconnected');\n SensorTagConnected = false;\n });\n\n // Enable IrTemperature sensor, setup 1s period and set callback to send AMQP message to Event Hubs\n sensorTag.enableIrTemperature(function (error) { if (error) console.log('enableIrTemperature ' + error); });\n sensorTag.setIrTemperaturePeriod(1000, function (error) { if (error) console.log('setIrTemperaturePeriod ' + error); });\n sensorTag.notifyIrTemperature(function (error) { if (error) console.log('notifyIrTemperature ' + error); });\n sensorTag.on('irTemperatureChange', function (objectTemperature, ambientTemperature) {\n var currentTime = new Date().toISOString();\n var irObjTemp = (objectTemperature.toFixed(1) * 9) / 5 + 32;\n connectthedots.send_message(\"IRTemperature\", \"F\", irObjTemp);\n });\n \n // Enable Humidity sensor, setup 1s period and set callback to send AMQP message to Event Hubs\n sensorTag.enableHumidity(function (error) { if (error) console.log('enableHumidity ' + error); });\n sensorTag.setHumidityPeriod(1000, function (error) { if (error) console.log('setHumidityPeriod ' + error); });\n sensorTag.notifyHumidity(function (error) { if (error) console.log('notifyHumidity ' + error); });\n sensorTag.on('humidityChange', function (temperature, humidity) {\n var currentTime = new Date().toISOString();\n var temp = (temperature.toFixed(1) * 9) / 5 + 32;\n var hmdt = humidity.toFixed(1);\n connectthedots.send_message(\"Temperature\", \"F\", temp);\n connectthedots.send_message(\"Humidity\", \"%\", hmdt);\n });\n }\n });\n}", "function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }", "function startHR() {\nheartRateArray = new Array();\nwindow.webapis.motion.start(\"HRM\", function onSuccess(hrmInfo) {\n if (hrmInfo.heartRate > 0) \n HR = hrmInfo.heartRate;\n});\n//sendingInterval = setInterval(sendHR, 5000);\nsendingInterval = setInterval(makeJsonHR, 5000);\n}", "async function detectBridgeIP() {\n try {\n const [{ ip }] = await huejay.discover();\n return ip;\n } catch(error) {\n console.log(error);\n }\n}", "function no_of_on_lights(arr){\n arr = command_executor(arr, Light);\n let on_lights_arr = [];\n for( i = 0; i < 1000; i++){\n for( j = 0; j < 1000; j++){\n if(arr[i][j].on){\n on_lights_arr.push(arr[i][j]);\n }\n }\n }\n let length = on_lights_arr.length;\n return length\n}", "async getNemesis(channel) {\n\t\tlet row = await sql.get(`SELECT * FROM Nemesis WHERE Channel = $channel`, {$channel: channel});\n\t\tif(row) {\n\t\t\tlet nemesis = {\n\t\t\t\tid: row.Player_ID,\n\t\t\t\tchannel: row.Channel,\n\t\t\t\ttype: row.Nemesis_Type,\n\t\t\t\tstartTime: row.Nemesis_Time,\n\t\t\t\tattackTime: row.Attack_Time,\n\t\t\t\tdestroyTime: row.Destroy_Time,\n\t\t\t\tenergizeTime: row.Energize_Time,\n\t\t\t\treviveTime: row.Revive_Time,\n\t\t\t\tburnTime: row.Burn_Time,\n\t\t\t\truinTime: row.Ruin_Time,\n\t\t\t\tbasePower: row.Base_Power,\n\t\t\t\tcooldown: row.Nemesis_Cooldown\n\t\t\t};\n\t\t\treturn nemesis;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "function startActivityMonitor() {\n\tclearInterval(activityLoop);\n\tlastActive = Math.ceil((new Date()).getTime() / 1000); //unix time in seconds\n\tactivityLoop = setInterval(timerIncrement, 31000); // Check user active every 31 seconds \n\n}", "function buyHost(){\n if(minions >= hostCost){\n\n //Simply pay in ticks; nothing further required if there's enough.\n if(ticks >= hostCost){\n ticks -= hostCost;\n\n //Removes ticks from the display\n removeTicks(hostCost);\n }\n //Otherwise, ticks and leeches will need to be removed- or maybe even just leeches.\n else{\n let remainingCost = hostCost;\n while(ticks < remainingCost && remainingCost > 0){\n leeches -= 1;\n remainingCost -= leechWeight;\n removeLeeches(1);\n }\n //Either cost is paid off, or the player now has enough ticks to foot the bill\n if(remainingCost > 0)\n {\n ticks -= remainingCost;\n removeTicks(remainingCost);\n }\n }\n\n //Finally, give the player the host and update displays/values\n scream.play();\n hosts += 1;\n\n //Calculate new values and update labels\n performCalculations();\n updateLabels();\n }\n}", "function scanPirates(callback) {\n serialPort.list(function (err, ports) {\n var pirates = [];\n ports.forEach(function(port) {\n // BusPirate v3\n if (port.vendorId == '0x0403' &&\n port.productId == '0x6001') {\n port.buspirate = 3;\n pirates.push(port);\n }\n });\n // return list of buspirates found\n callback(pirates);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the time necessary to compute the hash in milliseconds (worstcase scenario)
calculateTimeToHash(combinations) { return { md5: combinations / this.calculationTimes.md5, sha1: combinations / this.calculationTimes.sha1, sha256: combinations / this.calculationTimes.sha256, bcrypt: combinations / this.calculationTimes.bcrypt, ntlm: combinations / this.calculationTimes.ntlm, owasp: combinations * this.calculationTimes.owasp, online: combinations * this.calculationTimes.online, } }
[ "digesting() {}", "static getHash(block){\r\n const {timestamp, lastHash, data, nonce} = block;\r\n return this.createHash(data, timestamp, lastHash, nonce, difficulty);\r\n }", "function getHashDifficulty(hash) {\n let difficulty = 0\n\n for (let i = 0; i < hash.length; i++) {\n if (hash[i] === 0) {\n difficulty += 8\n continue\n } else if (hash[i] === 1) {\n difficulty += 7\n } else if (hash[i] < 4) {\n difficulty += 6\n } else if (hash[i] < 8) {\n difficulty += 5\n } else if (hash[i] < 16) {\n difficulty += 4\n } else if (hash[i] < 32) {\n difficulty += 3\n } else if (hash[i] < 64) {\n difficulty += 2\n } else if (hash[i] < 128) {\n difficulty += 1\n }\n break\n }\n\n return difficulty\n}", "calculateHash(data, timestamp, previousHash, nonce) {\n return SHA256(JSON.stringify(data) + timestamp + previousHash + nonce).toString();\n }", "getHashCode() {\n let hash = this._m[0] || 0;\n for (let i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this._m[i] || 0);\n }\n return hash;\n }", "function hash(uuid) {\n var hash = 0, i, chr;\n if (uuid.length === 0) return hash;\n for (i = 0; i < uuid.length; i++) {\n chr = uuid.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n if (hash < 0) {\n hash += 1;\n hash *= -1;\n }\n return hash % constants.localStorage.numBins;\n}", "static async hash(data) {\n if (! (\"subtle\" in window.crypto)) {\n return undefined;\n }\n\n let input = new TextEncoder().encode(data);\n let hash = await window.crypto.subtle.digest(\"SHA-512\", input);\n let bytes = new Uint8Array(hash);\n\t let hex = Array.from(bytes).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n\t return hex.slice(0, 32);\n }", "consistent(blindHash, factor, hash) {\n let n = this.key.keyPair.n;\n let e = new BigInteger(this.key.keyPair.e.toString());\n blindHash = blindHash.toString();\n let bigHash = new BigInteger(hash, 16);\n let b = bigHash.multiply(factor.modPow(e, n)).mod(n).toString();\n let result = blindHash === b;\n return result;\n }", "function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}", "executionTime() {\n const start = process.hrtime();\n // Divide by a million to get nanoseconds to milliseconds\n const elapsed = process.hrtime(start)[1] / ONE_MILLION;\n return `${elapsed.toFixed(DECIMAL_PRECISION)}ms`;\n }", "getHashCode() {\n let hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n }", "function hashMessage(message, algorithm) {\n const hash = crypto.createHash(algorithm);\n hash.update(message);\n const hashValue = hash.digest('hex')\n console.log(hashValue);\n return hashValue;\n}", "function hash_code ( display_name ) {\n\n\tvar d = new Date().getTime();\n\td += display_name;\n\n\tif (window.performance && typeof window.performance.now === \"function\") {\n\t\td += performance.now(); //use high-precision timer if available\n\t}\n\n\tvar hash = 0, i, chr, len;\n\tlen = d.length;\n\n\tif ( len === 0 )\n\t \treturn hash;\n\n\tfor( i = 0; i < len; i++ ) {\n\n\t\tchr = d.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + chr;\n\t\thash |= 0; // Convert to 32bit integer\n\n\t}\n\n\tconsole.log ('Anonymous user id: '+ hash );\n\n\treturn hash;\n}", "hashCode () {\n\n /* x hash code. */\n const xstr = String(this._x);\n const len0 = xstr.length;\n let xhsh = 0;\n for (let i = 0; i < len0; ++i) {\n xhsh = Math.imul(31, xhsh) ^ xstr.charCodeAt(i) | 0;\n }\n xhsh >>>= 0;\n\n /* y hash code. */\n const ystr = String(this._y);\n const len1 = ystr.length;\n let yhsh = 0;\n for (let j = 0; j < len1; ++j) {\n yhsh = Math.imul(31, yhsh) ^ ystr.charCodeAt(j) | 0;\n }\n yhsh >>>= 0;\n\n /* Composite hash code. */\n let hsh = -2128831035;\n hsh = Math.imul(16777619, hsh) ^ xhsh;\n hsh = Math.imul(16777619, hsh) ^ yhsh;\n return hsh;\n }", "async getSysUpTime()\n {\n return ((new Date()).getTime() - this.cache.startTime.getTime()) / 10;\n }", "function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}", "static hash(imageData, canvas) {\n let size = Average.size,\n pixelCount = (size * size);\n\n // console.log(`avgwidth:${imageData.width}. avgheight:${imageData.height}`);\n\n if (imageData.width != size || imageData.size != size) {\n // console.log(`Scaling the image`);\n imageData = Resample.nearestNeighbour(canvas, imageData, size, size);\n console.log(`new imagedata:${typeof imageData}`);\n console.log(imageData.data);\n }\n\n imageData = Colour.grayscale(canvas, imageData);\n\n let sum = 0;\n for (let i = 0; i < pixelCount; i++) {\n // already grayscale so just take the first channel\n console.log(`new imagedata:${typeof imageData}`);\n console.log(imageData.data);\n sum += imageData.data[4 * i];\n }\n\n let average = Math.floor(sum / pixelCount),\n hash = 0,\n one = 1;\n\n for (let i = 0; i < pixelCount; i++) {\n if (imageData.data[4 * i] > average) {\n hash |= one;\n }\n\n one = one << 1;\n }\n\n return hash;\n }", "function core_sha1(x, len) {\n\t/* append padding */\n\tx[len >> 5] |= 0x80 << (24 - len % 32);\n\tx[((len + 64 >> 9) << 4) + 15] = len;\n\n\tvar w = Array(80);\n\tvar a =\t1732584193;\n\tvar b = -271733879;\n\tvar c = -1732584194;\n\tvar d =\t271733878;\n\tvar e = -1009589776;\n\n\tfor(var i = 0; i < x.length; i += 16) {\n\t\tvar olda = a;\n\t\tvar oldb = b;\n\t\tvar oldc = c;\n\t\tvar oldd = d;\n\t\tvar olde = e;\n\n\t\tfor(var j = 0; j < 80; j++) {\n\t\t\tif(j < 16) w[j] = x[i + j];\n\t\t\telse w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\n\t\t\tvar t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n\t\t\t\t\t\t\t\t\t\t\t safe_add(safe_add(e, w[j]), sha1_kt(j)));\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rol(b, 30);\n\t\t\tb = a;\n\t\t\ta = t;\n\t\t}\n\n\t\ta = safe_add(a, olda);\n\t\tb = safe_add(b, oldb);\n\t\tc = safe_add(c, oldc);\n\t\td = safe_add(d, oldd);\n\t\te = safe_add(e, olde);\n\t}\n\treturn Array(a, b, c, d, e);\n\n}", "function getTimeInMilliseconds(h, m, s, ms){\n return h * 3600000 + m * 60000 + s * 1000 + ms; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets Resources versions from environmental variable RESOURCES_VERSIONS should be string in format: "resourceOneName=1.0,resourceTwoName=1.1"
function getVersionFromConfig (resourceString) { const resourceVersionMap = {}; resourceString .split(',') .forEach(e => e.split('=') .reduce((p, c) => { resourceVersionMap[p] = { contentVersion: c, acceptVersion: c.split('.')[0], }; })); return resourceVersionMap; }
[ "getResources(includeTs) {\n const resources = this.data.manifest.control.resources;\n let pathsCollection = [];\n Object.keys(resources).forEach(resourceType => {\n let paths;\n if (resourceType !== constants.LIBRARY_ELEM_NAME) {\n paths = (resourceType === constants.CODE_ELEM_NAME && !includeTs) ? [] : resources[resourceType].map((resource) => resource.$.path);\n }\n else {\n paths = flatMap(resources[resourceType], (resource) => resource['packaged_library'] ? resource['packaged_library'].map((packagedLib) => packagedLib.$.path) : []);\n }\n pathsCollection.push(...paths);\n });\n return pathsCollection;\n }", "function updateDeployPreviewVersions(versions) {\n const newVersions = [versions[0], versions[versions.length - 1]];\n console.log(\n 'Netlify deploy previews will only deploy a subset of available versions: ' +\n newVersions.join(' - '),\n );\n return newVersions;\n}", "function getApiVersion (suppVerList, verList, index, fallbackIndex, apiType)\n{\n var ip = null;\n var port = null;\n var config = configUtils.getConfig();\n \n try {\n var verCnt = verList.length;\n var suppVerCnt = suppVerList.length;\n } catch(e) {\n return null;\n }\n for (var i = index; i < verCnt; i++) {\n for (var j = 0; j < suppVerCnt; j++) {\n try {\n if (verList[i]['version'] != suppVerList[j]) {\n continue;\n } else {\n return {'version': verList[i]['version'], 'index': i,\n 'protocol': verList[i]['protocol'], \n 'ip': verList[i]['ip'], 'port': verList[i]['port'],\n 'fallbackIndex': -1};\n }\n } catch(e) {\n continue;\n }\n }\n }\n /* We are done with all versions in catalog, so now fall back to next\n * available supported list \n */\n for (var i = fallbackIndex; i >= 0; i--) {\n for (var j = 0; j < verCnt; j++) {\n if (suppVerList[i] != verList[j]) {\n /* Put index verCnt, such that next time, it does not fall into\n * earlier loop\n */\n return {'version': suppVerList[i], 'index': verCnt,\n 'protocol': verList[j]['protocol'],\n 'ip': verList[j]['ip'], \n 'port': verList[j]['port'], 'fallbackIndex': i};\n }\n }\n }\n return null;\n}", "async function getPkgReleases({ lookupName, registryUrls }) {\n const { registry, repository } = getRegistryRepository(\n lookupName,\n registryUrls\n );\n logger.debug({ registry, repository }, 'terraform.getDependencies()');\n const cacheNamespace = 'terraform';\n const pkgUrl = `${registry}/v1/modules/${repository}`;\n const cachedResult = await renovateCache.get(cacheNamespace, pkgUrl);\n // istanbul ignore if\n if (cachedResult) {\n return cachedResult;\n }\n try {\n const res = (await got(pkgUrl, {\n json: true,\n hostType: 'terraform',\n })).body;\n const returnedName = res.namespace + '/' + res.name + '/' + res.provider;\n if (returnedName !== repository) {\n logger.warn({ pkgUrl }, 'Terraform registry result mismatch');\n return null;\n }\n // Simplify response before caching and returning\n const dep = {\n name: repository,\n versions: {},\n };\n if (res.source) {\n dep.sourceUrl = parse(res.source);\n }\n dep.releases = res.versions.map(version => ({\n version,\n }));\n if (pkgUrl.startsWith('https://registry.terraform.io/')) {\n dep.homepage = `https://registry.terraform.io/modules/${repository}`;\n }\n logger.trace({ dep }, 'dep');\n const cacheMinutes = 30;\n await renovateCache.set(cacheNamespace, pkgUrl, dep, cacheMinutes);\n return dep;\n } catch (err) {\n if (err.statusCode === 404 || err.code === 'ENOTFOUND') {\n logger.info(\n { lookupName },\n `Terraform registry lookup failure: not found`\n );\n logger.debug({\n err,\n });\n return null;\n }\n logger.warn(\n { err, lookupName },\n 'Terraform registry failure: Unknown error'\n );\n return null;\n }\n}", "function loadProjectVersions($scope, $element, project, env, ns, answer, caches) {\n var projectAnnotation = \"project\";\n var versionAnnotation = \"version\";\n var projectNamespace = project.$namespace;\n var projectName = project.$name;\n var cache = caches[ns];\n if (!cache) {\n cache = {};\n caches[ns] = cache;\n }\n var status = {\n rcs: [],\n pods: [],\n routes: [],\n services: []\n };\n var imageStreamTags = [];\n function updateModel() {\n var projectInfos = {};\n var model = $scope.model || {};\n angular.forEach(status.rcs, function (item) {\n var metadata = item.metadata || {};\n var name = metadata.name;\n var labels = metadata.labels || {};\n var annotations = metadata.annotations || {};\n var spec = item.spec || {};\n var selector = spec.selector;\n var project = labels[projectAnnotation];\n var version = labels[versionAnnotation];\n // lets try the S2I defaults...\n if (!project) {\n project = labels[\"app\"];\n }\n if (!version) {\n version = annotations[\"openshift.io/deployment-config.latest-version\"];\n }\n if (project && version && project === projectName) {\n var projects = projectInfos[project];\n if (!projects) {\n projects = {\n project: project,\n versions: {}\n };\n projectInfos[project] = projects;\n }\n var versionInfo = projects.versions[version];\n if (!versionInfo) {\n versionInfo = {\n replicationControllers: {}\n };\n projects.versions[version] = versionInfo;\n }\n if (name) {\n versionInfo.replicationControllers[name] = item;\n item.$name = name;\n if (projectNamespace && projectName) {\n item.$viewLink = UrlHelpers.join(\"/workspaces/\", projectNamespace, \"projects\", projectName, \"namespace\", ns, \"replicationControllers\", name);\n }\n else {\n Developer.log.warn(\"Missing project data! \" + projectNamespace + \" name \" + projectName);\n }\n item.$services = [];\n var rcLink = null;\n status.services.forEach(function (service) {\n var repSelector = Kubernetes.getSelector(item);\n var serviceSelector = Kubernetes.getSelector(service);\n if (serviceSelector && repSelector &&\n Kubernetes.selectorMatches(serviceSelector, repSelector) &&\n Kubernetes.getNamespace(service) === Kubernetes.getNamespace(item)) {\n status.routes.forEach(function (route) {\n var serviceName = Kubernetes.getName(service);\n if (serviceName === Kubernetes.getName(route)) {\n service[\"$route\"] = route;\n service[\"$host\"] = Core.pathGet(route, [\"spec\", \"host\"]);\n item.$services.push(service);\n if (!rcLink) {\n var url = Kubernetes.serviceLinkUrl(service, true);\n if (url) {\n // TODO find icon etc?\n rcLink = {\n name: serviceName,\n href: url\n };\n }\n }\n }\n });\n }\n });\n item[\"$serviceLink\"] = rcLink;\n }\n item.$buildId = annotations[\"fabric8.io/build-id\"] || item.$buildId;\n item.$buildUrl = annotations[\"fabric8.io/build-url\"] || item.$buildUrl;\n item.$gitCommit = annotations[\"fabric8.io/git-commit\"] || item.$gitCommit;\n item.$gitUrl = annotations[\"fabric8.io/git-url\"] || item.$gitUrl;\n item.$gitBranch = annotations[\"fabric8.io/git-branch\"] || item.$gitBranch;\n if (!item.$gitCommit) {\n var image = getImage(item);\n if (image) {\n if (!$scope.$isWatchImages) {\n $scope.$isWatchImages = true;\n Kubernetes.watch($scope, $element, \"images\", null, function (data) {\n imageStreamTags = data;\n checkForMissingMetadata();\n });\n }\n else {\n checkForMissingMetadata();\n }\n }\n function getImage(item) {\n var image = \"\";\n // lets see if we can find the commit id from a S2I image name\n // TODO needs this issue fixed to find it via an OpenShift annotation:\n // https://github.com/openshift/origin/issues/6241\n var containers = Core.pathGet(item, [\"spec\", \"template\", \"spec\", \"containers\"]);\n if (containers && containers.length) {\n var container = containers[0];\n if (container) {\n image = container.image;\n }\n }\n return image;\n }\n function checkForMissingMetadata() {\n angular.forEach(projects.versions, function (vi) {\n angular.forEach(vi.replicationControllers, function (item, name) {\n if (!item.$gitCommit) {\n var image = getImage(item);\n if (image) {\n angular.forEach(imageStreamTags, function (imageStreamTag) {\n var imageName = imageStreamTag.dockerImageReference;\n if (imageName && imageName === image) {\n var foundISTag = imageStreamTag;\n var manifestJSON = imageStreamTag.dockerImageManifest;\n if (manifestJSON) {\n var manifest = angular.fromJson(manifestJSON) || {};\n var history = manifest.history;\n if (history && history.length) {\n var v1 = history[0].v1Compatibility;\n if (v1) {\n var data = angular.fromJson(v1);\n var env = Core.pathGet(data, [\"config\", \"Env\"]);\n angular.forEach(env, function (envExp) {\n if (envExp) {\n var values = envExp.split(\"=\");\n if (values.length === 2 && values[0] == \"OPENSHIFT_BUILD_NAME\") {\n var buildName = values[1];\n if (buildName) {\n item.$buildId = buildName;\n item.$buildUrl = Developer.projectWorkspaceLink(ns, projectName, \"buildLogs/\" + buildName);\n }\n }\n }\n });\n var labels = Core.pathGet(data, [\"config\", \"Labels\"]);\n if (labels) {\n item.$gitCommit = labels[\"io.openshift.build.commit.id\"] || item.$gitCommit;\n item.$gitCommitAuthor = labels[\"io.openshift.build.commit.author\"] || item.$gitCommitAuthor;\n item.$gitCommitDate = labels[\"io.openshift.build.commit.date\"] || item.$gitCommitDate;\n item.$gitCommitMessage = labels[\"io.openshift.build.commit.message\"] || item.$gitCommitMessage;\n item.$gitBranch = labels[\"io.openshift.build.commit.ref\"] || item.$gitBranch;\n if (!item.$gitUrl && item.$gitCommit) {\n item.$gitUrl = Developer.projectWorkspaceLink(ns, projectName, \"wiki/commitDetail///\" + item.$gitCommit);\n }\n }\n }\n }\n }\n }\n });\n }\n }\n });\n });\n }\n }\n if (selector) {\n var selectorText = Kubernetes.labelsToString(selector, \",\");\n var podLinkUrl = UrlHelpers.join(Developer.projectLink(projectName), \"namespace\", ns, \"pods\");\n item.pods = [];\n item.$podCounters = Kubernetes.createPodCounters(selector, status.pods, item.pods, selectorText, podLinkUrl);\n }\n }\n });\n // lets check for a project name if we have lots of RCs with no pods, lets remove them!\n angular.forEach(projectInfos, function (project, projectName) {\n var rcsNoPods = [];\n var rcsWithPods = [];\n angular.forEach(project.versions, function (versionInfo) {\n var rcs = versionInfo.replicationControllers;\n angular.forEach(rcs, function (item, name) {\n var count = Kubernetes.podCounterTotal(item.$podCounters);\n if (count) {\n rcsWithPods.push(name);\n }\n else {\n rcsNoPods.push(function () {\n delete rcs[name];\n });\n }\n });\n });\n if (rcsWithPods.length) {\n // lets remove all the empty RCs\n angular.forEach(rcsNoPods, function (fn) {\n fn();\n });\n }\n });\n if (hasObjectChanged(projectInfos, cache)) {\n Developer.log.debug(\"project versions has changed!\");\n answer[ns] = projectInfos;\n }\n }\n Kubernetes.watch($scope, $element, \"replicationcontrollers\", ns, function (data) {\n if (data) {\n status.rcs = data;\n updateModel();\n }\n });\n Kubernetes.watch($scope, $element, \"services\", ns, function (data) {\n if (data) {\n status.services = data;\n updateModel();\n }\n });\n Kubernetes.watch($scope, $element, \"routes\", ns, function (data) {\n if (data) {\n status.routes = data;\n updateModel();\n }\n });\n Kubernetes.watch($scope, $element, \"pods\", ns, function (data) {\n if (data) {\n status.pods = data;\n updateModel();\n }\n });\n }", "function getResources() {\n\t\t\treturn $q.when(resources);\n\t\t}", "function prepare() {\n var releases = [];\n\n // release:env\n envs.forEach(function (env) {\n var _tasks = [];\n // all apps with `env` settings\n apps.forEach(function (app) {\n _tasks.push('release:' + app + ':' + env);\n });\n releases.push({\n task: 'release:' + env,\n arr : _tasks\n });\n });\n\n // release:app1\n apps.forEach(function (app) {\n // `app` with dev settings\n releases.push({\n task: 'release:' + app,\n arr : ['release:' + app + ':dev']\n });\n });\n\n // release:app1:env\n apps.forEach(function (app) {\n envs.forEach(function (env) {\n releases.push({\n task: 'release:' + app + ':' + env,\n arr : ['release:' + app + ':' + env]\n });\n });\n });\n\n var _tasks = [];\n apps.forEach(function (app) {\n _tasks.push('release:' + app + ':dev');\n });\n\n releases.push({\n task: 'release',\n arr : _tasks\n });\n\n return releases;\n}", "function filterVersions(versionNamesUnfiltered, options) {\n if (options.onlyIncludeVersions) {\n return versionNamesUnfiltered.filter((name) => (options.onlyIncludeVersions || []).includes(name));\n }\n else {\n return versionNamesUnfiltered;\n }\n}", "function loadVersions() {\n showMessage(\"Loading available API versions ...\");\n console.log(\"loadVersions() started\");\n osapi.jive.connects.get({\n alias : ALIAS,\n href : '/services/data'\n }).execute(function (response) {\n console.log(\"loadVersions() response = \" + JSON.stringify(response));\n if (response.error) {\n if (response.error.code == 401) {\n console.log(\"Received a 401 response, triggering reconfiguration\");\n osapi.jive.connects.reconfigure(ALIAS, response, function(feedback) {\n console.log(\"Received reconfigure feedback \" + JSON.stringify(feedback));\n loadVersions();\n })\n }\n else {\n alert(\"Error \" + response.error.code + \" loading data: \" + response.error.message);\n }\n }\n else {\n versions = response.content;\n var html = \"\";\n $.each(versions, function(index, v) {\n html += '<li class=\"version-item\">'\n + '<a class=\"version-link\" href=\"#\" data-index=\"' + index + '\">' + v.label + '</a>'\n + ' (Version ' + v.version + ')</li>';\n });\n $(\"#versions-list\").html(\"\").html(html);\n $(\".version-link\").click(function() {\n var index = $(this).attr(\"data-index\");\n version = versions[index];\n $(\".version-title\").html(\"\").html(version.label + ' (Version ' + version.version + ')');\n loadResources();\n });\n showOnly(\"versions-div\");\n }\n });\n}", "async function getMicroAppVersions() {\n const compRegistryAPI = global.RM_COMPREGISTRY_URL;\n return fetch(compRegistryAPI)\n .then(res => {\n if (res.data && res.data.length) {\n console.log(chalk.green('Component Registry Data:'));\n createMicroAppRegistryTable(res.data);\n } else {\n console.log(chalk.red(`(\\u2718) No components found in registry!`));\n }\n return res.data;\n })\n .catch(err => {\n console.log(chalk.red('Component Registry Error -'));\n console.log(chalk.red(`(\\u2718) ${err.toString()}`));\n return { err };\n });\n}", "function getEndpointsByEnvironment(){\n const env = getEnvironmentString();\n\n const envs = {\n \"develop01\": {\n \"stage\": \"develop01\",\n \"kasEndpoint\": \"https://api-develop01.develop.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm-develop01.develop.virtru.com\",\n \"easEndpoint\": \"https://accounts-develop01.develop.virtru.com\",\n },\n \"staging\": {\n \"stage\": \"staging\",\n \"kasEndpoint\": \"https://api.staging.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm.staging.virtru.com\",\n \"easEndpoint\": \"https://accounts.staging.virtru.com\",\n },\n \"production\": {\n \"stage\": \"production\",\n \"kasEndpoint\": \"https://api.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm.virtru.com\",\n \"easEndpoint\": \"https://accounts.virtru.com\",\n }\n };\n\n return envs[env] || envs['production'];\n}", "function getVersion() {\n var contents = grunt.file.read(\"formulate.meta/Constants.cs\");\n var versionRegex = new RegExp(\"Version = \\\"([0-9.]+)\\\";\", \"gim\");\n return versionRegex.exec(contents)[1];\n }", "function filterNeededVersions (neededVersions, allVersions) {\n la(is.array(neededVersions), 'needed versions should be a list', neededVersions)\n la(is.array(allVersions), 'all versions should be a list', allVersions)\n if (is.empty(neededVersions)) {\n return allVersions\n }\n return allVersions.filter(function (version) {\n return neededVersions.some(function (ver) {\n return semver.satisfies(version, ver)\n })\n })\n}", "function updateVersions() {\r\n\r\n\t\t\t\t\t\tconsole.log(\"updateVersions\");\r\n\r\n\t\t\t\t\t\tinekonApi.getVersions($scope.cartId)\r\n\t\t\t\t\t\t\t\t.then(\r\n\t\t\t\t\t\t\t\t\t\tfunction(result) {\r\n\t\t\t\t\t\t\t\t\t\t\tvar data = result.data;\r\n\t\t\t\t\t\t\t\t\t\t\t$scope.cartId = data.id;\r\n\t\t\t\t\t\t\t\t\t\t\t$scope.versions = data.versions;\r\n\t\t\t\t\t\t\t\t\t\t\tconsole.log($scope.cartId,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t$scope.versions);\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t}", "async listVersions({ id, fields = [] } = {}) {\n const dbService = await this.service('dbService');\n const table = this.tableName;\n\n if (_.isNil(id)) {\n // The scanner route\n const result = await dbService.helper\n .scanner()\n .table(table)\n .filter('attribute_not_exists(latest)') // we don't want to return the v0000_ one\n .limit(2000)\n .projection(fields)\n .scan();\n return _.map(result, item => toDataObject(item));\n }\n\n const result = await dbService.helper\n .query()\n .table(table)\n .key('id', id)\n .forward(false)\n .filter('attribute_not_exists(latest)') // we don't want to return the v0000_ one\n .limit(2000)\n .projection(fields)\n .query();\n const versions = _.map(result, item => toDataObject(item));\n if (versions.length === 0) throw this.boom.notFound(`The workflow template \"${id}\" is not found`, true);\n\n return versions;\n }", "function extractVersionNumbers(aTags) {\n const aFilteredResult = [];\n aTags.forEach(function (tag) {\n const versionNumber = getVersionNumberFromTagName(tag.name);\n if (versionNumber) {\n tag.cdToolkitVersionNumber = versionNumber;\n aFilteredResult.push(tag)\n }\n });\n\n return aFilteredResult;\n}", "function fnValidateConfigVersion(){\n return {\n inCase: { has: \"version\" },\n prop: \"version\",\n check: [\n { check: isNEString, error: `'version' PROPERTY MUST BE A NON-EMPTY STRING` },\n { check: isIncludedIn([\"1.18\", \"1.19\", \"2.0\", \"2.1\", \"2.2\", \"2.3\", \"2.4\"]), error: version => `THIS CONFIGURATION FILE REQUIRES A VERSION OF EASY-SAMBA COMPATIBLE WITH '${version}'` }\n ]\n };\n}", "function getVersions(res)\n { //powershell -command \"& {&Get-ItemPropertyValue 'D:\\unityVersions\\unity1 - Copy (4)\\Editor\\Uninstall.exe' -name 'VersionInfo' | ConvertTo-Json}\"\n return new promise(function(resolve,reject){\n\n var asyncOperations = res.unity.length;\n var result = [];\n\n res.unity.forEach(function(element){\n\n if(fs.existsSync(element+\"Uninstall.exe\")){\n\n var command = 'powershell -command \"& {&Get-ItemPropertyValue -Path \\''+ element + \"Uninstall.exe\" +'\\' -name \\'VersionInfo\\' | ConvertTo-Json}\"';\n //console.log(command);\n child.exec(command,function(error, ls,stderr){\n\n if(error) {console.error(error);reject(error);} //this is the error on our side\n //this is the error that will be outputed if command is invalid or sm sht\n if(stderr) {\n console.error(stderr);\n console.warn(\"Command that was executed when error happened:\\n\" + command);\n reject(stderr);\n }\n\n ls = ls.toString();\n ls = ls.replace(/\\n|\\r/g, \"\");\n if(ls==\"\") {\n toastr.warn(\"info about unity was returned empty (unity will not be visible as installed)\\n \"+ element);\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }else{\n return\n }\n\n };\n ls = JSON.parse(ls);\n\n\n result.push({\n parentPath:element,\n path:ls.FileName,\n version: ls.ProductName,\n modules:[\n /*{\n name:\"Android\"\n path:\"...Editor\"\n version:\"N/A\"\n }*/\n ]\n });\n\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }\n })\n\n }\n else{\n toastr.error(element+\"Uninstall.exe does not exists\");\n }\n\n });\n })\n\n }", "function getVersionInfo() {\r\n return [\r\n ['node-sass', package.version, '(Wrapper)', '[JavaScript]'].join('\\t'),\r\n ['libsass ', package.libsass, '(Sass Compiler)', '[C/C++]'].join('\\t'),\r\n ].join(eol);\r\n}", "function getInstalledVersionsTableRowData(ivLists = []) {\n var list = '';\n var installedVersionsLists = [];\n if(typeof(ivLists) !== 'undefined' && !$.isArray(ivLists)){\n installedVersionsLists.push(ivLists);\n }else{\n installedVersionsLists = ivLists;\n }\n if(typeof(installedVersionsLists) !== 'undefined' && installedVersionsLists !== '') {\n $.each(installedVersionsLists, function(i, item) {\n list += `\n <tr>\n <td>${item.Version}</td>\n <td>${item.Descr}</td>\n <td>${(moment(item.ReleaseDate).isValid()) ? moment(item.ReleaseDate).format('MM/DD/YYYY') : '00/00/0000'}</td>\n <td>${(moment(item.InstalledDate).isValid()) ? moment(item.InstalledDate).format('MM/DD/YYYY') : '00/00/0000'}</td>\n </tr>\n `;\n });\n }\n loadInstalledVersionsTable(list);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
next letter in the alphabet. You will write a function nextLetter to do this. The function will take a single parameter str (string). EXAMPLES: "Hello" > "Ifmmp" "What is your name?" > "Xibu jt zpvs obnf?" "zoo" > "app" "zzZAaa" > "aaABbb" Note: spaces and special characters should remain the same. Capital letters should transfer in the same way but remain capitilized.
function nextLetter(str) { // go for it }
[ "function fearNotLetter(str) {\n for (var i = 0; i < str.length - 1; i++) {\n if (str.charCodeAt(i + 1) == str.charCodeAt(i) + 1) {\n console.log(\"next char is next in alphabet\");\n }\n else {\n return String.fromCharCode(str.charCodeAt(i) + 1);\n }\n }\n //return undefined\n}", "function queueNames(name) {\n\n // Make sure name is in lower case \n name = name.toLowerCase();\n\n //Take first letter of name\n firstLetter = name.charCodeAt(0);\n\n if (firstLetter > 108 && firstLetter < 123) {\n\n // Displays 'Back to the line!' alert pop-up, if the first letter of the name is between the letter L and is letter Z.\n alert('Back to the line!');\n\n } else if (firstLetter > 122 || firstLetter < 97) {\n\n // Display 'Invalid Name!' alert pop-up, if the first letter is not a chracter from the alphabet.\n alert('Invalid Name!');\n\n\n } else {\n //Display 'Next' alert pop-up, if the first letters is before letter M. \n alert('Next!')\n }\n}", "function isLetter(str) {\n if (str.length == 1 && str.match(/[a-zA-Z]/i)) {\n document.getElementById(\"messages\").innerHTML = \"\";\n currentLetter = str.toLowerCase();\n return true;\n } else if (str !== 'Shift' && str !== 'CapsLock' && str !== 'F5') {\n document.getElementById(\"messages\").innerHTML = \"Please input letters only!\";\n return false;\n }\n}", "function missingLetter(str) {\n\tfor (var i = 0; i < str.length - 1; i++) {\n\t\tif (str.charCodeAt(i + 1) - str.charCodeAt(i) != 1) {\n\t\t\t\treturn String.fromCharCode(str.charCodeAt(i) + 1);\n\t\t}\n\t}\n\treturn 'No Missing Letter';\n}", "function generateRandomLetter() {\n return String.fromCharCode(Math.floor(Math.random() * 26) + 97);\n }", "function getValidLetterGuess() {\n //this helper function is used to determine if letter guess is valid\n function guessIsValid(letter) {\n //use regex to determine if letter is in the alphabet and ignore case sensitivty\n const validEntries = /[a-z]/i;\n //if the letter is in the alphabet and the length of the letter is 1\n if (validEntries.test(letter) && letter.length === 1) {\n return letter;\n } else {\n return false;\n }\n }\n //declare a variable named letter and assign it a falsy value to start off\n let letter = \"\";\n //while the letter is falsy\n while (!letter) {\n //program will stop to get user input\n let input = readline.question(\"\\nGuess a letter: \");\n\n if (guessIsValid(input)) {\n letter = input;\n } else {\n console.log(\"Please enter a valid letter\");\n }\n }\n return letter.toLowerCase();\n}", "function addLetterToCurrentWord(editableDiv, letter) {\n\tvar oldStr = editableDiv.textContent;\n\tvar curPos = getCaretPositionInDiv(editableDiv);\n\tvar firstPos = getStartingPositionOfCurrentWord(editableDiv);\n\tvar lastPos = getLastPositionOfCurrentWord(editableDiv);\n\tvar newWord = oldStr.substr(firstPos, curPos-firstPos)+letter+oldStr.substr(curPos, lastPos-curPos+1);\n\treturn newWord;\n}", "function letterAtPosition(n) {\n\treturn !Number.isInteger(n) || n < 1 ? 'invalid' : String.fromCharCode(97 + n - 1);\n}", "function encodeLetter(letter) {\n return alphabet.indexOf(letter.toLowerCase());\n}", "function findFirstLetter(word){\n\treturn word[0].toUpperCase();\n}", "function getCodeFromLetter(str){\n return str.charCodeAt(0)-96;\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}", "shifter(str) {\n\t\tlet newString = '';\n\t\tfor (const char of str) {\n\t\t\tnewString += /[a-z]/.test(char) ? String.fromCharCode(((char.charCodeAt(0) - 18) % 26) + 97) : char;\n\t\t}\n\t\treturn newString;\n\t}", "function convertLetter(letter){\n if(letter==='r')return 'ROCK ';\n if(letter==='p')return 'PAPER';\n return 'SCISSOR';\n}", "function isLetter(c) {\n return c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90 ; \n}", "function getLetterFromCode(num){\n return String.fromCharCode(num+96);\n}", "function addNextWord() {\n let words = controller.words.split(\", \"),\n nextWord = words[controller.currentWordIndex]\n\n // Create Points\n pnts = createPoints(nextWord)\n\n // Add Word\n drawingLetters = new Letter(nextWord, pnts)\n\n if (words.length - 1 > controller.currentWordIndex) {\n controller.currentWordIndex++\n } else {\n controller.currentWordIndex = 0\n }\n}", "function guessIsValid(letter) {\n //use regex to determine if letter is in the alphabet and ignore case sensitivty\n const validEntries = /[a-z]/i;\n //if the letter is in the alphabet and the length of the letter is 1\n if (validEntries.test(letter) && letter.length === 1) {\n return letter;\n } else {\n return false;\n }\n }", "function anagramHelper(str, current, anagrams) {\n if (!str.length && current.length) {\n anagrams.push(current);\n } else {\n for (let i = 0; i < str.length; i++) {\n // base letter, slice and concat\n const newStr = str.slice(0, i).concat(str.slice(i+1));\n const newAna = current.concat(str[i]);\n anagramHelper(newStr, newAna, anagrams);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the current read stream to the next one if the last one is done and has been cleared, or no source has yet been chosen.
_next() { if (!this._current) { if (!this._streams.length) { this._enabled = false; return this.end(); } this._current = new stream.Readable().wrap(this._streams.shift()); this._current.on('end', () => { this._current = null; this._next(); }); this._current.pipe(this, { end: false }); } }
[ "_read() {\n if (this.index <= this.array.length) {\n //getting a chunk of data\n const chunk = {\n data: this.array[this.index],\n index: this.index\n };\n //we want to push chunks of data into the stream\n this.push(chunk);\n this.index += 1;\n } else {\n //pushing null wil signal to stream its done\n this.push(null);\n }\n }", "function loadNextItem() {\n\tif (queue.length === 0) {\n\t\t// if there's something playing stop it.\n\t\tloadCandidate(null);\n\t\t\n\t\tif (refillingQueue) {\n\t\t\t// loadNextItem will be called when the queue is refilled\n\t\t\treturn;\n\t\t}\n\t\t\n\t\trefillingQueue = true;\n\t\trefillQueue(function() {\n\t\t\trefillingQueue = false;\n\t\t\tif (queue.length === 0) {\n\t\t\t\tconsole.log(\"Couldn't find anything to add to the queue. Checking again shortly.\");\n\t\t\t\tsetTimeout(function() {\n\t\t\t\t\tif (liveCandidate === null) {\n\t\t\t\t\t\tloadNextItem();\n\t\t\t\t\t}\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t\telse if (liveCandidate === null) {\n\t\t\t\t// load the next item if there's still nothing playing\n\t\t\t\t// a live stream could have been added to the front.\n\t\t\t\tloadNextItem();\n\t\t\t}\n\t\t});\n\t}\n\telse {\n\t\tloadCandidate(queue.shift());\n\t}\n}", "function PlayNextStreamInQueue() { \r\n \r\n ytAudioQueue.splice(0, 1); \r\n \r\n // if there are streams remaining in the queue then try to play \r\n if (ytAudioQueue.length != 0) { \r\n console.log(\"Now Playing \" + ytAudioQueue[0].videoName); \r\n PlayStream(ytAudioQueue[0].streamUrl); \r\n } \r\n }", "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 }", "next() {\n const idx = this.getIdx();\n if (idx + 1 < this.state.records.length) {\n this.playRecord(this.getKey(idx + 1));\n }\n }", "playNext() {\n\n // if it is the last chord of the sequence start again from the first one, otherwise go to the next one\n if (this.playing >= this.sequence.length - 1) {\n this.playing = 0; // set the number of the next track (here: the first one)\n }\n else {\n this.playing++; // set the number of the next track\n }\n\n this.playCurrent(); // play the track selected above\n\n }", "lock() {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n this.isLocked = true;\n if (this.previous) {\n this.previous.lock();\n }\n }", "fillBuffer_() {\n if (this.sourceUpdater_.updating()) {\n return;\n }\n\n if (!this.syncPoint_) {\n this.syncPoint_ = this.syncController_.getSyncPoint(this.playlist_,\n this.mediaSource_.duration,\n this.currentTimeline_);\n }\n\n // see if we need to begin loading immediately\n let segmentInfo = this.checkBuffer_(this.sourceUpdater_.buffered(),\n this.playlist_,\n this.mediaIndex,\n this.hasPlayed_(),\n this.currentTime_(),\n this.syncPoint_);\n\n if (!segmentInfo) {\n return;\n }\n\n let isEndOfStream = detectEndOfStream(this.playlist_,\n this.mediaSource_,\n segmentInfo.mediaIndex);\n\n if (isEndOfStream) {\n this.mediaSource_.endOfStream();\n return;\n }\n\n if (segmentInfo.mediaIndex === this.playlist_.segments.length - 1 &&\n this.mediaSource_.readyState === 'ended' &&\n !this.seeking_()) {\n return;\n }\n\n // We will need to change timestampOffset of the sourceBuffer if either of\n // the following conditions are true:\n // - The segment.timeline !== this.currentTimeline\n // (we are crossing a discontinuity somehow)\n // - The \"timestampOffset\" for the start of this segment is less than\n // the currently set timestampOffset\n if (segmentInfo.timeline !== this.currentTimeline_ ||\n ((segmentInfo.startOfSegment !== null) &&\n segmentInfo.startOfSegment < this.sourceUpdater_.timestampOffset())) {\n this.syncController_.reset();\n segmentInfo.timestampOffset = segmentInfo.startOfSegment;\n }\n\n this.currentTimeline_ = segmentInfo.timeline;\n this.loadSegment_(segmentInfo);\n }", "fillBuffer() {\n let dataWanted = this.bufferSize - this.dataAvailable;\n\n if (!this._pendingBufferRead && dataWanted > 0) {\n this._pendingBufferRead = this._read(dataWanted);\n\n this._pendingBufferRead.then((result) => {\n this._pendingBufferRead = null;\n\n if (result) {\n this.onInput(result.buffer);\n\n this.fillBuffer();\n }\n });\n }\n }", "function qNext() {\n var o = deferreds.shift(); //remove first element\n\n if( o ){\n o.deferred\n .fail(function( xml, textStatus ){\n qNext();\n });\n o.deferred\n .done(function( xml, textStatus ){\n recombined.push({\n xml: xml,\n category: o.category,\n index: o.index\n });\n self.setState({ data: recombined });\n qNext();\n });\n }\n }", "async consumeNext() {\n const file = this.files[this.handledFiles];\n await file.consume(async (file, isSuccess) => {\n this.handledFiles++;\n console.log(`Consumed ${this.handledFiles}/${this.totalFiles} files`);\n await this.updateProgressStatus(file, isSuccess);\n\n if (this.progressStatus === 'progressing' && this.handledFiles < this.totalFiles) {\n await this.consumeNext();\n } else {\n if (this.progressStatus === 'failed') {\n await this.persistStatus(TASK_FAILED_STATUS);\n console.log(\n `Failed to finish sync task. Skipping the remaining files. Most recent delta file successfully consumed is created at ${this.latestDelta.toISOString()}.`);\n } else {\n await this.persistStatus(TASK_SUCCESS_STATUS);\n console.log(\n `Finished sync task successfully. Ingested ${this.totalFiles} files. Most recent delta file consumed is created at ${this.latestDelta.toISOString()}.`);\n }\n }\n });\n }", "selectNext() {\n\n // select the next, or if it is the last entry select the first again\n if (this.selected >= this.sequence.length - 1) {\n this.selected = 0;\n }\n else {\n this.selected++;\n }\n\n // highlight the selected entry\n this.highlightSelected();\n\n }", "next () {\n // Wrap cursor to the beginning of the next non-empty buffer if at the\n // end of the current buffer\n while (this.buffer_i < this.buffers.length &&\n this.offset >= this.buffers[this.buffer_i].length) {\n this.offset = 0;\n this.buffer_i ++;\n }\n\n if (this.buffer_i < this.buffers.length) {\n let byte = this.buffers[this.buffer_i][this.offset];\n\n // Advance cursor\n this.offset++;\n return byte;\n }\n else {\n throw this.END_OF_DATA;\n }\n }", "function next () {\n var msg = nextMessage()\n if (!msg) {\n return stopQueue()\n }\n\n _self.currentMessage = msg.text\n _self.color = msg.color\n\n if (!_self.show) {\n _self.show = true\n }\n }", "function AudioStream(initialBuffer) {\n let sourceBuffer;\n let index = 0; // keeps track of the incoming buffer stream number\n let isReady = false;\n const bufferBacklog = []; // adding mediaBuffer takes time, sometimes we receive a new stream the add is complete\n const mediaSource = new MediaSource();\n\n // this event marks the start, that it is ready to take in audio buffers\n mediaSource.addEventListener(\"sourceopen\", function () {\n sourceBuffer = mediaSource.addSourceBuffer('audio/webm;codecs=\"opus\"');\n // For video:\n /*\n sourceBuffer = mediaSource.addSourceBuffer( 'video/webm; codecs=\"opus, vp9\"');\n */\n console.log(\"audio stream is ready!\");\n sourceBuffer.appendBuffer(initialBuffer);\n myAudio.play();\n\n // Thes event runs whenever there is an add\n sourceBuffer.addEventListener(\"updateend\", () => {\n index += 1;\n isReady = true;\n console.log(\"update ended\");\n const nextBuffer = bufferBacklog.shift();\n if (!nextBuffer) {\n return;\n }\n isReady = false;\n sourceBuffer.appendBuffer(nextBuffer);\n });\n });\n\n const mediaSourceUrl = URL.createObjectURL(mediaSource);\n // For Video:\n /*\n const myAudio = document.createElement(\"video\");\n myAudio.src = mediaSourceUrl;\n container.append(myAudio);\n */\n const myAudio = new Audio(mediaSourceUrl);\n\n // Helper functions\n this.addBuffer = (buffer) => {\n if (!isReady) {\n bufferBacklog.push(buffer);\n return;\n }\n isReady = false;\n sourceBuffer.appendBuffer(buffer);\n };\n\n this.shouldReset = (newIndex) => {\n /* If the incoming newIndex is smaller than our current index\n * then we know that the user is transmitting a new recording stream\n */\n return newIndex < index;\n };\n\n this.destroy = () => {\n mediaSource.endOfStream();\n myAudio.pause();\n console.log(\"destroying audio\");\n };\n this.getIndex = () => index;\n}", "checkPendingReads() {\n this.fillBuffer();\n\n let reads = this.pendingReads;\n while (reads.length && this.dataAvailable &&\n reads[0].length <= this.dataAvailable) {\n let pending = this.pendingReads.shift();\n\n let length = pending.length || this.dataAvailable;\n\n let result;\n let byteLength = this.buffers[0].byteLength;\n if (byteLength == length) {\n result = this.buffers.shift();\n }\n else if (byteLength > length) {\n let buffer = this.buffers[0];\n\n this.buffers[0] = buffer.slice(length);\n result = ArrayBuffer.transfer(buffer, length);\n }\n else {\n result = ArrayBuffer.transfer(this.buffers.shift(), length);\n let u8result = new Uint8Array(result);\n\n while (byteLength < length) {\n let buffer = this.buffers[0];\n let u8buffer = new Uint8Array(buffer);\n\n let remaining = length - byteLength;\n\n if (buffer.byteLength <= remaining) {\n this.buffers.shift();\n\n u8result.set(u8buffer, byteLength);\n }\n else {\n this.buffers[0] = buffer.slice(remaining);\n\n u8result.set(u8buffer.subarray(0, remaining), byteLength);\n }\n\n byteLength += Math.min(buffer.byteLength, remaining);\n }\n }\n\n this.dataAvailable -= result.byteLength;\n pending.resolve(result);\n }\n }", "function onSourceOpen(e) {\n const mediaSrc = e.target;\n\n if (mediaSrc.sourceBuffers.length > 0) {\n return;\n }\n\n const sourceBuffer = mediaSrc.addSourceBuffer('video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"');\n const initSegment = new Uint8Array(queue.shift());\n\n const firstAppendHandler = (event) => {\n const srcbuf = event.target;\n srcbuf.removeEventListener('updateend', firstAppendHandler);\n\n appendNextMediaSegment(mediaSrc);\n };\n\n sourceBuffer.addEventListener('updateend', firstAppendHandler);\n sourceBuffer.addEventListener('update', () => { appendNextMediaSegment(mediaSrc); });\n sourceBuffer.appendBuffer(initSegment);\n}", "function pullReadStream(options, makeData) {\n var stream = pull.defer();\n stream.setIterator = function (iterator) {\n stream.resolve(function (end, cb) {\n if (!end) {\n iterator.next(function (err, key, value) {\n if (err) {\n return cb(err);\n }\n if (key === undefined || value === undefined) {\n return cb(true);\n }\n cb(null, makeData(key, value));\n });\n } else {\n iterator.end(cb);\n }\n });\n };\n\n return stream;\n}", "_handleNextDataEvent() {\n this._processingData = false;\n let next = this._dataEventsQueue.shift();\n if (next) {\n this._onData(next);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pass videoservie.ts as a object, when you call toolbar, it will call videoservice too
function ToolbarComponent(videoService) { this.videoService = videoService; // now you can use videoService function on template }
[ "function configurarBarrasVideo(){\n\n ///////////////////////PROGRESO//////////////////////\n //Listener para cuando el usuario arrastre la barra de progreso\n barraProgreso.addEventListener(\"change\", function() {\n //Calcular tiempo exacto\n var tiempo = video.duration * (barraProgreso.value / 100);\n \n //Actualizar con tiempo\n video.currentTime = tiempo;\n });\n \n //Listener para que la barra de progreso avance con el video\n video.addEventListener(\"timeupdate\", function() {\n //Calcular progreso del video\n var tiempo = (100 / video.duration) * video.currentTime;\n \n //Actualizar barra con el tiempo del video\n barraProgreso.value = tiempo;\n });\n\n //Pausar el video mientras el usuario mueve la barra de progreso\n barraProgreso.addEventListener(\"mousedown\", function() {\n video.pause();\n\n console.log(video.currentTime);\n actualizaIconoPlay();\n });\n\n //Reanudar el video cuando el usuario deje de arrastrar la barra de progreso\n barraProgreso.addEventListener(\"mouseup\", function() {\n video.play();\n //Calcular tiempo exacto\n var tiempo = video.duration * (barraProgreso.value / 100);\n\n //Actualizar con tiempo\n video.currentTime = tiempo;\n actualizaIconoPlay();\n });\n\n ///////////////////////VOLUMEN//////////////////////\n // Listener para cambiar volumen cuando cambie la barra de volumen\n barraVolumen.addEventListener(\"change\", function() {\n video.volume = barraVolumen.value;\n actualizarIconoSonido();\n });\n}", "displayMovieFromLS() {\n const movies = this.getMovieFromLS()\n movies.forEach(movie => {\n this.addMovieToUI(movie)\n })\n }", "function videoClick(clickedVideo){\n console.log('video es'+clickedVideo);\n sessionStorage.setItem('videoid', clickedVideo);\n}", "function openVideo() {\r\n\t\tTitanium.Platform.openURL(movie.trailerUrl);\r\n\t}", "editTracksInfo () {\n //\n }", "function Video (dataVideo) { \n this.$el = \"\"; // this will hold the video html element\n this.data = dataVideo;\n this.init = function (videoHtmlEL){ //when creating a new Video object we need to define the html element to connect it to\n\n // create the video in html\n var output = '';\n switch(true){\n case (this.data.type == 'html5') :\n output += '<video id=\"catbearsVideo\" width=\"100%\" height=\"100%\" controls=\"\">'\n output += '<source src=\"../video/'\n output += this.data.fileName\n output += '\" type=\"video/mp4\"/>'\n output += 'Your browser does not support HTML5 video.'\n output += '</video>'\n break;\n case (this.data.type == 'youtube') : \n // embed video\n break; \n\n\n } \n // append the video \n $(videoHtmlEL).append(output);\n this.$el = document.getElementById(\"catbearsVideo\");\n }; \n this.play = function (){\n this.$el.play()\n // $el play\n }\n this.pause = function (){\n this.$el.pause()\n }\n this.togglePlayPause = function () { \n if(this.$el.paused){\n this.$el.play();\n }else{ \n this.$el.pause();\n }; \n };\n this.seekTo = function (second){\n this.$el.currentTime = second;\n }\n}", "getVideoType() {\n return this.videoType;\n }", "constructor(movieService, router) {\n this.movieService = movieService;\n this.router = router;\n }", "function fnVideoImage(ProductId,videoProduct,ImagemProdPri,NomeProd){\r\n var replaceNomeProd = NomeProd.replace(/-/g,' ');\r\n if (videoProduct==\"\"){\r\n document.getElementById(\"id-video-image\"+ProductId).innerHTML=\"<div class='ImgCapaListProd DivListproductStyleImagemZoom'><img src=\"+ ImagemProdPri +\" alt=\\\"\"+ replaceNomeProd +\"\\\" onerror='MostraImgOnError(this,0)'\"+ sLazy +\"></div>\";\r\n }else{\r\n document.getElementById(\"id-video-image\"+ProductId).innerHTML=\"<video id=prodVideo\"+ ProductId +\" class='videoProd' preload=auto loop src='https://my.mixtape.moe/\"+ videoProduct +\".mp4'></video>\";\r\n function execVideoEvents(){\r\n var oVideo=document.getElementById(\"prodVideo\"+ProductId);\r\n if(FCLib$.isOnScreen(oVideo))oVideo.play();\r\n }\r\n execVideoEvents();\r\n FCLib$.AddEvent(document,\"scroll\",execVideoEvents);\r\n }\r\n }", "function switchVideo(video1, video2 , h , w){\n\n if(!video1)\n video1=document.getElementById(\"localVideo\");\n\n if(video2==undefined){\n if(document.getElementById(\"remotes\").getElementsByTagName(\"video\")[0]!=undefined)\n video2=document.getElementById(\"remotes\").getElementsByTagName(\"video\")[0];\n else\n video2=null;\n }\n\n if(webrtc.webrtc.getPeers().length==0){\n hideDiv(\"localVideo\");\n $(\"#media_settings_btn\").removeClass(\"hidedisplay\");\n \n if (callflag==0){\n showDiv(\"notificationsDiv\");\n }\n else if(callflag==1){\n showDiv(\"notificationsDiv\"); \n $('#notifications').text('Your partner has left');\n }\n }else if(webrtc.webrtc.getPeers().length>0){\n console.log(\"remote members to canvas center\");\n // stop the waiting music \n // stopWaitingMusic();\n if(video1 && video2 && video1!=video2){ \n showDiv(\"localVideo\");\n }\n $('#notifications').text('');\n hideDiv(\"notificationsDiv\");\n $(\"#media_settings_btn\").addClass(\"hidedisplay\");\n hidetooltip(tooltiproomnotifications);\n } \n \n drawStuff(video1,video2,h,w);\n}", "constructor() { \n \n PatchedVideoSerializerV2.initialize(this);\n }", "function video_click(e) {\n\t//console.log(e);\n\t//console.log(this);\n\tif (this.paused == true) {\n\t\tthis.play();\n\t} else {\n\t\tthis.pause();\n\t}\n}", "function cargarVideo(url,imagen){\r\n var v = document.createElement(\"video\"); \r\n //if ( (!v.play) && (!Liferay.Browser.isSafari())) { // If no, use Flash.\r\n if(!Modernizr.video){\r\n var params = {\r\n allowfullscreen: \"true\",\r\n allowscriptaccess: \"always\",\r\n wmode:\"transparent\"\r\n };\r\n var flashvars = {\r\n config: \"{'playlist':[ {'url': '\"+url+\"','autoPlay':false,'autoBuffering':true}]}&\" \r\n };\r\n //swfobject.embedSWF(\"http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n swfobject.embedSWF(\"flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n }\r\n}", "function toggleVolBtn() {\n\tif (PLAYER.type==\"yt\" || PLAYER.type==\"dm\") {\n\t\t$_voldownbtn.show();\n\t\t$_volupbtn.show();\n\t} else {\n\t\t$_voldownbtn.hide();\n\t\t$_volupbtn.hide();\n\t}\n}", "insertVideos() {\n for(let i = 0; i < this.options.src.length; i++) {\n let videoTypeArr = this.options.src[i].split('.');\n let videoType = videoTypeArr[videoTypeArr.length - 1];\n\n this.addSourceToVideo(this.options.src[i], `video/${videoType}`);\n }\n }", "function loadVideoStream (url) {\n\tvar outputVideo = '';\n\t$('#stream').click(function(e){\n\t\te.preventDefault();\n\t\t$.getJSON( url + '/main_page/build_video_stream', function(data){\n\t\t\tif (data.result != false) {\n\t\t\t\t$.each(data, function(){\n\t\t\t\t\t$.each(this, function(key, value){\n\t\t\t\t\t\t// console.log(value);\n\t\t\t\t\t\toutputVideo += generateVideoTags(value);\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\t// var element = document.getElementById('list_video');\n\t\t\t\t// element.innerHTML = outputVideo;\n\t\t\t\t$(\"#list_video\").html(outputVideo);\n\t\t\t\t// $('#ul').show().html\n\t\t\t};\n\t\t\t// console.log(outputVideo);\n\t\t\t// console.log(data);\n\t\t})\n\t})\n}", "function startVideo() {\n mini_peer.setLocalStreamToElement({ video: true, audio: true }, localVideo);\n}", "function setupControlBar() {\n videojs_player.controlBar.addClass('vjs-live');\n window._ThePlayer = videojs_player;\n\n var playToggle = videojs_player.controlBar.children_[0].el_;\n playToggle.addEventListener(\"click\", function () {\n setTimeout(function () {\n if (iov_player.playing === true) {\n iov_player.stop();\n iov_player.playing = false;\n videojs_player.controlBar.playToggle.handlePause();\n } else {\n spinner.show();\n iov_player.resume(function () {\n setTimeout(function () {\n spinner.hide();\n }, 0);\n }, function () {\n // reset the timeout monitor \n videojs_player.trigger('timeupdate');\n });\n iov_player.playing = true;\n videojs_player.controlBar.playToggle.handlePlay();\n }\n }, 0);\n });\n }", "_setFocusSettings(settings) {\n \n settings.mediaplayer.consumer = this; \n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a middleware for transforming XHR loaded Blobs into more useful objects
function blobMiddlewareFactory() { return function blobMiddleware(resource, next) { if (!resource.data) { next(); return; } // if this was an XHR load of a blob if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { // if there is no blob support we probably got a binary string back if (!window.Blob || typeof resource.data === 'string') { var type = resource.xhr.getResponseHeader('content-type'); // this is an image, convert the binary string into a data url if (type && type.indexOf('image') === 0) { resource.data = new Image(); resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); resource.type = _Resource2.default.TYPE.IMAGE; // wait until the image loads and then callback resource.data.onload = function () { resource.data.onload = null; next(); }; // next will be called on load return; } } // if content type says this is an image, then we should transform the blob into an Image object else if (resource.data.type.indexOf('image') === 0) { var _ret = function () { var src = Url.createObjectURL(resource.data); resource.blob = resource.data; resource.data = new Image(); resource.data.src = src; resource.type = _Resource2.default.TYPE.IMAGE; // cleanup the no longer used blob after the image loads // TODO: Is this correct? Will the image be invalid after revoking? resource.data.onload = function () { Url.revokeObjectURL(src); resource.data.onload = null; next(); }; // next will be called on load. return { v: void 0 }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } } next(); }; }
[ "function getFileBlob(url, cb) {\n var xhr = new XMLHttpRequest() //creo una nueva instancia de XMLHttpRequest\n xhr.open('GET', url) //inicializo una peticion asincronica del url al server\n xhr.responseType = \"blob\" // declaro que el valor del tipo de respuesta es blob (para luego usarlo mas adelante)\n xhr.addEventListener('load', () => { //Le agrego un event listener que cuando cargue se va a ejecutar \n cb(xhr.response) //mi cb (callback) con la respuesta del servidor\n })\n xhr.send() //Envia la peticion nuevamente. \n }", "static blobToImage(data)\n\t{\n\t\tvar URLObj = window['URL'] || window['webkitURL'];\n\t\tvar src = URLObj.createObjectURL(data);\n\t\tvar img = new Image();\n\t\timg.src = src;\n\t\treturn img;\n\t}", "function request_filter(reqFromApp, respToApp, next) {\n\n var ctype = reqFromApp.headers['content-type']; \n if (!ctype) \n return next();\n\n var body = reqFromApp.body;\n var obj = null; // JSON body\n\n log.info('Request filter: %s %s enc [%s] body length %d body:\\n%s',\n reqFromApp.method,\n reqFromApp.url,\n ctype,\n body? body.length : 0,\n body? body.toString():'');\n\n if (ctype.indexOf('application/json') >= 0) {\n obj = JSON.parse(body.toString());\n\n log.info('Request filter: %s with json body of length %d on URL %s : \\n%s',\n reqFromApp.method,\n body? body.length : 0,\n reqFromApp.url,\n body? JSON.stringify(obj, null, 2) : ''\n );\n }\n next();\n}", "_handleFile(req, files, callback) {\r\n /**\r\n * Create a writable stream using concat-stream that will\r\n * concatenate all the buffers written to it and pass the\r\n * complete buffer to a callback function\r\n */\r\n const fileManipulate = concat((imageData) => {\r\n /**\r\n * read the image buffer with Jimp\r\n * it return a promise\r\n */\r\n Jimp.read(imageData)\r\n .then((image) => {\r\n // precess the Jimp image buffer\r\n this.processImage(image, callback);\r\n })\r\n .catch(callback);\r\n });\r\n\r\n // write the uploaded file buffer to the fileManipulate stream\r\n files.stream.pipe(fileManipulate);\r\n }", "function processData(record, { signedUrl = false } = { }) {\n const rv = {\n json: { }\n }\n for (const [k, v] of Object.entries(record)) {\n if (v instanceof FileList) {\n const fileNameArray = []\n for (const file of v) {\n if (signedUrl) {\n if (!rv.files) rv.files = []\n rv.files.push(file)\n } else {\n if (!rv.form) rv.form = new FormData()\n rv.form.append('file-data', file) // add\n }\n fileNameArray.push(file.name)\n }\n rv.json[k] = fileNameArray.join(',') // array\n } else {\n rv.json[k] = v\n }\n }\n if (rv.form) rv.form.append('json-data', JSON.stringify(rv.json)) // set the JSON\n return rv\n}", "_bufferParse(response)\n {\n return new Promise((resolve, reject) => {\n response.on('error', reject);\n\n let dataBuffer = [];\n\n response.on('data', (data) => {\n dataBuffer.push(data);\n });\n\n response.on('end', () => resolve(dataBuffer));\n });\n }", "function isXHR2WithBlobSupported() {\n if (!window.hasOwnProperty('ProgressEvent') || !window.hasOwnProperty('FormData')) {\n return false;\n }\n let xhr = new XMLHttpRequest();\n if (typeof xhr.responseType === 'string') {\n try {\n xhr.responseType = 'blob';\n return xhr.responseType === 'blob';\n }\n catch (e) {\n return false;\n }\n }\n else {\n return false;\n }\n}", "verify(req, res, buf) {\n if (req.originalUrl.startsWith('/.../...')) {\n req.rawBody = buf.toString()\n }\n }", "function transform (file, transformer, callback) {\n var handler;\n\n if (file.isBuffer()) {\n handler = bufferHandler;\n }\n\n if (file.isStream()) {\n handler = streamHandler;\n }\n\n // Read file buffer/stream contents\n handler.read(file.contents, function (err, contents) {\n // Pass `contents` string to transformer function\n transformer(contents, function (err, transformed) {\n if (err) {\n callback(err);\n } else {\n // Convert back `transformed` string to buffer/stream\n handler.convert(transformed, function (err, converted) {\n file.contents = converted;\n callback(null, file);\n });\n }\n });\n });\n}", "function getFileObject(filePathOrUrl, cb) {\n getFileBlob(filePathOrUrl, function(blob) { //fn2 //llama a la funcion getFileBlob con el url introducido y una funcion que: \n cb(blobToFile(blob, '' + $$(\"#nuevocodigo\").val() + '.jpg')); //ejecuta nuestro cb (callback) sobre el blob con nombre y fecha cambiada (el nombre sera 'test.jpg')\n });\n }", "function MyFile(nombre){\n this.name = nombre; //nombre del archivo con su extension\n this.type; //tipo de archivo (ej application, image etc) \n this.codeType; //tipo codificacion del contenido (ej base64, base32, etc)\n this.data; //contenido del archivo\n \n //trabajamos sobre el dataURL --> \"data:application/pdf;base64,datossss\" \"data:image/png;base64,datosss\"\n this.parseDataURL = function(dataURL){\n var dataURLSeparado = dataURL.split(\",\");\n \n //obtenemos los datos\n this.data = dataURLSeparado[1];\n //la primera parte es la cabecera del archivo\n var cabecera = dataURLSeparado[0].split(\";\"); \n \n //obtenemos el typo de codificacion\n this.codeType = cabecera[1];\n //obtenemos el tipo de archivo\n this.type = cabecera[0].split(\":\")[1];\n };\n}", "function createResponseObj(data, mediaHash) {\n if (!data) {\n out = Object.create(null);\n return out;\n }\n // We need to inspect the retrieved objects and indicate which of them\n // include blobs (media) data. That will make client life easier\n var out = {\n objectData: data,\n mediaInfo: Object.create(null)\n };\n\n var mediaInfo = out.mediaInfo;\n Object.keys(data).forEach(function(aKey) {\n var object = data[aKey];\n for(var prop in object) {\n var value = object[prop];\n if (value.indexOf('blob:') === 0) {\n var blobId = Utils.getBlobId(object[prop]);\n if (!mediaHash || mediaHash && mediaHash[blobId]) {\n mediaInfo[blobId] = {\n objId: aKey,\n objProp: prop\n }\n }\n // The blob property is not sent in the object\n delete object[prop];\n }\n }\n });\n\n return out;\n}", "function createSplitter() {\n let transform = new stream_1.Transform();\n let buffer = Buffer.alloc(0);\n transform._transform = (chunk, _encoding, callback) => {\n buffer = Buffer.concat([buffer, chunk]);\n let offset = 0;\n while (offset + 4 < buffer.length) {\n const length = buffer.readInt32LE(offset);\n if (offset + 4 + length > buffer.length)\n break;\n transform.push(buffer.slice(offset, offset + 4 + length));\n offset += 4 + length;\n }\n buffer = buffer.slice(offset);\n callback();\n };\n return transform;\n}", "parsedProbe() {\n if (!this.probe) {\n return {};\n }\n\n const { id, meta, tags } = this.probe;\n const { type } = tags;\n let source;\n\n if (type === \"image\") {\n source = `input/${id}.${meta[\"File:FileTypeExtension\"]}`;\n } else if (type === \"video\") {\n source = `input/transcoded/${id}.mp4`;\n }\n\n return {\n isImage: type === \"image\",\n isVideo: type === \"video\",\n type,\n source,\n thumbnail: `input/thumbnails/${id}.jpg`,\n status: \"parsed\",\n name: meta[\"File:FileName\"],\n id,\n hasFused: this.probe.has_fused\n };\n }", "function interceptor(buffer) {\n\n // Do nothing if the response isn't html.\n if(buffer.headers['content-type'] !== 'text/html') return\n\n // Parse the page.\n $ = cheerio.load(buffer.getData())\n var root = $('body').length ? $('body') : $.root\n\n root.append('<script src=\"/socket.io/socket.io.js\"></script>\\n')\n root.append('<script>\\n' + listenAndReloadScript + '\\n</script>\\n')\n\n // overwrite data in the request\n buffer.setData($.html())\n}", "function Blob(repository, obj) {\n this.repository = repository;\n _immutable(this, obj).set(\"id\").set(\"data\");\n }", "function objToData(o) {\n console.log(o) // XXX TEMPORARY\n\n var fd = new FormData()\n\n for (var k in o) fd.append(k, encodeURIComponent(o[k]))\n\n return fd\n}", "loadPreviews () {\n this.files.map(file => {\n if (!file.previewData && window && window.FileReader && /^image\\//.test(file.file.type)) {\n const reader = new FileReader()\n reader.onload = e => Object.assign(file, { previewData: e.target.result })\n reader.readAsDataURL(file.file)\n }\n })\n }", "function cleanXHRData(item) {\n\tdelete item.request.headers;\n\tdelete item.request.cookies;\n\tdelete item.request.httpVersion;\n\tdelete item.request.queryString;\n\tdelete item.request.headersSize;\n\tdelete item.request.bodySize;\n\tdelete item.cache;\n\tdelete item.timings;\n\tdelete item.serverIPAddress;\n\tdelete item['_initiator'];\n\tdelete item['_priority'];\n\tdelete item.connection;\n\tdelete item.pageref;\n\tdelete item.startedDateTime;\n\tdelete item.time;\n\tdelete item.response.cookies;\n\tdelete item.response['_transferSize'];\n\tdelete item.response.redirectURL;\n\tdelete item.response.headersSize;\n\tdelete item.response.bodySize;\n\tdelete item.response.httpVersion;\n\tdelete item.response.statusText;\n\tdelete item.response.headers;\n\tdelete item.response.content.size;\n\tdelete item.response.content.compression;\n\tdelete item.response.content['_resourceType'];\n}", "function getRequests() {\n try {\n if (window.httpRequests) {\n return window.httpRequests.map(function (record) {\n if (record.request.responseType !== 'blob') {\n return record;\n }\n return {\n timing: record.timing,\n request: {\n responseURL: record.request.responseURL,\n status: record.request.status,\n statusText: record.request.statusText,\n responseText: '{ \"blob\": \"redacted\" }'\n }\n };\n });\n } else {\n return [];\n }\n } catch (e) {\n console.error('Protractor Browser Interceptor removeListener error: ', e);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change heading bg color
function changeHeadingBg(color){ document.getElementById("heading").style.background = color; }
[ "function h1Correct(){\r\n\t\t\th1.style.background = correctColor;\r\n\t\t}", "function colorHeader(i) {\n $(\"#heading\" + i).addClass(\"hasEvent\");\n }", "_applyConfigStyling() {\n if (this.backgroundColor) {\n const darkerColor = new ColorManipulator().shade(-0.55, this.backgroundColor);\n this.headerEl.style['background-color'] = this.backgroundColor; /* For browsers that do not support gradients */\n this.headerEl.style['background-image'] = `linear-gradient(${this.backgroundColor}, ${darkerColor})`;\n }\n\n if (this.foregroundColor) {\n this.headerEl.style.color = this.foregroundColor;\n }\n }", "function headBG() {\n let headBG = document.getElementById('headBG').value;\n let thList = document.querySelectorAll('th');\n for (let th of thList) {\n th.style.backgroundColor = headBG;\n }\n}", "function colour_headings() {\n\t$(\".party_name h3\").each(function() {\n\t\t//assign the current text of heading to a variable\n\t\tvar heading_text = $(this).text();\n\n\t\t// Make a switch statement that will change colour of row\n\t\tswitch (heading_text) {\n\n\t\t\tcase \"Conservative\":\n\t\t\t$(this).parent().parent().css({color: \"blue\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Labour\":\n\t\t\t$(this).parent().parent().css({color: \"red\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Liberal Democrats\":\n\t\t\t$(this).parent().parent().css({color: \"#FC0\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Green Party\":\n\t\t\t$(this).parent().parent().css({color: \"#00FF00\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Plaid Cymru\":\n\t\t\t$(this).parent().parent().css({color: \"#6C3\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Democratic Unionist Party\":\n\t\t\t$(this).parent().parent().css({color: \"brown\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Scottish National Party\":\n\t\t\t$(this).parent().parent().css({color: \"#FF0\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Sinn Fein\":\n\t\t\t$(this).parent().parent().css({color: \"#060\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Social Democratic and Labour Party\":\n\t\t\t$(this).parent().parent().css({color: \"#3C3\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Alliance Party\":\n\t\t\t$(this).parent().parent().css({color: \"#FFEE10\"});\n\t\t\tbreak;\n\n\t\t\tcase \"UKIP\":\n\t\t\t$(this).parent().parent().css({color: \"purple\"});\n\t\t\tbreak;\n\n\t\t\tcase \"Ulster Unionists\":\n\t\t\t$(this).parent().parent().css({color: \"#99F\"});\n\t\t\tbreak;\n\n\t\t\tcase \"BNP\":\n\t\t\t$(this).parent().parent().css({color: \"midnightblue\"});\n\t\t\tbreak;\n\n\t\t\t//Spending Sections\n\n\t\t\tcase \"Pensions\":\n\t\t\t$(this).parent().parent().css({color: \"#6ec138\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Health Care\":\n\t\t\t$(this).parent().parent().css({color: \"#ffe061\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Welfare\":\n\t\t\t$(this).parent().parent().css({color: \"#64b2df\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Education\":\n\t\t\t$(this).parent().parent().css({color: \"#ae1916\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Local Government\":\n\t\t\t$(this).parent().parent().css({color: \"#404040\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Interest on Debt\":\n\t\t\t$(this).parent().parent().css({color: \"#bfbfbf\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Defence\":\n\t\t\t$(this).parent().parent().css({color: \"#ff2d22\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Protection\":\n\t\t\t$(this).parent().parent().css({color: \"#6ec138\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Transport\":\n\t\t\t$(this).parent().parent().css({color: \"#175778\"})\n\t\t\tbreak;\n\n\t\t\tcase \"Central Government\":\n\t\t\t$(this).parent().parent().css({color: \"#000000\"})\n\t\t\tbreak;\n\n\t\t}\n\t});\n\n} //End of colour_headings()", "function color() {\n let hue = Math.round(Math.random()*360);\n let matches = this.style.backgroundColor.match(/\\d+/g);\n let hslCode = rgbToHsl(matches[0], matches[1], matches[2]);\n console.log(hslCode);\n this.style.backgroundColor = `hsl(${hue}, 100%, ${Math.round(hslCode[2]*100)}%)`;\n}", "function zmienKolor() {\nthis.style.backgroundColor = 'beige';\n }", "function addHeaderStyle(element) {\n element.style.margin = '6px 0px 3px 0px';\n element.style.width = width + 'px';\n element.style.textAlign = 'center';\n element.style.backgroundColor = '#cccccc';\n element.style.fontVariant = 'small-caps';\n element.style.fontWeight = 'normal';\n element.style.fontSize = '0.8em';\n }", "function fixHead() {\n var thead = $(settings.table).find(\"thead\");\n var tr = thead.find(\"tr\");\n var cells = thead.find(\"tr > *\");\n\n setBackground(cells);\n cells.css({\n 'position': 'relative'\n });\n }", "function changeColor(bottle, color) {\n bottle.attr('style', 'background-color: ' + color);\n }", "function setBGColorByHash(docObj, bgColor) { \n if (docObj.location) {\n var tagName = docObj.location.hash;\n // Use the stored hash value if it exists because the location.hash\n // may be wrong in internal web browser\n if (RTW_Hash.instance)\n tagName = RTW_Hash.instance.getHash();\n if (tagName != null)\n tagName = tagName.substring(1);\n \n var codeNode = docObj.getElementById(\"RTWcode\");\n if (tagName != null && tagName != \"\") { \n if (!isNaN(tagName))\n tagName = Number(tagName) + 10; \n setBGColorByElementsName(docObj, tagName, bgColor);\n }\n }\n}", "function drawHorizon(w, h, this_color) {\n p5.fill(this_color);\n p5.noStroke();\n p5.rect(0, h / 2, w, h);\n }", "function changeDisplayBackgroundColor() {\n iterations++;\n $(\"#display\").css(\"background-color\", DISPLAY_BACKGROUND_COLORS[iterations % DISPLAY_BACKGROUND_COLORS.length]);\n }", "function colorFondo(color) {\r\n\tdocument.bgColor=color;\r\n\t}", "function changeBodyBg(color){\r\n document.body.style.background = color;\r\n}", "static forceColor() {\n chalk_1.default.level = 1; // `1` - Basic 16 colors support.\n }", "setColor(clutterColor) {\n this._horizLeftHair.background_color = clutterColor;\n this._horizRightHair.background_color = clutterColor;\n this._vertTopHair.background_color = clutterColor;\n this._vertBottomHair.background_color = clutterColor;\n }", "function getColor() {\n randomcolor = Math.floor(Math.random() * colors.length);\n quotesBkg.style.backgroundColor = colors[randomcolor];\n // topbar.style.backgroundColor = colors[randomcolor];\n}", "function goBlue() {\n $target.css({\n backgroundColor: 'blue'\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a floating GUI box with demolition parameters.
function createDemolishFloat() { var options=document.evaluate('//select[@name="abriss"]/descendant::option', document, null, XPSnap, null); myoptions=""; for (var i=0; i<options.snapshotLength; i++) { if(options.snapshotItem(i).innerHTML.indexOf(aLangGameText[16]) != -1) { continue; } myoptions+="<option value='"+options.snapshotItem(i).innerHTML+"'>"+options.snapshotItem(i).innerHTML+"</option>" } var DemoListForm=document.createElement("form"); DemoListForm.id="demolistform"; var floatClose = "<a href='#' onclick='document.body.removeChild($(\"demolistform_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>"; DemoListForm.innerHTML = floatClose; DemoListForm.innerHTML += "<br/>" + aLangTaskOfText[18].big() +"<br/><br/>"; DemoListForm.innerHTML+= aLangGameText[7] + ": <select id='crtvillagee' disabled=true><option value='" + currentID() + "'>" + currentVillageName() + "</option></select><br/><br/>"; DemoListForm.innerHTML+=aLangTaskOfText[18]+": <select id='selecteddemo'>"+myoptions+"</select><br/><br/>" var tSubmitBtn = document.createElement("input"); tSubmitBtn.value = "OK"; tSubmitBtn.type = "button"; tSubmitBtn.addEventListener('click', setDemoCookies, true); DemoListForm.appendChild(tSubmitBtn); var doWrapper = document.createElement("div"); doWrapper.id = "demolistform_wrapper"; doWrapper.appendChild(DemoListForm); var formCoords = getOption("DEMOLISH_POSITION", "218px_468px"); formCoords = formCoords.split("_"); doWrapper.style.top = formCoords[0]; doWrapper.style.left = formCoords[1]; document.body.appendChild(doWrapper); makeDraggable($("demolistform")); }
[ "function FluidPanel() {}", "onDemandCreateGUI() {\n \n if (this.internal.parentDomElement===null)\n return;\n \n this.internal.parentDomElement.empty();\n \n let basediv=webutil.creatediv({ parent : this.internal.parentDomElement});\n this.internal.domElement=basediv;\n \n let f1 = new dat.GUI({autoPlace: false});\n basediv.append(f1.domElement);\n\n // Global Properties\n let s1_on_cb=(e) => {\n let ind=this.internal.data.allnames.indexOf(e);\n this.setCurrentGrid(ind);\n };\n\n this.internal.data.allnames=[];\n for (let i=0;i<this.internal.multigrid.getNumGrids();i++) {\n this.internal.data.allnames.push(this.internal.multigrid.getGrid(i).description);\n }\n \n let sl=f1.add(this.internal.data,'currentname',this.internal.data.allnames).name(\"Current Grid\");\n sl.onChange(s1_on_cb);\n\n let dp=f1.add(this.internal.data,'showmode',this.internal.data.allshowmodes).name(\"Grids to Display\");\n let dp_on_cb=() => {\n this.showhidemeshes();\n this.updategui(true);\n };\n dp.onChange(dp_on_cb);\n\n webutil.removedatclose(f1);\n\n \n // --------------------------------------------\n let ldiv=$(\"<H4></H4>\").css({ 'margin':'15px'});\n basediv.append(ldiv);\n\n this.internal.landlabelelement=webutil.createlabel( { type : \"success\",\n name : \"Current Electrode Properties\",\n parent : ldiv,\n });\n let sbar=webutil.creatediv({ parent: basediv});\n let inlineform=webutil.creatediv({ parent: sbar});\n let elem1=webutil.creatediv({ parent : inlineform,\n css : {'margin-top':'20px', 'margin-left':'10px'}});\n \n let elem1_label=$(\"<span>Electrode: </span>\");\n elem1_label.css({'padding':'10px'});\n elem1.append(elem1_label);\n this.internal.currentelectrodeselect=webutil.createselect({parent : elem1,\n values : [ 'none' ],\n callback : (e) => {\n this.selectElectrode(e.target.value,true);\n this.centerOnElectrode();\n },\n });\n\n this.internal.checkbuttons={};\n\n let sbar2=webutil.creatediv({ parent: basediv});\n for (let i=0;i<PROPERTIES.length;i++) {\n this.internal.checkbuttons[PROPERTIES[i]]=\n webutil.createcheckbox({\n name: PROPERTIES[i],\n type: \"info\",\n checked: false,\n parent: sbar2,\n css: { 'margin-left': '5px' ,\n 'margin-right': '5px',\n 'width' : '100px'}\n });\n }\n \n \n \n\n // ----------- Landmark specific stuff\n\n if (this.internal.gridPropertiesGUI===null) {\n const f2 = new dat.GUI({autoPlace: false});\n console.log('F2=',f2,JSON.stringify(this.internal.data));\n \n console.log('Creating modal');\n let modal=webutil.createmodal(\"Grid Properties\",\"modal-sm\");\n this.internal.gridPropertiesGUI=modal.dialog;\n modal.body.append(f2.domElement);\n\n \n console.log('Radius=',this.internal.data.radius);\n \n f2.add(this.internal.data, 'radius',0.5,8.0).name(\"Radius\").step(0.5).onChange(() => {\n let grid=this.internal.multigrid.getGrid(this.internal.currentgridindex);\n grid.radius=this.internal.data.radius;\n this.updateMeshes(true);\n });\n \n console.log('Color=',this.internal.data.color);\n \n f2.addColor(this.internal.data, 'color').name(\"Landmark Color\").onChange(()=> { \n this.updatecolors();\n });\n \n webutil.removedatclose(f2);\n this.internal.folders=[f1, f2];\n } else {\n this.internal.folders[0]=f1;\n }\n // Save self for later\n \n // ---------------\n // rest of gui \n // ---------------\n\n let bbar0=webutil.createbuttonbar({ parent: basediv,\n css : {'margin-top': '20px','margin-bottom': '10px'}});\n\n \n let update_cb=() => { this.updateGridProperties();};\n webutil.createbutton({ type : \"primary\",\n name : \"Display Properties\",\n position : \"bottom\",\n tooltip : \"Click this to set advanced display properties for this set (color,radius)\",\n parent : bbar0,\n callback : update_cb,\n });\n\n let load_cb=(f) => { this.loadMultiGrid(f); };\n webfileutil.createFileButton({ type : \"warning\",\n name : \"Load\",\n position : \"bottom\",\n tooltip : \"Click this to load points from either a .mgrid or a .bisgrid file\",\n parent : bbar0,\n callback : load_cb,\n },{\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : false,\n suffix : \".bisgrid,.mgrid\",\n });\n\n let save_cb=(f) => {\n f=f || 'landmarks.bisgrid';\n console.log('f=',f);\n let suffix=f.split(\".\").pop();\n if (suffix===\"land\")\n return this.exportMultiGrid(f);\n else\n return this.saveMultiGrid(f);\n };\n\n\n \n webfileutil.createFileButton({ type : \"primary\",\n name : \"Save\",\n position : \"bottom\",\n tooltip : \"Click this to save points to a .bisgrid or .mgrid file\",\n parent : bbar0,\n callback : save_cb,\n },\n {\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : true,\n suffix : \".bisgrid,.mgrid\",\n initialCallback : () => { return this.getInitialSaveFilename(); },\n });\n\n \n webutil.createbutton({ type : \"info\",\n name : \"Multisnapshot (Current Grid)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(false).catch( (e) => { console.log(e);});}\n });\n\n webutil.createbutton({ type : \"danger\",\n name : \"Multisnapshot (All Grids)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(true).catch( (e) => { console.log(e);});}\n });\n\n \n webutil.tooltip(this.internal.parentDomElement);\n \n // ----------------------------------------\n // Now create modal\n // ----------------------------------------\n\n \n\n }", "function showF(){\n\tif(F.checked==false){\n\t\tftc.checked=false; // Hide FTC when f(x) is not visible.\n\t\tmarks.checked=false;\t\n\t}\n\tGraphButton();\n}", "function enable_dvab_floating() {\r\n\t/* already run? */\r\n\tif(window.enable_dvab_floating_run != undefined) return;\r\n\r\n\t/* scroll action buttons of DV on scrolling DV */\r\n\t$j(window).scroll(function() {\r\n\t\tif(!$j('.detail_view').length) return;\r\n\t\tif(!screen_size('md') && !screen_size('lg')) {\r\n\t\t\t$j('.detail_view .btn-toolbar').css({ 'margin-top': 0 });\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t/* get vscroll amount, DV form height, button toolbar height and position */\r\n\t\tvar vscroll = $j(window).scrollTop();\r\n\t\tvar dv_height = $j('[id$=\"_dv_form\"]').eq(0).height();\r\n\t\tvar bt_height = $j('.detail_view .btn-toolbar').height();\r\n\t\tvar form_top = $j('.detail_view .form-group').eq(0).offset().top;\r\n\t\tvar bt_top_max = dv_height - bt_height - 10;\r\n\r\n\t\tif(vscroll > form_top) {\r\n\t\t\tvar tm = parseInt(vscroll - form_top) + 60;\r\n\t\t\tif(tm > bt_top_max) tm = bt_top_max;\r\n\r\n\t\t\t$j('.detail_view .btn-toolbar').css({ 'margin-top': tm + 'px' });\r\n\t\t} else {\r\n\t\t\t$j('.detail_view .btn-toolbar').css({ 'margin-top': 0 });\r\n\t\t}\r\n\t});\r\n\twindow.enable_dvab_floating_run = true;\r\n}", "function createPluginsGui() {\n\n var widgets = [],\n toggles = {type:'panel', layout: 'vertical', label: false, alphaStroke: 0, widgets:[], width:200, contain: false, innerPadding: false, padding: 0},\n faders = {type:'panel', layout: 'vertical', label: false, alphaStroke: 0, widgets:[], expand:true, contain: false, innerPadding: false, padding: 0}\n\n for (var j in PLUGIN.parameters) {\n if (256 & PLUGIN.parameters.flags) continue\n let w = paramsToWidget(PLUGIN.parameters[j], PLUGIN.id)\n if (!w) continue\n var pane = w.type === 'button' ? toggles : faders\n pane.widgets.push({\n type: 'panel',\n height: 35,\n layout: 'horizontal',\n label: false,\n padding: 0,\n alphaStroke: 0,\n widgets: [\n {\n type: 'text',\n value: PLUGIN.parameters[j].name,\n label: false,\n expand: w.type === 'button',\n width: 100,\n alphaStroke: 0,\n alphaFillOff: 0,\n align: 'left',\n colorWidget: '#ccc'\n },\n w\n ]\n })\n if (w.type === 'fader') {\n pane.widgets[pane.widgets.length-1].widgets.push({\n type: 'input',\n label: false,\n width: 80,\n unit: w.unit,\n linkId: w.linkId,\n alphaStroke: 0,\n bypass: true\n })\n }\n }\n\n if (toggles.widgets.length) widgets.push(toggles)\n if (faders.widgets.length) widgets.push(faders)\n\n _receive('/EDIT', 'plugin_modal', {\n widgets: widgets,\n popupLabel: STRIP_NAMES[CURRENT_SSID] + ' ^chevron-right ' + PLUGIN_NAMES[CURRENT_SSID + '_' + PLUGIN.id]\n })\n\n}", "function DragFloat(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.DragFloat(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }", "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 AttachToBoxBehavior(ui){this.ui=ui;/**\n * The name of the behavior\n */this.name=\"AttachToBoxBehavior\";/**\n * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)\n */this.distanceAwayFromFace=0.15;/**\n * The distance from the bottom of the face that the UI should be attached to (default: 0.15)\n */this.distanceAwayFromBottomOfFace=0.15;this._faceVectors=[new FaceDirectionInfo(BABYLON.Vector3.Up()),new FaceDirectionInfo(BABYLON.Vector3.Down()),new FaceDirectionInfo(BABYLON.Vector3.Left()),new FaceDirectionInfo(BABYLON.Vector3.Right()),new FaceDirectionInfo(BABYLON.Vector3.Forward()),new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];this._tmpMatrix=new BABYLON.Matrix();this._tmpVector=new BABYLON.Vector3();this._zeroVector=BABYLON.Vector3.Zero();this._lookAtTmpMatrix=new BABYLON.Matrix();/* Does nothing */}", "function update_gui()\n{\n\tnotevaluesgui.message('set', selected.obj.notevalues.getvalueof());\n\tnotetypegui.message('set', selected.obj.notetype.getvalueof());\n\tRandom.message('set', selected.obj.random.getvalueof());\n\tGroove.message('set', (selected.obj.swing.getvalueof()*100)-50);\n\tChannel.message('set', selected.obj.channel.getvalueof());\n\tMode.message('set', selected.obj.mode.getvalueof());\n\tPolyOffset.message('set', selected.obj.polyoffset.getvalueof());\n\tif((pad_mode == 6)||(key_mode == 6))\n\t{\n\t\toutlet(0, 'button', 3, 2, selected.hold);\n\t}\n}", "function initFloatingLabels() {\n\t(0,$)(document).on('ready', function() {\n \"undefined\" != typeof FloatLabels && new FloatLabels(\".js-ws-floating-labels\",{\n prioritize: \"placeholder\"\n })\n})\n}", "function buildBox() {\n var innerContent = getInnerContent();\n var buttons = '';\n if(curOpt.ok){\n buttons = '<div class=\\'pm-popup-buttons\\'> <button class=\\'button\\'>OK</button></div>';\n }\n var boxHtml = '<div id=\\'pm_'+curOpt.id+'\\' class=\\'pm_popup\\'><div class=\\'pm-popup-inner\\'> '+innerContent + buttons+'</div></div>';\n var thisPopup = $(boxHtml).appendTo('body');\n if (curOpt.ok) {\n //attach events\n thisPopup.find('.button').click(function() {\n $(window).scrollTop(0);\n hide();\n curOpt.ok();\n });\n }\n }", "function DragFloat2(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Vector2(v);\r\n const ret = bind.DragFloat2(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }", "function addLabelAndBox(name) {\n addLabel(name);\n addTextBox(name);\n}", "function Sprite_FloatingInfo() {\n this.initialize(...arguments);\n }", "function TabSystem() {\r\n this.input = function(title, type, unit) {\r\n var el = document.createElement(\"div\");\r\n el.style = `\r\n width: fit-content;\r\n height: fit-content;\r\n float: left;\r\n display: block;\r\n margin-bottom: 0.5rem;\r\n `;\r\n el.className = \"fd-input\";\r\n\r\n var p = document.createElement(\"p\");\r\n p.innerHTML = title;\r\n p.style = `\r\n margin: 0;\r\n line-height: 1rem;\r\n font-weight: lighter;\r\n `\r\n el.appendChild(p);\r\n\r\n var input = document.createElement(\"input\");\r\n input.style = `\r\n height: 2rem;\r\n width: 5rem;\r\n border-radius: 0.25rem 0.25rem 0 0;\r\n background-color: \r\n margin: 0;\r\n background-color: var(--main-bg-color);\r\n border: solid 2px var(--slider-color);\r\n outline: none;\r\n padding: 0.25rem;\r\n box-sizing: border-box;\r\n font-size: 1.2em;\r\n color: var(--paragraph-color);\r\n font-family: bahnschrift;\r\n font-weight: lighter;\r\n `\r\n switch(type) {\r\n case \"number\": \r\n input.type = \"number\"\r\n break;\r\n case \"search\":\r\n input.type = \"search\"\r\n break;\r\n }\r\n el.appendChild(input);\r\n\r\n if(unit) {\r\n var p = document.createElement(\"p\");\r\n p.innerHTML = unit;\r\n p.style = `\r\n display: inline-block;\r\n margin: 0 0 0 0.5rem;\r\n color: var(--paragraph-color);\r\n opacity: 0.6;\r\n `;\r\n input.style.display = \"inline-block\";\r\n el.appendChild(p);\r\n }\r\n\r\n return el;\r\n },\r\n this.slider = function(title, showValue) {\r\n var el = document.createElement(\"div\");\r\n el.style = `\r\n width: 100%;\r\n height: fit-content;\r\n float: left;\r\n display: block;\r\n `;\r\n\r\n var p = document.createElement(\"p\");\r\n p.innerHTML = title;\r\n p.style = `\r\n margin: 0;\r\n line-height: 1rem;\r\n font-weight: lighter;\r\n `\r\n el.appendChild(p);\r\n\r\n var slider = document.createElement(\"input\");\r\n slider.style = `\r\n margin: 0; \r\n width: 10rem;\r\n display: inline-block;\r\n `\r\n slider.className = \"fd-slider\";\r\n slider.type = \"range\";\r\n el.appendChild(slider);\r\n\r\n if(showValue) {\r\n var p = document.createElement(\"p\");\r\n p.innerHTML = \"1\";\r\n p.style = `\r\n margin: 0 0 0 0.5rem;\r\n display: inline-block;\r\n line-height: 0.5rem;\r\n vertical-align: middle;\r\n `;\r\n el.appendChild(p);\r\n\r\n slider.addEventListener(\"change\", function(e) {\r\n p.innerHTML = e.target.value;\r\n })\r\n }\r\n\r\n return el;\r\n },\r\n this.checkBox = function(title, customStyle) {\r\n var cont = document.createElement(\"div\");\r\n cont.setAttribute(\"name\", title);\r\n var style = customStyle ? customStyle : \"width: 100%; height: fit-content; float: left; display: block; margin-top: 0.2rem\"; \r\n cont.style = style;\r\n var el = document.createElement(\"label\");\r\n el.setAttribute(\"name\", title);\r\n el.className = \"control control-checkbox\";\r\n el.innerHTML = title;\r\n var box = document.createElement(\"input\");\r\n box.type = \"checkbox\";\r\n\r\n box.isActive = false;\r\n\r\n //BUG: Two ripples appear. Fix this sometime!!\r\n //el.classList.add(\"ripple-element\");\r\n //appendRipple(el);\r\n var ind = document.createElement(\"div\");\r\n ind.className = \"control_indicator\";\r\n\r\n el.appendChild(box);\r\n el.appendChild(ind);\r\n cont.appendChild(el);\r\n \r\n return cont;\r\n\r\n/*\r\n <label class=\"control control-checkbox\">\r\n First checkbox\r\n <input type=\"checkbox\" checked=\"checked\" />\r\n <div class=\"control_indicator\"></div>\r\n </label>*/\r\n\r\n },\r\n this.select = function(options, display, title, useOptionsAsNames) {\r\n var wrapper = document.createElement(\"div\");\r\n wrapper.style = `\r\n height: 5rem;\r\n width: fit-content;\r\n display: block;\r\n `\r\n\r\n var el = document.createElement(\"div\");\r\n el.className = \"select\";\r\n\r\n if(title) {\r\n var p = document.createElement(\"p\");\r\n p.innerHTML = title;\r\n p.style = `\r\n margin: 0;\r\n line-height: 1rem;\r\n font-weight: lighter;\r\n height: 1rem;\r\n `;\r\n wrapper.appendChild(p);\r\n }\r\n\r\n var sel = document.createElement(\"select\");\r\n\r\n var x;\r\n var i = 0;\r\n for(x of options) {\r\n var opt = document.createElement(\"option\");\r\n opt.innerHTML = x;\r\n if(useOptionsAsNames) {\r\n opt.value = x;\r\n } else {\r\n opt.value = i;\r\n i++\r\n }\r\n\r\n sel.appendChild(opt);\r\n }\r\n\r\n el.appendChild(sel);\r\n\r\n var arr = document.createElement(\"div\");\r\n arr.className = \"select_arrow\";\r\n\r\n el.appendChild(arr);\r\n if(display) {\r\n sel.value = display;\r\n }\r\n\r\n wrapper.appendChild(el);\r\n return wrapper;\r\n }\r\n\r\n}", "function DragFloat3(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.DragFloat3(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }", "function hideVacationForm(b){\n var containerHeight = (b)?\"550px\":\"200px\";\n \n var slideName = (b)?\"vacation_enabled\":\"vacation_disabled\";\n var slide = dijit.byId(slideName);\n var container = dijit.byId('vacation_container');\n require([\"dojo/dom\", \"dojo/_base/fx\", \"dojo/on\", \"dojo/dom-style\", \"dojo/query\", \"dojo/domReady!\"],\n function(dom, fx, on, style, query){\n container.selectChild(slide); \n style.set(slideName, \"opacity\", \"0\");\n query(\".vacation_container\").style(\"height\", containerHeight);\n \n var fadeArgs = {\n node: slideName\n };\n fx.fadeIn(fadeArgs).play(); \n }); \n}", "function displaystripbrdDialog()\r\n{\r\n\tdocument.getElementById(\"RowSize\").value = globalBBwidth;\r\n\tdocument.getElementById(\"ColSize\").value = globalBBheight;\r\n showDialog(document.getElementById('adjustBB_dialog'), null);\r\n}", "function DN50LFFreseOptimaFlangeCalculator() {\n var minFlow = 2.48;\n var maxFlow = 15;\n var minDp = 7;\n var maxDp = 600;\n \n this.getName = function() {\n return \"DN50LF\";\n }\n \n this.calculateSetting = function(flow, pressure) {\n if (!canCalculateFlow(flow)) return -1;\n if (!canCalculateDp(pressure)) return -1;\n \n return (-0.0007 * Math.pow(flow, 3)) + (0.0111 * Math.pow(flow, 2)) + (0.2671 * flow) - 0.1437;\n }\n \n this.calculateDp = function(flow, pressure) {\n if (!canCalculateFlow(flow)) return -1;\n \n if (flow < 3.9) return 6.5;\n var s = this.calculateSetting(flow, pressure);\n return (0.25 * Math.pow(s, 3)) - (0.25 * Math.pow(s, 2)) + (0.5 * s) + 6;\n }\n \n function calculateDelta(setting) {\n return 1;\n }\n \n function canCalculateFlow(flow) {\n return flow >= minFlow && flow <= maxFlow ? true : false;\n }\n \n function canCalculateDp(pressure) {\n return pressure >= minDp && pressure <= maxDp ? true : false; \n }\n} // DN50LFFreseOptimaFlangeCalculator" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the name of the current matrix class
getClassName() { return 'Matrix'; }
[ "static get screenName() {\n return this.__proto__.constructor.name;\n }", "processNamedClass() {\n if (!this.tokens.matches2(tt._class, tt.name)) {\n throw new Error(\"Expected identifier for exported class name.\");\n }\n const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);\n this.processClass();\n return name;\n }", "getComponentType() {\n return utilities_1.getComponentInstanceTypeFromComponentName(this.constructor.getComponentName());\n }", "getClassName() {\n return 'Quaternion';\n }", "getClassName() {\n return 'Color4';\n }", "function getIEClass()\n{\n if(isIE(6))\n return \"ie ie6 lte9 lte8 lte7 lte6\";\n if(isIE(7))\n return \"ie ie7 lte9 lte8 lte7\";\n if(isIE(8))\n return \"ie ie8 lte9 lte8\";\n if(isIE(9))\n return \"ie ie9 lte9\";\n if(isIE())\n return \"ie\";\n return \"\";\n}", "__extractNameAndMountPath() {\n let name = this.constructor.name || '';\n name = _.snakeCase(name);\n name = name.replace(/_(ctrl|controller)$/, '');\n return name || utils.getName();\n }", "function ajax_getClassName( element ) {\r\n if (ie4 && browser != \"Opera\" && ! ie8)\r\n return (element.getAttribute(\"className\"));\r\n else return (element.getAttribute(\"class\"));\r\n}", "static get table() { return this.name; }", "toString() {\n return `${this.constructor.name}( ${this._stack\n .map((rc) => rc.toString())\n .join(', ')} )`;\n }", "get computeTypeName() {\n return this.getStringAttribute('compute_type_name');\n }", "klass(i) {\n var col, mod, ncol, row;\n ncol = 3;\n mod = i % ncol;\n row = (i - mod) / ncol + 1;\n col = mod + 1;\n return `r${row}c${col}`;\n }", "function getClass(){\n\tvar classes = ['barbarian', 'monk', 'fighter', 'paladin', 'rogue', 'ranger',\n\t'bard', 'wizard', 'warlock', 'sorcerer', 'cleric', 'druid'];\n\treturn classes[Math.floor((Math.random() * classes.length) + 1)-1];\n}", "function getCurrentPlayerClass() {\n if(getLastPlayer().getSide() === \"good\") {\n return \"chessMan2\";\n } else {\n return \"chessMan1\";\n }\n}", "name() {\n return this._command.name;\n }", "function frameType(frame) {\n var frameClass = frame.attr(\"class\");\n if (frameClass.indexOf(\"readyFrame\") != -1)\n return \"readyFrame\";\n else if (frameClass.indexOf(\"ackRRFrame\") != -1)\n return \"ackRRFrame\";\n else if (frameClass.indexOf(\"ackREJFrame\") != -1)\n return \"ackREJFrame\";\n else if (frameClass.indexOf(\"ackPollFrame\") != -1)\n return \"ackPollFrame\";\n else if (frameClass.indexOf(\"transmittedFrame\") != -1)\n return \"transmittedFrame\";\n else if (frameClass.indexOf(\"infoFrame\") != -1)\n return \"infoFrame\";\n else if (frameClass.indexOf(\"ackFinalFrame\") != -1)\n return \"ackFinalFrame\";\n}", "function get_tblName_from_selectedBtn() {\n return (selected_btn === \"btn_ete_exams\") ? \"ete_exam\" :\n (selected_btn === \"btn_duo_exams\") ? \"duo_exam\" :\n (selected_btn === \"btn_ntermen\") ? \"ntermen\" :\n (selected_btn === \"btn_results\") ? \"results\" : null ;\n }", "function nameOf(fun) {\n var ret = fun.toString();\n ret = ret.substr('function '.length);\n ret = ret.substr(0, ret.indexOf('('));\n return ret;\n }", "function currentThread() {\n\treturn java.lang.Thread.currentThread();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of "chunks". A chunk is an array consisting of many stacks. A stack is an array consisting of many events.
collect() { // Join active and finalized stacks. We want to make sure we iterate over // every event. const stacks = [...this.finalizedStacks]; Object.values(this.activeStacks).forEach((s) => stacks.splice(s.id, 0, s.events) ); return stacks.reduce((chunks, stack) => { if (stack.length === 0) { return chunks; } // We're the first chunk in, meaning we don't need to worry about any // chunks behind us. Just push it. if (chunks.length === 0) { chunks.push([stack]); return chunks; } // If the root event is an HTTP request, this a complete chunk. Push it. if (stack[0].http_server_request) { chunks.push([stack]); return chunks; } // Check to see if the previous chunk began with an HTTP request. If it // does, push a new chunk. Otherwise, append to the last chunk. const prevChunk = chunks[chunks.length - 1]; const prevStack = prevChunk[prevChunk.length - 1]; if (prevStack[0].http_server_request) { chunks.push([stack]); } else { prevChunk.push(stack); } return chunks; }, []); }
[ "chunk(arr, size) {\n if(typeof size === 'undefined') {\n size = 1;\n }\n let arrayChunks = [];\n for(let i = 0; i < arr.length; i+=size) {\n let arrayChunk = arr.slice(i, i+size);\n arrayChunks.push(arrayChunk);\n }\n return arrayChunks;\n }", "function chunk(array, chunkSize, processChunk) {\n for (let i = 0; i < array.length; i += chunkSize) {\n const chunk = array.slice(i, i + chunkSize);\n processChunk(chunk);\n }\n}", "function chunk(array, size) {\n\n // #1 solution\n // let i = 0\n // let total = 0\n // let temp = []\n // let resultArray = []\n\n // for (let item in array) { \n // temp.push(array[item])\n\n // i++\n // total++\n // if (i === size || total === array.length) { \n // resultArray.push(temp)\n // temp = []\n // i = 0\n // }\n // }\n // return resultArray\n \n // #2 solution\n // let resultArray = new Array(Math.ceil(array.length / size))\n // for (let i = 0; i < resultArray.length; i++) {\n // resultArray[i] = []\n // }\n\n // let i = 0\n // let total = 0\n // array.forEach((val) => {\n // resultArray[i].push(val)\n // total++\n // if (total % size === 0 || array.length === total) {\n // i++\n // }\n // })\n // return resultArray\n\n // #3 slice\n let results = []\n let index = 0\n while (index < array.length) {\n results.push(array.slice(index, index + size))\n index += size\n }\n return results\n}", "async function getEventsChunks (eventsChunks = [], lastDoc) {\n const result = await queryPagedEventsWithLimit(lastDoc);\n console.log('Read events length', eventsChunks.length);\n eventsChunks = eventsChunks.concat(result.docs);\n\n if (result.lastDoc) {\n return getEventsChunks(eventsChunks, result.lastDoc);\n }\n\n return eventsChunks;\n}", "get ancestorAndSubsequentSlices() {\n var res = [];\n\n res.push(this);\n\n for (var aSlice of this.enumerateAllAncestors())\n res.push(aSlice);\n\n this.iterateAllSubsequentSlices(function(sSlice) {\n res.push(sSlice);\n });\n\n return res;\n }", "getChunksInRange(point1, point2)\n {\n var chunks = [];\n \n for(var x = point1.x, xi = 0; x <= point2.x; x += X_CHUNKS_PER_REGION * TILE_SIZE, xi++) // add 32 each iteration\n {\n var addedIndex = false;\n\n for(var y = point1.y; y <= point2.y; y += Y_CHUNKS_PER_REGION * TILE_SIZE) // same here, 32 per iteration\n {\n var chunk = WORLD.getChunk(x, y);\n if(chunk == null)\n continue;\n \n if(!addedIndex)\n {\n addedIndex = true;\n chunks.push(new Array());\n }\n\n chunks[xi].push(chunk);\n }\n }\n return chunks;\n }", "save_stack(s){\n var v = [];\n for(var i=0; i<s; i++){\n v[i] = this.stack[i];\n }\n return { stack: v, last_refer: this.last_refer, call_stack: [...this.call_stack], tco_counter: [...this.tco_counter] };\n }", "function sliceArray(anim, beginSlice, endSlice) {\n // Add your code below this line\n return anim.slice(beginSlice, endSlice);\n // Add your code above this line\n}", "function chunker(text, len){\r\n var chunks = [];\r\n while(text.length > len){\r\n chunks.unshift(text.substr(0,len))\r\n text = text.substr(len);\r\n }\r\n chunks.unshift(text);\r\n return chunks;\r\n }", "function partition_array(arr, chunksize){\n len = arr.length;\n ans = [];\n tmp = [];\n for(i = 0; i < len; i ++){\n if(i !== 0 && i % chunksize === 0){\n ans.push(tmp.slice(0));\n tmp = [];\n }\n tmp.push(arr[i]);\n }\n if(tmp.length !== 0){\n ans.push(tmp);\n }\n return ans;\n}", "function tasks_stack() {\r\n let stackdata = new Stack(1);\r\n stackdata.push(4);\r\n stackdata.push(8);\r\n stackdata.push(9);\r\n stackdata.push(10);\r\n stackdata.push(11);\r\n\r\n stackdata.parse_llist();\r\n let out = stackdata.pop();\r\n let out1 = stackdata.pop();\r\n let out2 = stackdata.pop();\r\n let out3 = stackdata.pop();\r\n // let out4 = stackdata.pop();\r\n // let out5 = stackdata.pop();\r\n // let out6 = stackdata.pop();\r\n // let out7 = stackdata.pop();\r\n console.log(\r\n \" gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n // out4.value,\r\n // out5.value,\r\n // out6.value,\r\n // out7.value\r\n );\r\n stackdata.push(100);\r\n stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n\r\n console.log(\r\n \"peeking out \",\r\n // stackdata.peek(),\r\n stackdata.is_empty(),\r\n stackdata\r\n );\r\n stackdata.parse_llist();\r\n }", "__groupNodesByPosition(rawNodes) {\n const nodes = [];\n let tmpStack = [];\n _.each(rawNodes, (rawNode, index) => {\n // Check current and next node position\n const $rawNode = $(rawNode);\n const currentNodePosition = this.__getBottomPosition($rawNode);\n let nextNodePosition = -9999;\n if (rawNodes[index + 1]) {\n nextNodePosition = this.__getBottomPosition(rawNodes[index + 1]);\n }\n\n const isListItem = this.__isListItem($rawNode);\n let gapThreshold = 20;\n if (isListItem) {\n gapThreshold = 15;\n }\n\n // Too far appart, we need to add them\n if (currentNodePosition - nextNodePosition > gapThreshold) {\n let content = $rawNode.html();\n\n // We have something in the stack, we need to add it\n if (tmpStack.length > 0) {\n tmpStack.push($rawNode);\n content = _.map(tmpStack, tmpNode => tmpNode.html()).join('\\n');\n tmpStack = [];\n }\n\n nodes.push({ type: this.getNodeType($rawNode), content });\n return;\n }\n\n // Too close, we keep in the stack\n tmpStack.push($rawNode);\n });\n return nodes;\n }", "function newStack() {\n let stack = [];\n return {\n push: function(value) {\n stack.push(value);\n },\n pop: function() {\n stack.pop();\n },\n printStack: function() {\n stack.forEach((value) => console.log(value));\n },\n }\n}", "function StackEmitter() {\n // The Array that holds the active StreamStack instances on a parent Stream.\n this._stacks = [];\n // Get a reference to the original 'emit' function, since we're about to\n // monkey-patch with our own 'emit' function.\n this._origEmit = this.emit;\n // Mix-in the rest of the StackEmitter properties.\n for (var prop in StackEmitter.prototype) {\n this[prop] = StackEmitter.prototype[prop];\n }\n}", "exportStack() {\n return this.stack.exportStack();\n }", "getRoomStack(rooms) {\n var result = [];\n for (var i = 0; i < rooms.length; i++) {\n var room = rooms[i]\n if (\n room.Name !== \"Entrance Hall\"\n && room.Name !== \"Foyer\"\n && room.Name !== \"Grand Staircase\"\n && room.Name !== \"Upper Landing\"\n ) {\n result.push(room);\n }\n }\n return result;\n }", "function getStockSymbols(stocks) {\n var symbols = [], // empty array that is going to store our symbols\n counter, // keeps track of the current index in the array\n stock; // keeps track of the current stock in the array\n\n // three parts\n // first part is what we want to get executed, initializing the counter which will point to the first index in the array\n // second part is the condition that we want to be true as long as we want the for loop to continue, in this case we want\n // the for loop to continue as like as the counter is smaller than the length of the stocks\n // the third part is what we want to execute at the bottom of each iteration thru the loop, and in this case we want to\n // increment counter\n for(counter = 0; counter < stocks.length; counter++){\n // assigning stock at the index of the counter\n // were looping through each item in the stocks array and assigning it to variable stock\n stock = stocks[counter];\n // we are adding to the symbols array and pull out the symbol from the stock and add it to the symbols array\n symbols.push(stock.symbol);\n }\n\n return symbols;\n}", "get stacksRecursively() {\n function search(stackArtifacts, assemblies) {\n if (assemblies.length === 0) {\n return stackArtifacts;\n }\n const [head, ...tail] = assemblies;\n const nestedAssemblies = head.nestedAssemblies.map(asm => asm.nestedAssembly);\n return search(stackArtifacts.concat(head.stacks), tail.concat(nestedAssemblies));\n }\n ;\n return search([], [this]);\n }", "function build_groups_array(data) {\n var results = new Array();\n \n // Map from CRID to group index.\n var crids_map = {};\n \n var group_title = \"\";\n var group_synopsis = \"\";\n for (var i = 0, len = data.events.length; i < len; i++) {\n var event = data.events[i];\n\n // Check CRID first.\n var crid_index = crids_map[event.event_crid];\n if (crid_index != undefined) {\n\n // Add new member to existing group.\n var members = results[crid_index];\n members.push(i);\n\n } else {\n \n // Is next event in current group, or start a new one?\n if (results.length > 0 && event.title == group_title && event.synopsis == group_synopsis) {\n // Add new member to the latest existing group.\n var members = results[results.length - 1];\n members.push(i);\n } else {\n // Create new members array with this event, and push a new group.\n var new_members = [i];\n results.push(new_members);\n group_title = event.title;\n group_synopsis = event.synopsis;\n \n // Remember the index of this group in the CRID map.\n if (event.event_crid.length > 0) {\n crids_map[event.event_crid] = results.length - 1;\n }\n }\n\n }\n }\n return results;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a JavaScript program to find ALL the Armstrong numbers between 0 and 999, store them in array an output that array to the console. Note : An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.
function findArm(){ let armstrongNumbers = []; for (let num = 0; num<1000 ; num++) { let numA = (num.toString()).split(''); let x = numA.length; let sum = 0 for (let i = 0 ; i < x ; i++) { if (numA[i] >= 0 ) { sum += (Math.pow(numA[i], x)); } } if (num === sum) { armstrongNumbers.push(num); } }; console.log(armstrongNumbers); }
[ "function findArmstrongNumbers(num1, num2) {\n // num1 and num2 are Numbers\n\n let newArray = [];\n for (let i = num1; i <= num2; i++) {\n let strArray = [];\n\n strArray = i.toString().split('');\n let intArray = [];\n for (let j = 0; j < strArray.length; j++) {\n intArray.push(parseInt(strArray[j]));\n }\n let total = 0;\n for (let k = 0; k < intArray.length; k++) {\n\n total += Math.pow(intArray[k], intArray.length)\n }\n if (i === total) {\n newArray.push(i)\n }\n }\n return newArray;\n}", "function identifyArmstrongNumbers(num1, num2) {\n // initialize the array\n let armstrongNumbers = [];\n // loop from NUM1 to NUM2\n for (i = num1; i <= num2; i++) {\n // change the i to a string\n let string = i.toString();\n // initialize total to 0\n let total = 0;\n // loop through each string\n for (j = 0; j < string.length; j++) {\n // change each index of the value to a number\n let number = parseInt(string[j]);\n // add that number to the power of the .LENGTH of the string\n total = total + Math.pow(number, string.length);\n // push the i to the array\n if (total === i) {\n armstrongNumbers.push(i);\n }\n }\n }\n return armstrongNumbers\n}", "function isArmstrongNumber (number) {\n let arrayDigits = number.toString().split('');\n\n let constructedNumber = arrayDigits.reduce((accumulator, value, index) => {\n return accumulator + Math.pow(value, arrayDigits.length);\n }, 0);\n\n if (constructedNumber === number) {\n console.log(`${number} is Armstrong number`);\n } else {\n console.log(`${number} is not Armstrong number`);\n }\n\n return constructedNumber === number;\n}", "function armstrongNumber(armNumber){\r\n\tvar rem,sum=0;\r\n\tvar n=armNumber;//n is a temporary number equals to \r\n\twhile(n>0) \r\n\t{ \r\n\t\trem=n%10; \r\n\t\tsum=sum+(rem*rem*rem); \r\n\t\tn= parseInt(n/10); \r\n\t} \r\n\r\n\t\tif(armNumber==sum) \r\n\t\t\t//console.log(armNumber + \" is a armstrong number \"); \r\n\t\t\treturn armNumber + \" is a armstrong number \";\r\n\t\telse \r\n\t\t\t//console.log(armNumber + \" not armstrong number\"); \r\n\t\t\treturn armNumber + \" not armstrong number\";\r\n\t\treturn 0; \r\n}", "function luckySevens(max) {\n let result = [];\n for (let i = 1; i <= max; i++) {\n if (i % 7 === 0) {\n result.push(i);\n } \n }\n return result;\n}", "function twentyFivePalindromes(){\n //create loop that starts with 109 until array length = 25\n //pass value into function that reverses the value\n //function to find sum\n //pass sum into func isPalindrome?\n //if true\n //pass into is greater than 1000 checker\n //if true, return value to array\n let palNumbers = [];\n //let i = 109;\n //while(palNumbers.length < 25) {\n for (i = 109; palNumbers.length < 25; i++) {\n let iReversed = findReverseVal(i); ///returns an integer\n let sum = findSum(i, iReversed);\n\n if (sumIsPalindrome(sum) && sumIsGreaterThanK(sum)) {\n palNumbers.push(i);\n }\n //i++;\n }\n return palNumbers;\n}", "function luckySevens(num) {\n\n let newArr = [];\n \n for (let i = 1; i < num; i++){\n if (i % 7 === 0) {\n newArr.push(i)\n }\n }\n return newArr;\n }", "function roboNumbers(number) {\n const numbersArray = [];\n for(let i = 0; i <= number; i++){\n if (checkIfContains3(i)){\n numbersArray.push(\"Won't you be my neighbor?\");\n } else if(checkIfContains2(i)) {\n numbersArray.push(\"Boop!\");\n } else if(checkIfContains1(i)) {\n numbersArray.push(\"Beep!\");\n } else {\n numbersArray.push(i);\n }\n }\n return fixFormatting(numbersArray);\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 addOne(arr) {\n let carry = 1\n let result = []\n for (let i = arr.length - 1; i >= 0; i--) {\n console.log(i)\n const total = arr[i] + carry\n if(total === 10) {\n carry = 1\n } else {\n carry = 0\n }\n result[i] = total % 10\n }\n if(carry === 1) {\n for(let i = 0; i < arr.length + 1; i++) {\n result[i] = 0\n }\n result[0] = 1\n }\n console.log('result',result)\n return result\n}", "function numLetters(){\n let allNums = [];\n // hundred and = 10\n let hundreds = [13, 13, 15, 14, 14, 13, 15, 15, 14];\n // eleven, twelve, thirteen, fourteen....nineteen\n let teens = [3, 6, 6, 8, 8, 7, 7, 9, 9, 8];\n // starting with twenty--ninety\n let tens = [6, 6, 5, 5, 5, 7, 6, 6];\n // singles has 1 - 9\n let singles = [3, 3, 5, 4, 4, 3, 5, 5, 4];\n for(let h = -1; h < hundreds.length; h++){\n //teens are included once per hundred\n teens.forEach((num) => allNums.push(num));\n for(let t = -1; t < tens.length; t++){\n //maybe add an if when t is 0 to add w/e remainder is left from the 3 as well from ven, lve, rteen, rteen, teen, teen, enteen....\n for(let s = 0; s < singles.length; s++){\n allNums.push(singles[s]);\n allNums.push(tens[t]);\n allNums.push(hundreds[h]);\n }\n }\n }\n allNums.push(10);//1000\n // filter added to remove the undefined added because of the -1 starting points\n return allNums.filter(x => x).reduce((a, b) => a + b);\n}", "function generateNumbers(){\n var set=new Array();\n for(i=0;i<9;i++){\n var number=Math.floor(Math.random()*9+1);\n while(set.indexOf(number)>-1){\n number=Math.floor(Math.random()*9+1);\n }\n set[i]=number;\n }\n return set;\n}", "function findMultiples(int,limit){\n //your code here\n let array = []\n for(i=1; i <= Math.floor(limit/int); i++) {\n array.push(int * i)\n }\n return array\n}", "function eulerProblem1(limit) {\n let sum = 0;\n let multiples = [];\n for (let i = 1; i < limit; i++) {\n if (i%3 === 0 || i%5 === 0) {\n multiples.push(i); // add the multiple to the array list\n sum += i;\n }\n }\n multiples.unshift(sum); // add solution to position 0\n return multiples;\n}", "function vinculum(number) {\n let numbersub = number;\n let num = number;\n let bararray = [];\n let romanNumeralStr = ''\n\n if (num < 1000) {\n romanNumeralStr += getRoman(num);\n }\n\n while (num > 999) {\n let barnum = 0;\n\n while (num > 999) {\n // Keep track of how many bars need to go over the number\n barnum++;\n num = Math.floor(num / 1000);\n if (num < 1000) {\n let tempStr = getRoman(num);\n romanNumeralStr = romanNumeralStr + tempStr\n let barlen = barnum - 1\n\n // The array holds the bars that go over the roman numerals.\n // The foor loop determines how many dashes are needed to go over the\n // roman numeral.\n for (let i = 0; i < barnum; i++) {\n let line = '-'\n let barstr = line.repeat(romanNumeralStr.length);\n if (bararray.length <= barlen) {\n bararray.push(barstr)\n } else {\n let tempstr = bararray[i]\n bararray[i] = tempstr + barstr;\n }\n }\n }\n }\n\n let total = Math.floor(num) * Math.pow(1000, barnum);\n let tempnum = numbersub - total;\n num = tempnum;\n\n if (num < 1000) {\n let tempStr = getRoman(num);\n romanNumeralStr = romanNumeralStr + tempStr\n }\n }\n\n // This loop puts bars over the roman numeral\n let barfinal = '';\n for (let i = bararray.length - 1; i > -1; i--) {\n barfinal += bararray[i] + '<br>';\n }\n\n romanNumeralStr\n return barfinal + romanNumeralStr;\n}", "function main() {\n let numerator = [3];\n let denominator = [2];\n let count = 0;\n for (let i = 1; i <= 1000; i += 1) {\n // console.log(numerator, denominator);\n let temp = carryForwardSum(numerator, denominator);\n numerator = carryForwardSum(temp, denominator);\n denominator = temp;\n temp = null;\n if (numerator.length > denominator.length) {\n count += 1;\n }\n }\n return count;\n}", "function resultant(major_generator, minor_generator) {\n\t// var major_generator = 7;\n\t// var minor_generator = 3;\n\n\tvar total_counts = major_generator * minor_generator;\n\tvar result_counter = 0;\n\tvar major_mod = 0;\n\tvar minor_mod = 0;\n\tvar i = 0;\n\tvar j = 0;\n\tvar resultant = [];\n\n\tconsole.log(\"Generator Total = %d \\n\", total_counts);\n\n\twhile (i < total_counts) {\n\t i++;\n\t result_counter++;\n\t major_mod = i % major_generator;\n\t minor_mod = i % minor_generator;\n\t if ((major_mod == 0) || (minor_mod == 0)) {\n\t\t resultant.push(result_counter);\n\t\t result_counter = 0;\n\t }\n\t console.log(\"%d \\n\", i);\n\t console.log(\"Modulus of %d is %d \\n\", major_generator, major_mod);\n\t console.log(\"Modulus of %d is %d \\n\", minor_generator, minor_mod);\n\t}\n\n\tconsole.log(\"\\n\");\n\tconsole.log(\"The resultant is \", resultant);\n\tconsole.log(\"The resultant length is \", resultant.length);\n\treturn resultant;\n}", "function solution(number) {\n // set minimum parameter of zero\n let total = 0\n // iterate through each number\n for (let i = 0; i < number; i++)\n // if statement\n // if a number less than 10 is not a muliple of 3 or 5\n if (i % 3 === 0 || i % 5 === 0) {\n // return total number of 3 or 5 mulpiples\n // no duplicates\n total += i\n }\n // total count\n return total;\n}", "function babbage() {\n const endDigits = 269696;\n let num = Math.ceil(Math.sqrt(endDigits));\n\n while (num * num % 1000000 !== endDigits) {\n num += 2;\n }\n\n return num;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render Initial Bookmarks Control
function controlRenderInitialBookMarks() { bookMarksView.render(model.state.bookmarks); }
[ "function bbedit_components_draw_menu() {}", "onRender() {}", "render() {\n if (this.selected) {\n // If selected, fill the note as such and ignore everything else.\n this.fill(SELECTED);\n this.opacity(1);\n } else {\n if (this.playing) {\n // If the note is playing, fill the note as such.\n this.fill(PLAYING);\n } else {\n // Otherwise, check if the note is suggested.\n if (this.suggested) {\n this.fill(SUGGESTED, true);\n } else {\n this.fill(NORMAL);\n }\n }\n // If the note is being hovered over, alter its opacity.\n if (this.hovered) {\n this.opacity(0.65);\n } else {\n this.opacity(1);\n }\n }\n }", "function view_setSortStateDirty() {\n\n $(\"#nameSortStateCaret\").html(dirtyCaret);\n $(\"#gradeSortStateCaret\").html(dirtyCaret);\n\n}", "function createFrontPainter(diy, sheet) {\n // Since the marker doesn't have any markup boxes or other objects\n // that need access to the sheet they are used on, we don't need to\n // do anything to set up for the marker, so when we're called the\n // second time to set up the marker we just return.\n if (sheet.sheetIndex == 2) return;\n\n // Create the markup boxes we'll use to display formatted text:\n\n // the character title (our name field)\n titleBox = Talisman.titleBox(sheet, true, 13);\n\n // the text of the special ability\n specialTextBox = Talisman.titleBox(sheet, false, 7.5);\n specialTextBox.setReplacementForTag(\n 'hr', '<image res://talisman/decorations/character-divider.png 1.853333in>'\n );\n specialTextBox.lineTightness = 1.5;\n specialTextBox.alignment = specialTextBox.LAYOUT_TOP | specialTextBox.LAYOUT_LEFT;\n\n // the starting location and alignment\n startBox = Talisman.bodyBox(sheet);\n}", "render() {\n // For example:\n // console.log('The object \"' + this.holder.id + '\" is ready');\n // this.holder.style.backgroundColor = this.options.color;\n // this.holder.innerHTML = 'Hello World!';\n }", "init() {\n this.drawAccountInfo();\n }", "render() {\n super.render();\n\n this.fieldset = this.innerWrapper.append( 'fieldset' );\n\n if ( this.layer.hasReviews ) {\n\n this.reviewInfo = this.fieldset.append( 'div' )\n .classed( 'hoot-form-field', true )\n .append( 'span' )\n .classed( '_icon info review-count', true )\n .text( `There are ${this.layer.reviewStats.unreviewedCount} reviews` );\n\n this.acceptAll = this.fieldset.append( 'div' )\n .classed( 'hoot-form-field', true )\n .append( 'a' )\n // .attr( 'href', '!#' )\n .text( 'Resolve all remaining reviews' )\n .on( 'click', () => {\n d3.event.stopPropagation();\n d3.event.preventDefault();\n\n this.conflicts.resolve.acceptAll( this.layer );\n } );\n\n this.conflicts.init( this.layer )\n .then( () => this.listen() );\n\n } else {\n this.reviewCompleteButtons();\n }\n }", "_setBookmark() {\n const { isLogged, type } = this._props;\n const {\n bookmarkLoggedinTemplate, bookmarkNotLoggedTemplate, bookmarkSavednewsTemplate, cardBookmark,\n } = this._blockElements;\n const bookmarkNode = this._domElement.querySelector(cardBookmark);\n let template;\n\n if (isLogged && type === 'main') {\n template = bookmarkLoggedinTemplate;\n } else if (!isLogged && type === 'main') {\n template = bookmarkNotLoggedTemplate;\n } else if (isLogged && type === 'saved') {\n template = bookmarkSavednewsTemplate;\n }\n\n const bookmarkElement = template.cloneNode(true).content;\n bookmarkNode.appendChild(bookmarkElement);\n }", "function initializeMarkingMenu() {\n\n\t//Unload Radial Menu\n\tvar radialMenuContainer = document.getElementById('radial-menu-container');\n\tif (radialMenuContainer != null) {\n\t\tradialMenuContainer.parentNode.removeChild(radialMenuContainer);\n\t}\n\n\t// Load Marking Menu\n\tvar interactionContainer = document.getElementById('interaction-container');\n\tif (markingMenuSubscription != null) {\n\t\tmarkingMenuSubscription.unsubscribe();\n\t}\n\tvar markingMenuContainer = document.getElementById('marking-menu-container');\n\tif (markingMenuContainer == null) {\n\t\tinteractionContainer.innerHTML += \"<div id=\\\"marking-menu-container\\\" style=\\\"height:100%;width:100%\\\" onmousedown=\\\"markingMenuOnMouseDown(event)\\\" oncontextmenu=\\\"preventRightClick(event)\\\"></div>\";\n\t}\n}", "renderedCallback() {\n if (this.initialRender) {\n if (!this.disableAutoScroll) {\n this.setAutoScroll();\n }\n }\n this.initialRender = false;\n }", "function init(){\n buildToolbar();\n initEditor();\n }", "function showBookShelf() {}", "positionMarkings() {}", "function JournalDisplay () {\n this._init ();\n}", "function setBook(bk, place, callback) {\n p.book = bk;\n var pageCount = 0;\n if (typeof callback == 'function') {\n var watchers = {\n 'monocle:componentchange': function (evt) {\n dispatchEvent('monocle:firstcomponentchange', evt.m);\n return (pageCount += 1) == p.flipper.pageCount;\n },\n 'monocle:componentfailed': function (evt) {\n fatalSystemMessage(k.LOAD_FAILURE_INFO);\n return true;\n },\n 'monocle:turn': function (evt) {\n deafen('monocle:componentfailed', listener);\n callback();\n return true;\n }\n }\n var listener = function (evt) {\n if (watchers[evt.type](evt)) { deafen(evt.type, listener); }\n }\n for (evtType in watchers) { listen(evtType, listener) }\n }\n p.flipper.moveTo(place || { page: 1 }, initialized);\n }", "function markModel(markMode, rectangle) {\n\n\n\n}", "function _renderBook(book) {\n\t\tbook.render(booksGrid);\n\t\t\n\t\t// Needs to bind the delete event after the buttons are appended to the DOM\n\t\tdeleteButton = document.querySelector('.btn-delete');\n\t\tdeleteButton.addEventListener('click', deleteBook);\n\t}", "render(){\n\t\tthis.loadStyle();\n\t\tthis.renderView();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a line for a commit contains, commit log, revision details, review state and action buttons TODO fusion with commits.js version
function createItem(revision) { var block = $('<div></div>').attr('class', 'commit-item2'); var actions = $('<div></div>'); var title = $('<div></div>') .text(revision.Message) .attr('class', 'commit-title2') .appendTo(block); $('<div></div>') .text("Revision : " + revision.Revision + " by " + revision.Author + " on " + revision.Timestamp) .attr('class', 'commit-subtitle') .appendTo(title); $('<div></div>') .attr('class', 'commit-annotation-summary') .append($('<span class="label label-primary"><i class="fa fa-eye"></i> ' + revision.NumberReviewers + ' </span>')) .append($('<span class="label label-success"><i class="fa fa-comment"></i> ' + revision.NumberComments + ' </span>')) .append($('<span class="label label-warning"><i class="fa fa-comments"></i> ' + revision.NumberReplies + ' </span>')) .append($('<span class="label label-danger"><i class="fa fa-heart"></i> ' + revision.NumberLikes + ' </span>')) .appendTo(block); if (revision.ApprovedBy) { $('<div></div>') .text('Cool! Approved by: ' + revision.ApprovedBy) .appendTo(actions); } else if (getUsername() !== revision.Author) { $('<button class="btn btn-success button-ok"><i class="fa fa-check"></i> Approve</button>').on('click', approveCommit).appendTo(actions); } actions.appendTo(block); block.on('click', { revision: revision.Revision }, openForReview); $('<div></div>').attr('class', 'commit-item-footer').appendTo(block); block.appendTo(insertPoint); }
[ "function formatCommitInfo( line ) {\n // Result is in format e.g. d748d93 1465819027 committer@email.com A commit message\n // First field is the truncated hash; second field is a unix timestamp (seconds\n // since epoch); third field is the committer email; subject is everything after.\n let fields = line.match(/^([0-9a-f]+)\\s+(\\d+)\\s+(\\S+)\\s+(.*)$/);\n if( fields ) {\n return {\n id: fields[1],\n commit: fields[1],\n date: new Date( Number( fields[2] ) * 1000 ),\n committer: fields[3],\n subject: fields[4]\n };\n }\n return false;\n}", "function get_msg(commit) {\n\n var msg = commit.author.name + \" <\" + commit.author.email + \">\\n\";\n msg += commit.url + \"\\n\\n\" + commit.message + \"\\n\\n\";\n\n commit.added.forEach(function (val) {\n msg += \"A\\t\" + val + \"\\n\";\n });\n commit.removed.forEach(function (val) {\n msg += \"D\\t\" + val + \"\\n\";\n });\n commit.modified.forEach(function (val) {\n msg += \"M\\t\" + val + \"\\n\";\n });\n\n return msg;\n}", "function reformatCommit (commit) {\n if (commit.committerDate) {\n commit.committerDate = dateFormat(commit.committerDate, 'yyyy-mm-dd', true);\n }\n var isReleaseCommit = commit.type === 'chore' && commit.scope === 'release';\n if (!isReleaseCommit) {\n return commit;\n }\n var affectedPackages = analyzer.getAffectedPackages(getAffectsLine(commit));\n var hasVersion = affectedPackages[0] &&\n tagging.getTagParts(affectedPackages[0]) &&\n tagging.getTagParts(affectedPackages[0]).version;\n\n if (!hasVersion) {\n return commit;\n }\n var newVersion = tagging.getTagParts(affectedPackages[0]).version;\n commit.version = newVersion;\n return commit;\n}", "_generateTagLine(newVersion, currentVersion) {\n if (this.repoUrl && Str.weaklyHas(this.repoUrl, 'github.com')) {\n return (`## [${newVersion}](${this.repoUrl}/compare/v${currentVersion}...v${newVersion}) - ` +\n `(${Moment().format('YYYY-MM-DD')})`)\n } else {\n return (`## ${newVersion} - (${Moment().format('YYYY-MM-D')}) `)\n }\n }", "function RepoCommit() {\n _classCallCheck(this, RepoCommit);\n\n RepoCommit.initialize(this);\n }", "prompter(cz, commit) {\n // console.log('\\nLine 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.\\n');\n console.log(\n '\\n1行目は100文字で切り取られ、超過分は次行以降に記載されます。\\n'\n );\n\n // Let's ask some questions of the user\n // so that we can populate our commit\n // template.\n //\n // See inquirer.js docs for specifics.\n // You can also opt to use another input\n // collection library if you prefer.\n cz.prompt([\n {\n type: 'list',\n name: 'type',\n message: 'コミットする変更タイプを選択:',\n choices: choicesPrefix\n },\n {\n type: 'input',\n name: 'scope',\n message:\n '変更内容のスコープ(例:コンポーネントやファイル名):(enterでスキップ)\\n'\n },\n {\n type: 'list',\n name: 'emoji',\n message: 'コミット内容に合うemojiを選択:',\n choices: choicesEmojiPrefix\n },\n {\n type: 'input',\n name: 'subject',\n message: '変更内容を要約した本質的説明:\\n'\n },\n {\n type: 'input',\n name: 'body',\n message: '変更内容の詳細:(enterでスキップ)\\n'\n },\n {\n type: 'confirm',\n name: 'isBreaking',\n message: '破壊的変更を含みますか?',\n default: false\n },\n {\n type: 'input',\n name: 'breaking',\n message: '破壊的変更についての記述:\\n',\n when(answers) {\n return answers.isBreaking;\n }\n },\n {\n type: 'confirm',\n name: 'isIssueAffected',\n message: 'issueに関連した変更ですか?',\n default: false\n },\n {\n type: 'input',\n name: 'issues',\n message: '関連issueを追記 (例:\"fix #123\", \"re #123\"):\\n',\n when(answers) {\n return answers.isIssueAffected;\n }\n }\n ]).then(answers => {\n const maxLineWidth = 100;\n\n const wrapOptions = {\n trim: true,\n newline: '\\n',\n indent: '',\n width: maxLineWidth\n };\n\n // parentheses are only needed when a scope is present\n let scope = answers.scope.trim();\n scope = scope ? `(${answers.scope.trim()})` : '';\n\n // Hard limit this line\n const head = `${answers.type}${scope}: :${\n answers.emoji\n }: ${answers.subject.trim()}`.slice(0, maxLineWidth);\n\n // Wrap these lines at 100 characters\n const body = wrap(answers.body, wrapOptions);\n\n // Apply breaking change prefix, removing it if already present\n let breaking = answers.breaking ? answers.breaking.trim() : '';\n breaking = breaking\n ? `BREAKING CHANGE: ${breaking.replace(/^BREAKING CHANGE: /, '')}`\n : '';\n breaking = wrap(breaking, wrapOptions);\n\n const issues = answers.issues ? wrap(answers.issues, wrapOptions) : '';\n\n const footer = filter([breaking, issues]).join('\\n\\n');\n\n commit(`${head}\\n\\n${body}\\n\\n${footer}`);\n console.log(`\n======================\n${head}\\n\\n${body}\\n\\n${footer}\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 }", "toString() {\n return `${changelogTitle}\n${changelogDescription}\n\n${stringifyReleases(this._releases, this._changes)}\n\n${stringifyLinkReferenceDefinitions(this._repoUrl, this._releases)}`;\n }", "function getHistoricalCommits() {\n return __awaiter(this, void 0, void 0, function* () {\n const projectDir = getProjectDir();\n if (!projectDir || !Util_1.isGitProject(projectDir)) {\n return null;\n }\n // get the repo url, branch, and tag\n const resourceInfo = yield getResourceInfo(projectDir);\n if (resourceInfo && resourceInfo.identifier) {\n const identifier = resourceInfo.identifier;\n const tag = resourceInfo.tag;\n const branch = resourceInfo.branch;\n const latestCommit = yield getLastCommit();\n let sinceOption = \"\";\n if (latestCommit) {\n // add a second\n const newTimestamp = parseInt(latestCommit.timestamp, 10) + 1;\n sinceOption = ` --since=${newTimestamp}`;\n }\n else {\n sinceOption = \" --max-count=50\";\n }\n const cmd = `git log --stat --pretty=\"COMMIT:%H,%ct,%cI,%s\" --author=${resourceInfo.email}${sinceOption}`;\n // git log --stat --pretty=\"COMMIT:%H, %ct, %cI, %s, %ae\"\n const resultList = yield GitUtil_1.getCommandResult(cmd, projectDir);\n if (!resultList) {\n // something went wrong, but don't try to parse a null or undefined str\n return null;\n }\n let commits = [];\n let commit = null;\n for (let i = 0; i < resultList.length; i++) {\n let line = resultList[i].trim();\n if (line && line.length > 0) {\n if (line.indexOf(\"COMMIT:\") === 0) {\n line = line.substring(\"COMMIT:\".length);\n if (commit) {\n // add it to the commits\n commits.push(commit);\n }\n // split by comma\n let commitInfos = line.split(\",\");\n if (commitInfos && commitInfos.length > 3) {\n let commitId = commitInfos[0].trim();\n if (latestCommit &&\n commitId === latestCommit.commitId) {\n commit = null;\n // go to the next one\n continue;\n }\n let timestamp = parseInt(commitInfos[1].trim(), 10);\n let date = commitInfos[2].trim();\n let message = commitInfos[3].trim();\n commit = {\n commitId,\n timestamp,\n date,\n message,\n changes: {},\n };\n }\n }\n else if (commit && line.indexOf(\"|\") !== -1) {\n // get the file and changes\n // i.e. backend/app.js | 20 +++++++++-----------\n line = line.replace(/ +/g, \" \");\n // split by the pipe\n let lineInfos = line.split(\"|\");\n if (lineInfos && lineInfos.length > 1) {\n let file = lineInfos[0].trim();\n let metricsLine = lineInfos[1].trim();\n let metricsInfos = metricsLine.split(\" \");\n if (metricsInfos && metricsInfos.length > 1) {\n let addAndDeletes = metricsInfos[1].trim();\n // count the number of plus signs and negative signs to find\n // out how many additions and deletions per file\n let len = addAndDeletes.length;\n let lastPlusIdx = addAndDeletes.lastIndexOf(\"+\");\n let insertions = 0;\n let deletions = 0;\n if (lastPlusIdx !== -1) {\n insertions = lastPlusIdx + 1;\n deletions = len - insertions;\n }\n else if (len > 0) {\n // all deletions\n deletions = len;\n }\n commit.changes[file] = {\n insertions,\n deletions,\n };\n }\n }\n }\n }\n }\n if (commit) {\n // add it to the commits\n commits.push(commit);\n }\n let commit_batch_size = 15;\n // send in batches of 15\n if (commits && commits.length > 0) {\n let batchCommits = [];\n for (let commit of commits) {\n batchCommits.push(commit);\n // if the batch size is greather than the theshold\n // send it off\n if (!Util_1.isBatchSizeUnderThreshold(batchCommits)) {\n // send off this set of commits\n let commitData = {\n commits: batchCommits,\n identifier,\n tag,\n branch,\n };\n yield sendCommits(commitData);\n batchCommits = [];\n }\n }\n // send the remaining\n if (batchCommits.length > 0) {\n let commitData = {\n commits: batchCommits,\n identifier,\n tag,\n branch,\n };\n yield sendCommits(commitData);\n batchCommits = [];\n }\n }\n // clear out the repo info in case they've added another one\n myRepoInfo = [];\n }\n /**\n * We'll get commitId, unixTimestamp, unixDate, commitMessage, authorEmail\n * then we'll gather the files\n * COMMIT:52d0ac19236ac69cae951b2a2a0b4700c0c525db, 1545507646, 2018-12-22T11:40:46-08:00, updated wlb to use local_start, xavluiz@gmail.com\n \n backend/app.js | 20 +++++++++-----------\n backend/app/lib/audio.js | 5 -----\n backend/app/lib/feed_helpers.js | 13 +------------\n backend/app/lib/sessions.js | 25 +++++++++++++++----------\n 4 files changed, 25 insertions(+), 38 deletions(-)\n */\n function sendCommits(commitData) {\n // send this to the backend\n HttpClient_1.softwarePost(\"/commits\", commitData, Util_1.getItem(\"jwt\"));\n }\n });\n}", "function InsertLine(context_) {\n td.lineState = 'true';\n td.lineCount = 0;\n // context_.actionContext.document.showMessage(\"Line drawn\");//debugging\n}", "function generateGitContent(data) {\n return (\n `\n## Github details\n${data.name} <br>\n[GitHub URL](${data.url}) <br>\n[Image URL](${data.image}) <br>\nEmail: ameliajanegoodson@gmail.com <br>\n\n`)\n}", "function parseChangelog({ changelogContent, repoUrl, }) {\n const changelogLines = changelogContent.split('\\n');\n const changelog = new changelog_1.default({ repoUrl });\n const unreleasedHeaderIndex = changelogLines.indexOf(`## [${constants_1.unreleased}]`);\n if (unreleasedHeaderIndex === -1) {\n throw new Error(`Failed to find ${constants_1.unreleased} header`);\n }\n const unreleasedLinkReferenceDefinition = changelogLines.findIndex((line) => {\n return line.startsWith(`[${constants_1.unreleased}]:`);\n });\n if (unreleasedLinkReferenceDefinition === -1) {\n throw new Error(`Failed to find ${constants_1.unreleased} link reference definition`);\n }\n const contentfulChangelogLines = changelogLines.slice(unreleasedHeaderIndex + 1, unreleasedLinkReferenceDefinition);\n let mostRecentRelease;\n let mostRecentCategory;\n let currentChangeEntry;\n /**\n * Finalize a change entry, adding it to the changelog.\n *\n * This is required because change entries can span multiple lines.\n *\n * @param options\n * @param options.removeTrailingNewline - Indicates that the trailing newline\n * is not a part of the change description, and should therefore be removed.\n */\n function finalizePreviousChange({ removeTrailingNewline = false, } = {}) {\n if (!currentChangeEntry) {\n return;\n }\n // This should never happen in practice, because `mostRecentCategory` is\n // guaranteed to be set if `currentChangeEntry` is set.\n /* istanbul ignore next */\n if (!mostRecentCategory) {\n throw new Error('Cannot finalize change without most recent category.');\n }\n if (removeTrailingNewline && currentChangeEntry.endsWith('\\n')) {\n currentChangeEntry = currentChangeEntry.slice(0, currentChangeEntry.length - 1);\n }\n changelog.addChange({\n addToStart: false,\n category: mostRecentCategory,\n description: currentChangeEntry,\n version: mostRecentRelease,\n });\n currentChangeEntry = undefined;\n }\n for (const line of contentfulChangelogLines) {\n if (line.startsWith('## [')) {\n const results = line.match(/^## \\[(\\d+\\.\\d+\\.\\d+)\\](?: - (\\d\\d\\d\\d-\\d\\d-\\d\\d))?(?: \\[(\\w+)\\])?/u);\n if (results === null) {\n throw new Error(`Malformed release header: '${truncated(line)}'`);\n }\n // Trailing newline removed because the release section is expected to\n // be prefixed by a newline.\n finalizePreviousChange({\n removeTrailingNewline: true,\n });\n mostRecentRelease = results[1];\n mostRecentCategory = undefined;\n const date = results[2];\n const status = results[3];\n changelog.addRelease({\n addToStart: false,\n date,\n status,\n version: mostRecentRelease,\n });\n }\n else if (line.startsWith('### ')) {\n const results = line.match(/^### (\\w+)$\\b/u);\n if (results === null) {\n throw new Error(`Malformed category header: '${truncated(line)}'`);\n }\n const isFirstCategory = mostRecentCategory === null;\n finalizePreviousChange({\n removeTrailingNewline: !isFirstCategory,\n });\n if (!isValidChangeCategory(results[1])) {\n throw new Error(`Invalid change category: '${results[1]}'`);\n }\n mostRecentCategory = results[1];\n }\n else if (line.startsWith('- ')) {\n if (!mostRecentCategory) {\n throw new Error(`Category missing for change: '${truncated(line)}'`);\n }\n const description = line.slice(2);\n finalizePreviousChange();\n currentChangeEntry = description;\n }\n else if (currentChangeEntry) {\n currentChangeEntry += `\\n${line}`;\n }\n else if (line === '') {\n continue;\n }\n else {\n throw new Error(`Unrecognized line: '${truncated(line)}'`);\n }\n }\n // Trailing newline removed because the reference link definition section is\n // expected to be separated by a newline.\n finalizePreviousChange({ removeTrailingNewline: true });\n return changelog;\n}", "function createCreditNoteDetailLine()\n{\n\ttry\n\t{\n\t\t// create credit note line\n\t\tcreditNoteRecord.selectNewLineItem('item');\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'item', COMMISSIONITEMINTID); \n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'amount', comTotal);\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'taxcode', TAXINTID);\n\t\tcreditNoteRecord.commitLineItem('item');\n\t\t\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createCreditNoteDetailLine\", e);\t\t\t\t\n\t} \n\n}", "function iglooRevision () {\n\t// Content detail\n\tthis.user = ''; // the user who made this revision\n\tthis.page = ''; // the page title that this revision belongs to\n\tthis.pageTitle = ''; // also the page title that this revision belongs to\n\tthis.namespace = 0;\n\tthis.revId = 0; // the ID of this revision (the diff is between this and oldId)\n\tthis.oldId = 0; // the ID of the revision from which this was created\n\tthis.type = 'edit';\n\t\n\tthis.revisionContent = ''; // the content of the revision\n\tthis.diffContent = ''; // the HTML content of the diff\n\tthis.revisionRequest = null; // the content request for this revision.\n\tthis.diffRequest = null; // the diff request for this revision\n\tthis.revisionLoaded = false; // there is content stored for this revision\n\tthis.diffLoaded = false; // there is content stored for this diff\n\t\n\tthis.displayRequest = false; // diff should be displayed when its content next changes\n\tthis.page = null; // the iglooPage object to which this revision belongs\n\t\n\t// Constructor\n\tif (arguments[0]) {\n\t\tthis.setMetaData(arguments[0]);\n\t}\n}", "function git_commit_hash () {\n if (!_HASH) {\n var start = process.cwd(); // get current working directory\n process.chdir(get_base_path()); // change to project root\n var cmd = 'git rev-parse HEAD'; // create name.zip from cwd\n var hash = exec_sync(cmd); // execute command synchronously\n process.chdir(start); // change back to original directory\n _HASH = hash.replace('\\n', ''); // replace the newline\n }\n return _HASH;\n}", "function Commit(repository, obj) {\n this.repository = repository;\n obj.author = new Signature(obj.author);\n obj.committer = new Signature(obj.committer);\n _immutable(this, obj).set(\"id\").set(\"tree\", \"treeId\").set(\"parents\").set(\"message\").set(\"messageEncoding\").set(\"author\").set(\"committer\");\n }", "function check_rev_comment(lines) {\n console.log(lines);\n var title = lines[0];\n // check title\n console.log(\">> checking title line:\" + title);\n if (check_rev_titile(title) != 0) {\n console.log(\">> Title check failed\");\n core.setFailed(\"Title check failed:\" + title);\n return 1;\n } else {\n console.log(\">> Title is OK!\");\n }\n\n // check for mandatory fields\n console.log(\">> checking mandatory fields!\");\n var mand_fields = ['Summary:', 'Test Plan:', 'Reviewed-by:', 'Issue:'];\n mand_fields.forEach(mf => {\n if (lines.find(l => l.startsWith(mf)) == undefined) {\n console.log(\"Missing mandatory field:\" + mf);\n core.setFailed(\"Missing mandatory field '\" + mf + \"' in git log\");\n return 1;\n }\n });\n console.log(\">> All mandatory fields are present\");\n return 0;\n}", "function LineColComponent(props) {\n const translator = props.translator || nullTranslator;\n const trans = translator.load('jupyterlab');\n return (React.createElement(TextItem, { onClick: props.handleClick, source: trans.__('Ln %1, Col %2', props.line, props.column), title: trans.__('Go to line number…') }));\n}", "function lineDataToTableRow(line) {\n\t\t// Input variables\n\t\tconst sequence = line[0];\n\t\tconst flags = line[1];\n\t\tconst timestamp = line[2];\n\t\tconst payload = line.slice(3);\n\t\tconst type = flags & Flags.TYPE_MASK;\n\t\t\n\t\t// Output variables\n\t\tvar who = \"\\u25CF\"; // Type string\n\t\tvar nameColor = null; // Type string/null\n\t\tvar lineElems = []; // Type list<HTMLElement>\n\t\tvar quoteText = null; // Type string/null\n\t\tvar tr = document.createElement(\"tr\");\n\t\t\n\t\t// Take action depending on head of payload\n\t\tif (type == Flags.PRIVMSG) {\n\t\t\twho = payload[0];\n\t\t\tnameColor = nickColorModule.getNickColor(who);\n\t\t\tvar s = payload[1];\n\t\t\tvar mematch = formatTextModule.matchMeMessage(s);\n\t\t\tif (mematch != null)\n\t\t\t\ts = mematch[1];\n\t\t\t\n\t\t\tif ((flags & Flags.OUTGOING) != 0)\n\t\t\t\ttr.classList.add(\"outgoing\");\n\t\t\tif ((flags & Flags.NICKFLAG) != 0)\n\t\t\t\ttr.classList.add(\"nickflag\");\n\t\t\tquoteText = formatTextModule.fancyToPlainText(s.replace(/\\t/g, \" \"));\n\t\t\tlineElems = formatTextModule.fancyTextToElems(s);\n\t\t\tif (mematch != null) {\n\t\t\t\ttr.classList.add(\"me-action\");\n\t\t\t\tquoteText = \"* \" + who + \" \" + quoteText;\n\t\t\t} else {\n\t\t\t\tquoteText = \"<\" + who + \"> \" + quoteText;\n\t\t\t}\n\t\t\t\n\t\t} else if (type == Flags.NOTICE) {\n\t\t\tif ((flags & Flags.OUTGOING) != 0)\n\t\t\t\ttr.classList.add(\"outgoing\");\n\t\t\twho = \"(\" + payload[0] + \")\";\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[1]);\n\t\t} else if (type == Flags.NICK) {\n\t\t\tlineElems.push(textNode(payload[0] + \" changed their name to \" + payload[1]));\n\t\t\ttr.classList.add(\"nick-change\");\n\t\t} else if (type == Flags.JOIN) {\n\t\t\twho = \"\\u2192\"; // Rightwards arrow\n\t\t\tlineElems.push(textNode(payload[0] + \" joined the channel\"));\n\t\t\ttr.classList.add(\"user-enter\");\n\t\t} else if (type == Flags.PART) {\n\t\t\twho = \"\\u2190\"; // Leftwards arrow\n\t\t\tlineElems.push(textNode(payload[0] + \" left the channel\"));\n\t\t\ttr.classList.add(\"user-exit\");\n\t\t} else if (type == Flags.QUIT) {\n\t\t\twho = \"\\u2190\"; // Leftwards arrow\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[1]);\n\t\t\tlineElems.splice(0, 0, textNode(payload[0] + \" has quit: \"));\n\t\t\ttr.classList.add(\"user-exit\");\n\t\t} else if (type == Flags.KICK) {\n\t\t\twho = \"\\u2190\"; // Leftwards arrow\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[2]);\n\t\t\tlineElems.splice(0, 0, textNode(payload[0] + \" was kicked by \" + payload[1] + \": \"));\n\t\t\ttr.classList.add(\"user-exit\");\n\t\t} else if (type == Flags.TOPIC) {\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[1]);\n\t\t\tlineElems.splice(0, 0, textNode(payload[0] + \" set the channel topic to: \"));\n\t\t} else if (type == Flags.INITNOTOPIC) {\n\t\t\tlineElems.push(textNode(\"No channel topic is set\"));\n\t\t} else if (type == Flags.INITTOPIC) {\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[0]);\n\t\t\tlineElems.splice(0, 0, textNode(\"The channel topic is: \"));\n\t\t} else if (type == Flags.SERVERREPLY) {\n\t\t\tlineElems = formatTextModule.fancyTextToElems(payload[1]);\n\t\t} else if (type == Flags.NAMES) {\n\t\t\tconst ABBREVIATE_NAMES_LIMIT = 15;\n\t\t\tvar text = textNode(\"Users in channel: \" + payload.slice(0, ABBREVIATE_NAMES_LIMIT).join(\", \"));\n\t\t\tlineElems.push(text);\n\t\t\tif (payload.length > ABBREVIATE_NAMES_LIMIT) {\n\t\t\t\ttext.data += \", \";\n\t\t\t\tvar moreText = \"(... \" + (payload.length - ABBREVIATE_NAMES_LIMIT) + \" more members ...)\";\n\t\t\t\tvar moreElem = utilsModule.createElementWithText(\"a\", moreText);\n\t\t\t\tmoreElem.onclick = function() {\n\t\t\t\t\ttext.data = \"Users in channel: \" + payload.join(\", \");\n\t\t\t\t\tmoreElem.parentNode.removeChild(moreElem);\n\t\t\t\t};\n\t\t\t\tlineElems.push(moreElem);\n\t\t\t}\n\t\t\ttr.classList.add(\"user-list\");\n\t\t} else if (type == Flags.MODE) {\n\t\t\tlineElems.push(textNode(payload[0] + \" set mode \" + payload[1]));\n\t\t\ttr.classList.add(\"mode-change\");\n\t\t} else if (type == Flags.CONNECTING) {\n\t\t\tvar str = \"Connecting to server at \" + payload[0] + \", port \" + payload[1] + \", \" + (payload[2] ? \"SSL\" : \"no SSL\") + \"...\";\n\t\t\tlineElems.push(textNode(str));\n\t\t} else if (type == Flags.CONNECTED) {\n\t\t\tlineElems.push(textNode(\"Socket opened to IP address \" + payload[0]));\n\t\t} else if (type == Flags.DISCONNECTED) {\n\t\t\tlineElems.push(textNode(\"Disconnected from server\"));\n\t\t} else {\n\t\t\twho = \"RAW\";\n\t\t\tlineElems.push(textNode(\"flags=\" + flags + \" \" + payload.join(\" \")));\n\t\t}\n\t\t\n\t\t// Make timestamp cell\n\t\tvar td = utilsModule.createElementWithText(\"td\", formatDate(timestamp));\n\t\ttr.appendChild(td);\n\t\t\n\t\t// Make nickname cell\n\t\ttd = utilsModule.createElementWithText(\"td\", who);\n\t\tif (who != \"\\u25CF\" && who != \"\\u2190\" && who != \"\\u2192\" && who != \"RAW\")\n\t\t\ttd.oncontextmenu = menuModule.makeOpener([[\"Open PM window\", function() { self.openPrivateMessagingWindow(who, null); }]]);\n\t\tif (nameColor != null)\n\t\t\ttd.style.color = nameColor;\n\t\ttr.appendChild(td);\n\t\t\n\t\t// Make message cell and its sophisticated context menu\n\t\ttd = document.createElement(\"td\");\n\t\tlineElems.forEach(function(elem) {\n\t\t\ttd.appendChild(elem);\n\t\t});\n\t\tvar menuItems = [[\"Quote text\", null]];\n\t\tif (quoteText != null) {\n\t\t\tmenuItems[0][1] = function() {\n\t\t\t\tinputBoxModule.putText(quoteText, true);\n\t\t\t};\n\t\t}\n\t\tmenuItems.push([\"Mark read to here\", function() {\n\t\t\tif (tr.classList.contains(\"read\") && !confirm(\"Do you want to move mark upward?\"))\n\t\t\t\treturn;\n\t\t\tnetworkModule.sendAction([[\"mark-read\", self.activeWindow[0], self.activeWindow[1], sequence + 1]], null);\n\t\t\telemId(\"messages-scroller\").focus();\n\t\t}]);\n\t\tmenuItems.push([\"Clear to here\", function() {\n\t\t\tif (confirm(\"Do you want to clear text?\"))\n\t\t\t\tnetworkModule.sendAction([[\"clear-lines\", self.activeWindow[0], self.activeWindow[1], sequence + 1]], null);\n\t\t\telemId(\"messages-scroller\").focus();\n\t\t}]);\n\t\ttd.oncontextmenu = menuModule.makeOpener(menuItems);\n\t\ttr.appendChild(td);\n\t\t\n\t\t// Finishing touches\n\t\tvar isRead = sequence < windowData[self.activeWindow[2]].markedReadUntil;\n\t\ttr.classList.add(isRead ? \"read\" : \"unread\");\n\t\treturn tr;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the pandoc AST generated from the file tokens and the converter options
getPandocAst() { return tokens && markdownItPandocRenderer(tokens, this.converter.options); }
[ "generate() {\n var ast = this.ast;\n\n this.print(ast);\n this.catchUp();\n\n return {\n code: this.buffer.get(this.opts),\n tokens: this.buffer.tokens,\n directives: this.directives\n };\n }", "function generateDocumentation(fileNames, options) {\n // Build a program using the set of root file names in fileNames\n //console.log('generateDocumentation')\n var program = ts.createProgram(fileNames, options);\n // Get the checker, we will use it to find more about classes\n var checker = program.getTypeChecker();\n \n var output = [];\n // Visit every sourceFile in the program\n for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {\n var sourceFile = _a[_i];\n if (!sourceFile.isDeclarationFile) {\n // Walk the tree to search for classes\n ts.forEachChild(sourceFile, visit);\n }\n }\n // print out the doc\n fs.writeFileSync(\"./classes_test.json\", JSON.stringify(output, undefined, 4));\n return;\n /** visit nodes finding exported classes */\n function visit(node) {\n //console.log(node.name)\n // Only consider exported nodes\n if (!isNodeExported(node)) {\n return;\n }\n if(ts.isEnumDeclaration(node) && node.name.text){\n \n output.push(serializeEnum(node));\n\n }else if (ts.isInterfaceDeclaration(node)){\n\n //var symbol = checker.getSymbolAtLocation(node.name);\n output.push(serializeEnum(node));\n // console.log(\"isInterfaceDeclaration\", node.name)\n\n }else if (ts.isClassDeclaration(node) && node.name) {\n // This is a top level class, get its symbol symbol.members\n var symbol = checker.getSymbolAtLocation(node.name);\n if (symbol) {\n output.push(serializeClass(symbol));\n }\n // No need to walk any further, class expressions/inner declarations\n // cannot be exported\n }\n else if (ts.isModuleDeclaration(node)) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n }\n /** Serialize a symbol into a json object */\n function serializeSymbol(symbol) {\n //getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;\n var name009 = checker.getTypeOfSymbolAtLocation(symbol,symbol.valueDeclaration)//: string;\n\n // const kind = symbol.valueDeclaration ? symbol.valueDeclaration.kind : undefined\n var test = checker.getDefaultFromTypeParameter(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n \n var type = checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n var name = symbol.getName()\n if(name===\"idgen\"){\n type = JSON.parse(type)\n }\n\n //add optional value \n if(symbol.valueDeclaration ){\n if(symbol.valueDeclaration.questionToken){\n type = [ 'Optional', type ]\n }else if (symbol.valueDeclaration.initializer){\n //array of litteralexpression\n //var ss = checker.getTypeFromTypeNode(symbol.valueDeclaration.initializer)\n //var startV = checker.typeToString(symbol.valueDeclaration.initializer)\n\n }\n }\n\n \n\n // var checker.isOptionalParameter(node: ParameterDeclaration);\n\n //var opt = checker.isOptionalParameter(symbol.valueDeclaration);\n\n return {\n name: name,\n type: type//checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))\n };\n }\n\n function serializeEnum(node){\n var details = {\"@type\":\"Enum\", \"@id\":node.name.text}\n const members = node.members;\n\n node.members.forEach((value)=>{\n var {name, type} = serializeSymbol(value.symbol)\n details[name] = type\n \n })\n return details\n }\n /** Serialize a class symbol information */\n function serializeClass(symbol) {\n \n var classDetails = serializeSymbol(symbol);\n var details = {'@id':classDetails.name, '@type':classDetails.type}\n //var prop ={}\n \n symbol.members.forEach((value)=>{\n var {name, type} = serializeSymbol(value)\n var typeValue = //classDetails.name\n details[name] = type\n \n })//.forEachChild(serializeSymbol)\n \n var parentType = symbol.valueDeclaration.parent.classifiableNames\n \n if(parentType.has(\"WoqlDocument\")){\n details[\"@type\"] = 'Document'\n }\n\n \n //details.properties = prop\n \n // Get the construct signatures\n var constructorType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);\n // var te= constructorType.getConstructSignatures()\n /*details.constructors = constructorType\n .getConstructSignatures()\n .map(serializeSignature);*/\n return details;\n }\n /** Serialize a signature (call or construct) */\n function serializeSignature(signature) {\n return {\n parameters: signature.parameters.map(serializeSymbol),\n returnType: checker.typeToString(signature.getReturnType()),\n //documentation: ts.displayPartsToString(signature.getDocumentationComment(checker))\n };\n }\n /** True if this is visible outside this file, false otherwise */\n function isNodeExported(node) {\n return ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0 ||\n (!!node.parent && node.parent.kind === ts.SyntaxKind.SourceFile));\n }\n}", "cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }", "_generate(ast) {}", "function generar_docs() {\n return src(\"./scss/styles.scss\")\n .pipe(sassdoc(doc_options));\n}", "function copy(){\n var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;\n \n return function copyParser(input){\n lexical = _lexical;\n cc = _cc.concat([]); // copies the array\n column = indented = 0;\n tokens = tokenizeCSharp(input, _tokenState);\n return parser;\n };\n }", "function buildDoc(cb) {\n spawn.sync(\"jsdoc\", [\"-r\", \"-c\", \"./.jsdoc.json\", \"-d\", \"./docs\", \"./src\"]);\n cb();\n}", "function styleguide() {\n\t// list templates\n\treturn src(paths.views.index.src)\n\t\t.pipe(plumber())\n\t\t.pipe(data(() => JSON.parse(fs.readFileSync(`${paths.data.temp}${paths.data.file}`))))\n\t\t.pipe(pug({\n\t\t\tpretty: true,\n\t\t\tbasedir: 'src'\n\t\t}))\n\t\t.pipe(lec({\n\t\t\teolc: 'CRLF'\n\t\t}))\n\t\t.pipe(dest(paths.views.index.dest))\n}", "function convert_docx_to_html(file) {\n let output = 'html.html'\n execSync(`pandoc ${file} -o ${output} --extract-media=.`)\n console.info(\"Converted docx file to HTML\")\n return output\n}", "get parser() {\n return this.p.parser\n }", "tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.start, to: this.pos,\n text: this.state.sliceDoc(token.start, this.pos),\n type: token.type } : null;\n }", "tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }", "function captureTomDoc(comments) {// collect lines up to first paragraph break\n const lines = [];for (let i = 0; i < comments.length; i++) {const comment = comments[i];if (comment.value.match(/^\\s*$/)) break;lines.push(comment.value.trim());} // return doctrine-like object\n const statusMatch = lines.join(' ').match(/^(Public|Internal|Deprecated):\\s*(.+)/);if (statusMatch) {return { description: statusMatch[2], tags: [{ title: statusMatch[1].toLowerCase(), description: statusMatch[2] }] };}}", "getMarkdownsFromDir() {\n const requireContext = require.context(\"./events/\", true, /(.*)\\.md/);\n return requireContext.keys().map((fileName) => {\n const file = fileName.split(\".\")[1].replace(\"/\", \"\");\n const mdContent = require(`./events/${file}.md`).default;\n\n return {\n file,\n content: mdContent,\n };\n });\n }", "function normalizeOptions(code, opts, tokens) {\n var style = \" \";\n if (code && typeof code === \"string\") {\n var indent = (0, _detectIndent2.default)(code).indent;\n if (indent && indent !== \" \") style = indent;\n }\n\n var format = {\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n shouldPrintComment: opts.shouldPrintComment,\n retainLines: opts.retainLines,\n comments: opts.comments == null || opts.comments,\n compact: opts.compact,\n minified: opts.minified,\n concise: opts.concise,\n quotes: opts.quotes || findCommonStringDelimiter(code, tokens),\n indent: {\n adjustMultilineComment: true,\n style: style,\n base: 0\n }\n };\n\n if (format.minified) {\n format.compact = true;\n\n format.shouldPrintComment = format.shouldPrintComment || function () {\n return format.comments;\n };\n } else {\n format.shouldPrintComment = format.shouldPrintComment || function (value) {\n return format.comments || value.indexOf(\"@license\") >= 0 || value.indexOf(\"@preserve\") >= 0;\n };\n }\n\n if (format.compact === \"auto\") {\n format.compact = code.length > 100000; // 100KB\n\n if (format.compact) {\n console.error(\"[BABEL] \" + messages.get(\"codeGeneratorDeopt\", opts.filename, \"100KB\"));\n }\n }\n\n if (format.compact) {\n format.indent.adjustMultilineComment = false;\n }\n\n return format;\n}", "function WordParser () {}", "function buildTree(targetPath) {\n log.info('Building documentation tree');\n\n var tree = processDirectory(targetPath);\n\n log.info('Processed directories: %d', processedDirectories);\n log.info('Processed documents: %d', processedDocuments);\n\n if(!tree.hasIndex) {\n log.warn('Documentation tree has no root index.md');\n\n //create empty index\n tree.hasIndex = true;\n tree.documents.push({\n id: tree.id,\n name: 'index',\n meta: {},\n content: ''\n });\n }\n\n return tree;\n}", "function makepot(options, callback) {\n var dir = options.dir;\n if (options.verbose) {\n config.verbose = options.verbose; \n }\n var list = [ ];\n walk(dir, function(error, files) {\n try {\n if (error) throw error;\n \n for (var i = 0; i < files.length; i++) {\n if (path.extname(files[i]) == \".php\") {\n var php = fs.readFileSync(files[i], 'utf-8');\n var data = extract(php);\n if (config.verbose) {\n console.log(\"Found \" + data.length + \" hits in \" + files[i]);\n }\n var result = {\n hits: data.length,\n file: files[i],\n data: data\n };\n if (result.hits > 0) {\n list.push(result);\n }\n }\n }\n \n var result = {\n data: list,\n pot: [ ]\n };\n \n var g = group(list);\n var keys = Object.keys(g);\n for (var i = 0; i < keys.length; i++) {\n var pot = convert(g[keys[i]]);\n result.pot.push({\n name: keys[i],\n content: pot\n });\n }\n \n if (typeof callback == \"function\") {\n callback(null, result);\n }\n }\n catch (e) {\n if (config.verbose) {\n console.error(e);\n }\n \n if (typeof callback == \"function\") {\n callback(e);\n }\n }\n });\n}", "function buildDocsEntry() {\n const output = join('docs/src/docs-entry.js');\n const getName = fullPath => fullPath.replace(/(\\/README)|(\\.md)/g, '').split('/').pop();\n const docs = glob\n .sync([\n join('docs/**/*.md'),\n join('packages/**/*.md'),\n '!**/node_modules/**'\n ])\n .map(fullPath => {\n const name = getName(fullPath);\n return `'${name}': () => import('${path.relative(join('docs/src'), fullPath)}')`;\n });\n\n const content = `${tips}\nexport default {\n ${docs.join(',\\n ')}\n};\n`;\n fs.writeFileSync(output, content);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Code Example 8.18 Return an array of File objects for a given Folder argument.
function getFilesForFolder(folder) { var fileIt = folder.getFiles(), file, files = []; while(fileIt.hasNext()) { file = fileIt.next(); files.push(file); } return files; }
[ "getFiles(dir) {\n return (new fs.Dir(this.dst, dir)).files;\n }", "function LerArquivos(folderPath) {\n fs.readdirSync(folderPath).forEach(file => {\n console.log(file);\n });\n}", "async getFolderChildren(params) {\n const folderId = params.parentId;\n const response = await ApiMiddleware.getData(\n ANCHOR.CONTRACT_FOLDERS + `/${folderId}`\n );\n\n if (!response.body.files) {\n return [];\n }\n\n const elements = [];\n response.body.files.map(item => {\n let newItem;\n if (item.contentType === \"system/folder\") {\n newItem = new ContractFolderModel(\n item.id,\n item.parentFileId,\n item.name,\n item.dateModification || item.dateCreation,\n item.creePar\n );\n } else {\n const downloadLink = `${API.API_URL}${\n ANCHOR.CONTRACT_FOLDERS\n }/${folderId}/file/${item.id}`;\n newItem = new ContractFileModel(\n item.id,\n item.parentFileId,\n item.name,\n downloadLink,\n item.dateModification || item.dateCreation,\n item.creePar\n );\n }\n elements.push(newItem);\n return null;\n });\n\n return elements;\n }", "LoadFolder(folder) {\n return __awaiter(this, void 0, void 0, function* () {\n this.ClearMain(); //Clear all current folders and files\n this.ClearSideBar(); //Clear the sidebar\n const childFolders = yield this.Api.GetChildFolders(folder);\n const childFiles = yield this.Api.GetChildFiles(folder);\n let folderParseErrorCount = 0;\n let fileParseErrorCount = 0;\n //Load folders first\n for (const folder_ of childFolders) {\n if (folder_ instanceof CloudFolder === false) {\n folderParseErrorCount++;\n continue;\n }\n this.AddFolderToMain(folder_, true);\n this.AddFolderToSidebar(folder_, true);\n }\n //Load files\n for (const file_ of childFiles) {\n if (file_ instanceof CloudFile === false) {\n fileParseErrorCount++;\n continue;\n }\n this.AddFileToMain(file_, true);\n }\n if (folderParseErrorCount !== 0)\n this.DisplayMessage(`An error occured while parsing the folder. (${folderParseErrorCount}x)`, AlertStyle.Danger);\n if (fileParseErrorCount !== 0)\n this.DisplayMessage(`An error occured while parsing the file. (${fileParseErrorCount}x)`, AlertStyle.Danger);\n this.Current = folder;\n if (childFolders.length !== 0) {\n //Displays in which folder the user is currently in\n $(\"#fm-sb-folders\").find(`div[data-folder-id'${folder.elementId}']`).addClass(\"fm-sb-folders-current\"); //undefined is not a function\n }\n if (childFiles.length !== 0) {\n //Do nothing\n }\n if (childFiles.length === 0 && childFolders.length === 0) { //If there's nothing in the folder.\n if (folder.elementId === \"root\")\n this.DisplayMessage(\"Welcome ! This is your root folder. Drag some files here to upload them or create a folder by clicking the + button.\", AlertStyle.Success);\n else\n this.DisplayMessage(\"This folder is empty.\", AlertStyle.Info);\n }\n });\n }", "_retrieveTestReportFiles(root) {\n const traverseFile = (file, jsonFiles) => {\n if (file.type === 'file' && file.name.indexOf('.json') > 0) {\n jsonFiles.push(file.url);\n }\n else if (file.files) {\n for (let i = 0; i < file.files.length; i++) {\n traverseFile(file.files[i], jsonFiles);\n }\n }\n return jsonFiles;\n }\n return traverseFile(root, []);\n }", "function getShapeFiles(directory, callback){\n var shapeFiles = [];\n fs.readdir(directory, function(err, files){\n if (err) {\n console.log(\"Error: \", err);\n callback(err, null);\n }\n else{\n files.forEach(function(file, index){\n\n if(path.extname(file) == \".shp\") {\n shapeFiles.push(file);\n }\n });\n callback(null, shapeFiles);\n }\n });\n\n}", "async function discoverFiles (directory, ext, searchSubDirectories = true) {\n\n\tconst fileList = [];\n\tconst items = await this.listDirectory(directory);\n\tconst directoryList = [];\n\tconst regexp = new RegExp(`.${ext}$`, `i`);\n\n\t// Add all the files and remember the directories for recursion later.\n\tfor (const item of items) {\n\t\tconst itemAbsolute = path.join(directory, item);\n\t\tconst isDir = (searchSubDirectories ? await this.isDirectory(itemAbsolute) : false); // eslint-disable-line no-await-in-loop\n\n\t\tif (isDir) { directoryList.push(itemAbsolute); }\n\t\telse if (itemAbsolute.match(regexp)) { fileList.push(itemAbsolute); }\n\t}\n\n\t// Recursively get all the files from each of the subdirectories.\n\tfor (const dir of directoryList) {\n\t\tconst subFiles = await this.discoverFiles(dir, ext, searchSubDirectories); // eslint-disable-line no-await-in-loop\n\t\tfileList.push(...subFiles);\n\t}\n\n\treturn fileList;\n\n}", "function getFileListing(basePath, testPath, dir, srvScope)\n{\n var uri = getResolvedURI(basePath);\n var chromeDir = getChromeDir(uri);\n //chromeDir.appendRelativePath(dir);\n //basePath += '/' + dir;\n\n var ioSvc = Components.classes[\"@mozilla.org/network/io-service;1\"].\n getService(Components.interfaces.nsIIOService);\n var testsDirURI = ioSvc.newFileURI(chromeDir);\n var testsDir = ioSvc.newURI(testPath, null, testsDirURI)\n .QueryInterface(Components.interfaces.nsIFileURL).file;\n\n var singleTestPath;\n if (testPath != undefined) {\n var extraPath = testPath;\n \n var fileNameRegexp = /(browser|test)_.+\\.(xul|html|js)$/;\n\n // Invalid testPath...\n if (!testsDir.exists())\n return [];\n\n if (testsDir.isFile()) {\n if (fileNameRegexp.test(testsDir.leafName))\n var singlePath = basePath + '/' + testPath;\n var links = {};\n links[singlePath] = true;\n return [links, null];\n\n // We were passed a file that's not a test...\n return [];\n }\n\n // otherwise, we were passed a directory of tests\n basePath += \"/\" + testPath;\n }\n var [links, count] = srvScope.list(basePath, testsDir, true);\n return [links, null];\n}", "getFiles(id) {\r\n return this.drive.files.get({ fileId: id });\r\n }", "function readAll(startPath,filter){\n let jsonContent, contents;\n\n if (!fs.existsSync(startPath)){\n console.log(\"no dir \",startPath);\n return;\n }\n\n var files=fs.readdirSync(startPath);\n for(var i=0;i<files.length;i++){\n var filename=path.join(startPath,files[i]);\n var stat = fs.lstatSync(filename);\n if (stat.isDirectory()){\n readAll(filename,filter); //recurse\n }\n else if (filename.indexOf(filter)>=0) {\n contents = fs.readFileSync(filename);\n // Define to JSON type\n jsonContent = JSON.parse(contents);\n studentArray.push(sanitizeJSON(jsonContent));\n };\n };\n}", "function _getSampleTestFiles () {\n return [{\n path: path.join(testSuitesRelativePath, 'test-txt.txt'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-txt.txt'))\n }, {\n path: path.join(testSuitesRelativePath, 'test-tsv.tsv'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-tsv.tsv'))\n }, {\n path: path.join(testSuitesRelativePath, 'test-html.xhtml'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-html.xhtml'))\n }, {\n path: path.join(testSuitesRelativePath, 'resources.txt'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'resources.txt'))\n }, {\n path: path.join(FRAMEWORK_NAME, 'arguments.txt'),\n contents: Assets.getText(path.join('sample-tests', 'arguments.txt')) \n }];\n }", "function listCall(path, refreshCallback){\n\n\tMeteor.call(\"listContents\", path, \"d\", function(error, result){\n\t if(error){\n\t console.log(error.reason);\n\t return;\n\t }\n\t Session.set(\"folderArr\", result.split('\\n'));\n\t Meteor.call(\"listContents\", path, \"f\", function(error, result){\n\t if(error){\n\t console.log(error.reason);\n\t return;\n\t }\n\t Session.set(\"fileArr\", result.split('\\n'));\n\t refreshCallback();\n\t });\n\t});\n}", "function displayFolderContent(folderElement) {\n var contentDiv = clearAndReturnContentDiv();\n var folderContent = fileSystem.sortFolderContent(folderElement.children);\n for (var i = 0; i < folderContent.length; i++) {\n var contentItem = $(\"<div data-id='\" + folderContent[i].id + \"'><div>\" + folderContent[i].name + \"</div></div>\");\n contentItem.addClass(\"contentItem\");\n contentItem.contextmenu(function (event) {\n showContextMenu(event);\n return false;\n });\n if (fileSystem.isFolder(folderContent[i])) {\n contentItem.attr(\"data-type\", \"folder\");\n $(\"<img src='_images/folder.png'/>\").prependTo(contentItem);\n } else {\n contentItem.attr(\"data-type\", \"file\");\n $(\"<img src='_images/file.png'/>\").prependTo(contentItem);\n }\n contentDiv.append(contentItem);\n contentItem.click(onContentItemClick);\n }\n }", "function getPhotosRecursively( dirPath ) {\n\t\tvar albums = [];\n\t\tfs.readdirSync( dirPath ).forEach( function( filename ) {\n\t\t\tvar filePath = dirPath+'/'+filename;\n\t\t\tvar file = fs.statSync( filePath );\n\t\t\tif ( file.isFile() ) {\n\t\t\t\tif ( /\\.(jpg|jpeg|png|webp|gif)$/i.test( filename ) ) {\n\t\t\t\t\talbums.push( filePath );\n\t\t\t\t}\n\t\t\t} else if ( file.isDirectory() ) {\n\t\t\t\talbums.push( getPhotosRecursively( filePath ) );\n\t\t\t}\n\t\t} );\n\t\treturn albums;\n\t}", "function ObjectFiles() {\n _super.call(this, \"Files\");\n }", "function returnSubFolders(dir){\n return fs.readdirSync(dir).reduce(function(list, file) {\n const name = path.join(dir, file);\n const isDir = fs.statSync(name).isDirectory();\n if (isDir) {\n list.push(name);\n }\n return list;\n }, []);\n}", "function getRepoFiles(repoPath) {\n var cwd = repoPath;\n // console.log('running git ls-files on: ' + cwd);\n var filesNamesString = ShellCommander_1.runShellCommand('git ls-files', repoPath);\n var fileNamesArray = ShellCommander_1.formatOutputNewLine(filesNamesString);\n return fileNamesArray;\n}", "function castFiles(files) {\n return _.castArray(files).map((f) => ({\n tempFilePath: f.tempFilePath, // tempFilePath is moved\n path: f.path, // path is copied, original file is not touched\n type: f.mimetype || f.type,\n name: f.name,\n size: f.size,\n }));\n }", "function readFiles(dirName, processOnFileContent, onError) {\n\tfs.readdir(dirName, function(err, fileNames) {\n\t\tif(err) {\n\t\t\tonError(err)\n\t\t\treturn\n\t\t}\n\n\t\t//Now we have all fileNames....\n\t\tfileNames.forEach(function(fileName) {\n\t\t\tvar filePath = path.join(dirName, fileName)\n\t\t\tfs.readFile(filePath, function(err, content) {\n\t\t\t\tif(err) {\n\t\t\t\t\tonError(err) \n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessOnFileContent(filePath, content)\n\t\t\t})\n\t\t})\n\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
description checks if someone has won the game paramaters: plays (array) collection of 9 character values that are all 'x', 'o', or '_' for blank returns: (string) 'x' or 'o' if the respective player won, 't' for tie, or '_' if game isn't over
function checkForWin(plays) { let matches = getPossibleMatches(plays); //scans the object for any instances of 'xxx/' or 'ooo/' which indicates a //win const winner = Object.values(matches).reduce((result, direction) => { if(result !== '_') { return result; } if(direction.includes('xxx/')) { return 'x'; } if(direction.includes('ooo/')) { return 'o'; } return '_'; }, '_'); //checks for a tie if(plays.indexOf('_') === -1 && winner === '_') { return 't'; } return winner; }
[ "function searchForPlay(plays)\n{\n //all possible win combinations\n let matches = getPossibleMatches(plays);\n //a dumbed down version of possible win combinations (Basically, a count\n //of numbers of x's, o's, and blanks of each win combination on the board)\n let simplifiedMatches = simplifyMatches(matches);\n //the indexes for win combinations, based on a board like this: 0 1 2\n // 3 4 5\n // 6 7 8\n const matchIndexes = '012/345/678/036/147/258/048/246/';\n // the number of x's and o's respectively in a match possibility\n const typeOfPlays = [\n '02/', //checks if there is a play for a win\n '20/', //checks if the opponent needs to be blocked from a win\n '01/', //checks for possibility of two o tiles and a blank spot\n '00/' //checks for possibility of one o tile in a line of blank spots\n ];\n //the index for the variable 'matchIndexes' to chose\n let matchIndex = -1;\n\n //iterates through 'typeOfPlays' in respective order, and determines an\n //exact 'typeOfPlay' once the best option is found\n typeOfPlays.forEach(typeOfPlay =>\n {\n //checks the possiblility of given 'typeOfPlay'\n let isPlay = ((simplifiedMatches.horizontal.includes(typeOfPlay)) || (simplifiedMatches.vertical.includes(typeOfPlay)) || (simplifiedMatches.diagonal.includes(typeOfPlay)));\n\n //if a typeOfPlay has not yet been determined and a typeOfPlay has now\n //been determined than an exact 'matchIndex' is determined\n if(isPlay && matchIndex === -1)\n {\n matchIndex = determineExactPlay(simplifiedMatches, typeOfPlay);\n }\n });\n\n //checks if a play was found\n if(matchIndex > -1)\n {\n //finds match\n let indexesForMatch = matchIndexes.split('/')[matchIndex].split('');\n\n //iterates through the three spots of the match to find the blank spot\n //to play an 'o'\n for(let i = 0; i < indexesForMatch.length; i++)\n {\n if(plays[indexesForMatch[i]] === '_')\n {\n return indexesForMatch[i];\n }\n }\n }\n\n //if a logical play is not found an 'o' is placed anywhere that is blank\n return plays.indexOf('_');\n}", "function game_over() {\n // you must try all 8 possibilities to determine if the game is won by someone:\n // 3 rows, 3 columns, and 2 diagonals!\n // Also, if all cells are occupied, and no one won, then it is a tie!\n \n // if no one won, and it is not a tie, then it is on going.\n return \"+\";\n}", "function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\n}", "checkIfWin(){\n\t\tconst g = this.state.grid;\n\t\tvar hits = 0;\n\n\t\tfor(var i = 0; i < this.gridSize; i++) {\n\t\t\tfor(var j = 0; j < this.gridSize; j++) {\n\t\t\t\tif (g[i][j] === \"Hit\") {\n\t\t\t\t\thits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(hits === this.maxNumberOfShips*2){\n\t\t\tvar theWinner = \"\";\n\n\t\t\tif(this.props.id === \"gridA\"){\n\t\t\t\ttheWinner = \"PlayerB\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttheWinner = \"PlayerA\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\n\t\t}\n\n\t}", "compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }", "function check_game_winner(state) {\n var winner;\n var patterns = winning_patterns;\n // loop over each of the winning patterns\n for (var pidx = 0; pidx < patterns.length; pidx++) {\n var pattern = patterns[pidx];\n // check if the red player has won thegame by completing the pattern\n if (match_pattern(state, pattern, 'red')) {\n // set the winner to red\n winner = 'red';\n // check if the yellow player has won the game by completing the pattern\n } else if (match_pattern(state, pattern, 'yellow')) {\n // set the winner to yellow\n winner = 'yellow';\n }\n // checks if a winner has been identified and sends returns the player\n if (winner) {\n return winner;\n }\n }\n\n /**\n * if a player hasn't won the game and there are no more positions that can\n * be played the game must have ended in a draw\n */\n var draw = true;\n for (var x = 0; x <= 7; x++) {\n for (var y = 0; y <= 6; y++) {\n if (!state[x][y]) {\n return undefined;\n }\n }\n }\n return '';\n }", "checkNaturalWin(){\n let win = false;\n\n //Player has natural 9\n if(this.playerHand.total === 9 && this.bankerHand.total <= 8 || \n //Player has natural 8\n this.playerHand.total === 8 && this.bankerHand.total <= 7 \n ){\n this.playerHand.win = true;\n win = true;\n }\n //Banker has a natural 9\n else if(this.bankerHand.total === 9 && this.playerHand.total <= 8 || \n //Player has natural 8\n this.bankerHand.total === 8 && this.playerHand.total <= 7 \n ){\n this.bankerHand.win = true;\n win = true;\n }\n\n return win;\n }", "function playRound(playerSelection, computerSelection) {\n \nlet concaten = computerSelection.concat(playerSelection) ;\nlet result = \"\" ;\nlet WLD = \" \" ;\n\nlet weWin = `You lose! Our ${computerSelection} beats your ${playerSelection}`;\nlet youWin = `We lose! Your ${playerSelection} beats our ${computerSelection}`;\nlet draw = `It's a draw! ; We both chose ${computerSelection}` ;\n\n\n// Below CW = computer wins ; PW = player wins ; NW = nobody wins (ie it's a draw)\nswitch(concaten) {\n case \"PaperRock\":\n result = weWin ;\n WLD = \"CW\" ;\n break;\n case \"PaperScissors\":\n result = youWin ;\n WLD = \"PW\" ;\n break; \n case \"RockPaper\":\n result = youWin ;\n WLD = \"PW\" ;\n break;\n case \"RockScissors\":\n result = weWin ;\n WLD = \"CW\" ;\n break;\n case \"ScissorsPaper\":\n result = weWin ;\n WLD = \"CW\" ;\n break; \n case \"ScissorsRock\":\n result = youWin ;\n WLD = \"PW\" ;\n break; \n case \"RockRock\" :\n result = draw ;\n WLD = \"NW\" ;\n break; \n case \"PaperPaper\" :\n result = draw ;\n WLD = \"NW\" ;\n break; \n case \"ScissorsScissors\" :\n result = draw ;\n WLD = \"NW\" ;\n break; \n default: \n result = null ;\n WLD = `concaten has value ${concaten}` \n } // end switch\n\nreturn [result, WLD] ;\n\n } // end playRound", "function computerPlay() {\n \n var empties = findEmpties(gameArray);\n var choice;\n \n choice = Math.floor(Math.random() * empties.length);\n gameArray[empties[choice]] = compSymb;\n $('#' + empties[choice]).html(comp);\n checkGameDone(compSymb);\n }", "function givePlayerSymbol(){\r\n\tif (player){\r\n\t\treturn \"X\";\r\n\t}else {\r\n\t\treturn \"O\";\r\n\t}\r\n\r\n}", "function hasWon(){\n\n //check all the lites to check if they're green. if so add one to the greentilecounter\n $tileArray.each(function (i, value) {\n if($($tileArray[i]).attr('class') === \"green\"){\n greenTileCount ++;\n }\n });\n\n tilesToGo = greenTileCount;\n\n //log valueof greentielcounter at start\n console.log(greenTileCount + \" at start of function\")\n\n // if number of green tiles = the array length then youve won.\n if(greenTileCount == $tileArray.length) {\n $('#welcome').delay(400).fadeIn();\n player1score = turnCounter;\n resetBoard();\n\n addToScoreBoard();\n\n $gridSizeSelector.hide();\n // $welcomeMsg.hide();\n $gridSizeSelector.show(); \n\n $tileArray.each(function(i, value){\n $(this).css({\"background-color\":\"rgba(41,242,44,0.8)\"});\n $(this).delay(1000).fadeOut();\n })\n $p1score.html(\"you've won, big ups! choose next level to play\");\n return true;\n }\n greenTileCount = 0;\n }", "function game() {\n let score = [0,0];\n while (score[0] !== 5 && score[1] !== 5) {\n let resultMessage = playRound(playerChoice(), computerPlay());\n if(resultMessage === undefined) {\n break;\n } else {\n roundWinner(resultMessage,score);\n }\n }\n checkWinner(score);\n}", "function getWinning() {\n let result = ''\n if (game.winner != PLAYER_NONE) {\n const winning = findTriplet(game.board[game.winner], 15)\n for (let w = 0; w < winning.length; ++w) {\n winning[w] = game.board[game.winner][winning[w]]\n }\n for (let m = 0; m < CELLS; ++m) {\n if (winning.includes(VALUES[m])) {\n result += outerCell(m)\n }\n }\n }\n return result\n}", "function wordCheck(userGuess) {\n if (gameFinished === true) {\n resetFunction();\n return;\n }\n var isItLetter = false;\n var alphabetArray = [\"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 for (i = 0; i < alphabetArray.length; i++) {\n if (userGuess === alphabetArray[i]) {\n isItLetter = true;\n }\n }\n if (isItLetter === false) {\n alert(\"I'm having a crap attack! That wasn't a letter!\");\n return;\n }\n var doesItMatch = false;\n for (i = 0; i < wordChoice.length; i++) {\n if (userGuess === wordChoice[i]) {\n doesItMatch = true;\n playSpace[i] = userGuess;\n }\n }\n var didWeWin = true;\n for (i = 0; i < wordChoice.length; i++) {\n if (playSpace[i] != wordChoice[i]) {\n didWeWin = false;\n }\n }\n if (didWeWin === true) {\n winnerFunction();\n return;\n }\n for (i = 0; i < alreadyGuessed.length; i++) {\n if (userGuess === alreadyGuessed[i]) {\n return;\n }\n }\n if (!doesItMatch) {\n guessesRemaining--;\n guessesRemainingFunction();\n alreadyGuessed.push(userGuess);\n alreadyGuessedFunction();\n }\n if (guessesRemaining === 0) {\n loserFunction();\n return;\n }\n }", "function checkWinner() {\n if (player1Score === 20) {\n setMessage(\"player 1 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n } else if (player2Score === 20) {\n setMessage(\"player 2 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n }\n }", "function checkWinStates() {\n const xtop = /XXX....../; // x top row\n const xmid = /...XXX.../; // x middle row\n const xbot = /......XXX/; // x bottom row\n const xldg = /X...X...X/; // x left to right diagonal\n const xrdg = /..X.X.X../; // x right to left diagonal\n const xlco = /X..X..X../; // x left column\n const xmco = /.X..X..X./; // x middle column\n const xrco = /..X..X..X/; // x right column\n\n const otop = /OOO....../; // o top row\n const omid = /...OOO.../; // o middle row\n const obot = /......OOO/; // o bottom row\n const oldg = /O...O...O/; // o left to right diagonal\n const ordg = /..O.O.O../; // o right to left diagonal\n const olco = /O..O..O../; // o left column\n const omco = /.O..O..O./; // o middle column\n const orco = /..O..O..O/; // o right column\n\n const empt = /E/; // there is an empty square\n\n state = '';\n for(let i=0;i<9;i++) state += boardData[currentBoard].getSquare(i).state;\n\n switch(true) {\n case xtop.test(state):\n case xmid.test(state):\n case xbot.test(state):\n case xldg.test(state):\n case xrdg.test(state):\n case xlco.test(state):\n case xmco.test(state):\n case xrco.test(state):\n boardData[currentBoard].state = X;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/VictoryX.svg\"].texture);\n break;\n case otop.test(state):\n case omid.test(state):\n case obot.test(state):\n case oldg.test(state):\n case ordg.test(state):\n case olco.test(state):\n case omco.test(state):\n case orco.test(state):\n boardData[currentBoard].state = O;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/VictoryO.svg\"].texture);\n break;\n case empt.test(state):\n // NO WIN CONDITION, BOARD STILL PLAYABLE\n break;\n default:\n boardData[currentBoard].state = C;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/cats.svg\"].texture);\n }\n\n \n state = '';\n for(let i=0;i<9;i++) state += boardData[i].state;\n let xOffset = globalBoardVictorySprites[0].width / 2;\n let yOffset = globalBoardVictorySprites[0].height / 2;\n let x1, x2, y1, y2;\n\n switch(true) {\n case xtop.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[2].x + xOffset;\n y2 = globalBoardVictorySprites[2].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xmid.test(state):\n x1 = globalBoardVictorySprites[3].x + xOffset;\n y1 = globalBoardVictorySprites[3].y + yOffset;\n x2 = globalBoardVictorySprites[5].x + xOffset;\n y2 = globalBoardVictorySprites[5].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xbot.test(state):\n x1 = globalBoardVictorySprites[6].x + xOffset;\n y1 = globalBoardVictorySprites[6].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xldg.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xrdg.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xlco.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xmco.test(state):\n x1 = globalBoardVictorySprites[1].x + xOffset;\n y1 = globalBoardVictorySprites[1].y + yOffset;\n x2 = globalBoardVictorySprites[7].x + xOffset;\n y2 = globalBoardVictorySprites[7].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xrco.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case otop.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[2].x + xOffset;\n y2 = globalBoardVictorySprites[2].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case omid.test(state):\n x1 = globalBoardVictorySprites[3].x + xOffset;\n y1 = globalBoardVictorySprites[3].y + yOffset;\n x2 = globalBoardVictorySprites[5].x + xOffset;\n y2 = globalBoardVictorySprites[5].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case obot.test(state):\n x1 = globalBoardVictorySprites[6].x + xOffset;\n y1 = globalBoardVictorySprites[6].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case oldg.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case ordg.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case olco.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case omco.test(state):\n x1 = globalBoardVictorySprites[1].x + xOffset;\n y1 = globalBoardVictorySprites[1].y + yOffset;\n x2 = globalBoardVictorySprites[7].x + xOffset;\n y2 = globalBoardVictorySprites[7].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case orco.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case empt.test(state):\n // NO WIN CONDITION, PLAY CONTINUES\n break;\n default:\n let x = 0;\n let o = 0;\n for(let i=0;i<9;i++) {\n if(boardData[i].state == X) x++;\n if(boardData[i].state == O) o++;\n }\n\n if(o > x) {\n // O VICTORY\n } else if(x > o) {\n // X VICTORY\n } else {\n // CATS GAME\n }\n victory = true;\n }\n}", "function checkPlayerArray() {\n\tif (arrayJug.length == arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\tcontador = contador + 100;\n\t\tscore_elem.innerHTML = \"Score: \" + contador;\n\t\tconsole.log(\"Turno AI\")\n\t\tsetTimeout(function(){\n\t\t\tpaseDeTurno(true);\n\t\t}, 500);\n\t}\n\telse if (arrayJug.length != arrayAI.length && compareArrays(arrayJug, arrayAI) === true) {\n\t\treturn;\n\t}\n\telse {\n\t\tanimacionGmOver()\n\t}\t\n\n}", "function gameWon(){\n var allCardsFound;\n for (var i = 0; i < cardNb; i++){\n if(!card[i].found){\n allCardsFound = false;\n return allCardsFound;\n }\n }\n if (allCardsFound !== false){\n titleText = \"CONGRATULATIONS\"\n subtitleText = \"You won!\"\n return true;\n }\n else{\n return false;\n }\n}", "function readyToPlay() {\n\t\talert(\"Player X goes first\");\n\t\tfor (var i = 0; i < 9; i ++){\n\t\tself.gameObj.gameBoard[i].piece = \" \";\n\t\t}\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Match respondents to project parameters
matchRespondentsToProjectParams() { this.results = matchRespondents(this.parsedData, this.projectParams); }
[ "function annoyEveryoneWithResponse(res) {\n var target = res.message.room.toLowerCase();\n roomAssociations.forEach(function (association, i, associations) {\n association.rooms.forEach(function (room, j, rooms) {\n if (room.name.toLowerCase() == target || (room.old_name && room.old_name.toLowerCase() == target)) {\n buildHTML(association.repos, function(err, html) {\n if (err) {\n res.send(\"There was a problem...\" + \"\\n\" + err);\n } else if (html) {\n messageHipchatRoom(room.id, html);\n } else {\n res.send(\"There are no pull requests! (pizzadance)\");\n }\n });\n }\n });\n });\n }", "function extPart_parametersMatch(partName, partListA, partListB)\n{\n var retVal = true;\n\n // walk the list of search patterns to determine the parameter names\n var paramNames = new Array();\n var searchPatterns = extPart.getSearchPatterns(partName);\n for (var i=0; i < searchPatterns.length; i++)\n {\n if (searchPatterns[i].paramNames)\n {\n var newParams = searchPatterns[i].paramNames.split(\",\");\n paramNames = paramNames.concat(newParams);\n }\n }\n \n // also need to add the node param if it exists\n var nodeParamName = extPart.getNodeParamName(partName);\n if (nodeParamName)\n {\n paramNames.push(nodeParamName);\n } \n\n // call extUtils.parametersMatch with the specific list of parameter names to check\n\n\t//HACK : to match site relative connection path to doc-relative connection path\n\t//the following parameters\"cname,ext\" are sufficient in the\n\t//match list since in a given site the user tend to use the same connection include file(\"cname.ext) in majority of cases\n\tif ((partName == \"connectionref_statement\") || (partName == \"Connection_include\"))\n\t{\n\t var tempParamNames = paramNames;\n\t\tparamNames = new Array();\n\t\tfor (var i =0 ; i < tempParamNames.length ; i++)\n\t\t{\n\t\t\tvar bIgnoreConnectionParam = ((tempParamNames[i] == \"urlformat\") || (tempParamNames[i] == \"UrlFormat\") || (tempParamNames[i] == \"relpath\") || (tempParamNames[i] == \"ConnectionPath\"));\n\t\t\tif (!bIgnoreConnectionParam)\n\t\t\t{\n\t\t\t\tparamNames.push(tempParamNames[i]);\n\t\t\t}\n\t\t}\n\t}\n retVal = extUtils.parametersMatch(partListA, partListB, paramNames);\n\n return retVal;\n}", "matchPermission(items, data) {\n let matched = false,\n entityField,\n matchPerm;\n for (let i = 0, len = items.length; i < len; i++) {\n let iam = items[i];\n if (typeof iam !== 'string' || !iam) continue;\n try {\n iam = iam.split(':').splice(1); // remove first iam\n } catch (e) {\n continue;\n }\n // iam[0] - is category\n if (iam[0] !== data.category) {\n // Check if we want pattern matching or not.\n if (data.pattern !== true || typeof data.category !== 'string') continue;\n if (data.category.indexOf(iam[0]) !== 0) continue;\n }\n // check against any given actions.\n if (data.action) {\n let iamAct = this.fromPermissionBinary(iam[1]),\n dataAct = this.fromPermissionAction(data.action);\n if (dataAct.read && !iamAct.read) continue;\n if (dataAct.create && !iamAct.create) continue;\n if (dataAct.update && !iamAct.update) continue;\n if (dataAct.delete && !iamAct.delete) continue;\n }\n // check against any given entities.\n // By default, if the IAM does not have any entity, but we requested an entity, we stop.\n if (data.entity_type) {\n let entity = iam[3];\n if (!entity) continue;\n let tmp = entity.split('#'),\n entityField = tmp[0],\n entityId = tmp[1];\n if (data.entity_type !== entityField) continue;\n if (data.entity_id !== null) {\n if (typeof entityId === 'undefined') continue;\n if (data.entity_id !== entityId) continue;\n }\n }\n // IF we reached this, that means that we've passed all filters.\n matched = true;\n matchPerm = items[i];\n if (iam[3]) { // entity type.\n entityField = iam[3];\n }\n break;\n }\n let res = {\n match: matched\n };\n if (entityField) { // we have the entityField.\n res.entity_field = entityField;\n }\n if (matched) {\n res.permission = matchPerm;\n }\n return res;\n }", "function testResponse (res, keyword) {\n // for (var i=0; i<keyword.length; i++) {\n // if (keyword[i].test(res)) {\n // return true;\n // }\n // }\n // if (kyle.test(res) || davis.test(res)) {\n // return true;\n // }\n // if (name===\"Bebe Ballo\" || name===\"Shriyans Lenkala\" || name===\"Keyshawn Ebanks\") { \n // return true;\n // }\n return false;\n}", "function extUtils_parametersMatch(params1, params2, paramsToMatchArg)\n{\n var retVal = true;\n var paramsToMatch = paramsToMatchArg;\n\n if (!paramsToMatch && params1 != null)\n {\n paramsToMatch = new Array();\n for (var param in params1)\n {\n paramsToMatch.push(param);\n }\n }\n\n // Check that common properties have the same value\n if (params1 != null && params2 != null && paramsToMatch.length > 0) {\n //check if the parameters match\n for (var i=0; i < paramsToMatch.length; i++)\n {\n var param = paramsToMatch[i];\n\n // Parameters beginning with 'MM_' are excluded from the comparison. Such\n // parameters are used internally and are not part of the Server Behavior's\n // actual parameter list.\n // Also, don't bother if params2 entry is null\n if (param && param.indexOf('MM_') != 0 && params2[param] != null)\n {\n // if one's node is editable region, compare to its parent node instead\n var params1Effective = extUtils.setEditableToParent(params1[param]);\n var params2Effective = extUtils.setEditableToParent(params2[param]);\n\n if (params2Effective != params1Effective)\n {\n // The parameters could still be equivalent if both arrays\n retVal = ( typeof params2Effective == \"object\" && params2Effective.length\n && typeof params1Effective == \"object\" && params1Effective.length\n && params2Effective.length == params1Effective.length\n );\n if (retVal)\n {\n // Make copies of the parameter arrays so that we don't update them\n // in place.\n var tmpParams2 = params2Effective.slice(0);\n var tmpParams1 = params1Effective.slice(0);\n tmpParams2.sort();\n tmpParams1.sort();\n for (var j = 0; retVal && j < tmpParams2.length; ++j)\n {\n if (tmpParams2[j] != tmpParams1[j])\n retVal = false;\n }\n }\n\n //if any parameter doesn't match, break\n if (!retVal)\n break;\n }\n }\n }\n }\n\n return retVal;\n}", "respond (...args) {\n return this.listen('respond', ...args)\n }", "async verbs(verb, words) {\n let key;\n let value;\n let room;\n const server = index_1.api.servers.servers[this.type];\n const allowedVerbs = server.attributes.verbs;\n if (!(words instanceof Array)) {\n words = [words];\n }\n if (server && allowedVerbs.indexOf(verb) >= 0) {\n server.log(\"verb\", \"debug\", {\n verb: verb,\n to: this.remoteIP,\n params: JSON.stringify(words),\n });\n // TODO: investigate allowedVerbs being an array of Constants or Symbols\n switch (verb) {\n case \"quit\":\n case \"exit\":\n return this.destroy();\n case \"paramAdd\":\n key = words[0];\n value = words[1];\n if (words[0] && words[0].indexOf(\"=\") >= 0) {\n const parts = words[0].split(\"=\");\n key = parts[0];\n value = parts[1];\n }\n if (config_1.config.general.disableParamScrubbing ||\n index_1.api.params.postVariables.indexOf(key) >= 0) {\n this.params[key] = value;\n }\n return;\n case \"paramDelete\":\n key = words[0];\n delete this.params[key];\n return;\n case \"paramView\":\n key = words[0];\n return this.params[key];\n case \"paramsView\":\n return this.params;\n case \"paramsDelete\":\n for (const i in this.params) {\n delete this.params[i];\n }\n return;\n case \"roomAdd\":\n room = words[0];\n return index_1.chatRoom.addMember(this.id, room);\n case \"roomLeave\":\n room = words[0];\n return index_1.chatRoom.removeMember(this.id, room);\n case \"roomView\":\n room = words[0];\n if (this.rooms.indexOf(room) >= 0) {\n return index_1.chatRoom.roomStatus(room);\n }\n throw new Error(await config_1.config.errors.connectionNotInRoom(this, room));\n case \"detailsView\":\n return {\n id: this.id,\n fingerprint: this.fingerprint,\n remoteIP: this.remoteIP,\n remotePort: this.remotePort,\n params: this.params,\n connectedAt: this.connectedAt,\n rooms: this.rooms,\n totalActions: this.totalActions,\n pendingActions: this.pendingActions,\n };\n case \"documentation\":\n return index_1.api.documentation.documentation;\n case \"say\":\n room = words.shift();\n await index_1.api.chatRoom.broadcast(this, room, words.join(\" \"));\n return;\n }\n const error = new Error(await config_1.config.errors.verbNotFound(this, verb));\n throw error;\n }\n else {\n const error = new Error(await config_1.config.errors.verbNotAllowed(this, verb));\n throw error;\n }\n }", "matchAndFetchModifiers(env) {\n const f = filterUnits[filterSequences[this.i]];\n if (\n f.matchAndFetchModifiers instanceof Function &&\n f.type === env.modifier &&\n this.match()\n ) {\n f.matchAndFetchModifiers(env);\n }\n }", "match(path, params={}) {\n params.router = this;\n params.route = this.routes.find(({ re }) => {\n const match = re.exec(path);\n if (match) {\n params.length = 0;\n re.keys.forEach((key, i) => {\n params[key.name] = match[i + 1];\n if (typeof key.name === 'number') {\n params.length = key.name + 1;\n }\n });\n return true;\n }\n });\n return params;\n }", "matches(from, to) {\n let matchesFrom = false;\n if (this.from === \"*\") {\n matchesFrom = true;\n }\n else if (Array.isArray(this.from)) {\n const array = this.from;\n matchesFrom = array.some(state => state === from);\n }\n else {\n matchesFrom = this.from === from;\n }\n let matchesTo = false;\n if (this.to === \"*\") {\n matchesTo = true;\n }\n else if (Array.isArray(this.to)) {\n const array = this.to;\n matchesTo = array.some(state => state === to);\n }\n else {\n matchesTo = this.to === to;\n }\n return matchesFrom && matchesTo;\n }", "function SearchPattInfo(paramNames, isOptional, limitSearch, pattern, match)\n{\n this.paramNames = paramNames;\n this.isOptional = isOptional;\n this.limitSearch = limitSearch;\n this.pattern = pattern;\n this.match = match;\n}", "function suggestProject(name,dateStart,dateEnd,description,additional){\n\n if (additional !==\"\" ){\n var array = additional.split(',');\n }\n\n var send = {ProjectName: name, Technologies: Tecnologias, EndDate:dateEnd, StartDate:dateStart, Description: description, \n CourseId: vm.courseData.CourseId, StudentUserId: vm.courseData.StudentUserId, OtherFiles:array }\n console.log(send);\n\n CourseService.ProjectPropose(send)\n .then(function(response){\n\n if (response.data.ReturnStatus ==\"1\"){\n FlashService.Success(\"Proyecto sugerido exitosamente\", true);\n $location.path('/studentprofile')\n }\n else\n FlashService.Error(\"El proyecto no se ha podido sugerir\");\n\n }, function(response){\n\n FlashService.Error(\"El proyecto no se ha podido sugerir\");\n });\n\n }", "function match(req, res) {\n let username = req.session.username;\n if (!username) {\n res.render('improper');\n return;\n }\n\n let answersForCurrentUser = Model.getAllAnswersForUser(username);\n let userMatches = new Map();\n if (answersForCurrentUser) {\n answersForCurrentUser.forEach((answerForCurrentUser, i, arr) => {\n // get all the answers for same question for other users\n Model.getAllAnswersForQuestion(answerForCurrentUser.questionId)\n // filter for matching answer\n .filter(currentAnswer => currentAnswer.answer === answerForCurrentUser.answer)\n // filter out the user we're matching\n .filter(currentAnswer => currentAnswer.username != username)\n // count matches of other users to current user\n .forEach((currentAnswer, i) => {\n if (userMatches.has(currentAnswer.username)) {\n let matches = userMatches.get(currentAnswer.username);\n matches++;\n userMatches.set(currentAnswer.username, matches);\n } else {\n userMatches.set(currentAnswer.username, 1);\n }\n });\n });\n }\n let matches = [];\n // sort the userMatches map from highest match to lowest\n let userMatchesSortedDesc = new Map([...userMatches.entries()]\n // sort by match count\n .sort((a, b) => b.value - a.value))\n // add each string to matches array\n .forEach((val, key) => matches.push(`User: ${key} matched ${val} answers`));\n console.log(matches);\n res.render('matches', { \n title: 'SER421 MVC Ex Survey Matches', \n username: username,\n matches: matches\n });\n}", "function testMatch(match, vars) {\n\n vars = vars || {};\n\n return function() {\n Object.keys(match).forEach(function(key) {\n assert.isString(match[key]);\n if(key === 'suffix') {\n assert.equal(match[key], '');\n return;\n }\n assert.equal(match[key], vars[key] || key);\n });\n };\n\n }", "function extUtils_extractParameters(searchPatterns)\n{\n var parameters = new Object();\n\n //find all the parameters in the current participant,\n for (var i=0; i < searchPatterns.length; i++)\n {\n //check if we have parameters and that a match list was created\n if (searchPatterns[i].paramNames && searchPatterns[i].match)\n {\n //get the list of parameters to extract for this pattern\n var paramList = searchPatterns[i].paramNames.split(\",\");\n\n //get the match information\n var match = searchPatterns[i].match;\n var isMultiple = (match.length > 0 && typeof match[0] == \"object\");\n\n //now, extract the parameters from this pattern\n for (var j=0; j < paramList.length; j++)\n {\n var paramName = paramList[j];\n\n //skip over blank parameter names\n if (paramName)\n {\n if (!isMultiple)\n {\n if (match.length > j+1)\n {\n parameters[paramName] = match[j+1];\n }\n else\n {\n alert(dwscripts.sprintf(MM.MSG_NoMatchForParameter, paramName));\n parameters[paramName] = \"\";\n }\n }\n else\n {\n parameters[paramName] = new Array();\n for (var k=0; k < match.length; k++)\n {\n if (match[k].length > j+1)\n {\n parameters[paramName].push(match[k][j+1]);\n }\n else\n {\n alert(errMsg(MM.MSG_NoMatchForParameter, paramName));\n parameters[paramName].push(\"\");\n }\n }\n }\n }\n }\n }\n }\n\n return parameters;\n}", "static find_status(action) {\n if (!Server.pending || file !== Server.pending.agenda) return null;\n let match = null;\n\n for (let status of Pending.status) {\n let found = true;\n\n for (let [name, value] of Object.entries(action)) {\n if (name !== \"status\" && value !== status[name]) found = false\n };\n\n if (found) match = status\n };\n\n return match\n }", "function searchJSON(input) {\n\tvar searchStr = input.toLowerCase();\n\t\n\tfilteredObjects = [];\n\n\t$.each(jsonObjects, function(i, item) { \n\t\tvar project = item.projectTitle.toLowerCase(),\n\t\t\tdescription = item.projectDescription.toLowerCase();\n\n\t\tif((project.indexOf(searchStr) >= 0) || (description.indexOf(searchStr) >= 0)) {\n\t\t\tfilteredObjects.push(item);\n\t\t}\n\t});\n}", "getV3ProjectsIdMergeRequestsMergeRequestIdAwardEmojiAwardId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let awardId = 56;*/ // Number | The ID of the awar\n/*let id = 56;*/ // Number |\n/*let mergeRequestId = 56;*/ // Number | \napiInstance.getV3ProjectsIdMergeRequestsMergeRequestIdAwardEmojiAwardId(incomingOptions.awardId, incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "async function matchJobTitle(userIdIn, preferenceIn) {\n\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n var searchPreferences = await db.collection('preferences').find({userId: new ObjectID(userIdIn)}).toArray();\n //console.log(searchPreferences);\n var locationPrefs = [];\n for (var i = 0; i < searchPreferences.length; i++) {\n if (searchPreferences[i].type == 'location') {\n //var commaIndex = searchPreferences[i].preference.indexOf(',');\n locationPrefs.push(searchPreferences[i].preference); //.slice(0, commaIndex));\n }\n }\n var {preference} = preferenceIn;\n\n var locationsOR = [];\n for (var i = 0; i < locationPrefs.length; i++) {\n var commaIndex = locationPrefs[i].indexOf(',');\n var citySegment = locationPrefs[i].slice(0, commaIndex);\n var stateSegment = locationPrefs[i].slice(commaIndex + 2);\n locationsOR.push({city: citySegment, state: stateSegment});\n }\n\n if (locationsOR.length > 0) {\n var matches = await db.collection('jobs').find(\n {crawled: true, jobTitle: { $regex: preference, $options: 'i' }, $or: locationsOR }\n ).project({_id: 1}).toArray();\n\n await db.close();\n return matches.map(function(a) {return a._id;});\n }\n else {\n await db.close();\n return [];\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scroll down to project information
function showProjectInfo() { if (localStorage.getItem("aProjectIndex") != -1) { var aProject = document.getElementsByClassName("a-project"); aProject[localStorage.getItem("aProjectIndex")].scrollIntoView(); window.scrollBy(0, -80); localStorage.setItem("aProjectIndex", -1); } toTopWhenReload(); }
[ "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}", "function displayProjectsList() {\n\t\t\t\t\t$(\"#d-percent_complete\").css('width', '0%');\t// Shrink the bar down to 0% so it grows when opening a new project.\n\t\t\t\t\t$projectListEles.addClass(\"show\");\n\t\t\t\t\t$projectDetailsEles.removeClass(\"show\");\t\n\t\t\t\t\tclearHash();\n\t\t\t\t}", "function learnMore() {\n $('html, body').animate({\n scrollTop: $('#ps-home-description').offset().top + 'px'\n }, 'slow');\n }", "function openProject(path) {\n\n\t\t// Load project\n\t\tloadProject( path, function() {\n\n\t\t\t// if everything go right show build screen\n\t\t\t$('#screen-main').fadeOut(300, function() {\n\n\t\t\t\t// Close project name if opened\n\t\t\t\tcloseProjectName();\n\n\t\t\t\t// Resize logo\n\t\t\t\t$('header').animate({padding : '20px'}, 300, function () {\n\n\t\t\t\t\t// Show project name\n\t\t\t\t\t$('.project-title').text(require('./js/models.js').project.name);\n\n\t\t\t\t\t// Show next screen\n\t\t\t\t\t$('#screen-build').fadeIn(300);\n\n\t\t\t\t\t// Enable last project button\n\t\t\t\t\t$('#open-last-project-button').removeAttr('disabled')\n\n\t\t\t\t});\n\n\t\t\t});\n\n\t\t}, function (err) {\n\t\t\t// If there is any error reading the json file\n\t\t\tshowAlert('error', err);\n\t\t});\n\n\t}", "function grabJumpToContent()\n{\n\tvar oXMLDoc = getXMLDocument(smf_prepareScriptUrl(smf_scripturl) + 'action=xmlhttp;sa=jumpto;xml', grabJumpResponse);\n}", "function displayProject(index) {\r\n localStorage.setItem(\"aProjectIndex\", index);\r\n window.open(\"ProjectsInfo.html\",\"_self\");\r\n}", "function getAllprojects(){\n\n}", "function loadProjects() {\n API.getProjects()\n .then((res) => setProjects(res.data))\n .catch((err) => console.log(err));\n }", "function projectDisplay() {\n// set variable outside of click function to hold previously clicked project\nvar lastClick;\n $('.project-tile').click(function(e){\n// set variables\n let $target = $(e.currentTarget);\n let $targetId = $target.attr('data-target');\n let $slick = $(`#${$targetId}-slick`);\n let $gifSlide = $target.attr('data-value') || 0;\n// change slide in gif orbit to project that was clicked on\n $('.project-container').slick('slickGoTo', $gifSlide )\n// closes project details if already open, else opens project details\n if (lastClick === $targetId && ($('.project-tile').hasClass('selectedItem'))) {\n $('.project-description').hide();\n $('.project-tile').removeClass('selectedItem');\n } else {\n lastClick = $targetId;\n $('.project-tile').removeClass('selectedItem');\n $target.addClass('selectedItem');\n $('.project-description').hide();\n $(`#${$targetId}-description`).removeClass('hidden').fadeToggle(1000);\n// initializes slick carousel for screenshots in project details\n $slick.slick({\n prevArrow: \"<img class='slick-prev' src='img/left-arrow-icon.png'>\",\n nextArrow: \"<img class='slick-next' src='img/right-arrow-icon.png'>\"\n });\n };\n });\n}", "function addProjectDetails(e) {\n\t// Prevent following the link\n\te.preventDefault();\n\n\t// Get the div ID, e.g., \"project3\"\n\tvar projectID = $(this).closest('.project').attr('id');\n\t// get rid of 'project' from the front of the id 'project3'\n\tvar idNumber = projectID.substr('project'.length);\n var url = \"/project/\" + idNumber;\n console.log(\"AJAX get from URL \" + url);\n\t$.get(url, displayRetrievedDetails);\n}", "function loadProject() {\n\t\t/*\n\t\t//use temp project stubs here \n\t\tvar project = project1;\n\t\tfor (var i = 0; i <= project.tasks.length - 1; i++) { \n\t\t\taddTableRow(project.tasks[i]);\n\t\t\tgenerateTaskDetailsModal(project.tasks[i]);\t\n\t\t};\n\t\t*/\n\t\tgenerateLeftTable();\n\t\tgenerateRightDayTable();\n\t\tgenerateRightWeekTable();\n\t\tgenerateRightMonthTable();\n\t\tgenerateRightQuarterTable();\n\t}", "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 printProjects(){\n let user = retrieveUserInfo();\n let projects = user.projects.split(\", \");\n let output = \"\";\n\n for (let i = 0; i < projects.length; i++){\n db.collection(\"projects\").where(\"projectid\", \"==\", projects[i])\n .get()\n .then(function(querySnapshot) {\n querySnapshot.forEach(function (doc) {\n output += \"<div class = \\\"container\\\">\"\n output += \"<div class=\\\"demo-card-wide mdl-card mdl-shadow--2dp\\\">\"\n output += \"<div class=\\\"mdl-card__title\\\">\"\n output += \"<h2 class=\\\"mdl-card__title-text\\\">\" + \"Group project \" + (i+1) + \": \" + doc.data().projname + \"</h2>\"\n output += \"</div>\"\n output += \"<div class=\\\"mdl-card__supporting-text\\\">\"\n output += \"<b>Unit name:</b> \" + doc.data().unitname + \"<br><br>\"\n output += \"<b>Unit description:</b> \" + doc.data().unitdesc + \"<br><br>\"\n output += \"<b>Unit code:</b> \" + doc.data().unitcode + \"<br>\"\n output += \"</div>\"\n output += \"<div class=\\\"mdl-card__actions mdl-card--border\\\">\"\n output += \"<b>Weightage:</b> \" + doc.data().weightage + \"%<br>\"\n output += \"</div>\"\n output += \"<div class=\\\"mdl-card__actions mdl-card--border\\\">\"\n output += \"<a id=\\\"\" + i + \"\\\" class=\\\"mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect\\\" onclick = \\\"window.location.href=\\'project.html\\'; projectIndex(this.id);\\\">\"\n output += \"Get Started\"\n output += \"</a>\"\n output += \"</div>\"\n output += \"</div>\"\n output += \"</div>\"\n });\n })\n .then(()=> {\n document.getElementById(\"projectArea\").innerHTML = output;\n initBackgroundImage();\n })\n }\n}", "function fetchProject() {\n $.ajax({\n url: `${baseURL}/project`,\n method: 'GET',\n headers : {\n access_token : localStorage.getItem('jwtToken')\n }\n })\n .done(projects => {\n \n console.log(projects, 'fetch project');\n if (projects.length > 0) {\n $('.fixed-action-btn').show()\n $('.remark').hide()\n $('.project-cards').show()\n $('.detailed-project').hide()\n $('.project-cards').empty()\n projects.forEach(project => {\n // console.log(project, 'dari for each fetch');\n // console.log(project._id, 'dr fetch nyari id prjct ada gakkk');\n \n // <i class=\"material-icons\" style=\"color: orange;\">delete</i>\n\n $('.project-cards').append(`\n \n <div class=\"col s4\">\n <div class=\"card cyan darken-4\">\n <div class=\"card-content white-text\">\n <div class=\"project-title\">\n <span style=\"font-size: 35px; margin-bottom: 30px;\" class=\"card-title\">${project.title}</span>\n </div>\n <p>“Focus on being productive instead of busy.” <br>\n – Tim Ferriss</p>\n </div>\n <div class=\"card-action\">\n <div>\n <a href=\"#\"><i class=\"fas fa-users\"></i>&nbsp;${project.members.length}</a>\n <a href=\"#\"><i class=\"far fa-list-alt\"></i>&nbsp;${project.todos.length}</a>\n </div>\n <div>\n <i onclick=\"showDetailProject('${project._id}')\" class=\"material-icons clickable\" style=\"color: orange;\">navigate_next</i>\n </div>\n </div>\n </div>\n </div>\n \n `)\n })\n } else {\n $('.remark').show()\n $('.project-cards').hide()\n $('.detailed-project').hide()\n $('.fixed-action-btn').hide()\n }\n })\n .fail(err => {\n console.log(`failed to fetch project`);\n \n })\n .always(() => {\n console.log(`complete`);\n \n })\n}", "function infoscroll() {\n $('html, body').animate({\n 'scrollTop': $('#infos').offset().top\n }, 900);\n}", "function getProjectbyId(project_id){\n\n}", "function onProjectSelect() {\n\t\tself.tableData = (self.resourceMap && self.resourceMap[self.project.id]) || [];\n\t\tself.gridOptions.data = self.tableData;\n\t\tself.gridApi.grid.clearAllFilters();\n\t\tself.gridApi.pagination.seek(1);\n\t\tvar rowCount = Math.min(10, self.tableData.length);\n\t\tangular.element(document.getElementsByClassName('grid')[0]).css('height', ((rowCount + 6) * 30) + 'px');\n\t}", "updateProjectListView(projectData) {\n this.clearInnerHTML(this.projects);\n this.projectData.forEach(project => this.render(project));\n }", "function goToByScroll(dataslide, mstime) {\n $('html,body').animate({\n scrollTop: $('.slide[data-slide=\"' + dataslide + '\"]').offset().top\n }, mstime);\n setActivePage(dataslide);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests server to send folder contents. Populates folderArr with folder contents. refreshCallback is a function which can be called after asynchronous server call is completed.
function listCall(path, refreshCallback){ Meteor.call("listContents", path, "d", function(error, result){ if(error){ console.log(error.reason); return; } Session.set("folderArr", result.split('\n')); Meteor.call("listContents", path, "f", function(error, result){ if(error){ console.log(error.reason); return; } Session.set("fileArr", result.split('\n')); refreshCallback(); }); }); }
[ "onUpdateFolder() {\n this.store.query(\"folder\", {})\n .then((results) => {\n // Rebuild the tree\n this.send('buildTree', { folders: results });\n })\n .catch(() => {\n this.growl.error('Error', 'Error while retrieving folders');\n });\n }", "getFolders() {\n return fetch(this.BASE_API + \"/folders\", {\n method: 'GET',\n headers: {\n 'Accept': 'application/json'\n },\n });\n }", "async getFolderChildren(params) {\n const folderId = params.parentId;\n const response = await ApiMiddleware.getData(\n ANCHOR.CONTRACT_FOLDERS + `/${folderId}`\n );\n\n if (!response.body.files) {\n return [];\n }\n\n const elements = [];\n response.body.files.map(item => {\n let newItem;\n if (item.contentType === \"system/folder\") {\n newItem = new ContractFolderModel(\n item.id,\n item.parentFileId,\n item.name,\n item.dateModification || item.dateCreation,\n item.creePar\n );\n } else {\n const downloadLink = `${API.API_URL}${\n ANCHOR.CONTRACT_FOLDERS\n }/${folderId}/file/${item.id}`;\n newItem = new ContractFileModel(\n item.id,\n item.parentFileId,\n item.name,\n downloadLink,\n item.dateModification || item.dateCreation,\n item.creePar\n );\n }\n elements.push(newItem);\n return null;\n });\n\n return elements;\n }", "LoadFolder(folder) {\n return __awaiter(this, void 0, void 0, function* () {\n this.ClearMain(); //Clear all current folders and files\n this.ClearSideBar(); //Clear the sidebar\n const childFolders = yield this.Api.GetChildFolders(folder);\n const childFiles = yield this.Api.GetChildFiles(folder);\n let folderParseErrorCount = 0;\n let fileParseErrorCount = 0;\n //Load folders first\n for (const folder_ of childFolders) {\n if (folder_ instanceof CloudFolder === false) {\n folderParseErrorCount++;\n continue;\n }\n this.AddFolderToMain(folder_, true);\n this.AddFolderToSidebar(folder_, true);\n }\n //Load files\n for (const file_ of childFiles) {\n if (file_ instanceof CloudFile === false) {\n fileParseErrorCount++;\n continue;\n }\n this.AddFileToMain(file_, true);\n }\n if (folderParseErrorCount !== 0)\n this.DisplayMessage(`An error occured while parsing the folder. (${folderParseErrorCount}x)`, AlertStyle.Danger);\n if (fileParseErrorCount !== 0)\n this.DisplayMessage(`An error occured while parsing the file. (${fileParseErrorCount}x)`, AlertStyle.Danger);\n this.Current = folder;\n if (childFolders.length !== 0) {\n //Displays in which folder the user is currently in\n $(\"#fm-sb-folders\").find(`div[data-folder-id'${folder.elementId}']`).addClass(\"fm-sb-folders-current\"); //undefined is not a function\n }\n if (childFiles.length !== 0) {\n //Do nothing\n }\n if (childFiles.length === 0 && childFolders.length === 0) { //If there's nothing in the folder.\n if (folder.elementId === \"root\")\n this.DisplayMessage(\"Welcome ! This is your root folder. Drag some files here to upload them or create a folder by clicking the + button.\", AlertStyle.Success);\n else\n this.DisplayMessage(\"This folder is empty.\", AlertStyle.Info);\n }\n });\n }", "function refreshCurrentDir() {\n\t\t\t$scope.loading = true;\n\t\t\t$scope.files = [];\n\t\t\tfileBrowseService.getFilesInDir(fileSystemLocation + $scope.currentDir)\n\t\t\t\t.then(function(response) {\n\t\t\t\t\tresults = response.data.files;\n\t\t\t\t\t$scope.currentDir = response.data.parentPath;\n\t\t\t\t\tif ($scope.currentDir.substr($scope.currentDir.length-1,1) !== '/')\n\t\t\t\t\t\t$scope.currentDir += '/';\n\t\t\t\t\tif ($scope.currentDir !== '/')\n\t\t\t\t\t\tresults.unshift({\n\t\t\t\t\t\t\tname: '..',\n\t\t\t\t\t\t\tisFolder: true\n\t\t\t\t\t\t});\n\t\t\t\t\t$scope.files = results;\n\t\t\t\t\t$scope.loading = false;\n\t\t\t\t},function(response) {$scope.warnNetworkError();});\n\t\t}", "refreshMainFolderTree() {\n let $currentFolderTree = $('#tree-container').find('.foldertree-widget')\n\n if ($currentFolderTree.length) {\n let postData = {\n _token: this.ajaxToken,\n _action: 'requestMainFolderTree',\n }\n\n let url = this.routes.foldersTreeAjax\n\n $.ajax({\n url: url,\n type: 'get',\n cache: false,\n dataType: 'json',\n data: postData,\n })\n .done((data) => {\n if ($currentFolderTree.length && typeof data.folderTree !== 'undefined') {\n $currentFolderTree.fadeOut('slow', () => {\n $currentFolderTree.replaceWith(data.folderTree)\n $currentFolderTree = $('#tree-container').find('.foldertree-widget')\n $currentFolderTree.fadeIn()\n this.initNestables()\n this.bindMainTrees()\n this.resize()\n this.lazyload.bindAjaxLink()\n })\n }\n })\n .always(() => {\n this.lazyload.canvasLoader.hide()\n })\n } else {\n console.debug('No main folder-tree available.')\n }\n }", "resetFolders(){\n // clear folder paths \n this._folderPaths = [];\n\n // update file\n return this.update();\n }", "async getFolders() {\n const matches = await this.client('folders').select('folder');\n return matches.map(match => match.folder);\n }", "function iterateFoldersFunction( parentFolder, folderFunction ){\t\r\n\r\n\t//\tlog.thisLevel( log.level.debug );\r\n\t//\tlog.debug( 'parentFolder.prettyName ' + parentFolder.prettyName )\r\n\r\n\tif( ! parentFolder.isServer ) { \r\n\t\t//\tapply fuction to folder and see if need to stop iteration \r\n\t\tif( folderFunction( parentFolder ) ){ return; }\r\n\t}\r\n\r\n\tif( parentFolder.hasSubFolders ) {\r\n\r\n\t\tvar subFolders = parentFolder.GetSubFolders();\r\n\r\n\t\tvar collection = new carrot_garden.util.classCollection();\r\n\r\n\t\tvar done = false;\r\n\t\twhile( ! done ) {\r\n\r\n\t\t\tvar folder = subFolders.currentItem()\r\n\t\t\t\t.QueryInterface(Components.interfaces.nsIMsgFolder);\r\n\t\t\t\t\r\n\t\t\tvar folderName = folder.prettyName.toLowerCase();\r\n\t\t\t\r\n\t\t\tcollection.add( folderName, folder );\t//\t(key,value,memo)\r\n\r\n\t\t\ttry { subFolders.next(); }\r\n\t\t\tcatch( ex ) { done = true; }\r\n\t\t}\r\n\r\n\t\tcollection.sortBy('key');\r\n\t\t//log.debug( collection.size() )\r\n\t\t\r\n\t\tfunction iterateThis( folderName, folder ){\t\t//\t(key,value,memo)\r\n\t\t//\tlog.thisLevel( log.level.debug );\r\n\t\t//\tlog.debug( folderName );\r\n\t\t\titerateFoldersFunction( folder, folderFunction );\r\n\t\t}\r\n\t\t\r\n\t\tcollection.iterate( iterateThis );\r\n\r\n\t}\r\n}", "function iterateServersFunction( folderFunction ){\r\n\r\n\tvar service = Components.classes[\"@mozilla.org/messenger/account-manager;1\"]\r\n\t\t.getService(Components.interfaces.nsIMsgAccountManager);\r\n\t\r\n\tvar servers = service.allServers;\r\n\r\n\tvar alreadyProcessed = new Object();\r\n\r\n\tfor( var k = 0; k < servers.Count(); k++ ) {\r\n\r\n\t\tvar server = servers.GetElementAt( k )\r\n\t\t\t.QueryInterface(Components.interfaces.nsIMsgIncomingServer);\r\n\r\n\t\tvar parentFolder = server.rootMsgFolder;\r\n\r\n\t\tvar parentFolderName = parentFolder.prettyName;\r\n\t\t//log.debug('parentFolderName ' + parentFolderName)\r\n\r\n\t\tif ( alreadyProcessed[ parentFolderName ] ) {\r\n\t\t\t// \tprevent duplicate servers\r\n\t\t} else {\r\n\t\t\talreadyProcessed[ parentFolderName ] = true;\r\n\t\t\titerateFoldersFunction( parentFolder, folderFunction );\r\n\t\t}\r\n\t}\r\n}", "editFolder(aTabID, aFolder) {\n let folder = aFolder || GetSelectedMsgFolders()[0];\n\n // If a server is selected, view settings for that account.\n if (folder.isServer) {\n MsgAccountManager(null, folder.server);\n return;\n }\n\n if (folder.flags & Ci.nsMsgFolderFlags.Virtual) {\n // virtual folders get their own property dialog that contains all of the\n // search information related to the virtual folder.\n this.editVirtualFolder(folder);\n return;\n }\n\n let title = gMessengerBundle.getString(\"folderProperties\");\n\n function editFolderCallback(aNewName, aOldName, aUri) {\n if (aNewName != aOldName)\n folder.rename(aNewName, msgWindow);\n }\n\n function rebuildSummary(msgFolder) {\n if (msgFolder.locked) {\n msgFolder.throwAlertMsg(\"operationFailedFolderBusy\", msgWindow);\n return;\n }\n if (msgFolder.supportsOffline) {\n // Remove the offline store, if any.\n let offlineStore = msgFolder.filePath;\n if (offlineStore.exists())\n offlineStore.remove(false);\n }\n msgFolder.msgDatabase.summaryValid = false;\n\n try {\n msgFolder.closeAndBackupFolderDB(\"\");\n }\n catch(e) {\n // In a failure, proceed anyway since we're dealing with problems\n msgFolder.ForceDBClosed();\n }\n // these two lines will cause the thread pane to get reloaded\n // when the download/reparse is finished. Only do this\n // if the selected folder is loaded (i.e., not thru the\n // context menu on a non-loaded folder).\n if (msgFolder == GetLoadedMsgFolder()) {\n gRerootOnFolderLoad = true;\n gCurrentFolderToReroot = msgFolder.URI;\n }\n msgFolder.updateFolder(msgWindow);\n }\n\n window.openDialog(\"chrome://messenger/content/folderProps.xul\",\n \"\", \"chrome,modal,centerscreen\",\n {folder: folder, serverType: folder.server.type,\n msgWindow: msgWindow, title: title,\n okCallback: editFolderCallback, tabID: aTabID,\n name: folder.prettyName,\n rebuildSummaryCallback: rebuildSummary});\n }", "function getLocalFolders() {\r\n\tvar server = getLocalFoldersServer();\r\n\tvar folder = server.rootFolder;\r\n\treturn folder;\r\n}", "onFolderLoading(aFolderLoading) {\n if (this._tabInfo) {\n document\n .getElementById(\"tabmail\")\n .setTabBusy(this._tabInfo, aFolderLoading);\n }\n\n FolderDisplayListenerManager._fireListeners(\"onFolderLoading\", [\n this,\n aFolderLoading,\n ]);\n }", "setFolders(state, folders) {\n state.list = folders\n }", "function checkForFolder() {\n var fileExist = false;\n var subFolder = false;\n var request = gapi.client.request({\n 'path': '/drive/v3/files',\n 'method': 'GET',\n 'params': {q: \"name = 'ENGR 1200'\"}\n });\n request.execute(function(resp) { \n if(resp.files.length > 0) {\n for(var i =0; i < resp.files.length; i++) {\n if(resp.files[i].mimeType == \"application/vnd.google-apps.folder\") {\n fileExist = true;\n ENGRFolderId = resp.files[0].id;\n break;\n }\n }\n }\n if(!fileExist) {\n alert(\"Creating the folder ENGR 1200 in your Google Drive\");\n folderCreate();\n } else {\n console.log(\"That folder already exists\");\n var requester = gapi.client.request({\n 'path': '/drive/v3/files',\n 'method': 'GET',\n 'params': {q: \"name = 'Auto Save'\"}\n });\n requester.execute(function(res) { \n console.log(res);\n if(res.files.length > 0) {\n for(var i =0; i < res.files.length; i++) {\n if(res.files[i].mimeType == \"application/vnd.google-apps.folder\") {\n subFolder = true;\n autoSaveFolderId = res.files[0].id;\n break;\n }\n }\n }\n //Checks to see if the auto save folder exists.\n if(!subFolder) {\n subFolderCreate();\n } else {\n readFiles(ENGRFolderId, autoSaveFolderId);\n }\n });\n \n\n }\n });\n }", "async function getAllBookmarkFolders() {\n const [rootTree] = await browser.bookmarks.getTree();\n const livemarksFolders = (await LivemarkStore.getAll()).map(livemark => {\n return livemark.id;\n });\n\n const folders = [];\n const visitChildren = (tree) => {\n for (const child of tree) {\n if (child.type !== \"folder\" || !child.id) {\n continue;\n }\n\n // if the folder belongs to a feed then skip it and its children\n if (livemarksFolders.includes(child.id)) {\n continue;\n }\n\n folders.push(child);\n visitChildren(child.children);\n }\n };\n\n visitChildren(rootTree.children);\n return folders;\n}", "function displayFolderContent(folderElement) {\n var contentDiv = clearAndReturnContentDiv();\n var folderContent = fileSystem.sortFolderContent(folderElement.children);\n for (var i = 0; i < folderContent.length; i++) {\n var contentItem = $(\"<div data-id='\" + folderContent[i].id + \"'><div>\" + folderContent[i].name + \"</div></div>\");\n contentItem.addClass(\"contentItem\");\n contentItem.contextmenu(function (event) {\n showContextMenu(event);\n return false;\n });\n if (fileSystem.isFolder(folderContent[i])) {\n contentItem.attr(\"data-type\", \"folder\");\n $(\"<img src='_images/folder.png'/>\").prependTo(contentItem);\n } else {\n contentItem.attr(\"data-type\", \"file\");\n $(\"<img src='_images/file.png'/>\").prependTo(contentItem);\n }\n contentDiv.append(contentItem);\n contentItem.click(onContentItemClick);\n }\n }", "updateFolderAndNotify(\n aFolder,\n aCallback,\n aCallbackThis,\n aCallbackArgs,\n aSomeoneElseWillTriggerTheUpdate\n ) {\n // register for the folder loaded notification ahead of time... even though\n // we may not need it...\n let folderListener = {\n onFolderEvent(aEventFolder, aEvent) {\n if (aEvent == \"FolderLoaded\" && aFolder.URI == aEventFolder.URI) {\n MailServices.mailSession.RemoveFolderListener(this);\n aCallback.apply(aCallbackThis, aCallbackArgs);\n }\n },\n };\n\n MailServices.mailSession.AddFolderListener(\n folderListener,\n Ci.nsIFolderListener.event\n );\n\n if (!aSomeoneElseWillTriggerTheUpdate) {\n aFolder.updateFolder(null);\n }\n }", "function folder_rss_template(){\n\n\tif(setup_ajax()!=false){\n \n\t\tvar url=\"folder_rss_template.php\";\n\n\t\tfolders_ajax_send_prepare(url);\n\n\t\txmlHttp.send('folder_id=' + window.name); \n\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom type guard for Method. Returns true if node is instance of Method. Returns false otherwise. Also returns false for super interfaces of Method.
function isMethod(node) { return node.kind() == "Method" && node.RAMLVersion() == "RAML10"; }
[ "function isMethod(node) {\n\t return node.kind() == \"Method\" && node.RAMLVersion() == \"RAML08\";\n\t}", "_handles_method(method) {\n if (this.methods._all) {\n return true;\n }\n\n let name = method.toLowerCase();\n\n if (name === 'head' && !this.methods['head']) {\n name = 'get';\n }\n\n return Boolean(this.methods[name]);\n }", "function hasTypeAnnotation (path: NodePath): boolean {\n if (!path.node) {\n return false;\n }\n else if (path.node.typeAnnotation) {\n return true;\n }\n else if (path.isAssignmentPattern()) {\n return hasTypeAnnotation(path.get('left'));\n }\n else {\n return false;\n }\n}", "hasInheritance(node) {\n let inherits = false;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (match_1.default(child, 'extends', 'implements')) {\n inherits = true;\n }\n }\n return inherits;\n }", "function isMethodAt(thing, key) {\n return thing && typeof thing[key] === 'function';\n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }", "function check(...types) {\n for (const type of types) {\n if (type === currentToken().type) {\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'] === Bot.__pulumiType;\n }", "function instanceOf(obj, base) {\n while (obj !== null) {\n if (obj === base.prototype)\n return true;\n if ((typeof obj) === 'xml') { // Sonderfall mit Selbstbezug\n return (base.prototype === XML.prototype);\n }\n obj = Object.getPrototypeOf(obj);\n }\n\n return false;\n}", "function instanceOf(obj, func) {\n if (typeof func === 'function' && obj instanceof func) {\n return true;\n } else {\n return cajita.inheritsFrom(obj, getFakeProtoOf(func));\n }\n }", "static isRange(obj) {\n return obj instanceof Range;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }", "isFunctionOrBreed(value) {\n doCheck(\n value.constructor.name === \"Function\" || value.constructor === BreedType,\n \"Attempt to call a non-function\"\n );\n }", "isNodeOperation(value) {\n return Operation.isOperation(value) && value.type.endsWith('_node');\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServiceLinkedRole.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }", "function isValidFunctionExpression(node) {\n if (node && node.type === 'FunctionExpression' && node.body) {\n return true;\n }\n return false;\n}", "supports(name) {\r\n const isEvent = this.supportedEvents.includes(name);\r\n const isMethod = typeof this[name] === 'function';\r\n return isEvent || isMethod;\r\n }", "function ISFUNCTION(value) {\n return value && Object.prototype.toString.call(value) == '[object Function]';\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isFunctor : a > Boolean
function isFunctor(m) { return !!m && hasAlg('map', m) }
[ "function ISFUNCTION(value) {\n return value && Object.prototype.toString.call(value) == '[object Function]';\n}", "hasCallback() {}", "function isCallback(node) {\n return node && node.type === typescript_estree_1.AST_NODE_TYPES.TSFunctionType;\n }", "function isApplicativeRepr(Repr) {\n\t return typeof Repr[$of] === 'function' &&\n\t typeof Repr[$of] ()[$ap] === 'function';\n\t }", "function instanceOf(obj, func) {\n if (typeof func === 'function' && obj instanceof func) {\n return true;\n } else {\n return cajita.inheritsFrom(obj, getFakeProtoOf(func));\n }\n }", "isDelta(value) {\n\t\treturn value && value.ops;\n }", "function not(f){\n return function(){\n // console.log(arguments);\n \n var result = f.apply(this,arguments);\n return !result;\n };\n}", "function isDOMWrapper(type, value) {\n return t.logicalExpression(\"&&\", t.binaryExpression(\"===\", type, t.stringLiteral(\"function\")), t.memberExpression(value, t.identifier(\"__jsxDOMWrapper\")));\n}", "function isObject(element) {\n if (!element) return false\n if (typeof element !== 'object') return false\n if (element instanceof Array) return false\n return true\n}", "isFunctionOrBreed(value) {\n doCheck(\n value.constructor.name === \"Function\" || value.constructor === BreedType,\n \"Attempt to call a non-function\"\n );\n }", "function typeOf(obj) {\n var result = typeof obj;\n if (result !== 'object') { return result; }\n if (null === obj) { return result; }\n if (cajita.inheritsFrom(obj, DisfunctionPrototype)) { return 'function'; }\n if (cajita.isFrozen(obj) && typeof obj.call === 'function') {\n return 'function';\n }\n return result;\n }", "hasTriples(subject, predicate, object) {\n throw new Error('hasTriples has not been implemented');\n }", "function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n }", "function isCanvas(element)\n{\n\tif (typeof element !== 'object')\n\t{\n\t\treturn false;\n\t}\n\n\ttry\n\t{\n\t\tvar tag = element.tagName;\n\t}\n\tcatch (e)\n\t{\n\t\treturn false;\n\t}\n\n\treturn tag == 'CANVAS' || tag == 'canvas';\n}", "function bool(i) /* (i : int) -> bool */ {\n return $std_core._int_ne(i,0);\n}", "static pseudo_compares_as_obj(a) {\n return a['$reql_type$'] === 'GEOMETRY';\n }", "function noFlags(){\n return (typeof(p) == typeof(v));\n}", "is_op(op) {\n\t\treturn Object.keys(this.ops).includes(op);\n\t}", "some(cb) {\n for (var item = this._head; item; item = item.next) {\n if (cb(item.data)) {\n return true;\n }\n }\n return false;\n }", "function isValidFunctionExpression(node) {\n if (node && node.type === 'FunctionExpression' && node.body) {\n return true;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions used to change the vertex count of the displayed graph.
function increaseVertexCount() { let vertexCount = retrieveVertexCount(); if (vertexCount < 100) { ++vertexCount; document.getElementById("vertices").value = vertexCount.toString(); document.getElementById("vertices").dispatchEvent(new Event("change")); } }
[ "_changeVertexCount(count, semantic) {\r\n\r\n // update vertex count and validate it with existing streams\r\n if (!this.vertexCount) {\r\n this.vertexCount = count;\r\n } else {\r\n this._validateVertexCount(count, semantic);\r\n }\r\n }", "set_cellCount(newval)\n {\n this.liveFunc.set_cellCount(newval);\n return this._yapi.SUCCESS;\n }", "function updateNumberOfGuests() {\n \tcontainer.find(\"#numberOfGuests\").html(model.getNumberOfGuests());\n }", "function increaseStepCount() {\n lx.stepCount++;\n }", "function numerize() {\n for(trackListNode of getTracklistNodes())\n numerizeTracklist(trackListNode)\n}", "function updateNumberOfPlayers(){\n\n // this is the real number of players\n numberOfPlayers = inPlayerId - 1;\n}", "set ForceVertex(value) {}", "function setMinesNegsCount(board) {\r\n var currSize = gLevels[gChosenLevelIdx].SIZE;\r\n for (var i = 0; i < currSize; i++) {\r\n for (var j = 0; j < currSize; j++) {\r\n var cell = board[i][j];\r\n var count = calculateNegs(board, i, j)\r\n cell.minesAroundCount = count;\r\n }\r\n }\r\n\r\n\r\n}", "function updateCountDisplays() {\n\tdocument.getElementById(\"watcherCount\").innerHTML = ((watchers == 0) ? \"No\" : watchers) + \" viewer\" + ((watchers != 1) ? \"s\" : \"\");\n}", "function _processNodesCnt() {\n if (firstCntFlag) {\n _processNodesGlobalCnt();\n firstCntFlag = false;\n }\n\n const {nodeMap} = processedGraph;\n Object.keys(nodeMap).forEach((id) => {\n if (isNaN(id)) return;\n const node = nodeMap[id];\n const iterator = node.scope.split(SCOPE_SEPARATOR);\n\n if (!node.parent) return;\n do {\n const name = iterator.join(SCOPE_SEPARATOR);\n const scopeNode = nodeMap[name];\n if (_checkShardMethod(node.parallel_shard)) {\n if (scopeNode.specialNodesCnt.hasOwnProperty('hasStrategy')) {\n scopeNode.specialNodesCnt['hasStrategy']++;\n } else {\n scopeNode.specialNodesCnt['hasStrategy'] = 1;\n }\n }\n if (node.instance_type !== undefined) {\n if (scopeNode.specialNodesCnt.hasOwnProperty(node.instance_type)) {\n scopeNode.specialNodesCnt[node.instance_type]++;\n } else {\n scopeNode.specialNodesCnt[node.instance_type] = 1;\n }\n }\n iterator.pop();\n } while (iterator.length);\n });\n}", "function updateNitems(add=true){\n\tif(add){\n\t\tnItems++;\n\t}else{\n\t\tnItems--;\n\t}\n\tdocument.getElementById( \"counter\" ).innerHTML =nItems+\" items\";\n}", "setUsersOnline (state, count) {\n state.usersOnline = count\n }", "function increaseConnectionCount() {\n\t\tconnectionCount++;\n\t\tlogger.info(\"I have %d connections\", connectionCount);\n\t}", "function addNodeCountsToTree() {\n\t'use strict';\n\t// Iterate through all the queue nodes.\n\t$('#exploreList').children('ul').children('li').each(function() {\n\t\tvar queueId = $(this).attr('id');\n\t\t// Set that to this so we can use it in the callback.\n\t\tvar that = this;\n\t\t$.get(\n\t\t\tstarexecRoot + 'services/cluster/queues/details/nodeCount/' + queueId,\n\t\t\t'',\n\t\t\tfunction(numberOfNodes) {\n\t\t\t\tlog('numberOfNodes: ' + numberOfNodes);\n\t\t\t\t// Insert the node count span inside the node list.\n\t\t\t\t$(that)\n\t\t\t\t.prepend('<span class=\"nodeCount\">(' + numberOfNodes + ')</span>');\n\t\t\t},\n\t\t\t'json'\n\t\t);\n\t});\n}", "SetBoundingSphereCount() {}", "incDotCounter() {\n if (!this.penType) {\n this.incGhostsDots();\n } else {\n this.incGlobalDots();\n }\n }", "getVertexIndices() {\n throw new Error('getVertexIndices() not implemented.');\n }", "function addToCount() {\n totalButtonsPressed++;\n recentButtonsPressed++;\n}", "updateNeighborCounts () {\n // for each cell in the grid\n\t\tfor (var column = 0; column < this.numberOfColumns; column++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n\n\t\t\t\t// reset it's neighbor count to 0\n this.cells[column][row].liveNeighborCount = 0;\n\n\t\t\t\t// get the cell's neighbors\n\t\t\t\tthis.getNeighbors(this.cells[column][row]);\n\n\t\t\t\t// increase liveNeighborCount by 1 for each neighbor that is alive\n\t\t\t\tfor (var i = 0; i < this.getNeighbors(this.cells[column][row]).length; i++){\n\t\t\t\t\tif (this.getNeighbors(this.cells[column][row])[i].isAlive == true){\n\t\t\t\t\t\tthis.cells[column][row].liveNeighborCount += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n }\n }\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define transform stream structure
function Transform() { stream.Transform.call(this, {objectMode: true}); }
[ "function createSplitter() {\n let transform = new stream_1.Transform();\n let buffer = Buffer.alloc(0);\n transform._transform = (chunk, _encoding, callback) => {\n buffer = Buffer.concat([buffer, chunk]);\n let offset = 0;\n while (offset + 4 < buffer.length) {\n const length = buffer.readInt32LE(offset);\n if (offset + 4 + length > buffer.length)\n break;\n transform.push(buffer.slice(offset, offset + 4 + length));\n offset += 4 + length;\n }\n buffer = buffer.slice(offset);\n callback();\n };\n return transform;\n}", "function stream(opts){\n // Dispatch to tx and vechain handlers\n const handlers = (opts.handlers.tx || []).concat(opts.handlers.vechain || []);\n\n // Connect to server\n const web3 = thorify(new Web3(), opts.source || 'https://vethor-node.vechain.com/doc/swagger-ui/');\n\n // Subscribe to blocks\n const subscription = web3.eth.subscribe('newBlockHeaders')\n\n // Process transactions\n subscription.on('data', (data)=>{\n if(data.transactions.length == 0) return;\n\n // Retrieve transaction\n web3.eth.getTransaction(data.transactions[0]).then(tx => {\n // Transform transactions and forward to handlers\n const transformed = transform(tx);\n for(var h = 0; h < handlers.length; h += 1)\n handlers[h](transformed);\n })\n })\n}", "transform() {\n // check for undefined variables in the generated file to determine if there are env variables being used and such.\n this.alertForUndefinedVariables();\n // remove some of the sample files that aren't used\n this.cleanUpSDKFiles();\n // map variables as per the file\n if (this.config.variablesToReplace) {\n this.replaceVariableInFile();\n }\n\n // HTTPD.CONF METHODS\n this.createVirtualHostFiles();\n this.createVhostSymLinks();\n this.replaceVariableInVhostFile();\n this.removeNonWhitelistedDirectives();\n if (this.config.appendToVhosts) {\n this.appendAdditionalDirectives();\n }\n\n // DISPATCHER.ANY METHODS\n this.createFarmFiles();\n this.checkIncludesInFarms();\n this.checkFarmDocRoot();\n this.checkRenderers();\n this.checkCache();\n this.checkClientHeaders();\n this.checkDispatcherVirtualhosts();\n this.checkFilter();\n this.checkRewrites();\n // symlinks are created once all the content is finalized to ignore duplicate file being returned\n this.createFarmSymLinks();\n this.removeNonPublishFarms();\n // create the summary report for the conversion performed\n SummaryReportWriter.writeSummaryReport(\n this.conversionSteps,\n path.dirname(this.dispatcherConfigPath),\n Constants.DISPATCHER_CONVERTER_REPORT\n );\n }", "function generator2stream(g){\n\treturn stream.Readable({\n\t\tobjectMode:true,\n\t\tread: function(size){\n\t\t\tlet rs = g.next()\n\t\t\tif(rs.done) return this.push(null);\n\t\t\tif(rs.value instanceof Promise){\n\t\t\t\trs.value.then((data)=>{\n\t\t\t\t\tthis.push(data);\n\t\t\t\t},(err)=>{\n\t\t\t\t\tthis.push(err);\n\t\t\t\t})\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.push(rs.value)\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t})\n}", "function StreamMap (nitems, func, callback) {\n\n // input\n this.nitems = nitems || 10;\n this.func = func;\n this.cb = callback;\n\n // statistics\n this.started = 0;\n this.running = 0;\n this.finished = 0;\n\n // control\n this.consume = callback ? true : false;\n this.endingFunc = null;\n\n if (!(this instanceof StreamMap))\n return new StreamMap(this.options);\n Transform.call(this, { objectMode: true });\n\n this.on('finish', function () {\n debug('- finish', { started: this.started, running: this.running, finished: this.finished });\n });\n\n this.on('end', function () {\n debug('- end', { started: this.started, running: this.running, finished: this.finished });\n if (this.consume) this.cb(undefined, { started: this.started, running: this.running, finished: this.finished });\n });\n\n this.on('error', function (err) {\n debug('- error', err);\n if (this.consume) this.cb(err, { started: this.started, running: this.running, finished: this.finished });\n });\n\n // if we do not consume the stream, do nothing else\n if (!this.consume) {\n return;\n }\n\n this.on('readable', function () {\n debug('- readable');\n while (this.read());\n });\n}", "function transform(tx){\n return {\n blockchain : 'vechain',\n block : tx.blockNumber, // or blockRef (?)\n id : tx.id,\n source : tx.origin,\n //operations : [], // TODO: operations from clauses (transfers, contract calls)\n result : null,\n }\n}", "function makeChainTransform (chain) {\n const trsfs = chain.fields.transformationFunctions.map((trsf) => {\n if (trsf.fields.isEnabled === false) {\n return identity\n } else {\n return runModule(trsf.fields.code)\n }\n })\n return function transform (entry) {\n return trsfs.reduce((entry, t) => t(entry), entry)\n }\n}", "function compileStream() {\n\t'use strict';\n\tds.compile({\n\t\t'csdl': 'interaction.content contains \"datasift\"'\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Compiled filter hash: ' + response.hash);\n\t\t\tprepareQuery(response.hash);\n\t\t}\n\t});\n}", "function pipe() {\n const messages = getMessages();\n const msgStream = new stream.Readable({ objectMode: true });\n messages.forEach(m => msgStream.push(new Buffer(m)));\n msgStream.push(null);\n\n let processed = 0;\n const countStream = new stream.Transform({ objectMode: true,\n transform: (chunk, encoding, callback) => {\n processed++;\n callback(null, chunk);\n }\n });\n \n const out = kafka.Producer.createWriteStream(globalConfig, topicConfig, streamConfig);\n out.on('error', e => console.error('Producer stream error: ' + e));\n out.on('finish', () => {\n console.log(`Out stream finished, ${processed} items run through the pipe`);\n });\n\n msgStream.pipe(countStream).pipe(out);\n}", "function buildStreamResponse(parameters) {\n var response = new events.EventEmitter();\n response.stream = JSONStream.parse('*');\n response.index = 0;\n response.stream.on('data', function (data) {\n response.emit('data', data,\n parameters && parameters[response.index++]);\n });\n response.stream.on('end', response.emit.bind(response, 'end'));\n response.once('error', (error) => {\n response.emit('error', error, parameters);\n });\n response.isIntellogoStream = true;\n return response;\n }", "function transform (file, transformer, callback) {\n var handler;\n\n if (file.isBuffer()) {\n handler = bufferHandler;\n }\n\n if (file.isStream()) {\n handler = streamHandler;\n }\n\n // Read file buffer/stream contents\n handler.read(file.contents, function (err, contents) {\n // Pass `contents` string to transformer function\n transformer(contents, function (err, transformed) {\n if (err) {\n callback(err);\n } else {\n // Convert back `transformed` string to buffer/stream\n handler.convert(transformed, function (err, converted) {\n file.contents = converted;\n callback(null, file);\n });\n }\n });\n });\n}", "function CausalStream(parent, site, options){\n Duplex.call(this, options);\n this._parent = parent;\n this._ivv = new IVV(site);\n this._buffer = [];\n}", "function parseTransformArray(model) {\n var first = null;\n var node;\n var previous;\n var lookupCounter = 0;\n function insert(newNode) {\n if (!first) {\n // A parent may be inserted during node construction\n // (e.g., selection FilterNodes may add a TimeUnitNode).\n first = newNode.parent || newNode;\n }\n else if (newNode.parent) {\n previous.insertAsParentOf(newNode);\n }\n else {\n newNode.parent = previous;\n }\n previous = newNode;\n }\n model.transforms.forEach(function (t) {\n if (transform_1.isCalculate(t)) {\n node = new calculate_1.CalculateNode(t);\n }\n else if (transform_1.isFilter(t)) {\n // Automatically add a parse node for filters with filter objects\n var parse = {};\n var filter = t.filter;\n var val = null;\n // For EqualFilter, just use the equal property.\n // For RangeFilter and OneOfFilter, all array members should have\n // the same type, so we only use the first one.\n if (predicate_1.isFieldEqualPredicate(filter)) {\n val = filter.equal;\n }\n else if (predicate_1.isFieldRangePredicate(filter)) {\n val = filter.range[0];\n }\n else if (predicate_1.isFieldOneOfPredicate(filter)) {\n val = (filter.oneOf || filter['in'])[0];\n } // else -- for filter expression, we can't infer anything\n if (val) {\n if (datetime_1.isDateTime(val)) {\n parse[filter['field']] = 'date';\n }\n else if (vega_util_1.isNumber(val)) {\n parse[filter['field']] = 'number';\n }\n else if (vega_util_1.isString(val)) {\n parse[filter['field']] = 'string';\n }\n }\n if (util_1.keys(parse).length > 0) {\n var parseNode = new formatparse_1.ParseNode(parse);\n insert(parseNode);\n }\n node = new filter_1.FilterNode(model, t.filter);\n }\n else if (transform_1.isBin(t)) {\n node = bin_1.BinNode.makeFromTransform(t, model);\n }\n else if (transform_1.isTimeUnit(t)) {\n node = timeunit_1.TimeUnitNode.makeFromTransform(t);\n }\n else if (transform_1.isAggregate(t)) {\n node = aggregate_1.AggregateNode.makeFromTransform(t);\n if (selection_1.requiresSelectionId(model)) {\n insert(node);\n node = new indentifier_1.IdentifierNode();\n }\n }\n else if (transform_1.isLookup(t)) {\n node = lookup_1.LookupNode.make(model, t, lookupCounter++);\n }\n else {\n log.warn(log.message.invalidTransformIgnored(t));\n return;\n }\n insert(node);\n });\n var last = node;\n return { first: first, last: last };\n}", "static define(spec) {\n return new StreamLanguage(spec)\n }", "function restructureObjectStream (columns, showAllColumns) {\n return through2.obj(function (obj, enc, callback) {\n if ((columns.length > 0) && (!showAllColumns)) {\n var structuredObj = {}\n columns.forEach((el) => {\n path.set(structuredObj, el, path.get(obj, el))\n })\n this.push(structuredObj)\n } else {\n this.push(obj)\n }\n callback()\n })\n}", "function Transform() {\n _classCallCheck(this, Transform);\n\n this.matrix = Matrix.identity(3);\n this._centerPoint = new Point(0, 0);\n }", "pipe(out) { return reduce(((x, y) => x.pipe(y)), this.streams[0], this.streams.slice(1)).pipe(out); }", "function IcecastWriteStack(stream, metaint) {\n StreamStack.call(this, stream);\n this.metaint = metaint;\n this.counter = 0;\n this._metadataQueue = [];\n}", "function StreamChecker(options) {\n if (!(this instanceof StreamChecker)) {\n return new StreamChecker(options);\n }\n\n if (!options) {\n options = {};\n }\n\n options.objectMode = true;\n stream.Transform.call(this, options);\n\n this.status = {\n 'pass': 'P',\n 'fail': 'F',\n 'time': 'T',\n 'error': 'E'\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the duration of the video changes. Updates the duration text as appropriate.
function onDurationChange(e) { var newDuration = Math.floor(video.duration); if (newDuration != durInt) { durInt = newDuration; dur_str = " / " + toTimeString(durInt); updateTimeBar(); } }
[ "function updateTimeElapsed() {\n var time = formatTime(Math.round(video.currentTime));\n timeElapsed.innerText = formatTimeHumanize(time);\n timeElapsed.setAttribute('datetime', `${time.hours}h ${time.minutes}m ${time.seconds}s`);\n }", "function updateDurationLabel() {\n if (dataAvailable) {\n durationLabel.innerText = parseTime(audioPlayer.currentTime) + \" / \" + parseTime(currentLength);\n } else {\n durationLabel.innerText = parseTime(audioPlayer.currentTime);\n }\n}", "function updateDuration() {\n\tconst deltaS = (dateInput(\"dateEnd\") + timeInput(\"timeEnd\") - (dateInput(\"dateStart\") + timeInput(\"timeStart\"))) / 1000;\n\tconst round = 3600 / parseInt(ele(\"timeResolutionsInput\").value);\n\tconst duration = Math.ceil(deltaS / round) * round;\n\tconst hours = Math.floor(duration / 3600);\n\tconst minutes = Math.floor((duration - hours * 3600) / 60);\n\tconst seconds = Math.floor(duration - hours * 3600 - minutes * 60);\n\tele(\"duration\").innerText = `${hours}:${pad(minutes, 2)}:${pad(seconds, 2)}`;\n}", "function updateVideoCurrentTime() {\n let curtime = convertSecondsToMinutes(video.currentTime);\n videotime.innerHTML = curtime+' / '+videoduration;\n }", "function onTimeUpdate(e) {\n var newTime = Math.floor(video.currentTime);\n if (newTime != timeInt) {\n timeInt = newTime;\n time_str = toTimeString(timeInt);\n updateTimeBar();\n }\n}", "handleDurationchange() {\n if (this.player_.duration() === Infinity) {\n this.startTracking();\n } else {\n this.stopTracking();\n }\n }", "function _updateDurationSettings() {\n durationPerMeasure = divisions * (4 / beatType) * beats;\n }", "function decreaseDuration() {\n let durationDisplay = $(\"selectedDuration\");\n let duration = parseInt(durationDisplay.textContent);\n if (duration > 1) {\n durationDisplay.textContent = (duration - 1) + \" hour(s) long\";\n }\n }", "formatVideoLength(time = null){\n if(time == null) return ;\n \n var a = time.match(/\\d+H|\\d+M|\\d+S/g);\n var result = 0;\n \n var d = { 'H': 3600, 'M': 60, 'S': 1 };\n var num;\n var type;\n \n for (var i = 0; i < a.length; i++) {\n num = a[i].slice(0, a[i].length - 1);\n type = a[i].slice(a[i].length - 1, a[i].length);\n \n result += parseInt(num) * d[type];\n }\n\n //Format seconds to actual time\n d = Number(result);\n var h = Math.floor(d / 3600);\n var m = Math.floor(d % 3600 / 60);\n var s = Math.floor(d % 3600 % 60);\n\n var hDisplay = h > 0 ? h + (h == 1 ? \" hour, \" : \" hours, \") : \"\";\n var mDisplay = m > 0 ? m + (m == 1 ? \" minute, \" : \" minutes, \") : \"\";\n var sDisplay = s > 0 ? s + (s == 1 ? \" second\" : \" seconds\") : \"\";\n return hDisplay + mDisplay + sDisplay;\n }", "function updateCurrentTime() {\n video.currentTime = (progress.value * video.duration) / 100;\n}", "function displayTimestampTotal() {\n timeTotal.innerText = `${timeFormat(video.duration).minutes}:${timeFormat(video.duration).seconds}`;\n}", "increaseTime() {\r\n this.duration += 1;\r\n }", "set duration(val) {\n this.timestamp.end = new Date(this.timestamp.start);\n this.timestamp.end.setHours(this.timestamp.end.getHours()+val);\n }", "function increaseDuration() {\n let maxDuration = 4; // MODDABLE\n let durationDisplay = $(\"selectedDuration\");\n let duration = parseInt(durationDisplay.textContent);\n if (duration < maxDuration) {\n let hr = parseInt($(\"selectedHour\").textContent);\n // if no hour is selected then there is no problem updating duration\n if (isNaN(hr)) {\n durationDisplay.textContent = duration + 1 + \" hour(s) long\";\n } else { // hour is selected, make sure it works with the duration\n // convert hr to 0-23\n if ($(\"selectedHour\").textContent.split(\" \")[1] == \"PM\") {\n if (hr == 12) {\n hr = 0;\n }\n hr += 12;\n } else {\n if (hr == \"12\") {\n hr = 0;\n }\n }\n if (hr + duration + 1 <= parseInt(normalHours.start) + parseInt(normalHours.num_hours)) {\n durationDisplay.textContent = (duration + 1) + \" hour(s) long\";\n }\n }\n }\n }", "function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }", "function updateProgressValue() {\n progressBar.max = song.duration;\n progressBar.value = song.currentTime;\n document.querySelector('.currentTime').innerHTML = formatTime(Math.floor(song.currentTime));\n if (document.querySelector('.durationTime').innerHTML === 'NaN:NaN') {\n document.querySelector('.durationTime').innerHTML = '0:00';\n } else {\n document.querySelector('.durationTime').innerHTML = formatTime(Math.floor(song.duration));\n }\n}", "updateVideoTime(videoPlayer, time) {\n videoPlayer.currentTime = time;\n \n }", "set overridedDuration(duration) {\r\n this._durationOverrided = true;\r\n this._duration = duration;\r\n this._mediaInfo.duration = duration;\r\n }", "updateElapsedTime(){\n\t\tthis.props.updateElapsedTime(this.refs.audioElement.currentTime);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
De fibbonacci getallen is een rij getallen die begint met 1, 1. Het volgende getal is steeds de som van de twee vorige getallen, dus 1, 1, 2, 3, 5, 8, 13 enz. Deze functie geeft een array terug met daarin de fibbonacci reekst tot en met het getal n. De reeks begint met n = 0, dus fibbonacci(8) geeft [1, 1, 2, 3, 5, 8, 13, 21, 34] tip: met uitkomst.push(5) voeg je het getal 5 aan de array 'uitkomst' toe
function fibbonacci(n) { var uitkomst = []; // the magic starts here... return uitkomst; }
[ "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 fibb() {\n var list = [0,1];\n for( i = 2; i < 100; i++) {\n\tlist[i] = list[i-1] + list[i-2];\n }\n return list;\n}", "function fibonacciSequence() {\n\tlet arr = [0, 1];\n\tfor(let i = 2; ; i++){\n\t\tlet item = arr[i-1] + arr[i-2];\n\t\tif (item < 255){\n\t\t\tarr.push(item);\n\t\t}else{\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn arr;\n}", "function displayFibonacciArray(fibCount){\n\tgetFibonacciArray(fibCount);\n}", "function genfib() {\n let arr = [];\n\n return function fib() {\n if (arr.length === 0) {\n arr.push(0);\n } else if (arr.length === 1) {\n arr.push(1);\n } else {\n arr.push(arr[arr.length - 2] + arr[arr.length - 1]);\n }\n\n return arr[arr.length - 1];\n }\n}", "function fibArrayWithFibIterator(inputIteration){\n for(var i = 1; i <= inputIteration; i ++){\n var pushMe = fibIterator(i);\n fibArray.push(pushMe);\n }\n return fibArray;\n}", "function FibonacciSumEven (n) {\n let start = [1, 2];\n let sumOfEven = 2;\n\n for (let i = start.length-1; i < n-2; i++) {\n let nextNumb = start[i] + start[i-1];\n start.push(nextNumb);\n if (nextNumb % 2 === 0) {\n sumOfEven += nextNumb;\n }\n }\n\n return sumOfEven;\n}", "function chebab(a,b,n)\n{\n var xnodes=linspace(1/(2*n+2)*Math.PI,(2*n+1)/(2*n+2)*Math.PI,n+1);\n// disp(xnodes)\n var abnodes=zeros(n+1,1);\n for(var i=0;i<=n;i++)\n {\n\tabnodes[n-i]= (Math.cos(xnodes[i])+1)/2*(b-a)+a;\n }\n return(abnodes)\n\n}", "function faculteit(n) {\n\n}", "function faktorial(n)\r\n{\r\n\tif (n == 0) return 1\r\n\treturn n * faktorial( n - 1 ) // 5 * ( 4 * ( 3 * ( 2 * ( 1 ) ) ) )\r\n}", "function isFibonacci(num) {\n var fibonacci = [0, 1];\n var sum = 0;\n while (sum < num) {\n sum = fibonacci[fibonacci.length-1] + fibonacci[fibonacci.length-2];\n fibonacci.push(sum);\n }\n return num === sum;\n}", "function nearestFibonacci(num)\n{\n // Base Case\n if (num == 0) {\n return;\n }\n \n // Initialize the first & second\n // terms of the Fibonacci series\n let first = 0, second = 1;\n \n // Store the third term\n let third = first + second;\n \n // Iterate until the third term\n // is less than or equal to num\n while (third <= num) {\n \n // Update the first\n first = second;\n \n // Update the second\n second = third;\n \n // Update the third\n third = first + second;\n }\n \n // Store the Fibonacci number\n // having smaller difference with N\n let ans = (Math.abs(third - num)\n >= Math.abs(second - num))\n ? second\n : third;\n \n // Print the result\n console.log(ans)\n}", "function fib(index) {\n var r;\n for (r of fibGen(index))\n ;\n return r;\n}", "function Start()\n{\n\t//Will contain all calculated fibonacci values\n\tvar aftermath = [0,1];\n\t\n\t//The \"+\" operator is used to convert from string to number \n\tvar userInput = +document.getElementById('followup').value;\n\t\n\t\n\tFibonacci(userInput,aftermath);\n\t\n\tResult(aftermath[userInput]);\n\t\n}", "function rFib(num){\n if(num == 0){ //there is no 0 in fibonacci\n return 0\n }\n else if(num == 1){ //base case\n return 1\n }\n else if(num == 2){ //second base case\n return 1\n }\n else if(num % 1 > 0){\n return rFib(Math.floor(num)) //floor any non whole number\n }\n else{\n return rFib(num - 1) + rFib(num - 2) //start the call stack until base cases are reached\n }\n}", "function addOne(arr) {\n let carry = 1\n let result = []\n for (let i = arr.length - 1; i >= 0; i--) {\n console.log(i)\n const total = arr[i] + carry\n if(total === 10) {\n carry = 1\n } else {\n carry = 0\n }\n result[i] = total % 10\n }\n if(carry === 1) {\n for(let i = 0; i < arr.length + 1; i++) {\n result[i] = 0\n }\n result[0] = 1\n }\n console.log('result',result)\n return result\n}", "function dynamicProgramming(coins, sum) {\n if (coins.length < 1) return 0\n const table = [...Array(sum + 1)].map(e => Array(coins.length + 1).fill(0))\n // when sum is 0, there's 1 way to fulfil it. simply by doing nothing\n for (let i = 0; i < table[0].length; i++) {\n table[0][i] = 1\n }\n for (let i = 1; i < table.length; i++) {\n for (let j = 1; j < table[i].length; j++) {\n table[i][j] = table[i][j-1]\n if (i - coins[j-1] >= 0) {\n table[i][j] += table[i-coins[j-1]][j]\n }\n }\n }\n console.log(table)\n return table[table.length-1][table[0].length-1]\n}", "countingBills(input) {\n // Set sum to zero\n let sum = 0;\n // Represent denominations of money\n let bills = [1,5,10,20,50,100];\n // Multiply the first number of bills by 1 and add to sum\n // Multiply the second number of bills by 5 and add to sum\n // Multiply the third number of bills by 10 and add to sum\n // Multiply the fourth number bills by 20 and add to sum\n // Multiply the fifth number bills by 50 and add to sum\n // Multiply the sixth number bills by 100 and add to sum\n for(let i = 0; i < input.length; i++ ){\n sum += input[i] * bills[i];\n }\n \n // Output sum\n return sum; \n }", "function recursiveNthFib(n) {\n // initialization a cache array with a lenght of n\n const cache = Array(n); // cache.length returns n\n\n // define a recursive helper function\n function recursiveHelper(n) {\n // try to access the answer from the cache\n let answer = cache(n);\n\n if (!answer) {\n answer = naiveNthFib(n);\n // save this answer in our cache\n cache(n) = answer;\n }\n\n return answer;\n }\n // don't foget to call the recursiveHelper\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if user list box is already open
function checkUserAccessVal(resource_id) { // If user list box is already open on same row, then close it (i.e. user clicked the link to close it) if ($('#input_linkusers_selected_id_'+resource_id).prop('checked') && $('#user_current_resource_id').val() == resource_id && $('#choose_user_div').css('display') != 'none') { $('#cancel_user_btn').click(); return; } // Now go ahead and check it $('#input_linkdags_selected_id_'+resource_id).prop('checked',false); $('#input_linkusers_all_id_'+resource_id).prop('checked',false); $('#input_linkusers_selected_id_'+resource_id).prop('checked',true); // Open the user list box selectResourceUsers(resource_id); }
[ "function checkDagAccessVal(resource_id) {\r\n\t// If user list box is already open on same row, then close it (i.e. user clicked the link to close it)\r\n\tif ($('#input_linkdags_selected_id_'+resource_id).prop('checked') && $('#dag_current_resource_id').val() == resource_id && $('#choose_dag_div').css('display') != 'none') {\r\n\t\t$('#cancel_dag_btn').click();\r\n\t\treturn;\r\n\t}\r\n\t// Now go ahead and check it\r\n\t$('#input_linkusers_all_id_'+resource_id).prop('checked',false);\r\n\t$('#input_linkusers_selected_id_'+resource_id).prop('checked',false);\r\n\t$('#input_linkdags_selected_id_'+resource_id).prop('checked',true);\r\n\t// Open the user list box\r\n\tselectResourceDags(resource_id);\r\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 }", "isLoginAndRegisterPopUpDisplayed() {\n return elementUtil.isElementDisplayed(this.loginAndRegisterPopUp);\n }", "function checkLogedInUser() {\n\n}", "function finalListIsEmpty(){\r\n\t\t\t//user selected at least 1 item\r\n\t\t\tif($('#prettyList li').length > 0){\r\n\t\t \t$('.listIsEmpty').css(\"display\", \"none\");\r\n\t\t \t$('#submitBtn').show();\r\n\t\t \t$('#changeSomethingBtn').show();\r\n\t\t\t}\r\n\t\t\t//user didnt choose any items but clicked button to proceed\r\n\t\t\telse{ \r\n\t\t\t\t$('.listIsEmpty').css(\"display\", \"block\");\r\n\t\t \t$('#submitBtn').hide();\r\n\t\t \t$('#changeSomethingBtn').hide();\r\n\t\t\t}\r\n\t\t}", "isAdding() {\n return Template.instance().uiState.get(\"addChat\") == CANCEL_TXT;\n }", "function isDialogVisible() {\n return getActivePage().find('.ui-popup-container').not('.ui-popup-hidden').length > 0;\n}", "function isDialogOpened(){\n return (ipc.sendSync('isDialogOpenedRequest'));\n}", "function isWaitingListExisting() {\n\tvar waitingList = spaceExpressConsoleDrawing.employeesWaiting;\n\tif(waitingList.length > 0) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function checkForInviteBox() {\r\n\t\t// Get container of invite dialog.\r\n\t\tvar inviteBoxCheck = document.getElementsByClassName('eventInviteLayout')[0] || document.getElementsByClassName('standardLayout')[0] ||\r\n\t\t\tdocument.getElementById('fb_multi_friend_selector_wrapper');\r\n\t\t\r\n\t\t// Check for match of inviteBoxCheck, and the TBODY that is later used as an insertion anchor.\r\n\t\tif (inviteBoxCheck && inviteBoxCheck.getElementsByTagName('tbody')[0]) {\r\n\t\t\t// Add the button.\r\n\t\t\taddButton(inviteBoxCheck);\r\n\t\t\t\r\n\t\t\t// Can not be used at the moment. I have not found a way to re-apply the event handler.\r\n\t\t\t/* Remove node insertion watcher (it's strange, but it needs to be delayed a ms)\r\n\t\t\twindow.setTimeout(function () {\r\n\t\t\t\twindow.removeEventListener('DOMNodeInserted', checkForInviteBox, false);\r\n\t\t\t }, 1);\r\n\t\t\t*/\r\n\t\t}\r\n\t}", "function openClose__UserTool() {\n $('.list__Tool-User').toggleClass('display__block');\n}", "function isPrivateLobby(name){\n for(var i = 0; i < private_lobby_list.length; i++){\n if(private_lobby_list[i].name === name){\n return true;\n }\n }\n return false;\n}", "function isUserStillWaiting(request) {\n\treturn false; //Allow user to return the pool for selection.\n}", "function _isPanelOpen() {\n return $issuesPanel.is(\":visible\");\n }", "function openLogin(){\n\n $(\"#login_popup\").show();\n popupIsOpen = true;\n\n}", "function addGuest() {\n enterGuest();\n dialog.dialog(\"close\");\n // This probably doesn't belong here, but it seems to work. It prevents the following: fill out form, click review, click add guest, menu is still showing. Which is not a real big problem, since clicking will not attend still hides the menu.\n $(\"#menuChoice\").addClass(\"hidden\");\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 checkMenu() {\n if ($(\"header\").is(\":visible\")) {\n closeMenu();\n } else {\n openMenu();\n }\n}", "function showItems() {\n // Get li's in list\n var listitems = $('li.alert');\n if(listitems.length <= 1) {\n $('#alertgroupParent').hide();\n // parentList.parents('ul').hide();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a util function checks whether the campaign is in contractual status. if true, then the contract information cannot be modified.
function check_contract_signing_status(brand_campaign_id, account_id){ return get_inf_status(brand_campaign_id, account_id) .then(res => { if (res.inf_status && res.inf_status.indexOf('contract') !== -1){ return true; } return false; }); }
[ "checkContract() {\n if (!isDef(this.contract)) {\n throw new Error('Contract not defined. It was probably never deployed');\n }\n }", "function isContractPayable(definition) {\n let fallback = definition.nodes.find(node => node.nodeType === \"FunctionDefinition\" &&\n functionKind(node) === \"fallback\");\n if (!fallback) {\n return false;\n }\n return mutability(fallback) === \"payable\";\n }", "function isCampaignSet() {\n if (allUrlParameters.hasOwnProperty('utm_campaign')){\n return allUrlParameters.utm_campaign;\n } else {\n return '(not set)';\n }\n}", "canInputFieldDisabled() {\n if (this.isIndianSubsidiary)\n return !(\n this.rule.fieldName === this.FIELD_NAME_LIST.vat &&\n this.user.legalform !== USER_TYPE_ENTERPRISE\n );\n return this.rule.fieldName === this.FIELD_NAME_LIST.customerCode;\n }", "function checkForSale() {if (canBorrowMoney === true){console.log (person + \" is approved for the loan!\");\n return status === true;\n}else {\n console.log(person + \" not approved for the loan.\");\n}\n return status === false;\n}", "function checkForChallengesAllowed() {\n vm.challengesAllowed = true;\n // Check for allowed weekend challenges\n if (!vm.competition.allowWeekendChallenges &&\n ((moment().format('ddd') === 'Fri' && moment().format('H') >= 17) ||\n moment().format('ddd') === 'Sat' ||\n moment().format('ddd') === 'Sun')) {\n vm.challengesAllowed = false;\n }\n }", "validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }", "isLockedWork() {\n let userId = userService.getLoggedId();\n let attendance = attendanceService.getAttendance(workToEdit.idAttendance);\n if(!attendance || !attendance.approved)\n return false;\n return true;\n }", "function isRequired(state: ConsentState, filter?: (country: any) => boolean) {\n const { countryCode, consented, previouslyConsented } = state;\n // Affected countries: EEA members except Germany and Austria\n if (!window.champaign) return false;\n const countries = window.champaign.countries\n .filter(c => c.eea_member)\n .filter(filter || (() => true))\n .map(c => c.alpha2);\n const inAffectedCountry = includes(countries, countryCode);\n return inAffectedCountry && !previouslyConsented && consented === null;\n}", "checkInvoiceStatus({commit}, payload) {\n\t\t\tfunction getInvoiceStatus({commit}, payload) {\n\t\t\t\taxios\n\t\t\t\t\t.get( $axios + '/invoices/statusByMonth/' + payload.month +'/'+ payload.clientId)\n\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\tcommit('SET_INVOICE_STATUS_BY_MONTH', response.data)\n\t\t\t\t\t})\n\t\t\t}\n\t\t\tgetInvoiceStatus({commit}, payload);\n\t\t}", "toggleApproval(currency, current_approval) {\n let new_approval = !current_approval\n if(new_approval) {\n this.approveCurrency(currency)\n } else {\n this.unapproveCurrency(currency)\n }\n }", "function isAccessibleByTransportMode() {}", "getCheckCompanyCode() {\n\t\t\n\t\tvar flag = true;\n\t\tconsole.log(\"comp\");\n\t\tconsole.log(this.state.compId);\n\t\tif (this.state.selectedCompany.name === \"Trader Company\" || this.state.selectedCompany.name === \"Broker Company\") {\n\t\t\t\n\t\tif (this.state.compId.compCode =this.state.userJson[\"companyCode\"]){\n\t\t\tflag = true;\n\t\t\t\n\t\t}\n\t\t else flag = false;\n\t\t}\n\t\treturn flag;\n\t}", "function Active_DeactiveCampaign(record) {\n debugger;\n var Enabled = record.Enabled;\n var message = \"\";\n if (Enabled == \"False\") {\n message = confirm('Are you sure you want to activate this item?');\n }\n else {\n message = confirm('Are you sure you want to de-activate this item?');\n }\n\n if (message != 0) {\n return true;\n }\n else {\n return false;\n }\n\n\n}", "function isValid(entry) {\n if (entry.status && entry.lastName && entry.dateKey) {return true}\n else {return false}\n }", "async isPaused() {\n await this.getContract()\n return await this.contract.methods.paused().call()\n }", "function checkStatus() {\n\t'use strict';\n\tconsole.log('Checking data coverage for our query period');\n\n\tds.historics.status({\n\t\t'start': startTime,\n\t\t'end': endTime\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic status for query period: ' + JSON.stringify(response));\n\t\t\tcompileStream();\n\t\t}\n\t});\n}", "checkActionStatus() {\n if (this.state >= SolairesAction.STATUS.DONE)\n return;\n if (this.state == SolairesAction.STATUS.ACK)\n SolairesAction.updateGMAck(false);\n }", "function hasChanged(oldCampaign, newCampaign) {\n for (var key in newCampaign) {\n var oldAttr = oldCampaign[key];\n var newAttr = newCampaign[key];\n\n if (\n newAttr !== oldAttr &&\n !(isEmptyArray(newAttr) && isEmptyArray(oldAttr))\n ) {\n return true;\n }\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the value of the current input focused or 1 if not found any
async getFocusedValue() { const focusedInput = await this.getFocusedInput(); if (focusedInput) { return focusedInput.getValue(); } return undefined; }
[ "focusedTabIndex() {\n\t\tvar index = this.tabs.findIndex(function(tab) {\n\t\t\treturn tab === document.activeElement;\n\t\t});\n\n\t\treturn (index === -1) ? 0 : index;\n\t}", "function spinputvalue () {\n if (!isContentEditable) return element.value;\n return element.innerText;\n }", "function inputValue() {\n //*1 Get clicked numpad value\n const value = getNumpadValue();\n\n //*2 if a digit has been clicked\n if (value !== 0 && !isNaN(value)) {\n setCellValue(value);\n } else if (value === \"clear\") {\n setCellValue(\"\");\n } else return;\n resetNumpad();\n}", "function findSearchValue() {\n return $('#search-input').val();\n}", "function getInputValue(id) {\n var inputValue = document.getElementById(id).value;\n return parseInt(inputValue, 10);\n}", "get focusChanged() {\n return (this.flags & 1) /* Focus */ > 0\n }", "function inputvalue(){\n return input.value\n}", "function getActiveItemValue()/*:**/ {\n return AS3.getBindable(this,\"activeItemValueExpression\").getValue();\n }", "getItemOfCurrentModel() {\n const e = this.modelValue;\n return fn(this.choicesInstance._store.choices, (t) => t.value == e);\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}", "function focus_curve_ind ()\r\n{\r\n\t// get index of curve in focus\r\n\tvar curve_in_focus = selections.focus();\r\n\r\n\t// return local index of curve\r\n\tvar curve_in_focus_ind = -1;\r\n\r\n // find curve index, if not null\r\n var curr_sel_ind = 0;\r\n for (var k = 0; k < max_num_sel; k++) {\r\n\r\n // check for curve index in current selection\r\n var ind_sel = selections.in_filtered_sel_x(curve_in_focus, k+1);\r\n\r\n // if found index (and within max number of plots), we're done\r\n if ((ind_sel != -1) &&\r\n (ind_sel < max_num_plots)) {\r\n curve_in_focus_ind = ind_sel + curr_sel_ind;\r\n break;\r\n }\r\n\r\n // otherwise, update index into selection\r\n curr_sel_ind = curr_sel_ind + Math.min(selections.len_filtered_sel(k+1), max_num_plots);\r\n\r\n }\r\n\r\n\treturn curve_in_focus_ind;\r\n}", "_containsFocus() {\n const activeElement = _getFocusedElementPierceShadowDom();\n return activeElement && this._element.nativeElement.contains(activeElement);\n }", "function view_GetFooterFormGradeInputValue() {\n return parseInt($(\"#input-grade\").val());\n}", "_handleFocusChange() {\n this.__focused = this.contains(document.activeElement);\n }", "_getTabIndex() {\n if (this.disabled) {\n return -1;\n }\n return this.useActiveDescendant || !this.listKeyManager.activeItem ? this.enabledTabIndex : -1;\n }", "function IsWindowFocused(flags = 0) {\r\n return bind.IsWindowFocused(flags);\r\n }", "get attachTargetFocused() {\n return this.isFocused(document.activeElement) || this.attachTarget === this.lastActiveElement;\n }", "function getViewState() {\n\t\tfor (var i = 0; i < document.forms.length; i++) {\n\t\t\tvar viewStateElement = document.forms[i][VIEW_STATE_PARAM];\n\n\t\t\tif (viewStateElement) {\n\t\t\t\treturn viewStateElement.value;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "getInputProperty(input) {\n if (input.tagName === 'TEXTAREA') return 'value';\n if (input.tagName === 'SELECT') return 'value';\n if (input.tagName === 'OPTION') return 'selected';\n if (input.tagName === 'INPUT') {\n const type = input.getAttribute('type');\n if (['radio', 'checkbox'].includes(type)) return 'checked';\n return 'value';\n }\n console.warn('FormSync: Cannot synchronize value of form element %o, is unknown.', input);\n return 'value';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Triggered when an external subject token is needed to be exchanged for a GCP access token via GCP STS endpoint. This uses the `options.credential_source` object to figure out how to retrieve the token using the current environment. In this case, this uses a serialized AWS signed request to the STS GetCallerIdentity endpoint. The logic is summarized as: 1. Retrieve AWS region from availabilityzone. 2a. Check AWS credentials in environment variables. If not found, get from securitycredentials endpoint. 2b. Get AWS credentials from securitycredentials endpoint. In order to retrieve this, the AWS role needs to be determined by calling securitycredentials endpoint without any argument. Then the credentials can be retrieved via: securitycredentials/role_name 3. Generate the signed request to AWS STS GetCallerIdentity action. 4. Inject xgoogcloudtargetresource into header and serialize the signed request. This will be the subjecttoken to pass to GCP STS.
async retrieveSubjectToken() { // Initialize AWS request signer if not already initialized. if (!this.awsRequestSigner) { this.region = await this.getAwsRegion(); this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { // Check environment variables for permanent credentials first. // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html if (process.env['AWS_ACCESS_KEY_ID'] && process.env['AWS_SECRET_ACCESS_KEY']) { return { accessKeyId: process.env['AWS_ACCESS_KEY_ID'], secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], // This is normally not available for permanent credentials. token: process.env['AWS_SESSION_TOKEN'], }; } // Since the role on a VM can change, we don't need to cache it. const roleName = await this.getAwsRoleName(); // Temporary credentials typically last for several hours. // Expiration is returned in response. // Consider future optimization of this logic to cache AWS tokens // until their natural expiration. const awsCreds = await this.getAwsSecurityCredentials(roleName); return { accessKeyId: awsCreds.AccessKeyId, secretAccessKey: awsCreds.SecretAccessKey, token: awsCreds.Token, }; }, this.region); } // Generate signed request to AWS STS GetCallerIdentity API. // Use the required regional endpoint. Otherwise, the request will fail. const options = await this.awsRequestSigner.getRequestOptions({ url: this.regionalCredVerificationUrl.replace('{region}', this.region), method: 'POST', }); // The GCP STS endpoint expects the headers to be formatted as: // [ // {key: 'x-amz-date', value: '...'}, // {key: 'Authorization', value: '...'}, // ... // ] // And then serialized as: // encodeURIComponent(JSON.stringify({ // url: '...', // method: 'POST', // headers: [{key: 'x-amz-date', value: '...'}, ...] // })) const reformattedHeader = []; const extendedHeaders = Object.assign({ // The full, canonical resource name of the workload identity pool // provider, with or without the HTTPS prefix. // Including this header as part of the signature is recommended to // ensure data integrity. 'x-goog-cloud-target-resource': this.audience, }, options.headers); // Reformat header to GCP STS expected format. for (const key in extendedHeaders) { reformattedHeader.push({ key, value: extendedHeaders[key], }); } // Serialize the reformatted signed request. return encodeURIComponent(JSON.stringify({ url: options.url, method: options.method, headers: reformattedHeader, })); }
[ "async getSecurityToken() {\n if (isSasTokenProvider(this._context.tokenCredential)) {\n // the security_token has the $management address removed from the end of the audience\n // expected audience: sb://fully.qualified.namespace/event-hub-name/$management\n const audienceParts = this.audience.split(\"/\");\n // for management links, address should be '$management'\n if (audienceParts[audienceParts.length - 1] === this.address) {\n audienceParts.pop();\n }\n const audience = audienceParts.join(\"/\");\n return this._context.tokenCredential.getToken(audience);\n }\n // aad credentials use the aad scope\n return this._context.tokenCredential.getToken(Constants.aadEventHubsScope);\n }", "function main(\n sourceName = 'FULL_PATH_TO_SOURCE',\n user = 'someuser@domain.com'\n) {\n // [START securitycenter_set_source_iam]\n // Imports the Google Cloud client library.\n const {SecurityCenterClient} = require('@google-cloud/security-center');\n\n // Creates a new client.\n const client = new SecurityCenterClient();\n\n async function setSourceIamPolicy() {\n // sourceName is the full resource name of the source to be\n // updated.\n // user is an email address that IAM can grant permissions to.\n /*\n * TODO(developer): Uncomment the following lines\n */\n // const sourceName = \"organizations/111122222444/sources/1234\";\n // const user = \"someuser@domain.com\";\n const [existingPolicy] = await client.getIamPolicy({\n resource: sourceName,\n });\n\n const [updatedPolicy] = await client.setIamPolicy({\n resource: sourceName,\n policy: {\n // Enables partial update of existing policy\n etag: existingPolicy.etag,\n bindings: [\n {\n role: 'roles/securitycenter.findingsEditor',\n // New IAM Binding for the user.\n members: [`user:${user}`],\n },\n ],\n },\n });\n console.log('Updated policy: %j', updatedPolicy);\n }\n setSourceIamPolicy();\n // [END securitycenter_set_source_iam]\n}", "function createTokenForCRM() {\n var api_user = {\n user_id: user.user_id,\n email: user.email,\n name: user.name\n };\n\n var options = {\n subject: user.id,\n expiresInMinutes: 60,\n audience: configuration.telco_crm_api_client_id,\n issuer: 'https://sandrino-dv.auth0.com'\n };\n\n return jwt.sign(api_user, \n new Buffer(configuration.telco_crm_api_client_secret, 'base64'), options); \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 }", "static getRequestorOrg(ctx) {\n\t\t//Return requestor MSP value\n\t\treturn ctx.clientIdentity.getMSPID();\n\t}", "static createFromGoogleCredential(googleCredentials) {\n return CallCredentials.createFromMetadataGenerator((options, callback) => {\n let getHeaders;\n if (isCurrentOauth2Client(googleCredentials)) {\n getHeaders = googleCredentials.getRequestHeaders(options.service_url);\n }\n else {\n getHeaders = new Promise((resolve, reject) => {\n googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {\n if (err) {\n reject(err);\n return;\n }\n if (!headers) {\n reject(new Error('Headers not set by metadata plugin'));\n return;\n }\n resolve(headers);\n });\n });\n }\n getHeaders.then(headers => {\n const metadata = new metadata_1.Metadata();\n for (const key of Object.keys(headers)) {\n metadata.add(key, headers[key]);\n }\n callback(null, metadata);\n }, err => {\n callback(err);\n });\n });\n }", "async function authorize_request(req) {\n await req.sts_sdk.authorize_request_account(req);\n await authorize_request_policy(req);\n}", "getV3ProjectsIdTriggersToken(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let token = \"token_example\";*/ // String | The unique token of trigger\napiInstance.getV3ProjectsIdTriggersToken(incomingOptions.id, incomingOptions.token, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function fromCognitoIdentityPool(_a) {\n var _this = this;\n var accountId = _a.accountId, _b = _a.cache, cache = _b === void 0 ? Object(_localStorage__WEBPACK_IMPORTED_MODULE_4__[\"localStorage\"])() : _b, client = _a.client, customRoleArn = _a.customRoleArn, identityPoolId = _a.identityPoolId, logins = _a.logins, _c = _a.userIdentifier, userIdentifier = _c === void 0 ? !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined : _c;\n var cacheKey = userIdentifier ? \"aws:cognito-identity-credentials:\" + identityPoolId + \":\" + userIdentifier : undefined;\n var provider = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(_this, void 0, void 0, function () {\n var identityId, _a, _b, IdentityId, _c, _d, _e, _f;\n var _g;\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_h) {\n switch (_h.label) {\n case 0:\n _a = cacheKey;\n if (!_a) return [3 /*break*/, 2];\n return [4 /*yield*/, cache.getItem(cacheKey)];\n case 1:\n _a = (_h.sent());\n _h.label = 2;\n case 2:\n identityId = _a;\n if (!!identityId) return [3 /*break*/, 7];\n _d = (_c = client).send;\n _e = _aws_sdk_client_cognito_identity__WEBPACK_IMPORTED_MODULE_1__[\"GetIdCommand\"].bind;\n _g = {\n AccountId: accountId,\n IdentityPoolId: identityPoolId\n };\n if (!logins) return [3 /*break*/, 4];\n return [4 /*yield*/, Object(_resolveLogins__WEBPACK_IMPORTED_MODULE_5__[\"resolveLogins\"])(logins)];\n case 3:\n _f = _h.sent();\n return [3 /*break*/, 5];\n case 4:\n _f = undefined;\n _h.label = 5;\n case 5: return [4 /*yield*/, _d.apply(_c, [new (_e.apply(_aws_sdk_client_cognito_identity__WEBPACK_IMPORTED_MODULE_1__[\"GetIdCommand\"], [void 0, (_g.Logins = _f,\n _g)]))()])];\n case 6:\n _b = (_h.sent()).IdentityId, IdentityId = _b === void 0 ? throwOnMissingId() : _b;\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(function () { });\n }\n _h.label = 7;\n case 7:\n provider = Object(_fromCognitoIdentity__WEBPACK_IMPORTED_MODULE_3__[\"fromCognitoIdentity\"])({\n client: client,\n customRoleArn: customRoleArn,\n logins: logins,\n identityId: identityId,\n });\n return [2 /*return*/, provider()];\n }\n });\n }); };\n return function () {\n return provider().catch(function (err) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(_this, void 0, void 0, function () {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_a) {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(function () { });\n }\n throw err;\n });\n }); });\n };\n}", "async function verify( token ) {\n const ticket = await client.verifyIdToken({\n idToken: token,\n audience: CLIENT_ID, \n });\n //En el payload vamos a tener toda la informacion del usuario\n const payload = ticket.getPayload();\n // const userid = payload['sub'];\n // If request specified a G Suite domain:\n //const domain = payload['hd'];\n return {\n nombre: payload.name,\n email:payload.email,\n img: payload.picture,\n google: true \n }\n}", "static async getAccountId() {\n var sts = new AWS.STS();\n var resp = await sts.getCallerIdentity({}).promise();\n return resp.Account;\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 }", "async function doAblyTokenRequestWithAuthURL() {\n clearStatus();\n writeStatus(\"Requesting TokenDetails object from auth server\");\n\n ably = new Ably.Realtime({ authUrl: \"/tokenrequest\" });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n}", "newAuthorisedCapability (holder, id, type, location, sphere, validFrom, validTo) {\n const subject = {\n id: 'did:caelum:' + this.did + '#issued-' + (id || 0),\n capability: {\n type: type || 'member',\n sphere: (['over18', 'oidc'].includes(type) ? 'personal' : 'professional')\n }\n }\n if (location) subject.capability.location = location\n const credential = {\n '@context': [\n 'https://www.w3.org/2018/credentials/v1',\n 'https://caelumapp.com/context/v1'\n ],\n id: 'did:caelum:' + this.did + '#issued',\n type: ['VerifiableCredential', 'AuthorisedCapability'],\n issuer: 'did:caelum:' + this.did,\n holder: holder,\n issuanceDate: new Date().toISOString(),\n credentialSubject: subject\n }\n return credential\n }", "async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secret);\n if (secretObj.token) {\n this.oauthToken = secretObj;\n } else {\n this.serviceAccountKey = secretObj;\n }\n this.logger.info(`Get secret from SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n return;\n }\n this.logger.warn(`Cannot find SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n }\n // To be compatible with previous solution.\n const oauthTokenFile = this.getContentFromEnvVar(DEFAULT_ENV_OAUTH);\n if (oauthTokenFile) {\n this.oauthToken = JSON.parse(oauthTokenFile);\n }\n const serviceAccountKeyFile =\n this.getContentFromEnvVar(DEFAULT_ENV_KEYFILE);\n if (serviceAccountKeyFile) {\n this.serviceAccountKey = JSON.parse(serviceAccountKeyFile);\n }\n }", "function attachToken(request) {\r\n var token = getToken();\r\n if (token) {\r\n request.headers = request.headers || {};\r\n request.headers['x-access-token'] = token;\r\n }\r\n return request;\r\n }", "function getRequestToken(){\n console.log('Fetching request token from Twitter..');\n client.fetchRequestToken( 'oob', function( token, data, status ){\n if( ! token ){\n console.error('Twitter failure: status '+status+', failed to fetch request token');\n process.exit( EXIT_AUTHFAIL );\n }\n client.setAuth( consumerKey, consumerSec, token.key, token.secret );\n prompt('Enter verifier from '+token.getAuthorizationUrl(), getAccessToken );\n } );\n }", "getCurrentWebIdentity(webUrl, formDigestValue) {\n const requestOptions = {\n url: `${webUrl}/_vti_bin/client.svc/ProcessQuery`,\n headers: {\n 'X-RequestDigest': formDigestValue\n },\n body: `<Request AddExpandoFieldTypeSuffix=\"true\" SchemaVersion=\"15.0.0.0\" LibraryVersion=\"16.0.0.0\" ApplicationName=\"${config_1.default.applicationName}\" xmlns=\"http://schemas.microsoft.com/sharepoint/clientquery/2009\"><Actions><Query Id=\"1\" ObjectPathId=\"5\"><Query SelectAllProperties=\"false\"><Properties><Property Name=\"ServerRelativeUrl\" ScalarProperty=\"true\" /></Properties></Query></Query></Actions><ObjectPaths><Property Id=\"5\" ParentId=\"3\" Name=\"Web\" /><StaticProperty Id=\"3\" TypeId=\"{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}\" Name=\"Current\" /></ObjectPaths></Request>`\n };\n return new Promise((resolve, reject) => {\n request_1.default.post(requestOptions).then((res) => {\n const json = JSON.parse(res);\n const contents = json.find(x => { return x.ErrorInfo; });\n if (contents && contents.ErrorInfo) {\n return reject(contents.ErrorInfo.ErrorMessage || 'ClientSvc unknown error');\n }\n const identityObject = json.find(x => { return x._ObjectIdentity_; });\n if (identityObject) {\n return resolve({\n objectIdentity: identityObject._ObjectIdentity_,\n serverRelativeUrl: identityObject.ServerRelativeUrl\n });\n }\n reject('Cannot proceed. _ObjectIdentity_ not found'); // this is not supposed to happen\n }, (err) => { reject(err); });\n });\n }", "getV3TemplatesLicensesName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesLicensesName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function checkCompIdentity(cwc, identityKey, from) {\n Assert.equal(\n cwc.window.document.getElementById(\"msgIdentity\").value,\n from,\n \"msgIdentity value should be as expected.\"\n );\n Assert.equal(\n cwc.window.getCurrentIdentityKey(),\n identityKey,\n \"The From identity should be correctly selected.\"\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hideMask_YearMonthDate() ================ Remove the Mask 'YYYY/MM' from a Date field Parameters Return value
function hideMask_YearMonthDate(oElement) { var lstrValue = oElement.value; re = new RegExp("/","g"); oElement.value = lstrValue.replace(re,""); oElement.select(); }
[ "function putMask_YearMonthDate(oElement)\n{\n var lstrValue = oElement.value;\n if(lstrValue == \"\" || !isInteger(lstrValue))\n return;\n\n re = new RegExp(\"/\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n if (lstrValue.length == 6) {\n partOne = lstrValue.substring(0,4);\n partTwo = lstrValue.substring(4);\n oElement.value = partOne + \"/\" +partTwo;\n }\n}", "function hideMask_Date(oElement)\n{\n var lstrValue = oElement.value;\n\n re = new RegExp(\"/\",\"g\");\n oElement.value = lstrValue.replace(re,\"\");\n oElement.select();\n}", "function hideMask_DateTime(oElement)\n {\n var lstrValue = oElement.value;\n\n re = new RegExp(\"/\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n\n re = new RegExp(\":\",\"g\");\n oElement.value = lstrValue.replace(re,\"\");\n oElement.select();\n }", "function putMask_Date(oElement)\n{\n var lstrValue = oElement.value;\n if(lstrValue == \"\" || !isValidDate(lstrValue))\n return;\n\n re = new RegExp(\"/\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n\n lstrValue = lstrValue.toUpperCase();\n if (lstrValue.length == 8) {\n partOne = lstrValue.substring(0,2);\n partTwo = lstrValue.substring(2,4);\n partThree = lstrValue.substring(4);\n oElement.value = partOne + \"/\" +partTwo + \"/\" +partThree;\n }\n}", "function hideMask_PartNumber(aField)\n{\n var lobjFrcFw = handlePartFranchise( '1', aField, '' , arguments[1]);\n var lstrFrcLen ;\n if( lobjFrcFw != null ) {\n lstrFrcLen = lobjFrcFw.value.length;\n } else {\n lstrFrcLen = 0\n }\n lstrValue = aField.value.substring(lstrFrcLen);\n re = new RegExp(\"-\",\"g\");\n aField.value = lstrValue.replace(re,\"\");\n aField.select();\n}", "function CP_clearDisabledDates() {\r\n this.disabledDatesExpression = \"\";\r\n this.yearmax = \"\";\r\n this.yearmin = \"\";\r\n this.yearSelectStart = \"\";\r\n this.yearSelectStartOffset = CP_YearOfset();\r\n}", "function hideMask_Number(aField)\n{\n lstrValue = aField.value;\n re = new RegExp(\",\",\"g\");\n aField.value = lstrValue.replace(re,\"\");\n aField.select();\n}", "function fixRadMonthYearPicker() {\n fixRadMonthYearPicker_2(uiStartYearMonthID);\n fixRadMonthYearPicker_2(uiEndYearMonthID);\n}", "function formatDateddMMyyyy(d){\n return d.substr(0,2) + '/' + d.substr(2,2) + '/' + d.substr(4,4) ;\n }", "function changeImmYear()\n{\n let form = this.form;\n let censusId = form.Census.value;\n let censusYear = censusId.substring(censusId.length - 4);\n let immyear = this.value;\n if (this.value == '[')\n {\n this.value = '[Blank';\n }\n let res = immyear.match(/^[0-9]{4}$/);\n if (!res)\n { // not a 4 digit number\n res = immyear.match(/^[0-9]{2}$/);\n if (res)\n { // 2 digit number\n // expand to a 4 digit number which is a year in the\n // century up to and including the census year\n immyear = (res[0] - 0) + 1900;\n while (immyear > censusYear)\n immyear -= 100;\n this.value = immyear;\n } // 2 digit number\n } // not a 4 digit number\n\n this.checkfunc();\n}", "dateformat(date) { return \"\"; }", "function reset_date() {\n\tconsole.log('resetting or initing date format');\n\tconst RESET = '%q %d, %Y %I:%m%p';\n\tdocument.getElementById('dateFormat').value = RESET;\n\tsaveThing(LS_KEY_DATE, document.getElementById('dateFormat').value);\n\treturn RESET;\n}", "function maskPaymentInformation() {\r\n var validationType = $(this).attr(\"validation\");\r\n var value = $(this).val();\r\n if ((validationType != undefined && validationType != \"undefined\" && value != \"\" && value != undefined) && (validationType == \"SSN\" || validationType == \"credit\" || validationType == \"debit\" || validationType == \"Date\")) {\r\n var roundVal = value.trim().length;\r\n var regExp = new RegExp(\"^.{\" + roundVal + \"}\");\r\n var astrekStr = \"\";\r\n for (var int = 0; int < roundVal; int++) {\r\n astrekStr = astrekStr + \"*\";\r\n }\r\n if ($(this).attr(\"maskedValue\") == undefined) {\r\n $(this).attr({\r\n \"maskedValue\": value\r\n });\r\n\r\n } else if ($(this).attr(\"maskedValue\") != undefined) {\r\n $(this).attr(\"maskedValue\", value);\r\n }\r\n $(this).val(value.replace(regExp, astrekStr))\r\n }\r\n}", "function fillDateAccessed(){\n\tif (document.getElementById(\"month-accessed\").value == '') {\n\t\tdocument.getElementById(\"month-accessed\").value = theMonth;\n\t}\n\tif (document.getElementById(\"day-accessed\").value == '') {\n\t\tdocument.getElementById(\"day-accessed\").value = theDay;\n\t}\n\tif (document.getElementById(\"year-accessed\").value == '') {\n\t\tdocument.getElementById(\"year-accessed\").value = theYear;\n\t}\n}", "function isFourDigitYear(year) {\n\n if (year.length != 4) {\n tDoc.calControl.year.value = calDate.getFullYear();\n tDoc.calControl.year.select();\n tDoc.calControl.year.focus();\n }\n else {\n return true;\n }\n}", "function formatDateInput(date) {\n if(scope.isDate(date)) {\n var date = moment(date);\n var dateOutputFormat = scope.dateOutputFormat;\n if(date.isSame(new Date, 'year')) {\n dateOutputFormat = scope.dateOutputNoYearFormat;\n }\n return date.format(dateOutputFormat);\n }\n return \"\";\n }", "function portalGetDateTime(valMonth, valDay, valYear, valHH, valMM)\r\n{\r\n //set the value \r\n var strDate = valMonth + '/' + valDay + '/' + valYear;\r\n strDate += ' ';\r\n strDate += valHH;\r\n\r\n strDate += ':';\r\n\r\n strDate += valMM;\r\n\r\n strDate += ':';\r\n\r\n //seconds are always zero!\r\n strDate += '00';\r\n\r\n return strDate;\r\n}", "function filter_by_month() {\n //get the value of the month and year the user wants to query\n let year_month = document.getElementById('query_month').value;\n if (year_month == \"\") return;\n let list = year_month.split(\"-\");\n let search_year = list[0];\n let search_month = list[1];\n\n table = document.getElementById(\"output_table\");\n tr = table.getElementsByTagName('tr');\n\n // Loop through all table rows, and hide those that don't match the year and month query\n for (i = 0; i < tr.length; i++) {\n td = tr[i].getElementsByTagName(\"td\")[0];\n if (td) {\n column_date = td.innerHTML.split(\"-\");\n if (column_date[0]==search_year && column_date[1]==search_month) {\n tr[i].style.display = \"\";\n } else {\n tr[i].style.display = \"none\";\n }\n }\n }\n }", "function setYear() {\n\n // GET THE NEW YEAR VALUE\n var year = tDoc.calControl.year.value;\n\n // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR\n if (isFourDigitYear(year)) {\n calDate.setFullYear(year);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n else {\n // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH\n tDoc.calControl.year.focus();\n tDoc.calControl.year.select();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replenish card to it's original index
function takeCardAndReplenish(db, card) { const rank = card.rank; const cards = db.get(['game', 'cards' + rank]); let index = -1; for(let i = 0; i < cards.length; i ++) { if(cards[i].key == card.key) { index = i; break; } } if(index < 0) { return; } const nextCard = db.get(['game', 'deck' + rank, 0]); if(nextCard) { db.set(['game', 'cards' + rank, index], nextCard); db.set(['game', 'cards' + rank, index, 'status'], 'board'); } else { db.set(['game', 'cards' + rank, index], { status: 'empty' }); } db.shift(['game', 'deck' + rank]); }
[ "function addFlippedCard(card) {\n flippedCards.push(card);\n}", "add(card, index = 0){\n if(card instanceof Card){\n this._cards.splice(Math.min(index, this._cards.length -1), 0, card);\n }\n }", "function discardCard(card, index)\n { \n if(card.discard === true)\n {\n card.orginalIndex = index;\n let cards = discardedCards;\n cards.push(card);\n setDiscardedCards(cards);\n }\n\n //Returns true or false for the filter function\n return card.discard !== true;\n }", "static checkValidity(card,index) {\n if(Deck.checkValid(card.value)) {\n let randIdx = Deck.generateRandomCardIndex();\n while(randIdx === index && Deck.checkValid(deck[randIdx].value)) {\n randIdx = Deck.generateRandomCardIndex();\n }\n console.log(`values before swapping in ${index} card`);\n console.log(deck[index],deck[randIdx]);\n let temp = deck[randIdx];\n deck[randIdx] = card;\n deck[index] = temp;\n console.log(`values after swapping in ${index} card`);\n console.log(deck[index],deck[randIdx]);\n }\n }", "function discard(index)\n {\n let cards = activeCards;\n cards[index].discard = true;\n cards[index].orginalIndex = index;\n setActiveCards(cards);\n next();\n }", "function fillipingCards(newDeck) {\n if (newDeck.length === 0) {\n for (var i = frontPile.length; i > 0; i--) {\n newDeck.unshift(frontPile.shift());\n }};\n}", "flipped(cards) {\n\t\tlet flipped = [];\n\t\tfor ( let i = 0; i < 16; i++) {\n\t\t\tif (cards[i].flipped) {\n\t\t\t\tflipped.push(i);\n\t\t\t}\n }\n return flipped;\n }", "function moveToDiscard(index) {\n\tswitch(index) {\n\t\tcase 0:\n\t\t\t$(\"#card\"+index).animate({\n\t\t\t\ttop: '427px',\n\t\t\t\tleft: '203px'\n\t\t\t}, 500, function() {\n\t\t\t\t$(\"#card\"+index).rotate({duration:600,angle:0,animateTo:40});\n\t\t\t});\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\t$(\"#card\"+index).animate({\n\t\t\t\ttop: '363px',\n\t\t\t\tleft: '152px'\n\t\t\t}, 500, function() {\n\t\t\t\t$(\"#card\"+index).rotate({duration:400,angle:0,animateTo:20});\n\t\t\t}); \n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t$(\"#card\"+index).animate({\n\t\t\t\ttop: '324px',\n\t\t\t\tleft: '86px'\n\t\t\t}, 500, function() {\n\t\t\t}); \n\t\t\tbreak;\n\t\tcase 3:\n\t\t\t$(\"#card\"+index).animate({\n\t\t\t\ttop: '307px',\n\t\t\t\tleft: '9px'\n\t\t\t}, 500, function() {\n\t\t\t\t$(\"#card\"+index).rotate({duration:400,angle:0,animateTo:-20});\n\t\t\t}); \n\t\t\tbreak;\n\t\tcase 4:\n\t\t\t$(\"#card\"+index).animate({\n\t\t\t\ttop: '317px',\n\t\t\t\tleft: '-72px'\n\t\t\t}, 500, function() {\n\t\t\t\t$(\"#card\"+index).rotate({duration:600,angle:0,animateTo:-40});\n\t\t\t}); \n\t\t\tbreak;\n\t}\n}", "flipWord(word) {\n this.cards[word].isFlipped = true;\n }", "static prepCard(card) {\n card.name = card.name.split('-').join(' ');\n card.reverse = Math.random() > .8 ? true : false;\n }", "function changeHandNum(playerIndex, newNum) {\n\tlet player = playersContainer.children[playerIndex];\n\tlet numElem = player.getElementsByClassName('card-num')[0];\n\tnumElem.innerText = newNum;\n}", "incrementCard() {\n if (this.state.cardIndex + 1 >= this.state.total) return;\n this.setState((prevState) => ({ cardIndex: prevState.cardIndex + 1 }));\n }", "function resetMatchedCards() {\n matchedCards = [];\n}", "function editCard({ signal }) {\n const newCard = {\n ...objToModify,\n front: formData.front,\n back: formData.back,\n };\n updateCard(newCard, signal).then(() => updateDecks(signal));\n }", "clickCard(index) {\n\t\t let flipped = this.flipped(this.state.cards);\n if (flipped.length < 2) {\n this.channel.push(\"click\", { state: this.state, card: index })\n .receive(\"ok\", this.newView);\n }\n }", "decrementCard() {\n if (this.state.cardIndex <= 0) return this.setState({ cardIndex: null });\n this.setState((prevState) => ({ cardIndex: prevState.cardIndex - 1 }));\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 restockDeck() {\n deck = deck.concat(pile);\n pile.splice(0, pile.length);\n}", "function dealCard(target) {\n let num = random();\n let card = deck.splice(num, 1);\n target.push(card.toString());\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }