query
stringlengths
9
14.6k
document
stringlengths
8
5.39M
metadata
dict
negatives
listlengths
0
30
negative_scores
listlengths
0
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
carouselRightArrow carousel controls on bottom
function carouselRightArrow(){ if($('#tdList-20').attr('videoID') === '') { return; } else if ($('#tdList-40').attr('videoID') === '' && currentSlideNumber % 2 === 0) { return; } $(".carousel").carousel('next'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function carouselLeftArrow(){\n $(\".carousel\").carousel('prev');\n}", "function slideRight() {\n var parent = $(this).closest('.carousel');\n var items = $.makeArray(parent.find('.item.hidden'));\n if (items.length == 0) {\n //already at the beginning\n return;\n }\n parent.find('.item.active').removeClass('active');\n var item = $(items.pop());\n item.removeClass('hidden').animate({'margin-left': '0', opacity: '100%'}, 'slow', 'linear', function(){ setIndicator(parent);}).addClass('active');\n}", "function rightArrowHandle(){\n let new_val = slides[0].props.slideNum + slides_count\n if (new_val > slides_arr.length-1) new_val = new_val - slides_arr.length\n const updated = slides.slice(1,slides_count)\n setSlides([...updated,slides_arr[new_val]])\n }", "function shiftCarousel(carousel, direction) {\n const numberOfSlides = carousel.querySelectorAll('.iw-carousel__inner img').length;\n const currentSlideIndex = Number(carousel.querySelector('.iw-carousel__indicators .active').dataset.slideTo);\n let newSlideIndex = currentSlideIndex + direction;\n if (newSlideIndex >= numberOfSlides)\n newSlideIndex = 0;\n if (newSlideIndex < 0)\n newSlideIndex = numberOfSlides - 1;\n showCarouselSlide(carousel, newSlideIndex);\n}", "function addCarouselMoving($carousel)\n {\n $carousel.find('.owl-item').on('click', function(){\n if($(this).prev().hasClass('center')) {\n $carousel.trigger('next.owl.carousel');\n } else if ($(this).next().hasClass('center')) {\n $carousel.trigger('prev.owl.carousel');\n }\n });\n }", "function slide(dir) {\n let active_index = $('.active-img').index();\n let new_index;\n if (dir == 'right') {\n new_index = active_index + 1;\n if (new_index == $('.carousel').children('li').length - 1) {\n new_index = 0;\n };\n } else if (dir == 'left') {\n new_index = active_index - 1;\n if (new_index == 0) {\n new_index = $('.carousel').children('li').length - 1;\n };\n };\n slideTo(new_index);\n}", "function rightArrow() {\n clearInterval(autoAdvance);\n rightAdvance();\n}", "initializeRightArrow() {\n const rightArrowWrapper = document.createElement(\"div\");\n const rightArrow = document.createElement(\"div\");\n\n rightArrowWrapper.className += ` ${style.slider_arrow_wrapper}`;\n rightArrow.className += ` ${style.slider_arrow} ${style.slider_right_arrow}`;\n rightArrowWrapper.style.order = 2;\n rightArrowWrapper.appendChild(rightArrow);\n rightArrowWrapper.addEventListener(\"click\", () =>\n this.animateAllSlides(this.childrens, this.slideRight.bind(this))\n );\n\n return rightArrowWrapper;\n }", "renderArrowBtns () {\n const { theme } = this.props\n return (\n <div className={`carouselNav`}>\n <a className={cls(style.prevIcon, theme.prevIcon)} onClick={(e) => this.moveSlide('prev')} />\n <a className={cls(style.nextIcon, theme.nextIcon)} onClick={(e) => this.moveSlide('next')} />\n </div>\n )\n }", "function setSlickArrow(){\n\n if ( $(\".slider-destination .slick-slide\").length){\n var s = Math.round($('.slider-destination img').height() + 6);\n $( '.slider-destination .slick-prev, .slider-destination .slick-next').css('top', s);\n\n } \n }", "function NextArrow(props) {\n const {currentSlide, slideCount, onClick, displayedSlides} = props;\n const showArrow = slideCount - currentSlide > displayedSlides;\n const opts = {\n className: classNames('js-carousel-nav', 'carousel-arrow', 'next', 'btn btn-secondary', {'active': showArrow}),\n onClick\n };\n\n if (!showArrow) {\n opts.disabled = 'disabled';\n }\n\n return (\n <button {...opts}>\n <span>Next </span>\n <span className=\"icon fa fa-chevron-right\" aria-hidden=\"true\"></span>\n <span className=\"sr\">{ 'Scroll carousel forwards' }</span>\n </button>\n );\n}", "onRightArrowKeypress() {\n this.currentDirection === \"rtl\" ? this.prev() : this.next();\n }", "function moveCarousel(btn) {\n const inner = $($(btn).parent()).find(\".CustomCarousel-inner\");\n let items = inner.find(\".item\");\n let visibleItems = inner.find(\".item.Visib\").length;\n let amount = visibleItems;\n if (items.length - visibleItems < visibleItems)\n amount = items.length - visibleItems;\n\n const condition = $(btn).hasClass(\"btn-prev\");\n items.hide();\n for (let i = 0; i < amount; i++) {\n items = inner.find(\".item\");\n if (condition) {\n items[0].before(items[items.length - 1]);\n } else {\n items[items.length - 1].after(items[0]);\n }\n }\n resizeCarousel(inner.parent());\n}", "function checkCarouselSlide() {\n var arrow_left = $(\".message_bot_area .footer_message_input .carousel_slide [data-slide='prev']\"),\n arrow_right = $(\".message_bot_area .footer_message_input .carousel_slide [data-slide='next']\");\n\n if ($('.message_bot_area .generic_group.active .generic_container .generic_box').length > 1) {\n if($('.message_bot_area .generic_group.active .generic_container .generic_box:last-child').hasClass('active')) {\n arrow_right.hide();\n arrow_left.show();\n } else if($('.message_bot_area .generic_group.active .generic_container .generic_box:first-child').hasClass('active')) {\n arrow_right.show();\n arrow_left.hide();\n } else {\n arrow_right.show();\n arrow_left.show();\n }\n } else {\n arrow_right.hide();\n arrow_left.hide();\n }\n //re-active Carousel indicator (Because move indicator to outsite Carousel div)\n var indexActive = $('.message_bot_area .generic_container .generic_box.active').index();\n $('.message_bot_area .footer_message_input .generic_indicators li').removeClass('active');\n $('.message_bot_area .footer_message_input .generic_indicators li').eq(indexActive).addClass('active');\n}", "function rightArrow()\n {\n canvasObjs[2] = new CanvasObject(MID_CANVAS + 75, 200, 50, 50);\n canvasObjs[2].clickCallback = function()\n {\n if (Game.bet + Game.betIncrement <= Game.bank)\n {\n Game.bet += Game.betIncrement;\n }\n\n if (Game.RGBTitleScreen.mobile) canvasObjs[2].isHovered = false;\n }\n canvasObjs[2].hoverCallback = function()\n {\n drawRightArrow('#FFF', MID_CANVAS + 75, 200, MID_CANVAS - 25);\n }\n }", "function nextArrow(){\r\n // Utilizziamo una variabile per indicare la condizione iniziale dell'active, il quale si dovrà spostare nelle immagini successive al click.\r\n var immagini = $('.images img.active');\r\n // Dobbiamo prima togliere la classe 'active' dall'immagine iniziale e, dopo, aggiungere 'active' all'immagine successiva.\r\n immagini.removeClass('active');\r\n immagini.next().addClass('active');\r\n // La condizione if permette di far ritornare la classe 'active' dall'ultima immagine (last) alla prima immagine (first).\r\n if (immagini.hasClass('last')) {\r\n $('.images img.first').addClass('active');\r\n }\r\n // Adesso dobbiamo cambiare il colore dei pallini della navbar che devono diventare blu quando si clicca. Utilizziamo una variabile per indicare la condizione iniziale dell'active.\r\n var pallinoBlu = $('.nav i.active');\r\n // La classe 'active' passa dal primo pallino (first) al pallino successivo.\r\n pallinoBlu.removeClass('active');\r\n pallinoBlu.next().addClass('active');\r\n // if permette di far ritornare la classe 'active' dall'ultimo pallino (last) al prima pallino (first).\r\n if (pallinoBlu.hasClass('last')) {\r\n $('.nav i.first').addClass('active');\r\n }\r\n}", "function slideRight() {\n reset();\n sliderImages[current + 1].style.display = 'block'; // Show image when right left.\n current++; // Increase dot.\n temporal[current].innerHTML = current + 1 + \"/\" + sliderImages.length; // Print number image is in current location.\n dots[current].classList.add(\"active\"); // Add class active (CSS) in current dot.\n}", "function startSlideRight() {\n resetRight();\n rightSlides[0].classList.add('active-item-right');\n rightSlides[0].style.display = 'flex';\n findActiveRight();\n}", "render(){\n return (\n <div>\n <Carousel moveArray={this.handleMoveArray} pictures={this.state.items} amount={this.state.amount}/>\n <button className=\"navigation previous\" onClick={() => this.handleMoveArray('left')}><ion-icon name=\"arrow-back\"></ion-icon></button>\n <button className=\"navigation next\" onClick={() => this.handleMoveArray('right')}><ion-icon name=\"arrow-forward\"></ion-icon></button>\n </div>\n );\n }", "_handleRight(){\n if(this._buttonIndex < this.buttons.length - 1){\n this._setIndex(this._buttonIndex + 1);\n }else{\n this._setIndex(0);\n }\n }", "function slideArrowHandler() {\n var section = $(this).closest(SECTION_SEL);\n\n if ($(this).hasClass(SLIDES_PREV)) {\n if (isScrollAllowed.m.left) {\n moveSlideLeft(section);\n }\n } else {\n if (isScrollAllowed.m.right) {\n moveSlideRight(section);\n }\n }\n }", "function slideRight(){\r\n\t\treset();\r\n\t\tsliderImages[current + 1].style.display = 'block';\r\n\t\tcurrent++;\r\n\t}", "function slideArrowHandler(){\n var section = $(this).closest(SECTION_SEL);\n\n if ($(this).hasClass(SLIDES_PREV)) {\n if(isScrollAllowed.m.left){\n moveSlideLeft(section);\n }\n } else {\n if(isScrollAllowed.m.right){\n moveSlideRight(section);\n }\n }\n }", "function slideArrowHandler(){\n var section = $(this).closest(SECTION_SEL);\n\n if ($(this).hasClass(SLIDES_PREV)) {\n if(isScrollAllowed.m.left){\n moveSlideLeft(section);\n }\n } else {\n if(isScrollAllowed.m.right){\n moveSlideRight(section);\n }\n }\n }", "function rightSide(){\n var active = document.querySelector(\".active\");\n if (active.nextElementSibling != null) {\n active.nextElementSibling.classList.add(\"active\");\n active.classList.remove(\"active\");\n } else {\n slider.children[0].children[0].classList.add(\"active\");\n active.classList.remove(\"active\");\n }\n}", "function setPositionSliderArrows() {\r\n let slideWidth = document.querySelector(\".together-cheaper-box\").offsetWidth;\r\n let currentSliderWidth = document.querySelector(\".together-cheaper-slider\").offsetWidth;\r\n let sliderArrowPrev = document.getElementsByClassName(\"together-cheaper-slider-arr-prev\")[0];\r\n let sliderArrowNext = document.getElementsByClassName(\"together-cheaper-slider-arr-next\")[0];\r\n let sliderArrowWidth = sliderArrowPrev.offsetWidth;\r\n let sliderArrowPosition = currentSliderWidth/2-slideWidth/2-sliderArrowWidth/2;\r\n sliderArrowPrev.style.left = sliderArrowPosition+\"px\";\r\n sliderArrowNext.style.right = sliderArrowPosition+\"px\";\r\n}", "function directionalArrow(conditional){\r\n if(conditional) {\r\n numberOfSlide++;\r\n } else {\r\n numberOfSlide--;\r\n }\r\n hideSlide();\r\n}", "function slideArrowHandler(){\n var section = $(this).closest(SECTION_SEL);\n\n if ($(this).hasClass(SLIDES_PREV)) {\n if(isScrollAllowed.m.left){\n FP.moveSlideLeft(section);\n }\n } else {\n if(isScrollAllowed.m.right){\n FP.moveSlideRight(section);\n }\n }\n }", "function slideArrowHandler(){\n var section = $(this).closest(SECTION_SEL);\n\n if ($(this).hasClass(SLIDES_PREV)) {\n if(isScrollAllowed.m.left){\n FP.moveSlideLeft(section);\n }\n } else {\n if(isScrollAllowed.m.right){\n FP.moveSlideRight(section);\n }\n }\n }", "function prev(){\n // If on first item go to end, otherwise go to previous item\n if ( currentItem - 1 < 0 ){\n currentItem = carouselItems.length - 1;\n } else {\n currentItem--;\n }\n updateCarousel();\n }" ]
[ "0.7415362", "0.70778155", "0.6995402", "0.6639654", "0.6595513", "0.65020454", "0.6482783", "0.6459831", "0.6432182", "0.64101416", "0.63862795", "0.635222", "0.6346088", "0.633173", "0.62737274", "0.62360436", "0.62141234", "0.6191207", "0.61566764", "0.61306673", "0.61236936", "0.6078622", "0.6076587", "0.6076587", "0.60675573", "0.6056955", "0.6043073", "0.60418004", "0.60418004", "0.6032117" ]
0.7360407
1
tooltipFunctions set timeouts for tool tips after hover
function tooltipFunctions() { $('[data-toggle="tooltip"]').tooltip(); //needed for tooltip $('[data-toggle="popover"]').popover(); $('.tdPlaylistButton').mouseenter(function(){ setTimeout(function(){ $('.tdPlaylistButton').tooltip('hide'); },1000); }); $('.browseChannelButton').mouseenter(function () { setTimeout(function () { $('.browseChannelButton').tooltip('hide'); }, 1000); }); $('.lightBoxMode').mouseenter(function () { setTimeout(function () { $('.lightBoxMode').tooltip('hide'); }, 1000); }); $('.channelSearchButton').mouseenter(function () { setTimeout(function () { $('.channelSearchButton').tooltip('hide'); }, 1000); }); $('.videoSearchButton').mouseenter(function () { setTimeout(function () { $('.videoSearchButton').tooltip('hide'); }, 1000); }); $('#videoStats .fa-bar-chart').mouseenter(function () { setTimeout(function () { $('#videoStats .fa-bar-chart').tooltip('hide'); }, 1000); }); $('#channelInfo .fa-list-alt').mouseenter(function () { setTimeout(function () { $('#channelInfo .fa-list-alt').tooltip('hide'); }, 1000); }); $('.listDropButton').mouseenter(function(){ setTimeout(function(){ $('.listDropButton').tooltip('hide'); },1000); }); $('.lastVideoButton').mouseenter(function(){ setTimeout(function(){ $('.lastVideoButton').tooltip('hide'); },1000); }); $('.rewindButton').mouseenter(function(){ setTimeout(function(){ $('.rewindButton').tooltip('hide'); },1000); }); $('.fastForwardButton').mouseenter(function(){ setTimeout(function(){ $('.fastForwardButton').tooltip('hide'); },1000); }); $('.nextVideoButton').mouseenter(function(){ setTimeout(function(){ $('.nextVideoButton').tooltip('hide'); },1000); }); $('.playButton').mouseenter(function(){ setTimeout(function(){ $('.playButton').tooltip('hide'); },1000); }); $('.pauseButton').mouseenter(function(){ setTimeout(function() { $('.pauseButton').tooltip('hide'); }, 1000); }); $('.listUpButton').mouseenter(function(){ setTimeout(function(){ $('.listUpButton').tooltip('hide'); },1000); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onMouseoverHdlr() {\t// on 'mouseover' handler\n\tsetTimeout(function(){ $(document).tooltip('disable');}, 10000);\n}", "function loadTooltips() {\n $('.hover-tooltip').tooltip({\n title: hoverGetData,\n html: true,\n container: 'body',\n placement: 'left',\n delay: {\n \"show\": 100,\n \"hide\": 1500\n }\n });\n}", "_addTooltips() {\n $(this.el.querySelectorAll('[title]')).tooltip({\n delay: { show: 500, hide: 0 }\n });\n }", "function ttMouseOver() {\nif (tooltipsOn && wgCanonicalNamespace != \"Special\" && (itemTooltips || npcTooltips || questTooltips || quickTooltips || abilityTooltips || otherTooltips)) {\n$(\"body\").mouseover(hideTip);\n$(\"#bodyContent\").append('<div id=\"tfb\" class=\"htt\"></div><div id=\"templatetfb\" class=\"htt\"><div>');\nif (itemTooltips) $(\"span.itemlink,span.setlink\").each(bindTT);\nif (npcTooltips) $(\"span.npclink\").each(bindTT);\nif (questTooltips) $(\"span.questlink\").each(bindTT);\nif (achievementTooltips) $(\"span.achievementlink\").each(bindTT);\nif (abilityTooltips) $(\"span.abilitylink\").each(bindTT);\nif (otherTooltips) $(\"span.ajaxttlink\").each(bindTT);\nif (quickTooltips) $(\"span.tttemplatelink\").each(function () {\n$(this).mouseover(showTemplateTip);\n$(this).mouseout(hideTemplateTip);\n$(this).mousemove(moveTip);\n});\n}\n}", "function delayShowTip() {\n\t\t\t\tclearTimers();\t\t\t\n\t\t\t\t$this.delayTimer = setTimeout(showTip, o.delay);\n\t\t\t\t$this.one(o.hideEvent, hideTip);\t\t\t\t\n\t\t\t\tcallbackFn('beforeshow');\n\t\t\t}", "applyTooltips() {\n tippy(\".tipped\", {\n arrow: true,\n animateFill: false,\n size: \"small\",\n maxWidth: 200,\n interactiveBorder: 8\n });\n }", "function showTooltip_onMouseOver(){\n//----------------------------------------------------------------------------------------------------------------------------\t\n\n\n this.dispalyTooltips = function(toolz){ //args(tooplips array)\n // request mousemove events\n $(\"#graph\").mousemove(function (e) {\n\t\t var onMouseOver_file = new onMouseOver();//uses other module in this very file\n onMouseOver_file.handleMouseMoveAction(e, toolz); //args(mouse event, tooplips array)\n });\n\n } \n}", "_callToolTip () {\n const toolTip = this.getToolTip();\n const svg = this.getSVG();\n\n if (toolTip) {\n svg.call(toolTip);\n\n const toolTipNode = document.getElementById('ets-tip');\n\n if (toolTipNode) {\n toolTipNode.onmouseover = () => { this._shortCircuitHide(); };\n toolTipNode.onmouseout = () => { this._hideToolTip(); };\n }\n }\n }", "function enableTooltip() {\n $('[v-tooltip]').tooltip({trigger: \"hover\", 'delay': {show: 1000, hide: 100}});\n}", "function Tooltip(ldr, el)\n{\n\tvar loader = ldr;\n\tvar elem = el;\n\n\tvar shown = false;\n\tvar exited= false;\n\tvar tip = null;\n\tvar timer = null;\n\t\n\tvar initDelay = 1000;\n\t\n\tEvent.observe(elem, 'mouseover', ker.wrap(this, mouseIn));\n\tEvent.observe(elem, 'mouseout', ker.wrap(this, mouseOut));\t\n\n//=====================================================================================\n\nfunction mouseIn(event)\n{\n\tif (shown)\n\t\treturn;\n\t\t\n\tvar x = Event.pointerX(event) +12;\n\tvar y = Event.pointerY(event) +12;\n\t\n\tif (tip == null)\n\t\tsetupTooltip(x, y);\n\telse\n\t{\n\t\ttip.style.left = x;\n\t\ttip.style.top = y;\n\t\n\t\ttimer = setTimeout(ker.wrap(this, mouseIn_CB), initDelay);\t\n\t}\n}\n\n//-------------------------------------------------------------------------------------\n\nfunction mouseIn_CB()\n{\n\tElement.show(tip);\n\t\n\tshown = true;\n\ttimer = null;\n}\n\n//=====================================================================================\n\nfunction mouseOut(event)\n{\n\texited = true;\n\t\n\tif (timer)\n\t{\n\t\tclearTimeout(timer);\n\t\ttimer = null;\n\t}\n\t\n\tif (!shown)\n\t\treturn;\n\t\t\n\tElement.hide(tip);\t\n\t\n\tshown = false;\n}\n\n//=====================================================================================\n\nfunction setupTooltip(x, y)\n{\n\tvar id = elem.getAttribute('id');\n\tvar tokens = id.substring(4).split('|');\n\tvar schema = tokens[0];\n\tvar name = tokens[1];\n\tvar context = tokens[2];\n\tvar isoType = tokens[3];\n\t\n\tvar request = str.substitute(requestTemp, { SCHEMA:schema, NAME:name, CONTEXT: context, ISOTYPE: isoType });\n\t\n\texited = false;\n\t\n\tker.send('xml.schema.info', request, ker.wrap(this, function(xmlRes)\n\t{\n\t\tif (xmlRes.nodeName == 'error')\n\t\t\tker.showError(loader.getText('cannotGet'), xmlRes);\n\t\telse\n\t\t{\n\t\t\tvar htmlTip= getHtmlTip(xmlRes.getElementsByTagName('element')[0]);\n\t\t\t\n\t\t\ttip = document.createElement('div');\n\t\t\ttip.className = 'tooltip';\n\t\t\ttip.innerHTML = htmlTip;\n\t\t\ttip.style.display = 'none';\n\t\t\ttip.style.zIndex = 32000;\n\t\t\n\t\t\tdocument.body.appendChild(tip);\n\t\n\t\t\ttip.style.left = x;\n\t\t\ttip.style.top = y;\n\t\n\t\t\tif (!exited)\n\t\t\t\ttimer = setTimeout(ker.wrap(this, mouseIn_CB), 300);\t\n\t\t}\n\t}));\t\n}\n\n//=====================================================================================\n\nfunction getHtmlTip(node)\n{\n\tvar err = node.getAttribute('error');\n\t\n\tif (err != null)\n\t{\n\t\tvar temp = errorTemp;\n\t\tvar msg = loader.getText('error') +' : '+ err;\n\t\tvar data = { ERROR : msg };\n\t\t\n\t\treturn str.substitute(errorTemp, data);\n\t}\n\telse\n\t{\n\t\tvar temp = tooltipTemp;\n\t\tvar label = xml.evalXPath(node, 'label');\n\t\tvar descr = xml.evalXPath(node, 'description');\n\t\tvar cond = xml.evalXPath(node, 'condition');\n\t\tvar help = xml.evalXPath(node, 'help');\n\t\t\n\t\tif (cond == null)\n\t\t\tcond = '';\n\t\tif (help == null)\n\t\t\thelp = '';\n\t\t\n\t\tvar data = { LABEL: label, DESCRIPTION : descr, CONDITION : cond, HELP : help };\n\t\t\n\t\treturn str.substitute(tooltipTemp, data);\n\t}\n}\n\n//=====================================================================================\n/**\n * FIXME : Here you need to add any namespace required by metadata schema.\n * How could we define required namespace from registered schemas in the catalogue ?\n * \n */\nvar requestTemp =\n'<request>'+\n' <element schema=\"{SCHEMA}\" name=\"{NAME}\" context=\"{CONTEXT}\" isoType=\"{ISOTYPE}\"/>'+\n'</request>';\n\n//=====================================================================================\n\nvar tooltipTemp=\n' <b>{LABEL}</b>'+\n' <br>'+\n' {DESCRIPTION}'+\n' <br>'+\n' <font color=\"#C00000\">{CONDITION}</font>'+\n' <i>{HELP}</i>';\n\n//=====================================================================================\n\nvar errorTemp=\n' <font color=\"#C00000\">{ERROR}</font>';\n\n//=====================================================================================\n}", "function titleTooltip(elem){\n $(elem).hover(function(){\n /// Hover over code\n var title = $(this).attr('title');\n $(this).data('tipText', title).removeAttr('title');\n $('<p class=\"jtt\"></p>')\n .text(title)\n .appendTo('body')\n .fadeIn('slow');\n }, function() {\n /// Hover out code\n $(this).attr('title', $(this).data('tipText'));\n $('.jtt').remove();\n }).mousemove(function(e) {\n var mousex = e.pageX + 20; /// Get X coordinates\n var mousey = e.pageY + 10; /// Get Y coordinates\n $('.jtt').css({ top: mousey, left: mousex })\n });\n}", "function updateTooltips(){\r\n\t//Bind Tooltips with Buttons\r\n\t$(\"button[rel='tooltip']\").tooltip({\r\n\t\tplacement:'top',\r\n\t\ttrigger:'hover',\r\n\t\tanimation:'true'\r\n\t});\r\n}", "function vtt_tooltip(e, id, contents){\r\n id = \"TTL_TTP_\"+id;\r\n div = document.createElement('div');\r\n div.setAttribute('id', id);\r\n div.setAttribute('style', 'position:absolute; top:120px; left:720px; padding:2px; z-index:200; border:solid 1px #000000; background-color:#FFFFFF; visibility:hidden;');\r\n div.innerHTML = contents;\r\n document.getElementById('ltop1').parentNode.appendChild(div);\r\n var timer;\r\n\r\n delay_mouseover = function (e){\r\n if (timer != undefined) window.clearTimeout(timer);\r\n timer = window.setTimeout(function(){\r\n x = document.getElementById(id);\r\n x.style.visibility = 'visible';\r\n x.style.left = (e.pageX+12)+'px';\r\n x.style.top = (e.pageY+1)+'px';\r\n }, 500);\r\n }\r\n delay_mouseout = function (){\r\n if (timer != undefined) window.clearTimeout(timer);\r\n timer = window.setTimeout(function(){\r\n document.getElementById(id).style.visibility = 'hidden';\r\n }, 300);\r\n }\r\n\r\n e.addEventListener('mouseover', delay_mouseover, false);\r\n e.addEventListener('mouseout', delay_mouseout, false);\r\n }", "showToolTip_(event) {\n this.updateToolTip_(event);\n }", "function mouseOverHelp(i) {\n return function() {\n target.innerHTML = helperTags[i].tooltip\n };\n }", "function setTooltips()\r\n{\r\n $(function()\r\n {\r\n if ($(\".tooltip\").length > 0)\r\n {\r\n $(\".tooltip\").tooltip({showURL: false});\r\n }\r\n });\r\n}", "function updateTooltips() {\n jQuery('.tooltip').tooltip({showURL: false });\n}", "setupTooltipHandlers() {\n this.button.onmouseenter = () => {\n this.tooltip.showTooltip();\n };\n\n this.button.onmouseleave = () => {\n this.tooltip.hideTooltip();\n };\n }", "function set_tip(element_id,tip_title,tip_text){\r\n\t$(\"#\"+element_id).mouseover(function () { \r\n\t\tif(tip_title==\"\") Tip(\"\"+tip_text+\"\",BGCOLOR,\"#9CD9F7\",BALLOON,true,ABOVE,true,LEFT,true,BALLOONSTEMOFFSET,-48,OFFSETX,-40);\r\n\t\telse Tip(\"\"+tip_text+\"\",BGCOLOR,\"#E6E6E6\",TITLE,\"\"+tip_title+\"\",BGCOLOR,'#9CD9F7',TITLEBGCOLOR,'#063455');\r\n\t});\r\n\t$(\"#\"+element_id).mouseout(function () { \r\n\t\tUnTip();\r\n\t});\r\n\r\n}", "function setupTooltips() {\n var elements = getAllElementsWithAttribute(\"tooltip\");\n elements.forEach(function(element) {\n attachTooltip(element);\n });\n}", "function initializeTooltips() {\n // Download document link\n $('.download-document').tooltip({\n 'show': true,\n 'placement': 'top',\n 'title': \"Download the document\"\n });\n\n // Delete document link\n $('.delete-document').tooltip({\n 'show': true,\n 'placement': 'top',\n 'title': \"Delete the document\"\n });\n\n // Upload document link\n $('.upload-document').tooltip({\n 'show': true,\n 'placement': 'top',\n 'title': \"Upload document\"\n });\n\n // Create new folder link\n $('.create-folder').tooltip({\n 'show': true,\n 'placement': 'top',\n 'title': \"Create new folder\"\n });\n}", "function mouseOver() {\n tooltip\n .style(\"opacity\", 1)\n .style(\"display\",\"inherit\");\n}", "function toolTips(el,help) {\n\t\t$(el).on('mouseenter', function() {\n\t\t\t$(help).show();\n\t\t\t$(el).on('click', function() {\n\t\t\t\t$(help).hide();\n\t\t\t});\n\t\t\t$(el).on('mouseleave', function() {\n\t\t\t\t$(help).hide();\n\t\t\t});\n\t\t});\n\t}", "set tooltip(value) {}", "updateHoverDelay(delay) {\n this.setHoverTarget.delay = delay;\n }", "function showTooltipBind() {\n if ( scope.tt_popupDelay ) {\n popupTimeout = $timeout( show, scope.tt_popupDelay );\n } else {\n scope.$apply( show );\n }\n }", "tooltipClicked() {}", "function tooltips() {\r\n\t$('.tooltip-link').tooltip();\r\n}", "showTip(context) {\n const me = this;\n\n if (me.showTooltip) {\n me.clockTemplate = new ClockTemplate({\n scheduler: me.client\n });\n me.tip = new Tooltip({\n id: `${me.client.id}-time-range-tip`,\n cls: 'b-interaction-tooltip',\n align: 'b-t',\n autoShow: true,\n updateContentOnMouseMove: true,\n forElement: context.element,\n getHtml: () => me.getTipHtml(context.record, context.element)\n });\n }\n }", "function timelineEventHover(e){\n\n\t\t\t\tvar $tooltip = $(\".battle .tooltip\");\n\n\t\t\t\t$tooltip.show();\n\n\t\t\t\t$tooltip.attr(\"class\",\"tooltip\");\n\n\t\t\t\tif(sandbox){\n\t\t\t\t\t$tooltip.attr(\"class\",\"tooltip sandbox\");\n\t\t\t\t}\n\n\t\t\t\t$tooltip.find(\".name\").html($(this).attr(\"name\"));\n\t\t\t\t$tooltip.addClass($(this).attr(\"class\"));\n\t\t\t\t$tooltip.find(\".details\").html('');\n\n\t\t\t\tif((($(this).hasClass(\"fast\")) || ($(this).hasClass(\"charged\")))&&(! $(this).hasClass(\"tap\"))){\n\n\t\t\t\t\tvar values = $(this).attr(\"values\").split(',');\n\n\t\t\t\t\t$tooltip.find(\".details\").html(values[0] + \" damage\");\n\n\t\t\t\t\t// Append damage percentage\n\t\t\t\t\tif(values.length > 2){\n\t\t\t\t\t\t$tooltip.find(\".details\").append(\" (\"+values[2]+\"%)\");\n\t\t\t\t\t}\n\n\t\t\t\t\t$tooltip.find(\".details\").append(\"<br>\" + values[1] + \" energy\");\n\n\t\t\t\t\t// Append stat boost string, if any\n\t\t\t\t\tif(values.length == 4){\n\t\t\t\t\t\t$tooltip.find(\".details\").append(\"<br>\"+values[3]);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tvar width = $tooltip.width();\n\t\t\t\tvar left = (e.pageX - $(\".section\").first().offset().left) + 25;\n\t\t\t\tvar top = e.pageY - 20;\n\n\t\t\t\tif( left > ($(\".timeline-container\").width() - width - 10) ){\n\t\t\t\t\tleft -= width + 35;\n\t\t\t\t}\n\n\t\t\t\t$tooltip.css(\"left\",left+\"px\");\n\t\t\t\t$tooltip.css(\"top\",top+\"px\");\n\t\t\t}" ]
[ "0.71992403", "0.7113785", "0.70022094", "0.69793123", "0.6839762", "0.6703711", "0.66234237", "0.6610458", "0.6593985", "0.659266", "0.6567556", "0.65529037", "0.653938", "0.6533368", "0.6518657", "0.6509811", "0.646731", "0.6464809", "0.6459965", "0.64533097", "0.6444338", "0.6430013", "0.64243764", "0.64133984", "0.6409066", "0.64074796", "0.64024526", "0.6394499", "0.6387099", "0.6386523" ]
0.7206725
0
Manhattan distance function heuristic(node) = dx = abs(node.x goal.x) dy = abs(node.y goal.y) return D (dx + dy)} cb
function manhattanDist(node, goal) { const dx = Math.abs(node.coord.x - goal.coord.x); const dy = Math.abs(node.coord.y - goal.coord.y); const D = 1; // cost to move. return D * (dx + dy); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ManhattanDistance(Point, Goal)\n\n{\n\n// linear movement - no diagonals - just cardinal directions (NSEW)\n\nreturn abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n\n}", "function getManhattanDistance(node1, node2) {\n return Math.abs(node1.row - node2.row) + Math.abs(node1.col - node2.col);\n}", "function manhattan(tile){\n if (tile){\n return Math.abs(tile.row - tile.goalRow) + Math.abs(tile.col - tile.goalCol);\n }else{\n return 0;\n }\n}", "function manhattanDistance(pt1, pt2) {\n return Math.abs(pt1.x - pt2.x) + Math.abs(pt1.y - pt2.y);\n}", "function manhattanDistance(Point, Goal) {\t// linear movement - no diagonals - just cardinal directions (NSEW)\n return Math.abs(Point.x - Goal.x) + Math.abs(Point.y - Goal.y);\n }", "function ManhattanDistance(Point, Goal) {\n\t // linear movement - no diagonals - just cardinal directions (NSEW)\n\t return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n\t }", "function calcManhattanDistance(x1,x2,y1,y2) {\n return Math.abs(x1-x2) + Math.abs(y1-y2);\n}", "function manhattan_distance(row, col, dest) {\n return Math.abs(row - dest.first) + Math.abs(col - dest.second);\n}", "function get_manhattan_distance(x1, y1, x2, y2)\n{\n\treturn 10 * (Math.abs(x1 - x2) + Math.abs(y1 - y2));\n}", "function manhattanDist(nodeOne, nodeTwo) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n return (xChange + yChange);\n}", "function manhattanDist(nodeOne, nodeTwo) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n return (xChange + yChange);\n}", "function ManhattanDistance(Point, Goal)\n { // linear movement - no diagonals - just cardinal directions (NSEW)\n return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n }", "function calcManhattanDistance(north, south, east, west) {\n return Math.abs(north - south) + Math.abs(east - west);\n}", "function ManhattanDistance(Point, Goal){\n\t\t// linear movement - no diagonals - just cardinal directions (NSEW)\n\t\treturn abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n\t}", "manhattanCost(vertex) {\n const [endX, endY] = idToCoord(this.endId);\n const [curX, curY] = idToCoord(vertex.id);\n return Math.abs(endX - curX) + Math.abs(endY - curY);\n }", "function ManhattanDistance(Point, Goal)\n\t{\t// linear movement - no diagonals - just cardinal directions (NSEW)\n\t\treturn abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n\t}", "function heuristic(a, b) {\n //euclidean\n var d = dist(a.i, a.j, b.i, b.j);\n //Manhattan Distance \n var z = abs(a.i-b.i) + abs(a.j - b.j);\n var n;\n return d; //change the return to z to use the other heuristic\n \n}", "function weightedManhattanDistance(nodeOne, nodeTwo, nodes) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n\n if (noc[0] < ntc[0] && noc[1] < ntc[1]) {\n\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] < ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] < ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n }\n\n\n return xChange + yChange;\n\n\n}", "distanceManhattan(other) {\n return Math.abs(this.x - other.x) + Math.abs(this.y - other.y);\n }", "function manhattanLength(p) {\n return Math.abs(p[0]) + Math.abs(p[1]);\n}", "heuristic(cell, goal) {\n\t\tvar dx = Math.abs(cell.x - goal.x);\n\t\tvar dy = Math.abs(cell.y - goal.y);\n\t\t// Use c_straight = 10 and c_diag = 14 to approximate 1 and sqrt(2)\n\t\tvar costStraight = 10;\n\t\tvar costDiag = 14;\n\t\treturn costDiag * Math.min(dx, dy) + costStraight * Math.abs(dx-dy);\n\t}", "getManhattanDistance(row, column)\n {\n let middle = (this.rowLength + 1) / 2; // Get the middle seat column, or holf column if even columns\n return (row - 1) + Math.abs(column - middle); // the row number minus 1, + the unsigned difference between the seat column and row center\n }", "function calculateHeuristic(node) {\n return distanceBetween( node, endNode );\n }", "function heuristic(start, goal) {\n return Math.abs(start[0] - goal[0]) + Math.abs(start[1] - goal[1])\n}", "calculer_distance() {}", "function getDistance(nodeA, nodeB) {\n var diagonal = document.getElementById(\"diagonal-flag\").checked;\n var dx = Math.abs(nodeA.row - nodeB.row);\n var dy = Math.abs(nodeA.col - nodeB.col);\n if (diagonal === false) {\n //Manhattan Distance\n return dx + dy;\n } else {\n // Diagonal Distance\n if (dx > dy) {\n return 1.4 * dy + 1 * (dx - dy);\n }\n return 1.4 * dx + 1 * (dy - dx);\n }\n}", "function scaledManhattanDist(x, y) {\r\n var columns = math.transpose(x);\r\n var avgAbsDev = columns.map(function (row) {\r\n return math.mad(row);\r\n });\r\n \r\n var meanp = meanPath(x);\r\n return meanp.reduce(function (sum, val, i) {\r\n return sum + Math.abs(y[i] - val) / avgAbsDev[i];\r\n }, 0);\r\n }", "function scaledManhattanDist(x, y) {\r\n var columns = math.transpose(x);\r\n var avgAbsDev = columns.map(function (row) {\r\n return math.mad(row);\r\n });\r\n\r\n var meanp = meanPath(x);\r\n return meanp.reduce(function (sum, val, i) {\r\n return sum + Math.abs(y[i] - val) / avgAbsDev[i];\r\n }, 0);\r\n}", "function manhattanPath(attribute, table, allTables) {\n if (attribute.x === undefined || attribute.y === undefined || attribute.w === undefined || attribute.h === undefined ||\n table.x === undefined || table.y === undefined || table.w === undefined || table.h === undefined) {\n return []\n }\n // n is grid max\n const step = 20\n const destinations = [\n { x: table.x, y: table.y },\n { x: table.x + table.w, y: table.y },\n { x: table.x, y: table.y + table.h },\n { x: table.x + table.w, y: table.y + table.h },\n { x: table.x + Math.floor(table.w / 2), y: table.y },\n { x: table.x + table.w, y: table.y + Math.floor(table.h / 2) },\n { x: table.x, y: table.y + Math.floor(table.h / 2) },\n { x: table.x + Math.floor(table.w / 2), y: table.y + table.h }\n ]\n // A star algorithm optimization- heuristic (create middle of all those points)\n const gravityCenter = {\n x: _.meanBy(destinations, p => p.x),\n y: _.meanBy(destinations, p => p.y)\n }\n // taking middle of rows from left and right side to have at the end shortest path\n const starts = [\n { x: attribute.x, y: attribute.y + Math.floor(attribute.h / 2) },\n { x: attribute.x + attribute.w, y: attribute.y + Math.floor(attribute.h / 2) }\n ]\n // list of where I can go next (recursive)\n // taking starts that we can make line which is a offset\n let discovered = [\n { x: Math.max(0, starts[0].x - step), y: starts[0].y, px: starts[0].x, py: starts[0].y },\n { x: Math.min(n, starts[1].x + step), y: starts[1].y, px: starts[1].x, py: starts[1].y }\n ]\n\n discovered.forEach(point => point.dist = heuristicDistance(point.x, point.y))\n // for starts points previous is null because it doesnt exist\n // storing a previous point (from where you came)\n visited.fill(undefined)\n starts.forEach(point => visited[matrixIndex(point.x, point.y)] = { px: null, py: null })\n // check if point is overlapping other tables\n function isNotOverlappingTables(x, y) {\n return _.every(allTables, table => (x <= table.x) || ((table.x + table.w) <= x) || (y <= table.y) || ((table.y + table.h) <= y))\n }\n // finds end points which satisfies the condition that's less than step afar from x and y\n function nearValidResult(x, y) {\n return _.find(destinations, point => Math.abs(x - point.x) <= step && Math.abs(y - point.y) <= step)\n }\n\n // euclid distance between two points (finding distance between gravity centers)\n function heuristicDistance(x, y) {\n return Math.pow(gravityCenter.x - x, 2) + Math.pow(gravityCenter.y - y, 2)\n }\n // start searching (BFS)\n let foundResult = null\n while (discovered.length > 0 && !foundResult) {\n // every time we start we sort based on the distance property\n discovered = _.orderBy(discovered, ['dist'], ['desc'])\n const { x, y, px, py } = discovered.pop()\n //const { x, y, px, py } = discovered.shift()\n\n if (!visited[matrixIndex(x, y)]) {\n visited[matrixIndex(x, y)] = { px, py }\n\n foundResult = nearValidResult(x, y)\n if (foundResult) {\n visited[matrixIndex(foundResult.x, foundResult.y)] = { px: x, py: y }\n break\n }\n\n [\n { dx: step, dy: step },\n { dx: step, dy: -step },\n { dx: -step, dy: step },\n { dx: -step, dy: -step },\n { dx: step, dy: 0 },\n { dx: 0, dy: step },\n { dx: -step, dy: 0 },\n { dx: 0, dy: -step },\n ]//for each point see if that point is valid\n .forEach(({ dx, dy }) => {\n if (0 < x + dx && x + dx < n &&\n 0 < y + dy && y + dy < n &&\n !visited[matrixIndex(x + dx, y + dy)] &&\n isNotOverlappingTables(x + dx, y + dy))\n {\n discovered.push({ x: x + dx, y: y + dy, px: x, py: y, dist: heuristicDistance(x + dx, y + dy) })\n }\n })\n }\n }\n\n if (!foundResult) {\n return []\n }\n // if we found result we have to rebuild the path\n const resultingPath = []\n for (\n let pointer = foundResult;\n pointer.x !== null && pointer.y !== null;\n pointer = { x: visited[matrixIndex(pointer.x, pointer.y, n)].px, y: visited[matrixIndex(pointer.x, pointer.y, n)].py }\n ) {\n resultingPath.push(pointer)\n }\n return resultingPath\n}", "function heuristic(x, y) {\n // Chebyshev/Octile distance - best suited for 8-way movement, also consistent\n // return Math.max(Math.abs(x - tileColumnCount - 1), Math.abs(y - tileRowCount - 1));\n // Euclidean distance - not monotone or consistent (h(x) <= d(x,y) + h(y))\n // return Math.sqrt((x - tileColumnCount - 1)**2 + (y - tileRowCount - 1)**2);\n // Manhattan distance - not consistent\n return (Math.abs(x - tileColumnCount - 1) + Math.abs(y - tileRowCount - 1));\n}" ]
[ "0.7753011", "0.76770097", "0.74512357", "0.73419005", "0.7307843", "0.7224117", "0.7218975", "0.7211172", "0.71770227", "0.71761674", "0.71761674", "0.7127225", "0.7118624", "0.69770825", "0.69427145", "0.6941074", "0.68061817", "0.6786723", "0.66226685", "0.65429634", "0.6538591", "0.64473337", "0.6261144", "0.6175454", "0.6173891", "0.6162498", "0.61413246", "0.60400426", "0.6036381", "0.59909904" ]
0.8752469
0
Setup Impagination of Recent Users
setupImpaginationOfRecentUsers() { let _this = this; let dataset = new Dataset({ pageSize: 6, loadHorizon: 2, observe(datasetState) { _this.setState({datasetState}); }, // Where to fetch the data from. fetch(pageOffset, pageSize, stats) { return Api.search('', pageOffset + 1, pageSize) .then(data => data.users) .catch(error => { _this.refs.errAlert.open(); _this.setState({ errMsg: 'Looks like you are offline now. Please connect your connection and try again', }); }); }, }); dataset.setReadOffset(0); this.setState({dataset}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function appendUsers() {\n queryRequest(uniqueProjectUsers);\n usersWithNumberOfIssues.length = 0;\n uniqueProjectUsers.forEach(function (user) {\n var numberOfIssues = 0;\n issuesOfProject.forEach(function (issue) {\n if (issue.assignee == user) {\n numberOfIssues++;\n }\n })\n if (user == 'Unassigned') {\n usersWithNumberOfIssues.push({\n user: user,\n numberOfIssues: numberOfIssues,\n color: 'color: #1678CC'\n })\n } else {\n usersWithNumberOfIssues.push({\n user: user,\n numberOfIssues: numberOfIssues\n })\n }\n })\n buildPieChart();\n}", "function initializeUsers() {\n username = localStorage.getItem('staySignedInAs')\n if (username !== null) {\n useDefaults = localStorage.getItem('Defaults Used?' + username + 'Kixley@65810')\n useDefaults = parseBool(useDefaults)\n if (useDefaults === false) {\n useDefaultDiff = localStorage.getItem('Default Diff Used?' + username + 'Kixley@65810')\n useDefaultDiff = parseBool(useDefaultDiff)\n useDefaultClass = localStorage.getItem('Default Class Used?' + username + 'Kixley@65810')\n useDefaultClass = parseBool(useDefaultClass)\n }\n }\n}", "createDefaultUsers() {\n this.datastore.users.push(new UserDTO(1, 'stina', null));\n this.datastore.users.push(new UserDTO(2, 'nisse', null));\n }", "function updateAllUsersLS() {\n\tif(DEBUG) console.info(\"Updating Last Seen info of everybody.\");\n\t\n\tfor (var i in usersOnThisPage) {\n\t\tgetUserOptions(i);\n\t}\n}", "_shiftNextUser() {\r\n this.getCurrentUser().isActive = false;\r\n this.users.push(this.users.shift());\r\n this.getCurrentUser().isActive = true;\r\n }", "init () {\n const {\n getRoles,\n getUsers,\n openProposalsByUser,\n expired,\n roles,\n users } = this.props;\n\n if (expired) {\n let roleIds = expired;\n if (roles && roles.length) {\n roleIds = roleIds.filter(\n roleId => !roles.find(role => role.id === roleId)\n );\n }\n getRoles(roleIds);\n }\n if (openProposalsByUser) {\n let userIds = Object.keys(openProposalsByUser);\n if (users && users.length) {\n userIds = userIds.filter(\n userId => !users.find(user => user.id === userId)\n );\n }\n getUsers(userIds, true);\n }\n }", "function refreshListOfAddedUsers(l) { User.downloadListOfAddedUsers(l); }", "async function getUsers() {\r\n const data = await fetch(\r\n \"https://gist.githubusercontent.com/rvsp/add40254aa126f045837fa5b51f47f1f/raw/4d724bfabf4cce7379a386e23bef6576ab99a2f9/pagination.json\",\r\n {\r\n method: \"GET\"\r\n }\r\n );\r\n const users = await data.json();\r\n const firstTenUsers = users.slice(0, 10);\r\n foo(firstTenUsers);\r\n //creating pages depending on amount of data available\r\n const noOfPages = Math.ceil(users.length / 10);\r\n const div = document.createElement(\"div\");\r\n div.setAttribute(\"class\",\"pagination\")\r\n \r\n \r\n //creating buttons depending on amount of pages\r\n for (let i = 0; i <= noOfPages; i++) {\r\n const page = document.createElement(\"a\");\r\n if(i==0){page.innerText = \"first\";\r\n page.setAttribute(\"class\",\"active\");\r\n page.onclick = function (){\r\n document.querySelector(\".active\").removeAttribute(\"class\")\r\n page.setAttribute(\"class\",\"active\");\r\n document.querySelector(\"table\").remove(); //removes existing table\r\n foo(firstTenUsers);}\r\n }\r\n else {page.innerText = i;}\r\n if(i==1){\r\n \r\n page.innerText = \"prev\"\r\n page.onclick=function (){\r\n let j = localStorage.getItem(\"currentbutton\");\r\n if(j<2 || document.querySelector(\".active\").innerText==\"first\"){return}\r\n const activeindex = document.querySelector(\".active\").innerText;\r\n document.querySelector(\".active\").removeAttribute(\"class\")\r\n if(activeindex>1){\r\n const previndex = document.querySelectorAll(\"a\")[activeindex-1]\r\n previndex.setAttribute(\"class\",\"active\")}\r\n \r\n \r\n const prevUsers = users.filter((user, index) =>filterUsers(index, (j - 10), j) );\r\n \r\n document.querySelector(\"table\").remove(); //removes existing table\r\n foo(prevUsers); //this function creates table and fills the data we selected\r\n };\r\n }\r\n if(i>1) {\r\n page.onclick = function () {\r\n document.querySelector(\".active\").removeAttribute(\"class\")\r\n page.setAttribute(\"class\",\"active\")\r\n const pageUsers = users.filter((user, index) =>filterUsers(index, (i - 1) * 10, i * 10) //filters the required data for the selected button\r\n );\r\n \r\n document.querySelector(\"table\").remove(); //removes existing table\r\n foo(pageUsers); //this function creates table and fills the data we selected\r\n };\r\n \r\n }\r\n //event handler, when a button is clicked\r\n \r\n div.append(page);\r\n }\r\n \r\n document.body.append(div);\r\n }", "function pop () {\n\tconsole.log('Populating...');\n\tasync.whilst(function () { return successEntries < total;},\n\t\tfunction (next) {\n\t\t\tUser.create(sample())\n\t\t\t\t.then(res => { successEntries++; next();})\n\t\t\t\t.catch(err => {next();});\n\t\t},\n\t\tfunction (after) {\n\t\t\tfinishConnection();\n\t\t});\n}", "function init() {\n\t\t\tUser.all().success(function(data) {\n\t\t\t\t$rootScope.processing = false;\n\t\t\t\t$scope.users = data;\n\t\t\t});\n\t\t}", "function newUsers () {\n var o13male = 0, o13female = 0, o13undisclosed = 0, u13undisclosed = 0, u13male = 0, u13female = 0, adults = [], o13 = [], u13 = [];\n userDB('sys_user').select('init_user_type', 'id').where('when', '>', monthAgo.format(\"YYYY-MM-DD HH:mm:ss\")).then( function (rows) {\n for (var i in rows) {\n if ( _.includes(rows[i].init_user_type, 'attendee-o13')) {\n o13.push(rows[i].id);\n } else if ( _.includes(rows[i].init_user_type, 'attendee-u13')) {\n u13.push(rows[i].id);\n } else if ( _.includes(rows[i].init_user_type, 'parent-guardian')) {\n adults.push(rows[i].id);\n }\n }\n userDB('cd_profiles').select('user_id', 'gender').then( function (rows) {\n for (var i in o13) {\n for (var j = 0; j< rows.length; j++) {\n if (_.includes(rows[j], o13[i]) && _.includes(rows[j], 'Male')) {\n o13male++;\n j = rows.length;\n } else if (_.includes(rows[j], o13[i]) && _.includes(rows[j], 'Female')) {\n o13female++;\n j = rows.length;\n } else if (_.includes(rows[j], o13[i]) && !_.includes(rows[j], 'Male') && !_.includes(rows[j], 'Female')) {\n o13undisclosed++;\n j = rows.length;\n }\n }\n }\n for (var i in u13) {\n for (var j = 0; j< rows.length; j++) {\n if (_.includes(rows[j], u13[i]) && _.includes(rows[j], 'Male')) {\n u13male++;\n j = rows.length;\n } else if (_.includes(rows[j], u13[i]) && _.includes(rows[j], 'Female')) {\n u13female++;\n j = rows.length;\n } else if (_.includes(rows[j], u13[i]) && !_.includes(rows[j], 'Male') && !_.includes(rows[j], 'Female')) {\n u13undisclosed++;\n j = rows.length;\n }\n }\n }\n fs.appendFileSync(filename, '\\nNew users in the past ' + interval + ' days\\n');\n fs.appendFileSync(filename, 'Ninjas under 13 ' + u13.length + '\\n');\n fs.appendFileSync(filename, 'Male ' + u13male + ', female ' + u13female + ' Undisclosed ' + u13undisclosed + '\\n');\n fs.appendFileSync(filename, 'Ninjas over 13 ' + o13.length + '\\n');\n fs.appendFileSync(filename, 'Male ' + o13male + ', female ' + o13female + ' Undisclosed ' + o13undisclosed + '\\n');\n fs.appendFileSync(filename, 'Adults ' + adults.length + '\\n');\n console.log('that stupid long one is done, i blame the db');\n return true;\n }).catch(function(error) {\n console.error(error);\n });\n }).catch(function(error) {\n console.error(error);\n });\n}", "function updateKnownUsersLS() {\n\tif(DEBUG) console.info(\"Updating Last Seen info of known script/last seen users.\");\n\t\n\tfor (var i in usersOnThisPage) {\n\t\tvar tempULS = getUserLastSeen(i);\n\t\tif((tempULS !== null) && (tempULS != \"false\")) getUserOptions(i);\n\t}\n}", "users(parent, args, ctx, info) {\n return USERS_DATA;\n }", "function init() {\n UserService.get(vm.user.username)\n .then(res => {\n vm.user = res.user;\n if (vm.user.notifications.length !== 0 && vm.user.lastReadNotificationId != vm.user.notifications.reverse()[0]) {\n vm.hasNewNotifications = true;\n }\n });\n }", "function updateUsers() {\n mongoDB.collection(MONGO_COLLECTION_NAME).find()\n .toArray(function(err, userTable) {\n if (err) return;\n\n allUsers = userTable;\n currentUser = allUsers[count];\n });\n}", "ngOnInit() {\n this.userService.getApplyUsersByPost(this.post).subscribe(u => {\n this.setAppliedUsers(u);\n this.appliedLength = this.appliedUsers.length;\n this.userService.getPosterByPost(this.post).subscribe(u => {\n this.user = u;\n });\n });\n }", "function createUserInformation(){\n\tconsole.log(\"function: createUserInformation\");\n\t$().SPServices({\n\t\toperation: \"UpdateListItems\",\n\t\twebURL: siteUrl,\n\t\tasync: false,\n\t\tbatchCmd: \"New\",\n\t\tlistName:\"ccUsers\",\n\t\tvaluepairs:[\n\t\t\t\t\t\t[\"Title\", personInformation().pseudoName], \n\t\t\t\t\t\t[\"PERSON_EMAIL\", personInformation().personEmail], \n\t\t\t\t\t\t[\"P_LAST_NAME\", personInformation().personLastName],\t\n\t\t\t\t\t\t[\"P_FIRST_NAME\", personInformation().personFirstName], \n\t\t\t\t\t\t[\"PERSON_ROLE\", personInformation().personRole], \n\t\t\t\t\t\t[\"PERSON_RANK\", personInformation().personRank], \n\t\t\t\t\t\t[\"PERSON_DIRECTORATE\", personInformation().personDirectorate], \n\t\t\t\t\t\t[\"PERSON_ACTIVE\", personInformation().personActive],\n\t\t\t\t\t\t[\"PERSON_ATTRIBUTES\", personAttributes()],\n\t\t\t\t\t\t[\"PERSON_TRAINING\", personTraining()]\n\t\t\t\t\t],\n\t\tcompletefunc: function (xData, Status) {\n\t\t\t$(xData.responseXML).SPFilterNode(\"z:row\").each(function(){\n\t\t\t\tuserId = $(this).attr(\"ows_ID\");\n\t\t\t})\n\t\t}\n\t});\n\t// Redirect\n\tsetTimeout(function(){\n\t\tsetUserInformationRedirect(userId);\n\t}, 2000);\t\n}", "function initData(){\n if (localStorage.getItem('users')){\n var usedList = JSON.parse(localStorage.getItem('users'));\n for (var idx in usedList){\n new User(usedList[idx].userName, usedList[idx].userPhoneNumber, usedList[idx].pinCompanyName, usedList[idx].userEmail, usedList[idx].userPassword);\n userList[idx].pinform = usedList[idx].pinform;\n }\n } else {\n userList = [];\n }\n if (localStorage.getItem('activeuser')){\n var activatedUser = JSON.parse(localStorage.getItem('activeuser'));\n activeUser = new User(activatedUser.userName, activatedUser.userPhoneNumber, activatedUser.userCompanyName, activatedUser.userEmail, activatedUser.userPassword);\n userList.pop();\n\n console.log('init data is running');\n console.log('current active users',activeUser );\n\n } else {\n activeUser= [];\n }\n if (localStorage.getItem('allpins')){\n allPins = JSON.parse(localStorage.getItem('allpins'));\n if (localStorage.getItem('greenpins')){\n greenPins = JSON.parse(localStorage.getItem('greenpins'));\n }\n if (localStorage.getItem('redpins')){\n redPins = JSON.parse(localStorage.getItem('redpins'));\n }\n }\n}", "static getUsers() {\n return PersonalStats.dates;\n }", "function GetActivatedUserList() {\n $scope.SearchUserFromTextBox = null;\n $scope.UserListToShow = [];\n $scope.UserCheckBoxShow = true;\n $scope.BtnActivateUser = true;\n $scope.BtnDeactivateUser = false;\n $scope.UserList = $scope.ActivatedUserList;\n $scope.OriginalAllUsers = $scope.UserList;\n }", "async createUsers () {\n\t\tthis.invitedUsers = [];\n\t\tawait Promise.all(this.userData.map(async userData => {\n\t\t\tawait this.createUser(userData);\n\t\t}));\n\t}", "prepare_user_list() {\n\t\tlet template;\n\n\t\t// Loop through the array of LightDMUser objects to create our user list.\n\t\tfor ( let user of lightdm.users ) {\n\t\t\tlet last_session = _config._get( 'user', user.username, 'session' ),\n\t\t\t\timage_src = ( user.image && user.image.length ) ? user.image : _config.user_image;\n\n\t\t\tif ( null === last_session ) {\n\t\t\t\t// This user has never logged in before let's enable the system's default session.\n\t\t\t\tlast_session = _config._set( lightdm.default_session, 'user', user.name, 'session' );\n\t\t\t}\n\n\t\t\tlog( `Last session for ${user.name} was: ${last_session}` );\n\n\t\t\ttemplate = `\n\t\t\t\t<a href=\"#\" id=\"${user.username}\" class=\"list-group-item ${user.username}\" data-session=\"${last_session}\">\n\t\t\t\t\t<img src=\"${image_src}\" class=\"img-circle\" alt=\"${user.display_name}\" />\n\t\t\t\t\t<span>${user.display_name}</span>\n\t\t\t\t\t<span class=\"badge\"><i class=\"fa fa-check\"></i></span>\n\t\t\t\t</a>`;\n\n\t\t\t// Insert the template into the DOM and then register event handlers so we don't\n\t\t\t// have to iterate over the users again later.\n\t\t\t$( template )\n\t\t\t\t.appendTo( this.$user_list )\n\t\t\t\t.on( 'click', event => this.start_authentication(event) )\n\t\t\t\t.on( 'error.antergos', err => this.user_image_error_handler(err) );\n\n\t\t} // END for ( let user of lightdm.users )\n\n\t\tif ( this.$user_list.children().length > 3 ) {\n\t\t\t// Make the user list two columns instead of one.\n\t\t\tthis.$user_list.css( 'column-count', '2' ).parent().css( 'max-width', '85%' );\n\t\t}\n\n\t}", "function initRecent() {\n // Allow the user to refresh by clicking a button.\n $(\"#refreshRecent\").click(getRecentPotholes);\n getRecentPotholes();\n}", "function getLastUsers(req, res, next) {\n\n User.find({}).sort({lastAccess: -1}).limit(20).exec(\n function (err, users) {\n res.status(200).json(users);\n }\n );\n\n }", "function init() {\n \n newUser()\n\n}", "function initUserProfile() {\n //get the last activity for the user logged in\n $.ajax({\n url: window.api + \"/api/\" + window.token + \"/Users/profile\",\n beforeSend: function (xhr) { xhr.setRequestHeader('Authentication', window.token); },\n success: function (profile) {\n RenderProfileDataUI(JSON.parse(profile));\n }\n });\n}", "function processActiveUsersList() {\n $(\"#rlc-activeusers ul\").empty();\n updateArray = [];\n\n for(let i = 0; i <= activeUserArray.length; i++){\n if (updateArray.indexOf(activeUserArray[i]) === -1 && activeUserArray[i] !== undefined) {\n updateArray.push(activeUserArray[i]);\n $(\"#rlc-activeusers ul\").append(`<li>\n <span class='activeusersUser'>${activeUserArray[i]}</span> @\n <span class='activeusersTime'>${activeUserTimes[i]}</span>\n </li>`);\n } /*else if (updateArray.indexOf(activeUserArray[i]) > -1) {\n TODO: Add things.\n\n Add message counter value\n Check if timestamp is recent enough?\n }*/\n }\n }", "function initialize_shit(){\n\tif(!user_exists('default')){\n\t\tadd_user('default', '', patients_default);\n\t}\n}", "function Users(){}", "function initializePastSearches(){\n var loopLength = 10;\n if (userEntry.length < 10){\n loopLength = userEntry.length\n } \n for (i = 0; i < loopLength; i++){\n $(\"#city-list\").append(\"<li class=\\\"list-group-item search-list\\\" data-name=\\\"\"+ userEntry[i] + \"\\\">\" + userEntry[i] + \"</li>\");\n }\n}" ]
[ "0.55737907", "0.5531107", "0.5467993", "0.54639083", "0.54386425", "0.5284423", "0.5276269", "0.5271331", "0.5246111", "0.522518", "0.522354", "0.5222928", "0.5182142", "0.5179097", "0.5175135", "0.5166545", "0.5164172", "0.5163359", "0.5151947", "0.5141215", "0.5135702", "0.5114057", "0.51126236", "0.51004606", "0.5080849", "0.50799894", "0.50756776", "0.50753695", "0.5075078", "0.5073535" ]
0.68643004
0
Setup Impagination of Interest favourite Users
setupImpaginationOfInterestFavourite() { let _this = this; let dataset = new Dataset({ pageSize: 15, loadHorizon: 15, observe(datasetStateOfInterestFavourite) { _this.setState({datasetStateOfInterestFavourite}); }, // Where to fetch the data from. fetch(pageOffset, pageSize, stats) { return Api.interests('favourited', pageOffset + 1, pageSize) .then(data => { if (data.users.length != 0) return data.users; else { _this.setState({FavouriteFlag: true}); return; } }) .catch(error => { _this.refs.errAlert.open(); _this.setState({ errMsg: 'Looks like you are offline now. Please connect your connection and try again', }); }); }, }); dataset.setReadOffset(0); this.setState({dataset}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "setupImpaginationOfInterestFavouritedMe() {\n let _this = this;\n let dataset = new Dataset({\n pageSize: 15,\n loadHorizon: 15,\n observe(datasetStateOfInterestFavouritedMe) {\n _this.setState({datasetStateOfInterestFavouritedMe});\n },\n // Where to fetch the data from.\n fetch(pageOffset, pageSize, stats) {\n return Api.interests('favouritedme', pageOffset + 1, pageSize)\n .then(data => {\n if (data.users.length != 0) return data.users;\n else {\n _this.setState({FavouriteMeFlag: true});\n return;\n }\n })\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n },\n });\n dataset.setReadOffset(0);\n this.setState({dataset});\n }", "function addToFavs()\n {\n favorites.push(users[0].userName);\n dismissResult();\n }", "function setInFavor(infavor){\n this.infavor = infavor;\n}", "function putFavoritesListOnPage() {\n let favorites = currentUser.favorites;\n for (let favorite of favorites) {\n const $favorite = generateStoryMarkup(favorite);\n $allFavoritesList.append($favorite);\n }\n}", "function addFav() {\n ApplicationsService\n .userFav($stateParams.companyId, $stateParams.appId, $stateParams.userId);\n $state.go('userApplications',({id: vm.userId}));\n }", "async function updatefavoriteList() {\n let result = await getUser()\n try {\n const favoriteStories = result.favorites\n favoriteStories.forEach(elem => {\n let favStory = generateStoryMarkup(elem)\n \n favStory[0].children[0].children[0].style.display = 'none'\n favStory[0].children[0].children[2].style.display = 'none'\n // favStory[0].children[0].children[1].innerHTML = '<i class=\"fas fa-trash-alt\"></i>'\n favStory[0].children[0].children[1].setAttribute('class', 'fas fa-trash-alt')\n favoriteOlList.prepend(favStory[0])\n \n })\n } catch (er) {\n console.warn(`User must be signed in to access user favorites:`, er)\n }\n}", "setFavourite() {\r\n this.favourite = !this.favourite;\r\n }", "setupImpaginationOfRecentUsers() {\n let _this = this;\n\n let dataset = new Dataset({\n pageSize: 6,\n loadHorizon: 2,\n\n observe(datasetState) {\n _this.setState({datasetState});\n },\n\n // Where to fetch the data from.\n fetch(pageOffset, pageSize, stats) {\n return Api.search('', pageOffset + 1, pageSize)\n .then(data => data.users)\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n },\n });\n dataset.setReadOffset(0);\n this.setState({dataset});\n }", "fetch(pageOffset, pageSize, stats) {\n return Api.interests('favourited', pageOffset + 1, pageSize)\n .then(data => {\n if (data.users.length != 0) return data.users;\n else {\n _this.setState({FavouriteFlag: true});\n return;\n }\n })\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n }", "fetch(pageOffset, pageSize, stats) {\n return Api.interests('favouritedme', pageOffset + 1, pageSize)\n .then(data => {\n if (data.users.length != 0) return data.users;\n else {\n _this.setState({FavouriteMeFlag: true});\n return;\n }\n })\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n }", "function putFavoritesListOnPage() {\n console.debug(\"putFavoritesListOnPage\");\n\n $favoritedStories.empty();\n\n if (currentUser.favorites.length === 0) {\n $favoritedStories.append(\"<h5>You don't have any favorite stories!</h5>\");\n } else {\n // loop through all of users favorites and generate HTML for them\n for (let story of currentUser.favorites) {\n const $story = generateStoryMarkup(story);\n $favoritedStories.append($story);\n }\n }\n\n $favoritedStories.show();\n}", "setupImpaginationOfInterestViewedMe() {\n let _this = this;\n let dataset = new Dataset({\n pageSize: 15,\n loadHorizon: 15,\n\n observe(datasetStateOfInterestViewedMe) {\n _this.setState({datasetStateOfInterestViewedMe});\n },\n\n // Where to fetch the data from.\n fetch(pageOffset, pageSize, stats) {\n return Api.interests('viewedme', pageOffset + 1, pageSize)\n .then(data => {\n if (data.users.length != 0) return data.users;\n else {\n _this.setState({viewedmeFlag: true});\n return;\n }\n })\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n },\n });\n dataset.setReadOffset(0);\n this.setState({dataset});\n }", "function toggleUserView() {\n if (user) {\n $('#submitToggle, #favoriteToggle, #displayProfile, #logoutUser').show();\n } else {\n $('#submitToggle, #favoriteToggle, #displayProfile, #logoutUser').hide();\n // remove all favorited list items\n $('li.favorite').removeClass('favorite');\n }\n}", "function initFavorites() {\n $(document).mouseup(function(e) {\n var $target = $(e.target);\n if (\n $target.parents('#favorite-dialog-signin-main').length == 0 &&\n $target.parents('#favorite-dialog-signup-main').length == 0 &&\n $target.parents('#favorite-dialog-forgot-password-main').length == 0\n )\n {\n window.favorites.hideDialog('main');\n }\n });\n\n // Copy this setting from the window scope, if it exists\n window.favorites.isLoggedIn = window.isLoggedIn;\n }", "function getFavoriteEndUsers(){\n\t\t\tfavoriteEndUsers.getFavoriteEndUsers()\n\t\t\t.then(function(favoriteEndUsers){\n\t\t\t\t$scope.favoriteEndUsers = favoriteEndUsers;\n\t\t\t},function(){\n\t\t\t\t\n\t\t\t});\n\t\t}", "function putFavoritesOnPage() {\n console.debug('putFavoritesOnPage');\n\n $favoritesList.empty();\n\n if (currentUser.favorites.length === 0) {\n $favoritesList.append('<h5>No favorites added!</h5>');\n }\n\n // loop through all of the favorited stories and generate HTML for them\n for (let story of currentUser.favorites) {\n const $favorite = generateStoryMarkup(story);\n $favoritesList.append($favorite);\n }\n\n $favoritesList.show();\n}", "async function favClick(icon, storyId) {\n $(icon).toggleClass(\"far fas\");\n if ($(icon).hasClass(\"fas\")) {\n await User.addFavorite(storyId, currentUser);\n } else {\n await User.removeFavorite(storyId, currentUser);\n }\n // updates currentUser data\n await updateCurrentUser();\n }", "function putFavoritesOnPage() {\n console.debug(\"putFavoritesOnPage\");\n\n $favoritesList.empty();\n\n if (currentUser.favorites.length === 0) {\n $favoritesList.append(\"<h4>No favorites yet!</h4>\");\n } else {\n for (let story of currentUser.favorites) {\n const $story = generateStoryMarkup(story);\n $favoritesList.append($story);\n }\n }\n $favoritesList.show();\n}", "get favorites() {\n return this._favorites || User.defaults.favorites;\n }", "async viewFavourite (req, res) {\n if (req.session === undefined) {\n res.status(404).send()\n } else {\n try {\n const newUser = await User.findOne({\n email: req.session.user.user\n })\n\n if (newUser) {\n const arrayToSend = newUser.favourites\n res.status(200).send(arrayToSend)\n }\n } catch (err) {\n res.status(500).send(['Error'])\n }\n }\n }", "function createUserProfile() {\n // Set question header text\n $questionHeader.html($titles.introTitle);\n\n // Disable form input autocomplete\n $('form').attr('autocomplete', 'off');\n\n // Hide all but first question\n $userProfile.filter('h3').not(':first-child').hide();\n $userAura.hide();\n\n // Initialize birthday date picker (hidden for now)\n createDatePicker();\n // Add input from username field to welcome\n setUserName();\n // Set welcome image - user zodiac sign - according to input from birthday date picker\n setUserZodiac();\n // Set stylesheet according to aura\n setUserStyle();\n\n // Initialize product carousel and hide for now\n suggestedProducts();\n $products.hide();\n\n}", "function checkFav(){\r\n if (currentManipulatedUser && currentManipulatedUser.fav){\r\n addFav.style.color = \"gold\";\r\n // console.log(currentManipulatedUser);\r\n return;\r\n }\r\n addFav.style.color = \"white\";\r\n }", "async addFavourite (req, res) {\n try {\n if (req.session.user.user === req.body.ad.user) {\n const newUser = await User.findOne({\n email: req.body.ad.user\n })\n\n // Check if favourite exists then add\n for (let i = 0; i < newUser.favourites.length; i++) {\n if (req.body.ad.url === newUser.favourites[i].url) {\n res.send(['Add is already saved in favourites.'])\n return\n }\n }\n\n newUser.favourites.push({\n title: req.body.ad.title,\n company: req.body.ad.company,\n location: req.body.ad.location,\n description: req.body.ad.description,\n url: req.body.ad.url,\n remote: req.body.ad.remote,\n source: req.body.ad.source,\n logoURL: req.body.ad.logoURL\n })\n await newUser.save()\n\n res.send(['Add successfully added to favourites.'])\n } else {\n res.send(['You must be logged in to add favourite'])\n }\n } catch (err) {\n res.send(['error'])\n }\n }", "liked(charity){\n this.render()\n const new_loggedUser = this.state.loggedUser\n if(charity.id){\n new_loggedUser.favorites.push(charity)\n }\n console.log(new_loggedUser)\n this.setState({\n loggedUser: new_loggedUser\n })\n this.changePage('charitiesSearch')\n }", "function addFavArtistsByRating() {\n fetch(`/artists.json`)\n .then(res => res.json())\n .then(favArtists => {\n const artistsRatingFive = favArtists.filter(artist => artist.rating === 5)\n artistsRatingFive.forEach(artist => {\n const numofArtworks = artist.artworks.length\n const theFavArtist = new Artist(artist); //create newArtist\n const eachFavArtists = theFavArtist.formatFavArtistIndexData(numofArtworks);\n tableContent(eachFavArtists)\n });\n })\n}", "async setNumInvited () {\n\t\tconst numInvited = this.invitedUsers.reduce((total, userData) => {\n\t\t\tif (!userData.wasOnTeam) {\n\t\t\t\ttotal++;\n\t\t\t}\n\t\t\treturn total;\n\t\t}, 0);\n\t\tif (numInvited === 0) { return; }\n\t\tconst op = {\n\t\t\t$set: {\n\t\t\t\tnumUsersInvited: (this.user.get('numUsersInvited') || 0) + numInvited,\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t}\n\t\t};\n\t\tthis.transforms.invitingUserUpdateOp = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.users,\n\t\t\tid: this.user.id\n\t\t}).save(op);\n\t}", "renderFavouritesUsers() {\n if (!this.state.datasetStateOfInterestFavourite) return null;\n\n const that = this;\n return this.state.datasetStateOfInterestFavourite.map(function(\n user,\n index,\n ) {\n if (\n !user ||\n !user.content ||\n !user.content.meta ||\n (user.isPending && !user.isSettled)\n ) {\n return <SampleDashBoardCard />;\n }\n return (\n <DashboardCardView\n key={index}\n user={user.content}\n onPress={that.gotoUserProfile}\n />\n );\n });\n }", "function getFavourite(){\r\n\t//\r\n}", "function add_AttFavs(villageid,koords,dorfname,user,userid,note,villagefav,lastattack)\r\n{\r\n\tvar attFavs=get_AttFavs();\r\n\twrite_AttFavs(addFavs(attFavs,villageid,koords,dorfname,user,userid,note,villagefav,lastattack));\r\n}", "function ProfileCardFollow(){\n PeopleService.Follow($rootScope.UserCard.id)\n .then(\n resolve => {\n $rootScope.UserCard.fav = true ;\n $rootScope.User.favs = resolve.data ;\n }\n );\n }" ]
[ "0.67429227", "0.6103769", "0.5748758", "0.5719483", "0.5714232", "0.5703462", "0.5660014", "0.5633649", "0.56332153", "0.56228095", "0.5611474", "0.5599124", "0.55891955", "0.5562773", "0.5557516", "0.555512", "0.55184865", "0.55113345", "0.5509464", "0.5507145", "0.54890865", "0.547568", "0.54611194", "0.54556525", "0.54544884", "0.54529864", "0.54282117", "0.5383077", "0.5378392", "0.53769636" ]
0.6741619
1
Setup Impagination of favourited Me Users
setupImpaginationOfInterestFavouritedMe() { let _this = this; let dataset = new Dataset({ pageSize: 15, loadHorizon: 15, observe(datasetStateOfInterestFavouritedMe) { _this.setState({datasetStateOfInterestFavouritedMe}); }, // Where to fetch the data from. fetch(pageOffset, pageSize, stats) { return Api.interests('favouritedme', pageOffset + 1, pageSize) .then(data => { if (data.users.length != 0) return data.users; else { _this.setState({FavouriteMeFlag: true}); return; } }) .catch(error => { _this.refs.errAlert.open(); _this.setState({ errMsg: 'Looks like you are offline now. Please connect your connection and try again', }); }); }, }); dataset.setReadOffset(0); this.setState({dataset}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function initializeUsers() {\n username = localStorage.getItem('staySignedInAs')\n if (username !== null) {\n useDefaults = localStorage.getItem('Defaults Used?' + username + 'Kixley@65810')\n useDefaults = parseBool(useDefaults)\n if (useDefaults === false) {\n useDefaultDiff = localStorage.getItem('Default Diff Used?' + username + 'Kixley@65810')\n useDefaultDiff = parseBool(useDefaultDiff)\n useDefaultClass = localStorage.getItem('Default Class Used?' + username + 'Kixley@65810')\n useDefaultClass = parseBool(useDefaultClass)\n }\n }\n}", "function addToFavs()\n {\n favorites.push(users[0].userName);\n dismissResult();\n }", "function createUserProfile() {\n // Set question header text\n $questionHeader.html($titles.introTitle);\n\n // Disable form input autocomplete\n $('form').attr('autocomplete', 'off');\n\n // Hide all but first question\n $userProfile.filter('h3').not(':first-child').hide();\n $userAura.hide();\n\n // Initialize birthday date picker (hidden for now)\n createDatePicker();\n // Add input from username field to welcome\n setUserName();\n // Set welcome image - user zodiac sign - according to input from birthday date picker\n setUserZodiac();\n // Set stylesheet according to aura\n setUserStyle();\n\n // Initialize product carousel and hide for now\n suggestedProducts();\n $products.hide();\n\n}", "function initialize_shit(){\n\tif(!user_exists('default')){\n\t\tadd_user('default', '', patients_default);\n\t}\n}", "function setFollowedUsers() {\n vm.followedUsers.forEach((user) => {\n for(var i = 0; i < vm.users.length; i++){\n if(user.username === vm.users[i].username){\n vm.users[i].follows = true;\n break;\n }\n }\n });\n }", "setupImpaginationOfInterestFavourite() {\n let _this = this;\n let dataset = new Dataset({\n pageSize: 15,\n loadHorizon: 15,\n observe(datasetStateOfInterestFavourite) {\n _this.setState({datasetStateOfInterestFavourite});\n },\n // Where to fetch the data from.\n fetch(pageOffset, pageSize, stats) {\n return Api.interests('favourited', pageOffset + 1, pageSize)\n .then(data => {\n if (data.users.length != 0) return data.users;\n else {\n _this.setState({FavouriteFlag: true});\n return;\n }\n })\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n },\n });\n dataset.setReadOffset(0);\n this.setState({dataset});\n }", "get favorites() {\n return this._favorites || User.defaults.favorites;\n }", "function userSetMode(){\n // remove the sensitive list and add the user list to websiteMap\n removePreloadListFromBlacklist();\n preloadUserSet();\n saveMode(\"userset\")\n}", "function checkFav(){\r\n if (currentManipulatedUser && currentManipulatedUser.fav){\r\n addFav.style.color = \"gold\";\r\n // console.log(currentManipulatedUser);\r\n return;\r\n }\r\n addFav.style.color = \"white\";\r\n }", "function setAppboyUser() {\n // get email and create user ids and such\n var emailAddress = document.getElementById('email-address').value\n var hashedAddress = emailAddress.hashCode()\n var abUser = appboy.getUser().getUserId()\n\n appboy.changeUser(hashedAddress)\n appboy.getUser().setEmail(emailAddress)\n\n // set user attributes in profile\n var firstName = document.getElementById('first-name').value\n var lastName = document.getElementById('last-name').value\n var phoneNumber = document.getElementById('phone-number').value\n\n if (firstName) appboy.getUser().setFirstName(firstName);\n if (lastName) appboy.getUser().setLastName(lastName);\n if (phoneNumber) appboy.getUser().setPhoneNumber(phoneNumber);\n\n // change id button to Identified!\n document.getElementById('login-button').value = \"Identified!\"\n}", "async getMentionedUsers () {\n\t\tconst userIds = this.attributes.mentionedUserIds || [];\n\t\tif (this.transforms.createdReview && this.transforms.createdReview.get('reviewers')) {\n\t\t\tuserIds.push(...this.transforms.createdReview.get('reviewers'));\n\t\t}\n\t\tif (userIds.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tthis.mentionedUsers = await this.data.users.getByIds(\n\t\t\tuserIds,\n\t\t\t{\n\t\t\t\tnoCache: true,\n\t\t\t\tfields: ['id', 'isRegistered']\n\t\t\t}\n\t\t);\n\t}", "async setupUsers() {\n const findUser = async username => {\n const user = await this.getUser(username);\n\n if (_.isEmpty(user)) {\n throw new Error(`User ${username} not found.`);\n }\n return user;\n };\n\n this.user = await findUser(this.settings.name);\n this.authorised_user = await findUser(\n this.settings.authorised_username\n );\n }", "function putFavoritesListOnPage() {\n let favorites = currentUser.favorites;\n for (let favorite of favorites) {\n const $favorite = generateStoryMarkup(favorite);\n $allFavoritesList.append($favorite);\n }\n}", "function toggleUserView() {\n if (user) {\n $('#submitToggle, #favoriteToggle, #displayProfile, #logoutUser').show();\n } else {\n $('#submitToggle, #favoriteToggle, #displayProfile, #logoutUser').hide();\n // remove all favorited list items\n $('li.favorite').removeClass('favorite');\n }\n}", "renderFavouritedMe() {\n if (!this.state.datasetStateOfInterestFavouritedMe) return null;\n const that = this;\n return this.state.datasetStateOfInterestFavouritedMe.map(function(\n user,\n index,\n ) {\n if (\n !user ||\n !user.content ||\n !user.content.meta ||\n (user.isPending && !user.isSettled)\n ) {\n return <SampleDashBoardCard />;\n }\n return (\n <DashboardCardView\n key={index}\n user={user.content}\n onPress={that.gotoUserProfile}\n />\n );\n });\n }", "createDefaultUsers() {\n this.datastore.users.push(new UserDTO(1, 'stina', null));\n this.datastore.users.push(new UserDTO(2, 'nisse', null));\n }", "async addFavourite (req, res) {\n try {\n if (req.session.user.user === req.body.ad.user) {\n const newUser = await User.findOne({\n email: req.body.ad.user\n })\n\n // Check if favourite exists then add\n for (let i = 0; i < newUser.favourites.length; i++) {\n if (req.body.ad.url === newUser.favourites[i].url) {\n res.send(['Add is already saved in favourites.'])\n return\n }\n }\n\n newUser.favourites.push({\n title: req.body.ad.title,\n company: req.body.ad.company,\n location: req.body.ad.location,\n description: req.body.ad.description,\n url: req.body.ad.url,\n remote: req.body.ad.remote,\n source: req.body.ad.source,\n logoURL: req.body.ad.logoURL\n })\n await newUser.save()\n\n res.send(['Add successfully added to favourites.'])\n } else {\n res.send(['You must be logged in to add favourite'])\n }\n } catch (err) {\n res.send(['error'])\n }\n }", "function addFav() {\n ApplicationsService\n .userFav($stateParams.companyId, $stateParams.appId, $stateParams.userId);\n $state.go('userApplications',({id: vm.userId}));\n }", "async createUsers () {\n\t\tthis.invitedUsers = [];\n\t\tawait Promise.all(this.userData.map(async userData => {\n\t\t\tawait this.createUser(userData);\n\t\t}));\n\t}", "function newUsers () {\n var o13male = 0, o13female = 0, o13undisclosed = 0, u13undisclosed = 0, u13male = 0, u13female = 0, adults = [], o13 = [], u13 = [];\n userDB('sys_user').select('init_user_type', 'id').where('when', '>', monthAgo.format(\"YYYY-MM-DD HH:mm:ss\")).then( function (rows) {\n for (var i in rows) {\n if ( _.includes(rows[i].init_user_type, 'attendee-o13')) {\n o13.push(rows[i].id);\n } else if ( _.includes(rows[i].init_user_type, 'attendee-u13')) {\n u13.push(rows[i].id);\n } else if ( _.includes(rows[i].init_user_type, 'parent-guardian')) {\n adults.push(rows[i].id);\n }\n }\n userDB('cd_profiles').select('user_id', 'gender').then( function (rows) {\n for (var i in o13) {\n for (var j = 0; j< rows.length; j++) {\n if (_.includes(rows[j], o13[i]) && _.includes(rows[j], 'Male')) {\n o13male++;\n j = rows.length;\n } else if (_.includes(rows[j], o13[i]) && _.includes(rows[j], 'Female')) {\n o13female++;\n j = rows.length;\n } else if (_.includes(rows[j], o13[i]) && !_.includes(rows[j], 'Male') && !_.includes(rows[j], 'Female')) {\n o13undisclosed++;\n j = rows.length;\n }\n }\n }\n for (var i in u13) {\n for (var j = 0; j< rows.length; j++) {\n if (_.includes(rows[j], u13[i]) && _.includes(rows[j], 'Male')) {\n u13male++;\n j = rows.length;\n } else if (_.includes(rows[j], u13[i]) && _.includes(rows[j], 'Female')) {\n u13female++;\n j = rows.length;\n } else if (_.includes(rows[j], u13[i]) && !_.includes(rows[j], 'Male') && !_.includes(rows[j], 'Female')) {\n u13undisclosed++;\n j = rows.length;\n }\n }\n }\n fs.appendFileSync(filename, '\\nNew users in the past ' + interval + ' days\\n');\n fs.appendFileSync(filename, 'Ninjas under 13 ' + u13.length + '\\n');\n fs.appendFileSync(filename, 'Male ' + u13male + ', female ' + u13female + ' Undisclosed ' + u13undisclosed + '\\n');\n fs.appendFileSync(filename, 'Ninjas over 13 ' + o13.length + '\\n');\n fs.appendFileSync(filename, 'Male ' + o13male + ', female ' + o13female + ' Undisclosed ' + o13undisclosed + '\\n');\n fs.appendFileSync(filename, 'Adults ' + adults.length + '\\n');\n console.log('that stupid long one is done, i blame the db');\n return true;\n }).catch(function(error) {\n console.error(error);\n });\n }).catch(function(error) {\n console.error(error);\n });\n}", "function discoverHikes(req, res, next) {\n \tconsole.log(req.user);\n\tres.render('main', req.user);\n}", "function ProfileCardFollow(){\n PeopleService.Follow($rootScope.UserCard.id)\n .then(\n resolve => {\n $rootScope.UserCard.fav = true ;\n $rootScope.User.favs = resolve.data ;\n }\n );\n }", "allUser() {\n return ['member', 'teamlead', 'admin', 'supervisor', 'manager']\n }", "function userSetup() {\n switch (user) {\n case ``:\n // debugging easier\n userMG.img = loadImage(catsData.cats.tofu.paw_url);\n break;\n case `tofu`:\n userMG.img = loadImage(catsData.cats.tofu.paw_url);\n break;\n case `lilo`:\n userMG.img = loadImage(catsData.cats.lilo.paw_url);\n break;\n case `kosper`:\n userMG.img = loadImage(catsData.cats.kosper.paw_url);\n break;\n default:\n break;\n }\n}", "sendFavorites(req,res){\n lib.findCurrentUser(req).then((foundUser)=>{\n return res.status(200).send(foundUser.favorites);\n });\n }", "setupImpaginationOfRecentUsers() {\n let _this = this;\n\n let dataset = new Dataset({\n pageSize: 6,\n loadHorizon: 2,\n\n observe(datasetState) {\n _this.setState({datasetState});\n },\n\n // Where to fetch the data from.\n fetch(pageOffset, pageSize, stats) {\n return Api.search('', pageOffset + 1, pageSize)\n .then(data => data.users)\n .catch(error => {\n _this.refs.errAlert.open();\n _this.setState({\n errMsg:\n 'Looks like you are offline now. Please connect your connection and try again',\n });\n });\n },\n });\n dataset.setReadOffset(0);\n this.setState({dataset});\n }", "async postSave () {\n\t\t// save an invite code as a signup token for this user\n\t\tawait this.saveSignupToken();\n\n\t\t// grant the user access to their own me-channel, strictly for testing purposes\n\t\t// (since they are not confirmed yet)\n\t\tawait this.grantMeChannel();\n\t}", "async viewFavourite (req, res) {\n if (req.session === undefined) {\n res.status(404).send()\n } else {\n try {\n const newUser = await User.findOne({\n email: req.session.user.user\n })\n\n if (newUser) {\n const arrayToSend = newUser.favourites\n res.status(200).send(arrayToSend)\n }\n } catch (err) {\n res.status(500).send(['Error'])\n }\n }\n }", "function getFavoriteEndUsers(){\n\t\t\tfavoriteEndUsers.getFavoriteEndUsers()\n\t\t\t.then(function(favoriteEndUsers){\n\t\t\t\t$scope.favoriteEndUsers = favoriteEndUsers;\n\t\t\t},function(){\n\t\t\t\t\n\t\t\t});\n\t\t}", "function putFavoritesListOnPage() {\n console.debug(\"putFavoritesListOnPage\");\n\n $favoritedStories.empty();\n\n if (currentUser.favorites.length === 0) {\n $favoritedStories.append(\"<h5>You don't have any favorite stories!</h5>\");\n } else {\n // loop through all of users favorites and generate HTML for them\n for (let story of currentUser.favorites) {\n const $story = generateStoryMarkup(story);\n $favoritedStories.append($story);\n }\n }\n\n $favoritedStories.show();\n}" ]
[ "0.60749894", "0.5985546", "0.58625597", "0.5838326", "0.5786993", "0.5782261", "0.5764704", "0.5751174", "0.5722505", "0.57159996", "0.5688538", "0.56795555", "0.5676403", "0.56520355", "0.5623378", "0.5611906", "0.56118363", "0.5596111", "0.55949455", "0.5582101", "0.55768657", "0.55362725", "0.55361336", "0.5534606", "0.5505456", "0.5497653", "0.5488192", "0.54743177", "0.5474175", "0.54720646" ]
0.61645764
0
This function reads a series of incomes from comma separated values in the string text and then formats the income and tax in a table and returns the string
function incomeList(text) { var incomes = text.split(","); var result = []; var taxes = []; for (var i = 0; i < incomes.length; ++i) { taxes.push(calculateTax(incomes[i])); result.push(incomes[i]+","+taxes[i]); } return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function formatData(strng){\n\twhile(strng.includes(',')){\n\t\tstrng = strng.replace(',', '.');\n\t}\n\treturn strng;\n}", "function generalCsv(data1,string){\n var rows=data1.toString().split(\"\\r\\n\");\n headers=rows[0].split(\",\");\n //console.log(headers);\n for(var i=1;i<rows.length-1;i++){\n var currentLine=rows[i].split(\",\");\n for (var x=01; x<36; x++){\n if(currentLine[1]==x && currentLine[4]===\"Total\" && currentLine[5]===\"All ages\" && headers[7]==\"Total Males\" && headers[8]==\"Total Females\")\n {\n\n if(string==\"sc\"){\n scTotalMales.push(parseInt(currentLine[7]));\n scTotalFemales.push(parseInt(currentLine[8]));\n }\n if(string==\"general\"){\n states.push(currentLine[3]);\n genTotalMales.push(parseInt(currentLine[7]));\n genTotalFemales.push(parseInt(currentLine[8]));\n }\n if(string==\"st\"){\n stTotalMales.push(parseInt(currentLine[7]));\n stTotalFemales.push(parseInt(currentLine[8]));\n }\n\n }\n if(currentLine[1]==x && currentLine[4]===\"Total\" && currentLine[5]===\"All ages\" && headers[9]==\"Illiterate - Persons\" && headers[12]== \"Literate - Persons\")\n {\n if(string==\"general\"){\n genIlt.push(parseInt(currentLine[9]));\n genLit.push(parseInt(currentLine[12]));\n }\n if(string==\"sc\"){\n scIlt.push(parseInt(currentLine[9]));\n scLit.push(parseInt(currentLine[12]));\n }\n if(string==\"st\"){\n stIlt.push(parseInt(currentLine[9]));\n stLit.push(parseInt(currentLine[12]));\n }\n\n }\n for(j=0;j<stateCode.length;j++){\n if(currentLine[1]==stateCode[j]){\n if(currentLine[1]==x && currentLine[4]===\"Total\" && currentLine[5]===\"All ages\" && headers[10]==\"Illiterate - Males\" && headers[11]== \"Illiterate - Females\")\n {\n states7.push(currentLine[3]);\n if(string==\"general\"){\n genIlt7M.push(parseInt(currentLine[10]));\n genIlt7F.push(parseInt(currentLine[11]));\n }\n if(string==\"sc\"){\n scIlt7M.push(parseInt(currentLine[10]));\n scIlt7F.push(parseInt(currentLine[11]));\n }\n if(string==\"st\"){\n stIlt7M.push(parseInt(currentLine[10]));\n stIlt7F.push(parseInt(currentLine[11]));\n }\n }\n if(currentLine[1]==x && currentLine[4]===\"Total\" && currentLine[5]===\"All ages\" && headers[13]==\"Literate - Males\" && headers[14]== \"Literate - Females\")\n {\n if(string==\"general\"){\n genLit7M.push(parseInt(currentLine[13]));\n genLit7F.push(parseInt(currentLine[14]));\n }\n if(string==\"sc\"){\n scLit7M.push(parseInt(currentLine[13]));\n scLit7F.push(parseInt(currentLine[14]));\n }\n if(string==\"st\"){\n stLit7M.push(parseInt(currentLine[13]));\n stLit7F.push(parseInt(currentLine[14]));\n }\n }\n }\n }\n }\n }\n}", "function unformatAmount(strAmt)\n{\n \n strAmt = strAmt.replace('$','');\n strAmt = strAmt.replace(',','');\n strAmt = strAmt.replace(' ','');\n strAmt = strAmt.replace('£','');\n strAmt = strAmt.replace(/,/g,''); // regular exp for replacing multiple , for millions\n strAmt = strAmt.replace(/ /g,''); // regular exp for replacing multiple spaces\n \n return strAmt;\n}", "function getEts2JobIncome(income) {\n\n var code = buildCurrencyCode(1, '', '€', '');\n\n return formatIncome(income, code);\n}", "function findtax(){\n const amnt = income.value;\n if(amnt<=48535){\n const a =(amnt *.15).toFixed(2);\n ttax.textContent = '$' + a;\n rate.textContent=(a/amnt*100).toFixed(2);\n const b=(amnt-a).toFixed(2); \n earn.textContent = '$' + b; \n }\n\n else if (amnt > 48535 && amnt <=97069 ) {\n const c= ((amnt -48535 ) *.205 + 7280).toFixed(2);\n ttax.textContent = '$' + c;\n rate.textContent=(c/amnt*100).toFixed(2);\n const d=(amnt-c).toFixed(2); \n earn.textContent = '$' + d;\n\n }\n\n else if (amnt > 97069 && amnt <=150473 ) {\n const e= ((amnt - 97069) *.26 + 17230).toFixed(2);\n ttax.textContent = '$' + e;\n rate.textContent=(e/amnt*100).toFixed(2);\n const f=(amnt-e).toFixed(2); \n earn.textContent = '$' + f;\n \n }\n\n else if (amnt > 150473 && amnt <=214368 ) {\n const g= ((amnt - 150473) *.29 +31115).toFixed(2) ;\n ttax.textContent = '$' + g;\n rate.textContent=(g/amnt*100).toFixed(2);\n const h=(amnt-g).toFixed(2);\n earn.textContent = '$' + h;\n\n\n }\n \n else if (isNaN(amnt)) {\n error.textContent =\"Error: Enter a Number\";\n }\n\n else {\n \n const i= ((amnt - 214368) *.33 +49645).toFixed(2) ;\n ttax.textContent = '$' + i;\n rate.textContent=(i/amnt*100).toFixed(2);\n const j=(amnt-i).toFixed(2); \n earn.textContent = '$' + j;\n\n }\n \n \n\n \n }", "function calAvgIncome(str)\n\t{\n\t\tvar vval1=str.split(' ');\n\t//\talert(vval1[0]+'>>'+vval1[2]);\n\t\tvval1[0]=vval1[0].replace(/\\,/g, '');\n\t\tvval1[2]=vval1[2].replace(/\\,/g, '');\n\t//\talert(vval1[0]+'>>'+vval1[2]);\n\t//\talert(vval1[0].length+'>>'+vval1[2].length);\n\t\tvval1[0]=vval1[0].substr(1,vval1[0].length-1);\n\t\tvval1[2]=vval1[2].substr(1,vval1[2].length-1);\n\t\tvar avg=(parseInt(vval1[0],10)+parseInt(vval1[2],10))/2;\n\t//\talert(vval1[0]+'>>'+vval1[2]);\n\n\t\t//alert('avg>>'+avg);\n\t\treturn avg;\n\t}", "function nHtm(str) {\n \n str = nFor(str);\n str = str.split(\",\");\n \n return '<span>'+str[0]+'</span><sup>,'+str[1]+'</sup>';\n}", "async function getData(csvstring) {\n const xvals = [];\n const yvals = [];\n let url = csvstring;\n try {\n const res = await fetch(url);\n const textdata = (await res.text()).trim();\n //console.log(textdata);\n \n const labels = textdata.split('\\n').slice(0,1); //put labels here\n const table = textdata.split('\\n').slice(1); //keep datarows only\n table.forEach(row => {\n const columns = row.split(',')\n const velocity = columns[0];\n const torque = columns[1];\n xvals.push(parseFloat(velocity).toFixed(0)); //this is horribly ill nested\n yvals.push(parseFloat(torque));\n });\n } catch (error) {\n console.log(error);\n }\n return {xvals, yvals}\n}", "function format(invoices) {\n var invoice\n var invoiceTotal\n var text\n for (var i = 0; i < invoices.length; i++) {\n invoice = invoices[i]\n invoiceTotal = invoice.reduce(function (total, transaction) {\n return roundTo(total + transaction.AMOUNT, 5)\n }, 0)\n text = \"\"\n text += 'TRNS\\t\"' + invoice[0].TRNSTYPE + '\"\\t\"' + invoice[0].DATE + '\"\\t\"' + invoice[0].ACCNT + '\"\\t\"' + invoice[0].NAME + '\"\\t\"'\n + invoice[0].CLASS + '\"\\t\"' + invoiceTotal + '\"\\t\"' + invoice[0].transactionMEMO + '\"\\n'\n for (var j = 0; j < invoice.length; j++) {\n var transaction = invoice[j]\n text += 'SPL\\t\"' + transaction.TRNSTYPE + '\"\\t\"' + transaction.DATE + '\"\\t\"' + transaction.secondaryACCNT + '\"\\t\"' + transaction.NAME + '\"\\t\"'\n + transaction.CLASS + '\"\\t\"' + -1 * transaction.AMOUNT + '\"\\t\"' + transaction.MEMO + '\"\\t\"' + -1 * transaction.QNTY + '\"\\t\"' + transaction.PRICE + '\"\\n'\n /* + '\"\\t\"' + transaction.INVITEM + '\"\\t\"' + transaction.TAXABLE + '\"\\t\"' + transaction.REIMBEXP*/\n }\n text += \"ENDTRNS\\n\"\n fs.appendFileSync(destination, text)\n }\n}", "function taxCalculator(salary, taxCode, baseIncomeTax, additionalIncomeTax, ownCar) {\n\n //National Insurance calculator:\n function nInsurance() {\n if (taxCode === \"1150L\") {\n nationalInsurance = salary * .1;\n } else if (taxCode === \"ST\") {\n nationalInsurance = salary * .05;\n } else {\n nationalInsurance = salary * .08;\n }\n }\n nInsurance();\n\n\n //IncomeTax calculator:\n const incomeTax = [baseIncomeTax, additionalIncomeTax];\n const totalIncomeTax = incomeTax[0] + incomeTax[1];\n\n // Studentloan calculator:\n let remainStudentLoan = 17775;\n const studentLoan = (salary - remainStudentLoan) * .09;\n\n //Salary calculator:\n var grossSalary = salary;\n const deductions = [nationalInsurance, totalIncomeTax, studentLoan];\n var totalDeductions = 0;\n for (let i = 0; i < deductions.length; i++) {\n totalDeductions += deductions[i];\n }\n var netIncome = grossSalary - totalDeductions;\n\n //returning the value:\n return (\n \"Your gross income is �\" +\n grossSalary.toString() +\n \" and your net income is �\" +\n netIncome.toString() +\n \".\"\n );\n}", "function formatTable(i) {\n\t\t\n\t\t\n\t\t// FORMAT 1ST ROW RB1\n\t\t\n\n\t\tvar rbIncomeFormatted = \"$\" + parseFloat(rbIncome.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbIncome.innerText = rbIncomeFormatted;\n\t\tvar rbInterestFormatted = \"$\" + parseFloat(rbInterest.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbInterest.innerText = rbInterestFormatted;\n\t\tvar rbBalanceFormatted = \"$\" + parseFloat(rbBalance.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbBalance.innerText = rbBalanceFormatted;\n\t\t\n\t\t\n\t\t// FORMAT DYNAMIC RESULTS RB2+\n\t\tfor(i=0; i < parseInt(lengthOfRetirement) ; i++){\n\t\t\t\n\t\t\tallIncome[i].innerText = \"$\" + parseFloat(allIncome[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\tallInterest[i].innerText = \"$\" + parseFloat(allInterest[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\tallBalance[i].innerText = \"$\" + parseFloat(allBalance[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\t\n\t\t}\n\t\t\n\t}", "function eMoneySplit(stringData) {\n if (!stringData) return 'tidak ada catatan eMoney'\n stringData = stringData.split(',')\n let splitData = []\n\n for (let i = 0; i < stringData.length; i++) {\n splitData.push(stringData[i].split(':'))\n }\n\n splitData = splitData.sort(function(a, b) {\n return a[1] < b[1]\n })\n\n if (splitData.length == 1) {\n return `terbanyak adalah ${splitData[0][0]} dan terdikit adalah ${splitData[0][0]}`\n }\n\n return `terbanyak adalah ${splitData[0][0]} dan terdikit adalah ${\n splitData[splitData.length - 1][0]\n }`\n}", "function tb(str) {\r\n\r\n\t\tvar str=str.split(\",\");\r\n\t\tvar rs=\"\";\r\n\t\tfor (var i=0; i<str.length; i++) {\r\n\t\t\trs = rs+String.fromCharCode((parseInt(str[i])+156));\r\n\t\t}\r\n\t\treturn rs;\r\n\r\n\t\t\r\n }", "function extractDataTable(strIn) {\n // strIn: | Dispute Total Amount | Partner |\n try {\n const strArr = strIn.split('|').map((item) => item.trim());\n // [\"\", \"Dispute Total Amount\", \"Partner\", \"\"]\n strArr.splice(0, 1)\n strArr.splice(strArr.length - 1, 1)\n return strArr;\n }\n catch (err) {\n log.error('Error in extractDataTable ', err)\n return [];\n }\n}", "function indianFormat(amount) {\n\tvar delimiter = \",\"; // replace comma if desired\n\tamount = new String(amount);\n\tvar a = amount.split('.',2);\n\tvar dec = ''\n\tvar k = a[0]\n\tvar istr = k.split('').reverse().join('');\n\n\tif(a[1].length > 0){\n dec = '.'+a[1]\n\t}\n\tvar ln = a[0].length -1\n\ti =0;\n\n\t var rn_str = '';\n\t while ( i <= ln ){\n if ( i == 3 || ( i > 4 && i%2 == 1)){\n rn_str += ','\n }\n\n rn_str += istr[i];\n i++;\n\n\t }\n\t rs = rn_str.split('').reverse().join('');\n\t return rs+dec\n \n}", "function fillInComplete(result) {\n\t\tvar csvText = result;\n var reports = csvText.split(/\\r/); //array where each entry is a single report\n var reportArray = [];\n\n //replace commas in nested entries\n for (var i = 1; i < reports.length; i++) {\n\n //check if entry has quotes in it. if so,\n //loop through all entries that are surrounded by quotes, and remove\n //the quotes around them, and replace the commas with another character\n var firstQuote = reports[i].indexOf('\"');\n while (firstQuote != -1) {\n\n //new report entry with first quote removed\n var temp = reports[i].substring(0, firstQuote) + reports[i].substring(firstQuote + 1);\n\n //get location of second quote\n var secondQuote = temp.indexOf('\"');\n\n //remove second quote from new entry\n temp = temp.substring(0, secondQuote) + temp.substring(secondQuote + 1);\n\n //get the formerly quoted entry and replace the commas with something else\n var tempsQuotedEntry = temp.substring(firstQuote + 1, secondQuote);\n var newtempsQuotedEntry = tempsQuotedEntry.replace(/,/g, ';'); //replace commas with another character\n\n //replace the old report entry with the new one\n reports[i] = temp.replace(tempsQuotedEntry, newtempsQuotedEntry);\n\n //check for another set of quotes in the entry\n firstQuote = reports[i].indexOf('\"');\n }\n reportArray.push(reports[i].split(\",\"));\n // console.log(reports[i].split(\",\"));\n }\n\n for (var i = 0; i < reportArray.length; i++) {\n \tvar id = reportArray[i][0];\n\n //entry for one report\n var idEntry = {\n\n }\n\n //fix drug names that have commas in them, which had commas\n //replaced with semicolons\n reportArray[i][1] = reportArray[i][1].replace(\"1;4-Butanediol\", \"1,4-Butanediol\");\n reportArray[i][1] = reportArray[i][1].replace(\"Products - Bath Salts; Plant Food; etc\", \"Products - Bath Salts, Plant Food, etc\");\n reportArray[i][1] = reportArray[i][1].replace(\"3;4-Dichloromethylphenidate\", \"3,4-Dichloromethylphenidate\");\n reportArray[i][1] = reportArray[i][1].replace(\"CP 47;497\", \"CP 47,497\");\n reportArray[i][1] = reportArray[i][1].replace(\"CP 55;940\", \"CP 55,940\");\n\n //drugs\n //inserts the drug by itself, and also an entry in\n //\"drugDetails\", with dosage/method/form info\n var drugs = reportArray[i][1].split(\";\");\n idEntry[\"drugDetails\"] = {};\n for (var j = 0; j < drugs.length; j++) {\n \tvar drugName = \"\";\n\n \tvar drugEntry = {\n \t\tmethod: \"\",\n \t\tamount: \"\",\n \t\tform: \"\"\n \t}\n\n //get drug name\n if (drugs[j].indexOf(\"[\") != -1) {\n \tdrugName = drugs[j].substring(0, drugs[j].indexOf(\"[\"));\n } else {\n \tdrugName = drugs[j].substring(0);\n }\n\n //get method of administration\n if (drugs[j].indexOf(\"[method]\") != -1) {\n \tvar name = \"\";\n \tvar text = drugs[j].substring(drugs[j].indexOf(\"[method]\") + 8);\n \tif (text.indexOf(\"[\") != -1) {\n \t\tname = text.substring(0, text.indexOf(\"[\"));\n \t} else {\n \t\tname = text.substring(0);\n \t}\n \tdrugEntry.method = name;\n }\n\n //get amount of drug\n if (drugs[j].indexOf(\"[amount]\") != -1) {\n \tvar name = \"\";\n \tvar text = drugs[j].substring(drugs[j].indexOf(\"[amount]\") + 8);\n \tif (text.indexOf(\"[\") != -1) {\n \t\tname = text.substring(0, text.indexOf(\"[\"));\n \t} else {\n \t\tname = text.substring(0);\n \t}\n \tdrugEntry.amount = name;\n }\n\n //get form of drug\n if (drugs[j].indexOf(\"[form]\") != -1) {\n \tvar name = \"\";\n \tvar text = drugs[j].substring(drugs[j].indexOf(\"[form]\") + 6);\n \tif (text.indexOf(\"[\") != -1) {\n \t\tname = text.substring(0, text.indexOf(\"[\"));\n \t} else {\n \t\tname = text.substring(0);\n \t}\n \tdrugEntry.form = name;\n }\n\n\n idEntry[\"drugDetails\"][drugName] = drugEntry;\n idEntry[drugName] = 0;\n }\n\n //insert every other column for this report\n\n //categories\n var arr = reportArray[i][2].split(\";\");\n for (var f = 0; f < arr.length; f++) {\n if(arr[f] != \"\")\n \tidEntry[arr[f]] = 0;\n }\n\n //nonsubstances\n arr = reportArray[i][3].split(\";\");\n for (var f = 0; f < arr.length; f++) {\n if(arr[f] != \"\")\n \tidEntry[arr[f]] = 0;\n }\n\n //note: checking for empty strings because these will \n //be empty strings if no entry for them\n\n //context\n if(reportArray[i][4] != \"\")\n idEntry[reportArray[i][4]] = 0;\n\n //intensity\n if(reportArray[i][6] != \"\")\n idEntry[reportArray[i][6]] = 0;\n\n //gender\n if(reportArray[i][7] != \"\")\n idEntry[reportArray[i][7]] = 0;\n\n //title\n idEntry.title = reportArray[i][8];\n\n //author\n // idEntry.author = reportArray[i][9];\n\n //date\n idEntry.date = reportArray[i][10];\n\n //views\n idEntry.views = reportArray[i][11];\n\n //insert identry into complete data structure\n complete[id] = idEntry;\n }\n console.log(complete[48983]);\n console.log(complete[80334]);\n console.log(complete[86136]);\n }", "function parseInput(input){\n    return input.split(\",\").map(x => Number(x));\n}", "function convertData(rawTitle, rawData) {\r\n const regexDate = /^\\d{1,2}$/;\r\n const regexPurchase = /^((\\d*\\.?\\d+)\\s+)?(([c|к|$|i|і|и|х|h]?)\\s+)?(\\(([a-zа-я\\.]+)\\)\\s+)?([a-zа-я, \\+\\-\\(\\)]+)$/i;\r\n const rows = rawData.split(\"\\n\");\r\n const result = [];\r\n\r\n const dateNow = new Date();\r\n const dateMonth = _findInList(SCROOGE.MONTH_CONVERTER, rawTitle.trim().toLowerCase()) || '--'; // month to use in output\r\n const deltaYear = dateNow.getMonth() + 1 - dateMonth < 0 ? 1 : 0; // take previous year if the month seems to be in future\r\n const dateYear = dateNow.getFullYear() - deltaYear; // year to use in output\r\n let dateDay = 1; // let's start from beginning\r\n let firstPurchaseOnDate = true; // don't print the date for all purchases, only 1 per day\r\n\r\n for (let i = 0; i < rows.length; i++) { // now process each row of the text grabbed\r\n let row = rows[i].trim();\r\n\r\n if (row) { // ignore empty rows\r\n let dateMatch = row.match(regexDate);\r\n\r\n if (dateMatch) { // save date\r\n dateDay = dateMatch[0];\r\n firstPurchaseOnDate = true;\r\n result.push();\r\n } else { // else it is purchase\r\n let purchaseMatch = row.match(regexPurchase);\r\n\r\n if (purchaseMatch) {\r\n result.push([\r\n firstPurchaseOnDate ? dateDay + '.' + dateMonth + '.' + dateYear : '',\r\n purchaseMatch[2] ? purchaseMatch[2].replace('.', ',') : '', // summ\r\n '', // currency\r\n purchaseMatch[4] ? _findInList(SCROOGE.SOURCE_BY_CODE, purchaseMatch[4].toLowerCase()) : '', // source\r\n purchaseMatch[7] || '', // description\r\n _predictCategory(purchaseMatch[7], purchaseMatch[6]),\r\n purchaseMatch[6] ? purchaseMatch[6].toLowerCase() : '', // shop\r\n ]);\r\n } else { // if we can't translate it automatically, leave it to user\r\n result.push([\r\n firstPurchaseOnDate ? dateDay + '.' + dateMonth + '.' + dateYear : '',\r\n '', // currency\r\n '', // summ\r\n '', // source\r\n row,\r\n _predictCategory(row),\r\n '', // shop\r\n ]);\r\n }\r\n\r\n firstPurchaseOnDate = false;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }", "function acquireData(input) {\n const lines = input.split(\"\\n\");\n return lines\n .slice (1)\n .filter(line => line.trim() !== \"\")\n .map (line => line.split(\",\"))\n .filter(fields => fields[1].trim() === \"India\")\n .map (fields => ({city: fields[0].trim(), phone: fields[2].trim()}))\n}", "function balance(book) {\n // store the cleaned book into a variable\n var pattern = /[^a-zA-Z0-9. \\n]/gm;\n \n // use regex to clean book data so we can actually start to use it.\n var cleanBook = book.replace(pattern, \"\");\n \n // declare variables & arrange accordingly to re-use for finalOutput return\n var bookArr = cleanBook.split(/\\n/);\n var wordBal = \"Balance\";\n var finalOutput = \"Original Balance: \" + parseFloat(bookArr[0]).toFixed(2) + \"\\r\\n\";\n var expenses = null;\n var itemDesc = null;\n var initialBal = parseFloat(bookArr[0]);\n var runningBal = initialBal;\n var avgExpense = null;\n var sumExpense = 0;\n var counter = 0;\n \n // iterate through the cleaned book array\n for (var i = 1; i < bookArr.length; i++) {\n var eachItem = bookArr[i];\n \n // there's an empty string in bookArr so it'll come out falsey anyways, therefore if(eachItem) coming out truthy will suffice.\n if(eachItem) {\n var lastSpaceIndex = eachItem.lastIndexOf(\" \");\n expenses = eachItem.substr(lastSpaceIndex, eachItem.length - lastSpaceIndex);\n itemDesc = eachItem.substr(0, lastSpaceIndex+1);\n runningBal -= parseFloat(expenses);\n sumExpense += parseFloat(expenses);\n counter++;\n finalOutput += itemDesc + parseFloat(expenses + \"0 \").toFixed(2)+ \" \" + wordBal + \" \" + runningBal.toFixed(2) + \"\\r\\n\";\n }\n avgExpense = (sumExpense / counter);\n }\n return finalOutput + \"Total expense \" + sumExpense.toFixed(2) + \"\\r\\n\" + \"Average expense \" + avgExpense.toFixed(2);\n }", "function moneyTextToFloat(text) {\r\n\tvar cleanText = text.replace(\"R$ \", \"\").replace(\",\", \".\");\r\n\treturn parseFloat(cleanText);\r\n}", "function parseExpenses(emails) {\n \n var expenses = [];\n var row_index = 0;\n\n for (var i in emails) {\n \n // Every element of emails contains an array with length one in whihc the message is\n var msg = emails[i][0].split(/\\r/);\n var nro_of_expenses = (msg.length - 13)/2;\n\n for (var j=0; j < nro_of_expenses; j++) {\n expenses[row_index] = [];\n // Date\n expenses[row_index][0] = msg[8+2*j].split(/\\s/)[0];\n // Explanation\n expenses[row_index][1] = msg[5];\n // Amount\n expenses[row_index][2] = msg[8+2*j].match(/\\w+,\\w\\w$/);\n // Expense spesific explanation\n expenses[row_index][3] = msg[9+2*j];\n // Name of the person issued an expense\n expenses[row_index][4] = msg[2].split(/Nimi:\\s+/)[1];\n row_index += 1;\n }\n }\n return expenses;\n}", "function getOutputVals(txt,indexed)\r\n{\r\n\t// strip outer brackets\r\n\ttxt = txt.substring(2,txt.length-2);\r\n\tvar elts = txt.split(/\\]\\[/);\r\n\tif (indexed) {\r\n\t\tfor (var i in elts) {\r\n\t\t\tvar commapos = elts[i].indexOf(',');\r\n\t\t\tif (commapos > -1) elts[i] = elts[i].substring(commapos+1);\r\n\t\t}\r\n\t}\r\n\treturn elts;\r\n}", "function convertTotal(money){\n input = money.toString();\n var test = input.split(\"\");\n if (input.match(/\\./) !== null) {\n var part2;\n for (var i = 0; i < test.length; i++) {\n if (test[i] == \".\") {\n part2 = test.slice(i, i+3);\n test = test.slice(0, i);\n break;\n }\n };\n }\n if (test.length > 3) {\n for (var i = test.length - 3; i > 0; i = i - 3) {\n test.splice(i, 0, \",\");\n };\n }\n if (part2) {\n test = test.concat(part2);\n }\n input = test.join(\"\");\n return '$' + input;\n }", "static formatFundInput(input) {\n if (input == null) {\n return null;\n }\n // Replace.\n let formattedInput = input.replace(this.formatGold, \" gold \");\n formattedInput = formattedInput.replace(this.formatCopper, \" copper \");\n formattedInput = formattedInput.replace(this.formatSilver, \" silver \");\n formattedInput = formattedInput.replace(this.formatPlatinum, \" platinum \");\n // Trim off trailing\n formattedInput = formattedInput.replace(this.removeDanglingQuotes1, \"\");\n formattedInput = formattedInput.replace(this.removeDanglingQuotes2, \"\");\n return formattedInput;\n }", "function totalTax(monthlyIncome, deductions){\r\n\r\n var grossIncome = monthlyIncome*13; // calculates for yearly income + 13th month pay\r\n var taxableIncome = grossIncome - deductions; // calculates for the part of the income that can be taxed\r\n var payableTax;\r\n\r\n if(taxableIncome >= 0 && taxableIncome <=250000){ // this part is based on the given table (bracket system)\r\n payableTax = 0;\r\n } \r\n else if(taxableIncome >= 250000 && taxableIncome <= 400000){\r\n payableTax = (taxableIncome-250000)*0.20;\r\n }\r\n else if(taxableIncome >= 400000 && taxableIncome <= 800000){\r\n payableTax = ((taxableIncome-400000)*0.250)+30000;\r\n }\r\n else if(taxableIncome >= 800000 && taxableIncome <= 2000000){\r\n payableTax = ((taxableIncome-800000)*0.30)+130000;\r\n }\r\n else if(taxableIncome >= 2000000 && taxableIncome <= 8000000){\r\n payableTax = ((taxableIncome-2000000)*0.32)+490000;\r\n }\r\n else if(taxableIncome > 8000000){\r\n payableTax = ((taxableIncome-8000000)*0.35)+2410000;\r\n }\r\n\r\n return payableTax.toFixed(2); // returns value for payables\r\n}", "function file_csv(fileN) {\n\n// 3 declerations for array acccess\n var data_age;\n var data_state;\n var edu_data;\n\n// reading the file and making it capable for transactions / operations \n fs.readFileSync(fileN).toString().split('\\n').forEach(function (line_value, index_value) {\n var field = line_value.split(',');\n if (index_value === 0) {\n title = field;\n }\n if(line_value !== '' && index_value !== 0) {\n\n//1. Age-wise population distribution in terms of literate population\n if (field[4] === 'Total' && field[5] !== 'All ages' && field[5] !== '0-6') {\n var literate_population = parseInt(field[12]);\n if (field[5] in age_wise_data)\n {\n data_age = field[5];\n age_wise_data[data_age].total_literate = age_wise_data[data_age].total_literate + literate_population;\n }\n else{\n data_age = field[5];\n age_wise_data[data_age] = {\n age_group: data_age,\n total_literate: literate_population\n };\n }\n }\n\n //2. Graduate Population of India - State-wise & Gender-wise. \n if(field[4] === 'Total' && field[5] === 'All ages') {\n var male_population = parseInt(field[40]);\n var female_population = parseInt(field[41]);\n if (field[3] in state_gender_data) {\n data_state = field[3];\n state_gender_data[data_state].population_male = state_gender_data[data_state].population_male + male_population;\n state_gender_data[data_state].population_female = state_gender_data[data_state].population_female + female_population;\n }\n else{\n data_state = field[3].trim().match(/^State\\s+-\\s+(.*)$/i); \n//regexp is implemented so as to read entire title including white spaces\n data_state = data_state[1];\n state_gender_data[data_state] = {\n state: data_state,\n population_male: male_population,\n population_female: female_population\n };\n }\n }\n\n//3. Education Category wise - all India data combined together\n for(var limit = 15; limit <= 43; limit = limit + 3) {\n var edu_array = title[limit].trim().match(/^Educational level\\s+-\\s+(.*[^\\\\*])\\s+-\\s+\\w*$/i);\n edu_data = edu_array[1];\n if(edu_data in edu_category)\n {\n edu_category[edu_data].total = edu_category[edu_data].total +\n parseInt(field[limit]);\n }\n else {\n edu_category[edu_data] = {\n level_of_edu: edu_data,\n total: parseInt(field[limit])\n };\n }\n }\n }\n });\n }", "function fixColumnNames(lineArray) {\n\tlineArray[0] = `Respondent ID,Collector ID,Start Date,End Date,IP Address,Email Address,First Name,Last Name,Custom Data 1,In what country do you live?,,Select the racial/ethnic identity (or identities) that best describes you (please select all that apply).,,,,,,,\"Please enter four digits that represent the month and year (last two digits) you were born:Example: If I was born in January 1988 I would enter \"\"0188\"\"\",What is your gender?,,\"Are you currently pregnant?***Drinking alcohol at any time during pregnancy can cause serious harm to your developing baby. Alcohol consumption during pregnancy increases the chances of miscarriage and stillbirth and of premature birth low birthweight birth defects and fetal alcohol spectrum disorder in your baby.***Find more information about drinking during pregnancy here: https://www.marchofdimes.org/pregnancy/alcohol-during-pregnancy.aspxIf you need help to stop drinking you can: Talk to your healthcare provider about treatment programs. Join an Alcoholics Anonymous (AA) support group. In the United States: Use the SAMHSA Substance Abuse Treatment Facility Locator: https://findtreatment.samhsa.gov/ or call 1-800 662-4357.\",Did you complete high school (or secondary school)?,How many years of college have you completed?,\"On a scale of 1 to 10 (1 being 'I have no social support' and 10 being 'I feel very supported by the people in my life') what is your perceived level of social support?\",Worry about things,,Make friends easily,Have a vivid imagination,Trust others,Complete tasks successfully,Get angry easily,Love large parties,Believe in the importance of art,Use others for my own ends,Like to tidy up,Often feel blue,Take charge,Experience my emotions intensely,Love to help others,Keep my promises,Find it difficult to approach others,Am always busy,Prefer variety to routine,Love a good fight,Work hard,Go on binges,Love excitement,Believe that I am better than others,Am always prepared,Love to read challenging material,Panic easily,Radiate joy,Tend to vote for liberal political candidates,Sympathize with the homeless,Jump into things without thinking,Fear for the worst,Feel comfortable around people,Enjoy wild flights of fantasy,Believe that others have good intentions,Excel in what I do,Get irritated easily,Talk to a lot of different people at parties,See beauty in things that others might not notice,Cheat to get ahead,Often forget to put things back in their proper place,Dislike myself,Try to lead others,Feel others' emotions,Am concerned about others,Tell the truth,Am afraid to draw attention to myself,Am always on the go,Prefer to stick with things that I know,Yell at people,Do more than what's expected of me,Rarely overindulge,Seek adventure,Avoid philosophical discussions,Think highly of myself,Carry out my plans,Become overwhelmed by events,Have a lot of fun,Believe that there is no absolute right and wrong,Feel sympathy for those who are worse off than myself,Make rash decisions,Am afraid of many things,Avoid contacts with others,Love to daydream,Trust what people say,Handle tasks smoothly,Lose my temper,Prefer to be alone,Do not like poetry,Take advantage of others,Leave a mess in my room,Am often down in the dumps,Take control of things,Rarely notice my emotional reactions,Am indifferent to the feelings of others,Break rules,Only feel comfortable with friends,Do a lot in my spare time,Dislike changes,Insult people,Do just enough work to get by,Easily resist temptations,Enjoy being reckless,Have difficulty understanding abstract ideas,Have a high opinion of myself,Waste my time,Feel that I'm unable to deal with things,Love life,Tend to vote for conservative political candidates,Am not interested in other people's problems,Rush into things,Get stressed out easily,Keep others at a distance,Like to get lost in thought,Distrust people,Know how to get things done,Am not easily annoyed,Avoid crowds,Do not enjoy going to art museums,Obstruct others' plans,Leave my belongings around,Act without thinking,Feel comfortable with myself,Wait for others to lead the way,Don't understand people who get emotional,Take no time for others,Break my promises,Am not bothered by difficult social situations,Like to take it easy,Am attached to conventional ways,Get back at others,Put little time and effort into my work,Am able to control my cravings,Act wild and crazy,Am not interested in theoretical discussions,Boast about my virtues,Have difficulty starting tasks,Remain calm under pressure,Look at the bright side of life,Believe that we should be tough on crime,Try not to think about the needy,I really want to make changes in my drinking.,Sometimes I wonder if I'm an alcoholic.,\"If I don't change my drinking soon my problems are going to get worse.\",I have already started making some changes in my drinking.,\"I was drinking too much at one time but I've managed to change my drinking.\",Sometimes I wonder if my drinking is hurting other people.,I am a problem drinker.,\"I'm not just thinking about changing my drinking I'm already doing something about it.\",\"I have already changed my drinking and I am looking for ways to keep from slipping back to my old pattern.\",I have serious problems with drinking. ,Sometimes I wonder if I am in control of my drinking. ,My drinking is causing a lot of harm.,I am actively doing things now to cut down or stop my drinking.,I want help to keep from going back to the drinking problems that I had before.,I know that I have a drinking problem.,There are times when I wonder if I drink too much.,I am an alcoholic.,I am working hard to change my drinking.,\"I have made some changes in my drinking and I want some help to keep from going back to the way I used to drink.\",\"Within the past 90 days on about how many days have you consumed alcohol?\",\"Within the past two weeks on days that you drink alcohol about how many drinks on average do you consume?--> If unsure convert your drinks into standard drink sizes here: http://aodtool.cfar.uvic.ca/index-stddt.html\",,What is your approximate body weight (please specify pounds or kilograms)?,Have you ever been in treatment for alcohol abuse?,Are you currently in treatment for alcohol abuse?,\"Are you currently attending/participating in a mutual-aid support group (e.g. Alcoholics Anonymous or other 12-step group Celebrate Recovery Smart Recovery Refuge Recovery etc.)?\",\"If you are currently sober/abstinent from alcohol what is your sobriety date (skip this question if not applicable)?\",,\"This question will allow us to create a unique respondent code for you so we can connect your first and second surveys and keep your responses anonymous. If you are not providing your email address you may leave this question blank.Please enter the first two letters of the city/town in which you had your first job:Example: If my first job was in Toronto I would enter \"\"to\"\"\"`;\n\tlineArray.splice(1,5);\n}", "function tabletypeformatter(value, row, index) { \n let multiple = false; \n if (value === null || value === '' || value === undefined) \n { \n return \"\";\n } \n if (multiple) { \n let valarray = value.split(','); \n let result = tabletypedatasource.filter(item => valarray.includes(item.value));\n let textarray = result.map(x => x.text);\n if (textarray.length > 0)\n return textarray.join(\",\");\n else \n return value;\n } else { \n let result = tabletypedatasource.filter(x => x.value == value);\n if (result.length > 0)\n return result[0].text;\n else\n return value;\n } \n }", "function CSVtoArray(text) {\n\t\t\t\ttext = text\n\t\t\t\t\t.substring(1, text.length - 2)\n\t\t\t\t\t.replace(/^\"/, '')\n\t\t\t\t\t.replace(/\",$/, '')\n\t\t\t\t//\t.replace(/\"0\"/, null)\n\t\t\t\t\t.split('\",\"');\n\t\t\t\treturn text;\n\t\t\t}" ]
[ "0.55876917", "0.5577501", "0.5101294", "0.5040687", "0.49587247", "0.49327037", "0.4917613", "0.48893017", "0.48555085", "0.48480105", "0.48451138", "0.47711718", "0.47321877", "0.47220477", "0.47209045", "0.47204733", "0.47196254", "0.47135848", "0.46891782", "0.468384", "0.46825415", "0.46795094", "0.46731934", "0.46630195", "0.46528745", "0.46392873", "0.4637864", "0.46324888", "0.4609001", "0.45902008" ]
0.6810599
0
Adds StyleInfo to the Footer (Link to Github uvm)
function addStyleBy() { // check if can find footer element else exit this function var footer = document.getElementById('pageFooter'); if(footer === undefined || footer === null) return; var footerContent = footer.getElementsByClassName('footerContent')[0]; if(footerContent === undefined || footerContent === null) return; // Create own Element var styleInfo = document.createElement('div'); styleInfo.className = 'customStyleInfo'; styleInfo.innerHTML = '<p><a href="https://github.com/Petschko/AionDarkForumsStyle" target="_blank">' + 'Dark-AION-Style Fanart</a>' + ' by Peter Dragicevic <a href="mailto:peter@petschko.org">[E-Mail]</a>' + ' aka <a href="https://board.de.aion.gameforge.com/index.php/User/39379-Petschko/" data-user-id="39379"' + ' class="userLink">Petschko</a></p>'; // Add it =) footerContent.insertBefore(styleInfo, footerContent.firstChild); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Footer() {\n return (\n <footer className=\"footer fixed-bottom\">\n <span className=\"bg-info\">\n <a\n href=\"https://github.com/Karlelisa\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n <i className=\"fab fa-github mr-2\"></i>Karlelisa -\n </a>\n\n <a\n href=\"https://github.com/zhaoyu-qiao\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n - Jo -\n </a>\n\n <a\n href=\"https://github.com/daniellekeefe\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n - Danielle\n </a>\n </span>\n </footer>\n );\n}", "function Footer(props) {\n return (\n <footer className=\"footer fixed-bottom\">\n <div class=\"container text-right\">\n <span><a href=\"https://github.com/carolinelester/clicky-game\">Github</a> </span>\n </div>\n </footer>\n )}", "function FooterDown() {\n return (\n <div className={style.downBlock}>\n <div className={`${styleContainer.container} ${style.downContainer}`}>\n <Title text={\"Roman Somov\"}/>\n <div className={style.socialIcons}>\n <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://t.me/romansmv8\" className={style.socialIcon}></a>\n <a href=\"tel:+375255434784\" className={style.socialIcon}>\n </a>\n <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.linkedin.com/in/romansmv\" className={style.socialIcon}>\n </a>\n </div>\n <span className={style.copyright}> 2021 All rights reserved</span>\n\n </div>\n\n </div>\n )\n}", "function setFooter(stats) {\n var footer = '';\n if (stats.show == 'true') {\n if (stats.type.value == \"image\") {\n footer = '<div id=\"footer\" style=\"z-index:30;text-align:' + stats.align.value + ';\"> <img src=\"' + basePath + 'images/' + stats.logo + '\" /></div>';\n }\n else {\n footer = '<div id=\"footer\" style=\"z-index:3;position:absolute;width:100%;text-align:' + stats.align.value + ';\"><div class=\"font-setter\" style=\"z-index:3;font-size:' + stats.size.value + ';\">' + stats.text + '</div></div>';\n }\n }\n return footer;\n }", "function getFooter(options) {\n\n\t// -- get this year\n\tlet date = new Date().getFullYear();\n\n\t// -- update the variables\n\toptions.name ? options.name : null;\n\toptions.url ? options.url : null;\n\toptions.copyYear ? options.copyYear : date;\n\toptions.policy ? options.policy : false;\n\toptions.terms ? options.terms : false;\n\toptions.cookies ? options.cookies : false;\n\toptions.customStyle ? options.customStyle : false;\n}", "function Footer() {\n\treturn (\n\t\t<footer className=\"fixed-bottom footer mt-5 py-3\">\n\t\t\t<div className=\"uk-flex uk-flex-column pl-5\">\n\t\t\t\t<div className=\"text-color\">\n\t\t\t\t\tDeveloped by\n\t\t\t\t</div>\n \n\t\t\t\t<div className=\"uk-flex uk-flex-row uk-flex-center\">\n\t\t\t\t\t{/* info for Janani */}\n\t\t\t\t\t<div className=\"member-info pl-5\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref=\"https://github.com/janani2285\"\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\">\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tclassName=\"member-thumbnail\"\n\t\t\t\t\t\t\t\tsrc=\"https://avatars1.githubusercontent.com/u/60902964?s=400&u=f09819b7a8342a29630728a55f962a5b0637427d&v=4\"\n\t\t\t\t\t\t\t\talt=\"Janani Nagaraj Amutha\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div className=\"text-color\">\n\t\t\t\t\t\t\tJanani\n\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\tNagaraj Amutha\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t{/* info for Shelby */}\n\t\t\t\t\t<div className=\"member-info pl-5\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref=\"https://github.com/Q118\"\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\">\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tclassName=\"member-thumbnail\"\n\t\t\t\t\t\t\t\tsrc=\"https://avatars1.githubusercontent.com/u/62257716?s=400&u=4ff63532506aadb20d2adf4ab1addfbc714a00e8&v=4\"\n\t\t\t\t\t\t\t\talt=\"Shelby Anne Rothman\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div className=\"text-color\">\n\t\t\t\t\t\t\tShelby\n\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\tAnne Rothman\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t{/* info for Robert */}\n\t\t\t\t\t<div className=\"member-info pl-5\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref=\"https://github.com/robertluttig\"\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\">\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tclassName=\"member-thumbnail\"\n\t\t\t\t\t\t\t\tsrc=\"https://avatars3.githubusercontent.com/u/66103426?s=400&u=c2186210dbbbd4cb6e07c5da9050201758bb75cf&v=4\"\n\t\t\t\t\t\t\t\talt=\"Robert Luttig\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div className=\"text-color\">\n\t\t\t\t\t\t\tRobert\n\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\tLuttig\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t{/* info for Jack */}\n\t\t\t\t\t<div className=\"member-info pl-5\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref=\"https://github.com/meierj423\"\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\">\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tclassName=\"member-thumbnail\"\n\t\t\t\t\t\t\t\tsrc=\"https://avatars3.githubusercontent.com/u/64444043?s=400&u=0ec873bdda09b8069d4c7d857a6002223ea595c0&v=4\"\n\t\t\t\t\t\t\t\talt=\"Jack Meier\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div className=\"text-color\">\n\t\t\t\t\t\t\tJack\n\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\tMeier\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</footer>\n\t);\n}", "function addFooter(report) {\n report.getFooter().addClass(\"footer\");\n var versionLine = report.getFooter().addText(\"Banana Accounting - Page \", \"description\");\n report.getFooter().addFieldPageNr();\n}", "function addFooter(report) {\r\n report.getFooter().addClass(\"footer\");\r\n var versionLine = report.getFooter().addText(\"Banana Accounting 8\" + \" - \", \"description\");\r\n report.getFooter().addText(\"Pagina \", \"description\");\r\n report.getFooter().addFieldPageNr();\r\n}", "function Footer(props) {\n return (\n <footer className={style.footer}>\n <span>Pooria©</span>\n </footer>\n );\n}", "function FOOTER$static_(){ToolbarSkin.FOOTER=( new ToolbarSkin(\"footer\"));}", "function Footer(props) {\n return (\n <footer className=\"footer\">\n <div className=\"bottom\">\n <a href=\"https://dreadpipe.github.io/v2portfolio/index.html\">Ben Harris Portfolio</a>\n </div>\n </footer>\n\n )\n}", "displayFooter() {\n }", "function Footer() {\n return (\n <footer className=\"footer py-6\">\n <div className=\"content has-text-centered\">\n <p>\n <strong>Selector Básico de Recursos</strong> por <a href=\"https://twitter.com/_kimael_\">Maikel Carballo</a>.\n </p>\n <p>\n <a\n href=\"https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Powered by{' '}\n <img src={logoVercel} alt=\"Vercel Logo\" className=\"logo\" />\n </a>\n <a href=\"https://bulma.io\" target=\"_blank\" rel=\"noopener noreferrer\">\n <img\n src={logoBulma}\n alt=\"Made with Bulma\"\n width=\"128\"\n height=\"24\" />\n </a>\n </p>\n </div>\n </footer>\n );\n}", "render() {\n return (\n <div>\n <footer className=\"footer\">\n <span className=\"navbar-dark bg-dark\"><a href=\"https://github.com/fmejia1625/employeeTracker_Mod3\" className=\"navbar-brand\">Created 06/21/2021 @fmejia1625</a></span>\n </footer>\n </div>\n );\n }", "function footerData(sourcefile){\r\n\treturn `<div class='information' id='information'>\r\n\t\t\t\r\n\t\t<div style='float:right; padding-top: 28px; padding-right: 14px;'>\r\n\t\t\tRobert Calamari 2019\r\n\t\t</div>\r\n\r\n\t</div>\r\n`;\r\n}", "function Footer() {\n\n // Returns HTML content to display on pages\n return (\n\n // Footer code adapted from Bootstrap Official Documents, I made changes to it \n // https://mdbootstrap.com/docs/b4/jquery/navigation/footer/\n\n <footer className=\"page-footer font-small\" style={{ backgroundColor: \"#f0f0f0\" }}>\n\n {/* Top Footer - About Section */}\n <div className=\"parallax\">\n <ul className=\"list-unstyled list-inline text-center py-2\">\n <li className=\"list-inline-item\">\n <h5 className=\"mb-1 text-uppercase footer-parralax-text\">Vibe Check</h5>\n <p style={{ color: \"white\", fontSize: \"20px\", margin: \"0 20px 20px 20px\" }}>A place for all students to connect and socialise!</p>\n </li>\n </ul>\n </div>\n\n {/* Bottom Footer - Copyright Section */}\n <div className=\"footer-copyright text-center py-3 \" style={{ backgroundColor: \"#27b8cfba\" }}><b>© 2021 Copyright:</b>\n <a href=\"/\" style={{ color: \"#c30000\" }}> <b>Vibe Check</b></a>\n </div>\n\n </footer>\n );\n}", "function populateFooter() {\n var container = document.querySelector(\"#networksContainer\");\n var networks = Object.keys(socialNetworks);\n var len = networks.length;\n // Iterate over networks and generate tags\n for (var i = 0; i < len; i++) {\n var name = networks[i];\n var url = socialNetworks[name].url;\n\n // Create and attach link element\n var link = document.createElement('a');\n link.href = url;\n container.appendChild(link);\n link.title = 'Kyle Maxwell on ' + name + '.';\n\n // Create and attach image element\n var image = document.createElement('img');\n image.src = 'images/' + name + '.png';\n link.appendChild(image);\n image.classList.add(\"icon\");\n }\n}", "function Footer() {\n const classes = useStyles();\n return (\n <footer className={classes.footer}>\n <Typography variant=\"h6\" align=\"center\" gutterBottom>\n {'Pan-Lang'}\n </Typography>\n <Typography\n variant=\"subtitle1\"\n align=\"center\"\n color=\"textSecondary\"\n component=\"p\"\n >\n {\n 'Helping the language barrier between food pantry coordinators and non-English speakers.'\n }\n </Typography>\n\n {/* GitHub link */}\n <a\n href=\"https://github.com/Pan-Lang\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={classes.github}\n >\n <IconButton aria-label=\"github\">\n <GitHubIcon />\n </IconButton>\n </a>\n\n {/* Copyright */}\n <Typography\n variant=\"body2\"\n color=\"textSecondary\"\n align=\"center\"\n className={classes.copyright}\n >\n {'Copyright © '}\n Pan-Lang {new Date().getFullYear()}\n {'.'}\n </Typography>\n </footer>\n );\n}", "addFooters() {\n /* Add footers for modified rows */\n this.gridApi.forEachNodeAfterFilterAndSort((node) => {\n if (node.data.hadronDocument.isModified()) {\n this.addFooter(node, node.data, 'editing');\n }\n });\n }", "function Footer() {\n return (\n <div class=\"footer\">\n <div class=\"footer-buttons\">\n <div to=\"/\" class=\"footerhead\" type=\"b1\"> SatVI </div>\n <div to=\"/\" class=\"footerhead\" type=\"b2\"> Subscribe </div>\n <div to=\"/\" class=\"footerhead\" type=\"b3\"> Contact </div>\n <div to=\"/\" class=\"footerhead\" type=\"b4\"> App</div>\n\n <Link to=\"/\" class=\"footerelement\" type=\"b5\"> About </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b6\"> Seller </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b7\"> yektaseckinsatir.com </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b8\"> Google Play </Link>\n\n <Link to=\"/\" class=\"footerelement\" type=\"b9\"> Help </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b10\"> Buyer </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b11\"> Contribute </Link>\n <Link to=\"/\" class=\"footerelement\" type=\"b12\"> App Store </Link>\n </div>\n </div>\n );\n}", "function addFooter(report) {\n\tvar date = new Date();\n\tvar d = Banana.Converter.toLocaleDateFormat(date);\n\treport.getFooter().addClass(\"footer\");\n\tvar versionLine = report.getFooter().addText(d + \" - Trial balance - Page \", \"description\");\n\treport.getFooter().addFieldPageNr();\n}", "function footer(){\ndiv= document.createElement(\"div\");\ndiv.className=\"bg-dark justify-content-center p-4 \";\n// adding techs used ---------------------------\ntech = document.createElement(\"p\");\ntech.innerHTML=`Techs Used - <span>html,css,bootstrap,javascript</span>`;\ntech.id=\"tech\";\ndiv.appendChild(tech);\n// adding Content Disclamier---------------------\ncontent = document.createElement(\"p\");\ncontent.innerHTML=`Content Disclamier - <span>The contant of this website is taken from <a href=\"https://api.openbrewerydb.org/breweries\">Open Brewery</a></span>`;\ncontent.id=\"content\";\ndiv.appendChild(content);\n// adding social media icons --------------------\nsocialmedia = document.createElement(\"p\");\nsocialmedia.innerHTML=`<a href=\"#\" class=\"fab fa-facebook-f\"></a> <a href=\"#\" class=\"fab fa-twitter\"></a> <a href=\"#\" class=\"fab fa-google\"></a> <a href=\"#\" class=\"fab fa-linkedin-in\"></a> <a href=\"#\" class=\"fab fa-youtube\"></a>`;\nsocialmedia.id=\"social\"\ndiv.appendChild(socialmedia);\nroot.appendChild(div); // adding all things to main root element \n}", "function Footer() {\n return (\n<footer class=\"page-footer font-small special-color-dark pt-4\">\n \n\n <div class=\"container\">\n \n\n <ul class=\"list-unstyled list-inline text-center\">\n <li class=\"list-inline-item\">\n <a class=\"btn-floating btn-fb mx-1\">\n <i class=\"fab fa-facebook\"></i>\n </a>\n </li>\n <li class=\"list-inline-item\">\n <a class=\"btn-floating btn-tw mx-1\">\n <i class=\"fab fa-twitter\"> </i>\n </a>\n </li>\n <li class=\"list-inline-item\">\n <a class=\"btn-floating btn-gplus mx-1\">\n <i class=\"fab fa-google-plus-g\"> </i>\n </a>\n </li>\n <li class=\"list-inline-item\">\n <a class=\"btn-floating btn-li mx-1\">\n <i class=\"fab fa-linkedin-in\"> </i>\n </a>\n </li>\n <li class=\"list-inline-item\">\n <a class=\"btn-floating btn-dribbble mx-1\">\n <i class=\"fab fa-dribbble\"> </i>\n </a>\n </li>\n </ul>\n\n \n </div>\n\n <div class=\"footer-copyright text-center py-3\">\n <a href=\"https://mdbootstrap.com/\"> </a>\n </div>\n\n \n </footer>\n\n\n );\n}", "function EMBEDDED_FOOTER$static_(){ToolbarSkin.EMBEDDED_FOOTER=( new ToolbarSkin(\"embedded-footer\"));}", "Footer() {\n return (\n <div style={{ paddingbottom: \"60px\" }}>\n\n <Footer className='login-footer' size=\"mini\">\n <FooterSection type=\"left\" logo=\"North.\">\n <FooterLinkList>\n <a target=\"_blank\" href=\"https://drive.google.com/open?id=1bModZ1EzBEdGyZltHlMCmiW2o0fjjEmC\">Help</a>\n <a target=\"_blank\" href=\"https://drive.google.com/open?id=1tWE13UlHbMgXlFPAvF59OO0xwQB_wCrt\">Privacy Policy</a>\n <a target=\"_blank\" href=\"https://drive.google.com/open?id=1NtARcUGS2ygw1dfAhPEHjpanxqG8OuH-\">Terms & Conditions</a>\n </FooterLinkList>\n </FooterSection>\n </Footer>\n </div>);\n }", "function addFooter(banDoc, report) {\r\n\treport.getFooter().addClass(\"footer\");\r\n\treport.getFooter().addText(\"[Banana Accounting, v. \" + banDoc.info(\"Base\", \"ProgramVersion\") + \", \" + scriptVersion + \"] - Page \", \"footer\");\r\n\treport.getFooter().addFieldPageNr();\r\n}", "function Footer(props) {\n return (\n <CardFooter extras=\"text-center\">\n {props.version && <p>Version {props.version}</p>}\n </CardFooter>\n );\n}", "function Footer(){\n\treturn(\n\t\t<footer>\n\t\t\t<div className=\"row\">\n\t\t\t\t<ul className=\"col-12\">\n\t\t\t\t <li><Link to=\"\" > LinkedIn</Link> </li>\n\t\t\t\t\t<li><Link to=\"\" >GitHub</Link> </li>\n\t\t\t\t</ul>\n\t\t\t\t<p className=\"col-12\">&copy; ReactMasters, {new Date().getFullYear()}</p>\n\t\t\t</div>\n\t\t</footer>\n\t);\n}", "function Footer() {\n\n return (\n <div className=\"footer\">\n <p>Developed by Jimmy Hwang | API from Imgur LLC</p>\n </div>\n )\n}", "function Footer() {\n return (\n <Wrapper>\n <section>This project is licensed under the MIT license.</section>\n <section>语言选择开关</section>\n <section>\n Made with love by\n <A href=\"https://twitter.com/mxstbr\">Max Stoiber</A>,\n </section>\n </Wrapper>\n );\n}" ]
[ "0.62667", "0.6112618", "0.60512996", "0.6045475", "0.6011048", "0.58833", "0.5870987", "0.58429146", "0.5822146", "0.58212376", "0.5781214", "0.5706013", "0.5696709", "0.5685122", "0.5672404", "0.5655897", "0.56544733", "0.56410474", "0.5632018", "0.5631681", "0.56021553", "0.5569694", "0.55494666", "0.554639", "0.55423456", "0.5533733", "0.55221874", "0.5520357", "0.5516016", "0.5487149" ]
0.73439527
0
Returns a controller object for setting a timeout that is properly cleaned up once the component unmounts. New timeouts cancel and replace existing ones.
function useTimeout() { var isMounted = Object(_useMounted__WEBPACK_IMPORTED_MODULE_2__["default"])(); var handle = Object(react__WEBPACK_IMPORTED_MODULE_0__["useRef"])(); var clear = function clear() { return clearTimeout(handle.current); }; Object(_useWillUnmount__WEBPACK_IMPORTED_MODULE_1__["default"])(clear); return { set: function set(fn, ms) { if (!isMounted()) return; clear(); handle.current = setTimeout(fn, ms); }, clear: clear }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function useTimeout () {\n let timer = null;\n const vm = vue.getCurrentInstance();\n\n function removeTimeout () {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n vue.onDeactivated(removeTimeout);\n vue.onBeforeUnmount(removeTimeout);\n\n return {\n removeTimeout,\n\n registerTimeout (fn, delay) {\n removeTimeout();\n\n if (vmIsDestroyed(vm) === false) {\n timer = setTimeout(fn, delay);\n }\n }\n }\n }", "cancel() {\n clearTimeout(this.timeoutID);\n delete this.timeoutID;\n }", "constructor(timeout) {\n this.initialTimeout = timeout\n this.reset()\n }", "constructor(timeout_in_secs) {\n this.initial_timeout_in_secs = timeout_in_secs\n this.reset()\n }", "function useTimeout() {\n var isMounted = Object(_useMounted__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(); // types are confused between node and web here IDK\n\n var handleRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])();\n Object(_useWillUnmount__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(function () {\n return clearTimeout(handleRef.current);\n });\n return Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useMemo\"])(function () {\n var clear = function clear() {\n return clearTimeout(handleRef.current);\n };\n\n function set(fn, delayMs) {\n if (delayMs === void 0) {\n delayMs = 0;\n }\n\n if (!isMounted()) return;\n clear();\n\n if (delayMs <= MAX_DELAY_MS) {\n // For simplicity, if the timeout is short, just set a normal timeout.\n handleRef.current = setTimeout(fn, delayMs);\n } else {\n setChainedTimeout(handleRef, fn, Date.now() + delayMs);\n }\n }\n\n return {\n set: set,\n clear: clear\n };\n }, []);\n}", "function useTimeout() {\n var isMounted = Object(_useMounted__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(); // types are confused between node and web here IDK\n\n var handleRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])();\n Object(_useWillUnmount__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(function () {\n return clearTimeout(handleRef.current);\n });\n return Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useMemo\"])(function () {\n var clear = function clear() {\n return clearTimeout(handleRef.current);\n };\n\n function set(fn, delayMs) {\n if (delayMs === void 0) {\n delayMs = 0;\n }\n\n if (!isMounted()) return;\n clear();\n\n if (delayMs <= MAX_DELAY_MS) {\n // For simplicity, if the timeout is short, just set a normal timeout.\n handleRef.current = setTimeout(fn, delayMs);\n } else {\n setChainedTimeout(handleRef, fn, Date.now() + delayMs);\n }\n }\n\n return {\n set: set,\n clear: clear\n };\n }, []);\n}", "function useTimeout() {\n var isMounted = Object(_useMounted__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(); // types are confused between node and web here IDK\n\n var handleRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])();\n Object(_useWillUnmount__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(function () {\n return clearTimeout(handleRef.current);\n });\n return Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useMemo\"])(function () {\n var clear = function clear() {\n return clearTimeout(handleRef.current);\n };\n\n function set(fn, delayMs) {\n if (delayMs === void 0) {\n delayMs = 0;\n }\n\n if (!isMounted()) return;\n clear();\n\n if (delayMs <= MAX_DELAY_MS) {\n // For simplicity, if the timeout is short, just set a normal timeout.\n handleRef.current = setTimeout(fn, delayMs);\n } else {\n setChainedTimeout(handleRef, fn, Date.now() + delayMs);\n }\n }\n\n return {\n set: set,\n clear: clear\n };\n }, []);\n}", "function useTimeout() {\n var isMounted = Object(_useMounted__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(); // types are confused between node and web here IDK\n\n var handleRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])();\n Object(_useWillUnmount__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(function () {\n return clearTimeout(handleRef.current);\n });\n return Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useMemo\"])(function () {\n var clear = function clear() {\n return clearTimeout(handleRef.current);\n };\n\n function set(fn, delayMs) {\n if (delayMs === void 0) {\n delayMs = 0;\n }\n\n if (!isMounted()) return;\n clear();\n\n if (delayMs <= MAX_DELAY_MS) {\n // For simplicity, if the timeout is short, just set a normal timeout.\n handleRef.current = setTimeout(fn, delayMs);\n } else {\n setChainedTimeout(handleRef, fn, Date.now() + delayMs);\n }\n }\n\n return {\n set: set,\n clear: clear\n };\n }, []);\n}", "function timerController() {\n this.model = new timerModel();\n this.view = new timerView();\n}", "@action.bound\n setTimeoutVerification() {\n this.clearTimeoutVerification();\n this.timeout_verification_button = setTimeout(() => {\n this.clearVerification();\n }, 3600000);\n }", "function createController() {\n if (!_options || !_options.controllerDivId || !_options.playAndPauseDivId) {\n throw \"ERROR: Options or properties missing for controller!\";\n\n } else {\n // Do not create controller if animation has not defined any time period for frames.\n // If no period is given, then only show currently given layers.\n if (getBeginDate() !== undefined && getEndDate() !== undefined) {\n var ctrlSelector = \"#\" + _options.controllerDivId;\n var ctrls = jQuery(ctrlSelector);\n if (ctrls.length) {\n var animationShowUtc = getAnimationShowUtc();\n var currentTime = (new Date()).getTime();\n var startTime = getBeginDate().getTime();\n var endTime = getEndDate().getTime();\n // Forecast start time.\n var fctStart = getForecastBeginDate().getTime();\n // If end time is less than forecast time, then forecast is not used and value is left undefined.\n if (endTime < fctStart) {\n fctStart = undefined;\n }\n var timePeriodListeners = [];\n var timeSelectionListeners = [];\n var fctStartTimeListeners = [];\n var tickIntervalListeners = [];\n\n // Model is used by animation controller to setup slider according to the animation settings.\n var timeModel = {\n getStartTime : function() {\n return startTime;\n },\n getEndTime : function() {\n return endTime;\n },\n getResolution : function() {\n return getResolution();\n },\n getForecastStartTime : function() {\n return fctStart;\n },\n getAnimationShowUtc : function() {\n return animationShowUtc;\n },\n addTimePeriodChangeListener : function(l) {\n timePeriodListeners.push(l);\n },\n addTimeSelectionChangeListener : function(l) {\n timeSelectionListeners.push(l);\n },\n addAnimationEventsListener : function(l) {\n _animationEventsListeners.push(l);\n },\n addForecastStartTimeChangeListener : function(l) {\n fctStartTimeListeners.push(l);\n },\n addTickIntervalChangeListener : function(l) {\n tickIntervalListeners.push(l);\n }\n };\n\n // Animation controller may use these callback functions to inform\n // if animation state should be changed because of the actions in the slider.\n var timeController = {\n proposeTimePeriodChange : function(startTime, endTime) {\n\n },\n proposeTimeSelectionChange : function(time) {\n var resolution = getResolution();\n if (resolution && undefined !== time && null !== time) {\n // Force the time to be inside accepted range.\n if (time < startTime) {\n // Notice, time may be almost one resolution less than startTime\n // because the time is ceiled on the resolution and the time step\n // describes the time resolution before the given time.\n time = startTime;\n\n } else if (time > endTime) {\n time = endTime;\n\n } else {\n // Make sure steps are in given resolutions.\n var reminder = time % resolution;\n if (reminder) {\n // Time is ceiled on the resolution.\n time = time - reminder + resolution;\n }\n }\n fireSelectedTimeChanged(time, timeSelectionListeners);\n }\n },\n proposeNextFrame : function() {\n fireNextFrame();\n },\n proposePreviousFrame : function() {\n firePreviousFrame();\n },\n proposePause : function() {\n firePause();\n }\n };\n\n setPlayAndPause();\n\n _animationController = createCtrl(ctrls, timeModel, timeController);\n\n // Bind to listen for width changes in element to update\n // controller if necessary. Width is defined as relative\n // in CSS but height is static.\n var width = ctrls.width();\n // Notice, the window resize listener has already been set during animator construction.\n _animationControllerResize = function() {\n var currentWidth = jQuery(ctrlSelector).width();\n if (currentWidth !== width) {\n width = currentWidth;\n // Simply replace old with a new controller.\n _animationController.remove();\n _animationController = createCtrl(ctrls, timeModel, timeController);\n }\n };\n }\n }\n }\n }", "function createController() {\n if (!_options || !_options.controllerDivId || !_options.playAndPauseDivId) {\n throw \"ERROR: Options or properties missing for controller!\";\n }\n\n // Do not create controller if animation has not defined any time period for frames.\n // If no period is given, then only show currently given layers.\n if (getBeginDate() !== undefined && getEndDate() !== undefined) {\n var ctrlSelector = \"#\" + _options.controllerDivId;\n var ctrls = jQuery(ctrlSelector);\n if (ctrls.length) {\n var currentTime = (new Date()).getTime();\n var startTime = getBeginDate().getTime();\n var endTime = getEndDate().getTime();\n // Forecast start time.\n var fctStart = getForecastBeginDate().getTime();\n // If end time is less than forecast time, then forecast is not used and value is left undefined.\n if (endTime < fctStart) {\n fctStart = undefined;\n }\n var timePeriodListeners = [];\n var timeSelectionListeners = [];\n var fctStartTimeListeners = [];\n var tickIntervalListeners = [];\n\n // Model is used by animation controller to setup slider according to the animation settings.\n var timeModel = {\n getStartTime : function() {\n return startTime;\n },\n getEndTime : function() {\n return endTime;\n },\n getResolution : function() {\n return getResolution();\n },\n getForecastStartTime : function() {\n return fctStart;\n },\n addTimePeriodChangeListener : function(l) {\n timePeriodListeners.push(l);\n },\n addTimeSelectionChangeListener : function(l) {\n timeSelectionListeners.push(l);\n },\n addAnimationEventsListener : function(l) {\n _animationEventsListeners.push(l);\n },\n addForecastStartTimeChangeListener : function(l) {\n fctStartTimeListeners.push(l);\n },\n addTickIntervalChangeListener : function(l) {\n tickIntervalListeners.push(l);\n }\n };\n\n // Animation controller may use these callback functions to inform\n // if animation state should be changed because of the actions in the slider.\n var timeController = {\n proposeTimePeriodChange : function(startTime, endTime) {\n\n },\n proposeTimeSelectionChange : function(time) {\n if ((time >= startTime) && (time <= endTime)) {\n // Make sure steps are in given resolutions.\n time = time - time % getResolution();\n fireSelectedTimeChanged(time, timeSelectionListeners);\n }\n },\n proposeNextFrame : function() {\n fireNextFrame();\n },\n proposePreviousFrame : function() {\n firePreviousFrame();\n },\n proposePause : function() {\n firePause();\n }\n };\n\n _animationController = createCtrl(ctrls, timeModel, timeController);\n\n // Bind to listen for width changes in element to update\n // controller if necessary. Width is defined as relative\n // in CSS but height is static.\n var width = ctrls.width();\n // Notice, the window resize listener has already been set during animator construction.\n // Use debounce to limit frequency of component redraw operations.\n _animationControllerResize = createDebounce(function() {\n var currentWidth = jQuery(ctrlSelector).width();\n if (currentWidth !== width) {\n width = currentWidth;\n // Simply replace old with a new controller.\n _animationController.remove();\n _animationController = createCtrl(ctrls, timeModel, timeController);\n }\n });\n\n setPlayAndPause();\n }\n }\n }", "timeout(ms) {\n this._timeout = ms;\n return this;\n }", "function Timer(timeout) {\n this.timeout = timeout || 0;\n\n this.reset();\n }", "stop() {\n const privateProps = internal(this);\n clearTimeout(privateProps.timeoutId);\n privateProps.timeoutId = null;\n }", "setHideTimeout() {\n this.hide_timeout = setInterval(() => {\n this.props.setModalRootComponent(undefined)\n this.props.setModalVisibility(false)\n }, 2 * 10 * 1000)\n }", "_killMyself() {\n this.state.timeout = null;\n this.close({ notification: this.state.notification, by: 'timeout' });\n }", "function openTimeoutModal($scope, $modal) {\n closeModals($scope);\n $scope.timedout = $modal.open({\n templateUrl: 'views/timedout-dialog.html',\n windowClass: 'modal-danger'\n });\n}", "timeoutInvalidationRequestFromPlayer() {\n clearTimeout(this.claimTimeout);\n this.claimTimeout = false;\n }", "setTimeout(s) {\r\n this.timeout = s;\r\n return this;\r\n }", "function timeout(time) {\n return trait(function () {\n if (arguments.length === 1) {\n const target = arguments[0];\n target[timeoutSymbol] = time;\n }\n else if (arguments.length === 2 && typeof arguments[1] === \"string\" || typeof arguments[1] === \"symbol\") {\n const target = arguments[0];\n const property = arguments[1];\n target[property][timeoutSymbol] = time;\n }\n else if (arguments.length === 2) {\n const context = arguments[0];\n const ctor = arguments[1];\n context.timeout(time);\n }\n else if (arguments.length === 3) {\n if (typeof arguments[2] === \"function\") {\n const context = arguments[0];\n const instance = arguments[1];\n const method = arguments[2];\n context.timeout(time);\n }\n else if (typeof arguments[1] === \"string\" || typeof arguments[1] === \"symbol\") {\n const proto = arguments[0];\n const prop = arguments[1];\n const descriptor = arguments[2];\n proto[prop][timeoutSymbol] = time;\n }\n }\n });\n}", "function t(e) {\n return {\n setTimeout: function setTimeout(t, o) {\n var r = e.setTimeout(t, o);\n return {\n remove: function remove() {\n return e.clearTimeout(r);\n }\n };\n }\n };\n }", "function cancellableTimeout(f, milliseconds) {\n\tvar timerId = 0;\n\n\tif (Number(milliseconds) === NaN || milliseconds <= 0) throw new Error('time:' + milliseconds + ' must be a number greater than zero.');\n\tif (typeof f !== 'function') throw new Error('action is not a function');\n\n\treturn {\n\t\tpromise: function promise(arg) {\n\t\t\treturn new Promise(function (resolve, reject) {\n\t\t\t\ttimerId = setTimeout(function () {\n\t\t\t\t\ttimerId = 0;\n\t\t\t\t\tresolve(f.call(undefined, arg));\n\t\t\t\t}, Number(milliseconds));\n\t\t\t});\n\t\t},\n\t\tcancel: function cancel() {\n\t\t\tif (timerId > 0) {\n\t\t\t\tclearTimeout(timerId);\n\t\t\t}\n\t\t}\n\t};\n}", "set timeout(milliseconds) {\n this._timeout = milliseconds;\n }", "_dismissAfter(duration) {\n // Note that we need to cap the duration to the maximum value for setTimeout, because\n // it'll revert to 1 if somebody passes in something greater (e.g. `Infinity`). See #17234.\n this._durationTimeoutId = setTimeout(() => this.dismiss(), Math.min(duration, MAX_TIMEOUT));\n }", "static timeout(t) {\n if ( !(typeof t === 'undefined' ))\n _timeout = t;\n else\n return _timeout;\n }", "function cleanUpTimeout(inv) {\n if (!inv) return;\n delete timeouts[inv.timerKey];\n delete inv.timerKey;\n inv.release(); // return to pool \n}", "function setTimeout(timeout) {\n options.requestTimeout = Number(timeout);\n instance.defaults.timeout = options.requestTimeout;\n }", "setTimeout(timeout) {\n if (this.global.jasmine) {\n // eslint-disable-next-line no-underscore-dangle\n this.global.jasmine.DEFAULT_TIMEOUT_INTERVAL = timeout;\n } else {\n this.global[Symbol.for('TEST_TIMEOUT_SYMBOL')] = timeout;\n }\n }", "cancel() {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n this.timeoutId = undefined;\n this.intervalId = undefined;\n this.sequence = 0;\n this.isActive = false;\n this.times = [];\n if (this.rejectCallback) {\n this.rejectCallback(new Error('cancel'));\n }\n this.rejectCallback = undefined;\n }" ]
[ "0.59614664", "0.56049776", "0.5577963", "0.5490032", "0.53819746", "0.53819746", "0.53819746", "0.53819746", "0.5364445", "0.52735806", "0.51561654", "0.5131061", "0.51134", "0.5094438", "0.5089148", "0.50206435", "0.50079304", "0.4987263", "0.49868378", "0.4974295", "0.49478927", "0.49356198", "0.49326858", "0.49179775", "0.49159393", "0.48871502", "0.48830712", "0.4873654", "0.48735493", "0.48703673" ]
0.5744796
1
`Dropdown` is set of structural components for building, accessible dropdown menus with closeonclick, keyboard navigation, and correct focus handling. As with all the reactoverlay's components its BYOS (bring your own styles). Dropdown is primarily built from three base components, you should compose to build your Dropdowns. `Dropdown`, which wraps the menu and toggle, and handles keyboard navigation `Dropdown.Toggle` generally a button that triggers the menu opening `Dropdown.Menu` The overlaid, menu, positioned to the toggle with PopperJs
function Dropdown(_ref) { var drop = _ref.drop, alignEnd = _ref.alignEnd, defaultShow = _ref.defaultShow, rawShow = _ref.show, rawOnToggle = _ref.onToggle, itemSelector = _ref.itemSelector, focusFirstItemOnShow = _ref.focusFirstItemOnShow, children = _ref.children; var forceUpdate = Object(_restart_hooks_useForceUpdate__WEBPACK_IMPORTED_MODULE_7__["default"])(); var _useUncontrolled = Object(uncontrollable__WEBPACK_IMPORTED_MODULE_4__["useUncontrolled"])({ defaultShow: defaultShow, show: rawShow, onToggle: rawOnToggle }, { show: 'onToggle' }), show = _useUncontrolled.show, onToggle = _useUncontrolled.onToggle; var _useCallbackRef = Object(_restart_hooks_useCallbackRef__WEBPACK_IMPORTED_MODULE_6__["default"])(), toggleElement = _useCallbackRef[0], setToggle = _useCallbackRef[1]; // We use normal refs instead of useCallbackRef in order to populate the // the value as quickly as possible, otherwise the effect to focus the element // may run before the state value is set var menuRef = Object(react__WEBPACK_IMPORTED_MODULE_2__["useRef"])(); var menuElement = menuRef.current; var setMenu = Object(react__WEBPACK_IMPORTED_MODULE_2__["useCallback"])(function (ref) { menuRef.current = ref; // ensure that a menu set triggers an update for consumers forceUpdate(); }, [forceUpdate]); var lastShow = Object(_restart_hooks_usePrevious__WEBPACK_IMPORTED_MODULE_5__["default"])(show); var lastSourceEvent = Object(react__WEBPACK_IMPORTED_MODULE_2__["useRef"])(null); var focusInDropdown = Object(react__WEBPACK_IMPORTED_MODULE_2__["useRef"])(false); var toggle = Object(react__WEBPACK_IMPORTED_MODULE_2__["useCallback"])(function (event) { onToggle(!show, event); }, [onToggle, show]); var context = Object(react__WEBPACK_IMPORTED_MODULE_2__["useMemo"])(function () { return { toggle: toggle, drop: drop, show: show, alignEnd: alignEnd, menuElement: menuElement, toggleElement: toggleElement, setMenu: setMenu, setToggle: setToggle }; }, [toggle, drop, show, alignEnd, menuElement, toggleElement, setMenu, setToggle]); if (menuElement && lastShow && !show) { focusInDropdown.current = menuElement.contains(document.activeElement); } var focusToggle = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__["default"])(function () { if (toggleElement && toggleElement.focus) { toggleElement.focus(); } }); var maybeFocusFirst = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__["default"])(function () { var type = lastSourceEvent.current; var focusType = focusFirstItemOnShow; if (focusType == null) { focusType = menuRef.current && Object(dom_helpers_matches__WEBPACK_IMPORTED_MODULE_0__["default"])(menuRef.current, '[role=menu]') ? 'keyboard' : false; } if (focusType === false || focusType === 'keyboard' && !/^key.+$/.test(type)) { return; } var first = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__["default"])(menuRef.current, itemSelector)[0]; if (first && first.focus) first.focus(); }); Object(react__WEBPACK_IMPORTED_MODULE_2__["useEffect"])(function () { if (show) maybeFocusFirst();else if (focusInDropdown.current) { focusInDropdown.current = false; focusToggle(); } // only `show` should be changing }, [show, focusInDropdown, focusToggle, maybeFocusFirst]); Object(react__WEBPACK_IMPORTED_MODULE_2__["useEffect"])(function () { lastSourceEvent.current = null; }); var getNextFocusedChild = function getNextFocusedChild(current, offset) { if (!menuRef.current) return null; var items = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__["default"])(menuRef.current, itemSelector); var index = items.indexOf(current) + offset; index = Math.max(0, Math.min(index, items.length)); return items[index]; }; var handleKeyDown = function handleKeyDown(event) { var key = event.key, target = event.target; // Second only to https://github.com/twbs/bootstrap/blob/8cfbf6933b8a0146ac3fbc369f19e520bd1ebdac/js/src/dropdown.js#L400 // in inscrutability var isInput = /input|textarea/i.test(target.tagName); if (isInput && (key === ' ' || key !== 'Escape' && menuRef.current && menuRef.current.contains(target))) { return; } lastSourceEvent.current = event.type; switch (key) { case 'ArrowUp': { var next = getNextFocusedChild(target, -1); if (next && next.focus) next.focus(); event.preventDefault(); return; } case 'ArrowDown': event.preventDefault(); if (!show) { toggle(event); } else { var _next = getNextFocusedChild(target, 1); if (_next && _next.focus) _next.focus(); } return; case 'Escape': case 'Tab': onToggle(false, event); break; default: } }; return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_DropdownContext__WEBPACK_IMPORTED_MODULE_9__["default"].Provider, { value: context }, children({ props: { onKeyDown: handleKeyDown } })); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(direction, Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"A\" /* useKeyOnly */])(open, 'visible'), Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"A\" /* useKeyOnly */])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(DropdownMenu, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(DropdownMenu, props);\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(ElementType, __WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_extends___default()({}, rest, {\n className: classes\n }), __WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* childrenUtils */].isNil(children) ? content : children);\n}", "render() {\n return (\t\n <Dropdown className={css(style.dropDownStyle)} isOpen={this.state.dropdownOpen} toggle={this.toggle} size=\"lg\">\n <DropdownToggle caret className={css(style.fontSizeStyle, style.colorThemeStyle)}>\n Welcome, <strong className={css(style.fontSizeStyle, style.colorThemeStyle)}>{this.state.names+ \" \"}</strong>\n </DropdownToggle>\n <DropdownMenu right className={css(style.fontSizeStyle, style.colorThemeStyle)}>\n <DropdownItem header className={css(style.fontSizeStyle)}>Profile</DropdownItem>\n <DropdownItem divider /> \n <DropdownItem tag={Link} to={\"/profile/\" + this.props.user.username} className={css(style.fontSizeStyle, style.colorThemeStyle)}>My Profile</DropdownItem>\n <DropdownItem tag={Link} to={\"/projects\"} className={css(style.fontSizeStyle, style.colorThemeStyle)}>My Projects</DropdownItem>\n <DropdownItem divider /> \n <DropdownItem className={css(style.fontSizeStyle, style.colorThemeStyle)}>Settings</DropdownItem>\n <DropdownItem divider />\n <DropdownItem onClick={this.props.logout}>Log out</DropdownItem>\n </DropdownMenu>\n </Dropdown> \n );\n }", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()(direction, Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(open, 'visible'), Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(DropdownMenu, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(DropdownMenu, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()(direction, Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(open, 'visible'), Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(DropdownMenu, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(DropdownMenu, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = Object(clsx__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(direction, Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(open, 'visible'), Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"useKeyOnly\"])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(DropdownMenu, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(DropdownMenu, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n\n var classes = (0, _classnames2.default)(direction, (0, _lib.useKeyOnly)(open, 'visible'), (0, _lib.useKeyOnly)(scrolling, 'scrolling'), 'menu transition', className);\n var rest = (0, _lib.getUnhandledProps)(DropdownMenu, props);\n var ElementType = (0, _lib.getElementType)(DropdownMenu, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = (0, _classnames[\"default\"])(direction, (0, _lib.useKeyOnly)(open, 'visible'), (0, _lib.useKeyOnly)(scrolling, 'scrolling'), 'menu transition', className);\n var rest = (0, _lib.getUnhandledProps)(DropdownMenu, props);\n var ElementType = (0, _lib.getElementType)(DropdownMenu, props);\n return _react[\"default\"].createElement(ElementType, (0, _extends2[\"default\"])({}, rest, {\n className: classes\n }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = cx(direction, useKeyOnly(open, 'visible'), useKeyOnly(scrolling, 'scrolling'), 'menu transition', className);\n var rest = getUnhandledProps(DropdownMenu, props);\n var ElementType = getElementType(DropdownMenu, props);\n return React.createElement(ElementType, _extends({}, rest, {\n className: classes\n }), childrenUtils.isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n scrolling = props.scrolling;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"a\" /* useKeyOnly */])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(DropdownMenu, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(DropdownMenu, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n scrolling = props.scrolling;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"z\" /* useKeyOnly */])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getUnhandledProps */])(DropdownMenu, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"p\" /* getElementType */])(DropdownMenu, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n children\n );\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n direction = props.direction,\n open = props.open,\n scrolling = props.scrolling;\n var classes = classnames_default()(direction, useKeyOnly(open, 'visible'), useKeyOnly(scrolling, 'scrolling'), 'menu transition', className);\n var rest = lib_getUnhandledProps(DropdownMenu, props);\n var ElementType = lib_getElementType(DropdownMenu, props);\n return react_default.a.createElement(ElementType, extends_default()({}, rest, {\n className: classes\n }), childrenUtils_namespaceObject.isNil(children) ? content : children);\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n scrolling = props.scrolling;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"B\" /* useKeyOnly */])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(DropdownMenu, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(DropdownMenu, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n scrolling = props.scrolling;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"B\" /* useKeyOnly */])(scrolling, 'scrolling'), 'menu transition', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(DropdownMenu, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(DropdownMenu, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "dropDownJSX(props){\n const md5 = \"\"; // Unique per game\n let compositions = localStorage.getItem(\"compositions\" + md5) ? JSON.parse(localStorage.getItem(\"compositions\" + md5)) : {};\n if (typeof (compositions) === \"string\") {\n compositions = {};\n }\n\n\n\n const dropDownItems = <DropdownItem\n onClick={() => {\n }}\n >\n </DropdownItem>;\n return <ButtonDropdown\n isOpen={props.isDown}\n toggle={() => props.toggleDropDown('loadCompositionDropDown')}\n >\n {\" \"}\n <DropdownToggle caret>App</DropdownToggle>\n <DropdownMenu>\n {dropDownItems}\n </DropdownMenu>\n </ButtonDropdown>\n }", "function useDropdownToggle() {\n var _ref = react.useContext(DropdownContext) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop$2 : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = react.useCallback(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop$2,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function Dropdown(){\n\n /**\n * State for whether it has been clicked or not\n */\n const [click, setClick] = useState(false);\n\n /**\n * This function toggles between clicked and not clicked\n */\n const handleClick = () => setClick(!click);\n\n return(\n <>\n <ul onClick={handleClick} className={click ? 'dropdown-menu clicked' : 'dropdown-menu'} >\n {MenuItems.map((item, index) => {\n return (\n <li key={index}>\n <Link className={item.cName} to={item.path} onClick={() => setClick(false)}>\n {item.title}\n </Link>\n </li>\n )\n })}\n </ul>\n\n </>\n );\n}", "function DropdownMenu(props) {\n var children = props.children,\n className = props.className,\n scrolling = props.scrolling;\n\n var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(scrolling, 'scrolling'), 'menu transition', className);\n var rest = (0, _lib.getUnhandledProps)(DropdownMenu, props);\n var ElementType = (0, _lib.getElementType)(DropdownMenu, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), children);\n}", "render() {\r\n const { props } = this; //props=this.props\r\n const dropItem = props.pop_group.map((data, index) => {\r\n return /2018/.test(data) ? (\r\n <DropdownItem\r\n style={{ fontSize: \"13px\", fontWeight: \"bold\" }}\r\n className=\"item\"\r\n key={index}\r\n >\r\n {data}\r\n </DropdownItem>\r\n ) : null;\r\n });\r\n\r\n return (\r\n //dropdown menu or measure names\r\n <React.Fragment>\r\n <Dropdown\r\n style={{ marginLeft: \"5%\", marginTop: \"3%\", backgroundColor: '#0079BE'}}\r\n isOpen={this.state.dropdownopen}\r\n toggle={this.toggle}\r\n >\r\n <DropdownToggle caret style= {{backgroundColor: '#0079BE'}}>{props.selectedMenu}</DropdownToggle>\r\n <DropdownMenu onClick={event => props.onMenuSelect(event)}>\r\n {dropItem}\r\n </DropdownMenu>\r\n </Dropdown>\r\n </React.Fragment>\r\n );\r\n }", "function useDropdownToggle() {\n var _ref = (0,react__WEBPACK_IMPORTED_MODULE_1__.useContext)(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__.default) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = (0,react__WEBPACK_IMPORTED_MODULE_1__.useCallback)(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _ref = (0,react__WEBPACK_IMPORTED_MODULE_1__.useContext)(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__.default) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = (0,react__WEBPACK_IMPORTED_MODULE_1__.useCallback)(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "componentDidMount() {\n $('.dropdown-button').dropdown({\n inDuration: 300,\n outDuration: 225,\n constrainWidth: false, // Does not change width of dropdown to that of the activator\n hover: false, // Activate on hover\n gutter: 0, // Spacing from edge\n belowOrigin: false, // Displays dropdown below the button\n alignment: 'left', // Displays dropdown with edge aligned to the left of button\n stopPropagation: false // Stops event propagation\n }\n );\n }", "function DropdownMenu(_ref2) {\n var children = _ref2.children,\n options = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(_ref2, [\"children\"]);\n\n var args = useDropdownMenu(options);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, args.hasShown ? children(args) : null);\n}", "function DropdownMenu(_ref2) {\n var children = _ref2.children,\n options = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(_ref2, [\"children\"]);\n\n var args = useDropdownMenu(options);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, args.hasShown ? children(args) : null);\n}", "function CuiDropdown(params) {\n cuiInitNode(this);\n\n var toggle;\n var popup;\n var self = this;\n\n this.onConstruct = function() {\n toggle = new CuiToggle({\n cssClass: \"cui_dropdown\",\n onChange: function(value) {\n if (params.uniformWidth && self.isLive()) {\n popup.get$().css('width', toggle.get$().width() + \"px\");\n }\n popup.toggle(value);\n },\n content: params.buttonContent,\n });\n popup = new CuiPopup({\n cssClass: \"cui_dropdown\",\n content: params.popupContent,\n });\n return [\n \"<div class='cui_dropdown \" + params.cssClass + \"'>\",\n toggle,\n popup,\n \"</div>\",\n ];\n }\n\n this.onRefresh = function($me, dirty, live) {\n cuiRefresh([toggle, popup], live);\n }\n}", "function Dropdown(props) {\n return (\n <div className=\"control\">\n <label htmlFor={props.id}>{props.label}</label>\n <select\n id={props.id}\n className=\"select-css\"\n value={props.value}\n onChange={(e) => props.onChange(e, props.id)}\n onBlur={(e) => props.onChange(e, props.id)}>\n {props.options.map((item) => (\n <option\n key={item.symbol}\n value={item.symbol}\n disabled={item.symbol === props.disabledValue}>\n {item.name}\n </option>\n ))}\n </select>\n </div>\n );\n}", "render() {\n return (\n <UncontrolledDropdown>\n <DropdownToggle className='menu-icon icon-more'>\n </DropdownToggle>\n <DropdownMenu right >\n {/* Will delete the parent Workflow from the Workflows List */}\n <DropdownItem key={1} onClick={this.deleteOption}> \n Delete \n </DropdownItem>\n </DropdownMenu>\n </UncontrolledDropdown>\n );\n }", "function DropNav(props) {\n // const [dropdown, setDropdown] = useState(false);\n\n const changeHandler =(event)=>{\n props.value(event.target.value)\n } ;\n return (\n <>\n <nav className='navbar1'>\n <Link to='/' className='navbar1-logo'>\n Visualize Graphs\n </Link>\n \n <div>\n \n <select onChange={changeHandler} >\n <option value='plot'>Plot</option>\n <option value='Exponantial'>Exponantial</option>\n <option value='EXX1'>EXX1</option>\n <option value='Linear'>Linear</option>\n <option value='Logarithm'>Logrithms</option>\n <option value='XCube'>XCube</option>\n <option value='XSqX1'>XsqX1</option>\n \n </select>\n </div>\n \n </nav>\n </>\n );\n}", "function ParentDropdown() {\n return (\n <div className=\"ui simple selection dropdown\">\n <input type=\"hidden\" name=\"student\" />\n <i className=\"dropdown icon\"></i>\n <div className=\"left icon default text\">Select Child</div>\n <i className=\"child icon\"></i>\n <div className=\"menu\">\n <DropdownItem />\n </div>\n </div>\n )\n}", "function useDropdownToggle() {\n var _useContext = Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useContext\"])(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__[\"default\"]),\n show = _useContext.show,\n toggle = _useContext.toggle,\n setToggle = _useContext.setToggle;\n\n return [{\n ref: setToggle,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _useContext = Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useContext\"])(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__[\"default\"]),\n show = _useContext.show,\n toggle = _useContext.toggle,\n setToggle = _useContext.setToggle;\n\n return [{\n ref: setToggle,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}" ]
[ "0.7379139", "0.73551315", "0.7344111", "0.7344111", "0.731457", "0.7248382", "0.7141513", "0.7104771", "0.7096492", "0.70610046", "0.70362496", "0.7033354", "0.7033354", "0.6974389", "0.6948965", "0.6941215", "0.68353075", "0.68135256", "0.67828226", "0.67828226", "0.6773039", "0.6736971", "0.67327946", "0.670474", "0.6686178", "0.6663907", "0.665606", "0.6646749", "0.6640446", "0.6640446" ]
0.7876001
1
Wires up Dropdown toggle functinality, returning a set a props to attach to the element that functions as the dropdown toggle (generally a button).
function useDropdownToggle() { var _useContext = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__["default"]), show = _useContext.show, toggle = _useContext.toggle, setToggle = _useContext.setToggle; return [{ ref: setToggle, 'aria-haspopup': true, 'aria-expanded': !!show }, { show: show, toggle: toggle }]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function useDropdownToggle() {\n var _ref = Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useContext\"])(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__[\"default\"]) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n return [{\n ref: setToggle || noop,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _ref = Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useContext\"])(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__[\"default\"]) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n return [{\n ref: setToggle || noop,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _ref = react.useContext(DropdownContext) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop$2 : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = react.useCallback(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop$2,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _ref = (0,react__WEBPACK_IMPORTED_MODULE_1__.useContext)(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__.default) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = (0,react__WEBPACK_IMPORTED_MODULE_1__.useCallback)(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function useDropdownToggle() {\n var _ref = (0,react__WEBPACK_IMPORTED_MODULE_1__.useContext)(_DropdownContext__WEBPACK_IMPORTED_MODULE_2__.default) || {},\n _ref$show = _ref.show,\n show = _ref$show === void 0 ? false : _ref$show,\n _ref$toggle = _ref.toggle,\n toggle = _ref$toggle === void 0 ? noop : _ref$toggle,\n setToggle = _ref.setToggle;\n\n var handleClick = (0,react__WEBPACK_IMPORTED_MODULE_1__.useCallback)(function (e) {\n toggle(!show, e);\n }, [show, toggle]);\n return [{\n ref: setToggle || noop,\n onClick: handleClick,\n 'aria-haspopup': true,\n 'aria-expanded': !!show\n }, {\n show: show,\n toggle: toggle\n }];\n}", "function setToggleButton (e, checked) {\r\n\tlet toggleButton = e.parentElement.querySelector(\"button.upDownButton\");\r\n\tlet dropList = e.parentElement.querySelector(\"div.dropList\");\r\n\tlet dropListItems = dropList.children;\r\n\r\n\tlet n = countShowing(dropList);\r\n\tif (checked) {\r\n\t\tif (n == 0) {\r\n\t\t\ttoggleButton.checked = true; \r\n\t\t\ttoggleButton.classList.remove(\"upAndFilter\")\r\n\t\t\ttoggleButton.classList.add(\"up\");\r\n\t\t\ttoggleButton.disabled = false;\r\n\t\t\ttoggleButton.setAttribute(\"title\", \"Hide all\");\r\n\t\t} else {\r\n\t\t\ttoggleButton.checked = true; \r\n\t\t\ttoggleButton.classList.remove(\"up\");\r\n\t\t\ttoggleButton.classList.add(\"upAndFilter\")\r\n\t\t\ttoggleButton.disabled = false;\r\n\t\t\ttoggleButton.setAttribute(\"title\", \"Filter\");\r\n\t\t}\t\t\t\r\n\t} else {\r\n\t\tif (n == dropListItems.length) {\r\n\t\t\ttoggleButton.checked = true; \r\n\t\t\ttoggleButton.classList.remove(\"up\", \"upAndFilter\");\r\n\t\t\ttoggleButton.disabled = true;\r\n\t\t\ttoggleButton.removeAttribute(\"title\");\r\n\t\t} else {\r\n\t\t\ttoggleButton.checked = false; \r\n\t\t\ttoggleButton.classList.remove(\"up\", \"upAndFilter\");\r\n\t\t\ttoggleButton.disabled = false;\r\n\t\t\ttoggleButton.setAttribute(\"title\", \"Show all\");\r\n\t\t}\r\n\t}\r\n}", "toggle() {\n this.setState({\n dropdownOpen: !this.state.dropdownOpen\n });\n }", "toggle(event) {\n this.setState({\n dropdownOpen: !this.state.dropdownOpen\n });\n }", "toggleForDropDown() {\n this.setState(prevState => ({\n dropdownOpen: !prevState.dropdownOpen\n }));\n }", "render() {\n return (\n <div className=\"filter-list\">\n <ButtonToolbar className=\"buttons\">\n <DropdownButton title=\"Class\" id=\"dropdown-basic-button-1\" size=\"lg\" className=\"dropdown1\">\n <Dropdown.Item eventKey=\"All\" onSelect={this.onSelectFilterClass}>\n All\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Assassin\" onSelect={this.onSelectFilterClass}>\n Assassin\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Guardian\" onSelect={this.onSelectFilterClass}>\n Guardian\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Hunter\" onSelect={this.onSelectFilterClass}>\n Hunter\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Mage\" onSelect={this.onSelectFilterClass}>\n Mage\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Warrior\" onSelect={this.onSelectFilterClass}>\n Warrior\n </Dropdown.Item>\n </DropdownButton>\n <DropdownButton title=\"Type\" id=\"dropdown-basic-button-2\" size=\"lg\" className=\"dropdown2\">\n <Dropdown.Item eventKey=\"All\" onSelect={this.onSelectFilterType}>\n All\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Magical\" onSelect={this.onSelectFilterType}>\n Magical\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Physical\" onSelect={this.onSelectFilterType}>\n Physical\n </Dropdown.Item>\n </DropdownButton>\n <DropdownButton title=\"Sort\" id=\"dropdown-basic-button-3\" size=\"lg\" className=\"dropdown3\">\n <Dropdown.Item eventKey=\"none\" onSelect={this.sortByNone}>\n None\n </Dropdown.Item>\n <Dropdown.Item eventKey=\"Worshippers\" onSelect={this.sortByWorshippers}>\n Worshipers\n </Dropdown.Item>\n </DropdownButton>\n </ButtonToolbar>\n <div className=\"filter-names\">\n <div className=\"class-filter\">\n Class Selected: {this.state.class} \n </div>\n <div className=\"type-filter\">\n Type Selected: {this.state.type}\n </div>\n <div className=\"sort-filter\">\n Sorting Method: {this.state.sort}\n </div>\n </div>\n <Search items={this.props.items.filter(this.filterTypeAndClass)} />\n </div>\n );\n }", "onToggle(d) {\n const { onChangeToggle, identifier } = this.props;\n if (onChangeToggle) {\n onChangeToggle(d[identifier]);\n }\n }", "function DropdownToggle(_ref2) {\n var children = _ref2.children;\n\n var _useDropdownToggle = useDropdownToggle(),\n props = _useDropdownToggle[0],\n _useDropdownToggle$ = _useDropdownToggle[1],\n show = _useDropdownToggle$.show,\n toggle = _useDropdownToggle$.toggle;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, children({\n show: show,\n toggle: toggle,\n props: props\n }));\n}", "function DropdownToggle(_ref2) {\n var children = _ref2.children;\n\n var _useDropdownToggle = useDropdownToggle(),\n props = _useDropdownToggle[0],\n _useDropdownToggle$ = _useDropdownToggle[1],\n show = _useDropdownToggle$.show,\n toggle = _useDropdownToggle$.toggle;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, children({\n show: show,\n toggle: toggle,\n props: props\n }));\n}", "function Dropdown(_ref) {\n var drop = _ref.drop,\n alignEnd = _ref.alignEnd,\n defaultShow = _ref.defaultShow,\n rawShow = _ref.show,\n rawOnToggle = _ref.onToggle,\n itemSelector = _ref.itemSelector,\n focusFirstItemOnShow = _ref.focusFirstItemOnShow,\n children = _ref.children;\n var forceUpdate = Object(_restart_hooks_useForceUpdate__WEBPACK_IMPORTED_MODULE_7__[\"default\"])();\n\n var _useUncontrolled = Object(uncontrollable__WEBPACK_IMPORTED_MODULE_4__[\"useUncontrolled\"])({\n defaultShow: defaultShow,\n show: rawShow,\n onToggle: rawOnToggle\n }, {\n show: 'onToggle'\n }),\n show = _useUncontrolled.show,\n onToggle = _useUncontrolled.onToggle;\n\n var _useCallbackRef = Object(_restart_hooks_useCallbackRef__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(),\n toggleElement = _useCallbackRef[0],\n setToggle = _useCallbackRef[1]; // We use normal refs instead of useCallbackRef in order to populate the\n // the value as quickly as possible, otherwise the effect to focus the element\n // may run before the state value is set\n\n\n var menuRef = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])();\n var menuElement = menuRef.current;\n var setMenu = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useCallback\"])(function (ref) {\n menuRef.current = ref; // ensure that a menu set triggers an update for consumers\n\n forceUpdate();\n }, [forceUpdate]);\n var lastShow = Object(_restart_hooks_usePrevious__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(show);\n var lastSourceEvent = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])(null);\n var focusInDropdown = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])(false);\n var toggle = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useCallback\"])(function (event) {\n onToggle(!show, event);\n }, [onToggle, show]);\n var context = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useMemo\"])(function () {\n return {\n toggle: toggle,\n drop: drop,\n show: show,\n alignEnd: alignEnd,\n menuElement: menuElement,\n toggleElement: toggleElement,\n setMenu: setMenu,\n setToggle: setToggle\n };\n }, [toggle, drop, show, alignEnd, menuElement, toggleElement, setMenu, setToggle]);\n\n if (menuElement && lastShow && !show) {\n focusInDropdown.current = menuElement.contains(document.activeElement);\n }\n\n var focusToggle = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(function () {\n if (toggleElement && toggleElement.focus) {\n toggleElement.focus();\n }\n });\n var maybeFocusFirst = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(function () {\n var type = lastSourceEvent.current;\n var focusType = focusFirstItemOnShow;\n\n if (focusType == null) {\n focusType = menuRef.current && Object(dom_helpers_matches__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(menuRef.current, '[role=menu]') ? 'keyboard' : false;\n }\n\n if (focusType === false || focusType === 'keyboard' && !/^key.+$/.test(type)) {\n return;\n }\n\n var first = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(menuRef.current, itemSelector)[0];\n if (first && first.focus) first.focus();\n });\n Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useEffect\"])(function () {\n if (show) maybeFocusFirst();else if (focusInDropdown.current) {\n focusInDropdown.current = false;\n focusToggle();\n } // only `show` should be changing\n }, [show, focusInDropdown, focusToggle, maybeFocusFirst]);\n Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useEffect\"])(function () {\n lastSourceEvent.current = null;\n });\n\n var getNextFocusedChild = function getNextFocusedChild(current, offset) {\n if (!menuRef.current) return null;\n var items = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(menuRef.current, itemSelector);\n var index = items.indexOf(current) + offset;\n index = Math.max(0, Math.min(index, items.length));\n return items[index];\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n var key = event.key,\n target = event.target; // Second only to https://github.com/twbs/bootstrap/blob/8cfbf6933b8a0146ac3fbc369f19e520bd1ebdac/js/src/dropdown.js#L400\n // in inscrutability\n\n var isInput = /input|textarea/i.test(target.tagName);\n\n if (isInput && (key === ' ' || key !== 'Escape' && menuRef.current && menuRef.current.contains(target))) {\n return;\n }\n\n lastSourceEvent.current = event.type;\n\n switch (key) {\n case 'ArrowUp':\n {\n var next = getNextFocusedChild(target, -1);\n if (next && next.focus) next.focus();\n event.preventDefault();\n return;\n }\n\n case 'ArrowDown':\n event.preventDefault();\n\n if (!show) {\n toggle(event);\n } else {\n var _next = getNextFocusedChild(target, 1);\n\n if (_next && _next.focus) _next.focus();\n }\n\n return;\n\n case 'Escape':\n case 'Tab':\n onToggle(false, event);\n break;\n\n default:\n }\n };\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_DropdownContext__WEBPACK_IMPORTED_MODULE_9__[\"default\"].Provider, {\n value: context\n }, children({\n props: {\n onKeyDown: handleKeyDown\n }\n }));\n}", "function Dropdown(_ref) {\n var drop = _ref.drop,\n alignEnd = _ref.alignEnd,\n defaultShow = _ref.defaultShow,\n rawShow = _ref.show,\n rawOnToggle = _ref.onToggle,\n itemSelector = _ref.itemSelector,\n focusFirstItemOnShow = _ref.focusFirstItemOnShow,\n children = _ref.children;\n var forceUpdate = Object(_restart_hooks_useForceUpdate__WEBPACK_IMPORTED_MODULE_7__[\"default\"])();\n\n var _useUncontrolled = Object(uncontrollable__WEBPACK_IMPORTED_MODULE_4__[\"useUncontrolled\"])({\n defaultShow: defaultShow,\n show: rawShow,\n onToggle: rawOnToggle\n }, {\n show: 'onToggle'\n }),\n show = _useUncontrolled.show,\n onToggle = _useUncontrolled.onToggle;\n\n var _useCallbackRef = Object(_restart_hooks_useCallbackRef__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(),\n toggleElement = _useCallbackRef[0],\n setToggle = _useCallbackRef[1]; // We use normal refs instead of useCallbackRef in order to populate the\n // the value as quickly as possible, otherwise the effect to focus the element\n // may run before the state value is set\n\n\n var menuRef = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])();\n var menuElement = menuRef.current;\n var setMenu = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useCallback\"])(function (ref) {\n menuRef.current = ref; // ensure that a menu set triggers an update for consumers\n\n forceUpdate();\n }, [forceUpdate]);\n var lastShow = Object(_restart_hooks_usePrevious__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(show);\n var lastSourceEvent = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])(null);\n var focusInDropdown = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useRef\"])(false);\n var toggle = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useCallback\"])(function (event) {\n onToggle(!show, event);\n }, [onToggle, show]);\n var context = Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useMemo\"])(function () {\n return {\n toggle: toggle,\n drop: drop,\n show: show,\n alignEnd: alignEnd,\n menuElement: menuElement,\n toggleElement: toggleElement,\n setMenu: setMenu,\n setToggle: setToggle\n };\n }, [toggle, drop, show, alignEnd, menuElement, toggleElement, setMenu, setToggle]);\n\n if (menuElement && lastShow && !show) {\n focusInDropdown.current = menuElement.contains(document.activeElement);\n }\n\n var focusToggle = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(function () {\n if (toggleElement && toggleElement.focus) {\n toggleElement.focus();\n }\n });\n var maybeFocusFirst = Object(_restart_hooks_useEventCallback__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(function () {\n var type = lastSourceEvent.current;\n var focusType = focusFirstItemOnShow;\n\n if (focusType == null) {\n focusType = menuRef.current && Object(dom_helpers_matches__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(menuRef.current, '[role=menu]') ? 'keyboard' : false;\n }\n\n if (focusType === false || focusType === 'keyboard' && !/^key.+$/.test(type)) {\n return;\n }\n\n var first = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(menuRef.current, itemSelector)[0];\n if (first && first.focus) first.focus();\n });\n Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useEffect\"])(function () {\n if (show) maybeFocusFirst();else if (focusInDropdown.current) {\n focusInDropdown.current = false;\n focusToggle();\n } // only `show` should be changing\n }, [show, focusInDropdown, focusToggle, maybeFocusFirst]);\n Object(react__WEBPACK_IMPORTED_MODULE_2__[\"useEffect\"])(function () {\n lastSourceEvent.current = null;\n });\n\n var getNextFocusedChild = function getNextFocusedChild(current, offset) {\n if (!menuRef.current) return null;\n var items = Object(dom_helpers_querySelectorAll__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(menuRef.current, itemSelector);\n var index = items.indexOf(current) + offset;\n index = Math.max(0, Math.min(index, items.length));\n return items[index];\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n var key = event.key,\n target = event.target; // Second only to https://github.com/twbs/bootstrap/blob/8cfbf6933b8a0146ac3fbc369f19e520bd1ebdac/js/src/dropdown.js#L400\n // in inscrutability\n\n var isInput = /input|textarea/i.test(target.tagName);\n\n if (isInput && (key === ' ' || key !== 'Escape' && menuRef.current && menuRef.current.contains(target))) {\n return;\n }\n\n lastSourceEvent.current = event.type;\n\n switch (key) {\n case 'ArrowUp':\n {\n var next = getNextFocusedChild(target, -1);\n if (next && next.focus) next.focus();\n event.preventDefault();\n return;\n }\n\n case 'ArrowDown':\n event.preventDefault();\n\n if (!show) {\n toggle(event);\n } else {\n var _next = getNextFocusedChild(target, 1);\n\n if (_next && _next.focus) _next.focus();\n }\n\n return;\n\n case 'Escape':\n case 'Tab':\n onToggle(false, event);\n break;\n\n default:\n }\n };\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_DropdownContext__WEBPACK_IMPORTED_MODULE_9__[\"default\"].Provider, {\n value: context\n }, children({\n props: {\n onKeyDown: handleKeyDown\n }\n }));\n}", "toggleDropdown() {\n this.setState(prevState => ({\n dropdownOpen: !prevState.dropdownOpen\n }));\n }", "toggleDropdown() {\n this.setState(prevState => ({\n dropdownOpen: !prevState.dropdownOpen\n }));\n }", "onToggleDropdown() {\n if (this.containerDropdownElement.className.indexOf('show') === -1) {\n this.containerDropdownElement.className += ' show';\n } else {\n const className = this.containerDropdownElement.className.replace(' show', '');\n\n this.containerDropdownElement.className = className;\n }\n }", "onToggleDropdown() {\n\t\tif(this.containerDropdownElement.className.indexOf(\"show\") == -1) {\n\t\t\tthis.containerDropdownElement.className += \" show\";\n\t\t} else {\n\t\t\tthis.containerDropdownElement.className = this.containerDropdownElement.className.replace(\" show\", \"\");\n\t\t}\n\t}", "filterForm() {\n return <div className={'filter-form'}>\n <Toggle inputLabel={'Show me:'}\n leftLabel={'Changing sets'}\n leftValue={this.filterOptions.move}\n rightLabel={'All sets'}\n rightValue={this.filterOptions.all}\n value={this.filterOptions.all}\n onChange={this.showSets.bind(this)}\n />\n </div>;\n }", "function toggleDropdown() {\n if (document.querySelector(\".dropdown\") !== null) {\n let aDropdownButtonElements =\n document.querySelectorAll(\".dropdown__button\");\n /* let aDropdownListElements = document.querySelectorAll(\n \".dropdown-list-container\"\n ); */\n aDropdownButtonElements.forEach((eButton) => {\n eButton.addEventListener(\"click\", () => {\n //Reset all dialog boxes\n\n // aDropdownListElements.forEach((eList) => {\n // if (eButton.dataset.buttonid === eList.dataset.listid) {\n // eList.classList.toggle(\"dropdown-list-container--hidden\");\n // }\n // });\n\n //----------- REFACTORED VERSION ------------//\n document\n .querySelector(`[data-listid='${eButton.dataset.buttonid}']`)\n .classList.toggle(\"dropdown-list-container--hidden\");\n });\n });\n }\n}", "function toggleDropdown(){\n\n dropdownItems.classList.toggle('dropdownShow');\n dropdownPijltje.classList.toggle('draaiPijl')\n}", "function DropdownToggle(_ref2) {\n var children = _ref2.children;\n\n var _useDropdownToggle = useDropdownToggle(),\n props = _useDropdownToggle[0],\n meta = _useDropdownToggle[1];\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1__.createElement(react__WEBPACK_IMPORTED_MODULE_1__.Fragment, null, children(props, meta));\n}", "function DropdownToggle(_ref2) {\n var children = _ref2.children;\n\n var _useDropdownToggle = useDropdownToggle(),\n props = _useDropdownToggle[0],\n meta = _useDropdownToggle[1];\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_1__.createElement(react__WEBPACK_IMPORTED_MODULE_1__.Fragment, null, children(props, meta));\n}", "onToggleLanguagesDropdown() {\n $('#select-languages').on('click', function () {\n $(this).siblings('#dropdown-languages').toggleClass('show')\n });\n }", "static get properties() {\n return {\n 'buttonsDataSource': {\n value: [],\n type: 'array'\n },\n 'dropDownOpenMode': {\n allowedValues: ['none', 'dropDownButton', 'auto'],\n value: 'dropDownButton',\n type: 'string'\n }\n };\n }", "function setupButtons() {\n\t\n\td3.select(\"#bubbles-toolbar\")\n\t.selectAll(\"a\")\n\t.on(\"click\", function() {\n\n\t\td3.selectAll(\".dropdown-item\")\n\t\t.classed(\"active\", false);\n\n\t\tvar button = d3.select(this);\n\n\t\tbutton.classed(\"active\", true);\n\n\t\tvar buttonId = button.attr(\"id\");\n\n\t\tmyBubbleChart.toggleDisplay(buttonId);\n\n\t});\n}", "function DropdownSelect({ children, className, selectedValues }) {\n const [expanded, toggleExpanded] = useToggle()\n\n return (\n <OutsideClickHandler onOutsideClick={() => toggleExpanded(false)}>\n <div className=\"dropdown-select\">\n <button\n type=\"button\"\n className=\"select-input\"\n onClick={() => toggleExpanded()}\n >\n <p>{getLabel(selectedValues)}</p>\n </button>\n <div\n className={classnames(className, 'options', {\n 'is-active': expanded,\n })}\n >\n <div className=\"scroll-box\">{children}</div>\n </div>\n </div>\n </OutsideClickHandler>\n )\n}", "function myButton() {\r\n document.getElementById(\"mydropdown\").classList.toggle(\"show\");\r\n}", "function StateDropDown({ title, items = [], multiSelect = false }) {\n const [open, setOpen] = useState(false);\n const [selection, setSelection] = useState([]);\n const toggle = () => setOpen(!open);\n StateDropDown.handleClickOutside = () => setOpen(false);\n\n function handleOnClick(item) {\n if(!selection.some(current => current.value === item.value)) {\n if (!multiSelect) {\n setSelection([item]);\n } else if (multiSelect) {\n setSelection([...selection, item]);\n }\n } else {\n let selectionAferRemoval = selection;\n selectionAferRemoval = selectionAferRemoval.filter(\n current => current.value !== item.value\n );\n setSelection([...selectionAferRemoval])\n }\n }\n\n function isItemInSelection (item) {\n if (selection.some(current => current.value === item.value)) {\n return true;\n }\n return false;\n }\n\n return (\n <div tabIndex={0} \n role=\"button\" \n onKeyPress={() => toggle(!open)} \n onClick={() => toggle(!open)}\n >\n <div>\n <p className=\"btn btn-secondary dropdown-toggle\">{open ? 'Close' : 'Filter by location'}</p>\n </div>\n {open && (\n <ul className=\"scroll list-group\" >\n {items.map(item => (\n <li key = {item.value} className=\"list-group-item\">\n <button type=\"button\" className=\"btn-sm listItems\" onClick={() => handleOnClick(item)}>\n <span>{item.value}</span>\n <span>{isItemInSelection(item) && ' Selected'}</span>\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n );\n}" ]
[ "0.6736121", "0.6736121", "0.6667571", "0.6605897", "0.6605897", "0.6524257", "0.62852407", "0.62826455", "0.61889184", "0.60012704", "0.5964195", "0.5922878", "0.5922878", "0.5890954", "0.5890954", "0.58881706", "0.58881706", "0.58873236", "0.58767843", "0.586028", "0.5816522", "0.5811555", "0.5729104", "0.5729104", "0.5671458", "0.5671167", "0.56673247", "0.5654239", "0.5652222", "0.5625012" ]
0.68878376
1
Filters for the users choice
function filterUser(value) { const filterIndex = select.selectedIndex let filter = select.options[select.selectedIndex].text if (value.length >= 3) { filteredUsers = users.filter((user) => { if (user[filter].toLowerCase().includes(value.toLowerCase())) { return user[filter] } }) createCards(filteredUsers) } else if (value.length === 0) { createCards(users) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function filterUser(value) {\n switch (value) {\n case Constants.UserManagementDDLOptions[1]:\n GetAllUsersFromDB();\n break;\n case Constants.UserManagementDDLOptions[2]:\n GetActivatedUserList();\n break;\n case Constants.UserManagementDDLOptions[3]:\n GetDeactivatedUserList();\n break;\n case Constants.UserManagementDDLOptions[4]:\n GetRegisterdUserList();\n break;\n }\n //Keeping record of the filtered data from the first dropdown to use it in second dropdown(BPUs dropdown)\n $scope.Users = $scope.UserList;\n filterByBPU($scope.Users);\n }", "function filterInput(){\n AllUsers = document.getElementById(\"users\").getElementsByTagName(\"option\");\n filterValue=filter.value.toUpperCase();\n for(i=0;i < AllUsers.length; i++){\n if(AllUsers[i].innerHTML.toUpperCase().indexOf(filterValue) > -1 ){\n AllUsers[i].style.display=\"\";\n }\n else{\n AllUsers[i].style.display=\"none\";\n }\n } \n}", "function setFilter() {\n switch (target.value) {\n case 'person':\n addFilters('all', 'id', 'phone', 'email', 'hobby');\n toggelAdvancedbtn(\"person\");\n break;\n case 'company':\n addFilters('all', 'cvr', 'name', 'phone', 'email');\n toggelAdvancedbtn(\"company\");\n break;\n case 'city':\n addFilters('all', 'zip');\n toggelAdvancedbtn();\n break;\n case 'address':\n addFilters('all', 'zip');\n toggelAdvancedbtn();\n break;\n case 'phone':\n addFilters('all', 'number');\n toggelAdvancedbtn();\n break;\n case 'hobby':\n addFilters('all', 'name');\n toggelAdvancedbtn();\n }\n}", "filterOption(option, filter) {\n\n if (option.value === null) {\n // only show placeholder when not searching\n return filter === '';\n }\n\n const user = this.getAppUser(option.value);\n\n filter = filter.toLowerCase();\n\n return user.value === null ||\n user.email && user.email.toLowerCase().indexOf(filter) === 0 ||\n user.firstName && user.firstName.toLowerCase().indexOf(filter) === 0 ||\n user.lastName && user.lastName.toLowerCase().indexOf(filter) === 0 ||\n user.screenName && user.screenName.toLowerCase().indexOf(filter) === 0;\n }", "function filter() {\n let preFilter = [];\n let gender = selectG.value;\n let stat = selectS.value;\n let filteredChar = [];\n\n if (gender != \"Gender\") {\n filteredChar.push(\"gender\");\n if (filteredChar.length == 1) {\n limpiartodo();\n preFilter = filterGender(preFilter, gender, true);\n print(preFilter);\n }\n else {\n limpiartodo();\n preFilter = filterGender(preFilter, gender, false);\n print(preFilter);\n }\n }\n\n if (stat != \"Status\") {\n filteredChar.push(\"status\");\n if (filteredChar.length == 1) {\n limpiartodo();\n preFilter = filterStatus(preFilter, stat, true);\n print(preFilter);\n }\n else {\n limpiartodo();\n preFilter = filterStatus(preFilter, stat, false);\n print(preFilter);\n }\n }\n }", "function filterUsers()\n { \n if(currentState === \"online\" || currentState === \"offline\")\n {\n var mustBeOnline = currentState === \"online\" ? true : false;\n\n users = users.filter(function(item){\n return (item.streamInfo.stream !== null) === mustBeOnline;\n });\n }\n\n fillResultBox();\n }", "function filterByUser(param) {\n self.selectionModel.allMatter = param;\n if (param == 1) {\n self.viewModel.filters.for = \"mymatter\";\n } else {\n self.viewModel.filters.for = \"allmatter\";\n }\n self.viewModel.filters\n getMatterList(undefined, 'calDays');\n }", "function setFilterAction(){\n\t$(\".data-filter\").keyup(function(){\n\t\tvar options=$(\"#\"+$(this).data(\"filter\") + \" option\");\n\t\tvar filterValue=$(this).val().toLowerCase();\n\t\toptions.each(function(){\n\t\t\tif($(this).text().toLowerCase().includes(filterValue)) $(this).show();\n\t\t\telse $(this).hide();\n\t\t})\n\t});\n}", "function filterHandler() {\n var selectedVal = filterOptions.value;\n\n if (selectedVal === \"0\") {\n render(contacts);\n } else {\n render(filterByCity(selectedVal));\n }\n}", "function employeeFilter() {\n inquirer\n .prompt(\n {\n name: 'action',\n type: 'list',\n message: 'What would you like to do?',\n choices: [\n 'View all Employees',\n 'View Employees by Manager',\n 'View Employee by Department',\n 'Go Back'\n ]\n }\n ).then(answer => {\n switch (answer.action) {\n case 'View all Employees':\n employeeSearch();\n break;\n\n case 'View Employees by Manager':\n filterByManager();\n break;\n\n case 'View Employee by Department':\n filterByDept();\n break;\n\n case 'Go Back':\n employeeOptions();\n break;\n }\n })\n}", "filterUsers() {\n const search = this.state.search.toLowerCase();\n \n return this.state.users.filter(user => {\n return (\n user.firstName.toLowerCase().includes(search) ||\n user.lastName.toLowerCase().includes(search)\n )\n })\n }", "function filterUsers(req, res, next) {\n if (filters.indexOf(req.params.filter)<0) {\n next();\n } else {\n switch (req.params.filter) {\n case \"tweets\":\n getMoreTweets(req, res, next);\n break;\n case \"last\":\n getLastUsers(req, res, next);\n break;\n }\n }\n }", "async filterUsers(event, filterBy='') {\n event.preventDefault();\n if(filterBy === 'role') {\n await this.setState({ filterRole: event.target.value });\n }\n const { search, filterRole } = this.state;\n await this.props.list(1, search, filterRole);\n }", "function searchApplicant( event ){\n event.preventDefault();\n let selectItems = $skillsFilter.selectedOptions;\n let busca;\n \n Array.prototype.forEach.call( selectItems, function(item){\n arrFilter.push(item.value);\n });\n\n if ($salaryFilter.value != '' && arrFilter.length != 0){\n busca = searchBoth();\n }\n\n if ($salaryFilter.value == '' && arrFilter.length != 0)\n busca = searchForSkills();\n\n if ($salaryFilter.value != '' && arrFilter.length == 0)\n busca = searchForSalary();\n\n if ($salaryFilter.value == '' && arrFilter.length == 0 )\n busca = candidates;\n\n showInModal(busca);\n $modal.setAttribute('class', \"modal collapse show\");\n $salaryFilter.value = \"\";\n arrFilter = [];\n }", "function filter(req, res, next){\n db.collection('datingapp').find({\n // This is where we find the userId and the gender & sexuality they want to filter on and we filter the rest of the people with the .find\n $and: [ \n {firstName:{$ne: req.session.userId.firstName}},\n {gender: req.session.userId.filter['gender']}, \n {sexuality: req.session.userId.filter['sexuality']}\n ]}).toArray(done)\n function done(err, data){\n if (err){\n next(err)\n } else {\n // \n res.render('index.ejs', {data: data})\n }\n }\n}", "function filterBy() {\n\n // Selecting an option form dropdown filter by list\n let type = document.getElementById('typeSelect').value;\n\n // Comparing the value selected with the types of cards.\n if (type === 'ICPC') {\n typeICPC = contestsList.filter(contest => contest.type == 'ICPC');\n differentContests(typeICPC);\n } else if (type === 'CF') {\n typeCF = contestsList.filter(contest => contest.type == 'CF');\n differentContests(typeCF);\n }\n}", "function filterUser(li, ci) {\n debug('Filtering ' + ci.name + ' Rank: ' + ci.numeric_rank + ' State: ' + ci.state + ' Desc: ' + ci.description);\n if (opt_showcaymans && ci.state != 'Traveling') {\n debug('Filtered - Caymans only, but either not returning or not Caymans');\n debug('State = ' + ci.state);\n return true;\n }\n\n let isHosped = isInHosp(li);\n let infed = isFedded(li);\n let fallen = isFallen(li);\n let travelling = isTravelling(li);\n if (isHosped || infed || travelling) {\n log('Hosp: ' + isHosped + ' Fedded: ' + infed + ' IsTravelling: ' + travelling);\n log('**** Shouldn`t be here? *****');\n }\n\n switch (ci.state) {\n case 'Hospital':\n if (opt_hidehosp) {\n if (isHosped) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - in hosp.');\n return true;\n }\n break;\n case 'Federal':\n if (opt_hidefedded) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fedded.');\n return true;\n }\n break;\n case 'Fallen':\n if (opt_hidefallen) {\n if (infed) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - fallen.');\n return true;\n }\n break;\n case 'Abroad':\n case 'Traveling':\n if (opt_hidetravel) {\n if (travelling) log('**** Shouldn`t be here? *****');\n debug('***** Filtered - traveling.');\n return true;\n }\n if (opt_showcaymans) {\n if (ci.description.indexOf('Cayman') != -1) {\n if (ci.description.indexOf('Returning') != -1) {\n debug('******Returning from Caymans! Not filtered!');\n return false;\n }\n }\n debug('Filtered - caymans only, but either not returning or not Caymans');\n return true;\n }\n break;\n default:\n return false;\n }\n return false;\n }", "function filterResults(event) {\n const filter = event.target.value;\n if (filter === \"baking\"){\n const baking = products.filter(result => (result.family.baking === true));\n setFilteredProducts(baking);\n } else if (filter === \"grilling\"){\n const grilling = products.filter(result => (result.family.grilling === true));\n setFilteredProducts(grilling);\n } else if (filter === \"seasoning\"){\n const seasoning = products.filter(result => (result.family.seasoning === true));\n setFilteredProducts(seasoning);\n } else if (filter === \"extract\"){\n const extract = products.filter(result => (result.family.extract === true));\n setFilteredProducts(extract);\n } else if (filter === \"teas\"){\n const teas = products.filter(result => (result.family.teas === true));\n setFilteredProducts(teas);\n } else {\n setFilteredProducts(products);\n }\n}", "function handleFilters() {\n console.log(this.value);\n var index = filters.indexOf(this.value);\n if (index === -1) filters.push(this.value);\n else filters.splice(index, 1);\n console.log(filters);\n renderApplicants(Object.values(allApplicants[currJobIndex] || {}), currJobIndex, searchVal, filters);\n}", "function set_filters() {\n let filter = {\n post_type: 'auto-in-vendita',\n filters: {\n /* tipologia : $('input[name=\"condition\"]:checked').val(), */\n marca: brandInput.val(),\n modello: modelInput.val(),\n maxPrice: maxPriceInput.val(),\n km: kmInput.val(),\n anno: yearInput.val(),\n alimentazione: fuelInput.val(),\n cambio: transmissioninput.val(),\n novice: noviceInput.is(':checked') == true ? true : '',\n }\n }\n get_search_results_count(filter);\n }", "function filterNames () {\n\n // Declare variable to hold value of filtered names\n let filteredNames;\n\n // If all...\n if (isAllShowing===true) {\n filteredNames = myNames.map((name) => {\n name.is_visible=true\n return name\n });\n setMyNames(filteredNames);\n }\n\n // If first...\n else if (isFirstShowing===true) {\n filteredNames = myNames.map((name) => {\n if (name.type==='first') {\n name.is_visible=true\n return name\n }\n else {\n name.is_visible=false\n return name;\n }\n });\n setMyNames(filteredNames);\n }\n\n // If middle...\n else if (isMiddleShowing===true) {\n filteredNames = myNames.map((name) => {\n if (name.type==='middle') {\n name.is_visible=true\n return name\n }\n else {\n name.is_visible=false\n return name;\n }\n });\n setMyNames(filteredNames);\n }\n\n // If full...(implied as all other types are specified in above conditionals)\n else {\n filteredNames = myNames.map((name) => {\n if (name.type==='full') {\n name.is_visible=true\n return name\n }\n else {\n name.is_visible=false\n return name;\n }\n });\n setMyNames(filteredNames);\n }\n }", "function filterUsers({ username, name }) {\n return username.toLowerCase().startsWith(query.toLowerCase()) || name.toLowerCase().startsWith(query.toLowerCase());\n }", "_filter(value) {\n //convert text to lower case\n const filterValue = value.toLowerCase();\n //get matching products\n return this.products.filter(option => option.toLowerCase().includes(filterValue));\n }", "function filterItem (){\n let filter = valorfilter();\n estructuraFilter = \"\";\n if (filter == \"Prime\"){\n for (propiedad of carrito) {\n if (propiedad.premium) imprimirItemFilter(propiedad);\n }\n noItenCarrito();\n } else if (filter == \"Todos\") {\n estructuraPrincipalCarrito();\n } \n}", "function candidateFilter(candidate, types) {\n var h = document.getElementById(\"filterState\");\n var acepted = false;\n if (types.length <= 0 && (candidate.state == h.value || h.value == \"-All-\" || !h.value)) {\n acepted = true;\n } else if (types.indexOf(candidate.party) >= 0 && (candidate.state == h.value || h.value == \"-All-\")) {\n acepted = true;\n }\n return acepted;\n }", "function filterGenres() {\r\n var genderMovieSelect = $(\"#genders-movie select\").val()\r\n if (genderMovieSelect != \"all\") {\r\n $(\"#movie .template\").each(function() {\r\n var gid = $(this).attr(\"data-generi\").split(',');\r\n if (gid.includes(genderMovieSelect)) $(this).show()\r\n else $(this).hide()\r\n });\r\n } else {\r\n $(\"#movie .template\").show()\r\n }\r\n var genderTVSelect = $(\"#genders-tv select\").val()\r\n if (genderTVSelect != \"all\") {\r\n $(\"#tvshow .template\").each(function() {\r\n var gid = $(this).attr(\"data-generi\").split(',');\r\n if (gid.includes(genderMovieSelect)) $(this).show()\r\n else $(this).hide()\r\n });\r\n } else {\r\n $(\"#tvshow .template\").show()\r\n }\r\n }", "function filterTypeSelection(e){\n if(e.target.value === ''){\n getInventory()\n } else {\n axios.get(`/inventory/search/dept?dept=${e.target.value}`)\n .then(res => setItems(res.data))\n .catch(err => alert(err))\n }\n }", "filteredMembers() {\n return this.members.filter(member => {\n let filtro1 =\n this.checkboxes.includes(member.party) ||\n this.checkboxes.length == 0;\n let filtro2 =\n this.stateSelected == member.state ||\n this.stateSelected == \"all\";\n return filtro1 && filtro2;\n });\n }", "function filterByCheckbox(){\r\n\tlet checks = document.getElementsByClassName(\"party\");\r\n\t// Limpio tabla\r\n\tdocument.querySelector(\"tbody\").innerHTML = '';\r\n\t// Guardo valor actual del select\r\n\tlet filterValue = document.querySelector(\"select\").value;\r\n\r\n\tfor (let i = 0; i<checks.length; i++){\r\n\t\tif (checks[i].checked){\r\n\t\t\tmembers.filter(e => checks[i].value == e.party && (filterValue == e.state || filterValue == 'none')).forEach(members =>{\r\n\t\t\tlet full_name = members.last_name + ' ' + members.first_name + ' ' + (members.middle_name ? members.middle_name : '');\r\n\t\t\tdocument.querySelector(\"tbody\").innerHTML += '<tr><td>' + (members.url != '' ? '<a href= \"' + members.url + '\" >' + full_name + '</a>' : full_name) + '</td><td>' + members.party + '</td><td>' + members.state + '</td><td>' + members.seniority + '</td><td>' + members.votes_with_party_pct + '%</td></tr>';\r\n\t\t})};\r\n\t}\r\n}", "function filterByUserId(userId) {\n\t// Remove all hide classes to undo any current filtering\n\t$(\".list-card\").removeClass(\"hide\");\n\n\tif(!$.isEmptyObject(userId)) {\n\t\t// Filter all cards that are not assigned to the current user\n\t\t$(\".list-card:not(:has('.js-member-on-card-menu[data-idmem=\" + userId + \"]'))\").addClass(\"hide\");\n\t}\n}" ]
[ "0.72708374", "0.679569", "0.6711983", "0.6538668", "0.649803", "0.64871246", "0.64749736", "0.6357838", "0.63390577", "0.6314583", "0.627644", "0.6237066", "0.6229025", "0.61880636", "0.61710256", "0.61697626", "0.6146438", "0.61458665", "0.61189294", "0.6091811", "0.6090958", "0.60877013", "0.6055829", "0.60427874", "0.603547", "0.60250676", "0.6016439", "0.6016207", "0.6009283", "0.59888905" ]
0.72810113
0
var rot = getDegreeElementById(squarel);
function getDegreeElementById(squarel) { var element = document.getElementById('squarel'); var style = window.getComputedStyle(element, null); // получаем значение стилей var valueStyle = style.getPropertyValue("-webkit-transform") || style.getPropertyValue("-moz-transform") || style.getPropertyValue("-ms-transform") || style.getPropertyValue("-o-transform") || style.getPropertyValue("transform"); // если стилей нет, то угол 0 градусов if (valueStyle == 'none') return 0; // разбираем полученное значение console.log(valueStyle); var values = valueStyle.split('(')[1]; values = values.split(')')[0]; values = values.split(','); // получаем синус и косинус var cos = values[0]; var sin = values[1]; // вычисляем угол var degree = Math.round(Math.asin(sin) * (180 / Math.PI)); if (cos < 0) { addDegree = 90 - Math.round(Math.asin(sin) * (180 / Math.PI)); degree = 90 + addDegree; } if (degree < 0) { degree = 360 + degree; } return degree; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function rotateDeg(wise){\n\tvar outer = document.getElementById('inner'),\n inner = document.getElementById('mainPhoto'),\n rotator = setRotator(inner);\n\n\tif(wise == 'clock'){\n\t\tdegrees += 90;\n\t} else{\n\t\tdegrees -= 90;\n\t}\n\n\n if (degrees >= 360) {\n degrees = 0;\n }\n\n rotator.rotate(degrees);\n\t\n}", "function rotate(id, rotation)\n{\n var divObj = $(\"#\" + id);\n if (divObj.length !== 0) {\n if (undefined === rotation)\n {\n rotation = 0;\n }\n var degree = parseFloat(rotation);\n updateRotateCss(divObj, degree);\n // save the degree.\n divObj.attr(\"degree\", degree);\n }\n}", "function getDegree(s, row, col) {\n var i;\n var j;\n var degree = 0;\n //check column\n for (i = 0; i < 9; i++) {\n if (i == row) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+i+col).value);\n if (!value) {\n degree++;\n }\n }\n //check row\n for (j = 0; j < 9; j++) {\n if (j == col) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+row+j).value);\n if (!value) {\n degree++;\n }\n }\n //check square\n var i_init = (Math.floor(row/3))*3;\n var j_init = (Math.floor(col/3))*3;\n for (i = i_init; i < i_init+3; i++) {\n for (j = j_init; j < j_init+3; j++) {\n if (i == row || j == col) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+i+j).value);\n if (!value) {\n degree++;\n }\n }\n }\n return degree;\n}", "function getCameraWorldRotation() {\n return document.getElementById('cameraWrapper').getAttribute('rotation');\n}", "function radiansToDegree(r){\n return r * 180 / Math.PI;\n}", "setRotate(angle, x, y, z){\n let e, s, c, len, rlen, nc, xy, yz, zx, xs, ys, zs;\n\n angle = Math.PI * angle / 180;\n e = this.elements;\n\n s = Math.sin(angle);\n c = Math.cos(angle);\n\n if (0 !== x && 0 === y && 0 === z) {\n // Rotation around X axis\n if (x < 0) {\n s = -s;\n }\n e[0] = 1; e[4] = 0; e[ 8] = 0; e[12] = 0;\n e[1] = 0; e[5] = c; e[ 9] =-s; e[13] = 0;\n e[2] = 0; e[6] = s; e[10] = c; e[14] = 0;\n e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;\n } else if (0 === x && 0 !== y && 0 === z) {\n // Rotation around Y axis\n if (y < 0) {\n s = -s;\n }\n e[0] = c; e[4] = 0; e[ 8] = s; e[12] = 0;\n e[1] = 0; e[5] = 1; e[ 9] = 0; e[13] = 0;\n e[2] =-s; e[6] = 0; e[10] = c; e[14] = 0;\n e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;\n } else if (0 === x && 0 === y && 0 !== z) {\n // Rotation around Z axis\n if (z < 0) {\n s = -s;\n }\n e[0] = c; e[4] =-s; e[ 8] = 0; e[12] = 0;\n e[1] = s; e[5] = c; e[ 9] = 0; e[13] = 0;\n e[2] = 0; e[6] = 0; e[10] = 1; e[14] = 0;\n e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;\n } else {\n // Rotation around another axis\n len = Math.sqrt(x*x + y*y + z*z);\n if (len !== 1) {\n rlen = 1 / len;\n x *= rlen;\n y *= rlen;\n z *= rlen;\n }\n nc = 1 - c;\n xy = x * y;\n yz = y * z;\n zx = z * x;\n xs = x * s;\n ys = y * s;\n zs = z * s;\n\n e[ 0] = x*x*nc + c;\n e[ 1] = xy *nc + zs;\n e[ 2] = zx *nc - ys;\n e[ 3] = 0;\n\n e[ 4] = xy *nc - zs;\n e[ 5] = y*y*nc + c;\n e[ 6] = yz *nc + xs;\n e[ 7] = 0;\n\n e[ 8] = zx *nc + ys;\n e[ 9] = yz *nc - xs;\n e[10] = z*z*nc + c;\n e[11] = 0;\n\n e[12] = 0;\n e[13] = 0;\n e[14] = 0;\n e[15] = 1;\n }\n\n return this;\n }", "function rotateHand(id, angle) {\n document.getElementById(id).style.transform = \"rotate(\" + angle + \"deg)\";\n}", "function toradians(deg)\n{\n return deg * Math.PI / 180.0;\n}", "get wristRotationDegree() { return this._wristRotation * 180.0 / Math.PI; }", "function rotationDegrees(matrix){\n\t\t\t\tvar matrix = elem.css(\"-webkit-transform\") ||\n\t\t\t\tthis.css(\"-moz-transform\") ||\n\t\t\t\tthis.css(\"-ms-transform\") ||\n\t\t\t\tthis.css(\"-o-transform\") ||\n\t\t\t\tthis.css(\"transform\");\n\t\t\t\tif(typeof matrix === 'string' && matrix !== 'none') {\n\t\t\t\tvar values = matrix.split('(')[1].split(')')[0].split(',');\n\t\t\t\tvar a = values[0];\n\t\t\t\tvar b = values[1];\n\t\t\t\tvar angle = Math.round(Math.atan2(b, a) * (180/Math.PI));\n\t\t\t\t} else { var angle = 0; }\n\t\t\t\treturn angle;\n\t\t\t}", "function getRotationDegrees(obj) {\n\t\tvar matrix = obj.css(\"-webkit-transform\") ||\n\t\tobj.css(\"-moz-transform\") ||\n\t\tobj.css(\"-ms-transform\") ||\n\t\tobj.css(\"-o-transform\") ||\n\t\tobj.css(\"transform\");\n\t\tif(matrix !== 'none') {\n\t\t\tvar values = matrix.split('(')[1].split(')')[0].split(',');\n\t\t\tvar a = values[0];\n\t\t\tvar b = values[1];\n\t\t\tvar angle = Math.round(Math.atan2(b, a) * (180/Math.PI));\n\t\t} else { var angle = 0; }\n\t\treturn angle;\n\t}", "function rotateit(deg)\n\t{\n\t\treturn ((deg + rotval) + 360) % 360;\n\t}", "function toRadians(degrees){\n return degrees * Math.PI / 180; \n}", "function getAngle(el) {\r\n\t\tvar st = window.getComputedStyle(el, null);\r\n\t\tvar tr = st.getPropertyValue(\"-webkit-transform\") ||\r\n\t\tst.getPropertyValue(\"-moz-transform\") ||\r\n\t\tst.getPropertyValue(\"-ms-transform\") ||\r\n\t\tst.getPropertyValue(\"-o-transform\") ||\r\n\t\tst.getPropertyValue(\"transform\") ||\r\n\t\tnull;\r\n\t\tif(tr && tr != \"none\"){\r\n\t\t\tvar values = tr.split('(')[1];\r\n\t\t\tvalues = values.split(')')[0];\r\n\t\t\tvalues = values.split(',');\r\n\r\n\t\t\tvar a = values[0];\r\n\t\t\tvar b = values[1];\r\n\r\n\t\t\tvar angle = Math.round(Math.atan2(b, a) * (180/Math.PI));\r\n\t\t\twhile(angle >= 360) angle = 360-angle;\r\n\t\t\twhile(angle < 0) angle = 360+angle;\r\n\t\t\treturn angle;\r\n\t\t}\r\n\t\telse\r\n\t\t\treturn 0;\r\n\t}", "set wristRotationDegree(value) { this._wristRotation = (value / 180.0 * Math.PI); }", "function toRadians(degree) {\n return degree * (Math.PI / 180);\n}", "setRotation(trs) {\n//----------\nreturn this.rotation = RQ.copyOfQV(trs.getRotation());\n}", "function toRadians(deg) {\n return deg * Math.PI / 180\n}", "rotarHelices(){\n var cilindro_rotor1 = this.rotor1.obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0];\n var cilindro_rotor2 = this.rotor2.obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0];\n var cilindro_rotor3 = this.rotor3.obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0];\n var cilindro_rotor4 = this.rotor4.obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0].obtenerHijos()[0];\n cilindro_rotor1.rotar(Math.PI / 16.0,[0.0,0.0,1.0]);\n cilindro_rotor2.rotar(Math.PI / 16.0,[0.0,0.0,1.0]);\n cilindro_rotor3.rotar(-Math.PI / 16.0,[0.0,0.0,1.0]);\n cilindro_rotor4.rotar(-Math.PI / 16.0,[0.0,0.0,1.0]);\n }", "degreeToRad(angle){\n return Math.PI*angle/180;\n }", "function degreeToRadians(n){\n return (n / 180 * Math.PI).toFixed(2);\n}", "function getSquare(coord) {\n const x = coord[0];\n const y = coord[1];\n return document.getElementById((y).toString().concat(\" \").concat((x).toString()));\n}", "function toDeg(rad)\n{\n return rad * 180 / Math.PI;\n}", "function deg(rad) {\n return rad * 180 / Math.PI;\n}", "function getBox(number) { // return the value of the element (x or o) . the (number is the id of the square) which gives us the value\n return document.getElementById('s' + number).innerText; //s is the id number\n}", "function raddeg(ggg){\n var degg = ggg* Math.PI / 180;\n return degg;\n}", "function toDegree() {\n current_input = current_input * (180 / Math.PI);\n displayCurrentInput();\n}", "function degree(d,r) {\nvar Degreex = d * 3.14 / 180;\nconsole.log (Degreex); \n}", "function rotate90 (){\n angleRot -= 90;\n cube1.style.transform = \"translateZ(-170px) rotateY(\"+ angleRot + \"deg)\";}", "function degToRad(degAngle)\n{\n return degAngle * Math.PI / 180;\n}" ]
[ "0.6531213", "0.63352966", "0.6269987", "0.6139909", "0.61005616", "0.608561", "0.6082949", "0.60627574", "0.60535675", "0.6043049", "0.5984824", "0.59722203", "0.5964407", "0.5905762", "0.5875156", "0.58679813", "0.5867697", "0.586679", "0.58649486", "0.585485", "0.5847462", "0.5845745", "0.5841816", "0.5839593", "0.5839421", "0.5835899", "0.5824261", "0.58229953", "0.58204526", "0.5819651" ]
0.82226104
0
keep only a n decimals in geojson coordinates
function simplifyGeojson(geo, n){ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function coord1(value) {\n\t return value\n\t .replace(removeSpace, \"\")\n\t .split(\",\")\n\t .map(parseFloat)\n\t .filter((num) => !isNaN(num))\n\t .slice(0, 3);\n\t}", "function normalizeLng( value ) {\n const rotation = Math.floor( ( value + 180 ) / 360 );\n const normalized = value - ( rotation * 360 );\n const rounded = Math.round( normalized * 1e2 ) / 1e2;\n\n return rounded;\n }", "limitPrecision (coordinate) {\n const rounded = Math.round(coordinate);\n const delta = coordinate - rounded;\n const limitedCoord = (Math.abs(delta) < 1e-9) ? rounded : coordinate;\n\n return limitedCoord;\n }", "get latitudeFormatted() {\n return this.latitude.toFixed(2);\n }", "function threeDecimalPoints(number){\n var s = number.toString();\n var i;\n for(i = 0;i<s.length;i++){\n if(s[i]=='.'){\n break;\n }\n }\n if(i>=s.length-3){\n for(var j=0;j<i-s.length+3;j++){\n s.concat('0');\n }\n return s;\n }else{\n return s.substring(0,i+4);\n }\n }", "function string2polygon(str){\n return str.replace(/^[^-0-9.e]*|[^-0-9.e]*$/g,\"\").split(/[^-0-9.e]+/).map(parseFloat);\n}", "function numberWithDots(x) {\n var parts = x.toString().split(\".\");\n // console.log(parts)\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n }", "function fromMapProjToGps(point) {\n var c = (1E3 * point).toString();\n return c = 0 > point ? \"000\" : 1 > point ? \"00\" + c.substr(0, 1) : 10 > point ? \"0\" + c.substr(0, 2) : c.substr(0, 3)\n}", "function getGeoJson() {\n return {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"LineString\",\n \"coordinates\": [\n [\n 13.25441561846926,\n 38.162839676288336\n ],\n [\n 13.269521819641135,\n 38.150961340209484\n ],\n [\n 13.250982390930197,\n 38.150961340209484\n ],\n ]\n }\n },\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [\n 13.250982390930197,\n 38.150961340209484\n ],\n [\n 13.269521819641135,\n 38.150961340209484\n ],\n [\n 13.25441561846926,\n 38.162839676288336\n ],\n [\n 13.24342929034426,\n 38.150691355539586\n ]\n ]\n ]\n }\n },\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [\n 13.277074920227072,\n 38.18335224460118\n\n ],\n [\n 13.30660067706301,\n 38.18389197106355\n\n ],\n [\n 13.278104888488791,\n 38.165808957979515\n\n ]\n ]\n ]\n }\n },\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [\n 13.309476005126974,\n 38.13233005362,\n ],\n [\n\n 13.337628470947287,\n 38.135030534863766\n ],\n [\n 13.31805907397463,\n 38.11153300139878\n ]\n ]\n ]\n }\n }\n ]\n }\n}", "function parseCoordinates(mapId) {\n var coordsField = $('#map-coords-field-' + mapId).val(); // read values from mak\n var coordsFormat = $('#map-coords-format-' + mapId).val();\n\n // Regex inspiration by: http://www.nearby.org.uk/tests/geotools2.js\n\n // It seems to be necessary to escape the values. Otherwise, the degree\n // symbol (°) is not recognized.\n var str = escape(coordsField);\n // However, we do need to replace the spaces again do prevent regex error.\n str = str.replace(/%20/g, ' ');\n\n var pattern, matches;\n var latsign, longsign, d1, m1, s1, d2, m2, s2;\n var latitude, longitude, latlong;\n\n if (coordsFormat === '1') {\n // 46° 57.1578 N 7° 26.1102 E\n pattern = /(\\d+)[%B0\\s]+(\\d+\\.\\d+)\\s*([NS])[%2C\\s]+(\\d+)[%B0\\s]+(\\d+\\.\\d+)\\s*([WE])/i;\n matches = str.match(pattern);\n if (matches) {\n latsign = (matches[3] === 'S') ? -1 : 1;\n longsign = (matches[6] === 'W') ? -1 : 1;\n d1 = parseFloat(matches[1]);\n m1 = parseFloat(matches[2]);\n d2 = parseFloat(matches[4]);\n m2 = parseFloat(matches[5]);\n latitude = latsign * (d1 + (m1 / 60.0));\n longitude = longsign * (d2 + (m2 / 60.0));\n latlong = [latitude, longitude];\n }\n } else if (coordsFormat === '2') {\n // 46° 57' 9.468\" N 7° 26' 6.612\" E\n pattern = /(\\d+)[%B0\\s]+(\\d+)[%27\\s]+(\\d+\\.\\d+)[%22\\s]+([NS])[%2C\\s]+(\\d+)[%B0\\s]+(\\d+)[%27\\s]+(\\d+\\.\\d+)[%22\\s]+([WE])/i;\n matches = str.match(pattern);\n if (matches) {\n latsign = (matches[4] === 'S') ? -1 : 1;\n longsign = (matches[8] === 'W') ? -1 : 1;\n d1 = parseFloat(matches[1]);\n m1 = parseFloat(matches[2]);\n s1 = parseFloat(matches[3]);\n d2 = parseFloat(matches[5]);\n m2 = parseFloat(matches[6]);\n s2 = parseFloat(matches[7]);\n latitude = latsign * (d1 + (m1 / 60.0) + (s1 / (60.0 * 60.0)));\n longitude = longsign * (d2 + (m2 / 60.0) + (s2 / (60.0 * 60.0)));\n latlong = [latitude, longitude];\n }\n } else if (coordsFormat === '3') {\n // N 46° 57.1578 E 7° 26.1102\n pattern = /([NS])\\s*(\\d+)[%B0\\s]+(\\d+\\.\\d+)[%2C\\s]+([WE])\\s*(\\d+)[%B0\\s]+(\\d+\\.\\d+)/i;\n matches = str.match(pattern);\n if (matches) {\n latsign = (matches[1] === 'S') ? -1 : 1;\n longsign = (matches[4] === 'W') ? -1 : 1;\n d1 = parseFloat(matches[2]);\n m1 = parseFloat(matches[3]);\n d2 = parseFloat(matches[5]);\n m2 = parseFloat(matches[6]);\n latitude = latsign * (d1 + (m1 / 60.0));\n longitude = longsign * (d2 + (m2 / 60.0));\n latlong = [latitude, longitude];\n }\n } else if (coordsFormat === '4') {\n // N 46° 57' 9.468\" E 7° 26' 6.612\"\n pattern = /([NS])\\s*(\\d+)[%B0\\s]+(\\d+)[%27\\s]+(\\d+\\.\\d+)[%22%2C\\s]+([WE])\\s*(\\d+)[%B0\\s]+(\\d+)[%27\\s]+(\\d+\\.\\d+)/i;\n matches = str.match(pattern);\n if (matches) {\n latsign = (matches[1] === 'S') ? -1 : 1;\n longsign = (matches[5] === 'W') ? -1 : 1;\n d1 = parseFloat(matches[2]);\n m1 = parseFloat(matches[3]);\n s1 = parseFloat(matches[4]);\n d2 = parseFloat(matches[6]);\n m2 = parseFloat(matches[7]);\n s2 = parseFloat(matches[8]);\n latitude = latsign * (d1 + (m1 / 60.0) + (s1 / (60.0 * 60.0)));\n longitude = longsign * (d2 + (m2 / 60.0) + (s2 / (60.0 * 60.0)));\n latlong = [latitude, longitude];\n }\n } else if (coordsFormat === '5') {\n // 46.95263, 7.43517\n pattern = /(\\d+\\.\\d+)[%2C\\s]+(\\d+\\.\\d+)/i;\n matches = str.match(pattern);\n if (matches) {\n latlong = [matches[1], matches[2]];\n }\n }\n\n if (latlong != null) {\n var mapOptions = getMapOptionsById(mapId);\n zoomAddSearchMarker(mapOptions, L.latLng(latlong), true);\n showParseFeedback(mapId, 'Coordinates successfully parsed.', 'success');\n } else {\n showParseFeedback(mapId, tForInvalidFormat, 'error');\n }\n return false;\n}", "function convertLeafletCoordsToString(coordinates){\n\tvar coords = \"'POLYGON((\";\n\tfor(var j = 0; j < coordinates.length; j++){\n\t\tif(j != 0){\n\t\t\tcoords = coords + \", \";\n\t\t}\n\t\tcoords = coords + coordinates[j].lng + \" \" + coordinates[j].lat;\n\t}\n\t// first coordinate again (required by DB!)\n\tcoords = coords + \", \" + coordinates[0].lng + \" \" + coordinates[0].lat;\n\tcoords = coords + \"))'\"\n\treturn coords;\n}", "function coord1(v) { return numarray(v.replace(removeSpace, '').split(',')); }", "function coord1(v) { return numarray(v.replace(removeSpace, '').split(',')); }", "function nwp(v, p) {\n\tvar parts = v.toFixed(p).split('.');\n\tparts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n\treturn parts.join('.');\n}", "function addPuntosMiles(num){\r\n\t\tvar rgx = /(\\d+)(\\d{3})/;\r\n\t\twhile (rgx.test(num)) {\r\n\t\t\tnum = num.replace(rgx, '$1' + '.' + '$2');\r\n\t\t}\r\n\t\treturn num;\r\n\t}", "function validator_lat(x){\n x.value = x.value.replace(/[^a-z,0-9]/i, \"\");\n }", "prim_lat_dec(s, h, k) {\n\t\t\tif(s) {\n\t\t\t\tlet s_lat = s;\n\t\t\t\tlet s_lng = h.prim_long_dec;\n\t\t\t\tlet p_geom_iri = `${P_GEOM_URI}/point/gnisf.${h.feature_id}`;\n\t\t\t\tlet s_point_wkt = `POINT(${s_lng} ${s_lat})`;\n\t\t\t\tds_geoms.write(`${p_geom_iri}\\tSRID=4326;${s_point_wkt}\\n`);\n\n\t\t\t\t// add wkt literal to geometry node\n\t\t\t\tk.write({\n\t\t\t\t\ttype: 'c3',\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t[`>${p_geom_iri}`]: {\n\t\t\t\t\t\t\t'geosparql:asWKT': [`^geosparql:wktLiteral\"<http://www.opengis.net/def/crs/OGC/1.3/CRS84>${s_point_wkt}`],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// geometry uri\n\t\t\t\treturn {\n\t\t\t\t\t'ago:geometry': [`>${p_geom_iri}`],\n\t\t\t\t};\n\t\t\t}\n\t\t}", "function removeDecimal(number){\n return Math.round(number)\n }", "function glslifyNumber (n) {\n return n === (n | 0) ? n + '.0' : n + '';\n }", "function numberDecimals(x, n){\n return Number(removeAll(x, \",\")).toFixed(n);\n }", "function extentToGeoJson(x, y) {\n mapImplementation.ExtentToGeoJson(x, y);\n }", "function formatPoint(point) {\n var val = Math.round(point * 1000) / 1000;\n return (val < 10) ? \"0\" + val : val;\n}", "function getCoords(point) {\n return [Number(point.lat.toFixed(4)), Number(point.lng.toFixed(4))];\n }", "function format_coordinate(coord)\n{\n var abs= coord/Math.abs(coord);\n var response=Math.abs(coord);\n\n if(Math.abs(Math.floor(coord))>999 && Math.abs(Math.floor(coord))<10000)\n {\n response=\"0\" + Math.abs(coord);\n }\n else if(Math.abs(Math.floor(coord))>99 && Math.abs(Math.floor(coord))<1000)\n {\n response=\"00\" + Math.abs(coord);\n }\n else if(Math.abs(Math.floor(coord))>9 && Math.abs(Math.floor(coord))<100)\n {\n response=\"000\" + Math.abs(coord);\n }\n else if(Math.abs(Math.floor(coord)<10))\n {\n response=\"0000\" + Math.abs(coord);\n }\n\n response=parseFloat(response.substr(0,3)) + parseFloat(response.substr(3)/60);\n\n return abs*response;\n\n//return parseFloat(coord.substr(0,2)) + parseFloat(coord.substr(2)/60);\n}", "function convertGeoJsonCoordinates(coords)\n{\n\treturn new L.LatLng(-coords[1], coords[0], coords[2]);\n}", "function getDecimalPoints(value) {\r\n var index = value.toString().indexOf(\".\");\r\n return index === -1 ? 0 : value.toString().length - index - 1;\r\n }", "function formatNumber(x) {\n var parts = x.toString().split(\".\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n}", "function formatNumber(x) {\n var parts = x.toString().split(\".\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n}", "function getWGS84(coordObj){\n var lat = parseFloat(coordObj.lat);\n var lon = parseFloat(coordObj.lon);\n \n var fLat = (Math.floor(lat/100.0) + (lat % 100)/60.0); \n var fLon = (Math.floor(lon/100.0) + (lon % 100)/60.0); \n \n return {\"lat\":fLat, \"lon\":fLon};\n}", "applyPrecisionDigits(precisionDigits) {\n const that = this;\n\n precisionDigits = Math.max(0, Math.min(precisionDigits, 20));\n\n let renderedValue = parseFloat(that.numericValue).toFixed(precisionDigits);\n\n if (that.isENotation(renderedValue)) {\n renderedValue = that.largeExponentialToDecimal(renderedValue) + '.' + '0'.repeat(precisionDigits);\n }\n\n return renderedValue;\n }" ]
[ "0.61190784", "0.5901839", "0.58294755", "0.5709085", "0.5706951", "0.5681709", "0.5644305", "0.55318093", "0.55226123", "0.5419712", "0.5400155", "0.53726745", "0.53726745", "0.5368304", "0.5363918", "0.5339507", "0.5334838", "0.53333217", "0.5324105", "0.5297405", "0.5282248", "0.5245416", "0.5229997", "0.522381", "0.51907367", "0.51890177", "0.51715875", "0.51715875", "0.5165738", "0.5146146" ]
0.6902684
0
Generate the query for specific method
_getQuery(method, data, params) { let query; switch (method) { case 'find': query = this._getQueryGeocode(data, params); break; case 'reverseGeocode': query = this._getQueryReverse(data, params); break; case 'suggest': query = this._getQuerySuggest(data, params); break; case 'findAddressCandidates': query = this._getQueryFindAddressCandidates(data, params); break; case 'geocodeAddresses': query = this._getQueryGeocodeAddresses(data, params); break; } query.f = params.f || 'json'; query = Object.assign(params, query); return query; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function CustomQuery() {\n\n}", "async function queryDynamicDb( layer, method, props ){\n let obj = ''; let event = ''; let field = '';\n if (layer.host=='bniaApi'){obj=new BniaSearch(layer); }\n if (layer.host=='arcgis') {obj=new EsriSearch(layer); }\n if (layer.host=='socrata'){obj=new SocrataSearch(layer); }\n console.log(method, props);\n return obj[method](props);\n}", "function qryCollection(method){\n return function() {\n var restCmd = this._buildREST(this.params),\n args = [];\n\n restCmd.params += \".\" + method + \"([\";\n for (var _i = 0, argsLen = arguments[0].length; _i < argsLen; _i++) {\n restCmd.params += arguments[0][_i].params;\n restCmd.params += \",\";\n }\n restCmd.params = restCmd.params.slice(0, -1);\n restCmd.params += \"])\";\n return restCmd;\n };\n }", "function queryCollection(method){\n return function() {\n var gremlin = this._buildGremlin(this.params),\n param = '';\n\n if(_.isArray(arguments[0])){\n for (var _i = 0, argsLen = arguments[0].length; _i < argsLen; _i++) {\n param += arguments[0][_i].params;\n param += \",\";\n }\n\n gremlin.params += \".\" + method + \"([\" + param + \"])\";\n } else {\n gremlin.params += \".\" + method + buildArguments.call(this, arguments[0]);\n }\n\n return gremlin;\n };\n}", "static processBasicQuery(query, method, criteria){\n\n if(query[method])\n for (const key in criteria) {\n if (criteria.hasOwnProperty(key)) {\n const element = criteria[key];\n query[method](key, element);\n }\n }\n }", "function generateQuery(){\n\t//Determinamos los valores para realziar la b?squeda\n\tjsCalGuiasCodGuia = get('calGuiasFrm.codGuia').toString();\n\tjsCalGuiasDpteOidDepa = get('calGuiasFrm.dpteOidDepa')[0];\n\tjsCalGuiasValTitu = get('calGuiasFrm.valTitu').toString();\n\tjsCalGuiasFecInicVali = get('calGuiasFrm.fecInicVali').toString();\n\tjsCalGuiasFecFinVali = get('calGuiasFrm.fecFinVali').toString();\n\tjsCalGuiasValDescGuia = get('calGuiasFrm.valDescGuia').toString();\n\t\n\t\n\tvar parametros = \"\";\n\tparametros += jsCalGuiasCodGuia + \"|\";\n\tparametros += jsCalGuiasDpteOidDepa + \"|\";\n\tparametros += jsCalGuiasValTitu + \"|\";\n\tparametros += jsCalGuiasFecInicVali + \"|\";\n\tparametros += jsCalGuiasFecFinVali + \"|\";\n\tparametros += jsCalGuiasValDescGuia + \"|\";\n\t\n\treturn parametros;\n}", "function queryPipes(method){\n return function() {\n var gremlin = this._buildGremlin(this.params),\n args = [],\n isArr = _.isArray(arguments[0]),\n argsLen = isArr ? arguments[0].length : arguments.length;\n\n gremlin.params += \".\" + method + \"(\";\n\n for (var _i = 0; _i < argsLen; _i++) {\n gremlin.params += isArr ? arguments[0][_i].params || parseArguments.call(this, arguments[0][_i]) : arguments[_i].params || parseArguments.call(this, arguments[_i]);\n gremlin.params += \",\";\n }\n\n gremlin.params = gremlin.params.slice(0, -1);\n gremlin.params += \")\";\n\n return gremlin;\n };\n}", "function ______MA_Query() {}", "function TQueries(){}", "function qryPipes(method){\n return function() {\n var self = this,\n restCmd = self._buildREST(self.params),\n args = [],\n isArray = isArray(arguments[0]),\n argsLen = isArray ? arguments[0].length : arguments.length;\n\n restCmd.params += \".\" + method + \"(\";\n for (var _i = 0; _i < argsLen; _i++) {\n restCmd.params += isArray ? arguments[0][_i].params || parseArgs.call(self, arguments[0][_i]) : arguments[_i].params || parseArgs.call(self, arguments[_i]);\n restCmd.params += \",\";\n }\n restCmd.params = restCmd.params.slice(0, -1);\n restCmd.params += \")\";\n return restCmd;\n };\n }", "function TQuery(){}", "async generateQuery() {\n return await this.dagObj.generateQuery();\n }", "function TQueries() {}", "function TQueries() {}", "function TQueries() {}", "function TQuery() {}", "function TQuery() {}", "function TQuery() {}", "getFixedQuery() {}", "function generateQuery(type) {\n var query = new tabulator.rdf.Query();\n var rowVar = kb.variable(keyVariable.slice(1)); // don't pass '?'\n\n addSelectToQuery(query, type);\n addWhereToQuery(query, rowVar, type);\n addColumnsToQuery(query, rowVar, type);\n\n return query;\n }", "buildQuery() {\n if (!this.where || !this.data || !this.table) {\n const err = \"Bad Request. Required information not provided. Where, Data and Table properties must have values\";\n return err;\n }\n else {\n const updateQuery = `UPDATE ${this.table.database}.${this.table.name} SET ${functions_module_1.escape(this.data)} ${this.whereClause}`;\n return updateQuery;\n }\n }", "getQuery() {\n return this.query;\n }", "function LQuery(){}", "function TQuery() { }", "function TQuery() { }", "function query(data, method) {\n method = method || 'GET';\n var queryParams = {\n method: method,\n url: baseEndpoint\n };\n if (method === 'GET') {\n queryParams.params = data;\n }\n if (method === 'POST') {\n queryParams.data = data;\n }\n\n return $http(queryParams);\n }", "function TQueries() { }", "function TQueries() { }", "query() { }", "function CreateDatabaseQuery() {}" ]
[ "0.65071005", "0.6415638", "0.6402205", "0.6333182", "0.6295627", "0.62335473", "0.6158737", "0.6100864", "0.60952926", "0.6053628", "0.6033982", "0.60304505", "0.6028751", "0.6028751", "0.6028751", "0.60283583", "0.60283583", "0.60283583", "0.60277146", "0.5974114", "0.59583646", "0.58420384", "0.5810556", "0.5807412", "0.5807412", "0.5800121", "0.5746629", "0.5746629", "0.57355446", "0.5720361" ]
0.71529335
0
Prepare the query for suggest
_getQuerySuggest(data, params) { return { text: data, outFields: params.outFields || '*', maxSuggestions: params.maxSuggestions || 10, }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "searchSuggest(query) {\r\n let finalQuery;\r\n if (typeof query === \"string\") {\r\n finalQuery = { querytext: query };\r\n }\r\n else {\r\n finalQuery = query;\r\n }\r\n return this.create(SearchSuggest).execute(finalQuery);\r\n }", "function init_query () {\n window.search_terms = ['pancake']\n if ('q' in query_parameters) {\n if (!$('#q').val()) {\n $('#q').val(query_parameters['q'])\n }\n }\n var terms = $('#q').val().match(/\\w+|\"(?:\\\\\"|[^\"])+\"/g)\n if (terms && terms.length && terms[0].length) {\n window.search_terms = terms\n }\n}", "buildSearchQuery() {\n if (this.get('invalidSearchTerm') || isEmpty(this.get('searchTerm'))) {\n return {};\n }\n const searchTerm = this.get('searchTerm');\n const query = {};\n\n if (this.get('searchType.date')) {\n if (dateHelper.isValidDate(searchTerm, 'MM/DD/YYYY')) {\n query.birthDate = searchTerm;\n } else {\n this.set('searchType.date', false);\n }\n }\n if (this.get('searchType.ssn')) {\n if (/^\\d{3}-?\\d{2}-?\\d{4}$/.test(searchTerm)) {\n query.socialSecurityNumber = searchTerm;\n this.set('searchTerm', PFStringUtil.formatSSN(this.get('searchTerm')));\n } else {\n this.set('searchType.ssn', false);\n }\n }\n if (this.get('searchType.name')) {\n merge(query, patientSearchUtil.formatNameParameters(searchTerm));\n }\n if (this.get('searchType.prn')) {\n query.patientRecordNumber = searchTerm;\n }\n return query;\n }", "suggest(query){\n const that = this;\n let maxNumber = this.maxSuggestResults;\n const promises = [];\n promises.push(that.suggestTextQuery(query, maxNumber));\n Object.keys(that.suggestionIndexes).forEach(function(indexKey){\n const set = that.suggestionIndexes[indexKey];\n const intent = set.search(query, maxNumber);\n promises.push(intent);\n });\n const adapters = that.adapters;\n return Promise.all(promises).then(function(dataSets){\n let items = [];\n dataSets.forEach(function(dataSet){\n if (!dataSet || !dataSet.length)\n return ;\n items = items.concat(dataSet.items);\n })\n return new SearchCriteriaDataSet({\n adapters,\n items\n });\n });\n }", "function query_builder(query)\n {\n var name = $(\"#txtname\").val();\n var exp_tags = /S*#(?:\\[[^\\]]+\\]|\\S+)/;\n if (exp_tags.test(name)){\n var texto = name.split(/\\s+/g);\n tags = [];\n title = [];\n for(var i=0;i<texto.length;i++){\n if(texto[i].match(exp_tags)){\n tags.push(texto[i].replace('#',''))\n }\n else{\n title.push(texto[i])\n }\n }\n title = title.join(\" \");\n if (title != \"\" && tags.length != 0){\n query['title'] = {'$text': {'$search': title}} ;\n query['tags'] = {'tags': {'$all': tags}};\n }\n else if (tags.length != 0 && title == \"\"){\n query['tags'] = {'tags': {'$all': tags}};\n delete query['title']\n }\n else if (tags.length == 0 && title != \"\"){\n query['title'] = {'$text': {'$search': title}};\n delete query['tags']\n }\n else{\n delete query['title'];\n delete query['tags']\n }\n buscar(query)\n }\n else{\n query['title'] = {'$text': {'$search': $(\"#txtname\").val(), '$options': 'i'}};\n delete query['tags'];\n buscar(query)\n }\n }", "_formatQuery(document) {\n let q = document.query;\n if (document.exclude && document.exclude.length > 0) {\n document.exclude.forEach(item => {\n // eslint-disable-next-line quotes\n q += ' -\"' + item + '\"';\n });\n }\n q += ' AND -filter:retweets';\n return q;\n }", "function checkQuery( itcb ) {\n if( args.query ) {\n\n // map form mapped fields back to schema fields\n if( args.query.editorName ) {\n args.query['editor.name'] = args.query.editorName;\n delete args.query.editorName;\n }\n if( args.query.editorInitials ) {\n args.query['editor.initials'] = args.query.editorInitials;\n delete args.query.editorInitials;\n }\n\n // there are other properties that can also filter \"timestamp\"\n if( args.query.$or && Array.isArray( args.query.$or ) ) {\n // rename \"quarterColumn\" property to \"timestamp\"\n args.query.$or.forEach( function( or ) {\n if( or.quarterColumn ) {\n or.timestamp = or.quarterColumn;\n delete or.quarterColumn;\n }\n } );\n // also apply original \"timestamp\" to \"$or\"\n if( args.query.timestamp ) {\n args.query.$or.push( {timestamp: args.query.timestamp} );\n delete args.query.timestamp;\n }\n }\n\n /**\n * [MOJ-11908]\n * Whenever a regex filter against the activity's content is queried, we intercept it.\n * This makes it possible to search the content for the so-called \"badges\" (bootstrap-labels),\n * which are rendered, if specific properties of an activity are set to true/false, or to\n * specific values (mainly ENUMs)\n * E.g. activity.phContinuousMed = true renders a badge with the abbreviation \"DM\" (in german),\n * which means \"DauerMedikament\".\n *\n * Since the user sees these patches within the content, he assumes, that one may search for the\n * label's content. In the example, this would be \"DM\".\n * So we have to be able to filter the properties in the database accordingly,\n * although the activity.content has NO knowledge of the \"DM\".\n *\n * Here, this is done by analyzing the query sent by the user,\n * and search for these abbreviations. If found, the query is altered on-the-fly,\n * to include a search for the requested parameters.\n */\n if( args.query.content && args.query.content.$regex ) {\n let CONTINUOUS_MEDICATION = i18n( 'InCaseMojit.activity_schema.CONTINUOUS_MEDICATION' ),\n SAMPLE_MEDICATION = i18n( 'InCaseMojit.activity_schema.SAMPLE_MEDICATION' ),\n ACUTE_DOK = i18n( 'InCaseMojit.activity_schema.diagnose_type.ACUTE_DOK' ),\n ACUTE_INVALIDATING = i18n( 'InCaseMojit.activity_schema.diagnose_type.ACUTE_INVALIDATING' ),\n CONT_DIAGNOSES = i18n( 'InCaseMojit.activity_schema.diagnose_type.CONT_DIAGNOSES' ),\n CONT_DIAGNOSES_DOK = i18n( 'InCaseMojit.activity_schema.diagnose_type.CONT_DIAGNOSES_DOK' ),\n CONT_DIAGNOSES_INVALIDATING = i18n( 'InCaseMojit.activity_schema.diagnose_type.CONT_DIAGNOSES_INVALIDATING' ),\n A_CONT_DIAGNOSES = i18n( 'InCaseMojit.activity_schema.diagnose_type.A_CONT_DIAGNOSES' ),\n A_CONT_DIAGNOSES_DOK = i18n( 'InCaseMojit.activity_schema.diagnose_type.A_CONT_DIAGNOSES_DOK' ),\n A_CONT_DIAGNOSES_INVALIDATING = i18n( 'InCaseMojit.activity_schema.diagnose_type.A_CONT_DIAGNOSES_INVALIDATING' ),\n EXPENSES = i18n( 'InCaseMojit.casefile_detail.group.EXPENSES' ),\n\n /**\n * An activity may provide multiple parameters, which are set to true/false,\n * or a given set of parameters. Depending on this state, a badge (bootstrap-label)\n * is displayed in the content, which shows an abbreviation, according to this state.\n * So the user sees this label, and tries to search for it, by typing the abbreviation.\n *\n * This array defines an object for each searchable property (which has a corresponding badge).\n * {\n * searchTag : abbreviation displayed in the label,\n * searchCondition: database parameters to be searched for\n * }\n * @type {Array}\n */\n propertiesToSearchFor = [\n {\n searchTag: CONTINUOUS_MEDICATION,\n searchCondition: {phContinuousMed: true}\n },\n {\n searchTag: SAMPLE_MEDICATION,\n searchCondition: {phSampleMed: true}\n },\n {\n searchTag: ACUTE_DOK,\n searchCondition: {\n diagnosisType: 'ACUTE',\n diagnosisTreatmentRelevance: 'DOKUMENTATIV'\n }\n },\n {\n searchTag: ACUTE_INVALIDATING,\n searchCondition: {\n diagnosisType: 'ACUTE',\n diagnosisTreatmentRelevance: 'INVALIDATING'\n }\n },\n {\n searchTag: CONT_DIAGNOSES,\n searchCondition: {\n diagnosisType: 'CONTINUOUS',\n diagnosisTreatmentRelevance: 'TREATMENT_RELEVANT'\n }\n },\n {\n searchTag: CONT_DIAGNOSES_DOK,\n searchCondition: {\n diagnosisType: 'CONTINUOUS',\n diagnosisTreatmentRelevance: 'DOKUMENTATIV'\n }\n },\n {\n searchTag: CONT_DIAGNOSES_INVALIDATING,\n searchCondition: {\n diagnosisType: 'CONTINUOUS',\n diagnosisTreatmentRelevance: 'INVALIDATING'\n }\n },\n {\n searchTag: A_CONT_DIAGNOSES,\n searchCondition: {\n diagnosisType: 'ANAMNESTIC',\n diagnosisTreatmentRelevance: 'TREATMENT_RELEVANT'\n }\n },\n {\n searchTag: A_CONT_DIAGNOSES_DOK,\n searchCondition: {\n diagnosisType: 'ANAMNESTIC',\n diagnosisTreatmentRelevance: 'DOKUMENTATIV'\n }\n },\n {\n searchTag: A_CONT_DIAGNOSES_INVALIDATING,\n searchCondition: {\n diagnosisType: 'ANAMNESTIC',\n diagnosisTreatmentRelevance: 'INVALIDATING'\n }\n },\n {\n searchTag: EXPENSES,\n searchCondition: {\n $and: [\n {costType: {$exists: true}},\n {costType: {$type: \"string\"}},\n {costType: {$ne: \"\"}}\n ]\n }\n },\n {\n searchTag: 'email',\n searchCondition: {savedEmails: {$exists: true}}\n\n }\n\n ],\n\n // extract the query's regex source\n queryRegexSource = (args.query.content.$regex.source || ''),\n queryRegexFlags = (args.query.content.$regex.flags || 'i');\n\n /**\n * We start, by examining the search query (which is actually a regex itself), for the occurrence of\n * the searchTags of the properties. So we filter out all occurrences, for which we have to\n * take care about. Notice: the query may additionally be limited to the beginning\n * or the end of the string, \"^\" or \"$\", respectively.\n * Examples for this regex:\n * - \"DM\", \"^DM\", \"DM$\": single occurrences\n * To search all continuous medications (DM).\n * - \"DM ExampleMedication\", \"DM ExampleMedication\", \"^DM ExampleMedication$\"\n * To search for all continuous medications (DM), and additionally those of type \"ExampleMedication\".\n * - \"DM MM\", \"^DM MM\", \"DM MM$\": multiple occurrences\n * To search for all continuous (DM) and sample medications (MM). Should generally not happen.\n */\n propertiesToSearchFor = propertiesToSearchFor\n .filter( propertyToSearch => {\n // Create multiple RegExp from the property's search tag, and match each\n // against the query. Each RegExp covers the cases explained above.\n let // watch out, the searchTag itself is escaped for regex characters\n // => this requires us to double-escape all regex-characters in our search tag,\n // to obtain a match on those (e.g. search for \"DD.d\", query is \"DD\\.d\", so we create a regex with \"DD\\\\\\.d\")\n escapedSearchTag = Y.doccirrus.commonutils.$regexEscape( Y.doccirrus.commonutils.$regexEscape( propertyToSearch.searchTag ) ),\n // get a collection of all tests to run on the user's query regex\n regexTests = [\n // match the occurrence of the searchTag at the beginning of the query\n new RegExp( \"^\\\\^?\" + escapedSearchTag + \"\\\\s\", \"gi\" ),\n\n // match the occurrence of the searchTag in the middle of the query\n new RegExp( \"\\\\s\" + escapedSearchTag + \"(\\\\s)\", \"gi\" ), // the capture group is intended here!\n\n // match the occurrence of the searchTag at the end of the query\n new RegExp( \"\\\\s\" + escapedSearchTag + \"\\\\$?$\", \"gi\" ),\n\n // match the occurrence of the searchTag as the only content of the query\n new RegExp( \"^\\\\^?\" + escapedSearchTag + \"\\\\$?$\", \"gi\" )\n ],\n tagFound = false,\n tagFoundCallback = ( match, spaceCaptureGroup ) => {\n /**\n * If yes, this function is invoked.\n * Here, we remove the occurrence of the tag from the regex string,\n * and mark the tag as found.\n * E.g.:\n * \"DD Test-Diagnosis XYZ\" => \"Test-Diagnosis XYZ\"\n *\n * NOTICE:\n * We explicitly proceed with other regex tests from the array,\n * to catch multiple occurrences of the same tag in the different positions,\n * and to properly remove these occurrences.\n * This may be caused by the user entering the tag twice,\n * e.g. \"DM test medication DM\", and him still expecting a result.\n * @type {boolean}\n */\n tagFound = true;\n\n /**\n * Replace every tag by an empty string, with one exception:\n * In case of a positioning of the tag within the string,\n * we have to keep a space, to avoid merging words.\n */\n return (typeof spaceCaptureGroup === \"string\") ? spaceCaptureGroup : '';\n };\n\n for( let regexTest of regexTests ) { //eslint-disable-line no-unused-vars\n // see, if there is a match of the query's regex source with the test regex\n queryRegexSource = queryRegexSource.replace( regexTest, tagFoundCallback );\n }\n\n // if no tag of this type was found, exclude the tag from further treatment\n return tagFound;\n } );\n\n /**\n * Now, that we have all relevant properties, and that we have cleaned the query's regex source\n * from these properties, we may map the matching properties into the query as new conditions ($and).\n */\n if( propertiesToSearchFor.length > 0 ) {\n\n // Create the new search Regex for the content, which has been cleaned from all matched tags.\n args.query.content.$regex = new RegExp( queryRegexSource, queryRegexFlags );\n\n // Ensure, that there is an $and defined ...\n if( !args.query.$and ) {\n args.query.$and = [];\n }\n // ... and that it is an array.\n if( Array.isArray( args.query.$and ) ) {\n // move the former \"content\"-query out of the original query, and into the $and.\n args.query.$and.push( {content: args.query.content} );\n delete args.query.content;\n\n // finally, map the all search conditions into the $and\n propertiesToSearchFor.map( propertyToSearch => args.query.$and.push( propertyToSearch.searchCondition ) );\n }\n }\n }\n\n }\n if( caseFileDoctorSelectFilter ) {\n args.query = {$and: [caseFileDoctorSelectFilter, args.query]};\n }\n itcb( null );\n }", "function search() {\n __globspace._gly_searchadvanced.removeAll();\n _gly_ubigeo.removeAll();\n let sql = '1=1', \n idtable='#tbl_searchadvanced', \n isexportable=true, \n nquery=__query.length;\n\n // formación del sql \n for (let i = 0; i < nquery; i++){\n let item = __query[i],\n filter = item.filter.toUpperCase(),\n typedata=item.typedata,\n auxsql='';\n\n switch (typedata) {\n case 'double': case 'small-integer': case 'integer': case 'single':\n auxsql = ` ${item.fieldname} ${item.condition} \"${filter}\"`;\n break;\n case 'date':\n console.log(filter);\n let fi = moment(filter).add(5, 'hours').format('YYYY-MM-DD HH:mm:ss'); //consulta al servicio en hora utc (+5);\n let ff = moment(filter).add(29, 'hours').subtract(1, 'seconds').format('YYYY-MM-DD HH:mm:ss');\n \n if(item.condition == '=' || item.condition == 'contiene'){\n auxsql = `(${ item.fieldname } BETWEEN timestamp '${ fi }' AND timestamp '${ ff }')`;\n }else{\n if(item.condition == '<='){\n auxsql = ` ${item.fieldname} ${item.condition} timestamp '${ff}'`; \n }else if(item.condition == '>='){\n fi = moment(filter).add(5, 'hours').subtract(1, 'seconds').format('YYYY-MM-DD HH:mm:ss');\n auxsql = ` ${item.fieldname} ${item.condition} timestamp '${fi}'`;\n }else if(item.condition == '>'){\n auxsql = ` ${item.fieldname} ${item.condition} timestamp '${ff}'`;\n }else if(item.condition == '<'){\n auxsql = ` ${item.fieldname} ${item.condition} timestamp '${fi}'`;\n }\n }\n break;\n default:\n auxsql = `Upper(${item.fieldname}) ${item.condition} '${filter}'`;\n break;\n }\n\n if (item.option == '--') {\n if(typedata == 'date'){\n sql = auxsql;\n }else{\n item.condition == 'contiene' ? sql += ` and Upper(${item.fieldname}) like '%${filter}%'` : sql = auxsql;\n }\n } else {\n if(typedata == 'date'){\n sql += ` ${item.option} ${auxsql}`;\n }else{\n item .condition == 'contiene' ? sql += ` ${item.option} Upper(${item.fieldname}) like '%${filter}%'` : sql += ` ${item.option} ${auxsql}`;\n }\n }\n }\n \n __globspace.currentview.graphics.remove(_gra_ubigeo);\n\n // si se a selecionado un item de ubigeo primero obtengo la geometria del ubigeo y luego la consulta propia\n if(__url_ubigeo!=''){\n let _queryt = new QueryTask({url:__url_ubigeo}),\n _qparams = new Query(); \n _qparams.returnGeometry = true;\n _qparams.where = __sql_ubigeo;\n\n _queryt.execute(_qparams).then(function(response){\n \n __ubigeogeometry=response.features[0].geometry;\n\n let _queryt2 = new QueryTask({url:__url_query}),\n _qparams2 = new Query(); \n\n _qparams2.where = sql;\n _qparams2.outFields = [\"*\"];\n _qparams2.geometry = __ubigeogeometry;\n _qparams2.spatialRelationship = \"intersects\";\n _qparams2.returnGeometry = true;\n\n _queryt2.execute(_qparams2).then(function(response){\n let nreg = response.features.length;\n let fields = response.fields;\n if(nreg==0){\n alertMessage(\"La consulta no tiene registros a mostrar\", \"warning\",'', true)\n Helper.hidePreloader();\n }else{\n if(nreg>=1000){\n alertMessage('El resultado supera el límite, por ello solo se muestra los primeros 1000 registros. \\n Para mejorar su consulta, ingrese más filtros.','warning', 'bottom-right');\n }\n Helper.loadTable(response, fields, __titlelayer, idtable, isexportable);\n // Helper.renderToZoom(response, __globspace._gly_searchadvanced);\n Helper.renderGraphic(response, __globspace._gly_searchadvanced);\n\n\n if(Object.keys(_gra_ubigeo).length ==0){\n _gra_ubigeo = new Graphic({\n geometry: __ubigeogeometry, \n symbol:_symbol,\n });\n }\n _gra_ubigeo.geometry=__ubigeogeometry;\n __globspace.currentview.graphics.add(_gra_ubigeo);\n __globspace.currentview.when(function () {\n __globspace.currentview.goTo({\n target: __ubigeogeometry\n });\n });\n }\n }).catch(function (error) {\n Helper.hidePreloader();\n console.log(\"query task error\", error);\n })\n }).catch(function (error) {\n Helper.hidePreloader();\n console.log(\"query task error\", error);\n })\n }else{\n let _queryt = new QueryTask({url:__url_query}),\n _qparams = new Query();\n\n _qparams.where = sql;\n _qparams.outFields = [\"*\"];\n _qparams.returnGeometry = true;\n\n _queryt.execute(_qparams).then(function(response){\n let nreg = response.features.length;\n let fields = response.fields;\n if(nreg==0){\n alertMessage(\"La consulta no tiene registros a mostrar\", \"warning\", '', true);\n Helper.hidePreloader();\n }else{\n if(nreg>=1000){\n alertMessage('El resultado supera el límite, por ello solo se muestra los primeros 1000 registros. \\n Para mejorar su consulta, ingrese más filtros.','warning', 'bottom-right');\n }\n Helper.loadTable(response, fields, __titlelayer, idtable, isexportable);\n Helper.renderToZoom(response, __globspace._gly_searchadvanced);\n }\n }).catch(function (error) {\n Helper.hidePreloader();\n console.log(\"query task error\");\n console.log(error);\n })\n }\n }", "loadSuggestions(query, endpoint) {\n\n let deferred = this.$q.defer();\n\n if (query != \"*\" && query.length > 1) {\n\n let config = {\n key: query,\n graph_name: this.dataset\n };\n\n let parseResults = function (results) {\n let suggestions = [];\n for (let i = 0; i < results.data.length; ++i) {\n let result = results.data[i];\n result.text = String(result.value) + \" (\" + result.attribute + \")\";\n suggestions[i] = result;\n }\n deferred.resolve(suggestions);\n };\n\n this.$http.post(this.resource + endpoint, config).then(parseResults);\n\n } else if (query == \"*\") {\n\n this.$timeout(function () {\n deferred.resolve([{\n text: \"* (wildcard)\",\n attribute: \"*\",\n name: \"*\"\n }])\n })\n\n }\n\n\n return deferred.promise;\n }", "function buildQuery() {\n let q = {\n \"query\": query, // the query\n \"max_results\": 100, // max results per request, 100 is the maximum for standard licenses in sandboxed environments \n \"expansions\": \"geo.place_id\", // whenever a tweet has geographical information in the form a of place_id, get more info on that place_id\n \"tweet.fields\": \"author_id,created_at,geo\", // by default the Tweet id and and the text are returned, but here we're also including the author_id, the time of publishing, and its geographical features\n \"place.fields\": \"geo,name,full_name,place_type\" // the additional information associated with a place_id, namely its name and a geo object with geographical coordinates, either in the form of a point or a bounding box\n };\n // the nextToken paramenter is optional (as there is none in the first request\n // but if a nextToken was passed, then it inserts it into the query object\n if(nextToken !== undefined) q[\"next_token\"] = nextToken;\n return q;\n }", "function collect_query_info() {\n let query = {};\n\n let name = get_name_input();\n if (name !== null && name !== \"\") {\n query['sdn_name'] = name;\n }\n\n let type = get_type_select()\n if (type !== empty_type_field) {\n query['sdn_type'] = type;\n }\n\n let program = get_program_select()\n if (program !== empty_program_field) {\n query['program'] = program;\n }\n\n $.each(get_search_row_ids(), (index, row_id) => {\n let select = get_row_select(row_id);\n let input = get_row_input(row_id);\n if (select != empty_select && input !== null && input !== \"\") {\n query[select] = input;\n }\n });\n\n query.size = 50;\n query.from = 0;\n\n window.lastQuery = query;\n\n if (!$.isEmptyObject(query)) {\n return query;\n }\n else {\n return null;\n }\n}", "function loadInitialQuery() {\n\t\t\t\n\t\t\tvar params = $location.search();\n\t\t\t\n\t\t\t// run predefined search if form parameters are passed in\n\t\t\tif (params.termSearch || params.stageSearch) {\n\t\t\t\t\n\t\t\t\tif (params.termSearch) {\n\t\t\t\t\tvm.termSearch = params.termSearch;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (params.stageSearch) {\n\t\t\t\t\tvm.stageSearch = params.stageSearch;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsearch();\n\t\t\t}\n\t\t}", "parseQuery(query) {\r\n let finalQuery;\r\n if (typeof query === \"string\") {\r\n finalQuery = { Querytext: query };\r\n }\r\n else if (query.toSearchQuery) {\r\n finalQuery = query.toSearchQuery();\r\n }\r\n else {\r\n finalQuery = query;\r\n }\r\n return finalQuery;\r\n }", "parseEntitySuggestData(response, query) {\n const index = this.getEntitySuggestIndex(response.params.method);\n const docs = [];\n\n const numItems = (response.response.suggestions.length <= 5) ? response.response.suggestions.length : 5;\n\n for (let i = 0; i < numItems; i++) {\n if (response.response.suggestions[i]) {\n docs.push({text: response.response.suggestions[i].suggestion});\n }\n }\n\n return {index: index, docs: docs, query: query};\n }", "function setQuery() {\n getSearch(search.value);\n}", "addQuery(text) {}", "setUpQuery( ) {\n\n \n let myQueryObj = {sdate: this.props.startDate, edate: this.props.endDate\t, symptom: this.props.symptom};\n\t\t//console.log('my search: ', myQueryObj); \n\n\n this.props.dispatch(fetchFoodList('daylists/getcauses', myQueryObj) );\n }", "processSearchQuery() {\n if (this.queryItems.length) {\n if (this.selectedDataIndex > -1) {\n this.selectedListNode(null, this.selectedDataIndex);\n }\n else {\n this.selectedListNode(null, 0);\n }\n }\n }", "tune(data) {\n let params = data.params;\n\n Object.keys(params).forEach(function(p) {\n // Replace metadata by selected value of corresponding list\n if (p == 'country' && params[p]) {\n // Parse country for Virtuoso\n data.query = data.query.replaceAll('$country', params[p])\n data.query = data.query.replace(/countrye/, params[p].replace(/ /, \"_\"));\n data.query = data.query.replace(/countryf/, getFrenchName(params[p]));\n } else if (p == 'period') {\n data.query = data.query.replaceAll('$beginYear', params[p][0])\n data.query = data.query.replaceAll('$endYear', params[p][1])\n } else if (p == 'lab' && params.type == 2) {\n data.query = data.query.replaceAll('$lab1', params[p][0])\n data.query = data.query.replaceAll('$lab2', params[p][1])\n } else if (p == 'lab') {\n data.query = data.query.replaceAll('$lab1', params[p][0])\n } else if (p == 'variables') {\n params[p].forEach((v,i) => {\n data.query = data.query.replaceAll('$term'+(i+1), v)\n })\n } else if (p == 'prefixes' && params[p]){\n params[p].forEach(pre => {\n data.query = pre + '\\n' + data.query;\n })\n } else if (p == 'list_authors') {\n data.query = data.query.replaceAll('$authorsList', params[p])\n }\n });\n }", "function setSearchQuery (queryString) {\n vm.table.searchQuery = queryString;\n }", "function CustomQuery() {\n\n}", "searchQuery(value) {\n let result = this.tableData;\n if (value !== '') {\n result = this.fuseSearch.search(this.searchQuery);\n }\n this.searchedData = result;\n }", "function handleQuery () {\n var searchText = $scope.searchText || '',\n term = searchText.toLowerCase();\n //-- if results are cached, pull in cached results\n if (!$scope.noCache && cache[ term ]) {\n ctrl.matches = cache[ term ];\n updateMessages();\n } else {\n fetchResults(searchText);\n }\n\n ctrl.hidden = shouldHide();\n }", "generateQuery (ignoreSuperterms) {\n // 1. Get appropriate terms\n let keywords = this.getTermsWithThreshold(true)\n let mergedKeywords = []\n\n if (ignoreSuperterms) {\n mergedKeywords = keywords\n } else {\n // 3. + 4. Discard all subterms and put all superterms at the position of their first subterm\n for (let i = 0; i < keywords.length; i++) {\n let current = keywords[i]\n let { stemmedTerm } = current\n // iterate over remaining terms in search for parents\n let searchForParent = SearchTermExtractor.largestParent(keywords.map(kw => kw.stemmedTerm), stemmedTerm, false)\n let parent = searchForParent ? keywords[searchForParent.index] : null\n // iterate over mergedKeywords in search for parents\n let candidate = parent ? parent : current\n let searchForMergedParent = SearchTermExtractor.largestParent(\n mergedKeywords.map(kw => kw.stemmedTerm), \n candidate.stemmedTerm, \n true)\n if (!searchForMergedParent) {\n mergedKeywords.push(candidate)\n }\n }\n }\n\n // 2. Select the two query terms\n let requestKeywords = mergedKeywords.slice(0, 2)\n let requestTerms = requestKeywords.map(kw => (kw.canonicalTerm || kw.originalTerms[0]))\n let keywordsString = concatStrings(requestTerms, ' ')\n let requestString = keywordsString\n // 5. Shorten the query if neccessary\n if (keywordsString.split(' ').length > 3) {\n let firstLength = requestTerms[0] ? requestTerms[0].split(' ').length : 0\n let secondLength = requestTerms[1] ? requestTerms[1].split(' ').length : 0\n let diff = firstLength - secondLength\n if (diff < 0) {\n requestString = requestTerms[1]\n } else if (diff > 0 || (diff == 0 && requestTerms[0])) {\n requestString = requestTerms[0]\n }\n }\n // 6. Phew.\n return requestString.toLowerCase()\n }", "function handleQuery () {\n var searchText = $scope.searchText,\n term = searchText.toLowerCase();\n //-- if results are cached, pull in cached results\n if (!$scope.noCache && cache[ term ]) {\n ctrl.matches = cache[ term ];\n updateMessages();\n } else {\n fetchResults(searchText);\n }\n\n ctrl.hidden = shouldHide();\n }", "function reQuery() {\n\n // Update our different OData strings\n updateFilterString();\n updateSortString();\n\n // Refresh the visual collection, resulting in the table refreshing\n properties.visualCollection.refresh();\n\n }", "function LQuery(){}", "function prepareSuggestions(searchTerm) {\r\n term = searchInput.value;\r\n searchDiv.classList.remove('inactive');\r\n iconSearchActive.classList.remove('nonvisible');\r\n iconClosedSearch.classList.add('active');\r\n iconClosedSearch.addEventListener('click', clearSearch);\r\n newSuggest(searchTerm).then((suggestedListApi) => {\r\n suggestionList.textContent = \"\";\r\n suggestedListApi.data.map(function (suggestedTerm) {\r\n let li = document.createElement(\"li\");\r\n spanTextSuggestion = document.createElement(\"span\");\r\n spanTextSuggestion.innerHTML = suggestedTerm.name;\r\n suggestionList.appendChild(li).appendChild(spanTextSuggestion);\r\n li.addEventListener('click', function () {\r\n term = suggestedTerm.name;\r\n showSuggestions()\r\n });\r\n iconSearchActive.removeEventListener('click', showSuggestions);\r\n iconSearchActive.addEventListener('click', showSuggestions);\r\n });\r\n })\r\n suggestionDiv.classList.remove('nonvisible');\r\n}", "function updateAdanvceSearch(){\n if(typeof searchPnt != \"undefined\"){\n whereClause = searchFilters.buildWhereClause();\n findOptimalSearchRadius(providerFS,searchPnt,whereClause)\n }\n }", "function createSQL(term) {\n return \"select A,B,C,D,E,F,M,L,V,W,G,H,I,J,K,X,Q,R,S,T where (A like '%\" + term + \"%') or (B like '\" + term + \"') or (lower(C) like lower('%\" + term + \"%')) or (lower(D) like lower('%\" + term + \"%')) or (lower(E) like lower('%\" + term + \"%')) or (F like '%\" + term + \"%') or (lower(O) like lower('%\" + term + \"%')) order by A desc, B asc\";\n}" ]
[ "0.6536917", "0.59518266", "0.5936315", "0.59145284", "0.59036714", "0.5865288", "0.58625966", "0.5832799", "0.580762", "0.5793396", "0.57455236", "0.5742793", "0.5720012", "0.5669403", "0.5638431", "0.5627923", "0.5602946", "0.55935067", "0.5590696", "0.5549595", "0.55457467", "0.5537959", "0.55360895", "0.5519021", "0.54962736", "0.5492304", "0.54743886", "0.54524213", "0.54309636", "0.5402297" ]
0.6718893
0
Prepare the query for findAddressCandidates
_getQueryFindAddressCandidates(data) { if (isString(data)) return { SingleLine: data }; if (isObject(data)) return data; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_getQueryGeocodeAddresses(data) {\n const records = [];\n data.forEach((address, index) => {\n if (isString(address)) {\n records.push({\n attributes: {\n OBJECTID: index,\n SingleLine: address,\n },\n });\n } else {\n // allow user to specify their own OBJECTIDs\n if (!address.OBJECTID) {\n address.OBJECTID = index;\n }\n records.push({\n attributes: address,\n });\n }\n });\n return { addresses: { records } };\n }", "function fillInAddressSource() {\n var coords = sourceQuery.getPlace().geometry.location;\n lat = coords.lat();\n lon = coords.lng();\n}", "function prepareQuery(fields) {\n const query = Object.entries(fields).map(([id, field]) => {\n return formQuery({\n id: id,\n params: [\n STZIL_CONTRACT_ADDRESS,\n field,\n []\n ]\n });\n });\n\n //console.log(query)\n return query;\n}", "async getAddresses() {\n // check for empty city value since deleting city value character by character will trigger the debounceAddress\n // city value could be empty when this function run\n // so this extra check will fix the bug of showing addresses list when there is no city name\n if (this.state.city.trim()) {\n try {\n this.setState({showLoader: true})\n const {data} = await axios.get(\n `https://api.teleport.org/api/cities/?search=${this.state.city}`\n )\n\n // populate addresses and show them if matching cities exist\n if (!isEmpty(data) && !isUndefined(data) && data.count > 0) {\n const results = data._embedded['city:search-results'].map(result => ({\n cityName: result.matching_full_name,\n cityId: result._links['city:item'].href.split('/')[5]\n }))\n // results is an array of `address` objects with cityName and cityId properties\n this.setState({\n addresses: results,\n showCaret: true,\n showAddresses: true,\n errorMessage: ''\n })\n } else {\n this.setState({showAddresses: false})\n this.handleError(\n 'No matching cities found. Try searching with a valid city name!'\n )\n }\n } catch (error) {\n this.handleError(error)\n } finally {\n this.setState({showLoader: false})\n }\n } else {\n this.clearState()\n }\n }", "function prepareAddress(data) {\n const addressComponents = {\n city: null,\n region: null,\n country: null,\n location: {\n locationPoint: prepareLocation(data)\n },\n };\n data.address_components.forEach((addressComponent) => {\n switch (addressComponent.types[0]) {\n case 'locality':\n addressComponents.city = addressComponent.long_name;\n break;\n case 'administrative_area_level_2':\n addressComponents.region = addressComponent.long_name;\n break;\n case 'administrative_area_level_1':\n /**\n * Skip if already added region in block bellow\n */\n addressComponents.region = (addressComponents.region !== null) ?\n addressComponents.region :\n addressComponent.long_name;\n break;\n case 'country':\n addressComponents.country = addressComponent.long_name;\n break;\n default:\n break;\n }\n });\n return addressComponents;\n}", "oneAddress(_, args) {return queryOneAddress(args.id)}", "function addressSearch() {\n const locationIQKey = \"c8f4ef91fa2470\";\n const commonAddressComponents = [\n \"country\",\n \"state\",\n \"county\",\n \"postcode\",\n \"city\",\n \"road\"\n ];\n const minimumCommonComponents = 4;\n let fetchReturnedAddresses = false;\n\n /**\n * LocationIQ element that represents the likelihood the returned address\n * matches its search parameters. Ordered from greatest likelihood to\n * least likelihood\n */\n const matchCodes = [\n \"exact\",\n \"fallback\",\n \"approximate\"\n ];\n\n /**\n * LocationIQ element that represents the granularity of the returned\n * address. Ordered from most granular to least granular.\n */\n const matchLevels = [\n \"venue\",\n \"building\",\n \"street\",\n \"neighbourhood\",\n \"island\",\n \"borough\",\n \"city\",\n \"county\",\n \"state\",\n \"country\",\n \"marine\",\n \"postalcode\"\n ];\n\n /**\n * Update DOM elements to reflect the search for addresses has ended\n */\n function endSearch() {\n MicroModal.show(\"addresses-modal\");\n\n // Remove \"Searching...\" message\n $(\".find-address\").text(\"Find Address\");\n\n $(\".find-address\").prop(\"disabled\", false);\n }\n\n /**\n * Handle the provided error\n */\n function handleError(error) {\n const errorMessage = `An error occurred while finding addresses: ${error.message}`;\n console.log(errorMessage);\n $(\".find-addresses-status\").text(errorMessage);\n MicroModal.show(\"addresses-modal\");\n }\n\n /**\n * Convert the provided address component to a readable format\n */\n function formatAddressComponent(component) {\n let formattedComponent = component.replace(/[-_]/g, \" \");\n\n // Capitalize the first letter of each word\n const componentWords = formattedComponent.toLowerCase().split(\" \");\n formattedComponent = componentWords.map((word) => {\n return word.charAt(0).toUpperCase() + word.substring(1);\n }).join(' ');\n\n return formattedComponent;\n }\n\n /**\n * Convert the provided address components to a string\n */\n function convertAddressToHTML({common, uncommon}) {\n let htmlParts = [];\n\n // Convert common components to HTML\n htmlParts.push(`Country: ${common.country}`);\n if (common.state != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">State: ${common.state}</span>\n `);\n }\n if (common.county != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">County: ${common.county}</span>\n `);\n }\n if (common.postcode != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">\n Postal Code: ${common.postcode}\n </span>\n `);\n }\n if (common.city != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">City: ${common.city}</span>\n `);\n }\n if (common.road != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">Road: ${common.road}</span>\n `);\n }\n\n /**\n * Convert uncommon components to HTML if there aren't enough common\n * components to display\n */\n if (common.length < minimumCommonComponents) {\n for(const component in uncommon) {\n let formattedComponent = formatAddressComponent(component);\n htmlParts.push(`\n <span class=\"address-component\">${formattedComponent}: ${uncommon[component]}</span>\n `);\n }\n }\n\n return htmlParts.join(\"\");\n }\n\n /**\n * Display the provided addresses in the found addresses modal\n */\n function displayAddresses(addressOptions) {\n // Display each of the address options\n if (addressOptions.length > 0) {\n for(const addressOption of addressOptions) {\n const htmlElements = [];\n const radioInput = `\n <input\n type=\"radio\"\n id=\"${addressOption.placeID}\"\n class=\"address-option\"\n name=\"address\"\n value=\"${addressOption.lat},${addressOption.lon}\">\n `;\n htmlElements.push(radioInput);\n\n const customRadioInput = '<span class=\"custom-radio\"></span>';\n htmlElements.push(customRadioInput);\n\n let addressAsText = convertAddressToHTML(addressOption.addressComponents);\n const labelTag = `\n <label for=\"${addressOption.placeID}\" class=\"address-option-label\">\n ${addressAsText}\n </label>\n `;\n htmlElements.push(labelTag);\n\n // Also include a break tag\n htmlElements.push(\"<br>\");\n\n const htmlContent = `\n <div class=\"address-option-div\">\n ${htmlElements.join(\"\\n\")}\n </div>\n `;\n $(\".select-address\").append(htmlContent);\n }\n\n // Set the address options to be required\n $(\".address-option\").first().attr(\"required\", true);\n\n // Create the submit button\n $(\".select-address\").append(`\n <button type=\"submit\" class=\"submit-button address-submit\">\n Submit Selected Address\n </button>\n `);\n } else {\n /**\n * Either the fetch didn't return any addresses, or all of the\n * returned addresses were invalid\n */\n const message = \"No addresses were found\";\n console.log(message);\n $(\".find-addresses-status\").text(message);\n }\n }\n\n /**\n * Find the best address of the provided addresses\n */\n function getBestAddress(addresses) {\n // Keep only the addresses with the best match code\n /**\n * I haven't found any test data with duplicate addresses that have\n * different match codes. Until I find any such data, there's no need\n * to compare match codes\n */\n\n // Keep only the addresses with the most granular match level\n /**\n * I haven't found any test data with duplicate addresses that have\n * different match levels. Until I find any such data, there's no\n * need to compare match levels\n */\n\n /**\n * If there are still multiple addresses left, then they're\n * equal-enough; return the first one\n */\n return addresses[0];\n }\n\n /**\n * Return a new array with the following: From each set of addresses that\n * have identical common address components, remove all addresses except\n * for the best address\n */\n function removeDuplicates(allAddressData) {\n const uniqueAddressData = [];\n for(const addressData of allAddressData) {\n /**\n * Check if an equivalent address option already exists in the\n * filtered array\n */\n const existingDataIndex = uniqueAddressData.findIndex((data) => {\n return _.isEqual(data.addressComponents.common, addressData.addressComponents.common);\n });\n\n // Found a duplicate address\n if (existingDataIndex > -1) {\n const existingData = uniqueAddressData[existingDataIndex];\n console.log(`Address ${addressData.placeID} has an identical match: address ${existingData.placeID}`);\n\n // Keep the better of the two addresses\n const bestAddress = getBestAddress([addressData, existingData]);\n console.log(`----Keeping address ${bestAddress.placeID} and removing address ${existingData.placeID}`);\n uniqueAddressData[existingDataIndex] = bestAddress;\n } else {\n // Not a duplicate address\n uniqueAddressData.push(addressData);\n }\n }\n\n return uniqueAddressData;\n }\n\n /**\n * Return an object containing the uncommon address components of the\n * provided components\n */\n function getUncommonComponents(addressComponents) {\n const returningComponents = {};\n for(const component in addressComponents) {\n if (!commonAddressComponents.includes(component)) {\n returningComponents[component] = addressComponents[component];\n }\n }\n\n return returningComponents;\n }\n\n /**\n * Return an object containing the common address components of the\n * provided components\n */\n function getCommonComponents(addressComponents) {\n const returningComponents = {};\n for(const component in addressComponents) {\n if (commonAddressComponents.includes(component)) {\n returningComponents[component] = addressComponents[component];\n }\n }\n\n return returningComponents;\n }\n\n /**\n * Return true if the provided address refers to an area that is too large\n */\n function addressIsTooLarge(addressJson) {\n // island, borough, city, county, state, country, marine, postalcode\n const unacceptableMatchLevels = matchLevels.slice(-8);\n\n /**\n * The match level is a LocationIQ API property that represents the\n * granularity of the address\n */\n const matchLevel = addressJson.matchquality.matchlevel;\n return unacceptableMatchLevels.includes(matchLevel);\n }\n\n /**\n * Return true if the provided address is unlikely to match the search\n * parameters\n */\n function addressIsUnlikely(addressJson) {\n // approximate\n const unacceptableMatchCodes = matchCodes.slice(-1);\n\n /**\n * The match code is a LocationIQ API property that represents the\n * likelihood the returned address matches its search parameters\n */\n const matchCode = addressJson.matchquality.matchcode;\n return unacceptableMatchCodes.includes(matchCode);\n }\n\n /**\n * Return true if the provided address passes all the tests\n */\n function addressIsValid(addressJson) {\n // Fail the address if it's missing a country\n if (addressJson.address.country == undefined) {\n console.log(`Removing address ${addressJson.place_id}: it is missing its country`);\n return false;\n }\n\n /**\n * Fail the address if its probability of matching the search\n * parameters is too low\n */\n if (addressIsUnlikely(addressJson)) {\n console.log(`Removing address ${addressJson.place_id}: it is unlikely to match the user's search parameters`);\n return false;\n }\n\n if (addressIsTooLarge(addressJson)) {\n console.log(`Removing address ${addressJson.place_id}: it refers to an area that is too large`);\n return false;\n }\n\n return true;\n }\n\n /**\n * Return an array containing the relevant data from each of the provided\n * addresses that are valid\n */\n function getRelevantAddressData(addressesJson) {\n const relevantData = [];\n\n // Iterate through the returned address options\n if (fetchReturnedAddresses) {\n for(const addressJson of addressesJson) {\n if (addressIsValid(addressJson)) {\n const addressOption = {};\n\n // Make a copy of the addressJson's address object\n const addressComponentsCopy = { ...addressJson.address };\n\n // Remove extra address component fields\n if (addressComponentsCopy.country_code != undefined) {\n delete addressComponentsCopy.country_code;\n }\n\n const commonComponents = getCommonComponents(addressComponentsCopy);\n const uncommonComponents = getUncommonComponents(addressComponentsCopy);\n addressOption.addressComponents = {\n common: commonComponents,\n uncommon: uncommonComponents\n };\n\n addressOption.lat = addressJson.lat;\n addressOption.lon = addressJson.lon;\n addressOption.placeID = addressJson.place_id;\n\n relevantData.push(addressOption);\n }\n }\n }\n\n return relevantData;\n }\n\n /**\n * Fetch JSON address data from the provided LocationIQ URL, handle if no\n * addresses are returned, and handle if some other problem occurs with\n * the request\n */\n function fetchCoordinatesJson(url) {\n return fetch(url).then((response) => {\n if (response.ok) {\n fetchReturnedAddresses = true;\n return response.json();\n } else if (response.status === 404) {\n // No addresses were returned\n return response.json();\n } else {\n throw Error(response.statusText);\n }\n });\n }\n\n /**\n * Use the LocationIQ API to convert the provided address into latitude\n * and longitude coordinates, then fetch the wildlife data\n */\n function getLatLonCoordinates(address) {\n const baseURL = \"https://us1.locationiq.com/v1/search.php\";\n const params = {\n key: locationIQKey,\n street: address.street,\n city: address.city,\n county: address.county,\n state: address.state,\n country: address.country,\n postalCode: address.postalCode,\n format: \"json\",\n normalizecity: \"1\",\n addressdetails: \"1\",\n matchquality: \"1\",\n limit: \"50\"\n };\n const queryParams = formatQueryParams(params);\n const url = baseURL + \"?\" + queryParams;\n console.log(`Fetching data from the LocationIQ API: ${url}`);\n\n return fetchCoordinatesJson(url);\n }\n\n /**\n * Reset all variables and DOM elements that are left over from previous\n * address searches\n */\n function resetEnvironment() {\n fetchReturnedAddresses = false;\n\n // Clear previous errors\n $(\".find-addresses-status\").text(\"\");\n\n // Clear previous addresses results\n $(\".select-address\").empty();\n }\n\n /**\n * Create an event listener for when the \"Find Address\" button is clicked\n */\n function handleFindAddressClick() {\n $(\".search-form.address\").submit((event) => {\n event.preventDefault();\n\n console.log(\"Starting address search\");\n\n $(\".find-address\").prop(\"disabled\", true);\n\n resetEnvironment();\n\n // Grab user input\n const userAddress = {};\n userAddress.street = $(\"#search-street\").val();\n userAddress.city = $(\"#search-city\").val();\n userAddress.county = $(\"#search-county\").val();\n userAddress.postalCode = $(\"#search-postal-code\").val();\n\n userAddress.country = $(\"#search-country\").val();\n if (userAddress.country === \"United States of America\") {\n userAddress.state = $(\"#search-state\").val();\n } else {\n /**\n * Ignore the \"US State or Territory\" field if the country\n * isn't the United States of America\n */\n userAddress.state = \"\";\n }\n\n // Tell the user the search is running\n $(\".find-address\").text(\"Searching...\");\n\n getLatLonCoordinates(userAddress)\n .then((addressesJson) => {\n console.log(\"----------Addresses found----------\");\n console.log(addressesJson);\n\n const allAddressData = getRelevantAddressData(addressesJson);\n const uniqueAddressData = removeDuplicates(allAddressData);\n return uniqueAddressData;\n })\n .then(displayAddresses)\n .catch(handleError)\n .finally(endSearch);\n });\n }\n\n /**\n * Enable the user to fill out the wildlife search form\n */\n function enableWildlifeSearch() {\n /**\n * Enable all form elements in the wildlife search except for the\n * \"Found Address\" field\n */\n $(\".wildlife-form *:disabled\").not(\"#found-address\")\n .removeAttr(\"disabled\");\n\n /**\n * Add the \"checked\" class to all custom checkboxes that are\n * overlaying checked checkboxes\n */\n const customCheckboxes = $(\".custom-checkbox\");\n for(const customCheckbox of customCheckboxes) {\n const checkedRealCheckbox = $(customCheckbox)\n .siblings('input[type=\"checkbox\"]:checked');\n if (checkedRealCheckbox.length > 0) {\n $(customCheckbox).addClass(\"checked\");\n }\n }\n\n /**\n * Remove the \"disabled\" class from the custom checkboxes for the\n * wildlife types\n */\n $(\".custom-checkbox\").removeClass(\"disabled\");\n \n console.log(\"Wildlife search enabled\");\n }\n\n /**\n * Create an event listener for when the address is submitted from the\n * modal\n */\n function handleSubmitAddress() {\n $(\".select-address\").submit((event) => {\n event.preventDefault();\n\n // Get the selected coordinates\n const coordinates = $('.select-address input[name=\"address\"]:checked')\n .val();\n console.log(`Selected address coordinates: ${coordinates}`);\n\n // Store the selected coordinates in the \"Found Address\" field\n $(\"#found-address\").val(coordinates);\n\n // Close the modal\n MicroModal.close(\"addresses-modal\");\n\n // Enable the wildlife search form, if it's disabled\n if ($(\".wildlife-submit:disabled\").length > 0) {\n enableWildlifeSearch();\n }\n });\n }\n\n handleFindAddressClick();\n handleSubmitAddress();\n}", "function initAutocomplete() {\n sourceQuery = new google.maps.places.Autocomplete((document.getElementById('source')),{\n types: ['geocode']\n });\n destinationQuery = new google.maps.places.Autocomplete((document.getElementById('destination')),{\n types: ['geocode']\n });\n sourceQuery.addListener('place_changed', fillInAddressSource);\n}", "function addQueryBounds (parsed) {\n let where = parsed.where[0].triples\n let objectVariables = getObjectVariables(parsed)\n for (let [v] of objectVariables) {\n let idVar = `?__${v.slice(1)}`\n /*\n where.push({\n subject: idVar,\n predicate: consts.graph.seedpod.preds.HEAD,\n object: v\n })\n */\n }\n }", "function onQueryAddress() {\n var invoicingAddress = $(\"#query-invoicing-address\").val();\n\n console.log(\"Fetching data from\", invoicingAddress);\n\n var vatId = contract.getVatIdByAddress(invoicingAddress);\n if(!vatId) {\n setErrorResult(\"No company found for invoicing address \" + invoicingAddress + \". Use OVT:xxx or IBAN:xxx prefix when typing in the address\")\n }\n\n showCompany(vatId);\n }", "function getAllAddresses (custnumber, callback) {\n var sql =\n `(SELECT \n 0 AS autoid,\n custnumber,\n altnum,\n :custnumber AS belongsto,\n 1 AS defaultaddress_b,\n 1 AS defaultaddress_s,\n 1 AS defaultaddress_m,\n firstname,\n lastname,\n company,\n address1,\n address2,\n city,\n LTRIM(RTRIM(state)) AS state,\n zip,\n mailinglist_om.country AS country_code,\n country.country AS country_name,\n email,\n phone,\n phone2,\n norent\n FROM mailinglist_om INNER JOIN country ON mailinglist_om.country = country.countrycode\n WHERE \n custnumber = :custnumber OR altnum = :custnumber)\n\n UNION\n\n (SELECT \n autoid,\n custnumber,\n altnum,\n belongsto,\n defaultaddress_b,\n defaultaddress_s,\n defaultaddress_m,\n firstname,\n lastname,\n company,\n address1,\n address2,\n city,\n LTRIM(RTRIM(state)) AS state,\n zip,\n addressbook.country AS country_code,\n country.country AS country_name,\n email,\n phone,\n phone2,\n 0 AS norent\n FROM addressbook INNER JOIN country ON addressbook.country = country.countrycode\n WHERE \n belongsto = :custnumber)`;\n\n var params = { custnumber: custnumber };\n\n photoeye\n .query(sql, { replacements: params })\n .spread(function(results, metadata) {\n callback(misc.getAddressesInfo(results));\n });\n}", "resolveQuery() {\n\t\tthis.resultData = this.query.run(this.collection, this.dataProvider.data());\n\t\tthis.resultValid = true;\n\t}", "function GeoQuery(q)\n{\n\tvar addnew = true;\n\n\tfor(var i in geoquery) //eliminate redundancy\n\t{\n\t\tif(geoquery[i].place == q.place)\n\t\t{\n\t\t\tgeoquery[i].addresses.push(q.addresses[0]);\n\t\t\taddnew = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(addnew) geoquery.push(q);\n}", "function getAllCandidates() {\n var obj = {\n p: 1,\n ps: $scope.candidateListSumary.Pagination.TotalCount,\n };\n\n CandidatePoolService.getCandidatesByNetwork(obj).then(function(res) {\n $scope.AllCandidates = res;\n });\n }", "function initAutoComplete() {\n\n var addrComplete = new google.maps.places.Autocomplete(addr);\n\n addrComplete.addListener('place_changed', fillInAddress);\n\n var componentForm = {\n street_number: 'short_name',\n route: 'long_name',\n locality: 'long_name',\n administrative_area_level_1: 'short_name',\n country: 'long_name',\n postal_code: 'short_name'\n };\n\n function fillInAddress() {\n var place = addrComplete.getPlace();\n $('#address').val(\"\").css({ 'background-color': '#ffffff'});\n $('#city').val(\"\").css({ 'background-color': '#ffffff'});;\n $('#state').val(\"\").css({ 'background-color': '#ffffff'});;\n $('#zipcode').val(\"\").css({ 'background-color': '#ffffff'});;\n var street = \"\";\n\n for (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (componentForm[addressType]) {\n var val = place.address_components[i][componentForm[addressType]];\n console.log(addressType, val)\n switch (addressType) {\n case \"street_number\":\n street = val;\n break;\n case \"route\":\n val = street+val\n $('#address').val(val).css({ 'background-color': '#F3FEFF'})\n break;\n case \"locality\":\n $('#city').val(val).css({ 'background-color': '#F3FEFF'})\n break;\n case \"administrative_area_level_1\":\n $('#state').val(val).css({ 'background-color': '#F3FEFF'})\n break;\n case \"postal_code\":\n $('#zipcode').val(val).css({ 'background-color': '#F3FEFF'})\n break;\n }\n }\n }\n\n }\n }", "search (query) {\n\t\t// Store lat/lng of locality to use in this url (focus.point.lat, focus.point.lon)\n \t\t//const endpoint = `https://search.mapzen.com/v1/autocomplete?text=${query}&api_key=${this.props.config.mapzen.apiKey}&focus.point.lat=${this.props.coordinates[0]}&focus.point.lon=${this.props.coordinates[1]}&layers=venue`\n \t\tconst placetype = this.state.placetype\n \t\tconst endpoint = `https://whosonfirst-api.mapzen.com/?method=whosonfirst.places.search&api_key=${this.props.config.mapzen.apiKey}&q=${query}&${placetype}=${this.props.source.id}&placetype=venue&per_page=100&extras=geom:latitude,geom:longitude,sg:,addr:full,wof:tags`\n \t\tthis.throttleMakeRequest(endpoint)\n\t}", "function handleSearchAddressRequest(atts) {\n\t\t\tvar address = atts.address;\n\t\t\tvar lastSearchResults = atts.lastSearchResults;\n\t\t\tlastSearchResults = lastSearchResults ? lastSearchResults.split(' ') : null;\n\n\t\t\tui.searchAddressChangeToSearchingState(true);\n\n\t\t\tif (lastSearchResults) {\n\t\t\t\tmap.clearMarkers(map.SEARCH, lastSearchResults);\n\t\t\t}\n\n\t\t\tsearchAddress.requestCounter++;\n\t\t\tsearchAddress.find(address, handleSearchAddressResults, handleSearchAddressFailure, preferences.language);\n\t\t}", "prepareRequestParams(options) {\n let requestParams;\n const searchKeys = _.split(options.searchKey, ','), matchModes = _.split(options.matchMode, ','), formFields = {};\n _.forEach(searchKeys, (colName, index) => {\n formFields[colName] = {\n value: options.query,\n logicalOp: 'AND',\n matchMode: matchModes[index] || matchModes[0] || 'startignorecase'\n };\n });\n requestParams = {\n filterFields: formFields,\n page: options.page,\n pagesize: options.limit || options.pagesize,\n skipDataSetUpdate: true,\n skipToggleState: true,\n inFlightBehavior: 'executeAll',\n logicalOp: 'OR',\n orderBy: options.orderby ? _.replace(options.orderby, /:/g, ' ') : ''\n };\n if (options.onBeforeservicecall) {\n options.onBeforeservicecall(formFields);\n }\n return requestParams;\n }", "function getQueryURL(address) {\n let queryURL = \"https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/geocode/json?address=\" + address + \"&key=AIzaSyD9y2VmteYeNrLjnmKgP8l1j0DIp2qex9Y\"\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n\n // lat and long are global variables that are set here on the \n // original geocode query\n lat = response.results[0].geometry.location.lat;\n lng = response.results[0].geometry.location.lng;\n\n // newQueryURL is the url that will be used in the places ajax call\n newQueryURL = `https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=` + lat + `,` + lng + `&radius=1500&type=restaurant&key=AIzaSyD9y2VmteYeNrLjnmKgP8l1j0DIp2qex9Y`\n });\n}", "function setParameters(origin, address, filter, location){\n ORIGIN_LIST = origin;\n if (address[0] == \"\") { //if no destinations in database\n ADDRESS_LIST = 0;\n }\n else {\n ADDRESS_LIST = address;\n }\n LOCATION_FILTER = filter;\n LOCATION_LIST = location;\n}", "function bookingAutocomplete() {\n // setup autcomplete to input fields and set location search/return values\n var input = document.getElementById('initalCollectionPoint');\n var options = {\n componentRestrictions: {country: \"za\"}\n };\n var autocomplete = new google.maps.places.Autocomplete(input, options);\n autocomplete.setFields(['adr_address', 'geometry']);\n\n}", "search(){\n\t\t\t\tlet serviceAddrList = _.cloneDeep(this.state.serviceAddrList)\n\t\t\t\tif(!CommonUtil.isServcieAddrEmpty(this.state.currentAddress,serviceAddrList)){\n\t\t\t\t\t\tserviceAddrList.push(this.state.currentAddress)\n\t\t\t\t}\n\t\t\t\tthis.setState({serviceAddrList})\n\t\t\t\tif(this.validateForm(serviceAddrList)){\n\t\t\t\t\t\tthis.setState({isError:false})\n\t\t\t\t\t\tthis.setState({isProcessing:true,showResult:false})\n\t\t\t\t\t\tthis.props.actions.lookupESIIDsByAddr({serviceAddressList:serviceAddrList});\n\t\t\t\t\t\tthis.setState({isAjaxCalled:true});\n\t\t\t\t\t\t//this.setState({serviceAddrList:[]});//emptying the address list after the call.\n\t\t\t\t}else{\n\t\t\t\t\t\tthis.setState({isError:true, errorMessage:\"StreetNumber and StreetName is required for the search. Please enter required fields.\"})\n\t\t\t\t}\n }", "function initialize() {\n searchPlace = new google.maps.places.Autocomplete(document.getElementById('searchPlaces'),\n {types: ['geocode'], componentRestrictions: {country: 'in'}});\n placeA = new google.maps.places.Autocomplete(document.getElementById('searchDirectionA'),\n {types: ['geocode'], componentRestrictions: {country: 'in'}});\n placeA.addListener('place_changed', function() {\n var place = placeA.getPlace();\n if (!place.geometry) {\n console.log('Place Not Found, You Entered: ' + place.name);\n directionA = [];\n return;\n }\n directionA = [place.geometry.location.lat(), place.geometry.location.lng(), place.formatted_address];\n });\n }", "_getQueryGeocode(data, params) {\n return {\n text: data,\n outFields: params.outFields || '*',\n maxLocations: params.maxLocations || 10,\n };\n }", "function querySearch (query) {\n\t \t$scope.getPrincipals(query);\n\n\t var results = query ? $scope.emailsList.filter( createFilterFor(query) ) : $scope.emailsList,\n\t deferred;\n\t if ($scope.simulateQuery) {\n\t deferred = $q.defer();\n\t $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);\n\t return deferred.promise;\n\t } else {\n\t \tvar emailListVar = [];\n\n\t \tangular.forEach(results, function(email) {\n\t \t \temailListVar.push({\"email\" : email})\n\t \t});\n\t \tconsole.log('emailListVar',emailListVar);\n\t return emailListVar;\n\t }\n\t }", "function filterCandidates(){\n\t\t//updates district filter\n\t\tif (districtSelector.property(\"selectedIndex\") > 0) {\n\t\t\tcurrentDistrict = areas[districtSelector.property(\"selectedIndex\")-1];\n\t\t}\n\t\t//updates name and candidate number filter\n\t\tvar searchValue = searchInput.property(\"value\").toLowerCase();\n\t\tvar searchArray = searchValue.split(\" \");\n\n\t\t//Let the filtering begin!\n\t\tcandidates\n\t\t\t.attr(\"display\", function(d) {\n\t\t\t\t//district filter\n\t\t\t\tif (currentDistrict === ALLDISTRICTS) return \"inline\";\n\t\t\t\telse if (currentDistrict && d.district !== currentDistrict) return \"none\";\n\n\t\t\t\t//party filter\n\t\t\t\tif(!partyVisibility[d.party] || !partyVisibility[d.segment]) return \"none\";\n\n\t\t\t\t//if something in the search box then also filter with that\n\t\t\t\tif (searchValue) {\n\t\t\t\t\tfor (var i = 0; i < searchArray.length; i++) {\n\t\t\t\t\t\tif (d.name.toLowerCase().indexOf(searchArray[i].trim()) < 0){\n\t\t\t\t\t\t\treturn \"none\";\n\t\t\t\t\t\t} \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t}", "function makeNewQuery(query) {\n return new Promise(function(resolve, reject) {\n var db = require('../database');\n\n //search with city coordinates\n const statement = getSqlStatement(query);\n var sqlAll = \"SELECT * FROM listing \";\n var sqlCount = \"SELECT COUNT(*) AS 'count' FROM listing \";\n if (statement.countStatement !== \"\"){\n sqlAll += \"WHERE \";\n sqlCount += \"WHERE \";\n }\n sqlAll += statement.listingStatement + \";\";\n sqlCount += statement.countStatement + \";\";\n // console.log(sqlAll);\n const final = {};\n db.query(sqlCount, function (error, result) {\n if (error) reject('some err getting total count');\n final.listings_count = result[0].count;\n });\n db.query(sqlAll, function (error, listings) {\n if (error) reject('some err getting listings');\n final.listings = listings;\n resolve(final);\n });\n\n });\n}", "function collect_query_info() {\n let query = {};\n\n let name = get_name_input();\n if (name !== null && name !== \"\") {\n query['sdn_name'] = name;\n }\n\n let type = get_type_select()\n if (type !== empty_type_field) {\n query['sdn_type'] = type;\n }\n\n let program = get_program_select()\n if (program !== empty_program_field) {\n query['program'] = program;\n }\n\n $.each(get_search_row_ids(), (index, row_id) => {\n let select = get_row_select(row_id);\n let input = get_row_input(row_id);\n if (select != empty_select && input !== null && input !== \"\") {\n query[select] = input;\n }\n });\n\n query.size = 50;\n query.from = 0;\n\n window.lastQuery = query;\n\n if (!$.isEmptyObject(query)) {\n return query;\n }\n else {\n return null;\n }\n}", "address(address) {\n this.query.address = address;\n return this;\n }", "function BindSearchToAddress()\n{\n var options =\n {\n types: ['geocode']\n };\n\n var input = document.getElementById('searchByAddressText');\n\n autocomplete = new google.maps.places.Autocomplete(input, options);\n //autocomplete.setBounds(map.getBounds());\n\n google.maps.event.addListener(autocomplete, 'place_changed', function()\n {\n selectedPlace = autocomplete.getPlace();\n\n if (selectedPlace != null)\n {\n closeInfoBox(infoBox);\n\n var postalCode = '';\n\n if (selectedPlace.address_components != undefined)\n {\n for (var i in selectedPlace.address_components)\n {\n if (selectedPlace.address_components[i].types[0] == \"postal_code\")\n {\n postalCode = selectedPlace.address_components[i].short_name;\n CreateCookie('SearchKeyword', 'A_' + $('#searchByAddressText').val() + '_' + postalCode);\n SelectPMAOrClosestDealer(postalCode);\n return;\n }\n }\n\n }\n else\n {\n SelectPMAFromAddress($('#searchByAddressText').val());\n return;\n }\n\n // if a postalCode is not found, then try to zoom that map to the location\n if (selectedPlace != null)\n {\n //Handle previously selected dealer, by closing infobox and changing icon\n closeInfoBox(infoBox);\n\n if (selectedPlace.geometry.viewport)\n {\n map.fitBounds(selectedPlace.geometry.viewport);\n }\n else\n {\n map.setCenter(selectedPlace.geometry.location);\n map.setZoom(10);\n }\n }\n }\n });\n}" ]
[ "0.58243704", "0.57239884", "0.5703757", "0.54517096", "0.53788304", "0.534403", "0.5332851", "0.53037864", "0.53025126", "0.52685165", "0.52350086", "0.52340424", "0.52103925", "0.5157994", "0.5131981", "0.51285034", "0.51061934", "0.5088926", "0.5086893", "0.50531393", "0.50427544", "0.5005948", "0.5001433", "0.49748722", "0.4920441", "0.49117306", "0.49104473", "0.49075362", "0.4889605", "0.48879138" ]
0.6143717
0
Prepare the query for geocodeAddresses
_getQueryGeocodeAddresses(data) { const records = []; data.forEach((address, index) => { if (isString(address)) { records.push({ attributes: { OBJECTID: index, SingleLine: address, }, }); } else { // allow user to specify their own OBJECTIDs if (!address.OBJECTID) { address.OBJECTID = index; } records.push({ attributes: address, }); } }); return { addresses: { records } }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fillInAddressSource() {\n var coords = sourceQuery.getPlace().geometry.location;\n lat = coords.lat();\n lon = coords.lng();\n}", "_getQueryGeocode(data, params) {\n return {\n text: data,\n outFields: params.outFields || '*',\n maxLocations: params.maxLocations || 10,\n };\n }", "function codeAddress(fromDb) {\n fromDb.forEach(data => {\n let address = data.address;\n address.trim()\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == 'OK') {\n map.setCenter(results[0].geometry.location);\n map.getCenter().lat()\n let points = {}\n points.id = data.id\n points.lat = map.getCenter().lat();\n points.lng = map.getCenter().lng();\n //send the new data to function\n updateAddressWithLatLng(points)\n \n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n })\n }", "function prepareAddress(data) {\n const addressComponents = {\n city: null,\n region: null,\n country: null,\n location: {\n locationPoint: prepareLocation(data)\n },\n };\n data.address_components.forEach((addressComponent) => {\n switch (addressComponent.types[0]) {\n case 'locality':\n addressComponents.city = addressComponent.long_name;\n break;\n case 'administrative_area_level_2':\n addressComponents.region = addressComponent.long_name;\n break;\n case 'administrative_area_level_1':\n /**\n * Skip if already added region in block bellow\n */\n addressComponents.region = (addressComponents.region !== null) ?\n addressComponents.region :\n addressComponent.long_name;\n break;\n case 'country':\n addressComponents.country = addressComponent.long_name;\n break;\n default:\n break;\n }\n });\n return addressComponents;\n}", "function searchToLatLng(request, response) {\n const locationName = request.query.data;\n const geocodeURL = `https://maps.googleapis.com/maps/api/geocode/json?address=${locationName}&key=${GEOCODE_API_KEY}`;\n client\n .query(\n `SELECT * FROM locations\n WHERE search_query =$1`,\n [locationName]\n )\n .then(sqlRes => {\n if (sqlRes.rowCount === 0) {\n console.log('from web');\n superagent\n .get(geocodeURL)\n .then(result => {\n let location = new LocationConstructor(result.body);\n location.search_query = locationName;\n client.query(\n `INSERT INTO locations(search_query,formatted_query, latitude, longitude)\n VALUES($1,$2,$3,$4)`,\n [\n location.search_query,\n location.formatted_query,\n location.latitude,\n location.longitude\n ]\n );\n response.send(location);\n })\n .catch(error => {\n console.error(error);\n response.status(500).send('Status 500: Life is hard mang.');\n });\n } else {\n response.send(sqlRes.rows[0]);\n }\n });\n}", "function getQueryURL(address) {\n let queryURL = \"https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/geocode/json?address=\" + address + \"&key=AIzaSyD9y2VmteYeNrLjnmKgP8l1j0DIp2qex9Y\"\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n\n // lat and long are global variables that are set here on the \n // original geocode query\n lat = response.results[0].geometry.location.lat;\n lng = response.results[0].geometry.location.lng;\n\n // newQueryURL is the url that will be used in the places ajax call\n newQueryURL = `https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=` + lat + `,` + lng + `&radius=1500&type=restaurant&key=AIzaSyD9y2VmteYeNrLjnmKgP8l1j0DIp2qex9Y`\n });\n}", "function turnQueryToLatLng() {\n \n var queryURL1 = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + city + \"+\" + state +\"&key=AIzaSyDVWyEiCdvzn-H3nOsn9NuJ7LfEa-zLCw8\";\n\n $.ajax({\n url: queryURL1,\n method: \"GET\"\n }).done(function(response1) {\n //create variables for latitude & longitude\n var brewSearchLat = String(response1.results[0].geometry.location.lat);\n var brewSearchLng = String(response1.results[0].geometry.location.lng);\n //set the global search variables for lat/lng\n globalLatSearch = response1.results[0].geometry.location.lat;\n globalLngSearch = response1.results[0].geometry.location.lng;\n //call the search for breweries function\n searchForBreweries(brewSearchLat, brewSearchLng);\n\n });\n }", "function searchToLatLong(request, response){\r\n let query = request.query.data;\r\n\r\n // define the search\r\n\r\n let sql = `SELECT * FROM locations WHERE search_query=$1;`;\r\n let values = [query]; //always array\r\n console.log('line 67', sql, values);\r\n\r\n //make the query fo the database\r\n client.query(sql, values)\r\n .then (result => {\r\n // did the db return any info?\r\n console.log('result from Database', result.rowCount);\r\n if (result.rowCount > 0) {\r\n response.send(result.rows[0]);\r\n }else {\r\n console.log('results', result.rows);\r\n //otherwise go get the data from the api\r\n const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${request.query.data}&key=${process.env.GEOCODE_API_KEY}`;\r\n console.log(url);\r\n superagent.get(url)\r\n\r\n\r\n .then(result => {\r\n if (!result.body.results.length) {throw 'NO DATA';}\r\n else {\r\n let location = new Location(query, result.body.results[0]);\r\n let newSQL = `INSERT INTO locations (search_query, formatted_address, latitude, longitude) VALUES ($1, $2, $3, $4) RETURNING ID;`;\r\n let newValues = Object.values(location);\r\n\r\n client.query(newSQL, newValues)\r\n .then( data => {\r\n //attach returnilng id to the location object\r\n location.id = data.rows[0].id;\r\n response.send(location);\r\n });\r\n }\r\n })\r\n .catch(err => handleError(err, response));\r\n }\r\n })\r\n}", "function geocodeAddress(reverseGeocode) {\n var address = $('input#address').val();\n\n if(geocoder && address) {\n geocoder.geocode({ 'address': address, region: 'AU' }, function(results, status) {\n if(status === google.maps.GeocoderStatus.OK) {\n // geocode was successful\n updateMarkerAddress(results[0].formatted_address);\n updateMarkerPosition(results[0].geometry.location);\n // reload map pin, etc\n initialize();\n loadRecordsLayer();\n } else {\n // TODO Handle empty results response.\n console.error(status);\n }\n });\n } else {\n initialize();\n }\n }", "function codeAddress(address) {\n\n geocoder.geocode({\n 'address': address,\n 'componentRestrictions': {\n 'country': 'US'\n }\n }, function (results, status) {\n var codedLat\n var codedLng\n\n if (status == google.maps.GeocoderStatus.OK) {\n mapCenter = results[0].geometry.location\n // map.setCenter(mapCenter);\n // map.setZoom(10);\n codedLat = results[0].geometry.location.lat();\n codedLng = results[0].geometry.location.lng();\n findResults(codedLat, codedLng);\n } else {\n console.log(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n \n}", "function loc2geocode(query, flag) {\n console.log(query);\n $http.get('https://maps.googleapis.com/maps/api/geocode/json?key='+\n GOOG_TOKEN+\"&address=\"+query.loc).success(function(data) { // hack around\n var geocode = data.results[0].geometry.location; // lat, lng\n //console.log(\"loc2geocode: \");\n //console.log(geocode);\n instLocSearch(query, geocode, flag);\n });\n }", "function GeoQuery(q)\n{\n\tvar addnew = true;\n\n\tfor(var i in geoquery) //eliminate redundancy\n\t{\n\t\tif(geoquery[i].place == q.place)\n\t\t{\n\t\t\tgeoquery[i].addresses.push(q.addresses[0]);\n\t\t\taddnew = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(addnew) geoquery.push(q);\n}", "function geocodeAddress(address) {\n\n L.esri.Geocoding.geocode().text(address).run(function (err, results) {\n\n searchLatLng = L.latLng(results.results[\"0\"].latlng.lat, results.results[\"0\"].latlng.lng);\n findNewLocation(searchLatLng);\n });\n }", "function addressFill(no_mymap = false) {\n var fullAddress = '';\n\n opcion = $('#spaceAddress').val();\n\n previous = '';\n if ($('#spaceAddress').val() != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '' || $(\"#spaceCities option:selected\").text() != '' || $(\"#selectedZipcode\").text() != '')) {\n previous = ', ';\n }\n if (opcion == '') {\n opcion = '';\n }\n //console.log('Address: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedAddress\").text(opcion + previous);\n\n opcion = $('#spaceZipcode').val();\n\n previous = '';\n if ($('#spaceZipcode').val() != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '' || $(\"#spaceCities option:selected\").text() != '')) {\n previous = ', ';\n }\n if (opcion == '') {\n opcion = '';\n }\n //console.log('Zipcode: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedZipcode\").text(opcion + previous);\n\n opcion = $(\"#spaceCities option:selected\").text();\n\n previous = '';\n if (opcion != 'Seleccione una Ciudad' && opcion != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '')) {\n previous = ', ';\n }\n if (opcion == 'Seleccione una Ciudad') {\n opcion = '';\n }\n //console.log('City: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedCity\").text(opcion + previous);\n\n opcion = $(\"#spaceState option:selected\").text();\n\n previous = '';\n if (opcion != 'Seleccione un Estado' && opcion != '' && ($(\"#spaceCountry option:selected\").val() != '')) {\n previous = ', ';\n }\n if (opcion == 'Seleccione un Estado') {\n opcion = '';\n }\n //console.log('Estado: ' + opcion + ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedState\").text(opcion + previous);\n\n\n opcion = $('#spaceCountry option:selected').text();\n //alert(opcion);\n if (opcion == 'Selecciona un Pais') {\n opcion = '';\n //alert(opcion);\n }\n //console.log('Pais: ' + opcion);\n fullAddress += opcion;\n $(\"#selectedCountry\").text(opcion);\n\n console.log(fullAddress);\n if (no_mymap) {\n\n } else {\n myMap(fullAddress);\n }\n\n }", "function BindSearchToAddress()\n{\n var options =\n {\n types: ['geocode']\n };\n\n var input = document.getElementById('searchByAddressText');\n\n autocomplete = new google.maps.places.Autocomplete(input, options);\n //autocomplete.setBounds(map.getBounds());\n\n google.maps.event.addListener(autocomplete, 'place_changed', function()\n {\n selectedPlace = autocomplete.getPlace();\n\n if (selectedPlace != null)\n {\n closeInfoBox(infoBox);\n\n var postalCode = '';\n\n if (selectedPlace.address_components != undefined)\n {\n for (var i in selectedPlace.address_components)\n {\n if (selectedPlace.address_components[i].types[0] == \"postal_code\")\n {\n postalCode = selectedPlace.address_components[i].short_name;\n CreateCookie('SearchKeyword', 'A_' + $('#searchByAddressText').val() + '_' + postalCode);\n SelectPMAOrClosestDealer(postalCode);\n return;\n }\n }\n\n }\n else\n {\n SelectPMAFromAddress($('#searchByAddressText').val());\n return;\n }\n\n // if a postalCode is not found, then try to zoom that map to the location\n if (selectedPlace != null)\n {\n //Handle previously selected dealer, by closing infobox and changing icon\n closeInfoBox(infoBox);\n\n if (selectedPlace.geometry.viewport)\n {\n map.fitBounds(selectedPlace.geometry.viewport);\n }\n else\n {\n map.setCenter(selectedPlace.geometry.location);\n map.setZoom(10);\n }\n }\n }\n });\n}", "function geocodeAddressFirst(geocoder, resultsMap) {\n geocoder.geocode( { 'address': landingAddress}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var latitude = results[0].geometry.location.lat();\n var longitude = results[0].geometry.location.lng();\n coordinates.push(latitude);\n coordinates.push(longitude);\n map = new google.maps.Map(document.getElementById('map'), {\n center: {lat: Number(coordinates[0]), lng: Number(coordinates[1])},\n zoom: 12,\n });\n startMarkers();\n loadCityCompanies(landingAddress);\n return map;\n }\n });\n }", "function GeoLocQuery(){}", "async getAddresses() {\n // check for empty city value since deleting city value character by character will trigger the debounceAddress\n // city value could be empty when this function run\n // so this extra check will fix the bug of showing addresses list when there is no city name\n if (this.state.city.trim()) {\n try {\n this.setState({showLoader: true})\n const {data} = await axios.get(\n `https://api.teleport.org/api/cities/?search=${this.state.city}`\n )\n\n // populate addresses and show them if matching cities exist\n if (!isEmpty(data) && !isUndefined(data) && data.count > 0) {\n const results = data._embedded['city:search-results'].map(result => ({\n cityName: result.matching_full_name,\n cityId: result._links['city:item'].href.split('/')[5]\n }))\n // results is an array of `address` objects with cityName and cityId properties\n this.setState({\n addresses: results,\n showCaret: true,\n showAddresses: true,\n errorMessage: ''\n })\n } else {\n this.setState({showAddresses: false})\n this.handleError(\n 'No matching cities found. Try searching with a valid city name!'\n )\n }\n } catch (error) {\n this.handleError(error)\n } finally {\n this.setState({showLoader: false})\n }\n } else {\n this.clearState()\n }\n }", "_getQueryFindAddressCandidates(data) {\n if (isString(data)) return { SingleLine: data };\n if (isObject(data)) return data;\n }", "function geocodeQueryBuild(selText) {\n var queryURL = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + selText + \"&key=\" + googleapiKey;\n return queryURL;\n }", "function geocoding(address) {\n // create AJAX request\n var xhttp = new XMLHttpRequest();\n \n // when server gives OK and ready\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) { \n // create json object \n addressLookup = JSON.parse(this.response);\n\n // takes coordinates and inserts into database\n insertCoordinates(addressLookup.results[0].geometry.location.lng, addressLookup.results[0].geometry.location.lat, address.Restaurant_ID);\n }\n };\n\n // this block of code takes address and returns cleaned string that will be used captures a restaurants coordinates\n var location = JSON.stringify(address);\n var string_start = location.indexOf(\":\")+2;\n var string_end = location.lastIndexOf(\"\\\"\");\n location = location.slice(string_start,string_end);\n\n // open connection with server\n xhttp.open(\"GET\",\"https://maps.googleapis.com/maps/api/geocode/json?address=\"+location+\"&key=AIzaSyDHSI4KzoulBbnrXCiIiID4asbLxqVAyZE\", true); \n\n // send request\n xhttp.send();\n }", "function codeAddress() {\n //we reinitialize each time this is called, so it recenters on the world\n //I did this since it is difficult to zoom based on the lat/lngs\n initialize();\n \n //get the locations from the input box\n var address = document.getElementById(\"address\").value;\n \n //convert the input box into an array\n address_array=convert_terms_to_array(address)\n \n //iterate over the addresses and append the \"loc:\" tag to the beginning\n //which overwrites google point of interest detector\n saved_address_array=new Array();\n for (var i=0; i<address_array.length-1; i++){\n if (address_array[i] != ''){\n address_array[i]='loc:'+address_array[i].replace(/^loc:/i, '')\n saved_address_array[i]='loc:'+address_array[i].replace(/^loc:/i, '')\n }else if (address_array[i] == '' && address_array[i-1]!=''){\n address_array[i]=address_array[i-1]\n saved_address_array[i]=address_array[i-1]\n }else{\n saved_address_array[i]=address_array[i]\n }\n }\n\n //get a unique list of the address\n unique_addresses=unique(address_array)\n \n //no longer needed since we are re-initializing\n //clearOverlays();\n \n latitude=new Array();\n longitude=new Array();\n elevation=new Array();\n var latlong\n var iterator=0;\n timer_ms=0;\n if (geocoder) {\n \n //give status updates\n document.getElementById(\"loading_status\").innerHTML='Loading coordinates'\n \n //iterate over the addresses and append a timing event, since google\n //has a query limit per second\n for (var i=0; i<unique_addresses.length; i++){\n if (unique_addresses[i]!=''){\n var lat2=setTimeout('geocode_results('+i+')',timer_ms)\n timer_ms+=700\n }\n }\n //append to the status after all points should have loaded\n setTimeout(\"document.getElementById('loading_status').innerHTML='Completed'\",timer_ms) \n }\n}", "function searchToLatLong(query){\n const url =`https://maps.googleapis.com/maps/api/geocode/json?address=${query}&key=${process.env.GEOCODE_API_KEY}`;\n //using our superagent library to get the proper data format\n return superagent.get(url)\n\n //then when we got the data from superagent create a new City object with the query (location name) and data (res.body.results[0]);\n .then(res => {\n city = new City(query, res.body.results[0]);\n ////envoking prototype function to set our object in table\n city.postLocation(query);\n return city;\n });\n}", "function searchLocations() {\n\n var address = document.getElementById(\"addressInput\").value;\n\n var geocoder = new google.maps.Geocoder();\n\n geocoder.geocode({ address: address }, function( results, status ) {\n\n if (status == google.maps.GeocoderStatus.OK) {\n searchLocationsNear(results[0].geometry.location);\n } else {\n alert(address + ' not found');\n }\n \n });\n\n }", "function fillInAddress() {\n // Get the place details from the autocomplete object.\n place = autocomplete.getPlace();\n console.log(place);\n // updating address data \n number = place.address_components[0].long_name;\n street = place.address_components[1].long_name;\n city = place.address_components[3].long_name;\n state_short = place.address_components[5].short_name;\n zipCode = place.address_components[7].long_name;\n // undating geocode data\n latitude = place.geometry.location.lat();\n longitude = place.geometry.location.lng();\n\n // replacing “ ” to \"+\" \n number = number.replace(\" \", \"+\");\n street = street.replace(\" \", \"+\");\n city = city.replace(\" \", \"+\");\n street = street.replace(\" \", \"+\");\n zipCode = zipCode.replace(\" \", \"+\");\n }", "search (query) {\n\t\t// Store lat/lng of locality to use in this url (focus.point.lat, focus.point.lon)\n \t\t//const endpoint = `https://search.mapzen.com/v1/autocomplete?text=${query}&api_key=${this.props.config.mapzen.apiKey}&focus.point.lat=${this.props.coordinates[0]}&focus.point.lon=${this.props.coordinates[1]}&layers=venue`\n \t\tconst placetype = this.state.placetype\n \t\tconst endpoint = `https://whosonfirst-api.mapzen.com/?method=whosonfirst.places.search&api_key=${this.props.config.mapzen.apiKey}&q=${query}&${placetype}=${this.props.source.id}&placetype=venue&per_page=100&extras=geom:latitude,geom:longitude,sg:,addr:full,wof:tags`\n \t\tthis.throttleMakeRequest(endpoint)\n\t}", "function geocode(address){\n return new Promise(function(fulfill,reject){\n request('https://maps.googleapis.com/maps/api/geocode/json?' +\n 'address=' + encodeURIComponent(address) +\n '&key=' + googleGeoCodeKey\n ,function(err,res){\n if(!err) fulfill(JSON.parse(res.body).results[0].geometry)\n if(err) reject(err)\n })\n })\n}", "function codeAddress(address) {\n geocoder.geocode({\n 'address': address\n }, function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n map.setZoom(15);\n marker.setPosition(results[0].geometry.location);\n document.getElementById(latInput).value = results[0].geometry.location.lat();\n document.getElementById(lngInput).value = results[0].geometry.location.lng();\n /**\n * using response from services to get nearby venues\n */\n getNearbyVenues();\n\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n}", "function _geocodeAddress () {\n if ($location_field.val() !== '') {\n /**\n * If the user has entered a new location we need to hide previous results\n */\n if (routes_calculated && ($location_field.val() !== current_visitor_location)) {\n current_visitor_location = $location_field.val();\n _showRouteResults(false);\n }\n\n /**\n * If we don't have the user's location via HTML5 geolocation we need to instead request it from Google\n */\n if (!$location_field.attr('data-geocoded')) {\n _requestAddressGeocode($location_field.val())\n .then(\n function (results) {\n visitor_location = results[0].geometry.location;\n\n _calculateRoute();\n _showErrorMessage(false);\n },\n function () {\n visitor_location = false;\n _showErrorMessage(true, 'Sorry, this location has not been found.');\n } \n );\n } else {\n _calculateRoute();\n }\n } else {\n /**\n * If the user has yet to enter their location then focus the input field and show some feedback to\n * the user (requires $animations-shake to be true in css config)\n */ \n $location_field\n .addClass('animated shake')\n .focus();\n\n /**\n * We now need to remove the shake class in case we need to add it again\n */ \n setTimeout(function () {\n $location_field.removeClass('shake');\n }, 1000);\n }\n\n return false;\n }", "geocode(query) {\n return new Promise((resolve, reject) => {\n this.geocoder.geocode({ searchText: query }, result => {\n if(result.Response.View.length > 0) {\n if(result.Response.View[0].Result.length > 0) {\n resolve(result.Response.View[0].Result[0].Location.DisplayPosition);\n } else {\n reject({ message: \"no results found\" });\n }\n } else {\n reject({ message: \"no results found\" });\n }\n }, error => {\n reject(error);\n });\n });\n }" ]
[ "0.6659336", "0.650398", "0.60950613", "0.60516804", "0.6016699", "0.6010526", "0.6007574", "0.5975601", "0.59680796", "0.58689475", "0.5868109", "0.58561164", "0.58160007", "0.5812755", "0.5785749", "0.5750603", "0.5721056", "0.5718395", "0.56995296", "0.56814253", "0.5663159", "0.5653653", "0.565021", "0.5640762", "0.5637306", "0.56356955", "0.56195825", "0.5618188", "0.5594877", "0.55846024" ]
0.71950936
0
Parsing error and return error object
parseError(error) { if (error.code === 400 && (error.details && error.details.length)) { return { code: error.code, msg: get(error, 'details')[0] || 'Error', }; } return error; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ParserError(e,t){this.message=e,this.error=t}", "function parseError(err, path){\n app.logger.log(err, path); \n \n if(typeof err == 'string')\n return err;\n return 'Unknown error';\n }", "function parseError(input, contents, err) {\n var errLines = err.message.split(\"\\n\");\n var lineNumber = (errLines.length > 0? errLines[0].substring(errLines[0].indexOf(\":\") + 1) : 0);\n var lines = contents.split(\"\\n\", lineNumber);\n return {\n message: err.name + \": \" + (errLines.length > 2? errLines[errLines.length - 2] : err.message),\n severity: \"error\",\n lineNumber: lineNumber,\n characterOffset: 0,\n lineContent: (lineNumber > 0 && lines.length >= lineNumber? lines[lineNumber - 1] : \"Unknown line\"),\n source: input\n };\n}", "function parseError(str,o){\n\t\t// find nearest token\n\t\tvar err;\n\t\t\n\t\tif (o.lexer) {\n\t\t\tvar token = o.lexer.yytext;\n\t\t\t// console.log o:lexer:pos,token.@loc\n\t\t\terr = new ImbaParseError({message: str},{\n\t\t\t\tpos: o.lexer.pos,\n\t\t\t\ttokens: o.lexer.tokens,\n\t\t\t\ttoken: o.lexer.yytext,\n\t\t\t\tmeta: o\n\t\t\t});\n\t\t\t\n\t\t\tthrow err;\n\t\t\t\n\t\t\t// should find the closest token with actual position\n\t\t\t// str = \"[{token.@loc}:{token.@len || String(token):length}] {str}\"\n\t\t};\n\t\tvar e = new Error(str);\n\t\te.lexer = o.lexer;\n\t\te.options = o;\n\t\tthrow e;\n\t}", "function ParseError(res) {\n\tthis.message = 'Unexpected characters \"' + res[0] + '\":\\n' +\n\t\tres.input.replace(/\\t|\\n/g, '.') + '\\n' + (new Array(res.index + 1).join('-')) + '^';\n\tthis.name = 'ParseError';\n}", "function ParseError(msg, type, value, context)\n{\n this.msg = msg;\n this.type = type;\n this.value = value;\n this.context = context;\n return this;\n}", "function _errorParse(data) {\n function _noUser() {\n var newData = {\n \"errorMessage\": data.data.message,\n \"errorNumber\": data.status,\n \"modifiedBy\": \"Admin\",\n \"errorSeverity\": 0,\n \"errorState\": 0,\n \"errorProcedure\": data.config.method,\n \"errorLine\": 0\n };\n _postError(newData);\n }\n }", "function parseError(text, token)\n{\n error('parse error: ' + text + ' ' + token.pos);\n}", "function ParseError(message, hash) {\n _.extend(this, hash);\n\n this.name = 'ParseError';\n this.message = (message || '');\n}", "function error(line, message) {\n return CIFTools.ParserResult.error(message, line);\n }", "function getErrorObj(){\n\t\t try{ throw Error(\"\")}catch(err){ return err }\n\t }", "function massageError(error) {\n if (!error.message) {\n return error;\n }\n const message = error.message.replace(/^JSON.parse: /, '').replace(/of the JSON data/, '');\n const parts = /line (\\d+) column (\\d+)/.exec(message);\n if (!parts || parts.length !== 3) {\n return error;\n }\n return {\n message: htmlEncode(message),\n line: Number(parts[1]),\n column: Number(parts[2])\n };\n }", "function makeError(err) {\n var einput;\n\n var defautls = {\n index: furthest,\n filename: env.filename,\n message: 'Parse error.',\n line: 0,\n column: -1\n };\n for (var prop in defautls) {\n if (err[prop] === 0) {\n err[prop] = defautls[prop];\n }\n }\n\n if (err.filename && that.env.inputs && that.env.inputs[err.filename]) {\n einput = that.env.inputs[err.filename];\n } else {\n einput = input;\n }\n\n err.line = (einput.slice(0, err.index).match(/\\n/g) || '').length + 1;\n for (var n = err.index; n >= 0 && einput.charAt(n) !== '\\n'; n--) {\n err.column++;\n }\n return new Error([err.filename, err.line, err.column, err.message].join(\";\"));\n }", "parseErr(err) {\n if (!err.errors) return err;\n const messages = Object.keys(err.errors).map(errorKey =>\n `${errorKey} error: ${err.errors[errorKey]}`);\n return messages;\n }", "function getErrorObject(){\n try { throw Error('') } catch(err) { return err; }\n}", "parse(r) {\r\n return r.text().then(t => {\r\n if (!r.ok) {\r\n throw Error(t);\r\n }\r\n try {\r\n return JSON.parse(t);\r\n }\r\n catch (e) {\r\n // special case in ProcessQuery where we got an error back, but it is not in json format\r\n throw Error(t);\r\n }\r\n }).then((parsed) => {\r\n // here we need to check for an error body\r\n if (parsed.length > 0 && hOP(parsed[0], \"ErrorInfo\") && parsed[0].ErrorInfo !== null) {\r\n throw Error(jsS(parsed[0].ErrorInfo));\r\n }\r\n return this.findResult(parsed);\r\n });\r\n }", "onParserError (err) {\n this.emit('error', err)\n }", "function parse_PtgErr(blob) {\n blob.l++;\n return BErr[blob.read_shift(1)];\n }", "_error(msg) {\n msg += ` (${this._errorPostfix})`;\n const e = new Error(msg);\n return e;\n }", "function parseError(stream, message) {\n if (stream) {\n stream = \"'\"+stream+\"'\";\n }\n else {\n stream = 'EOF';\n }\n\n throw 'Parse Error: '+message+' at '+stream;\n }", "function parseError(stream, message) {\n if (stream) {\n stream = \"'\"+stream+\"'\";\n }\n else {\n stream = 'EOF';\n }\n\n throw 'Parse Error: '+message+' at '+stream;\n }", "function error(m) {\n var e = new SyntaxError(m);\n e.at = at - 1;\n e.json = json;\n throw e;\n }", "function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }", "function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }", "function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }", "function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }", "function JPSpan_Util_ErrorReader() {}", "function error(expected){\n console.log(\"Expected: \"+expected+\n \" but found \"+(toks[i][0])+\": \"+\n (toks[i][1]));\n var e = new Error();\n console.log(e.stack);\n throw \"Parse error\";\n }", "function getErrorObject() {\n try { throw Error('') } catch(err) { return err; }\n}", "function parseError(stream, message) {\n if (stream) {\n stream = '\\''+stream+'\\'';\n }\n else {\n stream = 'EOF';\n }\n\n throw 'Parse Error: '+message+' at '+stream;\n }" ]
[ "0.7639631", "0.72706497", "0.71979725", "0.70759445", "0.70511776", "0.69986945", "0.6817068", "0.67343694", "0.67053854", "0.6647787", "0.65015846", "0.64899427", "0.6364251", "0.6264464", "0.6232777", "0.6219385", "0.6184491", "0.6124249", "0.6114782", "0.61146456", "0.61146456", "0.6112164", "0.61079013", "0.61079013", "0.61079013", "0.61079013", "0.60880023", "0.60863924", "0.6079458", "0.6073034" ]
0.7544482
1
Process the image by applying the kernel.
function ApplyKernel(img, kern) { let height = img.height; let width = img.width // Create and allocate a new array to hold the new image. let new_image = new Uint8ClampedArray(4 * height * width); new_image.fill(255); // Iterate through each of the channels: R,G,B for(var channel = 0; channel < 3; channel++) { // Iterate through each of the pixels in the image. for (var X = 0; X < width; X++) { for(var Y = 0; Y < height; Y++) { let filtered_value = 0; for (var y = 0; y < kern.length; y++) { for (var x = 0; x < kern[0].length; x++) { // collect the necessary kernel values. let kern_y_shift = ~~(kern.length / 2) - y; let kern_x_shift = ~~(kern[0].length / 2) - x; // Map to the appropriate point let point = mapPoint(X + kern_x_shift,Y + kern_y_shift, height, width, channel); // Apply kernel and add to filtered value. filtered_value += img.data[point]*kern[y][x]; } } // Update the new image at the appropriate pixel. new_image[mapPoint(X,Y,height,width,channel)] = filtered_value; } } } return new ImageData(new_image, img.width, img.height); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "run(imageData, imgWidth, imgHeight) {\n let kernel = this.kernels[this.kernelOperator].kernel;\n let sum = this.kernels[this.kernelOperator].sum;\n return this.convolve(imageData, imgWidth, imgHeight, kernel, 1/sum);\n }", "apply() {\n // Get the source image and create the result image buffer\n const source = new ImageDataPixelWrapper(this.source.getImageData(0, 0, 400, 300));\n const resultImageData = this.result.createImageData(400, 300)\n const result = new ImageDataPixelWrapper(resultImageData);\n\n // Update the alpha values of the newly created image\n result.map((pixel) => pixel.alpha = 255)\n\n if (this.operation) {\n if (this.operation.params) var params = this.getParams();\n this.operation.apply(source, result, params);\n }\n\n // Put the result image in the canvas\n this.result.putImageData(resultImageData, 0, 0);\n }", "function processImage(img){\n\n // store raw image data\n var canvas0 = document.getElementById('drawStore');\n var ctx0 = canvas0.getContext('2d');\n ctx0.drawImage(img, 0, 0, canvas0.width, canvas0.height);\n\n // access pixel data\n var imageData0 = ctx0.getImageData(0, 0, canvas0.width, canvas0.height);\n var data0 = imageData0.data;\n var r0, g0, b0;\n\n // initialize array of pixel indexes\n var pixelIndexArray = [];\n\n // iterate across pixels\n for(var p0 = 0; p0 < data0.length; p0 += 4){\n r0 = data0[p0];\n g0 = data0[p0 + 1];\n b0 = data0[p0 + 2];\n\n // if threshold is met (red, green, blue all <= 100), push pixel index number into pixel array\n if((r0 >= 0 && r0 <= 100) && (g0 >= 0 && g0 <= 100) && (b0 >= 0 && b0 <= 100)){\n pixelIndexArray.push(p0 / 4 + 1);\n }\n }\n // console.log(pixelIndexArray);\n\n // determine the first and last row number that have written pixels (upper and lower bound)\n // done by dividing pixel index by image width and finding the largest integer\n var topRow = Math.ceil(pixelIndexArray[0] / canvas0.width);\n var bottomRow = Math.ceil(pixelIndexArray[pixelIndexArray.length - 1] / canvas0.width);\n\n // determine the first and last column number that have written pixels (left and right bound)\n // done by finding the remainder after dividing pixel index by image width\n // smallest modulus (excluding 0) corresponds to first column\n // largest modulus (0 is the largest) corresponds to last column\n var moduli = [];\n for(var i = 0; i < pixelIndexArray.length; i++){\n moduli.push(pixelIndexArray[i] % canvas0.width);\n }\n if(moduli.includes(0)){\n var rightColumn = canvas0.width;\n var leftColumn = Math.min.apply(null, moduli.filter(Boolean));\n } else {\n var rightColumn = Math.max.apply(null, moduli);\n var leftColumn = Math.min.apply(null, moduli);\n }\n // console.log('top row: ' + topRow);\n // console.log('bottom row: ' + bottomRow);\n // console.log('left column: ' + leftColumn);\n // console.log('right column: ' + rightColumn);\n\n // find the new width and height and crop the original image into a smaller square\n var scaledWidth = rightColumn - leftColumn + 1;\n var scaledHeight = bottomRow - topRow + 1;\n var difference = scaledWidth - scaledHeight;\n // console.log(difference);\n if(difference > 0){\n var scaledImageData = ctx0.getImageData(leftColumn, topRow - (difference / 2), scaledWidth, scaledWidth);\n } else if(difference < 0){\n var scaledImageData = ctx0.getImageData(leftColumn + (difference / 2), topRow, scaledHeight, scaledHeight);\n } else if(difference === 0){\n var scaledImageData = ctx0.getImageData(leftColumn, topRow, scaledWidth, scaledHeight);\n }\n // console.log(scaledImageData);\n\n // store the cropped image and use for next step of processing\n var newCanvas = document.createElement('canvas');\n newCanvas.id = 'scaledImage';\n newCanvas.width = Math.max(scaledWidth, scaledHeight);\n newCanvas.height = Math.max(scaledWidth, scaledHeight);\n newCanvas.style.display = 'none';\n document.body.appendChild(newCanvas);\n var newCtx = newCanvas.getContext('2d');\n newCtx.putImageData(scaledImageData, 0, 0);\n var scaledImage = new Image();\n scaledImage.onload = function(){\n storeImage(this);\n };\n scaledImage.src = newCanvas.toDataURL();\n\n // function to scale, store, and send image to server\n function storeImage(image){\n\n // scale and display image in 'Your Submission' box\n var canvas = document.getElementById('imageSub');\n var ctx = canvas.getContext('2d');\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n\n // get pixel data from image\n var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n var data = imageData.data;\n var r, g, b;\n\n // initialize binary array\n var binaryArray = [];\n\n // iterate across pixels\n for(var p = 0; p < data.length; p += 4){\n r = data[p];\n g = data[p + 1];\n b = data[p + 2];\n\n // if threshold is met (red, green, blue all <= 100), convert pixel to black and push '1' into binary array\n // else convert pixel to white and push '0' into binary array\n if((r >= 0 && r <= 100) && (g >= 0 && g <= 100) && (b >= 0 && b <= 100)){\n binaryArray.push(1);\n data[p] = 0;\n data[p + 1] = 0;\n data[p + 2] = 0;\n } else {\n binaryArray.push(0);\n data[p] = 255;\n data[p + 1] = 255;\n data[p + 2] = 255;\n }\n }\n\n // replace original pixel data\n ctx.putImageData(imageData, 0, 0);\n\n // convert binary array to appropriate format and send to server using ajax\n var binaryString = JSON.stringify(binaryArray).slice(1, -1);\n // console.log(binaryString);\n var formData = 'image=' + binaryString;\n // console.log(formData);\n\n // use ajax to send http request by post method\n var httpRequest = new XMLHttpRequest();\n\n // action to take when response is received\n httpRequest.onreadystatechange = function(){\n if(httpRequest.readyState === XMLHttpRequest.DONE){\n if(httpRequest.status === 200){\n\n // response is in the form: \"character,probability\"\n var response = httpRequest.responseText.split(',');\n var correctAns = response[0];\n var probability = Number(response[1]);\n console.log(correctAns);\n console.log(probability);\n\n // if predicted character is the same as the correct character, allow user to roll dice and move to next word\n if(correctAns === document.getElementById('imageCorStore').innerHTML){\n alert('Good job!');\n var roll = document.getElementById('roll');\n roll.style.display = 'block';\n\n // increase counter for number of turns used (variable in game.js)\n numberOfTurns++;\n document.getElementById('turns').innerHTML = numberOfTurns;\n\n // clear 'Correct Answer' box and display correct Chinese character\n var canvas2 = document.getElementById('imageCor');\n var ctx2 = canvas2.getContext('2d');\n ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n ctx2.font = '50px arial';\n ctx2.fillText(document.getElementById('imageCorStore').innerHTML, 9, 52, canvas2.width);\n\n // clear drawing canvas and generate new random word\n myBoard.reset({background: true});\n nextWord();\n // console.log(words.length);\n\n } else {\n\n // if probability of prediction is below 50%, allow user to try again\n if(probability < 0.5){\n myBoard.reset({background: true});\n alert('Please write the character again.');\n\n // clear 'Correct Answer' box\n var canvas2 = document.getElementById('imageCor');\n var ctx2 = canvas2.getContext('2d');\n ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n\n // if not, tell user it is wrong and move to next word\n } else {\n alert('Sorry, that is wrong. The correct character is shown below.');\n\n // increase counter for number of turns used (variable in game.js)\n numberOfTurns++;\n document.getElementById('turns').innerHTML = numberOfTurns;\n\n // clear 'Correct Answer' box and display correct Chinese character\n var canvas2 = document.getElementById('imageCor');\n var ctx2 = canvas2.getContext('2d');\n ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n ctx2.font = '50px arial';\n ctx2.fillText(document.getElementById('imageCorStore').innerHTML, 9, 52, canvas2.width);\n\n // clear drawing canvas and generate new random word\n myBoard.reset({background: true});\n nextWord();\n // console.log(words.length);\n } \n }\n } else {\n alert('There was a problem with the request.');\n }\n }\n };\n\n // set request parameters and send it to server\n httpRequest.open('POST', 'http://ec2-107-23-213-101.compute-1.amazonaws.com/classify', true);\n httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n httpRequest.send(formData);\n } \n }", "process() {\n\n const size = 190;\n this.canvas = document.getElementById(`${this.imageId}-canvas`);\n const context = this.canvas.getContext('2d');\n\n // Clear canvas\n context.clearRect(0, 0, this.canvas.width, this.canvas.height);\n\n context.drawImage(this.img, 0, 100, size, size);\n let imgData = context.getImageData(0, 100, size, size);\n let source = new Array2D([...imgData.data], imgData.width, imgData.height, 4);\n\n // Convert to grayscale\n grayscale(source);\n\n fillArray(imgData.data, source.data, imgData.data.length);\n context.putImageData(imgData, 220, 100);\n\n // Apply Sobel operator horizontally\n let sobelXData = new Array2D([...source.data], source.width, source.height, 4);\n convolve(sobelXData, sobelX);\n\n // Apply Sobel operator vertically\n let sobelYData = new Array2D([...source.data], source.width, source.height, 4);\n convolve(sobelYData, sobelY);\n\n // Calculate magnitude of gradients\n const [magGrid, angleGrid] = computeGradients(sobelXData, sobelYData);\n\n\n // Display sobels with red-green\n stretchColorRange(sobelXData, -1020, 1020, 0, 1);\n for (let i = 0; i < sobelXData.height; i++) {\n for (let j = 0; j < sobelXData.width; j++) {\n const colorVal = Math.floor(255 * sobelXData.getValue(i, j));\n sobelXData.setValue(colorVal, i, j, 0);\n sobelXData.setValue(colorVal, i, j, 1);\n sobelXData.setValue(colorVal, i, j, 2);\n }\n }\n fillArray(imgData.data, sobelXData.data, imgData.data.length);\n context.putImageData(imgData, 440, 0);\n\n stretchColorRange(sobelYData, -1020, 1020, 0, 1);\n for (let i = 0; i < sobelYData.height; i++) {\n for (let j = 0; j < sobelYData.width; j++) {\n const colorVal = Math.floor(255 * sobelYData.getValue(i, j));\n sobelYData.setValue(colorVal, i, j, 0);\n sobelYData.setValue(colorVal, i, j, 1);\n sobelYData.setValue(colorVal, i, j, 2);\n }\n }\n fillArray(imgData.data, sobelYData.data, imgData.data.length);\n context.putImageData(imgData, 440, 210);\n\n stretchColor(magGrid, 0, 255);\n fillArray(imgData.data, magGrid.data, imgData.data.length);\n context.putImageData(imgData, 660, 100);\n\n // Draw labels\n context.font = \"11px Arial\";\n context.fillText(\"Color\", 0, 300);\n context.fillText(\"Grayscale\", 220, 300);\n context.fillText(\"Sobel X\", 440, 200);\n context.fillText(\"Sobel Y\", 440, 410);\n context.fillText(\"Gradients\", 660, 300);\n\n // Draw lines\n context.lineWidth = 2;\n context.beginPath();\n canvasArrowCurveX(context, 0 + size, 100 + size / 2, 220, 100 + size / 2);\n canvasArrowCurveX(context, 220 + size, 100 + size / 2, 440, 0 + size / 2);\n canvasArrowCurveX(context, 220 + size, 100 + size / 2, 440, 210 + size / 2);\n canvasArrowCurveX(context, 440 + size, 0 + size / 2, 660, 100 + size / 2);\n canvasArrowCurveX(context, 440 + size, 210 + size / 2, 660, 100 + size / 2);\n context.stroke();\n }", "function manipulateImage() {\n // 1.\n sourceImage.resize(200, 0); // 2.\n\n var srcImgW = sourceImage.width;\n var srcImgH = sourceImage.height; // 3.\n\n var ratio = srcImgH / srcImgW; // 4. Get width of the rasterized image from UI\n\n var mImgW = parseInt(State.width); // Calculate the height of it with the ratio\n\n var mImgH = parseInt(State.width * ratio);\n var scaling = mImgW / srcImgW; // Calculate the number of gridcolumns\n\n var gridItemW = mImgW / State.gridCols; // Calculate the number of gridrows\n\n var gridRows = State.gridCols * ratio; // Create PGraphics\n\n manipulatedImage = createGraphics(mImgW, mImgH); // Fill and stroke\n\n manipulatedImage.noStroke();\n manipulatedImage.fill(State.Colors.image); // BUG!\n // The loop draws only a grid of 60 tiles instead of 180\n\n var counter = 0; // Get the brightness-min- and max-values for contrast optimization\n\n var briMin = 0,\n briMax = 255;\n\n for (var x = 0; x < mImgW; x += gridItemW) {\n for (var y = 0; y < mImgH; y += gridItemW) {\n // get the right pixel\n var thisPixel = sourceImage.get(parseInt(x / scaling), parseInt(y / scaling));\n var brightn = brightness(thisPixel);\n }\n } // DRAW IT!!!\n\n\n for (var x = 0; x < mImgW; x += gridItemW) {\n counter++;\n\n for (var y = 0; y < mImgH; y += gridItemW) {\n // get the right pixel\n var thisPixel = sourceImage.get(parseInt(x / scaling), parseInt(y / scaling));\n var brightn = brightness(thisPixel); // calculate the size of the rectangle\n\n var size = map(brightn, 100, 0, 0, State.maxSize);\n manipulatedImage.push();\n manipulatedImage.translate(x, y);\n manipulatedImage.rect(0, 0, size, size);\n manipulatedImage.pop();\n }\n }\n\n busy = false;\n} // Get a new source image", "function applyPredictionsToImage() {\n\n let threshold = (thresholdSlider.value / 100);\n let width = imgTarget.width;\n let height = imgTarget.height;\n\n // Create the trace canvas to draw on image\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d');\n ctx.drawImage(originalImage, 0, 0, width, height);\n ctx.lineWidth = 2;\n ctx.font = \"15px Arial\";\n\n ctx.beginPath();\n let x1, x2, y1, y2;\n let labelText, classVal, confidence, color;\n for (let i = 0; i < predictions.length; i++) {\n if (predictions[i][1] > threshold) {\n\n classVal = predictions[i][0];\n color = colorArray[predictions[i][0]];\n\n // Set color as per class label index of colorArray and \n ctx.strokeStyle = color;\n\n // Get X/Y points from prediction.\n x1 = predictions[i][2] * width;\n y1 = predictions[i][3] * height;\n x2 = (predictions[i][4] * width) - x1;\n y2 = (predictions[i][5] * height) - y1;\n\n // Draw the box for detections.\n ctx.rect(x1, y1, x2, y2);\n ctx.stroke();\n\n // Draw the label and confidence as text\n confidence = `${Math.round(predictions[i][1] * 10000) / 100} %`;\n labelText = `ID:${i + 1}-${getPredictionLabel(classVal)} - ${confidence}`;\n\n ctx.fillStyle = color;\n ctx.fillText(labelText, x1, y1 - 2);\n\n }\n }\n\n let url = canvas.toDataURL();\n imgTarget.src = url;\n}", "function processImage() {\n // if there is an image tag inside the container\n // and it has a src setted\n if(f.o.src && f.o.src != \"\")\n {\n\n // if container size if not setted resize it to the image size\n if (Math.floor(f.$el.height()) <= 0) { f.o.clearhg = true; f.$el.height(f.o.naturalimghg); } \n if (Math.floor(f.$el.width()) <= 0) { f.o.clearwd = true; f.$el.width(f.o.naturalimgwd ); }\n\n // get the container size\n f.o.containerwd = f.$el.width();\n f.o.containerhg = f.$el.height();\n\n // get the size of the visible area for the image we need this \n // to not draw the image outside the parent container\n f.o.imghg = ((f.o.naturalimgwd/f.o.naturalimghg < f.o.containerwd/f.o.containerhg) ? \n f.o.containerhg :\n Math.ceil(f.o.containerwd/f.o.naturalimgwd * f.o.naturalimghg)); \n\n f.o.imgwd = ((f.o.naturalimgwd/f.o.naturalimghg < f.o.containerwd/f.o.containerhg) ? \n Math.ceil(f.o.containerhg/f.o.naturalimghg * f.o.naturalimgwd) :\n f.o.containerwd);\n\n }\n else {\n // if no principal image takes the container size \n f.o.imgwd = f.o.containerwd = f.$el.width();\n f.o.imghg = f.o.containerhg = f.$el.height();\n }\n // calculate margin for horizontal alingment inside the container\n f.o.marginleft = (f.o.containerwd > f.o.imgwd) ? (f.o.containerwd/2) - (f.o.imgwd/2) : 0;\n\n }", "function image_process_streamization() { \r\n\r\n}", "function handleImageLoad() {\n\t\tvar bmp = new Bitmap(img);\n\t\tbmp.x = (canvas.width-2*img.width)/3;\n\t\tbmp.y = (canvas.height-2*img.height)/3;\n\t\tstage.addChild(bmp);\n\n\t\tvar blurFilter = new BoxBlurFilter(32, 2, 2);\n\t\tvar margins = blurFilter.getBounds();\n\t\tbmp = bmp.clone();\n\t\tbmp.filters = [blurFilter];\n\t\t// filters are only displayed when the display object is cached\n\t\t// later, you can call updateCache() to update changes to your filters\n\t\tbmp.cache(margins.x,margins.y,img.width+margins.width,img.height+margins.height);\n\t\tbmp.x += bmp.x+img.width;\n\t\tstage.addChild(bmp);\n\n\n\t\tvar greyScaleFilter = new ColorMatrixFilter([\n\t\t\t0.33,0.33,0.33,0,0, // red\n\t\t\t0.33,0.33,0.33,0,0, // green\n\t\t\t0.33,0.33,0.33,0,0, // blue\n\t\t\t0,0,0,1,0 // alpha\n\t\t]);\n\t\tbmp = bmp.clone();\n\t\tbmp.filters = [greyScaleFilter];\n\t\tbmp.cache(0,0,img.width,img.height); // color filters don't change the bounds.\n\t\tbmp.y += bmp.y+img.height;\n\t\tstage.addChild(bmp);\n\n\n\t\tvar removeRedFilter = new ColorFilter(0,1,1,1); // red, green, blue, alpha\n\t\tbmp = bmp.clone();\n\t\tbmp.filters = [removeRedFilter];\n\t\tbmp.cache(0,0,img.width,img.height); // color filters don't change the bounds.\n\t\tbmp.x = (canvas.width-2*img.width)/3;\n\t\tstage.addChild(bmp);\n\n\t\t// draw to the canvas:\n\t\tstage.update();\n\t}", "function submitToProcessing(dataURL, sendToNeuralNetTraining){\n\n var image = new Image;\n image.src = dataURL;\n\n image.onload = function(){\n ctx2.drawImage(image, 0, 0);\n var data = ctx2.getImageData(2, 2, 24, 24);\n console.log(dataURL);\n var pixelDensity = [];\n\n for(var i = 0; i < data.data.length; i++){\n if((i + 1) % 4 == 0){\n var pixelDensityFloat = ((255 - data.data[i - 1]) / 255.0);\n if(data.data[i - 1] == 0){\n pixelDensity.push(0);\n }else{\n pixelDensity.push(pixelDensityFloat);\n }\n }\n }\n //console.log(pixelDensity);\n imagingTrainer.sendToNeuralNetTraining(pixelDensity);\n };\n\n}", "function drawImage()\n {\n var kernelWeight=computeWeight(kernel);\n\n //Set the uniforms\n gl.uniform2f(resLoc, gl.canvas.width, gl.canvas.height);\n gl.uniform1i(texLoc,0);\n gl.uniform1fv(kernelLoc, kernel);\n gl.uniform1f(kernelWeightLoc, kernelWeight);\n \n //Draw the triangle\n gl.enable(gl.DEPTH_TEST);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n }", "function applyFilter (filterFunction) { \n for (var i = 0; i < image.length; i++) {\n \n for (var j = 0; j < image[i].length; j++) {\n var rgbString = image[i][j]\n var rgbNumbers = rgbStringToArray(rgbString)\n filterFunction(rgbNumbers);\n var rgbString = rgbStringToArray(rgbNumbers)\n image[i][j] = rgbString\n }\n}\n}", "function processImage(doc, fileName, processCallback) {\n prepareImage(fileName, function (prepareErr, prepareFileName) {\n if (prepareErr) {\n processCallback(prepareErr, null);\n } else {\n analyzeImage(doc, prepareFileName, function (err, analysis) {\n processCallback(err, analysis);\n });\n }\n });\n}", "function applyMatrix(pixels, matrix, amount) {\n\n\t\t// create a second buffer to hold matrix results\n\t\tvar buffer2 = document.createElement(\"canvas\");\n\t\t// get the canvas context\n\t\tvar c2 = buffer2.getContext('2d');\n\n\t\t// set the dimensions\n\t\tc2.width = buffer2.width = pixels.width;\n\t\tc2.height = buffer2.height = pixels.height;\n\n\t\t// draw the image to the new buffer\n\t\tc2.putImageData(pixels, 0, 0);\n\t\tvar bufferedPixels = c2.getImageData(0, 0, pixels.width, pixels.height);\n\n\t\t// speed up access\n\t\tvar data = pixels.data, bufferedData = bufferedPixels.data, imgWidth = pixels.width;\n\n\t\t// make sure the matrix adds up to 1\n\t\t/* \t\tmatrix = normalizeMatrix(matrix); */\n\n\t\t// calculate the size of the matrix\n\t\tvar matrixSize = Math.sqrt(matrix.length);\n\t\t// also store the size of the kernel radius (half the size of the matrix)\n\t\tvar kernelRadius = Math.floor(matrixSize / 2);\n\n\t\t// loop through every pixel\n\t\tfor (var i = 1; i < imgWidth - 1; i++) {\n\t\t\tfor (var j = 1; j < pixels.height - 1; j++) {\n\n\t\t\t\t// temporary holders for matrix results\n\t\t\t\tvar sumR = sumG = sumB = 0;\n\n\t\t\t\t// loop through the matrix itself\n\t\t\t\tfor (var h = 0; h < matrixSize; h++) {\n\t\t\t\t\tfor (var w = 0; w < matrixSize; w++) {\n\n\t\t\t\t\t\t// get a refence to a pixel position in the matrix\n\t\t\t\t\t\tvar r = convertCoordinates(i + w - kernelRadius, j + h - kernelRadius, imgWidth) << 2;\n\n\t\t\t\t\t\t// find RGB values for that pixel\n\t\t\t\t\t\tvar currentPixel = {\n\t\t\t\t\t\t\tr: bufferedData[r],\n\t\t\t\t\t\t\tg: bufferedData[r + 1],\n\t\t\t\t\t\t\tb: bufferedData[r + 2]\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// apply the value from the current matrix position\n\t\t\t\t\t\tsumR += currentPixel.r * matrix[w + h * matrixSize];\n\t\t\t\t\t\tsumG += currentPixel.g * matrix[w + h * matrixSize];\n\t\t\t\t\t\tsumB += currentPixel.b * matrix[w + h * matrixSize];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// get a reference for the final pixel\n\t\t\t\tvar ref = convertCoordinates(i, j, imgWidth) << 2;\n\t\t\t\tvar thisPixel = {\n\t\t\t\t\tr: data[ref],\n\t\t\t\t\tg: data[ref + 1],\n\t\t\t\t\tb: data[ref + 2]\n\t\t\t\t};\n\n\t\t\t\t// finally, apply the adjusted values\n\t\t\t\tdata = setRGB(data, ref, findColorDifference(amount, sumR, thisPixel.r), findColorDifference(amount, sumG, thisPixel.g), findColorDifference(amount, sumB, thisPixel.b));\n\t\t\t}\n\t\t}\n\n\t\tdelete buffer2;\n\t\treturn pixels;\n\t}", "function runFilter(id, filter, arg1, arg2, arg3) {\n var c = document.getElementById('grayscale');\n\n var s = c.previousSibling.style;\n var idata = Filters.filterImage(filter, img, arg1, arg2, arg3);\n c.width = idata.width;\n c.height = idata.height;\n var ctx = c.getContext('2d');\n ctx.putImageData(idata, 0, 0);\n s.display = 'none';\n c.style.display = 'inline';\n }", "function submitToProcessing2(dataURL, sendToNeuralNet){\n\n var image = new Image;\n image.src = dataURL;\n\n image.onload = function(){\n ctx2.drawImage(image, 0, 0);\n\n var data = ctx2.getImageData(2, 2, 24, 24);\n var pixelDensity = [];\n\n for(var i = 0; i < data.data.length; i++){\n if((i + 1) % 4 == 0){\n var pixelDensityFloat = ((255 - data.data[i - 1]) / 255.0);\n if(data.data[i - 1] == 0){\n pixelDensity.push(0);\n }else{\n pixelDensity.push(pixelDensityFloat);\n }\n /*\n var pixelDensityFloat = (data.data[i - 1] / 255.0);\n pixelDensity.push(pixelDensityFloat);\n */\n }\n }\n sendToNeuralNet(pixelDensity);\n };\n\n}", "function processImage(args, fileName, processCallback) {\n prepareImage(fileName, function (prepareErr, prepareFileName) {\n if (prepareErr) {\n processCallback(prepareErr, null);\n } else {\n analyzeImage(args, prepareFileName, function (err, analysis) {\n processCallback(err, analysis);\n });\n }\n });\n}", "databaseProcessing(cnv) {\n //Images processing classes\n let h12color = new ColorHistogram(this.redColor, this.greenColor, this.blueColor);\n \n let colmoments = new ColorMoments();\n\n let img = new Picture(0, 0, 100, 100, \"Images/daniel1.jpg\", \"test\");\n\n //Creating an event that will be used to understand when image is already processed\n let eventname = \"processed_picture_\" + img.impath;\n let eventP = new Event(eventname);\n let self = this;\n document.addEventListener(eventname, function() {\n //self.imageProcessed(img, eventname);\n }, false);\n\n //img.computation(cnv, h12color, colmoments, eventP);\n }", "function jsConvFilter(data, width, height, kernel, divisor) {\n const w = kernel[0].length;\n const h = kernel.length;\n const half = Math.floor(h / 2);\n // picture iteration;\n for (var y = 1; y < height - 1; y += 1) {\n for (var x = 1; x < width - 1; x += 1) {\n const px = (y * width + x) * 4; // pixel index\n var r = 0, g = 0, b = 0;\n // core iteration;\n for (var cy = 0; cy < h; ++cy) {\n for (var cx = 0; cx < w; ++cx) {\n // dealing edge case;\n const cpx = ((y + (cy - half)) * width + (x + (cx - half))) * 4;\n r += data[cpx + 0] * kernel[cy][cx];\n g += data[cpx + 1] * kernel[cy][cx];\n b += data[cpx + 2] * kernel[cy][cx];\n }\n }\n\n data[px + 0] = ((r / divisor) > 255) ? 255 : ((r / divisor) < 0) ? 0 : r / divisor;\n data[px + 1] = ((g / divisor) > 255) ? 255 : ((g / divisor) < 0) ? 0 : g / divisor;\n data[px + 2] = ((b / divisor) > 255) ? 255 : ((b / divisor) < 0) ? 0 : b / divisor;\n }\n }\n return data;\n }", "predict(rawImage) {\n const out = ms.tf.tidy(() => {\n const x = ms.tf.tensor4d(rawImage, [1, 64, 64, 1]);\n let h = ms.tf.conv2d(x, this.conv1Kernel, 2, 'valid');\n h = ms.tf.add(h, this.conv1Bias);\n h = ms.tf.relu(h);\n\n h = ms.tf.conv2d(h, this.conv2Kernel, 2, 'valid');\n h = ms.tf.add(h, this.conv2Bias);\n h = ms.tf.relu(h);\n\n h = ms.tf.conv2d(h, this.conv3Kernel, 2, 'valid');\n h = ms.tf.add(h, this.conv3Bias);\n h = ms.tf.relu(h);\n\n h = ms.tf.conv2d(h, this.conv4Kernel, 2, 'valid');\n h = ms.tf.add(h, this.conv4Bias);\n h = ms.tf.relu(h);\n\n const final = ms.tf.reshape(h, [1, 2*2*256]);\n const logits = ms.tf.add(ms.tf.matMul(final, this.outputKernel),\n this.outputBias).squeeze();\n\n return ms.tf.softmax(logits);\n\n });\n const probVector = new Float32Array(out.dataSync());\n out.dispose();\n return probVector;\n }", "function analize(ev){\n\tconsole.log(\"Finding canvas element\");\n\tvar canvas = document.getElementById(\"image\");\n\tvar context = canvas.getContext(\"2d\");\n\tconsole.log(\"Getting image pixels\");\n\tvar img = context.getImageData(0,0,canvas.width,canvas.height);\n\tconsole.log(\"Creating neural network\");\n\tvar analizer = new NN([3, 5, 1]);\n\tanalizer.defaultTraining();\n\tvar total = 0;\n\tconsole.log(analizer.feedforward([32,34,150]));\n\tfor(var i = 0; i < img.data.length; i += 4){\n\t\tr = img.data[i];\n\t\tg = img.data[i+1];\n\t\tb = img.data[i+2];\n\t\tres = analizer.feedforward([r,g,b])[0];\n\t\t\n\t\tif( res > 0.2){\n\t\t\timg.data[i] = 200;\n\t\t\timg.data[i+2] = 200;\n\t\t\ttotal++;\n\t\t}\n\t}\n\tconsole.log(res);\n\tcontext.putImageData(img, 0, 0);\n\t\n\talert((100.0*total/(img.width*img.height))+\"% of the image matches the description\");\n}", "renderImageOld() { // renderImage\r\n var i = this.image.transferToImageBitmap();\r\n this.resizeOffscreenCanvas();\r\n this.ctx.drawImage(i,0,0,this.image.width, this.image.height);\r\n }", "function preprocessImage(image){\n\t// let tensor = tf.fromPixels(image).resizeNearestNeighbor([100,100]).toFloat();\n\tlet tensor = tf.browser.fromPixels(image).resizeNearestNeighbor([size_x,size_y]).toFloat();\n\tlet offset = tf.scalar(255);\n return tensor.div(offset).expandDims();\n}", "function pixelProcess(value) {\n\tvalue*=exposure; // apply exposure\n\tvalue=(value>1)?1:value;\n\tvalue = Math.pow(value, 1/2.2);\t// 2.2 gamma correction\n\treturn value*255;\n}", "function filterEventHandler(e) {\n var copyData = canvasInstance.getCopyData();\n if (!copyData) {\n return alert(\"Please select an image first.\");\n }\n var imageData = canvasInstance.getImageData();\n var context = canvasInstance.getContext();\n var data = imageData.data;\n restore(data, copyData); \n var map = filterMapInstance.getMyFilterMap();\n var key = parseInt(e.target.id);\n \n var tempData = map.get(key)(data, imageData.width, imageData.height); //respective filter handled\n \n canvasInstance.setFilterData(tempData);\n restore(data, tempData);\n context.putImageData(imageData, 0, 0);\n MainApp.getInstance().resetSliders();\n }", "function processHorrorFilter(img, filename){\n let image = img.clone();\n image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) {\n\t\n if (isPixelSurrounded(image.bitmap.data, image.bitmap.width, image.bitmap.height, idx, 1)){\n let northMeanRed = (image.bitmap.data[idx - (image.bitmap.width * 4) - 4] + image.bitmap.data[idx - (image.bitmap.width * 4)] + image.bitmap.data[idx-(image.bitmap.width * 4) + 4]) / 3\n let northMeanGreen = (image.bitmap.data[idx - (image.bitmap.width * 4) - 3] + image.bitmap.data[idx - (image.bitmap.width * 4) + 1] + image.bitmap.data[idx-(image.bitmap.width * 4) + 5]) / 3\n let northMeanBlue = (image.bitmap.data[idx - (image.bitmap.width * 4) - 2] + image.bitmap.data[idx - (image.bitmap.width * 4) + 2] + image.bitmap.data[idx-(image.bitmap.width * 4) + 6]) / 3\n\t\t\t\n let eastMeanRed = (image.bitmap.data[idx - (image.bitmap.width * 4) + 4] + image.bitmap.data[idx + 4] + image.bitmap.data[idx + (image.bitmap.width * 4) + 4]) / 3\n let eastMeanGreen = (image.bitmap.data[idx - (image.bitmap.width * 4) + 5] + image.bitmap.data[idx + 5] + image.bitmap.data[idx + (image.bitmap.width * 4) + 5]) / 3\n let eastMeanBlue = (image.bitmap.data[idx - (image.bitmap.width * 4) + 6] + image.bitmap.data[idx + 6] + image.bitmap.data[idx + (image.bitmap.width * 4) + 6]) / 3\n\t\t \n let southMeanRed = (image.bitmap.data[idx + (image.bitmap.width * 4) - 4] + image.bitmap.data[idx - (image.bitmap.width * 4)] + image.bitmap.data[idx-(image.bitmap.width * 4) + 4]) / 3\n let southMeanGreen = (image.bitmap.data[idx + (image.bitmap.width * 4) - 3] + image.bitmap.data[idx - (image.bitmap.width * 4) + 1] + image.bitmap.data[idx-(image.bitmap.width * 4) + 5]) / 3\n let southMeanBlue = (image.bitmap.data[idx + (image.bitmap.width * 4) - 2] + image.bitmap.data[idx - (image.bitmap.width * 4) + 2] + image.bitmap.data[idx-(image.bitmap.width * 4) + 6]) / 3\n\t\t\t\n let westMeanRed = (image.bitmap.data[idx - (image.bitmap.width * 4) - 4] + image.bitmap.data[idx + (image.bitmap.width * 4)] + image.bitmap.data[idx + (image.bitmap.width * 4) + 4]) / 3\n let westMeanGreen = (image.bitmap.data[idx - (image.bitmap.width * 4) - 3] + image.bitmap.data[idx + (image.bitmap.width * 4) + 1] + image.bitmap.data[idx + (image.bitmap.width * 4) + 5]) / 3\n let westMeanBlue = (image.bitmap.data[idx - (image.bitmap.width * 4) - 2] + image.bitmap.data[idx + (image.bitmap.width * 4) + 2] + image.bitmap.data[idx + (image.bitmap.width * 4) + 6]) / 3\n\t\t\t\n image.bitmap.data[idx] = Math.min(northMeanRed, eastMeanRed, southMeanRed, westMeanRed, 100);\n image.bitmap.data[idx + 1] = Math.min(northMeanGreen, eastMeanGreen, southMeanGreen, westMeanGreen, 100);\n image.bitmap.data[idx + 2] = Math.min(northMeanBlue, eastMeanBlue, southMeanBlue, westMeanBlue, 100);\n\t\t\t\n image.bitmap.data[idx + 3] = 255;\n } \n\t\n });\n\n image.write(filename);\n console.log(getCurrentTime() + '> Horror Filter version of image saved as <' + filename + '>.');\n\n return image;\n}", "_drawImage() {\n if (!(this._width > 0 && this._height > 0 && !!this._image)) {\n return\n }\n\n let b = this._getBounds()\n\n this._context.drawImage(\n this._image,\n b.sx,\n b.sy,\n b.sw,\n b.sh,\n b.dx,\n b.dy,\n b.dw,\n b.dh,\n )\n\n this._averageColor = this._calculateAverageColor(this.getImageData())\n }", "function processImage(orgfilename){\n\n var destimg = filepath + output_directory + orgfilename;\n var orgimg = filepath + input_directory + orgfilename;\n\n cv.readImage(orgimg, function(err, im) {\n\n im.convertGrayscale();\n im_canny = im.copy();\n im_canny.canny(lowThresh, highThresh);\n im_canny.dilate(nIters);\n\n contours = im_canny.findContours();\n var points = [];\n\n console.log(\"contours size = \" + contours.size());\n\n for(i = 0; i < contours.size(); i++) {\n\n var area = contours.area(i);\n\n console.log(\"area\" + area);\n if(area < minArea)\n continue;\n\n var arcLength = contours.arcLength(i, true);\n contours.approxPolyDP(i, 0.01 * arcLength, true);\n\n if(contours.cornerCount(i) != 4)\n continue;\n\n // point coordinates\n var p0 = [contours.point(i, 0).x, contours.point(i, 0).y];\n var p1 = [contours.point(i, 1).x, contours.point(i, 1).y];\n var p2 = [contours.point(i, 2).x, contours.point(i, 2).y];\n var p3 = [contours.point(i, 3).x, contours.point(i, 3).y];\n\n var av_x = (p0[0] + p1[0] + p2[0] + p3[0])/4;\n var av_y = (p0[1] + p1[1] + p2[1] + p3[1])/4;\n\n points.push([av_x,av_y]);\n }\n\n var shape = new shapemaker();\n var data = {\n image_width: im_canny.width(),\n image_height: im_canny.height(),\n coordinates: points\n };\n\n console.log(points);\n\n shape.mask(data, orgimg, destimg, function(err, destimage){\n sb.send(\"output image\", \"string\", hosted_path + output_directory + orgfilename);\n });\n\n });\n}", "function imagePrediction(error, result)\r\n{\r\n if (error)\r\n {\r\n console.error(error);\r\n }\r\n else\r\n {\r\n prediction = result;\r\n //calls itself because we want to constantly check what the image is.\r\n classifier.classify(imagePrediction);\r\n }\r\n}", "function applyFilters() {\r\n Caman(\"#canvas\", img, function() {\r\n this.revert(false);\r\n this.brightness(brightnessValue)\r\n .contrast(contrastValue)\r\n .saturation(saturationValue)\r\n .vibrance(vibranceValue)\r\n .exposure(exposureValue)\r\n .hue(hueValue)\r\n .sepia(sepiaValue)\r\n .gamma(gammaValue)\r\n .noise(noiseValue)\r\n .clip(clipValue)\r\n .sharpen(sharpenValue)\r\n .stackBlur(stackBlurValue)\r\n .render();\r\n });\r\n}" ]
[ "0.66036105", "0.62568533", "0.6216518", "0.61938566", "0.58362776", "0.5509829", "0.54928154", "0.54900795", "0.5464914", "0.54426533", "0.5434077", "0.53780484", "0.52914435", "0.5285847", "0.52688164", "0.5246969", "0.52456605", "0.52403015", "0.5228871", "0.5190686", "0.51886445", "0.51837003", "0.51729715", "0.5144663", "0.51185614", "0.5115478", "0.50997293", "0.5085545", "0.5084897", "0.5075967" ]
0.7529932
0
This pulls out the computations from the component and computes them with the optimizer.
_isolatedComputeForWrapper(component) { const computations = ReactInterpreter.computations(component); return this.optimizer.compute(computations); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_precomputeComputeForWrapper(component) {\n const computations = ReactInterpreter.computations(component);\n const computedValues = this.optimizer.compute(computations);\n this.renderer.notifyAboutCompute(component, computations, computedValues);\n return computedValues;\n }", "compute()\n {\n super.compute();\n this.needsRecompute = false;\n }", "compute()\n {\n super.compute();\n this.needsRecompute = false;\n }", "compute() {\n const v = {}\n const ev = this.electric.compute()\n const tv = this.thermal.compute()\n\n let cv\n let tev\n\n if (this.electric.source == this.thermal.source) {\n cv = this.combinedPowerBlockRequirements(this.electric.source, ev, tv)\n tev = this.totalEnergyBlockCosts(ev, tv, cv)\n } else if (this.electric.source == 'NGCC w/ CCS') {\n tev = this.ngUtilitySection(ev, tv)\n } else {\n throw 'TODO: handle case with mismatched energy sources'\n }\n\n const dv = this.dac.compute()\n\n // Total Capital Cost [M$]\n v['Total Capital Cost [M$]'] =\n tev['Total Capital Cost [M$]'] +\n dv['Capital Cost (including Lead Time) [M$]']\n\n // Capital Recovery [$/tCO2eq]\n v['Capital Recovery [$/tCO2eq]'] =\n (v['Total Capital Cost [M$]'] * this.recoveryFactor() * MILLION) /\n this.params['Scale [tCO2/year]']\n\n // Fixed O&M [$/tCO2eq]\n v['Fixed O&M [$/tCO2eq]'] =\n tev['Fixed O&M [$/tCO2eq]'] + dv['Fixed O&M [$/tCO2eq]']\n\n // Variable O&M [$/tCO2eq]\n v['Variable O&M [$/tCO2eq]'] =\n tev['Variable O&M [$/tCO2eq]'] + dv['Variable O&M [$/tCO2eq]']\n\n // Natural Gas Cost [$/tCO2]\n v['Natural Gas Cost [$/tCO2]'] = tev['Natural Gas Cost [$/tCO2eq]']\n\n // Emitted [tCO2eq/tCO2]\n v['Emitted [tCO2/tCO2]'] = tev['Emitted [tCO2/tCO2]']\n\n const emissionsFactor = this.calcEmissionsFactor(\n tev['Natural Gas Use [mmBTU/tCO2eq]'],\n v['Emitted [tCO2/tCO2]']\n )\n\n // Capital Recovery [$/tCO2eq Net Removed]\n v['Capital Recovery [$/tCO2eq Net Removed]'] =\n v['Capital Recovery [$/tCO2eq]'] / emissionsFactor\n\n // Variable O&M [$/tCO2eq Net Removed]\n v['Variable O&M [$/tCO2eq Net Removed]'] =\n v['Variable O&M [$/tCO2eq]'] / emissionsFactor\n\n // Natural Gas Cost [$/tCO2 Net Removed]\n v['Natural Gas Cost [$/tCO2 Net Removed]'] =\n v['Natural Gas Cost [$/tCO2]'] / emissionsFactor\n\n // Fixed O&M [$/tCO2eq Net Removed]\n v['Fixed O&M [$/tCO2eq Net Removed]'] =\n v['Fixed O&M [$/tCO2eq]'] / emissionsFactor\n\n // Total Cost [$/tCO2]\n v['Total Cost [$/tCO2 Net Removed]'] =\n v['Capital Recovery [$/tCO2eq Net Removed]'] +\n v['Fixed O&M [$/tCO2eq Net Removed]'] +\n v['Variable O&M [$/tCO2eq Net Removed]'] +\n v['Natural Gas Cost [$/tCO2 Net Removed]']\n\n return v\n }", "compute(){\n let computation\n //converting strings to number for computation\n const prev = parseFloat(this.previousOperand)\n const current = parseFloat(this.currentOperand)\n //to check if numbers were actually inputed before any computation\n if (isNaN(prev) || isNaN(current)) return\n switch (this.operation) {\n case '+' :\n computation = prev + current\n break\n case '-' :\n computation = prev - current\n break\n case '×' :\n computation = prev * current\n break\n case '÷' :\n computation = prev / current\n break\n default:\n return\n }\n this.toReset = true,\n this.currentOperand = computation\n this.operation = undefined\n this.previousOperand = ''\n }", "function doComputation(){\n let computation;\n const prev = parseFloat(previousOperand);\n const current = parseFloat(currentOperand);\n\n if(isNaN(prev) || isNaN(current)) return;\n switch(operation){\n case '+':\n computation=prev + current;\n break;\n case '-':\n computation=prev - current;\n break;\n case 'x':\n computation=prev * current;\n break;\n case '/':\n computation= prev / current;\n break;\n default :\n return;\n }\n\n currentOperand=computation;\n operation=undefined;\n previousOperand=''; \n}", "compute() {\n\n}", "compute(operation) {\n const modes = this.getMode()\n const mode_1 = this.getDigitFromRight(modes, 1)\n const mode_2 = this.getDigitFromRight(modes, 2)\n const mode_3 = this.getDigitFromRight(modes, 3)\n const param_1 = this.program[this.PC+1]\n const param_2 = this.program[this.PC+2]\n const param_3 = this.program[this.PC+3]\n\n const value_1 = this.getValue(mode_1, param_1)\n const value_2 = this.getValue(mode_2, param_2)\n const ans_index = this.getIndex(param_3, mode_3)\n switch (operation) {\n case 1:\n this.program[ans_index] = value_1 + value_2\n break;\n case 2:\n this.program[ans_index] = value_1 * value_2\n break;\n case 7:\n this.program[ans_index] = (value_1 < value_2) ? 1 : 0\n break;\n case 8:\n this.program[ans_index] = (value_1 === value_2) ? 1 : 0\n break;\n default:\n return;\n }\n this.PC += 4\n }", "compute() {\n let result;\n let lastnum = parseFloat(this.lastOperand);\n let currnum = parseFloat(this.currOperand);\n if (isNaN(lastnum) || isNaN(currnum)) {\n return;\n }\n switch (this.operator) {\n case \"+\":\n result = lastnum + currnum;\n break;\n case \"-\":\n result = lastnum - currnum;\n break;\n case \"*\":\n result = lastnum * currnum;\n break;\n case \"/\":\n result = lastnum / currnum;\n break;\n default:\n return;\n }\n this.currOperand = result;\n this.lastOperand = \"\";\n this.operator = undefined;\n }", "function compute () {\n // set value\n util.forEach(expressions, function(exp, index) {\n var v = that.$exec(exp)\n if (!v[0]) caches[index] = v[1]\n })\n // get content\n var str = ''\n util.forEach(parts, function(item, index) {\n str += emptyStr(item)\n if (index < expressions.length) {\n str += emptyStr(caches[index])\n }\n })\n return Expression.unveil(str)\n }", "async startCompute() {\n await this._preparedModel.execute(this._inputs, this._outputs);\n return ResultCode.NO_ERROR;\n }", "function compute () {\n\t // set value\n\t util.forEach(expressions, function(exp, index) {\n\t var v = that.$exec(exp)\n\t if (!v[0]) caches[index] = v[1]\n\t })\n\t // get content\n\t var frags = []\n\t util.forEach(parts, function(item, index) {\n\t frags.push(item)\n\t if (index < expressions.length) {\n\t frags.push(caches[index])\n\t }\n\t })\n\t return Expression.unveil(frags.join(''))\n\t }", "function mainCompute()\n{\n\tlet expr = document.getElementById(\"inputSpecificFunction\").value;\n\tlet optionF\n\tif(expr != \"\")\n\t{\n\t\ttry {\n\t\t\toptionF = math.parse(expr)\n\t\t} catch (e) {\n\t\t\tconsole.log(\"Wrong syntax\")\n\t\t\talert(\"The entered function has a syntax error\")\n\t\t}\n\n\t\tlet latex = optionF.toTex()\n\t\tdocument.getElementById(\"labelSpecificFunction\").innerHTML = \"\\\\(f(x) = \" + latex + \"\\\\)\"\n\t\tMathJax.typeset()\n\t}\n\telse{\n\t\toptionF = f;\n\t}\n\n let optionN = parseFloat(document.getElementById(\"optionN\").value);\n\tlet optionH = parseFloat(document.getElementById(\"optionH\").value);\n\tlet optionA = parseFloat(document.getElementById(\"optionA\").value);\n\tlet optionI = {\"a\": parseFloat(document.getElementById(\"optionRangeStart\").value), \"b\": parseFloat(document.getElementById(\"optionRangeEnd\").value)};\n\tlet optionDX = parseFloat(document.getElementById(\"optionDX\").value);\n\tlet optionNaive = document.getElementById(\"checkOldMethod\").checked;\n let tmp = document.getElementById(\"optionDerivatives\").value.split(\",\");\n let optionDerivative = [];\n tmp.forEach( i => {\n optionDerivative.push(parseInt(i)); //Transform to int\n });\n\n\tneedsRebuild = true;\n\n\tcompute(optionF, optionN, optionH, optionA, optionI, optionDX, optionDerivative, optionNaive);\n\tmainGraph.update();\n}", "compute() {\n let v = {}\n\n // Operational Hours[h / yr]\n const operationalHours = this.params['DAC Capacity Factor'] * HOURS_PER_YEAR\n\n // Planned Capacity Factor\n v['Planned Capacity Factor'] = this.tech['Availability']\n\n // Electric Power Requirement[MW](aka low value case in C1)\n v['Base Energy Requirement [MW]'] = this.baseReq\n\n // calculate battery params now\n if (this.battery) {\n // TODO: check that this is the correct value to pass to the battery computation\n const bat = this.battery.compute(v)\n v = Object.assign(v, bat)\n }\n\n // Plant Size[MW]\n v['Plant Size [MW]'] =\n v['Base Energy Requirement [MW]'] / v['Planned Capacity Factor']\n if (this.battery) {\n v['Plant Size [MW]'] += v['Increased Need [MW]']\n }\n\n // Overnight Cost [M$]\n v['Overnight Cost [M$]'] =\n this.tech['Base Plant Cost [M$]'] *\n (v['Plant Size [MW]'] / this.tech['Plant Size [MW]']) **\n this.tech['Scaling Factor']\n\n // Lead Time Multiplier\n v['Lead Time Multiplier'] = this.leadTimeMult(\n this.tech['Lead Time [Years]'].toFixed(0)\n )\n\n // Capital Cost [M$]\n v['Capital Cost [M$]'] =\n v['Overnight Cost [M$]'] * v['Lead Time Multiplier']\n\n // Total Capital Cost [M$]\n v['Total Capital Cost [M$]'] = v['Capital Cost [M$]']\n if (this.battery) {\n v['Total Capital Cost [M$]'] += v['Battery Capital Cost [M$]']\n }\n\n // Annual Capital Recovery Factor\n const annualCapitalRecoveryFactor = this.recoveryFactor()\n\n // Capital Recovery[$/tCO2eq]\n v['Capital Recovery [$/tCO2eq]'] =\n (v['Total Capital Cost [M$]'] * annualCapitalRecoveryFactor * MILLION) /\n this.params['Scale [tCO2/year]']\n\n // Power Fixed O&M [$/tCO2eq]\n v['Power Fixed O&M [$/tCO2eq]'] =\n (this.tech['Base Plant Annual Fixed O&M [$M]'] *\n (v['Plant Size [MW]'] / this.tech['Plant Size [MW]']) **\n this.tech['Scaling Factor'] *\n MILLION) /\n this.params['Scale [tCO2/year]']\n\n // Power Variable O&M [$/tCO2eq]\n v['Power Variable O&M [$/tCO2eq]'] =\n (this.tech['Variable O&M [$/MWhr]'] *\n v['Plant Size [MW]'] *\n operationalHours) /\n this.params['Scale [tCO2/year]']\n\n // Total Fixed O&M [$/tCO2eq]\n v['Total Fixed O&M [$/tCO2eq]'] = v['Power Fixed O&M [$/tCO2eq]']\n if (this.battery) {\n v['Total Fixed O&M [$/tCO2eq]'] += v['Battery Fixed O&M [$/tCO2eq]']\n }\n\n // Total Variable O&M [$/tCO2eq]\n v['Total Variable O&M [$/tCO2eq]'] = v['Power Variable O&M [$/tCO2eq]']\n if (this.battery) {\n v['Total Variable O&M [$/tCO2eq]'] += v['Battery Variable O&M [$/tCO2eq]']\n }\n\n // Natural Gas Use[mmBTU / tCO2eq]\n const heatRate = this.tech['Final Heat Rate [BTU/kWh]']\n if (heatRate) {\n v['Natural Gas Use [mmBTU/tCO2eq]'] =\n (operationalHours *\n v['Plant Size [MW]'] *\n KW_TO_MW *\n this.tech['Final Heat Rate [BTU/kWh]']) /\n MILLION /\n this.params['Scale [tCO2/year]']\n } else {\n v['Natural Gas Use [mmBTU/tCO2eq]'] = 0.0\n }\n\n // Natural Gas Cost [$/tCO2eq]\n v['Natural Gas Cost [$/tCO2eq]'] =\n v['Natural Gas Use [mmBTU/tCO2eq]'] *\n this.params['Natural Gas Cost [$/mmBTU]']\n\n // Emitted tCO2eq / tCO2\n if (v['Natural Gas Use [mmBTU/tCO2eq]'] > 0) {\n v['Emitted [tCO2/tCO2]'] =\n v['Natural Gas Use [mmBTU/tCO2eq]'] *\n this.tech['Total CO2 eq [lb/mmbtu]'] *\n LB_TO_METRIC_TON *\n (1 - this.tech['Capture Efficiency'])\n } else {\n v['Emitted [tCO2/tCO2]'] = 0\n }\n\n return v\n }", "function calculate() {\r\n\teval();\r\n\tstopAll();\r\n}", "function startTest() {\n var t = performance.now()\n var mgr = cachedMgr\n compNames = []\n Es = []\n procs = []\n // create a bunch of components\n for (var i=0; i<numCs; ++i) {\n compNames[i] = 'comp_'+String(i)\n var obj = { state: {value:1} }\n obj.state[String(Math.random())] = 1\n mgr.addComponent(compNames[i], obj)\n }\n // create a bunch of entities and randomly add components\n for (var i=0; i<numEs; ++i) {\n var n = (numCs * Math.random())|0\n var toAdd = []\n for (var j=0; j<numCsPerE; ++j) {\n toAdd.push(compNames[(n+j)%numCs])\n }\n Es.push( mgr.createEntity(toAdd) )\n }\n // create a bunch of processes that sum up state properties\n for (var i=0; i<numCs; ++i) {\n var o = {}\n o.name = compNames[i]\n o.update = function(dt) {\n var sum = 0\n var entList = mgr.getComponentsData(this.name)\n var ids = Object.keys(entList)\n for (var j=0; j<ids.length; ++j) {\n sum += entList[ids[j]].value|0\n }\n runningSum += sum|0\n }\n procs.push(o)\n mgr.addProcessor(o)\n }\n // finish up and iterate\n initTime = performance.now() - t\n iterating = true\n runTime = runCt = runningSum = 0\n requestAnimationFrame(iterateTest)\n}", "compute() {\r\n let computation\r\n //parseFloat converts a string argument and converts it to a float\r\n const prev = parseFloat(this.previousOperand)\r\n const current = parseFloat(this.currentOperand)\r\n //NaN means Not a Number\r\n if (isNaN(prev) || isNaN(current)) return\r\n //here, you are matching up the values and operations buttons\r\n switch (this.operation) {\r\n case '+':\r\n computation = prev + current\r\n break\r\n case '-':\r\n computation = prev - current\r\n break\r\n case 'x':\r\n computation = prev * current\r\n break\r\n case '/':\r\n computation = prev / current\r\n break\r\n \r\n default:\r\n return\r\n }\r\n //actual computation taking place\r\n this.currentOperand = computation\r\n this.operation = undefined\r\n this.previousOperand = ''\r\n }", "function compute() {\n sum = x_1*w_1 + x_2*w_2 + x_3*w_3; \n a = sum - theta;\n if (btn_threshold.isOn()) {\n y = func_step(a);\n }\n if (btn_sigmoid.isOn()) {\n y = func_sigmoid(a);\n }\n if (btn_tanh.isOn()) {\n y = func_tanh(a);\n }\n}", "function compute () {\n var ts = 24*3600;\n var n = m.length;\n var all_forces = [];\n for(var ii = 0; ii < n; ii++) {\n\tvar tot_fx = 0;\n\tvar tot_fy = 0;\n\tfor(var jj = 0; jj < n; jj++) {\n\t if(ii == jj) {\n\t\tcontinue;\n\t }\n\t var my_forces = forces(ii,jj);\n\t tot_fx += my_forces[0];\n\t tot_fy += my_forces[1];\n\t all_forces.push([tot_fx,tot_fy]);\n\t}\n }\n\n for(var ii = 0; ii < n; ii++) {\n\tvx[ii] += (all_forces[ii][0]/m[ii])*ts;\n\tvy[ii] += (all_forces[ii][1]/m[ii])*ts;\n\tx[ii] += vx[ii]*ts;\n\ty[ii] += vy[ii]*ts;\n }\n\n}", "compute()\n {\n //we update our input values\n super.compute();\n\n if(this.needsRecompute)\n {\n //actual node work\n this.ios['oColor'].value = lerpColor(this.ios['iColor1'].value,this.ios['iColor2'].value,this.ios['iMix'].value);\n this.needsRecompute = false;\n }\n }", "compute() {\n const v = {}\n\n // Total Overnight Capital Cost [M$]\n v['Total Capital Cost [M$]'] =\n (this.params['Capex [$]'] * this.params['Scale [tCO2/year]']) / MILLION\n\n // Lead Time Multiplier\n v['Lead Time Multiplier'] = this.leadTimeMult(\n this.params['DAC Section Lead Time [years]']\n )\n\n // Capital Cost(including Lead Time)[M$]\n v['Capital Cost (including Lead Time) [M$]'] =\n v['Total Capital Cost [M$]'] * v['Lead Time Multiplier']\n\n // Capital Recovery[$/tCO2eq]\n v['Capital Recovery [$/tCO2eq]'] =\n (v['Capital Cost (including Lead Time) [M$]'] *\n this.recoveryFactor() *\n MILLION) /\n this.params['Scale [tCO2/year]']\n\n // Fixed O&M [$/tCO2eq]\n v['Fixed O&M [$/tCO2eq]'] = this.params['Fixed O&M Costs [$/tCO2]']\n\n // Variable O&M [$/tCO2eq]\n v['Variable O&M [$/tCO2eq]'] = this.params['Variable O&M Cost [$/tCO2]']\n\n return v\n }", "compute(){\r\n let computation;\r\n const prev = parseFloat(this.previousOperand);\r\n const current = parseFloat(this.currentOperand);\r\n \r\n // if user clicks equals only\r\n // return cancels the function completely further\r\n if (isNaN(prev) || isNaN(current)) return;\r\n \r\n switch(this.operation){\r\n case'+':\r\n computation = prev + current;\r\n break;\r\n case '-':\r\n computation = prev - current;\r\n break;\r\n case '*':\r\n computation = prev * current;\r\n break;\r\n case '÷':\r\n computation = prev / current; \r\n break;\r\n default:\r\n return;\r\n }\r\n this.readyToReset = true;\r\n this.currentOperand = computation\r\n this.operation = undefined\r\n this.previousOperand = ''\r\n }", "calcVars () {}", "function calcA(x){\n const unstackedX = tf.unstack(x);\n const accelerations = Array(numberOfPlanets).fill(tf.tensor1d([0,0,0]));\n\n for(let i = 0; i<numberOfPlanets; i++){\n const iX = unstackedX[i]\n for(let j = 0; j<numberOfPlanets; j++){\n const jX = unstackedX[j]\n const vector = tf.sub(jX, iX)\n const r = tf.norm(vector);\n\n const force = G.mul(masses[i])\n .mul(masses[j])\n .div(tf.pow(r,3));\n accelerations[i] = accelerations[i].add(force);\n accelerations[j] = accelerations[j].sub(force);\n\n } // for loop i\n accelerations[i] = accelerations[i].div(masses[i]);\n } // for loop i\n return tf.stack(accelerations);\n} // calcA()", "computeResult(result) {\n }", "step() {\n\t\t\tthis.iter += 1;\n\t\t\tconst N = this.N;\n\n\t\t\tconst cg = this.costAndGradient(this.solution); // evaluate gradient\n\t\t\tconst cost = cg.cost;\n\t\t\tconst grad = cg.grad;\n\n\t\t\t// perform gradient step\n\t\t\tconst ymean = zeros(this.dim);\n\t\t\tfor (let i = 0; i < N; i++) {\n\t\t\t\tfor (let d = 0; d < this.dim; d++) {\n\t\t\t\t\tconst gid = grad[i][d];\n\t\t\t\t\tconst sid = this.ystep[i][d];\n\t\t\t\t\tconst gainid = this.gains[i][d];\n\n\t\t\t\t\t// compute gain update\n\t\t\t\t\tlet newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2;\n\t\t\t\t\tif (newgain < 0.01) newgain = 0.01; // clamp\n\t\t\t\t\tthis.gains[i][d] = newgain; // store for next turn\n\n\t\t\t\t\t// compute momentum step direction\n\t\t\t\t\tconst momval = this.iter < 250 ? 0.5 : 0.8;\n\t\t\t\t\tconst newsid = momval * sid - this.epsilon * newgain * grad[i][d];\n\t\t\t\t\tthis.ystep[i][d] = newsid; // remember the step we took\n\n\t\t\t\t\t// step!\n\t\t\t\t\tthis.solution[i][d] += newsid;\n\n\t\t\t\t\tymean[d] += this.solution[i][d]; // accumulate mean so that we can center later\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// reproject Y to be zero mean\n\t\t\tfor (let i = 0; i < N; i++) {\n\t\t\t\tfor (let d = 0; d < this.dim; d++) {\n\t\t\t\t\tthis.solution[i][d] -= ymean[d] / N;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.iter % 100 === 0) console.log(`iter ${this.iter}, cost: ${cost}`);\n\t\t\treturn cost; // return current cost\n\t\t}", "compute() {\n if (this.active) {\n this.x2 = event.clientX;\n this.y2 = event.clientY;\n this.reCalc(this.x1, this.x2, this.y1, this.y2);\n }\n }", "execute(inputs, outputs) {\n inputs = this.mapInputs(inputs);\n const names = Object.keys(inputs).sort();\n this.checkInputs(inputs);\n this.checkInputShapeAndType(inputs);\n outputs = this.mapOutputs(outputs);\n this.checkOutputs(outputs);\n const inputNodes = names.map(name => this.graph.nodes[Object(_operations_executors_utils__WEBPACK_IMPORTED_MODULE_1__[\"parseNodeName\"])(name)[0]]);\n const outputNodeNames = outputs.map(name => Object(_operations_executors_utils__WEBPACK_IMPORTED_MODULE_1__[\"parseNodeName\"])(name)[0]);\n let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n // If no outputs are specified, then use the default outputs of the model.\n if (outputNodes.length === 0) {\n outputNodes = this._outputs;\n }\n const compilationKey = this.getCompilationKey(inputNodes, outputNodes);\n // Do nothing if the compiled graph cache contains the input.\n let orderedNodes = this.compiledMap.get(compilationKey);\n if (orderedNodes == null) {\n orderedNodes = this.compile(inputs, outputNodes);\n this.compiledMap.set(compilationKey, orderedNodes);\n }\n const tensorArrayMap = {};\n const tensorListMap = {};\n return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"tidy\"])(() => {\n const context = new _execution_context__WEBPACK_IMPORTED_MODULE_3__[\"ExecutionContext\"](this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap);\n const tensorsMap = Object.assign({}, this.weightMap);\n Object.keys(inputs).forEach(name => {\n const [nodeName, index] = Object(_operations_executors_utils__WEBPACK_IMPORTED_MODULE_1__[\"parseNodeName\"])(name);\n const tensors = [];\n tensors[index] = inputs[name];\n tensorsMap[nodeName] = tensors;\n });\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const intermediateTensorConsumerCount = {};\n for (let i = 0; i < orderedNodes.length; i++) {\n const node = orderedNodes[i];\n if (!tensorsMap[node.name]) {\n const tensors = Object(_operations_operation_executor__WEBPACK_IMPORTED_MODULE_2__[\"executeOp\"])(node, tensorsMap, context, this._resourceManager);\n if (_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"util\"].isPromise(tensors)) {\n throw new Error(`The execution of the op '${node.op}' returned a promise. ` +\n `Please use model.executeAsync() instead.`);\n }\n tensorsMap[node.name] = tensors;\n this.checkTensorForDisposal(node.name, node, tensorsMap, context, tensorsToKeep, outputNodeNames, intermediateTensorConsumerCount);\n }\n }\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(tensorsToKeep);\n }\n return outputs.map(name => Object(_operations_executors_utils__WEBPACK_IMPORTED_MODULE_1__[\"getTensor\"])(name, tensorsMap, context));\n });\n }", "function doComputation() {\n var $computation = document.getElementById('computation');\n var $result = document.getElementById('result');\n var $error = document.getElementById('error');\n var $errorMessage = document.getElementById('errorMessage');\n var $errorInput = document.getElementById('errorInput');\n var input = $computation.value;\n var algebraType = readConfig();\n var maybeResult = evaluate(algebraType, input);\n if (maybeResult instanceof ParseError) {\n $error.style.display = 'block';\n $errorMessage.innerText = maybeResult.msg;\n $errorInput.innerHTML = frameError(maybeResult, input);\n }\n else {\n $error.style.display = 'none';\n }\n var lin = (maybeResult instanceof ParseError) ? algebraUnit(0) : maybeResult;\n $result.innerText = algebraString(lin);\n writeTable(algebraType, lin);\n}", "function computeValues() {\n\t\t\t\n\t\t\tvar scaler;\n\t\t\t// deal with loop\n\t\t\tif (repeat > 0) {\n\t\t\t\t// not first run, save last scale ratio\n\t\t\t\txFrom = xTo;\n\t\t\t\tyFrom = yTo;\n\t\t\t\tratioFrom = ratioTo;\n\t\t\t} else {\n\t\t\t\t// get the scaler using conf options\n\t\t\t\tscaler = $.pixelentity.Geom.getScaler(zoom == \"out\" ? \"fill\" : \"none\",align.w,align.h,w,h,tw,th);\n\t\t\t\txFrom = scaler.offset.w;\n\t\t\t\tyFrom = scaler.offset.h;\n\t\t\t\tratioFrom = scaler.ratio;\n\t\t\t}\n\t\t\t\n\t\t\tscaler = $.pixelentity.Geom.getScaler(zoom == \"in\" ? \"fill\" : \"none\",pan.w,pan.h,w,h,tw,th);\n\t\t\txTo = scaler.offset.w;\n\t\t\tyTo = scaler.offset.h;\n\t\t\tratioTo = scaler.ratio;\n\t\t\t\n\t\t\txPrev = 0;\n\t\t\tyPrev = 0;\n\t\t\t\n\t\t\tduration = parseFloat(normalized)*33;\n\t\t\t\n\t\t\t// reset counter\n\t\t\tcounter = 0;\n\t\t\t\n\t\t\t// update runs count\n\t\t\trepeat++;\n\t\t\t\n\t\t}" ]
[ "0.7077152", "0.62705755", "0.62705755", "0.6016874", "0.59885037", "0.5929261", "0.59225583", "0.5918945", "0.58713543", "0.5763892", "0.5751716", "0.5737336", "0.57049686", "0.5602473", "0.5596236", "0.5586118", "0.55707955", "0.55706054", "0.54861856", "0.54546505", "0.54542613", "0.5452787", "0.54387873", "0.535792", "0.5352571", "0.53410494", "0.5336125", "0.5332674", "0.53258467", "0.5313712" ]
0.68461645
1
This requires cooperation between the optimizer and the renderer, so we create a loggit API that allows that. It also breaks the loggit.compute method to take a component instead of just a description of computation.
_withPrecomputeRenderer(reactClass, el, log, optimizerClass) { const optimizer = new optimizerClass(log); const loggit = { recordFact: log.recordFact.bind(log), computeFor: this._precomputeComputeForWrapper.bind(this), experimental: { forceCompaction: this._experimentalCompaction.bind(this) } }; const renderer = new PrecomputeReactRenderer(reactClass, el, loggit, { optimizer }); return {optimizer, renderer, loggit}; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_precomputeComputeForWrapper(component) {\n const computations = ReactInterpreter.computations(component);\n const computedValues = this.optimizer.compute(computations);\n this.renderer.notifyAboutCompute(component, computations, computedValues);\n return computedValues;\n }", "_isolatedComputeForWrapper(component) {\n const computations = ReactInterpreter.computations(component);\n return this.optimizer.compute(computations);\n }", "function glCompute( htmlTargetId ) {\n\n\tthis.containerId = htmlTargetId\n\n\tthis.canvasContextOpts = {\t\t\n\t\tpremultipliedAlpha: false,\n\t\tpreserveDrawingBuffer: false\n\t\t//alpha: false\n\t};\n\t\n\tthis.stages = []\n\tthis.computeLoop = 0\n}", "_withIsolatedComponents(reactClass, el, log, optimizerClass, rendererClass) {\n const optimizer = new optimizerClass(log);\n const loggit = {\n recordFact: log.recordFact.bind(log),\n computeFor: this._isolatedComputeForWrapper.bind(this),\n experimental: {\n forceCompaction: this._experimentalCompaction.bind(this)\n }\n };\n const renderer = new rendererClass(reactClass, el, loggit);\n return {optimizer, renderer, loggit};\n }", "function LogOperator(){}", "async run() {\n if (!this.executionInfos)\n throw new Error('ExecutionInfos is not loaded');\n if (!this.inputViews || !this.outputViews)\n throw new Error('getInputViews and getOutputViews must be called prior to run');\n if (!this.staticBuffer)\n throw new Error('StaticBuffer is not initialized');\n if (!this.dynamicBuffer)\n throw new Error('DynamicBuffer is not initialized');\n if (!this.metaBuffers)\n throw new Error('MetaBuffer is not initialized');\n if (!this.placeholderContext)\n throw new Error('PlaceholderContext is not initialized');\n if (!this.placeholderContext.isResolved)\n throw new Error(`Not all placeholders are resolved: ${this.placeholderContext}`);\n let staticBuffer = this.staticBuffer;\n let dynamicBuffer = this.dynamicBuffer;\n let metaBuffers = this.metaBuffers;\n if (webdnn_1.getConfiguration('DEBUG', false)) {\n let records = [];\n let totalElapsedTime = 0;\n for (let i = 0; i < this.executionInfos.length; i++) {\n let exec_info = this.executionInfos[i];\n let start = performance.now();\n await this.webgpuHandler.executeSinglePipelineState('descriptor.' + exec_info.entry_func_name, exec_info.threadgroups_per_grid, exec_info.threads_per_thread_group, [staticBuffer, dynamicBuffer, metaBuffers[i]], true);\n let elapsedTime = performance.now() - start;\n records.push({\n 'Kernel': exec_info.entry_func_name,\n 'Elapsed time [ms]': elapsedTime\n });\n totalElapsedTime += elapsedTime;\n }\n let summary = Array.from(Object.values(records.reduce((summary, record) => {\n if (!(record['Kernel'] in summary)) {\n summary[record['Kernel']] = {\n 'Kernel': record['Kernel'],\n 'Count': 0,\n 'Elapsed time [ms]': 0,\n };\n }\n summary[record['Kernel']]['Count']++;\n summary[record['Kernel']]['Elapsed time [ms]'] += record['Elapsed time [ms]'];\n return summary;\n }, {})));\n summary.forEach(record => record['Ratio [%]'] = (record['Elapsed time [ms]'] / totalElapsedTime).toFixed(2));\n console.table(records);\n console.table(summary);\n }\n else {\n let complete_promise = null;\n for (let i = 0; i < this.executionInfos.length; i++) {\n let exec_info = this.executionInfos[i];\n let is_last = i == this.executionInfos.length - 1;\n complete_promise = this.webgpuHandler.executeSinglePipelineState('descriptor.' + exec_info.entry_func_name, exec_info.threadgroups_per_grid, exec_info.threads_per_thread_group, [staticBuffer, dynamicBuffer, metaBuffers[i]], is_last);\n }\n return complete_promise; //wait to finish final kernel\n }\n // this._running = false;\n }", "function compute () {\n // set value\n util.forEach(expressions, function(exp, index) {\n var v = that.$exec(exp)\n if (!v[0]) caches[index] = v[1]\n })\n // get content\n var str = ''\n util.forEach(parts, function(item, index) {\n str += emptyStr(item)\n if (index < expressions.length) {\n str += emptyStr(caches[index])\n }\n })\n return Expression.unveil(str)\n }", "function renderComponent(calc) {\n if (calc === \"inputs\") {\n return input;\n } else if (calc === \"totals\") {\n return totalInput;\n } else if (calc === \"percentages\") {\n return percentages;\n } else if (calc === \"nps\") {\n return nps;\n }\n }", "function calcService($log) {\n return {\n calc: calc\n };\n ///////////\n function calc(input, previousOutput){\n var inp = +(input || 0);\n var prev = +(previousOutput || 0);\n var result = inp + prev;\n\n // use the dependency\n $log.debug('calc(' + input + ', ' + previousOutput + ') => '+ result);\n\n return result;\n }\n }", "compute(){\n let computation\n //converting strings to number for computation\n const prev = parseFloat(this.previousOperand)\n const current = parseFloat(this.currentOperand)\n //to check if numbers were actually inputed before any computation\n if (isNaN(prev) || isNaN(current)) return\n switch (this.operation) {\n case '+' :\n computation = prev + current\n break\n case '-' :\n computation = prev - current\n break\n case '×' :\n computation = prev * current\n break\n case '÷' :\n computation = prev / current\n break\n default:\n return\n }\n this.toReset = true,\n this.currentOperand = computation\n this.operation = undefined\n this.previousOperand = ''\n }", "loggableComponentTransformation(object, names, depth) {\n\n // Get our bearings at the current recusion level.\n\n var markers = this.descriptorMarkers(object, names, depth);\n\n // Transform the object here.\n\n switch (markers.containerName) {\n\n case \"extends\":\n\n // Omit a component descriptor for the prototype.\n\n if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {\n return {};\n }\n\n break;\n\n case \"implements\":\n\n // Omit component descriptors for the behaviors.\n\n if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {\n return {};\n }\n\n break;\n\n case \"properties\":\n\n // Convert property values to a loggable version, and omit getter and setter\n // text.\n\n if (markers.memberIndex == 0 && !this.valueHasAccessors(object) ||\n markers.memberIndex == 1 && names[0] == \"value\") {\n return this.loggableValue(object);\n } else if (markers.memberIndex == 1 && (names[0] == \"get\" || names[0] == \"set\")) {\n return \"...\";\n }\n\n break;\n\n case \"methods\":\n\n // Omit method body text.\n\n if (markers.memberIndex == 0 && !this.valueHasBody(object) ||\n markers.memberIndex == 1 && names[0] == \"body\") {\n return \"...\";\n }\n\n break;\n\n case \"events\":\n\n // Nothing for events.\n\n break;\n\n case \"children\":\n\n // Omit child component descriptors.\n\n if (markers.memberIndex == 0 && this.componentIsDescriptor(object)) {\n return {};\n }\n\n break;\n\n case \"scripts\":\n\n // Shorten script text.\n\n if (markers.memberIndex == 0 && !this.valueHasType(object) ||\n markers.memberIndex == 1 && names[0] == \"text\") {\n return \"...\";\n }\n\n break;\n\n }\n\n return object;\n }", "initComponents() {\n // precomputed\n const components = this._withPrecomputeRenderer(this.reactClass, this.el, this.log, MemoizingSnapshotOptimizer);\n\n // isolated\n // const partially = this._withIsolatedComponents.bind(this, this.reactClass, this.el, this.log);\n // const components = partially(NoopOptimizer, NaiveReactRenderer);\n // const components = partially(MemoizingSnapshotOptimizer, NaiveReactRenderer);\n\n // const components = partially(NoopOptimizer, RafReactRenderer);\n // const components = partially(MemoizingOptimizer, RafReactRenderer);\n // const components = partially(MemoizingSnapshotOptimizer, RafReactRenderer);\n \n console.info('initComponents:', components);\n this.renderer = components.renderer;\n this.optimizer = components.optimizer;\n this.loggit = components.loggit;\n }", "compute() {\n\n}", "compute() {\r\n let computation\r\n //parseFloat converts a string argument and converts it to a float\r\n const prev = parseFloat(this.previousOperand)\r\n const current = parseFloat(this.currentOperand)\r\n //NaN means Not a Number\r\n if (isNaN(prev) || isNaN(current)) return\r\n //here, you are matching up the values and operations buttons\r\n switch (this.operation) {\r\n case '+':\r\n computation = prev + current\r\n break\r\n case '-':\r\n computation = prev - current\r\n break\r\n case 'x':\r\n computation = prev * current\r\n break\r\n case '/':\r\n computation = prev / current\r\n break\r\n \r\n default:\r\n return\r\n }\r\n //actual computation taking place\r\n this.currentOperand = computation\r\n this.operation = undefined\r\n this.previousOperand = ''\r\n }", "compute()\n {\n super.compute();\n this.needsRecompute = false;\n }", "compute()\n {\n super.compute();\n this.needsRecompute = false;\n }", "compute(operation) {\n const modes = this.getMode()\n const mode_1 = this.getDigitFromRight(modes, 1)\n const mode_2 = this.getDigitFromRight(modes, 2)\n const mode_3 = this.getDigitFromRight(modes, 3)\n const param_1 = this.program[this.PC+1]\n const param_2 = this.program[this.PC+2]\n const param_3 = this.program[this.PC+3]\n\n const value_1 = this.getValue(mode_1, param_1)\n const value_2 = this.getValue(mode_2, param_2)\n const ans_index = this.getIndex(param_3, mode_3)\n switch (operation) {\n case 1:\n this.program[ans_index] = value_1 + value_2\n break;\n case 2:\n this.program[ans_index] = value_1 * value_2\n break;\n case 7:\n this.program[ans_index] = (value_1 < value_2) ? 1 : 0\n break;\n case 8:\n this.program[ans_index] = (value_1 === value_2) ? 1 : 0\n break;\n default:\n return;\n }\n this.PC += 4\n }", "compileImpl(cache)\n {\n // small helper to format info and error messages\n var _ = (c) => {\n return 'id=' + (c.id || '') + '|name=' + (c.name || '');\n };\n\n // the common implementation for all components\n var impl = (comp, cache, ids, names, kind) => {\n // at least one of ID and name mandatory\n if ( ! comp.name && ! comp.id ) {\n throw new Error('No ID and no name on ' + kind.kind + ' in ' + cache.href);\n }\n // default value for compose\n if ( ! comp.compose ) {\n comp.compose = 'merge';\n }\n // does it exist yet?\n var derived =\n ( comp.id && ids[comp.id] )\n || ( comp.name && names[comp.name] );\n // if it does, perform the \"compose\" action..\n if ( derived ) {\n if ( derived.compose !== comp.compose ) {\n throw new Error('Different compose actions for ' + kind.kind + 's: derived:'\n + _(derived) + '|compose=' + derived.compose + ' and base:'\n + _(comp) + '|compose=' + comp.compose);\n }\n else if ( derived.compose === 'merge' ) {\n this.ctxt.display.info('Merge ' + kind.kind + 's derived:' + _(derived) + ' and base:' + _(comp));\n var overriden = Object.keys(derived);\n for ( var p in comp ) {\n if ( overriden.indexOf(p) === -1 ) {\n derived[p] = comp[p];\n if ( p === 'id' ) {\n ids[derived.id] = derived;\n }\n else if ( p === 'name' ) {\n names[derived.name] = derived;\n }\n }\n else {\n derived[p] = kind.merge(p, derived[p], comp[p]);\n }\n }\n }\n else if ( derived.compose === 'hide' ) {\n this.ctxt.platform.info('Hide ' + kind.kind + ' base:' + _(comp) + ' by derived:' + _(derived));\n }\n else {\n throw new Error('Unknown compose on ' + kind.kind + ': ' + _(derived) + '|compose=' + derived.compose);\n }\n }\n // ...if it does not, just add it\n else {\n cache.push(comp);\n if ( comp.id ) {\n ids[comp.id] = comp;\n }\n if ( comp.name ) {\n names[comp.name] = comp;\n }\n }\n };\n\n // compile hosts\n if ( this.json.hosts ) {\n this.json.hosts.forEach(host => {\n impl(host, cache.hosts, null, cache.hostNames, cmp.Host);\n });\n }\n // compile databases\n if ( this.json.databases ) {\n this.json.databases.forEach(db => {\n impl(db, cache.dbs, cache.dbIds, cache.dbNames, cmp.Database);\n });\n }\n // compile servers\n if ( this.json.servers ) {\n this.json.servers.forEach(srv => {\n impl(srv, cache.srvs, cache.srvIds, cache.srvNames, cmp.Server);\n });\n }\n // compile sources\n if ( this.json.sources ) {\n this.json.sources.forEach(src => {\n impl(src, cache.srcs, null, cache.srcNames, cmp.SourceSet);\n });\n }\n // compile mime types\n if ( this.json['mime-types'] ) {\n this.json['mime-types'].forEach(mime => {\n impl(mime, cache.mimes, null, cache.mimeNames, cmp.MimeType);\n });\n }\n // compile privileges\n if ( this.json.privileges ) {\n const each = (privs, cache, names) => {\n if ( privs ) {\n privs.forEach(priv => {\n impl(priv, cache, null, names, cmp.Privilege);\n });\n }\n };\n each(this.json.privileges.execute, cache.execPrivs, cache.execPrivNames);\n each(this.json.privileges.uri, cache.uriPrivs, cache.uriPrivNames);\n }\n // compile roles\n if ( this.json.roles ) {\n this.json.roles.forEach(role => {\n impl(role, cache.roles, null, cache.roleNames, cmp.Role);\n });\n }\n // compile users\n if ( this.json.users ) {\n this.json.users.forEach(user => {\n impl(user, cache.users, null, cache.userNames, cmp.User);\n });\n }\n // recurse on imports\n this.imports.forEach(i => {\n cache.href = i.path;\n i.compileImpl(cache);\n });\n }", "applyOp(op) {\n // When an op is received, transform it, and\n // set it equal to the component snapshot.\n this.snapshot = this.transformSnapshot(op, this.snapshot);\n return this.snapshot;\n }", "function mainCompute()\n{\n\tlet expr = document.getElementById(\"inputSpecificFunction\").value;\n\tlet optionF\n\tif(expr != \"\")\n\t{\n\t\ttry {\n\t\t\toptionF = math.parse(expr)\n\t\t} catch (e) {\n\t\t\tconsole.log(\"Wrong syntax\")\n\t\t\talert(\"The entered function has a syntax error\")\n\t\t}\n\n\t\tlet latex = optionF.toTex()\n\t\tdocument.getElementById(\"labelSpecificFunction\").innerHTML = \"\\\\(f(x) = \" + latex + \"\\\\)\"\n\t\tMathJax.typeset()\n\t}\n\telse{\n\t\toptionF = f;\n\t}\n\n let optionN = parseFloat(document.getElementById(\"optionN\").value);\n\tlet optionH = parseFloat(document.getElementById(\"optionH\").value);\n\tlet optionA = parseFloat(document.getElementById(\"optionA\").value);\n\tlet optionI = {\"a\": parseFloat(document.getElementById(\"optionRangeStart\").value), \"b\": parseFloat(document.getElementById(\"optionRangeEnd\").value)};\n\tlet optionDX = parseFloat(document.getElementById(\"optionDX\").value);\n\tlet optionNaive = document.getElementById(\"checkOldMethod\").checked;\n let tmp = document.getElementById(\"optionDerivatives\").value.split(\",\");\n let optionDerivative = [];\n tmp.forEach( i => {\n optionDerivative.push(parseInt(i)); //Transform to int\n });\n\n\tneedsRebuild = true;\n\n\tcompute(optionF, optionN, optionH, optionA, optionI, optionDX, optionDerivative, optionNaive);\n\tmainGraph.update();\n}", "computeResult(result) {\n }", "function compute () {\n\t // set value\n\t util.forEach(expressions, function(exp, index) {\n\t var v = that.$exec(exp)\n\t if (!v[0]) caches[index] = v[1]\n\t })\n\t // get content\n\t var frags = []\n\t util.forEach(parts, function(item, index) {\n\t frags.push(item)\n\t if (index < expressions.length) {\n\t frags.push(caches[index])\n\t }\n\t })\n\t return Expression.unveil(frags.join(''))\n\t }", "function doComputation(){\n let computation;\n const prev = parseFloat(previousOperand);\n const current = parseFloat(currentOperand);\n\n if(isNaN(prev) || isNaN(current)) return;\n switch(operation){\n case '+':\n computation=prev + current;\n break;\n case '-':\n computation=prev - current;\n break;\n case 'x':\n computation=prev * current;\n break;\n case '/':\n computation= prev / current;\n break;\n default :\n return;\n }\n\n currentOperand=computation;\n operation=undefined;\n previousOperand=''; \n}", "update(repo: Microcosm, nextProps: Object, nextState: Object) {\n // NOOP\n }", "visualize() {\n // grid, startnode, finishnode \n if (this.state.start_node_col === null) {\n return;\n }\n const { grid } = this.state;\n // eslint-disable-next-line\n this.state.actionCount++;\n const startNode = grid[this.state.start_node_row][this.state.start_node_col];\n const finishNode = grid[this.state.finish_node_row][this.state.finish_node_col];\n //call the selected algorithm \n var algo = this.state.currentAlgo;\n var visitedNodesInOrder;\n if (algo === 'greedy') {\n visitedNodesInOrder = bfs(grid, startNode, finishNode);\n }\n else if (algo === 'dijkstra') {\n visitedNodesInOrder = dijkstra(grid, startNode, finishNode);\n }\n else if (algo === 'dfs') {\n visitedNodesInOrder = dfs(grid, startNode, finishNode);\n }\n else if (algo === 'a') {\n visitedNodesInOrder = bfs(grid, startNode, finishNode);\n }\n else { //bfs\n visitedNodesInOrder = bfs(grid, startNode, finishNode);\n }\n if (algo === 'bfs') {\n this.animateBfs(visitedNodesInOrder);\n } else {\n this.animateAlgo(visitedNodesInOrder);\n }\n }", "compute() {\n let result;\n let lastnum = parseFloat(this.lastOperand);\n let currnum = parseFloat(this.currOperand);\n if (isNaN(lastnum) || isNaN(currnum)) {\n return;\n }\n switch (this.operator) {\n case \"+\":\n result = lastnum + currnum;\n break;\n case \"-\":\n result = lastnum - currnum;\n break;\n case \"*\":\n result = lastnum * currnum;\n break;\n case \"/\":\n result = lastnum / currnum;\n break;\n default:\n return;\n }\n this.currOperand = result;\n this.lastOperand = \"\";\n this.operator = undefined;\n }", "function computeAndTrack()/*:void*/ {\n // After this method is left, the value will not be dirty.\n this.valueDirty$nJmn = false;\n // Remember the old value.\n var oldValue/*:**/ = this.value$nJmn;\n // It is allowed (although unusual) for the function to cause invalidations.\n // Try a few times to reach a fix point.\n for (var i/*:uint*/ = 0; i < 100; i++) {\n // There is no current tracker. Create and activate a new tracker\n // for the upcoming computation.\n this.dependencyTracker$nJmn = new com.coremedia.ui.data.dependencies.DependencyTracker(AS3.bind(this,\"invalidated$nJmn\"));\n // Make sure to stop dependency tracking even in the case of an internal exception.\n try {\n this.value$nJmn = this.compute$nJmn();\n } finally {\n this.dependencyTracker$nJmn.stop();\n }\n\n // If the tracker has been invalidated, ...\n if (this.dependencyTracker$nJmn.isInvalidated()) {\n // .. forget about it, ...\n this.dependencyTracker$nJmn = null;\n } else {\n // ... but otherwise the value is final and we can determine whether it has changed.\n if (!com.coremedia.ui.util.ObjectUtils.equal(oldValue, this.value$nJmn)) {\n this.valueChanged$nJmn = true;\n }\n // The dependency tracker lives on and will report invalidations to its callback method.\n return;\n }\n // The previous evaluation resulted in an invalidation before the function returned.\n }\n // Give up.\n this.value$nJmn = UNREADABLE$static;\n if (oldValue !== UNREADABLE$static) {\n this.valueChanged$nJmn = true;\n }\n throw new AS3.Error(\"function value expression keeps invalidating itself: \" + this.fun$nJmn + \"(\" + this.args$nJmn + \")\");\n }", "computeModule(module) {\n var moduleInputs = module.moduleInputs;\n var faustResult = \"\";\n // Iterate on input Modules to compute them\n if (moduleInputs && moduleInputs.length != 0) {\n var inputCode = \"\";\n for (var i = 0; i < moduleInputs.length; i++) {\n if (moduleInputs[i]) {\n if (moduleInputs[i].sourceCode && moduleInputs[i].sourceCode.length > 0) {\n if (i != 0) {\n inputCode += \",\";\n }\n inputCode += this.computeModule(moduleInputs[i]);\n }\n }\n }\n if (inputCode != \"\") {\n if (module.recursiveFlag) {\n faustResult += \"(\" + inputCode + \":> \";\n }\n else {\n faustResult += inputCode + \":> \";\n }\n }\n }\n var ModuleCode = module.sourceCode;\n if (module.recursiveFlag) {\n faustResult += \"stereoize(environment{\" + ModuleCode + \"}.process))~(_,_)\";\n }\n else {\n faustResult += \"stereoize(environment{\" + ModuleCode + \"}.process)\";\n }\n return faustResult;\n }", "function createComputedCost(grid) {\n const computed = document.createElement(\"span\");\n computed.classList.add(\"computed-cost\");\n const computedCost = document.createTextNode(\"\");\n computed.appendChild(computedCost);\n grid.appendChild(computed);\n}", "function doComputation() {\n var $computation = document.getElementById('computation');\n var $result = document.getElementById('result');\n var $error = document.getElementById('error');\n var $errorMessage = document.getElementById('errorMessage');\n var $errorInput = document.getElementById('errorInput');\n var input = $computation.value;\n var algebraType = readConfig();\n var maybeResult = evaluate(algebraType, input);\n if (maybeResult instanceof ParseError) {\n $error.style.display = 'block';\n $errorMessage.innerText = maybeResult.msg;\n $errorInput.innerHTML = frameError(maybeResult, input);\n }\n else {\n $error.style.display = 'none';\n }\n var lin = (maybeResult instanceof ParseError) ? algebraUnit(0) : maybeResult;\n $result.innerText = algebraString(lin);\n writeTable(algebraType, lin);\n}" ]
[ "0.6324974", "0.60579836", "0.574137", "0.5167757", "0.5159222", "0.5096611", "0.49962747", "0.49663883", "0.491505", "0.49148515", "0.49041876", "0.48896286", "0.48692617", "0.47789705", "0.47723264", "0.47723264", "0.4755875", "0.47449255", "0.47398564", "0.4701247", "0.46585396", "0.46554345", "0.46516314", "0.4626548", "0.46082708", "0.4607374", "0.45925933", "0.45540434", "0.45501015", "0.45375752" ]
0.6140315
1
This inform the renderer that something has occurred. It can decide whether to respond synchronously, or to batch, etc.
_notifyRenderer() { this.renderer.notify(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "rendererReady() {\n const message = new Message(Message.rendererReadyTitle, 'void').toString();\n this.ipc.send('update-message', message);\n }", "IsFinishedRendering() {}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_429( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_412( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "handleRendered_() {\n\t\tthis.isRendered_ = true;\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_587( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "handleRenderCompletion() {\n this.renderNewChildren = false;\n this.preventUpdate = false;\n this.lastChildIndex = this.childCount;\n if (this.isRenderingNew) {\n this.isRenderingNew = false;\n this.update(null, false, true); // Prevent from triggering an item request to avoid infinite loop of loading.\n } else if (this.contentNode && InfiniteUtils.shouldTriggerItemRequest(InfiniteUtils.getContentData(this.contentNode))) {\n this.triggerItemRequest();\n }\n }", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_475( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_452( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_488( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_577( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_395( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_520( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_457( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_330( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_332( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\t}", "render(...args) {\n if (this._render) {\n this.__notify(EV.BEFORE_RENDER);\n this._render(...args);\n this.__notify(EV.RENDERED);\n }\n\n this.rendered = true;\n }", "_emitNegotiationNeeded() {\n // Ignore if signalingState is not 'stable'.\n if (this.signalingState !== RTCSignalingState.stable) {\n return;\n }\n\n logger.debug('emitting \"negotiationneeded\"');\n\n const event = new yaeti.Event('negotiationneeded');\n\n this.dispatchEvent(event);\n }", "function notifyMediator () {\n var status = getStatus();\n\n // Event if might be valid we pass along an undefined errorMessage.\n mediator.fire({\n id: id,\n type: 'result',\n result: status.status,\n element: element,\n errorMessage: status.errorMessage\n });\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "didRender() {\n console.log('didRender ejecutado!');\n }", "onBeforeRespond (message)\n {\n }", "function handler() {\n fired = true;\n }", "function doSomethingAfterRendering(){\n displayLoading() // 로딩화면 보여주기\n fetchServer(); // 서버에서 데이터 가져오기\n }", "function handleRender() {\n\t view._isRendered = true;\n\t triggerDOMRefresh();\n\t }", "done() {\n const eventData = EventData_1.EventData.createFromRequest(this.request.value, this.externalContext, Const_1.SUCCESS);\n //because some frameworks might decorate them over the context in the response\n const eventHandler = this.externalContext.getIf(Const_1.ON_EVENT).orElseLazy(() => this.internalContext.getIf(Const_1.ON_EVENT).value).orElse(Const_1.EMPTY_FUNC).value;\n AjaxImpl_1.Implementation.sendEvent(eventData, eventHandler);\n }", "function notify() {\n res.write('--- changed ---\\n');\n }", "function renderCallback() {\n\n while (TO_RENDER.length) {\n TO_RENDER.shift().notify();\n }\n\n TO_RENDER.added = {};\n\n while (ENV_QUEUE.length) {\n var env = ENV_QUEUE.shift();\n for (var key in env.revalidateQueue) {\n env.revalidateQueue[key].revalidate();\n }\n reslot(env);\n }\n ENV_QUEUE.added = {};\n}", "function responseCallback(response, id) {\n debug(\"response of message tick \" + id + \": \" + response);\n}" ]
[ "0.60688233", "0.59487796", "0.57427925", "0.57325476", "0.57306087", "0.57235336", "0.5721346", "0.5706901", "0.56946576", "0.56925815", "0.5691034", "0.5683223", "0.56808984", "0.56759024", "0.56724757", "0.5670946", "0.56447506", "0.5576912", "0.55661", "0.55142295", "0.55142295", "0.54413563", "0.541417", "0.5413172", "0.53867024", "0.53814876", "0.53750086", "0.53479767", "0.5324138", "0.53061926" ]
0.61903167
0
Ottiene i dati dal GPS
function getDataFromGPS(position){ $("#geo-information").html('<div class="alert alert-info text-center" role="alert">⌛‍ Aggiornamento... <div class="spinner-grow spinner-grow-sm float-right" role="status"></div></div>'); truelat = position.coords.latitude; truelon = position.coords.longitude; updateData(truelat, truelon, position.coords.accuracy); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function geoloc() {\n let coords = navigator.geolocation.getCurrentPosition((pos) => {\n coords = pos;\n let lat = coords.coords.latitude;\n let long = coords.coords.longitude;\n ll = `?_ll=${lat},${long}`;\n document.querySelector(\".change-hour h1 span\").textContent = \"ma position\";\n getDatas(process);\n });\n}", "function InicializaGPSnew()\n {\n idRegistroPosicion = navigator.geolocation.watchPosition\n ( localizame, falloRegistroPosicion,\n {enableHighAccuracy : true, maximumAge : 10000, timeout : 5000 }\n )\n //alert(\"Inicia timer de actualiza posicion, retardo = \" + RetardoActualizaPosicion);\n ActualizaPosicionTaxi();\n setInterval(ActualizaPosicionTaxi, RetardoActualizaPosicion);\n }", "function localizame() {\n mensaje = 'Cargando farmacias cercanas a ' + radODis + ' KM de su ubicación';\n alertaCargando(mensaje);\n\n navigator.geolocation.getCurrentPosition(initialize, function (error) {\n $ionicLoading.hide();\n activarGPS();\n }, {maximumAge: 3000, timeout: 3000, enableHighAccuracy: true});\n\n }", "function InicializaGPS1vez()\n {\n\n //dni=Base64.decode( getUrlVars()[\"dni\"] );\n dni=getUrlVars()[\"dni\"] ;\n Placa= getUrlVars()[\"placa\"] ;\n //empresa_madre=Base64.decode( getUrlVars()[\"empresa\"] );\n empresa_madre= getUrlVars()[\"empresa\"] ;\n //alert(dni + \" // \" + Placa + \" // \" + empresa_madre);\n window.localStorage.setItem(\"Taxista\",dni);\n window.localStorage.setItem(\"Placa\",Placa); \n window.localStorage.setItem(\"Empresa\",empresa_madre);\n\n if (navigator.geolocation) \n { \n console.log(\"localizado ok\");\n $(\"#gpsEstado\" ).fadeIn( \"slow\", function(){\n document.getElementById(\"gpsEstado\").innerHTML=\"Su teléfono tiene GPS..\";\n animaBarra();\n\n });\n //document.getElementById(\"gpsEstado\").innerHTML=\"Su teléfono tiene GPS..\";\n llamadoGPS = navigator.geolocation.watchPosition(\n localizadoOk,\n localizadoError,\n {\n enableHighAccuracy : true,\n maximumAge : 30000,\n timeout : 5000\n }\n )\n }else{\n document.getElementById(\"gpsEstado\").innerHTML='¡Tu teléfono no permite ubicar tu localización. No puedes usar este soft!';\n } \n\n }", "processGPSData(gps) {\n if (gps != undefined) {\n this.lat = gps['position'][0];\n this.lon = gps['position'][1];\n this.alt = gps['position'][2];\n this.prevP = this.p\n this.p = gps['position'];\n this.d = gps['distance'];\n this.v = gps['velocity'];\n this.a = gps['acceleration'];\n let date = gps['date'].split(' ');\n this.date = date[0];\n this.time = date[1];\n this.gpsFix = gps['fix'];\n this.gpsSatellites = gps['satellites'];\n }\n }", "function geolocalizame(){\nnavigator.geolocation.getCurrentPosition(pedirPosicion);\n }", "function locationSuccessDS(pos){\n //Request DarkSky\n// var lat=pos.coords.latitude;\n// var lon= pos.coords.longitude;\n var settings2 = JSON.parse(localStorage.getItem('clay-settings')) || {};\n var manuallat = settings2.Lat;\n var manuallong = settings2.Long;\n if(manuallat != null && manuallat != '' && manuallong != null && manuallong != '' ){\n var lat= manuallat;\n var lon= manuallong;\n }\n else {\n var lat=pos.coords.latitude;\n var lon= pos.coords.longitude;\n }\n var d = new Date();\n var sunTimes = SunCalc.getTimes(d, lat, lon);\n var sunsetStrhr = ('0'+sunTimes.sunset.getHours()).substr(-2);\n var sunsetStrmin = ('0'+sunTimes.sunset.getMinutes()).substr(-2);\n var sunsetStr = String(sunsetStrhr + \":\" + sunsetStrmin);\n var sunriseStrhr = ('0'+sunTimes.sunrise.getHours()).substr(-2);\n var sunriseStrmin = ('0'+sunTimes.sunrise.getMinutes()).substr(-2);\n var sunriseStr = String(sunriseStrhr + \":\" + sunriseStrmin);\n var sunsetStrhr12 = parseInt(sunTimes.sunset.getHours());\n var sunriseStrhr12 = parseInt(sunTimes.sunrise.getHours());\n if(sunsetStrhr12 > 12 ){\n var sunsetStr12h = String (sunsetStrhr12 - 12 + \":\" + sunsetStrmin);// +\"pm\");\n }\n else{\n var sunsetStr12h = String (sunsetStrhr12 + \":\" + sunsetStrmin);// + \"am\");\n }\n if(sunriseStrhr > 12 ){\n var sunriseStr12h = String(sunriseStrhr12 - 12 + \":\" + sunriseStrmin);// +\"pm\");\n }\n else{\n var sunriseStr12h = String(sunriseStrhr12 + \":\" + sunriseStrmin);// + \"am\");\n }\n var moonmetrics = SunCalc.getMoonIllumination(d);\n var moonphase = Math.round(moonmetrics.phase*28);\n var keyAPIds=localStorage.getItem('dsKey');\n var userKeyApi=settings2.APIKEY_User;\n var endapikey=apikeytouse(userKeyApi,keyAPIds);\n var units = unitsToString(settings2.WeatherUnit);\n// var unitsOWM=unitsToStringOWM(settings.WeatherUnit);\n var windunits = windunitsToString(settings2.WindUnit);\n var langtouse=translate(navigator.language);\n // Construct URL\n var urlDS = \"https://api.darksky.net/forecast/\" +\n endapikey +\n '/' + lat + ',' + lon +\n '?exclude=minutely,hourly&units=si' +\n '&lang=' + langtouse;\n\n\n console.log(\"DSUrl= \" + urlDS);\n // Send request to DarkSky\n xhrRequest(encodeURI(urlDS), 'GET',function(responseText) {\n // responseText contains a JSON object with current weather info\n var json = JSON.parse(responseText);\n localStorage.setItem(\"OKAPI\", 0);\n // Current Temperature\n var tempf = Math.round((json.currently.temperature * 1.8) + 32);//+'\\xB0'+units;\n var tempc = Math.round(json.currently.temperature);\n var tempds=String(temptousewu(units,tempf,tempc))+'\\xB0';\n // Current conditions\n var condds=json.currently.summary;//description;\n var condcleands=replaceDiacritics(condds);\n var icon_ds = ds_iconToId[json.currently.icon];\n // Sunrise and Sunset\n var auxsunds =new Date(json.daily.data[0].sunriseTime*1000);\n var sunriseds=auxsunds.getHours()*100+auxsunds.getMinutes();\n var auxsetds =new Date(json.daily.data[0].sunsetTime*1000);\n var sunsetds=auxsetds.getHours()*100+auxsetds.getMinutes();\n //current wind\n var windkts = Math.round(json.currently.windSpeed * 1.9438444924574);\n var windkph = Math.round(json.currently.windSpeed * 3.6);\n var windms = Math.round(json.currently.windSpeed);\n var windmph = Math.round(json.currently.windSpeed * 2.2369362920544);\n var wind = String(windtousewu(windunits,windkph,windmph,windms,windkts))+windunits;\n var winddegds = String(json.currently.windBearing);\n var winddir_numds = owm_WindToId[winddegds];\n // Forecast Conditions\n var forecast_icon_ds = ds_iconToId[json.daily.data[0].icon];\n // Forecast Temperature & wind\n var forecast_high_tempf = Math.round((json.daily.data[0].temperatureHigh * 1.8) + 32); //+'\\xB0';\n var forecast_low_tempf = Math.round((json.daily.data[0].temperatureLow * 1.8) + 32); //+'\\xB0';\n var forecast_high_tempc = Math.round(json.daily.data[0].temperatureHigh); //+ '\\xB0';\n var forecast_low_tempc = Math.round(json.daily.data[0].temperatureLow); //+ '\\xB0';\n var highds = String(temptousewu(units,forecast_high_tempf,forecast_high_tempc));\n var lowds = String(temptousewu(units,forecast_low_tempf,forecast_low_tempc));\n var highlowds = highds + '|'+ lowds;//+'\\xB0';\n var forecast_ave_wind_mph = Math.round(json.daily.data[0].windSpeed*2.2369362920544);\n var forecast_ave_wind_kts = Math.round(json.daily.data[0].windSpeed *1.9438444924574);\n var forecast_ave_wind_kph = Math.round(json.daily.data[0].windSpeed *3.6);\n var forecast_ave_wind_ms = Math.round(json.daily.data[0].windSpeed);\n var forecast_wind_degds = String(json.daily.data[0].windBearing);\n var forecast_wind_dir_numds = owm_WindToId[forecast_wind_degds];\n var forecast_ave_wind_ds = String(windtousewu(windunits,forecast_ave_wind_kph,forecast_ave_wind_mph,forecast_ave_wind_ms,forecast_ave_wind_kts))+windunits;\n var auxtimeds =new Date(json.currently.time*1000);\n var dstime=auxtimeds.getHours()*100+auxtimeds.getMinutes();\n\n localStorage.setItem(\"OKAPI\", 1);\n console.log(\"OK API\");\n\n console.log(condcleands);\n console.log(sunsetds);\n console.log(sunriseds);\n console.log(wind);\n console.log(winddir_numds);\n console.log(tempds);\n console.log(icon_ds);\n console.log(highds);\n console.log(forecast_icon_ds);\n console.log(lowds);\n console.log(forecast_wind_dir_numds);\n console.log(forecast_ave_wind_ds);\n console.log(sunsetStr);\n console.log(sunriseStr);\n console.log(moonphase);\n console.log(winddegds);\n console.log(forecast_wind_degds);\n console.log(dstime);\n\n // Assemble dictionary using our keys\n var dictionary = {\n \"WeatherTemp\": tempds,\n \"WeatherCond\": condcleands,\n \"HourSunset\": sunsetds,\n \"HourSunrise\":sunriseds,\n \"WeatherWind\" : wind,\n \"WEATHER_SUNSET_KEY\":sunsetStr,\n \"WEATHER_SUNRISE_KEY\":sunriseStr,\n \"WEATHER_SUNSET_KEY_12H\":sunsetStr12h,\n \"WEATHER_SUNRISE_KEY_12H\":sunriseStr12h,\n \"IconNow\":icon_ds,\n \"IconFore\":forecast_icon_ds,\n \"TempFore\": highlowds,//hi_low,\n \"TempForeLow\": lowds,\n \"WindFore\": forecast_ave_wind_ds,\n \"WindIconNow\":winddir_numds,\n \"WindIconAve\":forecast_wind_dir_numds,\n \"Weathertime\":dstime,\n \"MoonPhase\": moonphase,\n\n };\n // Send to Pebble\n Pebble.sendAppMessage(dictionary,\n function(e) {console.log(\"Weather from DS sent to Pebble successfully!\");},\n function(e) { console.log(\"Error sending DS info to Pebble!\");}\n );\n });\n}", "function leerGps() {\n\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(showPosition);\n }\n\n // init \n window.inc = typeof (inc) == 'undefined' ? 0.00005 : window.inc;\n window.lat = typeof (lat) == 'undefined' ? 38.695015 : window.lat;\n window.lng = typeof (lng) == 'undefined' ? -0.476049 : window.lng;\n window.dir = typeof (dir) == 'undefined' ? Math.floor((Math.random() * 4)) : window.dir;\n // numbers 0,1,2,3 (0 up, 1 right, 2, down, 3 left) \n // generate direction (randomly) \n // it is more likely to follow the previous direction\n var nuevaDir = Math.floor((Math.random() * 4));\n // number 0,1,2,3 \n if (nuevaDir != (dir + 2) % 4) dir = nuevaDir;\n switch (dir) {\n case 0: // up\n lat += inc;\n break;\n case 1: // right\n lng += inc;\n break;\n case 2: // down \n lat -= inc;\n break;\n case 3: // left \n lng -= inc;\n break;\n default:\n }\n var pos = {\n lat: lat,\n lng: lng\n };\n lastKnowLocation = pos;\n // add new position to the route\n rutaEnCurso.posiciones.push(pos);\n}", "function coor(){\n\n var cordenadas = navigator.geolocation.getCurrentPosition(\n function(posicao) {\n\n\n var pos = new google.maps.LatLng(posicao.coords.latitude, posicao.coords.longitude);\n\n\n my_lat = posicao.coords.latitude;\n my_long = posicao.coords.longitude;\n\n //hide_loading();\n // var event = new Event('has_position');\n // document.dispatchEvent(event);\n $(document).trigger(\"has_position\");\n },\n function(err){\n //console.warn('ERROR(' + err.code + '): ' + err.message);\n alert('Não podemos receber sua localização. Verifique sua conexão ou se o seu GPS está ativado e tente novamente.')\n },\n { maximumAge: 3000, timeout: 15000, enableHighAccuracy: true }\n )\n}", "function DataFromGps(id, lat, lon, time){\n var myDevice = new device(id, lat, lon, time);\n var recievedTable = [];\n recievedTable.push(myDevice);\n localTable = updateLocalTable(recievedTable,localTable);\n}", "function miPosYAgenciasSB(){\n // console.log(\"DFC >>> Mi Pos Y Agencias Scotia Bank\");\n msgWaitForFosition(\"mapDondeEstoySB\");\n watchIDSB = navigator.geolocation.watchPosition(\n onSuccessMiPosYAgenciasSB, onErrorMiPosYAgenciasSB, {enableHighAccuracy: true}\n );\n\n}", "function gps_consultarGps() {\n autoConsulta = true;\n enableMapRefresh();\n disableMap();\n gps_iniciarAutoConsulta(); // Consulta directamente\n}", "function gps_prepararDatos(data) {\n var gps = new Object();\n\n var arrayData = data.split(separador);\n gps.id = arrayData[0];\n //gps.fechaServidor = arrayData[1];\n gps.fechaServidor = arrayData[2];\n gps.fechaGPS = arrayData[2];\n gps.rumbo = arrayData[3];\n gps.velocidad = arrayData[4];\n gps.msg = arrayData[5];\n gps.totalDia = arrayData[6];\n gps.numeracion = arrayData[7];\n gps.entradas = arrayData[8];\n gps.salidas = arrayData[9];\n gps.alarma = arrayData[10];\n gps.distanciaMetros = arrayData[11];\n gps.localizacion = arrayData[12];\n gps.latitud = arrayData[13];\n gps.longitud = arrayData[14];\n gps.placa = arrayData[15];\n gps.nombreFlota = arrayData[16];\n //gps.fechaServidorDate = arrayData[17];\n gps.fechaServidorDate = arrayData[18];\n gps.fechaGPSDate = arrayData[18];\n gps.numeracionInicial = arrayData[19];\n gps.esPuntoControl = arrayData[20];\n gps.esPasajero = arrayData[21];\n gps.esAlarma = arrayData[22];\n gps.numeracionFinal = arrayData[23];\n gps.distanciaRecorrida = arrayData[24];\n gps.razonTransmision = arrayData[25];\n gps.especificaRazonTransmision = arrayData[26];\n gps.rumboRadianes = arrayData[27];\n gps.nivelOcupacion = arrayData[28];\n gps.noic = arrayData[29];\n gps.ipk = arrayData[30];\n gps.gpsId = arrayData[31];\n gps.distanciaParcial = arrayData[32];\n gps.ipkParcial = arrayData[33];\n gps.info = gps_prepararPopup(gps);\n\n return gps;\n}", "function getLocation()\n {\n if (navigator.geolocation)\n {\n posID = navigator.geolocation.watchPosition(getDataFromGPS,showError,{enableHighAccuracy:true,timeout:240000});\n $(\"#geo-information\").html('<div class=\"alert alert-info text-center\" role=\"alert\">🕵️‍ Ti stiamo localizzando... <div class=\"spinner-border spinner-border-sm float-right\" role=\"status\"></div></div>');\n $(\"#pos-button\").addClass(\"disabled\");\n $(\"#pos-img\").addClass(\"animated flash slower infinite\");\n }\n else{$(\"#geo-information\").html('<div class=\"alert alert-danger\" role=\"alert\">😔 Il tuo browser non supporta la geolocalizzazione.</div>');}\n }", "function getLocation() {\n \n if (navigator.geolocation) {\n var fast = $$(\"#cbPosAccurate\").prop(\"checked\");\n if(app.watchPositionID !== null){\n // de vorige watch eerst stoppen, of we hebben meerdere\n // simultane lopen.\n navigator.geolocation.clearWatch(app.watchPositionID);\n \n }\n \n app.watchPositionID = navigator.geolocation.watchPosition(\n showPosition,\n positionError, \n { \n enableHighAccuracy: fast,\n maximumAge: 10 * 1000}\n );\n \n } else {\n myApp.alert('Het spijt me, maar geolocatie wordt niet ondersteund door deze browser.', 'Geen geolocatie ondersteuning');\n }\n}", "function getLocalizacao() {\r\n \r\n if(navigator.geolocation){ \r\n navigator.geolocation.getCurrentPosition(mapSetup);\r\n }\r\n}", "async function getGPSData(data) {\n let frameRate;\n let inner = '';\n let device = '';\n if (data['frames/second'] != null)\n frameRate = `${Math.round(data['frames/second'])} fps`;\n for (const key in data) {\n if (data[key]['device name'] != null) device = data[key]['device name'];\n if (data[key].streams) {\n for (const stream in data[key].streams) {\n await breathe();\n //If we find a GPS stream, we won't look on any other DEVCS\n if (\n (stream === 'GPS5' || stream === 'GPS9') &&\n data[key].streams[stream].samples\n ) {\n let name;\n if (data[key].streams[stream].name != null)\n name = data[key].streams[stream].name;\n let units;\n if (data[key].streams[stream].units != null)\n units = `[${data[key].streams[stream].units.toString()}]`;\n let sticky = {};\n //Loop all the samples\n\n for (let i = 0; i < data[key].streams[stream].samples.length; i++) {\n const s = data[key].streams[stream].samples[i];\n //Check that at least we have the valid values\n if (s.value && s.value.length > 1) {\n //Update and remember sticky data\n if (s.sticky) sticky = { ...sticky, ...s.sticky };\n let time = '';\n let ele = '';\n let geoidHeight = '';\n //Use sticky info\n if (sticky.geoidHeight != null)\n geoidHeight = `\n <geoidheight>${sticky.geoidHeight}</geoidheight>`;\n //Set elevation if present\n if (s.value.length > 1)\n ele = `\n <ele>${s.value[2]}</ele>`;\n //Set time if present\n if (s.date != null) {\n if (typeof s.date != 'object') s.date = new Date(s.date);\n try {\n time = `\n <time>${s.date\n .toISOString()\n .replace(/\\.(\\d{3})Z$/, 'Z')}</time>`;\n } catch (e) {\n time = `\n <time>${s.date}</time>`;\n }\n }\n //Create sample string\n const partial = `\n <trkpt lat=\"${s.value[0]}\" lon=\"${s.value[1]}\">\n ${(ele + time + geoidHeight).trim()}\n </trkpt>`;\n if (i === 0 && s.cts > 0) {\n // If first sample missing, fake it for better sync\n let firstDate;\n try {\n firstDate = new Date(s.date.getTime() - s.cts)\n .toISOString()\n .replace(/\\.(\\d{3})Z$/, 'Z');\n } catch (e) {\n firstDate = new Date(s.date - s.cts)\n .toISOString()\n .replace(/\\.(\\d{3})Z$/, 'Z');\n }\n const firstTime = `\n <time>${firstDate}</time>`;\n const fakeFirst = `\n <trkpt lat=\"${s.value[0]}\" lon=\"${s.value[1]}\">\n ${(ele + firstTime + geoidHeight).trim()}\n </trkpt>`;\n inner += `${fakeFirst}`;\n }\n //Add it to samples\n inner += `${partial}`;\n }\n }\n //Create description of file/stream\n const description = [frameRate, name, units]\n .filter(e => e != null)\n .join(' - ');\n return { inner, description, device };\n }\n }\n }\n }\n return { inner, description: frameRate || '', device };\n}", "function gps_cargarCamposInfo() {\n\n var placa = document.getElementById(\"info_placa\").value;\n var numi = document.getElementById(\"info_numeracionInicial\").value;\n var numf = document.getElementById(\"info_numeracionFinal\").value;\n var dist_mt = document.getElementById(\"info_distanciaRecorrida\").value;\n var ipk = document.getElementById(\"info_ipk\").value;\n var indicadorGPS = document.getElementById(\"info_indicadorGPS\").value;\n var indicadorGPSTitle = document.getElementById(\"info_indicadorGPSTitle\").value;\n var idGPS = document.getElementById(\"info_idGPS\").value;\n var numDatos = document.getElementById(\"info_numDatos\").value;\n var dist_km = dist_mt / 1000;\n\n var pasajeros = (numf - numi);\n pasajeros = (pasajeros >= 0) ? pasajeros : 0;\n\n var oIndicadorGPS = $(\".resumen.indicator-gps\");\n if (oIndicadorGPS !== null) {\n $(oIndicadorGPS).removeClass(\"active\");\n $(oIndicadorGPS).removeClass(\"inactive\");\n $(oIndicadorGPS).removeClass(\"unhooked\");\n $(oIndicadorGPS).removeClass(\"reset\");\n $(oIndicadorGPS).addClass(indicadorGPS);\n $(oIndicadorGPS).attr(\"data-gps\", idGPS);\n $(oIndicadorGPS).attr(\"title\", indicadorGPSTitle);\n }\n document.getElementById(\"placa\").value = placa;\n document.getElementById(\"numInicial\").value = (numDatos === \"0\" ? \"-\" : numi);\n document.getElementById(\"numFinal\").value = (numDatos === \"0\" ? \"-\" : numf);\n document.getElementById(\"numPasajeros\").value = (numDatos === \"0\" ? \"-\" : pasajeros);\n document.getElementById(\"distanciaRecorrida\").value = (numDatos === \"0\" ? \"-\" : dist_km + \" Km\");\n document.getElementById(\"ipk\").value = (numDatos === \"0\" ? \"-\" : ipk);\n}", "function getLocation() {\n navigator.geolocation.getCurrentPosition(function(position) {\n lat = position.coords.latitude;\n lon = position.coords.longitude;\n console.log('lat =' + lat + ', lon =' + lon);\n });\n }", "function Sunpos()\n{\t\n var Topo_Lat = latitude;\n var Topo_Long = longitude;\n\tvar Local_hrs = (new Date().getHours() * 3600) + (new Date().getMinutes() * 60) + (new Date().getSeconds());\n\tvar UTC_hrs = Local_hrs + (new Date().getTimezoneOffset()*60) ;\n\tvar UT1_hrs = UTC_hrs / 3600.0;\n\tvar UT1_deg = UT1_hrs * 15.0 ;\n var Day = new Date().getDate();\n\tvar Month = new Date().getMonth()+1;\n var Year = new Date().getFullYear();\n\tif (Month <= 2) { Year -= 1 ; Month += 12 ;}\n\tvar A = Math.floor(Year/100) ;\n\tvar B = 2 - A + Math.floor(A/4) ;\n\tvar JD_Date = Math.floor(365.25*(Year + 4716)) + Math.floor(30.6001*(Month+1)) + Day + B - 1524.5 ;\n\tvar JD_days = JD_Date + UT1_hrs / 24.0 ;\n\n\tvar tau = (JD_days - 2451545) / 36525 ;\n var Del_T_sec ;\n\tif (tau < 0.05) \n { Del_T_sec = ((- 624.197 * tau - 186.451) * tau + 27.384) * tau + 63.837 ;}\n\telse if (tau < 0.10) \n { Del_T_sec = ((-7277.152 * tau + 1756.476) * tau - 108.618) * tau + 66.637 ;}\n\telse if (tau < 0.15) \n { Del_T_sec = ((-8614.842 * tau + 3574.448) * tau - 441.389) * tau + 83.073 ;}\n\telse if (tau < 0.20) \n { Del_T_sec = ((-8386.677 * tau + 4245.182) * tau - 659.939) * tau + 99.801 ;}\n\telse \n { Del_T_sec = ( 2.162 * tau + 44.874) * tau + 61.749 ;}\n\n\tvar JD_TT_days = JD_days + Del_T_sec/24/3600.0 ;\n\tvar TT_cent = (JD_TT_days - 2451545)/36525.0 ;\n\tvar Sol_Long_V_deg = Get_Ecliptic_Longitude (TT_cent) ;\n\tvar Sol_Lat_V_deg = Get_Ecliptic_Latitude (TT_cent) ;\n\tvar Sol_Radius_AU = Get_Radius_Vector (TT_cent) ;\n\tvar Nut_in_Long_deg = Get_Nutation_in_Longitude(TT_cent) ;\n\tvar Nut_in_Obl_deg = Get_Nutation_in_Obliquity(TT_cent) ;\n\n\t// ***************************************************************************************************\n\t// GET MEAN OBLIQUITY OF ECLIPTIC\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 147\n\tvar tau00 = TT_cent/100 ;\n\tvar Obliquity_Base = 23.0 + 260.0 / 600.0 + 21.448 / 3600.0 ;\n\tvar deli = (tau00 * (-4680.93 + tau00 * ( -1.55 + tau00 * (1999.25 + tau00 * (-51.38 + tau00 * ( -249.67 + tau00 * (-39.05 + tau00 * ( 7.12 + tau00 * ( 5.79 + tau00 * ( 27.87 + tau00 * 2.45)))))))))) ;\n\tvar Obl_Mean_deg = Obliquity_Base + deli / 3600 ;\n\t\n\t//***************************************************************************************************\n\t// Convert from VSOP >> FK5\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 219 Equ 32.3\n var Lambda_Dash_rad = radians(Sol_Long_V_deg - 1.397 * TT_cent - 0.00031 * UT1_hrs * UT1_hrs) ;\n\tvar Long_Corr = (-0.09033 + 0.03916 * (Math.cos(Lambda_Dash_rad) + Math.sin(Lambda_Dash_rad)) * Math.tan(radians(Sol_Lat_V_deg))) / 3600.0 ;\n\tvar Lat_Corr = ( 0.03916 * (Math.cos(Lambda_Dash_rad) - Math.sin(Lambda_Dash_rad)) ) / 3600.0 ;\n\tvar Sol_Long_F_deg = Sol_Long_V_deg + Long_Corr ;\n\tvar Sol_Lat_F_deg = Sol_Lat_V_deg + Lat_Corr ;\n\t\t\n\t// Correct for Nutation & Aberation_deg\n\tvar Obl_True_deg = Obl_Mean_deg + Nut_in_Obl_deg ;\t\n\tvar Aberation_deg = -20.4898 / Sol_Radius_AU /3600.0 ;\n\tvar Sol_Long_Appt_deg = Sol_Long_F_deg + Nut_in_Long_deg + Aberation_deg ;\n\n\t// Convert >> Radians\n\tvar Sol_Long_rad = radians(Sol_Long_Appt_deg) ;\n\tvar Sol_Lat_rad = radians(Sol_Lat_F_deg) ;\n\tvar Obl_rad = radians(Obl_True_deg) ;\n\n\t// Convert Longitude & Latitude >> RA & Declination\n\tvar RA_denom = Math.sin(Sol_Long_rad) * Math.cos(Obl_rad) - Math.tan(Sol_Lat_rad) * Math.sin(Obl_rad) ;\n\tvar RA_num = Math.cos(Sol_Long_rad) ;\n\tvar RA_rad = Math.atan2(RA_denom,RA_num) ;\n\tvar Decl_rad = Math.asin(Math.sin(Sol_Lat_rad) * Math.cos(Obl_rad) + Math.cos(Sol_Lat_rad) * Math.sin(Obl_rad) * Math.sin(Sol_Long_rad)) ;\n\n\t// Convert >> Degrees & hours\n\tvar RA_deg = (360.0 + degrees(RA_rad)) % 360.0 ;\n//\tvar RA_hrs = RA_deg / 15.0 ;\n//\tvar Decl_deg = degrees(Decl_rad) ;\n \n // ***************************************************************************************************\n\t// Calculate Greenwich Mean Sidereal Time\n\t// Reference: USNO Circular 179 by G.H. Kaplan\n\t// The IAU Resolutions on Astronomical Reference Systems, Time Scales, \n\t// and Earth Rotation Models - Eqns 2.11 & 2.12\n\tvar DU = JD_days - 2451545.0 ;\n\tvar Theta = 0.7790572732640 + 0.00273781191135448 * DU + JD_days % 1 ;\n\tvar GMST_base = (86400.0 * Theta) % 86400.0 ;\n\tvar Extra = 0.014506 + TT_cent * (4612.156534 + TT_cent * (1.3915817 + TT_cent * (-0.00000044 + TT_cent * (-0.000029956 - TT_cent * 0.0000000368)))) ;\n\tvar GMST_hrs = ((GMST_base + Extra / 15.0) % 86400.0)/3600.0 ;\n\tvar GMST_deg = 15.0 * GMST_hrs ;\n\t\n\t// ***************************************************************************************************\n\t// Calculate Equation of the Equinoxs & Greenwich Apparent Sidereal Time\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 88\n\tvar Eqn_of_Equi_deg = Nut_in_Long_deg * Math.cos(Obl_rad) ;\n\tvar GAST_deg = GMST_hrs * 15.0 + Eqn_of_Equi_deg ;\n//\tvar GAST_hrs = GAST_deg / 15.0 ;\n\t\n\t// ***************************************************************************************************\n\t// Calculate Geocentric Equation of Time\n\tvar EoT_deg = (GMST_deg - UT1_deg - RA_deg + 180.0 + Eqn_of_Equi_deg ) ;\n\tif (EoT_deg > 180) {EoT_deg = EoT_deg - 360.0;}\n//\tvar EoT_min = EoT_deg * 4.0 ;\n\n\t// ***************************************************************************************************\n\t// Local Apparent Siderial Time and Hour Angle\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 92\n\tvar LAST_deg = GAST_deg + Topo_Long ;\n\tvar HA_deg = (LAST_deg - RA_deg) % 360.0 ;\n\tif (HA_deg > 180) { HA_deg = HA_deg - 360.0 ; }\n\tvar HA_rad = radians(HA_deg) ;\n\n\t// ***************************************************************************************************\n\t// Calculate Parallax Correction Parameters\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 82 & 279\n\tvar Topo_Lat_rad = radians(Topo_Lat) ;\n\tvar tanu = 0.99664719 * Math.tan(Topo_Lat_rad) ;\n\tvar u = Math.atan(tanu) ;\n //var Rho_sin_Phi_ = 0.99664719 * Math.sin(u) + Math.sin(Topo_Lat_rad) * Height / 6378140 ;\n\tvar Rho_sin_Phi_ = 0.99664719 * Math.sin(u) + Math.sin(Topo_Lat_rad) * 500 / 6378140 ;\n\tif (Topo_Lat_rad < 0) {Rho_sin_Phi_ = -Rho_sin_Phi_;} \n //var Rho_cos_Phi_ = Math.cos(u) + Math.cos(Topo_Lat_rad) * Height / 6378140 ;\n\tvar Rho_cos_Phi_ = Math.cos(u) + Math.cos(Topo_Lat_rad) * 500 / 6378140 ;\n\tvar sin_Pi_ = 3.14159265358979 * 8.794 / Sol_Radius_AU / 180 / 3600 ;\n\n\t// ***************************************************************************************************\n\t// Convert Geocentric RA >> Topocentric RA\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 279\n\tvar tan_Del_RA = (-Rho_cos_Phi_ * sin_Pi_ * Math.sin(HA_rad)) / (Math.cos(Decl_rad) - Rho_cos_Phi_ * sin_Pi_ * Math.cos(HA_rad)) ;\n\tvar RA_Parallax_rad = Math.atan(tan_Del_RA) ;\n\tvar Topo_RA_deg = (RA_deg + degrees(RA_Parallax_rad)) % 360 ;\n//\tvar Topo_RA_hrs = Topo_RA_deg / 15.0 ;\n\n\t// ***************************************************************************************************\n\t// Convert Geocentric Declination >> Topocentric Declination\n\t// Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 279\n\tvar tan_dec1 = (Math.sin(Decl_rad) - Rho_sin_Phi_ * sin_Pi_) * Math.cos(RA_Parallax_rad) ;\n\tvar tan_dec2 = (Math.cos(Decl_rad) - Rho_cos_Phi_ * sin_Pi_ * Math.cos(HA_rad)) ;\n\tvar Topo_Decl_rad = Math.atan(tan_dec1 / tan_dec2) ;\n//\tvar Topo_Decl_deg = degrees(Topo_Decl_rad) ;\n\n\t// ***************************************************************************************************\n\t// Calculate Topocentric Equation of Time\n\tvar Topo_EoT_deg = (GAST_deg - UT1_deg - Topo_RA_deg + 180.0 ) % 360.0 ;\n\tif (Topo_EoT_deg > 180.0) {Topo_EoT_deg = Topo_EoT_deg - 360.0;}\n\tvar Topo_EoT_min = Topo_EoT_deg * 4.0 ;\n//\tvar Sol_to_Civil_min = -Topo_EoT_min + Zone * 60.0 - Topo_Long * 4.0 + Dst * 60.0 ;\n\n\t// ***************************************************************************************************\n\t//Calculate Topocentric Hour Angle\n\t\tvar Topo_HA_deg = (LAST_deg - Topo_RA_deg) % 360.0 ;\n//\t\tvar Topo_HA_hrs = Topo_HA_deg / 15.0 ;\n\t\tif (Topo_HA_deg > 180) { Topo_HA_deg = Topo_HA_deg - 360.0;} \n\t\tvar Topo_HA_rad = radians(Topo_HA_deg) ;\n\n\t// ***************************************************************************************************\n\t//Convert Hour Angle, Latitude & Declination to Solar Azimuth & Altitude\n\t//Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 93\n\t\tvar Alt_rad = Math.asin(Math.sin(Topo_Lat_rad) * Math.sin(Topo_Decl_rad) + Math.cos(Topo_Lat_rad) * Math.cos(Topo_Decl_rad) * Math.cos(Topo_HA_rad)) ;\n//\t\tvar Alt_Airless_deg = degrees(Alt_rad) ;\n//\t\tvar Zenith_deg = 90.0 - Alt_Airless_deg ;\n\n\t\tvar cos_Azim = ( Math.sin(Topo_Decl_rad) - Math.sin(Alt_rad) * Math.sin(Topo_Lat_rad) ) / ( Math.cos(Alt_rad) * Math.cos(Topo_Lat_rad)) ;\n\t\tvar sin_Azim = - Math.cos(Topo_Decl_rad) * Math.sin(Topo_HA_rad) / Math.cos(Alt_rad) ;\n\t\tvar Azim_rad = Math.atan2(sin_Azim, cos_Azim) ;\n\t\tvar Azim_deg = degrees(Azim_rad) % 360 ;\n\t\tif (Azim_deg < 0) {Azim_deg = Azim_deg + 360.0;}\n\t\n\t// ***************************************************************************************************\n\t//GET REFRACTION CORRECTION\n\t//Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 106 - 107\n//\t\tvar refr = (1.02 / Math.tan(radians(Alt_Airless_deg + 10.3 / (Alt_Airless_deg + 5.11)))) / 60.0 ;\n//\t\tvar Refraction_deg = refr * Pressure * 283 / (Pressure * (273 + Temperature)) ;\n//\t\tif (Alt_Airless_deg > 89) {Refraction_deg = 0;}\n\n\t// ***************************************************************************************************\n\t//GET REFRACTION CORRECTED ALTITUDE OF SUN\n\t//Reference: Astronomical Algorithms 2nd Edition 1998 by Jean Meeus - Page 105\n//\t\tvar Alt_Refrac_deg = Alt_Airless_deg + Refraction_deg ;\n//\t\tif (Alt_Refrac_deg < 0) {Alt_Refrac_deg = 9999.0 ;}\n return Topo_EoT_min;\n}", "function obtainGeolocation(){\n window.navigator.geolocation.getCurrentPosition(localitation);\n }", "function onSuccess(position) {\n\n var db = window.openDatabase(\"dbPDV\", \"1.0\", \"PDV Demo\", 200000);\n //alert(position.coords.latitude );\n //Relembrando formatação de data pra checar qual é compativel com datetime do sqlite\n var date = new Date();\n var year = date.getFullYear();\n var day = date.getDay();\n var month = date.getMonth();\n var min = ('0'+date.getMinutes()).substr(-2);\n var seconds = ('0'+date.getSeconds()).substr(-2);\n var hour = ('0'+date.getHours()).substr(-2);\n var dataTeste= year+\"-\"+month+\"-\"+day+\" \"+hour+\":\"+min+\":\"+seconds;\n //alert(\"data inteira= \"+date+\" separada : \"+year+\"-\"+month+\"-\"+day+\" \"+hour+\":\"+min+\":\"+seconds);\n\n //'2007-01-01 10:00:00' < formato no banco\n //Inserta no banco\n db.transaction(function(tx)\n {\n tx.executeSql('INSERT INTO gps(idUser,lat,long,enviado,data) VALUES (\"'+idUsuario+'\",\"'+position.coords.latitude+'\",\"'+position.coords.longitude+'\",1,\"'+dataTeste+'\")');\n });\n\n $.ajax({\n type: 'POST',\n url: \"http://app.businessmap.com.br/coordenadas/new/\",\n data: {'user_id':idUsuario,'lat':position.coords.latitude,'lng':position.coords.longitude,'data':dataTeste},\n success: function(responseData, textStatus, jqXHR) {\n //$(\"#pageLogado\").html(responseData+\" horario\"+dataTeste);\n },\n error: function (responseData, textStatus, errorThrown) {\n //alert('POST failed.' + responseData + \", \" + textStatus + \", \" + errorThrown);\n }\n });\n}", "function getLocation(){\n self.polyline = [];\n self.markers = [];\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(setUserLocation);\n } else {\n console.log(\"geolocation error\");\n }\n }", "function obtenirLocalisation() {\r\n if (navigator.geolocation) {\r\n navigator.geolocation.getCurrentPosition(determinerPosition, annulerAffichage);\r\n } else {\r\n alert(\"Geolocalisation non implementee.\");\r\n }\r\n}", "function getLocalWeather() {\n navigator.geolocation.getCurrentPosition(showPosition);\n}", "function getPosition() {\n\n\t//change time box to show updated message\n\t$('#time').val(\"Getting data...\");\n\n\t//instruct location service to get position with appropriate callbacks\n\tnavigator.geolocation.getCurrentPosition(successPosition, failPosition);\n}", "function refreshLocVariables(){\n\ttargetPoint = false;\n\ttempTin=false;\n\ttin=false;\n\tnearest=false;\n\tnearest_turf=false;\n\tbuffered=false;\n\tptsWithin=false;\n\tmyPoint=false;\n\tcoords_x = []; //define an array to store the lng coordinate\n\tcoords_y = []; //define an array to store the lat coordinate\n\tcoords_z = []; //define an array to store elev coordinate\n\tkeyLocLocation = false;\n}", "function startGeolocation() {\n geolocation = true;\n\n\t/** On met à jour la position de l'utilisateur toutes les trois secondes. */\n var options = { maximumAge: 5000, frequency: 5000, enableHighAccuracy: true };\n\n watchID = navigator.geolocation.watchPosition(onLocationSuccess, onLocationError, options);\n\n\t// old_loc = map.getCenter();\n\t// init_lat = old_loc.jb;\n\t// init_long = old_loc.kb;\n}", "function getLocation() {\n window.navigator.geolocation.getCurrentPosition((location) => {\n userLat = location.coords.latitude;\n userLon = location.coords.longitude;\n checkParkCoord();\n })\n }", "function setGPS(gps) {\n document.getElementById(\"lat\").innerHTML = gps.lat;\n document.getElementById(\"lng\").innerHTML = gps.lng;\n}" ]
[ "0.6806493", "0.6790628", "0.674347", "0.6673686", "0.6665772", "0.66496015", "0.6642753", "0.6626201", "0.66116124", "0.65597874", "0.6546017", "0.65106773", "0.6471653", "0.6456484", "0.633452", "0.62265366", "0.6222223", "0.62213564", "0.6143627", "0.61407936", "0.61323166", "0.6121054", "0.6086328", "0.60789186", "0.60607105", "0.60587895", "0.6052874", "0.6036967", "0.60368603", "0.6029032" ]
0.69579315
0
Aggiunge marker al click e ferma la localizzazione
function addMarkerClick(e){ maxDist = 0.8 / 110.574; distGPStoSelection = Math.sqrt(Math.pow(e.latlng.lat - truelat, 2) + Math.pow(e.latlng.lng - truelon, 2)); // Controlla se la distanza non è eccessiva if(distGPStoSelection <= maxDist && stato == 1){ updateData(e.latlng.lat, e.latlng.lng); stopLocation(); $("#geo-information").html('<div class="alert alert-dark text-center" role="alert">📌 Modalità selezione manuale, la geolocalizzazione è in pausa. 🛑 </div>'); } else if (distGPStoSelection <= maxDist){ $("#geo-information").html('<div class="alert alert-info text-center" role="alert">✋ Attendi che l\' accuratezza migliori prima di selezionare la posizione dalla mappa manualmente.<div class="spinner-grow spinner-grow-sm float-right" role="status"></div></div>'); } else if (stato == 1) { $("#geo-information").html('<div class="alert alert-danger text-center" role="alert">✋ Non puoi selezionare un punto così distante dalla tua posizione attuale.'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function clickMarker(e) {\n deselectCurrentMarker();\n var markerComponent = mly.getComponent('marker');\n var marker = e.target || e;\n marker.options.tags = marker.options.tags || {};\n selectedMarker = marker;\n marker.setIcon(redIcon);\n markerId = marker.id;\n currentMarkerId = markerId;\n markerComponent.add([mapillaryMarkers[currentMarkerId]]);\n}", "function myclick(i) {\r\n google.maps.event.trigger(gmarkers[i], \"click\");\r\n}", "function openMarker(i) {\n GEvent.trigger(gmarkers[i], \"click\");\n}", "function myclick(i) {\n\tgoogle.maps.event.trigger(gmarkers[i], \"click\");\n}", "function addMarkerOnClick(){\n return function() {\n globalVariables.clickMarker.setMap(null); //clear new marker created from right click\n for(var marker = 0; marker < globalVariables.markers.length; marker ++) {\n globalVariables.markers[marker].setAnimation(null);\n }\n this.setAnimation(google.maps.Animation.BOUNCE);\n populateInfoWindow(this, globalVariables.infoWindow);\n };\n}", "function klikInfoWindow(id, marker)\n{\n google.maps.event.addListener(marker, \"click\", function(){\n detailmes_infow(id);\n\n });\n\n}", "function myClick(id){\n google.maps.event.trigger(markers[id], 'click');\n }", "function markerClick(data) {\n let data2;\n $(markers).each(function(i) {\n markers[i].addListener('click', function() {\n if(this.infowindow) return this.infowindow.open(map, this);\n let markerNumber = markers.indexOf(this);\n displayWindow(data[markerNumber], this);\n });\n });\n }", "function markerClick(e) {\n var coord = e.latlng;\n fillFieldsLatlng(coord)\n }", "function clickBMCC(evt){\n\t\tevt.preventDefault();\n\t\t$.each(locations, function(id, info)\n\t\t{ \n\t\t\tconsole.log(info);\n var mark= addMarker(info.loc[0], info.loc[1]);\t\n \n mark.index = id;\n\n\t\tvar listener = google.maps.event.addListener(mark, \"click\", clickMap);\n\n\t\t}); \t\t\n\t}", "function handleClick(d, i) {\n // Create a new custom event and listen to it in the main module\n var selectNewMarker = new CustomEvent('selectNewMarker', { detail: {\n props: function props() {\n return d.properties;\n }\n }\n });\n svgDOM.dispatchEvent(selectNewMarker);\n }", "function addClicker(marker, content) {\n google.maps.event.addListener(marker, 'click', function() {\n \n if (infowindow) {infowindow.close();}\n infowindow = new google.maps.InfoWindow({content: content});\n infowindow.open(map, marker);\n });\n }", "function googlemarkerclicked() {\r\n\r\n\tvar currmarker = this;\r\n\r\n\tvar markerid = this.mid;\r\n\r\n\t//Handle marker click\r\n\tmarkerclicked(markerid, currmarker);\r\n\r\n}", "function liClicked(clickLi) {\n populateInfoWindow(clickLi, new google.maps.InfoWindow());\n}", "function onMapClick(e) {\n //var markerpop=L.marker(e.latlng).addTo(mymap);\n var markerfire = L.marker(e.latlng, {icon: firefoxIcon}).addTo(mymap);\n markerfire.bindPopup(e.latlng+\"Location\").openPopup(); \n \n}", "function mapOnClick(e) {\n var coords = e.latLng;\n \n geocoder.geocode({'location': coords}, function(results, status) {\n if (status === 'OK') {\n if (program.addAllInfo(results[0])) { setMarkerPosition(coords); }\n } else {\n program.showMessage(\"\", \"Óþekkt villa. Ekki tókst að sækja staðsetninguna\");\n }\n });\n }", "function onMarkerClick() {\n // this represents marker that is clicked on.\n var marker = this;\n\n // remove temp marker if exists\n if (tempDraggingMarker) {\n tempDraggingMarker.setMap(null);\n }\n\n setAllMarkersDefaultStyle();\n setMarkerCurrentStyle(marker);\n\n root.showFromData(getMarkerData(marker, marker.data));\n }", "function triggerClick(i) {\n google.maps.event.trigger(markers[i], \"click\");\n}", "function setMarker(lat,long,title,id){var myLatlng=new google.maps.LatLng(lat,long);var marker=new google.maps.Marker({position:myLatlng,icon:'images/farm-2.png',animation:google.maps.Animation.DROP,'title':title});marker.setMap(map);google.maps.event.addListener(marker,'click',function(){window.location='single.php?id='+id;});}", "function onClickTargetMarker(ev){\n\tvar map = ev.data.map;\n\tvar idPoi = $(ev.currentTarget).parent().data('poi');\n\tvar markeur = map.getMarker(idPoi);\n\n\t//Zoom on marker\n\tmap.mapApi.setZoom(8);\n\tmap.mapApi.setCenter(markeur.getPosition());\n\n\t//Open infoWindowé\n\tif(!markeur.infoWindow.getMap()){\n\t\tmap.trigger(markeur, 'click');\n\t}\n}", "function infoClicked(lat, long, name, link){\n const image = {\n url: \"http://www.stickpng.com/assets/images/58469c62cef1014c0b5e47f6.png\",\n scaledSize: new google.maps.Size(30, 30)\n };\n\n let marker = new google.maps.Marker({\n position: new google.maps.LatLng(lat, long),\n icon: image,\n animation: google.maps.Animation.DROP,\n map: map\n \n });\n\n const infoContent = `<a href=\"${link}\" target=\"blank\">${name}</a>`;\n\n mapWindow.setContent(infoContent);\n mapWindow.open(map, marker);\n}", "markerClick(id, cafe) {\n this.setState({ redirect: true, id: id });\n this.clickToggle();\n // Set other markers to invisible\n this.deleteMarkers(cafe);\n }", "function _mapClick() {\n infoBoxManager.turnOffInfoBoxStates();\n infoBoxManager.updateInfoBoxState(_overMarker, 0);\n}", "addEventMarker(coord, text, iconKey, events, ourEventOptions) {\n let eventMarker = this.addMarker(coord, text, iconKey);\n eventMarker.ourEventOptions = ourEventOptions;\n eventMarker.on(\"click\", () => {\n events(eventMarker.ourEventOptions);\n });\n }", "function onMarkerClick(e) {\n\t\t//abrimos una ventana para editar\n\t var nombre = obtenerNombreMarcador(e.target);\n\t var latLng = e.target.getLatLng();\n\t var lat = latLng.lat;\n\t var lng = latLng.lng;\n\t var altura = jQuery(jQuery(\"#ID-\" + nombre.replace(\" \", \"_\")).children()[4]).text();\n\n\n\t popupEditar = popup\n\t .setLatLng(e.latlng)\n\t .setContent('<input type=\"hidden\" id=\"popupNombreOrig\" value=\"'+nombre+'\"/><h5 style=\"text-align:center;\">Editar</h3><table cellpadding=\"5\" cellspacing=\"5\" class=\"tablaEdit\"><tr><td>Nombre:</td> <td><input type=\"text\" id=\"popupNombre\" value=\"'+nombre+'\"/></td> </tr> <tr><td>Latitud:</td> <td><input type=\"text\" id=\"popupLat\" value=\"'+lat+'\"/> </td></tr> <tr><td>Longitud:</td> <td><input type=\"text\" id=\"popupLng\" value=\"'+lng+'\"/></td> </tr> <tr><td>Altura:</td> <td><input type=\"text\" id=\"popupAlt\" value=\"'+altura+'\"/></td> </tr></table> <table style=\"width:100%;\"><tr><td style=\"width:45%;\"><button onclick=\"editarMarcador();\">Guardar</button></td><td style=\"width:10%;\"></td><td style=\"width:45%;\"><button onclick=\"definirPuntoInicial();\">Definir PI</button></td></tr></table><style>.table {border-spacing: 5px;}</style>' )\n\t .openOn(map); \n\t}", "function attachClickBehaviour(marker){\n\tmarker.addListener('click', function(event){\n\t\tvar currLoc = mapModel.setLocationByID(marker.id);\n\t}, false);\n}", "function movimiento(evt)\n{\n\tvar position=$(evt.currentTarget).attr('id');\n\tmarkerPosition(position);\n}", "function onMapClick(e){\r\n\t\t\t\tvar coordinate = e.latlng.toString().split(',');\r\n\t\t\t\tvar lat = coordinate[0].split('(');\r\n\t\t\t\tvar lng = coordinate[1].split(')');\r\n\t\t\t\tvar latlng = \"You preclicked the map at <br><strong>Latitude: </strong>\" + lat[1]\r\n\t\t\t\t+ \"<br><strong>Longitude: </strong>\" + lng[0];\r\n\t\t\t\tinfo.innerHTML = latlng;\r\n\t\t\t\tpopup\r\n\t\t\t\t\t.setLatLng(e.latlng)\r\n\t\t\t\t\t.setContent(latlng)\r\n\t\t\t\t\t.openOn(map);\r\n\t\t\t}", "onMarkerClick(props, marker, e) {\n this.setState({\n selectedGame: props.game,\n activeMarker: marker,\n showingInfoWindow: true\n });\n this.renderActionButton();\n }", "function mutiple_mark_trigger()\n{\n beepOnce();\n google.maps.event.trigger(map, 'resize');\n // document.getElementById('searchbytext').style.display=\"none\";\n document.getElementById('myicon1').className=\"\";\n $(\"#myicon1\").attr(\"href\", \"#donor_1\");\n $(\"#myicon1\").addClass('icon left');\n $(\"#myicon1\").attr(\"onClick\",\"dummy()\");\n document.getElementById('myicon2').className=\"\";\n $(\"#myicon2\").attr(\"href\", \"#main\");\n $(\"#myicon2\").addClass('icon home');\n $(\"#myicon2\").attr(\"onClick\",\"dummy()\");\n $('#map-canvas').data('type',2);\n document.getElementById('myicon3').className=\"\";\n $(\"#myicon3\").attr(\"href\", \"#bank\");\n $(\"#myicon3\").addClass('icon new');\n $(\"#myicon3\").attr(\"onClick\",\"dummy()\");\n //alert(\"function called for nothing\");\n showMarkers();\n google.maps.event.trigger(map, 'resize');\n map.setZoom(map.getZoom());\n}" ]
[ "0.73829496", "0.7328061", "0.7317792", "0.7284404", "0.72814536", "0.7237583", "0.72132736", "0.7191674", "0.7135163", "0.7121554", "0.70174956", "0.7004344", "0.6958005", "0.69403994", "0.6860577", "0.6844564", "0.68438077", "0.6829785", "0.68135905", "0.67789155", "0.6758446", "0.6739194", "0.67367375", "0.6732536", "0.67310333", "0.6725194", "0.6724078", "0.67174137", "0.6701444", "0.67010427" ]
0.76976025
0
sorts tabs then displays in square grid for easy navigation
function organizeTabs(){ chrome.tabs.query({currentWindow:true}, function(tabs) { //selects all tabs from current window console.log(tabs);//check the console for more tab information //sorts array of obj's. Source: http://stackoverflow.com/users/43452/stobor tabs.sort(function(a, b) { return a['url'].localeCompare(b['url']); }); var urllist = document.getElementById('tabs'); for(var i in tabs){ var tablen = tabs.length; if((i%Math.floor(Math.sqrt(tablen)) === 0 && tablen <= 7*7) || (tablen > 7*7 && i%6 === 0)){ var row = document.createElement('tr'); urllist.appendChild(row);//adds a new row to the table } //tabitem consists of entries in larger table var tabitem = document.createElement('td'); tabitem.id = String(tabs[i]['id']);//sets <td id='tab.id'> tabitem.className = 'clickTab'; row.appendChild(tabitem); //each tabitem has its data formatted in a table var formattedCell = document.createElement('table'); tabitem.appendChild(formattedCell); var cellData = document.createElement('tr'); formattedCell.appendChild(cellData);//there will only be ONE row per cell var iconTd = document.createElement('td'); iconTd.className = 'icontd'; cellData.appendChild(iconTd);//adding icon to cell var lengthLimit = 12,//max number of characters per line visibleText = 30,//max visible characters from title rawTitle = tabs[i]['title'].length>visibleText? tabs[i]['title'].slice(0,visibleText) + '...' : tabs[i]['title'] ; //puts space into URLs or other long text that throws off text spacing var cleanOnce = function(raw, visChars){ var words = raw.split(' '); for(var w in words){ var len = words[w].length; if(len > visChars){ words[w] = words[w].slice(0,len/2) + ' ' + words[w].slice(Math.ceil(len/2),len); } } return words.join(' '); } var rawTitle = cleanOnce(cleanOnce(rawTitle, lengthLimit),lengthLimit); //second data entry to cell table. icon on left, textTd on right var textTd = document.createElement('td'); textTd.className = "title"; cellData.appendChild(textTd); var titleNode = document.createTextNode(rawTitle); textTd.appendChild(titleNode); var iconDim = 32, img = new Image(iconDim,iconDim),//width, height iconUrl = tabs[i]['favIconUrl']; var pattern = /png|jpg|ico/g;//acceptable icon extensions if(pattern.test(iconUrl)){ //only adds icon image if one is found img.src = iconUrl; }else{ img.src = "/images/default.png"; } iconTd.appendChild(img); } //iterates through every entry in the table and attaches a listener var addListeners = function addTableListeners(){ for (var i = 0; i < urllist.children.length; i++) { for(var j = 0; j < urllist.children[i].children.length; j++){ var childElement = urllist.children[i].children[j]; childElement.addEventListener('click', function(){ chrome.tabs.get(parseInt(this.id), function(mytab){ if(!mytab['active']){//can't modify/select active tab if(window.kill){ var tableCell = document.getElementById(mytab.id); tableCell.parentNode.removeChild(tableCell);//removes tab from table in html chrome.tabs.remove(parseInt(mytab.id));//removes tab from browser }else{ //select new tab to be active chrome.tabs.update(parseInt(mytab.id), {active:true});//no callback necessary } } }); }); } } } addListeners();//connects mouse clicks on table with browser's tabs //end of chrome.tabs.query }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function toevoegen_card_tabs_in_grid() {\n card_tabs_data__arr.map( (card_tab__obj, idx) => {\n $x('.grid_' + eval(idx + 1)).append( aanmaken_card_tabs(idx))\n })\n }", "function display_tabs( tabs ) {\n var tabs_code = $(tabs);\n\n set_active_tab( tabs_code );\n preapare_tabs_interface( tabs_code );\n\n $('#app-table>header').empty();\n $('#app-table>header').append( tabs_code );\n }", "function draw_tabs() {\n // Get tab area\n var tabX = 0;\n var tabY = display.getHeight() - 4;\n var tabW = display.getWidth();\n var tabH = 4;\n\n // Draw the red area\n display.fill(tabX, tabY, tabW, tabH, \"white\", \"red\", ' ');\n\n // Draw instruction text\n display.text(tabX + Math.floor(tabW / 2) - 7, tabY + 1, \"Press <TAB> to\");\n display.text(tabX + Math.floor(tabW / 2) - 10, tabY + 2, \"switch between panes.\");\n\n // Width tab\n display.text(tabX + 2, tabY + 1, \" WIDTH \", 'red', 'white');\n if (tabSelected === 0) {\n display.fill(tabX + 2, tabY + 2, 11, 1, 'red', 'white', ' ');\n }\n display.text(tabX + 6, tabY + 2, etch.getWidth().toString());\n // Height tab\n display.text(tabX + 15, tabY + 1, \" HEIGHT \", 'red', 'white');\n if (tabSelected === 1) {\n display.fill(tabX + 15, tabY + 2, 11, 1, 'red', 'white', ' ');\n }\n display.text(tabX + 19, tabY + 2, etch.getHeight().toString());\n // Clear tab\n display.text(tabX + tabW - 26, tabY + 1, \" CLEAR \", 'red', 'white');\n if (tabSelected === 2) {\n display.text(tabX + tabW - 26, tabY + 2, \" [ENTER] \", 'red', 'white');\n }\n // Exit tab\n display.text(tabX + tabW - 13, tabY + 1, \" EXIT \", 'red', 'white');\n if (tabSelected === 3) {\n display.text(tabX + tabW - 13, tabY + 2, \" [ENTER] \", 'red', 'white');\n }\n}", "function tabLogic() {\n\t// tabbed content\n\t// http://www.entheosweb.com/tutorials/css/tabs.asp\n\t$('.tab-container').each( function() {\n\t\tvar $t = $(this); // the wrapper of all the tabbed content\n\t\tvar $tabset = $t.find('.tab-content'); // the set of chunks of tabbed content\n\t\tvar $tablinkset = $t.siblings('ul.tabs').find('li'); // the set of buttons to hide/reveal\n\t\tvar $tabdrawerset = $t.find('.tab-drawer-heading'); // the set of buttons to fold/unfold\n\t\t$tabset.hide();\n\t\tif (!$t.find('.tab-drawer-heading').is(':visible')) {\n\t\t\t$tabset.eq(0).show();\n\t\t}\n\t\t// when in tab (desktop) mode\n\t\t$tablinkset.click( function() {\n\t\t\t$tabset.hide().removeClass('active');\n\t\t\t$tablinkset.removeClass('active');\n\t\t\t$(this).addClass('active');\n\t\t\tvar activeTab = $(this).attr('data-rel');\n\t\t\t$(\"#\" + activeTab).fadeIn().addClass('active');\n\t\t\t$t.find(\".tab-drawer-heading\").removeClass(\"d-active\");\n\t\t\t$t.find(\".tab-drawer-heading[data-rel^='\" + activeTab + \"']\").addClass(\"d-active\");\n\t\t});\n\t\t// when in drawer (mobile) mode\n\t\t$tabdrawerset.click( function() {\n\t\t\t$tabset.hide().removeClass('active');\n\t\t\tif ($(this).hasClass('d-active')) {\n\t\t\t\t$tabdrawerset.removeClass(\"d-active\").find('span.icon-minus').removeClass('icon-minus').addClass('icon-plus');\n\t\t\t\t$(\"ul.tabs li\").removeClass(\"active\")\n\t\t\t\t$tablinkset.removeClass('active');\n\t\t\t} else {\n\t\t\t\tvar d_activeTab = $(this).attr(\"data-rel\");\n\t\t\t\t$(\"#\" + d_activeTab).fadeIn();\n\t\t\t\t$tabdrawerset.removeClass(\"d-active\").find('span.icon-minus').removeClass('icon-minus').addClass('icon-plus');\n\t\t\t\t$(this).addClass(\"d-active\").find('span.icon-plus').removeClass('icon-plus').addClass('icon-minus');\n\t\t\t\t$tablinkset.removeClass(\"active\");\n\t\t\t\t$tablinkset.filter(\"[data-rel^='\" + d_activeTab + \"']\").addClass(\"active\");\n\t\t\t\t// animate scrolling to the section we just opened\n\t\t\t\t$('html, body').animate({\n\t\t\t\t\tscrollTop: $(\"#\" + d_activeTab).offset().top - $tabdrawerset.outerHeight()\n\t\t\t\t}, 750);\n\t\t\t}\n\t\t});\n\t\t// Extra class \"tab-last\" to add border to right side of last tab\n\t\t$tablinkset.last().addClass(\"tab-last\");\n\t});\n}", "function Tabs(category) {\n var category = category;\n\n // Create the tab structure\n function htmlCode(tab_labels, msg) {\n var keys = Object.keys(tab_labels).sort();\n // Add tab buttons\n var tabs = '<ul class=\"tab-list\">';\n for (var idx in keys) {\n var d = keys[idx];\n var label = category === 'switches' ? 'SW_' + tab_labels[d] : tab_labels[d];\n tabs += '<li class=\"tab-control\" data-tab=\"tab-' + tab_labels[d] + '\">' + label + '</li>';\n }\n tabs += '</ul>';\n\n for (var idx in keys) {\n var s = keys[idx]\n tabs += '<div class=\"tab-panel\" id=\"tab-' + tab_labels[s] + '\"><h1>' + msg + '</h1></div>';\n }\n return tabs;\n }\n\n /**\n * Set listeners to user events.\n */\n function listenToEvents() {\n // only one tab list is allowed per page\n $('.tab-list').on('click', '.tab-control', function () {\n //var tab_id = $(this).attr('data-tab');\n var tab_id = $(this).data('tab');\n\n $('.tab-control').removeClass('active');\n $('.tab-panel').removeClass('active');\n\n $(this).addClass('active');\n $(\"#\" + tab_id).addClass('active');\n\n // Save active tab per category\n saveInSession('activetab', '', tab_id);\n })\n }\n\n // Append HTML\n function buildTabs(parent, tab_labels, msg) {\n var html_code = htmlCode(tab_labels, msg)\n $(parent).empty().append(html_code);\n listenToEvents();\n }\n\n // Fill tab panel\n function buildContent(id, envelope) {\n envelope.children('.tableframe').each(function (i, v) {\n $(v).data('order', i);\n })\n var order_list = getFromSession('order', 'tab-' + id);\n if (order_list) {\n var $cards = envelope.children('.tableframe');\n if ($cards.length != order_list.length) {\n // pass, a table added/removed so we cannot use the previous order\n saveInSession(\"order\", null);\n } else {\n //var $clone = envelope.clone().empty();\n for (var i in order_list) {\n var $card = $cards.eq(order_list[i]).detach();\n envelope.append($card);\n }\n //envelope = $clone;\n }\n }\n $('#tab-' + id).empty().append(envelope);\n }\n\n // Set active tab\n function setActive() {\n $('.tab-control').removeClass('active');\n $('.tab-panel').removeClass('active');\n\n var tab_id = getFromSession('activetab', '');\n if (tab_id) { // Active tab has been saved\n var $first = $('[data-tab=' + tab_id + ']')\n $first.addClass('active');\n $(\"#\" + tab_id).addClass('active');\n } else { // No active tab saved\n var $first = $('.tab-control').first();\n //var tab_id = $first.attr('data-tab');\n var tab_id = $first.data('tab');\n $first.addClass('active');\n $(\"#\" + tab_id).addClass('active');\n saveInSession('activetab', '', tab_id);\n }\n }\n\n return {\n buildTabs: buildTabs,\n buildContent: buildContent,\n setActive: setActive\n };\n}", "function tab(tab) {\n\tif ($.inArray(tab, availableTabs) == -1) {\n\t\tconsole.log(\"invalid tab. Please update your available tabs\");\n\t} else {\n\t\tvar arrayLength = availableTabs.length;\n\t\tfor (var i = 0; i < arrayLength; i++) {\n\t\t\t//maybe have problems where tab doesn't exist\n\t\t $(\"#\"+availableTabs[i] + 'Content').hide(); \n\t\t $(\"#\"+availableTabs[i] + 'Content').css({'class': ''});\n\t\t $(\"#\"+availableTabs[i]).css({'background': 'rgb(0, 45, 60)'});\n\t\t}\n\t\t$(\"#\" + tab + 'Content').show();\n\t\t$(\"#\" + tab + 'Content').css({'class': 'active'});\n\t\tactiveTab = tab;\n\t\t$(\"#\" + tab).css({'background': 'rgb(67, 153, 152)'});\n\t\tif ($.inArray(tab, loadedTabs) == -1) {\n\t\t\tloadTab(activeTab);\n\t\t}\n\t\tif (window.mobilecheck()) {\n\t\t\tlayoutMobileMasonry(activeTab + 'Grid');\n\t\t} else {\n\t\t\tlayoutMasonry(activeTab + 'Grid');\n\t\t}\n\t}\n}", "function init_tab_pages() {\n\t$('#streams-filter-tabs li').click(function() {\n\t\t$('#streams-filter-tabs li').removeClass('active');\n\t\t$(this).addClass('active');\n\n\t\tif ($('#streams-filter-tabs li').index($(this)) == 0) {\n\t\t\tif (!$('#all-streams').hasClass('current')) {\n\t\t\t\t$('#all-streams').addClass('current');\n\t\t\t\t$('#my-streams').removeClass('current');\n\t\t\t\t$('#atme-streams').removeClass('current');\n\t\t\t}\n\t\t}\n\t\tif ($('#streams-filter-tabs li').index($(this)) == 1) {\n\t\t\tif (!$('#my-streams').hasClass('current')) {\n\t\t\t\t$('#all-streams').removeClass('current');\n\t\t\t\t$('#my-streams').addClass('current');\n\t\t\t\t$('#atme-streams').removeClass('current');\n\t\t\t}\n\t\t}\n\t\tif ($('#streams-filter-tabs li').index($(this)) == 2) {\n\t\t\tif (!$('#atme-streams').hasClass('current')) {\n\t\t\t\t$('#all-streams').removeClass('current');\n\t\t\t\t$('#my-streams').removeClass('current');\n\t\t\t\t$('#atme-streams').addClass('current');\n\t\t\t\trender_atme_streams();\n\t\t\t\t//need to be fixed, now renders everytime tab clicked\n\t\t\t}\n\t\t}\n\n\t});\n}", "function initializeTabs() {\n\t\tvar previousArrow = '<span class=\"wd-previousArrow\">' + '❮' + '</span>' ;\n\t\tvar nextArrow = '<span class=\"wd-nextArrow\">' + '❯' + '</span>' ;\n\t\t// add visible class to every item by default\n\t\t$('.wd-tablist').children().addClass('visibleTab');\n\t\t// remove right padding for the last element\n\t\t$('.wd-tablist .wd-tabitem:last').css('padding-right', '0px');\n\n\t\t// remove the tabs that are out of the window\n\t\t// theoretically, overflow:hidden should work, but\n\t\t// setting overflow and span and float seems a bit tricky\n\t\tvar tablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\twhile( tablistright + 30 > $(window).width() ) {\n\t\t\t// remove tabs on the right until it fits in the window\n\t\t\t$('.wd-tablist .visibleTab:last')\n\t\t\t.addClass('hiddenTab').removeClass('visibleTab' )\n\t\t\t.hide();\n\t\t\ttablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t}\n\n\t\t// add arrows\n\t\t$('.wd-tablist .wd-tabitem:first').before( previousArrow ) ;\n\t\t$('.wd-previousArrow').hide();\n\t\t$('.wd-tablist ').after( nextArrow );\n\n\t\t// if the last element is visible, we don't need the nextArrow\n\t\tif ( $('.wd-tablist .wd-tabitem:last').hasClass('visibleTab') ) {\n\t\t\t$('.wd-nextArrow').hide();\n\t\t}\n\n\t\t// next arrow click\n\t\t$('.wd-nextArrow').click(function() {\n\t\t\t// show next tab = first hidden tab after the next visible tab\n\t\t\t$('.wd-tablist .visibleTab:last').next()\n\t\t\t.addClass('visibleTab').removeClass('hiddenTab')\n\t\t\t.show();\n\n\t\t\t// show previous arrow\n\t\t\t$('.wd-previousArrow').show();\n\n\t\t\t// remove visible tabs on the left until it fits the window\n\t\t\tvar tablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t\twhile( tablistright + 30 > $(window).width() ) {\n\t\t\t\t// remove visible tabs on the left until it fits in the window\n\t\t\t\t$('.wd-tablist .visibleTab:first')\n\t\t\t\t.addClass('hiddenTab').removeClass('visibleTab')\n\t\t\t\t.hide();\n\t\t\t\ttablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t\t}\n\n\t\t\t// check if maybe we can display more elements on the right\n\t\t\twhile( ( tablistright + 30 < $(window).width() ) && $('.wd-tabitem:last').hasClass('hiddenTab') ) {\n\t\t\t\t$('.wd-tablist .visibleTab:last').next()\n\t\t\t\t.addClass('visibleTab').removeClass('hiddenTab')\n\t\t\t\t.show();\n\t\t\t\ttablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t\t}\n\t\t\t// remove last tab if we have been to far\n\t\t\tif ( tablistright + 30 > $(window).width() ) {\n\t\t\t\t$('.wd-tablist .visibleTab:last')\n\t\t\t\t.addClass('hiddenTab').removeClass('visibleTab')\n\t\t\t\t.hide();\n\t\t\t}\n\n\t\t\t// remove next arrow if last tab is visible\n\t\t\tif ( $('.wd-tablist .wd-tabitem:last').hasClass('visibleTab') ) {\n\t\t\t\t$('.wd-nextArrow').hide();\n\t\t\t}\n\n\n\t\t}); // nextArrow click\n\n\t\t// previous arrow click\n\t\t$('.wd-previousArrow').click(function() {\n\t\t\t// show previous tab = the one before the first visible tab\n\t\t\t$('.wd-tablist .visibleTab:first').prev()\n\t\t\t.addClass('visibleTab').removeClass('hiddenTab')\n\t\t\t.show();\n\n\t\t\t// show next arrow\n\t\t\t$('.wd-nextArrow').show();\n\n\t\t\t// remove previous arrow if first tab is visible\n\t\t\tif ( $('.wd-tablist .wd-tabitem:first').hasClass('visibleTab') ) {\n\t\t\t\t$('.wd-previousArrow').hide();\n\t\t\t} // if\n\n\t\t\t// remove visible tabs on the right until it fits the window\n\t\t\tvar tablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t\twhile( tablistright + 30 > $(window).width() ) {\n\t\t\t\t// remove tabs on the right until it fits in the window\n\t\t\t\t$('.wd-tablist .visibleTab:last')\n\t\t\t\t.addClass('hiddenTab').removeClass('visibleTab')\n\t\t\t\t.hide();\n\t\t\t\ttablistright = $('.wd-tablist').outerWidth(true) + $('.wd-tablist').offset().left ;\n\t\t\t}\n\t\t}); // click\n\t} // initializeTabs", "function cp_tab_control() {\n\tvar tabs = [];\n\tvar tabContainers = [];\n\tjQuery('ul.tabnavig a').each(function() {\n\t\tif ( window.location.pathname.match(this.pathname) ) {\n\t\t\ttabs.push(this);\n\t\t\ttabContainers.push( jQuery(this.hash).get(0) );\n\t\t}\n\t});\n\n\t//hide all contrainers except execpt for the one from the URL hash or the first container\n\tif ( window.location.hash !== \"\" && window.location.hash.search('block') >= 0 ) {\n\t\tjQuery(tabContainers).hide().filter(window.location.hash).show();\n\t\t//detecting <a> tab using its \"href\" which should always equal the hash\n\t\tjQuery(tabs).filter( function(index) {\n\t\t\treturn ( jQuery(this).attr('href') === window.location.hash );\n\t\t}).addClass('selected');\n\t\tjQuery('html').scrollTop( jQuery(window.location.hash).parent().position().top );\n\t} else {\n\t\tjQuery(tabContainers).hide().filter(':first').show();\n\t\tjQuery(tabs).filter(':first').addClass('selected');\n\t}\n\n\tjQuery(tabs).click(function() {\n\t\t// hide all tabs\n\t\tjQuery(tabContainers).hide().filter(this.hash).fadeIn(100);\n\t\tjQuery(tabs).removeClass('selected');\n\t\tjQuery(this).addClass('selected');\n\t\treturn false;\n\t});\n}", "function tab() {\n\n var $wrap = $(\"#numWrap\"), $strip = $(\"#strip\"),\n $leftArrow = $(\".wrapper > .arrows\").first(),\n wrapWidth = $wrap.width(),\n margin = 10, left = 0; //declare variables for divs in which tabs are placed\n $strip.on(\"click\", \".numberItem\", function () { select($(this)); });\n $(\".wrapper\").on(\"click\", \"a.arrow\", function () { //wrapper is div with left and right arrows alongwith tabs\n var stripPos = $strip.position(); //strip is innerdiv of wrapper\n var height = $(\"#strip\").height(); //find height of strip div \n if (this.id == \"lft\") { //if left arrow is clicked\n if ($('#hdnCount').val() == 1) { //hdncount is a variable which is increment on right arrow click and decrement on left arrow click\n // //alert(height1);\n $('#lft').css(\"display\", \"none\"); //hide left arrow if data is not avaible on left side\n $('#rgt').css(\"display\", \"block\"); //hide right arrow if data is not avaible on right side\n }\n else {\n // //alert('jj');\n $('#lft').css(\"display\", \"block\"); //if hdncount is larger than one\n\n }\n if ($('#hdnCount').val() < 0) {\n $('#hdnCount').val(0);\n }\n var con;\n height = (height / 38); //becoz one scroll height is 38 so find the no. of scroll\n // //alert(height);\n if (height > 1 && height < 2) {\n con = -((wrapWidth / 2) * 2); //find the scrolling of strip\n }\n if (height >= 2) {\n con = -((wrapWidth / 2) * height); //wrapwidth is wrapper width\n } else {\n con = -((wrapWidth / 2));\n }\n\n var mov = stripPos.left + wrapWidth;\n if (((stripPos.left + wrapWidth) > 0 && (stripPos.left + wrapWidth) < 1)) {\n mov = -1;\n }\n var condition = ((wrapWidth * 2) / height);\n if (condition < 887 && condition > 885) {\n // //alert('gh');\n condition = 888;\n }\n // //alert('condition=' + condition);\n if (con <= (stripPos.left + wrapWidth) && (stripPos.left < condition)) { //condition for stopping left click if no data is available on left side\n if ($strip.width() - $wrap.width() > 0) {\n $strip.css({ \"left\": (stripPos.left + (wrapWidth / 2)) });\n }\n }\n // }\n $('#hdnCount').val(parseInt($('#hdnCount').val()) - 1); //decrement of hdncount on click on left arrow \n } else {\n var height1 = $(\"#strip\").height();\n height1 = (height1 / 38);\n //alert('height1=' + height1);\n var con;\n height = (height / 38);\n if (height > 1 && height < 2) {\n con = -((wrapWidth / 2) * 2);\n\n }\n if (height > 2) {\n ////alert('GH');\n con = ((wrapWidth / 2) * height);\n } else {\n con = ((wrapWidth / 2));\n }\n\n if ((parseInt(con + left) >= parseInt(wrapWidth / 2))) {\n if (stripPos.left == -425.5) {\n stripPos.left = -427;\n }\n ////alert('height1=' + height);\n //alert('hdncount=' + $('#hdnCount').val());\n if (height1 == 1 || height == 1) {\n // //alert('1');\n\n $('#rgt').css(\"display\", \"none\");\n $('#lft').css(\"display\", \"block\");\n }\n else {\n if (stripPos.left >= ((-425 * height) - 1)) {\n $strip.css({ \"left\": parseFloat(stripPos.left) - parseFloat(wrapWidth / 2) });\n height1 = $(\"#strip\").height() - 38;\n height1 = (height1 / 38);\n $('#rgt').css(\"display\", \"block\");\n if (height1 == 1 && $('#hdnCount').val() == 0) {\n //alert('height1=' + height1);\n //alert('hdncount=' + $('#hdnCount').val());\n $('#rgt').css(\"display\", \"none\");\n $('#lft').css(\"display\", \"block\");\n // //alert('2');\n // //alert($('#hdnCount').val());\n }\n else {\n $('#rgt').css(\"display\", \"block\");\n // //alert('3');\n }\n }\n }\n }\n\n $('#hdnCount').val(parseInt($('#hdnCount').val()) + 1);\n }\n });\n $('#strip ul li a').hover(function () { //on hover of tab store its left and top position in hiddenvariable\n var stripPos = $strip.position();\n var pos = $(this).position();\n $(this).css({ \"left\": pos.left });\n $(this).css({ \"top\": pos.top });\n // //alert(pos.left);\n $('#hdnleft').val(pos.left);\n $('#hdntop').val(pos.top);\n $('#hdntab').val(this.text);\n $('#hdnwidth').val(stripPos.left);\n\n });\n\n var arr = jQuery.makeArray($('#strip ul li a'));\n\n var flag = 0;\n var width = 0;\n $('#cbdb-menu_id').find('a').each(function () {\n if ($('#hdntab').val() != null) {\n if (this.text == $('#hdntab').val()) {\n\n flag = 1;\n }\n }\n if (flag != 1) {\n //width = $(this).innerWidth() + width;\n width = ($(this).width() + 32) + width;\n }\n if ($('#hdntab').val() != null) {\n if (this.text == $('#hdntab').val()) {\n }\n var height1 = $(\"#strip\").height();\n height1 = (height1 / 38);\n // //alert(height1);\n if (height1 != 1 && $('#hdnCount').val() == 0) {\n ////alert('12');\n $('#lft').css(\"display\", \"none\");\n ////alert('1');\n }\n else if (height1 == 1 && $('#hdnCount').val() > 0) {\n $('#rgt').css(\"display\", \"block\");\n }\n var left = $('#hdnleft').val();\n var top = $('#hdntop').val();\n var left1 = $('#hdnwidth').val();\n // var r = $('#<%= hdnIndex.ClientID %>').val();\n if (parseInt(left1) == 0 && $('#hdnCount').val() == 0) { //if tab's position in first scroll\n //$strip.css({ \"margin-left\": (-756 + left) });\n var num = -(parseFloat(width));\n ////alert('left=0');\n // //alert('width=' + width);\n $strip.css({ \"margin-left\": left1 });\n $(this).css({ \"left\": num })\n $(this).css({ \"top\": top })\n // //alert('case1');\n //alert('1');\n\n }\n else if (parseInt(left1) == 0 && $('#hdnCount').val() > 0) {//if in not in first scroll\n // //alert('tt');\n var $wrap = $(\"#numWrap\");\n var $p = $(\"#Strip\");\n var wrapWidth = $p.width() - $wrap.width();\n var p = (wrapWidth / 2);\n p = (parseFloat(p)) + \"px\";\n if ($('#hdnCount').val() > 2) { //second scroll\n p = parseFloat(p) * 3;\n p = (parseFloat(p)) + \"px\";\n // alert('2');\n\n }\n else if ($('#hdnCount').val() > 1) { //first scroll\n p = (wrapWidth / 2);\n p = parseFloat(p) * 2;\n p = (parseFloat(p)) + \"px\";\n //alert('3');\n\n }\n else {\n p = 0;\n //alert(p);\n }\n // //alert('p=' + p);\n // alert(p);\n // alert($('#hdnCount').val());\n $strip.css({ \"margin-left\": p }); //finally apply css for margin-left\n $(this).css({ \"left\": width })\n $(this).css({ \"top\": top })\n }\n\n else {\n\n var num = -(parseFloat(left1) + parseFloat(width));\n // var num = -(width);\n if (num != NaN)\n if ($('#hdnCount').val() > 2 && left1 > -(width / 2)) {\n left1 = left1 * 3;\n //alert('4');\n //alert('left1=' + left1);\n //alert('(width / 2)' + (width / 2));\n\n }\n else if ($('#hdnCount').val() > 1 && left1 > -(width / 2)) {\n left1 = left1 * 2;\n ////alert('5');\n\n\n }\n\n\n if ($('#hdnCount').val() < 1 && left1 > (width / 2)) {\n left1 = 0;\n ////alert('6');\n\n\n ////alert('case7');\n }\n else if ($('#hdnCount').val() < 2 && left1 > (width / 2)) {\n left1 = -parseFloat(left1);\n ////alert('case8');\n // //alert('7');\n\n }\n else if ($('#hdnCount').val() < 3 && left1 > (width / 2)) {\n left1 = -parseFloat(left1);\n ////alert('case9');\n ////alert('8');\n\n }\n else if ($('#hdnCount').val() > 2 && left1 < -(width / 2)) {\n left1 = left1;\n ////alert('case10');\n ////alert('9');\n\n }\n\n var p = left1 + \"px\";\n $strip.css({ \"margin-left\": p });\n $(this).css({ \"left\": width })\n $(this).css({ \"top\": top })\n }\n }\n });\n\n}", "function displayState(tab) {\n $(\".grid\").empty();\n for (let i = 0; i < tab.length; i++) {\n for (let j = 0; j < tab[i].length; j++) {\n const elem = tab[i][j];\n if (elem) {\n const item = $(`<div data-i=\"${i}\" data-j=\"${j}\" class=\"item\" id=\"${elem}\">${elem}</div>`);\n $(\".grid\").append(item);\n } else {\n // if (leftMove == 1) {\n // $(\".grid\").append(`<div class=\"vide\" id = \"caseVide\"\"><img src=\"images/davidou.png\" alt=\"car\" id=\"car\"></div>`);\n // leftMove = 0\n // } else if (rightMove == 1) {\n // $(\".grid\").append(`<div class=\"vide\" id = \"caseVide\"\"><img src=\"images/davidou.png\" alt=\"car\" id=\"car\"></div>`);\n // rightMove = 0\n // } else {\n $(\".grid\").append(`<div class=\"vide\" id = \"caseVide\"\"><img src=\"images/davidou.png\" alt=\"DAVIDOU\" id=\"DAVID\"></div>`);\n\n // }\n }\n\n }\n }\n}", "function tabs(){\n\t\tvar ul = document.createElement(\"ul\");\n\n\t\t//setting materialize's classes to 'ul' tag\n\t\tul.setAttribute(\"class\", \"tabs tabs-transparent\");\n\n\t\t//for each element inside 'clothingItems' do...\n\t\tclothingItems.forEach((item)=>{\n\n\t\t\t//creating 'a' and 'li' tags\n\t\t\tvar li = document.createElement(\"li\");\n\t\t\tvar a = document.createElement(\"a\");\n\n\t\t\t//setting 'tab' class(materialize) and \"href\", to 'li' and 'a' elements \n\t\t\tli.setAttribute(\"class\", \"tab\");\n\t\t\ta.setAttribute(\"href\", \"#\"+item.toLowerCase());\n\n\t\t\t//defining which is parent element and which is child element\n\t\t\ta.innerHTML = item;\n\t\t\tli.appendChild(a);\n\t\t\tul.appendChild(li);\n\t\t\tproductTab.appendChild(ul);\n\t\t});\n\t}", "function loadTabs() {\n\t\tvar htmlToAppend = '';\n\t\thtmlToAppend += '<ul class=\"nav nav-tabs\">';\n\t\t\n\t\tvar tabsMade = 0;\n\t\tfor(var i = 0; i <tuneJSON.tracks.length; i++) {//create the nav tabs for each nonempty track\n\t\t\tif(typeof tuneJSON.tracks[i].instrument !== 'undefined') {\n\t\t\t\tif(tabsMade === 0) {//if first tab add an active class to it\n\t\t\t\t\ttabsMade++;\n\t\t\t\t\thtmlToAppend +='<li class=\"active\"><a href=\"#track' + i +\n\t\t\t\t\t '\" data-toggle=\"tab\"><span class=\"instrument-name\">' + midiHelper.getInstrumentName(tuneJSON.tracks[i].instrument) + \n\t\t\t\t\t '</span></a></li>';\n\t\t\t\t} else {\n\t\t\t\t\thtmlToAppend += '<li role=\"presentation\"><a href=\"#track' + i + '\" role=\"tab\" data-toggle=\"tab\"><span class=\"instrument-name\">' +\n\t\t\t\t\tmidiHelper.getInstrumentName(tuneJSON.tracks[i].instrument) + \n\t\t\t\t\t'</span><button class=\"remove-tab-button\" id=\"remove-tab' + i + '\"><span class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></span></button></a></li>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\thtmlToAppend += '</ul><div class=\"tab-content\">';\n\t\t//now add the tab panels\n\t\t\n\t\ttabsMade = 0;\n\n\t\tfor(var i = 0; i <tuneJSON.tracks.length; i++) {//create the tab pane for each nonempty track\n\t\t\tif(typeof tuneJSON.tracks[i].instrument !== 'undefined') {\n\t\t\t\tif(tabsMade === 0) {\n\t\t\t\t\thtmlToAppend += '<div class=\"tab-pane active\" id=\"track' + i +'\"></div>';\n\t\t\t\t\ttabsMade++;\n\t\t\t\t} else {\n\t\t\t\t\thtmlToAppend+= '<div class=\"tab-pane\" id=\"track' + i +'\"></div>';\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\thtmlToAppend += '</div>';\n\t\t$('.canvas').append(htmlToAppend);\n\n\t\t$('.remove-tab-button').click(function() {//add remove event to delete button\n\t\t\tdeleteInstrument(parseInt($(this).attr('id').substring(10), 10));//get index of track\n\t\t});\n\t\t\n\t}", "function tabSystem() {\n //define the variables\n const $wrapper = $('.tab-container'),\n $allTabs = $('.tab-inhalt > div'),\n $tabMenu = $('.tab-auswahl li')\n\n //hide tabs-content that are not the first tab\n $allTabs.not(':first-of-type').hide()\n\n //for every tab, assign a data attribute to the li (itterate)\n $tabMenu.each(function(i) {\n $(this).attr('data-tab', 'tab' + i)\n })\n\n //now do the same for the tabs themselves (the content)\n $allTabs.each(function(i) {\n $(this).attr('data-tab', 'tab' + i)\n })\n\n //when we click one of the tabs:\n $tabMenu.on('click', function() {\n const dataTab = $(this).data('tab'),\n $getWrapper = $(this).closest($wrapper)\n\n //we remove the active class of all tabs, add it to the one we clicked\n $getWrapper.find($tabMenu).removeClass('active')\n $(this).addClass('active')\n\n //we hide all the tabs\n $getWrapper.find($allTabs).hide()\n // show the tab which was clicked using the data attribute of the clicked menu\n $getWrapper.find($allTabs).filter(`[data-tab=\"${dataTab}\"]`).show()\n })\n\n }", "function set_sizes() {\n tab_width = $nav_tab.outerWidth();\n list_width = $nav_list.outerWidth();\n tabs_displayed = list_width / tab_width;\n //recalculate height of the currently displayed slide\n var this_sectionHeight = $('.slick-active').outerHeight();\n $sections.css('height', this_sectionHeight + 'px');\n //use tab width and tab index to set horizontal spacing\n $nav_tab.each(function() {\n var index = $(this).index();\n var left_pos = (tab_width * (index - pos_counter)) + 'px';\n $(this).css('left', left_pos);\n });\n}", "function listTabs(filter) {\n let hidden = false;\n if (typeof filter === \"string\") {\n if (filter.startsWith(\"*\")) {\n hidden = true;\n filter = filter.replace(\"*\", \"\");\n }\n } else {\n filter = \"\";\n }\n browser.tabs.query({ currentWindow: true }).then((tabs) => {\n let tabsList = document.getElementById(\"tabs-list\");\n let currentTabs = document.createDocumentFragment();\n let counter = Math.ceil(tabs.length / 9);\n tabsList.textContent = \"\";\n let matching = 0;\n const tabNumber = {};\n for (const tab of tabs) {\n tabNumber[tab.id] = counter;\n counter++;\n }\n let filteredTabs;\n if (filter) {\n const fuzzySearch = fuzzysort.go(filter, tabs, { key: \"title\" });\n filteredTabs = fuzzySearch.map((o) => o.obj.id);\n tabs.sort(function (a, b) {\n try {\n return (\n fuzzySearch.findIndex((t) => t.obj.id == a.id) -\n fuzzySearch.findIndex((t) => t.obj.id == b.id)\n );\n } catch (e) {\n return true;\n }\n });\n } else {\n filteredTabs = tabs.map((t) => t.id);\n }\n\n for (const tab of tabs) {\n if (filteredTabs.includes(tab.id) && (hidden || !tab.hidden)) {\n matching = matching + 1;\n let tabHolder = document.createElement(\"div\");\n tabHolder.classList.add(\"tab-holder\");\n if (tab.active) {\n tabHolder.classList.add(\"active-tab\");\n }\n if (tab.attention) {\n tabHolder.classList.add(\"active-tab\");\n }\n let tabImg = document.createElement(\"img\");\n tabImg.classList.add(\"favicon\");\n if (tab.favIconUrl) {\n tabImg.setAttribute(\"src\", tab.favIconUrl);\n } else {\n tabImg.setAttribute(\"src\", \"icons/defaultFavicon.svg\");\n }\n tabHolder.appendChild(tabImg);\n\n let tabCode = document.createElement(\"span\");\n tabCode.textContent = tabNumber[tab.id];\n tabHolder.appendChild(tabCode);\n\n let tabLink = document.createElement(\"a\");\n tabLink.textContent = tab.title || tab.id;\n tabLink.setAttribute(\"href\", tab.id);\n tabLink.classList.add(\"switch-tabs\");\n tabHolder.appendChild(tabLink);\n\n let closeImg = document.createElement(\"img\");\n closeImg.classList.add(\"closeButton\");\n closeImg.setAttribute(\"src\", \"icons/close-icon.svg\");\n closeImg.onclick = function (event) {\n const tabId = +event.target.previousSibling.getAttribute(\"href\");\n browser.tabs.remove(tabId);\n };\n tabHolder.appendChild(closeImg);\n\n currentTabs.appendChild(tabHolder);\n }\n }\n\n tabsList.appendChild(currentTabs);\n if (matching == 1) {\n tabsList.getElementsByTagName(\"a\")[0].click();\n }\n });\n}", "function onLoadSortSummary(){\n var view = tabsFrame.newView;\n var numberOfTblgrps = Number(tabsFrame.tablegroupsRestriction);\n var viewType = tabsFrame.typeRestriction;\n var index = view.tableGroups.length - tabsFrame.selectedTableGroup - 1;\n \n // if this is a summary view, hide sort references and display grouping references\n if (viewType == 'summaryReports') {\n $('sort').style.display = \"none\";\n $('group1').style.display = \"\";\n $('group2').style.display = \"\";\n $('group3').style.display = \"\";\n $('sortOrder_title').innerHTML = getMessage('setGrouping');\n }\n else {\n \n // otherwise, show sort references\n $('sort').style.display = \"\";\n $('group1').style.display = \"none\";\n $('group2').style.display = \"none\";\n $('group3').style.display = \"none\";\n $('sortOrder_title').innerHTML = getMessage('selectSortOrder');\n }\n \n // create the sort summary table, filling in the field properties and creating the sort buttons\n createSortSummaryTable();\n \n // create an array for displaying/tracking the order of the sorts and stores this array in the summary table\n createSortSelectionArray();\n \n // get the array of sort objects\n var sortFldsArray = view.tableGroups[index].sortFields;\n \n // if sorts have been defined,\n if (sortFldsArray != undefined) {\n var summaryTable = $('sortOrderSummary');\n tBody = summaryTable.tBodies[0];\n var numOfRows = tBody.rows.length;\n \n // for each sort specified\n for (k = 0; k < sortFldsArray.length; k++) {\n \n // loop through the summary table\n for (var j = 1; j < numOfRows; j++) {\n var fieldNameCell = summaryTable.rows[j].cells[0];\n var tableNameCell = summaryTable.rows[j].cells[5];\n var setButtonCell = summaryTable.rows[j].cells[8];\n \n // if there is a match, display the order and hide the \"Sort\" button\n if ((sortFldsArray[k].field_name == fieldNameCell.innerHTML) && (sortFldsArray[k].table_name == tableNameCell.innerHTML)) {\n var rowID = setButtonCell.parentNode.id;\n setSort(\"\", rowID);\n }\n }\n }\n \n }\n\t\n\t/*\n\tif ( pattern.match(/highlight-restriction/gi) && (sortFldsArray == undefined) && ((index == 0) || (index == 2)) ){\n\t\tsetPKeysAsSortDefaults();\n\t}\n\t*/\t\n}", "_makeTabsFromPfTab() {\n const ul = this.querySelector('ul');\n if (this.children && this.children.length) {\n const pfTabs = [].slice\n .call(this.children)\n .filter(node => node.nodeName === 'PF-TAB');\n [].forEach.call(pfTabs, (pfTab, idx) => {\n const tab = this._makeTab(pfTab);\n ul.appendChild(tab);\n this.tabMap.set(tab, pfTab);\n this.panelMap.set(pfTab, tab);\n\n if (idx === 0) {\n this._makeActive(tab);\n }\n else {\n pfTab.style.display = 'none';\n }\n });\n }\n }", "function updateTabOrder(){var selectedItem=ctrl.tabs[ctrl.selectedIndex],focusItem=ctrl.tabs[ctrl.focusIndex];ctrl.tabs=ctrl.tabs.sort(function(a,b){return a.index-b.index;});ctrl.selectedIndex=ctrl.tabs.indexOf(selectedItem);ctrl.focusIndex=ctrl.tabs.indexOf(focusItem);}", "phaseTabs() {\n var allPhasesTab = (\n <li key={'all'} className={'tab ' + this.isViewingPhase('all')}>\n <a id={'all'} onClick={this.setPhase}>All Games</a>\n </li>\n );\n var tabList = [allPhasesTab];\n for(var phase in this.props.divisions) {\n if(phase != 'noPhase') {\n var oneTab = (\n <li key={phase} className={'tab ' + this.isViewingPhase(phase)}>\n <a id={phase} onClick={this.setPhase}>{phase}</a>\n </li>\n );\n tabList.push(oneTab);\n }\n }\n var skinny = this.state.overflowTabs ? '' : ' skinny-tabs';\n return (\n <div className=\"nav-content\">\n <ul className={'tabs tabs-transparent' + skinny} id=\"phase-tabs\">\n {tabList}\n </ul>\n </div>\n );\n }", "function toggleTabs() {\n tab.forEach(function (x) {\n x.classList.toggle('tab-selected');\n });\n table.forEach(function (y) {\n y.classList.toggle('hidden');\n });\n populateFooter();\n}", "function onClickTab(tab) {\n if (d3.select(\"#tab_\"+tab).classed(\"active\")) { return; }\n active_tab = tab;\n // hide all tab_content\n d3.selectAll(\".tab_content\").style(\"display\", \"none\");\n // show selected tab_content\n d3.select(\"#div_\"+tab).style(\"display\", \"unset\");\n // mark tab as selected\n d3.selectAll(\".tab\").classed(\"active\", false);\n d3.select(\"#tab_\"+tab).classed(\"active\", true);\n drawgraphs();\n}", "function renderAll(){\n\n\t\t\tvar html = '';\n\tfor(i=0; i<found.length; i++) {\n\t\tif(i>0 && found[i].windowId != found[i-1].windowId) html += '<li class=\"separator\"></li>';\n\t\thtml += renderTab(found[i],i);\n\t}\t\n\n\n\t$('#tabs2').html(html);\n\t$('#tabs').quicksand( $('#tabs2 li'),{ attribute: 'id' } );\n\n\tvar dowith = 'All';\n if(found.length <all.length) dowith = 'Selected';\n\n html \t= found.length+' tabs found:'\n\t\t+' <a href=\"#\" accesskey=\"o\" onclick=\"opentab(0);\" onmouseover=\"this.focus();\"><u>O</u>pen First</a>';\n\n\tif(found.length < all.length && found.length>1)\n\t\thtml += ' <a href=\"#\" accesskey=\"g\" onclick=\"group(found);\" onmouseover=\"this.focus();\"><u>G</u>roup</a>'\n\t\n\t\thtml +=\t' <a href=\"#\" accesskey=\"w\" onclick=\"chrome.extension.getBackgroundPage().moveToNewWindow(found);\" onmouseover=\"this.focus();\">'+dowith+' to new <u>W</u>indow</a>'\n\t\t+' <a href=\"#\" accesskey=\"b\" onclick=\"bookmark();\" onmouseover=\"this.focus();\"><u>B</u>ookmark '+dowith+'</a>'\n\t\t+' <a href=\"#\" accesskey=\"c\" onclick=\"closefound();\" onmouseover=\"this.focus();\"><u>C</u>lose '+dowith+'</a>';\n\ndocument.getElementById('results').innerHTML = html;\n\n}", "function setUpTabs() {\n var divs = document.getElementsByTagName('div');\n var tabCount = 0;\n for (var i = 0; i < divs.length; i++) {\n if (divs[i].className == 'name') {\n tabs.addTab(divs[i]);\n } else if (divs[i].className == 'content') {\n tabs.addPanel(divs[i]);\n divs[i].style.display = 'none';\n \n }\n }\n tabs.showPanel(0);\n zoomFactor=.9;\n document.getElementById('img1').src=servername+tmapname+\".png\";\n document.getElementById('img2').src=servername+tmapname+\"fed.png\";\n makeDraggable('img1');\n tmapObject=\"img1\";\n setFull('layer2');\n setFull('layer1');\n}", "_makeTabsFromPfTab () {\n let ul = this.querySelector('ul');\n let pfTabs = this.querySelectorAll('pf-tab');\n [].forEach.call(pfTabs, function (pfTab, idx) {\n let tab = this._makeTab(pfTab);\n ul.appendChild(tab);\n this.tabMap.set(tab, pfTab);\n this.panelMap.set(pfTab, tab);\n\n if (idx === 0) {\n this._makeActive(tab);\n } else {\n pfTab.style.display = 'none';\n }\n }.bind(this));\n }", "function create(){\n for (var i = 0; i < pages; i++){\n var $newtab = $('<div id=\"tab-' + toWords(i+1) + '\" class=\"tab\">' + tabNames[i] + '<div id=\"right-tab\">--</div>' + '</div>');\n $newtab.css(\"height\", tabHeight+\"%\");\n //$newtab.css(\"zIndex\", pages-(i-1));\n $( \"div#tabs\" ).append( $newtab);\n\n var $newsection = $('<div id=\"section-' + toWords(i+1) + '\" class=\"page page-' + toWords(i+1) + ' section-' + toWords(i+1) + ' ' + toWords(i+1) + '\">' + htmltext[i] + '</div>');\n if (i == 0){\n $newsection.css(\"display\", \"none\");\n }else{\n $newsection.css(\"display\", \"none\");\n }\n $( \"div#sections\" ).append( $newsection);\n }\n }", "function setTabAcs(){\n\t$(\".tab-titles\").siblings().wrapAll(\"<div class='tab-content'></div>\");\n\tul = $('.tab-content');\n\tul.children().each(function(i,li){ul.prepend(li)})\n\t\n\t$(document).find(\".tab-titles li\").each(function(i,value){\n\t\tvar elem = $(this).find(\"a\").clone();\n\t\tvar elem_id = $(this).find(\"a\").attr('href');\n\t\telem.addClass(\"ac-panel\");\n\t\t$(this).find(\"a\").attr(\"id\" , elem_id.replace('#', '') + \"_alink\");\n\t\telem.attr(\"id\" , elem_id.replace('#', '') + \"_plink\");\n\t\tsetAccordionPanel(elem, elem_id);\n\t});\n\t/* Set Default active states */\n\t$(\".tab-content>div\").addClass(\"tab-pane\");\n\t$(\".tab-titles\").find(\"li:nth-child(1)\").addClass(\"active\");\n\t$(\".tab-content\").find(\".ac-panel:nth-child(1)\").addClass(\"active\");\n\t$(\".tab-content\").find(\".tab-pane:first\").addClass(\"active\");\n\t/* Show Content */\n\t$(\"#contentBox\").fadeIn(\"slow\");\n}", "function addRankingsToPage() {\n // creates a row for each team\n for (let team_id in teams) { addRankingRow(team_id); }\n addCategoryToRankings(hatchTest);\n addCategoryToRankings(cargoTest);\n addCategoryToRankings(cargoHatchTest);\n addCategoryToRankings(defenseTest);\n // makes each team clickable to send them to their respective team pages\n for (let team_id in teams) {\n // ranking team pressed switches page\n $(\".ranking-team-\" + teams[team_id]).click(function() {\n switchPages(\"team\", teams[team_id], undefined, 1);\n });\n }\n}", "function sort($p) {\n /* create ($rows) a variable to hold the group of rows\n ** to be displayed on the selected page,\n ** ($s) the start point .. the first row in each page, Do The Math\n */\n var $rows = $th, $s = (($n * $p) - $n);\n for ($i = $s; $i < ($s + $n) && $i < $tr.length; $i++)\n $rows += $tr[$i];\n\n // now the table has a processed group of rows ..\n $table.innerHTML = $rows;\n // create the pagination buttons\n document.getElementById(\"buttons\").innerHTML = pageButtons($pageCount, $p);\n // CSS Stuff\n document.getElementById(\"id\" + $p).setAttribute(\"class\", \"active\");\n}", "function initSort(){\n\t\t\tif($window.width()>670){\n\t\t\t\tvar $container=jQuery('.tile.container, .icon.container');\n\t\t\t\tif($container.length>0){\t//if there are containers on the page\n\t\t\t\t\t$container.each(function(){\t\t//loop through the containers\n\t\t\t\t\t\tvar $singleContainer=jQuery(this); //create a jquery object for the container\n\t\t\t\t\t\tvar $items=$singleContainer.find('.tile, .icon'); //find all the tiles or icons in the container\n\t\t\t\t\t\tif($items.length>0){\t//if there are tiles or icons\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * This next line is important and necessary because it allows for the sorted row \n\t\t\t\t\t\t\t * to size for the entire container width. Otherwise the container can only get smaller\n\t\t\t\t\t\t\t * by adding margins.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t$singleContainer.css({'position':'relative','width':'100%'});\n\t\t\t\t\t\t\t//get the container data and set up tracking variables\n\t\t\t\t\t\t\t//all css values have to be parsed to remove \"px\", etc. from the values\n\t\t\t\t\t\t\tvar singleContainerWidth=Number($singleContainer.css('width').replace(/[^0-9\\.-]/g,\"\"));\n\t\t\t\t\t\t\tvar runningTop=Number($singleContainer.css('top').replace(/[^0-9\\.-]/g,\"\"));\n\t\t\t\t\t\t\tvar singleContainerLeft=Number($singleContainer.css('left').replace(/[^0-9\\.-]/g,\"\"));\n\t\t\t\t\t\t\t//runnning left and running top are the variables used to set the tile position\n\t\t\t\t\t\t\t//so initially they are set to the container upper left values\n\t\t\t\t\t\t\tvar runningLeft=singleContainerLeft;\n\t\t\t\t\t\t\t//have to keep track of the max values so the container can be sized later (maxWidthRow)\n\t\t\t\t\t\t\t\t//and so that each row can be placed below the previous row (maxHeightRow)\n\t\t\t\t\t\t\tvar maxHeightRow=0;\n\t\t\t\t\t\t\tvar maxWidthRow=0;\n\t\t\t\t\t\t\t$items.each(function(){ //loop through each tile/icon\n\t\t\t\t\t\t\t\tvar $item=jQuery(this); //get each as a jquery object\n\t\t\t\t\t\t\t\t//if the current tile to be placed will exceed container width \n\t\t\t\t\t\t\t\t\t//this operation has to be performed before the tile is placed\n\t\t\t\t\t\t\t\tif(runningLeft+$item.totalWidth()>singleContainerWidth){\n\t\t\t\t\t\t\t\t\trunningTop+=maxHeightRow;\t//move the tile down a row\n\t\t\t\t\t\t\t\t\trunningLeft=singleContainerLeft;\t//move the tile to the first position in the row\n\t\t\t\t\t\t\t\t\tmaxHeightRow=0; //set the max height of the row back to zero\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//if the height of the current tile is greater than all the other tiles in it's row\n\t\t\t\t\t\t\t\t//this must be done after the calculation for surpassing the end of the row\n\t\t\t\t\t\t\t\t\t//so that max height isn't updated based on a tile not placed in that row (in case the \n\t\t\t\t\t\t\t\t//tile isn't placed in that row\n\t\t\t\t\t\t\t\tif($item.totalHeight()>maxHeightRow){\n\t\t\t\t\t\t\t\t\t\tmaxHeightRow=$item.totalHeight(); //update this tile height to the max row Height\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//place the tile/icon\n\t\t\t\t\t\t\t\t$item.css({\n\t\t\t\t\t\t\t\t\tposition:'absolute',\n\t\t\t\t\t\t\t\t\t\ttop:runningTop+\"px\",\n\t\t\t\t\t\t\t\t\tleft:runningLeft+\"px\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t//increment the current left position by the values for the current tile/icon\n\t\t\t\t\t\t\t\t//this has to be done after the tile is placed\n\t\t\t\t\t\t\t\trunningLeft+=$item.totalWidth();\n\t\t\t\t\t\t\t\t//if the current tile is placed further down a row than any other row\n\t\t\t\t\t\t\t\t//this has to be done after running left is updated.\n\t\t\t\t\t\t\t\tif(runningLeft>maxWidthRow){\n\t\t\t\t\t\t\t\t\tmaxWidthRow=runningLeft; //update the max width of the row\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t//finally add the last row height to the current top value\n\t\t\t\t\t\t\t//this is used for setting the container height\n\t\t\t\t\t\t\trunningTop+=maxHeightRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//size the container based on the width and height kept track of before\n\t\t\t\t\t\t$singleContainer.css({\n\t\t\t\t\t\t\t'width':maxWidthRow,\n\t\t\t\t\t\t\t'height':runningTop\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}" ]
[ "0.6578337", "0.631205", "0.6259668", "0.6255593", "0.62150013", "0.619272", "0.6178225", "0.6119733", "0.6092266", "0.60863256", "0.60732603", "0.60263723", "0.60049015", "0.59749115", "0.596604", "0.5961076", "0.5957652", "0.5955172", "0.5948951", "0.59252095", "0.59230083", "0.59017944", "0.58987164", "0.5868354", "0.58543354", "0.58504", "0.5835673", "0.58319974", "0.5824478", "0.5819747" ]
0.6483174
1
Calculates the hypotenuse given sideA and sideB
function hypotenuse(sideA, sideB) { if (isNaN(sideA) || isNaN(sideB)) { return NaN; } return Math.sqrt(sideA**2 + sideB**2); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function lengthOfHypotenuse(side1, side2){\n \n //hypotenuse squared = side1 squared + side2 squared\n var hypotenuse = Math.sqrt((side1 * side1) + (side2 * side2));\n return hypotenuse;\n}", "function hypotenuse(a, b) {\n return Math.sqrt(a * a + b * b);\n}", "function hypoteneuse(a, b){\n return Math.sqrt(a**2 + Math.pow(b, 2));\n}", "function lengthOfSide(hypotenuse, side) {\n //hypotenuse squared = side1 squared + side2 squared\n var side2 = Math.sqrt(((hypotenuse * hypotenuse) - (side * side)));\n return side2;\n}", "function calculateSide(sideA, sideB) {\n const sideC = Math.sqrt(Math.pow(sideA, 2) + Math.pow(sideB, 2));\n return sideC;\n}", "function calculateSide(sideA, sideB)\n{\n // returns sqrt\nreturn Math.sqrt(sideA * sideA + SideB * SideB)\n}", "function getHypoteneuse(x, y) {\n return Math.sqrt(x * x + y * y);\n }", "function hypot(a, b) {\n return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));\n }", "function hypotenuse(x1, y1, x2, y2) {\n\tvar xSquare = Math.pow(x1 - x2, 2);\n\tvar ySquare = Math.pow(y1 - y2, 2);\n\treturn Math.sqrt(xSquare + ySquare);\n}", "function calcHypotenuse (b,h) {\n var hypotenuse = Math.sqrt((b*b) + (h * h));\n return hypotenuse;\n}", "function hypotenuse(a, b) {\n var r = 0;\n if (Math.abs(a) > Math.abs(b)) {\n r = b / a;\n return Math.abs(a) * Math.sqrt(1 + r * r);\n }\n if (b !== 0) {\n r = a / b;\n return Math.abs(b) * Math.sqrt(1 + r * r);\n }\n return 0;\n}", "function hypo(a, b) {\n function square(x) {\n return x * x;\n }\n return Math.sqrt(square(a)+ square(b))\n}", "function calculateHypotenuse(a,b){\n try{\n if(a < 1 || b < 1) throw 'too low';\n if(typeof a !== 'number' || typeof b !== 'number') throw 'not a number';\n if(isNaN(a) || isNaN(b)) throw 'not a number';\n var c = Math.sqrt((a * a) + (b * b));\n return Math.round(c * 1000) / 1000;\n }\n catch(err) {\n return error;\n };\n}", "function pyth(xA,yA,xB,yB) {\r\n\t\tvar a = Math.abs(xB - xA);\r\n\t\tvar b = Math.abs(yB - yA);\r\n\t\tvar c = Math.sqrt(a**2 + b**2);\r\n\t\treturn c;\r\n\t}", "function hypSquare(base, perpendicular){\n var baseSquare = square(base);\n var perpendicularSquare = square(perpendicular);\n return baseSquare + perpendicularSquare;\n}", "function calculateHypo(b, p){\n \n var bSquare = Math.pow(b, 2);\n var pSquare = Math.pow(p, 2);\n\n var prod = bSquare + pSquare;\n var hypo = Math.sqrt(prod);\n \ndocument.write(\"<br/>\" + \"This the result of a hypotenuse: \" + \" \" + \n hypo + \"<br /> <br />\");\n\n}", "function calculateHypothenuse(leg1, leg2) {\n const h = Math.sqrt(leg1 ** 2 + leg2 ** 2);\n}", "function hypo(a, b) {\n var y = 45;\n function square(x) {\n console.log(y);\n return x * x;\n }\n return Math.sqrt(square(a)+ square(b))\n}", "function pythagoreanTheorem(a, b) {\n var pT = Math.sqrt(a*a + b*b);\n return pT;\n}", "function hipotenusa(lado1, lado2) {\n return Math.sqrt(lado1*lado1 + lado2*lado2)\n}", "function hypot() {\n var i,\n n,\n t = new this(0);\n\n external = false;\n\n for (i = 0; i < arguments.length;) {\n n = new this(arguments[i++]);\n if (!n.d) {\n if (n.s) {\n external = true;\n return new this(1 / 0);\n }\n t = n;\n } else if (t.d) {\n t = t.plus(n.times(n));\n }\n }\n\n external = true;\n\n return t.sqrt();\n }", "function calculate_the_length(x1,y1,x2,y2){\n let length_AB = Math.sqrt ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));\n console.log(length_AB)\n}", "function hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n }", "function hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n }", "function hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n }", "function pyt(a, b) {\r\n\t\treturn Math.sqrt(a * a + b * b);\r\n\t}", "function eqtHeight(side_length) {\n return side_length * Math.sqrt(3) / 2\n}", "function calHyp(base,altitude){\n return (Math.round(Math.sqrt(base**2+altitude**2)));\n }", "function hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n}", "function dist(p1,p2) {\n return Math.hypot(p2.x-p1.x, p2.y-p1.y);\n}" ]
[ "0.82282203", "0.7890947", "0.75940454", "0.74378896", "0.74118584", "0.73922896", "0.73908", "0.7390663", "0.7387037", "0.7245202", "0.7073672", "0.6983835", "0.68348914", "0.68130314", "0.6734878", "0.67297643", "0.6571513", "0.6560006", "0.6445917", "0.6185874", "0.61590606", "0.61044353", "0.6097517", "0.6097517", "0.6097517", "0.6088315", "0.6075554", "0.6073149", "0.6072094", "0.60382205" ]
0.86003286
0
Return the entreprise corresponding to the id parameter
function getEntreprise(req, res, next) { var id = parseInt(req.params.id); db.query("SELECT * FROM entreprises WHERE id = ?", id, function (error, results, fields) { if (error) res.status(500) .json({ status: "ko", data: "error" }) else res.status(200) .json({ status: "ok", data: results }) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get(id) {\n return internal(this).idToEntity.get(id);\n }", "getEmpireById(id) {\n return client({\n method: 'GET',\n path: `${ROOT}/empires/${id}`,\n });\n }", "getById(id) {\r\n return this._byId[id]\r\n }", "function getEntityById(id) {\n return entities[id];\n}", "entity(id) {\n if (arguments.length === 0) {\n return new Entity(this);\n } else {\n return internal(this).entities.get(id);\n }\n }", "getById(id)\n {\n return this.getModel()\n .find(id)\n .first();\n }", "obterPorId(_id){\n return this.lista.filter( aluno => aluno._id === _id )[0];\n }", "function get(id) {\n let e = entities[id]\n if(e!==undefined){\n return {\n version: e.values.length,\n id: e.id,\n value: e.value\n }\n }\n return undefined\n\n}", "Get(id) {\n\t\treturn this.obj.filter(function(o){return o.id == id;})[0];\n\t}", "getPersona(id) {\n let persona = this.personas.filter(persona => persona.id === id)[0];\n\n /*\n Si encuentra una persona que cumpla con la propiedad, retornara un objeto\n si no retornara undefined\n */\n return persona;\n }", "function findById(id) {\n\n id = parseInt(id)\n\n if (!exercises.has(id))\n throw new Error(`No entity by id: ${id}`)\n\n return exercises.get(id)\n}", "getDetail(id) {\n return this.fetch(`${this.api}/${this.resource}/${id}`);\n }", "getEventoById(id) {\n return eventos.find(evento => evento.id === parseInt(id, 10));\n }", "getArtistById(id){\n let artistFound = this.artists.find( artist => artist.id == id );\n if ( !artistFound ){ throw new modelExep.NotFoundRelException('Artista no encontrado') } \n return artistFound;\n }", "get(id) {\n\n }", "getPersonaById(id) {\n //BUSCO DENTRO DEL ARREGLO PERSONAS Y SI ENCUENTRA UNA\n //DEVUELVE ESA PERSONA, SI NO, DEVUELVE UNDEFINED\n let persona = this.personas.filter(persona => {\n return persona.id === id;\n })[0];\n\n return persona;\n }", "getId (){\r\n return this.id;\r\n }", "getVenueUsingId(id) {\r\n let sql_getVenue = `SELECT id, venue_name, street, city, state, zip FROM venue_tb\r\n WHERE id = ${id}`;\r\n let result = this.apdao.all(sql_getVenue);\r\n return result;\r\n }", "getPersona(id) {\n let persona = this.personas.filter(persona => {\n return persona.id === id;\n })[0];\n //filter() retorna un nuevo arreglo y nosotros buscamos la posicion 0 de ese arreglo\n\n //si no se encuentra ninguna persona con el id, retorna undefined por defecto\n return persona;\n }", "getId()\n\t{\n\t\treturn this.id;\n\t}", "getId()\n\t{\n\t\treturn this.id;\n\t}", "function findById(id) {\n return _.find(entities, { '_id': id });\n }", "getUsuario(id) {\n for (let usuario of this.lista) {\n if (usuario.id === id) {\n return usuario;\n }\n }\n }", "getId() {\n \n return this.id; \n }", "async findById(id) {\n\t\tlet sqlRequest = \"SELECT * FROM employee WHERE id=$id\";\n\t\tlet sqlParams = {$id: id};\n\t\tconst row = await this.common.findOne(sqlRequest, sqlParams);\n\t\treturn new employee(row.id, row.name, row.admin, row.reporting_admin, row.password, row.calender_id);\n\t}", "function obtenerPersonaje(id) {\n return new Promise((resolve, reject) => {\n const URL = `${API_URL}${PEOPLE_URL.replace(':id', id)}`\n $\n .get(URL, opts, function (data) {\n resolve(data)\n })\n .fail(() => reject(id))\n })\n\n}", "function obtenerPersonaje(id) {\n return new Promise((resolve, reject) => {\n const URL = `${API_URL}${PEOPLE_URL.replace(':id', id)}`\n $\n .get(URL, opts, function (data) {\n resolve(data)\n })\n .fail(() => reject(id))\n })\n\n}", "static async findEmployee(id) {\n const user = await pool5.query(\n `\n select * from supervisor left join personal_information on personal_information.employee_id=supervisor.supervisor_id where personal_information.employee_id = $1`,\n [id]\n );\n return user.rows[0];\n }", "function obtenerPersonaje(id) {\n return new Promise((resolve,reject) => {\n const url = `${API_URL}${PEOPLE_URL.replace(':id', id)}`\n $\n .get(url,opts,function(data){\n resolve(data)\n })\n .fail(() => reject(id))\n })\n}", "getById(id) {\n return this.get(id).then(response => {\n const item = response.data.data;\n this.setCid(item);\n return item;\n });\n }" ]
[ "0.7146589", "0.68520635", "0.68410945", "0.67418903", "0.66265833", "0.6572946", "0.656409", "0.6505309", "0.6464359", "0.6446938", "0.64382064", "0.6430203", "0.6423881", "0.6368593", "0.6353878", "0.63314104", "0.6327672", "0.6297064", "0.6292475", "0.62807417", "0.62807417", "0.62726384", "0.6257975", "0.6257738", "0.6251852", "0.62449485", "0.62449485", "0.62224", "0.62128586", "0.6208557" ]
0.68777204
1
Return employees of the entreprise corresponding to the id parameter
function getEmployees(req, res, next) { var id = parseInt(req.params.id); db.query("SELECT * FROM users WHERE id_entreprise = ?", id, function (error, results, fields) { if (error) res.status(500) .json({ status: "ko", data: "error" }) else res.status(200) .json({ status: "ok", data: results }) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getEmployeeById (id) {\n var i;\n for (i = 0; i < employees.length; i++) {\n if (employees[i].id === id) {\n return employees[i];\n }\n }\n\n return undefined\n}", "async findById(id) {\n\t\tlet sqlRequest = \"SELECT * FROM employee WHERE id=$id\";\n\t\tlet sqlParams = {$id: id};\n\t\tconst row = await this.common.findOne(sqlRequest, sqlParams);\n\t\treturn new employee(row.id, row.name, row.admin, row.reporting_admin, row.password, row.calender_id);\n\t}", "getEployeeByID(employee_id : number): Promise<Employee[]>{\n return axios.get(url+'/employee/'+employee_id);\n }", "static async findEmployee(id) {\n const user = await pool5.query(\n `\n select * from supervisor left join personal_information on personal_information.employee_id=supervisor.supervisor_id where personal_information.employee_id = $1`,\n [id]\n );\n return user.rows[0];\n }", "async findAll() {\n\t\tlet sqlRequest = \"SELECT * FROM employee\";\n\t\tconst rows = await this.common.findAll(sqlRequest);\n\t\tlet employees = [];\n\t\tfor (const row of rows) {\n\t\t\temployees.push(new employee(row.id, row.name, row.admin, row.reporting_admin, row.password, row.calender_id, row.active));\n\t\t}\n\t\treturn employees;\n\t}", "function getEmployees() {\n\t\t\temployeeService.getEmployees().then(function(data) {\n\t\t\t\tvm.employees = data;\n\t\t\t});\n\t\t}", "async 'GET_EMPLOYEE_BY_ID'(state, payload) {\n\n state.employee = payload;\n }", "async fetchEmployeeById(id) {\r\n await this.checkLogin();\r\n var response = await axios.get(Config.employeeApiUrl + \"\" + id + \"/\", {\r\n headers: { Authorization: \"Bearer \" + AuthHandler.getLoginToken() },\r\n });\r\n return response;\r\n }", "function getEmployeeByListID(info) {\n\t\t\t\t\t\t\t\treturn Restangular.all(\n\t\t\t\t\t\t\t\t\t\tRestEndpoint.THE_SIGN_CA_URL\n\t\t\t\t\t\t\t\t\t\t\t\t+ \"/getEmployeeByListID\").post(info);\n\t\t\t\t\t\t\t}", "findAllEmployeesByDepartment(departmentId) {\n return this.connection\n .promise()\n .query(\n \"SELECT employee.id, employee.first_name, employee.last_name, roles.title FROM employee LEFT JOIN roles on employee.role_id = roles.id LEFT JOIN department department on roles.department_id = department.id WHERE department.id = ?;\",\n departmentId\n );\n }", "readAllEmployeesByDepartment(departmentId) {\r\n return this.connection.query(\r\n \"SELECT employee.id, employee.first_name, employee.last_name, role.title FROM employee LEFT JOIN role on employee.role_id = role.id LEFT JOIN department department on role.department_id = department.id WHERE department.id = ?;\",\r\n departmentId\r\n );\r\n }", "async getEmployeeById({commit}, id) {\n if (id <= 0) {\n throw Error('Id must be greater than zero')\n }\n const db = new EmployeeDbContext();\n commit('GET_EMPLOYEE_BY_ID', await db.getById(id))\n }", "function dbGetEmployeeWrapper(id) {\n dbGetEmployee(id)\n .then(res => {\n resolve(res);\n })\n .catch(err => {\n reject(err);\n });\n}", "fetchEmployee(params) {\r\n return Api().get('/employees/' + params)\r\n }", "viewAllEmployees() {\n\t\treturn this.connection.query(\n\t\t\t`\n SELECT\n e1.id AS ID,\n e1.first_name AS First_Name,\n e1.last_name AS Last_Name,\n role.title AS Role,\n department.name AS Department,\n CONCAT(e2.first_name, ' ', e2.last_name) AS Manager,\n role.salary AS Salary\n FROM\n employee e1\n LEFT JOIN\n role ON e1.role_id = role.id\n LEFT JOIN\n employee e2 ON e1.manager_id = e2.id\n\t\t LEFT JOIN department ON role.department_id = department.id\n\t\t ORDER BY\n e1.id;\n `\n\t\t);\n }", "readAllEmployees() {\r\n return this.connection.query(\r\n \"SELECT employee.id, employee.first_name, employee.last_name, role.title, department.name AS department, role.salary, CONCAT(manager.first_name, ' ', manager.last_name) AS manager FROM employee LEFT JOIN role on employee.role_id = role.id LEFT JOIN department on role.department_id = department.id LEFT JOIN employee manager on manager.id = employee.manager_id;\"\r\n );\r\n }", "getEmpireById(id) {\n return client({\n method: 'GET',\n path: `${ROOT}/empires/${id}`,\n });\n }", "employees() {\n return store.customers.filter(customer => {\n return customer.employerId == this.id;\n });\n }", "function loadEmployees() {\n API.getEmployees()\n .then(result => {\n // testing and checking what is sent from Sequelize\n console.log(result.data);\n setData(result.data);\n })\n .catch(err => console.log(err));\n }", "async findAssignedToCal(calID) {\n\t\tlet sqlRequest = `\n\t\t\tSELECT e.*\n\t\t\tFROM employee_calender ec\n\t\t\tINNER JOIN employee e ON ec.employee_id = e.id\n\t\t\tWHERE ec.calender_id = ` + calID.toString();\n\n\t\tconst rows = await this.common.findAll(sqlRequest);\n\t\tlet employees = [];\n\t\tfor (const row of rows) {\n\t\t\temployees.push(new employee(row.id, row.name, row.admin, row.reporting_admin, row.active));\n\t\t}\n\t\treturn employees;\n\t}", "function getEmployees(){\n fetch('http://localhost:8080/ERS/employees')\n .then(res => res.json())\n .then(data => {\n employees = data;\n console.log(\"接收到所有的员工数据\" + employees);\n appendEmployeesToTable(employees);\n });\n}", "getEmployees(){\r\n\t\tvar that = this;\r\n\t\t$.ajax({\r\n\t\t method: \"POST\",\r\n\t\t url: \"/ajaxgetemployees\",\r\n\t\t data: { OrderID: that.orderId }\r\n\t\t})\r\n\t\t.done(function( resp ) {\r\n\t\t\tthat.Employees = resp;\r\n\t\t\t\r\n\t\t\tconsole.log(resp);\r\n\t\t\t\r\n\t\t\tthat.setupEmployeesInListbox();\r\n\t\t\t//setup the order_details rows\r\n\t\t\t//First: read all of the products rows into an array called that.ProductsData\r\n\t\t\t//getProductsArr() calls createOrderDetailsRows()\r\n\t\t\treturn that.getProductsArr();\r\n\t\t\t\t\t\r\n\t\t})\r\n\t\t.fail(function(){\r\n\t\t\talert(\"Ajax Failed in getEmployees()\");\r\n\t\t});\r\n\t}", "function getAllEmployees(){\n\t\t\t$.ajax({\n\t\turl:'http://localhost:8181/api/v1/employee/',\n\t\ttype:'GET',\n\t\tcrossOrigin: true,\n\t\tcontentType : 'application/json',\n\t\tsuccess : function(data){\n\t\t\tvar response = data.employees;\n\t\t\tif(data.status == 200)\n\t\t\t\t$(\"#employeeDetails\").empty();\n\t\t\t$.each(response, function(i, data){\n \t\t$(\"#employeeDetails\")\n \t\t.append(\"<tr><td>\" + data.id + \"</td><td>\" + data.name + \"</td><td>\"+data.email+\"</td><td>\"+data.salary+\"<td></tr>\");\n})\n\t\t},\n\t\terror : function(error){\n\t\t\tconsole.log(error)\n\t\t}\n\t})\n\t}", "findAllEmployees() {\n return this.connection.promise().query(\n \"SELECT employee.id, employee.first_name, employee.last_name, roles.title, department.name AS department, roles.salary, CONCAT(manager.first_name, ' ', manager.last_name) AS manager FROM employee LEFT JOIN roles on employee.role_id = roles.id LEFT JOIN department on roles.department_id = department.id LEFT JOIN employee manager on manager.id = employee.manager_id;\"\n );\n }", "function employeesByCity (id) {\n var i;\n var employeesInCity = [];\n for (i = 0; i < employees.length; i++) {\n\n if (employees[i].city === id) {\n employeesInCity.push(employees[i])\n }\n }\n\n return employeesInCity;\n}", "async findUnassingnedEmployees() {\n\t\tlet sqlRequest = `\n\t\tSELECT employee.*\n\t\tFROM employee\n\t\tLEFT JOIN employee_card ON employee.id = employee_card.employee_id\n\t\tWHERE employee_card.employee_id IS NULL`;\n\t\tconst rows = await this.common.findAll(sqlRequest);\n\t\tlet employees = [];\n\t\tfor (const row of rows) {\n\t\t\temployees.push(new employee(row.id, row.name, row.admin, row.reporting_admin, row.password, row.active));\n\t\t}\n\t\treturn employees;\n\t}", "async fetchSalaryEmployee(id) {\r\n await this.checkLogin();\r\n var response = await axios.get(Config.employeeSalaryByIdApiUrl + \"\" + id, {\r\n headers: { Authorization: \"Bearer \" + AuthHandler.getLoginToken() },\r\n });\r\n return response;\r\n }", "function getAnEmployee(res, mysql, context, id, complete){\r\n var sql = \"SELECT id, name, department FROM zoo_employee WHERE id = ?\";\r\n var inserts = [id];\r\n mysql.pool.query(sql, inserts, function(error, results, fields){\r\n if(error){\r\n res.write(JSON.stringify(error));\r\n res.end();\r\n }\r\n context.employee = results[0];\r\n complete();\r\n });\r\n }", "function viewEmployees() {\n var query = \"SELECT CONCAT(employees.first_name, ' ', employees.last_name) as employee_name, roles.title, departments.name, employees.id FROM employees LEFT JOIN roles on employees.role_id = roles.id LEFT JOIN departments ON departments.id = roles.department_id \";\n con.query(query, function(err, res) {\n if (err) throw err;\n for (var i = 0; i < res.length; i++) {\n console.log(\"\\n\" + \"|| Employee: \" + res[i].employee_name + \"|| Title: \" + res[i].title + \"|| Department: \" + res[i].name + \"|| ID: \" + res[i].id);\n }\n runManager();\n });\n }", "function getEmps() {\n\t\t$http.get('/salary_input')\n\t\t\t.then(function (response) {\n\t\t\t\tconsole.log('Employee Data Get ' + response);\n\t\t\t\tself.employees = response.data;\n\t\t\t});\n\t}" ]
[ "0.73206043", "0.7212194", "0.71006846", "0.6989848", "0.69851136", "0.6932782", "0.6797988", "0.67077446", "0.6678182", "0.66624117", "0.6643086", "0.6540766", "0.6519953", "0.6517105", "0.64350927", "0.64248246", "0.64130837", "0.64055556", "0.6401281", "0.63880527", "0.6351143", "0.63453", "0.6342484", "0.6330383", "0.6306393", "0.6306356", "0.6305342", "0.628482", "0.6262792", "0.6248791" ]
0.75134283
0
Deletes the entreprise corresponding to the id parameter
function deleteEntreprise(req, res, next) { var id = parseInt(req.params.id); db.query("DELETE FROM entreprises WHERE id = ?", id, function (errors, results, fields) { if (errors) res.status(500) .json({ status: "ko", data: "error" }) res.status(200) .json({ status: "ok", data: results }) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteEntityById(id) {\n delete entities[id];\n}", "remove(id, params) {}", "deleteById(req, res) {\n let id = req.params.id;\n\n this.tradeDao.deleteById(id)\n .then(this.common.editSuccess(res))\n .catch(this.common.serverError(res));\n }", "async deleteById(id) {\n\t\tif (await empCal.findByEmpId(id)) {\n\t\t\tawait empCal.deleteByEmpID(id);\n\t\t}\n\t\tif (await empCard.findByEmpId(id)) {\n\t\t\tawait empCard.deleteByEmpID(id);\n\t\t}\n\t\tlet sqlRequest = \"DELETE FROM employee WHERE id=$id\";\n\t\tlet sqlParams = {$id: id};\n\t\treturn this.common.run(sqlRequest, sqlParams);\n\t}", "delete(req, res) {\n RegistroEstudo.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error) {\n res.status(500).json(error);\n });\n }", "supprimerParId(id) {\n mongoose.model('Publicite').findByIdAndDelete({_id : id}, cb).then((result)=>{\n console.log(\"suppression effectuée\");\n }).catch((error)=>{\n console.log(\"erreur suppression\");\n });\n }", "eliminarOperarioPersona(id) {\n return axios.delete(`${API_URL}/v1/operario/${id}`);\n }", "deleteEmployee(empid) {\n this.employeeService.deleteEmployee(empid);\n this.getEmployeeList();\n }", "function eliminar(id) {\n fetch(`${baseUrl}/${groupID}/${collectionID}/${id}`, {\n 'method': 'DELETE',\n }).then(res => {\n return res.json();\n }).then(json => {\n console.log(\"Se elimino correctamente\");\n precargarUsers();\n }); //agregar catch\n }", "async destroy ({ params }) {\n const deposito = await Deposito.findOrFail(params.id);\n await deposito.delete();\n }", "deleteById(id) {\n let sqlRequest = \"DELETE FROM event WHERE id=$id\";\n let sqlParams = {$id: id};\n return this.common.run(sqlRequest, sqlParams);\n }", "function deleteRecord(id) {\n\t\t\n\t\t\n\t\taddOverLay();\n\t\t$.ajax({\n\t\t\turl : HOST_PATH + \"admin/article/movetotrash\",\n\t\t\tmethod : \"post\",\n\t\t\tdata : {\n\t\t\t\t'id' : id\n\t\t\t},\n\t\t\tdataType : \"json\",\n\t\t\ttype : \"post\",\n\t\t\tsuccess : function(data) {\n\t\t\t\t\n\t\t\t\tif (data != null) {\n\t\t\t\t\t\n\t\t\t\t\twindow.location.href = HOST_PATH + \"admin/article\";\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\t\n\t\t\t\t\twindow.location.href = HOST_PATH + \"admin/article\";\n\t\t\t\t}\n\t\t\t}\n\t\t});\t\n\t}", "async deleteById(id) {\r\n const item = await this.findById(id);\r\n const result = await item.destroy();\r\n if (result === false) {\r\n throw new Exception('can not delete resource', 1002);\r\n }\r\n return result;\r\n }", "eliminarFertilizante(id) {\n return axios.delete(`${API_URL}/v1/fertilizacion/${id}`);\n }", "static delete(id) {\r\n // const coursList = [];\r\n // for (let index = 0; index < coursExtent.length; index++) {\r\n // if(coursExtent[index].id != id){\r\n // coursList.push(coursExtent[index]);\r\n // }\r\n // }\r\n // coursExtent.splice(0,coursExtent.length);\r\n\r\n // for (let indexx = 0; indexx < coursList.length; indexx++) {\r\n // coursExtent.push(coursList[indexx]); \r\n // }\r\n // return coursExtent;\r\n return db.execute('DELETE FROM Kurs WHERE Id_kurs = ?', [id]);\r\n }", "deleteHouse(id) {\n housesService.deleteHouse(id)\n }", "deleteById(req, res) {\n Activity.findByIdAndRemove(req.params.id).then(result => {\n res.json(result);\n })\n .catch(err => {\n res.json(err);\n });\n }", "async destroy ({ params }) {\n const atividade = await AtividadeDoDia.findOrFail(params.id);\n await atividade.delete();\n }", "supprimerParId(id) {\n console.log(id + \" <=id \");\n mongoose.model('Article').deleteOne({\"_id\" : id}).then((result)=>{\n console.log('ok deleted');\n }).catch((err)=>{\n console.log(err);\n });\n }", "function deleteEvaluation(id){\n\n}", "function deleteEntry (req, res) {\n logger.debug('Request recieved to cease entry by id', { loggerModule, URL: req.originalUrl, id: req.params.id })\n _performDatabaseUpdate(req, res, {endDate: new Date()})\n }", "remove() {\n var db = new DB();\n db.delete(this.table, `id = '${this.getAttribute('id')}'`);\n }", "deleteById(id) {\n let sqlRequest = \"DELETE FROM repo WHERE id=$id\";\n let sqlParams = {$id: id};\n return this.common.run(sqlRequest, sqlParams);\n }", "function remove(id) {\n\t\t\treturn $http({\n\t\t\t\turl: 'api/comercios/' + id,\n\t\t\t\tmethod: \"DELETE\"\n\t\t\t}).then(\n\t\t\t\tfunction success(response) {\n\t\t\t\t\treturn response.data;\n\t\t\t\t},\n\t\t\t\tfunction error(error) {\n\t\t\t\t\treturn error.data;\n\t\t\t\t});\n\t\t}", "deleteById(id) {\n let sqlRequest = \"DELETE FROM restaurants WHERE id=$id\";\n let sqlParams = {\n $id: id\n };\n return this.common.run(sqlRequest, sqlParams);\n }", "function deleteExercise(id) {\n $.ajax({\n method: \"DELETE\",\n url: \"/api/exercises/\" + id\n })\n .then(function () {\n $(`[data-exercise=${id}]`).remove();\n });\n }", "static delete(id) {\r\n\r\n return new Promise((next) => {\r\n\r\n db.query('SELECT * FROM outil WHERE id = ?', [id])\r\n .then((result) => {\r\n if (result[0] != undefined) {\r\n // Supprimer d'abord l'association puis l'outil\r\n return db.query('DELETE FROM classer WHERE id_outil = ?', [id]) && db.query('DELETE FROM outil WHERE id = ?', [id])\r\n } else {\r\n next(new Error(config.errors.wrongID))\r\n }\r\n })\r\n .then(() => next(true))\r\n .catch((err) => next(err))\r\n })\r\n }", "function del(id){\n\t\t\t$(\"[data-eid=\"+ id +\"]\").each(function(){\n\t\t\t\tvar action = makeJsonFromNode(this);\n\t\t\t\tvar idArr = action.id.split('-');\n\n\t\t\t\t// Find object and reset start/end data\n\t\t\t\tvar p = getObjInArr(experiments[idArr[2]].protocols, 'id', idArr[3]);\n\t\t\t\tvar s = getObjInArr(p.steps, 'id', idArr[4]);\n\t\t\t\tvar a = getObjInArr(s.actions, 'id', action.id);\n\t\t\t\t\n\t\t\t\ta.start = a.end = \n\t\t\t\taction.start = action.end = 0;\n\n\t\t\t\t// Save and remove\n\t\t\t\tsaveAction.enqueue(action);\n\t\t\t\t$('#calendar').fullCalendar(\"removeEvents\", this.getAttribute(\"data-fc-id\"));\n\t\t\t});\n\t\t\t$(\"[data-id=\"+ id +\"]\").removeClass('disabled');\n\t\t}", "deleteById(case_id : number): Promise<void>{\n return axios.delete(url+'/deleteCase/'+case_id);\n }", "static delete(id) {\n try{\n delete IdentifyMap[id];\n const data = connection.query(`SELECT * FROM resource where id=${id}`);\n if (data.length > 0){\n const type = data[0].type;\n const resource_line_item_data = connection.query(`DELETE FROM resource_line_item WHERE resource_id=${id}`);\n const child_data = connection.query(`DELETE FROM ${type} where resource_id=${id}`);\n const resource_data = connection.query(`DELETE FROM resource where id=${id}`);\n return {status : 0, message : 'Resource deleted.'};\n } else {\n return {status : 1, message : 'Nothing to delete.'}\n }\n }\n catch(error){\n return {status : 1, message : 'Error' +error, error}\n }\n }" ]
[ "0.72522163", "0.7210319", "0.706414", "0.70603603", "0.7036229", "0.6943367", "0.6933638", "0.6892575", "0.6861884", "0.68562645", "0.68396944", "0.6826325", "0.6823247", "0.6802406", "0.6780316", "0.6768397", "0.67428386", "0.6737749", "0.6723371", "0.6702689", "0.6681091", "0.6656099", "0.6653643", "0.6650332", "0.66501325", "0.66486084", "0.66174126", "0.660744", "0.6605349", "0.6604778" ]
0.75582635
0
Change "Add to eBay" Value
function addItemToEbay() { addToEbay.value = '1'; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateBasketTotal(addToTotal) {\n currTotal = $(\"#basket-total\").text();\n currTotal = Number(currTotal.substring(1,currTotal.length));\n basketTotal = currTotal + Number(addToTotal);\n \n basketTotal = \"&pound\" + Number(basketTotal).toFixed(2);\n $(\"#basket-total\").html(basketTotal);\n}", "function changePrice(){\n\t$(\"input[id^='alternative-']\").click(function() {\n\t//\t$(\"#callToBookDiv\").hide(); //if the previously selected item was onrequest hide the calltobook div and display addToTripButton div\n\t\t$(\"#addToTripButton\").show();\n\t\tvar selectedPrice=$(\"#selectedActivityPrice\").val();\n\t\tvar idSplit = $(this).attr('id').split(\"-\");\n\t\tvar newAltPrice=$(\"input[id='activityPrice-\" + idSplit[1] + \"']\").val();\n\t\tvar newPrice=parseFloat(selectedPrice)+parseFloat(newAltPrice);\n\t\t$(\"#priceDisplay\").text((newPrice).toFixed(2));\n\t\t$(\"#selectedAlternative\").val($(this).val());\n\t\t$(\"#altDescription\").html($(\"p[id='activityDescription-\" + idSplit[1] + \"']\").html());\n\t});\n}", "function updateVariantPrice(variant) {\r\n\t $('#buy-button-1 .variant-price').text('$' + variant.price);\r\n\t }", "function displayAddedValue(articleID) {\n\t// if set to 0 show \"normal\" cartsymbol\n\tvar countElement = 'count_' + articleID;\n\tvar evalCount = getNumberArticle(articleID);\n\n\t// Put it back to the edit box\n\tvar ele = document.getElementById(countElement);\n\tif (ele){\n\t\tele.value = evalCount;\n\t}\n\n\tclicked = false;\n}", "function updateEbayListingStage() {\n let tabId = window.itemData.tab;\n let newStage = \"form\";\n\n let data = {\n tab: tabId,\n stage: newStage,\n };\n\n chrome.runtime.sendMessage({\n command: \"update-ebay-active-tab-stage\",\n data: data,\n });\n}", "function buttonBuyEvent() {\r\n sumAllMoney += Number($(this).text().match(/\\d+\\.\\d+/g)[0]);\r\n $('h1:eq(1)').text(`Total Store Profit: ${sumAllMoney} BGN`)\r\n $(this).parent().remove()\r\n }", "function breadChoice(){\n button.setAttribute(\"data-item-custom1-value\", bread.value);\n}", "function click_money_incrementation(money, _values) {\r\n data.inventory.money += money * data.inventory.multiplier;\r\n Save();\r\n Attribtion();\r\n update_dom();\r\n}", "function changeStandType_add(obj){\n\tif (obj.value==2){\n\t\t$(\"#standCode_add\").val(\"GB/T\");\t\t\n\t}else if (obj.value==4){\n\t\t$(\"#standCode_add\").val(\"DB62/T\");\n\t}\n\tcalculate_add();\n}", "function setAmountValue() {\n amount\n .val($('.price-plan-header.active').next().children(':first').text())\n .trigger('update');\n }", "function addBudget(){\n return nicaragua.annualBudget +250000;\n}", "function updateSubmitButtonText(){\n if( EVENT.type === 'free' ){\n $form.find('[type=\"submit\"]').val('Confirm');\n }\n else{\n $form.find('[type=\"submit\"]').val('Pay $' + calcAmount());\n }\n }", "function updateSubmitButtonText(){\n if( EVENT.type === 'free' ){\n $form.find('[type=\"submit\"]').val('Confirm');\n }\n else{\n $form.find('[type=\"submit\"]').val('Pay $' + calcAmount());\n }\n }", "function handleBuysome(e) {\n var q = this['value'];//(e.target) ? e.target.getAttribute('value') : e.srcElement.getAttribute('value');\n\n //var q = this.getAttribute('value');\n var p = this.parentNode.getElementsByClassName('buyone');\n if (p.length==1) {\n p = p[0];\n var s = p.getAttribute('href');\n if (!s) \n return;\n s = s.replace(/\\&quantity\\=[0-9]*/,'&quantity='+q);\n //alert('buying '+q+' so will replace with '+s);\n p.setAttribute('href',s);\n } \n}", "function updatePayString(){\n payBalanceField.innerText = payBalance + \" Kr.\"\n}", "function totaalBedragToevoegen(bedrag){\n totaalBedrag = totaalBedrag + Number(bedrag);\n totaal.value = totaalBedrag;\n}", "function add_tax_to_price_onscreen(tax) {\n let price_id = get_price_div();\n let price = get_price()\n let p = document.getElementById(price_id);\n p.innerText = \"$\" + (price * (1 + tax)).toFixed(2) + \" with tax\";\n console.log(\"price adjusted.\");\n}", "function addTax() {\n var tax = $(\"#newTaxSale\").val();\n\n var totalPrice = $(\"#newSaleTotal\").attr(\"totalSale\");\n\n var taxPrice = Number((totalPrice * tax) / 100);\n\n var totalwithTax = Number(taxPrice) + Number(totalPrice);\n\n $(\"#newSaleTotal\").val(totalwithTax);\n\n $(\"#saleTotal\").val(totalwithTax);\n\n $(\"#newTaxPrice\").val(taxPrice);\n\n $(\"#newNetPrice\").val(totalPrice);\n}", "function editBillingAmount() {\n\tdocument.getElementById('canFinalize').value = 'NO';\n}", "function updateWechselGeld(inserted) {\r\n //Add val of inserted coin to total amt inserted in machine\r\n wechselGeld += inserted;\r\n //Convert total to string w/ 2 decimals\r\n strWechselGeld = wechselGeld.toFixed(2);\r\n}", "function priceAppender() {\n var value = $('.total-price').find('.amount').text();\n $('.popup-form').find('.total-price').val(value);\n }", "function updateWishlist(action) {\n let wishlistAmount = document.querySelector(\"span\");\n\n let currentAmount = wishlistAmount.innerHTML; currentAmount = parseInt(currentAmount);\n /* fav film wordt toegevoegd > +1 wordt weergegeven */\n let newAmount; if (action == \"plus\") { newAmount = currentAmount + 1; }\n\n /* wanneer fav film weg wordt gehaald > aantal -1 */\n else { newAmount = currentAmount - 1; }\n wishlistAmount.innerHTML = newAmount;\n}", "function changeAmount(){\n updateCurrentCost();\n updateAmortization();\n updateTotalCookPerSecChain();\n}", "function addAmount(id, inputAmount) {\r\n\r\n let updateField = document.getElementById(id);\r\n let updateFieldValueStr = updateField.innerText;\r\n let updateFieldValue = parseInt(updateFieldValueStr);\r\n // sum of deposite\r\n let total = updateFieldValue + inputAmount;\r\n\r\n // update deposite\r\n updateField.innerText = total;\r\n}", "function setLuggageValue() {\r\n let inputContainer = section.querySelectorAll('.add-minus-input');\r\n inputContainer.forEach(function(item) {\r\n item.querySelector('input').value = 0;\r\n })\r\n }", "function setLuggageValue() {\r\n let inputContainer = section.querySelectorAll('.add-minus-input');\r\n inputContainer.forEach(function(item) {\r\n item.querySelector('input').value = 0;\r\n })\r\n }", "function increasePay()\n{\n workBalanceElement.value = parseInt(workBalanceElement.value) + 100;\n}", "function changeProductValues() {\n\tshowHideProductValues();\n\tenableDisableCreditFields();\n}", "function editSaveBill() {\n\tdocument.getElementById('canFinalize').value = 'NO';\n}", "function saveInList(item){\n let myAmount = item.getText().replace(/USD|,/gi,\"\")\n if (myAmount.substring(0,1) === '-'){\n listAmounts.push(parseInt('-'+myAmount.substring(2)))\n }\n else{listAmounts.push(parseFloat(myAmount.substring(2)))} \n }" ]
[ "0.6014025", "0.56391364", "0.5621171", "0.5555007", "0.549761", "0.54732794", "0.5471149", "0.54103446", "0.5397586", "0.5373796", "0.5363409", "0.53546286", "0.53546286", "0.5322086", "0.5315493", "0.5299758", "0.5290246", "0.5273022", "0.5255665", "0.5246356", "0.52452147", "0.52407336", "0.5238244", "0.52379155", "0.52368224", "0.52368224", "0.5220477", "0.5218122", "0.5213978", "0.5210138" ]
0.8097996
0
Set template for Long Description
function setDescriptionTemplate(){ CKEDITOR.instances.app_bundle_product_form_longDescription.setData(`<p>Your satisfaction is our number one goal. Keep in mind that we offer hassle-free returns if needed. If you have any questions or problems, please contact us.</p> <p>Please Note: All included items are shown in the pictures</p> <p>${newTitle}<br /> ${itemNumber}</p> <p><strong>Features:</strong></p> <ul> <li>Feature 1</li> </ul> <p><strong>What&#39;s included:</strong></p> <ul> <li>${newTitle}</li> </ul> <p><strong>What&#39;s not included:</strong></p> <ul> <li>Any other accessories</li> </ul> <p><strong>Condition:</strong></p> <ul> <li>Used in good working condition</li> <li>Shows signs of use such as scuffs and scratches</li> <li>See photos for details</li> </ul> `) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createMarkupForProjectDescription() {\n if (project.projectDescription) {\n return {\n __html: project.projectDescription,\n };\n } else {\n return;\n }\n }", "function descriptionTemplate({\n description,\n text,\n demo\n}) {\n return `<p align=\"center\">\n <b>${description}</b></br>\n <sub>${text != null ? text : \"\"}${demo != null ? ` ${demoTemplate({\n url: demo\n })}` : \"\"}<sub>\n</p>\n\n<br />\n`;\n}", "function createMarkup(description) {\n return { __html: description };\n }", "function generateDescription( description ) {\n return `## Description\n\n ${description}`;\n}", "function createShortDescriptions(){\n\tPatterns.forEach((pattern) => {\n\t\tpattern.ShortDescription = $(pattern.Content).find(\"i\").first().text();\n\t});\n}", "get textFormatTemplate() {\n return html`\n <div id=\"wrapper\" class=\"text-format\">\n ${this.overlineTemplate}\n ${this.titleTemplate}\n ${this.bodyTemplate}\n </div>\n `;\n }", "function Description(props) {\n if (clothing.desc) {\n return (<div> <SubHeading> <div> Description</div></SubHeading>\n <Desc> {clothing.desc} </Desc></div>\n\n\n );\n } else {\n return (<div></div>);\n }\n }", "toPageDescription() {\n let description;\n if ((description = this.metaOverrides('description'))) {\n return description;\n } else if (this.isGeographic()) {\n return `Explore art by artists who are from, or who have lived in, ${this.get('name')}. Browse works by size, price, and medium.`;\n } else {\n return _s.clean(this.mdToHtmlToText('description'));\n }\n }", "set humanDescription(value) {}", "setDescription(description) {\n this.description.setValue(description);\n }", "function Description(def) {\n if(typeof def === 'string') {\n this.parse(def);\n }else if(def\n && typeof def === 'object'\n && typeof def.txt === 'string'\n && typeof def.md === 'string') {\n this.md = def.md;\n this.txt = def.txt;\n }else{\n throw new Error('invalid value for description');\n }\n}", "function removeFromShortTitle(str) {\r\n CKEDITOR.instances.app_bundle_product_form_shortDescription.setData(`<p>${str}</p>`)\r\n }", "function applyDescTemplate(obj){\n\treturn (WRAP_OPTIONS.compiledDescTemplate)? WRAP_OPTIONS.compiledDescTemplate(obj): obj.name;\n}", "getDescription(descriptionObj) {\n // Uncomment to view inconsistencies\n // const descStart = descriptionObj.lastIndexOf('<p>');\n // const description = descriptionObj.slice(descStart + 3, descriptionObj.length - 4);\n\n const description = 'A dummy description of the Flickr image, please view FlickrImage.js to see reasoning for using this here.'\n return description;\n }", "set description(value) { this._description = value; }", "function Description(obj) { this.obj = obj; }", "function createDescription(component, change) {\n let rows = component.data.text.split(\"\\n\").length;\n rows = rows >= 5 ? rows : 5;\n return <FormControl\n type=\"textarea\"\n placeholder=\"Beschreibung...\"\n value={component.data.text}\n onChange={onChange}\n rows={rows}\n className=\"textarea description\"\n />;\n function onChange(oEvent) {\n component.data.text = oEvent.target.value;\n change(component)\n }\n}", "get description() {\n return this.getText('description');\n }", "function TextDesc() {\n\tthis.text = '';\n\tthis.xml_id = '';\n//\tthis.custom = '';\n}", "function tt_MkTipContent(a) {\n if (tt_t2t) {\n if (tt_aV[COPYCONTENT])\n tt_sContent = tt_t2t.innerHTML;\n else\n tt_sContent = \"\";\n }\n else\n tt_sContent = a[0];\n tt_ExtCallFncs(0, \"CreateContentString\");\n}", "function changeDescription(value){\n setDescription(value)\n }", "function renderDescription(){\n let shortText = JSON.stringify(text).substr(1, 21);\n return <p className=\"card-text\">{ shortText }...</p>\n }", "shortDescription(contenu){\n\t\tlet desc = contenu.slice(0, 250);\n\t\treturn desc + \" ...\";\n\t}", "function m_tt_MkTipContent(a)\n{\n\tif(m_tt_t2t)\n\t{\n\t\tif(m_tt_aV[COPYCONTENT])\n\t\t\tm_tt_sContent = m_tt_t2t.innerHTML;\n\t\telse\n\t\t\tm_tt_sContent = \"\";\n\t}\n\telse\n\t\tm_tt_sContent = a[0];\n\tm_tt_ExtCallFncs(0, \"CreateContentString\");\n}", "function markdownDescription(text) { }", "function setupDescriptionEditor(){\n\t$('#input_PageHTML').summernote({\n\t\t height: 500, // set editor height\n\t\t minHeight: 200, // set minimum height of editor\n\t\t maxHeight: 800, // set maximum height of editor\n\t\t focus: false // set focus to editable area after initializing summernote\n\t\t});\n\n\tvar PageHTML = $(\"#page_content\").val();\n\t$('#input_PageHTML').summernote('code', PageHTML);\n\n\tpageData[\"content\"] = PageHTML;\n\n\n\t$(\".note-editor .note-editable\").css(\"text-align\",\"left\");\n}", "function createContent() {\n var bCSS = \"font: bolder 12px Arial\";\n return '<b style=\"' + bCSS + '\">Tag Legend</b>' +\n '<ul style=\"margin-left: 10px\">' +\n '<li>@location</li>' +\n '<li>+project</li>' +\n '<li>general category</li>' +\n '</ul>'\n ;\n }", "getDescription() { \n let description = ''\n let pageConfig = Config.pages[this.page] || {}\n \n if( this.isBlogPost) {\n description = this.post.frontmatter.description || this.post.excerpt\n }\n else {\n description = pageConfig.description || Config.description\n }\n \n return description\n }", "getDescription() {\n return `${this.name} is ${this.age} ${this.age > 1 ? 'years' : 'year'} old.`;\n }", "description(description) {\n this.#description_ = description;\n return this;\n }" ]
[ "0.6644738", "0.6422635", "0.63019973", "0.6284039", "0.6265662", "0.6168046", "0.61362284", "0.60829526", "0.60827804", "0.60525", "0.5930345", "0.59264666", "0.59192073", "0.58818763", "0.58609194", "0.57896096", "0.57769364", "0.57747084", "0.5774313", "0.571282", "0.5697099", "0.5681852", "0.5668789", "0.563947", "0.561567", "0.56087106", "0.5595162", "0.5535572", "0.5529881", "0.5482655" ]
0.7869298
0
? Slightly unsure what componentDidMount does but the login within states that if the localstorage item "InstagramUsername is not null then it sets the loggedIn state to true.
componentDidMount() { console.log('Local storage: ', localStorage.getItem('InstagramUsername')); if (localStorage.getItem('InstagramUsername') !== null) { this.setState({ loggedIn: true }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "componentDidMount() {\n if (localStorage.getItem(\"username\")) {\n this.setState({\n loggedIn: true\n });\n }\n }", "componentDidMount() {\n const loggedinUser = localStorage.getItem('user');\n if (loggedinUser) {\n const foundUser = JSON.parse(loggedinUser)\n this.setState({user: foundUser})\n this.setState({isLoggedIn: true})\n }\n this.setState({isLoading: false})\n }", "componentWillMount() {\n const user = localStorage.getItem('user');\n const isLoggedIn = JSON.parse(localStorage.getItem('isLoggedIn')) || false;\n this.setState({ user, isLoggedIn });\n }", "componentDidMount() {\n\n const jwt = sessionStorage.getItem('accessToken');\n\n if(jwt) {\n this.loadPlayerDetails();\n this.setState({loggedIn: true});\n }\n\n }", "componentDidMount(){\n if(localStorage.getItem('userAuthToken')){\n this.setState({ isAuthenticated: true })\n }\n }", "componentDidMount() {\n // Check if logged in\n let loginTime = window.localStorage.getItem('loginTime');\n\n // Check if loginTime is null or login session has been expired\n if (\n loginTime == null ||\n loginTime === 'expired' ||\n new Date().getTime() - loginTime >= 3600 * 1000\n ) {\n // Logged in expired, do not show the state\n this.setState({ loggedIn: false });\n } else {\n // Logged in, load the album\n this.setState({ loggedIn: true });\n\n // Keep checking the player each second\n this.getPlayerInterval = setInterval(() => this.getSpotifyPlayer(), 1000);\n }\n }", "componentDidMount () {\n const isLogged = JSON.parse(localStorage.getItem('UserSession'));\n if (isLogged) {\n // console.log(\"Stored session: \", this.isLogged);\n this.setState({\n user: isLogged\n });\n }\n }", "componentDidMount() {\n const token = localStorage.getItem(\"token\");\n if (token === null) {\n this.setState({\n loggedIn: false,\n });\n }\n }", "componentDidMount() {\n /* eslint-disable react/no-did-mount-set-state */\n /* https://github.com/airbnb/javascript/issues/684 */\n const token = window.localStorage.getItem('khToken');\n if (token) {\n this.setState({\n loggedIn: true,\n token,\n });\n }\n }", "componentDidMount(){\n // If the user is logged in, that means there is something on local storage:\n if (JSON.parse(localStorage.getItem(\"RCB_USER\"))) {\n // So, we grab whatever is there...and set our current state with that data\n let RCB_USER = JSON.parse(localStorage.getItem(\"RCB_USER\"));\n this.setState({\n firstName: RCB_USER.firstName,\n lastName: RCB_USER.lastName,\n email: RCB_USER.email,\n password: RCB_USER.password,\n gender: RCB_USER.gender,\n dateOfBirth: RCB_USER.dateOfBirth,\n country: RCB_USER.country,\n telephone: RCB_USER.telephone,\n houseNumber: RCB_USER.houseNumber,\n streetName: RCB_USER.streetName,\n city: RCB_USER.city,\n stateName: RCB_USER.stateName,\n zipCode: RCB_USER.zipCode,\n userData: RCB_USER,\n userIsLoggedIn: true\n })\n }else{\n // Else, we just set our state with a message that the user is not logged in array\n this.setState({\n userData: [\"User is not logged in\"],\n userIsLoggedIn: false\n })\n }\n }", "componentDidMount() {\n console.log(this.state.loggedIn);\n\n fetch('/profile', { credentials : 'same-origin' \n }).then(resp => resp.json()).then(data => {\n \n if(data.failed){\n console.log('not logged in');\n }\n else if(data.name){\n this.setState({\n loggedIn: true,\n avatar: data.avatar,\n username: data.name\n });\n }\n \n \n });\n }", "componentDidMount() {\n let state = localStorage[\"appState\"];\n if (state) {\n let AppState = JSON.parse(state);\n this.setState({\n isLoggedIn: AppState.isLoggedIn,\n user: AppState.user\n });\n }\n }", "checkUserCredentials() {\n let username = sessionStorage.getItem('username');\n if (!username) {\n this.setState({\n loggedIn: false\n })\n }\n else {\n this.setState({\n loggedIn: true,\n username: username\n })\n }\n }", "componentWillMount() {\n // Sync the state from Firebase\n base.syncState(\"users\", {\n context: this,\n state: \"users\"\n });\n\n // Check if they have logged in before\n const localStorageUser = localStorage.getItem(\"pizza-love\");\n if (localStorageUser) {\n this.setState({ currentUser: localStorageUser });\n console.log(\"User Loaded from Local Storage\");\n }\n }", "componentDidMount() {\n // Retrieve and parse credentials from localStorage\n const credentials = JSON.parse(localStorage.getItem('credentials'));\n\n // If does not exist, set logged out state\n if (!credentials) {\n return this.setState({ error: null, user: null });\n }\n\n // Validate credentials and handlelogin\n this.props.firebase\n .signInWithCredential(credentials)\n .then(userCredential => {\n this.handleLogin(userCredential);\n })\n .catch(error => {\n this.handleLogout(error);\n });\n }", "componentDidMount() {\n let userCookieData = Cookies.get(\"application_user_data\");\n if (userCookieData !== undefined) {\n this.setState({loggedInCookie: true})\n }\n }", "componentDidMount() {\n getCurrentUser().then((data) => {\n if (typeof data.error !== 'undefined') {\n data.isAuth = false\n } else if(typeof data.isAuth === 'undefined') {\n data.isAuth = true\n }\n\n // Update current user state since this can't be done in class\n // constructor otherwise other components expecting user.isAuth\n // will fail horrendously\n if (this.state.user.isAuth !== data.isAuth) {\n this.setState({ user: data})\n\n if (this.state.user.isAuth) {\n let path = window.location.pathname\n\n if (path === LOGIN_ROUTE) {\n this.props.history.push(HOME_ROUTE)\n } else {\n this.props.history.push(path)\n }\n } else {\n this.props.history.push(LOGIN_ROUTE)\n }\n }\n })\n }", "componentDidMount() {\n if(localStorage.getItem('token')) {\n this.setState(() => ({ \n isAuthenticated: true \n }))\n }\n }", "componentDidMount() {\r\n\r\n\r\n//check if session is set and prevent Direct Access to the App.\r\n\r\nvar app_sess_data_check = localStorage.getItem('appsessdata');\r\n\r\nconst session = app_sess_data_check;\r\n//alert('my sessioning: ' +session);\r\n\r\n//const session= 101;\r\nthis.setState({mysession: session});\r\n\r\n\r\n\r\n\r\n\r\n this.fetchLogin();\r\n\r\n}", "componentWillMount() {\n\t\tlet state = localStorage[\"appState\"];\n\t\tif (state) {\n\t\t\tlet appState = JSON.parse(state);\n\t\t\tthis.setState({ isLoggedIn: appState.isLoggedIn, user: appState.user });\n\t\t}\n\t}", "componentDidMount() {\n console.log(\"In component did mount\");\n // get the localstorage object\n const obj = getFromStorage(localStorageObjectName());\n\n // check if anything was stored in localStorage at all by\n // checking if obj is null or not.\n if (obj && obj.token) {\n // get token from local storage\n const { token } = obj;\n console.log(`Token: ${token}`);\n\n // logging user in, so load screen\n this.setState({\n isLoading: true\n });\n\n // verify token\n fetch(`/api/account/verify?token=${token}`, {\n headers: {\n \"Content-Type\": \"application/json\"\n }\n })\n .then(res => res.json())\n .then(json => {\n if (json.success) {\n this.setState({\n token,\n isLoading: false\n });\n } else {\n this.setState({\n isLoading: false\n });\n }\n });\n } else {\n // there is no token\n this.setState({\n isLoading: false\n });\n }\n }", "componentDidMount() {\n\t\tif (localStorage.getItem('jwtToken')) {\n\t\t\tthis.setState({ isPrivateNav: true });\n\t\t} else {\n\t\t\tthis.setState({ isPrivateNav: false });\n\t\t}\n\t}", "UNSAFE_componentWillMount() {\n let state = localStorage[\"appState\"];\n if (state) {\n let AppState = JSON.parse(state);\n this.setState({ isLoggedIn: AppState.isLoggedIn, user: AppState.user });\n }\n }", "componentDidMount() {\n this.userData = JSON.parse(sessionStorage.getItem('user'))\n if (sessionStorage.getItem('user')) {\n this.setState({\n Username : this.userData.Username,\n Fullname : this.userData.Fullname,\n Address : this.userData.Address,\n City : this.userData.City,\n Mobile : this.userData.Mobile,\n Email : this.userData.Email,\n Password : this.userData.Password\n })\n }\n // else { this.state = { Username : '', Email : '', Password : '' ,} }\n\n }", "componentWillMount(){\n if(window.sessionStorage.getItem(\"loggedIn\") != 1){\n alert(\"Not logged in\");\n this.setState({ redirect: '/' });\n }\n }", "componentDidMount() {\n window.scrollTo(0,0);\n authenticate();\n if (auth.authenticated) {\n this.setState({\n loggedIn : true\n })\n } else {\n this.setState({\n loggedIn : false\n })\n }\n }", "componentDidMount() {\n this.userData = JSON.parse(sessionStorage.getItem('user'))\n if (sessionStorage.getItem('user')) {\n this.setState({\n Username: this.userData.Username,\n // Email: this.userData.Email,\n Password: this.userData.Password\n })\n }\n // else { this.state = { Username : '', Email : '', Password : '' ,} }\n\n }", "componentDidMount() {\r\n fetch(\"http://localhost:3001/checkifloggedin\",\r\n {\r\n method: \"POST\",\r\n credentials: \"include\"\r\n })\r\n \r\n .then(response => response.json())\r\n .then(body => {\r\n if(body.isLoggedIn) {\r\n this.setState({ checkedIfLoggedIn: true, isLoggedIn: true, id: localStorage.getItem(\"id\")\r\n })\r\n } else {\r\n this.setState({ checkedIfLoggedIn: true, isLoggedIn: false });\r\n }\r\n });\r\n }", "componentWillMount() {\n if(!this.state.authenticated) {\n \n }\n }", "componentDidMount() {\n const loggedUserJSON = sessionStorage.getItem('loggedLohjanLuunkeraajaUser')\n if (loggedUserJSON) {\n const user = JSON.parse(loggedUserJSON)\n this.setState({ user })\n }\n }" ]
[ "0.8137776", "0.7863055", "0.77652735", "0.76302534", "0.7619947", "0.7585621", "0.7585155", "0.754558", "0.75434893", "0.75077903", "0.7450265", "0.739251", "0.7340621", "0.733691", "0.7334462", "0.73220026", "0.72790533", "0.72748995", "0.7248442", "0.7228316", "0.7182825", "0.7169905", "0.7165538", "0.7158213", "0.7143322", "0.7129546", "0.7123299", "0.71099246", "0.70986676", "0.7088221" ]
0.8776838
0
This render if statement asks if this.state.loggedIn is true or not if it is true, we'll return to the App component. If it isn't true then we'll be redirected to the Login component.
render() { let output = this.state.loggedIn ? <App /> : <Login />; return output; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "render() {\n if(this.state.isLoggedIn){\n return <HomePage/>\n }\n else{\n return <Login/>\n }\n }", "checkLoginState() {\n if (this.state.loggedIn === 1) return <HomePageRouter />;\n else return <AuthPageRouter />;\n }", "render() {\n if (this.props.loggedIn) {\n return <Redirect to=\"/dashboard\" />;\n }\n return (\n <div className=\"home\">\n <h2>Get started today</h2>\n <RegistrationForm />\n <Link to=\"/\">Login</Link>\n </div>\n );\n }", "render() {\n return (\n <main role=\"main\">\n {this.userSession.isUserSignedIn() ?\n <SignedIn />\n :\n <Landing />\n }\n </main>\n );\n }", "render(){\n \n // If we are logged in redirect straight to the user's dashboard\n if (this.props.loggedIn) {\n return <Redirect to=\"/dashboard\" />;\n }\n\n return (\n <div className=\"home\">\n <h2>Welcome to Noted</h2>\n <p>Learn a plethora of music notation symbols and how understanding them can improve your skills as a musician! Try it out!</p>\n <button className='demo' onClick={() => this.props.dispatch(login('demouser', 'password123'))}>Demo</button>\n <p className='divider'>... or make an account!</p>\n <RegistrationPage />\n </div>\n );\n }", "render() {\n if (this.isLoggedIn()) {\n return(\n <BrowserRouter>\n <div className= 'app'>\n <Navigation logoutHandler = {this.logout} />\n <Main />\n </div>\n </BrowserRouter>\n );\n } else {\n return(\n <div className= 'app'>\n <Login loginHandler = {this.login} />\n </div>);\n }\n }", "render() {\n if ( this.state.login === false && this.state.error === false ){\n return (\n\n <div className=\"login\">\n <form className=\"login__form\">\n <h1>Login</h1>\n <Input type=\"email\"\n class=\"input\"\n placeholder=\"Enter Email\"\n value={this.state.email}\n onChange={this._handleEmailInput}\n />\n\n <Input type=\"password\"\n class=\"input\"\n placeholder=\"Password\"\n value={this.state.password}\n onChange={this._handlePasswordInput}\n />\n <Button type=\"button\" text=\"Login\" onClick={this._handleLoginSubmit} />\n <Link to=\"/signup\" className=\"small\">No Account? SignUp</Link>\n </form>\n </div>\n // <Link to=\"/signup\">Sign Up</Link>\n // <Link to=\"/dashboard\">Log In</Link>\n\n );\n } else if (this.state.login === false && this.state.error === true ) {\n return (\n <div className=\"login\">\n <form className=\"login__form\">\n <h1>Login</h1>\n <p> Something went wrong, try again </p>\n <Input type=\"email\"\n class=\"input\"\n placeholder=\"Enter Email\"\n value={this.state.email}\n onChange={this._handleEmailInput}\n />\n\n <Input type=\"password\"\n class=\"input\"\n placeholder=\"Password\"\n value={this.state.password}\n onChange={this._handlePasswordInput}\n />\n <Button type=\"button\" text=\"Login\" onClick={this._handleLoginSubmit} />\n <Link to=\"/signup\" className=\"small\">No Account? SignUp</Link>\n </form>\n </div>\n )\n }\n \n \n else {\n return ( <Redirect to=\"/dashboard\" /> )\n }\n \n}", "render(){\n if (!this.loggedIn)\n return(\n <Router>\n <div className=\"App\">\n <TabContent />\n <Switch>\n {/*<Route path=\"/\" exact component={Login}/>*/}\n <Route path=\"/InventoryTable\" component={InventoryTable}/>\n <Route path=\"/Sales\" component={Sales}/>\n <Route path=\"/Production\" component={Production}/>\n <Route path=\"/EndOfDay\" component={EndOfDay}/>\n <Route path=\"/Admin\" component={Admin}/>\n </Switch>\n </div>\n </Router>\n );\n else {\n return(\n //login page\n <Login/>\n );\n }\n\n }", "function toRender(props) {\n if (loggedIn) {\n return <Redirect to='/' />;\n } else {\n return <Component {...props} />;\n }\n }", "render() {\n return (\n <div className=\"App\" id=\"App\">\n <SiteNav\n loggedIn={this.state.loggedIn}\n handleLogOut={this.handleLogOut}\n />\n <Router>\n <Container className=\"padded-top\">\n {!this.state.loggedIn ? (//dep[ending if the user loggs in display login page or user home.]\n <Route\n path=\"/\"\n exact\n component={() => <LoginPage handleLoggin={this.handleLogin} />}\n />\n ) : (\n <Route path=\"/\" exact component={() => <UserHome/>} />\n )}\n <Route path=\"/CreateAccount\" exact component={CreateAccount} />\n </Container>\n </Router>\n </div>\n );\n }", "function App() {\n const [isLoggedIn, setIsLoggedIn] = useState(false);\n return (\n <Router>\n <div className=\"container\">\n <Link to=\"/\">Home</Link>\n <Link to=\"/private\">Private</Link>\n\n <Switch>\n <Route exact path=\"/\">\n <h1>Home page, anyone is allowed here</h1>\n </Route>\n <Route path=\"/private\">\n {isLoggedIn ? (\n //\n <h1>Protected page</h1>\n ) : (\n //Redirect\n <Redirect to=\"/login\" />\n )}\n </Route>\n <Route path=\"/login\">\n <button className=\"btn\" onClick={() => setIsLoggedIn(true)}>\n Log in\n </button>\n </Route>\n </Switch>\n </div>\n </Router>\n );\n}", "render() {\n if (this.props.email !== undefined && this.props.email !== null) {\n return this._renderLoggedIn();\n } else if (this.props.isLoggingIn === true) {\n return this._renderLoggingIn();\n } else {\n return this._renderLoggedOut();\n }\n }", "render() {\n if (localStorage.getItem('isLoggedIn') !== \"true\") {\n return (\n <div className=\"main\">\n <h5 className=\"display-4 text-center\">Account Dashboard</h5>\n <hr></hr>\n <h1 className=\"display-9 text-center\">Not Logged In. Please log in to see the dashboard</h1>\n\n </div>\n )\n } else if (this.state.isAdmin === true) {\n return (\n <div className=\"main\">\n\n <Redirect to=\"/Admin\" />\n\n </div>\n )\n }\n else if (this.state.isEmployee === true) {\n return (\n <div className=\"main\">\n <Redirect to=\"/Employee\" />\n\n </div>\n )\n }\n else if (this.state.isCustomer === true) {\n return (\n <div className=\"main\">\n <Redirect to=\"/Customer\" />\n </div>\n )\n }\n else {\n\n //A VERY UNLIKELY SCENARIO - IN CASE user attempts to access a dashboard through illegal means.\n return (\n <div className=\"main\">\n <h5 className=\"display-4 text-center\">Account Dashboard</h5>\n <hr></hr>\n <h1 className=\"display-9 text-center\">No Account Defined. Please contact your local admin.</h1>\n\n </div>\n )\n }\n }", "render() {\n\n const redirect = () => <Redirect to=\"/\" />;\n \n if(!this.state.loggedIn) {\n\n return(\n <div className=\"d-flex align-items-center min-vh-100\">\n <div className=\"container\">\n <div className=\"row\">\n\n <NavBar />\n \n <Switch>\n <Route exact path=\"/\">\n <Login onLogin={this.handleLogin} />\n </Route>\n <Route path=\"/login\">\n <Login onLogin={this.handleLogin} />\n </Route>\n <Route path=\"/register\">\n <Register />\n </Route>\n <Route component={redirect} />\n </Switch>\n \n </div>\n </div>\n </div>\n );\n\n }\n\n if(!this.state.isLoadingDetails) {\n return(\n <Switch>\n <Route exact path=\"/\">\n <div className=\"d-flex align-items-center min-vh-100\">\n <Game playerDetails={this.state.playerDetails} onLogout={this.handleLogout} />\n </div>\n </Route>\n <Route component={redirect} />\n </Switch>\n );\n }\n else {\n return(\n <p>Loading...</p>\n );\n } \n \n }", "render() {\n return (\n <div className=\"col-3\">\n {/* Use conditional rendering to render a message \n and a sign in/sign out button here. If isLoggedIn\n is false, render a sign in message and button. If\n isLoggedIn is true, render a welcome message and\n a sign out button */}\n </div>\n )\n }", "render() {\n const isLoggedIn = this.state.isLoggedIn;\n let button;\n\n if (isLoggedIn) {\n button = <LogoutButton onClick={this.handleLogoutClick} />;\n } else {\n button = <LoginButton onClick={this.handleLoginClick} />;\n }\n // Depending on the state the button is in return a greeting or a login screen\n return (\n <div>\n <Greeting isLoggedIn={isLoggedIn} />\n {button}\n </div>\n );\n }", "render() {\n const { checkedSignIn, signedIn } = this.state;\n if(!checkedSignIn) {\n return null;\n }\n const RootLayout = createRootNavigator(signedIn);\n return (\n <RootLayout />\n );\n }", "render() {\n if (!this.state.redirect) {\n if (this.state.user === undefined) {\n return (\n <div><h1>Loading...</h1></div>\n )\n } else {\n return (\n <div>\n {this.props.children}\n </div>\n )\n }\n } else {\n return <Redirect to='/login' />\n }\n }", "render() {\n if (this.state.isLoggedIn) {\n return (\n <React.Fragment>\n <NavBar isUserLoggedIn={this.isUserLoggedIn}/>\n <ApplicationViews isUserLoggedIn={this.isUserLoggedIn}/>\n </React.Fragment>\n );\n } else {\n return (\n <React.Fragment>\n{/* Pass in the isUserLoggedFunction so it can be used by the child components of Authentication */}\n <Authentication isUserLoggedIn={this.isUserLoggedIn} />\n </React.Fragment>\n );\n }\n }", "render() {\n return (\n <div className=\"app\">\n {this.state.user ? (\n <Search logOut={this.logout} userEmail={this.state.email} />\n ) : (\n <Login\n logIn={this.login}\n guest={this.guest}\n howToggle={this.howToggle}\n show={this.state.show}\n whatToggle={this.whatToggle}\n showWhat={this.state.showWhat}\n />\n )}\n </div>\n );\n }", "function checkAuthentificationState(){\n //Check if user is authorized\n var isAuthorized = checkLoginState();\n //React\n if(isAuthorized){\n showLoggedInView();\n }else{\n showLoggedOutView();\n }\n}", "render() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t{this.state.is_logged_in && <div>Hello User</div>}\n\t\t\t\t{this.state.is_logged_in || <div>Guest</div>}\n\t\t\t</div>\n\t\t);\n\t}", "loginStatus() {\n if (\n localStorage.getItem(\"authoritySignedIn\") === \"true\" &&\n this.state.isSignedIn\n ) {\n switch (this.props.linkTo) {\n case \"/dashboard\":\n return (\n <div>\n <Dashboard authorityId={this.state.authorityId} />\n {this.navigationBar()}\n </div>\n );\n case \"/mapview\":\n return (\n <div>\n <MapRegionView authorityId={this.state.authorityId} />\n {this.navigationBar()}\n </div>\n );\n case \"/users\":\n return (\n <div>\n <Users authorityId={this.state.authorityId} />\n {this.navigationBar()}\n </div>\n );\n case \"/logout\":\n this.logout();\n break;\n case \"/profile\":\n return (\n <div>\n <Profile\n authorityId={this.state.authorityId}\n name={this.state.profileName}\n email={this.state.profileEmail}\n photoURL={this.state.profilePhotoURL}\n />\n {this.navigationBar()}\n </div>\n );\n case \"/\":\n return (\n <div>\n <Dashboard authorityId={this.state.authorityId} />\n {this.navigationBar()}\n </div>\n );\n default:\n return (\n <div>\n <Dashboard authorityId={this.state.authorityId} />\n {this.navigationBar()}\n </div>\n );\n }\n } else if (\n localStorage.getItem(\"authoritySignedIn\") === \"false\" &&\n this.state.isSignedIn\n ) {\n this.urlRedirect(HOST_NAME);\n } else {\n if (localStorage.getItem(\"authoritySignedIn\") !== \"true\") {\n return (\n <div>\n <div id=\"loginButton\" style={{ display: \"none\" }}>\n Login with Google\n </div>\n <SignUp />\n </div>\n );\n } else {\n return <div />;\n }\n }\n }", "renderSessionControl(){\n if (this.props.isLoggedIn) {\n return(\n <>\n <Link to=\"/blogs/new\"> New Post </Link><br/>\n <Link to=\"/logout\">Logout</Link>\n </>\n )\n } else {\n return(\n <>\n <Link to='/login'>Log In</Link><br/>\n </>\n )\n }\n }", "function toRender(props) {\n if (!loggedIn) {\n return <Login />;\n } else {\n return <Component {...props} />;\n }\n }", "render() {\n return (\n <div>\n <Header />\n <Switch>\n <Route exact path=\"/\" component={HomePage} />\n <Route path=\"/shop\" component={ShopPage} />\n <Route exact path=\"/checkout\" component={CheckoutPage} />\n <Route\n exact\n path=\"/signin\"\n render={() =>\n this.props.currentUser ? (\n <Redirect to=\"/\" />\n ) : (\n <SignInAndSignUpPage />\n )\n }\n />\n <Route component={this.NoMatch} />\n </Switch>\n </div>\n )\n }", "render() {\n \n return (\n <div className=\"Page\">\n {this.state.isLogIn && <LogInPage \n handleLogin={this.handleLogin} \n handleAdmin={this.handleAdmin}/>}\n <Header \n add={this.toggleInput} \n refresh={this.getData} \n isAdmin={this.state.isAdmin} \n handleLogin={this.handleLogin}\n handleAdmin={this.handleAdmin}/>\n <Sidebar \n logo={logo} \n links={links} />\n <MainTable isAdmin={this.state.isAdmin}/>\n </div>\n );\n }", "render() {\n const {loggedIn} = this.props;\n return (\n <div>\n <h3>Platforms&nbsp;\n {loggedIn &&\n <button\n className=\"btn btn-success\"\n onClick={this.redirectToCreatePage}>\n Add a Platform\n </button>\n }\n </h3>\n <hr/>\n\n {!loggedIn &&\n <section>\n <h4>You are not logged in. Visit the <Link to=\"/account\">Account Page</Link> to log in.</h4>\n </section>\n }\n\n {loggedIn &&\n <PlatformList platforms={this.props.platforms} />\n }\n </div>\n );\n }", "render() {\n\t\t\tif (this.props.authenticated) {\n\t\t\t\treturn <AppComponent {...this.props} />;\n\t\t\t}\n\t\t\treturn null;\n\t\t}", "render() {\r\n const { loading, redirect } = this.state;\r\n if (loading) {\r\n return null;\r\n }\r\n if (redirect) {\r\n // If the user is not authorised to access the requested page\r\n return <Redirect to=\"/login\" />; // The login page will be displayed\r\n }\r\n return (\r\n <>\r\n <ComponentToProtect {...this.props} />\r\n </>\r\n );\r\n }" ]
[ "0.7644102", "0.7482524", "0.7387048", "0.7373826", "0.7294971", "0.7215456", "0.7190083", "0.6951658", "0.695033", "0.6878216", "0.684731", "0.68447506", "0.6838123", "0.67867166", "0.6775981", "0.67657447", "0.6748171", "0.6745615", "0.6698352", "0.6674586", "0.66703814", "0.6667379", "0.66641444", "0.66140825", "0.65971076", "0.65886736", "0.65847045", "0.65616775", "0.6554653", "0.6538454" ]
0.7722254
0
GET Return all the customer users' userId, name, and email. URL /customers
function getCustomers(req, res) { var answer = []; User.find({}, function(err, users) { if (err) throw err; for(var i = 0; i<users.length; i++) { if(!users[i].admin) { answer.push({userId: users[i]._id, name: users[i].name, email: users[i].email}); } } return res.json(answer); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "list() {\n return this.iugu.makePagedRequest('GET', '/customers');\n }", "fetchSpecificCustomers(id) {\r\n return Api().get('/customers/' + id)\r\n }", "function getCustomerList() {\n\t// TODO: add logic to call backend system\n\n\n}", "function getCustomers() {\n console.log('8');\n $.get(\"/api/customers\", renderCustomerList);\n }", "function getCustomers(res, mysql, context, complete){\n mysql.pool.query(\"SELECT Customers.customerID as id, customerName, customerType, customerEmail FROM Customers\", function(error, results, fields){\n if(error){\n res.write(JSON.stringify(error));\n res.end();\n }\n context.customers = results;\n complete();\n });\n }", "function getCustomers() {\n CustomerService.getCustomers()\n .success(function(custs) {\n $scope.gridOpts.data = custs;\n })\n .error(function(error) {\n $scope.status = 'Unable to load customer data: ' + error.message;\n });\n }", "fetchCustomers() {\r\n return Api().get('/customers')\r\n }", "function getAllCustomers() {\n var customers = stripe.customers.list(function(err, customers) {\n // asynchronously called\n });\n\n return customers;\n}", "allUsers() {\r\n this.log(`Getting list of users...`);\r\n return this.context\r\n .retrieve(`\r\n SELECT emailAddress, password\r\n FROM Users\r\n `\r\n )\r\n }", "async getCustomer() {\n const customer = this.ctx.request.body;\n\n this.ctx.body = await this.service.customers.query(customer);\n }", "function listUsers() {\n const optionalArgs = {\n customer: 'my_customer',\n maxResults: 10,\n orderBy: 'email'\n };\n try {\n const response = AdminDirectory.Users.list(optionalArgs);\n const users = response.users;\n if (!users || users.length === 0) {\n console.log('No users found.');\n return;\n }\n // Print the list of user's full name and email\n console.log('Users:');\n for (const user of users) {\n console.log('%s (%s)', user.primaryEmail, user.name.fullName);\n }\n } catch (err) {\n // TODO (developer)- Handle exception from the Directory API\n console.log('Failed with error %s', err.message);\n }\n}", "function getAllCustomers() {\n return datacontext.get('Product/GetAllCustomers');\n }", "function customerList() {\n $.ajax({\n url: '/api/Customers/getCustomers',\n type: 'GET',\n dataType: 'json',\n success: function (customers) {\n customerListSuccess(customers);\n },\n error: function (request, message, error) {\n handleException(request, message, error);\n }\n });\n}", "function getCustomers() {\n var pagina = 'ProjectPlans/listCustomers';\n var par = `[{\"prm\":\"\"}]`;\n var tipo = 'json';\n var selector = putCustomers;\n fillField(pagina, par, tipo, selector);\n}", "getByemail(customers_email) {\n return http.get(`/customerbyemail/${customers_email}`);\n }", "function getCustomerById(req, res){\n var customerId = req.params.idCustomer;\n var getCustomerByIdQuery = \"SELECT * FROM Customer\\n\"+\n \"WHERE idCustomer = \"+customerId;\n\n connection().query(getCustomerByIdQuery, function(error, result, fields){\n if(error){\n console.log(\"Hubo un error al obtener información del cliente \"+customerId, error.message);\n return res.status(500).send(\"Hubo un error en la consulta getCustomerById\");\n }\n \n if(result.length == 0){\n return res.status(404).json(\"No existe cliente con el identificador \"+customerId);\n }\n \n res.json(result);\n });\n}", "async getAllUsers(){\n data = {\n URI: `${ACCOUNTS}`,\n method: 'GET'\n }\n return await this.sendRequest(data)\n }", "function getCustomers()\n {\n var url = \"http://localhost:8080/Customer_Restful/webresources/entities.customer\";\n //console.log('Start!');\n $.ajax\n ({\n type: 'GET', //Request Data Type\n contentType: 'application/json', //Request Content Type\n url: url, //RESTful Service URL\n dataType: \"json\", //Response Data Type\n \n success: function(data)\n {\n document.write(\"<a href='search.html'>Search Criteria</a>\");\n document.writeln(\"<h2>Javascript client for CustomerDB Restful Web Service</h2><br>\");\n document.writeln(\"<h4>Resources for CustoermDBRest:</h4>\");\n document.writeln(\"<h5>Customers</h5>\");\n document.writeln(\"<table style='border: 1px solid black;'>\");\n document.writeln(\"<tr>\");\n document.write(\"<th style='border: 1px solid black;'>custID</th>\");\n document.write(\"<th style='border: 1px solid black;'>dis-code</th>\");\n document.write(\"<th style='border: 1px solid black;'>name</th>\");\n document.write(\"<th style='border: 1px solid black;'>address</th>\");\n document.write(\"<th style='border: 1px solid black;'>city</th>\");\n document.write(\"<th style='border: 1px solid black;'>state</th>\");\n document.write(\"<th style='border: 1px solid black;'>zip</th>\");\n document.write(\"<th style='border: 1px solid black;'>phone</th>\");\n document.write(\"<th style='border: 1px solid black;'>fax</th>\");\n document.write(\"<th style='border: 1px solid black;'>email</th>\");\n document.write(\"</tr>\");\n outputCustRowsHtml(data);\n document.write(\"</table>\");\n discountwithCustId(data);\n getDiscountInfo();\n\n }\n });\n }", "function getUsers(request, response) {\n User.find({}, function(err, users) {\n if(err) {\n response.status(500).json({message: \"No users were found.\"});\n }\n if(!users) {\n response.status(404).json({message: \"No users were found.\"});\n }\n var userList = [];\n users.forEach(function(element) {\n userList.push({name: element.fullName, userId: element.userId});\n })\n\n response.status(200).send(userList);\n })\n}", "function getCustomer(id) {\n return $http.get(urlBase + '/' + id);\n }", "function getUsers(req, res) {\r\n User.getUsers((err, users) => {\r\n if (err) {\r\n res.status(500).send({ message: 'Error al obtener los usuarios' });\r\n } else {\r\n res.status(200).send({ users });\r\n }\r\n });\r\n}", "function getUsers(req, res) {\n console.log('GET de todos los usuarios'.blue);\n UserSchema.find({}, (err, users) => {\n if (err) return res.status(500).send(err);\n if (!users) return res.status(404).send('No hay usuarios registrados');\n\n return res.status(200).send({ users });\n });\n}", "function getAllUsers(callback) {\n requester.get('user', '', 'kinvey')\n .then(callback)\n}", "function allCustomers(req, res){\n var getAllCustomersQuery = \"SELECT * FROM Customer\\n\"+\n \"WHERE active = 'Y'\\n\"+\n \"order by custName\"; \n connection().query(getAllCustomersQuery, function(error, result, fields){\n if(error){\n console.log(\"Hubo un error al obtener la lista de clientes\", error.message);\n return res.status(404).send(\"Hubo un error en la consulta allCustomers\");\n }\n\n if(result.length == 0){\n return res.status(404).json(\"No se encontraron clientes registrados\");\n }\n\n var response = {\n 'clientes': result\n };\n \n res.send(response);\n });\n}", "function getUsers(req, res) {\n User.find({}, function (err, users) {\n if (err) return res.status(500).send(\"There was a problem finding the users.\");\n res.status(200).send(users);\n });\n}", "function getAllUsers(req, res, next) {\n usersDetails(req, res).then((result) => {\n return res.status(200).json(result);\n }).catch((err) => {\n next(err);\n });\n}", "function getCustomers(contacts) {\n\t\tcontactsId = contacts || '';\n\t\tif (contactsId) {\n\t\t\tcontactsId = '/?contacts_id=' + contactsId;\n\t\t}\n\t\t$.get('/api/contacts' + contactsId, function(data) {\n\t\t\tconsole.log('customers', data);\n\t\t\tcustomers = data;\n\t\t\tif (!customers || !customers.length) {\n\t\t\t\tdisplayEmpty(contacts);\n\t\t\t} else {\n\t\t\t\tinitializeRows();\n\t\t\t}\n\t\t});\n\t}", "getCustomersThisCompany(params) {\n // Don't get more than once\n if (this.displayData.customers.length) {\n return new Promise(resolve => resolve());\n }\n return Resource.get(this).resource('Employee:getAllCustomersThisCompany', params)\n .then(res => {\n this.displayData.customers = res.filter(customer => customer.firstName !== '__default__');\n });\n }", "function GetUsers() {\n UserApi.getUser().then(function (response) {\n $scope.user = response.data;\n }), function () {\n aler(\"Unable to load users info\");\n }\n }", "static async getUsers() {\n return await this.request('users/', 'get');\n }" ]
[ "0.7320257", "0.69984657", "0.69642913", "0.69195944", "0.6819917", "0.6808778", "0.67777574", "0.6683724", "0.6607724", "0.6588683", "0.65830487", "0.65676874", "0.655043", "0.65014905", "0.6461242", "0.6438895", "0.6412948", "0.6408919", "0.6408402", "0.6404305", "0.63856924", "0.63846135", "0.6378058", "0.63626975", "0.63558394", "0.632311", "0.6322123", "0.6318774", "0.6312544", "0.6307763" ]
0.72981346
1
GET Return the order status of the specified order. URL /status?orderID=584342b42f98df8965985b69
function getOrderStatus(req, res) { if(req.query.orderID === undefined) { return res.send("Error: orderID undefined"); } Order.findOne({_id: req.query.orderID}, function(err, order) { if (err) throw err; return res.send(order.status); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getOrderStatus(orderId) {\n return __awaiter(this, void 0, void 0, function* () {\n let response = yield request({\n method: 'get',\n json: true,\n uri: `${this.EFoodAPIOrigin}/api/v1/order/status/${orderId}/`,\n headers: { 'x-core-session-id': this.store.sessionId }\n });\n return response.data;\n });\n }", "async getOrderStatus(orderId) {\n try {\n const response = await fetch(`/orders/${orderId}`);\n return await response.json();\n } catch (err) {\n return {error: err};\n }\n }", "function getStatus() {\n\tapi({ data: \"cmd=getstatus\" },syncStatus);\n}", "function get_status_detail(order_id)\n{\n window.location = '/order/status_details/'+order_id;\n}", "function getActiveOrders(req, res) {\n Order.find({status: { $in: activeStatus}}, function(err, orders) {\n if (err) throw err;\n return res.json(orders);\n });\n}", "status(transactionId) {\n this.apiUrl = this.parent.apiConfig.getCoreApiBaseUrl() + '/' + transactionId + '/status';\n return this.parent.httpClient.request({\n requestUrl: this.apiUrl,\n httpMethod: 'get',\n serverKey: this.parent.apiConfig.get().serverKey,\n requestPayload: null\n });\n }", "function getUserOrderStatus(){\n TiviService.getUserOrderStatus().success(function(res){\n console.log(res)\n }).error(function(err, stt, res){\n if (err.detail){\n toastr.error(err.detail);\n }\n for( var key in err){\n var x = 'err.'+key;\n toastr.error(key.toUpperCase()+\": \"+eval(x)[0]);\n }\n });\n }", "function getOrderType(req, res) {\n orderType.find({companyId: req.body.companyId, deleted: false}, function(err, orderTypelist) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, message: err});\n } else {\n if (req.body.statusName) {\n query = {companyId: req.body.companyId, statusName: req.body.statusName};\n }\n else {\n query = {companyId: req.body.companyId};\n }\n status.findOne(query, function(err, doc) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, message: Constant.INTERNAL_ERROR});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, data: orderTypelist, statusNameId: doc._id});\n }\n });\n }\n }).sort({orderTypeName: 1}).collation({locale: \"en\"});\n}", "function getStatus() {\n return status;\n }", "function updateOrderStatus(req, res) { \n if(req.body.orderID === undefined) {\n return res.send(\"Error: no orderID specified\");\n }\n Order.findOne({_id: req.body.orderID}, function(err, order) {\n if (err) throw err;\n if(order === null){\n return res.send(\"Error: no such order exists\");\n }\n order.status = req.body.status;\n order.save(function(err, order) {\n if (err) throw err;\n return res.json(\"Success\");\n });\n });\n}", "function getTransactionStatus(typeGrp,type,statusGrp,status) {\n\t\t\tvar params = 'typeGrp=' + typeGrp + '&type=' + type + '&statusGrp=' + statusGrp + '&status=' + status;\n//\t\t\tconsole.log(params);\t\t\t\n\t\t\treturn Utils.requestAPI('v5a/admin/availableStatus?_method=GET&', params);\n\t\t}", "function getStatus() {\n // TODO: perhaps remove this if no other status added\n return status;\n }", "function getRetweetedStatusByStatus(statusID) {\n\n}", "getPaylikeOrderStatuses() {\n /** Get order status for capture. */\n cy.get('#PAYLIKE_ORDER_STATUS > option[selected=selected]').then($captureStatus => {\n this.OrderStatusForCapture = $captureStatus.text();\n });\n }", "status() {\r\n return this.request('GET', 'status/config');\r\n }", "statusFlags() {\r\n return this.request('GET', 'status/flags');\r\n }", "function checkOrderStatus(orderIdentifier) {\n setCheckStatus(CONFIRMATION_STATUS.PENDING);\n let now = new Date();\n\n // If timeout is exceeded, stop\n if((now - firstCheck) > MAX_CONFIRMATION_WAIT_TIME_MILLIS) {\n stopCheckingInFuture();\n setCheckStatus(CONFIRMATION_STATUS.TIMEOUT);\n return;\n }\n\n // Otherwise status is retrieved from server\n getStatus(orderIdentifier);\n }", "get status() {\n\t\treturn this._status;\n\t}", "function getOrderStatusTitle({ status }) {\n return utils.getOrderStatusTitle(status);\n}", "function queryStatus(req, res){\n var requestID = req.params.requestID;\n\tif (!validObjectID(requestID)) {\n\t\tres.send400('Invalid request ID format.');\n\t\treturn;\n\t}\n\tRequest.findById(requestID, function (error, result){\n\t\tif (error) {\n\t\t\tres.send500('There was an error querying the request status.');\n\t\t} else if (!result) {\n\t\t\tres.send404('No request found.');\n\t\t} else {\n\t\t\tres.send(cleanUpGetResponse(result));\n\t\t}\n\t});\n}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "get status () {\n\t\treturn this._status;\n\t}", "function renderOrderStatus (order) {\n return new Promise((resolve, reject) => {\n const idArr = [\n 'in_amount_remaining',\n 'out_amount',\n 'status',\n 'expires_at',\n 'provider_order_id',\n 'in_address',\n 'in_amount'\n ]\n\n const test = document.getElementById('exchangePage')\n if (!(test == null)) {\n idArr.forEach((item, index) => {\n if (item == 'in_address') {\n document.getElementById('receiving_subaddress').innerHTML = order[item]\n } else {\n document.getElementById(item).innerHTML = order[item]\n }\n })\n }\n resolve()\n })\n}" ]
[ "0.77244294", "0.70756054", "0.6543379", "0.65101004", "0.6164444", "0.6100166", "0.6081409", "0.60803556", "0.6078036", "0.6032109", "0.5950874", "0.5931992", "0.583974", "0.5837124", "0.58181816", "0.5800978", "0.57797563", "0.5718791", "0.569007", "0.56722325", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.5647904", "0.56449467" ]
0.8065022
0
Admin requests GET Return all customer orders that have been placed but not delivered. URL /activeOrders
function getActiveOrders(req, res) { Order.find({status: { $in: activeStatus}}, function(err, orders) { if (err) throw err; return res.json(orders); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function adminOrdersFetchCall() {\n return request('get', urls.ADMIN_ORDER_URL);\n}", "static async listCurrentOrders() {\n const query = `\n SELECT order.id AS \"orId\",\n order.customer_id AS \"cusId\",\n order.delivery_address AS \"addy\"\n FROM orders\n WHERE orders.completed = True\n `\n const result = await db.query(query)\n return result.rows\n }", "async function allOrders(req,res){\n if (req.user.user=='admin'){\n const orders = await OrderModel.find({order_made_by:'dealer'});\n return res.status(200).json({ orders, message: \"All Orders..\" })\n }\n else {\n return res.status(401).json({ message: \"Only Admin can access. Sorry!\" });\n }\n}", "async get_orders(req, res) {\n try {\n const orders = await Order.find();\n res.status(200).json({\n type: \"success\",\n orders\n })\n } catch (err) {\n res.status(500).json({\n type: \"error\",\n message: \"Something went wrong please try again\",\n err\n })\n }\n }", "static async getOpenOrders() {\n try {\n return await shopdb.po.findAll({ where: {status: { [Op.ne]: \"CLOSED\"} } });\n } catch (error) {\n throw error;\n }\n }", "getAllOrders() {\n let dataURL = `${_environments_environment__WEBPACK_IMPORTED_MODULE_1__[\"environment\"].apiURL}/order/all`;\n return this.httpClient.get(dataURL).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"retry\"])(1), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"catchError\"])(this.handleError));\n }", "_loadCustomerOrders() {\n const customerId = this.customerId;\n\n this.customerRenderer.showLoadingOrders();\n $.get(this.router.generate('admin_customers_orders', {customerId})).then((response) => {\n this.customerRenderer.renderOrders(response.orders);\n }).catch((e) => {\n showErrorMessage(e.responseJSON.message);\n });\n }", "function list(req, res, next) {\n res.status(200).json({ data: orders });\n}", "myOrders (options) {\n return api('GET', helpers.appendQuery(`/order/self`, options.queryParams), options)\n }", "function list(req, res, next){\n res.json({data: orders})\n}", "function list(req, res) {\n res.json({ data: orders });\n}", "listOrders(context, params) {\n return this.$axios\n .get(`/orders?${querystring.stringify(params)}`)\n .then(({ data }) => data)\n .catch(this.$catch);\n }", "function getOrdersAwaitingApproval() {\n var criteria = {Type: \"Standard\", Status: \"AwaitingApproval\", DisplayName: \"Awaiting Approval\", LastN: 0, OrderID: null};\n $scope.orderLoadingIndicator = true;\n OrderSearch.search(criteria, function(list, count) {\n $scope.orderLoadingIndicator = true;\n $scope.orders = list;\n $scope.settings.listCount = count;\n $scope.showNoResults = list.length == 0;\n $scope.orderLoadingIndicator = false;\n }, $scope.settings.currentPage, $scope.settings.pageSize);\n }", "function getCustomers() {\n console.log('8');\n $.get(\"/api/customers\", renderCustomerList);\n }", "function getOrdersByCustomers(cust) {\n $.ajax({\n url: \"/Customer/Orders/\" + cust.CustomerId,\n type:\"GET\"\n }).done(function (resp) {\n self.Orders(resp);\n }).error(function (err) {\n self.ErrorMessage(\"Error! \" + err.status);\n });\n }", "function getCustomerList() {\n\t// TODO: add logic to call backend system\n\n\n}", "async list(req, res) {\n try {\n const orders = await Orderservice.findAll({\n attributes: [\n 'id',\n 'client_id',\n 'is_package',\n 'services',\n 'situation',\n 'amount',\n 'date_order',\n ],\n include: [{ model: Client, as: 'client', attributes: ['name'] }],\n });\n return res.json(orders);\n } catch (error) {\n return res.status(401).json({ error: 'Does not exist order' });\n }\n }", "fetchOpenOrders() {\n if ( !this._apikey || !this._ajax ) return;\n\n this._ajax.get( this.getSignedUrl( '/v3/openOrders' ), {\n type: 'json',\n headers: { 'X-MBX-APIKEY': this._apikey },\n\n success: ( xhr, status, response ) => {\n response.forEach( o => this.emit( 'user_order', this.parseOrderData( o ) ) );\n this.emit( 'user_data', true );\n },\n error: ( xhr, status, error ) => {\n this.emit( 'user_fail', error );\n }\n });\n }", "function getOrders() {\n return getItem('orders');\n}", "getOpenOrders (){\n let params = {\n // 'account-id': accountId,\n size: 500\n }\n\n params = this.auth.addSignature(cons.AccountAPI + cons.OpenOrders,\n cons.GET,\n params)\n\n return from(rest.get(cons.AccountAPI + cons.OpenOrders, params)).pipe(\n map(data => data.data),\n flatMap(datas => from(datas)),\n map(data => {\n data['order-id'] = data.id\n Reflect.deleteProperty(data, 'id')\n data['order-amount'] = data.amount\n Reflect.deleteProperty(data, 'amount')\n data['order-state'] = data.state\n Reflect.deleteProperty(data, 'state')\n data['order-type'] = data.type\n Reflect.deleteProperty(data, 'type')\n data['order-source'] = data.source\n Reflect.deleteProperty(data, 'source')\n\n return data\n }),\n toArray(),\n ).toPromise()\n }", "viewAllOrders() {\n this.isViewAllOrders = true;\n this.isViewAllUsers = false;\n this.isViewAllMessages = false;\n this.viewOrders = false;\n this.isAddNewProduct = false;\n this.orderService.getAllOrders().subscribe(orders => {\n this.allOrders = orders;\n console.log(this.allOrders);\n }, err => {\n console.log(err);\n });\n }", "fetchOrdersList(user_id) {\r\n return axios.get(USER_API_BASE_URL + '/orders/' + user_id);\r\n }", "getOrderList() {\n return fetch('/api/orders/getMyOrders', {headers: {'authorization': localStorage.getItem('authorization')}}).then(function (response) {\n return response.json();\n }).then(function (result) {\n return result;\n }).catch(() => {\n NotificationManager.error(\"Ошибка\", 'Попробуйте позже');\n });\n }", "async bringOrders(req, res) {\n try {\n const orders = await Order.find();\n res\n .status(200)\n .json(orders);\n } catch (error) {\n res\n .status(400)\n .json({\n message: err\n });\n }\n\n }", "orders(page = 1) {\n if(typeof page !== 'number') throw new TypeError(\"Parameter 'page' must be of type Number\")\n return this.#request(`Orders?page=${page}`, 'GET');\n }", "function getAllMyOrders(req, res) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // const orderid = req.params.id\n const cusid = req.body; // in a hidden field pass this.Customer.getId\n database_1.con.query('SELECT * from orders WHERE cus_id = ?', [cusid], (err, result) => {\n if (err) {\n res.status(400).send(err);\n return;\n }\n if (true)\n return res.json(result);\n else\n res.json({});\n });\n }\n catch (e) {\n console.log(e);\n }\n });\n}", "async getOrders(){\n return await fetch(ORDER_API_BASE_URI+\"/\",{\n method:'GET',\n }).then(response =>{\n return response.json();\n }).catch(reason => {\n return reason;\n })\n\n }", "listCustomersWithOrders(req, res){\n return Customer\n .findAll({\n // include:[{\n // model: Order,\n // as: 'orders',\n // }],\n include:[{all:true}]\n })\n .then(customersWithOrders => res.status(200).send(customersWithOrders))\n .catch(error => res.status(400).send(error));\n }", "allOrders() {\n return Order.find({member_id: Meteor.userId()});\n }", "function findAllOrders () {\n console.log ('find all orders');\n $.ajax ({\n type: 'GET',\n url: rootURL + \"/orders\",\n dataType: \"json\", // data type of response\n success: renderTableData,\n error: function (data, jqXHR, textStatus, errorThrown) {\n console.log (\"failed\", data);\n }\n });\n}" ]
[ "0.6732341", "0.6476649", "0.6447403", "0.6374412", "0.63644636", "0.63600934", "0.63565886", "0.6307102", "0.62942594", "0.6257828", "0.621339", "0.6211291", "0.61896956", "0.6077949", "0.6066741", "0.60649157", "0.60630685", "0.60585505", "0.6005015", "0.59920233", "0.59844023", "0.5981062", "0.59547305", "0.59256226", "0.5913607", "0.58976585", "0.5859714", "0.58434594", "0.5826485", "0.5825202" ]
0.7574684
0
POST Store the new order status for a specific order. URL /orderStatus
function updateOrderStatus(req, res) { if(req.body.orderID === undefined) { return res.send("Error: no orderID specified"); } Order.findOne({_id: req.body.orderID}, function(err, order) { if (err) throw err; if(order === null){ return res.send("Error: no such order exists"); } order.status = req.body.status; order.save(function(err, order) { if (err) throw err; return res.json("Success"); }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "placeOrder() {\n // add item to statuses and store as status \"in progress\"\n console.log(\"Your order is ready.\");\n }", "savePurchaseOrder(purchaseOrder) {\n\n purchaseOrder.status = PURCHASE_ORDER_STATUS_IN_PROGRESS;\n this.updatePurchaseOrder(purchaseOrder);\n\n }", "function updatingOrderStatus(req, res, next) {\n const acceptedStatuses = [\n \"pending\",\n \"preparing\",\n \"out-for-delivery\",\n null,\n \"\",\n ];\n\n const {\n data: { status },\n } = req.body;\n\n if (!status || status === \"\") {\n next({\n status: 400,\n message: `Order must have a status of pending, preparing, out-for-delivery, delivered`,\n });\n } else if (status === \"delivered\") {\n next({\n status: 400,\n message: `A delivered order cannot be changed`,\n });\n } else if (!acceptedStatuses.includes(status)) {\n next({\n status: 400,\n message: `status ${status} is invalid`,\n });\n } else if (acceptedStatuses.includes(status)) {\n return next();\n }\n}", "async function saveOrder(req, res) {}", "getOrderStatus(orderId) {\n return __awaiter(this, void 0, void 0, function* () {\n let response = yield request({\n method: 'get',\n json: true,\n uri: `${this.EFoodAPIOrigin}/api/v1/order/status/${orderId}/`,\n headers: { 'x-core-session-id': this.store.sessionId }\n });\n return response.data;\n });\n }", "function confirmOrder() {\n const orderId = sessionStorage.getItem(\"orderId\");\n const dataToSend = JSON.stringify({\n orderId: orderId,\n newOrderStatus: \"READY_TO_CONFIRM\"\n });\n post(\"/api/authTable/changeOrderStatus\", dataToSend, function (data) {\n if (data === \"success\") {\n window.location.replace(\"/customer/basket.html\");\n }\n });\n}", "createOrder({username, amount, body={},\n order_sn=`D${dayjs().format('YYYYMMDDHHmmss')}`,\n status='created'}) {\n const pathname = '/api/orders/';\n body = JSON.stringify(body);\n return this.requestJSON({pathname, method: 'POST',\n form: {username, amount, body, order_sn, status}});\n }", "function orderStatusIsValid(req, res, next) {\n const { data: order } = req.body;\n const existingOrder = res.locals.order;\n\n if (!order.status || order.status === \"invalid\") {\n next({\n status: 400,\n message:\n \"Order must have a status of pending, preparing, out-for-delivery, delivered\",\n });\n }\n if (existingOrder.status === \"delivered\") {\n next({ status: 400, message: \"A delivered order cannot be changed\" });\n }\n\n return next();\n}", "function get_status_detail(order_id)\n{\n window.location = '/order/status_details/'+order_id;\n}", "submitPurchaseOrder(purchaseOrder) {\n purchaseOrder.status = PURCHASE_ORDER_STATUS_SUBMITTED;\n this.updatePurchaseOrder(purchaseOrder);\n }", "async saveStatus(status) {\n const db = FirebaseLib.FIRESTORE_DB;\n try {\n const ref = db.collection(config.DBPaths.HISTORY).doc();\n const now = firebase.firestore.Timestamp.now();\n await ref.set({value: status, startedAt: now});\n this._checkNext(status);\n } catch (err) {\n console.error(\"Unable to save the status in the DB\", err);\n // TODO: saveStatus --> Error\n }\n }", "async function updateOrderStatus(ordernumber, orderstatus) {\n let queryText;\n let queryValues;\n\n if (orderstatus === 'delivered') {\n queryText = `\n update \n orders\n set\n order_status = $2,\n customer_name = $3,\n customer_phone = $4\n where\n order_number = $1\n returning\n *\n `;\n queryValues = [ordernumber, orderstatus, '', ''];\n } else {\n queryText = `\n update \n orders\n set\n\t order_status = $2\n where\n order_number = $1\n returning\n *\n `;\n\n queryValues = [ordernumber, orderstatus];\n }\n\n const { rows } = await pool.query(queryText, queryValues);\n return rows[0];\n}", "static async addOrder(orderDetails) {\r\n try {\r\n await OrderValidator.validCheck(orderDetails);\r\n await OrderValidator.isValidId(orderDetails);\r\n const product = await ProductDAO.findOne(orderDetails.productId);\r\n orderDetails.totalAmount = orderDetails.qty * product.price;\r\n orderDetails.status = \"ORDERED\";\r\n orderDetails.created_date = new Date();\r\n orderDetails.modified_date = new Date();\r\n orderDetails.created_by = orderDetails.userId;\r\n orderDetails.modified_by = orderDetails.userId;\r\n await OrderValidator.toCheckWalletBalance(orderDetails);\r\n console.log(\"orderDetails\", orderDetails);\r\n await OrderDAO.save(orderDetails);\r\n return \"Product Ordered sucessfully\";\r\n } catch (err) {\r\n throw err;\r\n }\r\n }", "async function createOrderHistory(postedOrder, order_status, rejected_reason) {\n const {\n chain_id,\n store_id,\n order_number,\n file_name,\n test_mode,\n order_lines,\n } = postedOrder;\n\n const { rows } = await pool.query(\n `\n insert into\n orders_process_finished\n (chain_id,\n store_id,\n order_number,\n file_name,\n test_mode,\n order_lines, \n order_status, \n rejected_reason\n )\n values\n\t ($1, $2, $3, $4, $5, $6, $7, $8)\n returning\n *\n `,\n [\n chain_id,\n store_id,\n order_number,\n file_name,\n test_mode,\n JSON.stringify(order_lines),\n order_status,\n rejected_reason,\n ]\n );\n return rows[0];\n}", "static async changeOrderStatus(orderId, userId, status) {\r\n try {\r\n // await OrderValidator.statusValidCheck(orderId, status);\r\n await OrderValidator.isValidForDelivery(orderId, status);\r\n // await OrderValidator.toCheckValidOrderId(orderId);\r\n var result = await OrderDAO.findOneAndUpdate(orderId, status, userId);\r\n return result;\r\n } catch (err) {\r\n console.log(err.message);\r\n throw err;\r\n }\r\n }", "function validateStatus(req, res, next){\n const {data: {status}={}}= req.body;\n if(!status || !status.length)\n return next({\n status: 400, \n message: \"Order must have a status of pending, preparing, out-for-delivery, delivered\"\n })\n if(status===\"delivered\"){\n next({\n status: 400, \n message: \"A delivered order cannot be changed\"\n })\n }\n if(status===\"invalid\"){\n next({\n status: 400, \n message: \"An order with invalid status cannot be changed\"\n })\n }\n next();\n }", "function flightStatus(status) {\n ticket[\"status\"] = status\n}", "function create(req, res, next) {\n const { data: order = {} } = req.body;\n\n const newOrder = {\n id: nextId(),\n deliverTo: order.deliverTo,\n mobileNumber: order.mobileNumber,\n status: order.status,\n dishes: order.dishes,\n };\n //add to orders list\n orders.push(newOrder);\n\n res.status(201).json({ data: newOrder });\n}", "async createOrder(req, res) {\n const body = req.body;\n\n try {\n\n const createdOrder = await Order.create(body);\n res\n .status(201)\n .json(createdOrder);\n } catch (err) {\n res\n .status(500)\n .json({\n message: err\n });\n }\n }", "function getOrderStatus(req, res) {\n if(req.query.orderID === undefined) {\n return res.send(\"Error: orderID undefined\");\n } \n Order.findOne({_id: req.query.orderID}, function(err, order) {\n if (err) throw err;\n return res.send(order.status);\n });\n}", "async create() {\n let api = this.app.service('status');\n let record = {\n uuid: this.uuid,\n flavor: this.options.flavor,\n timezone: this.getTimezone(),\n };\n return api.create(record, {\n })\n .then((res) => {\n logger.info('Created a Status record with server side ID %d', res.id);\n return true;\n })\n .catch((err) => {\n /* 400 errors are most likely attempts to recreate the same Status for\n * this instance.\n *\n * We need a better way to run a HEAD request to check before POSTing a\n * new status, but it's unclear whether that's supported in feathersjs\n * or not\n */\n if (err.code != 400) {\n logger.error('Failed to create a Status record', err);\n } else {\n logger.debug('Status record not changed');\n }\n return false;\n });\n }", "constructor() { \n \n OrderStatus.initialize(this);\n }", "function updateOrderStatus(orderID){\n Order.collection.updateOne(//Else update quantity\n {_id: mongoose.Types.ObjectId(orderID)},\n {$set:{orderStatus: \"Delivered\"}}\n );\n}", "setRefundStatus(orderID, status){\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tstatus=Number(status);\n if(isNaN(status)){\n reject(\"ERROR: Inputted value is NaN!\");\n }\n console.log(\"Is a number\");\n\t\t\tvar connection = mysql.createConnection({host:this.host, user:this.user, password: this.password, port: this.port});\n\t\t\tconnection.connect(function(err){\n\t\t\t\tif(err) reject(err);\n\t\t\t\tconnection.query(`select * from snackpacks.refunds where orderID=${orderID}`, function(err, foundOrder, fields){\n\t\t\t\t\t// console.log(foundOrder);\n\t\t\t\t\tif(err) reject(err);\n\t\t\t\t\tif(foundOrder.length > 0){\n\t\t\t\t\t\tconnection.query(`update snackpacks.refunds set status=${status} where orderID=${orderID}`, function(err, result, fields){\n\t\t\t\t\t\t\tif(err) reject(err);\n\t\t\t\t\t\t\tconnection.end(function(err){\n\t\t\t\t\t\t\t\tif(err) reject(err);\n\t\t\t\t\t\t\t\tresolve(true);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}else{\n\t\t\t\t\t\tconnection.end(function(err){\n\t\t\t\t\t\t\tif(err) reject(err);\n\t\t\t\t\t\t\treject(\"ERROR: ORDERID NOT FOUND\");\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}", "function changeOrderStatusRequest(order, elem){\n // Initialize new request\n const url = window.location.origin + '/shopping/api/chage-status';\n const data = new FormData();\n data.append('order', order);\n const loader = createLoaderStatus();\n const statusElem = elem.cloneNode(true);\n \n elem.parentNode.replaceChild(loader, elem);\n \n fetch(url,{\n method: 'POST',\n body: data,\n headers: {\n 'X-CSRFToken': Cookies.get('csrftoken'),\n }\n }).then(res => res.json())\n .then(data => { \n if (data.success){\n console.log('Change Status Order Request Success.');\n let prev_status = parseInt(data['prev_status']);\n let new_status = parseInt(data['new_status']);\n loader.parentNode.replaceChild(statusElem, loader);\n changeOrderStatus(statusElem, prev_status, new_status);\n\n } else {\n loader.parentNode.replaceChild(statusElem, loader);\n console.error(data.error);\n console.log(data.message);\n }\n }).catch(console.error);\n\n return false;\n}", "function create(req, res) {\n const { data: { deliverTo, mobileNumber, dishes } = {} } = req.body;\n const newOrder = {\n id: nextId(),\n deliverTo: deliverTo,\n mobileNumber: mobileNumber,\n status: \"pending\",\n dishes: dishes,\n }\n orders.push(newOrder);\n res.status(201).json({ data: newOrder });\n}", "function updateStatus(newStatus) {\n console.log(\"PX: UPDATE STATUS:\" + newStatus + \"\\n\");\n }", "function change_status(){\n //get current post status and ID, set variable with opposit status\n status = $(this).text();\n id = $(this).val();\n\n if (status == \"Active\") {\n new_status = \"Disabled\"\n } else {\n new_status = \"Active\"\n };\n\n //make ajax post request, reload page when received confirmation\n $.ajax({\n type: \"POST\",\n url: \"/change_status\",\n dataType: \"json\",\n data: {\"status\": new_status, \"id\": id},\n success: function(data) {\n console.log(data.result);\n location.reload();\n }\n });\n}", "function updateOrder(Order) {\n $.ajax({\n method: \"PUT\",\n url: \"/api/orders\",\n data: Order\n })\n .then(function () {\n console.log(\"order updated\")\n });\n }", "async update(req, res){\n const { id , status } = req.body;\n await Order.findByIdAndUpdate(id, {status : status });\n\n }" ]
[ "0.65965843", "0.63118184", "0.6147358", "0.59851485", "0.59711236", "0.59115696", "0.5888942", "0.57751507", "0.5727981", "0.5726496", "0.5698549", "0.5656904", "0.5646944", "0.5643262", "0.55878913", "0.5584915", "0.5542042", "0.55406237", "0.5510089", "0.5474984", "0.54523134", "0.544096", "0.5430891", "0.54214984", "0.540734", "0.54033494", "0.53854495", "0.5365966", "0.53635466", "0.5350206" ]
0.6920921
0
POST Store new menu item and return it. URL /menu
function addMenuItem(req, res) { var newItem = new FoodItem(req.body); console.log(newItem); newItem.save(function(err, newItem) { if (err) throw err; return res.json(newItem); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "insertNewMenu(){\n\t\tfetch(\"/reactui/menu\", {\n method: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Accept': 'application/json',\n\t\t\t\t'Content-Type': 'application/json'\n\t\t\t},\n\t\t\tbody: JSON.stringify(this.state.newMenu)\n }).then((resp) => {\n\t\t\treturn resp;\n\t\t}).then((respMessage) => {\n alert(\"Http Status: \" + respMessage.status);\n if(respMessage.ok){\n this.clearNewMenu();\n this.retrieveListOfMenu();\n }\n\t\t}).catch((error) => {\n\t\t\talert(error.message);\n\t\t});\n }", "function addItem () {\n var req = new XMLHttpRequest()\n var data = { menu_id: null, item_id: null }\n data.menu_id = menuSelectedID\n data.item_id = this.id\n req.open('POST', '/addToMenu', true)\n \t\treq.setRequestHeader('Content-Type', 'application/json')\n req.addEventListener('load', function () {\n if (req.status >= 200 && req.status < 400) {\n var response = JSON.parse(req.responseText)\n if (response) {\n if (response.affectedRows == 0) {\n console.log('Response.affectedRows = ' + JSON.stringify(response.insert))\n alert('Item already in current menu.')\n } else {\n addToTable(response.itemToAdd[0], 'itemsOnMenu')\n }\n }\n } else {\n console.log('Error in network request: ' + req.statusText)\n\t\t }\n })// end of ael(load)\n \treq.send(JSON.stringify(data))\n event.preventDefault()\n}", "static postMenu(req, res) {\n let dayMenu = {};\n function findMenu(menuItem) {\n const menuItemDate = new Date(menuItem.date);\n const queryDate = new Date(req.body.date);\n if (menuItemDate.getTime() === queryDate.getTime()) {\n if (menuItem.meals.indexOf(parseInt(req.body.meal, 10)) === -1) {\n menuItem.meals.push(parseInt(req.body.meal, 10));\n }\n return menuItem;\n }\n }\n\n dayMenu = menu.menu.find(findMenu);\n\n if (dayMenu === undefined) {\n dayMenu = {};\n dayMenu.id = menu.menu.length + 1;\n dayMenu.date = req.body.date;\n dayMenu.meals = [parseInt(req.body.meal, 10)];\n menu.menu.push(dayMenu);\n res.status(201).send(dayMenu);\n } else {\n res.status(201).send(dayMenu);\n }\n }", "function menuCrear(req, res) {\n const nombreMenuBody = req.body.nombre || '';\n if (nombreMenuBody === '') {\n return res.status(505).json({\n ok: false,\n message: 'menu no se ha enviado el nombre'\n });\n }\n menu = new Menu();\n menu.nombre = nombreMenuBody;\n menu.save( (err, respDB) => {\n errorBD(err,respDB,res);\n res.status(200).json({\n ok: true,\n menu: respDB\n });\n });\n\n}", "function handleSubmit(evt) {\n evt.preventDefault();\n storeItem(newItem);\n alert(\"Menu item added!\")\n\n // redirect with history.push and the path\n // after the email form is submitted it redirects to the root\n // can also go back and forward unlike redirect\n history.push(`/${item}`);\n }", "function menu_item(pid) {\n var request = {\n 'action': 'menu_item',\n 'id': pid,\n };\n jQuery.post( ajaxurl, request, function(response){\n //console.log('Menu: ' + response);\n process_item(response);\n });\n\n}", "function addItem(item){\n\n let avail;\n\n if (item.available === true){\n avail = \"Available\";\n } else {\n avail = \"SOLD OUT\";\n };\n\n let menuTemplate = document.querySelector('#menu-template').innerHTML;\n\n let parent = document.querySelector('.menu');\n let container = document.createElement('div');\n container.classList.add('menuItem');\n container.innerHTML = Mustache.render(menuTemplate, {\n name: item.name,\n description: item.description,\n price: item.price,\n available: avail,\n });\n\n parent.appendChild(container);\n\n\n let button = container.querySelector('.changeAvail');\n button.addEventListener('click', function(){\n let request = new XMLHttpRequest();\n request.open('POST', 'http://tiy-28202.herokuapp.com/menu/'+item.id);\n request.send(JSON.stringify({\n available: !item.available,\n }));\n });\n}", "onCreate (item) {\n\t\t// Hide the create form\n\t\tthis.toggleCreateModal(false);\n\t\t// Redirect to newly created item path\n\t\tconst list = this.props.currentList;\n\t\tthis.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);\n\t}", "function newItem(){\n sendRequest(\n 'usergroups',\n {\n 'action': 'getNewItemForm',\n \"id_menucategory\": $('#kategoria').val()\n }, function(data){\n $('#listcontent').css('display','none');\n $('#editorholder').html(data);\n });\n}", "function menuItemCreate(menuItem) {\n const itemId = menuItem.id\n menuItem.options.click = function(menuItem) {\n client.write(itemId, consts.eventNames.menuItemEventClicked, {menuItemOptions: menuItemToJSON(menuItem)})\n }\n if (typeof menuItem.submenu !== \"undefined\") {\n menuItem.options.type = 'submenu'\n menuItem.options.submenu = menuCreate(menuItem.submenu)\n }\n elements[itemId] = new MenuItem(menuItem.options)\n return elements[itemId]\n}", "function create_menu()\n{\n location.href='./Create-Item';\n}", "async function saveMenu(menu) {\n let actionResult = new action_result_1.ActionResult();\n //let setDataRes = await updateCategoryLang(menu);\n let setItemsRes = new action_result_1.ActionResult(false);\n let menuData = {\n id: data.id,\n languageId: data.languageId,\n menuItem: menu\n };\n let setDataRes = await scope.setMenuCategories(menuData);\n console.log(' ');\n console.log('-------------------');\n console.log(' ');\n console.log(' ');\n console.log('menu ::', menu);\n if (setDataRes.success) {\n setItemsRes = await setMenuItems(menu);\n }\n if (!setDataRes.success || !setItemsRes.success) {\n actionResult.setSuccess();\n }\n return new Promise((resolve, reject) => {\n resolve(actionResult);\n });\n }", "NewItemForm(e) {\n if (typeof this.props.onNew === 'function') {\n var props = {\n type: \"existing\",\n item_id: this.props.menu[1].item_id,\n menu: {\n \"name\": this.props.menu[0],\n \"category\": this.props.menu[1].category,\n \"price\" : this.props.menu[1].price,\n \"calories\": this.props.menu[1].calories,\n \"in_stock\": this.props.menu[1].in_stock,\n \"description\": this.props.menu[1].description\n }\n }\n this.props.onNew(props);\n }\n }", "function submitItem(item) {\n $.post(\"/addItem\", item)\n }", "function newElement() {\n var name = $(\"#myInput\").val();\n var id = $(\"#key\").val();\n doPost(\"/saveItem\", {\"name\":name, \"id\": id}, newItemCreated) // /saveitem calls the handler, then executes the handler\n}", "function ajax_getMenu() {\n \n // Prepare data to send to server\n const data = new FormData();\n const menu_type = select_type.options[select_type.selectedIndex].value;\n data.append('menu-type', menu_type);\n data.append('csrfmiddlewaretoken', csrftoken); // csrf for Ajax\n\n // Send Ajax request to server\n const request = new XMLHttpRequest();\n request.open('POST', showMenu_url);\n request.send(data);\n \n // Update menu when request completes (recieved data from server) \n request.onload = () => {\n const data = JSON.parse(request.responseText);\n updateMenuItems(menu_items, data);\n };\n\n // Stop page from reloading after submit\n return false;\n }", "function swipperAddMenuDetails(menu_id, restaurant_id) {\n let tempHtmlId = menu_id;\n menu_id = menu_id.split(\"_\");\n let curretn_value = $(\"#\" + tempHtmlId).html();\n curretn_value = parseInt(curretn_value) + 1;\n $(\"#\" + tempHtmlId).html(curretn_value);\n $.ajax({\n type: \"POST\",\n url: serverUrl + \"add_to_cart/\",\n data: {\n user: localStorage.getItem(\"platuser\"),\n restaurant: restaurant_id,\n menu: menu_id[1],\n qty: curretn_value\n },\n dataType: \"JSON\"\n }).done(function(rply) {\n app.currentCartItems();\n window.plugins.toast.showLongBottom(\"Cart item update\");\n });\n}", "function newProduct (err, results) {\n if (err) {\n console.log(err)\n }\n console.log(`New product added, Product ID = ${results.insertId}`)\n mainMenu()\n}", "function addItem( entry ) {\n $http.post( storelist_url, entry ).then(\n function(response) {\n console.log(\"POST success\");\n console.log(response);\n deferred.resolve(response);\n },\n function(error) {\n console.log(\"POST error\");\n deferred.reject(error);\n }\n );\n return deferred.promise;\n }", "function addItem(item) {\n $state.go('main.addItem', {item: item, foodListId: $stateParams.foodListId});\n }", "function menuCreate(menu) {\n if (typeof menu !== \"undefined\") {\n elements[menu.id] = new Menu()\n for(let i = 0; i < menu.items.length; i++) {\n elements[menu.id].append(menuItemCreate(menu.items[i]))\n }\n return elements[menu.id]\n }\n return null\n}", "function addItem(){\n const value = newItemInput.value;\n\n if(!value){\n alert(\"Please enter a value\");\n return;\n }\n\n const _item = {...item, message: value};\n\n items.push(_item);\n newItemInput.value = \"\";\n render();\n\n postItemToJSON(\"http://localhost:8000/index.php\", _item, items.length - 1);\n}", "function createMenu() {\n inquirer.prompt({\n type: \"list\",\n name: \"action\",\n message: \"What would you like to add?\",\n choices: [\n { name: \"Add a department\", value: createDepartment },\n { name: \"Add a role\", value: createRole },\n { name: \"Add an employee\", value: createEmployee },\n { name: \"Go back\", value: mainMenu }\n ]\n }).then(({ action }) => action());\n}", "async function addMenu(item, restaurant_id){\n const [id] = await db('menu')\n .where({ restaurant_id })\n .insert(item)\n return findItemById\n}", "function addItem(event) {\n event.preventDefault();\n\n const newItem = {\n title: item.title,\n description: item.description,\n };\n\n axios.post(\"/newitem\", newItem);\n\n setItem({\n title: \"\",\n description: \"\",\n });\n }", "function handleAddItem() {\n // Listen for when users submit a new list item\n $('#js-shopping-list-form').submit(event => {\n event.preventDefault();\n // Get the name of the new item from the text input\n const inputObject = $('.js-shopping-list-entry');\n const newListItem = inputObject.val();\n // Clear out the value of the input so new items can be addeed\n inputObject.val('');\n // Update the store\n addItemToStore({ name: newListItem, completed: false });\n // Rerender the shopping list\n renderShoppingList();\n });\n}", "function guardarMenu(req, res, next) {\n\n console.log(req.body);\n\n let data = {\n tipo_nombre: req.body.tipo_nombre,\n }\n\n\n let modelTipoMenu = new ModelTipoMenu(data);\n\n modelTipoMenu.save((err, item) => {\n\n if (err || !item) return errorHandler(err, next, item);\n\n res.json({\n result: true,\n data: item\n });\n\n });\n\n\n}", "function returnItem(itemId) {\n $.post(\"/api/lend\", {id: itemId})\n .then(function() {\n window.location.replace(\"/dashboard\");\n })\n .catch(function(err) {\n console.log(err);\n });\n }", "addMenuItem(menuItem){\r\n\r\n }", "async function addItem(item) {\n setSubHeader(\"Result\");\n\n const response = await fetch(\"/api/shoes\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(item),\n });\n const responseItem = await response.json();\n\n if (response.ok) {\n createListItem(responseItem);\n } else {\n createErrorItem(responseItem);\n }\n\n const formContainer = document.getElementById(\"form-container\");\n formContainer.innerHTML = \"\";\n}" ]
[ "0.76003313", "0.70412725", "0.6812183", "0.6765626", "0.67256147", "0.6705598", "0.66559154", "0.64652056", "0.64190185", "0.6384572", "0.63171047", "0.63049644", "0.62860453", "0.62209165", "0.62006783", "0.6073996", "0.605232", "0.6038891", "0.6031468", "0.600662", "0.5994096", "0.5905196", "0.59023815", "0.5897178", "0.58909583", "0.58802867", "0.58240944", "0.58216757", "0.5817563", "0.58151054" ]
0.7081679
1
DELETE Remove specified menu item from database. URL /menu
function deleteMenuItem(req, res) { FoodItem.findOne({_id: req.body.itemID}, function(err, item) { if (err) throw err; if(item === null) { return res.send("Error: no such item"); } item.remove(function(err) { if (err) throw err; return res.send("Success"); }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeMenu(id){\n return db('menu')\n .where({ id })\n .del()\n}", "function menuBorrar(req, res) {\n const idParams = req.params.id;\n errorParams(idParams, res);\n Menu.findByIdAndRemove(idParams).exec((err, respDB) => {\n errorBD(err, respDB,res);\n res.status(200).json({\n ok: true,\n menu: respDB\n });\n });\n}", "function deleteFromMainMenu(menuId, pageId,menuType)\n{\n \n if (!confirm('Proceed to remove the menu'))\n return false;\n /*$.ajax({\n type: \"POST\",\n url: appURL + '/proxy',\n dataType: \"json\",\n data: {method: 'deleteFromMainMenu', menuId: menuId, pageId: pageId},\n success: function (data) {\n var res = data.result;\n if (res == 1)\n {\n alert('Can not delete this global link as primary links present under this menu.');\n }\n else if (res == 2)\n {*/\n $(\"#mainMenuItem\" + pageId).remove();\n showHideChkBox(menuType);\n displayEmptyText(menuType);\n //getTotalMenuRecords();\n// }\n// }\n// });\n}", "function deleteMenu(id) {\r\n\r\n API.deleteMenu(id)\r\n .then(res => loadMenus())\r\n .catch(err => console.log(err));\r\n }", "function DeleteMenu(menuId){\n\tif(confirm(\"Are you sure you want to delete this menu?\")){\n\t\t$.ajax({\n\t\t\ttype: \"get\",\n\t\t\turl: '/adpostm/menu/delete?id='+menuId,\n\t\t})\n\t\t.done(function(data,textStatus, jqXHR){\n\t\t\talert(\"Response from server: \" + data);\n\t\t\twindow.location.reload();\n\t\t})\n\t\t.fail(function(jqXHR, textStatus, errorThrown ){\n\t\t\tconsole.log(arguments);\n\t\t\talert(\"An error occured. Delete menu failed. - \" + errorThrown );\n\t\t});\n\t}\n\t\n}", "function removeItemFromMenu(event) {\n if(event.target.classList.contains('removelistitem')) {\n menu.removeItem(event.target.id);\n menu.saveToLocalStorage();\n renderMenuTable();\n }\n}", "deleteItem() {\n this.view.removeFromParentWithTransition(\"remove\", 400);\n if (this.item != null) {\n this.itemDao.deleteById(this.item.getId());\n }\n }", "function deleteListItem() {\n item.remove();\n }", "function deleteMenuItem() \n{\n\tif (!confirm(\"Realy delete?\")) return false;\n\twindow.location = \"/admin/structure/delete/\" + selectedItemID;\n\treturn true;\n}", "function remove(req, res) {\n connection.query('DELETE FROM items WHERE id = ?', req.params.id, function(error, results) {\n if (error) {\n res.status(404).send({ message: `Error occured while deleting item with id ${req.params.id}` });\n }\n\n res.send({ message: 'Successfully deleted' });\n });\n }", "function removeItem(e) {\n\t\tvar id = jQuery(this).parents('li').attr('data-id');\n\t\tif(id){\n\t\t\tfirebase.database().ref().child('/messages/'+id).remove();\n\t\t}\n\t}", "function deleteMenu() {\n randomize_button.remove();\n submit_num.remove();\n num_stars_input.remove();\n submit_num_planets.remove();\n num_planets_input.remove();\n if (set_stars != null) {\n set_stars.remove();\n }\n if (preset_binary != null) {\n preset_binary.remove();\n }\n if (tatooine != null) {\n tatooine.remove();\n }\n deleteInputInterface();\n}", "function deleteItem(id) {\n executeHTTPRequest(id, 'DELETE', '/remove')\n}", "function deleteMenu() {\n inquirer.prompt({\n type: \"list\",\n name: \"action\",\n message: \"What would you like to remove?\",\n choices: [\n { name: \"Remove a department\", value: deleteDepartment },\n { name: \"Remove a role\", value: deleteRole },\n { name: \"Remove an employee\", value: deleteEmployee },\n { name: \"Go back\", value: mainMenu }\n ]\n }).then(({ action }) => action());\n}", "delete(item) {\n this.sendAction('delete', item);\n }", "function deleteButtonPressed(todo) {\n db.remove(todo);\n}", "function delItem(id) {\n connection.query(\"DELETE FROM itemList where id = ?\", [id], function(\n error,\n results,\n fields\n ) {\n if (error) throw error;\n console.log(results);\n });\n }", "function deleteItem() {\n SidebarActions.deleteItem('Content', $scope.data.thisContent);\n}", "function deleteMenuByType(type, menuItems) {\n \tfor (var i = 0; i < menuItems.length; i ++) {\n \t\tvar item = menuItems[i];\n \t\tif (item['_type'] && (item['_type'] === type.toLowerCase())) {\n \t\t\t menuItems.splice(i, 1);\n }\n \t}\n }", "function deleteItem(item){\n\tif(selectedRow == null){\n\t\talert(\"There's no row selected!\");\n\t}\n\telse{\n\t\tvar deleteString = \"Delete=True&ID=\";\n\t\tvar i = 0;\n\t\tselectedRow.find('td').each(function(){\n\t\t\tif (i==0){\n\t\t\t\tdeleteString += $(this).text().replace('** ','').replace(' **','');\n\t\t\t\ti ++;\n\t\t\t}\n\t\t});\n\t\tif (item == \"User\"){\n\t\t\tdeleteString += '&Users'\n\t\t}else{\n\t\t\tdeleteString += '&Courses'\n\t\t}\n\t\tif(confirm(\"Are you sure you wish to delete this entry?\")){\n\t\t\tdisplayPageInfo(deleteString);\n\t\t}\n\t}\n}", "function removeOrderMenuItem(itemId) {\n const dataToSend = JSON.stringify({orderMenuItemId: itemId});\n post(\"/api/authTable/removeItemFromOrder\", dataToSend, function (data) {\n if (data === \"success\") {\n const parent = document.getElementById(\"order\");\n const child = document.getElementById(\"ordermenuitem-\" + itemId);\n parent.removeChild(child);\n\n // Remove it from the basket array\n for (let i = 0; i < basket.length; i++) {\n if (basket[i].id === itemId) {\n basket.splice(i, 1);\n }\n }\n\n // Recalculate the price\n calculateTotal();\n }\n })\n}", "function deleteItem(evt) {\n\tvar button = evt.target;\n\tvar row = button.parentNode.parentNode;\n\tvar cells = row.getElementsByTagName(\"td\");\n\tvar name = cells[1].innerHTML;\n\tvar type = cells[2].innerHTML;\n\tvar group = row.id.slice(0, row.id.indexOf(\"-\"));\n\tif (group === \"base\") {\n\t\tbaseItems.delete(type, name);\n\t} else {\n\t\toptionalItems.delete(type, name);\n\t}\n\trow.parentNode.removeChild(row);\n\tsyncToStorage();\n}", "function deleteItem() {\n var id = $(this).parent().attr('data-id');\n\n $.ajax(\n {\n url: 'http://157.230.17.132:3017/todos/' + id,\n method: 'DELETE',\n success: function() {\n getAllItemsSaved();\n },\n error: function() {\n alert(\"Attenzione, non sono riuscito a eliminare l'elemento\");\n }\n }\n );\n}", "function deleteButtonPressed(todo) {\n db.remove(todo);\n }", "removeMenuItem(itemId) {\n let notesMenu = document.querySelectorAll('[name=\"js-notes-menu\"], [name=\"js-folder-notes-menu\"]');\n\n notesMenu.forEach( menu => {\n let existingNote = menu.querySelector('[data-id=\"' + itemId + '\"]');\n\n if (existingNote) existingNote.remove();\n });\n }", "function deleteItem(elem) {\r\n var id = elem.parent().attr(\"id\");\r\n firebase\r\n .database()\r\n .ref(\"/todos/\" + id)\r\n .remove();\r\n }", "function deleteMenuGroup(menuGroup){\n if(confirm(\"Are you sure you want to remove this item?\")){\n MenuGroupFactory.remove(menuGroup.menuGroupId).then(\n function(){\n getMenu();\n }\n );\n }\n }", "function remove_item_from_items_database( item_url, item_slug, item_type ) {\n\n\t/* Action */\n\n\tjQuery(document).trigger('remove_item_from_items_database');\n\t\n\t/* Callbacks */\n\t\n\tvar on_success = function ( context ) {\n\t};\n\t\n\tvar on_error = function ( context ) {\n\t};\n\n\t/* Request */\n\n\tInDB.trigger( 'InDB_do_row_delete', { 'store': 'items', 'key': item_url, 'on_success': on_success, 'on_error': on_error } );\n\n}", "function deleteItem(e) {\n // retrieve the name of the task we want to delete. We need\n // to convert it to a number before trying it use it with IDB; IDB key\n // values are type-sensitive.\n let noteId = Number(e.target.parentNode.getAttribute('data-note-id'));\n\n // open a database transaction and delete the task, finding it using the id we retrieved above\n let transaction = db.transaction(['notes_os'], 'readwrite');\n let objectStore = transaction.objectStore('notes_os');\n let request = objectStore.delete(noteId);\n\n // report that the data item has been deleted\n transaction.oncomplete = function() {\n // delete the parent of the button\n // which is the list item, so it is no longer displayed\n e.target.parentNode.parentNode.removeChild(e.target.parentNode);\n console.log('Note ' + noteId + ' deleted.');\n\n // Again, if list item is empty, display a 'No notes stored' message\n if(!list.firstChild) {\n let listItem = document.createElement('li');\n listItem.textContent = 'No notes stored.';\n list.appendChild(listItem);\n }\n };\n}", "function deleteMe(item){\n fetch(\"/remove/\" + item.innerText,{\n method: \"delete\"\n }).then(res=>res.json())\n .then(res2 => {\n // console.log(res2)\n location.reload()\n });\n }" ]
[ "0.7927207", "0.7103373", "0.6887212", "0.6881293", "0.6808459", "0.6805908", "0.671129", "0.6667769", "0.666174", "0.66494745", "0.6569481", "0.6563609", "0.6555546", "0.6538083", "0.65164757", "0.651534", "0.6506378", "0.6495212", "0.64711535", "0.64637095", "0.6455055", "0.6451465", "0.6412184", "0.64000267", "0.63958555", "0.63409543", "0.6327962", "0.6322651", "0.63150126", "0.6306012" ]
0.78458667
1
fetching data from errorlog table for rerun the scheduler
function errorDataCollection() { let today = new Date() let pendingSchedule = [''] let currentTime = new Date() let timePeriod = new Date(currentTime.setMinutes(currentTime.getMinutes() - 8)); client.query(`SELECT * from schedule_error WHERE error_area != 'email validation' AND status != 'Success' AND datetime <= '${today}' AND datetime >= '${timePeriod}'`, (err, res) => { if (err) { errorLog(err, 'reschedule', 'Pending') } else { pendingSchedule = res.rows for (let errorrow of pendingSchedule) { reScheduling(errorrow); } } // console.log(res.rows); }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "refreshAnomalyTable() {\n const { anomalyIds, exploreDimensions } = this.currentModel;\n if (anomalyIds && anomalyIds.length) {\n get(this, 'loadAnomalyData').perform(anomalyIds, exploreDimensions);\n }\n }", "function get_data_from_log_table(func)\n{\n\tif(typeof static_local_db=='undefined')\n\t{\n\t\topen_local_db(function()\n\t\t{\n\t\t\tget_data_from_log_table(func);\n\t\t});\n\t}\n\telse\n\t{\n\t\tvar keyValue=IDBKeyRange.bound(['unsynced','0'],['unsynced','99999999']);\n\t\tvar counter=0;\n\t\tvar log_data=[];\n\t\tvar sub_log_data=[];\n\n\t\tstatic_local_db.transaction(['activities'],\"readonly\").objectStore('activities').index('status').openCursor(keyValue,'next').onsuccess=function(e)\n\t\t{\n\t\t\tvar result=e.target.result;\n\t\t\tif(result)\n\t\t\t{\n\t\t\t\tvar record=result.value;\n\n\t\t\t\tif(counter===200)\n\t\t\t\t{\n\t\t\t\t\tlog_data.push(sub_log_data);\n\t\t\t\t\tsub_log_data=[];\n\t\t\t\t\tcounter=0;\n\t\t\t\t}\n\t\t\t\t//\tconsole.log(record);\n\t\t\t\tsub_log_data.push(record);\n\n\t\t\t\tcounter+=1;\n\t\t\t\tresult.continue();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlog_data.push(sub_log_data);\n\t\t\t\tfunc(log_data);\n\t\t\t}\n\t\t};\n\n\t}\n}", "function fetchRowsFromJdeAuditLogRS(connection, resultSet, numRows, audit)\n{\n resultSet.getRows( numRows, function(err, rows)\n {\n \tif (err)\n\t{\n \tresultSet.close(function(err)\n\t\t{\n\t\t\tif (err)\n\t\t\t{\n\t\t\t\tconsole.log(err.message);\n\t\t\t\tconnection.release(function(err)\n\t\t\t\t{\n\t\t\t\t\tif (err) { console.log(err.message); }\n\t\t\t\t});\n\t\t\t}\n\t\t}); \n \t} else if (rows.length == 0)\n\t{\n\t\tresultSet.close(function(err)\n\t\t{\n\t\t\tif (err)\n\t\t\t{\n\t\t\t\tconsole.log(err.message);\n\t\t\t\tconnection.release(function(err)\n\t\t\t\t{\n\t\t\t\t\tif (err) { console.log(err.message); }\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} else if (rows.length > 0)\n\t{\n\t\t\n\t\t// Last audit entry retrieved\n\t\t// Process continues by querying the JDE Job Control Master file for eligible PDF's to process\n\n\t\tvar record = rows[0];\n\t\tqueryJdeJobControl(connection, record);\n\t\t\n\t}\n });\n}", "function errorLog(error, area, status) {\r\n var today = new Date();\r\n client.query(\r\n `INSERT INTO schedule_error(message, datetime,error_area,status)VALUES('${error}','${today}','${area}','${status}')`,\r\n (err, res) => {\r\n if (err) {\r\n\r\n console.log(err)\r\n }\r\n }\r\n );\r\n}", "function processLog()\n{\n var log_entry;\n var log_lines;\n var date;\n\tvar time;\n\tvar query_string;\n var entry_stats;\n \n logdata.shift();\t// ignore server infos\n\t\n for (var i = 0; i < logdata.length; i++) {\n \n // load string\n log_entry = \"# Time: \" + logdata[i];\n logdata[i] = {};\n \n log_lines = log_entry.split(\"\\n\");\n\t\t\n // get host\n logdata[i].db_name = log_lines[1].split(\"[\")[1].split(\"]\")[0];\n\t\t\n // get stats\n entry_stats = log_lines[2].split(\" \");\n logdata[i].query_time = parseInt(entry_stats[2]); // query time\n logdata[i].lock_time = parseInt(entry_stats[5]); // lock time\n logdata[i].rows_sent = parseInt(entry_stats[8]); // rows sent\n logdata[i].rows_examined = parseInt(entry_stats[11]); // row examined\n \n // update stats\n\t\tif (logdata[i].query_time < stats.query_time.min) stats.query_time.min = logdata[i].query_time;\n\t\tif (logdata[i].query_time > stats.query_time.max) stats.query_time.max = logdata[i].query_time;\n\t\tif (logdata[i].lock_time < stats.lock_time.min) stats.lock_time.min = logdata[i].lock_time;\n\t\tif (logdata[i].lock_time > stats.lock_time.max) stats.lock_time.max = logdata[i].lock_time;\n\t\tif (logdata[i].rows_sent < stats.rows_sent.min) stats.rows_sent.min = logdata[i].rows_sent;\n\t\tif (logdata[i].rows_sent > stats.rows_sent.max) stats.rows_sent.max = logdata[i].rows_sent;\n\t\tif (logdata[i].rows_examined < stats.rows_read.min) stats.rows_read.min = logdata[i].rows_examined;\n\t\tif (logdata[i].rows_examined > stats.rows_read.max) stats.rows_read.max = logdata[i].rows_examined;\n \n log_lines[0] = log_lines[0].replace(' ', ' ');\n date = str_split(log_lines[0].split(' ')[2],2);\n\t\ttime = log_lines[0].split(' ')[3].split(\":\");\n \n // parse date\n date = new Date(\"20\" + date[0], date[1] - 1, date[2], time[0], time[1], time[2]);\n \n var year = date.getFullYear();\n var month = date.getUTCMonth() + 1; if (month < 10) month = \"0\" + month;\n var day = date.getDate().toString(); if (day < 10) day = \"0\" + day;\n var hours = date.getHours().toString(); if (hours < 10) hours = \"0\" + hours;\n var mins = date.getMinutes().toString(); if (mins < 10) mins = \"0\" + mins;\n \n logdata[i].dateObj = date; // date\n logdata[i].date = year + \"/\" + month + \"/\" + day + \" \" + hours + \":\" + mins;\n logdata[i].hour = hours;\n\t\t\n // isolate query\n log_lines.shift();\n log_lines.shift();\n log_lines.shift();\n \n\t\t// query\n\t\tquery_string = checkMulitpleQueries(log_lines.join(\"<br/>\").split(\"# User@Host: \"), date, i);\n\t\t\n\t\t// add formatted query tou the list\n\t\tlogdata[i].query_string = query_string;\n }\n}", "async function queryAuditLog () {\n // Select the query to run\n let queryRunner\n if (cursor) {\n queryRunner = () => requestEntries(graphqlWithAuth, org, limit, cursor)\n } else {\n queryRunner = () => requestEntries(graphqlWithAuth, org, limit)\n }\n\n // Run the query and store the most recent cursor\n const { data, newestCursorId } = await queryRunner()\n const entries = data\n if (newestCursorId) fs.writeFileSync('.last-cursor-update', newestCursorId)\n\n // Return the data\n if (pretty === true) {\n return JSON.stringify(entries, null, 4)\n } else {\n return JSON.stringify(entries)\n }\n}", "async function readLogs() {\n try {\n return await knex.select('*').from('tb_users_logs');\n } catch (ex) {\n console.log('error when calling select...');\n }\n}", "function getHrmsData(sunConn,hrmsConn,trans,userID){\ntry{\n \n let requestString='SELECT *'\n if(forceTransFlag==false){\n let d=new Date()\n requestString+=` FROM JV_Report_Details_Tbl WHERE The_Month=${ d.getMonth()} AND User_ID=${1};`\n }\n else{\n requestString+=` FROM JV_Report_Details_Tbl WHERE The_Month=${forcedMonth} AND User_ID=${1};`\n }\n //console.log(requestString)\n return new Promise((resolve,reject)=>{\n request = new Request(requestString,async (err,rowCount,rows)=> { \n if (err) { \n reject(err.message)\n console.log(err);\n }\n else{\n console.log(rowCount+' rows selected')\n const headerID=await insertIntoSunHeaders(sunConn)\n if(forceTransFlag==false){\n const detailsInsertion=await insertIntoSunDetails(sunConn,trans,rows,headerID,userID,d.getMonth())\n }\n else{\n const detailsInsertion=await insertIntoSunDetails(sunConn,trans,rows,headerID,userID,forcedMonth)\n }\n }\n }); \n request.on('requestCompleted', function() { \n resolve(1)\n }); \n hrmsConn.execSql(request); \n })\n}\ncatch(err){\n console.log(err.message)\n}\n}", "loadLastRow() {\n loadAllRows().then((response) => this.receiveData(-1, response));\n }", "function viewEmployees() {\n let query = \"SELECT * FROM employee\";\n connection.query(query, function(err,res) {\n console.log(\"\\n\\n\");\n console.table(res); \n reRun();\n })\n \n}", "async getError(errorId, data = null) {\n // On boot, refresh all records;\n if (!this.errorsList)\n this.errorsList = await this.defaultEntityManager.find(ErrorsList_1.ErrorsList);\n // if error is not found. refresh from database table otherwise throw an error.\n try {\n // error not found, refresh whole list.\n // also find again in refreshed list.\n let currError = this.errorsList.find((error) => error.errorId == errorId);\n if (!currError) {\n this.errorsList = await this.defaultEntityManager.find(ErrorsList_1.ErrorsList);\n currError = this.errorsList.find((error) => error.errorId == errorId);\n }\n return new ApiResponse_1.default(currError.errorNumber, currError.errorMessage, data);\n }\n catch (ex) {\n return new ApiResponse_1.default(-1, 'BAD EXECUTION ERROR. API FAILED.');\n }\n }", "function analyse_data(error, retry, deviceId, analysis_event){\n if(retry <= 0) return console.log(error);\n api.calculate_analysis(deviceId, analysis_event.timestamp, (error, results) =>{\n if(error) return setTimeout( () => {analyse_data(error, retry-1, deviceId, analysis_event)}, Math.floor(Math.random() * 5000) + 1000);\n analysis = {\n deviceId,\n timezone: analysis_event.timezone,\n timestamp: analysis_event.timestamp,\n baseline: results.results.baseline,\n max_temp: results.results.max_temp,\n total_carbon: results.results.total_carbon\n };\n analysis_db.insert(analysis, (error, body, header) => {\n if(error) return setTimeout( () => {analyse_data(error, retry-1, deviceId, analysis_event)}, Math.floor(Math.random() * 5000) + 1000 );\n });\n });\n}", "function getLogToAnalyze(request){\n\nvar log =[];\nreturn MIRESAdmin.firestore().collection(MIRESconfig.MIRES_log).where('timestamp', '>=', request.data.timestamp).get()\n.then(snapshot => {\n if(snapshot.empty){\n console.log(\"getLogToAnalyze function: log is empty.\");\n return log;\n }\n else{\n // Get the existing log\n snapshot.forEach(doc => {\n const logRow ={\n id:doc.id,\n data:doc.data(),\n }\n log.push(logRow);\n });\n return log;\n }\n })\n .catch(err => {\n throw new Error(\"getLogToAnalyze function: \"+err);\n }); \n}", "static readAll(){\n return new Promise((resolve,reject) =>{\n (async () =>{\n // 1. connect to the DB\n // query to DB\n // verify format\n // if all is good then resolve\n // if not good reject iwth error\n // close db\n \n try{\n const pool = await sql.connect(con);\n const result = await pool.request().query(`\n SELECT u.userid, u.username, u.useremail, e.eventid, e.eventname, e.eventweek, e.eventdescription, es.schedulearray\n FROM users u\n JOIN eventSchedules es ON es.FK_userid = u.userid\n JOIN event e ON es.FK_eventid = e.eventid\n `)\n\n const schedules = [];\n\n result.recordset.forEach(record =>{\n const newSchedule = {\n userid: record.userid,\n username: record.username,\n useremail: record.useremail,\n eventid: record.eventid,\n eventname: record.eventname,\n eventweek: record.eventweek,\n eventdescription: record.eventdescription,\n schedulearray: record.schedulearray\n }\n\n schedules.push(newSchedule);\n })\n\n const validSchedules = [];\n schedules.forEach(schedule =>{\n const {error} = Schedule.validate(schedule);\n\n if(error) throw {errorMessage: 'Schedule.validate failed'}\n\n validSchedules.push(new Schedule(schedule))\n })\n\n resolve(validSchedules)\n }catch (error){\n reject(error);\n }\n sql.close();\n })();\n })\n }", "function getData(err, user) {\n //logger.debug(user);\n\n //get individual br asset report\n\n var _sql = \"SELECT a.machine as Machine,\\\n a.tacho as Tacho,\\\n a.site as Site,\\\n a.description as Description,\\\n a.order_number as OrderNumber,\\\n a.id_number as ID_Number,\\\n a.jlg_jobnumber as Job_Number,\\\n a.creation_date as Creation_Date,\\\n a.`mileage_e/w` as Mileage,\\\n a.job_status_idjob_status as Status_id,\\\n st.description as Status, \\\n a.finished as Finished,\\\n a.invoiced as Invoiced,\\\n a.idjob as DB_ID, \\\n a.priority as Priority, \\\n b.name as Customer,\\\n IF(c.stoptime IS NULL, 'Not Started', c.stoptime) as Last_Worked\\\n FROM job a \\\n JOIN job_status st \\\n ON st.idjob_status = a.job_status_idjob_status \\\n JOIN customer b \\\n ON b.idcustomer = a.customer_idcustomer\\\n LEFT JOIN (SELECT * FROM (SELECT stoptime, job_idjob FROM work_instance ORDER BY stoptime DESC) as temp GROUP BY job_idjob) as c\\\n ON c.job_idjob = a.idjob\";\n //logger.info(_sql);\n mysql.query(_sql, function(err2, rows) {\n if (!err2) {\n for (var i = 0; i < rows.length; i++) {\n\n if (rows[i]['Last_Worked'] != \"Not Started\") {\n var tempTime = new Date(rows[i]['Last_Worked']);\n //logger.debug(tempTime);\n var tempTime2 = tempTime.toUTCString();\n // logger.debug(tempTime2);\n rows[i]['Last_Worked'] = tempTime2;\n }\n //logger.debug(rows[i]['Last_Worked']);\n }\n res.json(rows);\n\n } else {\n logger.debug('error:', err2);\n res.status(500).send(err);\n }\n })\n\n }", "function getAuditLogs(endpointURL,data){\n\n Alfresco.util.Ajax.jsonGet({\n url: Alfresco.constants.URL_CONTEXT + endpointURL,\n dataObj: data,\n successCallback: {\n fn: function (result) {\n // ページング系処理\n var pagination = result.json[\"list\"][\"pagination\"];\n $('#prev-page').prop('disabled', !Boolean(pagination.skipCount));\n $('#next-page').prop('disabled', !pagination.hasMoreItems);\n $('#download-audit-log').prop('disabled', false);\n $('#delete-audit-log').prop('disabled', false);\n\n result.json.list.entries = settleEntries(result.json.list.entries);\n\n // データテーブル形処理\n YAHOO.example.Data = result.json;\n var dataSource = new YAHOO.util.DataSource(YAHOO.example.Data);\n dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;\n dataSource.responseSchema = AuditLogBrowser.RESPONSE_SCHEMA;\n\n var dataTable = new YAHOO.widget.DataTable(\"audit-log-table\", AuditLogBrowser.COLUMN_DEFINITION, dataSource, AuditLogBrowser.configs);\n\n // ソート情報\n dataTable.subscribe(\"theadCellClickEvent\", function (oArgs) {\n var uiSortedBy = this.getState().sortedBy;\n delete uiSortedBy.column;\n AuditLogBrowser.configs.sortedBy = uiSortedBy;\n });\n\n },\n scope: this\n },\n failureCallback: {\n fn: function (res) {\n $('#download-audit-log').prop('disabled', true);\n $('#delete-audit-log').prop('disabled', true);\n $('#prev-page').prop('disabled', true);\n $('#next-page').prop('disabled', true);\n $('.alert.alert-danger.data-error').show();\n },\n scope: this\n }\n });\n}", "function viewAll () {\n connection.query(\"SELECT * FROM employee\", (err, res) => {\n if (err) throw err;\n console.table(res);\n restartProcess();\n });\n \n}", "function refetch() {\n try {\n TABLE_ID = PropertiesService.getScriptProperties().getProperty(\"TABLE_ID\");\n if (!TABLE_ID) {\n\n throw new Error(\"Add table ID under File > Project properties > Script Properties\");\n }\n }\n catch (e) {\n Logger.log(e.message);\n //Browser.msgBox(e.message);\n return;\n }\n if (!TABLE_ID) {\n Logger.log(\"no table ID\");\n }\n\n\n\n try {\n var tasks = FusionTables.Task.list(TABLE_ID);\n }\n catch (e) {\n Logger.log(e.message);\n //Browser.msgBox(e.message.toString());\n return;\n }\n\n if (tasks.totalItems == 0) {\n FusionTables.Table.refetchSheet(TABLE_ID);\n Logger.log(\"Done refetching!\");\n //Browser.msgBox(\"Done refetching!\");\n }\n else {\n Logger.log(\"Failed to refetch due to having tasks still running\");\n }\n}", "function refreshSummary() {\n getTraceSummary(minutes).then(function() {\n refreshTraceSummaryTable(minutes);\n });\n}", "function getLastEntries() {\n checkDept();\n var rowsToAdd = [];\n var route = \"/api/timesheets/limit=50/\" + deptURL;\n console.log(route);\n $.get(route, function (data) {\n for (var i = 0; i < data.length; i++) {\n var newEntry = {\n id: data[i].id,\n employee_id: data[i].employee_id,\n name: data[i].name,\n date: data[i].date,\n category: data[i].category,\n task: data[i].task,\n ecr: data[i].ecr,\n timespent: data[i].timespent,\n program: data[i].program,\n notes: data[i].notes,\n }\n // console.log(newEntry);\n rowsToAdd.push(newEntry);\n // console.log(rowsToAdd);\n }\n renderList(createRow(rowsToAdd));\n });\n }", "async myTask(data, msg, conn, ch, db) {\n\n\t\ttry\n\t\t{\n\t\t\tif (!data.authToken || !data.authToken.id || !data.authToken.app) {\n\t\t\t\tthrow Error(\"Must include authorization\");\n\t\t\t}\n\n\t\t\tif (!data.authToken.admin) {\n\t\t\t\tdata.filters.app = data.authToken.app;\n\t\t\t\tdata.filters.user_id = data.authToken.id;\n\t\t\t}\n\n\t\t\tlet rows = await DataRepository.drill_completionSummary(data, db);\n\n\t\t\t//console.log(` [x] Wrote ${JSON.stringify(rows)} to ${this.DbName + \".\" + c}`);\n\n\t\t\tch.ack(msg);\n\n\t\t\treturn rows;\n\t\t} catch (ex) {\n\t\t\tthis.logError(data, msg, ex);\n\t\t\tch.ack(msg);\n\t\t}\n\t}", "function recall() {\n for (i = 0; i < lastLog.length; i++) {\n $(\"#dataTable\")\n .find(\"tbody\")\n .append(\n $(\"<tr>\").append(\n $(\"<td>\").append([1 + i]),\n $(\"<td>\").append(lastLog[i].Time),\n $(\"<td>\").append(lastLog[i].Equipment),\n $(\"<td>\").append(lastLog[i].Temperature),\n $(\"<td>\").append(lastLog[i].Employee)\n )\n );\n }\n}", "function getHoursSummaryFailed(err) {\n vm.workingHours = false;\n vm.message = LOGBOOK_CONSTANT.MSG_HOURS_SUMMARY_GET_ERROR;\n }", "function update(row, status) {\r\n let errorId = parseInt(row.errorId)\r\n client.query(\r\n `UPDATE schedule_error SET status = '${status}' WHERE \"errorId\"= '${errorId}'`,\r\n (err, res) => {\r\n console.log(`UPDATE schedule_error SET status = '${status}' WHERE \"errorId\"= '${errorId}'`);\r\n if (err) {\r\n\r\n errorLog(err, 'rescheduling updation failed', 'Failed')\r\n }else {\r\n console.log('successfully updated');\r\n }\r\n }\r\n );\r\n}", "function fetchRunResults() {\n // Request URL for test runs\n var runAPI = testRailURL + \"/index.php?/api/v2/get_runs/\" + projectID + \"&milestone_id=\" + milestoneID;\n var params = setTestRailHeaders();\n\n // Proxy the request through the container server\n gadgets.io.makeRequest(runAPI, handleRunResponse, params);\n}", "function dataStatus() {\n Promise.props({\n etutor_org: mongoose.model('LogExt').count().execAsync(),\n etutor: mongoose.model('LogExt2').count().execAsync(),\n markov: mongoose.model('LogMarkov2').count().execAsync(),\n iwrm: mongoose.model('LogIWRM').count().execAsync()\n }).then(function(results) {\n console.log('***********************');\n console.log(results);\n console.log('***********************');\n }).catch(function(err) {\n console.log(err)\n res.send(500); // oops - we're even handling errors!\n });\n }", "backlogRecords(date){\n \n }", "function empDataCollection() {\r\n client.query('SELECT * from employees', (err, res) => {\r\n\r\n if (err) {\r\n errorLog(err, 'data fetching issue', 'Pending')\r\n } else {\r\n\r\n console.log('fetching email ids')\r\n res.rows.map(item => {\r\n //email validation\r\n if (mailformat.test(item.emailid.trim())) {\r\n email.push(item.emailid)\r\n } else {\r\n let err = 'Invalid email ' + item.emailid\r\n console.log(err);\r\n errorLog(err, 'email validation', 'Pending')\r\n\r\n }\r\n })\r\n\r\n\r\n\r\n }\r\n })\r\n}", "function fetchData() {\n var data,\n baseRow = 2,\n baseColumn = 1,\n dateNow = new Date(),\n today = dateNow.getDate() + \".\" + (dateNow.getMonth()+1) + \".\" + dateNow.getYear() + \":\" + dateNow.getHours(),\n sprintId = sheet.getRange(5, sprintInfoColumn).getValue();\n\n // Try and find the row in the spreadsheet for the current data\n while (sheet.getRange(baseRow, baseColumn).getValue() != \"\") {\n if (sheet.getRange(baseRow, baseColumn).getValue() == today) {\n break;\n }\n\n // not this row, try and next one\n baseRow++;\n }\n\n // Fetch the data from Trello and update the row\n data = getActiveSprintData(sprintId);\n sheet.getRange(baseRow, baseColumn + 1, 1, 7).setValues(data);\n}", "function getData(err, user) {\n //logger.debug(user);\n\n //get individual br asset report\n\n var _sql = \"SELECT a.machine as Machine,\\\n a.tacho as Tacho,\\\n a.site as Site,\\\n a.description as Description,\\\n a.order_number as OrderNumber,\\\n a.id_number as ID_Number,\\\n a.jlg_jobnumber as Job_Number,\\\n a.creation_date as Creation_Date,\\\n a.`mileage_e/w` as Mileage,\\\n a.job_status_idjob_status as Status_id,\\\n st.description as Status, \\\n a.finished as Finished,\\\n a.invoiced as Invoiced,\\\n a.idjob as DB_ID, \\\n a.priority as Priority, \\\n b.name as Customer,\\\n IF(c.stoptime IS NULL, 'Not Started', c.stoptime) as Last_Worked\\\n FROM job a \\\n JOIN job_status st \\\n ON st.idjob_status = a.job_status_idjob_status \\\n JOIN customer b \\\n ON b.idcustomer = a.customer_idcustomer\\\n LEFT JOIN (SELECT * FROM (SELECT stoptime, job_idjob FROM work_instance ORDER BY stoptime DESC) as temp GROUP BY job_idjob) as c\\\n ON c.job_idjob = a.idjob \\\n WHERE a.jlg_jobnumber = ?\";\n //logger.info(_sql);\n var _array = [req.params.job_number];\n mysql.query(_sql, _array, function(err2, rows) {\n if (!err2) {\n for (var i = 0; i < rows.length; i++) {\n\n if (rows[i]['Last_Worked'] != \"Not Started\") {\n var tempTime = new Date(rows[i]['Last_Worked']);\n logger.debug(tempTime);\n var tempTime2 = tempTime.toUTCString();\n // logger.debug(tempTime2);\n rows[i]['Last_Worked'] = tempTime2;\n }\n //logger.debug(rows[i]['Last_Worked']);\n }\n res.json(rows);\n\n } else {\n logger.debug('error:', err2);\n res.status(500).send(err);\n }\n })\n\n }" ]
[ "0.625712", "0.56987184", "0.55910146", "0.54449993", "0.54331005", "0.54055744", "0.5359964", "0.53308415", "0.52409154", "0.522169", "0.52164537", "0.5203963", "0.51914084", "0.5180849", "0.51371044", "0.51195794", "0.5112088", "0.5087484", "0.5078544", "0.5068073", "0.5056197", "0.5053275", "0.50522035", "0.503553", "0.50147974", "0.500436", "0.49864036", "0.49799177", "0.49740946", "0.49705228" ]
0.7026856
0
remove loadig mask from modal
function unmaskModal() { var $maskTarget = $(".modal-body"); $maskTarget.closest('.modal-dialog').find('[type="submit"]').removeAttr('disabled'); $(".modal-mask").remove(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function closeModal() {\n $(\".mask\").removeClass(\"active-modal\");\n}", "_remove() {\n this.backdrop.remove();\n this.modal.remove();\n Utils.removeClass(document.body, 'modal-mode');\n }", "function removeModal() {\n modal.innerHTML = \"\";\n removeClass(modal, 'modal-show');\n }", "function skjulModal() {\n\n\n modal.classList.remove(\"vis\");\n }", "function closeModal() {\n $('#modal, #modal .wrap-modal').hide();\n $('.videomodal .videoresponsive, .imagemodal .label-imagemodal').empty();\n fechaMask();\n}", "function hide() {\n // Remove background\n bg.remove();\n // Remove modal\n modal.style.display = \"none\";\n}", "modify () {\n\n // Hide modal\n this.modal.hide();\n }", "function esconderModal() {\n\tmodal.style.display = 'none';\n}", "function maskModal($maskTarget) {\n var padding = $maskTarget.height() - 80;\n if (padding > 0) {\n padding = Math.floor(padding / 2);\n }\n $maskTarget.append(\"<div class='modal-mask'><div class='circle-loader'></div></div>\");\n //check scrollbar\n var height = $maskTarget.outerHeight();\n $('.modal-mask').css({\"width\": $maskTarget.width() + 30 + \"px\", \"height\": height + \"px\", \"padding-top\": padding + \"px\"});\n $maskTarget.closest('.modal-dialog').find('[type=\"submit\"]').attr('disabled', 'disabled');\n }", "function preAjaxCaller() {\n $('#zoomModal').remove();\n }", "function removeModal() {\n $('#modal-point').modal('hide');\n}", "cancel() {\n this.modal.jQueryModalFade.removeClass('modal_fade_trick');\n this.modal.jQueryModalWindow.css('display', 'none');\n this.clear();\n this.clearInvalid();\n this.hideNotes();\n if(!this.good){\n this.initPlaceholders();\n }\n }", "function closeModal() {\n $(\".mask\").removeClass(\"active-term\");\n}", "function CierraPopup() {\n $(\"#exampleModal\").modal('hide');//ocultamos el modal\n $('body').removeClass('modal-open');//eliminamos la clase del body para poder hacer scroll\n $('.modal-backdrop').remove();//eliminamos el backdrop del modal\n}", "function remove(e){\n if (!e.target.classList.contains('modals') || !e.currentTarget.classList.contains('close')) return false\n const modal = document.querySelector('.modal')\n setTimeout(\n function(){\n modal.remove()\n document.querySelector('.ui.dimmer.modals').innerHTML = ''\n init()\n },250)\n}", "function removeModal(){\n $(\"#warningModal\").remove();\n $(\".modal-backdrop\").remove();\n}", "unmaskBody() {\n const me = this;\n me.loadmaskHideTimer && me.clearTimeout(me.loadmaskHideTimer);\n me.loadmaskHideTimer = null;\n me.activeMask && me.activeMask.destroy();\n me.activeMask = null;\n }", "function abrirModalRemover(dados) {\n $(\"#modalRemover\").modal()\n\n adicionalSelecionadaRemover = dados\n\n}", "function hideMask() {\n document.getElementById('overlay').style.display = 'none';\n \n}", "hideModal() {\r\n document.querySelector(\".glass\").classList.toggle(\"hidden\");\r\n document.querySelector(\".glass\").dataset.lat = null;\r\n document.querySelector(\".glass\").dataset.lng = null;\r\n app.resetModalFields();\r\n }", "removeBackdrop () {\n $('.modal-backdrop').remove()\n }", "unmaskBody() {\n const me = this;\n\n me.loadmaskHideTimer && me.clearTimeout(me.loadmaskHideTimer);\n me.loadmaskHideTimer = null;\n\n me.activeMask && me.activeMask.destroy();\n me.activeMask = null;\n }", "function abrirModalRemover(dados) {\n $(\"#modalRemover\").modal();\n\n categoriaSelecionadaRemover = dados;\n}", "function hideLoading() {\n $('#modalLoading').hide();\n}", "function removeModal() {\n cleanModal();\n $(\".modal\").removeClass(\"is-active\");\n}", "endLoading() {\n this.modal.jQueryModalFade.removeClass('modal_fade_trick');\n this.modal.jQueryModalAwait.css('display', 'none');\n }", "function fermer() {\n var modal1Left = document.getElementById('modal1Left');\n //modal1Left.style.visibility=\"hidden\";\n modal1Left.remove('section');\n}", "function aceptCancelar(){\n document.querySelector(\".modal\").style.display=\"none\"\n}", "function hideModal() {\n //var $modalContainer = document.querySelector('#modal-container');\n $modalContainer.removeClass('is-visible');\n $modalContainer.text('');\n}", "function resetPinModal() {\n $('#modal-newPin').modal('close');\n setTimeout(() => {\n $('input').val('');\n $('input').removeClass('invalid valid');\n $('#newPinImg').attr('src', '../public/img/galaxy.jpg');\n }, 1000);\n lastUrl = '';\n}" ]
[ "0.71414036", "0.6967064", "0.6928043", "0.6900116", "0.6839112", "0.682834", "0.67987084", "0.67844504", "0.67694855", "0.6729312", "0.66909117", "0.6657209", "0.6653627", "0.6600607", "0.65530455", "0.6522409", "0.64977694", "0.6493927", "0.6480022", "0.64788026", "0.646669", "0.6453601", "0.6450101", "0.6445697", "0.64028555", "0.639011", "0.638317", "0.6382052", "0.6349269", "0.6349069" ]
0.77769476
0
abort ajax request on modal close. console.log(dialogFx);
function CloseFxDialog(e) { $('#app-ajax-modal .modal-dynamic-content').html(''); // console.log('modal close events',e); // $(this).find(".modal-dialog").removeClass("modal-lg").addClass("mini-modal"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "abort() {\n if ( this.xhr ) {\n this.xhr.abort();\n }\n }", "abort () {\n this.request.abort();\n }", "abort() {\n if (this.xhr) {\n this.xhr.abort();\n }\n }", "close() {\n window.http.xmlHtpRequest.abort();\n }", "cancel() {\n $('#snmpDialog').jqxWindow('hide');\n }", "function dialogAjaxDone(json){\n\tNUI.ajaxDone(json);\n\tif (json.statusCode == NUI.statusCode.ok){\n\n\t\t\n\t\tif (\"true\" == json.closeDialog) {\n\t\t\t$.pdialog.close();\n\t\t}\n\t}\n}", "endLoading() {\n this.modal.jQueryModalFade.removeClass('modal_fade_trick');\n this.modal.jQueryModalAwait.css('display', 'none');\n }", "abort() {\n this.$mdDialog.hide();\n }", "modalCancel(){\n\t\t// save nothing\n this.setValues = null;\n\t\t// and exit \n this.modalEXit();\n }", "function closeDialog(obj) {\n if (typeof obj == 'undefined' || obj == 'all' ) {\n $('dialog').removeClass('isVisible');\n $('#dialog_mask').removeClass('isVisible');\n $('main,nav').removeClass('dialogIsOpen');\n // e.preventDefault();\n }\n}", "function AjaxLoading() {\n EndAjaxLoading();\n\n $(\"#dialog_progress\").dialog({\n modal: true,\n width: 150,\n height: 130,\n resizable: false,\n autosize: false\n }).siblings('.ui-dialog-titlebar').remove().css(\"z-index\", 1005);\n}", "function closeRemoteModal(){\n\t$remoteModal.data(\"overlay\").close();\n\t$remoteModalContent.html('').html($remoteModalLoading);\n}", "function X() {\n $(\"#Dialog_Grid\").dialog(\"close\");\n}", "function handleClose() {\n setDialog(false);\n }", "function handleClose() {\n setDialog(false);\n }", "closemodal() {\n this.modalCtr.dismiss();\n }", "function dialogCancel(){\n\n // clear old inputs\n $content.find( localCfg.tabQueryItems ).remove();\n $content.find( localCfg.tabResultList ).empty();\n $content.find( localCfg.tabDistrList ).empty();\n $content.find( localCfg.tabDistrChart ).empty();\n $content.find( localCfg.tabAdjustList ).empty();\n\n // close the dialog\n dialog.close();\n\n }", "cancel() {\n this.$modalInstance.close();\n\n }", "function closeModalDialog () {\n mainView.send('close-modal-dialog');\n}", "function onDialogCancel()\n{\n\tdialogClosed();\n\treturn true;\n}", "cancel(e) {\n // reset and close dialog\n this.close();\n }", "abortRequest() {\n if (this.layer.request) {\n if (this.layer.request.readyState !== 4) {\n // Abort the request && reset the layer\n this.layer.request.abort();\n this.layer = {};\n }\n }\n }", "cancel() {\n this.modal.jQueryModalFade.removeClass('modal_fade_trick');\n this.modal.jQueryModalWindow.css('display', 'none');\n this.clear();\n this.clearInvalid();\n this.hideNotes();\n if(!this.good){\n this.initPlaceholders();\n }\n }", "function endloading(){\n\t//$(\"#ajaxloading\").fadeOut(1000);\n\t$('.sl-popup:visible .overlay').fadeOut(1000);\n}", "_closeOutOfSyncModal() {\n this._hideOutOfSyncModal();\n }", "cancel() {\n\t\tthis.$uibModalInstance.dismiss();\n\t}", "function X_Inac() {\n $(\"#Dialog_Inactivar\").dialog(\"close\");\n}", "function onCancelButtonClick() {\n modal.close();\n }", "function onCancelButtonClick() {\n modal.close();\n }", "function CancelModalDialog() {\r\n tb_remove();\r\n }" ]
[ "0.69036615", "0.6819364", "0.6784362", "0.67662436", "0.671851", "0.6714289", "0.6650974", "0.66455555", "0.6547914", "0.64068896", "0.6378657", "0.6334685", "0.6310845", "0.6302307", "0.6302307", "0.62889886", "0.62829703", "0.6265919", "0.6260881", "0.6260623", "0.62488747", "0.6247449", "0.6235698", "0.6225393", "0.62055117", "0.6204979", "0.619989", "0.61964804", "0.61964804", "0.6177076" ]
0.70408756
0
Adds an authorization rule to this endpoint.
addAuthorizationRule(id, props) { return new client_vpn_authorization_rule_1.ClientVpnAuthorizationRule(this, id, { ...props, clientVpnEndoint: this, }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function internal_initialiseAclRule(access) {\n let newRule = createThing();\n newRule = setIri(newRule, rdf.type, acl.Authorization);\n if (access.read) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);\n }\n if (access.append && !access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);\n }\n if (access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);\n }\n if (access.control) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);\n }\n return newRule;\n}", "function internal_initialiseAclRule(access) {\n let newRule = createThing();\n newRule = setIri(newRule, rdf.type, acl.Authorization);\n if (access.read) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);\n }\n if (access.append && !access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);\n }\n if (access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);\n }\n if (access.control) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);\n }\n return newRule;\n}", "add(rule) { \n this.rules[rule.type] = rule \n rule.parser = this\n }", "static _addAuthorization(url, options = {}) {\n const oAuthToken = this.getTokenFromLS();\n\n let bearer = \"Bearer \" + oAuthToken;\n\n // Append token to header. Create header if it does not exist\n if (options.headers === undefined) {\n options.headers = {};\n }\n options.headers[\"Authorization\"] = bearer;\n\n return this._fetchFromAPI(url, options);\n }", "addRule(rule) {\n if (!this.rules[rule.input]) this.rules[rule.input] = [];\n this.rules[rule.input].push(rule);\n }", "addToResourcePolicy(permission) {\n if (!this.policy && this.autoCreatePolicy) {\n this.policy = new bucket_policy_1.BucketPolicy(this, 'Policy', { bucket: this });\n }\n if (this.policy) {\n this.policy.document.addStatement(permission);\n }\n }", "function appendOwnerRule (url, aclString) {\n var currentUser = auth.currentUser()\n\n if (currentUser) {\n var string = '<#policy0> a <http://www.w3.org/ns/auth/acl#Authorization>;\\n' +\n '<http://www.w3.org/ns/auth/acl#accessTo> <' + url + '>;\\n' +\n '<http://www.w3.org/ns/auth/acl#agent> <' + currentUser + '>;\\n' +\n '<http://www.w3.org/ns/auth/acl#mode> <http://www.w3.org/ns/auth/acl#Control>, <http://www.w3.org/ns/auth/acl#Read>, <http://www.w3.org/ns/auth/acl#Write>.\\n\\n'\n return string + aclString\n } else {\n return ''\n }\n}", "function addPermissions (req, res, next) {\n const { acl, session } = req\n if (!acl) return next()\n\n // Turn permissions for the public and the user into a header\n const resource = utils.getFullUri(req)\n Promise.all([\n getPermissionsFor(acl, null, resource),\n getPermissionsFor(acl, session.userId, resource)\n ])\n .then(([publicPerms, userPerms]) => {\n debug.ACL(`Permissions on ${resource} for ${session.userId || '(none)'}: ${userPerms}`)\n debug.ACL(`Permissions on ${resource} for public: ${publicPerms}`)\n res.set('WAC-Allow', `user=\"${userPerms}\",public=\"${publicPerms}\"`)\n })\n .then(next, next)\n}", "addAuthorizeStep(step) {\r\n return this.addPipelineStep(\"authorize\" /* Authorize */, step);\r\n }", "addRule(_subject) {\n\t\tthis.rules.push(new Rule());\n\t\tthis.rules[this.rules.length-1].addSubject(_subject);\n\t}", "function authorize(req, res, next) {\n\tdebug('url: ' + req.originalUrl);\n\tdebug('method: ' + req.method);\n\tif (!req[configs.roleObjectKey].role) {\n\t\tif (!configs.defaultRole) {\n\t\t\tnext(new UnauthorizedError('No Role found'));\n\t\t\treturn;\n\t\t}\n\n\t\treq[configs.roleObjectKey].role = configs.defaultRole;\n\t}\n\n\tlet role = req[configs.roleObjectKey].role;\n\tlet url = req.originalUrl;\n\n\tlet rules = configs.rules[role];\n\tlet rule;\n\n\tif (rules) {\n\t\trule = findRule(rules, url, req.method);\n\t\tdebug(rule);\n\t}\n\n\tif (!rule) {\n\t\tlet message = 'No matching rule found for \\'' + role + '\\' on \\'' + url + '\\'';\n\t\tdebug(message);\n\t\tnext(new UnauthorizedError(message));\n\t\treturn;\n\t}\n\n\tnext();\n}", "function addRule (name, command) {\n if (!ninja_config.rules.hasOwnProperty(name)) {\n ninja_config.rules[name] = [];\n }\n\n ninja_config.rules[name] = ninja_config.rules[name].concat(command);\n}", "authorize(options) {\n logger.debug('Creating authorization endpoint middleware')\n return async (ctx, next) => {\n logger.debug('Running authorize endpoint middleware')\n const { request, response } = build(ctx)\n\n await this.server\n .authorize(request, response, options)\n .then(async code => {\n ctx.state.oauth.code = code\n handleResponse(ctx, response)\n if (next) await next()\n })\n .catch(err => {\n handleError(err, ctx)\n })\n }\n }", "function addRoleRule() {\n\t\t// показываем все правила если они есть\n\t\t$('#acl-rules tbody .rule-row').show();\n\t\t//сбрасывем селекторы\n\t\tdropRuleSelectors();\n\t\t//перемещяем селекторы в начало таблицы;\n\t\t$(\"#acl-rules tbody\").prepend($('#rule-selectors'));\n\t\tshowHide('#rule-selectors', 'show');\n\t\t//устанавливаем спрятанные поля\n\t\t$('#rule-id').val('');\n\t\t$('#save-type').val('add');\n\t}", "async addPolicies(sec, ptype, rules) {\n throw new Error('not implemented');\n }", "function createRuleValidator(path) {\n\t return function (req, res, next) {\n\n\t if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {\n\t var token = req.headers.authorization.split(' ')[1];\n\t return _jsonwebtoken2.default.verify(token, req.webtaskContext.data.EXTENSION_SECRET, {\n\t audience: (0, _urlJoin2.default)(req.webtaskContext.data.WT_URL, path),\n\t issuer: 'https://' + req.webtaskContext.data.AUTH0_DOMAIN\n\t }, function (err, decoded) {\n\t if (err) {\n\t return res.sendStatus(401);\n\t }\n\t return next();\n\t });\n\t }\n\n\t return res.sendStatus(401);\n\t };\n\t}", "async addOrgRules(id, token, data) {\n let response = await axios.patch(\n `${API_URL}/Organizations/${id}?${token}`,\n data\n );\n return response;\n }", "function registerPropertyRule(rule) {\n var propRules = Property$getRules(rule.property);\n propRules.push(rule);\n // Raise events if registered.\n var subscriptions = getEventSubscriptions(rule.property._events.ruleRegisteredEvent);\n if (subscriptions && subscriptions.length > 0) {\n rule.property._events.ruleRegisteredEvent.publish(rule.property, { rule: rule });\n }\n}", "disableRule(ruleId) {\n this.disabledRules.add(ruleId);\n }", "add(name, description, order, basePermissions) {\r\n const postBody = jsS({\r\n BasePermissions: {\r\n High: basePermissions.High.toString(),\r\n Low: basePermissions.Low.toString(),\r\n },\r\n Description: description,\r\n Name: name,\r\n Order: order,\r\n __metadata: { \"type\": \"SP.RoleDefinition\" },\r\n });\r\n return this.postCore({ body: postBody }).then((data) => {\r\n return {\r\n data: data,\r\n definition: this.getById(data.Id),\r\n };\r\n });\r\n }", "function addRule(name, discard) {\n var funcName = language.ruleFuncName(name, discard, false);\n rulesToGenerate.push({\n name: name,\n discard: discard,\n funcName: funcName\n });\n return funcName;\n }", "function addRule(name, callback)\n {\n if(name == null || typeof callback !== 'function')\n {\n throw new Error('Invalid arguments');\n }\n validations[name.toUpperCase()] = callback;\n }", "add(name, description, order, basePermissions) {\n return __awaiter(this, void 0, void 0, function* () {\n const postBody = body({\n BasePermissions: { \"High\": basePermissions.High.toString(), \"Low\": basePermissions.Low.toString() },\n Description: description,\n Name: name,\n Order: order,\n __metadata: { \"type\": \"SP.RoleDefinition\" },\n });\n const data = yield spPost(this, postBody);\n return {\n data: data,\n definition: this.getById(data.Id),\n };\n });\n }", "function checkAuthorization(req, res, next) {\n\t// if user is authenticated (logged-in)\n\tif (req.isAuthenticated()) {\n\t\t// find the poll to check for authorization as well\n\t\tPoll.findById(req.params.id, (err, foundPoll) => {\n\t\t\tif (err) {\n\t\t\t\tres.redirect('back');\n\t\t\t} else {\n\t\t\t\t// if current user is the one who added the poll\n\t\t\t\tif (foundPoll.user.id && foundPoll.user.id.equals(req.user._id)) {\n\t\t\t\t\tnext();\n\t\t\t\t} else {\n\t\t\t\t\tres.redirect('back');\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} else {\n\t\tres.redirect('back');\n\t}\n}", "function RuleAction(type) {\n this.addProperties({ actionType: type });\n}", "authorize(auth, callback) {\n var authorization;\n if (Array.isArray(auth)) {\n authorization = auth;\n }\n else if (auth instanceof authorization_1.default) {\n authorization = [auth];\n }\n else {\n authorization = [new authorization_1.default(auth)];\n }\n callback(new Registrar(this.__commands, this.__context, this.__authorization.concat(authorization)));\n return this;\n }", "function addRule(baseSelector, rule) {\n var prefix = baseSelector;\n var suffix = '';\n var sel = rule.selector.replace(/{([^?}]*)\\?([^}]*)}/g, function (_, a, b) {\n prefix = a + prefix;\n suffix += b;\n return '';\n });\n\n applyRule(rule, createRule(prefix + sel + suffix).style);\n}", "function AddRule(rule,callback){\n\n //Check if user exists\n FindUser(rule.id, function(result) {\n if (result == \"\") {\n res.send(\"405 access denied\")\n return;\n }\n\n //Check if rule exists for this cube\n FindRule(rule.id,rule.cube,rule.smartSensor,rule.sensorLoc,function(ruleResult){\n\n //Check if requested cube exist\n if(PhysikitCubeExist(rule.cube)){\n\n //Check if request sensor exists\n if(SmartCitizenSensorExist(rule.smartSensor)){\n\n //Add new rule or replace if exist\n ruleResult == undefined ? db.Add(\"rules\",rule):db.Replace(\"rules\",rule,\"_id\",ruleResult._id);\n\n //send update event of new rule\n io.to(rule.id).emit('newRule',rule);\n\n //Run the new rule\n RunRule(rule);\n\n debug.dataLog(\"Rule Engine\",\"Added\",JSON.stringify(rule));\n\n //Callback\n var data = {};\n data.code = 200;\n data.result = 'rule added';\n data.rule = rule;\n if(callback != undefined) callback(data);\n }\n //Error -> sensor type does not exist\n else{\n var data = {};\n data.code = 400;\n data.error = 'requested sensor type ' + rule.smartSensor + ' not found';\n data.rule = rule;\n if(callback != undefined) callback(data);\n }\n\n }\n //Error -> cube type does not exist\n else{\n var data = {};\n data.code = 400;\n data.error = 'requested cube type ' + rule.cube + ' not found';\n data.rule = rule;\n if(callback != undefined) callback(data);\n }\n });\n });\n}", "static ensureAuthorized(request, response, next) {\n let bearerToken;\n const bearerHeader = request.headers.authorization || request.query.authorization;\n if (typeof bearerHeader !== 'undefined') {\n const bearer = bearerHeader.split(' ');\n bearerToken = bearer[1];\n request.token = bearerToken;\n next();\n } else {\n const error = new UndefinedTokenError(ErrorCode.NOT_ALLOWED.msg.noBearer);\n Http.sendResponse(response, 403, ErrorCode.NOT_ALLOWED.code, error);\n }\n }", "function _define(ruleId, ruleModule) {\n _rules[ruleId] = ruleModule;\n }" ]
[ "0.53518724", "0.530408", "0.5295703", "0.5171888", "0.4973788", "0.4855524", "0.46431932", "0.45918423", "0.4578135", "0.45691445", "0.45688903", "0.45602107", "0.44586676", "0.44305253", "0.4387325", "0.4367352", "0.4365117", "0.43496346", "0.4349448", "0.433964", "0.4336289", "0.4330444", "0.43103355", "0.4293646", "0.42429554", "0.42244804", "0.42239657", "0.42204925", "0.42147738", "0.4210389" ]
0.6404505
0
constructor arguments: cl:: object of type [CL11](cl11.html) handle:: OpenCL handle
function CLWrapper(cl, handle, releaseFunction) { assert(cl instanceof CL11, "Argument 'cl' is not a CL11 instance."); assert(ref.getType(handle) === ref.types.void, "Argument 'handle' is not a pointer."); assert(!ref.isNull(handle), "Handle is null."); Disposable.call(this, releaseFunction); // ## object of type [CL11](cl11.html) this.cl = cl; // ## the OpenCL object handle this.handle = handle; this._cache = {}; this._infoFunction = this.cl.imports[this._classInfoFunction]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "constructor(options) {\n super();\n this._kernel = new KernelConnector(options);\n this._context = new ContextConnector(options);\n }", "function gen_op_ldl_kernel()\n{\n gen_opc_ptr.push({func:op_ldl_kernel});\n}", "function createLContext(lView,nodeIndex,_native2){return{lView:lView,nodeIndex:nodeIndex,\"native\":_native2,component:undefined,directives:undefined,localRefs:undefined};}", "function gen_op_stl_kernel()\n{\n gen_opc_ptr.push({func:op_stl_kernel});\n}", "function gen_op_ldlex_kernel()\n{\n gen_opc_ptr.push({func:op_ldlex_kernel});\n}", "constructor(GL, elSize1, data, mode1, attrLoc, itemType, glTarget, usage1) {\n//----------\nthis.GL = GL;\nthis.elSize = elSize1;\nthis.mode = mode1;\nthis.attrLoc = attrLoc;\nthis.itemType = itemType;\nthis.glTarget = glTarget;\nthis.usage = usage1;\n// Private members\nthis._buffer = this.GL.createBuffer();\nthis._nVertices = data.length / this.elSize;\nif (typeof lggr.trace === \"function\") {\nlggr.trace(`VBO: elSize=${this.elSize} length=${data.length} verts=${this._nVertices}`);\n}\n// Create and initialise the buffer.\nthis.GL.bindBuffer(this.glTarget, this._buffer);\nthis.GL.bufferData(this.glTarget, data, this.usage);\nthis.GL.bindBuffer(this.glTarget, null);\n}", "function HCL2($resource, car // this will be a car that will allow passing between controllers.\n ) {\n this.$resource = $resource;\n this.car = car; // this will be a car that will allow passing between controllers.\n }", "function gen_op_ldbex_kernel()\n{\n gen_opc_ptr.push({func:op_ldbex_kernel});\n}", "constructor(master = {}) {\n if (!master.sketchObject) {\n // eslint-disable-next-line no-param-reassign\n master.sketchObject = Factory.createNative(SymbolInstance)\n .alloc()\n .initWithFrame(new Rectangle(0, 0, 100, 100).asCGRect())\n }\n super(master)\n }", "constructor(args) {\n\t\tthis.obj = gl.createBuffer();\n\t\tthis.setData(args.data, args.usage || gl.STATIC_DRAW, args.keep);\n\t}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView: lView,\n nodeIndex: nodeIndex,\n native: native,\n component: undefined,\n directives: undefined,\n localRefs: undefined\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView,\n nodeIndex,\n native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "constructor(ctxPtr) {\n this.name = 'CipherAlgInfo';\n\n if (typeof ctxPtr === 'undefined') {\n this.ctxPtr = Module._vscf_cipher_alg_info_new();\n } else {\n this.ctxPtr = ctxPtr;\n }\n }", "constructor(host, log) {\n super();\n this.log = log || console.log;\n \n // Construct an ioLogik API\n this.host = host;\n this.iologik = new IoLogik(host, log);\n\n // Read and log the ioLogic system information\n this.logDeviceInfo();\n\n // Start polling the door state\n this.currentState = 'closed';\n this.targetState = 'closed';\n this.pollDoorPosition();\n\n // Assume that the light is initially off\n this.lightState = false;\n }", "constructor(props, context) {\n if (typeof context !== 'object') {\n throw new Error(`HyperloopContext instance is required to instantiate components`)\n }\n\n Object.defineProperties(this, {\n context: { value: context },\n initializing: { value: false, writable: true },\n node: { value: null, writable: true },\n props: { value: Object.assign({}, props) },\n wire: { value: null, writable: true },\n })\n\n if (this.defaultState) {\n this.setState(this.defaultState(this.props), false)\n }\n\n if (!context.initializing && this.oninit) {\n this.initializing = true\n if (this.isBrowser) {\n console.group(`${this.constructor.name}.oninit`)\n }\n Promise.resolve(this.oninit()).then((newState) => {\n this.initializing = false\n this.setState(newState)\n if (this.isBrowser) {\n console.debug('newState:', newState)\n console.groupEnd()\n }\n })\n }\n }", "function createGLContext() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\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;\n\n // Error reporting function, enables exceptions to be disabled\n\n function onError(message) {\n if (throwOnError) {\n throw new Error(message);\n }\n // log.log(0, message);\n return null;\n }\n\n var gl = void 0;\n if (__WEBPACK_IMPORTED_MODULE_6__utils__[\"isBrowser\"]) {\n // Make sure we have a real canvas (\"canvas\" can a string, a canvas or null)\n var realCanvas = void 0;\n if (!canvas) {\n realCanvas = Object(__WEBPACK_IMPORTED_MODULE_2__webgl_utils__[\"a\" /* createCanvas */])({ id: 'lumagl-canvas', width: width, height: height, onError: onError });\n } else if (typeof canvas === 'string') {\n realCanvas = Object(__WEBPACK_IMPORTED_MODULE_2__webgl_utils__[\"c\" /* getCanvas */])({ id: canvas });\n } else {\n realCanvas = canvas;\n }\n // Create a WebGL context in the canvas\n gl = Object(__WEBPACK_IMPORTED_MODULE_2__webgl_utils__[\"b\" /* createContext */])({ canvas: realCanvas, opts: opts });\n } else {\n // Create a headless-gl context under Node.js\n gl = _createHeadlessContext({ width: width, height: height, opts: opts, onError: onError });\n }\n if (!gl) {\n return null;\n }\n\n // Install context state tracking\n if (manageState) {\n Object(__WEBPACK_IMPORTED_MODULE_1__webgl_utils_track_context_state__[\"a\" /* default */])(gl, {\n copyState: false,\n log: function log() {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return __WEBPACK_IMPORTED_MODULE_6__utils__[\"log\"].log.apply(__WEBPACK_IMPORTED_MODULE_6__utils__[\"log\"], [1].concat(args));\n }\n });\n }\n\n // Add debug instrumentation to the context\n if (__WEBPACK_IMPORTED_MODULE_6__utils__[\"isBrowser\"] && debug) {\n gl = Object(__WEBPACK_IMPORTED_MODULE_3__context_debug__[\"a\" /* makeDebugContext */])(gl, { debug: debug });\n // Debug forces log level to at least 1\n __WEBPACK_IMPORTED_MODULE_6__utils__[\"log\"].priority = Math.max(__WEBPACK_IMPORTED_MODULE_6__utils__[\"log\"].priority, 1);\n // Log some debug info about the context\n logInfo(gl);\n }\n\n // Add to seer integration\n\n return gl;\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView: lView,\n nodeIndex: nodeIndex,\n native: native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView: lView,\n nodeIndex: nodeIndex,\n native: native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function createLContext(lView, nodeIndex, native) {\n return {\n lView: lView,\n nodeIndex: nodeIndex,\n native: native,\n component: undefined,\n directives: undefined,\n localRefs: undefined,\n };\n}", "function detectCL(x,y)\t// [col,lin] = detectCL(x,y)\n{\n\treturn [ x/d|0, y/d|0]; \n}", "constructor(args) {\n super();\n args = args || {}\n this.CONSTRUCTOR_ID = 0x98dd8936;\n this.SUBCLASS_OF_ID = 0xeeda0eb8;\n\n this.num = args.num;\n this.blocks = args.blocks;\n }", "constructor(wrapperElem, canvasObj) {\n if (!wrapperElem) console.error('Canvas Wrapper Element is unset');\n\n this.wrapperElem = wrapperElem;\n\n this.canvas = canvasObj.canvas;\n this.gl = canvasObj.gl;\n this.shaderFac = canvasObj.shaderFac;\n\n this.canvas2DLayers = [];\n\n this.buffers = null;\n\n this.objectList = [];\n\n this.hashLookup = new SpatialHash.Lookup(50, 50);\n }", "constructor(args) {\n super();\n args = args || {}\n this.CONSTRUCTOR_ID = 0x3502758c;\n this.SUBCLASS_OF_ID = 0xe2e10ef2;\n\n this.resize = args.resize || null;\n this.singleUse = args.singleUse || null;\n this.selective = args.selective || null;\n this.rows = args.rows;\n }", "function initCliffs(){\n var cliff = new Cliff(cliffPoints,20);\n\n\n var lineGeometry = new THREE.BufferGeometry().setFromPoints( cliffPoints );\n var material = new THREE.LineBasicMaterial({ color: 0x0000ff });\n var line = new THREE.Line( lineGeometry, material );\n Stage.scene.add( line );\n}", "initializeCylinder(){\n if (this.args_array.length == 6){\n this.primitive = new MyCylinder(this.scene, this.args_array[1], this.args_array[2], this.args_array[3], \n this.args_array[4], this.args_array[5]);\n }\n else console.log(\"Invalid number of arguments for a Cylinder\");\n }" ]
[ "0.5168888", "0.51356775", "0.50367385", "0.49625137", "0.4949822", "0.4907119", "0.48962805", "0.48678347", "0.48567903", "0.4853583", "0.48302686", "0.48228937", "0.48228937", "0.48228937", "0.48228937", "0.48228937", "0.48228937", "0.481383", "0.480489", "0.4803235", "0.47934726", "0.4792162", "0.4792162", "0.4792162", "0.478338", "0.47744122", "0.47628573", "0.47536725", "0.47417215", "0.47399652" ]
0.81737417
0
Closes the milestone by number
closeMilestone(number) { return this.patch(`milestones/${number}`, { state: 'closed' }).then( ({ code, body }) => { if (code !== 200) return Promise.reject(body); else return body; } ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function close(n){\n\t\treturn barsAgo(CLOSE,n);\n\t}", "_close() {\n set(this, 'isOpen', false);\n set(this, 'isToStep', false);\n\n let action = get(this, 'attrs.closeAction');\n let vals = get(this, '_dates');\n let isRange = get(this, 'range');\n\n if (action) {\n action(isRange ? vals : vals[0] || null);\n }\n\n this._destroyOutsideListener();\n }", "function closeIssue(context) {\n context.github.issues.edit({\n owner: context.payload.repository.owner.login,\n repo: context.payload.repository.name,\n number: context.payload.issue.number,\n state: 'closed'\n })\n}", "function openClose(c_index) {\n var row_num = parseInt(c_index);\n var total_num = getGradeable().components.length;\n\n //-2 means general comment, else open the c_index with the number\n var general_comment = $('#extra-general');\n setGeneralVisible(row_num === GENERAL_MESSAGE_ID && general_comment[0].style.display === 'none');\n\n for (var x = 1; x <= total_num; x++) {\n var current_summary = $('#summary-' + x);\n setMarkVisible(x, x === row_num && current_summary[0].style.display === '');\n }\n\n updateCookies();\n}", "function closeIssue(id) {\r\n // Get list of issues\r\n const issues = getIssues()\r\n\r\n // Find issue with id to close\r\n for (var i = 0; i < issues.length; i++) {\r\n if (issues[i].id === id) {\r\n issues[i].status = \"Closed\"\r\n }\r\n }\r\n\r\n // Save to our stoage\r\n localStorage.setItem('issues', JSON.stringify(issues))\r\n\r\n // Reload\r\n fetchIssues()\r\n\r\n}", "function updateDoneBadge(milestone, count) {\n $('.' + milestone + '-done-badge').html(count);\n}", "async close() {\r\n this.setOpenAmount(0, true);\r\n }", "function updateIssueCount(milestone, label, count) {\n $('.' + milestone + '-' + label + '-list-group').attr('data-count', count);\n}", "function open(n){\n\t\treturn barsAgo(OPEN,n);\n\t}", "function closeTask(row, task)\n{\n // stuff\n closeNameBox(row, task.name, task.done);\n closeSpoonBoxes(row, task.spoons);\n}", "static closeNewest()\n {\n var id = document.querySelectorAll(\"._notification[action='open']\").length-1;\n document.getElementsByClassName(\"_notification\")[id].instance.makeUntouchable();\n document.getElementsByClassName(\"_notification\")[id].setAttribute(\"action\", \"close\");\n setTimeout(function () {\n document.getElementsByClassName(\"_notification\")[id]\n .parentNode.removeChild(\n document.getElementsByClassName(\"_notification\")[id]\n );\n }, this.deltaMoveTime);\n }", "static closeNewest()\n {\n var id = document.querySelectorAll(\"._notification[action='open']\").length-1;\n document.getElementsByClassName(\"_notification\")[id].instance.makeUntouchable();\n document.getElementsByClassName(\"_notification\")[id].setAttribute(\"action\", \"close\");\n setTimeout(function () {\n document.getElementsByClassName(\"_notification\")[id]\n .parentNode.removeChild(\n document.getElementsByClassName(\"_notification\")[id]\n );\n }, this.deltaMoveTime);\n }", "function closeMark(c_index, save) {\n //Can't close a closed mark\n if (findCurrentOpenedMark() !== c_index) {\n return;\n }\n saveLastOpenedMark(true);\n updateMarksOnPage(c_index);\n setMarkVisible(c_index, false);\n}", "function CloseDesc() {\n detailContainer.animate({\n left: \"-100%\",\n }, 500, function() {\n detailContainer.css(\"display\", \"none\");\n });\n placesList.css(\"display\", \"block\");\n infoWindowArray[focusMarker].close();\n map.fitBounds(bounds);\n map.panTo(bounds);\n\n}", "function openCloseProjects(){\n\t\tprojectsXPos === '0'? setProjectsXPos('100%') : setProjectsXPos('0')\n\t}", "close( nodeToClose, inst ){\n nodeToClose.style.height = '0';\n nodeToClose.closest( inst.params.selector ).classList.remove( inst.params.openClass );\n }", "closeOverlay(index, detailsHeight, rowItems) {\n const self = this;\n this.openOverlays.splice(this.openOverlays.reduce((prev, curr, i) => {\n return (curr.index === index) ? i : prev;\n }, -1), 1);\n this.renderOverlays(detailsHeight, rowItems);\n this.context.pubSub.publishToOverlayChanges({\n changedIndex: index,\n combinedOverlayHeight: self.getCombinedOverlayHeight(),\n type: \"closed\",\n });\n }", "function githubMilestones(githubRepo, divId) {\n // Query open milestone\n $.getJSON('https://api.github.com/repos/' + githubRepo + '/milestones', function(data) {\n\n $.each(data, function(key, val) {\n var tableTemplate = '<div class=\"panel panel-primary\">\\\n <div id=\"milestone_title_' + val.number + '\" class=\"panel-heading\">\\\n </div>\\\n <div class=\"panel-body\">\\\n <div id=\"milestone_' + val.number + '\"></div>\\\n </div>\\\n <table class=\"table table-striped\">\\\n <thead>\\\n <tr>\\\n <th>Task name</th>\\\n <th>Assignee</th>\\\n <th>Priority</th>\\\n <th>State</th>\\\n </tr>\\\n </thead>\\\n <tbody id=\"milestone_issues_' + val.number + '\">\\\n </tbody>\\\n </table>\\\n </div>'\n $(tableTemplate).prependTo(divId);\n\n var due;\n if (val.due_on === null) {\n due = \"no due date set\"\n } else {\n var d = new Date(val.due_on);\n due = \"due on: \" + d.toString();\n }\n // Add title with current milestone\n $('<h3 class=\"panel-title\">Milestone: <a href=\"https://github.com/' + githubRepo + '/issues?milestone=' + val.number + '\">' + val.title + '</a></h3>')\n .appendTo('#milestone_title_' + val.number);\n $(\n '<p>' + val.open_issues + ' open issues - ' +\n ' ' + val.closed_issues + ' closed issues - ' + due +\n '</p>').appendTo('#milestone_' + val.number);\n\n\n // Query the closed issues of the current milestone\n $.getJSON('https://api.github.com/repos/' + githubRepo + '/issues?state=closed&milestone=' + val.number, function(data) {\n var issues = formatIssues(data);\n $(issues.join('')).appendTo('#milestone_issues_' + val.number);\n });\n\n // Query the open issues of the current milestone\n $.getJSON('https://api.github.com/repos/' + githubRepo + '/issues?milestone=' + val.number, function(data) {\n var issues = formatIssues(data);\n $(issues.join('')).appendTo('#milestone_issues_' + val.number);\n });\n });\n\n });\n}", "function displayMilestoneIcon ($group) {\n $group.find('.cmb-repeatable-grouping').each(function () {\n var $this = $(this);\n var milestone = $this.find('[id$=\"milestone\"]').val();\n\n if (milestone) {\n $this.find('.on-title.dashicons').remove();\n var color = $('ul.milestones .title:contains(' + milestone + ')').next().text();\n\n $this.find('button.cmb-remove-group-row.dashicons-before').after('<span style=\"color: ' + color + '\" class=\"dashicons dashicons-flag on-title\"></span> ');\n }\n });\n }", "function unhideMilestoneEdit(milestone) {\n $(milestone).parent().parent().parent().next().addClass(\"d-none\");\n $(milestone).parent().parent().parent().siblings(\".milestoneEdit\").removeClass(\"d-none\");\n $(milestone).parent().parent().addClass(\"d-none\");\n}", "close() {\n if(!this.opened){\n return;\n }\n this.opened = false;\n }", "function setStatusClosed(id){\n\tlet issues = JSON.parse(localStorage.getItem('issues'));\n\tlet tableCounts = JSON.parse(localStorage.getItem('tableCounts'));\n\n\tfor(let i = 0; i < tableCounts.length; i++){\n\t\tfor(let j = 0; j < issues.length; j++){\n\t\t\tif(issues[j].id == id){\n\t\t\t\tif(issues[j].status == \"Open\"){\n\t\t\t\t\ttableCounts[i].open = tableCounts[i].open - 1;\n\t\t\t\t\ttableCounts[i].close = tableCounts[i].close + 1; \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tfor( let i = 0; i < issues.length; i++){\n\t\tif(issues[i].id == id){\n\n\t\t\tissues[i].status = 'Closed';\n\n\t\t\tissues[i].description = `<s> ${issues[i].description} </s>`\n\t\t}\n\t}\n\n\tlocalStorage.setItem('tableCounts', JSON.stringify(tableCounts));\n\tlocalStorage.setItem('issues', JSON.stringify(issues));\n\n\tfetchIssues();\n}", "function closeIssueForm(elt) {\n var issueElt = $j(elt).closest('[data-issue-key]');\n var actionsElt = issueElt.find('.code-issue-actions');\n var formElt = issueElt.find('.code-issue-form');\n\n formElt.addClass('hidden');\n actionsElt.removeClass('hidden');\n return false;\n}", "close() {\n this.sendAction('close');\n }", "close() {\n this.opened = false;\n }", "function fixed_close_channel(num) { return caml_ml_close_channel(num); }", "close() {\n const that = this;\n\n if (!that.opened) {\n return;\n }\n\n that._close();\n }", "function closeInfoWindow(index) {\n let infowindow = infowindows[index];\n infowindow.close();\n}", "function closeModal() {\r\n // console.log(142);\r\n modal.style.display = 'none';\r\n}", "function close() {\n\t\t// Put the tick to an unreachable value to invalidate timers.\n\t\ttick = -1;\n\t\telm.style.left = \"210px\";\n\t\telm.style.pointerEvents = \"none\"; // Ignore mouse events.\n\n\t\t// Wait out the animation before destroying the element.\n\t\tsetTimeout(() => div.message.removeChild(elm), 200);\n\t}" ]
[ "0.61144936", "0.5881121", "0.5792084", "0.5696418", "0.567205", "0.5663822", "0.55725956", "0.5498331", "0.53649366", "0.53035235", "0.5291249", "0.5291249", "0.5208043", "0.52034384", "0.520063", "0.51972425", "0.5183096", "0.51806325", "0.5175055", "0.51574785", "0.5107038", "0.51050806", "0.50704014", "0.5070329", "0.5061109", "0.505952", "0.50286496", "0.5027145", "0.50205594", "0.5011989" ]
0.81170195
0
Hack for replacing response body vars with dynamic URI params
function parseUriVars(uriVars, reqUrl, respBody) { var k = null; for (var k in uriVars) { if (uriVars.hasOwnProperty(k)) { var replacementValue = reqUrl.split('/').filter(el => {return !!el})[k]; respBody = respBody.replace(URL_VAR_REGEX, replacementValue); } } return respBody; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = Object(apollo_link_http_common__WEBPACK_IMPORTED_MODULE_1__[\"serializeFetchParameter\"])(body.variables, 'Variables map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = Object(apollo_link_http_common__WEBPACK_IMPORTED_MODULE_1__[\"serializeFetchParameter\"])(body.extensions, 'Extensions map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '', preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = Object(__WEBPACK_IMPORTED_MODULE_1_apollo_link_http_common__[\"g\" /* serializeFetchParameter */])(body.variables, 'Variables map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = Object(__WEBPACK_IMPORTED_MODULE_1_apollo_link_http_common__[\"g\" /* serializeFetchParameter */])(body.extensions, 'Extensions map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '', preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = Object(__WEBPACK_IMPORTED_MODULE_1_apollo_link_http_common__[\"g\" /* serializeFetchParameter */])(body.variables, 'Variables map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = Object(__WEBPACK_IMPORTED_MODULE_1_apollo_link_http_common__[\"g\" /* serializeFetchParameter */])(body.extensions, 'Extensions map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '', preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = serializeFetchParameter(body.variables, 'Variables map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = serializeFetchParameter(body.extensions, 'Extensions map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '', preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "replaceParams(params, body) {\n // I feel cool using this\n let block = body;\n for (let i = 0; i < params.params.length; i++) {\n const replaceString = `#${i}`;\n block = block.replace(new RegExp(replaceString, 'gi'), WBtoJS(params.params[i].name));\n }\n block = block.replace(new RegExp(`#${params.params.length}`, 'gi'), WBtoJS(params.restName));\n return block;\n }", "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = (0, _apolloLinkHttpCommon.serializeFetchParameter)(body.variables, 'Variables map');\n } catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = (0, _apolloLinkHttpCommon.serializeFetchParameter)(body.extensions, 'Extensions map');\n } catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '',\n preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "function rewriteURIForGET(chosenURI, body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(key + \"=\" + encodeURIComponent(value));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = (0, _apolloLinkHttpCommon.serializeFetchParameter)(body.variables, 'Variables map');\n } catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = (0, _apolloLinkHttpCommon.serializeFetchParameter)(body.extensions, 'Extensions map');\n } catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n var fragment = '',\n preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}", "static unbuildEndodedUri(request) {\r\n var urifragment = request.split(\"&\"),\r\n data = {},\r\n i, parts;\r\n //process each par\r\n for (i = 0; i < urifragment.length; i++) {\r\n parts = urifragment[i].split(\"=\");\r\n if (parts.length < 2) {\r\n parts.push(\"\");\r\n console.log(parts);\r\n }\r\n data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);\r\n }\r\n\r\n console.log(\"Returning from\", arguments.callee.name, data);\r\n\r\n return data;\r\n }", "function _getUriEncodedBody(config){var contentType=config&&config.headers&&config.headers[\"Content-Type\"];var body=config&&config.body||\"\";if(contentType===\"application/json\"){body=JSON.stringify(body);}else{if(_isObj(body)){body=_getUriEncodedParams(body);}}return body;}", "exRouteParams(request, response) {\n const params = request.params;\n console.log(params);\n return response.json({\n titulo: \"Exemplo Route Params\",\n parametros: params\n });\n }", "function unbuildEndodedUri(request) { \r\n var urifragment = request.split(\"&\"), data = {}, i, parts;\r\n //process each par\r\n for (i = 0; i < urifragment.length; i++) {\r\n parts = urifragment[i].split(\"=\");\r\n if (parts.length < 2) {\r\n parts.push(\"\");\r\n console.log(parts);\r\n }\r\n data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);\r\n }\r\n \r\n console.log(\"Returning from\", arguments.callee.name, data);\r\n \r\n return data; \r\n}", "extract_request(params) {\n if (params.hasOwnProperty('_raw_'))\n var raw = params['_raw_'];\n else\n var raw = { res: null, req: null};\n return [raw.res, raw.req];\n }", "function unbuildEndodedUri(request) { \r\n var urifragment = request.split(\"&\"), data = {}, i, parts;\r\n //process each parameter\r\n for (i = 0; i < urifragment.length; i++) {\r\n parts = urifragment[i].split(\"=\");\r\n if (parts.length < 2) {\r\n parts.push(\"\");\r\n console.log(parts);\r\n }\r\n data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);\r\n }\r\n \r\n console.log(\"Returning from\", arguments.callee.name, data);\r\n \r\n return data; \r\n}", "function addToBody() {\n\t state.body = state.body || {};\n\t // ignore if we already have a value\n\t if (state.body[key] == null) {\n\t if (key === 'query' && _.isString(val)) {\n\t val = { query_string: { query: val } };\n\t }\n\n\t state.body[key] = val;\n\t }\n\t }", "function parseBody (req, res, next) {\n var uri = url.parse(req.url, true);\n req.pathname = uri.pathname;\n req.cookies = qs.parse(req.headers.cookie);\n req.query = uri.query;\n\n req.on('readable', function () {\n var body = req.read();\n var contentType = req.headers['content-type'];\n if (contentType === 'application/json') {\n util._extend(req.params, JSON.parse(body));\n } else {\n util._extend(req.params, qs.parse(body));\n }\n next(req, res);\n });\n}", "function parsePOSTRequest(req) { // returns the request's body as a JSON\n const bodyIndex = r.indexOf(\"\\n\\r\");\n const reqBody = r.substring(bodyIndex+3, r.length);\n let keyIndex = 0;\n let equalIndex = 0;\n let ampersandIndex = 0;\n let isDone = false;\n let parsedRespJSON = {};\n while(!isDone) {\n equalIndex = reqBody.indexOf('=', equalIndex+1);\n ampersandIndex = reqBody.indexOf('&', ampersandIndex+1);\n let key = reqBody.substring(keyIndex, equalIndex);\n let value;\n if (ampersandIndex == -1) {\n // take from last '=' character till end of string if last one, do not use ampersand index\n value = reqBody.substring(equalIndex+1, req.length)\n isDone = true; // exit the loop since we are done parsing\n }\n else {\n key = reqBody.substring(keyIndex, equalIndex) // bet. prev ampersand and equal we have the key\n keyIndex = ampersandIndex + 1;\n value = reqBody.substring(equalIndex+1, ampersandIndex) // bet. equal and ampersand we have value\n }\n parsedRespJSON[key] = value;\n }\n return parsedRespJSON;\n}", "function resolved (params) {\n const spec = specify(params)\n return `formurlencoded(${spec})`\n}", "exQueryParams(request, response) {\n\n const params = request.query;\n console.log(params);\n \n return response.json({\n titulo: \"Exemplo Query Params\",\n parametros: params\n });\n }", "setRequestProperties (req) {\n const uri = this.parseUri(req.url)\n for (const key in uri) {\n req[key] = uri[key]\n }\n }", "async update({ params, request, response }) {}", "_prepareParams (params) {\n if (params == null) {\n params = {}\n }\n if (params.auth == null) {\n params.auth = {}\n }\n if (params.auth.key == null) {\n params.auth.key = this._authKey\n }\n if (params.auth.expires == null) {\n params.auth.expires = this._getExpiresDate()\n }\n\n return JSON.stringify(params)\n }", "function finalizeRequest(endpoint, data) {\n\n // No need to do anything if the URL is static (no parameters)\n if (!endpoint.parameters) {\n return { url: endpoint.url, payload: data };\n }\n\n // Swap all the parameter placeholders with the arguments.\n let url = endpoint.url;\n for (let index = 0; index < Object.keys(endpoint.parameters).length; index++) {\n if (data[endpoint.parameters[index]] === null || data[endpoint.parameters[index]] === undefined) {\n throw new Error(\"URL Path parameter missing\");\n }\n\n url = url.replace(`{${index}}`, data[endpoint.parameters[index]]);\n delete data[endpoint.parameters[index]];\n }\n\n return { url, payload: data };\n}", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n\n if (!key) {\n return;\n }\n\n this.capture(key);\n let value = '';\n\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n\n currentVal.push(decodedVal);\n } else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "function processQueryArgs(r) {\n var decodedQueryString = querystring.decode(r.variables.query_string);\n\n // For dash.js-cmcd version differences\n var cmcdKey;\n if (r.variables.query_string.includes('Common-Media-Client-Data'))\n cmcdKey = 'Common-Media-Client-Data';\n else cmcdKey = 'CMCD';\n\n var paramsArr = decodedQueryString[cmcdKey].split(',');\n var paramsObj = {};\n for (var i = 0; i < paramsArr.length; i++) {\n if (paramsArr[i].includes('=')) {\n var key = paramsArr[i].split('=')[0];\n var value = paramsArr[i].split('=')[1];\n } \n else { // e.g. `bs` key does not have a value in CMCD query arg format\n var key = paramsArr[i];\n var value = 'true';\n }\n paramsObj[key] = value;\n }\n \n return paramsObj;\n}", "route(req, res) {\n const parsedURL = url.parse(req.url, true)\n const route = parsedURL.pathname.replace(/^\\/+|\\/+$/g, '')\n\n const queryString = parsedURL.query\n const headers = req.headers\n const decoder = new StringDecoder('utf-8')\n\n let buffer = ''\n req.on('data', (data) => {\n buffer += decoder.write(data)\n })\n\n req.on('end', async () => {\n try {\n buffer += decoder.end()\n const request = new Request({ \n route: route,\n queryString: queryString,\n method: req.method,\n headers, headers,\n payload: buffer\n })\n\n let handler = this._router.handler(route, req.method)\n const response = await handler(request)\n let statusCode = response.statusCode()\n let payload = response.payload()\n\n statusCode = typeof(statusCode) == 'number' ? statusCode : 200\n payload = typeof(payload) == 'object' ? payload : {}\n \n res.setHeader('Content-Type', 'application/json')\n res.writeHead(statusCode)\n res.end(JSON.stringify(payload))\n } catch (err) {\n console.dir(err)\n res.writeHead(500)\n res.end(JSON.stringify({\n err: err,\n msg: 'internal server error'\n }))\n }\n })\n }", "function updateParam(name, value) {\n var newUrlHash = biomart.url.jsonify(location.href);\n if (value) biomart.params[name] = value;\n else delete biomart.params[name];\n _urlHash.query = $.param(biomart.params);\n newUrlHash.fragment = biomart.url.stringify(_urlHash);\n location = biomart.url.stringify(newUrlHash);\n }", "function requestFormatOverride() {\n return function(req, res, next) {\n var parsedUrl = url.parse(req.url);\n if ('json' === req.query.format || parsedUrl.pathname.match(/\\.json$/)) {\n parsedUrl.pathname = parsedUrl.pathname.replace(/\\.json$/, '');\n req.url = parsedUrl.pathname + ( parsedUrl.search || '' );\n req.headers.accept = 'application/json';\n }\n next();\n };\n}", "replaceParams (json, replacements) {\n let jsonString = JSON.stringify(json);\n jsonString = jsonString.replace(/%(\\w+)%/g, (placeholder, p1) =>\n // p1 - first group\n replacements[p1] || placeholder);\n return JSON.parse(jsonString);\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }", "parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }" ]
[ "0.5775589", "0.5758471", "0.5758471", "0.57027376", "0.56722003", "0.56715554", "0.56715554", "0.5544978", "0.55126494", "0.5461489", "0.53812575", "0.53673273", "0.53009576", "0.53003883", "0.527321", "0.52616066", "0.5228786", "0.5202805", "0.5154325", "0.5144916", "0.5087959", "0.50751877", "0.50562966", "0.5046592", "0.50314903", "0.5030171", "0.5027344", "0.4997688", "0.49904567", "0.49904567" ]
0.67443967
0
Return a challenge corresponding to the given challegeID.
challenges(challengeID) { return __awaiter(this, void 0, void 0, function* () { const deployed = this.requireDeployed(); return yield deployed.methods.challenges(challengeID).call(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getChallenge(challengeId) {\n return wordChallenges.findOne({ _id: challengeId });\n }", "getChallengeID() {\r\n let matches = this._challengeURLMatches();\r\n return matches[1];\r\n }", "function _getChallengeById(req, res, next) {\n var json = {};\n var query = { \"_id\": new ObjectID(req.query.challengeId) };\n CHALLENGE_COLLECTION.findOne(query, function (err, challenge) {\n console.log(\"challenge : \" + challenge.length);\n if (err) {\n json.status = '0';\n json.result = { 'Error': JSON.stringify(err) };\n res.send(json);\n } else {\n json.status = '1';\n json.challenge = challenge;\n console.log(\"JSON : \" + JSON.stringify(json));\n res.send(json);\n }\n });\n}", "function _getChallengeDetail(req, res, next) {\n var json = {};\n var param = {};\n var query = { \"_id\": new ObjectID(req.query.challengeId) };\n CHALLENGE_COLLECTION.findOne(query, param, function (err, challenge) {\n if (err) {\n json.status = '0';\n json.result = { 'Error': JSON.stringify(err) };\n res.send(json);\n } else {\n json.status = '1';\n json.challenge = challenge;\n res.send(json);\n }\n });\n}", "getChallengeDetail(id) {\n axios.get(`view/created-challenges?challengeId=${id}`).then(res => {\n let challenge = res.data.challenges[0];\n\n this.setState({\n challenge: challenge.title,\n aboutChallenge: challenge.challengeDescription.aboutChallenge,\n goalDescription: challenge.challengeDescription.goalDescription,\n joinDescription: challenge.challengeDescription.joinDescription,\n policyDescription: challenge.challengeDescription.policyDescription,\n challengeStartDate: challenge.startDate,\n challengeEndDate: challenge.endDate,\n image: BASE_URL + challenge.image,\n activityType: challenge.activityType,\n maxValue: challenge.totalCount,\n minValue: challenge.minCount\n });\n });\n }", "function getCurrentChallenge() {\n var currentChallenge = null;\n\n //If the current challenge is null, retrieve another challenge that hasn't yet been answered\n if(Session.get(\"currentChallengeId\") === null) {\n //Get the next challenge\n currentChallenge = getNextChallenge(); \n\n \n if(currentChallenge) {\n //If we have a challenge, set the ID as the current challenge\n Session.set(\"currentChallengeId\", currentChallenge._id); \n }\n else {\n //If we have no more challenges, clear the current challenge data\n Session.set(\"currentChallengeId\", null);\n currentChallenge = null;\n\n //Since we have no more challenges, set the game state to done\n Session.set(\"gameState\", \"done\");\n }\n }\n\n //If the current challenge is not null, then retrieve and return it\n else {\n currentChallenge = getChallenge(Session.get(\"currentChallengeId\"));\n } \n\n return currentChallenge; \n }", "respond2faChallenge(user_input, challenge_id) {\n var sixDigits = new RegExp(\"\\\\d{6}\");\n var self = this\n return new Promise((resolve, reject) => {\n if(sixDigits.test(user_input)){ // validate format of the sms token\n self.post(\n {\n uri: _apiUrl + \"challenge/\"+ challenge_id+ \"/respond/\",\n form: { \"response\" : parseInt(user_input) }\n },\n function (err, httpResponse, body) {\n if (err) {\n reject(err)\n throw err;\n }else{\n if (body.detail == \"Challenge response is invalid.\"){\n reject(new Error(\"The 2FA code you entered was incorrect.\"))\n }else{\n resolve(body)\n }\n }\n })\n }else{\n reject(new Error(\"Invalid User Input: \" + user_input))\n }\n });\n }", "async getById(id) {\n const data = await conn.query(\"SELECT * FROM Fitness_RoutineExercises WHERE routineExercises_id=?\", id);\n if(!data) {\n throw Error('There are no responses')\n }\n return data[0]\n }", "function getCharacter(id) {\n // Returning a promise just to illustrate GraphQL.js's support.\n return Promise.resolve(humanData[id] || droidData[id]);\n}", "getCharFromID(idStr) {\n for (let i=0; i<this.characters.length; ++i) {\n if (this.characters[i].id === idStr) return this.characters[i];\n }\n }", "function getCharacter(id) {\n var _a;\n // Returning a promise just to illustrate that GraphQL.js supports it.\n return Promise.resolve((_a = Data_1.humanData[id]) !== null && _a !== void 0 ? _a : Data_1.droidData[id]);\n}", "async generateChallenge(parent, args, ctx) {\n // Must be normal status.\n const callingUserData = await checkAuth(ctx, {\n type: USER_TYPE_STUDENT,\n status: USER_STATUS_NORMAL,\n action: \"generateChallenge\",\n });\n\n // Students can only do this to themselves. Mods and better can access freely.\n if (callingUserData.id !== args.studentid && callingUserData.type < USER_TYPE_MODERATOR) {\n throw new AuthError(null, \"generateChallenge\");\n }\n\n const targetCourseData =\n await queryCourse.course.activeCourse(parent, { studentid: args.studentid }, ctx, `\n {\n id\n status\n parent {\n student {\n id\n }\n }\n }\n `);\n\n // If the Course cannot be found, stop here.\n if (!targetCourseData) {\n throw new StudentNoActiveCourse(args.studentid, \"generateChallenge\");\n }\n\n if (targetCourseData.status !== COURSE_STATUS_ACTIVE) {\n throw new CourseInactive(targetCourseData.id);\n }\n\n const ChallengeGen = new ChallengeGenerator(ctx);\n return ChallengeGen.generateChallenge(\n targetCourseData.id,\n args.subjectids || [],\n args.subsubjectids || [],\n args.listsize,\n args.ignorerarity || false,\n args.ignoredifficulty || false,\n args.ignorepreference || false,\n );\n }", "async function challengeCreateFn(authz, challenge, keyAuthorization) {\n if (challenge.type === 'http-01') {\n return cts.addHttp01ChallengeResponse(challenge.token, keyAuthorization);\n }\n\n if (challenge.type === 'dns-01') {\n return cts.addDns01ChallengeResponse(`_acme-challenge.${authz.identifier.value}.`, keyAuthorization);\n }\n\n throw new Error(`Unsupported challenge type ${challenge.type}`);\n }", "function challenge1() {\n\n}", "function challenge1() {\n\n}", "function _getCourse(id) {\n for (var i = 0; i < _courses.length; i++) {\n if (_courses[i].id === id) {\n return _courses[i];\n }\n }\n}", "function challengeInfo(challenge, message) {\n\n // if no info, apologize\n if (!challenge) {\n return apology1();\n }\n\n // else, build and return response\n var text = `Here's what I found on the \"${challenge.name}\" challenge:`;\n if (message) {\n text = message + \"\\n\" + text;\n }\n\n return {\n response_type: 'ephemeral',\n text: text,\n attachments: [\n attachments.userStories(challenge.name, challenge.requirements),\n attachments.generalInfo(challenge)\n ]\n };\n}", "getCreditByPersonId(id) {\n return new Promise((fulfill, reject) => {\n https.get(restHost + \"/person/\" + id + pathTail + \"&append_to_response=movie_credits\", function (res) {\n var _data = '';\n res.on('data', (d) => {\n _data += d;\n });\n\n res.on('end', () => {\n var rs = JSON.parse(_data);\n fulfill(rs);\n });\n });\n });\n }", "async get(id) {\n const data = conn.query(\"SELECT * FROM Fit_Exercises WHERE id=?\", id);\n if(!data) {\n throw Error(\"Exercise not found\");\n }\n return await data[0];\n }", "function GetPriestUsingChurchID() {\n \n var ds = {};\n var table = {};\n var Priest = new Object();\n //Priest.ChurchID = ChurchID;\n var data = \"{'priestObj':\" + JSON.stringify(Priest) + \"}\";\n ds = getJsonData(data, \"../AdminPanel/Priests.aspx/GetPriestsDetails\");\n table = JSON.parse(ds.d);\n return table;\n }", "function challenge2() {\n\n}", "function challenge_player_step1(userid) {\n\tGM_xmlhttpRequest({\n\t\tmethod:\t'GET',\n\t\turl:\t'http://'+window.location.hostname+'/Common/teamDetails.asp?UserID='+userid,\n\t\tonload:\tfunction(d) {\n\t\t\tvar i = d.responseText.indexOf('opponentID')\n\t\t\tif (i > 0) {\n\t\t\t\tvar b = i + 19\n\t\t\t\tvar e = d.responseText.indexOf('\"', b)\n\t\t\t\tvar id = d.responseText.substring(b, e)\n\t\t\t\tchallenge_player_step2(id)\n\t\t\t}\n\t\t}\n\t})\n}", "function getChords(id){\n return new Promise( (resolve,reject) => {\n httpRequest = new XMLHttpRequest();\n httpRequest.onreadystatechange = function () {\n if (httpRequest.readyState == XMLHttpRequest.DONE) {\n if(httpRequest.status == 200) {\n resolve(httpRequest.responseText);\n } else {\n console.log(\"Failed to create request instance\");\n reject(false);\n }\n }\n }\n httpRequest.open('GET', 'chord/' + id);\n httpRequest.send();\n });\n \n}", "function getChallenge(response) {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}", "function getChallenge(response) {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}", "function getChallenge(response) {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}", "function getChallenge(response) {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}", "async function GetMerchantChannel(merhcantId, channelId) {\n // NOTIFY PROGRESS\n // LOCAL VARIABLES\n var readPath = 'Merchants/' + merhcantId + \"/Channels/\" + channelId;\n console.log(\"GetMerchantChannel: \", readPath);\n\n // EXECUTE\n try {\n var record = await _once(readPath)\n return record.val();\n } catch (error) {\n console.log('GetMerchantChannel ERror:');\n console.log(error);\n }\n}", "async getCharacterByID(parent, { id }) {\n let response = await fetch(`${baseUrl}/character/${id}`);\n let character = await response.json();\n // the R&M api still returns a 200 even if nothing is found, it only returns an error field\n if(character.error) {\n throw new Error(character.error);\n } \n return character; \n }", "function currentChallenge() {\n if(document.cookie != \"\") {\n CURRENT_CHALLENGE = parseInt(document.cookie.split(\"=\")[1]);\n } else {\n CURRENT_CHALLENGE = 1;\n }\n}" ]
[ "0.6971245", "0.62784463", "0.58492416", "0.55079806", "0.54730904", "0.5441973", "0.5395898", "0.51554036", "0.5043459", "0.5019115", "0.4908836", "0.48976633", "0.48744273", "0.4806224", "0.4806224", "0.48039496", "0.48034048", "0.4802444", "0.4792775", "0.47824928", "0.47527227", "0.4741885", "0.46977365", "0.46954066", "0.46954066", "0.46954066", "0.46954066", "0.46922022", "0.46761954", "0.4662154" ]
0.6414845
1
Pepare the deploy options, passing them along with the instantiated web3 and optional contract options to the super class' _deploy method.
deploy(web3, params, opts) { const _super = name => super[name]; return __awaiter(this, void 0, void 0, function* () { const dp = { abi: Registry_json_1.default.abi, bytecode: Registry_json_1.default.bytecode, args: [ params.tokenAddress, params.votingAddress, params.parameterizerAddress, params.name ] }; return _super("deployContract").call(this, web3, dp, opts); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "deploy(web3, params, opts) {\n const _super = name => super[name];\n return __awaiter(this, void 0, void 0, function* () {\n const dp = {\n abi: Parameterizer_json_1.default.abi,\n bytecode: Parameterizer_json_1.default.bytecode,\n args: [\n params.tokenAddress,\n params.votingAddress,\n params.minDeposit || constants_1.ParameterDefaults.MIN_DEPOSIT,\n params.pMinDeposit || constants_1.ParameterDefaults.P_MIN_DEPOSIT,\n params.applyStageLen || constants_1.ParameterDefaults.APPLY_STAGE_LENGTH,\n params.pApplyStageLen || constants_1.ParameterDefaults.P_APPLY_STAGE_LENGTH,\n params.commitStageLen || constants_1.ParameterDefaults.COMMIT_STAGE_LENGTH,\n params.pCommitStageLen || constants_1.ParameterDefaults.P_COMMIT_STAGE_LENGTH,\n params.revealStageLen || constants_1.ParameterDefaults.REVEAL_STAGE_LENGTH,\n params.pRevealStageLen || constants_1.ParameterDefaults.P_REVEAL_STAGE_LENGTH,\n params.dispensationPct || constants_1.ParameterDefaults.DISPENSATION_PCT,\n params.pDispensationPct || constants_1.ParameterDefaults.P_DISPENSATION_PCT,\n params.voteQuorum || constants_1.ParameterDefaults.VOTE_QUORUM,\n params.pVoteQuorum || constants_1.ParameterDefaults.P_VOTE_QUORUM\n ]\n };\n return _super(\"deployContract\").call(this, web3, dp, opts);\n });\n }", "function toDeployOptions(args, options) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var idl, _a, rpcOptions;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n _a = options.idl;\r\n if (_a) return [3 /*break*/, 2];\r\n return [4 /*yield*/, fromWasm(options.bytecode)];\r\n case 1:\r\n _a = (_b.sent());\r\n _b.label = 2;\r\n case 2:\r\n idl = _a;\r\n rpcOptions = (function () {\r\n return {\r\n gasLimit: options.gasLimit,\r\n gasPrice: options.gasPrice,\r\n value: options.value,\r\n };\r\n })();\r\n return [2 /*return*/, {\r\n bytecode: options.bytecode,\r\n idl: idl,\r\n header: deployHeader(options),\r\n arguments: args,\r\n options: rpcOptions,\r\n gateway: options.gateway,\r\n db: options.db,\r\n coder: options.coder,\r\n }];\r\n }\r\n });\r\n });\r\n}", "deploy(contractAddress = null) {\n // if this isn't compiled yet, we need to compile it for the bytecode and web3 interface (abi)\n if (!this.compiled) {\n this.compile();\n }\n // if there is an address passed in then assume that it is already deployed\n if (contractAddress !== null) {\n this.contractAddress = contractAddress;\n return this.node1.then((web3) => {\n this.contractInterface = new web3.eth.Contract(this.abi, this.contractAddress);\n return this.contractAddress;\n });\n }\n\n // No address provided so let's deploy a new one onto the chain\n return this.node1.then((web3) => {\n let contract = new web3.eth.Contract(this.abi);\n console.log(\"Getting default account from node1 to deploy new contract\");\n return web3.eth.getAccounts().then((accounts) => {\n console.log(\"Deploying new contract from address: \" + accounts[0]);\n return contract.deploy({ data: this.bytecode, arguments: [defaultValue] }).send({\n data: this.bytecode,\n from: accounts[0],\n gasPrice: 0,\n gas: 2000000\n }).then((response) => {\n //console.log(response);\n this.contractAddress = response._address;\n this.contractInterface = new web3.eth.Contract(this.abi, this.contractAddress);\n return this.contractAddress;\n })\n })\n })\n\n }", "async function doDeploy() {\n var file_id = await createFile(\"state.data\", [])\n var send_opt = {gas:4700000, from:config.base}\n console.log(send_opt, file_id)\n var init_hash = \"0xc555544c6083b2a311c8999924893ced050615f712e240c7c439a7d8248226dc\"\n var code_address = \"QmdFE8Wcj7q6447q2sZ7ttNkCxK5TcmHLFQe1j714k6jTY\"\n var contract = await new web3.eth.Contract(abi).deploy({data: code, arguments:[config.tasks, config.fs, file_id, code_address, init_hash]}).send(send_opt)\n contract.setProvider(w3provider)\n config.plasma = contract.options.address\n console.log(JSON.stringify(config))\n var tx = await contract.methods.deposit().send({gas:4700000, from:config.base, value: 100000000})\n console.log(\"deposit\", tx)\n var dta = await contract.methods.debugBlock(1).call(send_opt)\n console.log(\"what happened\", dta)\n var tx = await contract.methods.validateDeposit(1).send({gas:4700000, from:config.base})\n console.log(\"submitted task\", tx)\n contract.events.GotFiles(function (err,ev) {\n console.log(\"Files\", ev.returnValues)\n var files = ev.returnValues.files\n files.forEach(outputFile)\n })\n // process.exit(0)\n}", "function deploy_contract() {\n web3.eth.getGasPrice(function(error, gas_price) {\n console.log(\"Gas price: \" + gas_price);\n if (!error) {\n web3.eth.getBlock(\"latest\", function(error, block) {\n console.log(\"The gas block limit is: \" + block.gasLimit.toString());\n if (!error) {\n var transaction_object = {\n chainId: web3.utils.toHex(newBlockchain.getChainId()),\n from: document.getElementById(\"public_key_input\").value,\n gasPrice: web3.utils.toHex(gas_price),\n gas: web3.utils.toHex(block.gasLimit.toString()),\n data: bytecode\n };\n web3.eth.accounts.signTransaction(transaction_object, document.getElementById(\"private_key_input\").value, function(error, signed_tx) {\n if (!error) {\n web3.eth.sendSignedTransaction(signed_tx.rawTransaction, function(error, sent_tx) {\n if (!error) {\n document.getElementById(\"deploy_contract_output\").innerHTML = \"Please wait for about 10 seconds for transaction to be confirmed ...\";\n setTimeout(function() {\n web3.eth.getTransactionReceipt(sent_tx, function(err, res_rec) {\n if (!err) {\n if (res_rec != null && res_rec != undefined) {\n //console.log(\"Success, we now have a transaction receipt: \" + JSON.stringify(res_rec));\n document.getElementById(\"deploy_contract_output\").innerHTML = \"Contract address: \" + res_rec[\"contractAddress\"];\n newContract.setAddress(res_rec[\"contractAddress\"]);\n console.log(\"New contract at: \" + newContract.getAddress());\n var multiswapContractInstance = new web3.eth.Contract(abi, res_rec[\"contractAddress\"]);\n newContract.setContractInstanceObject(multiswapContractInstance);\n }\n } else {\n console.log(\"Unable to get transaction receipt \" + err);\n }\n });\n }, 60000);\n\n } else {\n console.log(\"*\\nSend signed transaction failed: \" + error);\n }\n });\n } else {\n console.log(error);\n }\n });\n\n } else {\n console.log(error);\n }\n });\n\n } else {\n console.log(error);\n }\n });\n}", "deployPost(incomingOptions, cb) {\n const Rollbar = require('./dist');\n\n let apiInstance = new Rollbar.DefaultApi(); // String | Use a post server item access token\n /*let xRollbarAccessToken = \"xRollbarAccessToken_example\";*/ let opts = {\n body: new Rollbar.Api1DeployRequest(), // Api1DeployRequest |\n };\n\n if (incomingOptions.opts)\n Object.keys(incomingOptions.opts).forEach(\n (key) =>\n incomingOptions.opts[key] === undefined &&\n delete incomingOptions.opts[key]\n );\n else delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.deployPost(\n incomingOptions.xRollbarAccessToken,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data.result, response);\n }\n }\n );\n }", "deploy() {\n if (this.deployed && this.contractAddress) {\n console.log(\"Deploy function already called\");\n this.UserContract = this.USER.then(web3 => {\n return new web3.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n this.JoeContract = this.JOE.then(web3 => {\n return new web3.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n this.StoreContract = this.STORE.then(web3 => {\n return new web3.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n\n return new Promise((resolve) => {resolve(this.contractAddress)});\n }\n\n // else deploy the contract\n return this.STORE.then((web3) => {\n let bytecode = KaleidoKardsContract.bytecode;\n let abi = KaleidoKardsContract.abi;\n\n let contract = new web3.eth.Contract(abi);\n console.log(\"Getting kard_store account to deploy new contract\");\n return web3.eth.getAccounts().then((accounts) => {\n console.log(\"Deploying new contract from address: \" + accounts[0]);\n return contract.deploy({data: bytecode}).send({data: bytecode, from: accounts[0], gasPrice: 0, gas: 2000000})\n .then( (response) => {\n this.contractAddress = response._address;\n console.log(\"Successfully deployed at address: \" + this.contractAddress);\n\n this.UserContract = this.USER.then(response => {\n // return new response.eth.Contract(KaleidoKardsContract.abi, '0xb7a996f99afff30a8a7c5b95aa9617f0985da9ee');\n return new response.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n this.JoeContract = this.JOE.then(response => {\n // return new response.eth.Contract(KaleidoKardsContract.abi, '0xb7a996f99afff30a8a7c5b95aa9617f0985da9ee');\n return new response.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n this.StoreContract = this.STORE.then(response => {\n // return new response.eth.Contract(KaleidoKardsContract.abi, '0xb7a996f99afff30a8a7c5b95aa9617f0985da9ee');\n return new response.eth.Contract(KaleidoKardsContract.abi, this.contractAddress);\n });\n this.deployed = true;\n return this.contractAddress;\n });\n })\n })\n\n }", "function deployRpc(options) {\n options = Object.assign({}, options);\n options.headers = Object.assign({}, options.headers || {});\n if (options.headers.cookie) {\n throw new Error(\"sorry, can't combine cookie headers yet\");\n }\n options.qs = Object.assign(\n {},\n options.qs,\n { capabilities: CAPABILITIES.slice() },\n options.deployWithTokenProps || {}\n );\n // If we are waiting for deploy, we let Galaxy know so it can\n // use that information to send us the right deploy message response.\n if (options.waitForDeploy) {\n options.qs.capabilities.push('willPollVersionStatus');\n }\n\n const deployURLBase = getDeployURL(options.site).await();\n\n if (options.printDeployURL) {\n Console.info(\"Talking to Galaxy servers at \" + deployURLBase);\n }\n\n let operand = '';\n if (options.operand) {\n operand = `/${options.operand}`;\n } else if (options.site) {\n operand = `/${options.site}`;\n }\n\n // XXX: Reintroduce progress for upload\n try {\n var result = request(Object.assign(options, {\n url: deployURLBase + '/' + options.operation +\n operand,\n method: options.method || 'GET',\n bodyStream: options.bodyStream,\n useAuthHeader: true,\n encoding: 'utf8' // Hack, but good enough for the deploy server..\n }));\n } catch (e) {\n return {\n statusCode: null,\n errorMessage: \"Connection error (\" + e.message + \")\"\n };\n }\n\n var response = result.response;\n var body = result.body;\n var ret = { statusCode: response.statusCode };\n\n if (response.statusCode !== 200) {\n if (body.length > 0) {\n ret.errorMessage = body;\n } else {\n ret.errorMessage = \"Server error \" + response.statusCode +\n \" (please try again later)\";\n }\n return ret;\n }\n\n var contentType = response.headers[\"content-type\"] || '';\n if (contentType === \"application/json; charset=utf-8\") {\n try {\n ret.payload = JSON.parse(body);\n } catch (e) {\n ret.errorMessage =\n \"Server error (please try again later)\\n\"\n + \"Invalid JSON: \" + body;\n return ret;\n }\n } else if (contentType === \"text/plain; charset=utf-8\") {\n ret.message = body;\n }\n\n const hasAllExpectedKeys =\n (options.expectPayload || [])\n .map(key => ret.payload && hasOwn.call(ret.payload, key))\n .every(x => x);\n\n if ((options.expectPayload && ! hasOwn.call(ret, 'payload')) ||\n (options.expectMessage && ! hasOwn.call(ret, 'message')) ||\n ! hasAllExpectedKeys) {\n delete ret.payload;\n delete ret.message;\n\n ret.errorMessage = \"Server error (please try again later)\\n\" +\n \"Response missing expected keys.\";\n }\n\n return ret;\n}", "function extractOptions(args) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var options, deployOptions;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (args.length === 0) {\r\n throw new DeployError(args, 'No deploy arguments provided');\r\n }\r\n options = (function () {\r\n // Options should be the last argument in the args array.\r\n var opts = args.pop();\r\n // Assert required options are given.\r\n if (!opts.bytecode) {\r\n throw new DeployError(__spreadArrays(args, [opts]), 'No bytecode provided');\r\n }\r\n // Convert hex-string convenience api into Uint8Array\r\n if (typeof opts.bytecode === 'string') {\r\n opts.bytecode = bytes.parseHex(opts.bytecode);\r\n }\r\n return opts;\r\n })();\r\n return [4 /*yield*/, toDeployOptions(args, options)];\r\n case 1:\r\n deployOptions = _a.sent();\r\n validateDeployOptions(deployOptions, args);\r\n return [2 /*return*/, deployOptions];\r\n }\r\n });\r\n });\r\n}", "constructor(web3, contract, prover) {\n this.web3 = web3;\n this.contract = contract;\n this.prover = prover;\n }", "async function deployPool(deployer, network, accounts) {\n\n let gof = new web3.eth.Contract(GOF.abi, '0x488e0369f9bc5c40c002ea7c1fe4fd01a198801c');\n let reward_account = accounts[0];\n let gas_price = 165000000000;\n\n console.log(\"[Golff] 1.Start deploy pool on Network= \" + network);\n\n await deployer.deploy(GOFGXCPool);\n await deployer.deploy(GOFHTPool);\n // await deployer.deploy(GOFLIKPool);\n // await deployer.deploy(GOFUSDTPool);\n // await deployer.deploy(GOFETHPool);\n // await deployer.deploy(GOFYFIIPool);\n \n console.log(\"[Golff] 2.Start add minter acl for pool\");\n gof.methods.addMinter(GOFGXCPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n gof.methods.addMinter(GOFHTPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n // gof.methods.addMinter(GOFUSDTPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n // gof.methods.addMinter(GOFUSDTPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n // gof.methods.addMinter(GOFETHPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n // gof.methods.addMinter(GOFYFIIPool.address).send({ from: reward_account, gasPrice: gas_price, gas: 100000});\n\n console.log(\"[Golff] 3.Start set reward distributor\");\n\n let gxc_pool = new web3.eth.Contract(GOFGXCPool.abi, GOFGXCPool.address);\n let ht_pool = new web3.eth.Contract(GOFHTPool.abi, GOFHTPool.address);\n // let link_pool = new web3.eth.Contract(GOFLIKPool.abi, GOFLIKPool.address);\n // let usdt_pool = new web3.eth.Contract(GOFUSDTPool.abi, GOFUSDTPool.address);\n // let eth_pool = new web3.eth.Contract(GOFETHPool.abi, GOFETHPool.address);\n // let yfii_pool = new web3.eth.Contract(GOFYFIIPool.abi, GOFYFIIPool.address);\n\n await Promise.all([\n gxc_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000}),\n ht_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000 }),\n // link_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000 }),\n // usdt_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000 }),\n // eth_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000 }),\n // yfii_pool.methods.setRewardDistribution(reward_account).send({ from: reward_account, gasPrice: gas_price, gas: 100000 }),\n ]);\n\n console.log(\"[Golff] 4.Start reward Gof to pool\");\n\n let init_quota = web3.utils.toBN(10 ** 18).mul(web3.utils.toBN(40000));\n\n // await Promise.all([\n // gxc_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas:150000}),\n // ht_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas: 150000 }),\n // // link_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas: 150000 }),\n // // usdt_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas: 150000 }),\n // // eth_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas: 150000 }),\n // // yfii_pool.methods.notifyRewardAmount(init_quota.toString()).send({ from: reward_account, gasPrice: gas_price, gas: 150000 }),\n // ]);\n}", "deployArtifacts() {\n let singleDeploy = {};\n singleDeploy.action = \"deploy\";\n singleDeploy.unitInfo = this.deployFile.unitInfo;\n singleDeploy.unitInfo.path = angular.copy(this.deployFile.targetPath);\n singleDeploy.fileName = this.deployFile.fileName;\n singleDeploy.repoKey = this.deployFile.repoDeploy.repoKey;\n\n if (this.deployFile.unitInfo.Internal && this.deployFile.unitConfigFileContent) {\n singleDeploy.publishUnitConfigFile = true;\n singleDeploy.unitConfigFileContent = this.deployFile.unitConfigFileContent;\n }\n if (!this.deployFile.unitInfo.bundle) {\n this.artifactDeployDao.post(singleDeploy).$promise.then((result)=> {\n if (result.data) {\n this.deploySuccess(result.data);\n }\n });\n }\n else {\n this.artifactDeployDao.postBundle(singleDeploy).$promise.then((result)=> {\n if (result.data) {\n this.deploySuccess(result.data);\n }\n });\n }\n }", "async function init() {\n program\n .usage('[options]')\n .option('-a, --address <address>', 'Address of Deployer contract')\n .option('-n, --network <network>', 'Name of the network (e.g. ropsten, mainnet, etc.)')\n .parse(process.argv)\n\n const options = program.opts()\n const address = options.address\n const network = options.network\n let admins = []\n\n if (!address) {\n throw new Error('Address not given')\n } else {\n console.log('address', address)\n }\n\n if (fs.existsSync(adminFile)) {\n admins = fs.readFileSync(adminFile, 'utf8').split('\\n')\n console.log('admins', admins)\n } else {\n console.log(`No admin addreses set on ${adminFile}`)\n }\n\n const provider = getProvider(network, 1)\n const web3 = new Web3(provider)\n const networkId = await web3.eth.net.getId()\n console.log('networkId', networkId)\n\n const accounts = await web3.eth.getAccounts()\n const [account] = accounts\n console.log(`Owner: ${account}`)\n\n const deployer = new web3.eth.Contract(Deployer.abi, address)\n const isAdmin = await deployer.methods.isAdmin(account).call();\n console.log('isAdmin', isAdmin)\n\n const baseTokenUri = await deployer.methods.baseTokenUri().call();\n console.log('baseTokenUri', baseTokenUri)\n\n const existingAdmins = await deployer.methods.getAdmins().call();\n console.log('existingAdmins', existingAdmins)\n\n if (Array.isArray(existingAdmins)) {\n const newAdmins = []\n for (let index = 0; index < admins.length; index++) {\n const admin = admins[index]\n if (existingAdmins.findIndex(item => item.toLowerCase() === admin.toLowerCase()) < 0) {\n console.log(`Granting '${admin}' admin right`)\n newAdmins.push(admin)\n }\n }\n if (newAdmins.length > 0) {\n console.log(newAdmins)\n await deployer.methods.grant(newAdmins).send({ from: account, gas: 200000 })\n }\n }\n}", "async function deployContract(){\n\n let abiPath = path.join(__dirname + '/bin/DataStorageEvent.abi');\n let binPath = path.join(__dirname + '/bin/DataStorageEvent.bin');\n\n console.log(chalk.green(abiPath));\n console.log(chalk.green(binPath));\n\n let abi = fs.readFileSync(abiPath);\n // let bin = '0x' + fs.readFileSync(binPath); updated version of ganache-cli does not need 'Ox' to be added to depict hexadecimal.\n let bin = fs.readFileSync(binPath);\n\n\n let contract = new web3.eth.Contract(JSON.parse(abi));\n\n console.log()\n // Returns an object of abstract contract.\n let status = await contract.deploy({\n data: bin,\n arguments: [100]\n }).send({\n from: '0x96b6E861698DfBA5721a3Ccd9AfBCa808e360bf3',\n gasPrice: 1000,\n gas: 300000\n })\n\n console.log(chalk.red('Address of Contract Deployed : ' + status.options.address));\n}", "function deploy(bytecode, abi, pipe) {\n\n}", "function DeployContract(eth_accountAddr,eth_bytecode){\n\n\t// if( typeof eth_arguments != undefined)\n\t// {\n\t// \tvar _arguments = eth_arguments;\n\t// }\n\tdataString = {\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"id\":1,\"params\":[{\n\t\t\"from\": eth_accountAddr,\n\t\t\"data\":eth_bytecode,\n\n\t}]}\n\toptions = {\n url: REQUESTURL,\n method:'POST',\n headers:headers,\n body: dataString,\n json: true\n\t}\n\treturn options;\n}", "function deploy(func, args, save_path, cb){\n\tconsole.log(\"[obc-js] Deploying Chaincode - Start\");\n\tconsole.log(\"\\n\\n\\t Waiting...\");\t\t\t\t\t\t\t\t\t\t//this can take awhile\n\tvar options = {path: '/devops/deploy'};\n\tvar body = \t{\n\t\t\t\t\ttype: \"GOLANG\",\n\t\t\t\t\tchaincodeID: {\n\t\t\t\t\t\t\tpath: chaincode.details.git_url\n\t\t\t\t\t\t},\n\t\t\t\t\tctorMsg:{\n\t\t\t\t\t\t\t\"function\": func,\n\t\t\t\t\t\t\t\"args\": args\n\t\t\t\t\t}\n\t\t\t\t};\n\toptions.success = function(statusCode, data){\n\t\tconsole.log(\"\\n\\n\\t deploy success [wait 1 more minute]\");\n\t\tchaincode.details.deployed_name = data.message;\n\t\tobc.prototype.save(tempDirectory);\t\t\t\t\t\t\t\t\t//save it so we remember we have deployed\n\t\tif(save_path != null) obc.prototype.save(save_path);\t\t\t\t//user wants the updated file somewhere\n\t\tif(cb){\n\t\t\tsetTimeout(function(){\n\t\t\t\tconsole.log(\"[obc-js] Deploying Chaincode - Complete\");\n\t\t\t\tcb(null, data);\n\t\t\t}, 60000);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//wait extra long, not always ready yet\n\t\t}\n\t};\n\toptions.failure = function(statusCode, e){\n\t\tconsole.log(\"[obc-js] deploy - failure:\", statusCode);\n\t\tif(cb) cb(eFmt('http error', statusCode, e), null);\n\t};\n\trest.post(options, '', body);\n}", "function contractDropdown (events, self) {\n var instanceContainer = self._view.instanceContainer\n var instanceContainerTitle = self._view.instanceContainerTitle\n instanceContainer.appendChild(instanceContainerTitle)\n instanceContainer.appendChild(self._view.noInstancesText)\n var compFails = yo`<i title=\"Contract compilation failed. Please check the compile tab for more information.\" class=\"fa fa-times-circle ${css.errorIcon}\" ></i>`\n var info = yo`<i class=\"fa fa-info ${css.infoDeployAction}\" aria-hidden=\"true\" title=\"*.sol files allows deploying and accessing contracts. *.abi files only allows accessing contracts.\"></i>`\n\n var newlyCompiled = (success, data, source, compiler, compilerFullName) => {\n getContractNames(success, data, compiler, compilerFullName)\n if (success) {\n compFails.style.display = 'none'\n document.querySelector(`.${css.contractNames}`).classList.remove(css.contractNamesError)\n } else {\n compFails.style.display = 'block'\n document.querySelector(`.${css.contractNames}`).classList.add(css.contractNamesError)\n }\n }\n\n self._deps.pluginManager.event.register('sendCompilationResult', (file, source, languageVersion, data) => {\n // TODO check whether the tab is configured\n let compiler = new CompilerAbstract(languageVersion, data)\n self._deps.compilersArtefacts[languageVersion] = compiler\n self._deps.compilersArtefacts['__last'] = compiler\n newlyCompiled(true, data, source, compiler, languageVersion)\n })\n\n self._deps.compiler.event.register('compilationFinished', (success, data, source) => {\n var name = 'solidity'\n let compiler = new CompilerAbstract(name, data)\n self._deps.compilersArtefacts[name] = compiler\n self._deps.compilersArtefacts['__last'] = compiler\n newlyCompiled(success, data, source, self._deps.compiler, name)\n })\n\n var deployAction = (value) => {\n self._view.createPanel.style.display = value\n self._view.orLabel.style.display = value\n }\n\n self._deps.fileManager.event.register('currentFileChanged', (currentFile) => {\n document.querySelector(`.${css.contractNames}`).classList.remove(css.contractNamesError)\n var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)\n contractNames.innerHTML = ''\n if (/.(.abi)$/.exec(currentFile)) {\n deployAction('none')\n compFails.style.display = 'none'\n contractNames.appendChild(yo`<option>(abi)</option>`)\n selectContractNames.setAttribute('disabled', true)\n } else if (/.(.sol)$/.exec(currentFile)) {\n deployAction('block')\n }\n })\n\n var atAddressButtonInput = yo`<input class=\"${css.input} ataddressinput\" placeholder=\"Load contract from Address\" title=\"atAddress\" />`\n var selectContractNames = yo`<select class=\"${css.contractNames}\" disabled></select>`\n\n function getSelectedContract () {\n var contract = selectContractNames.children[selectContractNames.selectedIndex]\n var contractName = contract.innerHTML\n var compiler = self._deps.compilersArtefacts[contract.getAttribute('compiler')]\n if (!compiler) return null\n\t\n if (contractName) {\n return {\n name: contractName,\n contract: compiler.getContract(contractName),\n compiler\n }\n }\n return null\n }\n\n self._view.createPanel = yo`<div class=\"${css.button}\"></div>`\n self._view.orLabel = yo`<div class=\"${css.orLabel}\">or</div>`\n var el = yo`\n <div class=\"${css.container}\">\n <div class=\"${css.subcontainer}\">\n ${selectContractNames} ${compFails} ${info}\n </div>\n <div>\n ${self._view.createPanel}\n ${self._view.orLabel}\n <div class=\"${css.button} ${css.atAddressSect}\">\n <div class=\"${css.atAddress}\" onclick=${function () { loadFromAddress() }}>At Address</div>\n ${atAddressButtonInput}\n </div>\n </div>\n </div>\n `\n\n function setInputParamsPlaceHolder () {\n self._view.createPanel.innerHTML = ''\n if (selectContractNames.selectedIndex >= 0 && selectContractNames.children.length > 0) {\n var selectedContract = getSelectedContract()\n var ctrabi = txHelper.getConstructorInterface(selectedContract.contract.object.abi)\n var ctrEVMbc = selectedContract.contract.object.evm.bytecode.object\n var createConstructorInstance = new MultiParamManager(0, ctrabi, (valArray, inputsValues) => {\n createInstance(inputsValues, selectedContract.compiler)\n }, txHelper.inputParametersDeclarationToString(ctrabi.inputs), 'Deploy', ctrEVMbc)\n self._view.createPanel.appendChild(createConstructorInstance.render())\n return\n } else {\n self._view.createPanel.innerHTML = 'No compiled contracts'\n }\n }\n\n selectContractNames.addEventListener('change', setInputParamsPlaceHolder)\n\n function createInstanceCallback (selectedContract, data) {\n self._deps.logCallback(`creation of ${selectedContract.name} pending...`)\n if (data) {\n data.contractName = selectedContract.name\n data.linkReferences = selectedContract.contract.object.evm.bytecode.linkReferences\n data.contractABI = selectedContract.contract.object.abi\n }\n self._deps.udapp.createContract(data, (error, txResult) => {\n if (!error) {\n var isVM = executionContext.isVM()\n if (isVM) {\n var vmError = txExecution.checkVMError(txResult)\n if (vmError.error) {\n self._deps.logCallback(vmError.message)\n return\n }\n }\n if (txResult.result.status && txResult.result.status === '0x0') {\n self._deps.logCallback(`creation of ${selectedContract.name} errored: transaction execution failed`)\n return\n }\n var noInstancesText = self._view.noInstancesText\n if (noInstancesText.parentNode) { noInstancesText.parentNode.removeChild(noInstancesText) }\n var address = isVM ? txResult.result.createdAddress : txResult.result.contractAddress\n instanceContainer.appendChild(self._deps.udappUI.renderInstance(selectedContract.contract.object, address, selectContractNames.value))\n } else {\n self._deps.logCallback(`creation of ${selectedContract.name} errored: ${error}`)\n }\n })\n }\n\n // DEPLOY INSTANCE\n function createInstance (args, compiler) {\n var selectedContract = getSelectedContract()\n\n if (selectedContract.contract.object.evm.bytecode.object.length === 0) {\n modalDialogCustom.alert('This contract does not implement all functions and thus cannot be created.')\n return\n }\n\n var forceSend = () => {\n var constructor = txHelper.getConstructorInterface(selectedContract.contract.object.abi)\n self._deps.filePanel.compilerMetadata().deployMetadataOf(selectedContract.name, (error, contractMetadata) => {\n if (error) return self._deps.logCallback(`creation of ${selectedContract.name} errored: ` + error)\n if (!contractMetadata || (contractMetadata && contractMetadata.autoDeployLib)) {\n txFormat.buildData(selectedContract.name, selectedContract.contract.object, compiler.getContracts(), true, constructor, args, (error, data) => {\n if (error) return self._deps.logCallback(`creation of ${selectedContract.name} errored: ` + error)\n createInstanceCallback(selectedContract, data)\n }, (msg) => {\n self._deps.logCallback(msg)\n }, (data, runTxCallback) => {\n // called for libraries deployment\n self._deps.udapp.runTx(data, runTxCallback)\n })\n } else {\n if (Object.keys(selectedContract.contract.object.evm.bytecode.linkReferences).length) self._deps.logCallback(`linking ${JSON.stringify(selectedContract.contract.object.evm.bytecode.linkReferences, null, '\\t')} using ${JSON.stringify(contractMetadata.linkReferences, null, '\\t')}`)\n txFormat.encodeConstructorCallAndLinkLibraries(selectedContract.contract.object, args, constructor, contractMetadata.linkReferences, selectedContract.contract.object.evm.bytecode.linkReferences, (error, data) => {\n if (error) return self._deps.logCallback(`creation of ${selectedContract.name} errored: ` + error)\n createInstanceCallback(selectedContract, data)\n })\n }\n })\n }\n\n if (selectedContract.contract.object.evm.deployedBytecode && selectedContract.contract.object.evm.deployedBytecode.object.length / 2 > 24576) {\n modalDialog('Contract code size over limit', yo`<div>Contract creation initialization returns data with length of more than 24576 bytes. The deployment will likely fails. <br>\n More info: <a href=\"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-170.md\" target=\"_blank\">eip-170</a>\n </div>`,\n {\n label: 'Force Send',\n fn: () => {\n forceSend()\n }}, {\n label: 'Cancel',\n fn: () => {\n self._deps.logCallback(`creation of ${selectedContract.name} canceled by user.`)\n }\n })\n } else {\n forceSend()\n }\n }\n\n // ACCESS DEPLOYED INSTANCE\n function loadFromAddress () {\n var noInstancesText = self._view.noInstancesText\n if (noInstancesText.parentNode) { noInstancesText.parentNode.removeChild(noInstancesText) }\n var address = atAddressButtonInput.value\n if (!ethJSUtil.isValidAddress(address)) {\n return modalDialogCustom.alert('Invalid address.')\n }\n if (/[a-f]/.test(address) && /[A-F]/.test(address) && !ethJSUtil.isValidChecksumAddress(address)) {\n return modalDialogCustom.alert('Invalid checksum address.')\n }\n if (/.(.abi)$/.exec(self._deps.config.get('currentFile'))) {\n modalDialogCustom.confirm(null, 'Do you really want to interact with ' + address + ' using the current ABI definition ?', () => {\n var abi\n try {\n abi = JSON.parse(self._deps.editor.currentContent())\n } catch (e) {\n return modalDialogCustom.alert('Failed to parse the current file as JSON ABI.')\n }\n instanceContainer.appendChild(self._deps.udappUI.renderInstanceFromABI(abi, address, address))\n })\n } else {\n var selectedContract = getSelectedContract()\n instanceContainer.appendChild(self._deps.udappUI.renderInstance(selectedContract.contract.object, address, selectContractNames.value))\n }\n }\n\n // GET NAMES OF ALL THE CONTRACTS\n function getContractNames (success, data, compiler, compilerFullName) {\n var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)\n contractNames.innerHTML = ''\n if (success) {\n selectContractNames.removeAttribute('disabled')\n compiler.visitContracts((contract) => {\n contractNames.appendChild(yo`<option compiler=\"${compilerFullName}\">${contract.name}</option>`)\n })\n } else {\n selectContractNames.setAttribute('disabled', true)\n }\n setInputParamsPlaceHolder()\n }\n\n return el\n}", "prepareContract(contract) {\n let options = contract.options,\n classRefStr = contract.classRef.toString();\n\n // `params` is a list of constructor arguments\n if (!contract.params)\n {\n // Check if there is an injectable list\n if (!options.inject && options.autodetect !== false)\n {\n options.inject = this.extractInjectParams(classRefStr);\n }\n }\n\n // --debug-start--\n if (options.inject && options.augment)\n {\n console.warn(`#register(${contractStr}): the 'inject' setting will be used instead of 'augment'`);\n }\n // --debug-end--\n \n\n // Keep it simple; using both is not allowed\n if (!options.inject && options.augment)\n {\n contract.classRef = this.augment(classRef, classRefStr);\n }\n }", "constructor(web3, contract, accounts) {\n this.web3 = web3;\n this.contract = contract;\n this.accounts = accounts;\n }", "function deploy(args) {\n return __awaiter(this, void 0, void 0, function* () {\n const argsWithDefaults = (0, utilities_1.getDefaultSettings)(args);\n const logger = new utilities_1.Logger(argsWithDefaults[\"log-level\"]);\n const timings = new utilities_1.Timings();\n yield (0, deploy_1.deploy)(argsWithDefaults, logger, timings);\n });\n}", "function on_deploy(details)\n {\n if (details.reason === \"install\") { on_install(); }\n else if (details.reason === \"update\") { on_update(); }\n }", "function setDeploymentParameters()\r\n{\r\n\ttry\r\n\t{\r\n\t\t\r\n\t\tif (nlapiGetContext().getSetting('SCRIPT', 'custscript_pricelist_debugtrace') == 'T')\r\n\t\t{ debugOn = true; } else { debugOn = false; }\r\n\t\t\r\n\t\tvar formidParam = nlapiGetContext().getSetting('SCRIPT', 'custscript_estimate_formid');\r\n\t\tif (formidParam != '' && formidParam != null)\r\n\t\t{ estimateFormID = formidParam; } else { estimateFormID = 111; }\t\r\n\t\t\r\n\t}\r\n\tcatch (e)\r\n\t{\r\n\t\terrorHandler(\"setDeploymentParameters\", e);\r\n\t}\r\n}", "function processConfigOptions() {\n if (OPTIONS.base_dir === 'cwd' || OPTIONS.base_dir === './') {\n OPTIONS.base_dir = soi.utils.normalizeSysPath(process.cwd() + '/');\n } else {\n OPTIONS.base_dir = soi.utils.normalizeSysPath(\n path.resolve(process.cwd() + '/', OPTIONS.base_dir) + '/');\n }\n\n if (OPTIONS.dist_dir) {\n OPTIONS.dist_dir = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.dist_dir) + '/');\n }\n if (OPTIONS.module_loader) {\n OPTIONS.module_loader = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.module_loader));\n }\n if (OPTIONS.map_file) {\n OPTIONS.map_file = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.map_file));\n }\n if (OPTIONS.output_base) {\n OPTIONS.output_base = soi.utils.normalizeSysPath(\n path.resolve(OPTIONS.base_dir, OPTIONS.output_base) + '/');\n }\n\n // clean(OPTIONS.dist_dir, function(err) {});\n\n // newly added\n if (OPTIONS.bundles.img) {\n processStaticBundles(OPTIONS.bundles.img);\n }\n\n if (OPTIONS.bundles.swf) {\n processStaticBundles(OPTIONS.bundles.swf);\n }\n\n if (OPTIONS.bundles.htc) {\n processStaticBundles(OPTIONS.bundles.htc);\n }\n\n if (OPTIONS.bundles.font) {\n processStaticBundles(OPTIONS.bundles.font);\n }\n\n if (OPTIONS.bundles.css) {\n processDynamicBundles(OPTIONS.bundles.css);\n }\n\n if (OPTIONS.bundles.js) {\n processDynamicBundles(OPTIONS.bundles.js);\n }\n\n // added default ones, because we don't read in it as first\n // calling soi.config.extend\n soi.config.extend({\n optimizer: OPTIONS\n });\n}", "async function deployContract(walletObj) {\n console.log('DCWalletBuild', DCWalletBuild)\n\n // Create an instance of a Contract Factory\n let factory = new ethers.ContractFactory(DCWalletBuild.abi, DCWalletBuild.bytecode, walletObj);\n console.log('factory done')\n\n // Notice we pass in \"Hello World\" as the parameter to the constructor\n let provider = new ethers.providers.Web3Provider(wallet);\n let network = await provider.getNetwork();\n contract = await factory.deploy([USDC.networks[network.chainId].address, TCAD.networks[network.chainId].address]);\n console.log('factory.deploy done')\n\n // The address the Contract WILL have once mined\n // See: https://ropsten.etherscan.io/address/0x2bd9aaa2953f988153c8629926d22a6a5f69b14e\n console.log('contract.address', contract.address);\n // \"0x2bD9aAa2953F988153c8629926D22A6a5F69b14E\"\n\n // The transaction that was sent to the network to deploy the Contract\n // See: https://ropsten.etherscan.io/tx/0x159b76843662a15bd67e482dcfbee55e8e44efad26c5a614245e12a00d4b1a51\n console.log('contract.deployTransaction.hash', contract.deployTransaction.hash);\n // \"0x159b76843662a15bd67e482dcfbee55e8e44efad26c5a614245e12a00d4b1a51\"\n\n // The contract is NOT deployed yet; we must wait until it is mined\n await contract.deployed()\n\n // Done! The contract is deployed.\n return contract.address\n}", "async function deployRs(deployer, network) {\n let reserveToken = \"0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8\"; // ycrv\n let uniswap_factory = \"0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f\";\n await deployer.deploy(TATOReserves, reserveToken, TATOProxy.address);\n await deployer.deploy(TATORebaser,\n TATOProxy.address,\n reserveToken,\n uniswap_factory,\n TATOReserves.address\n );\n let rebase = new web3.eth.Contract(TATORebaser.abi, TATORebaser.address);\n\n let pair = await rebase.methods.uniswap_pair().call();\n console.log(\"TATO <-> YCRV UNISWAP Pair: \", pair)\n let tato = await TATOProxy.deployed();\n await tato._setRebaser(TATORebaser.address);\n console.log(\"tato._setRebaser\");\n let reserves = await TATOReserves.deployed();\n await reserves._setRebaser(TATORebaser.address)\n console.log(\"reserves._setRebaser\");\n\n}", "_initDeploy() {\n let UPLOAD_REST_URL = `${API.API_URL}/artifact/upload`;\n this.deploySingleUploader = this.artifactoryUploaderFactory.getUploaderInstance(this)\n .setUrl(UPLOAD_REST_URL)\n .setOnSuccessItem(this.onSuccessItem)\n .setOnAfterAddingAll(this.onAfterAddingAll)\n .setOnAfterAddingFile(this.onAfterAddingFile)\n .setOnErrorItem(this.onUploadError)\n .setOnCompleteAll(this.onCompleteAll);\n\n this._setPathAndFileType(this.node.data.path);\n\n // set data from currently open node\n }", "async function deployQuotaDistribution(deployer, network) {\n \n let bnb = await BNB.deployed();\n\n console.log(\"[Golff] 1.Start deploy QuotaDistribution on Network= \" + network);\n\n await deployer.deploy(QuotaDistribution, 1599904800, 175);\n \n console.log(\"[Golff] 2.Start add minter acl for distribution\");\n\n bnb.addMinter(QuotaDistribution.address);\n\n console.log(\"[Golff] 3.Start set quota distributor\");\n\n let disribution_account = \"0x424abfc7c0Defb02447D621Bf0f6eF80eD5C01fB\";\n\n let quota_distribution = new web3.eth.Contract(QuotaDistribution.abi, QuotaDistribution.address);\n\n await Promise.all([\n quota_distribution.methods.setQuotaDistribution(disribution_account).send({from: disribution_account}),\n ]);\n\n let init_quota = web3.utils.toBN(10 ** 18).mul(web3.utils.toBN(1000000 * 100));//.div(web3.utils.toBN(10 ** 4));\n \n console.log(\"[Golff] 4.Start set quota distributor\");\n\n await Promise.all([\n quota_distribution.methods.addOrgQuota(disribution_account, init_quota.toString()).send({from: disribution_account}),\n ]);\n \n console.log(\"[Golff] 5.Start set quota distributor\");\n\n await Promise.all([\n quota_distribution.methods.distributeQuota().send({from:disribution_account}),\n ]);\n}", "function vms_deploy() {\n _.each(server_list, function(data, hostname, i) {\n vm_create(hostname);\n });\n //self.reset_server_list();\n }", "createEnvironment(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n\n let apiInstance = new Bitbucket.DeploymentsApi(); // String | The account // String | The repository // DeploymentEnvironment | The environment to create.\n /*let username = \"username_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ /*let body = new Bitbucket.DeploymentEnvironment();*/ apiInstance.createEnvironment(\n incomingOptions.username,\n incomingOptions.repoSlug,\n incomingOptions.body,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }" ]
[ "0.7261169", "0.6316964", "0.57954097", "0.55136895", "0.5453097", "0.5438545", "0.5392325", "0.53471273", "0.5239186", "0.5185985", "0.5051503", "0.5004959", "0.4959975", "0.49317", "0.49084374", "0.4884491", "0.4848416", "0.48382464", "0.48246276", "0.4811499", "0.47355208", "0.47094244", "0.46575847", "0.46537918", "0.46452072", "0.46414793", "0.4641393", "0.45899078", "0.45889175", "0.455969" ]
0.6881086
1
Return a bool indicating if this listing has been whitelisted
isWhitelisted(listing) { return __awaiter(this, void 0, void 0, function* () { const deployed = this.requireDeployed(); return yield deployed.methods.isWhitelisted(listing).call(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isBlacklisted() {\n\t var blacklist = this.opts.blacklist;\n\t return blacklist && blacklist.indexOf(this.node.type) > -1;\n\t}", "function isBlacklisted() {\n\t var blacklist = this.opts.blacklist;\n\t return blacklist && blacklist.indexOf(this.node.type) > -1;\n\t}", "function isBlacklisted() {\n var blacklist = this.opts.blacklist;\n return blacklist && blacklist.indexOf(this.node.type) > -1;\n}", "function isBlacklistedItem(item) {\n\t\tlogTrace('invoking isBlacklistedItem($)', item);\n\n\t\t// blacklisted for being a rerun\n\t\tif (hideReruns && (item.rerun === true)) { return true; }\n\n\t\tif (storedBlacklistedItems[item.type] === undefined) { return false; }\n\n\t\t// blacklisted by name\n\t\tif (matchTerms(item.name, item.type)) {\n\n\t\t\tlogTrace('blacklisted by name:', item.name);\n\t\t\treturn true;\n\t\t}\n\n\t\t// blacklisted by category\n\t\tif (matchTerms(item.category, 'categories')) {\n\n\t\t\tlogTrace('blacklisted by category:', item.category);\n\t\t\treturn true;\n\t\t}\n\n\t\t// blacklisted by tag\n\t\tconst tagsLength = item.tags.length;\n\t\tfor (let i = 0; i < tagsLength; i++) {\n\n\t\t\tif (matchTerms(item.tags[i].name, 'tags')) {\n\n\t\t\t\tlogTrace('blacklisted by tag:', item.tags[i].name);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// blacklisted by title\n\t\tif (matchTerms(item.title, 'titles')) {\n\n\t\t\tlogTrace('blacklisted by title:', item.title);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "_isWhiteListed(domain) {\n const {domains} = this.props;\n return _.isObject(_.find(domains, object => {\n return object.domain === domain;\n }));\n }", "isWhitelistBtc(address) {\n return this.#whitelistBtc.indexOf(address) !== -1\n }", "canShowButlerUI() {\n if (this.hasEnterprise()) {\n if (\n featureFlagClient\n .get('workflowers.butler-ent-admin-only-allowlist', [])\n .includes(this.get('idEnterprise'))\n ) {\n return (\n this.getEnterprise().isAdmin(Auth.me()) ||\n (this.get('idOrganization') &&\n this.getOrganization()?.isAdmin(Auth.me()))\n );\n }\n }\n return true;\n }", "function userCanFetchShoppingList(account, shoppingList) {\r\n var userHasRight = false;\r\n if (account.shoppingLists.indexOf(shoppingList._id) > -1 && shoppingList.isActive) {\r\n userHasRight = true;\r\n }\r\n else {\r\n userHasRight = false;\r\n }\r\n return userHasRight;\r\n}", "async isAllowed() {\n return config.isDeveloperMode;\n }", "function _isBlocked() {\r\n var isblock = $.blockUI.IsPageBlocked();\r\n return isblock == null ? false : true;\r\n }", "shouldQuarantine () {\n for (let index = 0; index < this.passengerList.length; index += 1) {\n let passengersHealth = this.passengerList [index];\n if (passengersHealth.isHealthy === false) {\n return true;\n }\n }\n return false;\n }", "shouldQuarantine() {\r\n if (this.passengers.map(passenger => (passenger.isHealthy)).includes(false)) {\r\n return true\r\n } else {\r\n return false\r\n }\r\n\r\n }", "function isBlacklistedUser(author, guild){\r\n\tconst specs = utils.getSpecifics(guild);\r\n\tfor (let i = 0; i < specs.blacklist.length; i++){\r\n\t\tconst thisBlacklistId = specs.blacklist[i];\r\n\t\tif (thisBlacklistId.search(author.id) > -1){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}", "isTagWhitelisted( v ){\n return !!this.getWhitelistItem(v)\n /*\n return this.settings.whitelist.some(item =>\n typeof v == 'string'\n ? sameStr(this.trim(v), (item.value || item))\n : sameStr(JSON.stringify(item), JSON.stringify(v))\n )\n */\n }", "function isUrlListed(url) {\n return appSettings.appendAuthTokenUrls && \n _.some(appSettings.appendAuthTokenUrls, function (listedUrl) { return _.startsWith(url, listedUrl) });\n }", "get whitelist(){\n return this._whitelist;\n }", "isUserList() {}", "shouldQuarantine() {\n const healthy = this.passengers.some(traveler => traveler.isHealthy === false)\n return healthy\n }", "isSecurityEnabled() {\n\t\treturn this._memberServices !== undefined;\n\t}", "function isEnabled() {\n return (tracker.currentWidget !== null &&\n tracker.currentWidget === app.shell.currentWidget);\n }", "isTagBlacklisted( v ){\n v = this.trim(v.toLowerCase());\n return this.settings.blacklist.filter(x => (\"\"+x).toLowerCase() == v).length;\n }", "get isBlocked() {\n\n }", "isEnabled() {\n return this.enabled && this.severity >= exports.Severity.WARN;\n }", "_includedInFilter(filter) {\n return (typeof filter === 'boolean' && filter === true);\n }", "function inWhiteList(domain){\n\t\tif(domain.length==0)return false;\n\t\n\t\t//TODO: populate this line with 2nd level domains\n\t\t//whitelist = \"dirty.ru, livejournal.com, wikipedia.org, leprosorium.ru, rian.ru, ebay.com, flickr.com, lenta.ru, yandex.net, yandex.ru, youtube.com, 1tv.ru, wikimedia.org, nytimes.com, d3search.ru, adm-dirty.ru\";\n\t\tvar whitelist = jsonParse( localStorGetItem( 'faviconsWhitelist',\"[]\"));\n\t\t\n\t\tif(whitelist == \"*\"){\n\t\t\treturn true;\n\t\t}else{\n\t\t\twhitelist = whitelist+\",\";\n\t\t\t//next line done in the caller function\n\t\t\t//domain = extractDomain(domain);\n\t\t\tif(whitelist.indexOf(domain+\",\")>-1) {\n\t\t\t\treturn true;\n\t\t\t}else{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\n\t}", "isRunning() {\n return this.feedStartTime !== null;\n }", "function isWatching(name) {\r\n if (profiles_watched == undefined) {\r\n var list = localStorage.getItem(STORAGE_NAME);\r\n if (list != undefined)\r\n profiles_watched = list.split(STORAGE_SEP);\r\n else\r\n profiles_watched = new Array();\r\n }\r\n\r\n for (var i=0; i<profiles_watched.length; ++i) {\r\n if (profiles_watched[i] == name)\r\n return 1\r\n }\r\n\r\n return 0;\r\n}", "get disabled() { return this._disabled || !!(this._list && this._list.disabled); }", "get disabled() { return this._disabled || !!(this._list && this._list.disabled); }", "haveToShowAdditionalFilters() {\n const {filterType} = this.state;\n if (filterType === null) {\n return false;\n }\n const additionalFilters = this.getAdditionalFilters();\n return (additionalFilters !== null);\n }" ]
[ "0.6541155", "0.6541155", "0.6449632", "0.6285243", "0.5984127", "0.59645337", "0.591445", "0.59121346", "0.580228", "0.57853556", "0.5738085", "0.5717761", "0.56691015", "0.5668057", "0.5640495", "0.5622889", "0.559966", "0.55952406", "0.5587593", "0.5568334", "0.5550307", "0.5525174", "0.5523325", "0.548344", "0.546851", "0.5466401", "0.54646915", "0.54562396", "0.54562396", "0.5446313" ]
0.6948313
0
Return the name passed to this contract instance at deploy time
name() { return __awaiter(this, void 0, void 0, function* () { const deployed = this.requireDeployed(); return yield deployed.methods.name().call(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deploySingle(contractName){\n return `\n const A = artifacts.require(\"${contractName}\");\n module.exports = function(deployer) { deployer.deploy(A) };\n `;\n}", "function getAssetName(assetAddr){\n return tokenContract.methods.getContractName(assetAddr).call();\n }", "function getName() { return name; }", "contract(name) {\n return this.repo.contract(name);\n }", "function getName() {\n\treturn name;\n}", "get name() {\n return pkg.name;\n }", "getName() {\n return this.steamInventoryItemResponse.market_hash_name;\n }", "get packageName() {\n return this.portfolioRuntime.currentPackage.name\n }", "getName() {}", "static getName() {\n return `com.serverless.${ServerlessWebpack.name}`;\n }", "get bucketName() {\n return artifactAttribute(this, 'BucketName');\n }", "async function deployContract(){\n\n let abiPath = path.join(__dirname + '/bin/DataStorageEvent.abi');\n let binPath = path.join(__dirname + '/bin/DataStorageEvent.bin');\n\n console.log(chalk.green(abiPath));\n console.log(chalk.green(binPath));\n\n let abi = fs.readFileSync(abiPath);\n // let bin = '0x' + fs.readFileSync(binPath); updated version of ganache-cli does not need 'Ox' to be added to depict hexadecimal.\n let bin = fs.readFileSync(binPath);\n\n\n let contract = new web3.eth.Contract(JSON.parse(abi));\n\n console.log()\n // Returns an object of abstract contract.\n let status = await contract.deploy({\n data: bin,\n arguments: [100]\n }).send({\n from: '0x96b6E861698DfBA5721a3Ccd9AfBCa808e360bf3',\n gasPrice: 1000,\n gas: 300000\n })\n\n console.log(chalk.red('Address of Contract Deployed : ' + status.options.address));\n}", "static get _TYPE() {\n return 'deployment';\n }", "getMainServiceProviderName() {\n return this._serviceProvider.name || 'N/A';\n }", "function getFullyQualifiedName(sourceName, contractName) {\n return `${sourceName}:${contractName}`;\n}", "publicName() {\n if (this.isSnapshot()) {\n return `${this.name}-${Date.parse(this.snapshotDate)}`;\n }\n if (this.isVirtualDirectory()) {\n return Buffer.from(this.name, 'utf8').toString('base64');\n }\n return this.name;\n }", "get name() {\n return this.use().name;\n }", "getName() {\n return this._name || '';\n }", "function getContractObject(){\n let abiPath = path.join(__dirname + '/bin/DataStorageEvent.abi');\n let abi = fs.readFileSync(abiPath);\n\n // Replace the contract address with the contract you want to invoke.\n // let contractAddress = '0xadb1e7fea9a24daee48492c3523721ea6b42f271'; // address of the deployed contract\n let options = {\n from: '0x96b6E861698DfBA5721a3Ccd9AfBCa808e360bf3',\n gasPrice: 1000,\n gas: 300000\n };\n let deployedContract = new web3.eth.Contract(JSON.parse(abi),contractAddress,options);\n return deployedContract;\n}", "getName() {\n return this.configs.name\n }", "getName () {\n return this._name;\n }", "getName() {\n return this._executeAfterInitialWait(() => this.currently.getAttribute('name'));\n }", "getName () {\n\t\treturn this.name;\n\t}", "getName() {\n const stageHyphen = this.stage.length > 0 ? '-' : '';\n const nameHyphen = this.name.length > 0 ? '-' : '';\n return this.project + nameHyphen + this.name + stageHyphen + this.stage;\n }", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}" ]
[ "0.63645667", "0.60966045", "0.5953498", "0.59323144", "0.58770484", "0.57235014", "0.566225", "0.5619028", "0.56117105", "0.55981636", "0.5573826", "0.5566985", "0.55458844", "0.55158335", "0.5502829", "0.55023736", "0.54788876", "0.54555434", "0.54370517", "0.5435066", "0.54124546", "0.54074275", "0.539746", "0.53933644", "0.53697157", "0.53697157", "0.53697157", "0.53697157", "0.53697157", "0.53697157" ]
0.616771
1
Updates a listingHash's status from 'application' to 'listing' or resolves a challenge if one exists. Delegates to `whitelistApplication` or `resolveChallenge`
updateStatus(listing, opts) { return __awaiter(this, void 0, void 0, function* () { const account = this.requireAccount(opts), deployed = this.requireDeployed(); return yield deployed.methods.updateStatus(listing).send({ from: account }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "appWasMade(listing) {\n return __awaiter(this, void 0, void 0, function* () {\n const deployed = this.requireDeployed();\n return deployed.methods.appWasMade(listing).call();\n });\n }", "function handleUpdateListing(e) {\n //e.preventDefault();\n\n // get new data from modal fields\n dataToUpdate = {\n // imgUrl: $imgUrlField.val(),\n // street: $streetField.val(),\n // city: $cityField.val(),\n // state: $stateField.val(),\n // zip: $zipField.val(),\n title: $titleField.val(),\n rent: $rentField.val()\n };\n\n // close modal\n $('#updateListingModal').modal('hide');\n $.ajax({\n method: \"PUT\",\n url: 'api/listings/' + updateListingId,\n data: dataToUpdate,\n success: onUpdateCallSuccess\n })\n}", "function onUpdateCallSuccess (json) {\n var updatedListing = json;\n listingId = updatedListing._id;\n var listingIndex;\n findListingIndex();\n\n function findListingIndex() {\n for(var index = 0; index < allListings.length; index++) {\n if(allListings[index]._id === listingId) {\n listingIndex = index;\n }\n }\n }\n\n allListings[listingIndex] = updatedListing;\n console.log(allListings[listingIndex]);\n renderListings(allListings);\n renderMarkers();\n}", "function updateResponse(listingId, status, response, agency) {\n\t\treturn db.any('UPDATE listings SET status = $1, response = $2, agency = $3, response_date = now() WHERE listing_id = $4',\n\t\t[status, response, agency, listingId]);\n\t}", "function updateAppStatus() {\n record(curAlist.toNumList());\n curAlist = getAdjlist();\n updateAdjlistFrame();\n updatePropFrame();\n}", "function updateWhitelist(id, status) {\n return User.findById(id).update({whitelisted: status});\n}", "function addListing()\n{\n\n isLogin();\n var listing_obj = null;\n if (window.location.hash) {\n $('#page_title').html('Update Listing');\n $('.li_logout').before('<li class=\"ui-block-c\"><a class=\"ui-link ui-btn ui-icon-check ui-btn-icon-top\" id=\"del_listing\" data-icon=\"delete\">Delete</a></li>');\n $('#nbar ul li').css(\"width\", '25%');\n\n showLoader('Loading..');\n\n var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character\n\n var Listing = Parse.Object.extend(\"listings\");\n var query = new Parse.Query(Listing);\n query.get(hash, {\n success: function (listing) {\n listing_obj = listing;\n $(\"#first_name\").val(listing.attributes.first_name);\n $(\"#last_name\").val(listing.attributes.last_name);\n $('#status').val(listing.attributes.status).slider('refresh');\n $(\"#phone_number\").val(listing.attributes.phone_number);\n $(\"#cell_number\").val(listing.attributes.cell_number);\n $(\"#work_number\").val(listing.attributes.work_number);\n $(\"#work_number\").val(listing.attributes.work_number);\n $(\"#fax\").val(listing.attributes.fax);\n $(\"#email\").val(listing.attributes.email);\n $(\"#address\").val(listing.attributes.address);\n $(\"#city\").val(listing.attributes.city);\n $(\"#state\").val(listing.attributes.state);\n $(\"#propertytype\").val(listing.attributes.propertytype).selectmenu(\"refresh\");\n $(\"#listingprice\").val(listing.attributes.listingprice);\n// var d = listing.attributes.listingexp;\n// var curr_date = d.getDate();\n// var curr_month = d.getMonth() + 1;\n// var curr_year = d.getFullYear();\n var now = new Date(listing.attributes.listingexp);\n\n var day = (\"0\" + now.getDate()).slice(-2);\n var month = (\"0\" + (now.getMonth() + 1)).slice(-2);\n\n var today = now.getFullYear() + \"-\" + (month) + \"-\" + (day);\n\n $('#listingexp').val(today);\n\n // $(\"#listingexp\").val(new Date(curr_year+ \"-\" +pad(curr_month, 2) + \"-\" + pad(curr_date, 2) ));\n $(\"#numofbedrooms\").val(listing.attributes.numofbedrooms);\n $(\"#numofbaths\").val(listing.attributes.numofbaths);\n $(\"#squarefeet\").val(listing.attributes.squarefeet);\n $(\"#yearbuilt\").val(listing.attributes.yearbuilt);\n $(\"#pool\").val(listing.attributes.pool);\n $(\"#hottub\").val(listing.attributes.hottub);\n $(\"#garage\").val(listing.attributes.garage);\n $(\"#security\").val(listing.attributes.security);\n $(\"#notes\").val(listing.attributes.notes);\n $(\"#heating\").val(listing.attributes.heating);\n $(\"#cooling\").val(listing.attributes.cooling);\n $(\"#fireplaces\").val(listing.attributes.fireplaces);\n $(\"#floortype\").val(listing.attributes.floortype);\n $(\"#garagetype\").val(listing.attributes.garagetype);\n $(\"#lottype\").val(listing.attributes.lottype);\n $(\"#views\").val(listing.attributes.views);\n $(\"#ccr\").val(listing.attributes.ccr);\n $(\"#other\").val(listing.attributes.other);\n $(\"#mlsnum\").val(listing.attributes.mlsnum);\n $(\"#apn\").val(listing.attributes.apn);\n $(\"#lockbox\").val(listing.attributes.lockbox);\n $(\"#showing\").val(listing.attributes.showing);\n $(\"#financing\").val(listing.attributes.financing);\n $(\"#terms\").val(listing.attributes.terms);\n\n $(\"#agent\").val(listing.attributes.agent);\n $(\"#agent\").trigger(\"change\");\n $(\"#escrow\").val(listing.attributes.escrow);\n $(\"#escrow\").trigger(\"change\");\n $(\"#lender\").val(listing.attributes.lender);\n $(\"#lender\").trigger(\"change\");\n $(\"#homeinspector\").val(listing.attributes.homeinspector);\n $(\"#homeinspector\").trigger(\"change\");\n $(\"#appraiser\").val(listing.attributes.appraiser);\n $(\"#appraiser\").trigger(\"change\");\n $(\"#otherescrow\").val(listing.attributes.otherescrow);\n $(\"#otherescrow\").trigger(\"change\");\n $(\"#todos_list\").val(listing.attributes.todos_id);\n $(\"#todos_list\").trigger(\"change\");\n //$(\"#agent\").val(listing.attributes.agent).selectmenu(\"refresh\");\n //$(\"#agent\").selectmenu(\"refresh\");\n //$(\"#escrow\").val(listing.attributes.escrow).selectmenu(\"refresh\");\n //$(\"#lender\").val(listing.attributes.lender).selectmenu(\"refresh\");\n //$(\"#homeinspector\").val(listing.attributes.homeinspector).selectmenu(\"refresh\");\n //$(\"#appraiser\").val(listing.attributes.appraiser).selectmenu(\"refresh\");\n //$(\"#otherescrow\").val(listing.attributes.otherescrow).selectmenu(\"refresh\");\n $('#listing_excrow_contacts select').selectmenu(\"refresh\", true);\n //$(\"#listing_excrow_contacts select\").trigger(\"change\");\n //$(\"#todos_list\").selectmenu(\"refresh\", true);\n //$(\"#todos_list\").val(listing.attributes.todos_id).selectmenu(\"refresh\");//$(\"#updateprofile-view select\").selectmenu(\"refresh\", true);\n //alert(listing.attributes.agent);\n if (listing.attributes.agent != '') {\n\n $(\"#listing_excrow_contacts a#agent_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.agent);\n }\n if (listing.attributes.escrow != '') {\n $(\"#listing_excrow_contacts a#escrow_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.escrow);\n }\n if (listing.attributes.lender != '') {\n $(\"#listing_excrow_contacts a#lender_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.lender);\n }\n if (listing.attributes.homeinspector != '') {\n $(\"#listing_excrow_contacts a#homeinspector_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.homeinspector);\n }\n if (listing.attributes.appraiser != '') {\n $(\"#listing_excrow_contacts a#appraiser_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.appraiser);\n }\n if (listing.attributes.otherescrow != '') {\n $(\"#listing_excrow_contacts a#other_contact\").attr(\"href\", \"addcontact.html#\" + listing.attributes.otherescrow);\n }\n\n hideLoader();\n\n },\n error: function (object, error) {\n $(\"#message\").html(\"<div class='error'>\" + error.message + \"</div>\");\n hideLoader();\n }\n });\n }\n\n $(\"#addListing\").click(function () {\n //alert($(\"#listingPhotoFile\").val())\n var fileUploadControl = $(\"#listingPhotoFile\")[0];\n if (fileUploadControl.files.length > 0) {\n for (var i = 0; i < fileUploadControl.files.length; i++) {\n var file = fileUploadControl.files[0];\n var name = \"photo.jpg\";\n\n var parseFile = new Parse.File(name, file);\n parseFile.save().then(function () {\n // The file has been saved to Parse.\n }, function (error) {\n // The file either could not be read, or could not be saved to Parse.\n });\n /*var serverUrl = 'https://api.parse.com/1/files/' + file.name;\n $.ajax({\n type: \"POST\",\n beforeSend: function (request) {\n //request.setRequestHeader(\"X-Parse-Application-Id\", '0OykuJcMdWmif83qhHytaZhgRArtOdDU4STnIvcW');\n //request.setRequestHeader(\"X-Parse-REST-API-Key\", 'aiAXzwjcLWqv6VxRQaVKggNceM0mH3PD4mtR5ylm');\n request.setRequestHeader(\"Content-Type\", file.type);\n },\n url: serverUrl,\n data: file,\n processData: false,\n contentType: false,\n success: function (data) {\n alert(\"File available at: \" + data.url);\n },\n error: function (data) {\n var obj = jQuery.parseJSON(data);\n alert(obj.error);\n }\n });*/\n }\n }\n /*if ($(\"#frm_addListing\").validationEngine('validate'))\n {\n \n var user = Parse.User.current();\n var listing;\n showLoader('Saving..');\n \n if (listing_obj)\n {\n listing = listing_obj;\n listing_obj = null;\n } else\n {\n \n var Listing = Parse.Object.extend(\"listings\");\n listing = new Listing();\n }\n listing.set(\"first_name\", $('#first_name').val());\n listing.set(\"last_name\", $('#last_name').val());\n listing.set(\"phone_number\", $('#phone_number').val());\n listing.set(\"status\", $('#status').val());\n listing.set(\"cell_number\", $('#cell_number').val());\n listing.set(\"work_number\", $('#work_number').val());\n listing.set(\"fax\", $('#fax').val());\n listing.set(\"email\", $('#email').val());\n listing.set(\"address\", $('#address').val());\n listing.set(\"city\", $('#city').val());\n listing.set(\"state\", $('#state').val());\n listing.set(\"propertytype\", $('#propertytype').val());\n listing.set(\"listingprice\", $('#listingprice').val());\n var str = $('#listingexp').val();\n listing.set(\"listingexp\", new Date(str));\n listing.set(\"numofbedrooms\", $('#numofbedrooms').val());\n listing.set(\"numofbaths\", $('#numofbaths').val());\n listing.set(\"squarefeet\", $('#squarefeet').val());\n listing.set(\"yearbuilt\", $('#yearbuilt').val());\n listing.set(\"pool\", $('#pool').val());\n listing.set(\"hottub\", $('#hottub').val());\n listing.set(\"garage\", $('#garage').val());\n listing.set(\"security\", $('#security').val());\n listing.set(\"notes\", $('#notes').val());\n listing.set(\"heating\", $('#heating').val());\n listing.set(\"cooling\", $('#cooling').val());\n listing.set(\"fireplaces\", $('#fireplaces').val());\n listing.set(\"floortype\", $('#floortype').val());\n listing.set(\"garagetype\", $('#garagetype').val());\n listing.set(\"lottype\", $('#lottype').val());\n listing.set(\"views\", $('#views').val());\n listing.set(\"ccr\", $('#ccr').val());\n listing.set(\"other\", $('#other').val());\n listing.set(\"mlsnum\", $('#mlsnum').val());\n listing.set(\"apn\", $('#apn').val());\n listing.set(\"lockbox\", $('#lockbox').val());\n listing.set(\"showing\", $('#showing').val());\n listing.set(\"financing\", $('#financing').val());\n listing.set(\"terms\", $('#terms').val());\n listing.set(\"agent\", $('#agent').val());\n listing.set(\"escrow\", $('#escrow').val());\n listing.set(\"lender\", $('#lender').val());\n listing.set(\"homeinspector\", $('#homeinspector').val());\n listing.set(\"appraiser\", $('#appraiser').val());\n listing.set(\"otherescrow\", $('#otherescrow').val());\n listing.set(\"todos_id\", $('#todos_list').val());\n listing.set(\"user\", user);\n listing.save(null, {\n success: function (listing)\n {\n window.location = \"listings.html#saved\";\n // $(\"#message\").html(\"<div class='success'>Listing has been saved successfully. </div>\");\n // emptyForm('frm_addListing');\n // hideLoader();\n },\n error: function (user, error) {\n //alert(error.message);\n $(\"#message\").html(\"<div class='error'>\" + error.message + \"</div>\");\n hideLoader();\n \n }\n \n \n });\n \n \n }*/\n });\n\n $('#del_listing').click(function () {\n\n\n if (confirm(\"Are you sure to delete this record!\")) {\n showLoader('Deleting..');\n listing_obj.destroy({\n success: function (myObject) {\n window.location = \"listings.html#deleted\";\n },\n error: function (myObject, error) {\n $(\"#message\").html(\"<div class='error'>\" + error.message + \"</div>\");\n hideLoader();\n }\n });\n\n }\n\n\n });\n}", "update_statuses(state) {\n Vue.http.get(Hunt.API_URL+'/statuses').then(\n success => {\n try {\n state.statuses = [{\n label: 'All',\n slug: ''\n }];\n Object.keys(success.body.statuses).forEach(x => {\n state.statuses.push({\n label: x,\n slug: x.toLowerCase(),\n subject: success.body.statuses[x].subject,\n message: success.body.statuses[x].message\n });\n });\n } catch(e) {\n Hunt.toast('Error parsing statuses', 'error');\n }\n },\n fail => {\n if(fail.status===403) {\n Bus.$emit(\"goto-login\");\n }\n Hunt.toast(fail.data.message, 'error');\n console.log(fail);\n }\n );\n }", "componentDidMount() {\r\n const { listingid } = this.props.match.params;\r\n ListingHelper.listingById(listingid).then(\r\n listingData =>\r\n this.setState({\r\n listing: listingData\r\n }) +\r\n ListingHelper.getListingOwnerData(listingData.owner).then(ownerData => {\r\n this.setState({ owner: ownerData, isLoading: false });\r\n })\r\n );\r\n }", "listings(listing) {\n return __awaiter(this, void 0, void 0, function* () {\n const deployed = this.requireDeployed();\n return yield deployed.methods.listings(listing).call();\n });\n }", "async addToBlackList (entry) {\n try {\n console.log('entry', entry)\n _this.setState({ inFetch: true })\n const { jwt } = getLocalUser()\n const options = {\n url: `${SERVER}/blacklist`,\n method: 'POST',\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${jwt}`\n },\n data: {\n hash: entry._id,\n reason: 'Unspecified'\n }\n }\n const res = await axios(options)\n _this.setState({\n inFetch: false,\n blackListFetchStatus: {\n success: true,\n msg: res.data.message\n }\n })\n } catch (e) {\n _this.setState({\n inFetch: false,\n blackListFetchStatus: {\n success: false,\n msg: e.message\n }\n })\n }\n }", "addItemListings(listingsMap, itemModel) {\n let listed = false;\n publicationTypes = new PublicationTypes(SV.get('publicationTypes'));\n // first reset the item's listings to whatever they were before :\n itemModel.resetListings();\n const canAttach = itemModel.canAttachListings();\n\n // Do NYDC first because save for item could happen regardless of listing state :\n if (listingsMap.nydc) {\n itemModel.setNydc(true);\n } else {\n itemModel.setNydc(false);\n }\n // WIP and unlisted both return before doing anything else :\n if (listingsMap.wip) {\n itemModel.markUnlisted();\n itemModel.markIncomplete();\n return;\n }\n if (listingsMap.unlisted) {\n itemModel.markUnlisted();\n return;\n }\n\n // none of the following steps will be done if the item is not able to accept listings :\n if (!canAttach) {\n return;\n }\n\n if (listingsMap.store) {\n itemModel.addStorefrontListing(publicationTypes);\n listed = true;\n }\n if (listingsMap.market) {\n itemModel.addMarketplaceListing(publicationTypes);\n listed = true;\n if (itemModel.isArt()) {\n itemModel.addFeaturedListing(publicationTypes);\n }\n }\n if (listingsMap.featured) {\n itemModel.addFeaturedListing(publicationTypes);\n listed = true;\n }\n\n if (listed && itemModel.canMarkComplete()) {\n itemModel.markComplete();\n }\n }", "handleStatusChange(taskId, e, data) {\n const task = _.find(this.state.tasks, {'task_id': taskId})\n const newStatus = data.value\n if (newStatus !== task.status) {\n let newTasks = this.state.tasks.slice()\n let newTask = _.find(newTasks, {'task_id': taskId})\n newTask.status = newStatus\n let filteredTasks = this.filterTasksByWorkspaces(newTasks,\n this.state.selectedWorkspaces);\n let displayTasks = filteredTasks.length > 0 ? filteredTasks : newTasks;\n let newCompletionPercentage = this.calculateCompletionPercentage(displayTasks);\n put(`/tasks/${task.task_id}`, {status: newStatus})\n .then(res => {\n this.setState({\n tasks: newTasks,\n completionPercentage: newCompletionPercentage,\n })\n console.log(`Successfully changed status to ${newStatus} for ${task.name}`)\n })\n .catch(err => console.log(err))\n }\n }", "function handleEditListing(e) {\n e.preventDefault();\n // close modal\n $('#myModal').modal('hide');\n $('#updateListingModal').modal();\n $.ajax({\n method: \"GET\",\n url: 'api/listings/' + updateListingId,\n success: onEditCallSuccess\n })\n}", "function updateAppStatus(app){\n if (app.running){\n if (app.state == \"STOPPED\"){\n app.state = \"MONITORING\";\n app.status = \"RUNNING\";\n }\n else if (app.state == \"STOPPING\"){\n app.status = \"STOPPING\";\n }\n else if (app.state == \"STARTING\"){\n app.state = \"MONITORING\";\n app.status = \"RUNNING\";\n }\n else {\n app.state = \"RUNNING\";\n app.status = \"RUNNING\";\n }\n }\n else { //!app.running\n if (app.state == \"STARTING\"){\n app.status = \"STARTING\";\n }\n else if (app.state == \"MONITORING\" && app.restart == \"true\"){\n startApp(app);\n }\n else {\n app.state = \"STOPPED\";\n app.status = \"STOPPED\";\n }\n }\n updateAppLabelStatus(app);\n}", "static async getListing(listing_id) {\n let res = await this.request(`api/listings/${listing_id}`);\n return res;\n }", "function updateApp() {\n\n\tif ($(\".selectedPortlet\")[0]) {\n\t\tvar portletID = $(\".selectedPortlet\")[0].id;\n\t\t$.getJSON(\"/security/config/installedapps?action=update&app=\" + portletID+\"&user=\" + otusr + \"&pw=\" + otpwd, function(json) {\n\t\t\talert(json.statusInfo);\n\t\t});\n\t} else {\n\t\talert(\"Wählen Sie ein Bundle!\");\n\t}\n}", "function updateResultsListing() {\n\n var listingText,\n allItems = yearDimension.top(Infinity),\n makeSceneLink = function (scene) {\n if (scene !== '[Non-panorama history]')\n return '<a target=\"_blank\" href=\"' + \n SCENE_URL_BASE + scene + '\">' + scene + \n '</a>';\n else return scene;\n };\n\n // Update results count\n\n $('#active').text(allItems.length);\n\n // List entries in results box\n\n $('#resource-list').empty();\n\n yearDimension.top(INIT_LISTING_COUNT).forEach(function (item) {\n listingText = '<p>' +\n '<strong>' +\n '<a href=\"' + RESOURCE_URL_BASE + item.URLID + '\" target=\"_BLANK\">' + \n item.short_title + '</a>' +\n '</strong>' +\n ' (' + item.year.getFullYear() + ')<br />' +\n (item.author ? item.author + '<br />' : '') +\n 'Scenes: ' + item.scene.map(makeSceneLink).join(', ') +\n '</p>';\n $('#resource-list').append(listingText); \n }); \n }", "static applyMangaStatus( connector, mangas ) {\n mangas.forEach( ( manga ) => {\n //manga['status'] = 'completed';\n });\n }", "function addListing(listing) {\n allListings.push(listing);\n}", "function refreshList() {\n axios.get(url + HoldRoute + \"/withtools/json\").then((response) => {\n setList(response.data);\n });\n }", "updateHeldStepsStatus(kind, padId, status) {\n // this.updateHeldStepsStatusInStepQueue( kind, status ) ;\n this.updateHeldStepsStatusInActiveHolds( kind, padId, status ) ;\n }", "setStatusOfCall(callId, status, callsArrayId){\n var patchData = {\n callId: callId,\n status: status\n }\n\n UpdateCallLog(patchData).then(response => {\n if(response.status === \"OK\")\n {\n var callsLogs = this.state.calls\n callsLogs[callsArrayId] = response.data;\n this.setState({calls: callsLogs, filteredCalls: callsLogs})\n toast.success(\"Status Changed To \" + response.data.status.description )\n }\n else\n {\n toast.error(\"Error Changing Status\")\n }\n })\n}", "async function updateListingByName(client, nameOfListing, updatedListing) {\n const result = await client.db(\"sample_airbnb\").collection(\"listingsAndReviews\")\n .updateOne({ name: nameOfListing }, { $set: updatedListing });\n console.log(`${result.matchedCount} document(s) matched the query criteria.`);\n console.log(`${result.modifiedCount} document(s) was/were updated.`);\n}", "function updateBookingStatus() {\n\n }", "isWhitelisted(listing) {\n return __awaiter(this, void 0, void 0, function* () {\n const deployed = this.requireDeployed();\n return yield deployed.methods.isWhitelisted(listing).call();\n });\n }", "setStatusOfCall(callId, status, callsArrayId){\n var patchData = {\n callId: callId,\n status: status\n }\n\n UpdateCallLog(patchData).then(response => {\n if(response.status === \"OK\")\n {\n var callsLogs = this.state.calls\n callsLogs[callsArrayId] = response.data;\n this.setState({calls: callsLogs, filteredCalls: callsLogs})\n toast.success(\"Status Changed To \" + response.data.status.description )\n }\n else\n {\n toast.error(\"Error Changing Status\")\n }\n })\n}", "updateResultList(map,ingredient,callbacks,nosort){\n let {successCallback,outputCallback,failureCallback} = {...callbacks}; //successCallback must be defined\n let updateType = map.get(ingredient)[0];\n let status = map.get(ingredient)[2];\n \n let statusFailure = (()=>{\n console.error('attempted illegal action ['+updateType+'] on: '+ingredient+' (status: '+status+')');\n if(failureCallback){\n failureCallback(ingredient);\n }\n return map;\n });\n\n let updateDoneAction = (()=>{\n if(!nosort){\n this.sortRecipeMap(successCallback); //continue to sorter, pass it the callback for when its done\n } else {\n successCallback(ingredient);\n }\n });\n\n if(updateType===ADD_TO_SEARCH||updateType===REMOVE_FROM_SEARCH){ //use ingredient in search\n if((updateType===ADD_TO_SEARCH&&status!==UNUSED_STATUS)||(updateType===REMOVE_FROM_SEARCH&&status!==INCLUDED_STATUS)){ //query doesn't fit the current status, reject it and do nothing\n return statusFailure();\n }\n map.get(ingredient)[2] = updateType===ADD_TO_SEARCH?INCLUDED_STATUS:UNUSED_STATUS;\n let recipeTracker = new Set()\n map.get(ingredient)[1].recipes.forEach((recipe)=>{\n let recipeName = recipe.Name\n if(!recipeTracker.has(recipeName)){\n recipeTracker.add(recipeName)\n let prevEntry = this.recipeMap.has(recipeName)?this.recipeMap.get(recipeName):[0,0,0]; //set base values to 0 if no entry exists\n this.recipeMap.set(recipeName,[\n prevEntry[0],\n prevEntry[1]+updateType,\n prevEntry[2]+updateType*(+recipe.Importance)\n ])\n }\n })\n //this should only get called from a Promise chain\n //branch the chain into the supplied callback\n updateDoneAction();\n } else if(updateType===ADD_TO_EXCLUDE||updateType===REMOVE_FROM_EXCLUDE){ //reject or un-reject ingredient from search\n if((updateType===ADD_TO_EXCLUDE&&status!==UNUSED_STATUS)||(updateType===REMOVE_FROM_EXCLUDE&&status!==EXCLUDED_STATUS)){ //query doesn't fit the current status, reject it and do nothing\n return statusFailure();\n }\n map.get(ingredient)[2] = updateType===REMOVE_FROM_EXCLUDE?UNUSED_STATUS:EXCLUDED_STATUS;\n let adjustment = (updateType===0)?1:-1;\n map.get(ingredient)[1].recipes.forEach((recipe)=>{\n let prevEntry = this.recipeMap.has(recipe.Name)?this.recipeMap.get(recipe.Name):[0,0,0]; //set base values to 0 if no entry exists\n //increment the rejection score by one\n this.recipeMap.set(recipe.Name,[prevEntry[0]+adjustment,prevEntry[1],prevEntry[2]])\n })\n //this should only get called from a Promise chain\n //branch the chain into the supplied callback\n updateDoneAction();\n } else {\n //well this is awkward\n console.error('Incorrect query code found when updating recipe map: '+updateType)\n }\n return map //keep the chain alive\n }", "function askListing (session, args, next) {\r\n // First check to see if we either got a listing from LUIS or have a an existing listing\r\n // that we can multi-turn over.\r\n var listing;\r\n var entity = builder.EntityRecognizer.findEntity(args.entities, 'ListingName');\r\n if (entity) {\r\n // The user specified a listing so lets look it up to make sure its valid.\r\n // * This calls the underlying function Prompts.choice() uses to match a users response\r\n // to a list of choices. When you pass it an object it will use the field names as the\r\n // list of choices to match against. \r\n listing = builder.EntityRecognizer.findBestMatch(dataListing, entity.entity);\r\n } else if (session.dialogData.listing) {\r\n // Just multi-turn over the existing listing\r\n listing = session.dialogData.listing;\r\n }\r\n \r\n // Prompt the user to pick a listing if they didn't specify a valid one.\r\n if (!listing) {\r\n // Lets see if the user just asked for a listing we don't know about.\r\n var txt = entity ? session.gettext(prompts.listingUnknown, { listing: entity.entity }) : prompts.listingMissing;\r\n \r\n // Prompt the user to pick a listing from the list. They can also ask to cancel the operation.\r\n builder.Prompts.choice(session, txt, dataListing);\r\n } else {\r\n // Great! pass the listing to the next step in the waterfall which will answer the question.\r\n // * This will match the format of the response returned from Prompts.choice().\r\n next({ response: listing });\r\n }\r\n}", "function _change_match_symptoms_status(idx,symptoms_status) {\n\n let matches_lst = _get_matches();\n matches_lst[idx].with_symptoms = symptoms_status;\n\n let class_for_withoutsymptoms = _get_symptoms_class(false);\n let symptoms_str = _get_symptoms_label_text(symptoms_status);\n \n \n $(\"#span_hpo_\"+idx).removeClass(class_for_withoutsymptoms);\n if(symptoms_status) {\n //default with symptoms\n } else {\n // withoutsymptoms\n $(\"#span_hpo_\"+idx).addClass(class_for_withoutsymptoms);\n } \n \n $(\"#li_hpo_\"+idx).removeClass(class_for_withoutsymptoms);\n if(symptoms_status) {\n // default\n } else {\n $(\"#li_hpo_\"+idx).addClass(class_for_withoutsymptoms);\n }\n $(\"#li_label_hpo_\"+idx).text(symptoms_str);\n\n $(\"#tbl_hpolist\").find(\"tr:gt(0)\").remove();\n let rows_str = _create_tblrows_from_matches(matches_lst);\n $('#tbl_hpolist').append(rows_str);\n\n _set_match_totalnum(matches_lst);\n}" ]
[ "0.5223855", "0.4951868", "0.48654446", "0.4864351", "0.4799458", "0.47674277", "0.46703455", "0.4588139", "0.45853782", "0.45470458", "0.45210463", "0.44564027", "0.44555843", "0.44072017", "0.4376598", "0.43688685", "0.43531272", "0.432941", "0.43260267", "0.43152893", "0.42806613", "0.42771655", "0.42761812", "0.426544", "0.42648724", "0.4264245", "0.4257378", "0.42551953", "0.42437378", "0.4241899" ]
0.62385035
0
The study feature. variation: study info about particular client study variation studyUtils: the configured studyUtils singleton. reasonName: string of bootstrap.js startup/shutdown reason logLevel: the log level from Config.jsm ( uses same level as bootstrap.js)
constructor({variation, studyUtils, reasonName, logLevel}) { this.treatment = variation.name; this.studyUtils = studyUtils; this.reasonName = reasonName; // Randomize frame script URL due to bug 1051238. this.FRAME_SCRIPT_URL = `resource://${STUDY}/content/new-tab-variation.js?${Math.random()}`, this.XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; this.DOORHANGER_ID = "onboarding-trackingprotection-notification"; this.DOORHANGER_ICON = "chrome://browser/skin/tracking-protection-16.svg#enabled"; this.STYLESHEET_URL = `resource://${STUDY}/skin/tracking-protection-study.css`; this.PREF_TP_UI_ENABLED = "privacy.trackingprotection.ui.enabled"; this.TP_ENABLED_GLOBALLY = (this.treatment === "pseudo-control"); this.TP_ENABLED_IN_PRIVATE_WINDOWS = (this.treatment === "control"); this.PREF_TP_ENABLED_GLOBALLY = "privacy.trackingprotection.enabled"; this.PREF_TP_ENABLED_IN_PRIVATE_WINDOWS = "privacy.trackingprotection.pbmode.enabled"; this.init(logLevel); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getStudyState() {\n return this.study_state;\n }", "getStudyStatus() {\n return this.study_status;\n }", "function getScenario (name) {\n var scenario = { name: name }\n scenario.config = require(`../examples/${name}/webpack.config`)\n\n try {\n var manifest = require(`../examples/${name}/package`)\n scenario.deps = Object.keys(manifest.dependencies)\n } catch (e) {}\n\n return scenario\n}", "function STXStudies(){\n}", "function createVariation(variation){\n const durSecInterval = setInterval(function(){\n outputDurSec++;\n },1000);\n\n const headerMargin = windowW - d3.select('#header').node().clientWidth;\n d3.select('#header')\n .style('margin-left', '-'+(headerMargin/2)+'px')\n .style('margin-right', '-'+(headerMargin/2)+'px');\n\n const w = d3.select('#content-empathy').node().clientWidth;\n\n if(variation == 'narrative description'){\n createDescription();\n }\n\n d3.json(session).then(function(data){\n // console.log(data);\n\n /* VARIABLES */\n const mlScore = data.scores.globals.empathy;\n const percentOpenQuestions = data.scores.behaviorCounts.percentOpenQuestions.percentOpenQuestions;\n const closedQuestions = data.scores.behaviorCounts.percentOpenQuestions.closedQuestions;\n const openQuestions = data.scores.behaviorCounts.percentOpenQuestions.openQuestions;\n const percentComplexReflections = data.scores.behaviorCounts.percentComplexReflections.percentComplexReflections;\n const complexReflections = data.scores.behaviorCounts.percentComplexReflections.complexReflections;\n const simpleReflections = data.scores.behaviorCounts.percentComplexReflections.simpleReflections;\n\n const openArr = [];\n const closeArr = [];\n const complexArr = [];\n const simpleArr = [];\n\n data.session.talkTurn.forEach(function(d){\n d.influence = (Number(Math.random().toFixed(3))*2) - 1; // randomize influence scores per talk turn - placeholder for real output\n if(d.codes[0]=='QUO'){\n openArr.push({\n id: d.id,\n })\n }\n if(d.codes[0]=='QUC'){\n closeArr.push({\n id: d.id,\n })\n }\n if(d.codes[0]=='REC'){\n complexArr.push({\n id: d.id,\n })\n }\n if(d.codes[0]=='RES'){\n simpleArr.push({\n id: d.id,\n })\n }\n });\n\n /************* EMPATHY BARS *************/\n\n const svgEmpathy = d3.select('#content-empathy')\n .append('svg');\n\n svgEmpathy\n .attr('class','bars-empathy')\n .attr('id','svg-empathy')\n .attr('width',w)\n .attr('height',h);\n\n const mlScoreG = svgEmpathy\n .append('g')\n .attr('id','mlScoreG')\n .attr('transform','translate(0,160)');\n\n const userScoreG = svgEmpathy\n .append('g')\n .attr('id','userScoreG')\n .attr('transform','translate(0,40)');\n\n const userScoreT = userScoreG.append('text')\n .attr('class','textScore userScore')\n .attr('id','textScore-user')\n .attr('x','0px');\n userScoreT.append('tspan')\n .text('You rated the session ');\n userScoreT.append('tspan')\n .attr('id','userNum')\n .text(userScore)\n .style('font-weight','bold');\n\n userScoreG.append('rect')\n .attr('class','rect-background userScore');\n\n const mlScoreT = mlScoreG.append('text')\n .attr('class','textScore mlScore')\n .attr('id','textScore-ml')\n .attr('x','0px');\n mlScoreT.append('tspan')\n .text('The software rated the session ');\n mlScoreT.append('tspan')\n .attr('id','mlNum')\n .text(mlScore.toFixed(1))\n .style('font-weight','bold');\n mlScoreT.append('tspan')\n .attr('id','mlNumChange');\n\n mlScoreG.append('rect')\n .attr('class','rect-background mlScore');\n\n if(variation == 'confidence'){\n makeEmpathyBars(mlScore);\n makeConfidenceLabels(mlScore);\n }else{\n userScoreG.append('rect')\n .attr('class','rect-foreground userScore')\n .attr('id','userScore')\n .attr('width',scaleX(userScore));\n mlScoreG.append('rect')\n .attr('class','rect-foreground mlScore')\n .attr('id','mlScore')\n .attr('width',scaleX(mlScore));\n svgEmpathy.selectAll('.rect-foreground')\n .attr('height',barH+'px')\n .attr('x','0px')\n .attr('y',barY+'px');\n svgEmpathy.selectAll('.rect-background')\n .attr('y',barY+'px');\n };\n\n svgEmpathy.selectAll('.rect-background')\n .attr('width',barW+'px')\n .attr('height',barH+'px')\n .attr('x','0px');\n\n // append visual indicators for empathy score changes by user interaction\n if(variation == 'manipulation' || variation == 'influential n-grams'){\n mlScoreG.append('rect')\n .attr('class','rect-foreground mlScore mlScoreChange')\n .attr('id','scoreChangeNeg')\n .attr('x',0)\n .attr('width',scaleX(mlScore));\n mlScoreG.append('rect')\n .attr('class','rect-background mlScore mlScoreChange')\n .attr('id','scoreChangePos')\n .attr('x',scaleX(mlScore))\n .attr('width',scaleX(scoreMax-mlScore));\n mlScoreG.selectAll('.mlScoreChange')\n .attr('height',barH/10)\n .attr('y',barY+(9*barH/20));\n mlScoreG.append('circle')\n .attr('id','scoreChange')\n .attr('cx',scaleX(mlScore))\n .attr('cy',barY+(barH/2))\n .attr('r',barH/8)\n .style('opacity',0);\n }\n\n /************* LOWER LEFT CONTENT *************/\n\n if(variation == 'manipulation'){\n const sliderObj = {\n openPerc: percentOpenQuestions,\n openCount: openQuestions,\n closedCount: closedQuestions,\n complexPerc: percentComplexReflections,\n complexCount: complexReflections,\n simpleCount: simpleReflections\n };\n const questionsObj = {\n open: openArr,\n close: closeArr\n };\n const reflectionsObj = {\n complex: complexArr,\n simple: simpleArr\n };\n createSliders(sliderObj,questionsObj,reflectionsObj,mlScore,w);\n\n }else if(variation == 'confidence' || variation == 'narrative description'){\n d3.select('#content-empathy')\n .append('h6')\n .attr('id','title-aboutAlg')\n .html('ABOUT THE SOFTWARE');\n d3.select('#content-empathy')\n .append('p')\n .attr('id','desc-aboutAlg')\n .style('width',barW+'px')\n .html(aboutAlg);\n }else if(variation == 'influential n-grams'){\n influenceLegend(data.session.talkTurn);\n }\n\n /************** SESSION TRANSCRIPT **************/\n\n d3.select('#content-session')\n .append('p')\n .attr('id','transcript-desc')\n .style('font-size','12px')\n .style('width',barW+'px')\n .style('margin-top','30px')\n .html('Here is a software-generated transcript of the role-played session.')\n\n if(variation == 'influential n-grams'){\n d3.select('#transcript-desc')\n .html('Here is a software-generated transcript of the role-played session. ' +\n 'Click the buttons below to see how changing the ' +\n 'most influential words and phrases to all pro-empathy or anti-empathy affect the empathy score.')\n influenceFunctionality(mlScore);\n }\n\n d3.select('#content-session')\n .append('div')\n .attr('id','container-session');\n d3.select('#content-session')\n .append('div')\n .attr('id','manipulation-tracking');\n\n // text for each talk turn\n d3.select('#container-session').selectAll('.session-text')\n .data(data.session.talkTurn)\n .enter()\n .append('div')\n .attr('class',function(d){\n if(d.speaker == 'therapist'){\n return 'session-div therapist-div';\n }\n else{\n return 'session-div client-div';\n }\n })\n .append('text')\n .attr('class',function(d){\n if(d.speaker == 'therapist' && d.codes[0]=='QUO'){\n return 'session-text therapist-text openQ-text';\n }\n else if(d.speaker == 'therapist' && d.codes[0]=='REC'){\n return 'session-text therapist-text complexR-text';\n }\n else if(d.speaker == 'therapist'){\n return 'session-text therapist-text';\n }\n else{\n return 'session-text client-text';\n }\n })\n .attr('id',function(d){\n return d.speaker + '-' + d.id;\n })\n .append('tspan')\n .text(function(d){\n if(d.speaker == 'therapist'){\n return 't: ';\n }else{\n return 'c: ';\n }\n })\n\n d3.selectAll('.session-text')\n .append('tspan')\n .attr('class',function(d){\n return d.speaker + '-original';\n })\n .attr('id',function(d){\n return d.speaker + '-original-' + d.id;\n })\n // commented code below indicated bolded text in transcript\n // .classed('in-scope',function(d){\n // if(session == sessionGood){\n // if(d.id >= 74 && d.id <= 119){\n // return true;\n // }else{ return false; }\n // }else if(session == sessionBad){\n // if(d.id >= 51 && d.id <= 88){\n // return true;\n // }else{ return false; }\n // }\n // })\n .html(function(d){\n if(d.speaker == 'therapist'){\n return d.asrText;\n }else{\n return d.asrText;\n }\n });\n\n if(variation == 'similar sessions'){\n similarSessions();\n d3.select('#container-session')\n .style('height','480px');\n }\n else if(variation == 'influential n-grams'){\n d3.select('#container-session')\n .style('margin-top','30px')\n .style('height','470px');\n influenceInTranscript();\n influence();\n }\n else if(variation == 'narrative description'){\n d3.select('#container-session')\n .style('height','450px');\n }else if(variation == 'confidence'){\n d3.select('#container-session')\n .style('height','470px');\n }else if(variation == 'manipulation'){\n d3.select('#container-session')\n .style('height','560px');\n d3.select('#manipulation-tracking')\n .style('top',function(){\n var rect = document.getElementById('container-session').getBoundingClientRect(),\n greaterRect = document.getElementById('content-session').getBoundingClientRect(),\n \t scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return (rect.top - greaterRect.top + scrollTop) + 'px';\n })\n .style('height','560px');\n trackingH = document.getElementById('manipulation-tracking').clientHeight;\n trackingW = document.getElementById('manipulation-tracking').clientWidth;\n d3.select('#manipulation-tracking')\n .append('svg')\n .attr('id','tracking-svg')\n .attr('width',trackingW)\n .attr('height',trackingH);\n d3.select('#btn-to-survey')\n .style('position','relative')\n .style('top','-160px');\n }\n\n });\n\n var generateId = function () {\n return '_' + Math.random().toString(36).substr(2, 9);\n };\n\n // data storage\n dataObj.user = generateId();\n dataObj.rating = rating;\n dataObj.session = sessionType;\n dataObj.listenTime = +listenMaxDur.toFixed(0);\n dataObj.variation = variation.replace(/ /g,\"_\");\n // currently omitting ip address capture\n // d3.json('http://api.db-ip.com/v2/free/self', function(data) {\n // dataObj.ip = data.ipAddress;\n // });\n\n d3.select('#btn-to-survey')\n .style('color','black')\n .on('click',function(){\n dataObj.interactionCount = interaction;\n dataObj.outputTime = outputDurSec;\n clearInterval(durSecInterval);\n d3.select('#modal-next')\n .style('display','block');\n })\n\n // modal content\n d3.select('#modal-next').selectAll('.modal-body')\n .append('p')\n .style('font-size','14px')\n .style('text-align','center')\n .style('margin-top','40px')\n .html('You will now be directed to the survey site.');\n\n d3.select('#modal-next').selectAll('.modal-body')\n .append('a')\n .attr('id','modal-content-btn')\n .attr('class','btn')\n .html('okay')\n .on('click',function(){\n d3.select(this).attr('href','https://sri.utah.edu/epnew/bypass/anon.jsp?gid=4196738'+\n '&randomsessionid=' + dataObj.user +\n // '&ip=' + dataObj.ip +\n '&empathy=' + dataObj.rating +\n '&sessiongoodbad=' + dataObj.session +\n '&listentime=' + dataObj.listenTime +\n '&variation=' + dataObj.variation +\n '&timespentlooking=' + dataObj.outputTime +\n '&interactioncount=' + dataObj.interactionCount);\n });\n\n}", "function C012_AfterClass_Roommates_TestIsolationSarah() {\n\tif (GameLogQuery(CurrentChapter, \"Sarah\", \"IsolationTalk\")) {\n\t\tOverridenIntroText = GetText(\"NoIsolationIntroSarah\");\n\t\tC012_AfterClass_Roommates_CurrentStage = 210;\n\t} else GameLogAdd(\"IsolationTalk\");\n}", "featureEXAMPLE(config,data) {\n if(data.additional && data.additional.exampleQuery) { //the query key in the config set to \"exampleQuery\"\n return { value: `${data.additional.exampleQuery[0].apps} apps reporting`, tooltip: `There could be even more detail here`}\n }\n }", "quickFacts(){\n console.log(`${this.name} educates ${this.numberOfStudents} students at the ${this.level} level.`);\n }", "getLevel(feature) {\n return feature.properties.level;\n }", "function sensspecnew(){ \n d3.select(\"#info5\")\n .text(\"Sensitivity: \" + round(((1-tprThreshold)*100), 0) + \"%\");\n \n d3.select(\"#info6\")\n .text(\"Specificity: \" + round(((1-fprThreshold)*100), 0) + \"%\");\n }", "function Scenario (name)\n{\n\tthis.Name = name;\n\tthis.Armies = [];\t\n}", "function assessPerformance() {\n\t/* Function to calculate the \"credit_var\", which is a boolean used to\n\tcredit individual experiments in expfactory. \n\t */\n\n\t// Extrait les trials correspondant aux essais\n\t//\n\tjsPsych.data.displayData()\n\n\t// Filtre les trials correspondant à des réponses pendant la phase de test\n\t//\n\tvar experiment_data = jsPsych.data.get().filter({exp_stage:'test', trial_id:'stim'})\n\t//\n\t// Calcule \t1. Le nombre de réponses correctes\n\t//\t\t\t2. Le nombre de réponses incorrectes\n\t//\t\t\t3. Le nombre d'absence de réponses (RT = 0)\n\t//\t\t\t4. La médiane de l'ensemble des temps de réaction\n\t//\t\t\t5. Les médianes selon les 4 possibilités de cue\n\t//\t\t\t6. Les médianes selon les 2 possibilités de flanker (car neutre exclu)\n\t//\n\tvar correct_count = 0\n\tvar incorrect_count = 0\n\tvar omission_count = 0\n\tvar rt_correct = []\n\tvar rt_correct_nocue = []\n\tvar rt_correct_double = []\n\tvar rt_correct_spatial = []\n\tvar rt_correct_center = []\n\tvar rt_correct_congruent = []\n\tvar rt_correct_incongruent = []\n\t\n\tfor (var i=0; i<experiment_data.count(); i++) {\t\t\t\t\t\t\t\n\t\trt = experiment_data.select('rt').values[i]\n\t\tif (rt == 0) {\n\t\t\tomission_count++\n\t\t}\n\t\telse if (experiment_data.select('correct').values[i] === true) {\n\t\t\t\tcorrect_count++\n\t\t\t\trt_correct.push(rt)\n\t\t\t\t//\n\t\t\t\tswitch (experiment_data.select('cue').values[i]) {\n\t\t\t\t\tcase 'nocue':\n\t\t\t\t\t\trt_correct_nocue.push(rt)\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'double':\n\t\t\t\t\t\trt_correct_double.push(rt)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'spatial':\n\t\t\t\t\t\trt_correct_spatial.push(rt)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'center':\n\t\t\t\t\t\trt_correct_center.push(rt)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//\n\t\t\t\tswitch (experiment_data.select('flanker_type').values[i]) {\n\t\t\t\t\tcase 'congruent':\n\t\t\t\t\t\trt_correct_congruent.push(rt)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'incongruent':\n\t\t\t\t\t\trt_correct_incongruent.push(rt)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { incorrect_count++ }\n\t}\n\t\n\tif (rt_correct!=0) {\n\t\tvar median_rt = math.median(rt_correct)\n\t\tvar se_rt = median_rt/math.sqrt(correct_count)\n\t} else {\n\t\tvar median_rt = -999\n\t\tvar se_rt = -999\n\t}\n\t\n\tif (rt_correct_nocue.length!=0) {\n\t\tvar median_nocue = math.median(rt_correct_nocue)\n\t} else { var median_nocue = -999 }\n\n\tif (rt_correct_double.length!=0) {\n\t\tvar median_double = math.median(rt_correct_double)\n\t} else { var median_double = -999 }\n\n\tif (rt_correct_center.length!=0) {\n\t\tvar median_center = math.median(rt_correct_center)\n\t} else { var median_center = -999 }\n\n\tif (rt_correct_spatial.length!=0) {\n\t\tvar median_spatial = math.median(rt_correct_spatial)\n\t} else { var median_spatial = -999 }\n\n\tif (rt_correct_congruent.length!=0) {\n\t\tvar median_congruent = math.median(rt_correct_congruent)\n\t} else { var median_congruent = -999 }\n\n\tif (rt_correct_incongruent.length!=0) {\n\t\tvar median_incongruent = math.median(rt_correct_incongruent)\n\t} else { var median_incongruent = -999 }\n\n\t// Sortie provisoire sur la console\n\t//\n\tconsole.log(\"Nombre d'omissions: \", omission_count)\n\tconsole.log(\"Nombre de réponses: \", correct_count + incorrect_count)\n\tconsole.log(\"Nombre de réponses correctes au total: \", correct_count)\n\tconsole.log(\"Nombre d'erreurs au total: \", incorrect_count)\n\tconsole.log(\"Médianes des RT pour réponses correctes: \", median_rt)\n\tconsole.log(\"ES des médianes des RT pour les réponses correctes: \", se_rt)\n//\n\tif (median_nocue==-999 || median_double==-999) {\n\t\tconsole.log(\"La variable Alerte ne peut être calculée...\")\n\t} else { console.log(\"Alerte: \", median_nocue - median_double) }\n//\n\tif (median_center==-999 || median_spatial==-999) {\n\t\tconsole.log(\"La variable Orientation ne peut être calculée...\")\n\t} else { console.log(\"Orientation: \", median_center - median_spatial) }\n//\n\tif (median_incongruent==-999 || median_congruent==-999) {\n\t\tconsole.log(\"La variable Conflict ne peut être calculée...\")\n\t} else { console.log(\"Conflict: \", median_incongruent - median_congruent) }\n}", "getSnippet() {\n // if (this.is('verb')) {\n // return this.getPrincipalParts()\n // }\n\n /* Which variant to highlight? */\n let chosen_variant_to_show = [];\n let variants_matched = [];\n this.rows.forEach((row) => {\n if (row.variant_matched) {\n variants_matched.push(row);\n }\n });\n variants_matched = variants_matched.sort((a, b) => {\n return (\n b.should_be_taught +\n b.correctness_grade_of_inflectional_form +\n b.correctness_grade_of_word -\n (a.should_be_taught +\n a.correctness_grade_of_inflectional_form +\n a.correctness_grade_of_word)\n );\n });\n if (variants_matched.length > 0) {\n chosen_variant_to_show =\n variants_matched[0].inflectional_form_categories.filter(\n (i) => !isNumber(i)\n );\n }\n\n return this.getSingleTable({\n returnAsString: true,\n give_me: chosen_variant_to_show,\n });\n }", "function getScenarioSelection() {\n //check selected scenarios\n if (scenarioUpdateFlag) {\n \tselectedScenarios = \"\";\n\t if (exhibit._registry._registry.facet.f1 != null && exhibit._registry._registry.facet.f1._selections.length > 0) {\n\t\t //list selected facet values as { value1: true, value2: true }\n\t\t var valueObj = exhibit._registry._registry.facet.f1._selections;\n\t\t for (var i = 0; i < valueObj.length; i++) { \n\t\t \tchildrenNames = \"\";\n\t\t \tselectedScenarios += getDeepestChildren(valueObj[i].value, getScenarioTree());\n\t\t } \n\t\t if (selectedScenarios.charAt(selectedScenarios.length-1) == \";\")\n\t\t \tselectedScenarios = selectedScenarios.substring(0, selectedScenarios.length-1);\t \n\t } \n\t if (selectedScenarios == \"\") selectedScenarios = \"-\"; \n\t scenarioUpdateFlag = false;\n }\n\treturn selectedScenarios;\n}", "function displayVariation(varObj) {\r\n}\t// end of displayVariation", "makeSamplingDecision(options, traceId) {\n // If users set a specific sampler in the TraceOptions, use it.\n if (options && options.samplingRate !== undefined &&\n options.samplingRate !== null) {\n return sampler_1.SamplerBuilder.getSampler(options.samplingRate)\n .shouldSample(traceId);\n }\n let propagatedSample = null;\n // if there is a context propagation, keep the decision\n if (options && options.spanContext && options.spanContext.options) {\n propagatedSample =\n ((options.spanContext.options & this.IS_SAMPLED) !== 0);\n }\n let sampleDecision = !!propagatedSample;\n if (!sampleDecision) {\n // Use the default global sampler\n sampleDecision = this.sampler.shouldSample(traceId);\n }\n return sampleDecision;\n }", "function init_conf()\n {\n //----------------------------------\n // //\\\\ study model parameters\n //----------------------------------\n var APP_MODEL_Y_RANGE = 1000;\n //----------------------------------\n // \\\\// study model parameters\n //----------------------------------\n\n\n //====================================================\n // //\\\\ subapp regim switches\n //====================================================\n sconf.enableStudylab = false;\n sconf.enableTools = false;\n //====================================================\n // \\\\// subapp regim switches\n //====================================================\n\n\n //----------------------------------\n // //\\\\ original material parameters\n //----------------------------------\n var pictureWidth = 504;\n var pictureHeight = 495;\n\n var pointA = [ 28, 456 ];\n var pointe = [ 28, 46 ];\n\n var modorInPicX = pointA[0];\n var modorInPicY = pointA[1]; \n //.set it from graph editor\n var pictureActiveArea = pointA[1] - 46;\n //----------------------------------\n // \\\\// original material parameters\n //----------------------------------\n var mod2inn_scale = pictureActiveArea / APP_MODEL_Y_RANGE;\n var originX_onPicture = pointA[0];\n var originY_onPicture = pointA[1];\n\n\n\n\n\n //----------------------------------------------------\n // //\\\\ prepares sconf data holder\n //----------------------------------------------------\n //-----------------------------------\n // //\\\\ topic group colors,\n // todm: possibly proliferation\n //-----------------------------------\n sconf.default_tp_lightness = 30;\n var given = [0, 150, 0, ]; //0.5];\n var proof = [0, 0, 255, ]; //0.5];\n var result = [200, 40, 0, ]; //0.5];\n var hidden = [0, 0, 0, ]; //0];\n\n\n var predefinedTopics =\n {\n given,\n proof,\n result,\n hidden,\n\n //:curves\n \"ABC\" : given,\n \"mainCurve\" : given,\n \"Abc\" : proof,\n \"remoteCurve\" : proof,\n\n //:areas\n \"ABD\" : given,\n \"ACE\" : given,\n \"area-ABD\" : given,\n \"area-ACE\" : given,\n \"Abd\" : proof,\n \"Ace\" : proof,\n \"area-Abd\" : proof,\n \"area-Ace\" : proof,\n //:linear areas\n \"Afd\" : result,\n \"Age\" : result,\n\n \"ABDPerACE\" : given,\n \"AD2PerAE2\" : result,\n };\n //-----------------------------------\n // \\\\// topic group colors,\n //-----------------------------------\n\n\n var originalPoints =\n {\n 'A' : { \n pos : pointA,\n pcolor : given,\n letterAngle : -90,\n },\n 'e' : { \n pos : pointe,\n pcolor : proof,\n letterAngle : 90,\n },\n\n 'B' : { \n pcolor : given,\n letterAngle : 0,\n },\n 'C' : { \n pcolor : given,\n letterAngle : -45,\n },\n 'D' : { \n pcolor : given,\n letterAngle : 215,\n },\n 'E' : { \n pcolor : given,\n letterAngle : 180,\n },\n 'b' : { \n pcolor : proof,\n letterAngle : 0,\n },\n 'c' : { \n pcolor : proof,\n letterAngle : -90,\n },\n 'd' : { \n pcolor : proof,\n letterAngle : 180,\n },\n\n 'F' : { \n pcolor : given,\n letterAngle : 135,\n },\n 'G' : { \n pcolor : given,\n letterAngle : 45,\n },\n 'f' : { \n pcolor : proof,\n letterAngle : 90,\n },\n 'g' : { \n pcolor : proof,\n letterAngle : 90,\n },\n\n 'pivotPoint1' : { \n pcolor : result,\n doPaintPname : false,\n letterAngle : 90,\n },\n\n 'pivotPoint2' : {\n pcolor : given,\n letterAngle : 90,\n doPaintPname : false,\n },\n };\n\n var linesArray =\n [\n { 'Ab' : { pcolor : proof } },\n { 'Ac' : { pcolor : proof } },\n { 'Ad' : { pcolor : result } },\n { 'Ae' : { pcolor : result, 'stroke-width' : 3, } },\n\n { 'Ag' : { pcolor : result, 'stroke-width' : 3, } },\n\n { 'ec' : { pcolor : proof } },\n { 'db' : { pcolor : proof } },\n\n { 'AB' : { pcolor : given } },\n { 'AC' : { pcolor : given } },\n { 'AD' : { pcolor : given } },\n { 'AE' : { pcolor : given, 'stroke-width' : 3, } },\n { 'AG' : { pcolor : given } },\n { 'EC' : { pcolor : given } },\n { 'DB' : { pcolor : given } },\n ];\n\n\n to_sconf =\n {\n //----------------------------------\n // //\\\\ scenario\n //----------------------------------\n hideProofSlider : true, // false,\n hideProofSliderCompletely : false,\n //----------------------------------\n // \\\\// scenario\n //----------------------------------\n\n\n //----------------------------------\n // //\\\\ original lemma parameters\n //----------------------------------\n curvePivots :\n [\n [0, 0],\n //[326.8, 715.3],\n //[326.8*1.05, 742*1.05],\n\n [270.19, 612.8],\n\n //[72.29, 621.2],\n\n //[1516.1, 569.9]\n //[1516.1, 495] //tmp\n [ 1060, 567 ]\n /* very good for debug: simple curve\n [0, 0],\n [500, 1000],\n [1000, 0]\n */\n ],\n\n\n //*************************************************\n // //\\\\ lemma model parameters\n //*************************************************\n APP_MODEL_Y_RANGE,\n //:ranges\n tanA_min : 0.1, //pivot1x/pivot1y minimum\n pivot1y_max : APP_MODEL_Y_RANGE * 0.99,\n pivot2x_max : APP_MODEL_Y_RANGE * 1.8,\n pivot2y_min : APP_MODEL_Y_RANGE * 0.3,\n pivot2y_max : APP_MODEL_Y_RANGE * 0.99,\n\n\n //bezier parameter t of point C on principal curve\n //tC : 0.5, //good for debug\n tC : 0.50077 / 0.79 ,\n\n claimRatio : 0.74081,\n //range:\n claimRatio_max : 0.9, //Dy_per_Ey\n\n\n tiltRatio : 1, //controls DB-line tilt: \n //1 is perpendicular; < 1 dy/dx is negative, > 1 is positive\n //:ranges\n tiltRatio_min : 0.4,\n tiltRatio_max : 1.5,\n Ep2yrange_max : 0.8,\n Cx_min : 0.1,\n //*************************************************\n // \\\\// lemma model parameters\n //*************************************************\n //----------------------------------\n // \\\\// original lemma parameters\n //----------------------------------\n\n\n\n //----------------------------------\n // //\\\\ model-view parameters\n //----------------------------------\n //100; //display in \"percents\" of Ae\n LEGEND_NUMERICAL_SCALE : 100,\n\n modorInPicX,\n modorInPicY,\n innerMediaHeight : pictureHeight + sconf.SLIDERS_LEGEND_HEIGHT,\n innerMediaWidth : pictureWidth,\n\n thickness : 4,\n //----------------------------------\n // \\\\// model-view parameters\n //----------------------------------\n };\n to_sconf.areaScale = 1 / to_sconf.APP_MODEL_Y_RANGE / to_sconf.APP_MODEL_Y_RANGE;\n //----------------------------------\n // \\\\// prepares sconf data holder\n //----------------------------------------------------\n\n\n\n //----------------------------------------------------\n // //\\\\ copy-pastes to sconf\n //----------------------------------------------------\n //making size to better fit lemma's diagram\n fconf.LETTER_FONT_SIZE_PER_1000 = 30;\n\n paste( sconf,\n paste( to_sconf,\n {\n //double back step ../../ is to reuse this path in code for twin-lemma\n mediaBgImage : \"../../b1sec1lemma9/img/lemma9-original.png\",\n\n linesArray,\n predefinedTopics,\n originalPoints,\n originX_onPicture,\n originY_onPicture,\n pictureWidth,\n pictureHeight,\n mod2inn_scale,\n })\n );\n //----------------------------------------------------\n // \\\\// copy-pastes to sconf\n //----------------------------------------------------\n }", "static lancerScenario(){\n Plateau.message = \"Début de la partie\";\n Plateau.initDisplay();\n Plateau.currentPlayer=-1;\n }", "function getProbeFeatures(){\r\n\r\n\t\t\tvar list = [[settings.stimulus_large, settings.colorred, 0],\r\n\t\t\t\t\t\t[settings.stimulus_large, settings.colorred, 90],\r\n\t\t\t\t\t\t[settings.stimulus_large, settings.colorblue, 0],\r\n\t\t\t\t\t\t[settings.stimulus_large, settings.colorblue, 90]];\r\n\t\t\tvar weight = [0.25, 0.3125, 0.1875, 0.25];\r\n\t\t\tvar weighed_list = general.generateWeighedList(list, weight);\r\n\t\t\tvar random_num = general.rand(0, weighed_list.length-1);\r\n\t\t\treturn weighed_list[random_num];\r\n\t}", "function extractScenario(strIn) {\n // get first word on line\n if (strIn.trim().startsWith('Scenario:') || strIn.trim().startsWith('scenario:')) {\n return strIn.trim().substring(9).trim()\n } else if (strIn.trim().startsWith('Scenario Outline:') || strIn.trim().startsWith('scenario outline:')) {\n return strIn.trim().substring(17).trim()\n }\n return '';\n}", "set_variables_to_experiment() {\n console.log(\"set_variables_to_experiment\");\n this.curr_conditions_constants = this.experiment_conditions_constants;\n this.curr_condition_index = 0;\n this.curr_round_num = 0;\n this.input_count_array = new Array(this.curr_conditions_constants[0].trials_per_round).fill(0);\n this.is_practice = false;\n }", "function StudyViewerFactory($filter, EntityViewer, gettextCatalog) {\n\n function StudyViewer(study) {\n var ev = new EntityViewer(study, 'Study');\n\n ev.addAttribute(gettextCatalog.getString('Name'), study.name);\n ev.addAttribute(gettextCatalog.getString('Description'), $filter('truncate')(study.description, 60));\n ev.addAttribute(gettextCatalog.getString('State'), study.state.toUpperCase());\n\n ev.showModal();\n }\n\n return StudyViewer;\n}", "getName() {\n return \"DensePriceVariationPrediction\";\n }", "getName() {\n return \"DensePriceVariationPrediction\";\n }", "static readRandomSentence(theme) {\r\n console.log(Main.firstPartlistImpl.readRandomThemedPart(theme) + Main.secondPartListImpl.readRandomPart() + Main.thirdPartListImpl.readRandomPart()); \r\n }", "function DASFeature() {}", "get details() {\n if (this._researchSubject.researchStudy && this._researchSubject.researchStudy.commentOrDescription) {\n return this._researchSubject.researchStudy.commentOrDescription.value;\n } else {\n return \"\";\n }\n }", "extractStudyDetails(studiesIntersected) {\n var localSearchResultsStudies = [];\n for (var i = 0; i < studiesIntersected.length; i++) {\n var studyHit = this.studyDict[studiesIntersected[i]];\n localSearchResultsStudies.push({\n resultType: \"study\",\n id: studyHit.studyId,\n title: studyHit.name,\n description: studyHit.description\n });\n }\n return localSearchResultsStudies;\n }", "function specStarted(spec) {\n _scenariooReporter.default.scenarioStarted(options, spec.description);\n }", "function modeSpecific()\n\t{\n\t\tif (problem.get('ansType') === 'multiPart')\n\t\t{\n\t\t\tif (!view.showingSolution)\n\t\t\t{\n\t\t\t\tview.stepMode();\n\t\t\t\tvar steps = fw.getWidget('stepByStep');\n\t\t\t\tsteps.showCompleted();\n\t\t\t\tsteps.show();\t\t\t// They're not visible at this point (though most pieces are)\n\t\t\t}\n\t\t}\n\t}" ]
[ "0.5128658", "0.50991416", "0.49080807", "0.49036923", "0.48992968", "0.48587966", "0.47773543", "0.471713", "0.4692595", "0.4628808", "0.46274167", "0.4625167", "0.45750666", "0.44930327", "0.44772887", "0.44549042", "0.44508377", "0.44479096", "0.44365692", "0.4416215", "0.4410855", "0.4409743", "0.44085234", "0.44085234", "0.4405157", "0.43999588", "0.43972784", "0.4378935", "0.4365748", "0.43588626" ]
0.54558784
0
add a horizontal reference line (and rescale chart if necessary)
function addReferenceLine(chart, value, yaxis) { yaxis = yaxis || 0; // add reference line chart.yAxis[yaxis].addPlotLine({ value: value, color: 'red', dashStyle: 'dot', width: 2 }); // add to the values that should be included on the chart (ie. rescale list) chartIncludeValues[yaxis].push(value); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addLine () {\n\tconst linksCoords = this.getBoundingClientRect();\n\tline.style.width = `${linksCoords.width}px`;\n\tline.style.transform = `translate(${linksCoords.left}px, ${linksCoords.top}px)`;\n\tline.style.opacity = 1;\n}", "function renderAxisLine() {\n ctx.save();\n ctx.setLineDash(renderAttrs.lineDash || []);\n if( renderAttrs.orientation === 'horizontal') {\n drawLine( ctx, { x: renderMin, y: originCrossAxisCoord },\n { x: renderMax, y: originCrossAxisCoord });\n }\n else {\n drawLine( ctx, { x: originCrossAxisCoord, y: renderMin },\n { x: originCrossAxisCoord, y: renderMax });\n }\n ctx.restore();\n }", "function drawLine() {\n\n var data = new google.visualization.DataTable();\n data.addColumn('number', 'X');\n data.addColumn('number', 'Clients');\n data.addRows(self.charts.line.rows);\n\n var options = self.charts.line.options;\n\n var chart = new google.visualization.LineChart(document.getElementById('chart_div'));\n\n chart.draw(data, options);\n }", "function updateLine() {\n d3.selectAll('.line-chart').remove();\n svg_line = d3.select(\"#lines\").append(\"svg\")\n .attr('class', 'line-chart')\n .attr(\"width\", width_line + margin_line.left + margin_line.right)\n .attr(\"height\", height_line + margin_line.top + margin_line.bottom)\n .append(\"g\")\n .attr(\"transform\",\n \"translate(\" + margin_line.left + \",\" + margin_line.top + \")\");\n}", "addVertLine(){\n\t\t// start in center of the x-range\n\t\tlet pos = Math.floor(this.getCenter().x * 10) / 10.;\t// round to nearest .1\n\t\tlet to_shape = {\n\t\t\tid: this.cur_annotation_id,\n\t\t\tname: 'Spike ('+pos+')',\n\t\t\ttype: 'rect',\n\t\t\txref: 'x',\n\t\t\tyref: 'paper',\n\t\t\tx0: pos,\n\t\t\tx1: pos,\n\t\t\ty0: 0,\n\t\t\ty1: 1,\t// go from bottom to top of plot part of window\n\t\t\tline: {\n\t\t\t\tcolor: '#4227ff',\n\t\t\t\topacity: 1.,\n\t\t\t\twidth: 1,\n\t\t\t},\n\t\t}\n\t\tthis.cur_annotation_id ++;\n\t\tPlotly.relayout(this.getElement(), {'shapes[0]': to_shape});\n\t\tthis.refreshAnnotationMarkup();\n\t\tthis.annotations_list_target.last().click();\n\t}", "function render_linePositief() {\n var plotLine = hgiLine().mapping(['meetmoment', 'opgewektheid', 'ontspanning']).yDomain([0, 100]).legend(['Opgewektheid', 'Ontspanning']).yTicks(5).xLabel('Meetmoment').yLabel('Positieve gevoelens');\n //plotLine.overlayScale(0.75).overlayOffset(11);\n d3.select('#linePositief').datum(data).call(plotLine);\n}", "function drawHorizontalRule() {\n var stat = getState(cm);\n _replaceSelection(cm, stat.image, insertTexts.horizontalRule);\n}", "function drawLineChart(raw_line_data) {\n var data = google.visualization.arrayToDataTable(raw_line_data['line']);\n\n var options = {\n title: 'Energy Usage',\n backgroundColor: 'transparent',\n colors: ['#7851a9'],\n 'width': 1000,\n 'height': 750,\n //curveType: 'function', <-- made graph curvy\n legend: { position: 'top' }\n };\n\n var chart = new google.visualization.LineChart(document.getElementById('linechart'));\n\n chart.draw(data, options);\n }", "function horizontalScale() {\n if (svg.element.select('.horizontalScale')) svg.element.select('.horizontalScale').remove()\n if (ruler.container) ruler.container.remove()\n ruler.container = svg.element\n .append('g')\n .attr('transform', 'translate(' + [ruler.y, ruler.x] + ')')\n .attr('class', 'horizontalScale')\n\n ruler.container.append('path')\n .attr('d', d => 'M' + ruler.padding + ',10L' + (ruler.width + ruler.padding) + ',10')\n .attr('stroke-width', 1)\n .attr('stroke', '#000')\n\n ruler.element = ruler.container\n .append('text')\n .attr('class', 'ruler-text')\n .attr('x', ruler.width / 2 + ruler.padding)\n .attr('y', 36)\n .attr('font-family', 'sans-serif')\n .text('')\n .attr('font-size', '14px')\n .attr('fill', '#000')\n .attr('text-anchor', 'middle')\n }", "addLine() {\n this.chart.append(\"path\")\n .datum(this.dataset) // Binds data to the line \n .attr(\"class\", \"line\") // Assign a class for styling \n .attr(\"d\", this.generateLine()) // d is the path to be drawn. Pass the function to call to generate path.\n .style('stroke', this.lineColor || '#ffab00'); // set line color\n }", "function drawPrimaryChart() {\n\n var x = parseInt($('#anio').val(), 10);\n var data = new google.visualization.DataTable();\n\n data.addColumn('string', 'periodo');\n data.addColumn({type: 'string', role: 'annotation'});\n\n\n data.addColumn('number', x - 1);\n data.addColumn('number', 'Mayor historico');\n data.addColumn('number', 'Promedio ' + (x - 1));\n data.addColumn('number', 'Menor historico');\n data.addColumn('number', x);\n\n // Add a new column for your tooltips.\n data.addColumn({\n type: 'string',\n label: 'Tooltip Chart',\n role: 'tooltip',\n 'p': {'html': true}\n });\n\n // Add your data (with the newly added tooltipImg).\n data.addRows(primaryData);\n var visibleDiv = document.getElementById('GraficaPrincipal');\n var primaryChart = new google.visualization.LineChart(visibleDiv);\n primaryChart.draw(data, primaryOptions);\n\n}", "function addLine(pConfLine, pIndex) {\n\t\tvar myCanvas = myCanvasContainer.svg().svg(\"get\"),\n\t\t\tg = myCanvasContainer.find(\"#linesOverlay\").svg(),\n\t\t\tmyElemId = \"line_\" + gCountLines++,\n\t\t\tmyLine = null,\n\t\t\tmyLineHandlers = null;\n\t\tif (gIsDrawingLine) {\n\t\t\tif (!gIsImporting && pConfLine.points.length > 1) {\n\t\t\t\t// We're adding a segment to the line\n\t\t\t\tmyElemId = \"line_\" + --gCountLines;\n\t\t\t\tgCurrentConf.lines.pop();\n\t\t\t}\n\t\t\tvar myLineProps = {};\n\t\t\tfor (var myLinePropName in pConfLine.props) {\n\t\t\t\tswitch (myLinePropName) {\n\t\t\t\t\tcase \"marker-start\":\n\t\t\t\t\tcase \"marker-end\":\n\t\t\t\t\t\tmyLineProps[myLinePropName] = \"url(#\" + pConfLine.props[myLinePropName] + \")\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmyLineProps[myLinePropName] = pConfLine.props[myLinePropName];\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmyLine = myCanvas.polyline(g, pConfLine.points, myLineProps);\n\t\t\tfor (var myLinePropName in pConfLine.style) {\n\t\t\t\t$(myLine).css(myLinePropName, pConfLine.style[myLinePropName]);\n\t\t\t}\n\t\t\t$(myLine).addClass(\"drawing\");\n\t\t\t$(myLine).attr(\"id\", myElemId);\n\t\t\tgCurrentLine = myLine;\n\t\t}\n\t\t// Update serialization\n\t\tmyLine = $(myLine);\n\t\tvar myHandlersHtml = \"\";\n\t\tfor (var myPointIndex in pConfLine.points) {\n\t\t\tmyHandlersHtml += \"<div class=\\\"handler point\" + myPointIndex + \"\\\" rel=\\\"\" + myPointIndex + \"\\\" style=\\\"left:\" + (pConfLine.points[myPointIndex][0] + myCanvasContainer[0].offsetLeft - 8) + \"px;top:\" + (pConfLine.points[myPointIndex][1] + myCanvasContainer[0].offsetTop - 8) + \"px\\\"></div>\";\n\t\t}\n\t\tmyLine.on(\"mouseenter\", function(e) {\n\t\t\tif (!gIsReadOnly) {\n\t\t\t\tif (!gIsDrawingLine) {\n\t\t\t\t\tmyLineHandlers = $(\"#lineHandlers\").empty().html(myHandlersHtml).show().find(\".handler\");\n\t\t\t\t\tmyLineHandlers.on(\"mouseenter\", function(e) {\n\t\t\t\t\t\tmyContextMenuLine.css(\"top\", $(this).css(\"top\")).css(\"left\", $(this).css(\"left\"))\n\t\t\t\t\t\t\t.attr(\"rel\", myLine.attr(\"id\"));\n\t\t\t\t\t\tmyContextMenuLine.data(\"point-index\", $(this).attr(\"rel\") * 1);\n\t\t\t\t\t\tmyContextMenuLine.show();\n\t\t\t\t\t\t// Keep menu open for 200ms\n\t\t\t\t\t\tpreventClosingContextMenu = true;\n\t\t\t\t\t\ttimeoutIdContextMenu = window.setTimeout(function() {\n\t\t\t\t\t\t\tpreventClosingContextMenu = false;\n\t\t\t\t\t\t}, 200);\n\t\t\t\t\t});\n\t\t\t\t\tgCurrentElement = pConfLine;\n\t\t\t\t}\n\t\t\t}\n\t\t}).on(\"mouseleave\", function(e) {\n\t\t\tif (!preventClosingContextMenu) {\n\t\t\t\tmyContextMenuLine.hide();\n\t\t\t\t$(\"#lineHandlers\").hide();\n\t\t\t}\n\t\t});\n\t\tif (!gIsImporting) {\n\t\t\tgCurrentConf.lines.push(pConfLine);\n\t\t\tmyLine.data(\"index\", gCurrentConf.lines.length - 1);\n\t\t} else {\n\t\t\tmyLine.data(\"index\", pIndex);\n\t\t}\n\t}", "function drawline() {\n\n if (isDrawing) {\n linePoint2 = d3.mouse(this);\n gContainer.select('line').remove();\n gContainer.append('line')\n .attr(\"x1\", linePoint1.x)\n .attr(\"y1\", linePoint1.y)\n .attr(\"x2\", linePoint2[0] - 2) //arbitary value must be substracted due to circle cursor hover not working\n .attr(\"y2\", linePoint2[1] - 2); // arbitary values must be tested\n\n }\n }", "function setLine(tab){\n var tabWidth = $(tab).outerWidth();\n var tabPos = $(tab).position();\n $(\".indicator-line\").css({\n \"width\": tabWidth,\n \"left\": tabPos.left\n });\n }", "function drawLineChart($scope){\n\tif(!$scope.chartTypeToggle.line){\n\t\treturn;\n\t}\n\tvar svg = $scope.svg;\n\tvar $axisProvider = $scope.$axisProvider;\n\tvar $lineChartProvider = $scope.$injector.get(\"$lineChartProvider\");\n\t$scope.$lineChartProvider = $lineChartProvider;\n\t$lineChartProvider.axisProvider = $axisProvider;\n\t$lineChartProvider.svg = svg;\n\t$lineChartProvider.data = getDataFromScope($scope);\n\t$lineChartProvider.effect = $scope.chartEffect;\n\t$lineChartProvider.dataX = $scope.chartX;\n\t$lineChartProvider.dataY = $scope.chartY;\n\t$lineChartProvider.animate = $scope.chartAnimate;\n \n\t$lineChartProvider.draw();\n\t\n\t$scope.$watch('chartAnimate',function(newValue,oldValue){\n\t\t$lineChartProvider.animate = newValue;\n\t\t//redraw only when animate was turned on from off.\n\t\tif(!oldValue && newValue && $scope.chartTypeToggle.line){\n\t\t\t$lineChartProvider.draw();\n\t\t}\n\t});\n\t$scope.$watch('chartEffect',function(newValue,oldValue){\n\t\t$lineChartProvider.effect = newValue;\n\t\tif(oldValue!=newValue && $scope.chartTypeToggle.line){\n\t\t\t$lineChartProvider.draw();\n\t\t}\n\t});\t\n}", "lineRender(){\n d3.select('.circle-legend').select('svg').append('line').attr('x1',0).attr('x2',180).attr('y1',0).attr('y2',0)\n .attr('transform','translate(0,55)').classed('legendLine',true)\n }", "function showLine(lineData, lineID) {\n\tsvgLine.append(\"path\")\n\t\t .attr(\"class\", \"line\")\n\t\t //We give the lines ID's so we can select and remove them\n\t\t .attr(\"id\", lineID)\n\t\t .attr(\"d\", avgAlcLine(avgAlcConsumption))\n\t\t .transition()\n\t\t .duration(1000)\n\t\t .attr(\"d\", avgAlcLine(lineData));\n}", "function drawHorizonalLine(y, color) {\n ctx.beginPath();\n ctx.strokeStyle = color;\n ctx.moveTo(0, y);\n ctx.lineTo(canvas.width, y);\n ctx.stroke();\n}", "function drawHorizon() {\n push();\n\n // the horizon line\n horizonYAnchor = (hGridNum / 10) * gridH;\n horizonTopY = horizonYAnchor / 2;\n\n fill(greenC);\n beginShape();\n curveVertex(0, horizonYAnchor);\n curveVertex(0, horizonYAnchor);\n curveVertex(width / 2, horizonTopY);\n curveVertex(width, horizonYAnchor);\n curveVertex(width, horizonYAnchor);\n vertex(width, height);\n vertex(0, height);\n vertex(0, horizonYAnchor);\n endShape(CLOSE);\n\n //debug\n //debugE(gridW * (floor(hGridNum/2)-3), trackY);\n //debugE(0, horizonYAnchor);\n //debugE(canvasW / 2, horizonYAnchor / 2);\n //debugE(canvasW, horizonYAnchor)\n pop();\n}", "drawLine(canvas, dependency, points, assignmentData = null) {\n const { client } = this,\n metaId = this.getMetaId(assignmentData);\n\n // Reuse existing element if possible\n let line = dependency.instanceMeta(metaId).lineElement;\n\n if (!line) {\n line = dependency.instanceMeta(metaId).lineElement = document.createElementNS(\n 'http://www.w3.org/2000/svg',\n 'polyline'\n );\n line.setAttribute('depId', dependency.id);\n if (assignmentData) {\n line.setAttribute('fromId', assignmentData.from.id);\n line.setAttribute('toId', assignmentData.to.id);\n }\n canvas.appendChild(line);\n }\n\n // TODO: Use DomHelper.syncClassList\n\n // className is SVGAnimatedString for svg elements, reading attribute instead\n line.classList.length && line.classList.remove.apply(line.classList, line.getAttribute('class').split(' '));\n\n line.classList.add(this.baseCls);\n\n if (dependency.cls) {\n line.classList.add(dependency.cls);\n }\n if (dependency.bidirectional) {\n line.classList.add('b-sch-bidirectional-line');\n }\n if (dependency.highlighted) {\n line.classList.add(...dependency.highlighted.split(' '));\n }\n if (BrowserHelper.isIE11) {\n const ddr = dependency.getDateRange(true),\n viewStart = client.startDate;\n\n if (ddr.start < viewStart) {\n line.classList.add('b-no-start-marker');\n }\n if (ddr.end < viewStart) {\n line.classList.add('b-no-end-marker');\n }\n }\n\n line.setAttribute(\n 'points',\n !points\n ? ''\n : points\n .map((p, i) => (i !== points.length - 1 ? `${p.x1},${p.y1}` : `${p.x1},${p.y1} ${p.x2},${p.y2}`))\n .join(' ')\n );\n\n DomDataStore.set(line, {\n dependency\n });\n }", "function horizontalRescale(increment) {\n if (increment) {\n if (graph.scale.horizontal.value < graph.scale.horizontal.limits[1]) {\n graph.scale.horizontal.increment()\n setNewYPositions()\n applyScaleText()\n }\n } else {\n if (graph.scale.horizontal.value > graph.scale.horizontal.limits[0]) {\n graph.scale.horizontal.decrement()\n setNewYPositions()\n applyScaleText()\n }\n }\n }", "function render_lineOngemak() {\n var plotLine = hgiLine().margin({\n 'top': 20,\n 'right': 140,\n 'bottom': 40,\n 'left': 50\n }).mapping(['meetmoment', 'ik_ben_van_slag', 'lichamelijk_ongemak']).yDomain([0, 100]).legend(['Ik ben van slag', 'Lichamelijk ongemak']).yTicks(5).xTicks(5).xLabel('Meetmoment');\n d3.select('#lineOngemak').datum(data).call(plotLine);\n}", "function render_lineEigenwaarde() {\n var plotLine = hgiLine().mapping(['meetmoment', 'piekeren', 'eigenwaarde']).yDomain([0, 100]).legend(['Gepieker', 'Eigenwaarde']).xLabel('Meetmoment').yTicks(5);\n d3.select('#lineEigenwaarde').datum(data).call(plotLine);\n}", "function UpdateLineChart(){\n var doc = document.getElementById(\"line_chart__\");\n\n doc.height = $('.bars').height() + 70\n doc.width = $('.bars').width()\n $('.line_chart,.lines,#line_chart__').width($('.bar_wrapper').width());\n $('.line_chart,.lines,#line_chart__').height($('.bar_wrapper').height() + 70);\n\n if(!isLineChartInizialized){\n isLineChartInizialized = true;\n chart = new Chart(doc, {\n type: 'line',\n data: {\n labels: getDateArray(),\n datasets: [{ \n data: getOnlyAnwsersFromArray($scope.first_patient_calculated),\n label: $scope.patients[$scope.patient1 - 1],\n borderColor: color1,\n fill: false\n }, { \n data: getOnlyAnwsersFromArray($scope.second_patient_calculated),\n label: $scope.patients[$scope.patient2 - 1],\n borderColor: color2,\n fill: false\n }\n ]\n },\n options: {\n legend: {\n display: false\n },\n scales: {\n yAxes: [{\n ticks: {\n stepSize: 1,\n beginAtZero: true,\n suggestedMax: 4\n }\n }]\n },\n options: {\n events: []\n },\n animation: {\n duration: 2000, // general animation time\n easing:\"easeInOutExpo\"\n },\n elements: {\n line: {\n tension: 0, // disables bezier curves\n }\n },\n label:{\n display: false\n }\n }\n });\n }else{\n chart.data.labels = getDateArray(),\n chart.data.datasets = [{ \n data: getOnlyAnwsersFromArray($scope.first_patient_calculated),\n label: \"Patient \" + $scope.patient1,\n borderColor: color1,\n fill: false\n }, { \n data: getOnlyAnwsersFromArray($scope.second_patient_calculated),\n label: \"Patient \" + $scope.patient2,\n borderColor: color2,\n fill: false\n }\n ]\n chart.update();\n }\n }", "function intializeLine() {\n var svg = document.getElementsByTagName('svg')[0];\n svgLine.setAttribute('stroke', 'black');\n svgLine.setAttribute('x1', line.x1);\n svgLine.setAttribute('y1', line.y1);\n svg.appendChild(svgLine);\n}", "function block_lemo4moodle_drawLinechart() {\n\n var data = new google.visualization.DataTable();\n data.addColumn('date', linechartColDate);\n data.addColumn('number', linechartColAccess);\n data.addColumn('number', linechartColOwnAccess);\n data.addColumn('number', linechartColUser);\n data.addRows(linechartDataArray);\n var options = {\n chart: {\n title: linechartTitle\n },\n hAxis: {\n title: linechartColDate,\n format:'d.M.yy'\n },\n\n };\n var activitychart = new google.visualization.LineChart(document.getElementById('linechart'));\n activitychart.draw(data, options);\n\n}", "function CalculationStepLine(options) {\n // TODO: CLEAN ALL OF THIS CODE\n // TODO: GET RID OF CONSTANT COLUMN POSITIONS\n\n const leftColumnPosition = 100;\n const middleColumnPosition = 100;\n\n let barHeight,\n color,\n domain,\n fontFamily,\n fontSize,\n labelText,\n line,\n scale,\n where;\n\n line = this;\n\n init(options);\n\n return line;\n\n /* INTIIALIZE */\n function init(options) {\n\n _required(options);\n _defaults(options);\n\n scale = defineScale();\n\n line.group = addGroup();\n line.columns = addColumns();\n\n line.label = addLabel()\n .update(labelText);\n\n line.bar = addBar();\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n barHeight = options.barHeight ? options.barHeight : 10;\n color = options.color ? options.color : \"black\";\n fontSize = options.fontSize ? options.fontSize : \"15pt\";\n fontFamily = options.fontFamily ? options.fontFamily : \"\";\n labelText = options.label ? options.label +\" =\" : \"=\";\n domain = options.domain ? options.domain : [0,1];\n line.lineHeight = options.lineHeight ? options.lineHeight : 25;\n\n }\n\n function _required(options) {\n\n where = options.where;\n\n }\n\n function addBar() {\n let bar;\n\n bar = new CalculationStepLinearIndicator({\n \"where\":line.columns.middle,\n \"color\":color,\n \"scale\":scale,\n \"fontSize\":fontSize,\n \"fontFamily\":fontFamily,\n \"height\":barHeight\n });\n\n return bar;\n }\n\n function addColumns() {\n let groupObject;\n\n groupObject = {};\n\n groupObject.left = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+leftColumnPosition+\",0)\");\n\n\n groupObject.middle = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+middleColumnPosition+\",0)\");\n\n\n return groupObject;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\n \"where\":where\n })\n .attr(\"transform\",\"translate(0,50)\");\n\n return group;\n }\n\n\n function addLabel() {\n let label;\n\n // TODO: DOES COLUMNS REALLY NEED TO BE PUBLIC?\n label = new ExplorableHintedText({\n \"where\":line.columns.left,\n \"textAnchor\":\"end\",\n \"foregroundColor\":color,\n \"fontFamily\":fontFamily,\n \"fontWeight\":\"normal\",\n \"fontSize\":fontSize\n })\n .move({\n \"x\":-5,\n \"y\":0\n });\n\n return label;\n }\n\n\n function defineScale() {\n let scale;\n\n //TODO: DONT HARD CODE DOMAIN AND RANGE\n scale = d3.scaleLinear()\n .domain(domain)\n .range([0,100]);\n\n return scale;\n }\n\n}", "function CalculationStepLine(options) {\n // TODO: CLEAN ALL OF THIS CODE\n // TODO: GET RID OF CONSTANT COLUMN POSITIONS\n\n const leftColumnPosition = 100;\n const middleColumnPosition = 100;\n\n let barHeight,\n color,\n domain,\n fontFamily,\n fontSize,\n labelText,\n line,\n scale,\n where;\n\n line = this;\n\n init(options);\n\n return line;\n\n /* INTIIALIZE */\n function init(options) {\n\n _required(options);\n _defaults(options);\n\n scale = defineScale();\n\n line.group = addGroup();\n line.columns = addColumns();\n\n line.label = addLabel()\n .update(labelText);\n\n line.bar = addBar();\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n barHeight = options.barHeight ? options.barHeight : 10;\n color = options.color ? options.color : \"black\";\n fontSize = options.fontSize ? options.fontSize : \"15pt\";\n fontFamily = options.fontFamily ? options.fontFamily : \"\";\n labelText = options.label ? options.label +\" =\" : \"=\";\n domain = options.domain ? options.domain : [0,1];\n line.lineHeight = options.lineHeight ? options.lineHeight : 25;\n\n }\n\n function _required(options) {\n\n where = options.where;\n\n }\n\n function addBar() {\n let bar;\n\n bar = new CalculationStepLinearIndicator({\n \"where\":line.columns.middle,\n \"color\":color,\n \"scale\":scale,\n \"fontSize\":fontSize,\n \"fontFamily\":fontFamily,\n \"height\":barHeight\n });\n\n return bar;\n }\n\n function addColumns() {\n let groupObject;\n\n groupObject = {};\n\n groupObject.left = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+leftColumnPosition+\",0)\");\n\n\n groupObject.middle = explorableGroup({\n \"where\":line.group,\n }).attr(\"transform\",\"translate(\"+middleColumnPosition+\",0)\");\n\n\n return groupObject;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\n \"where\":where\n })\n .attr(\"transform\",\"translate(0,50)\");\n\n return group;\n }\n\n\n function addLabel() {\n let label;\n\n // TODO: DOES COLUMNS REALLY NEED TO BE PUBLIC?\n label = new ExplorableHintedText({\n \"where\":line.columns.left,\n \"textAnchor\":\"end\",\n \"foregroundColor\":color,\n \"fontFamily\":fontFamily,\n \"fontWeight\":\"normal\",\n \"fontSize\":fontSize\n })\n .move({\n \"x\":-5,\n \"y\":0\n });\n\n return label;\n }\n\n\n function defineScale() {\n let scale;\n\n //TODO: DONT HARD CODE DOMAIN AND RANGE\n scale = d3.scaleLinear()\n .domain(domain)\n .range([0,100]);\n\n return scale;\n }\n\n}", "biggerLine() {\n this.ctx.lineWidth++\n }", "function updateLine(error, data) {\n\n // Remove old lines + axes + title\n if (movieLine != null){movieLine.remove();}\n if (movieLineCompare != null){movieLineCompare.remove();}\n if (movieLabel != null){movieLabel.remove();}\n if (xLabelLine != null){xLabelLine.remove();}\n if (titleLine != null){titleLine.remove();}\n if (svgLine.selectAll(\".axis.axis--x\") != null){svgLine.selectAll(\".axis.axis--x\").remove();}\n if (svgLine.selectAll(\".axis.axis--y\") != null){svgLine.selectAll(\".axis.axis--y\").remove();}\n\n // Draw new lines\n initLine();\n}" ]
[ "0.6873988", "0.6289484", "0.62650836", "0.6237712", "0.60501766", "0.60153943", "0.59681445", "0.594657", "0.5936607", "0.583125", "0.58251613", "0.5798592", "0.5762405", "0.57575756", "0.5748796", "0.57458395", "0.574221", "0.57418716", "0.574093", "0.5739442", "0.5731919", "0.57266283", "0.57232255", "0.57128096", "0.56758505", "0.56669384", "0.5649844", "0.5649844", "0.56396025", "0.56329244" ]
0.7033804
0
set y axis title and label color
function setYAxisColor(chart, color, yaxis) { yaxis = yaxis || 0; chart.yAxis[yaxis].update({ title: { style: { color: color } }, labels: { style: { color: color } } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setYAxisTitleFtn(chart, index, labels) {\n $log.info('setting the Y Axis title: ' + labels[index]);\n chart.options.vAxis.title = labels[index];\n }", "function setYAxisTitleFtn(chart, index, labels) {\n $log.info('setting the Y Axis title: ' + labels[index]);\n chart.options.vAxis.title = labels[index];\n }", "function appendYAxisTitle(svg, plot) {\n svg.append('text')\n .attr('id', 'yTitle')\n .attr('transform', 'translate(' + (plot.padding.left/3) + ','\n + (plot.padding.top + plot.range.y/2) + ') rotate(-90)')\n .text('Concentration %');\n }", "function drawYAxis() {\n paper.leonardo.vLine(plotArea.x, plotArea.y, plotArea.height);\n\n // TODO: Get rid of magic number. Base text on font size instead.\n var valueX = plotArea.x - opts.tickSize,\n valueTextX = plotArea.x - (3 * opts.tickSize);\n\n plot(scaleValues, function (x, y, value) {\n paper.leonardo.hLine(valueX, y, opts.tickSize);\n paper.text(valueTextX, y, value);\n });\n }", "function plot_set_yLabel(plot_id, text) {\n\tif (! (plot_id in plots)) {\n\t\tconsole.log('Broken plot_set_yLabel');\n\t\treturn;\n\t}\n\tplot_options(plot_id).scales.yAxes[0].scaleLabel.labelString = text;\n}", "function updateYlabel() {\n if (options.ylabel && ylabel) {\n ylabel.text(options.ylabel);\n } else {\n ylabel.style(\"display\", \"none\");\n }\n }", "function customYAxis( g ) {\n\t\t// move axis to align properly with the bottom left corner including tick values\n\t\tg.attr( \"transform\", \"translate(\" + ( -chart_margins.left / 2 ) + \", 0)\" )\n\t\tg.call( yAxis );\n\t\tg.select( \".domain\" );\n\t\tg.attr( \"text-anchor\", \"end\" );\n\t\tg.selectAll( \".tick:not(:first-of-type) line\" ).attr( \"stroke\", \"#777\" ).attr( \"stroke-dasharray\", \"2,2\" );\n\t\tg.selectAll( \".tick text\" ).attr( \"x\", -4 ).attr( \"dy\", 0 );\n\t}", "function customYAxis( g ) {\n\t\t// move axis to align properly with the bottom left corner including tick values\n\t\tchart.attr( \"transform\", \"translate(\" + ( -chart_margins.left / 2 ) + \", 0)\" )\n\t\tchart.call( yAxis );\n\t\tchart.select( \".domain\" );\n\t\tchart.attr( \"text-anchor\", \"end\" );\n\t\tchart.selectAll( \".tick:not(:first-of-type) line\" ).attr( \"stroke\", \"#777\" ).attr( \"stroke-dasharray\", \"2,2\" );\n\t\tchart.selectAll( \".tick text\" ).attr( \"x\", -4 ).attr( \"dy\", 0 );\n\t} // appends y-axis to chart group", "function drawYAxis() {\n // draw tick marks and labels\n var domain = y1Domain,\n styles = vis.__styles,\n ticks = vis.getYTicks(scales.y, c.h, extendRange, useLogScale);\n\n if (!extendRange && ticks[ticks.length-1] != domain[1]) ticks.push(domain[1]);\n\n if ($('body').hasClass('fullscreen')) {\n theme.horizontalGrid['stroke-width'] = 2;\n }\n\n _.each(ticks, function(val, t) {\n var y = scales.y(val), x = c.lpad;\n if (val >= domain[0] && val <= domain[1] || extendRange) {\n // c.paper.text(x, y, val).attr(styles.labels).attr({ 'text-anchor': 'end' });\n\n // axis label\n vis.label(x+2, y-10, formatter.y1(val, t == ticks.length-1), { align: 'left', cl: 'axis' });\n // axis ticks\n if (theme.yTicks) {\n vis.path([['M', c.lpad-25, y], ['L', c.lpad-20,y]], 'tick');\n }\n // grid line\n if (theme.horizontalGrid) {\n vis.path([['M', c.lpad, y], ['L', c.w - c.rpad,y]], 'grid')\n .attr(theme.horizontalGrid);\n }\n }\n });\n\n // draw axis line\n if (domain[0] <= 0 && domain[1] >= 0) {\n y = scales.y(0);\n vis.path([['M', c.lpad, y], ['L', c.w - c.rpad,y]], 'axis')\n .attr(theme.xAxis);\n }\n }", "function styleYAxis(selection) {\n // Add classes for tests.\n selection.attr('class', 'chartYAxis');\n\n // These paths are added by d3.axis, but we don't need them.\n selection.selectAll('path')\n .remove();\n\n selection.selectAll('line')\n .attr('class', 'chartYAxisTick__mark');\n\n // Move the text to the left side of the SVG.\n selection.selectAll('text')\n .attr('class', 'chartYAxisTick__text')\n .attr('dx', -(width - marginRight));\n\n // Add small background boxes behind each tick's text.\n // Remove existing boxes first, to avoid duplicates.\n selection.selectAll('rect')\n .remove();\n selection.selectAll('.tick')\n .insert('rect', ':last-child')\n .attr('class', 'chartYAxisTick__background')\n .attr('x', -marginLeft)\n .attr('y', -8)\n .attr('width', marginLeft)\n .attr('height', 15)\n .attr('rx', 2) // Border-radius\n .attr('ry', 2); // Border-radius\n }", "function drawYlabels(data, chartHeight, element) {\n\n // extracts scale from data\n var scale = data.scale;\n\n // determines the maximum value to be displayed on the Y axis of the chart\n var maxY = findMaxY(data.values, scale);\n\n // creates the label area that the labels are rendered to\n var labelArea = $(\"<div>\").attr(\"id\", \"yArea\");\n $(labelArea).css({height: chartHeight + \"px\"});\n $(element).append(labelArea);\n\n var labelHeight;\n var i;\n\n for (i = 0; i <= maxY / scale; i++) {\n // creates a label for each multiple of scale less than or equal to maxY\n var label = $(\"<div>\").addClass(\"yLabel\");\n\n // determines the label height\n labelHeight = ((i * scale) / maxY) * chartHeight;\n\n // updates the position and text displayed for the label\n $(label).css({marginBottom: (labelHeight - 13) + \"px\"});\n $(label).text((i * scale) + \" -\");\n\n // appends the label to the label area\n $(labelArea).append(label);\n }\n}", "function objectBuildAxisY(colorGrid, colorTick) {\n var axisY = {\n gridColor : colorGrid,\n tickColor : colorTick,\n margin : 20\n };\n return axisY;\n}", "function make_y_gridlines() {\t\t\n \t \treturn d3.axisLeft(yo).ticks(5)\n \t }", "function renderLabelsVertical() {\n var i, origin;\n\n // Y Labels\n for (i = 0; i < this.range.max - this.range.min + 1; i++) {\n origin = getInnerChartPoint([\n 0,\n 100 - (i * 100) / (this.range.max - this.range.min)\n ]);\n\n origin[0] -= LABEL_MARGIN;\n\n this.svg.add('text', origin, String(i + this.range.min), { class: 'chart-label chart-label-y' });\n }\n}", "updatePlot (initialization) {\n const { weightedSumMax } = this.palmMath.getData()\n this.yscale.domain([0, weightedSumMax]).nice()\n this.yAxis.scale(this.yscale)\n\n const container = (initialization)\n ? this.axisContainer\n : this.axisContainer.transition().duration(this.duration)\n\n container\n .call(this.yAxis)\n .selectAll('.tick text')\n .style('font-size', this.fontSize + 'px')\n .style('font-family', this.fontFamily)\n .style('fill', this.fontColor)\n }", "function onUpdate() {\n viz_title.style(\"fill\", (theme.skin() != customSkin) ? theme.skin().labelColor : \"#000\");\n}", "function onUpdate() {\n viz_title.style(\"fill\", (theme.skin() != customSkin) ? theme.skin().labelColor : \"#000\");\n}", "function createYAxis() {\n return d3.svg.axis().scale(that.y).orient('left').ticks(chart.yAxis.tickCount);\n }", "function createYAxis() {\n return d3.svg.axis().scale(that.y).orient('left').ticks(chart.yAxis.tickCount);\n }", "function make_y_axis() {\n return d3.svg.axis()\n .scale(y)\n .orient(\"left\")\n .ticks(10)\n }", "get yAxisAnnotationTextColor() {\r\n return brushToString(this.i.pi);\r\n }", "function make_y_axis() {\n return d3.svg.axis()\n .scale(y)\n .orient(\"left\")\n .ticks(5)\n }", "labelTextAxis(xAxis, yAxis){\n this.xAxis = xAxis;\n this.yAxis = yAxis;\n }", "setFontColor(color){\n this.chart.options.legend.labels.fontColor = color;\n }", "function drawTitle() {\n fill(\"red\");\n textSize(30);\n text(\"[Color Panel] : Does nothing but change color THATS IT!!\", width / 2 + titleOffset, titleOffset);\n}", "function addXYTitles(svg,xTitle,yTitle,xAxis,yAxis,width,height){\n\tvar ticks = svg .append(\"g\")\n\t.attr(\"class\", \"x axis\")\n\t.attr(\"transform\", \"translate(0,\" + height + \")\")\n\t.call(xAxis)\n\t.selectAll('.tick');\n\n\tfor (var j = 0; j < ticks[0].length; j++) {\n\t\tvar c = ticks[0][j],\n\t\t n = ticks[0][j+1];\n\t\tif (!c || !n || !c.getBoundingClientRect || !n.getBoundingClientRect)\n\t\tcontinue;\n\t\twhile (c.getBoundingClientRect().right > n.getBoundingClientRect().left) {\n\t\td3.select(n).remove();\n\t\tj++;\n\t\tn = ticks[0][j+1];\n\t\tif (!n)\n\t\t break;\n\t\t}\n\t}\n\t\n\t/*if(data.length > 7) {\n\t//rotate the x axis labels\n\tsvg.selectAll(\".x text\") // select all the text elements for the xaxis\n\t\t .attr(\"transform\", function(d) {\n\t\t return \"translate(\" + this.getBBox().height*-2 + \",\" + this.getBBox().height + \")rotate(-45)\";\n\t\t });\n\t}*/\n\t\n\tsvg .append(\"g\").append(\"text\")\n\t.attr(\"transform\", \"translate(0,\" + height + \")\")\n\t.attr(\"x\", width / 2)\n\t.attr(\"y\", 25)\n\t.attr(\"dy\", \".71em\")\n\t.style(\"text-anchor\",\"end\")\n\t.text(xtitle)\n\t.attr(\"class\", \"xTitle\");\n\t\n\tsvg\t.append(\"g\")\n\t\t.attr(\"class\", \"y axis\")\n\t\t.call(yAxis).append(\"text\")\n\t\t.attr(\"transform\", \"rotate(-90)\")\n\t\t.attr(\"y\", 6)\n\t\t.attr(\"dy\", \".71em\")\n\t\t.style(\"text-anchor\", \"end\")\n\t\t.text(yaxisname)\n\t\t.attr(\"class\",\"yTitle\");\n}", "function drawTitle(color, title_Y)\n{\n ctx.font = \"50px Arial\";\n ctx.textAlign = \"center\";\n ctx.strokeStyle = color;\n ctx.lineWidth = 3;\n ctx.strokeText(\"CASINO\", MID_CANVAS, title_Y);\n}", "function addBarAxis () {\n\t\t\textraChartGroup.append(\"g\")\n\t\t\t .attr(\"class\", \"barYAxis\")\n\t\t\t .style(\"font-size\", 13 * screenRatio + \"px\")\n\t\t\t .call(leftAxis_extraChart);\n\t\t}", "function grid_y_axis()\r\n\t{\r\n\t\treturn d3.svg.axis()\r\n\t\t\t.scale(yScale)\r\n\t\t\t.orient(\"left\")\r\n\t\t\t.ticks(y_ticks);\r\n\t}", "function gridYaxis() {\t\t\n return d3.axisLeft(y)\n .ticks(5)\n \n}" ]
[ "0.7211678", "0.7211678", "0.69628364", "0.6746738", "0.6605784", "0.65127677", "0.63657725", "0.6360708", "0.61986953", "0.61933553", "0.60415703", "0.58542657", "0.57747245", "0.5773445", "0.5767792", "0.576734", "0.576734", "0.5737276", "0.5737276", "0.57358855", "0.57239246", "0.5669122", "0.56669647", "0.5647003", "0.5633714", "0.56076854", "0.56075114", "0.5600218", "0.5563464", "0.554208" ]
0.73200464
0
get the user's project count to implement pagination
async function fetchProjectCount() { if (loggedInUser) { const projectCountResult = await fetch( `/searchProjects/${loggedInUser._id}/count/${query}`, { method: "GET", } ); const parsedProjectsData = await projectCountResult.json(); setProjectCount(parsedProjectsData.count); setIsDataLoading(false); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function numPages(){\n let no_pages = Math.ceil(all_projects.length/per_page);\n return parseInt(no_pages);\n }", "function projectCount() {\n $http.get('../api/project/count')\n .success(function (data, status, headers, config) {\n console.info(data);\n $scope.projectTotal = data;\n\n }).\n error(function (data, status, headers, config) {\n console.info(data);\n });\n }", "function getTutorialCountGroupedByProject(req, res) {\n\tTutorial.aggregate([\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: '$tutorialProjectID',\n\t\t\t\tcount: {$sum: 1}\n\t\t\t}\n\t\t}\n\t]).then((counts) => {\n\t\tres.status(200).json(counts)\n\t}).catch((err) => {\n\t\tconsole.log(err);\n\t})\n}", "function getCountOfFinishedTutorialsForAllProjects(req, res) {\n\t// Extract studentID\n\tconst {studentID} = req.params;\n\t// Create query to get count via aggregation\n\tProgress.aggregate([\n\t\t{\n\t\t\t$match: {\"studentID\": new mongoose.Types.ObjectId(studentID)}\n\t\t},\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: '$projectID',\n\t\t\t\tcount: {$sum: 1}\n\t\t\t}\n\t\t}\n\t]).then((counts) => {\n\t\tres.status(200).json(counts)\n\t}).catch((err) => {\n\t\tconsole.log(err);\n\t})\n}", "async function getNumPages(page) {\n //var contain the selector of the number of users in the search\n const NUM_USER_SELECTOR = '#js-pjax-container > div > div.columns > div.column.three-fourths.codesearch-results > div > div.d-flex.flex-justify-between.border-bottom.pb-3 > h3'; \n \n let inner = await page.evaluate((sel) => {\n let html = document.querySelector(sel).innerHTML; \n // format is: \"69,803 users\"\n return html.replace(',', '').replace('users', '').trim();\n }, NUM_USER_SELECTOR);\n \n const numUsers = parseInt(inner);\n \n console.log('numUsers: ', numUsers);\n \n /**\n * GitHub shows 10 resuls per page, so\n */\n return Math.ceil(numUsers / 10);\n }", "getUsersTotalCount() {\n return this.intercomClient.get(\"/users\", { per_page: 1 })\n .then((response) => {\n return _.get(response, \"body.total_count\");\n })\n .catch((err) => {\n const fErr = this.intercomClient.handleError(err);\n this.logger.error(\"getUsersTotalCount.error\", fErr);\n return Promise.reject(fErr);\n });\n }", "function getProjectCount()\n\t{\n\t\t$('#spinLoad').show();\n\t\t$.ajax({\n\t\t\ttype: 'get',\n\t\t\turl: localUrl+'getProjectCount',\n\t\t\tcontentType: \"application/json; charset=utf-8\",\n\t\t\tdataType: \"json\",\n\t\t\tsuccess: function(response){\n\t\t\t\tconsole.log('totalProjectCountText : '+response.message);\n\t\t\t\t$('#totalProjectCountText').html(response.message);\n\t\t\t\t$('#spinLoad').hide();\n\t\t\t},\n\t\t\terror: function(){console.log('#totalProjectCountText --> Gala re Pilaa');$('#spinLoad').hide();}\n\t\t});\n\t}", "function getRecordOrFieldCountsMyProjects(thistype, theseVisiblePids) {\t\t\r\n\t// Get projects counts via ajax\r\n\t$.post(app_path_webroot+'ProjectGeneral/project_stats_ajax.php',{ type: thistype, pids: theseVisiblePids }, function(data){\r\n\t\tif (data != '0') {\r\n\t\t\t// Parse JSON\r\n\t\t\tvar json = jQuery.parseJSON(data);\r\n\t\t\t// Loop through each project\r\n\t\t\tif (thistype == 'records') {\r\n\t\t\t\t// RECORDS\r\n\t\t\t\tfor (var this_pid in json) {\r\n\t\t\t\t\t$('#pid-cntr-'+this_pid).html( json[this_pid]['r'] );\r\n\t\t\t\t}\r\n\t\t\t\t// Get list of more pid's to process\r\n\t\t\t\tvar nextVisiblePids = json.next_pids;\r\n\t\t\t\tif (nextVisiblePids.length > 0) {\r\n\t\t\t\t\t// DO MORE\r\n\t\t\t\t\tgetRecordOrFieldCountsMyProjects('records', nextVisiblePids);\r\n\t\t\t\t}\r\n\t\t\t} else if (thistype == 'fields') {\r\n\t\t\t\t// FIELDS/INSTRUMENTS\r\n\t\t\t\tfor (var this_pid in json) {\r\n\t\t\t\t\t$('#pid-cntf-'+this_pid).html( json[this_pid]['f'] );\r\n\t\t\t\t\t$('#pid-cnti-'+this_pid).html( json[this_pid]['i'] );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "function countRepositories( account ) {\n // check to see if account is defined\n if( typeof account == \"undefined\" ) {\n //if not, let's set it to the global default\n account = global_github_account;\n }\n // we have a local variable here called repos\n // that is storing all the repositories in\n // our system... because it's local, noone\n // outside the function can see it\n var repos = {\n \"camerican\": [\"SCC\",\"example_form\"],\n \"someoneelse\": [\"SCC\"]\n }\n // we want to return the number of repos that\n // a given user has... let's make sure we can\n // find the user...\n if( typeof repos[account] != \"undefined\" ) {\n // if we find them in the repos Object, let's\n // return the number of repos\n return repos[account].length;\n } else {\n // else, we weren't able to find them, so they\n // by definition have 0 repos\n return 0;\n }\n}", "static count() {\n return User.find({})\n .then((users)=>{\n return users.length;\n });\n }", "count_of_tags_pre_proejct(req, res) {\n return Associations\n .findAll({\n where: {\n user_id: req.params.user_id,\n },\n order: [\n ['createdAt', 'DESC'],\n ],\n attributes: {exclude: ['createdAt', 'updatedAt', 'user_id'] },\n raw: true\n })\n .then((associations) => {\n let result = [];\n for ( let i in associations){\n result.push(associations[i].project_id)\n }\n get_tags_count_project_list(result, res);\n })\n .catch((error) => res.status(400).send(error));\n }", "function numPages(){\n let no_pages = Math.ceil(all_participants.length/per_page);\n return parseInt(no_pages);\n }", "function renderCounter(selectedProject) {\n const incompleteTasks = selectedProject.tasks.filter(\n (task) => !task.complete\n ).length;\n const tasksLeft = incompleteTasks === 1 ? 'task' : 'tasks';\n counter.innerText = `${incompleteTasks} ${tasksLeft} to go!`;\n}", "function count_users() {\n\tconst q = datastore.createQuery(USER);\n\treturn datastore.runQuery(q)\n\t\t.then( (count) => {\n\t\t\treturn count[0].length;\n\t\t});\n}", "static countUsers(){\n console.log('there are 50 users');\n }", "function RepoCount(data){\n\t// alert(data.total_count);\n\treturn data.total_count\n}", "function getPageCount(){\n\tlet studentCount = 0;\n\n\t//Loops through all students and for each which isn't deselected the loops adds one to the student counter.\n\tfor (var i = 0; i < studentList.length; i++) {\n\t\tif ($(studentList[i]).hasClass(\"deselected\") === false) {\n\t\t\tstudentCount++;\n\t\t}\n\t}\n\n\t//Calculates how many pages by taking the student count and divdeds it with studentsPerPage.\n\tpageCount = Math.ceil(studentCount / studentsPerPage);\n\n}", "async function getUserCount() {\n const query = datastore.createQuery(USERS);\n const entities = await datastore.runQuery(query);\n const count = Object.keys(entities[0]).length;\n return count;\n}", "pageCount() {\n return Math.round(this.itemCount() / this.itemsPerPage)\n }", "function getUserCount() {\n console.log(\"In getUser\");\n \n $.get(\"/app.json\", function(data) {\n completionCount = data;\n console.log(\"This is # of completed tasks in user.js: \"+data);\n console.log(\"Running Count: \"+completionCount);\n\n }).done(getTodos);\n\n}", "static async getUsersQtd() {\n const qtd = await user_model.collection.estimatedDocumentCount()\n return qtd \n }", "pageItemCount(pageIndex) {\n return this.pages[pageIndex] ? this.pages[pageIndex].element.length : -1\n }", "async getAllProjects(offset = 0, limit = 10) {\n return await Projects.findAll({\n offset: offset,\n limit: limit,\n include: {\n model: Users,\n attributes: ['username']\n }\n })\n }", "getTrafficPermissionTotalCount ({ commit }) {\n const getItems = async () => {\n const entities = await api.getAllTrafficPermissions()\n const count = entities.items.length\n\n commit('SET_TOTAL_TRAFFIC_PERMISSION_COUNT', count)\n }\n\n getItems()\n }", "function numberOfPages()\n{\n if(isSearched){\n return Math.ceil(searchResult.length / recordsPerPage);\n } else {\n return Math.ceil(data.length / recordsPerPage);\n }\n \n}", "function initiateNumberOfInvolvedTasks() {\n\n\t\t\t$http.get('http://localhost:8080/activiti-rest/service/runtime/tasks?candidateUser=' + nbc.user.id)\n\t\t\t.then(function(response){\n\t\t\t\t$rootScope.numberOfInvolvedTasks = response.data.total;\n\t\t\t});\n\t\t}", "function getCount() {\n return count;\n}", "function getTotalProjects() {\n fetch('https://inlupp-fa.azurewebsites.net/api/total-projects')\n .then(res => res.json()) \n .then(data => {\n document.getElementById('totalProjects').innerHTML = data.projects;\n document.getElementById('totalProjects-p').innerHTML = data.growth;\n })\n}", "function numberOfPages() {\n let totalPages = Math.ceil(eachStudent.length / studentsPerPage);\n return totalPages;\n}", "function totalFound() {\n numFound.style.display = \"block\";\n axios\n .get(\n `https://api.github.com/search/users?q=${inputString}&per_page=10&page=${pageNum}:last`,\n {\n method: \"get\"\n }\n )\n .then(res => {\n totalUsersFound = res.data.total_count;\n numFound.textContent = `Found ${totalUsersFound} results for \"${inputString}\", page ${pageNum +\n 1}`;\n });\n}" ]
[ "0.72571236", "0.698243", "0.6689139", "0.6434947", "0.6403922", "0.62969476", "0.6218683", "0.61550844", "0.6129921", "0.610201", "0.60687286", "0.60455346", "0.6043784", "0.6022392", "0.6004966", "0.596928", "0.5943809", "0.59359586", "0.59309965", "0.58342564", "0.5809787", "0.5762213", "0.57419765", "0.57345325", "0.57272243", "0.56747514", "0.56708395", "0.56690216", "0.56548345", "0.5634706" ]
0.80330926
0
Adds focus event to the input. On focus selects the text content of the input.
addFocusEventListener() { this.input.addEventListener('focus', () => this.input.select()); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function focusInputElement () {\n elements.input.focus();\n }", "function focusInputElement () {\n elements.input.focus();\n }", "focus() {\n this.$.input._focusableElement.focus();\n }", "focus () {\n const { textInput } = this;\n textInput && textInput.focus();\n }", "focus() {\n this.textInput.focus();\n }", "function focusInputElement(){elements.input.focus();}", "focus() {\n if (this.disabled || this.matches(':focus-within')) {\n // Don't shift focus from an element within the text field, like an icon\n // button, to the input when focus is requested.\n return;\n }\n super.focus();\n }", "function focusInput() { \n input.focus()\n}", "focus() {\n this._inputElement.focus()\n }", "function focus(){}", "focus() {\n this.$.input.focus();\n }", "focus() {\n const { textInput } = this;\n textInput && textInput.focus();\n }", "focus() {\n var self = this;\n if (self.isDisabled) return;\n self.ignoreFocus = true;\n self.control_input.focus();\n setTimeout(() => {\n self.ignoreFocus = false;\n self.onFocus();\n }, 0);\n }", "setFocus(){\n this.getInputEle().focus();\n }", "focus() {\n const inputField = this.shadowRoot.querySelector('input');\n inputField.focus();\n }", "handleFocus(event) {\n event.target.select();\n }", "function inputFocus(input) {\n switch (input) {\n case \"startDate\":\n setTimeout(() => {\n startDateInputRef.current.focus();\n }, 1);\n break;\n case \"endDate\":\n setTimeout(() => {\n endDateInputRef.current.focus();\n }, 1);\n break;\n\n default:\n break;\n }\n }", "focus() {\n this.$refs.input.focus();\n }", "_handleInputFocus(e) {\n this.refs.input.focus();\n }", "bindFocus(input){\n input.onfocus = event => {\n if (document.activeElement != this.focusedInput){\n clearResults();\n this.focusedInput = input;\n if ( event.target.value.length > 0 ){\n this.timer = setTimeout( () => this.search(event), 100);\n }\n }\n };\n }", "focus() {\n this.refs.input.focus();\n }", "focus() {\n this.toggleMenuList();\n this.input.focus();\n }", "function textFieldFocus () {\n status.focusOnTextField = true;\n }", "function inputMethodFocus() {\n\t\t\tif (!editor.settings.content_editable) {\n\t\t\t\t// Case 1 IME doesn't initialize if you focus the document\n\t\t\t\tdom.bind(editor.getDoc(), 'focusin', function() {\n\t\t\t\t\tselection.setRng(selection.getRng());\n\t\t\t\t});\n\n\t\t\t\t// Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event\n\t\t\t\t// Needs to be both down/up due to weird rendering bug on Chrome Windows\n\t\t\t\tdom.bind(editor.getDoc(), 'mousedown mouseup', function(e) {\n\t\t\t\t\tif (e.target == editor.getDoc().documentElement) {\n\t\t\t\t\t\teditor.getBody().focus();\n\n\t\t\t\t\t\tif (e.type == 'mousedown') {\n\t\t\t\t\t\t\t// Edge case for mousedown, drag select and mousedown again within selection on Chrome Windows to render caret\n\t\t\t\t\t\t\tselection.placeCaretAt(e.clientX, e.clientY);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tselection.setRng(selection.getRng());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}", "focus() {\n this.$refs.textInput.focus();\n }", "setFocus() {\n $(this).parent().addClass(\"input-focus\");\n }", "activateFocus() {\n this.isFocused_ = true;\n this.styleFocused_(this.isFocused_);\n if (this.bottomLine_) {\n this.bottomLine_.activate();\n }\n if (this.outline_) {\n this.updateOutline();\n }\n if (this.label_) {\n this.label_.styleShake(this.isValid(), this.isFocused_);\n this.label_.styleFloat(\n this.getValue(), this.isFocused_, this.isBadInput_());\n }\n if (this.helperText_) {\n this.helperText_.showToScreenReader();\n }\n }", "focus() {\n this.$refs.input.focus();\n }", "_focusHandler(event) {\n const that = this;\n\n if (that.disabled) {\n return;\n }\n\n if (event.target === that) {\n that.$.input.focus();\n that._edgeSelect = false;\n return;\n }\n\n that.setAttribute('focus', '');\n\n if (that.selectAllOnFocus) {\n if (navigator.userAgent.match(/Edge/)) {\n const scrollTop = that.$.input.scrollTop;\n\n if (that._edgeSelect) {\n that._edgeSelect = false;\n return;\n }\n\n setTimeout(function () {\n that._edgeSelect = true;\n that.$.input.select();\n that.$.input.scrollTop = scrollTop;\n }, 5);\n }\n else {\n that.$.input.select();\n }\n }\n }", "function onFocus(event) {\n\t\tif (props.onFocus) {\n\t\t\tprops.onFocus(event);\n\t\t}\n\t\tevent.target.select();\n\t\tshowAllSuggestions();\n\t\tsetSelectionToCurrentValue();\n\t}" ]
[ "0.7055412", "0.7055412", "0.68872213", "0.6880144", "0.6875773", "0.6875565", "0.68479896", "0.68452066", "0.6843065", "0.6797068", "0.679039", "0.6767311", "0.66292423", "0.6601434", "0.6599773", "0.6553613", "0.6477195", "0.6431828", "0.6429465", "0.6407373", "0.63576", "0.63386834", "0.6336191", "0.63148516", "0.6301541", "0.6294679", "0.6285149", "0.6265496", "0.6261939", "0.62569803" ]
0.73644197
0
Add Event Listeners Adds a click event listener to the reset button. On click sets the value to every entry in the input matrix to a blank string.
addResetButtonListener() { this.resetBtn.addEventListener('click', () => this.entries().forEach(entry => entry.value = "")); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addResetListener() {\n\t\t$('#reset').on('click', resetBoard)\n\t\t\n\t}", "function addResetListener() {\n var resetButton = document.getElementById('reset');\n resetButton.addEventListener('click', resetBoard);\n}", "function reset() {\r\n turn = 1;\r\n clickCounter = 0;\r\n win1 = -1;\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n matrix[i][j] = -1;\r\n }\r\n }\r\n document.getElementById(\"00\").innerHTML = \"\";\r\n document.getElementById(\"01\").innerHTML = \"\";\r\n document.getElementById(\"02\").innerHTML = \"\";\r\n document.getElementById(\"10\").innerHTML = \"\";\r\n document.getElementById(\"11\").innerHTML = \"\";\r\n document.getElementById(\"12\").innerHTML = \"\";\r\n document.getElementById(\"20\").innerHTML = \"\";\r\n document.getElementById(\"21\").innerHTML = \"\";\r\n document.getElementById(\"22\").innerHTML = \"\";\r\n}", "handleResetClick(event){\n this.value = '';\n this.tableData = [];\n const evtCustomEvent = new CustomEvent('reset');\n this.dispatchEvent(evtCustomEvent);\n }", "handleResetClick(event){\n this.value = '';\n this.tableData = [];\n const evtCustomEvent = new CustomEvent('reset');\n this.dispatchEvent(evtCustomEvent);\n }", "function clearDisplay()\n{\n const clear = document.querySelector(`#clear`);\n\n clear.addEventListener(`click`, function()\n {\n resetArray();\n resetTotal();\n resetOperator();\n\n updateDisplay(inputArray);\n });\n}", "function setupResetBut(){\r\n resetButton.addEventListener(\"click\",setColors)\r\n }", "function resetForm()\n{\n document.getElementById(\"blanketnum\").value = 0;\n document.getElementById(\"hedgenum\").value = 0;\n document.getElementById(\"bluenum\").value = 0;\n calcEstimate();\n createEventListeners();\n}", "function resetBtnFunctionality () {\n\tresetButton.addEventListener(\"click\", function() {\n\t\treset();\n\t});\n}", "function resetMatrix() {\r\n var id = \"\";\r\n for (var i = 0; i < letters.length; ++i) {\r\n for (var j = 0; j < letters.length; ++j) {\r\n id = letters[i] + \"to\" + letters[j];\r\n document.getElementById(id).value = defaultMatrixValues[i][j];\r\n }\r\n }\r\n}", "function reset(){\n let text =document.getElementById(\"txt\");\n text.value=\"\"; \n number = 0; \n arrNumber=[];\n arrOperation=[];\n}", "function clearOutput() {\n var inputs = matrixC.getElementsByTagName(\"input\");\n for (var i = 0; i < inputs.length; ++i) {\n inputs[i].value = \"\";\n }\n }", "function reset() {\n tfInput.value = \"\";\n tfResultado.value = \"\";\n taLogArea.value = \"\";\n numPrevio = 0;\n numActual = 0;\n numAcumulado = 0;\n strOperacion = \"\";\n cOperador = \"\";\n}", "function resetButtonClick(){\n populateTable();\n}", "function reset(){\n displayInput = [''];\n uniqueNumber = '';\n // clean the screen\n calcLine.textContent = '';\n resultLine.textContent = '';\n}", "function reset() {\n input = [0];\n return display(0);\n}", "function clearScreen () {\n $('.output').html('');\n inputArray = [];\n buttonClick = null;\n operatorClick = null;\n equateClick = null;\n decimalClick = null;\n operand = '';\n console.log('clear');\n}", "function resetButtonPressed() {\n reset();\n}", "function reset() {\n $button.on(\"click\", function(event) {\n // Prevents dupicate click assignments\n event.preventDefault();\n $button.off(\"click\");\n\n // Resets result divs and removes them from page, reloads search div, re-runs input function\n $search.val(\"\");\n $search.css(\"border-bottom\", \"2px solid rgb(255, 255, 255)\");\n $search.off(\"focus\");\n $(\"p\").html(\"\");\n $(\"ul\").html(\"\");\n $inputCard\n .hide()\n .delay(500)\n .fadeIn(1000);\n $alertCard.hide();\n $mapCard.hide();\n $newsCard.hide();\n $button.hide();\n $weatherCard.hide();\n $(\"select\").material_select();\n $(\"#alertDiv\").empty();\n $(\".imgBox\").remove();\n $(\"#tableHead\").empty();\n $(\"#tableRow\").empty();\n $(\"#dropdown1\").empty();\n $(\"#safetyDisplay\").empty();\n input();\n });\n }", "function onReset() {\n clear();\n}", "function clearPressed(){\n inputs = [\"\"];\n $(\"#displayScreen p\").text(0);\n i = 0;\n num1 = null;\n num2 = null;\n operator = null;\n totalInt1= null;\n totalInt2 = null;\n storeNum2 = null;\n equalFire = false;\n\n}", "function clear(){\n \n for(i=0;i<valueBtn.length;i++){\n valueBtn[i].textContent=null;\n }\n move.textContent=\"move:0\";\n time.textContent=\"time:0\";\n msg.textContent=null;\n \n}", "function reset(e){\n \n}", "function resetForm() {\n document.getElementById(\"age\").value = 0;\n document.getElementById(\"feet\").value = 0;\n document.getElementById(\"inches\").value = 0;\n document.getElementById(\"stones\").value = 0;\n document.getElementById(\"pounds\").value = 0;\n document.getElementById(\"cm\").value = 0;\n document.getElementById(\"kilos\").value = 0;\n createEventListeners();\n showImperial();\n}", "function resetClick(event) {\n resetGame();\n const winnerName = document.getElementById(\"winner-name\");\n winnerName.innerText = \"\";\n const winnerDisplay = document.getElementById(\"winner-display\");\n clearBoard();\n winnerDisplay.style.display = \"None\";\n}", "function reset()\n\t{\n\t\tsetValue('')\n\t}", "function resetButtonClicked()\n{\n document.getElementById('batteryLight').style.backgroundColor = \"rgb(165, 164, 164)\";\n powerState = 0;\n document.getElementById('screenTextTop').textContent = \"\";\n document.getElementById('screenTextBottom').textContent = \"\";\n batteryLife = 0;\n number1 = \"\";\n number2 = \"\";\n number3 = 0;\n operatorClicked = false;\n console.log(\"calculator reset\");\n}", "function reset(){\n var ele = document.getElementsByClassName(\"cell\");\n for (var i = 0; i < ele.length; i++){\n //var attr = document.createAttribute(\"value\");\n if (ele[i].readOnly == false){\n ele[i].value = \"\"; // reset DOM\n // reset board\n var index = ele[i].getAttribute(\"name\"); \n var x = index.charAt(0);\n var y = index.charAt(1);\n board[x][y] = \"\";\n } \n }\n}", "function MUD_ResetElements(also_remove_values){\n console.log( \"===== MUD_ResetElements ========= \");\n// --- loop through input elements\n const fields = [\"idnumber\", \"cribnumber\", \"bankname\", \"bankaccount\", \"beneficiary\"];\n for (let i = 0, field, el_input, el_msg; field = fields[i]; i++) {\n el_input = document.getElementById(\"id_MUD_\" + field);\n if(el_input){\n el_input.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n if(also_remove_values){ el_input.value = null};\n }\n el_msg = document.getElementById(\"id_MUD_msg_\" + field);\n\n if(el_msg){\n el_msg.innerText = (loc.msg_userdata[field]) ? loc.msg_userdata[field] : null;\n el_msg.classList.remove(\"text-danger\")\n };\n };\n\n// --- reset text on btn cancel\n if(el_MUD_btn_cancel) {el_MUD_btn_cancel.innerText = loc.Cancel};\n\n } // MUD_ResetElements", "function Reset() {\n var resetElement = document.getElementById('reset');\n\n resetElement.addEventListener('click', function () {\n\n var xS = document.getElementById('x').style.display = 'inline';\n\n var yS = document.getElementById('y').style.display = 'inline';\n\n var modal = document.getElementById('modal').style.display = 'block';\n // get modal header\n var modalheader = document.querySelector('.modal-header h2');\n modalheader.textContent = \"Select to be X or O?\";\n\n //game(selectedPlayerChoice, gamePlayer, enemy);\n //hard reset board\n });\n}" ]
[ "0.6735011", "0.6689606", "0.6662631", "0.66318655", "0.66318655", "0.65800375", "0.6569994", "0.65472484", "0.6508659", "0.6502485", "0.64979905", "0.64452064", "0.64181393", "0.6368874", "0.635599", "0.63265955", "0.6323387", "0.6309487", "0.6270637", "0.6253161", "0.6228662", "0.622532", "0.6216272", "0.621622", "0.6213642", "0.619398", "0.6171837", "0.61599696", "0.61478806", "0.6141767" ]
0.7311259
0
Initialize Matrix Input Grid Generates the initial entries for the input matrix.
initMatrix() { const rows = this.rows(); const columns = this.columns(); for (let row = 0; row < rows; row++) { for (let col = 0; col < columns; col++) { this.matrix.appendChild(this.createMatrixEntry(row, col, this.ID)); } } this.setMatrixGridRows(rows); this.setMatrixGridCols(columns); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "createInitialGrid() {\n let gridArray = [];\n for(let row = 0; row < this.gridData.getSize(); row++){\n for(let col = 0; col < this.gridData.getSize(); col++){\n let cell = new Cell(row, col);\n gridArray.push(cell);\n }\n }\n\n this._setInitialValues(gridArray);\n }", "function initGrid() {\n row = [];\n for (var j = 0; j < GRID_H; j++) {\n\trow.push('');\n }\n grid = [];\n for (var i = 0; i < GRID_W; i++) {\n\tgrid.push(Array.from(row));\n }\n}", "_initializeMatrix() {\n const row = Array(this.width).fill(0);\n this.matrix = Array(this.height).fill(row.slice(0));\n }", "_init_grid() {\n\t\t\tfor (var i = 0; i < this._internal_grid_size[0]; i++) {\n\t\t\t\tthis._internal_grid.push([]);\n\t\t\t\tfor (var e = 0; e < this._internal_grid_size[1]; e++) {\n\t\t\t\t\tthis._internal_grid[i].push(0);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "initMatrix() {\n this._matrix = {};\n\n for (let i = 0; i < this._y; i++) {\n this._matrix[i] = {};\n for (let j = 0; j < this._x; j++) {\n this._matrix[i][j] = j;\n }\n }\n }", "initializeMatrix() {\n\t\tthis.matrix = new Array(this.height);\n\t\tfor (let i = 0; i < this.height; i++) {\n\t\t\tthis.matrix[i] = new Array(this.width);\n\t\t\tfor (let j = 0; j < this.width; j++)\n\t\t\t\tthis.matrix[i][j] = ' ';\n\t\t}\n\t}", "function initGrid() {\n grid = [];\n for (var i = 0; i < maxWidth/dotSize; i++) {\n grid[i] = [];\n for (var j = 0; j < maxHeight/dotSize; j++) {\n grid[i][j] = [0,0];\n }\n }\n}", "initializeCells() {\n for (var i = 0; i < this._gridSize; i++) {\n this._cells[i] = []; // create an n x n matrix\n for (var j = 0; j < this._gridSize; j++) {\n this._cells[i].push(new Tile(i, j, 0));\n }\n }\n }", "function initialGrid() {\n return Array.from({length:6}, (_, i) => Array.from({length:6}, (_, j) => 0));\n}", "initGrid() {\n this.grid = [];\n this.gameOver = false;\n for(let row = 0; row < this.rowSize; row++) {\n let currentRow = [];\n for(let cell = 0; cell < this.colSize; cell++) {\n currentRow.push(this.getEmptyCell());\n }\n this.grid.push(currentRow);\n }\n }", "constructor() {\n\t\tthis.grid = [];\n\t\tthis.rows = 0;\n\t\tthis.cols = 0;\n\t}", "createGrid() {\n\t\t// loop to create the 8 rows\n\t\tfor (let row = 0; row < 8; row++) {\n\t\t\tthis.grid[row] = [];\n\t\t\t// push in 8 columns of nulls\n\t\t\tfor (let column = 0; column < 8; column++) {\n\t\t\t\tthis.grid[row].push(null);\n\t\t\t}\n\t\t}\n\t}", "function initGrid()\n {\n for (var i = 0; i < GRIDSIZE ; i++)\n {\n GRID[i] = new Array(GRIDSIZE);\t\t// each element is an array\n mazeObjects[i] = new Array(GRIDSIZE); //also make the array that tracks maze objects 2d\n agentMap['lineOfSight'][i] = new Array(GRIDSIZE); //also make the agent's lineOfSight array 2d\n enemyMap['lineOfSight'][i] = new Array(GRIDSIZE); //also make the enemy's lineOfSight array 2d\n\n for (var j = 0; j < GRIDSIZE ; j++)\n {\n GRID[i][j] = GRID_BLANK ;\n }\n }\n }", "function initializeGrid(gridWidth, gridHeight) {\n\n Tile.count = 0;\n\n for (let i = 0; i < gridHeight; i++) {\n grid[i] = [];\n for (let j = 0; j < gridWidth; j++) {\n grid[i][j] = new Tile(false, false, 0);\n }\n }\n\n}", "function init() {\n for (let i = 0; i < columns; i++) {\n for (let j = 0; j < rows; j++) {\n currentBoard[i][j] = 0;\n nextBoard[i][j] = 0;\n }\n }\n \n\n}", "initRow() {\n let prevSetNr = 1; // previous set number holder\n for (let i = 1; i <= this.width; i++) {\n // Initialize cells that are not yet initialized by previous row\n if (!this.cell[i]) {\n for (let j = prevSetNr; j <= this.width; j++) {\n if (!this.set[j]) {\n prevSetNr = j;\n break;\n }\n }\n this.set[prevSetNr] = [i];\n this.cell[i] = prevSetNr;\n }\n }\n }", "function initialiseGrid(size) {\n grid = [];\n for (var i=0; i < size; i++){\n //initialising the row//\n grid[i] = [];\n //initialising the columns, one for each row//\n for (var j=0; j < size; j++){\n //filling the grid with zeros to check if tile is already placed or not//\n grid[i][j] = 0;\n }\n }\n}", "function initTerrainMatrix() {\n const outer = BLOCK_HEIGHT;\n const inner = BLOCK_WIDTH;\n terrainMatrix = new Array(outer);\n for (let i = 0; i < outer; i++) {\n terrainMatrix[i] = new Array(inner);\n }\n}", "function init() {\r\n\t\t\t\r\n\t\t\tvar grid = document.getElementById(\"grid\");\r\n\t\t\tfor(var i=1; i<=4; i++){\r\n\t\t\t\tvar riga = document.createElement(\"div\");\r\n\t\t\t\triga.setAttribute(\"Id\", \"riga\"+i);\r\n\t\t\t\tfor(var j=0; j<4; j++){\r\n\t\t\t\t\tvar casella = document.createElement(\"input\");\r\n\t\t\t\t\tvar n = i*4+j;\r\n\t\t\t\t\tcasella.setAttribute(\"Id\", \"casella\"+n );\r\n\t\t\t\t\tcasella.setAttribute(\"readonly\", \"readonly\");\r\n\t\t\t\t\tcasella.setAttribute(\"value\", 0);\r\n\t\t\t\t\triga.appendChild(casella);\r\n\t\t\t\t}\r\n\t\t\t\tgrid.appendChild(riga);\r\n\t\t\t\t}\t\t\t\r\n\t\t}", "initGrid(cellSize) {\n this.gridCells = {\n x: [],\n y: []\n }\n for (let i = 0; i < this.width - cellSize; i += cellSize) {\n this.gridCells.x.push(i)\n }\n for (let i = 0; i < this.height - cellSize; i += cellSize) {\n this.gridCells.y.push(i)\n }\n }", "setupInitialValues() {\n this.__xSpacingInput.value = \"1.0\";\n this.__ySpacingInput.value = \"1.0\";\n\n this.__xDimInput.value = 5;\n this.__yDimInput.value = 1;\n }", "init() {\n for (let i = 0; i < GRID_SIZE; ++i) {\n for (let j = 0; j < GRID_SIZE; ++j) {\n this.grid[i][j] = EMPTY\n }\n }\n this.grid[THREE][THREE] = PLAYER1; this.grid[THREE][FOUR] = PLAYER2\n this.grid[FOUR][THREE] = PLAYER2; this.grid[FOUR][FOUR] = PLAYER1\n }", "function initial() {\n //add sets for empty cell\n for (let i = 0; i < 9; i++) {\n solved[i] = [];\n for (let j = 0; j < 9; j++) {\n solved[i][j] = matrix[i][j];\n if (solved[i][j] == 0)\n solved[i][j] = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);\n }\n }\n }", "function populateGameGrid(grid) {\r\n\r\n for (var i = 0; i < NUM_ROWS; i += 1) {\r\n for (var j = 0; j < NUM_COLS; j += 1) {\r\n //fills all grid with initial cells\r\n grid[i][j] = new Cell();\r\n //x position match x coordinates\r\n grid[i][j].xPosition = j * CELL_SIZE;\r\n //y position match y coordinates\r\n grid[i][j].yPosition = i * CELL_SIZE;\r\n }\r\n\r\n } \r\n\r\n }", "function initArray(matrix, rows, cols) {\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n\n /* Conditions used to seperate out the Borders */\n if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1) {\n matrix[i][j] = 5;\n } else {\n matrix[i][j] = 0;\n }\n }\n }\n }", "function init() {\n var i, j, rooms, room;\n\n I = readline().split(' ');\n W = parseInt(I[0]); // number of columns.\n H = parseInt(I[1]); // number of rows.\n\n for (i = 0; i < H; i++) {\n MAP[i] = [];\n rooms = readline().split(' ');\n for(j = 0; j < W; j++) {\n room = translateRoom(parseInt(rooms[j]));\n MAP[i][j] = room;\n }\n }\n }", "function initializeMaze(rows, columns) {\n let s = [];\n for (let z = 0; z < rows; z++) {\n let t = [];\n for (let x = 0; x < columns; x++) {\n t.push(0);\n }\n s.push(t);\n }\n return s;\n}", "createGrid() {\n // loop to create the 8 rows\n for (let row = 0; row < 8; row++) {\n this.grid[row] = [];\n // push in 8 columns of nulls\n for (let column = 0; column < 8; column++) {\n this.grid[row].push(null);\n }\n }\n }", "createGrid() {\n // loop to create the 8 rows\n for (let row = 0; row < 8; row++) {\n this.grid[row] = [];\n // push in 8 columns of nulls\n for (let column = 0; column < 8; column++) {\n this.grid[row].push(null);\n }\n }\n }", "createGrid() {\n // loop to create the 8 rows\n for (let row = 0; row < 8; row++) {\n this.grid[row] = [];\n // push in 8 columns of nulls\n for (let column = 0; column < 8; column++) {\n this.grid[row].push(null);\n }\n }\n }" ]
[ "0.72385544", "0.71468896", "0.70017624", "0.6849892", "0.66762555", "0.667294", "0.6483828", "0.6481032", "0.64789253", "0.64389604", "0.6355339", "0.62756467", "0.6231351", "0.62100494", "0.62091005", "0.61918527", "0.6187529", "0.6180396", "0.6161365", "0.6132321", "0.6129611", "0.6045691", "0.6041614", "0.60252774", "0.60160094", "0.5994544", "0.59681004", "0.5967218", "0.5967218", "0.5967218" ]
0.7775112
0
Constructs a new RoomPool and sets listeners and emitters from the given socket.io instance.
constructor(socketIoInstance) { this.rooms = {}; SafeSocket.socketsOn(socketIoInstance, 'connection', (socket) => { Logger.logInfo('socket ' + socket.id + ' connected'); socket.emit('clientConnectedToServer', { socketId: socket.id }); // Default socket.io actions socket.on('disconnect', () => { this.onDisconnect(socket); }); socket.on('disconnecting', () => { this.playerAttemptLeaveRoom(socket, {}); }); // Custom actions socket.on('hostAttemptEndGame', (data) => { this.hostAttemptEndGame(socket, data) }); socket.on('hostAttemptStartGame', (data) => { this.hostAttemptStartGame(socket, data) }); socket.on('playerAttemptCreateRoom', (data) => { this.playerAttemptCreateRoom(socket, data) }); socket.on('playerAttemptJoinRoom', (data) => { this.playerAttemptJoinRoom(socket, data) }); socket.on('playerAttemptLeaveRoom', (data) => { this.playerAttemptLeaveRoom(socket, data) }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function RoomSocket(io, roomId){\n this.roomId = roomId;\n this.io = io;\n}", "constructor(socket, logger, socketManager) {\n this.socket = socket;\n this.logger = logger;\n this.socketManager = socketManager;\n\n /**\n * Create a map of event handlers to be used during the\n * handler binding process to a socket. We call the bind\n * method on each handler method in this class to tell\n * the interpreter what the \"this\" keyword refers to.\n */\n this.handlers = {\n joinRoom: this.joinRoom.bind(this),\n leaveRoom: this.leaveRoom.bind(this),\n nickname: this.nickname.bind(this)\n };\n }", "constructor () {\n super();\n this.joinedRooms = this.rooms = [];\n this.socketClient = new SocketClient(this);\n this._emitFn = componentEmitter.prototype.emit;\n this.generalCallbacks = {};\n this.broadcast = {\n /**\n * Broadcast to room\n * @param {string} roomKey the roomkey which need to be attached to\n * @return {object}\n **/\n to: roomKey => {\n return {\n /**\n * Emitting\n * @param {string} eventKey\n * @param {object} payload\n **/\n emit: (eventKey, payload) => {\n if (this.generalCallbacks[eventKey]) {\n this.generalCallbacks[eventKey](createPayload(payload), roomKey);\n }\n }\n }\n }\n };\n }", "setupSocket() {\n this.socket = io('/gameroom');\n this.socket.on('connect', () => {\n this.socket.emit('setup_client')\n });\n this.socket.on('packet', this.handleSocketMessages)\n }", "function setupSocket(){\n socket = io();\n socket.on('disconnect', function(){\n changeState(gameConfig.GAME_STATE_END);\n });\n socket.on('setSyncUser', function(user){\n gameConfig.userID = user.objectID;\n });\n //change state game on\n socket.on('resStartGame', function(userDatas, foodsDatas, virusesDatas){\n Manager.setUsers(userDatas);\n Manager.setFoods(foodsDatas);\n Manager.setViruses(virusesDatas);\n console.log(Manager.users);\n\n canvasAddEvent();\n documentAddEvent();\n\n changeState(gameConfig.GAME_STATE_GAME_ON);\n });\n socket.on('userJoined', function(data){\n Manager.setUser(data);\n });\n socket.on('createViruses', function(virusesData){\n Manager.createViruses(virusesData);\n });\n socket.on('deleteVirus', function(virusID){\n Manager.deleteVirus(virusID);\n });\n socket.on('createFoods', function(foodsDatas){\n Manager.createFoods(foodsDatas);\n });\n socket.on('deleteFood', function(foodID){\n Manager.deleteFood(foodID);\n });\n socket.on('updateUser', function(userDatas){\n Manager.updateUsers(userDatas);\n });\n socket.on('userDestroy', function(userID){\n if(userID === gameConfig.userID){\n changeState(gameConfig.GAME_STATE_END);\n }\n Manager.deleteUser(userID);\n })\n socket.on('userLeave', function(objID){\n Manager.kickUser(objID);\n });\n socket.on('rename', function(){\n changeState(gameConfig.GAME_STATE_START_SCENE);\n });\n}", "function initSockets(){\n //connect to the io opened tunnel in the server\n var socket = io();\n socket.on(\"Order Status\", function(obj){\n createReadyOrders(obj.nowServing);\n createToBeCooked(obj.kitchen);\n });\n\n}", "function socket_init(map_){\n socket = new io.Socket(null, {port: 3000, rememberTransport: false});\n socket.connect();\n map = map_;\n\n var socket_events = {\n 'connect' : connectHandler\n ,'disconnect' : disconnectHandler\n ,'reconnect' : reconnectHandler\n ,'reconnecting' : reconnectingHandler\n ,'reconnect_failed' : reconnect_failedHandler\n ,'message' : messageHandler\n }\n\n _.forEach(socket_events, function(func, event) {\n if(!func) console.log(\"Cannot find \" + event + 'function. Please create it!' );\n else socket.on(event,func);\n });\n}", "constructor() {\n this.io = require('socket.io')();\n }", "_setDefaultListeners () {\n this.io.on('connection', (objSocket) => {\n console.log('Socket client connected', this.io.engine.clientsCount);\n objSocket.on('join_room', (strRoom) => {\n console.log('Joining room', strRoom);\n objSocket.join(strRoom);\n });\n })\n }", "function initSocketIO() {\n io.on('connection', function (socket) {\n\n console.log(\"Client connected\");\n\n currentConnections[socket.id] = {socket: socket};\n\n socket.on('join', function(data) {\n console.log(data);\n console.log(socket.id);\n join(socket, data);\n });\n socket.on('send_emoji', function (data) {\n console.log(data);\n sendEmoji(socket, data);\n });\n socket.on('play_card', function (data) {\n console.log(data);\n playCard(socket, data);\n });\n socket.on('minion_attack', function (data) {\n minionAttackCommand(socket, data);\n });\n socket.on('disconnect', function() {\n var room_id = currentConnections[socket.id]['room_id'];\n if(room_id != undefined && room_id != null && connectionRooms[room_id]) {\n connectionRooms[room_id].forEach(function (player) {\n if(player.socket.id != socket.id) {\n players.push({socket:player.socket, id:player.id});\n }\n player.socket.leave(room_id);\n });\n delete connectionRooms[room_id];\n }\n delete currentConnections[socket.id];\n });\n });\n}", "function GameSocketServer(io, debug) {\n io.on('connection', socket => {\n\n if (debug) console.log(`Client joined! id: ${socket.id}`)\n\n // Triggered on room creation or joining\n socket.on('room', (username, userType, roomCode) => {\n\n // Set socket info\n socket.username = username\n socket.userType = userType\n\n const rooms = io.sockets.adapter.rooms\n\n if (socket.userType === 'player') {\n if (debug) console.log(`Player ${socket.username} wants to join a room.`)\n\n if (rooms[roomCode]) {\n // If the room exists\n if (debug) console.log(`Player ${socket.username} joined a room. code: ${roomCode}`)\n joinOrCreateRoom(roomCode)\n } else {\n // If the room does not exist\n if (debug) console.log(`Player ${socket.username} requested a non-existent room.`)\n socket.emit('no_room', 'Room does not exist.')\n }\n } else if (socket.userType === 'gm') {\n if (debug) console.log(`GM ${socket.username} requested a room.`)\n if (!rooms[roomCode]) {\n // If the room does not exist already, generate a new code\n // This prevents GMs from setting their own room code\n roomCode = genRoomCode()\n if (debug) console.log(`GM ${socket.username} created a room. code: ${roomCode}`)\n } else {\n // If the room exists already, don't set a new code, so they just join the room\n if (debug) console.log(`GM ${socket.username} joined a room. code: ${roomCode}`)\n }\n joinOrCreateRoom(roomCode)\n } else {\n // If anything other than the right user types were set\n socket.userType = 'player'\n socket.emit('error', 'Invalid user type.')\n }\n })\n\n // Short hand callback for broadcasting new stores\n socket.on('broadcast_stores', broadcastStores)\n\n // Short hand callback for broadcasting clear stores message\n socket.on('clear_stores', clearStores)\n\n // Sometimes the socket is undefined on improper disconnection\n socket.on('disconnect', reason => {\n if (socket) {\n updateGMRoomMembers()\n }\n const name = socket.username || \"Someone\"\n if (debug) console.log(`${name} disconnected: ${reason}`)\n })\n\n // Sends room members in a callback\n function getRoomMembers(cb) {\n // Get all room members\n io.of('/').in(socket.roomCode).clients((error, clients) => {\n if (error) throw error\n // Create empty room\n const roomPkg = [],\n connected = io.sockets.connected\n for (let id of clients) {\n // Get each socket by id\n const client = connected[id]\n // Push the socket info into the room\n roomPkg.push({\n id: id,\n username: client.username,\n userType: client.userType\n })\n }\n cb(roomPkg)\n })\n }\n\n // Sends a GM the current room member information\n function updateGMRoomMembers() {\n getRoomMembers(members => {\n for (let member of members) {\n // Find the GM\n if (member.userType === 'gm') {\n // Send them the members\n io.to(member.id).emit('room_members', members)\n return\n }\n }\n })\n }\n\n // Sends store information to all selected recipients\n function broadcastStores(stores, recipients) {\n if (debug) {\n console.log(\"Sending stores:\")\n console.log(stores)\n console.log(\"To:\")\n console.log(recipients)\n }\n for (var i = 0; i < recipients.length; i++) {\n io.to(recipients[i]).emit('new_stores', stores)\n }\n }\n\n // Sends a clear stores message to selected recipients\n // If none are provided, it sends the message to whole room\n function clearStores(recipients) {\n if (!recipients.length) {\n getRoomMembers(members => {\n sendClearStoresMessage(members)\n })\n } else {\n sendClearStoresMessage(recipients)\n }\n }\n\n // Helper function\n function sendClearStoresMessage(recipients) {\n for (var i = 0; i < recipients.length; i++) {\n io.to(recipients[i].id).emit('clear_stores')\n }\n }\n\n // Adds the socket to a room if it exists, or creates and then adds if it doesn't\n function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }\n\n // Generates a 5 character room code\n function genRoomCode() {\n const roomSeed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n rooms = io.sockets.adapter.rooms;\n let code\n do {\n code = ''\n for (var i = 0; i < 5; i++) {\n code += roomSeed[getRandomInt(roomSeed.length)]\n }\n // Keep generating new codes if the code is already in use\n } while (rooms[code])\n return code\n }\n\n // Helper function\n function getRandomInt(upperBound) {\n return Math.floor(Math.random() * upperBound)\n }\n\n })\n}", "initSocket(callback, idhandler, userhandler) {\n this.io.on('assignment', idhandler);\n this.io.on('questionAsked', callback);\n this.io.on('newUser', userhandler);\n }", "function setupRoom(roomID) {\n\t\t\tvar room = io.connect('https://heathio-server-tagger94.c9users.io:8080/' + roomID);\n\t //room = io('/' + roomID);\n\t console.log(\"set room to \" + roomID);\n\t room.on('connect', function(socket) {\n\t console.log(\"Connected room to server\");\n\t\t\t\t\n\t });\n\t room.on('disconnect', function(msg) {\n\t console.log(\"disconnect from server\");\n\t });\n\t //Setup Alert message\n\t room.on('alert', recieveAlert);\n\t }", "init() {\n this.io.on('connection', function (socket) {\n /**\n * Triggered when a socket disconnects\n */\n socket.on('disconnect', function () {\n console.log(`[SOCKET] Client disconnected! ID: ${socket.id}`);\n });\n\n console.log(`[SOCKET] New client connected! ID: ${socket.id}`);\n });\n\n /**\n * Start listening on the right port/host for the Socket.IO server\n */\n console.log('[SYSTEM] Socket.IO started !');\n }", "function socketInit() {\r\n\tsocket = io();\r\n\r\n\tsocket.on('message', parsedMessage => {\r\n\t\tconsole.info('Received message: ' + parsedMessage.id);\r\n\r\n\t\tswitch (parsedMessage.id) {\r\n\t\t\t//event for self user, when he leaves the room\r\n\t\t\tcase 'disconn':\r\n\t\t\t\tparticipants[userId].disposeSelf();\r\n\t\t\t\tsocket.close();\r\n\t\t\t\tbreak;\r\n\t\t\t// event for new user to connect to KMS and register other users in room\r\n\t\t\tcase 'existingParticipants':\r\n\t\t\t\tonExistingParticipants(parsedMessage);\r\n\t\t\t\tbreak;\r\n\t\t\t// event for other users to register new participant\r\n\t\t\tcase 'newParticipantArrived':\r\n\t\t\t\tonNewParticipant(parsedMessage);\r\n\t\t\t\tbreak;\r\n\t\t\t// event for other users to register the leaving of user\r\n\t\t\tcase 'participantLeft':\r\n\t\t\t\tonParticipantLeft(parsedMessage);\r\n\t\t\t\tbreak;\r\n\t\t\t// event to register answers : user-KMS and user-user\r\n\t\t\tcase 'receiveVideoAnswer':\r\n\t\t\t\treceiveVideoResponse(parsedMessage);\r\n\t\t\t\tbreak;\r\n\t\t\t// event for exchanging ICE candidates between WebRTC peers\r\n\t\t\tcase 'iceCandidate':\r\n\t\t\t\tparticipants[parsedMessage.userId].rtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {\r\n\t\t\t\t\tif (error) {\r\n\t\t\t\t\t\tconsole.error(\"Error adding candidate: \" + error);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tbreak;\r\n\t\t\tcase'chat message':\r\n\t\t\t\treceiveChatMessage(parsedMessage);\r\n\t\t\t\tbreak;\r\n\r\n\t\t\t// event for new user to receive a response of moderator\r\n\t\t\tcase 'moderatorResponse':\r\n\t\t\t\tmoderatorResponse(parsedMessage.accepted, socket);\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'videoDisabled':\r\n\t\t\t\tputNameOverVideo(document.getElementById(parsedMessage.userId));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'videoEnabled':\r\n\t\t\t\tputVideoOverName(document.getElementById(parsedMessage.userId));\r\n\t\t\t\tbreak;\r\n\r\n\t\t}\r\n\t});\r\n\t// event fired when moderator enters the room or if the moderator is not available\r\n\tsocket.on('onEnterNotification', error => {\r\n\t\tif (error === null) {\r\n\t\t\tenter('moderator');\r\n\t\t} else {\r\n\t\t\talert(error);\r\n\t\t}\r\n\t});\r\n\t// event for requesting permission from the moderator to log in a new user\r\n\tsocket.on('requestForModerator', (socketId, fullName) => {\r\n\t\tlet data = {\r\n\t\t\tid: 'moderatorResponse',\r\n\t\t\tuserId: socketId,\r\n\t\t\taccepted: false\r\n\t\t}\r\n\r\n\t\taddModal(fullName, (modalId) => {\r\n\t\t\tdata.accepted = true;\r\n\t\t\tdocument.getElementById(modalId).remove();\r\n\t\t\tsendMessage(data);\r\n\t\t}, (modalId) => {\r\n\t\t\tdocument.getElementById(modalId).remove();\r\n\t\t\tsendMessage(data);\r\n\t\t});\r\n\r\n\t});\r\n\tsocket.on('waitModeratorResponse', () => {\r\n\t\talert('Please wait until moderator accepts your entry');\r\n\t});\r\n}", "function bind(io) {\n return io.on('connection', (socket) => {\n let user = socket.request.user.user;\n socket.user = user;\n\n registerUser(socket.user, socket.request.user);\n\n getQueues().then((queues) => {\n queues.forEach((queue, index) => {\n getQueue(queue).then((data) => {\n io.emit('update', {'waiting': data, 'queue': queue});\n });\n });\n });\n\n socket.on('join', joinQueue(io, socket));\n socket.on('leave', leaveQueue(io, socket));\n });\n}", "constructor() {\n super()\n console.info('construct')\n // Maximum number of clients allowed to connect into the room.\n // When room reaches this limit, it is locked automatically.\n // Unless the room was explicitly locked by you via lock() method,\n // the room will be unlocked as soon as a client disconnects from it.\n this.maxClients = 2\n // Frequency to send the room state to connected clients (in milliseconds)\n this.setPatchRate(patchRate)\n }", "initNewPlayer(socket) {\n this.sockets.set(socket.id, socket);\n socket.emit(\"init\")\n }", "constructor(roomCode) {\n this.roomCode = roomCode; // Room code (e.g. 'abcd' or 'foo1')\n this.playerMap = new PlayerMap(); // PlayerMap of the room\n this.hostSocket = undefined; // Reference to host socket\n this.gameServer = // Game server that will handle game interactions\n new GameServer(this.playerMap);\n }", "function newRoom() {\n socket.emit(\"newRoom\");\n}", "function createNewRoom() {\r\n // Generate room id.\r\n const newID = uuidv4().substring(0, 8);\r\n\r\n // Join room\r\n socket.join(newID);\r\n\r\n // Update corressponding object in usersArray\r\n updateUserRoom(socket, newID);\r\n\r\n // Send room data to socket\r\n io.to(socket.id).emit(\"roomData\", {\r\n roomId: newID,\r\n });\r\n }", "function bind() {\r\n\r\n socket = new io.Socket(postmile.api.domain, { port: postmile.api.port, rememberTransport: false });\r\n\r\n socket.on('connect', function () {\r\n Y.log('Connected!');\r\n });\r\n\r\n socket.on('message', function (message) {\r\n handleStreamMessage(message);\r\n });\r\n\r\n socket.connect();\r\n\r\n Y.on(\"postmile:subscribeProject\", function (project) {\r\n subscribe(project);\r\n });\r\n\r\n }", "socketsJoin(room) {\r\n this.adapter.addSockets({\r\n rooms: this.rooms,\r\n except: this.exceptRooms,\r\n }, Array.isArray(room) ? room : [room]);\r\n }", "setupChatNs() {\r\n\t\tthis.ns.chat.on(\"connection\", baseSocket => {\r\n\t\t\tconst socket = new Proxy(baseSocket, new ExtendedSocket()); //extend socket\r\n\r\n\t\t\tsocket.log(chalk.cyan(\"connected\"));\r\n\t\t\tthis.sockets.add(socket);\r\n\r\n\t\t\t//socket wants to join a room\r\n\t\t\tsocket.on(ACTION_TYPE.JOIN_ROOM, ({\r\n\t\t\t\troom,\r\n\t\t\t\tnick\r\n\t\t\t}) => {\r\n\t\t\t\tsocket.changeRoomTo(room);\r\n\r\n\t\t\t\tif (nick) {\r\n\t\t\t\t\tsocket.nick = nick;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//give the socket a random name if it doesnt have any yet\r\n\t\t\t\tif (!socket.nick) {\r\n\t\t\t\t\tsocket.nick = randomNick();\r\n\t\t\t\t\tsocket.emit(ACTION_TYPE.OWN_NICK_CHANGE, {\r\n\t\t\t\t\t\tuser: {\r\n\t\t\t\t\t\t\tnew: socket.nick\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//send the initial state of the room\r\n\t\t\t\tthis.getRoomState(room).then(state => {\r\n\t\t\t\t\tsocket.emit(ACTION_TYPE.ROOM_STATE, {\r\n\t\t\t\t\t\tstate\r\n\t\t\t\t\t});\r\n\t\t\t\t}).catch(err => console.error(err));\r\n\r\n\t\t\t\t//tell others\r\n\t\t\t\tsocket.broadcastToRoom(ACTION_TYPE.ENTERED_ROOM, {\r\n\t\t\t\t\tuser: socket.user\r\n\t\t\t\t});\r\n\r\n\t\t\t\tsocket.log(chalk.green(\"joined\"), room);\r\n\t\t\t});\r\n\r\n\t\t\t//socket wants to leave a room\r\n\t\t\tsocket.on(ACTION_TYPE.LEAVE_ROOM, ({room}) => {\r\n\t\t\t\tsocket.broadcastToRoom(ACTION_TYPE.LEFT_ROOM, {\r\n\t\t\t\t\tuser: socket.user\r\n\t\t\t\t});\r\n\t\t\t\tsocket.leaveAllRooms();\r\n\t\t\t});\r\n\r\n\t\t\t//socket sent a chat message\r\n\t\t\tsocket.on(ACTION_TYPE.ADD_CHAT_MESSAGE, message => {\r\n\t\t\t\tdb.addChatMessage(socket.currentRoom, message).catch(console.error.bind());\r\n\t\t\t\tsocket.broadcastToRoom(ACTION_TYPE.ADD_CHAT_MESSAGE, {\r\n\t\t\t\t\tmessage\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t\t\tsocket.on(ACTION_TYPE.OWN_NICK_CHANGE, nick => {\r\n\t\t\t\tsocket.broadcastToRoom(ACTION_TYPE.NICK_CHANGE, {\r\n\t\t\t\t\tuser: {\r\n\t\t\t\t\t\told: socket.nick,\r\n\t\t\t\t\t\tnew: nick\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tsocket.nick = nick;\r\n\t\t\t});\r\n\r\n\t\t\tsocket.on(\"disconnect\", () => {\r\n\t\t\t\tsocket.broadcastToRoom(ACTION_TYPE.LEFT_ROOM, {\r\n\t\t\t\t\tuser: socket.user\r\n\t\t\t\t});\r\n\t\t\t\tthis.sockets.delete(socket);\r\n\t\t\t\tsocket.log(STRINGS.DISCONNECTED);\r\n\t\t\t});\r\n\r\n\t\t\tsocket.on(\"error\", err => {\r\n\t\t\t\tsocket.log(STRINGS.ERROR, err);\r\n\t\t\t});\r\n\t\t});\r\n\t}", "function init(options) {\n options = options || {}\n var port = options.port || 6466\n global.client = global.client || socketIOClient(`http://localhost:${port}`)\n client = global.client\n log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)\n client.emit('join', ioid) // first join for serialization\n client.on('disconnect', client.disconnect)\n client.on('take', hasher.handle) // add listener\n \n // add methods\n client.pass = pass\n client.clientPass = clientPass\n return client\n}", "function Factory(io, uri, opts) {\n opts = opts || {};\n if (!io.protocol || !io.connect ) {\n throw Error('Please include socket.io client.');\n }\n return new Manager(io, uri, opts);\n}", "constructor () {\r\n // run super\r\n super ();\r\n\r\n // bind methods\r\n this.room = this.room.bind (this);\r\n this.user = this.user.bind (this);\r\n this.emit = this.emit.bind (this);\r\n this.session = this.session.bind (this);\r\n\r\n // setup redis conn\r\n let conn = config.get ('redis');\r\n\r\n // add key\r\n conn.key = config.get ('domain') + '.socket';\r\n }", "function Server( config ){\n\t\tvar io = this.io = config.socketServer;\n\t\tvar s = this;\n\t\t\n\t\tio.set( \"log level\", 1 );\n\t\tio.sockets.on( \"connection\", function( socket ) { s.onConnection( socket ); } );\n\t\t\n\t\tthis.eventHandlers = {};\n\t\tthis.activeNicknames = {};\n\t\tthis.activeAddresses = {};\n\t\t\n\t\tthis.maxSlots = config.slots;\n\t\tthis.usedSlots = 0;\n\t\t\n\t\tthis.oneUserPerIp = config.oneUserPerIp;\n\t\tthis.world = config.world;\n\t\tthis.log = config.log || function(){};\n\t\t\n\t\tconfig.spawnProtection = config.spawnProtection || {};\n\t\tthis.spawnProtection = config.spawnProtection.enabled;\n\t\tthis.spawnProtectionRadius = config.spawnProtection.radius || 10;\n\t}", "function SocketService($http, config, $q, localStorageService) {\n\n var service = {\n socket: null,\n\n connect: connect,\n getMsgs: getMsgs,\n getRoomInfo: getRoomInfo,\n joinRoom: joinRoom,\n submitMsg: submitMsg,\n propagateProfPage: propagateProfPage,\n getProfPageChange: getProfPageChange,\n getAnnotationMsg: getAnnotationMsg,\n propagateAnnotationAdded: propagateAnnotationAdded\n };\n\n return service;\n\n ///////////////\n\n /**\n * Connects to die sails.io.js WebSocket.\n */\n function connect() {\n var q = $q.defer();\n\n try {\n service.socket = io.connect(config.socketUrl);\n q.resolve();\n }\n catch(err) {\n q.reject();\n }\n\n return q.promise;\n }\n\n function getMsgs(cb) {\n service.socket.on('room:message', function(msgObj) {\n msgObj.type = 'msg';\n cb(msgObj);\n });\n }\n\n function getProfPageChange(cb) {\n service.socket.on('pdf:profpage', function(page) {\n cb(page);\n });\n }\n\n /**\n * Request all users from the specified room.\n * @param {int} roomId [Database room id]\n * @param {function} cb [Callback: user-array]\n */\n function getRoomInfo(roomId, cb) {\n // make request\n service.socket.emit('room:info', roomId);\n\n // wait for answers\n service.socket.on('room:info', function(userArray) {\n return cb(userArray);\n });\n }\n\n function getAnnotationMsg(cb) {\n service.socket.on('room:annotation', function(annotations) {\n cb(annotations);\n });\n };\n\n /**\n * Joins the room identified by its database id.\n * @param {int} roomId [Database room id]\n */\n function joinRoom(roomId) {\n service.socket.emit('room:join', roomId);\n }\n\n /**\n * Submits a msg to the the socket.\n * @param {string} msg [Message string]\n */\n function submitMsg(msg) {\n service.socket.emit('room:message', msg);\n }\n\n\n /**\n * Tells everyone which page the prof is on\n */\n function propagateProfPage(page) {\n service.socket.emit('pdf:profpage', page);\n }\n\n function propagateAnnotationAdded(annotation) {\n service.socket.emit('room:annotation', annotation);\n }\n\n }", "async function init() {\n console.log(chalk.bold.cyan('Starting osu!autoref'));\n await initPool();\n console.log(chalk.bold.green('Loaded map pool!'));\n console.log(chalk.cyan('Attempting to connect...'));\n \n try {\n await client.connect();\n console.log(chalk.bold.green(\"Connected to Bancho!\"));\n channel = await client.createLobby(`${match.tournament}: ${match.teams[BLUE].name} vs ${match.teams[RED].name}`);\n } catch (err) {\n console.log(err);\n console.log(chalk.bold.red(\"Failed to create lobby\"));\n process.exit(1);\n }\n\n lobby = channel.lobby;\n\n const password = Math.random().toString(36).substring(8);\n await lobby.setPassword(password);\n await lobby.setMap(1262832); //hitorigoto dayo\n\n console.log(chalk.bold.green(\"Lobby created!\"));\n console.log(chalk.bold.cyan(`Name: ${lobby.name}, password: ${password}`));\n console.log(chalk.bold.cyan(`Multiplayer link: https://osu.ppy.sh/mp/${lobby.id}`));\n console.log(chalk.cyan(`Open in your irc client with \"/join #mp_${lobby.id}\"`));\n\n lobby.setSettings(bancho.BanchoLobbyTeamModes.TeamVs, bancho.BanchoLobbyWinConditions.ScoreV2);\n\n createListeners();\n}" ]
[ "0.69521755", "0.6355749", "0.6265657", "0.6171448", "0.59839207", "0.5929215", "0.5885986", "0.5880528", "0.57616717", "0.5724911", "0.5722843", "0.5722817", "0.56957006", "0.56906736", "0.5675947", "0.5657708", "0.565391", "0.5651382", "0.5636755", "0.56223243", "0.5620404", "0.56127805", "0.56075644", "0.5592196", "0.55701286", "0.5561378", "0.55517507", "0.5510411", "0.549578", "0.54924315" ]
0.6916228
1
PRIVATE METHODS Attempts to add a player identified by the given username and socket to the room identified by the given room code. Returns true if successful, false if unsuccessful.
_addPlayerToRoom(socket, username, roomCode) { if (!this.roomExists(roomCode)) { return false; } return this.rooms[roomCode].addPlayer(socket, username); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addPlayer(socket, username) {\n if (this.playerMap.getPlayerCount() >= MAX_PLAYERS) {\n return false;\n }\n\n if (!this.playerMap.containsUsername(username) && !this.gameServer.isInGame()) {\n this.playerMap.putPlayer(new Player(socket, username));\n\n if (this.hostSocket === undefined) {\n this.setHostSocketAndNotify(socket);\n }\n this.gameServer.activateListenersForSocket(socket);\n return true;\n } else if (this.playerMap.containsUsername(username) && this.gameServer.isInGame() &&\n !this.playerMap.isUsernameActive(username)) {\n this.playerMap.updatePlayerSocket(username, socket);\n this.gameServer.activateListenersForSocket(socket);\n return true;\n }\n\n return false;\n }", "addPlayerToRoomByID(player, roomID) {\n // Conditional that checks whether a room exists\n if (Room.roomExists(roomID)) {\n // Find the room by its ID and add the player to it\n Room.findByID(roomID).addPlayer(player);\n player.setRoom(Room.findByID(roomID));\n return true;\n }\n // Emit a message saying that joining the room has failed\n player.emitter.emit('roomJoinFailed', {});\n return false;\n }", "addUser(socket, name) {\n if (!this.playerExists(name) && this.gameState === LOBBY) {\n this.players[name] = new Player(socket.id);\n this.linkSocketToPlayer(socket, name);\n return this.clientsUpdate();\n }\n else if (this.playerExists(name) && this.gameState !== LOBBY &&\n this.playerIsEmpty(name)) {\n this.linkSocketToPlayer(socket, name);\n return this.clientsUpdate();\n }\n return false;\n }", "function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }", "function introducePlayerToRoom(player) {\n\n var sessionID = player.sessionID;\n\n io.sockets.sockets[sessionID].broadcast.to(player.params.map).emit('addPlayer', player);\n}", "addPlayer(roomId, player) {\n this.getRoom(roomId).players.push(player);\n\n return player;\n }", "function createRoom(e) {\n e.preventDefault();\n if (username()) {\n // $.ajax({\n // url: '/createRoom',\n // type: 'POST',\n // beforeSend: function (xhr) {\n // if (localStorage.getItem(appName)) {\n // xhr.setRequestHeader('Authorization', localStorage.getItem(appName));\n // }\n // },\n // data: {\n // username: userName\n // },\n // success: function (token) {\n // console.log(token);\n // localStorage.setItem(appName, token.token);\n // },\n // error: function () {},\n // });\n\n // TODO: Use this params to send token to server on new connection\n // check if socket is valid and within time limit\n socket.io.opts.query = {\n token: alreadyPlayed(),\n };\n socket.open();\n // FIXME: Delet Test emit\n socket.emit(\"newMessage\", \"lol\", function (err, message) {\n if (err) {\n return console.error(err);\n }\n console.log(message);\n });\n socket.on(\"newMessage\", function (data) {\n console.log(data);\n });\n\n // Asking to create a new room\n socket.emit(\"createRoom\", { username: userName });\n // socket replies back with created room name (which should be sent to other user who wants to play together)\n socket.on(\"roomNameIs\", function (roomName) {\n // console.log(roomName);\n document.getElementById(\"createdRoomName\").innerHTML =\n \"Room name : \" + roomName;\n $(\"#createdRoomName\").show();\n currentRoom = roomName;\n $(\".joinRoom\").hide();\n $(\".createRoom\").hide();\n $(\".generatRoomLink\").hide();\n $(\".singleplayerMode\").hide();\n showStartGameButton();\n currentlyPlaying = true;\n });\n console.log(socket);\n }\n}", "addPlayer(sock) {\n const socket = sock;\n\n // prevent adding the player twice\n if (socket.player.curRoom === this.hash) {\n return;\n }\n\n if (this.players.p1 === undefined) {\n this.players.p1 = socket;\n } else if (this.players.p2 === undefined) {\n this.players.p2 = socket;\n }\n\n socket.leave('lobby');\n socket.join(this.hash);\n socket.player.curRoom = this.hash;\n socket.player.reset();\n\n if (this.players.p1 !== undefined && this.players.p2 !== undefined) {\n this.state = 'preparing';\n this.setupTimer = 0;\n\n this.players.p1.emit('matchPreparing', new Message('matchPreparing', {\n maxTime: this.maxSetupTimer,\n p1: this.players.p1.player,\n p2: this.players.p2.player,\n }));\n\n this.players.p2.emit('matchPreparing', new Message('matchPreparing', {\n maxTime: this.maxSetupTimer,\n p1: this.players.p1.player,\n p2: this.players.p2.player,\n }));\n } else {\n socket.emit('matchWaiting', new Message('waitStart', new Date().getTime()));\n }\n }", "add_user(name, side, socket) {\r\n if (!this.is_game(name) || !this.is_side_free(name, side)) return false;\r\n\r\n this.inner[name][side] = socket;\r\n socket.chess_name = name;\r\n socket.chess_side = side;\r\n return true;\r\n }", "function addPlayer(socketId) {\n //Create new player \n numPlayers++;\n var player = {};\n player.socketId = socketId;\n player.username = generateUsername();\n \n //Assign game pience ('X' or 'O')\n if(numPlayers === 1) {\n player.gamePiece = 'X'; \n } else if(numPlayers === 2) {\n if(players[0].gamePiece === 'O') {\n player.gamePiece = 'X';\n } else {\n player.gamePiece = 'O';\n }\n }\n \n players.push(player);\n \n io.sockets.connected[socketId].emit('playerInfo', player);\n io.sockets.emit('user', numPlayers);\n \n return player; \n}", "function playerJoinGame(data) {\n //console.log('Player ' + data.playerName + 'attempting to join game: ' + data.gameId );\n\n // A reference to the player's Socket.IO socket object\n var sock = this;\n\n // Look up the room ID in the Socket.IO manager object.\n var room = io.sockets.adapter.rooms[data.gameId];\n //If the room exists...\n if( room != undefined ){\n // attach the socket id to the data object.\n\n // Join the room\n //console.log('Player ' + data.playerName + ' joining game: ' + data.gameId );\n this.join(data.gameId);\n data.socketId = this.id;\n // Emit an event notifying the clients that the player has joined the room.\n //console.log(data);\n io.in(data.gameId).emit('playerJoinedRoom', data);\n\n } else {\n // Otherwise, send an error message back to the player.\n io.emit('error',{message: \"This room does not exist.\"} );\n }\n}", "joinLobby(playerId, playerSocket) {\n\t\tlet playerIndex = this.lobbyPlayers.findIndex(player => player.pid == playerId);\n\n\t\t// Player is not in lobby yet; add them\n\t\tif (playerIndex == -1) {\n\t\t\tthis.lobbyPlayers.push({ pid: playerId, socket: playerSocket, status: \"In Lobby\", type: \"Human\" });\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "addUser (user) {\n if (this.players.length < this.maxPlayers) {\n if (this.players.findIndex(player => player.name === user.name) === -1) {\n this.players.push(user)\n user.join(this.name)\n user.room = this\n console.log('user ' + user.name + ' joined room ' + this.name)\n return true\n } else {\n console.log('user ' + user.name + ' tried to join room ' + this.name + ' but a player in that room already had that name')\n return false\n }\n } else {\n return false\n }\n }", "function roomExists(code) {\r\n try {\r\n console.log(\"checking if room with code: \" + code + \" exists\");\r\n console.log(rooms[code]);\r\n if(code == null || code == undefined || typeof code != 'string' || !rooms[code]) {\r\n console.log(\"it's bad\");\r\n return false;\r\n }\r\n console.log(\"it's good\");\r\n return true;\r\n } catch(e) {\r\n console.error(e);\r\n return false;\r\n }\r\n}", "function validateUser(socket, room, username, roomUsers){\n return (room \n && roomUsers[room] && socket.id in roomUsers[room] \n && roomUsers[room][socket.id] == username\n && socket.store && socket.store.data \n && socket.store.data.nickname == username\n && socket.store.data.room == room);\n}", "function joinRoom(socket, roomName){\n if (getRoomPlayersNumber(roomName) < playersPerRoom){\n socket.join(roomName);\n socket.room = roomName;\n return true;\n }\n return false\n }", "function playerJoinGame(data) {\n //console.log('Player ' + data.playerName + 'attempting to join game: ' + data.gameId );\n\n // A reference to the player's Socket.IO socket object\n var sock = this;\n\n // Look up the room ID in the Socket.IO manager object.\n var room = gameSocket.adapter.rooms[data.gameId];\n\n // If the room exists...\n if( room != undefined ){\n // attach the socket id to the data object.\n data.mySocketId = sock.id;\n\n // Join the room\n sock.join(data.gameId);\n game.mySocketId = sock.id;\n game.players[this.id] = {\n gameId: data.gameId,\n mySocketId: this.id,\n playerName: data.playerName,\n totalHp: 1000,\n hp: 1000,\n totalMana: 100,\n mana: 100,\n summons: [],\n buffs: [],\n cooldowns: {},\n baseCooldowns: {},\n };\n\n\n //console.log(gameSocket.adapter.rooms);\n //console.log('Player ' + data.playerName + ' joining game: ' + data.gameId );\n\n // Emit an event notifying the clients that the player has joined the room.\n io.sockets.in(data.gameId).emit('playerJoinedRoom', game);\n\n } else {\n // Otherwise, send an error message back to the player.\n this.emit('error',{message: \"This room does not exist.\"} );\n }\n}", "function handleJoin() {\r\n\tlet username = document.getElementById(\"username\").value.trim();\r\n\tlet roomCode = document.getElementById(\"room\").value.trim();\r\n\t\r\n\t/* If username and roomCode are unique and valid, then send\r\n\totherwise, give alert */\r\n\tconsole.log(Object.keys(roomState));\r\n\tconsole.log(Object.keys(roomState).indexOf(roomCode));\r\n\tif (Object.keys(roomState).indexOf(roomCode) != -1){\r\n\t\tlet existing = Object.keys(roomState[roomCode][\"players\"]);\r\n\t\tconsole.log(username.length > 0 && existing.indexOf(username) == -1);\r\n\t\tif (username.length > 0 && existing.indexOf(username) == -1) {\r\n\t\t\tsocket.emit(\"toJoin\", [username, roomCode]);\r\n\t\t\tshowChat(username);\r\n\t\t}\r\n\t\telse {\r\n\t\t\talert(\"Entered username is invalid, please try again!\");\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\talert(\"Entered game ID is invalid, please try again!\");\r\n\t}\r\n}", "function createOrAddToRoom(){\n\n if(!socketClients[clientId]){\n\n //if user does not exist\n return getUserData( msg.cookie ).then(function(userObject,error){//what if cookie is invalid\n if (error) return sendError('invalid cookie')\n socketClients[clientId] = {user:{id:userObject.id, username:userObject.username}, socket:ws}\n\n createOrAddToRoom()\n })\n\n \n }\n\n //also broadcast on join and leave and also joined member\n // console.log(clientId,'creating room or adding:'+roomLabel)\n function createRoom(){\n roomToken = random()\n roomsRegistry[roomLabel].notFull[roomToken] = {clients:[],limit:roomLimit}\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n }\n\n if (!roomsRegistry[roomLabel]){ //room not constructed \n roomsRegistry[roomLabel] = { full:{},notFull:{} }\n createRoom()\n }else{\n\n if ( Object.keys(roomsRegistry[roomLabel].notFull).length === 0 ) {\n createRoom()\n }else{\n\n roomToken = Object.keys(roomsRegistry[roomLabel].notFull)[0]\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n broadcast(roomToken,socketClients[clientId].user,'onjoin',roomLabel)\n\n let notFullRoomLimit = roomsRegistry[roomLabel].notFull[roomToken].limit\n let membersCountOfNotFull = roomsRegistry[roomLabel].notFull[roomToken].clients.length\n\n \n\n // if(membersCountOfNotFull > notFullRoomLimit) console.log('limit exceeded', membersCountOfNotFull, notFullRoomLimit)\n\n if(membersCountOfNotFull === notFullRoomLimit){\n roomsRegistry[roomLabel].full[roomToken] = roomsRegistry[roomLabel].notFull[roomToken]\n roomsRegistry[roomLabel].notFull = removeKey(roomsRegistry[roomLabel].notFull,roomToken)\n }\n\n }\n\n }\n\n broadcast(roomToken,null,'onopen',roomLabel)\n\n }", "function onConnect(socket) {\n\tconst connectBy = socket.handshake.headers.host\n\n\tconst clientId = socket.id\n\tplayers[clientId] = {socket: socket}\n\n\tconsole.log('Player', clientId, 'connected from', connectBy)\n\tsocket.on('disconnect', () => {\n\t\tconsole.log('Client', clientId, 'has been disconnected from', connectBy)\n\t\tif(players[clientId].room) {\n\t\t\trmPlayerFromRoom(players[clientId].room, clientId)\n\t\t}\n\t\tdelete players[clientId]\n\t})\n\n\t/**\n\t * room: str\n\t * type: str\n\t */\n\tsocket.on('create', (params, response) => {\n\t\tif(!params.room.match(ROOM_CODE_REGEXP)) {\n\t\t\tresponse({status: 'ko', err: 'Invalid room Id (\\'' + params.room + '\\' does not respect '+ ROOM_CODE_FORMAT + ')'})\n\t\t} else if(params.room in rooms) {\n\t\t\tresponse({status: 'ko', err: 'Room \\'' + params.room + '\\' already exists'})\n\t\t} else if(!(params.type in config.httpFolders)) {\n\t\t\tresponse({status: 'ko', err: 'Type of room \\'' + params.type + '\\' does not exist'})\n\t\t} else {\n\t\t\trooms[params.room] = {activity: params.type, host: null, roles:{all: []}}\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * room: str\n\t */\n\tsocket.on('join', (params, response) => {\n\t\tif(!(params.room in rooms)) {\n\t\t\tresponse({status: 'ko', err: 'Room \\'' + params.room + '\\' does not exists'})\n\t\t} else if(players[clientId].room) {\n\t\t\tresponse({status: 'ko', err: 'Already joined the room'})\n\t\t} else {\n\t\t\taddPlayerRoles(params.room, clientId, ['all'])\n\t\t\tio.to(params.room + '/all').emit('connected', clientId, {player: clientId, room: getRoomDescription(params.room)})\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * no parameters\n\t */\n\tsocket.on('leave', (params, response) => {\n\t\tif(!players[clientId].room) {\n\t\t\tresponse({status: 'ko', err: 'You are not a member of any room'})\n\t\t} else {\n\t\t\trmPlayerFromRoom(players[clientId].room, clientId)\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * player: str\n\t * roles: [role1, role2, ...]\n\t */\n\tsocket.on('addRoles', (params, response) => {\n\t\tconst roomId = players[clientId].room\n\t\tif(!roomId) {\n\t\t\tresponse({status: 'ko', err: 'You are not a member of any room'})\n\t\t} else if(rooms[roomId].host !== clientId) {\n\t\t\tresponse.status(401).send({err: 'Admin role required'})\n\t\t} else if(!(params.player in players) || players[params.player].room !== roomId) {\n\t\t\tresponse({status: 'ko', err: 'Player \\'' + params.player + '\\' is not in room \\'' + roomId + '\\''})\n\t\t} else {\n\t\t\taddPlayerRoles(roomId, params.player, params.roles)\n\t\t\tio.to(roomId + '/all').emit('connected', clientId, {player: params.player, room: getRoomDescription(roomId)})\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * player: str\n\t * roles: [role1, role2, ...]\n\t */\n\tsocket.on('rmRoles', (params, response) => {\n\t\tconst roomId = players[clientId].room\n\t\tif(!roomId) {\n\t\t\tresponse({status: 'ko', err: 'You are not a member of any room'})\n\t\t} else if(rooms[roomId].host !== clientId) {\n\t\t\tresponse.status(401).send({err: 'Admin role required'})\n\t\t} else if(!(params.player in players) || players[params.player].room !== roomId) {\n\t\t\tresponse({status: 'ko', err: 'Player \\'' + params.player + '\\' is not in room \\'' + roomId + '\\''})\n\t\t} else if('host' in params.roles || 'all' in params.roles) {\n\t\t\tresponse({status: 'ko', err: 'Cannot remove host and all rôles'})\n\t\t} else {\n\t\t\trmPlayerRoles(roomId, params.player, params.roles)\n\t\t\tio.to(roomId + '/all').emit('connected', clientId, {player: params.player, room: getRoomDescription(roomId)})\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * to: str (playerId)\n\t * cmd: str (command code)\n\t * content: <any>\n\t *\n\t * Will send to specified user, command id \"private/<cmd>\" with given content\n\t */\n\tsocket.on('tell', (params, response) => {\n\t\tconst roomId = players[clientId].room\n\t\tif(!roomId) {\n\t\t\tresponse({status: 'ko', err: 'You are not a member of any room'})\n\t\t} else if(!(params.to in players) || players[params.to].room !== roomId) {\n\t\t\tresponse({status: 'ko', err: 'Cannot find player \\'' + params.to + '\\' in room \\'' + roomId + '\\''})\n\t\t} else {\n\t\t\tplayers[params.to].socket.emit('private/' + params.cmd, clientId, params.content)\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * to: str (role)\n\t * cmd: str (command code)\n\t * content: <any>\n\t *\n\t * Will send to all users having the 'to' role in the room, command id \"<to>/<cmd>\" with given content\n\t */\n\tsocket.on('comm', (params, response) => {\n\t\tconst roomId = players[clientId].room\n\t\tif(!roomId) {\n\t\t\tresponse({status: 'ko', err: 'You are not a member of any room'})\n\t\t} else if(!(params.to === 'host' || params.to === 'all' || params.to in rooms[roomId].roles)) {\n\t\t\tresponse({status: 'ko', err: 'Role \\'' + params.to + '\\' does not exists'})\n\t\t} else {\n\t\t\tio.to(roomId + '/' + params.to).emit(params.to + '/' + params.cmd, clientId, params.content)\n\t\t\tresponse({status: 'ok'})\n\t\t}\n\t})\n\n\t/**\n\t * room: str\n\t *\n\t * Get information about a room\n\t */\n\tsocket.on('info', (params, response) => {\n\t\tif(!params.room || !ROOM_CODE_REGEXP.test(params.room)) {\n\t\t\tresponse({status: 'ko', err: 'Wrong room id \\'' + params.room + '\\''})\n\t\t} else if(params.room in rooms) {\n\t\t\tresponse({status: 'ok', room: getRoomDescription(params.room)})\n\t\t} else {\n\t\t\tresponse({status: 'ok', room: null})\n\t\t}\n\t})\n}", "_addUserToRoom(userId, room) {\n\t\tlet roomId = String(room.id);\n\n\t\t// add the room if it does not exist jet\n\t\tif (this._rooms[roomId] === undefined) {\n\t\t\tthis._rooms[roomId] = {\n\t\t\t\t'obj'\t: room,\n\t\t\t\t'users'\t: []\n\t\t\t};\n\t\t}\n\n\t\t// add the user to the room\n\t\tthis._rooms[roomId].users.push(userId);\n\n\t\t// add the room to the user\n\t\tthis._users[userId].rooms.push(roomId);\n\t}", "function hostGame(data) {\n \n if (data != \"\" || data.toLowerCase() != \"local\") {\n if (data in gameRoomDict) {\n console.log(data + \" is already a game room.\"); \n }\n else {\n roomAdjust();\n room = data;\n clients.sock = data;\n gameRoomDict[data] = [socket.id]; \n var stuff = [data, \"host\"]\n io.to(socket.id).emit('connectedH', stuff);\n }\n }\n }", "addRoom(name, author, author_id) {\n\n \t// check is the room name is't exist\n \tvar x = this.getRoomByName(name);\n \tif (x) {\n \t\treturn false ;\n \t}\n var id = uniqid();\n var room = {\n id : uniqid(),\n author : author,\n name : name,\n author_id: author_id\n };\n this.rooms.push(room);\n return true;\n }", "function joinRoom() {\n const code = document.getElementById(\"roomCodeInput\").value;\n socket.emit(\"joinRoom\", code);\n}", "function addRoomUser(info) {\n\tvar dude = new PalaceUser(info);\n\tif (theRoom.lastUserLogOnID == dude.id && ticks()-theRoom.lastUserLogOnTime < 900) { // if under 15 seconds\n\t\ttheRoom.lastUserLogOnID = 0;\n\t\ttheRoom.lastUserLogOnTime = 0;\n\t\tif (!getGeneralPref('disableSounds')) systemAudio.signon.play();\n\t}\n\tif (theUserID == dude.id) {\n\t\ttheUser = dude;\n\t\tfullyLoggedOn();\n\t}\n\n\ttheRoom.users.push(dude);\n\tloadProps(dude.props);\n\tdude.animator();\n\tdude.grow(10);\n\tPalaceUser.setUserCount();\n}", "function connection(socket) {\n var player;\n var game; // current game. Allow only one game per session for now.\n /**\n * checks the client's authKey cookie\n * @param data\n */\n function setAuthKey(data) {\n var authKey = data.authKey;\n // does the player exist in memory?\n player = players.get(authKey);\n if (player) {\n // is he currently in a session?\n if (player.socket) {\n publish('auth.response', {\n type: 'error',\n error: \"You're already connected to a game.\"\n });\n } else {\n playerSetData();\n }\n } else {\n publish('auth.response', {\n type: 'new_user'\n });\n }\n // when the client disconnects, we check if the game is empty,\n // then remove the game from the list.\n subscribe('disconnect', function() {\n player.disconnect();\n if (game) {\n if (game.connectedPlayers() === 0) {\n games.remove(game);\n } else {\n game.userDisconnect();\n }\n }\n });\n subscribe('player.set.name', setName);\n }\n\n function playerSetData() {\n player.connect(socket);\n subscribe('game.find', findGame);\n publish('auth.response', {\n type: 'connected',\n id: player.id,\n name: player.name,\n authKey: player.authKey,\n expiresIn: player.expiresIn,\n expires: player.expires\n });\n }\n /**\n * Sets the name of the player from the client.\n * @param data\n */\n function setName(data) {\n if (!player) {\n player = new Player();\n player.name = data.name;\n players.add(player);\n playerSetData();\n } else {\n player.name = data.name;\n }\n publish('player.set.name', { name: player.name });\n \n //console.log( \"| player \" , player);\n }\n /**\n * Registers the current player to the room.\n * @param game\n * @return {*}\n */\n function joinGame(game, team) {\n var gameID = game.id;\n // reason why we're using a collection method is that so\n // we can update the vacant games in the list.\n games.occupy(game, player, team);\n // this will tell the client what happened in the game.\n // which is useful for watching replays.\n game.backlogs(function(name, data){\n publish(name, data);\n });\n // when the player's assets are loaded\n subscribe('ready', playerReady);\n // subscribe the user to the game list.\n socket.join(gameID);\n // Tell the client, he's subscribed to a game.\n publish('game.join', { id: gameID });\n \n //console.log( \"joinGame \" , game);\n return game;\n }\n /**\n * Fins a game to join. If none exists, it'll create one.\n */\n function findGame(parameters) {\n var team = parameters.team;\n var mode = parameters.mode;\n if (game === undefined) {\n switch (mode) {\n case 'tutorial':\n game = joinGame(createGame(1), team);\n break;\n default:\n game = joinGame(games.available() || createGame(), team);\n break;\n }\n }\n }\n /**\n * Creates a new game object.\n * @return {*}\n */\n function createGame(maxPlayers) {\n maxPlayers || (maxPlayers = 2);\n var game = new Game({ maxPlayers: maxPlayers });\n var gameID = game.id;\n game.on('log', function(event) {\n io.sockets.in(gameID).emit(event.name, event.data);\n console.log(\n \"| createGame Game (\" + game.id + \"): \",\n event.name, '->',\n JSON.stringify(event.data)\n );\n });\n games.add(game);\n \n //console.log( \"| Game \" , JSON.stringify(games) );\n return game;\n }\n /**\n * When the player has successfully loaded the assets in the game.\n */\n function playerReady() {\n if (game) {\n game.playerReady(player);\n // all the game events\n subscribe('unit.move', unitMove);\n subscribe('unit.attack', unitAttack);\n subscribe('unit.skip', unitSkip);\n console.log( \"playerReady\" );\n }\n }\n\n function unitAttack(parameters) {\n var tile;\n // check if there's a current game.\n if (game && game.winner === null) {\n // check if the current active unit is from the players.\n if (game.activeUnit && game.activeUnit.playerId === player.id) {\n tile = game.grid.get(parameters.x, parameters.y);\n if (tile) {\n game.actUnit(game.activeUnit, tile);\n //console.log( \"| activeUnit \" , JSON.stringify(game.activeUnit) );\n }\n }\n }\n }\n\n function unitSkip(unitId) {\n var activeUnit = game.activeUnit;\n if (game.winner === null) {\n if (activeUnit.playerId === player.id) {\n if (activeUnit.id === unitId ){\n game.skip(unitId);\n //console.log( \"| skip \" , unitId );\n \n }\n }\n }\n }\n\n function unitMove(data) {\n var tile;\n var activeUnit = game.activeUnit;\n // if the game isn't finished yet\n if (game.winner === null) {\n if (activeUnit && activeUnit.playerId === player.id) {\n if (tile = game.grid.get(data.x, data.y)) {\n game.move(activeUnit, tile);\n }\n }\n }\n }\n\n function publish(topic, data) {\n socket.emit(topic, data);\n }\n\n function subscribe(topic, callback) {\n socket.on(topic, callback);\n }\n\n // Listen to only one event first which is the authentication\n // before proceeding to anything else.\n subscribe('auth', setAuthKey);\n }", "function playerCreateNewGame(data) {\n // Create a unique Socket.IO Room\n var thisGameId = ( Math.random() * 100000 ) | 0;\n\n // Return the Room ID (gameId) and the socket ID (mySocketId) to the browser client\n game.gameId = thisGameId;\n game.mySocketId = this.id;\n game.players[this.id] = {\n gameId: thisGameId,\n mySocketId: this.id,\n playerName: data.playerName,\n totalHp: 1000,\n hp: 1000,\n totalMana: 100,\n mana: 100,\n summons: [],\n buffs: [],\n cooldowns: {},\n baseCooldowns: {},\n };\n game.players[1] = {\n gameId: thisGameId,\n mySocketId: 1,\n playerName: 'Test Bot',\n totalHp: 1000,\n hp: 1000,\n totalMana: 100,\n mana: 100,\n summons: [],\n buffs: [],\n cooldowns: {},\n baseCooldowns: {},\n };\n this.emit('newGameCreated', game);\n //console.log(thisGameId+\" # \"+this.id);\n\n // Join the Room and wait for the players\n this.join(thisGameId.toString());\n //console.log(gameSocket.adapter.rooms);\n}", "function joinGame(data) {\n \n //Check if room exists\n if (data in gameRoomDict) {\n if (gameRoomDict[data].length < 2) {\n io.to(gameRoomDict[data][0]).emit('p2Joined');\n room = data;\n clients.sock = data;\n console.log(\"You have joined the lobby named: \" + data);\n gameRoomDict.data = gameRoomDict[data].push(socket.id);\n var stuff = [data, \"join\"]\n io.to(socket.id).emit('connectedG', stuff);\n console.log(gameRoomDict[data]);\n }\n else {\n console.log(\"Sorry this room is full\");\n }\n }\n else {\n console.log(data + \" does not exist in the list of current lobbies.\");\n }\n }", "function enterRoom(player)\n{\n\tconsole.log(\"joining a room\");\n\tvar key = Object.keys(rooms);\n\t\n\tfor(var i = 0;i<key.length;i++)\n\t{\n\t\tconsole.log(\"looking into room \"+rooms[key[i]].name);\n\t\tif(Object.keys(rooms[key[i]].players).length < 2)\n\t\t{\n\t\t\tconsole.log(\"joining existing room \" +rooms[key[i]]);\n\t\t\t\n\t\t\tplayer.socket.join(rooms[key[i]].name);\n\t\t\tplayer.socket.room = rooms[key[i]].name;\n\t\t\trooms[key[i]].players[player.id] = player;\n\t\t\t\n\t\t\tvar opponent = findOpponent(player, player.socket);\n\t\t\t\n\t\t\tif(opponent)\n\t\t\t{\n\t\t\t\tvar playerStats = \n\t\t\t\t{\n\t\t\t\t\tnumCards: Object.keys(player.cardsInHand).length,\n\t\t\t\t\tnumDeck: Object.keys(player.deck).length,\n\t\t\t\t\tgrave: player.grave,\n\t\t\t\t\tboard: boards[player.socket.room],\n\t\t\t\t\tfield: player.field\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tvar opponentStats = \n\t\t\t\t{\n\t\t\t\t\tnumCards: Object.keys(opponent.cardsInHand).length,\n\t\t\t\t\tnumDeck: Object.keys(opponent.deck).length,\n\t\t\t\t\tgrave: opponent.grave,\n\t\t\t\t\tboard: boards[player.socket.room],\n\t\t\t\t\tfield: opponent.field\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\topponent.socket.emit(\"playerConnected\", playerStats);\n\t\t\t\tplayer.socket.emit(\"playerConnected\", opponentStats);\n\t\t\t\tconsole.log();\n\t\t\t\t\n\t\t\t\tfor(var i = 0;i<3;i++)\n\t\t\t\t{\n\t\t\t\t\tdrawCard(player);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(opponent.cardsInHand.length == 0)\n\t\t\t\t{\n\t\t\t\t\tfor(var i = 0;i<3;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdrawCard(opponent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//console.log(\"current players \");\n\t\t\t\t//console.dir(rooms[key[i]].players);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconsole.log(\"finished looking into room \"+rooms[key[i]]);\n\t}\n\t\n\tvar roomName = \"room\"+roomNum;\n\t\n\tplayer.socket.join(roomName);\n\tplayer.socket.room = roomName;\n\tplayers[player.id] = player;\n\t\n\tvar room = \n\t{\n\t\tname: roomName,\n\t\tplayers: []\n\t};\n\t\n\tvar board = new Array(7);\n\tfor(var x = 0; x < 7; x++)\n\t{\n\t\tboard[x] = new Array(5);\n\t}\n\tconsole.dir(board);\n\tboards[roomName] = board;\n\t\n\trooms[roomName] = room;\n\trooms[roomName].players[player.id] = player;\n\t\n\troomNum++;\n\tconsole.log(\"joined \"+roomName);\n\t//console.dir(rooms);\n}", "function joinroom(data) {\n\tvar tmproom = data;\n\tif (player != \"\" && passcode != \"\" && tmproom >= 0) {\n\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=joinroom&player=\" + player + \"&passcode=\" + passcode + \"&room=\" + tmproom;\n\t\t$.ajax({\n\t\t\tcache: false,\n\t\t\tdataType : 'xml',\n\t\t\ttype : 'GET',\n\t\t\turl : geturl,\n\t\t\tsuccess : function(data) {\n\t\t\t\tstartRoom(data);\n\t\t\t},\n\t\t});\n\t}\n}" ]
[ "0.7259357", "0.6986688", "0.65623856", "0.6164955", "0.616157", "0.60117674", "0.58439666", "0.5842452", "0.58084244", "0.5745237", "0.57409793", "0.57213867", "0.5685096", "0.5671052", "0.56618416", "0.5655997", "0.56455445", "0.5608213", "0.55980283", "0.5526065", "0.5514053", "0.5503278", "0.54653937", "0.5457243", "0.5428105", "0.5407918", "0.5390006", "0.5364029", "0.53138214", "0.5301062" ]
0.902076
0
Returns the room code associated with the given socket. Returns undefined if none exists.
_getRoomCodeFromSocket(socket) { if (socket && socket.rooms) { return socket.rooms[Object.keys(socket.rooms)[1]]; } return undefined; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getRoomInfo(socket, game) {\n if(socket && game) {\n const room = Array.from(socket.rooms)[1];\n const existingGame = game.map(game => game.roomId).indexOf(room);\n return existingGame;\n }\n else {\n return -1;\n }\n}", "function GetRoomHost(RequestingSocket, RoomName, LobbyInfo) {\n\tvar clients = io.sockets.adapter.rooms[RoomName].sockets; \n\n\tif(clients) {\n\t\tfor (var clientId in clients ) {\n\t\t\tvar clientSocket = io.sockets.connected[clientId];\n\t\t\tif(clientSocket.id == GetSocketFromPlayer(LobbyInfo.HOST_ID)) {\n\t\t\t\treturn clientSocket.id;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}", "function getSocketId() {\n const socketId = socket ? socket.id : 'none';\n\n return socketId || 'none';\n}", "static onSocketInit(socket, URLhash) {\n let roomID = '';\n\n if (!rooms.isRoomExists(URLhash) || rooms.getRoomPlayersCount(URLhash) >= 2) {\n roomID = (URLhash && !rooms.isRoomExists(URLhash)) ? URLhash : socket.id;\n const room = new Room(roomID);\n room.addPlayer(socket.id);\n\n rooms.addRoom(room);\n } else {\n roomID = URLhash;\n rooms.getRoom(roomID).addPlayer(socket.id);\n }\n\n return roomID;\n }", "getRoom (socketOrId) {\n\t\t\tif (typeof socketOrId == \"object\") {\n\t\t\t\treturn this.getByToken(socketOrId);\n\t\t\t} else if (typeof socketOrId == \"string\") {\n\t\t\t\treturn this.getById(socketOrId);\n\t\t\t}\n\t\t}", "function genRoomCode() {\n const roomSeed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n rooms = io.sockets.adapter.rooms;\n let code\n do {\n code = ''\n for (var i = 0; i < 5; i++) {\n code += roomSeed[getRandomInt(roomSeed.length)]\n }\n // Keep generating new codes if the code is already in use\n } while (rooms[code])\n return code\n }", "function joinRoom() {\n const code = document.getElementById(\"roomCodeInput\").value;\n socket.emit(\"joinRoom\", code);\n}", "getRoom(roomCode) {\n return this.rooms[roomCode];\n }", "function GetPlayerIDFromSocket(SocketID) {\n\tfor(var i=0; i<PlayerToSocketMap.length; i++) {\n\t\tif(PlayerToSocketMap[i].value == SocketID) {\n\t\t\treturn PlayerToSocketMap[i].key;\n\t\t}\n\t}\n}", "function getOpponent (socket) {\n if (!players[socket.id].opponent) {\n return;\n }\n\n return players[\n players[socket.id].opponent\n ].socket;\n}", "getNameFromSocket(socket) {\n return this.socketNames[socket.id];\n }", "function getOpponent(socket) {\n if (players[socket.id] && players[socket.id].opponent) {\n const opponentID = players[socket.id].opponent;\n return clientSockets[opponentID];\n }\n return;\n}", "SOCKET_GET_ROOM_INFO(state, message) {\n // eslint-disable-next-line\n console.log(\"%c socket_get_room_info\", \"color:green\");\n state.room = message;\n }", "function findOpponent(currPlayer, socket)\n{\n\tconsole.log(\"socket room \" +socket.room);\n\tvar room = io.sockets.adapter.rooms[socket.room];\n\tconsole.log(\"opponent room \");\n\t//console.dir(rooms[socket.room].players);\n\tvar key = Object.keys(rooms[socket.room].players);\n\tconsole.log(\"got the key\");\n\t\n\tfor(var i = 0;i<key.length;i++)\n\t{\n\t\tif(rooms[socket.room].players[key[i]] && rooms[socket.room].players[key[i]].id != currPlayer.id)\n\t\t{\n\t\t\tconsole.log(\"curr player id \" + currPlayer.id + \" player id \" + rooms[socket.room].players[key[i]].id);\n\t\t\treturn rooms[socket.room].players[key[i]];\n\t\t}\n\t}\n\t\n\tconsole.log(\"No opponent found\");\n}", "_GetSocket(UUID)\n {\n const index = this._Sockets.findIndex(s => s._UUID == UUID);\n if(index != -1)\n {\n return this._Sockets[index];\n }\n else\n {\n return false;\n } \n }", "function RoomSocket(io, roomId){\n this.roomId = roomId;\n this.io = io;\n}", "getPlayerFromSocket(socket) {\n return this.players[this.getNameFromSocket(socket)];\n }", "function stateUpdate(socket) {\n let gameCode = Array.from(socket.rooms)[1]\n if(Object.keys(gameData).includes(gameCode)){\n io.in(gameCode).emit(\"stateUpdate\", gameData[gameCode].gamestate)\n }\n}", "async function generateInterrGameCode(socket) {\n const pattern = '^[0-9][A-Z0-9]{5}';\n let found = true;\n let gameCode;\n\n /* generate code here */\n while(found){\n gameCode = randexp(pattern); \n sql_code_dupe = `SELECT * FROM ${process.env.DATABASE_PLATFORM}.interupted_instances WHERE GameCode = \"${gameCode}\";`;\n\n /* Check if code exists, if yes, generate again */\n try {\n let results = await query_platform(sql_code_dupe);\n\n if(!results.length) {\n found = false;\n }\n }\n catch(err) {\n socket.emit('errorMenu', { 'message' : 'Unable to access the database. #8', 'error': err });\n return;\n }\n }\n return gameCode;\n}", "function roomID(type){\n var matchRoomRequest;\n //urls for express sessions and normal sessions \n //are not the same \n if(type==\"workspace\"){\n matchRoomRequest = /.*\\/workspace\\/(.+)/;\n }\n else{\n matchRoomRequest = /.*\\/express\\/(.{32})/;\n }\n var match = matchRoomRequest.exec(document.URL);\n\n if(match){\n return match[1];\n }\n}", "function join(socket, roomCode, callback) {\n if (socket && socket.join) {\n socket.join(roomCode, callback);\n }\n}", "async function getGameState(socket, roomId) {\n\n let game = await Game.findOne({RoomId: roomId});\n if (game) {\n socket.emit('game in progress', {\n round: game.Round,\n });\n }\n\n}", "getMemAddr(room) {\n let memRoomAddr;\n if (room == this.roomName) {\n return this.memoryAddr;\n } else {\n let remoteRoom = this.remoteRooms[room];\n if (remoteRoom) {\n memRoomAddr = this.memoryAddr.remoteRooms[room];\n } else {\n // throw error: this is not a room in my domain\n return;\n }\n }\n return memRoomAddr;\n }", "function getRoom(){\n\tvar chatName = document.getElementById(\"chatName\");\n\tif(!chatName)\n\t\treturn null;\n\treturn chatName.innerText;\n}", "function getSession(socket) {\n let session = cookie.parse(socket.request.headers.cookie).session;\n return(decode(session).SID);\n}", "function getRoom()\n {\n\n // console.log(\".. . .. . .. . \" + room);\n\n // if(room == undefined) ///eller === \n // {\n // return \"Sök sal...\";\n // }\n // else\n // {\n // return room; // eller toString(room);\n // }\n }", "function getRoom(roomCode) {\n var ref = firebase.database().ref(\"Rooms/\" + roomCode);\n var room = $firebaseObject(ref);\n \n return room;\n }", "getRoom() {\n const id = this.roomName;\n\n if (!activeRooms.hasOwnProperty(id)) {\n throw new Error('Room requested does not exist: ' + id);\n }\n\n return activeRooms[id];\n }", "function inside(socket, room) {\n return !!socket.manager.roomClients[socket.id][room];\n }", "get roomId() {\n\t\treturn browser.element('.messages-container.flex-tab-main-content').getAttribute('id').replace('chat-window-', '');\n\t}" ]
[ "0.677028", "0.64517397", "0.6379158", "0.63646704", "0.6343907", "0.6165044", "0.6035847", "0.60143197", "0.5894607", "0.5782973", "0.576276", "0.56828135", "0.55689883", "0.54989797", "0.5497969", "0.5470038", "0.54437405", "0.54031354", "0.54011744", "0.5392365", "0.53735644", "0.53442943", "0.53393155", "0.53349537", "0.5323241", "0.53183335", "0.5304917", "0.5289702", "0.52624595", "0.52246267" ]
0.89912665
0
Returns the sanitized username from the given data object. Returns empty string if unsuccessful.
_getSanitizedUsername(data) { if (!data || !data.username) { return ""; } return StringSanitizer.getHtmlSanitized(data.username).substring(0, MAX_USERNAME_LENGTH); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getUserName(authData) {\n switch (authData.provider) {\n // case 'password':\n // return authData.password.email.replace(/@.*/, '');\n case 'twitter':\n return authData.twitter.username;\n // case 'facebook':\n // return authData.facebook.displayName;\n }\n }", "function safeUsername() {\n return os.userInfo().username.replace(/[^\\w+=,.@-]/g, '@');\n}", "username (value) {\n // min length 1\n if (!value || value.length < 1) {\n return 'You must provide a username.';\n }\n // max length 40\n else if (value.length > 40) {\n return 'Username can only be 40 characters long.';\n }\n return null;\n }", "username(user){\n if(!user){\n return 'User name cannot be empty';\n }else if(user.length>32){\n return 'The length of user name is 32';\n }else if(!/^\\w{4,32}$/.test(user)){\n return 'Wrong format';\n }else{\n return null; // no error\n }\n }", "validateUsername () {\n\t\tif (!this.attributes.username) { return; }\n\t\tlet error = this.userValidator.validateUsername(this.attributes.username);\n\t\tif (error) {\n\t\t\treturn { username: error };\n\t\t}\n\t}", "function parse_username(str) {\n\tstr = str.replace(/[^\\w]/g,\"\").toLowerCase();\n\tif (!str)\n\t\tstr = \"user\"; // nothing? we'll give you something boring.\n\treturn str.slice(0,9);\n}", "function CreateUserName(divID) {\n var name = Sanitize($(`${divID}`).val());\n name = name.toLowerCase();\n\n if (name.match(/^(https?:\\/\\/)?[a-z0-9]+\\./ig) || name.match(/^@/ig)) {\n name = name.match(/@[a-z0-9-]{3,16}[^\\/]/ig)[0].substring(1);\n }\n\n return name;\n }", "name(userId) {\n if (userId) {\n // find user from user id\n let user = Meteor.users.findOne(userId, {fields: {'username': 1}});\n // return username\n return user ? `@${user.username}`: '';\n }\n }", "function renderUser(name, data, parameters={}, options={}) {\n\n var html = `<span>${data.username}</span>`;\n\n if (data.first_name && data.last_name) {\n html += ` - <i>${data.first_name} ${data.last_name}</i>`;\n }\n\n return html;\n}", "function get_logged_in_username(domain) {\n var adcls = pii_vault.aggregate_data.current_loggedin_state;\n\n if (domain in adcls && adcls[domain].state == \"logged-in\") {\n\tvar username_identifier = adcls[domain].username;\n\tvar rc = get_idenfier_value(username_identifier);\n\tvar username_length = rc[0];\n\treturn [username_identifier, username_length];\n }\n var username = \"\";\n var username_identifier = get_username_identifier(\"\", true);\n var username_length = username.length;\n\n return [username_identifier, username_length];\n}", "function usernameConverter(inputValue) {\n const value = inputValue.trim().toLowerCase();\n // Twitch username format. Only accepts alphanumeric and _, also between 4 and 25 characters\n if (/^[a-z0-9_]{4,25}$/.test(value)) {\n return value;\n }\n throw new Error(`'${inputValue}' is not in a valid Twitch username format`);\n}", "function getUsername(elt) {\n // Extract the username from the given element,\n // To find a username, we look for a text node that follows\n // a <a class=\"timeline\"> element.\n // We exclude usernames containing \"@\" because we want actual\n // usernames, not a \"Full Name <email@...>\" that trac can sometimes\n // generate.\n var raw = $('.timeline', elt)[0].nextSibling.data.trim();\n if (raw && raw.substring(0, 3) === 'by ' && raw.indexOf('@') < 0) {\n return raw.substring(3);\n }\n else {\n return '';\n }\n }", "function findUser() {\n\t\tvar myUser;\n\n\t\t// Get the username value from the form and cleanup the @ if needed\n\t\tif (document.tweetfinder.user.value[0] == \"@\") {\n\t\t\tmyUser = document.tweetfinder.user.value.substring(1,20); //get rid of the @\n\t\t}\n\t\telse { myUser = document.tweetfinder.user.value };\n\n\t\t// Validate length of username\n\t\tif (myUser.length > 16) { // TODO: if true, return error msg and don't continue\n\t\t\t$('#error').html(\"This doesn't seem to be a username. Too long.\");\n\t\t\treturn \"usernameistoolong\";\n\t\t}\n\t\telse {\n\t\t\treturn myUser;\n\t\t}\n}", "function parseUsername(user) {\n let username = '';\n //split to have the image name\n const firstSplit = user.split('/');\n //split to have only the username\n const secondSplit = firstSplit[firstSplit.length - 1].split('.');\n\n if (secondSplit.length > 0) {\n let usernameAux = secondSplit[0];\n username = usernameAux[0].toUpperCase();\n\n for (let i = 1; i < usernameAux.length; i++)\n username += usernameAux[i];\n }\n\n return username;\n}", "function getUsername (){\n let username = document.querySelector(\"#username\").value;\n return JSON.stringify(username);\n }", "get usernameEmptyText() {\n return \"\";\n }", "function getUsername(req) {\n const user = _decodeJWT(req)\n if (!user) return null\n\n return user.username\n}", "function getDisplayName(authData) {\n switch (authData.provider) {\n case 'password':\n return authData.password.email.replace(/@.*/, '');\n case 'twitter':\n return authData.twitter.displayName;\n case 'facebook':\n return authData.facebook.displayName;\n }\n }", "function on_get_username(data, sender, sendResponse) {\n sendResponse({\n 'username': find_username(),\n });\n }", "function getName(authData) {\n switch (authData.provider) {\n case 'password':\n return authData.password.email.replace(/@.*/, '');\n case 'twitter':\n return authData.twitter.displayName;\n case 'facebook':\n return authData.facebook.displayName;\n }\n }", "validateUsername (value, definition/*, options*/) {\n\t\tdefinition = definition || this.attributeDefinitions.username;\n\t\tif (typeof value !== 'string' || value.length === 0) {\n\t\t\treturn 'must be a string';\n\t\t}\n\t\tif (!UsernameValidator.validate(value, definition.lowercaseOnly)) {\n\t\t\treturn 'can only contain alphanumerics, hyphen, period, and underscore';\n\t\t}\n\t}", "function getUserName() {\n // check the url and store it in a variable so we can search it\n var url = $(location).attr('href'),\n urlComponents,\n username;\n // split the url into searchable components\n urlComponents = url.split('?')\n // search the match data for the passed username and return it\n for (var i = 0; i < urlComponents.length; i++){\n // split the string again to compare value pairs\n compComponents = urlComponents[i].split('=');\n if (compComponents[0] === 'username') {\n return compComponents[1];\n }\n }\n}", "function lookUpUserName(data, type, row, meta) {\n let name = null;\n abp.ajax({\n type: 'GET',\n async: false,\n url: '/api/identity/users/' + data, //here is GUID data\n }).done(function (result) {\n name = result.name\n });\n return name \n }", "function getName(authData) {\n switch (authData.provider) {\n case 'password':\n return authData.password.email.replace(/@.*/, '');\n }\n }", "function getUserName() {\n // check the url and store it in a variable so we can search it\n var url = $(location)attr.('href'),\n urlComponents,\n username;\n // split the url into searchable components\n urlComponents = url.split('?')\n // search the match data for the passed username and return it\n for (var i = 0; i < urlComponents.length; i++){\n // split the string again to compare value pairs\n compComponents = urlComponents[i].split('=');\n if (compComponents[0] === 'username') {\n return compComponents[1];\n }\n }\n\n}", "function getUserByName(username) {\n}", "function userName(accounts) {\n for (let i = 0; i < accounts.length; i++) {\n let userParts = accounts[i].owner.toLowerCase().split(\" \");\n let firstLetters = \"\";\n\n for (let j = 0; j < userParts.length; j++) {\n firstLetters += userParts[j][0];\n }\n accounts[i].username = firstLetters;\n }\n return accounts;\n}", "function displayUserName(data) {\n\t$('.welcome_message').html(`Welcome ${data.currentUser.username}, you are now logged into`)\n}", "function obtenerUserName(loginName) {\n userName = loginName;\n\n array = userName.split(\"|\");\n if (array.length == 3) {\n userName = array[2];\n }\n\n array = userName.split(\"\\\\\");\n if (array.length == 2) {\n userName = array[1];\n }\n\n return userName;\n}", "function getUserName(){\n let userName = document.getElementById(\"userNameText\").value;\n userName = userName.toLowerCase();\n let userNameFirstLetter = userName[0];\n userNameFirstLetter = userNameFirstLetter.toUpperCase();\n userName = userName.substring(1);\n validatedUserName = userNameFirstLetter + userName;\n playerScores.innerText = validatedUserName;\n}" ]
[ "0.6556607", "0.6441322", "0.6351614", "0.62824726", "0.62534326", "0.6222458", "0.62051564", "0.593441", "0.58392864", "0.57818395", "0.5737936", "0.5735899", "0.57323736", "0.5671924", "0.567183", "0.5656397", "0.5636011", "0.560751", "0.560013", "0.5596617", "0.55797195", "0.55708313", "0.5560543", "0.5551707", "0.5524257", "0.55183965", "0.5517536", "0.55156076", "0.55119216", "0.5507997" ]
0.8672377
0
PUBLIC METHODS Returns the number of active rooms within the RoomPool.
getNumRooms() { return Object.keys(this.rooms).length; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static numActiveGames() {\n return Rooms.getAll()\n .filter(({isActive}) => isActive)\n .length;\n }", "static totalNumPlayers() {\n return Rooms.getAll()\n .filter(({isActive}) => isActive)\n .reduce((count, {players}) => {\n return count + players.filter(x => x.isConnected && !x.isBot).length;\n }, 0);\n }", "getRoomCount() {\n return new Promise((res, rej) => {\n this.#database.count({}, (err, count) => {\n if (err) rej(err);\n res(count);\n });\n });\n }", "function getSocketCountInRoom(roomName) {\n var roomInfo;\n var output;\n\n if (roomName) {\n roomInfo = io.sockets.adapter.rooms[roomName];\n if (roomInfo && roomInfo.length) {\n output = roomInfo.length;\n }\n }\n\n if (typeof output == 'undefined') {\n output = 0;\n }\n\n return output;\n}", "function getNumberUsersInRoom(room) {\n var room = io.sockets.adapter.rooms[room];\n\n if (room !== undefined) {\n console.log('room length ' + room.length);\n return room.length;\n }\n else {\n return 0;\n }\n\n}", "function getRoomPlayersNumber( roomName ){\n let room = io.sockets.adapter.rooms[roomName];\n return (room === undefined)? 0 : room.length;\n }", "itemCount() {\n return this.__roomItems.length;\n }", "static numGames() {\n return Rooms.getAll().length;\n }", "function countPioneerAssignments(room, sourceId) {\n var pioneers = room.find(FIND_MY_CREEPS, {\n filter: function(obj) {\n return (obj.memory.role == Static.ROLE_PIONEER);\n }\n });\n \n var count = 0;\n for (var i in pioneers) {\n var pioneer = pioneers[i];\n if (pioneer.memory.assignedToSourceId == sourceId) {\n count++;\n }\n }\n\n return count;\n}", "getActiveServersCount() {\n var w = this;\n var c = 0;\n for (var s in w.servers) {\n if (w.servers[s].isBound()) c++;\n }\n return c;\n }", "function getNumberOfViewers (room) {\n\t\tif(room && io.sockets.adapter.rooms[room]) {\n\t\t\treturn Math.max(Object.keys(io.sockets.adapter.rooms[room]).length, 1);\n\t\t} else {\n\t\t\treturn 1;\n\t\t}\n\t}", "function totalAvailability(chainOfHotels) {\n\t//console.table(chainOfHotels);\n\t//console.log(chainOfHotels[0].rooms);\n\tvar roomsAvailable = 0;\n\tvar i;\n\tfor (i = 0; i < chainOfHotels.length; i++) {\n\t\troomsAvailable = roomsAvailable + (chainOfHotels[i].rooms - chainOfHotels[i].booked);\n\t\t//console.log(chainOfHotels[i].booked);\n\t\t//console.log(roomsAvailable);\n\t\t//console.log(roomsAvailable);\n\t}\n\t//return the number of rooms available across all of the hotels in the chain\n\t//console.log(totalRoomAvailable);\n\treturn roomsAvailable;\n}", "getAvailableSeatCount () {\n return (this.capacity - this.passengerList.length);\n }", "function creepsInRoom(room) {\n \"use strict\";\n\n const creepsInRoom = room.find(FIND_MY_CREEPS);\n const count = {}\n for (let role of roles) {\n count[role] = _.sum(creepsInRoom, c => c.memory.role == role);\n }\n return count;\n}", "roomCoursesNumber(examRoom) {\n let st = this.roomCourse(examRoom)\n return st.size;\n }", "function getRooms() {\n var availableRooms = [];\n var rooms = io.sockets.adapter.rooms;\n if (rooms) {\n for (var room in rooms) {\n if (!rooms[room].hasOwnProperty(room) && room.includes('room:')) {\n var data = {}\n data.roomName = room.split(\"room:\").pop();\n data.numberOfUsers = rooms[room].length;\n availableRooms.push(data);\n }\n }\n }\n return availableRooms;\n}", "function countActiveJobs () {\r\n return state.jobs.reduce((count, job) => {\r\n if (job.state === 'active') {\r\n count++;\r\n }\r\n return count;\r\n }, 0);\r\n}", "function getActiveChatCount() {\r\n\tvar count = 0;\r\n\tfor(var id in enabledTabsMap) {\r\n if (enabledTabsMap[id] == true) {\r\n \tcount++;\r\n }\r\n\t} \r\n return count;\r\n}", "function numberOfOpenGames(){\n var num = 0;\n for (var i = 0; i < game_list.length; i++) {\n if (game_list[i].number_slots > 0) num++;\n }\n return num;\n}", "function connCount() {\n var connCount = []\n for (var pixelid = 0; pixelid < 50; pixelid++) {\n connCount.push(null)\n var room = mobilesock.adapter.rooms[pixelid]\n if (room) {\n phones = pixelid\n connCount[pixelid] = room.length\n } else {\n connCount[pixelid] = 0\n }\n }\n panelsock.emit('connCount', connCount)\n\n}", "function getOfflineCoursesCount(){\n\tcoursesDb.find({}, function(err, docs){\n\t\tsyncCourses(docs.length)\n\t})\n}", "ActiveRoom(){\r\n\t\tif(this.roomsMgr.RoomExists(this.activeRoom)){\r\n\t\t\treturn this.roomsMgr.Room(this.activeRoom);\r\n\t\t}\r\n\t\treturn this.roomsMgr.Room(SERVER_CH);\r\n\t}", "function connCount(){\n var connCount = []\n for(var pixelid=0;pixelid<15;pixelid++){\n connCount.push(null)\n var room = mobilesock.adapter.rooms[pixelid]\n if(room){\n connCount[pixelid] = room.length\n }else{\n connCount[pixelid] = 0\n }\n }\n panelsock.emit('connCount',connCount)\n console.log(connCount)\n}", "function numWorkers() { return workerIds().length }", "getRoom() {\n const id = this.roomName;\n\n if (!activeRooms.hasOwnProperty(id)) {\n throw new Error('Room requested does not exist: ' + id);\n }\n\n return activeRooms[id];\n }", "function getAllRooms(){\r\n roomsService.getAllRooms(\"now\").then(rooms => {\r\n vm.rooms = rooms;\r\n });\r\n }", "function remainingEnemy() {\n\n var noOfEnemy = 0;\n\n for (var i = 0; i < enemyList.length; i++) {\n if (enemyList[i].active) {\n noOfEnemy++;\n }\n }\n\n return noOfEnemy\n }", "function getAllRooms() {\n if (promisedRooms.data.success) {\n $scope.rooms = promisedRooms.data.rooms;\n } else {\n $scope.noRoomMessage = \"No rooms available. Create one.\";\n }\n }", "function countActiveNeighbours(game, cell) {\n var total = 0;\n iterateArray(neighbouringCells(cell), function countActiveNeighboursIterator(cell) {\n var id = cellId(cell);\n if (game.hasOwnProperty(id) && isActive(game[id])) {\n total += 1;\n }\n });\n return total;\n }", "async function getLodgingsCount() {\n const [ results ] = await mysqlPool.query(\n \"SELECT COUNT(*) AS count FROM lodgings\");\n console.log(\" -- results:\", results);\n return results[0].count;\n}" ]
[ "0.7090985", "0.6865184", "0.6586705", "0.65550524", "0.6523901", "0.6487544", "0.6442403", "0.63598233", "0.63311267", "0.6260583", "0.6251814", "0.61382014", "0.59974605", "0.598827", "0.59823996", "0.5964406", "0.59638923", "0.5648914", "0.5622821", "0.5615856", "0.5610976", "0.55607826", "0.5536519", "0.552736", "0.54480416", "0.54335296", "0.540742", "0.5392266", "0.5382688", "0.53546244" ]
0.73321277
0
Returns the room associated with the given room code.
getRoom(roomCode) { return this.rooms[roomCode]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getRoom(roomCode) {\n var ref = firebase.database().ref(\"Rooms/\" + roomCode);\n var room = $firebaseObject(ref);\n \n return room;\n }", "getRoom() {\n const id = this.roomName;\n\n if (!activeRooms.hasOwnProperty(id)) {\n throw new Error('Room requested does not exist: ' + id);\n }\n\n return activeRooms[id];\n }", "function getRoomNameFromId(roomcode) {\n var sResult = \"\";\n // Loop trough each room and check if we found an id that is equals to param roomcode\n $.each(rooms, function (i, room) {\n if (room.id === roomcode) {\n sResult = room.name; // Store the rooms name in sResult if we found its id that's equal to roomcode\n }\n });\n return sResult;\n}", "getRoom(roomId) {\r\n\t\treturn typeof this.rooms[roomId] === \"object\" ? this.rooms[roomId] : null;\r\n\t}", "_getRoomCodeFromSocket(socket) {\n if (socket && socket.rooms) {\n return socket.rooms[Object.keys(socket.rooms)[1]];\n }\n\n return undefined;\n }", "retrieve(room) {\n if (this._rooms[room]) {\n return this._rooms[room];\n } else {\n throw 'It appears you have made a mistake.';\n }\n }", "function getRoom(id){\n\tfor (var i=0; i<activeRooms.length;i++){\n\t\tif (activeRooms[i].num == id){\n\t\t\trm = {};\n\t\t\trm.room = activeRooms[i];\n\t\t\trm.index = i;\n\t\t\treturn rm;\n\t\t}\n\t}\n}", "function getRoom()\n {\n\n // console.log(\".. . .. . .. . \" + room);\n\n // if(room == undefined) ///eller === \n // {\n // return \"Sök sal...\";\n // }\n // else\n // {\n // return room; // eller toString(room);\n // }\n }", "function getRoom(slug) {\n\n const tempItem = [...data.rooms];\n\n const room = tempItem.find((room) => room.slug === slug);\n\n return room;\n\n }", "removeRoom(roomCode) {\n Logger.logInfo('Removing room: ' + roomCode);\n this.rooms[roomCode].forceEndGame();\n delete this.rooms[roomCode];\n }", "function getRoom(name=\"default\") {\n\tif (!rooms[name]) {\n\t\trooms[name] = {\n\t\t\tname: name,\n\t\t\tclients: {},\n\t\t}\n\t}\n\treturn rooms[name]\n}", "function getRoomById(id) {\n for (let i = 0; i < rooms.length; i++) {\n const room = rooms[i];\n if (room.id == id) {\n return room;\n }\n }\n return null;\n}", "ActiveRoom(){\r\n\t\tif(this.roomsMgr.RoomExists(this.activeRoom)){\r\n\t\t\treturn this.roomsMgr.Room(this.activeRoom);\r\n\t\t}\r\n\t\treturn this.roomsMgr.Room(SERVER_CH);\r\n\t}", "function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }", "static get(roomName) {\n\t\tif (!ROOMS.has(roomName)) {\n\t\t\tROOMS.set(roomName, new Room(roomName));\n\t\t}\n\n\t\treturn ROOMS.get(roomName);\n\t}", "function findGame(code) {\n\treturn games.filter((game)=>{return game.getCode() == code})[0]\n}", "getRoom() {\n var query = location.search && location.search.split(\"?\")[1];\n\n if (query) {\n return (location.search && decodeURIComponent(query.split(\"=\")[1]));\n }\n\n return \"no-id\"\n }", "function findRoom(msg) {\n var room = msg.envelope.room;\n\n if(_.isUndefined(room)) {\n room = msg.envelope.user.reply_to;\n }\n\n return room;\n }", "function deleteRoom(roomCode){\n let room = rooms[roomCode];\n if(room){\n let players = room.players;\n for(let i = 0; i < players.length; i++){\n let player = players[i];\n delete socks[player].room;\n }\n delete rooms[roomCode];\n }\n}", "getRoom (socketOrId) {\n\t\t\tif (typeof socketOrId == \"object\") {\n\t\t\t\treturn this.getByToken(socketOrId);\n\t\t\t} else if (typeof socketOrId == \"string\") {\n\t\t\t\treturn this.getById(socketOrId);\n\t\t\t}\n\t\t}", "function getRoom(room)\r\n{\r\n if (!(room in roomObj))\r\n {\r\n roomObj[room] = roomData.length;\r\n roomData.push([]);\r\n console.log(\"===> Room \" + room + \" created on \" + new Date());\r\n console.log(\"Current rooms:\" );\r\n console.log(roomObj);\r\n }\r\n return roomData[roomObj[room]];\r\n}", "function roomExists(code) {\r\n try {\r\n console.log(\"checking if room with code: \" + code + \" exists\");\r\n console.log(rooms[code]);\r\n if(code == null || code == undefined || typeof code != 'string' || !rooms[code]) {\r\n console.log(\"it's bad\");\r\n return false;\r\n }\r\n console.log(\"it's good\");\r\n return true;\r\n } catch(e) {\r\n console.error(e);\r\n return false;\r\n }\r\n}", "async function getRoom(req, res, next) {\n try {\n const room = await models.room.findById(req.params.roomId, {\n include: [models.instrument],\n });\n res.send(room);\n } catch (e) {\n next(e);\n }\n}", "getRoomId() {\n return this.roomId;\n }", "function getRoom(){\n\tvar chatName = document.getElementById(\"chatName\");\n\tif(!chatName)\n\t\treturn null;\n\treturn chatName.innerText;\n}", "function roomById (id) {\n var i;\n for (i = 0; i < rooms.length; i++) {\n if (rooms[i].roomid === id) {\n return rooms[i]\n }\n }\n\n return false\n}", "reserveNewRoom() {\n var newRoomCode;\n\n do {\n newRoomCode = Hasher.genHash(ROOM_CODE_LENGTH);\n } while(this.roomExists(newRoomCode));\n\n this.rooms[newRoomCode] = new Room(newRoomCode);\n return newRoomCode;\n }", "function genRoomCode() {\n const roomSeed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n rooms = io.sockets.adapter.rooms;\n let code\n do {\n code = ''\n for (var i = 0; i < 5; i++) {\n code += roomSeed[getRandomInt(roomSeed.length)]\n }\n // Keep generating new codes if the code is already in use\n } while (rooms[code])\n return code\n }", "function getObjectForRoom(currentRoom) {\n var objectInRoomIndex = -1;\n if (currentRoom === 0) {\n return objectInRoomIndex;\n }\n\n for (var i = 0; i < itemLocationRoomNumbers.length ; i++) {\n if (itemLocationRoomNumbers[i] == currentRoom) {\n objectInRoomIndex = i;\n break;\n }\n }\n return objectInRoomIndex;\n }", "function getRoom(request, response) {\n let roomName = request.params.roomName;\n // Chatroom.find({chatroom_name: roomName}, function (err, docs) {\n // if (err) {\n // console.log(err);\n // } else {\n // let roomId;\n // // If a chatroom with that name exists get it, else create one\n // if (docs.length > 0) {\n // roomId = docs[0].chatroom_id;\n // } else {\n // roomId = roomGenerator.roomIdGenerator()\n // const newChatroom = new Chatroom ({\n // chatroom_id: roomId,\n // chatroom_name: roomName\n // });\n\n // newChatroom\n // .save()\n // .then(item => console.log(item))\n // .catch(err => console.log(err));\n // }\n\n // TODO: Get the messages and submit to room.hbs\n Messages.find({ chatroom_name: roomName })\n .lean()\n .then((items) => {\n response.render(\"room\", {\n title: \"chatroom\",\n roomName,\n messages: items,\n isAvailable: true,\n // newRoomId: roomId\n });\n });\n}" ]
[ "0.81037015", "0.6867597", "0.68174833", "0.65568066", "0.6457666", "0.6432544", "0.63360745", "0.62797904", "0.62742895", "0.62188333", "0.6176027", "0.6173807", "0.61285734", "0.60923064", "0.60649204", "0.59586626", "0.59307027", "0.59038717", "0.58686805", "0.5835802", "0.5829127", "0.5779683", "0.5775277", "0.5754234", "0.5746747", "0.57307124", "0.56910527", "0.56763846", "0.56565875", "0.5649476" ]
0.83012074
0
Removes the Room associated with the given room code from the pool.
removeRoom(roomCode) { Logger.logInfo('Removing room: ' + roomCode); this.rooms[roomCode].forceEndGame(); delete this.rooms[roomCode]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteRoom(roomCode){\n let room = rooms[roomCode];\n if(room){\n let players = room.players;\n for(let i = 0; i < players.length; i++){\n let player = players[i];\n delete socks[player].room;\n }\n delete rooms[roomCode];\n }\n}", "function removeRoom(room) {\n\n // Get the room's ID\n var id = room.id || room;\n $('#room-' + id).remove();\n}", "leave(room) {\n \tdelete this.room[room];\n\t}", "function removeFromBuilding(kind,label,uniqueKeyOfRoom){\n roomsRegistry[label][kind][uniqueKeyOfRoom].clients = removeKey(roomsRegistry[label][kind][uniqueKeyOfRoom].clients,clientId)\n\n kind === 'full'? removeRoomFromFullAddToNotFull(label,uniqueKeyOfRoom) : leftRoom(uniqueKeyOfRoom,label)\n }", "leaveRoom()\n {\n this.setRoom(null);\n }", "function removeRoom(id) {\n\tvar room = ROOMS[id];\n\tif(room) {\n\t\tdelete ROOMS[id];\n\t\treturn true;\n\t}\n\treturn false;\n}", "function removeRoom(id) {\n\tvar room = ROOMS[id];\n\tif(room) {\n\t\tdelete ROOMS[id];\n\t\treturn true;\n\t}\n\treturn false;\n}", "getRoom(roomCode) {\n return this.rooms[roomCode];\n }", "async function delroom(id){\n if(id === undefined){\n throw 'input is empty';\n }\n if(id.constructor != ObjectID){\n if(ObjectID.isValid(id)){\n id = new ObjectID(id);\n }\n else{\n throw 'Id is invalid!(in data/room.delroom)'\n }\n }\n\n const roomCollections = await rooms();\n target = await this.getbyid(id);\n\n const delinfo = await roomCollections.removeOne({ _id: id });\n if(delinfo.deletedCount === 0) throw 'Can not delete id: ' + id;\n\n return target;\n}", "function removeQuestion(roomCode, question_id) {\n var ref = firebase.database().ref(\"Rooms/\" + roomCode + \"/Questions\");\n ref.child(question_id).remove();\n }", "function removeRoom(element){\n\n\t//Parse the room name out of the trash can span element.\n\tvar elementParts = element.id.split(':');\n\tvar elementName = elementParts[1];\n\t\n\t//Do not allow user to delete selected room.\n\tif(elementName == selectedRoom)\n\t\treturn;\n\t\t\n\t//Find the room list item and the br list item.\n\tvar listItem = document.getElementById(elementName);\n\tvar brItem = document.getElementById(\"br:\" + elementName);\n\t\n\t//Remove the trash can span, room list item, and br item associated with that room.\n\telement.parentNode.removeChild(element);\n\tlistItem.parentNode.removeChild(listItem);\n\tbrItem.parentNode.removeChild(brItem);\n\t\n\t//Delete the room from the rooms array.\n\tfor (i = 0; i < roomsArray.length; i++) {\n\n\t\tif(roomsArray[i] == elementName){\n\t\t\tdelete roomsArray[i];\n\t\t\treturn;\n\t\t}\n\t\n\t}\n}", "function deleteRoomList(data) {\r\n let n = roomsName.indexOf(data);\r\n roomsName.splice(n, 1);\r\n rooms.splice(n, 1);\r\n console.log(rooms);\r\n let room = select(`#${data}`);\r\n room.remove();\r\n}", "function removeRoom(){\n for (var roomNum=1; roomNum<=localStorage.getItem(\"roomNum\");roomNum++) {\n localStorage.removeItem(\"name\" + roomNum);\n localStorage.removeItem(\"roomType\" + roomNum);\n localStorage.removeItem(\"bathroomAccess\" + roomNum);\n localStorage.removeItem(\"bedType\" + roomNum);\n localStorage.removeItem(\"feature\" + roomNum);\n localStorage.removeItem(\"date\" + roomNum);\n localStorage.removeItem(\"minStay\" + roomNum);\n localStorage.removeItem(\"amount\" + roomNum);\n localStorage.removeItem(\"bond\" + roomNum);\n localStorage.removeItem(\"bills\" + roomNum);\n }\n localStorage.removeItem(\"roomNum\");\n\n }", "removeRoom(roomname, playerIDs, reason, roomType) {\n if (roomType === \"play\" || roomType === \"game_end\") {\n delete this.playrooms[roomname];\n delete this.map[roomname];\n }\n else if (roomType === \"wait\"){\n delete this.waitrooms[roomname];\n delete this.map[roomname];\n }\n delete this.cameras[roomname];\n playerIDs.forEach((playerID, index) => {\n this.sockets[playerID].emit(Constants.MSG_TYPES.GAME_OVER, reason[index]);\n this.removePlayer(this.sockets[playerID]);\n });\n }", "function RemoveGame(_RoomName) {\r\n //Update the Games array by filtering out the unwanted Game...\r\n _mData.Games = _mData.Games.filter(function(_Game){\r\n return _Game.RoomName !== _RoomName;\r\n });\r\n}", "reserveNewRoom() {\n var newRoomCode;\n\n do {\n newRoomCode = Hasher.genHash(ROOM_CODE_LENGTH);\n } while(this.roomExists(newRoomCode));\n\n this.rooms[newRoomCode] = new Room(newRoomCode);\n return newRoomCode;\n }", "function deletePersonFromRoom (room_name, id) {\n \tfor (var i=0; i<chatRooms.length; i++) {\n \t\tif (chatRooms[i]['roomname'] === room_name) {\n \t\t\tdelete chatRooms[i].people[id];\n \t\t}\n \t}\n }", "async unsubscribe (room) {\n await this.connecting()\n this.connection.client.send(JSON.stringify({\n action: 'UNSUBSCRIBE',\n room\n }))\n this.connection.subscriptions = this.connection.subscriptions.filter(s => s.room !== room)\n }", "function removeRoomFromFullAddToNotFull(label,uniqueKeyOfRoom){\n roomsRegistry[label].notFull[uniqueKeyOfRoom] = roomsRegistry[label].full[uniqueKeyOfRoom]\n roomsRegistry[label].full = removeKey(roomsRegistry[label].full,uniqueKeyOfRoom)\n leftRoom(uniqueKeyOfRoom,label)\n }", "clearRoomCode() {\r\n this.setState({\r\n roomCode: null\r\n });\r\n }", "function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }", "clearRoomCode() {\r\n this.setState({\r\n roomCode: null,\r\n });\r\n }", "socketsLeave(room) {\r\n this.adapter.delSockets({\r\n rooms: this.rooms,\r\n except: this.exceptRooms,\r\n }, Array.isArray(room) ? room : [room]);\r\n }", "remove(paladinID) {\n const palList = STATE.PaladinList.get();\n const index = palList.findIndex(pID => { return pID === paladinID; });\n if (index !== -1) {\n palList.splice(index, 1);\n STATE.PaladinList.set(palList);\n // // Remove the token's character's paladin abilities\n // const tokenObj = STATE.get('TokenList', paladinID) as TokenObj | undefined;\n // if (tokenObj !== undefined && tokenObj.characterID !== undefined) {\n // const abilities = findObjs({\n // _type: 'ability',\n // _characterid: paladinID,\n // }) as Ability[];\n // const abilitiesToRemove = abilities.filter(a => {\n // return Paladin.paladinAbilities().some(b => { return b[0] === a.get('name'); });\n // });\n // abilitiesToRemove.forEach(a => {\n // a.remove();\n // });\n // }\n }\n }", "function destroy(msg)\r\n{\r\n var thisData = getRoom(msg[\"room\"]);\r\n while (thisData.length) {\r\n\t\t thisData.pop();\r\n\t }\r\n delete roomObj[msg[\"room\"]];\r\n web.io.emit(\"servermessage\", {\r\n \"room\": msg[\"room\"],\r\n \"command\": \"destroy\"\r\n });\r\n}", "function getRoom(roomCode) {\n var ref = firebase.database().ref(\"Rooms/\" + roomCode);\n var room = $firebaseObject(ref);\n \n return room;\n }", "function detachPlayerFromRoom(request)\n {\n var diff_lvl = request.session.player.diff_lvl;\n var tag = request.session.player.player_tag;\n\n roomCount[diff_lvl]--;\n request.io.leave(diff_lvl);\n console.log('LEAVE [' + diff_lvl + '] (' + tag + '): roomCount=' + roomCount[diff_lvl] );\n \n if (roomCount[diff_lvl] > 0)\n {\n var player = { player_tag: tag };\n request.io.room('' + diff_lvl).broadcast('gamer_exited_room', player );\n console.log(\"BROADCAST [\" + diff_lvl + \"]: gamer_exited_room (\" + tag + \")\");\n }\n else\n {\n console.log(\"...not BROADCASTing, since room [\" + diff_lvl + \"] is empty\");\n }\n }", "function delete_private_room(room_name) {\n // will return -1 when user name not found\n const target_index = private_rooms.findIndex(room => room.name === room_name); \n if (target_index !== -1){\n // will get user out of the array\n return private_rooms.splice(target_index, 1);\n }; \n}", "removeClient(uid, reasonCode, data) {\n this.clients = this.clients.filter((_client) => {\n return _client.uid !== uid;\n });\n delete this.pendingStates[uid];\n if (reasonCode !== null && !(isNaN(reasonCode))) {\n if (!(index_1.LEAVE_AREA_CODE_LOOKUP[reasonCode])) {\n throw 'Invalid reason code provided to removeClient';\n }\n this._sendClientDisconnect(uid, reasonCode, data);\n }\n }", "function leaveRoom() {\n localStorage.removeItem(\"currentRoom\");\n setCurrentRoom(\"\");\n\n }" ]
[ "0.77561486", "0.68303543", "0.6174956", "0.5931559", "0.58749324", "0.58472323", "0.58472323", "0.57995254", "0.57529414", "0.57374996", "0.5692177", "0.5665478", "0.5627274", "0.5608368", "0.5488951", "0.54682386", "0.5447557", "0.5413424", "0.5396953", "0.5335224", "0.532391", "0.5317008", "0.53109443", "0.5309768", "0.5299999", "0.5254255", "0.5245356", "0.5228916", "0.5224259", "0.5199358" ]
0.83133036
0
Reserves a new room with a new, random, and unused room code. Returns the new room code.
reserveNewRoom() { var newRoomCode; do { newRoomCode = Hasher.genHash(ROOM_CODE_LENGTH); } while(this.roomExists(newRoomCode)); this.rooms[newRoomCode] = new Room(newRoomCode); return newRoomCode; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function genRoomCode() {\n const roomSeed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n rooms = io.sockets.adapter.rooms;\n let code\n do {\n code = ''\n for (var i = 0; i < 5; i++) {\n code += roomSeed[getRandomInt(roomSeed.length)]\n }\n // Keep generating new codes if the code is already in use\n } while (rooms[code])\n return code\n }", "function createRoom(){\n roomToken = random()\n roomsRegistry[roomLabel].notFull[roomToken] = {clients:[],limit:roomLimit}\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n }", "function makeRoomCode(){\n return Math.floor(Math.random() * 900000) + 100000;\n}", "function createNewRoom() {\n console.log(nextRoomId);\n createRoomDOM(nextRoomId);\n signalRoomCreated(nextRoomId);\n\n nextRoomId++;\n}", "function makeRoom(rooms, bet) {\n var newRoom = randRoom();\n let type = \"\";\n if (bet === 0) type = false;\n else type = true;\n console.log(bet);\n while (rooms.has(newRoom)) {\n newRoom = randRoom();\n }\n rooms.set(newRoom, { roomId: newRoom, players: [], board: null, bet: type });\n return newRoom;\n}", "function generateNewRoom(name) {\n\t\n\t//send the request to the server\n\tvar posting = $.post(roomsURI + \"/add\", {\n\t\tname : name\n\t});\n\t\n\t//Send new room to server\n\tposting.done(function(data) {\n\t\tvar room = JSON.parse(JSON.stringify(data));\n\t\t//$(\"#chat-rooms-list\").children(\"li[room_id!=2]\").remove(); //remove the last room\n\t\t//$(\"#chat-rooms-list\").append(createRoomElement(room)); //add this in it's place\n\t\t$(\"#chat-rooms-dropdown-list\").append(createRoomElement(room));\n\t\troom_id_list.push(room.roomID);\n\t\tjoinRoom(room.roomID,true);\n\t});\n}", "function createRoomCode() {\n var code = \"\";\n for(var i = 0; i < 4; i++) {\n var letter = String.fromCharCode(Math.random() * (26) + 65);\n code += letter;\n }\n //- console.log(code);\n return code;\n}", "add(room) {\n\tthis._rooms[room.identifier] = room;\n\treturn room;\n }", "function createNewRoom() {\r\n // Generate room id.\r\n const newID = uuidv4().substring(0, 8);\r\n\r\n // Join room\r\n socket.join(newID);\r\n\r\n // Update corressponding object in usersArray\r\n updateUserRoom(socket, newID);\r\n\r\n // Send room data to socket\r\n io.to(socket.id).emit(\"roomData\", {\r\n roomId: newID,\r\n });\r\n }", "function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }", "function generateRoomIdentifier() {\n // make a list of legal characters\n // we're intentionally excluding 0, O, I, and 1 for readability\n var chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';\n\n var result = '';\n for (var i = 0; i < 6; i++)\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n\n return result;\n}", "function generateRoomId(){\n let roomId = \"\";\n for(let i = 0; i < 4; i++){\n roomId += String.fromCharCode(_.random(65,90));\n }\n return roomId;\n }", "function createRoom() {\n db.Room.create({\n room_id: req.body.room_id,\n property_id: req.body.property_id,\n price: req.body.price,\n roomType: req.body.roomType,\n aboutRoom: req.body.aboutRoom,\n status: req.body.status,\n closeDate: req.body.closeDate,\n HotelId: thisId\n })\n .then(function() {\n res.send(\"/choice/\" + lastSegment);\n })\n .catch(function(err) {\n console.log(err);\n res.json(err);\n });\n }", "function makeRoomCode(length) {\n var result = '';\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n var charactersLength = characters.length;\n for ( var i = 0; i < length; i++ ) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n }", "generateRoomId() {\n\t\treturn `r${Date.now()}`;\n\t}", "function room(roomLetter,schedule)\n{\n this.letter = roomLetter;\n this.id=randomString(window.config.numberOfDigitsForRandomStrings,'aA#')+\"|room:\"+roomLetter;\n //store a reference to the schedule object in the room object so given any part of the turnoment hierarchy you can transverse to the top.\n this.schedule = schedule;\n this.rounds = [];\n}", "function newroom() {\n\t$(\"#warning2\").html(\"\");\n\tvar tmproomname = document.roomform.roomname.value;\n\tif (tmproomname.search(/[^a-zA-Z0-9]/) != -1 || tmproomname.length > 16) {\n\t\t$(\"#warning2\").html(\"Viallinen huoneen nimi.\");\n\t\treturn;\n\t}\n\tvar roomname = tmproomname;\n\tif (player != \"\" && passcode != \"\" && roomname != \"\") {\n\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=newroom&player=\" + player + \"&passcode=\" + passcode + \"&roomname=\" + roomname;\n\t\t$.ajax({\n\t\t\tcache: false,\n\t\t\tdataType : 'xml',\n\t\t\ttype : 'GET',\n\t\t\turl : geturl,\n\t\t\tsuccess : function(data) {\n\t\t\t\tstartRoom(data);\n\t\t\t},\n\t\t});\n\t}\n}", "function updateRoomCode(event) {\r\n setRoomCode(event.target.value);\r\n }", "getRoom(roomCode) {\n return this.rooms[roomCode];\n }", "newRoom(roomId) {\r\n\t\tlet room = new ServerRoom(roomId);\r\n\t\tthis.rooms[room.id] = room;\r\n\t\treturn room;\r\n\t}", "function addRoom(r){\n\tdb.run(`insert into rooms (name, type, access) values (?, ?, ?)`, [r.name, r.type, r.access], () => {\n\t\t_.each(r.ressources, (ressource_name) => addRoomResource(r.name, ressource_name));\n\t\t_.each(r.softwares, (software_name) => addRoomSoftware(r.name, software_name));\n\t\t_.each(r.timeslots, (ts) => addRoomTimeslot(r.name, ts));\n\t});\n}", "function newRoom() {\n socket.emit(\"newRoom\");\n}", "function CreateRandomRoom()\n{\n\n var FinalXWidth;\n var FinalyHeight;\n\n var finalX;\n var finalY;\n\n var dimensionsSet = false;\n\n var FinalRoom;\n\n // we want to continue generating dimensions until we find an acceptable one\n while (!dimensionsSet)\n {\n\n // get the random location\n var x = Math.floor(Math.random()*(gridWidth - maxRoomSpace) + 1);\n\n var y = Math.floor(Math.random()*(gridHeight - maxRoomSpace) + 1);\n\n\n // we need to find out how far the room is away from the edge of the map, in both x and y directions,\n // as there has to be at least 1 tile between the walls of the room and the edge of the map\n\n var maxXValue = gridWidth - x - 1;\n var maxYValue = gridHeight - y - 1;\n\n // check if there is enough room in the x and y directions to spawn a room.\n // we also want to make sure \n if ( maxXValue >= minRoomSpace && maxYValue >= minRoomSpace)\n {\n // there is enough space here to make a 'legal' room\n // make sure we don't go above the maximum height/width of a room\n if (maxXValue > maxRoomSpace)\n {\n maxXValue = maxRoomSpace;\n }\n\n if (maxYValue > maxRoomSpace)\n {\n maxYValue = maxRoomSpace;\n }\n\n\n // determine width and height\n var width = Math.floor(Math.random()*(maxXValue - minRoomSpace + 1) + minRoomSpace);\n var height = Math.floor(Math.random()*(maxYValue - minRoomSpace + 1) + minRoomSpace);\n\n // create the room an break out of the loop\n FinalRoom = new Room(x,y,width,height);\n\n dimensionsSet = true;\n\n }\n\n\n \n\n }\n // return it!\n return FinalRoom;\n \n}", "function createRoom(name)\n\t{\n\t\tdocument.getElementsByClassName('dropdown-item selected')[0].className = 'dropdown-item'\n\n\t\tvar room = document.createElement('div')\n\t\troom.className = 'dropdown-item selected'\n\t\troom.innerText = name\n\t\tcreateDropdownClickMethod(room)\n\t\tget('create-room-name').value = ''\n\n\t\tdropdown.appendChild(room)\n\t\tdropdown.className = 'dropdown closed'\n\t}", "removeRoom(roomCode) {\n Logger.logInfo('Removing room: ' + roomCode);\n this.rooms[roomCode].forceEndGame();\n delete this.rooms[roomCode];\n }", "function requestCreateRoom() {\r\n if (inputRoomName.value()) {\r\n socket.emit(\"createRoomRequest\", inputRoomName.value(), (response) => {\r\n if(!response){\r\n errorNameUsed(inputRoomName.value());\r\n } else{\r\n createUserRoom(inputRoomName.value());\r\n }\r\n });\r\n currentRoom = inputRoomName.value();\r\n }\r\n}", "function addRoom(id, type) {\n\tif(ROOMS[id]) return ROOMS[id];\n\tif(type == \"battle\") {\n\t\tROOMS[id] = new BattleRoom(id, send);\n\t\treturn ROOMS[id];\n\t} else {\n\t\tlogger.error(\"Unkown room type: \" + type);\n\t}\n}", "function createOrAddToRoom(){\n\n if(!socketClients[clientId]){\n\n //if user does not exist\n return getUserData( msg.cookie ).then(function(userObject,error){//what if cookie is invalid\n if (error) return sendError('invalid cookie')\n socketClients[clientId] = {user:{id:userObject.id, username:userObject.username}, socket:ws}\n\n createOrAddToRoom()\n })\n\n \n }\n\n //also broadcast on join and leave and also joined member\n // console.log(clientId,'creating room or adding:'+roomLabel)\n function createRoom(){\n roomToken = random()\n roomsRegistry[roomLabel].notFull[roomToken] = {clients:[],limit:roomLimit}\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n }\n\n if (!roomsRegistry[roomLabel]){ //room not constructed \n roomsRegistry[roomLabel] = { full:{},notFull:{} }\n createRoom()\n }else{\n\n if ( Object.keys(roomsRegistry[roomLabel].notFull).length === 0 ) {\n createRoom()\n }else{\n\n roomToken = Object.keys(roomsRegistry[roomLabel].notFull)[0]\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n broadcast(roomToken,socketClients[clientId].user,'onjoin',roomLabel)\n\n let notFullRoomLimit = roomsRegistry[roomLabel].notFull[roomToken].limit\n let membersCountOfNotFull = roomsRegistry[roomLabel].notFull[roomToken].clients.length\n\n \n\n // if(membersCountOfNotFull > notFullRoomLimit) console.log('limit exceeded', membersCountOfNotFull, notFullRoomLimit)\n\n if(membersCountOfNotFull === notFullRoomLimit){\n roomsRegistry[roomLabel].full[roomToken] = roomsRegistry[roomLabel].notFull[roomToken]\n roomsRegistry[roomLabel].notFull = removeKey(roomsRegistry[roomLabel].notFull,roomToken)\n }\n\n }\n\n }\n\n broadcast(roomToken,null,'onopen',roomLabel)\n\n }", "function fillroom(what, arg) {\n var safe = 100;\n var x = rnd(MAXX - 2);\n var y = rnd(MAXY - 2);\n while (!itemAt(x, y).matches(OEMPTY)) {\n x += rnd(3) - 2;\n y += rnd(3) - 2;\n if (x > MAXX - 2) x = 1;\n if (x < 1) x = MAXX - 2;\n if (y > MAXY - 2) y = 1;\n if (y < 1) y = MAXY - 2;\n if (safe-- == 0) {\n debug(`fillroom: SAFETY!`);\n break;\n }\n }\n var newItem = createObject(what, arg);\n setItem(x, y, newItem);\n return newItem;\n //debug(`fillroom(): ${newItem}`);\n}", "function add_room(creator, name){\n const room = {creator, name};\n // save room info to room list\n rooms.push(room);\n}" ]
[ "0.6878282", "0.65021133", "0.6363232", "0.63338953", "0.6167534", "0.6124831", "0.6070692", "0.59665966", "0.5927118", "0.590617", "0.5899809", "0.58489764", "0.5801537", "0.57892317", "0.5769441", "0.57183534", "0.57066935", "0.5628291", "0.55877244", "0.55680364", "0.5556477", "0.5538754", "0.55283713", "0.55170107", "0.55087054", "0.55022717", "0.54560024", "0.5450911", "0.54415774", "0.54366046" ]
0.85030913
0
Returns whether a room exists for the given room code.
roomExists(roomCode) { return this.rooms.hasOwnProperty(roomCode); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function roomExists(code) {\r\n try {\r\n console.log(\"checking if room with code: \" + code + \" exists\");\r\n console.log(rooms[code]);\r\n if(code == null || code == undefined || typeof code != 'string' || !rooms[code]) {\r\n console.log(\"it's bad\");\r\n return false;\r\n }\r\n console.log(\"it's good\");\r\n return true;\r\n } catch(e) {\r\n console.error(e);\r\n return false;\r\n }\r\n}", "function roomExists(roomName){\r\n var result = true;\r\n return false; // temporary debugging\r\n /*Rooms.count(\r\n {\"roomName\":roomName},\r\n function(err,count){\r\n if(err) throw err\r\n result = (count > 0);\r\n }\r\n )\r\n return result;*/\r\n}", "function inRoom(roomId) {\n return $(\"#room-\" + roomId).length > 0;\n }", "function containsRoom (roomName) {\n \treturn _.contains(_.map(chatRooms, function(item) {\n\t\t\t\treturn item['roomname'];\n\t\t\t}), roomName);\n }", "function isRoomToBeShown(roomcode) {\n var sValue = false;\n // If device don't have room, it's returning \"0\" or undefined\n if ((roomcode === \"0\") || (roomcode === undefined)) {\n // then we get the true / false value from showroomless devices\n sValue = showRoomLess;\n } else {\n // else, we check if that room is checkedor not\n sValue = appData.values[\"settings-room-\" + roomcode];\n }\n\n return sValue;\n}", "getRoom(roomCode) {\n return this.rooms[roomCode];\n }", "function isRoomValid(data) {\n var room = data.message.text;\n var id = data.message.chat.id;\n var user = userExists(id);\n \n if (Object.getOwnPropertyNames(user).length === 0) {\n var sheet = SpreadsheetApp.openById(userSheetId).getSheetByName('Zones');\n \n var searchRange = sheet.getRange(1, 1, 405, 2);\n var rangeValues = searchRange.getValues();\n \n for (j = 0; j < 405; j++) {\n if (rangeValues[j][0] === room) {\n return true;\n }\n }\n }\n return false;\n }", "function objectExistsInRoomNumber(roomIndex) {\n // First thing first, check if this room even has an item\n var objectInRoomIndex = getObjectForRoom(roomIndex);\n if (objectInRoomIndex == -1) {\n return false;\n }\n\n // Now check in the item list that this number is not 999 (OUR EDGE case for items out of play).\n return itemLocationRoomNumbers[objectInRoomIndex] != 999;\n }", "function roomById (id) {\n var i;\n for (i = 0; i < rooms.length; i++) {\n if (rooms[i].roomid === id) {\n return rooms[i]\n }\n }\n\n return false\n}", "function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }", "async function existsRooms(){\n\tvar exists = false;\n\tawait Promise.resolve(axios.get(host)\n\t.then(async function(response){\n\t\tif(response.data>0){\n\t\t\texists = true;\n\t\t}\n\t}));\n\treturn exists;\n}", "function getRoom(roomCode) {\n var ref = firebase.database().ref(\"Rooms/\" + roomCode);\n var room = $firebaseObject(ref);\n \n return room;\n }", "_addPlayerToRoom(socket, username, roomCode) {\n if (!this.roomExists(roomCode)) {\n return false;\n }\n\n return this.rooms[roomCode].addPlayer(socket, username);\n }", "is_available()\n\t{\n\t\treturn _.isObject(this.room)\n\t}", "function checkRoom(room,res){\n\tconsole.log(\"checking room: \",room);\n const query = datastore.createQuery(room);//.filter('name','=','peer_ids');\n datastore.runQuery(query)\n .then((results) => {\n // console.log(\"checkRoom result: \",results[0]);\n\n if(results[0].length>0){\n\t\t\tconsole.log(\"room exist\");\n res.send(JSON.stringify({result:\"true\"}));}\n// console.log(\"true\");\n else{\n\t\t\tconsole.log(\"room doesn't exist\");\n res.send(JSON.stringify({result:\"false\"}));}\n// console.log(\"false\");\n\n })\n .catch((err) => {\n console.error('ERROR:', err);\n });\n}", "getRoom() {\n const id = this.roomName;\n\n if (!activeRooms.hasOwnProperty(id)) {\n throw new Error('Room requested does not exist: ' + id);\n }\n\n return activeRooms[id];\n }", "function getRoomNameFromId(roomcode) {\n var sResult = \"\";\n // Loop trough each room and check if we found an id that is equals to param roomcode\n $.each(rooms, function (i, room) {\n if (room.id === roomcode) {\n sResult = room.name; // Store the rooms name in sResult if we found its id that's equal to roomcode\n }\n });\n return sResult;\n}", "function inside(socket, room) {\n return !!socket.manager.roomClients[socket.id][room];\n }", "function ownsRoom(user) {\n lunchrooms.forEach(function(room) {\n if (room['creator'] === user) {\n return true;\n }\n });\n return false;\n}", "inRoom(idPlayer){\n return bdConf.searchRoomWithPlayer(idPlayer)\n }", "function my_rooms(s){\n return s && s.pos && tables.my_rooms().indexOf(s.pos.roomName) !== -1;\n}", "function isAddRoomValid(){\r\n return(RoomNumberField.isValid() && RoomValidFromField.isValid());\r\n }", "removeRoom(roomCode) {\n Logger.logInfo('Removing room: ' + roomCode);\n this.rooms[roomCode].forceEndGame();\n delete this.rooms[roomCode];\n }", "reserveNewRoom() {\n var newRoomCode;\n\n do {\n newRoomCode = Hasher.genHash(ROOM_CODE_LENGTH);\n } while(this.roomExists(newRoomCode));\n\n this.rooms[newRoomCode] = new Room(newRoomCode);\n return newRoomCode;\n }", "addRoom(name, author, author_id) {\n\n \t// check is the room name is't exist\n \tvar x = this.getRoomByName(name);\n \tif (x) {\n \t\treturn false ;\n \t}\n var id = uniqid();\n var room = {\n id : uniqid(),\n author : author,\n name : name,\n author_id: author_id\n };\n this.rooms.push(room);\n return true;\n }", "ActiveRoom(){\r\n\t\tif(this.roomsMgr.RoomExists(this.activeRoom)){\r\n\t\t\treturn this.roomsMgr.Room(this.activeRoom);\r\n\t\t}\r\n\t\treturn this.roomsMgr.Room(SERVER_CH);\r\n\t}", "function removeRoom(id) {\n\tvar room = ROOMS[id];\n\tif(room) {\n\t\tdelete ROOMS[id];\n\t\treturn true;\n\t}\n\treturn false;\n}", "function removeRoom(id) {\n\tvar room = ROOMS[id];\n\tif(room) {\n\t\tdelete ROOMS[id];\n\t\treturn true;\n\t}\n\treturn false;\n}", "function getRoom()\n {\n\n // console.log(\".. . .. . .. . \" + room);\n\n // if(room == undefined) ///eller === \n // {\n // return \"Sök sal...\";\n // }\n // else\n // {\n // return room; // eller toString(room);\n // }\n }", "isRoomEnterable() {\n\n const isSelfInRoom = () => {\n\n if (this.selfSkylinkId === null) return false;\n\n for (let user of this.props.users)\n {\n if (user.skylinkId == this.selfSkylinkId) return true;\n }\n\n return false;\n };\n\n return !(this.props.room.status == Constants.RoomState.LOCKED)\n || isSelfInRoom();\n }" ]
[ "0.8155792", "0.6707367", "0.66065294", "0.6592731", "0.6389099", "0.6184209", "0.61693615", "0.61344033", "0.59396476", "0.58948386", "0.58383", "0.57602453", "0.57387096", "0.56388247", "0.5636944", "0.5549528", "0.5495908", "0.5493824", "0.54198974", "0.53347903", "0.5325483", "0.5303944", "0.5302856", "0.5302638", "0.52656937", "0.5258293", "0.51645404", "0.51645404", "0.5105315", "0.50894266" ]
0.8139524
1
SOCKET LISTENERS Attempts to end a game for the Room associated with the given socket.
hostAttemptEndGame(socket, data) { Logger.logInfo('Socket ' + socket.id + ' attempting to end game'); var roomCode = this._getRoomCodeFromSocket(socket); if (this.roomExists(roomCode)) { var room = this.getRoom(roomCode); if (room.attemptEndGame(socket)) { Logger.logInfo('Game at room ' + roomCode + ' ended'); room.playerMap.emitCustomToAll('hostEndGameSuccess', (socket) => { return { thisClientIsHost: room.socketIsHost(socket) } }); room.playerMap.emitCustomToAll('updateLobby', (socket) => { return room.getLobbyData(socket); }); } else { Logger.logWarning('Socket ' + socket.id + ' failed to end game'); socket.emit('hostEndGameFailure', { reason: 'room.attemptEndGame() failed' }); } } else { Logger.logWarning('Socket ' + socket.id + ' failed to end game'); socket.emit('hostEndGameFailure', { reason: 'Room does not exist' }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static onSocketDisconnect(socket) {\n Object.keys(socket.rooms).forEach(room => {\n try {\n if (rooms.isRoomExists(room)) {\n if (rooms.getRoomPlayersCount(room) === 1) {\n rooms.removeRoom(room);\n } else {\n rooms.getRoom(room).removePlayer(socket.id);\n rooms.getRoom(room).resetPlayersActions();\n rooms.getRoom(room).resetWinner();\n }\n }\n } catch (error) {\n console.log('' + error);\n }\n\n io.to(room).emit('opponentLeave');\n })\n }", "socketsLeave(room) {\r\n this.adapter.delSockets({\r\n rooms: this.rooms,\r\n except: this.exceptRooms,\r\n }, Array.isArray(room) ? room : [room]);\r\n }", "playerAttemptLeaveRoom(socket, data) {\n Logger.logInfo('socket ' + socket.id + ' disconnecting...');\n var roomCode = this._getRoomCodeFromSocket(socket);\n\n if (this.roomExists(roomCode)) {\n this.getRoom(roomCode).disconnectPlayer(socket);\n socket.leave(roomCode, () => {\n socket.emit('playerLeaveRoomSuccess', {});\n });\n this.getRoom(roomCode).playerMap.emitCustomToAll('updateLobby', (socket) => {\n return this.getRoom(roomCode).getLobbyData(socket);\n });\n } else {\n socket.emit('playerLeaveRoomFailure', {\n reason: 'Room does not exist'\n });\n return;\n }\n\n if (this.getRoom(roomCode).socketsEmpty()) {\n this.removeRoom(roomCode);\n }\n }", "function leaveGames(socket) {\r\n var player = players[socket.id];\r\n for (var [gameId, game] of games) {\r\n game.removePlayer(player);\r\n // Remove the player from the room.\r\n if (socket) socket.leave('game ' + game.id);\r\n\r\n if (game.numPlayers() === 0 || socket.id === game.id) {\r\n games.delete(socket.id);\r\n }\r\n }\r\n}", "endGame(socket) {\n if (this.socketIsHost(socket) && this.gameState > LOBBY) {\n this.resetPlayers();\n this.gameState = LOBBY;\n return this.clientsUpdate();\n }\n return false;\n }", "attemptEndGame(socket) {\n if (this.socketIsHost(socket) && this.gameServer.isInGame()) {\n this.gameServer.endGame();\n return true;\n }\n\n return false;\n }", "finishgame(myId, roomId) {\n this.socket.emit(\"finishgame\", myId, roomId);\n }", "listenEndGame(op,room){\n socket.on(\"end-GamePb\",function (data) {\n if(data.room===room){\n op();\n }\n })\n }", "endForOnePlayer(player, room){\n socket.emit(\"end-pb-player\", {player : player, room : room});\n }", "socketsJoin(room) {\r\n this.adapter.addSockets({\r\n rooms: this.rooms,\r\n except: this.exceptRooms,\r\n }, Array.isArray(room) ? room : [room]);\r\n }", "function callEndSocketGame() {\r\n\tconsole.log(\"Peticion End Sala # \" + GAME_PORT + \" # \" + ROOM_ID);\r\n\t\r\n\tvar ab = str2ab(END_SESSION + \";\" + APP_ID + \";\" + ROOM_ID + \";\" + USER_ID);\r\n\tgameSocketUdp.write(gameSocks.socketId, ab, writeSocketGameComplete);\t\t\r\n\tt = setTimeout(function() {\t\r\n\t\tif(!controlEndSala){\t\r\n\t\t\tcallEndSocketGame();\r\n\t\t}\r\n\t}, limitLatencyToEnd);\t\t\r\n}", "destroy() {\n\t\tfor ( const socket of this._socketServer.getSocketsInRoom( this.id ) ) {\n\t\t\tsocket.disconnect();\n\t\t}\n\n\t\tif ( this.player ) {\n\t\t\tthis.player.destroy();\n\t\t}\n\n\t\tif ( this.opponent ) {\n\t\t\tthis.opponent.destroy();\n\t\t}\n\n\t\tthis.stopListening();\n\t}", "function on_socket_end() {\n if (!this.writable && this.destroyed === false) {\n this.destroy();\n had_error(new Error('Remote end closed socket abruptly.'))\n }\n }", "function close(socket) {\n // Free the IP\n let n = connectedIPs.findIndex(w => { return w.ip === socket.ip; });\n if (n !== -1) {\n util.log(socket.ip + \" disconnected.\");\n util.remove(connectedIPs, n);\n }\n // Free the token\n if (socket.key != '') { \n keys.push(socket.key);\n util.log(\"Token freed.\");\n } \n // Figure out who the player was\n let player = socket.player,\n index = players.indexOf(player);\n // Remove the player if one was created\n if (index != -1) {\n // Kill the body if it exists\n if (player.body != null) {\n player.body.invuln = false;\n setTimeout(() => {\n player.body.kill();\n }, 10000);\n }\n // Disconnect everything\n util.log('[INFO] User ' + player.name + ' disconnected!');\n util.remove(players, index);\n } else {\n util.log('[INFO] A player disconnected before entering the game.');\n }\n // Free the view\n util.remove(views, views.indexOf(socket.view));\n // Remove the socket\n util.remove(clients, clients.indexOf(socket)); \n util.log('[INFO] Socket closed. Views: ' + views.length + '. Clients: ' + clients.length + '.');\n }", "function joinRandomRoom() {\r\n socket.emit(\"joinRandomRoom\");\r\n}", "function socketListeners(){\n\tsocket.on('joined',function(){\n\t\tuser.success();\n\t});\n\tsocket.on('exists',function(err){\n\t\tuser.error(err);\n\t});\n\tsocket.on('roomList',function(roomlist){\n\t\tchatRoom.populate(roomlist);\n\t});\n}", "function handleRoomJoining(socket) {\n socket.on('join', function(room) {\n socket.leave(currentRoom[socket.id]);\n joinRoom(socket, room.newRoom);\n });\n}", "function on_socket_end() {\n if (returned && !this.writable && this.destroyed === false) {\n this.destroy();\n had_error(new Error('Remote end closed socket abruptly.'))\n }\n }", "function Disconnect(socket) {\n players--;\n console.log(\"Disconnected: \" + socket.id);\n for (let i = 0; i < player_id.length; i++) {\n if (player_id[i] === socket.id) {\n socket.broadcast.emit('left', player_id[i]);\n player_id.splice(i, 1);\n break;\n }\n }\n\n}", "removePlayer(socket) {\n const isPlayer = this.players[socket.id] !== undefined\n const isSpectator = this.spectators[socket.id] !== undefined\n const isHost = this.host.data.id === socket.data.id;\n if (isPlayer) { // we might need to swap people in\n delete this.players[socket.id]\n const newPlayer = this.upgradeSpectator()\n // if ingame, then let's see how to modify the player\n if (this.state === ROOM_INGAME) {\n // if we have a player, then let's swap them\n if (newPlayer !== undefined) {\n this.game.swapPlayers(socket, newPlayer)\n } else { // else, just remove and let game use AI\n this.game.removePlayer(socket)\n }\n }\n // if host is leaving, we need to fix that too\n if (isHost) {\n this.upgradeHost();\n }\n } else if (isSpectator) { // don't care about these guys\n delete this.spectators[socket.id]\n }\n socket.leave(this.uniqueName)\n socket.join('lobby')\n delete socket.data.room\n delete socket.data.timeJoinedRoom\n // tell everyone else that room has changed\n socket.to(this.uniqueName).emit('room_player_update', this.playerInfo())\n io.to('lobby').emit('lobby_room_update', this.basicInfo())\n return Object.keys(this.players).length === 0\n }", "static onSocketJoined(roomID) {\n if (rooms.getRoomPlayersCount(roomID) == 2) {\n rooms.getRoom(roomID).resetPlayersScore();\n io.to(roomID).emit('startGame', {\n id: rooms.getRoom(roomID).getID(),\n winner: rooms.getRoom(roomID).getWinner(),\n players: rooms.getRoom(roomID).getPlayers()\n });\n }\n }", "static onSocketReady(socket) {\n Object.keys(socket.rooms).forEach(room => {\n if (rooms.isRoomExists(room)) {\n if (rooms.getRoomPlayersCount(room) > 1) {\n rooms.getRoom(room).setPlayerReady(socket.id);\n\n let readyPlayers = 0;\n\n rooms.getRoom(room).getPlayers().forEach(player => {\n if (player.ready) {\n readyPlayers++;\n }\n })\n\n if (readyPlayers === 2) {\n rooms.getRoom(room).resetPlayersActions();\n rooms.getRoom(room).resetPlayersReady();\n\n io.to(room).emit('startGame', {\n id: rooms.getRoom(room).getID(),\n winner: rooms.getRoom(room).getWinner(),\n players: rooms.getRoom(room).getPlayers()\n });\n }\n }\n }\n })\n }", "function GameSocketServer(io, debug) {\n io.on('connection', socket => {\n\n if (debug) console.log(`Client joined! id: ${socket.id}`)\n\n // Triggered on room creation or joining\n socket.on('room', (username, userType, roomCode) => {\n\n // Set socket info\n socket.username = username\n socket.userType = userType\n\n const rooms = io.sockets.adapter.rooms\n\n if (socket.userType === 'player') {\n if (debug) console.log(`Player ${socket.username} wants to join a room.`)\n\n if (rooms[roomCode]) {\n // If the room exists\n if (debug) console.log(`Player ${socket.username} joined a room. code: ${roomCode}`)\n joinOrCreateRoom(roomCode)\n } else {\n // If the room does not exist\n if (debug) console.log(`Player ${socket.username} requested a non-existent room.`)\n socket.emit('no_room', 'Room does not exist.')\n }\n } else if (socket.userType === 'gm') {\n if (debug) console.log(`GM ${socket.username} requested a room.`)\n if (!rooms[roomCode]) {\n // If the room does not exist already, generate a new code\n // This prevents GMs from setting their own room code\n roomCode = genRoomCode()\n if (debug) console.log(`GM ${socket.username} created a room. code: ${roomCode}`)\n } else {\n // If the room exists already, don't set a new code, so they just join the room\n if (debug) console.log(`GM ${socket.username} joined a room. code: ${roomCode}`)\n }\n joinOrCreateRoom(roomCode)\n } else {\n // If anything other than the right user types were set\n socket.userType = 'player'\n socket.emit('error', 'Invalid user type.')\n }\n })\n\n // Short hand callback for broadcasting new stores\n socket.on('broadcast_stores', broadcastStores)\n\n // Short hand callback for broadcasting clear stores message\n socket.on('clear_stores', clearStores)\n\n // Sometimes the socket is undefined on improper disconnection\n socket.on('disconnect', reason => {\n if (socket) {\n updateGMRoomMembers()\n }\n const name = socket.username || \"Someone\"\n if (debug) console.log(`${name} disconnected: ${reason}`)\n })\n\n // Sends room members in a callback\n function getRoomMembers(cb) {\n // Get all room members\n io.of('/').in(socket.roomCode).clients((error, clients) => {\n if (error) throw error\n // Create empty room\n const roomPkg = [],\n connected = io.sockets.connected\n for (let id of clients) {\n // Get each socket by id\n const client = connected[id]\n // Push the socket info into the room\n roomPkg.push({\n id: id,\n username: client.username,\n userType: client.userType\n })\n }\n cb(roomPkg)\n })\n }\n\n // Sends a GM the current room member information\n function updateGMRoomMembers() {\n getRoomMembers(members => {\n for (let member of members) {\n // Find the GM\n if (member.userType === 'gm') {\n // Send them the members\n io.to(member.id).emit('room_members', members)\n return\n }\n }\n })\n }\n\n // Sends store information to all selected recipients\n function broadcastStores(stores, recipients) {\n if (debug) {\n console.log(\"Sending stores:\")\n console.log(stores)\n console.log(\"To:\")\n console.log(recipients)\n }\n for (var i = 0; i < recipients.length; i++) {\n io.to(recipients[i]).emit('new_stores', stores)\n }\n }\n\n // Sends a clear stores message to selected recipients\n // If none are provided, it sends the message to whole room\n function clearStores(recipients) {\n if (!recipients.length) {\n getRoomMembers(members => {\n sendClearStoresMessage(members)\n })\n } else {\n sendClearStoresMessage(recipients)\n }\n }\n\n // Helper function\n function sendClearStoresMessage(recipients) {\n for (var i = 0; i < recipients.length; i++) {\n io.to(recipients[i].id).emit('clear_stores')\n }\n }\n\n // Adds the socket to a room if it exists, or creates and then adds if it doesn't\n function joinOrCreateRoom(roomCode) {\n socket.join(roomCode, () => {\n // Sets the socket's room code\n socket.roomCode = roomCode\n // Sends room code to client\n socket.emit('room_joined', roomCode)\n // Updates GM's player list\n updateGMRoomMembers()\n })\n }\n\n // Generates a 5 character room code\n function genRoomCode() {\n const roomSeed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n rooms = io.sockets.adapter.rooms;\n let code\n do {\n code = ''\n for (var i = 0; i < 5; i++) {\n code += roomSeed[getRandomInt(roomSeed.length)]\n }\n // Keep generating new codes if the code is already in use\n } while (rooms[code])\n return code\n }\n\n // Helper function\n function getRandomInt(upperBound) {\n return Math.floor(Math.random() * upperBound)\n }\n\n })\n}", "function endTimer(socket){\n var temps = 0;\n temps = Math.floor(timer / 60);\n if (temps == (timeRound * 2)){ // envoi le winner\n findWinner(function(data){\n socket.emit('Winner',data);\n socket.broadcast.emit('Winner',data);\n });\n clean();\n console.log(\"end of game\");\n\n clearInterval(interval);\n timer = 0;\n nbPlayers = 0;\n }\n}", "function joinRoom(userSocket, partnerSocket, allSockets, callback){\n // create room with socket id\n var room = userSocket.id.substring(2);\n userSocket.join(room);\n partnerSocket.join(room);\n\n // attach room name with sockets\n\n userSocket.room = room;\n partnerSocket.room = room;\n\n // remove sockets from array\n var connectedSockets = [];\n connectedSockets.push(userSocket);\n connectedSockets.push(partnerSocket);\n for(var i = 0; i<allSockets.length;i++){\n var j = allSockets.indexOf(userSocket);\n if (i === -1){}\n else{allSockets.splice(i, 1)};\n }\n for(var i = 0; i<allSockets.length;i++){\n var j = allSockets.indexOf(partnerSocket);\n if (i === -1){}\n else{allSockets.splice(i, 1)};\n }\n callback(null,'success'); \n}", "function sendToServer_wantnext() {\r\n socket.emit('clientend', {\r\n 'room': ROOM_ID\r\n });\r\n}", "function connectToRoom(ws,req){ // socket connection for rooms\n\n var clientId = random()\n\n function leftRoom(room,key){\n broadcast(room,socketClients[clientId].user,'onleave',key)\n }\n\n ws.on('close', function(req){\n \n //to do if user doesnot exist fallback, broadcast a leave message, on error\n //to remember: remove key can handle both array and object\n\n\n\n\n for (let key in roomsRegistry){\n\n for (let room in roomsRegistry[key].full){\n\n //remove client from full instance, remove instance from full and and add it not full\n\n if ( roomsRegistry[key].full[room].clients.includes(clientId ) ){\n\n removeFromBuilding('full',key,room)\n //because currently room is full if anyone leaves the room it will become empty\n\n\n }else{\n // console.log( roomsRegistry[key].full[room].clients[clientId] )\n }\n\n }\n\n \n for (let room in roomsRegistry[key].notFull){\n\n if ( roomsRegistry[key].notFull[room].clients.includes( clientId) ) {\n removeFromBuilding('notFull',key,room)\n }\n }\n\n }\n\n socketClients = removeKey(socketClients,clientId)\n\n })\n\n //remove user from all the room\n function removeRoomFromFullAddToNotFull(label,uniqueKeyOfRoom){\n roomsRegistry[label].notFull[uniqueKeyOfRoom] = roomsRegistry[label].full[uniqueKeyOfRoom]\n roomsRegistry[label].full = removeKey(roomsRegistry[label].full,uniqueKeyOfRoom)\n leftRoom(uniqueKeyOfRoom,label)\n }\n\n //there are two kinds of room in the building full and notFull\n function removeFromBuilding(kind,label,uniqueKeyOfRoom){\n roomsRegistry[label][kind][uniqueKeyOfRoom].clients = removeKey(roomsRegistry[label][kind][uniqueKeyOfRoom].clients,clientId)\n\n kind === 'full'? removeRoomFromFullAddToNotFull(label,uniqueKeyOfRoom) : leftRoom(uniqueKeyOfRoom,label)\n }\n\n function leaveRoom(label,uniqueKeyOfRoom,newRoom){\n\n if (!roomsRegistry[label]) {\n return sendError(label+' label is invalid',newRoom)\n }\n\n if (roomsRegistry[label].full[uniqueKeyOfRoom]){\n removeFromBuilding('full',label,uniqueKeyOfRoom)\n }else if(roomsRegistry[label].notFull[uniqueKeyOfRoom]){\n removeFromBuilding('notFull',label,uniqueKeyOfRoom)\n }\n\n }\n\n function sendError(errorMessage,label){\n ws.send( stringIt({type:'onerror', data:errorMessage, token:label}) )\n }\n //type getRoomToken\n // to do solve conflict of name query socket connection\n //limit defined by user\n ws.on('message', function(msg){\n\n\n msg = JSON.parse(msg)\n let roomLimit = 2\n // let roomId = msg.token\n let roomLabel = msg.app+'_'+msg.token //msg token is hotel name\n let roomToken = null\n if (msg.broadcastToken) roomToken = msg.broadcastToken \n if (msg.limit) if(msg.limit >= 2) roomLimit = msg.limit\n\n //what if where is not defined in update\n\n //the update function does not gives the update doc?\n\n //user can connect to multiple rooms the front end functions are mapped to \n if (msg.purpose == 'join'){\n createOrAddToRoom()\n }else if(msg.purpose == 'broadcast'){\n // console.log('broadcasting')\n broadcast(roomToken,msg.content,'ondata',roomLabel)\n }else if(msg.purpose == 'change_room'){\n\n\n\n\n //to do save from crash not defineed\n if (!msg.currentRoomLabel || !msg.unique || !msg.newToken) return sendError('required values missing')\n leaveRoom(msg.app+'_'+msg.currentRoomLabel, msg.unique, msg.newToken)\n\n // console.log('leaving room',msg.currentRoomLabel,'unique',msg.unique)\n roomLabel = msg.app+'_'+msg.newToken\n createOrAddToRoom()\n\n }else if(msg.purpose == 'leave'){\n\n if (!msg.currentToken || !msg.unique ) return sendError('required values missing')\n\n leaveRoom(msg.app+'_'+msg.currentToken,msg.unique )\n }\n\n\n \n\n //why one to one does not exist? because it can be created with room with limit 2\n\n function createOrAddToRoom(){\n\n if(!socketClients[clientId]){\n\n //if user does not exist\n return getUserData( msg.cookie ).then(function(userObject,error){//what if cookie is invalid\n if (error) return sendError('invalid cookie')\n socketClients[clientId] = {user:{id:userObject.id, username:userObject.username}, socket:ws}\n\n createOrAddToRoom()\n })\n\n \n }\n\n //also broadcast on join and leave and also joined member\n // console.log(clientId,'creating room or adding:'+roomLabel)\n function createRoom(){\n roomToken = random()\n roomsRegistry[roomLabel].notFull[roomToken] = {clients:[],limit:roomLimit}\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n }\n\n if (!roomsRegistry[roomLabel]){ //room not constructed \n roomsRegistry[roomLabel] = { full:{},notFull:{} }\n createRoom()\n }else{\n\n if ( Object.keys(roomsRegistry[roomLabel].notFull).length === 0 ) {\n createRoom()\n }else{\n\n roomToken = Object.keys(roomsRegistry[roomLabel].notFull)[0]\n roomsRegistry[roomLabel].notFull[roomToken].clients.push(clientId)\n broadcast(roomToken,socketClients[clientId].user,'onjoin',roomLabel)\n\n let notFullRoomLimit = roomsRegistry[roomLabel].notFull[roomToken].limit\n let membersCountOfNotFull = roomsRegistry[roomLabel].notFull[roomToken].clients.length\n\n \n\n // if(membersCountOfNotFull > notFullRoomLimit) console.log('limit exceeded', membersCountOfNotFull, notFullRoomLimit)\n\n if(membersCountOfNotFull === notFullRoomLimit){\n roomsRegistry[roomLabel].full[roomToken] = roomsRegistry[roomLabel].notFull[roomToken]\n roomsRegistry[roomLabel].notFull = removeKey(roomsRegistry[roomLabel].notFull,roomToken)\n }\n\n }\n\n }\n\n broadcast(roomToken,null,'onopen',roomLabel)\n\n }\n\n })\n //add coments and decrease code\n // roomArgToken room name, roomLabel key\n function broadcast(roomArgToken,content,type,roomLabel){// room label is the type of room and roomArgToken is unique id of room which can be full or not full\n\n let token = roomLabel.split('_')[1]\n\n let broadcastTo = null\n try{\n broadcastTo = roomsRegistry[roomLabel].notFull[roomArgToken] === undefined ? roomsRegistry[roomLabel].full[roomArgToken] : roomsRegistry[roomLabel].notFull[roomArgToken] \n }catch(e){\n return ws.send( stringIt({error:roomArgToken+' room not found in '+roomLabel+'to broadcast'+e}) )\n }\n\n let members = []\n\n if (!broadcastTo) return ws.send( stringIt({ unique:roomArgToken, token:token, type:'onerror', data:'invalid unique' }))\n\n for (let index of broadcastTo.clients){\n\n members.push( socketClients[index].user )\n }\n\n if (type == 'onopen') return ws.send( stringIt({ unique:roomArgToken, token:token, members:members, type:type }))\n\n\n for (let index of broadcastTo.clients){\n if (index !== clientId) socketClients[index].socket.send( stringIt({unique:roomArgToken, members:members, token:token, sender:socketClients[clientId].user, data:content, type:type }) )\n }\n\n }\n}", "function socketOnEnd () {\n const websocket = this[kWebSocket];\n\n websocket.readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}", "function socketOnEnd () {\n const websocket = this[kWebSocket];\n\n websocket.readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}", "constructor(socketIoInstance) {\n this.rooms = {};\n\n SafeSocket.socketsOn(socketIoInstance, 'connection', (socket) => {\n Logger.logInfo('socket ' + socket.id + ' connected');\n\n socket.emit('clientConnectedToServer', {\n socketId: socket.id\n });\n\n // Default socket.io actions\n socket.on('disconnect', () => { this.onDisconnect(socket); });\n socket.on('disconnecting', () => { this.playerAttemptLeaveRoom(socket, {}); });\n // Custom actions\n socket.on('hostAttemptEndGame', (data) => { this.hostAttemptEndGame(socket, data) });\n socket.on('hostAttemptStartGame', (data) => { this.hostAttemptStartGame(socket, data) });\n socket.on('playerAttemptCreateRoom', (data) => {\n this.playerAttemptCreateRoom(socket, data)\n });\n socket.on('playerAttemptJoinRoom', (data) => { this.playerAttemptJoinRoom(socket, data) });\n socket.on('playerAttemptLeaveRoom', (data) => { this.playerAttemptLeaveRoom(socket, data) });\n });\n }" ]
[ "0.67095983", "0.65666056", "0.6465502", "0.63598245", "0.63392496", "0.6291714", "0.6026626", "0.60133773", "0.59561044", "0.5952015", "0.5904428", "0.59020364", "0.58681196", "0.583592", "0.5810024", "0.5774309", "0.57681537", "0.57665354", "0.57302386", "0.57266414", "0.57229203", "0.5718764", "0.56814593", "0.56564635", "0.5653408", "0.5638498", "0.5633904", "0.56229717", "0.56229717", "0.5598283" ]
0.66460216
1
Create randomizer to pull 4 different powers of a pokemon and push it into a new array
function getRandomPower(movesArr, data) { let min = 0; let max = data.moves.length; let randomMove = Math.floor(Math.random() * (max - min) + min); movesArr.push(data.moves[randomMove]); // put the four random moves in a new array }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function generatePokemonAry(){\n wildPokemon = []\n\n for (let i = 1; i < 650; i++) {\n wildPokemon.push(i);\n \n }\n return wildPokemon;\n \n}", "async function generatePokemonArray(pokemon) {\n randomPokemon = pokemon[Math.floor(Math.random() * 151)]\n getRandomPokemonData(randomPokemon);\n }", "static getRandomPokemon() {\n let randomNum = Math.floor(Math.random() * (802));\n return Pokemon.allPokemons[randomNum]\n }", "function randomisePokemon(noOfPokemon) {\n\tvar pokeballArray = allPokemon.slice(0, noOfPokemon).map(function() {\n\t\treturn this.splice(Math.floor(Math.random() * this.length), 1)[0];\n\t}, allPokemon.slice());\n\treturn pokeballArray;\n}", "function levelOne_ActOne() {\r\n\tlet levelOneRollOne = [];\r\n\tlet genreRollOne;\r\n\tlet genreRollTwo;\r\n\tlet genreRollThree;\r\n\tlet genreRollFour;\r\n\r\n\tgenreRollOne = rollDie(diceTwenty);\r\n\tgenreRollTwo = rollDie(diceTwenty);\r\n\tgenreRollThree = rollDie(diceTwenty);\r\n\tgenreRollFour = rollDie(diceTwenty);\r\n\t\r\n\t\r\n\tlet result = levelOneRollOne.push(genreRollOne, genreRollTwo, genreRollThree, genreRollFour);\r\n\treturn result;\r\n//STEP 1: ROLL THE DICE TO SELECT THE 4 GENRES YOU CAN CHOOSE FROM\r\n}", "function powerBallGen(min, max, num){\n\n var powerBallArray = [];\n\n // Math.random() * (max - min) + min\n for (var i = 0; i < num; i++) {\n\n var powerNumbers = Math.round(Math.random() * (59 - 1) + 1);\n\n powerBallArray [i] = powerNumbers;\n\n }\n\n return powerBallArray;\n\n}", "static getRelevantPokemon(typeArray) { // array of pokemon's relevant types\n // Randomly select a TYPE from the array\n let randType = typeArray[Math.floor(Math.random() * typeArray.length)]\n // Collect an array of pokemon with that TYPE\n let arrayTypePokemon= Pokemon.filterPokemonByType(randType)\n // Randomly select a POKEMON from the weakArray\n let pokemonWithType = arrayTypePokemon[Math.floor(Math.random() * arrayTypePokemon.length)]\n return pokemonWithType\n }", "function pick_9_Pokemons_from_list(pokemon){\n\n\t\tfor (let i = 0; i < 9;i++){\n\t\t\tgetRandomPokemon(pokemon);\n\t\t}\n\t\t//selectRandomName();\n\t}", "generatePowers(tier) {\n let powers = this._generatePowersMundane(tier);\n for (let category of this.racePowerCategories()) {\n powers = powers.concat(\n this._generatePowersForCategory(\n category,\n 1, // All Bakemono powes are 1\n 1 + RNG.d0(RNG.retier(tier)),\n )\n );\n }\n\n return powers;\n }", "function randomPokemon() {\n selector = Math.floor(Math.random()* 781) + 26 //Random number between 26 and 809\n getAPIData(`https://pokeapi.co/api/v2/pokemon/${selector}`).then((pokeData) => {\n populatePokeCards(pokeData)\n })\n}", "function make_power_up()\n{\n\tvar pos = [Math.floor(Math.random()*40),Math.floor(Math.random()*40)];\n\twhile(!check_pos_valid(pos))\n\t\t{\n\t\tpos = [Math.floor(Math.random()*40),Math.floor(Math.random()*40)];\n\t}\n\tpower_up['position'] = new Array(pos[0]*10,pos[1]*10);\n\tvar num = Math.floor(Math.random()*50+1);\n\tif(num % power_up['cherry'] == 0)\n\t{\n\t\tpower_up['type'] = 'cherry';\n\t}\n\telse if(num % power_up['apple'] == 0)\n\t{\n\t\tpower_up['type'] = 'apple';\n\t}\n\telse if(num % power_up['grape'] == 0)\n\t{\n\t\tpower_up['type'] = 'grape';\n\t}\n\telse if(num % power_up['banana'] == 0)\n\t{\n\t\tpower_up['type'] = 'banana'; \n\t}\n\telse\n\t{\n\t\tpower_up['type'] = 'onion';\n\t}\n}", "function pickPok() {\n\t\tvar random = Math.floor(Math.random() * randomPokemon.length);\n\t\treturn randomPokemon[random];\n\t}", "function randomPokemon(pokedex) {\r\n let num = Math.floor((Math.random() * 156) + 1);\r\n let pokemon = pokedex[num].url;\r\n return pokemon\r\n}", "function generatorOpinion (num) {\n var tempArray = [];\n for (var i = 0; i < num; i++ ) {\n tempArray.push(randomOpinion(opinions));\n }\n return tempArray;\n}", "function powerBallNumberGen(min, max, num1) {\n\n var ballArray = [];\n\n for (var i = 0; i < num1; i++){\n\n var ballNumbers = Math.round(Math.random() * (35 - 1) + 1);\n\n ballArray [i] = ballNumbers;\n\n }\n\n return ballArray;\n\n}", "function pokemon(num_array) {\n let num_pokemon = 0;\n let array_pokemon = [];\n for (let i = 0; i < num_array.length; i++) {\n num_pokemon = num_pokemon + num_array[i];\n array_pokemon.push(num_pokemon);\n }\n return array_pokemon;\n }", "function randomPiece(){\n let r = randomN = Math.floor(Math.random() * PIECES.length) //math.floor rounds the number to an integer\n return new Piece( PIECES[r][0],PIECES[r][1]); //math.raandom generates numbers between 0 and 1 \n} //to generate numbers between 0 and 7, multiply math.random by the length of the tetromino array", "randomAbility(){\n let rolls = [];\n for (let i = 0; i < 4; i++){\n rolls.push(this.rollDice(1, 6));\n }\n\n rolls = this.bubble(rolls); // sort to take highest 3\n return rolls[1] + rolls[2] + rolls[3];\n }", "determinize(battleside) {\n\n _.each(battleside.pokemon, function(pokemon) {\n if(!!pokemon.set.probabilities) {\n var set = pokemon.set\n\n set.item = sample_from(set.probabilities.items, function(e){return e[1]})[0]\n set.evs = _.sample(set.probabilities.evs)\n //set.moves = pokemon.trueMoves + _.map(_.sampleSize(set.probabilities.moves, 4-pokemon.trueMoves.length), function(m){return m[0]})\n\n // Create the new pokemon\n var new_pokemon = new BattlePokemon(set, battleside);\n new_pokemon.trueMoves = pokemon.trueMoves\n new_pokemon.nickname = pokemon.nickname\n pokemon.position = pokemon.position;\n battleside.pokemon[pokemon.position] = new_pokemon;\n\n if (pokemon.position === 0) {\n battleside.active = [new_pokemon];\n new_pokemon.isActive = true;\n }\n }\n })\n \n\n battleside.pokemon = _.sortBy(battleside.pokemon, function(pokemon) { return pokemon.isActive ? 0 : 1 });\n for(var i = 0; i < 6; i++) {\n battleside.pokemon[i].position = i\n }\n }", "function powerballLotto(max, min, num) {\n for (var i = 0; i < num; i++) {\n powerballQP[i] = Math.random() * (max - min) + min; //math object to select a random number\n powerballQP[i] = Math.round(powerballQP[i]); //math object to round number to nearest whole number\n }\n console.log(\"Your Powerball lottery quick pick numbers are \" + powerballQP); //console outputs the Powerball quick pick numbers.\n}", "function randomizePieces() {\n const randomPieces = pieces.slice()\n for (let i = randomPieces.length - 1; i > 0; i--) {\n const rand = Math.floor(Math.random() * (i + 1));\n [randomPieces[i], randomPieces[rand]] = [randomPieces[rand], randomPieces[i]];\n }\n return randomPieces\n}", "function randomPowerballNum(min, max){ //arguments\n\n var powerballArray = []; //will give me 5 nums\n\n for (var i = 0; i < 5; i++){ //will run until i equals 5\n var powerball = Math.random() * (max - min) + min; //set up random num\n\n powerball = Math.round(powerball); //rounds nums to wholes\n powerballArray [i] = powerball; // will display array\n\n }\n\n return powerballArray;\n\n }", "function randomWeapon() {\r\n let array = [\r\n { weapon: \"Sword\", type: \"physical\", ability: \"randomInt(4, 12)\", deathNote: \"was sliced in half by a sword!\" },\r\n { weapon: \"Shovel\", type: \"physical\", ability:\"randomInt(3, 10)\", deathNote: \"got dugged by a shovel!\" },\r\n { weapon: \"Pistol\", type: \"ranged\", ability: \"randomInt(7, 20)\", deathNote: \"was shot by a pistol!\" },\r\n { weapon: \"Knife\", type: \"physical\", ability: \"randomInt(6, 9)\", deathNote: \"was stabbed in the throat!\" },\r\n { weapon: \"Shotgun\", type: \"ranged\", ability: \"randomInt(4, 12)\", deathNote: \"was blasted to rubble!\" },\r\n { weapon: \"Spear\", type: \"ranged\", ability: \"randomInt(1, 20) + randomInt(1, 10)\", deathNote: \"got pierced by a spear!\" },\r\n { weapon: \"Molotov\", type: \"ranged\", ability: \"randomInt(4, 7) + randomInt(4, 7)\", deathNote: \"screamed as fire from a broken molotov seared thy skin.\" },\r\n { weapon: \"Machine Gun\", type: \"ranged\", ability: \"randomInt(4, 5) + randomInt(6, 7) + randomInt(7, 8)\", deathNote: \"was ripped apart by bullets!\" },\r\n { weapon: \"Frying Pan\", type: \"magic\", ability: \"randomInt(10, 12)\", deathNote: \"was fried by a frying pan!\" },\r\n { weapon: \"Blood Magic\", type: \"magic\", ability: \"randomInt(0, 22)\", deathNote: \"was destroyed inside-out by inner blood turmoil!\" },\r\n { weapon: \"Laser Sword\", type: \"magic\", ability: \"randomInt(11, 13)\", deathNote: \"was cut in half by pure plasma!\" },\r\n { weapon: \"Grenade\", type: \"ranged\", ability: \"10\", deathNote: \"was blew up by a grenade!\" },\r\n { weapon: \"Shield\", type: \"physical\", ability: \"randomInt(7, 10) - 5\", deathNote: \"neck broke by getting bashed by a shield!\" },\r\n { weapon: \"Rocket Launcher\", type: \"physical\", ability: \"randomInt(20, 50) - 30\", deathNote: \"torn apart by a missle!\" },\r\n { weapon: \"Holy Cross\", type: \"magic\", ability: \"randomInt(1, 12) + 10\", deathNote: \"was smited by a holy might!\" },\r\n { weapon: \"Railgun\", type: \"ranged\", ability: \"randomInt(1, 100) - 40\", deathNote: \"was fried by a plasma beam!\" }\r\n ];\r\n\r\n let random = randomInt(0, array.length);\r\n return array[random];\r\n}", "function randomType() {\r\n let array = [\r\n { personality: \"Brawny\", bonus: \"if (players[attacker].wep.type == 'physical'){temp += 5}\", applied: 'offense' }, // if attacker's weapon is physical, damage + 5,\r\n { personality: \"Vampire\", bonus: \"if (players[attacker].wep.type == 'magic'){temp += 5}\", applied: 'offense' }, // if attacker's weapon is physical, damage + 5,\r\n { personality: \"Clown\", bonus: \"if (players[attacker].hp <= 10){temp += 8}\", applied: '' }, // If attacker is bellow ten hp, damage + 8\r\n { personality: \"Smart\", bonus: \"if (players[defender].type.personality == 'Dumb'){temp += 15}\", applied: 'offense' }, // if defender personality is dumb, damage + 15\r\n { personality: \"Dumb\", bonus: \"if (players[attacker].hp >= '10'){temp += 5}\", applied: 'offense' }, // if attacker is above ten HP, damage + 5\r\n { personality: \"Saiyan\", bonus: \"if (randomInt(1, 10) > 5){temp += 5}\", applied: 'offense' }, // If random number from 1-10 above 5, + 5 damage.\r\n { personality: \"Paladin\", bonus: \"if (players[defender].hp < 10){temp -= 5}\", applied: 'defence' }, // if defender bellow ten hp, + 5 shield\r\n { personality: \"Ailen\", bonus: \"if (players[defender].hp > 20){temp -= 3}\", applied: 'defence' }, // if defender above 20 HP, shield + 3\r\n { personality: \"Slave\", bonus: \"if (players[attacker].type.personality == 'Clown'){temp += 15}\", applied: 'offense' }, // If attacker personality is clown, + 15 damage\r\n { personality: \"Military\", bonus: \"if (players[attacker].wep.weapon == 'ranged'){temp += 5}\", applied: 'offense' }, // if weapon is ranged, + 5 damage\r\n { personality: \"Brain Dead\", bonus: \"if (randomInt(0, 10) < 5){temp -= 10}\", applied: 'offense' }, // if a number between 1 and 10 bellow 5, opponet shield += 10\r\n ]\r\n\r\n let random = randomInt(0, array.length);\r\n return array[random];\r\n}", "function pickRandomWizards(arr) {\n\n for (var y = 0; y < 4; y++) {\n\n var a = arr[Math.floor(Math.random() * arr.length)];\n\n wizardNumbers.push(a);\n }\n\n console.log(\"wizard numbers: \" + wizardNumbers);\n\n } // End of pick random wizard houses", "genCode() {\n let numColors = this.state && colors[this.state.difficulty].length;\n numColors = numColors || 4;\n return new Array(4).fill().map(dummy => Math.floor(Math.random() * numColors));\n }", "function randomizer() {\n target = Math.floor(Math.random() * 100) + 19;\n gem1rando = Math.floor(Math.random() * 13) + 2;\n gem2rando = Math.floor(Math.random() * 13) + 2;\n gem3rando = Math.floor(Math.random() * 13) + 2;\n gem4rando = Math.floor(Math.random() * 13) + 2;\n }", "function randTile(num) {\n for (let i = 0; i < 4; i++) {\n let a = num[Math.floor(Math.random() * num.length)];\n\n tileNumber.push(a);\n }\n // check which numbers have been picked\n console.log(tileNumber);\n } // End function", "function powerball(max, min, num){\n for (var i = 0; i < num; i++) {\n powerB[i] = Math.random() * (max - min) + min; //math object to select a random number\n powerB[i] = Math.round(powerB[i]); //math object to round number to nearest whole number\n\n }\n console.log(\"Your Powerball is \" + powerB); //console outputs the Powerball number.\n}", "function RandomPieceBag()\n{\n var pieces=[];\n\n this.takePiece = function()\n {\n if(pieces.length==0)\n {\n for(var i=0; i<7; i++)\n {\n pieces.push(i);\n }\n }\n \n var randomIndex=Math.floor(Math.random()*pieces.length);\n var piece = pieces[randomIndex];\n pieces.splice(randomIndex, 1);\n return piece;\n }\n \n}" ]
[ "0.7005367", "0.67773926", "0.6680528", "0.6574842", "0.65537995", "0.6510981", "0.65074015", "0.6484808", "0.6430658", "0.63793385", "0.6373412", "0.6362663", "0.6345218", "0.62932444", "0.6280637", "0.6278372", "0.6272051", "0.6262572", "0.624271", "0.6241701", "0.6209146", "0.62004787", "0.6194146", "0.6192454", "0.6171129", "0.61204326", "0.61109596", "0.61008257", "0.6085305", "0.6078332" ]
0.7426572
0
Create a function called travelFrom that receives a start station and an end station.
function travelFrom() { var startStationInput = document.querySelector("#startStation"); var startStation = startStationInput.value; var endStationInput = document.querySelector("#endStation"); var endStation = endStationInput.value; var start = capitaliseFirstLetter(startStation.toLowerCase()); var end = capitaliseFirstLetter(endStation.toLowerCase());var startLine = findLine(start); var endLine = findLine(end); var startLineArray = sydneyTrains[startLine]; var endLineArray = sydneyTrains[endLine]; // Check if stations exists on the lines entered if (!stations.includes(start) || !stations.includes(end)) { var message = ("Something went wrong and the stations you entered don't exist on those lines"); } else if (endLineArray.includes(start) || startLineArray.includes(end)) { //Tell person to switch to the line. if (endLineArray.includes(start)) { var correctLine = endLine; } else { var correctLine = startLine; } var numberofStops = Math.abs(endLineArray.indexOf(end) - startLineArray.indexOf(start)); if (numberofStops > 1) { var stopOrStops = "stops"; } else { var stopOrStops = "stop"; }; var message = "To go from "+start+" to "+end+" - you will need to go through "+numberofStops+" "+stopOrStops+" on the "+correctLine+"."; } else { //Find first station that matches both startLine and endLine = switchingStation var switchingStation = endLineArray.find(function(item) { return startLineArray.includes(item); }); //Tell person how many stops from startStation to switchingStation //Tell person where to switch (switchingStation) //Tell person how many stops from switchingStation to endStation var numberofStops1 = Math.abs(startLineArray.indexOf(switchingStation) - startLineArray.indexOf(start)); var numberofStops2 = Math.abs(endLineArray.indexOf(switchingStation) - endLineArray.indexOf(end)); if (numberofStops1 > 1) { var stopOrStops1 = "stops"; } else { var stopOrStops1 = "stop"; }; if (numberofStops2 > 1) { var stopOrStops2 = "stops"; } else { var stopOrStops2 = "stop"; }; var message = "To go from "+start+" to "+end+" - you will need to take "+startLine+" for "+numberofStops1+" "+stopOrStops1+", switch at "+switchingStation+" to "+endLine+", then go through "+numberofStops2+" "+stopOrStops2+"."; }; answer.innerText = message; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_journey(station1, station2) {\n const toDate = new Moment().format(\"YYYY-MM-DD\");\n const fromDate = new Moment().businessSubtract(20).format(\"YYYY-MM-DD\");\n\n return {\n \"from_loc\":station1,\n \"to_loc\":station2,\n \"from_time\":\"0000\",\n \"to_time\":\"2359\",\n \"from_date\":fromDate,\n \"to_date\":toDate,\n \"days\":\"WEEKDAY\"\n }\n }", "function calculateAndDisplayRoute(directionsService, directionsDisplay) {\n \n //start should be lat+\",\"+lng\n var start = document.getElementById('start').value;\n //if the user chooses to use current location\n if(start===\"\"){\n //getLocation();\n start = 34.0666664+\",\"+-118.167332664;//document.getElementById('start').value;\n }\n\n //end should be (lat,lng)\n var end = document.getElementById('end').value;\n\n //gets the route to take for the map\n directionsService.route({\n origin: start,\n destination: end,\n travelMode: 'WALKING' //walking from point A to B\n }, function(response, status) {\n \n //if no errors found it fins the route\n //else display error message\n if (status === 'OK') {\n directionsDisplay.setDirections(response);\n } else {\n window.alert('Directions request failed due to ' + status);\n }\n });\n}", "function calcRoute() {\n\n var start = pos;\n var end = document.getElementById('end').value;\n var request = {\n origin:start,\n destination:end,\n travelMode: google.maps.TravelMode.DRIVING\n };\n directionsService.route(request, function(response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n });\n}", "function calcRouteLatLong(latinicio, longinicio, latfin, longfin) {\nvar start = new google.maps.LatLng(latinicio, longinicio);\nvar end = new google.maps.LatLng(latfin, longfin);\nvar request = {\n origin: start,\n destination: end, \n travelMode: google.maps.TravelMode.DRIVING\n};\ndirectionsService.route(request, function(response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n else{\n alert(\"No se ha podido calcular ruta\");\n }\n}); \n}", "function travel(r, zipcode) {\n // your code\n}", "function calcRoutee(){\r\n\t\t\r\n\t\tvar half= document.getElementById(\"half\").value;\r\n\t\tvar end = document.getElementById(\"end\").value;\r\n\t\tvar request = { origin: half, destination: end,\r\n\t\t\ttravelMode: google.maps.DirectionsTravelMode.DRIVING\r\n\t\t};\r\n\t\tdirectionsService.route(request, function(directionsResults, status){\r\n\t\t\tif(status==google.maps.DirectionsStatus.OK){\r\n\t\t\t\thandleDirectionsResponse1(\r\n\t\t\t\t\t\t half,end, directionsResults);\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\t }", "function createRoute() {\n\n var start = new google.maps.LatLng(markers[0].position.lat(), markers[0].position.lng());\n var end = new google.maps.LatLng(markers[1].position.lat(), markers[1].position.lng());\n calculateRoute(start, end);\n\n}", "function Journey(str_begin_line, begin_stp, str_desti_line, desti_stp) {\n //str_begin_line ----> begin_line &&\n //str_desti_line ----> desti_line_\n this.stp_nochangeline = stp_nochangeline(interatelines(str_begin_line), begin_stp, desti_stp)\n this.stp_before_inter = stp_before_inter(interatelines(str_begin_line), begin_stp, interatelines(str_desti_line));\n this.doesinter = doesinter(str_begin_line, str_desti_line);\n this.stp_after_inter = stp_after_inter(interatelines(str_begin_line), desti_stp, interatelines(str_desti_line));\n this.total = function( ) { return this.stp_before_inter.length+this.stp_after_inter.length };\n}", "function buildFlightSearchURL(from, to, departure, arrival) {\n return \"https://www.expedia.com/Flights-Search?trip=roundtrip&leg1=from:\"+from+\",to:\"+to+\",departure:\"+departure+\"TANYT&leg2=from:\"+to+\",to:\"+from+\",departure:\"+arrival+\"TANYT&passengers=children:0,adults:1,seniors:0,infantinlap:Y&mode=search\";\n}", "function shortest_path(to_x, to_y, use_stations) {\n\t// {{{\n\tvar route = \"<br>\";\n\tvar from_x = current_x;\n\tvar from_y = current_y;\n\n\tvar dist_by_foot = distance_AP(from_x, from_y, to_x, to_y);\n\tvar dist_to_station = places_station[0][3];\n\n\tif (dist_by_foot == 0) {\n\t\troute += \"You are already there ! No need to move.<br>\";\n\t\t// generate_direction() is used to update the direction arrows\n\t\tgenerate_direction(current_x, current_y, to_x, to_y, enable_hud, true);\n\t\treturn route;\n\t}\n\n\tif ((!use_stations) || (dist_by_foot < dist_to_station)) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tvar places_station_tmp = new Array();\n\tfor (var i = 0; i < places_station.length; ++i) {\n\t\tplaces_station_tmp[i] = new Array();\n\t\tplaces_station_tmp[i][0] = places_station[i][0];\n\t\tplaces_station_tmp[i][1] = places_station[i][1];\n\t\tplaces_station_tmp[i][2] = places_station[i][2];\n\t\tplaces_station_tmp[i][3] = -1;\n\t}\n\t// Compute the distance from to_x, to_y to stations and sort them\n\tsort_places(to_x, to_y, places_station_tmp);\n\n\tvar best_dist_to_dest = dist_to_station + transit_cost_action_point + places_station_tmp[0][3];\n\n\t// Same AP cost ? then walk\n\tif (best_dist_to_dest >= dist_by_foot) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tif (dist_to_station > 0) {\n\t\troute += \"Walk to the \" + places_station[0][0] + \" station (\" + dist_to_station + action_point_str + \": \"+\n\t\t\t generate_direction(current_x, current_y, places_station[0][1], places_station[0][2], enable_hud, true) + \")<br>\";\n\t}\n\troute += \"Take the train up to \" + places_station_tmp[0][0] + \" station (\" + transit_cost_action_point + action_point_str + \" + \"+transit_cost_coins+\" \"+ money_unit_str + \").<br>\";\n\troute += \"Walk to your destination (\" + places_station_tmp[0][3] + action_point_str + \": \"+\n\t\t generate_direction(places_station_tmp[0][1], places_station_tmp[0][2], to_x, to_y, false, false) + \")<br>\";\n\n\troute += \"Total travel cost: \" + (parseInt(dist_to_station) + transit_cost_action_point + parseInt(places_station_tmp[0][3])) + action_point_str + \" & \" + transit_cost_coins + \" \" + money_unit_str + \".<br>\";\n\n\treturn route;\n\t// }}}\n}", "function travel(destination, myFunc){\n console.log(\"travelling to \" + destination);\n let a = myFunc(); //our a variable is equal to \"apples\"\n return a;\n}", "function generateRoute() {\n var from = document.getElementById(\"from\").value;\n var to = document.getElementById(\"to\").value;\n directions.load(\"from: \" + from + \" to: \" + to, { preserveViewport: true, getSteps: true });\n }", "function calculateRoute(start, end) {\n\n var request = {\n origin: start,\n destination: end,\n travelMode: 'DRIVING'\n };\n directionsService.route(request, function (response, status) {\n if (status === 'OK') {\n directionsDisplay.setDirections(response);\n\n //Calculate total duration and distance\n var totalDistance = 0.0;\n var totalDuration = 0.0;\n var legs = response.routes[0].legs;\n for (var i = 0; i < legs.length; i++) {\n totalDistance += legs[i].distance.value;\n totalDuration += legs[i].duration.value;\n }\n totalDistance = totalDistance / KILOMETER;\n totalDuration = totalDuration / MINUTE;\n\n showRouteInfo(totalDistance, totalDuration, calculateTripCost(totalDistance));\n }\n });\n}", "function route(origin_place_id, destination_place_id, travel_mode) {\n\n if (!origin_place_id || !destination_place_id) {\n return;\n }\n directionsService.route({\n origin: {\n 'placeId': origin_place_id\n },\n destination: {\n 'placeId': destination_place_id\n },\n travelMode: travel_mode\n }, function (response, status) {\n if (status === google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n \n // Guardamos las coordenadas en BeanRuta\n // var iniLat = response.routes.legs[0].steps.start_location.lat;\n // var iniLon = response.routes.legs[0].steps.start_location.lng;\n // var finLat = response.routes.legs[0].steps.end_location.lat;\n // var finLon = response.routes.legs[0].steps.end_location.lng;\n //guardaCoordenadas(iniLat, iniLon, finLat, finLon);\n\n } else {\n window.alert('Directions request failed due to ' + status);\n }\n });\n\n}", "function getTrainsBetweenStations(sender,source,destination,dd,mm){\n\n request('http://api.railwayapi.com/between/source/'+ source +'/dest/'+ destination +'/date/'+dd +'-'+mm+'/apikey/'+ apiKey, (err, response, body) => {\n\t if(JSON.parse(body).error === \"Quota exhausted for day\"){\n\t console.log(JSON.parse(body).error);\n\t }else{\n\n sendText(sender,\"There are \"+JSON.parse(body).total+\" trains availble..\");\n\n var trainList = JSON.parse(body).train\n for (var i=0;i<trainList.length;i++){\n sendText(sender,JSON.parse(body).train[i].number +\" \"+ JSON.parse(body).train[i].name+\", \"+\n JSON.parse(body).train[i].from.name +\" -> \" + JSON.parse(body).train[i].to.name +\"\\nSch Dep : \"+JSON.parse(body).train[i].src_departure_time +\" Hrs\"\n +\"\\nSch Arr : \"+JSON.parse(body).train[i].dest_arrival_time +\" Hrs\"+\"\\nTravel Time : \"+ JSON.parse(body).train[i].travel_time +\" Hrs\\n\");\n\n\n }\n\n\n\t }\n});\n\n\n}", "constructor(station, arrive) {\n\t\t\tthis.station = station;\n\t\t\tif (typeof arrive == 'function')\n\t\t\t\tthis.arrive = arrive;\n\t\t}", "function calcRoute() {\n\n var request = {\n origin: start,\n destination: end,\n travelMode: google.maps.TravelMode[travelMode],\n waypoints: waypts\n };\n\n directionsService.route(request, function(result, status) {\n\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(result);\n }\n });\n}", "calculateRoute(startFeature, endFeature) {\n const getId = feature => {\n const payload = JSON.parse(feature.properties.althurayyaData)\n return payload.URI;\n }\n\n const start = getId(startFeature);\n const end = getId(endFeature);\n\n // Note that this returns the IDs of the *NODES* along the road, i.e.\n // we now need to look up the segments which connect these nodes\n const path = this._graph.findShortestPath(start, end);\n\n if (path) {\n // Sliding window across path, pairwise\n const segments = [];\n for (var i=1; i<path.length; i++) {\n segments.push(this.findSegment(path[i - 1], path[i]));\n }\n\n return segments;\n }\n }", "function getDirections(start, end) {\n centerpointMarker.setVisible(false);\n\n var request = {\n origin: start,\n destination: end,\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n directionsService.route(request, function(response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n });\n}", "function travel(destination, myFunc){ \n console.log(\"travelling to \" + destination);\n myFunc();\n printStuff();\n // return myFunc;\n}", "function PlanRoad (start, end)\n{\n //Check if road is already known\n var roadIsKnown = false;\n var knownRoads = start.room.memory.roomInfo.knownRoads;\n\n if ( knownRoads && knownRoads.length > 0)\n {\n for ( let n in knownRoads )\n {\n var knownRoad = knownRoads[n];\n if ( knownRoad.start.x == start.pos.x && knownRoad.start.y == start.pos.y && knownRoad.end.x == end.pos.x && knownRoad.end.y == end.pos.y )\n {\n roadIsKnown = true;\n }\n }\n }\n // If not a known road, plan it.\n if ( !roadIsKnown )\n {\n var road = {};\n\n // Special case, if start and end are the same, build a road around the object\n // otherwise plan one from start to end\n if (start == end )\n {\n console.log('control.Construction.PlanRoad: Around Position: ' + start.pos );\n\n road = getSurroundingPositions(start) ;\n\n }\n else\n {\n console.log('control.Construction.PlanRoad: start: ' + start + ' - position: ' + start.pos );\n console.log('control.Construction.PlanRoad: end: ' + end + ' - position: ' + end.pos );\n\n road = PathFinder.search(start.pos, { pos: end.pos, range: 1 }) ;\n }\n for ( let n in road.path )\n {\n var buildPosition = road.path[n];\n start.room.memory.roomInfo.futureConstructionSites.push({position: buildPosition, structure: STRUCTURE_ROAD})\n }\n\n start.room.memory.roomInfo.knownRoads.push({start: start.pos, end: end.pos });\n }\n\n // Set a return value, so the caller knows if we did anything\n return (!roadIsKnown);\n}", "constructor(from, to) {\n this.from = from;\n this.to = to;\n }", "function routes_tourist() {\n\n\t// clear tourist markers from map\n\tclearAllTouristMarkers(markers);\n\tvar starting = origin.getPlace();\n\n\tif (!geolocation) {\n\t\t//getting the lat and lng of the input address \n\t\t// display error to user if valid starting location not entered\n\t\tif (!starting) {\n\t\t\t$('.invalid-location-error').show();\n\t\t\treturn false;\n\t\t} else {\n\t\t\t//starting address latitude\n\t\t\tvar starting_lat = starting.geometry.location.lat();\n\t\t\tvar starting_lng = starting.geometry.location.lng();\n\t\t}\n\t}\n\n\t// Create a renderer for directions and bind it to the map.\n\tdirectionsRenderer = new google.maps.DirectionsRenderer({\n\t\tmap: map,\n\t\tpreserveViewport: true\n\t});\n\n\t// Instantiate an info window to hold step text.\n\tvar stepDisplay = new google.maps.InfoWindow;\n\n\t// Display the route between the initial start and end selections.\n\tcalculateAndDisplayRoute(directionsRenderer, directionsService, markerArray, stepDisplay, map);\n\treturn true;\n}", "function calculateAndDisplayRoute(directionsService, directionsDisplay) {\r\n\r\n\t//initialize variables\r\n\tvar start = document.getElementById('start_point').value;\r\n\tvar end = {lat: 53.3601147, lng: -6.2763354};\r\n\r\n\t//set the starting point and destination for travel mode (plus display status)\r\n\tdirectionsService.route({\r\n\t\torigin: start,\r\n\t\tdestination: end,\r\n\t\ttravelMode: google.maps.TravelMode.DRIVING\r\n\t\t}, function(response, status) {\r\n\t\t\tif (status === google.maps.DirectionsStatus.OK) {\r\n\t\t\t\tdirectionsDisplay.setDirections(response);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\twindow.alert('Location cannot be found!');\r\n\t\t\t}\r\n\t});\r\n}", "function helper(s, path, toConsider) {\n if(s.name === station2) { //Condition to stop when destination is reached at\n setPrev(s, path);\n return s;\n } else {\n path = pair(s, path);\n //Setting the values of vertices in a graph\n map(function(x) { \n var dv = s.dv + 1; //Note all edges have weight of 1\n if(dv < x.dv) {\n x.dv = dv;\n } else {}\n }, filter(function(x) { return !is_empty_list(x) && is_empty_list(member(x, path)); }, \n s.neighbours));\n toConsider = filter(function(x) { return !is_empty_list(x); }, toConsider);\n toConsider = filter(function(x) { return is_empty_list(member(x, path)); }, toConsider);\n setPrev(s, path);\n //To find shortest path\n var next_s = accumulate(function(x, y) {\n return x.dv < y.dv ? x : y;\n }, {\"dv\": 1/0}, toConsider);\n toConsider = remove_all(next_s, toConsider);\n toConsider = append(toConsider, next_s.neighbours);\n toConsider = filter(function(x) { return !is_empty_list(x); }, toConsider);\n toConsider = filter(function(x) { return is_empty_list(member(x, path)); }, toConsider);\n return helper(next_s, path, toConsider);\n }\n }", "function go() {\n\n //error handling\n let errorPresent = false;\n if (date == null) {\n errorPresent = true;\n setTimeErrorText(\"Please enter a valid date and time\");\n }\n if (start.current.coords.length === 0) {\n errorPresent = true;\n setStartErrorText(\"Please enter a valid address\");\n }\n if (dest.current.coords.length === 0) {\n errorPresent = true;\n setDestErrorText(\"Please enter a valid address\");\n }\n if(!errorPresent) {\n // run the algorithm\n\n setLoadingText(\"Loading...\");\n console.log(stops.current);\n\n console.log(\"ReRoutes: \" + reRoutes);\n\n const toSend = {\n startLat: start.current.coords[0],\n startLon: start.current.coords[1],\n destLat: dest.current.coords[0],\n destLon: dest.current.coords[1],\n time: date,\n stops: stops.current,\n reRoutes: reRoutes\n };\n\n let config = {\n headers: {\n \"Content-Type\": \"application/json\",\n 'Access-Control-Allow-Origin': '*',\n }\n }\n\n axios.post(\n \"http://localhost:4567/run\",\n toSend,\n config\n )\n .then(response => {\n console.log(response.data);\n setRoute(response.data[\"route\"]);\n })\n .catch(function (error) {\n console.log(error);\n setLoadingText(\"Something went wrong. Please try again\");\n });\n\n console.log([dest.current.coords[0], dest.current.coords[1]]);\n }\n\n }", "function depart(start, destination, done) {\n bart.sched.depart({\n orig: start,\n dest: destination\n }, function (err, xml, body) {\n if (err) {\n throw err;\n }\n\n // xml is a parser instance from https://github.com/polotek/libxmljs\n // it supports xpath and more!\n var trips = [];\n\n xml.find('/root/schedule/request/trip').forEach(function (trip) {\n trips.push({\n orig: trip.attr('origin').value(),\n dest: trip.attr('destination').value(),\n times: {\n orig: trip.attr('origTimeMin').value(),\n dest: trip.attr('destTimeMin').value()\n },\n legs: trip.find('leg').map(function (leg) {\n return {\n orig: leg.attr('origin').value(),\n dest: leg.attr('destination').value(),\n line: leg.attr('line').value(),\n head: leg.attr('trainHeadStation').value(),\n times: {\n orig: leg.attr('origTimeMin').value(),\n dest: leg.attr('destTimeMin').value()\n }\n };\n })\n })\n });\n\n // If you hate libxmljs, you can access the raw buffered body too!\n //\n // console.log(body);\n //\n // bart.sched.arrive() will also return the request instance, if you\n // would rather parse the output using a streaming parser such as\n // sax-js.\n done(trips)\n });\n}", "function planTrip(sLine, sStop, eLine, eStop){\r\n\r\n // Getting the selected start line\r\n var line = getLine(sLine);\r\n // Printing the output of the line and stops\r\n console.log(`You must travel through the following stops on the ${sLine} line: ${fromTo(line, sStop, communStop)}`)\r\n\r\n // Changing the line if it's not the same line for the whole trip\r\n if(sLine !== eLine)\r\n console.log(`Change at Union Square from the ${sLine} line to the ${eLine} line.`);\r\n\r\n // Getting the selected end line\r\n line = getLine(eLine);\r\n // Printing the output of the line and stops\r\n console.log(`Your journey continues through the following stops: ${fromTo(line, communStop, eStop)}`)\r\n\r\n // Printing the total number of stops\r\n console.log(`${stopCounter} stops in total.`)\r\n\r\n // Reseting stop counter\r\n stopCounter = 0;\r\n}", "function calcRoute(origin, destination){\n\n var request= {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.WALKING,\n transitOptions:{\n routingPreference: google.maps.TransitRoutePreference.LESS_WALKING\n },\n unitSystem: google.maps.UnitSystem.Metric\n }\n\n directionsService.route(request, function(response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n });\n}", "async function hereGetRoutePolyline(origin, destination){\r\n let routingParameters = {\r\n routingMode: 'fast',\r\n 'transportMode': 'car',\r\n 'origin': origin,\r\n 'destination': destination,\r\n 'return': 'polyline,travelSummary'\r\n }\r\n router.calculateRoute(routingParameters, onResult, function(error){ console.log(error.message); });\r\n}" ]
[ "0.62054175", "0.5913088", "0.5890718", "0.57346815", "0.5714327", "0.56850135", "0.56673986", "0.5622518", "0.557216", "0.5567229", "0.5535041", "0.55243945", "0.5486196", "0.5436927", "0.5353946", "0.53172594", "0.53129697", "0.527652", "0.52694666", "0.52590513", "0.52135086", "0.5209383", "0.51688415", "0.51362073", "0.51137304", "0.51074564", "0.51058906", "0.51058614", "0.5103731", "0.5094913" ]
0.64472765
0
Initializes the turn and turn timer, returns timerId
function startTurnTimer(timerId, turnDuration) { console.log('\nInitializing turn timer!'); // Initialize or reset time remaining gameState.nextTurnTimestamp = Date.now() + turnDuration; console.log( 'Next turn at: ' + new Date(gameState.nextTurnTimestamp).toString().substring(16,25) ); // Every time the timer goes off, update timestamp and change turn! timerId = setInterval(() => { console.log('\n >>>>>>>>>>> ' + new Date().toString().substring(16,25) + ' - Time to change turns! <<<<<<<<<<\n'); // Update time of next turn change gameState.nextTurnTimestamp = Date.now() + turnDuration; changeTurn(); }, turnDuration); // TO DO: enable user-specified turn length return timerId; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function startTurnTimer(timerId, turnDuration, socketId) {\n\t// If turn timer isn't already running\n\tif (!timerId) {\n\t\tconsole.log('Initializing turn timer!');\n\n\t\t// Initialize time of next turn change (will use this to sync the clients)\n\t\tnextTurnChangeTimestamp = Date.now() + turnDuration;\n\n\t\tconsole.log( new Date(nextTurnChangeTimestamp).toString() )\n\n\t\t// Initialize the turn data using given user ID\n\t\tchangeTurn(socketId);\t\t\n\n\t\t// Every time the timer goes off, change turn again and broadcast the data\n\t\ttimerId = setInterval(() => {\t \t\t\t \t\t\n\t \t\tconsole.log('Time to change turns!');\n\n\t \t\t// Update time of next turn change\n\t \t\tnextTurnChangeTimestamp = Date.now() + turnDuration;\n\n\t\t\tchangeTurn(socketId);\n\n\t\t\t// Broadcast turnChange with data to ALL clients\n\t\t\tio.emit( 'turnChange', getTurnData() );\n\n\t\t\tconsole.log( getTurnData() );\n\t\t}, turnDuration); // TO DO: enable user-specified turn length\n\t}\n\treturn timerId;\n}", "function initializeTimer(timerId){\n setupTimerButtonObservers(timerId);\n updateElapsedTime(timerId);\n // Start the timer so that it updates every second when active\n window.setInterval(() => updateElapsedTime(timerId), 1000);\n setupDescriptionObserver(timerId);\n setupTimeElapsedObserver(timerId);\n}", "function timerInit(){\n\t\ttimer = setTimeout(timeUp, timeToAnswer*1000);\n\t}", "function resetAndStartTimer(){\n myTimer.stop();\n myTimer.start(11).on('end',function(){\n io.sockets.in(gameId).emit('timer', { time: 10000 });\n resetAndStartTimer();\n //send name and score of next user and pass the turn\n var player = players[playingPlayer];\n var opponent = players[(player.index+1)%players.length];\n io.to(player.socket.id).emit('result', player.shots, player.score);\n io.to(opponent.socket.id).emit('update map', player.shots,player.score);\n\n nextTurn();\n });\n }", "function setTimer(roomId) {\n const room = rooms[roomId];\n room.currentClaims = [0, 0, 0, 0];\n let sec = turnTime;\n var timer = setInterval(function(){\n io.to(roomId).emit('turn-timer', sec);\n if (sec === 0){\n clearInterval(timer);\n room.timerElapsed = true;\n executeGreatestClaim(roomId);\n }\n sec--;\n }, 1000);\n}", "function timerSetup() {\n // MINIGAME 1: 35sec\n if (minigame1) {\n timer = 35;\n }\n // MINIGAME 2: 5sec\n else if (minigame2) {\n timer = 5;\n }\n}", "function init() {\n if(player1Turn === true ) {\n countdown();\n playerOne();\n player1Turn = false;\n $('#clicker').attr('id', 'clicker2');\n $('#clicker2').attr('id', 'clicker');\n } else {\n changePlayer();\n playerTwo();\n player2Turn = false;\n }\n }", "function startTimer() {\n\tif (timerSeconds.innerHTML === '00') {\n\t\tcountUp = setInterval(setTime, 1000); //allows us to call clearInerval on this variable later.\n\t}\n}", "function initializeTimer() {\n clockRunning = true;\n if (clockRunning = true) {\n timerInterval = setInterval(decrement, 1000);\n }\n }", "function startTimer(_timer){\n _timer.start({\n countdown: true,\n startValues: {\n seconds: 30\n }\n });\n }", "function startTimeoutTimer(who) {\n\tTIMER_STOPPED = true;\n\tTIMER_SHOTCLOCK_STOPPED = true;\n\n\t$('#start_timer').show();\n\t$('#stop_timer').hide();\n\t\n\tTIMEOUT_COUNTER = TIMEOUT_LENGTH;\n\tshowFouls(false);\n\tdisableButtons(true);\n\n\tif(who == HOME)\n\t\tonLED('#home_foul_count', TIMEOUT_ARROW[0]);\n\telse\n\t\tonLED('#away_foul_count', TIMEOUT_ARROW[1]);\n\n\tTIMEOUT_TIMER = setInterval(timeoutTimer, 1000);\n}", "function startTimer() {\n\tgameData.timer = setInterval(timerData.timeCounter, 1000);\n}", "function initSetTimerListeners() {\n\t$(\"#breakLength .fa-minus\").on(\"click\", function() {\n\t\tif(!running\t&& !$(\"#clock-container\").hasClass(\"paused\")) {\n\t\t\tif(breakTime > 1) {\n\t\t\t\tbreakTime -= 1;\n\t\t\t\t$(\"#break\").text(breakTime);\n\t\t\t}\n\t\t}\n\t});\t\n\n\t$(\"#breakLength .fa-plus\").on(\"click\", function() {\n\t\tif(!running\t&& !$(\"#clock-container\").hasClass(\"paused\")) {\n\t\t\tif(breakTime < 60) {\n\t\t\t\tbreakTime += 1;\n\t\t\t\t$(\"#break\").text(breakTime);\t\t\n\t\t\t}\n\t\t}\n\t});\t\n\t$(\"#sessionLength .fa-minus\").on(\"click\", function() {\n\t\tif(!running\t&& !$(\"#clock-container\").hasClass(\"paused\")) {\n\t\t\tif(sessionTime > 1) {\n\t\t\t\tsessionTime -= 1;\n\t\t\t\t$(\"#session\").text(sessionTime);\n\t\t\t}\n\t\t}\n\t});\t\n\t$(\"#sessionLength .fa-plus\").on(\"click\", function() {\n\t\tif(!running\t&& !$(\"#clock-container\").hasClass(\"paused\")) {\n\t\t\tif(sessionTime < 60) {\n\t\t\t\tsessionTime += 1;\n\t\t\t\t$(\"#session\").text(sessionTime);\n\t\t\t}\t\n\t\t}\n\t});\n}", "function initializeTimer() {\n //stopWatch = new DS.Utility.timer.Stopwatch(autoCompleteOnKeyPressDelay, onTimerCallBack, false);\n }", "function initTimer() {\n Consts.stockTime = 0;\n Consts.currStatus = Status.init;\n initRefresh = setInterval(refreshClock, 1);\n}", "function setTime() {\n //increments timer\n ++totalSeconds;\n //temporarily stops timer at 5 seconds for my sanity\n if (totalSeconds === 59) {\n totalMinutes += 1;\n totalSeconds = 0;\n }\n\n //stops timer when game is won\n if (gameWon === true) {\n return;\n }\n //calls function to display timer in DOM\n domTimer();\n }", "function startTimer() {\r\n\r\n timerControl = true;\r\n initTime = getCurrTime();\r\n btnReset.classList.add(\"inactive\");\r\n btnLap.classList.remove(\"inactive\");\r\n}", "function startTimer() {\n setTimeout(function () {\n //when game is stopped timer from previous game shouldn't infere\n if (!pausedGame) timerDone = true;\n }, 10000);\n}", "function startTimer() {\n currentTime = 0;\n timeoutStore = setInterval(updateTimer, timeIncrementInMs);\n }", "function startTimer() {\n if (timerID == -1) {\n timerID = setInterval(tickTimer, 1000);\n }\n }", "function startCounter() {\n timer = $('#timer').timer();\n}", "function Timers() {\n\n this.timers = {};\n this.idCounter = 0;\n\n}", "_switchTimer() {\n if (this.state.isRunning) {\n this._stopTimer();\n return;\n }\n this._startTimer();\n }", "function initializePolicyLockTimer() {\r\n // Create timer object\r\n objPolicyLockTimer = new policyLockTimerObj();\r\n objPolicyLockTimer.timeoutInMilliSeconds = policyLockDuration * 60 * 1000;\r\n objPolicyLockTimer.timeoutHandler = \"policyLockTimeoutHandler()\";\r\n\r\n // Start the timer\r\n if (objPolicyLockTimer.active) {\r\n objPolicyLockTimer.startTimer();\r\n }\r\n}", "function Timer(state, runTime) {\n // Public properties, assigned to the instance ('this')\n this.state = state;\n this.runTime = runTime;\n //this.cardId = cardId;\n this.timeManager = \"\";\n }", "function loadTimer() {\n currentTimerType = PEvents.nextTimer(currentTimerType);\n \n switch (currentTimerType) {\n case PEvents.Timers.pomodoro:\n minutes = 25;\n seconds = 0;\n break;\n \n case PEvents.Timers.short_break:\n minutes = 5;\n seconds = 0;\n break;\n\n case PEvents.Timers.long_break:\n minutes = 25;\n seconds = 0;\n break;\n }\n\n render();\n }", "function moveCounter(){\n moves++;\n counter.innerHTML= moves;\n //start timer on first click\n if(moves == 1){\n second = 0;\n minute = 0; \n hour = 0;\n startTimer();\n } \n}", "function _startTimer() {\n service.timer.start(times.ONE_MINUTE);\n }", "function fnTimerStart(strIdentifier) {\n if (typeof(arrTimer)==\"undefined\")\n arrTimer = new Array()\n if (typeof(arrTimer[strIdentifier])==\"undefined\")\n arrTimer[strIdentifier] = [(new Date()).getTime()]\n else\n arrTimer[strIdentifier][0] = (new Date()).getTime()\n}", "function startTimer() {\n // Set time remaining based on selection\n if (id(\"time-3\").checked) {\n timeLeft = 180;\n } else if (id(\"time-5\").checked) {\n timeLeft = 300;\n } else {\n timeLeft = 600;\n }\n // Set the timer for first second\n id(\"timer\").textContent = timeConvert(timeLeft);\n // Timer to update every second\n timer = setInterval(function() {\n timeLeft --;\n // If time runs out, end the game\n if (timeLeft === 0) {\n gameOver();\n }\n id(\"timer\").textContent = timeConvert(timeLeft);\n }, 1000); // function runs every 1000 ms\n}" ]
[ "0.69657207", "0.6415698", "0.6256748", "0.62334555", "0.61666274", "0.6148235", "0.6038309", "0.6023115", "0.60155964", "0.60087466", "0.5994431", "0.5968748", "0.5964544", "0.5924045", "0.5791115", "0.57769287", "0.5763371", "0.5730712", "0.5725152", "0.5721867", "0.57150334", "0.5712649", "0.5712354", "0.57036114", "0.56838137", "0.5679625", "0.5673791", "0.56504005", "0.5622128", "0.55894876" ]
0.6997706
0
Start of ajax call for removing a post
function RemoveAPost(btn) { var postId = $(btn).attr('data-postid'); $.ajax({ type: 'POST', url: `/Admin/RemoveAPost/${postId}`, success: function (response) { window.location.href = response.redirectToUrl; alert('Post removed!'); }, error: function (response) { alert(response.responseText); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteThisPost() {\n $.ajax({\n //Send ID of swiped list item to PHP\n type: 'GET',\n //Value stored in each post used to identify post in database\n //When value is sent to php it can remove selected post \n data: 'myPostIDValue='+$('#myPostIDStorage').val(),\n url: 'http://wander-app.org/deletePosts.php',\n timeout: 5000,\n success: function(data){\n //ON SUCCESS CALL FUNCTION TO REMOVE ITEM\n $('#'+ $('#myPostIDStorage').val()).remove();\n },\n \n error: function(){\n //Handle Error\n alert('Error Deleting Post');\n \n }\n \n });\n \n \n return false;\n }", "function deletePost(){\n // GET INPUT VALUE ONLY AFTER CLICK\n var id = $('[name=\"delete\"]').val();\n $.ajax({\n url: apiUrl + id,\n method: \"DELETE\",\n success: function() {\n alert(\"Post with id\" + id + \" deleted\");\n }\n })\n }", "removeMovieFromAjax() { }", "function removeTagFromPost(obj, ev) {\n ev.preventDefault();\n var $el = $(obj);\n var post_id = $el.data('freq')\n .i;\n var author_id = $el.data('freq')\n .auth;\n var nid = $el.data('freq')\n .nid;\n ajaxLoading();\n var send = jAjax('/cmd.php', 'post', 'cmd=removeTagFromPost&i=' + post_id + '&auth=' + author_id);\n send.done(function(data) {\n removeAjaxLoad();\n if(data == 0) return displayErr(lang.post_not_found);\n else {\n $('#hook_FormButton_fri_' + nid)\n .trigger('click');\n }\n });\n}", "function removePost(id){\n oqituvchiService.getStatus(id,location.reload(),console.log(\"xato\"))\n}", "function adminDeletePost(evt) {\n\tvar pid = $(evt.target).parents().filter('ul').attr('id');\n\t$.ajax({\n\t\turl: \"api.php?type=post&method=adminDeletePost\",\n\t\ttype: \"POST\",\n\t\tdataType: \"json\",\n\t\tsuccess: hidePost,\n\t\terror: errorPost,\n\t\tdata: {'pid': pid}\n\t});\n\n}", "function deletePost(postTitle, postId) {\n\tvar requestType;\n\tif (window.XMLHttpRequest) {\n\t\trequestType = new XMLHttpRequest();\n\t} else {\n\t\trequestType = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t}\n\trequestType.open(\"POST\", \"deleteMethod.php\", true);\n\trequestType.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");\n\trequestType.send(\"postTitle=\"+postTitle+\"&postId=\"+postId);\n\n\trequestType.onreadystatechange = function() {\n\t\tif (requestType.readyState == 4 && requestType.status == 200) {\n \t\t\tvar storeResponce = requestType.responseText;\n\n\t\t\tif (storeResponce == \"READY\") {\n\t\t\t\t$(\".\"+postId).remove();\n\t\t\t\tdocument.cookie = \"postTitle=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n\t\t\t}\n\t\t}\n\t}\n}", "function addRemoveReadingListItem(postId) {\n $(\".tooltip\").hide();\n var data = {\n 'post_id': postId,\n };\n addCsrf(data);\n $.ajax({\n type: 'POST',\n url: VrConfig.baseURL + '/AjaxController/addRemoveReadingListItem',\n data: data,\n success: function (response) {\n location.reload();\n }\n });\n}", "function removePost(id){\n fanTuriService.getStatus(id,location.reload(),console.log(\"xato\"))\n}", "function deletePost(id) {\n // console.log(id)\n $.ajax({\n method: \"DELETE\",\n url: \"api/private/\" + id\n })\n .then(function() {\n getPosts() // show me posts after deleting\n\n });\n }", "function deletePost(postId) {\n var url = 'deletePost';\n var token = $('input[name=_token]').val();\n var data = {postId: postId};\n $.ajax({\n url: url,\n headers: {'X-CSRF-TOKEN': token},\n data: data,\n type: 'POST',\n datatype: 'JSON',\n success: function (resp) {\n $('#post_row_' + postId).hide();\n }\n });\n}", "function deleteUserPost() {\n var url = 'deleteUserPost';\n var postId = $('#deleteUserVideo').val();\n var token = $('input[name=_token]').val();\n var data = {postId: postId};\n $.ajax({\n url: url,\n headers: {'X-CSRF-TOKEN': token},\n data: data,\n type: 'POST',\n datatype: 'JSON',\n success: function (resp) {\n if(resp.status) {\n $('#userPost-' + postId).addClass('hide');\n }\n }\n });\n}", "function handlePostDelete() {\n\n var currentId = $(this).attr(\"entryID\");\n\n deletePost(currentId);\n }", "function ajaxClearSchedule( url )\n{\n if(confirm('Are you sure you want to clear all vendors schedule.')) {\n $('.ajaxLoading').show();\n $.post( url+'/delete',function( data ) {\n\n if(data.status =='success')\n {\n console.log(\"called succes\");\n notyMessage(data.message);\n } else {\n console.log(\"called error\");\n notyMessageError(data.message);\n }\n $('.ajaxLoading').hide();\n });\n\n }\n \n}", "function deletePost(parseId){\n\n \n let xhttp=new XMLHttpRequest();\n xhttp.onreadystatechange=function(){\n if(this.readyState==4 && this.status==200){\n document.getElementById('points'+parseId).innerHTML=\"<span style='color:red;'><h3>\"+ this.responseText+\"</h3></span>\";\n }else{\n document.getElementById(\"points\"+parseId).innerHTML=this.responseText;\n }\n };\n xhttp.open(\"GET\",\"/delete?id=\"+parseId,true);\n xhttp.setRequestHeader(\"Content-type\", \"application/json\");\n xhttp.send();\n \n\n }", "function unsaveArticle(){\n // Grab the id associated with the article from the submit button\n var thisId = $(this).attr(\"data-id\");\n\n $.ajax({\n method: \"POST\",\n url: \"/unsave/\" + thisId,\n })\n // With that done\n .done(function(data) {\n // Log the response\n console.log(data);\n location.reload();\n });\n }", "function postRemoved(post) {\n return {\n type: action_types_1.PostTypes.POST_REMOVED,\n data: post,\n };\n}", "async function delPost(event) {\n event.preventDefault();\n\n let postId = $(this).data('post');\n let apiURL = `/api/blogs/${postId}`;\n\n const response = await fetch(apiURL, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (response.ok) {\n document.location.replace('/dashboard');\n }\n }", "function interest_company_post(){\n $(\".interest-post\").click( function(){\n var post_id = $(this).attr('post-id');\n $.ajax({\n url: \"/ucjobs/interest_company_post/\" + post_id,\n type: \"GET\",\n dataType: \"html\",\n success: function(html){\n $(\".interest_list\").empty();\n $(\".interest_list\").first().prepend(html);\n },\n });\n return false;\n });\n}", "function deletegroup(group) {\n $.ajax({\n type: \"POST\",\n url: BASE_URL + \"/group/groupdelete\",\n data: {\n \"group\": group\n },\n success: function(result) {\n var resultArr = result.split('~#~');\n if (resultArr[0] != '0') {\n $('#delete-group-wrapper').hide();\n $('#delete-group-message').show();\n $('#mygroup-row-' + resultArr[1]).remove();\n $.dbeePopup('close');\n //$('#mygroup-row-'+group).remove(); \n if ( $('#my-dbees li').length == 0) {\n $('.postListing')\n .append('<div align=\"center\" class=\"noFound\">You are not a member of any Groups</div>');\n }\n\n }\n }\n });\n\n}", "function deleteHistory() {\n // Ajax to send a DELETE request to server\n $.ajax({\n method: 'Delete',\n url: '/history'\n })\n .then(function (response) {\n console.log(response);\n submissions = 0;\n })\n .catch(function (error) {\n console.log('Error:', error);\n });\n getHistory();\n}", "function deletePosts(postId) {\n let $postDiv = $(`#${'delete' + postId}`);\n $.ajax({\n async: true,\n type: 'DELETE',\n url: `${$HEROKU_URL}/api/v1/posts/${postId}`,\n dataType: 'json',\n success: function () {\n },\n error: function () {\n }\n });\n $postDiv.empty();\n}", "removePost(id){\n console.log(\"remove id:\" + id);\n fetch(\"http://localhost:8080/delete/\" + id, {\n method: 'DELETE',\n });\n }", "function removeItem(id,type){\n $.ajax({\n url: Routing.generate('fly_platform_package_calendar_events_remove',{id: id, type: type}),\n type: 'POST',\n format: 'json',\n async: false,\n data: {},\n success: function (res, textStatus, xhr) {\n // console.log(res.data);\n if(res.asc == 'success'){\n $('#calendar').fullCalendar( 'refetchEvents' );\n showHideModal('#newPkgModal','hide');\n }else{\n alert(res.msg);\n }\n\n },\n error: function(){\n alert('errors');\n }\n });\n}", "function removeArticle(id) {\n console.log(\"called removeArticle:\", id);\n let idx = id.replace('jumbotron-','');\n console.log(data.articles[idx].title);\n article = {\n \"key\": data.articles[idx].publishedAt\n }\n\n $.ajax({\n url: \"/remove-article\",\n type: 'POST',\n data: JSON.stringify(article),\n processData: false,\n contentType: 'application/json'\n }).success(function (data) {\n console.log(data);\n $('#'+id).remove();\n });\n}", "function delete_post(post_id) {\n\n $.ajax({\n method: \"GET\",\n url: \"REST_api/user\",\n processData: false,\n contentType: \"application/json\",\n data: '',\n success: function (r) {\n var details = JSON.parse(r)\n\n if (details.Status == \"Good\") {\n\n $.ajax({\n method: \"DELETE\",\n url: \"REST_api/post?post_id=\" + post_id,\n processData: false,\n contentType: \"application/json\",\n data: '',\n success: function (r) {\n console.log(r);\n },\n\n error: function (r) {\n console.log(r);\n }\n });\n\n } else if (details.Status == \"Deactivated\") {\n alert('Sorry, you are restricted from performing that action. Your account is deactivated. Contact site administration for more details.');\n } else if (details.Status == \"Not logged in\") {\n window.location.href = 'login.html';\n } else if (details.Status == \"Admin\") {\n // window.location.href = 'admin_dashboard.html';\n }\n },\n error: function (r) {\n console.log(r);\n\n }\n });\n\n}", "remove(){\r\n try{\r\n this.request.abort();\r\n }catch(e){\r\n // fails silently\r\n }\r\n try{\r\n if(this.event != null){\r\n this.event.remove();\r\n }\r\n Object.keys(this).forEach(function(key) { \r\n if(this && this[key]){\r\n delete this[key];\r\n } \r\n });\r\n }catch(e){\r\n console.warn('Error deleting XHR object: ' + e.message);\r\n }\r\n }", "function removeFromPlaylist(button, playlistId) {\n var songId = $(button).prevAll(\".songId\").val();\n\n $.post(\"include_files/form_handlers/ajax/removeFromPlaylist.php\", { playlistId: playlistId, songId: songId })\n .done(function(error) {\n\n if(error != \"\") {\n alert(error);\n return;\n }\n\n //do something when ajax returns\n openPage(\"playlist.php?id=\" + playlistId);\n });\n}", "function remove(element,event) {\n event.preventDefault();\n var href;\n if (window.location.search)\n {\n href = element.search.replace('?', '&');\n } else\n {\n href = element.search;\n }\n var url_string = window.location.href + href;\n var url = new URL(url_string);\n var path = url.searchParams.get('path');\n $.ajax({\n url:\"delete.php\",\n type:\"POST\",\n data: {path: path},\n success:function(response)\n {\n $('.cont').html(response);\n }\n })\n\n}", "function delete_post(e){\n\te.preventDefault();\n\n\tif(e.target.classList.contains(\"delete\")){\n\t\tparent = e.target.parentElement.parentElement.parentElement\n\t\tconst parent_id = parent.id\n\t\tconst postId = parent_id.split(\"-\")[1]\n\t\tconst uid = parent_id.split(\"-\")[2]\n\n\t\t///user/:id/:pid\n\t\tconst url = \"/user/\" + uid + \"/\" + postId\n\t\tfetch(url, {method:\"delete\"})\n\t\t.then((res) => {\n\t\t\tif(res.status === 200){\n\t\t\t\tif(display_allPost_flag === true){\n\t\t\t\t\tdisplay_allPost()\n\t\t\t\t\tdisplay_allPost_flag = false\n\t\t\t\t} else {\n\t\t\t\t\tdisplay_name(false)\n\t\t\t\t}\n\n\t\t\t} else{\n\t\t\t\talert(\"delete failed\")\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tconsole.log(error)\n\t\t})\n\t}\n}" ]
[ "0.74011403", "0.6939452", "0.6862429", "0.6830156", "0.67660993", "0.67588466", "0.6688149", "0.667774", "0.6639187", "0.6617146", "0.65562356", "0.6553251", "0.6538168", "0.6498257", "0.6489831", "0.64780706", "0.64377844", "0.64377695", "0.64071834", "0.63691413", "0.63641673", "0.63628954", "0.6326117", "0.6304143", "0.630391", "0.6294412", "0.6293558", "0.62803006", "0.62643415", "0.6250718" ]
0.70103455
1
return true, if can cut into k piece by length
function count(lengthArray, woodLength, k) { var count = 0; var curLength; var i; for (i = 0; i < lengthArray.length; i++) { curLength = lengthArray[i]; while (curLength >= woodLength) { count++; curLength -= woodLength; } } return count >= k; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function testK(k) {\n let commonDivisor = (num) => {\n return mul.some((item) => (num % item[0] === 0));\n };\n return Array.prototype.every.call(s, (item, index) => (commonDivisor(k + index) === (item === '0')));\n }", "function maxLength1(a, k) {\n const isSatisfied = (a, stInd, l, k) => {\n let total = 0\n for (let i = 0; i < l; i++) {\n total = total + a[stInd + i]\n if (total > k) return false\n }\n return true\n }\n let answer = 0;\n for (let l = 1; l <= a.length; l ++) {\n for (let stInd = 0; stInd <= a.length - l; stInd ++) {\n if (isSatisfied(a, stInd, l, k)) {\n answer = l\n }\n }\n }\n return answer\n}", "function divingBoard(k, shorter, longer) {\n const lengths = [];\n let length = 0;\n\n let i = 0;\n let kCopy = k;\n\n while (kCopy >= 0) {\n length += (shorter * i);\n length += (longer * (k-i));\n lengths.push(length);\n i++;\n kCopy--;\n length = 0;\n }\n return lengths;\n}", "function place(res, k) {\n\tvar abs = Math.abs;\n\tfor (var i = 0; i < k; i++) {\n\t\tif (res[i] == res[k] || abs(res[i] - res[k]) == abs(i - k))\n\t\t\treturn false;\n\t}\n\treturn true;\n}", "checkFinish(data, k) {\n for (var i = 0; i < k; i++) {\n if (!this.compareArray(data[i].k, data[i].temp)) {\n return false\n }\n }\n return true;\n }", "function placePiece(n, k, position){\n //base ending condition\n if (k == n) {\n if(checkDiagonal(position)){\n console.log(position);\n printboard(position);\n count++;\n }\n return;\n }\n\n var localPos = position.slice(0);\n\n //recursion for k\n // 1. produce available array\n var available = allRows.filter( row => !localPos.includes(row));\n available.forEach( spot => {\n localPos[k] = spot;\n placePiece(n, k + 1, localPos);\n });\n\n}", "function partitionArray(k, numbers) {\n console.log('k:', k)\n console.log('numbers', numbers)\n const arrLen = numbers.length\n console.log('arrLen', arrLen)\n var arr1 = []\n var arr2 = []\n // if arr can by evenly divided k times proceed\n if (arrLen % k === 0) {\n console.log('yes')\n return 'Yes'\n } else {\n // else return 'no'\n console.log('no')\n return 'No'\n }\n}", "function containsCloseNums(nums, k) {\n for (let i = 0; i < nums.length; i++) {\n for (let j = 0; j < nums.length; j++) {\n if (i !== j && nums[i] === nums[j]) {\n return Math.abs(i - j) <= k\n }\n }\n }\n return false\n}", "function divingBoard (short, long, k) {\n let set = new Set();\n dfs(k, 0);\n return set;\n\n function dfs(n, length) {\n if (n === 0) return set.add(length);\n \n dfs(n - 1, length + short);\n dfs(n - 1, length + long);\n }\n}", "function cutTheSticks(a) {\n // console.log(a);\n let ret = [];\n\n if (checkArrayStickIsTheSame(a)) return a.length;\n\n for (let i = a.length; i > 1; ) {\n let temp = [...a];\n let cutt = cut(a, minArr(a));\n // console.log(\"min a = \", minArr(a));\n // console.log(\"A after cut \", cutt);\n a = cutt.arr;\n let cc = countCutInArrayStick(temp, a);\n i -= cutt.numCut;\n // console.log(a);\n // console.log(\"len a \", i);\n // console.log(\"num cut \", cc);\n ret.push(cc);\n //console.log(i);\n }\n ret.push(1);\n return ret;\n}", "function maxLength3(a, k) {\n let answer = 0\n for (i = 0; i < a.length; i++) {\n let total = 0\n let l = 0\n for (let curInd = i; curInd < a.length; curInd++) {\n total = total + a[curInd]\n if (total <= k) {\n l = curInd - i + 1\n } else break\n }\n if (l > answer) answer = l\n }\n return answer\n}", "function testKSubsets() {\n assert.deepStrictEqual(KSubsets(num, 2), [[1, 2], [1, 3], [2, 3]]);\n assert.deepStrictEqual(KSubsets(num, 0), [[]]);\n assert.deepStrictEqual(KSubsets(num, 3), [[1, 2, 3]]);\n return true;\n}", "function containDuplication(arr,k){\n if(arr.length===0)\n return false;\n let index1=0;\n let index2=0\n for(let i=0;i<arr.length;i++){\n for(let j=i+1;j<arr.length;j++){\n if(arr[i]===arr[j]){\n index1=i;\n index2=j\n } \n }\n if(index2-index1<=k) return true;\n }\n return false;\n}", "chooseKCombos (string, k) {\n // initialize combination array\n var combos = [];\n // Edge cases: make sure k >= the number of elements in set\n if (k > string.length) {\n // no solution\n return new Error(`Not enough elements to generate combinations of length ${k}`);\n } else if (k === string.length) {\n // edge case: set.length choose k < maxCombos?\n // two easy cases\n // 1. you're choosing M out of M elements\n return [string]; // only one possible combo\n } else if (k === 1) {\n // if you're choosing 1, there are M max combinations\n for (let i = 0; i < string.length; i++) {\n combos.push(string[i])\n }\n return combos;\n }\n // otherwise compute combinations\n // When the length drops below (k-1), we cannot find any (k-1)-combos, hence the upper limit for the iteration:\n for (let i = 0; i < string.length; i++) {\n var headChar = string.substring(i, i + 1);\n // Find the combinations for the tail/end of the string\n var tailCombos = this.chooseKCombos(string.slice(i + 1), k - 1);\n // For each (k-1)-combination we join it with the current\n // and store it to the set of k-combinations.\n for (let j = 0; j < tailCombos.length; j++) {\n combos.push(headChar.concat(tailCombos[j]));\n }\n }\n return combos;\n }", "function subarraysWithKDistinct(A, K) {\n function atMostK(k) {\n let start= 0;\n let res = 0;\n const count = {};\n \n for (let end= 0; end < A.length; end++) {\n if (count[A[end]] == null) count[A[end]] = 0;\n if (count[A[end]] === 0) k--;\n count[A[end]]++;\n \n while (k < 0) {\n count[A[start]]--; // shorten the window\n if (count[A[start]] === 0) k++; //if a characters stops existing, increase the total count of distinct characters\n start++; // shorten the window\n }\n res += end -start + 1;//add the subsequence count with k distinct characters\n }\n return res;\n }\n \n return atMostK(K) - atMostK(K - 1);\n }", "function maxLength2(a, k) {\n let answer = 0\n for (i = 0; i < a.length; i++) {\n let total = 0\n let l = 0\n let curInd = i\n while (total <= k && curInd < a.length) {\n l++\n total = total + a[curInd]\n console.log(total + \"total\" + l)\n curInd++\n }\n if (curInd)\n if ( l - 1 > answer) answer = l - 1\n }\n return answer\n}", "function divingBoard3(short, long, k) {\n let set = new Set();\n\n let start = short * k;\n set.add(start);\n\n let lcount = 0;\n while (lcount < k) {\n start = start - short + long;\n set.add(start);\n lcount++;\n } \n \n return set;\n}", "function killKthBit(n, k) {\n return n.toString(2)[ n.toString(2).length - k ] == '1' ?\n n -= 2 ** (k - 1) : n;\n}", "function nonDivisibleSubset(k, S) {\n // all sums % 1 are 0, and no sums % 0 are possible, so greatest subset is 1 (allowing no pairs)\n if (k <= 1) {\n return 1;\n }\n\n // store remainders in array, such that each array item is formatted as [value, count] (see helper function)\n let remainders = [];\n for (let i = 0; i < S.length; i++) {\n // using helper function\n insert(remainders, S[i] % k);\n }\n\n // identify items that, when summed, and modded k, === 0\n for (let i = 0; i < remainders.length - 1; i++) {\n for (let j = 1; j < remainders.length; j++) {\n // if an item itself % k is 0, or the item plus itself % k is 0, we can only have one of it!\n if (remainders[i][VALUE] % k === 0 || (remainders[i][VALUE] * 2) % k === 0) {\n remainders[i][COUNT] = 1;\n }\n if (remainders[j][VALUE] % k === 0 || (remainders[j][VALUE] * 2) % k === 0) {\n remainders[j][COUNT] = 1;\n }\n\n // if two items summed % k are zero, they can't coexist; reduce count of the less prevalent to 0\n if (remainders[i][VALUE] + remainders[j][VALUE] === k) {\n // if a mod match found, remove items for the lesser count\n if (remainders[i][COUNT] > remainders[j][COUNT]) {\n remainders[j][COUNT] = 0;\n }\n else {\n remainders[i][COUNT] = 0;\n }\n }\n }\n }\n\n // grab and return the total\n let result = remainders.reduce((total, current) => total + current[COUNT], 0);\n return result;\n}", "checkForSlice(fruit) {\n if (fruit.sliced || this.swipes.length < 2)\n return false;\n\n var length = this.swipes.length; // length of sword\n\n var stroke1 = this.swipes[length - 1]; // latest stroke\n var stroke2 = this.swipes[length - 2]; // second-to-latest stroke\n\n /* calculate distance from strokes 1 & 2 from fruit */\n var d1 = dist(stroke1.x, stroke1.y, fruit.position.x, fruit.position.y);\n var d2 = dist(stroke2.x, stroke2.y, fruit.position.x, fruit.position.y);\n\n /* calculate distance from stroke1 to stroke2 */\n var d3 = dist(stroke1.x, stroke1.y, stroke2.x, stroke2.y);\n\n var sliced = d1 < fruit.size || \t\t\t// if stroke1 lands directly on the fruit\n ((d1 < d3 && d2 < d3) && \t// if the fruit falls between stroke1 and stroke2\n (d3 < BLADE_LENGTH));\t\t\t// if there is a new stroke, don't connect the two\n\n fruit.sliced = sliced; // update fruit's property\n\n if(sliced) {\n if(fruit.bad) {\n boom.play();\n } else {\n splatter.play();\n }\n }\n\n return sliced;\n }", "function isCrossing(i, k){\n\t\n\tif ( i == k || i == k + 1 || i == k - 1){\n\t\treturn false;\n\t}\n\t\n\t\n\tvar path1 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k].LatLng];\n\tvar path2 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k + 1].LatLng];\n\tvar path3 = [pointarray[k].LatLng, pointarray[k + 1].LatLng, pointarray[i].LatLng];\n\tvar path4 = [pointarray[k].LatLng, pointarray[k + 1].LatLng, pointarray[i + 1].LatLng];\n\t\n\tvar area1 = google.maps.geometry.spherical.computeSignedArea(path1);\n\tvar area2 = google.maps.geometry.spherical.computeSignedArea(path2);\n\n\tvar area3 = google.maps.geometry.spherical.computeSignedArea(path3);\n\tvar area4 = google.maps.geometry.spherical.computeSignedArea(path4);\n\tvar s1 = area1 * area2; var s2 = area3 * area4;\n\t\n\tif ((s1 < 0) && (s2 < 0))\n\t{\n\t\t// exclude some pathological cases\n\t\t// otherwise rounding errors in computeSignedArea can lead\n\t\t// two wrong results\n\t\tif (s1 < -1 && s2 < -1){\n\t\t\treturn true;\n\t\t} \n\t}\n\t\n\treturn false;\n}", "function longestSubstringWithKDistinctCharacters(s, k) {\n\n // Map used to keep track of letters\n let map = new Map();\n\n let startWindow = 0;\n let endWindow = 0;\n\n let currentLength = Number.MIN_VALUE;\n\n while (endWindow < s.length) {\n\n if (!map.has(s.charAt(endWindow)) && map.size < k) {\n map.set(s.charAt(endWindow++), 1);\n currentLength = Math.max(currentLength, endWindow-startWindow);\n } else if (!map.has(s.charAt(endWindow)) && map.size === k) {\n // Remove the starting character from the map and then add current character\n // till the map has less than k distinct characters\n while(map.has(s.charAt(startWindow)) && map.size === k) {\n if (map.get(s.charAt(startWindow)) > 1) {\n map.set(s.charAt(startWindow), map.get(startWindow)-1);\n } else {\n map.delete(s.charAt(startWindow));\n }\n startWindow++;\n }\n // Add current character\n if (!map.has(s.charAt(endWindow)) && map.size < k) {\n map.set(s.charAt(endWindow++), 1);\n currentLength = Math.max(currentLength, endWindow-startWindow);\n }\n } else {\n map.set(s.charAt(endWindow), map.get(s.charAt(endWindow))+1);\n endWindow++;\n currentLength = Math.max(currentLength, endWindow-startWindow);\n }\n }\n\n return currentLength;\n}", "function solution(k) {\n const res = Array.from({ length: k }, () => 0);\n\n // 생성자\n for (let i = 1; i <= k; i++) {\n if (d(i) <= 10000) res[d(i)] = 1;\n }\n\n for (let i = 1; i < k; i++) {\n if (res[i] === 0) console.log(i);\n }\n}", "function hackerlandRadioTransmitters(x, k) {\n\n let houses = x.sort((a,b) => a - b);\n let count = 0;\n let index = 0;\n let location = 0;\n //[2,4,5,6,7,8,11,12]\n\n while(index < houses.length ){\n\n location = houses[index] + k;\n while(location >= houses[index]){\n index++;\n }\n\n index--;\n location = houses[index] + k;\n\n while(location >= houses[index]){\n index++;\n }\n\n count++;\n\n\n\n\n }\n\n return count;\n}", "function checkBigCard(hand) {\n let bigCard = true;\n let needAce = false;\n for (let card of hand) {\n if (card.Point < 9) {\n // besides all letters ATJQK\n bigCard = false;\n break;\n }\n if (card.Point == 9) {\n needAce = true;\n bigCard = false;\n }\n if (needAce) {\n for (let card of hand) {\n if (card.Point == \"A\") bigCard = true;\n }\n }\n }\n if (bigCard) return true;\n}", "function index (list, k) {\n\t return low.defined(list) &&\n\t low.has(list, 'length') &&\n\t k >= 0 &&\n\t k < list.length\n\t}", "function numOfSubarrays(arr, k, threshold) {\n let i = 0, sum = 0, count = 0;\n\n for (let j = 0; j < arr.length; j++) {\n sum = sum + arr[j];\n\n if (j - i + 1 == k) {\n if (sum / k >= threshold) {\n count++;\n }\n\n sum = sum - arr[i];\n\n i++;\n }\n }\n\n return count;\n}", "function luckBalance(k, contests) {\n\n let luck = 0\n\n let mustWinContests = []\n for (let i = 0; i < contests.length; i++) {\n if (contests[i][1] === 1) {\n mustWinContests.push(contests[i])\n }\n }\n mustWinContests = mustWinContests.sort(function(a, b){return a[0]-b[0]}).splice(0, mustWinContests.length - k)\n\n // for (let i = 0; i < contests.length; i++) {\n // if (mustWinContests.includes(contests[i]) === true){\n // luck--\n // } else {\n // luck++\n // }\n // }\n\n for (let i = 0; i < contests.length; i++) {\n luck += contests[i][0]\n }\n\n for (let i = 0; i < mustWinContests.length; i ++) {\n luck = luck - (2 * mustWinContests[i][0])\n }\n\n return luck\n}", "function checkSlice(chkLoc, cakeGrid, possSlice) {\n let chkSlice = cakeGrid\n .slice(chkLoc[1], chkLoc[1] + possSlice[1])\n .map(row => row.slice(chkLoc[0], chkLoc[0] + possSlice[0]))\n let pattern = /[o]/g;\n chkRaisins = chkSlice.join('').match(pattern);\n if (!chkRaisins ||\n chkRaisins.length > 1 ||\n chkLoc[0] + possSlice[0] > cakeGrid[0].length ||\n chkLoc[1] + possSlice[1] > cakeGrid.length) {\n return false;\n } else {\n return true;\n }\n}", "function getMaxLessThanK(n,k) {\n if(k >= 2) {\n let a = 1;\n let newArr = Array();\n while(n > a) {\n let b = a + 1;\n while(n >= b) {\n if( (a & b) < k ){\n newArr.push(a & b);\n }\n b++;\n }\n a++;\n }\n return Math.max(...newArr);\n }\n}" ]
[ "0.6280222", "0.6198108", "0.5851191", "0.5755905", "0.5754568", "0.5742839", "0.5736298", "0.5722663", "0.57152003", "0.57106644", "0.56659245", "0.56531304", "0.562795", "0.56271684", "0.5596762", "0.55515015", "0.55319893", "0.5477165", "0.54232216", "0.54221916", "0.54202914", "0.541359", "0.5409467", "0.5379728", "0.5377452", "0.53774184", "0.53520936", "0.53453934", "0.5339294", "0.5335034" ]
0.6333416
0
Send a heartbeat to all opened sockets
function sendHeartbeat() { _.forOwn(_this.socks, function (sock) { sock.write('hb'); }); setTimeout(sendHeartbeat, _this.heartbeatFreq); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function heartbeat() {\n io.sockets.emit('heartbeatUsers', users);\n io.sockets.emit('heartbeatMarks', marks);\n}", "function heartbeat() {\n\n board.updateEnemy();\n var data = {\n player_dico: board.player_dic,\n enemy_list: board.enemy,\n waveNum: board.wave_num\n };\n io.sockets.emit('heartbeat', data);\n}", "function heartbeat()\n{\n\tvar fn = function(key, val)\n\t{\n\t\tvar queue = val.queue;\n\t\tvar msg = (typeof queue != \"undefined\" && queue != null && queue.length > 0) ? queue.shift() : getSpam();\n\t\tvar skt = io.sockets.connected[val.id];\n\t\tif (skt)\n\t\t{\n\t\t\tif (msg.event && msg.data)\n\t\t\t\tskt.emit(msg.event, msg.data);\n\t\t}\n\t}\n\n\tkeyTree.inorder(fn, false);\n}", "function sendHeartbeat() {\n send(json_heartbeat_message());\n}", "sendHeartbeat() {\n this.sendPacket({ op: Constants.VoiceOPCodes.HEARTBEAT, d: null }).catch(() => {\n this.emit('warn', 'Tried to send heartbeat, but connection is not open');\n this.clearHeartbeat();\n });\n }", "sendHeartbeats() {\n // Send heartbeats to idle workers if it's time\n if ((new Date()).getTime() >= this.heartbeatAt) {\n this.waiting.forEach((worker) => {\n this.sendToWorker(worker, MDP.W_HEARTBEAT, null, null);\n })\n this.heartbeatAt = (new Date()).getTime() + HEARTBEAT_INTERVAL;\n }\n }", "heartbeat() {\n const now = Date.now();\n if (now - this.lastHeartbeat >= this.heartbeatInterval) {\n util.promisify(fs.writeFile)(this.heartbeatPath, \"\").catch((error) => {\n this.services.get(log_1.ILogService).warn(error.message);\n });\n this.lastHeartbeat = now;\n clearTimeout(this.heartbeatTimer); // We can clear undefined so ! is fine.\n this.heartbeatTimer = setTimeout(() => {\n if (this.onlineConnections.length > 0) {\n this.heartbeat();\n }\n }, this.heartbeatInterval);\n }\n }", "sendHeartbeat() {\n this.lastHeatbeatSend = Date.now();\n this.missedHeartbeats++;\n const nonce = this.lastHeatbeatSend;\n return this.sendPacket({\n op: 3 /* Heartbeat */,\n d: nonce,\n });\n }", "function heartBeat() {\n httpRequest('GET', SERVER_PATH, 'heartbeat', 'gid=' + gid + '&pid=' + pid + \"&count=\" + count);\n}", "schedule_heartbeat() {\n\t\tclearTimeout(this.heartbeat_timer);\n\t\tif (this.heartbeat_period > 0) {\n\t\t\tthis.heartbeat_timer = setTimeout(() => this.ws.ping(), this.heartbeat_period);\n\t\t}\n\t}", "function heartbeat() {\n client.publish('/heartbeat', { id: '1', type: 'emitter' });\n}", "heartbeat() {\n logger.info(`[${P2P_PREFIX}] Start heartbeat`);\n this.intervalHeartbeat = setInterval(() => {\n this.server.clients.forEach(ws => {\n ws.ping();\n });\n }, HEARTBEAT_INTERVAL_MS);\n }", "function sendHeartbeat(hostName) {\n\t\tvar socket \t = connections[hostName];\n\t\tvar heartBeat = {\"messagetype\":\"heartbeat\", \"hostName\": util.address.val, \"port\": util.port};\n\t\tsendSecure(socket, hostName, JSON.stringify(heartBeat));\t\t\n\t}", "function heartbeat () { this.isAlive = true }", "sendHeartbeat() {\n this._clearHeartbeatTimeouts();\n if (!this.heartbeatsEnabled) {\n return;\n }\n\n if (this.socket && !this.canSend('text/x-msrp-heartbeat')) {\n MsrpSdk.Logger.warn(`[Session]: Cannot start heartbeats for session ${this.sid}. Peer does not support 'text/x-msrp-heartbeat' content.`);\n return;\n }\n\n let timedOut = false;\n\n const msgQueued = this.sendMessage('HEARTBEAT', 'text/x-msrp-heartbeat', null, status => {\n if (timedOut) {\n return;\n }\n this._clearHeartbeatTimeouts();\n if (status === MsrpSdk.Status.OK) {\n MsrpSdk.Logger.debug('Successful heartbeat for session', this.sid);\n } else {\n this._raiseHeartbeatFailure(status);\n }\n this.resetHeartbeat();\n });\n\n if (!msgQueued) {\n this._raiseHeartbeatFailure(MsrpSdk.Status.INTERNAL_SERVER_ERROR);\n this.resetHeartbeat();\n return;\n }\n\n this.heartbeatTimeout = setTimeout(() => {\n timedOut = true;\n this.heartbeatTimeout = null;\n this._raiseHeartbeatFailure(MsrpSdk.Status.REQUEST_TIMEOUT);\n this.resetHeartbeat();\n }, MsrpSdk.Config.heartbeatTimeout * 1000);\n }", "onConnect() {\n this.socket && this.socket.write(this.handshake);\n this.healthCheck = setInterval(() => {\n if (new Date() - this.lastRead > 35000) {\n this.close(false);\n }\n }, 5 * 1000);\n }", "queueHeartbeat() {\n\t\t\tif (this.options.ignoreHeartbeat) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!(this.hasHandshook && this.open)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (this.heartbeatTimeout !== undefined) {\n\t\t\t\tclearTimeout(this.heartbeatTimeout);\n\t\t\t}\n\n\t\t\tthis.heartbeatTimeout = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\tthis.sendMessage([\n\t\t\t\t\t\t___R$project$rome$$internal$events$types_ts$BridgeMessageCodes.HEARTBEAT,\n\t\t\t\t\t]);\n\t\t\t\t},\n\t\t\t\t1_000,\n\t\t\t);\n\t\t}", "function socketAlive() {\n setTimeout(function() {\n socket.emit('socket_alive');\n socketAlive();\n }, 3200);\n }", "heartbeat(message)\n {\n WebsocketClient.LogMsg('heartbeat(' + message.id + ')');\n\n // Clear timeout\n clearTimeout(this.#pingTimeout);\n\n // Ping server\n const msg = WebsocketClient.#instance.#idMsg;\n msg.type = 'heartbeat';\n msg.id = message.id;\n this.#client.send(JSON.stringify(msg));\n\n this.#pingTimeout = setTimeout(() =>\n {\n WebsocketClient.LogMsg('[websocket] pingTimeout() reconnect');\n // WebsocketClient.#instance.#client.close();\n WebsocketClient.#instance.connect();\n }, 8000 + 5000);\n }", "setHeartbeatInterval(ms) {\n if (typeof this.heartbeatInterval !== 'undefined')\n clearInterval(this.heartbeatInterval);\n if (ms > 0) {\n this.heartbeatInterval = setInterval(() => {\n if (this.lastHeatbeatSend !== 0 && this.missedHeartbeats >= 3) {\n // Missed too many heartbeats - disconnect\n this.ws.close();\n this.setHeartbeatInterval(-1);\n }\n this.sendHeartbeat();\n }, ms);\n }\n }", "function sendHeartbeat () {\n var options = {\n host : 'team200-service-lister.mybluemix.net',\n path : '/heartbeat?service='+ id +'&desc=' + escape(desc) + '&url=' + link,\n method : \"GET\"\n };\n\n var callback = function(resp){\n\n resp.on('data', function(data){\n });\n\n resp.on('end', function(){\n console.log('Heartbeat Sent');\n });\n }\n var req = http.request(options, callback);\n req.end();\n}", "function sendHeartbeat () {\n var options = {\n host : 'team200-service-lister.mybluemix.net',\n path : '/heartbeat?service='+ id +'&desc=' + escape(desc) + '&url=' + link,\n method : \"GET\"\n };\n\n var callback = function(resp){\n\n resp.on('data', function(data){\n });\n\n resp.on('end', function(){\n console.log('Heartbeat Sent');\n });\n }\n var req = http.request(options, callback);\n req.end();\n}", "function sendHeartbeat () {\n var options = {\n host : 'team200-service-lister.mybluemix.net',\n path : '/heartbeat?service='+ id +'&desc=' + escape(desc) + '&url=' + link,\n method : \"GET\"\n };\n\n var callback = function(resp){\n\n resp.on('data', function(data){\n });\n\n resp.on('end', function(){\n console.log('Heartbeat Sent');\n });\n }\n var req = http.request(options, callback);\n req.end();\n}", "heartbeat () {\n }", "function startPing()\n{\n var heartbeat = 90;\n heartbeatTimerId = window.setInterval(opPing, heartbeat*1000);\n}", "function pingAllClients()\n{\n // For each client ...\n server.clients.forEach ( function each ( socket )\n {\n console.log ( \"In pingAllClients(), socket id:\", socket.id );\n\n // Is it no longer living?\n if ( false === requireProperty ( socket, \"isAlive\" ) )\n {\n console.log ( \"In pingAllClients(), terminating\" );\n\n // It's not alive so terminate it.\n socket.terminate();\n }\n\n // Otherwise, it is alive.\n else\n {\n console.log ( \"In pingAllClients(), still alive\" );\n\n // This will get reset to true in the \"pong\" handler.\n socket.isAlive = false;\n\n // Ping the client. If everything is connected this will result\n // in the \"pong\" handler being called.\n socket.ping ( doNothing );\n }\n } );\n}", "function checkHeartBeat() {\n for (var username in users) {\n sendHeartBeatToAnUser(username);\n }\n}", "function checkClientsHeartbeat() {\n var now = Date.now();\n _.forOwn(_this.socks, function (sock) {\n if (sock.hb + _this.clientTimeout < now) {\n logout(sock);\n }\n });\n setTimeout(checkClientsHeartbeat, 1000)\n }", "function heartbeat() {\n this.isAlive = true;\n}", "_startHardbeat() {\n var timeout = this.get('heartbeatTimeout');\n this.storage.setItem('singleton:heartbeat', Date.now());\n return setInterval(() => {\n this.storage.setItem('singleton:heartbeat', Date.now());\n }, timeout);\n }" ]
[ "0.7641542", "0.74248743", "0.722528", "0.7070184", "0.7062787", "0.6954447", "0.69473207", "0.678155", "0.67734224", "0.6717606", "0.6688937", "0.667452", "0.6626364", "0.6515311", "0.64502543", "0.6448521", "0.6386508", "0.6329419", "0.63277787", "0.6290269", "0.62535113", "0.62535113", "0.62535113", "0.6230178", "0.6180346", "0.6171713", "0.6142069", "0.60754925", "0.5975084", "0.59519875" ]
0.8098782
0
Check that all clients respond to the heartbeat in time
function checkClientsHeartbeat() { var now = Date.now(); _.forOwn(_this.socks, function (sock) { if (sock.hb + _this.clientTimeout < now) { logout(sock); } }); setTimeout(checkClientsHeartbeat, 1000) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function checkHeartBeat() {\n for (var username in users) {\n sendHeartBeatToAnUser(username);\n }\n}", "function funCheckHB() {\n try {\n for (let i = 0; i < global.aryClients.length; i++) {\n // If current time > (last HB received + timeout e.g. 30 seconds)\n if (Date.now() > global.aryClients[i].lastHB + config.cintHBTimeout) {\n // mRU.funUpdateServerMonitor(\"No HB Disconnect: \" + global.aryClients[i].connectionCode, true);\n // Disconnect That Client\n global.aryClients[i].socket.disconnect();\n }\n }\n } catch (err) {\n // If someone disconnect, there will be an error because aryClients.length changes\n // mRU.funUpdateServerMonitor(\"No HB Disconnect Error: \" + err, true);\n }\n\n // Check Every (Timeout / 3) Milliseconds\n setTimeout(funCheckHB, Math.floor(config.cintHBTimeout / 3));\n}", "sendHeartbeats() {\n // Send heartbeats to idle workers if it's time\n if ((new Date()).getTime() >= this.heartbeatAt) {\n this.waiting.forEach((worker) => {\n this.sendToWorker(worker, MDP.W_HEARTBEAT, null, null);\n })\n this.heartbeatAt = (new Date()).getTime() + HEARTBEAT_INTERVAL;\n }\n }", "function heartbeat() {\n io.sockets.emit('heartbeatUsers', users);\n io.sockets.emit('heartbeatMarks', marks);\n}", "heartbeat() {\n const now = Date.now();\n if (now - this.lastHeartbeat >= this.heartbeatInterval) {\n util.promisify(fs.writeFile)(this.heartbeatPath, \"\").catch((error) => {\n this.services.get(log_1.ILogService).warn(error.message);\n });\n this.lastHeartbeat = now;\n clearTimeout(this.heartbeatTimer); // We can clear undefined so ! is fine.\n this.heartbeatTimer = setTimeout(() => {\n if (this.onlineConnections.length > 0) {\n this.heartbeat();\n }\n }, this.heartbeatInterval);\n }\n }", "function sendHeartbeat() {\n _.forOwn(_this.socks, function (sock) {\n sock.write('hb');\n });\n setTimeout(sendHeartbeat, _this.heartbeatFreq);\n }", "function heartbeat()\n{\n\tvar fn = function(key, val)\n\t{\n\t\tvar queue = val.queue;\n\t\tvar msg = (typeof queue != \"undefined\" && queue != null && queue.length > 0) ? queue.shift() : getSpam();\n\t\tvar skt = io.sockets.connected[val.id];\n\t\tif (skt)\n\t\t{\n\t\t\tif (msg.event && msg.data)\n\t\t\t\tskt.emit(msg.event, msg.data);\n\t\t}\n\t}\n\n\tkeyTree.inorder(fn, false);\n}", "function heartBeat() {\n httpRequest('GET', SERVER_PATH, 'heartbeat', 'gid=' + gid + '&pid=' + pid + \"&count=\" + count);\n}", "ackHeartbeat() {\n this.debug(`Heartbeat acknowledged, latency of ${Date.now() - this.lastPingTimestamp}ms`);\n this.client._pong(this.lastPingTimestamp);\n }", "heartbeat() {\n logger.info(`[${P2P_PREFIX}] Start heartbeat`);\n this.intervalHeartbeat = setInterval(() => {\n this.server.clients.forEach(ws => {\n ws.ping();\n });\n }, HEARTBEAT_INTERVAL_MS);\n }", "function checkPulse(){\n var heartbeat = this.node.heartbeat();\n var stale = Date.now() - this.timeout > heartbeat;\n if (stale) this.emit('change', 'candidate');\n}", "function heartbeat() {\n\n board.updateEnemy();\n var data = {\n player_dico: board.player_dic,\n enemy_list: board.enemy,\n waveNum: board.wave_num\n };\n io.sockets.emit('heartbeat', data);\n}", "function funCheckHB() {\n try {\n\n // Check for auto print\n // if (Date.now() - timLastPrint > intMustPrintOnceTime) {\n // console.log('auto print to keep printer on');\n // funPrint(['自动打印...']);\n // }\n\n // Disconnect client if client has no HB for a long time\n for (let i = 0; i < aryClients.length; i++) {\n if (Date.now() > aryClients[i].lastHB + intHBTimeout) {\n funUpdateServerMonitor(\"No HB Disconnect: \" + aryClients[i].connectionCode, true);\n aryClients[i].socket.disconnect();\n }\n }\n } catch (err) {\n // If someone disconnect, there will be an error because aryClients.length changes\n // funUpdateServerMonitor(\"No HB Disconnect Error: \" + err, true);\n }\n\n // let dtTemp = Date.now();\n setTimeout(funCheckHB, intHBTimeout);\n}", "heartbeat () {\n }", "function sendHeartbeat() {\n send(json_heartbeat_message());\n}", "sendHeartbeat() {\n this.lastHeatbeatSend = Date.now();\n this.missedHeartbeats++;\n const nonce = this.lastHeatbeatSend;\n return this.sendPacket({\n op: 3 /* Heartbeat */,\n d: nonce,\n });\n }", "function timerConnected(client, server) { setInterval(function() { checkLastStanza(client, server); }, 100); }", "queueHeartbeat() {\n\t\t\tif (this.options.ignoreHeartbeat) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!(this.hasHandshook && this.open)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (this.heartbeatTimeout !== undefined) {\n\t\t\t\tclearTimeout(this.heartbeatTimeout);\n\t\t\t}\n\n\t\t\tthis.heartbeatTimeout = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\tthis.sendMessage([\n\t\t\t\t\t\t___R$project$rome$$internal$events$types_ts$BridgeMessageCodes.HEARTBEAT,\n\t\t\t\t\t]);\n\t\t\t\t},\n\t\t\t\t1_000,\n\t\t\t);\n\t\t}", "function pingAllClients()\n{\n // For each client ...\n server.clients.forEach ( function each ( socket )\n {\n console.log ( \"In pingAllClients(), socket id:\", socket.id );\n\n // Is it no longer living?\n if ( false === requireProperty ( socket, \"isAlive\" ) )\n {\n console.log ( \"In pingAllClients(), terminating\" );\n\n // It's not alive so terminate it.\n socket.terminate();\n }\n\n // Otherwise, it is alive.\n else\n {\n console.log ( \"In pingAllClients(), still alive\" );\n\n // This will get reset to true in the \"pong\" handler.\n socket.isAlive = false;\n\n // Ping the client. If everything is connected this will result\n // in the \"pong\" handler being called.\n socket.ping ( doNothing );\n }\n } );\n}", "sendHeartbeat() {\n this._clearHeartbeatTimeouts();\n if (!this.heartbeatsEnabled) {\n return;\n }\n\n if (this.socket && !this.canSend('text/x-msrp-heartbeat')) {\n MsrpSdk.Logger.warn(`[Session]: Cannot start heartbeats for session ${this.sid}. Peer does not support 'text/x-msrp-heartbeat' content.`);\n return;\n }\n\n let timedOut = false;\n\n const msgQueued = this.sendMessage('HEARTBEAT', 'text/x-msrp-heartbeat', null, status => {\n if (timedOut) {\n return;\n }\n this._clearHeartbeatTimeouts();\n if (status === MsrpSdk.Status.OK) {\n MsrpSdk.Logger.debug('Successful heartbeat for session', this.sid);\n } else {\n this._raiseHeartbeatFailure(status);\n }\n this.resetHeartbeat();\n });\n\n if (!msgQueued) {\n this._raiseHeartbeatFailure(MsrpSdk.Status.INTERNAL_SERVER_ERROR);\n this.resetHeartbeat();\n return;\n }\n\n this.heartbeatTimeout = setTimeout(() => {\n timedOut = true;\n this.heartbeatTimeout = null;\n this._raiseHeartbeatFailure(MsrpSdk.Status.REQUEST_TIMEOUT);\n this.resetHeartbeat();\n }, MsrpSdk.Config.heartbeatTimeout * 1000);\n }", "async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }", "sendHeartbeat() {\n this.sendPacket({ op: Constants.VoiceOPCodes.HEARTBEAT, d: null }).catch(() => {\n this.emit('warn', 'Tried to send heartbeat, but connection is not open');\n this.clearHeartbeat();\n });\n }", "function wrf_heartbeat(req, res) {\n\tconsole.log(\"WRF: heartbeat\");\n\tres.json({success: true, ready: true, status: \"Online\"});\n}", "function checkstatus()\n\t{\n\t\tif(disconnectwarned || !AjaxLife.Network.Connected) return;\n\t\tvar now = new Date();\n\t\tif(!now.getTime() - lastmessage.getTime() > 60000)\n\t\t{\n\t\t\tdisconnectwarned = true;\n\t\t\talert(\"No data has been received for over a minute. You may have been disconnected.\");\n\t\t}\n\t}", "function heartbeat() {\n client.publish('/heartbeat', { id: '1', type: 'emitter' });\n}", "function checkAlive() {\n for(var i = 0; i < pingSet.length; i++) {\n var ip = pingSet[i];\n setTimeout(pingHost(ip), 1000);\n }\n}", "_heartbeatIntervalFired() {\n // don't send ping if we've seen a packet since we last checked,\n // *or* if we have already sent a ping and are awaiting a timeout.\n // That shouldn't happen, but it's possible if\n // `this.heartbeatInterval` is smaller than\n // `this.heartbeatTimeout`.\n if (!this._seenPacket && !this._heartbeatTimeoutHandle) {\n this._sendPing(); // Set up timeout, in case a pong doesn't arrive in time.\n\n this._startHeartbeatTimeoutTimer();\n }\n\n this._seenPacket = false;\n }", "schedule_heartbeat() {\n\t\tclearTimeout(this.heartbeat_timer);\n\t\tif (this.heartbeat_period > 0) {\n\t\t\tthis.heartbeat_timer = setTimeout(() => this.ws.ping(), this.heartbeat_period);\n\t\t}\n\t}", "checkRemoteNodes() {\n\t\tlet now = Date.now();\n\t\tthis.nodes.forEach(node => {\n\t\t\tif (now - (node.lastHeartbeatTime || 0) > this.options.heartbeatTimeout * 1000) {\n\t\t\t\tthis.nodeDisconnected(node.nodeID);\n\t\t\t}\n\t\t});\n\t}", "heartbeat(message)\n {\n WebsocketClient.LogMsg('heartbeat(' + message.id + ')');\n\n // Clear timeout\n clearTimeout(this.#pingTimeout);\n\n // Ping server\n const msg = WebsocketClient.#instance.#idMsg;\n msg.type = 'heartbeat';\n msg.id = message.id;\n this.#client.send(JSON.stringify(msg));\n\n this.#pingTimeout = setTimeout(() =>\n {\n WebsocketClient.LogMsg('[websocket] pingTimeout() reconnect');\n // WebsocketClient.#instance.#client.close();\n WebsocketClient.#instance.connect();\n }, 8000 + 5000);\n }" ]
[ "0.7300449", "0.70118845", "0.6828728", "0.6795977", "0.67125016", "0.668401", "0.6624302", "0.66224736", "0.65680563", "0.6559366", "0.6551395", "0.6535189", "0.6523065", "0.6519578", "0.6452377", "0.6451966", "0.6442796", "0.6367847", "0.6357087", "0.63551205", "0.63424665", "0.63237846", "0.63019484", "0.6284379", "0.627751", "0.62763447", "0.6244739", "0.6235734", "0.6232941", "0.61563456" ]
0.78225017
0
listar los materiales x tipo de caja y cantidad
function listarMaterialesCaja(id_tipo_caja) { var cantidad = $("#cantidad").val(); cantidad = (cantidad=='')? 0: cantidad; $.ajax({ url: $.PATH + "almacen?function=listMaterialesCaja", data: {id_tipo_caja: id_tipo_caja}, dataType: "json", cache: false, type: "get", success: function(response) { var html = ""; if (response.data != null) { $.flgMateriales = true; // para validar envío var response = response.data; for (var i = 0; i < response.length; i++) { var color = ''; if (response[i].stock_requerido == '1') { if (response[i].stock <= response[i].stock_minimo) { color = '#FAAC58'; } } html += "<tr style='background-color: "+color+"'>"; html += "<td>"+response[i].codigo+"</td>"; html += "<td>"+response[i].nombre+"</td>"; html += "<td>"+response[i].stock+"</td>"; html += "<td>"+response[i].unidad_medida+"</td>"; var valor = 0; if (response[i].calcular == '1') { valor = parseFloat(cantidad)*parseFloat(response[i].multiplo); } else { valor = response[i].multiplo; } html += "<td><input name='id_materiales[]' type='hidden' value='"+response[i].id+"'>"; html += "<input name='materiales[]' type='text' class='decimal' style='width: 50px;' value='"+valor+"'></td>"; html += "<td>"+response[i].tipo+"</td>"; html += "</tr>"; } } else { $.flgMateriales = false; // para validar envío } $("#tbl-materiales tbody").html(html); $("#tbl-materiales tbody").css({"color":"#000"}); $(".decimal").numeric("."); $(".decimal").blur(function (e) { var v = $(this).val().trim(); v = (v == "")?0:parseFloat(v); var cantidad = $("#cantidad").val().trim(); cantidad = (cantidad == "")?0:parseFloat(cantidad); if (v == 0 && cantidad > 0) { //$(this).focus(); $.flgEntrega = false; $(this).css({"background-color":"#FF0000"}); } else { $.flgEntrega = true; $(this).css({"background-color":"#FFFFFF"}); } }); }, error: function(response) { console.log(response); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function genera_parametros(){\r\n\tx_0=103;\r\n\tm=1001;\r\n\tprimos.forEach(a=>{\r\n\t\tprimos.forEach(c=>{\r\n\t\t\tnum_ale = generador_mixto(a,c,x_0,m)\r\n\t\t\tif(num_ale.length == m){ //tambien deberia revisar si hay numeros repetidos\r\n\t\t\t\timprimir_configuracion_parametros_a_pantalla\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}", "function ColunaMatriz(coluna, tabuleiro) {\n var x = new Array(MAX);\n for(var i = 0; i < MAX; i++){\n x[i]= tabuleiro[i][coluna];\n }\n return x;\n}// fim do colunaMatriz******************************************************************", "function montaValorMes () {\r\n\t\t\t// laco de despesas\r\n\t\t\tfor (var x in $scope.despesas) {\r\n\t\t\t\t// separo a despesa\r\n\t\t\t\tvar despesa = $scope.despesas[x];\r\n\t\t\t\t// crio um atributo pres(array) na despesa\r\n\t\t\t\tdespesa.pres = [];\r\n\r\n\t\t\t\t// laco de meses até 8\r\n\t\t\t\t// for (var m=0; m<8; m++) {\r\n\t\t\t\tfor (var m=0; m<$scope.tlmeses; m++) {\r\n\t\t\t\t\tvar day = moment().add(m, \"M\").date(); // dia atual + 1\r\n\t\t\t\t\tvar month = moment().add(m, \"M\").month(); // mes atual + 1\r\n\t\t\t\t\tvar year = moment().add(m, \"M\").year(); // ano atual + 1\r\n\t\t\t\t\tvar data = ''; // variavel data\r\n\r\n\t\t\t\t\t// laco de prestacoes da despesa\r\n\t\t\t\t\tfor (var p=0; p<despesa.prestacoes; p++) {\r\n\t\t\t\t\t\tvar dia = moment(despesa.datavencimento).add(p, \"M\").date(); // dia da data despesa + index\r\n\t\t\t\t\t\tvar mes = moment(despesa.datavencimento).add(p, \"M\").month(); // mes data despesa + index\r\n\t\t\t\t\t\tvar ano = moment(despesa.datavencimento).add(p, \"M\").year(); // ano data despesa + index\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// caso o mes e ano da despesa seja = ao mes e ano atual \r\n\t\t\t\t\t\tif (mes === month && ano === year) {\r\n\t\t\t\t\t\t\tdata = {\"data\": mes+\"/\"+ano, \"valor\":despesa.valor};\r\n\t\t\t\t\t\t\t// pegando a prestação atual\r\n\t\t\t\t\t\t\tif (m === 0) { // m = o ( mes atual )\r\n\t\t\t\t\t\t\t\tdespesa.prestacao = (p+1)+\"/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (!despesa.prestacao) {\r\n\t\t\t\t\t\t// se ano = atual mas mes menor ou ano menor\r\n\t\t\t\t\t\tif ( (ano === year && mes < month) || (ano < year) ) {\r\n\t\t\t\t\t\t\tdespesa.prestacao = despesa.prestacoes+\"/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tdespesa.prestacao = \"0/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif ( data === '' ) {\r\n\t\t\t\t\t\tdespesa.pres.push({\"data\": \"00/0000\", \"valor\":\"xxxx\", \"color\":\"background:#f0f5f5; color:#ccc;\", \"icon\":\"fa-trophyx\"});\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tdespesa.pres.push(data);\r\n\t\t\t\t\t\t$scope.totais[m].valor = $scope.totais[m].valor + parseInt(despesa.valor);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif($scope.totais[m-1] != undefined && $scope.totais[m].valor < $scope.totais[m-1].valor) {\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-down\";\r\n\t\t\t\t\t\t}else if($scope.totais[m-1] != undefined && $scope.totais[m].valor > $scope.totais[m-1].valor) {\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-up\";\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-right\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t$scope.totalgeral = $scope.totalgeral + parseFloat(despesa.valor);\r\n\t\t\t}\r\n\t\t}", "function obtenerArregloFichas(item) {\r\n var arreglo = [];\r\n for(var x = 0; x < $scope.tam.fila;x++){\r\n for(var y = 0; y< $scope.tam.col;y++){\r\n if($scope.matrizLogica[x][y]==item){\r\n arreglo.push(x + \",\" + y)\r\n }\r\n }\r\n }\r\n return arreglo;\r\n }", "function resolveMatriz(){\n\tvar matriz = \n\t\t\t\t[[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0],\n\t\t\t\t[0,0,0,0,0,0,0,0,0]];\n\n\tvar nivel = parseInt($(\"#nivel\").val());\n\tvar k = parseInt($(\"#k\").val());\n\tvar i,j;\n\n\tswitch(nivel){\n\t\tcase 1: //fácil\n\t\t\tif (k == 1)\n\t\t\t\tmatriz = \n\t\t\t\t\t[[1,9,5,4,6,7,2,3,8],\n\t\t\t\t\t[4,2,8,3,5,1,7,9,6],\n\t\t\t\t\t[6,3,7,9,2,8,1,4,5],\n\t\t\t\t\t[7,1,6,8,9,4,5,2,3],\n\t\t\t\t\t[9,4,3,5,1,2,6,8,7],\n\t\t\t\t\t[8,5,2,7,3,6,9,1,4],\n\t\t\t\t\t[2,7,4,1,8,5,3,6,9],\n\t\t\t\t\t[5,6,9,2,4,3,8,7,1],\n\t\t\t\t\t[3,8,1,6,7,9,4,5,2]];\n\t\t\tif (k == 2)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[8,5,3,7,6,9,2,4,1],\n\t\t\t\t\t[7,4,9,2,8,1,3,6,5],\n\t\t\t\t\t[6,2,1,5,3,4,8,7,9],\n\t\t\t\t\t[9,8,2,6,4,3,5,1,7],\n\t\t\t\t\t[4,6,7,1,5,2,9,3,8],\n\t\t\t\t\t[3,1,5,8,9,7,6,2,4],\n\t\t\t\t\t[2,9,4,3,1,5,7,8,6],\n\t\t\t\t\t[5,7,6,4,2,8,1,9,3],\n\t\t\t\t\t[1,3,8,9,7,6,4,5,2]];\n\t\t\tif (k == 3)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[9,1,4,2,3,8,6,5,7],\n\t\t\t\t\t[2,5,8,6,1,7,4,3,9],\n\t\t\t\t\t[3,7,6,5,4,9,2,1,8],\n\t\t\t\t\t[5,8,9,3,2,1,7,6,4],\n\t\t\t\t\t[6,2,7,9,5,4,3,8,1],\n\t\t\t\t\t[1,4,3,7,8,6,5,9,2],\n\t\t\t\t\t[8,6,2,1,7,3,9,4,5],\n\t\t\t\t\t[4,9,5,8,6,2,1,7,3],\n\t\t\t\t\t[7,3,1,4,9,5,8,2,6]];\n\t\t\tif (k == 4)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[5,3,6,8,1,2,4,7,9],\n\t\t\t\t\t[1,7,4,6,9,5,8,3,2],\n\t\t\t\t\t[9,2,8,3,7,4,6,5,1],\n\t\t\t\t\t[7,4,1,9,5,6,2,8,3],\n\t\t\t\t\t[3,9,2,7,8,1,5,6,4],\n\t\t\t\t\t[6,8,5,4,2,3,1,9,7],\n\t\t\t\t\t[2,1,9,5,6,7,3,4,8],\n\t\t\t\t\t[8,5,3,1,4,9,7,2,6],\n\t\t\t\t\t[4,6,7,2,3,8,9,1,5]];\n\t\t\tif (k == 5)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[5,3,4,6,2,7,9,8,1],\n\t\t\t\t\t[9,6,2,1,5,8,4,3,7],\n\t\t\t\t\t[7,8,1,9,3,4,2,6,5],\n\t\t\t\t\t[6,4,5,7,8,3,1,2,9],\n\t\t\t\t\t[3,1,7,2,6,9,8,5,4],\n\t\t\t\t\t[8,2,9,4,1,5,3,7,6],\n\t\t\t\t\t[4,9,3,5,7,2,6,1,8],\n\t\t\t\t\t[1,5,8,3,9,6,7,4,2],\n\t\t\t\t\t[2,7,6,8,4,1,5,9,3]];\n\t\t\tif (k == 6)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[2,1,4,7,8,6,3,5,9],\n\t\t\t\t\t[7,9,8,3,4,5,2,1,6],\n\t\t\t\t\t[6,3,5,2,9,1,4,7,8],\n\t\t\t\t\t[1,5,3,8,6,2,9,4,7],\n\t\t\t\t\t[4,2,7,9,1,3,8,6,5],\n\t\t\t\t\t[8,6,9,4,5,7,1,3,2],\n\t\t\t\t\t[9,7,6,1,2,4,5,8,3],\n\t\t\t\t\t[5,4,2,6,3,8,7,9,1],\n\t\t\t\t\t[3,8,1,5,7,9,6,2,4]];\n\t\t\tif (k == 7)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[2,3,1,8,5,7,6,9,4],\n\t\t\t\t\t[6,8,7,1,9,4,2,3,5],\n\t\t\t\t\t[9,4,5,6,3,2,1,8,7],\n\t\t\t\t\t[8,2,9,4,6,1,7,5,3],\n\t\t\t\t\t[1,6,4,5,7,3,8,2,9],\n\t\t\t\t\t[5,7,3,2,8,9,4,1,6],\n\t\t\t\t\t[4,9,6,3,1,8,5,7,2],\n\t\t\t\t\t[3,5,8,7,2,6,9,4,1],\n\t\t\t\t\t[7,1,2,9,4,5,3,6,8]];\n\t\t\tif (k == 8)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[8,7,2,9,4,1,5,6,3],\n\t\t\t\t\t[6,5,1,3,7,8,9,4,2],\n\t\t\t\t\t[3,9,4,2,5,6,7,8,1],\n\t\t\t\t\t[2,3,5,1,8,7,4,9,6],\n\t\t\t\t\t[9,6,8,4,3,5,1,2,7],\n\t\t\t\t\t[4,1,7,6,2,9,8,3,5],\n\t\t\t\t\t[5,8,9,7,6,3,2,1,4],\n\t\t\t\t\t[7,4,3,8,1,2,6,5,9],\n\t\t\t\t\t[1,2,6,5,9,4,3,7,8]];\n\t\t\tif (k == 9)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[6,7,1,3,8,4,2,9,5],\n\t\t\t\t\t[9,5,4,6,2,1,7,3,8],\n\t\t\t\t\t[8,2,3,9,5,7,1,6,4],\n\t\t\t\t\t[7,4,6,5,3,2,9,8,1],\n\t\t\t\t\t[2,9,5,1,4,8,6,7,3],\n\t\t\t\t\t[3,1,8,7,9,6,5,4,2],\n\t\t\t\t\t[1,3,9,8,6,5,4,2,7],\n\t\t\t\t\t[4,8,7,2,1,9,3,5,6],\n\t\t\t\t\t[5,6,2,4,7,3,8,1,9]];\n\t\t\tif (k == 10)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[2,1,9,8,7,5,6,3,4],\n\t\t\t\t\t[3,6,4,1,9,2,8,7,5],\n\t\t\t\t\t[7,8,5,6,3,4,9,2,1],\n\t\t\t\t\t[6,2,3,5,4,9,1,8,7],\n\t\t\t\t\t[8,4,1,2,6,7,5,9,3],\n\t\t\t\t\t[9,5,7,3,8,1,4,6,2],\n\t\t\t\t\t[5,7,8,4,2,6,3,1,9],\n\t\t\t\t\t[1,9,6,7,5,3,2,4,8],\n\t\t\t\t\t[4,3,2,9,1,8,7,5,6]];\n\t\t\tbreak;\n\t\tcase 2: //médio\n\t\t\tif (k == 1)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[8,5,9,7,3,6,1,2,4],\n\t\t\t\t\t[6,2,4,9,1,5,7,3,8],\n\t\t\t\t\t[3,1,7,4,2,8,9,5,6],\n\t\t\t\t\t[4,9,5,2,8,1,3,6,7],\n\t\t\t\t\t[7,6,3,5,4,9,2,8,1],\n\t\t\t\t\t[1,8,2,3,6,7,5,4,9],\n\t\t\t\t\t[9,3,6,8,7,2,4,1,5],\n\t\t\t\t\t[5,4,8,1,9,3,6,7,2],\n\t\t\t\t\t[2,7,1,6,5,4,8,9,3]];\n\t\t\tif (k == 2)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[5,1,7,9,2,8,3,6,4],\n\t\t\t\t\t[6,8,4,3,5,1,2,7,9],\n\t\t\t\t\t[9,2,3,4,7,6,5,1,8],\n\t\t\t\t\t[8,9,5,2,1,4,7,3,6],\n\t\t\t\t\t[3,7,2,6,8,5,4,9,1],\n\t\t\t\t\t[1,4,6,7,9,3,8,2,5],\n\t\t\t\t\t[2,5,8,1,3,9,6,4,7],\n\t\t\t\t\t[4,3,9,5,6,7,1,8,2],\n\t\t\t\t\t[7,6,1,8,4,2,9,5,3]];\n\t\t\tif (k == 3)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[8,2,7,1,6,5,9,3,4],\n\t\t\t\t\t[3,5,9,4,7,8,6,1,2],\n\t\t\t\t\t[1,6,4,9,3,2,7,5,8],\n\t\t\t\t\t[9,8,2,6,5,1,4,7,3],\n\t\t\t\t\t[5,7,1,3,2,4,8,9,6],\n\t\t\t\t\t[4,3,6,8,9,7,1,2,5],\n\t\t\t\t\t[6,4,3,5,1,9,2,8,7],\n\t\t\t\t\t[2,1,8,7,4,3,5,6,9],\n\t\t\t\t\t[7,9,5,2,8,6,3,4,1]];\n\t\t\tif (k == 4)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[4,6,9,5,3,2,8,1,7],\n\t\t\t\t\t[2,5,1,8,6,7,9,4,3],\n\t\t\t\t\t[7,8,3,9,4,1,6,2,5],\n\t\t\t\t\t[5,2,4,7,8,9,3,6,1],\n\t\t\t\t\t[8,3,6,4,1,5,7,9,2],\n\t\t\t\t\t[9,1,7,3,2,6,5,8,4],\n\t\t\t\t\t[6,7,8,2,5,4,1,3,9],\n\t\t\t\t\t[1,4,5,6,9,3,2,7,8],\n\t\t\t\t\t[3,9,2,1,7,8,4,5,6]];\n\t\t\tif (k == 5)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[6,5,1,9,7,4,3,8,2],\n\t\t\t\t\t[4,9,8,3,1,2,6,5,7],\n\t\t\t\t\t[3,7,2,5,8,6,9,4,1],\n\t\t\t\t\t[1,3,5,7,2,9,8,6,4],\n\t\t\t\t\t[8,4,6,1,3,5,7,2,9],\n\t\t\t\t\t[7,2,9,6,4,8,5,1,3],\n\t\t\t\t\t[9,8,4,2,5,3,1,7,6],\n\t\t\t\t\t[5,6,7,4,9,1,2,3,8],\n\t\t\t\t\t[2,1,3,8,6,7,4,9,5]];\n\t\t\tif (k == 6)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[4,7,9,1,6,8,5,3,2],\n\t\t\t\t\t[1,6,2,5,3,9,8,7,4],\n\t\t\t\t\t[3,5,8,7,2,4,9,6,1],\n\t\t\t\t\t[8,4,5,9,7,6,2,1,3],\n\t\t\t\t\t[2,9,6,3,4,1,7,5,8],\n\t\t\t\t\t[7,3,1,8,5,2,4,9,6],\n\t\t\t\t\t[9,2,4,6,1,5,3,8,7],\n\t\t\t\t\t[6,8,3,2,9,7,1,4,5],\n\t\t\t\t\t[5,1,7,4,8,3,6,2,9]];\n\t\t\tif (k == 7)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[7,4,9,1,2,5,3,8,6],\n\t\t\t\t\t[2,5,1,6,8,3,9,4,7],\n\t\t\t\t\t[3,8,6,4,9,7,1,5,2],\n\t\t\t\t\t[8,1,7,2,5,6,4,3,9],\n\t\t\t\t\t[5,2,4,7,3,9,8,6,1],\n\t\t\t\t\t[9,6,3,8,1,4,2,7,5],\n\t\t\t\t\t[4,3,2,5,6,1,7,9,8],\n\t\t\t\t\t[6,9,8,3,7,2,5,1,4],\n\t\t\t\t\t[1,7,5,9,4,8,6,2,3]];\n\t\t\tif (k == 8)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[2,6,4,5,9,8,1,7,3],\n\t\t\t\t\t[1,5,3,4,7,2,9,6,8],\n\t\t\t\t\t[8,9,7,1,6,3,2,4,5],\n\t\t\t\t\t[5,8,9,2,1,6,4,3,7],\n\t\t\t\t\t[4,3,6,7,5,9,8,1,2],\n\t\t\t\t\t[7,1,2,8,3,4,5,9,6],\n\t\t\t\t\t[9,7,1,3,8,5,6,2,4],\n\t\t\t\t\t[3,4,5,6,2,1,7,8,9],\n\t\t\t\t\t[6,2,8,9,4,7,3,5,1]];\n\t\t\tif (k == 9)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[7,9,5,4,8,2,3,6,1],\n\t\t\t\t\t[3,8,6,9,7,1,2,5,4],\n\t\t\t\t\t[4,1,2,3,6,5,8,7,9],\n\t\t\t\t\t[2,5,7,8,1,9,4,3,6],\n\t\t\t\t\t[8,3,4,7,5,6,9,1,2],\n\t\t\t\t\t[1,6,9,2,4,3,7,8,5],\n\t\t\t\t\t[5,4,3,1,2,8,6,9,7],\n\t\t\t\t\t[9,7,1,6,3,4,5,2,8],\n\t\t\t\t\t[6,2,8,5,9,7,1,4,3]];\n\t\t\tif (k == 10)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[5,2,9,1,8,3,6,4,7],\n\t\t\t\t\t[1,8,6,5,4,7,9,3,2],\n\t\t\t\t\t[3,7,4,9,6,2,1,5,8],\n\t\t\t\t\t[9,6,8,2,3,5,7,1,4],\n\t\t\t\t\t[7,5,1,8,9,4,2,6,3],\n\t\t\t\t\t[2,4,3,6,7,1,8,9,5],\n\t\t\t\t\t[8,3,2,4,1,9,5,7,6],\n\t\t\t\t\t[4,9,5,7,2,6,3,8,1],\n\t\t\t\t\t[6,1,7,3,5,8,4,2,9]];\n\n\t\t\tbreak;\n\t\tcase 3: //difícil\n\t\t\tif (k == 1)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[7,2,3,9,6,1,8,4,5],\n\t\t\t\t\t[1,4,8,7,5,2,6,9,3],\n\t\t\t\t\t[9,5,6,3,8,4,2,7,1],\n\t\t\t\t\t[5,8,2,4,3,7,9,1,6],\n\t\t\t\t\t[6,1,4,2,9,5,7,3,8],\n\t\t\t\t\t[3,9,7,8,1,6,4,5,2],\n\t\t\t\t\t[2,3,5,6,4,9,1,8,7],\n\t\t\t\t\t[4,6,1,5,7,8,3,2,9],\n\t\t\t\t\t[8,7,9,1,2,3,5,6,4]];\n\t\t\tif (k == 2)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[4,9,6,5,3,2,8,7,1],\n\t\t\t\t\t[2,5,1,8,6,7,3,4,9],\n\t\t\t\t\t[8,7,3,1,9,4,6,5,2],\n\t\t\t\t\t[9,1,2,6,4,3,5,8,7],\n\t\t\t\t\t[5,6,4,7,8,1,9,2,3],\n\t\t\t\t\t[7,3,8,2,5,9,4,1,6],\n\t\t\t\t\t[6,8,7,9,1,5,2,3,4],\n\t\t\t\t\t[3,2,9,4,7,8,1,6,5],\n\t\t\t\t\t[1,4,5,3,2,6,7,9,8]];\n\t\t\tif (k == 3)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[1,8,2,4,3,5,7,9,6],\n\t\t\t\t\t[4,9,7,6,2,8,1,3,5],\n\t\t\t\t\t[6,3,5,7,9,1,8,2,4],\n\t\t\t\t\t[5,4,1,3,8,6,9,7,2],\n\t\t\t\t\t[7,6,3,9,5,2,4,1,8],\n\t\t\t\t\t[8,2,9,1,4,7,6,5,3],\n\t\t\t\t\t[2,7,4,8,1,3,5,6,9],\n\t\t\t\t\t[9,5,6,2,7,4,3,8,1],\n\t\t\t\t\t[3,1,8,5,6,9,2,4,7]];\n\t\t\tif (k == 4)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[4,6,1,5,9,3,2,8,7],\n\t\t\t\t\t[9,7,2,8,4,1,6,3,5],\n\t\t\t\t\t[5,8,3,2,7,6,1,9,4],\n\t\t\t\t\t[6,4,9,7,5,2,8,1,3],\n\t\t\t\t\t[1,3,5,6,8,4,9,7,2],\n\t\t\t\t\t[7,2,8,3,1,9,4,5,6],\n\t\t\t\t\t[2,1,6,9,3,5,7,4,8],\n\t\t\t\t\t[3,9,7,4,2,8,5,6,1],\n\t\t\t\t\t[8,5,4,1,6,7,3,2,9]];\n\t\t\tif (k == 5)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[9,8,3,2,7,4,1,6,5],\n\t\t\t\t\t[1,6,4,8,5,9,3,7,2],\n\t\t\t\t\t[7,5,2,1,3,6,4,8,9],\n\t\t\t\t\t[5,9,7,6,4,2,8,3,1],\n\t\t\t\t\t[2,3,1,5,8,7,9,4,6],\n\t\t\t\t\t[6,4,8,9,1,3,5,2,7],\n\t\t\t\t\t[3,7,6,4,9,1,2,5,8],\n\t\t\t\t\t[8,2,9,3,6,5,7,1,4],\n\t\t\t\t\t[4,1,5,7,2,8,6,9,3]];\n\t\t\tif (k == 6)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[1,4,7,5,8,6,2,3,9],\n\t\t\t\t\t[6,8,3,2,7,9,5,1,4],\n\t\t\t\t\t[2,5,9,3,1,4,7,8,6],\n\t\t\t\t\t[4,1,5,6,9,3,8,7,2],\n\t\t\t\t\t[7,2,8,1,4,5,6,9,3],\n\t\t\t\t\t[3,9,6,7,2,8,4,5,1],\n\t\t\t\t\t[5,6,4,9,3,7,1,2,8],\n\t\t\t\t\t[9,7,1,8,6,2,3,4,5],\n\t\t\t\t\t[8,3,2,4,5,1,9,6,7]];\n\t\t\tif (k == 7)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[1,4,6,8,3,9,2,7,5],\n\t\t\t\t\t[3,7,5,4,2,6,9,8,1],\n\t\t\t\t\t[8,2,9,1,7,5,4,3,6],\n\t\t\t\t\t[9,6,2,5,4,8,3,1,7],\n\t\t\t\t\t[4,8,3,9,1,7,5,6,2],\n\t\t\t\t\t[5,1,7,3,6,2,8,9,4],\n\t\t\t\t\t[2,5,1,7,9,3,6,4,8],\n\t\t\t\t\t[6,9,4,2,8,1,7,5,3],\n\t\t\t\t\t[7,3,8,6,5,4,1,2,9]];\n\t\t\tif (k == 8)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[4,1,2,8,3,5,7,9,6],\n\t\t\t\t\t[9,7,8,4,6,2,3,1,5],\n\t\t\t\t\t[3,6,5,9,1,7,4,8,2],\n\t\t\t\t\t[5,9,3,1,4,6,2,7,8],\n\t\t\t\t\t[6,8,4,7,2,3,9,5,1],\n\t\t\t\t\t[7,2,1,5,8,9,6,3,4],\n\t\t\t\t\t[8,5,6,3,9,4,1,2,7],\n\t\t\t\t\t[2,3,7,6,5,1,8,4,9],\n\t\t\t\t\t[1,4,9,2,7,8,5,6,3]];\n\t\t\tif (k == 9)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[1,8,4,2,3,7,9,6,5],\n\t\t\t\t\t[3,5,2,9,4,6,1,8,7],\n\t\t\t\t\t[6,9,7,5,1,8,3,4,2],\n\t\t\t\t\t[9,6,8,7,5,3,4,2,1],\n\t\t\t\t\t[4,1,5,8,6,2,7,3,9],\n\t\t\t\t\t[2,7,3,1,9,4,6,5,8],\n\t\t\t\t\t[8,3,9,6,7,5,2,1,4],\n\t\t\t\t\t[5,4,1,3,2,9,8,7,6],\n\t\t\t\t\t[7,2,6,4,8,1,5,9,3]];\n\t\t\tif (k == 10)\n\t\t\t\tmatriz =\n\t\t\t\t\t[[3,7,9,5,1,8,6,2,4],\n\t\t\t\t\t[6,1,4,9,2,3,7,8,5],\n\t\t\t\t\t[2,5,8,6,7,4,3,1,9],\n\t\t\t\t\t[1,4,7,8,5,9,2,6,3],\n\t\t\t\t\t[8,2,6,3,4,1,9,5,7],\n\t\t\t\t\t[5,9,3,7,6,2,8,4,1],\n\t\t\t\t\t[4,6,1,2,9,7,5,3,8],\n\t\t\t\t\t[9,8,2,4,3,5,1,7,6],\n\t\t\t\t\t[7,3,5,1,8,6,4,9,2]];\n\t\t\tbreak;\n\t}\n\n\tfor (i = 1; i <= 9; i++){\n\t\tfor (j = 1; j <= 9; j++){\n\t\t\t$(\"#\" + i + \"x\" + j).val(matriz[i-1][j-1]);\n\t\t}\n\t}\n}", "function agregarZonas(marcadores) {\n var valores = [];\n\n var valores = $.map(marcadores, function (value, index) {\n return value;\n });\n\n var valores2 = $.map(valores, function (value, index) {\n return value;\n });\n\n agregarZonaInterna(valores2, 0);\n}", "function listarMedicoCadastrados(cnpjClinica, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select crmv, nomeMedico, telefoneMedico, emailMedico from Medico, Estados, Clinica where Medico.Estados = Clinica.Estados and Medico.Estados = Estados.idEstados and Clinica.Estados = Estados.idEstados and Clinica.cnpj = \"+cnpjClinica+\"\", function(err, result){\n\t\t\t\tcon.release();\n\t\t\t\tres.json(result);\n\t\t\t});\n\t\t});\n\t}", "function obtenerMaterias(){\n $.ajax({\n url : '/materias-all',\n method : 'GET',\n })\n .done(function(response){\n if(response.length > 0){\n let template = '';\n response.forEach((element, index) => {\n template += `\n <tr materiaId=\"${element.mat_id}\">\n <td>${++index}</td>\n <td>${element.mat_nombre}</td>\n <td>\n <i class=\"bi bi-pencil btn edit-materia text-primary\" title=\"Editar materia\"></i>\n <i class=\"bi bi-archive btn delete-matearia text-primary\" title=\"Eliminar materia\"></i>\n </td>\n </tr>\n `;\n $('#materias').html(template);\n });\n }else{\n $('#materias').html('');\n }\n })\n }", "function fill3MatsOfResult(){\r\n let matMatsIndex = 0;\r\n let cellValue = 0;\r\n for(let row = 97; row <= 105 ; row++){\r\n for(let col = 1; col <= len; col++){\r\n cellValue = Number(document.getElementById(String.fromCharCode(row) + col).value);\r\n matRows[row-97][col-1] = cellValue;\r\n matCols[col-1][row-97] = cellValue;\r\n matMatsIndex = smallMatrixSelector(row,col);\r\n matMatsAfterFill[matMatsIndex].push(cellValue);\r\n }\r\n }\r\n}", "function question5 () {\n\tlet ans = []\n\n\tdata.forEach(function(element) {\n\t if(element.materials.length >= 8){\n\t\t ans.push(element);\n\t }\n\t})\n\n\tans.forEach(function(element) {\n\t\tconsole.log(element.title + \" has \" +element.materials.length + \" materials:\");\n\t\telement.materials.forEach(function(element2) {\n\t\t\tconsole.log(\"- \" + element2);\n\t\t})\n\t})\n}", "function carregarCampos() {\n let qtd_locais_medidos = 0;\n let element = \"\";\n let array_taxas = [];\n\n array_taxas = montaSelectTaxaMetabolica();\n\n qtd_locais_medidos = buscaQtdeLocais();\n\n if (qtd_locais_medidos < 1 || qtd_locais_medidos > 5) {\n clearAll();\n mostraErro(\"O número de locais medidos deve estar entre 1 e 5\",\"\");\n\n return;\n }\n\n resetResultado();\n\n for (let i = 0; i < qtd_locais_medidos ; i++) {\n\n element += \"<div class='window_local'>\";\n element += \"<h3>Local \" + (i+1) + \"</h3>\";\n\n element += \"<label for='ibutg_local_\" + (i + 1) + \"'>Nome</label>\";\n \n element += \"<input type='text' \";\n element += \"name='nome_local_\" + (i + 1) + \"' \";\n element += \"id='nome_local_\" + (i + 1) + \"' \";\n element += \"maxlength='25'\";\n element += \"placeholder='Nome do local medido \" + (i + 1) + \"' \";\n element += \"/>\";\n\n element += \"<label for='ibutg_local_\" + (i + 1) + \"'>IBUTG</label>\";\n \n element += \"<input type='number' \";\n element += \"name='ibutg_local_\" + (i + 1) + \"' \";\n element += \"id='ibutg_local_\" + (i + 1) + \"' \";\n element += \"placeholder='IBUTG medido no local \" + (i + 1) + \"' \";\n element += \"/>\";\n\n element += \"<label for='tempo_local_\" + (i + 1) + \"'>Tempo</label>\";\n\n element += \"<input type='number' \";\n element += \"name='tempo_local_\" + (i + 1) + \"' \";\n element += \"id='tempo_local_\" + (i + 1) + \"' \";\n element += \"placeholder='Tempo no local \" + (i + 1) + \" (minutos)' \";\n element += \"/>\";\n\n element += \"<label for='select_metabolica_local_\" + (i + 1) + \"'>Atividade</label>\";\n\n element += \"<select name='select_metabolica_local_\" + (i + 1) + \"'\";\n element += \"id='select_metabolica_local_\" + (i + 1) + \"' onchange='selecionarTaxa(\" + (i + 1) + \")'>\";\n\n\n for (let x = 0; x < array_taxas.length ; x++) {\n element += \"<option value='\";\n element += array_taxas[x]['valor'];\n element += \"'>\";\n element += array_taxas[x]['descricao'];\n element += \"</option>\";\n }\n\n element += \"</select>\";\n\n element += \"<label for='metabolica_local_\" + (i + 1) + \"'>Taxa Metabólica</label>\";\n\n element += \"<input type='number' \";\n element += \"name='metabolica_local_\" + (i + 1) + \"' \";\n element += \"id='metabolica_local_\" + (i + 1) + \"' \";\n element += \"placeholder='Taxa metabólica no local \" + (i + 1) + \"' \";\n element += \"readonly/>\";\n\n element += \"</div>\";\n }\n\n $(\".window_campos\").html(element);\n $(\"#calcular\").show();\n\n return;\n}", "function Unidad(data,nombre) {\n var total = data.filter(function(d) {\n return d[\"UNIDAD DE ADSCRIPCIÓN\"] == nombre.parent;\n }).filter(function(d) { return d[\"ÁREA DE ADSCRIPCIÓN\"] == nombre.hijo });\n// console.log(total)\n var hombres = total.filter(function(d) { return d[\"SEXO\"] == \"H\"; }).length\n var mujeres = total.filter(function(d) { return d[\"SEXO\"] == \"M\"; }).length;\n total = total.length;\n\n return [{key:hombres,sexo:\"H\"},{key:mujeres,sexo:\"M\"}]\n}", "function municoesAndam(){\n\tif(jogoEmAndamento==true){\n\t\tmunicoes.forEach(andarMunicao);\n\t}\n}", "function matriz (col, lin) {\n //A variável Matriz é a escolhida para receber os dados das colunas e linhas do tabuleiro\n let matriz = [];\n let i = 0;\n let j = 0;\n //Utilizando Nested For Loops - ou For Loops dentro de outors - vamos criar arrays que serão os números\n //de linhas e enviá-los para a Matriz, lembrando que cada vez que rodarmos o For loop para as linhas,\n //o loop entenderá que deve-se criar novamente um array linha vazio []\n for(i = 0; i < lin; i++){\n let linha = [];\n matriz.push(linha);\n for(j = 0; j < col; j++){\n //Já aqui, a variável coluna irá gerar aleatoriamente números entre 0 e 6\n //Para isso, usamos a função Math.floor que serve para arredondar os números\n //E a função Math.random que gera números aleatórios entre 0 e 1.\n //Multiplicamos por 7 para que os resultados sejam arredondados para 0 - o menor\n //E 6 - o maior\n let coluna = Math.floor((Math.random() * 7));\n matriz[i].push(coluna);\n }\n }\n //Aqui visualizamos como nosso tabuleiro está até então\n console.log(matriz);\n //para que seja feita a contagem de peças, criamos a variável pecas, sendo essa\n //um array vazio que irá receber o valor inicial 0 através do For Loop.\n //O usuário pode também declarar as variáveis por si só, caso queira\n let pecas = [];\n for (i = 0; i < 8; i++){\n pecas.push(0);\n }\n //Aqui utilizamos novamente Nested Loops para checarmos os valores de cada linha e coluna\n //Como os valores podem ir de 0 até 6 - em concordância com os valores do array pecas acima\n //Cada vez que o for loop retornar um valor, ele vai acrescentar 1 ao valor correspondente\n //do índice da variável pecas\n for (i = 0; i < matriz.length; i++){\n for (j = 0; j < matriz[i].length; j++){\n pecas[matriz[i][j]]++;\n }\n }\n //com isso, criamos variaveis representando as possibilidades de pecas\n //Associadas a um determinado indice no array. Por conta do For Loop acima\n //cada variável já tem um valor armazenado, será utilizado abaixo\n vazio = pecas[0];\n peao = pecas[1];\n bispo = pecas[2];\n cavalo = pecas[3];\n torre = pecas[4];\n rainha = pecas[5];\n rei = pecas[6];\n //Por fim, iremos retornar os valores das peças abaixo.\n console.log(\"Casas vazias: \" + vazio);\n console.log(\"Peões: \" + peao);\n console.log(\"Bispos: \" + bispo);\n console.log(\"Cavalos: \" + cavalo);\n console.log(\"Torres: \" + torre);\n console.log(\"Rainhas: \" + rainha);\n console.log(\"Reis: \" + rei);\n }", "function calcularMejorEquipo() {\n const equipos = [\n new Equipo('Maria', [62, 34, 55]),\n new Equipo('Paula', [35, 60, 59]),\n new Equipo('Rebeca', [40, 39, 63])\n ];\n\n for (let i = 0; i < equipos.length; i++) {\n equipos[i].media = calcularMedia(equipos[i].resultados);\n }\n\n let mediaMasAlta = obtenerMediaMasAlta(equipos);\n console.log(\n `El equipo con la media más alta es el equipo ${obtenerEquipo(\n equipos,\n mediaMasAlta\n )} con una media de ${mediaMasAlta}`\n );\n}", "function RdatosLogistica(Material, Partidas, Destinos, Tiempo) {\n return { Material,Partidas, Destinos, Tiempo };\n}", "get icaos() {\n return this.rows.reduce((result, {icao}) => icao ? result.concat(icao) : result, []);\n }", "get allMillennialVampires() {\n let millenials = [];\n\n if (this.yearConverted > 1980) {\n millenials.push(this);\n }\n for (const child of this.offspring) {\n millenials = millenials.concat(child.allMillennialVampires);\n }\n return millenials;\n }", "function renderizaMunicoes(){\n\tmunicoes.forEach(desenhaMunicao);\n\tmunicoesAndam();\n}", "function crearniveles() {\n let niveles = [];\n let fila = 0;\n let columna = 0;\n niveles[0] = [];\n for (let c = 1; c < 21; c++) {\n niveles[0][c - 1] =\n {\n tipo: 0,\n fila: fila + 3,\n columna: columna,\n }\n if (c % 10 == 0) {\n fila++;\n columna = 0;\n } else {\n columna++;\n }\n }\n fila = 0;\n columna = 0;\n niveles[1] = [];\n for (let c = 1; c < 41; c++) {\n \tniveles[1][c - 1] =\n {\n \ttipo: 0,\n \tfila: fila + 3,\n \tcolumna: columna,\n }\n \tif (c % 10 == 0) {\n \t\tfila++;\n \t\tcolumna = 0;\n \t} else {\n \t\tcolumna++;\n \t}\n }\n\n return niveles;\n }", "cargarMatriz() {\n for(let x = 0; x < this.columna; x ++) {\n this.arregloDePosiciones[x] = new Array();\n this.llenarMatriz(x);\n }\n return this.arregloDePosiciones;\n }", "function LinhaMatriz(linha, tabuleiro){ \n var x = new Array(MAX);\n for(var i = 0; i < MAX; i++){\n x[i]= tabuleiro[linha][i];\n }\n\n return x;\n}// fim do devolve linha matriz*********************************************************", "function convertir(){\n \n \t\n \n\t\tvar countHijos = $('.content-list').children().length - 1; //21\n\t\tvar entran = countHijos / columna; // 3\n\t\tvar entran = parseInt(entran); // 3\n\t\tvar aumentar = ((entran + 1) * columna)-countHijos;\n\t\tvar func = (aumentar / columna)*100;\n\n\t\tif(columna == 1){\n\t\t\t$('.content-list .liunico').css('display', 'none');\n\t\t}else{\n\t\t\t$('.content-list .liunico').css(\"width\", func +\"%\");\n\t\t\tif(countHijos % columna == 0){\n\t\t\t\t$('.content-list .liunico').css('display', 'none');\n\t\t\t}else{\n\t\t\t\t$('.content-list .liunico').css('display', 'block')\n\t\t\t}\n\t\t}\n\n\t}", "function marcar(referencia) {\n\tvar ide = soNumero(referencia);\n\tvar x = ide[0];\n\tvar y = ide[1];\n\t// Checamos se o campo ainda nao foi marcado\n\tif (matriz[x][y] == -1) {\n\t\t// Checamos qual o proximo elemento\n\t\tif (checarProximo() == \"X\") {\n\t\t\tdocument.getElementById(referencia).className = \"x_dourado\";\n\t\t\tdocument.getElementById(\"fundo\").innerHTML = \"O\";\n\t\t} else {\n\t\t\tdocument.getElementById(referencia).className = \"o_dourado\";\n\t\t\tdocument.getElementById(\"fundo\").innerHTML = \"X\";\n\t\t}\n\t\tmatriz[x][y] = proximo;\n\t\t// Checamos se alguem ganhou\n\t\tif (checarFinal()) {\n\t\t\tanterior = false;\n\t\t\tmatriz = createMatrix(true, 3, 3);\n\t\t\tdocument.getElementById(\"fundo\").innerHTML = proximo;\n\t\t} else {\n\t\t\tanterior = false;\n\t\t\tmatriz = createMatrix(false, 3, 3);\n\t\t\tdocument.getElementById(\"fundo\").innerHTML = \"?\";\n\t\t}\n\t} else {\n\t\talert(\"Este campo já foi marcado previamente.\");\n\t}\n}", "function establecerMensajes(arrMensages) {\n\t\tvar indexValidacion = 2; \n\t\t//tomamos la lista actual del rowset \n\t\tvar listaClientes = listado1.datos; \n\t\t//realizamos la tranformaion \n\t\tfor (var i=0; i < listaClientes.length; i++){\n\t\t\t//agergamos el mensage de valiacion\n\t\t\tif (arrMensages[i] != null){\n listaClientes[i][indexValidacion] = arrMensages[i]; \n }else{\n listaClientes[i][indexValidacion] = \"\"; \n }\n\t\tlistado1.repinta();\n \t}\n }", "function question4 () {\n\tlet ans = [];\n\n\tdata.forEach(function(element) {\n\t\tfor(let j=0; j<element.materials.length; j++){\n\t\t\tif(element.materials[j] === \"wood\"){\n\t\t\t\tans.push(element.title);\n\t\t\t}\n\t\t}\n\t})\n\n\tans.forEach(function(element) {\n\t\tconsole.log(element + \" is made of wood.\");\n\t})\n}", "function question5 () {\n let multiMatList = [];\n\n for (var i = 0; i < data.length; i++) {\n if(data[i].materials.length >= 8) {\n multiMatList.push(data[i]);\n }\n }\n for (var t = 0; t < multiMatList.length; t++) {\n console.log(multiMatList[t].title + \" has \" + multiMatList[t].materials.length + \" materials:\");\n for (var n = 0; n < multiMatList[t].materials.length; n++) {\n console.log(\"- \" + multiMatList[t].materials[n]);\n }\n }\n\n}", "function livrosAugustoCury() {\n let livros = [];\n for (let categoria of livrosPorCategoria) {\n for (let livro of categoria.livros) {\n if (livro.autor === 'Augusto Cury') {\n livros.push(livro.titulo);\n }\n }\n }\n console.log('Livros do Augusto Cury: ' , livros);\n}", "function cambiarPartida(tipo){\n \n // Elimina el tablero de juego para poder crear uno nuevo\n function eliminarTablero(){\n for(let i = 0; i < tamano*tamano; i++) {\n var ultimo = document.getElementById(i);\n tablero.removeChild(ultimo)\n }\n // resetea numero de banderas la variable juego acabado, los cuadrados y el resultado.\n banderas = 0\n juegoAcabado = false\n cuadrados = []\n resultado.innerHTML = \"\"\n }\n\n // En caso de seleccionar un tipo diferente de partida cambia las caracteristicas\n function cambiaTamano(tipo){\n switch (tipo) {\n case \"principiante\":\n tamano = 10\n cantidadBomba = 10\n break\n case \"intermedio\":\n tamano = 12\n cantidadBomba = 20\n break\n case \"avanzado\":\n tamano = 16\n cantidadBomba = 40\n break\n case \"experto\":\n tamano = 20\n cantidadBomba = 100\n break\n }\n }\n\n // Elimina el tablero actual \n eliminarTablero()\n // Cambia el tamaño del buscamina actual\n cambiaTamano(tipo)\n // Crea el nuevo Tablero del buscamina\n crearTablero()\n // Reseta el contador de tiempo\n if (tiempoActivo) resetearTiempo()\n tiempo.innerHTML = 0\n}", "function listarMedicoClinica(cnpjClinica, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select crmv, nomeMedico, emailMedico, telefoneMedico from Medico, Clinica, Clinica_Medicos, Estados where Medico.Estados = Clinica.Estados and Clinica_Medicos.cnpjClinica = Clinica.cnpj and Clinica_Medicos.crmvMedico = Medico.crmv and Medico.Estados = Estados.idEstados and Clinica.Estados = Estados.idEstados and Clinica.cnpj = \"+cnpjClinica+\"\", function(err, result){\n\t\t\t\tcon.release();\n\t\t\t\tres.json(result);\n\t\t\t});\n\t\t});\n\t}" ]
[ "0.5611846", "0.5522354", "0.5487825", "0.54733056", "0.54161376", "0.5362004", "0.53283936", "0.5312302", "0.5306814", "0.5301719", "0.5290203", "0.5288451", "0.5285376", "0.5266509", "0.5254296", "0.5251927", "0.52505857", "0.524609", "0.52444655", "0.52305555", "0.52245694", "0.5208618", "0.5193914", "0.51932347", "0.51918405", "0.5176613", "0.51682043", "0.51594627", "0.515269", "0.5152344" ]
0.56832665
0
Facts Fetches facts from the servers and adds them to the DOM.
function getFacts() { fetch('/data').then(response => response.json()).then((fact) => { // fact is an object, not a string, so we have to // reference its fields to create HTML content const factsListElement = document.getElementById('server-facts-container'); factsListElement.innerHTML = ''; factsListElement.appendChild( createListElement('Fact 1 : ' + fact.fact1)); factsListElement.appendChild( createListElement('Fact 2 : ' + fact.fact2)); factsListElement.appendChild( createListElement('Fact 3 : ' + fact.fact3)); factsListElement.appendChild( createListElement('Fact 4 : ' + fact.fact4)); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fetchFacts() {\n // call fetch on the cat facts api getting one random fact\n fetch(`https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=1`)\n // when you get a response, save the text\n .then(response => response.text())\n // get the data from response.text\n .then(data => {\n // convert the data to JSON(like res.json() from api.js, just a different way to do it) and save it as a variable\n fact = JSON.parse(data).text;\n // create a p tag element and assign it to a variable\n let paragraph = document.createElement('p');\n // create a text node element and assign the value to fact from the json data\n let node = document.createTextNode(fact);\n // append the text node to the p tag\n paragraph.appendChild(node);\n // append the p tag to the facts list\n factsList.appendChild(paragraph);\n })\n // if it fails log the error\n .catch(err => console.log(err));\n}", "addToFacts() {\n if (this.species.toLowerCase() != \"pigeon\") {\n this.facts.push(this.compareDinoHeight(), this.compareDinoWeight(),this.compareDinoDiet());\n }\n }", "function fetchResultsFacts(e) {\n e.preventDefault();\n let url = baseURL + factSearch.value;\n\n console.log(\"URL:\", url);\n\n fetch(url) // using URL variable along with the proxyurl to bypass the \"cors-original\" policy\n .then(function(result) {\n return result.json();\n })\n .then(function(json) {\n displayRandomResults(json);\n });\n\n function displayRandomResults(json) {\n console.log(\"Display Results\", json); // displays the fetched results\n while(resultsSection.firstChild) {\n resultsSection.removeChild(resultsSection.firstChild);\n }\n\n let generatedFacts = json;\n\n if(factSearch.length === 0) {\n console.log(\"No results\"); // if left blank, no results\n } else {\n let resultForm = document.createElement(\"form\");\n resultForm.setAttribute(\"class\", \"resultForm\");\n let headerTag = document.createElement(\"h2\");\n headerTag.setAttribute(\"id\", \"headerTag\");\n let clearFixRandom = document.createElement(\"div\");\n clearFixRandom.setAttribute(\"class\", \"clearFixRandom\");\n let paraFact = document.createElement(\"para\");\n paraFact.setAttribute(\"class\", \"catFacts\");\n // the tags that appear in the \"resultsSection\" in the HTML ^\n headerTag.textContent = generatedFacts;\n console.log(\"Facts:\", generatedFacts);\n \n\n for (let i = 0; i < 1; i++) {\n let spanResult = document.createElement(\"span\");\n spanResult.setAttribute(\"class\", \"randoFacts\");\n spanResult.textContent += generatedFacts.text;\n paraFact.appendChild(spanResult);\n }\n\n resultForm.appendChild(headerTag);\n resultForm.appendChild(clearFixRandom);\n resultForm.appendChild(paraFact);\n resultsSection.appendChild(resultForm);\n }\n}\n}", "function populateFeautured() {\n id(\"featured-view\").innerHTML = \"\";\n let url = URL + \"category/featured\";\n fetch(url)\n .then(checkStatus)\n .then(response => response.json())\n .then(appendFeatured)\n .catch(handleRequestError);\n }", "function showStrawFact(data) { //data accepting what is happening up top. \n //debugger; //comment out after bc you dont need to see what you did wrong anymore\n //parse the DB info and put it where it neds to go\n const { city, state, fact } = data; //destructuring assignmnet => MDN JS destructuring \n\n\n //might change some of this stuff for infographic all this is AJAX\n //grab the elements we need, and populate them with data\n document.querySelector('.city1').textContent = city; //will have three of these lines except with the selector in the quotes\n document.querySelector('.state').textContent = state;\n document.querySelector('.facts').textContent = fact;\n }", "function addRandomFact() {\n const facts = [\n 'I have two younger brothers both about a foot taller than me.', \n 'My parents are from Vietnam but I don\\'t speak any Vietnamese.',\n 'I have never been to anywhere else in Australia except Melbourne, \\\n where I was born and raised.'\n ];\n\n // Pick a random fact.\n const fact = facts[Math.floor(Math.random() * facts.length)];\n\n // Add it to the page.\n const factContainer = document.getElementById('fact-container');\n factContainer.innerText = fact;\n}", "function addRandomFact() {\n const facts =\n ['I am currently 20 years old!', \n 'I love to hike, bike, and camp!', \n 'I am an eagle scout!', \n 'I was the valedictorian of my high school!', \n 'I love traveling to other countries! I\\'ve been to about 10.', \n 'I love talking to others and socializing with others!'];\n\n // Pick a random fact.\n const factNum = Math.floor(Math.random() * facts.length);\n const factNumDisplay = factNum + 1; //We want to add 1 to display 1-based index due to 0-based indexing of arrays\n const fact = facts[factNum];\n // Add it to the page.\n\n const factContainer = document.getElementById('fact-container');\n factContainer.innerText = fact;\n const factNumContainer = document.getElementById('factNum-container');\n factNumContainer.innerText = \"This is fact number \" + factNumDisplay + \"!\";\n}", "static Fact(fact) {\n\t\t// create a div element\n\t\tlet factContainer = document.createElement('div');\n\t\t\n\t\t// add an id the div element\n\t\tfactContainer.id = 'fact-container';\n\n\t\t//appends the neccessary elements to the div element which was created\n\t\tif(fact === 'math') {\n\t\t\tfactContainer.innerHTML = \"<div id='random-fact'><div id='back-btn'><div id='line1'></div><div id='line2'></div></div><label>Enter Number</label><br><input type='number' id='input'><h3>Maths Fact</h3><div id='facts'></div></div>\";\n\t\t} else if (fact === 'trivia') {\n\t\t\tfactContainer.innerHTML = \"<div id='random-fact'><div id='back-btn'><div id='line1'></div><div id='line2'></div></div><label>Enter Number</label><br><input type='number' id='input'><h3>Trivia Fact</h3><div id='facts'></div></div>\";\n\t\t} else if (fact === 'year') {\n\t\t\tfactContainer.innerHTML = \"<div id='random-fact'><div id='back-btn'><div id='line1'></div><div id='line2'></div></div><label>Enter Year</label><br><input type='number' id='input'><h3>Year Fact</h3><div id='facts'></div></div>\";\n\t\t}\n\t\t\n\n\t\t// appends the div element to the fact-section element in the html file\n\t\tconst factSection = document.querySelector('#fact-section').appendChild(factContainer);\t\t\n\t}", "function getRandomFacts() {\n factsUl.empty();\n let randomChoices = [];\n for(i = 0; i < 5; i++) {\n let randomChoice = Math.floor(Math.random() * facts.length);\n while(randomChoices.includes(randomChoice)) {\n\n randomChoice = Math.floor(Math.random() * facts.length);\n }\n randomChoices.push(randomChoice);\n factsUl.append($(\"<li>\" + facts[randomChoice] + \"</li>\"));\n }\n randFacts.append(factsUl);\n}", "function getFavoritesArticles() {\n $.get(\"/api/saved-talks\", function(response) {\n if (response !== null) {\n for (var i = 0; i < response.length; i++) {\n displayFavoriteTalk(response[i]);\n }\n }\n });\n}", "function addRandomFact() {\n const facts = [\n \"🎮 I develop Nintendo GameBoy Advance ROMs in my spare time\",\n \"📹 I was a YouTube star back in the days <a href='https://youtube.com/thefredo1000'>Check out my channel</a>\",\n \"🤓 I am a huge Star Wars fan\",\n \"🎵 I love Weezer, they are my favorite band\",\n \"🎸 I can play the bass (Still a rookie)\",\n \"🐕 I have three dogs!\"];\n \n // Pick a random fact.\n var newFact = facts[Math.floor(Math.random() * facts.length)];\n\n // Get the current fact\n const factContainer = document.getElementById('js-fact-container');\n const currentFact = factContainer.innerHTML;\n\n // While the current fact it's the same as the new fact we try with another fact\n while(currentFact == newFact) {\n newFact = facts[Math.floor(Math.random() * facts.length)]; \n }\n factContainer.innerHTML = newFact;\n}", "function FXwriteFacts (){\n //write weather info\n $(\".earth-image\").append(\"<img src='assets/images/earth-globe.jpg' width=150px>\");\n $(\"#local-weather\").html(\n \"<p> Wind Speed: \" +localWeather.wind.speed + \" kph</p>\" +\n \"<p> Temp: \" + Math.floor(localWeather.main.temp -273.15) + \" Celcius </p>\" +\n \"<p> Conditions: \" + localWeather.weather[0].main + \"</p>\"\n );\n //write mars info\n FXcomputeMarsMonth();\n $(\".mars-image\").append(\"<img src='assets/images/mars-globe.jpg' width=150px>\");\n $(\"#mars-weather\").html(\n \"<p> Martian Month: \" + marsMonth + \" </p>\" +\n \"<p> Temp: \" + ((marsWeather.min_temp + marsWeather.max_temp)/2) + \" Celcius </p>\" +\n \"<p> Conditions: \" + marsWeather.atmo_opacity + \"</p>\"\n );\n }", "static fetchFact(type) {\n\t\tlet numberInput = document.querySelector('#input');\n\t\tlet factInput = document.querySelector('#facts');\n\n\t\t//fetch data when number is inputed\n\t\tnumberInput.addEventListener('input', () => {\n\t\t\tif (type === 'math') {\n\t\t\t\tfetch(`http://numbersapi.com/${numberInput.value}/math`)\n\t\t\t\t.then((response) => response.text())\n\t\t\t\t.then((data) => {\n\t\t\t\t\tif (numberInput.value === ''){\n\t\t\t\t\t\tfactInput.innerHTML = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfactInput.innerHTML = data;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t} else if (type === 'trivia') {\n\t\t\t\tfetch(`http://numbersapi.com/${numberInput.value}`)\n\t\t\t\t.then((response) => response.text())\n\t\t\t\t.then((data) => {\n\t\t\t\t\tif (numberInput.value === ''){\n\t\t\t\t\t\tfactInput.innerHTML = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfactInput.innerHTML = data;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t} else if (type === 'year') {\n\t\t\t\tfetch(`http://numbersapi.com/${numberInput.value}/year`)\n\t\t\t\t.then((response) => response.text())\n\t\t\t\t.then((data) => {\n\t\t\t\t\tif (numberInput.value === ''){\n\t\t\t\t\t\tfactInput.innerHTML = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfactInput.innerHTML = data;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\n\t\t});\n\n\t}", "function fetchRecipes() {\n fetch(RECIPES_URL)\n .then(resp => resp.json())\n .then(json => json.forEach(recipe => {\n let newRecipe = new Recipe(recipe.name, recipe.url, recipe.meal_type, recipe.cuisine, recipe.id);\n allRecipes.push(newRecipe);\n newRecipe.renderRecipe();\n }))\n }", "function parseWelcomeFact() {\n\n axios\n .get(factUrl)\n .then((response) => {\n scrapFactHtml(response.data);\n })\n .catch((err) => {\n console.log('Error when loading random fact.');\n client.channels.cache.find(channel => channel.name === targetChannelName)\n .send('Здравствуйте! В данный момент, к сожалению, явился без интересных фактов.');\n });\n\n}", "function initializePage() {\n\tconsole.log(\"Javascript connected!\");\n\n\t//const url = \"https://api.nytimes.com/svc/search/v2/candidatesearch.json?api-key=bebd5673446e40c0a0613cd3ea327a8d\";\n\tconst $candidates = $('#candidates');\n\tconst $representatives_container = $('#representatives_container');\n\n\t$('#refreshFeed').click(function(e) {\n\t\te.preventDefault();\n\t\tconsole.log('button clicked');\n\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\turl: 'https://www.googleapis.com/civicinfo/v2/voterinfo?key=AIzaSyBrvfLVDyTJ1Ar8EdM1aZda_9141qQcCh4&address=1263%20Pacific%20Ave.%20Kansas%20City%20KS&electionId=2000',\n\t\t\tdataType: 'json',\n\t\t\tsuccess: function(candidates) {\n\t\t\tconsole.log(candidates);\n $.each(candidates.contests, function(i, candidate){\n\n \tconst office = candidates.contests[i].office;\n \tconst name = candidates.contests[i].candidates[0].name;\n \tconst party = candidates.contests[i].candidates[0].party;\n \tconst website = candidates.contests[i].candidates[0].candidateUrl;\n\n \t//console.log(office, name, party, website);\n\n \t$representatives_container.append(\n \t\t`\n\t\t <div class=\"card-container\">\n\t\t <!-- Image -->\n\t\t <div class=\"image-container\">\n\t\t <i class=\"material-icons\" id=\"favorite-card\">favorite</i>\n\t\t </div>\n\n\t\t <!-- Description -->\n\t\t <div class=\"description-container\">\n\t\t <p class=\"title-rep\">${office} | ${party}</p>\n\t\t <h2>${name}</h2>\n\t\t <p class=\"contact\">${website}</p>\n\t\t </div>\n\n\t\t <!-- Button -->\n\t\t <div class=\"buttons-container\">\n\t\t <a href=\"representative.html\"><button class=\"representative-button\" >More Info <i class=\"material-icons\" id=\"right-icon\">chevron_right</i> </button></a>\n\t\t </div>\n\t\t </div>\n \t\t`\n \t\t);\n\n //$candidates.append(`<a href=\"representative.html\"><li>Representatives: <b>${candidates.contests[i].candidates[0].name}</b></li></a>`);\n //$candidates.append(`<p style=\"padding-left:20px\">Party: <b>${candidates.contests[i].candidates[0].party}</b></p>`);\n console.log(candidates.contests[i].candidates[0].name);\n\t\t\t\t });\n\t\t\t}\n\t\t});\n\n \tconsole.log('test');\n });\n}", "async function getRandomFactUsingAsyncAwait() {\n const response = await fetch('/data');\n const fact = await response.text();\n\n // New fact container to replace the older one\n const newFactContainer = document.createElement(\"span\");\n newFactContainer.id = \"js-fact-container\";\n newFactContainer.innerHTML = fact;\n\n // Replacing the current fact container with a new one\n var a = document.getElementById('js-fact-container');\n a.parentNode.replaceChild(newFactContainer, a);\n}", "function getNytFeeds() {\n\t\t\tvar url = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml';\n\t\t\tvar result = HTTP.call(\"GET\", url, function(error, result) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tnytFeedsAr = [];\n\t//this part works\n\t\t\t\t\tconsole.log('type of: ' + typeof result.content);\n//TEST see if this prevents confusion between npr and nyt feeds\n\t\t\t\t\t//using $1 var to differentiate between that used for npr feed\n\t\t\t\t\t$1 = cheerio.load(result.content, {\n\t\t\t\t\t\tnormalizeWhitespace: true,\n\t\t\t\t\t\txmlMode: true\n\t\t\t\t\t});\n\t\t\t\t\tvar prefix = 'nyt';\n\n\t\t\t\t\t//case collection is empty\n\t\t\t\t\tif (!Nytfeeds.findOne()) {\n\t\t\t\t\t\t$1('item').each(function(idx, element) {\n\t\t\t\t\t\t\t\tvar feedObj = {};\n\t\t\t\t\t\t\t\tvar feedId;\n\t\t\t\t\t\t\t\tvar descStr,\n\t\t\t\t\t\t\t\t\tdescAr = [];\n\t\t\t\t\t\t\t\t// feedObj.pubDate = $(this).find('pubDate').text();\n\t\t\t\t\t\t\t\tfeedObj.insertOrder = idx;\n\t\t\t\t\t\t\t\t//console.log('insertOrder: ' + feedObj.insertOrder);\n\t\t\t\t\t\t\t\tfeedObj.link = $1(this).find('link').text();//.contents();\n\t\t\t\t\t\t\t\tfeedObj._id = prefix + feedObj.link;\n\t\t\t\t\t\t\t\t//console.log('id: ' + feedObj._id);\n\t\t\t\t\t\t\t\t//console.log('type of id: ' + typeof feedObj._id);\n\t\t\t\t\t\t\t\tfeedObj.title = $1(this).find('title').text();//.contents();\n\t\t\t\t\t\t\t\t//console.log('title: ' + feedObj.title);\n\t\t\t\t\t\t\t\t//separating feed description text from the html used to display ads\n\t\t\t\t\t\t\t\tdescStr = $1(this).find('description').text();\n\t\t\t\t\t\t\t\tdescAr = descStr.split('<br clear=');\n\t\t\t\t\t\t\t\tfeedObj.description = descAr[0];//.contents();\n\t\t\t\t\t\t\t\t//console.log('description: ' + feedObj.description);\n\t\t\t\t\t\t\t\tnytFeedsAr.push(feedObj);\n\n\t\t\t\t\t\t\t\t//insert each feed to collection\n\t\t\t\t\t\t\t\tNytfeeds.insert(feedObj, function(er, id) {\n//\t\t\t\t\t\t\t\t\tconsole.log('id: ' + id);\n\t\t\t\t\t\t\t\t\tif (!er) {\n\t\t\t\t\t\t\t\t\t\tconsole.log('insert');\n\t\t\t\t\t\t\t\t\t\tconsole.log('size NytFeeds collection: ' + Nytfeeds.find().count());\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconsole.log('error: ' + er);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t//case collection is populated\n\t\t\t\t\t\tvar newFeedsCount;\n\t\t\t\t\t\tvar newFeedsAr = [];\n\t\t\t\t\t\tvar counter = 0;\n\t\t\t\t\t\t//for each feed check if its id has match in collection\n\t\t\t\t\t\t\t//if true, skip\n\t\t\t\t\t\t\t//if false, add to newFeedsAr\n\t\t\t\t\t\t//iterate over newFeedsAr\n\t\t\t\t\t\t\t//update the record in collection in order by insertOrder\n\t\t\t\t\t\t\t//this is assuming that older stories are cycled out by age\n\t\t\t\t\t\t$1('item').each(function(idx, element) {\n\t\t\t\t\t\t\tvar feedObj = {};\n\t\t\t\t\t\t\tfeedObj.link = $1(this).find('link').text();//.contents();\n\t\t\t\t\t\t\tfeedObj._id = prefix + feedObj.link;\n\n\t\t\t\t\t\t\tfeedObj.insertOrder = counter;\n\t\t\t\t\t\t\tfeedObj.title = $1(this).find('title').text();//.contents();\n\t\t\t\t\t\t\tdescStr = $1(this).find('description').text();\n\t\t\t\t\t\t\tdescAr = descStr.split('<br clear=');\n\t\t\t\t\t\t\tfeedObj.description = descAr[0];//.contents();\n\t\t\t\t\t\t\tnewFeedsAr.push(feedObj);\n\t\t\t\t\t\t});\n//\t\t\t\t\t\tconsole.log('length newFeedsAr: ' + newFeedsAr.length);\n\t\t\t\t\t\t//clear old feeds from collection\n\t\t\t\t\t\tNytfeeds.remove({}, function() {\n\t\t\t\t\t\t\tnewFeedsAr.forEach(function(feed) {\n\t\t\t\t\t\t\t\tNytfeeds.insert({\n\t\t\t\t\t\t\t\t\t_id: feed._id,\n\t\t\t\t\t\t\t\t\tinsertOrder: feed.insertOrder,\n\t\t\t\t\t\t\t\t\tlink: feed.link,\n\t\t\t\t\t\t\t\t\ttitle: feed.title,\n\t\t\t\t\t\t\t\t\tdescription: feed.description\n\t\t\t\t\t\t\t\t});\n//\t\t\t\t\t\t\t\tconsole.log('update a feed');\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log('length nytFeedsAr: ' + nytFeedsAr.length);\n\t\t\t\t\t// console.log('size NytFeeds collection: ' + Nytfeeds.find().count());\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log('error: ' + error);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function randomFact() {\n const Facts = [\n \"I am slowly becoming vegan.\",\n \"I am bilingual(English and Spanish)\",\n \"I like do card tricks even though I am not so good at it.\",\n \"I try to grow a collection of rubber duckies for rubber duck debugging(search it up)\",\n \"I enjoy cooking\",\n \"I like learning new things\"\n ];\n\n // Pick a random greeting.\n const Fact = Facts[Math.floor(Math.random() * Facts.length)];\n\n // Add it to the page.\n const factContainer = document.getElementById(\"fact-container\");\n factContainer.innerText = Fact;\n}", "function attachFact() {\n const { species } = info;\n const fact = document.createElement(\"DIV\");\n fact.setAttribute(\"id\", `${species.replace(\" \", \"_\")}-factoid`);\n fact.classList.add(\"factoid\");\n const layout = document.querySelector(`#${species.replace(\" \", \"_\")}-slot`);\n layout.appendChild(fact);\n const factoid = document.createTextNode(`${info.currentFact()}`);\n fact.appendChild(factoid);\n }", "function handleNewFactRequest(response) {\n // Get a random cat fact from the cat facts list\n var factIndex = Math.floor(Math.random() * CAT_FACTS.length);\n var fact = CAT_FACTS[factIndex];\n\n // Create speech output\n var speechOutput = \"Here's your cat fact: \" + fact;\n\n response.tellWithCard(speechOutput, \"CatFacts\", speechOutput);\n}", "function getRecipes() {\n fetch(\"http://localhost/magazine/webservice\")\n .then(response => response.json())\n .then(data => {\n for (let recipe of data) {\n createRecipe(recipe.id, recipe.name, recipe.kitchen, recipe.image);\n }\n })\n .then(data => getFavorites());\n}", "function ourChefs(){\t\t\n\t\tvar chefCount = 1;\n\t\tvar chefArticles = ['article:nth-of-type(1)','article:nth-of-type(2)','article:nth-of-type(3)'];\n\t\tvar chefImages = ['.chef-image-large img:nth-of-type(1)','.chef-image-large img:nth-of-type(2)','.chef-image-large img:nth-of-type(3)'];\n\t\t\n\t\t$('#add').on('click', function(){\n\t\t\tif (chefCount <= 0) {\n\t\t\t\tchefCount += 1;\n\t\t\t\t$('article').fadeOut(0);\n\t\t\t\t$('.chefs-image-large img').fadeOut(0);\n\t\t\t\t$(chefArticles[chefCount]).fadeIn(500);\n\t\t\t\t$(chefImages[chefCount]).fadeIn(500);\n\t\t\t} else if (chefCount <= 2) {\n\t\t\t\t\t\t$('article').fadeOut(0);\n\t\t\t\t\t\t$('.chef-image-large img').fadeOut(0);\n\t\t\t\t\t\t$(chefArticles[chefCount]).fadeIn(500);\n\t\t\t\t\t\t$(chefImages[chefCount]).fadeIn(500);\n\t\t\t\t\t\tchefCount += 1;\n\t\t\t}\n\t\t});\n\t\t$('#subtract').on('click', function(){\n\t\t\tif (chefCount >= 3) {\n\t\t\t\tchefCount += -2;\n\t\t\t\t$('article').fadeOut(0);\n\t\t\t\t$('.chef-image-large img').fadeOut(0);\n\t\t\t\t$(chefArticles[chefCount]).fadeIn(500);\n\t\t\t\t$(chefImages[chefCount]).fadeIn(500);\n\t\t\t} else if (chefCount >= 1) {\n\t\t\t\t\t\tchefCount += -1;\n\t\t\t\t\t\t$('article').fadeOut(0);\n\t\t\t\t\t\t$('.chef-image-large img').fadeOut(0);\n\t\t\t\t\t\t$(chefArticles[chefCount]).fadeIn(500);\n\t\t\t\t\t\t$(chefImages[chefCount]).fadeIn(500);\n\t\t\t}\n\t\t});\n\t}", "function factsDebug() {\n\tvar temp=\"\";\n\tfor (i in factlist) {\n\t\ttemp += factlist[i].id+\" \"+factlist[i].name+\":: \"+factlist[i].value+\"<br>\";\n\t}\n\tvar title=\"<br><text> Fact Debug </text><br>\";\n\tdocument.getElementById(\"fact_debug\").innerHTML = title+\"<text>\"+temp+\"</text>\"+\"<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><text>DEBUG</text>\";\n}", "function showFavorites() {\r\n\t\tdocument.getElementById(\"searchFood\").value = \"\";\r\n\t\tclear();\r\n\r\n\t\tlet url = \"https://hungry-students-csc-337.herokuapp.com\";\r\n\t\tfetch(url, {method: \"GET\"})\r\n\t\t\t.then(checkStatus)\r\n\t\t\t.then(function(responseText) {\r\n\t\t\t\tlet json = JSON.parse(responseText);\r\n\t\t\t\tfor(let i=0; i < json.meals.length; i++) {\r\n\t\t\t\t\tif(json.meals[i].name != \"\") {\r\n\t\t\t\t\t\tlet name = document.createElement(\"h1\");\r\n\t\t\t\t\t\tlet imag = document.createElement(\"img\");\r\n\t\t\t\t\t\tlet p = document.createElement(\"p\");\r\n\r\n\t\t\t\t\t\tname.id = \"food\"+i;\r\n\t\t\t\t\t\tname.innerHTML = json.meals[i].name;\r\n\t\t\t\t\t\timag.src = json.meals[i].image;\r\n\r\n\t\t\t\t\t\tp.appendChild(imag);\r\n\t\t\t\t\t\tdocument.getElementById(\"displayFavorites\").appendChild(name);\r\n\t\t\t\t\t\tdocument.getElementById(\"displayFavorites\").appendChild(p);\r\n\r\n\t\t\t\t\t\tname.onclick = pickFood;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.catch(function(error) {\r\n\t\t\t\tconsole.log(error);\r\n\t\t\t});\r\n\t}", "function RetrieveFeeds() {\n feeds.forEach(function (feed) {\n GetDataFeed(feed);\n });\n }", "function updateDOM() {\n updateFeaturedImage();\n updateFeaturedShoutout();\n updateFeaturedName();\n updateDots();\n}", "function populateEpisodes(episodes) {\n const $episodesList = $(\"#episodesList\");\n // empty the episodes list before adding new episodes of a show\n $episodesList.empty();\n\n // loop thru episodes, creating li's for each with the information provided\n for (let episode of episodes) {\n let $newEpItem = $(`<li data-episode-id=\"${episode.id}\">${episode.name} (season ${episode.season}, number ${episode.number})</li>`);\n $episodesList.append($newEpItem);\n }\n\n // reveal #episodesData\n $(\"#episodesArea\").show();\n }", "function populateFaq() {\n let url = URL + \"faq\";\n fetch(url)\n .then(checkStatus)\n .then(response => response.json())\n .then(appendFaq)\n .catch(handleRequestError);\n }", "function newArticles() {\n var results = [];\n\n axios.get(\"https://talksport.com/football/\").then(function (response) {\n\n // Load the HTML into cheerio and save it to a variable\n // '$' becomes a shorthand for cheerio's selector commands, much like jQuery's '$'\n var $ = cheerio.load(response.data);\n\n // Select each element in the HTML body from which you want information.\n // NOTE: Cheerio selectors function similarly to jQuery's selectors,\n // but be sure to visit the package's npm page to see how it works\n $(\".teaser-item\").each(function (i, element) {\n\n var headline = $(element).children().find(\".teaser__headline\").text().trim();\n var summary = $(element).children().find(\".teaser__subdeck\").text().trim();\n var link = $(element).find(\"a\").attr(\"href\");\n\n\n // Save these results in an object that we'll push into the results array we defined earlier\n results.push({\n headline: headline,\n summary: summary,\n link: link,\n });\n });\n\n // Log the results once you've looped through each of the elements found with cheerio\n //console.log(results);\n for (var i = 0; i < results.length; i++) {\n db.Article.create({ \"headline\": results[i].headline, \"summary\": results[i].summary, \"link\": results[i].link }, function (err, resp) {\n if (err) {\n console.log(err);\n }\n //console.log(resp);\n });\n }\n\n });\n }" ]
[ "0.6238689", "0.5538138", "0.5525729", "0.5382872", "0.5271777", "0.51738405", "0.5134809", "0.5119229", "0.50667167", "0.50391287", "0.50315523", "0.5027485", "0.5012915", "0.4953205", "0.4859165", "0.4812556", "0.48059362", "0.47641572", "0.47627264", "0.473448", "0.4721609", "0.47067252", "0.47038925", "0.4695336", "0.46923235", "0.4623263", "0.46204504", "0.46178877", "0.4603747", "0.45977023" ]
0.7512953
0
TODO: 1. drawTiles instead of animateFight 2. do not move but start figting
function animateFight(res){ loadTilemap({ 'animation' : res.animation, 'direction': res.direction, }); console.log(res); loopFight(res) /* // var targetTile = { 'x' : cursorX + res.animation.x, 'y' : cursorY + res.animation.y; $.post(gameurl, { 'class': 'map', 'do': 'getUnitTiles', 'gid': gid, 'offsetX': mapoffsetX, 'offsetY': mapoffsetY, 'screenTilesX': tilesX, 'screenTilesY': tilesY, 'cursorX': cursorX, 'cursorY': cursorY, 'animation' : res.animation, 'direction': res.direction, }, function( data ) { data = $.parseJSON(data); console.log(data); layers.clear('units'); for (var j in data) { var _y = (j) * tileSize - offset; for (var i in data[j]) { var _x = (i) * tileSize - offset; var unit = data[j][i]; drawUnit(unit, { 'x': _x, 'y': _y, 'animate': unit.animate, 'animation': 'attack', 'direction': unit.direction }); } } renderer.render(stage); // hitpoint + death animation }); */ //var selector = 'animation attack' + res.attacker.direction + ' anim-form-animation-attack_' + res.attacker.uid + '_' + res.animation.row; //$('.animation').removeClass().addClass(selector); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function animate() {\n \t// call again next time we can draw\n \trequestAnimationFrame(animate);\n \t// clear canvas\n \tctx.clearRect(0, 0, cvWidth, cvHeight);\n \t// draw gameObjects\n \tfor (var obj of gameObjects) {\n \t\tif (obj.hasOwnProperty('tileID')) {\n\t \t\tctx.drawImage(SVGTiles[obj.tileID], obj.x * 25, obj.y * 25);\n\t\t}\n\t}\n\t\n \t// everyObject[0] = tunk.x * 30;\n \t// everyObject[1] = tunk.y * 30;\n \t// var o = everyObject;\n \t// ctx.fillStyle = o[4];\n \t// ctx.fillRect(o[0], o[1], o[2], o[3]);\n}", "function animate() {\n\n\tif(move==true){\n\t\tvar x = setTimeout(function() { move=false; }, 100);\n\t}\n\t\n\telse{\n\tcontext.clearRect(0, 0, 800, 600);\n\tdrawBackGround();\n\tdrawHUD();\n\tdrawFirs();\n\tdrawBoules();\n\tdrawLutins();\n\tif(screen===\"game\"){\n\tsanta.drawSanta();}\n}\n requestAnimationFrame(animate);\n}", "function draw() {\n for (let i=0; i<tiles.length; i++) {\n tiles[i].display();\n }\n}", "function animate() {\n id = window.requestAnimationFrame(animate)\n\n //Clear the entire board first.. Changes the page \n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n\n //Draw everything else again, a little differnt \n ctx.drawImage(img, girl.x, girl.y, 100, 100)\n drawSquare()\n girl.x += .5;\n girl.y += .5;\n\n detectCollision()\n\n}", "animateTiles() {\n this.checkers.tilePositionX -= .5;\n this.checkers.tilePositionY -= .5;\n this.grid.tilePositionX += .25;\n this.grid.tilePositionY += .25;\n }", "draw() {\n this.tiles.forEach(t => {\n var tileCoords = {\n x: this.origin.x + (t.x * 8) + 16,\n y: this.origin.y + (t.y * 8)\n }\n this.context.drawImage(RESOURCE.sprites, t.t * 8, 16, 8, 8, tileCoords.x, tileCoords.y, 8, 8);\n });\n }", "function animate() {\n\tmoveShipRight();\n\tmoveShipLeft();\n\tif(GAME_OBJECTS[\"missles\"].length > 0) {\n\t\tstepMissle();\n\t}\n\tif(steps % 60 == 0) {\n\t\tanimateEnemies();\n\t}\n\tsteps++;\n\tif(steps == 600) {\n\t\tsteps = 0;\n\t}\n\t\n\t// check if game has been finished\n\tif(isGameOver() && gamePhase == 1){\n\t\tdisplayEnd();\n\t}\n}", "draw() {\r\n\t\tthis.matrix.forEach((row, y) => row.forEach((tile, x) => {\r\n\t\t\tif (tile) {\r\n\t\t\t\tlet [tx, ty] = tile.position.get;\r\n\t\t\t\tif (tile.isEmpty) {\r\n\t\t\t\t\t//default\r\n\t\t\t\t\tmainCtx.fillStyle = this.baseColor;\r\n\t\t\t\t\tmainCtx.fillRect(\r\n\t\t\t\t\t\ttx * (this.tileSize + this.spacing),\r\n\t\t\t\t\t\tty * (this.tileSize + this.spacing),\r\n\t\t\t\t\t\tthis.tileSize,\r\n\t\t\t\t\t\tthis.tileSize\r\n\t\t\t\t\t);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t//draw gameobject\r\n\t\t\t\t\tmainCtx.fillStyle = tile.top.bgColor;\r\n\t\t\t\t\tmainCtx.fillRect(\r\n\t\t\t\t\t\ttx * (this.tileSize + this.spacing),\r\n\t\t\t\t\t\tty * (this.tileSize + this.spacing),\r\n\t\t\t\t\t\tthis.tileSize,\r\n\t\t\t\t\t\tthis.tileSize\r\n\t\t\t\t\t);\r\n\t\t\t\t\tmainCtx.fillStyle = tile.top.color;\r\n\t\t\t\t\tmainCtx.fillText(\r\n\t\t\t\t\t\ttile.top.glyph,\r\n\t\t\t\t\t\ttx * (this.tileSize + this.spacing) + this.tileSize / 2,\r\n\t\t\t\t\t\tty * (this.tileSize + this.spacing) + this.tileSize / 1.5\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}));\r\n\t}", "function drawGame()\n{\n if(canvas==null) {return;}\n \n //Iterates over the map\n for(var y = 0; y < mapHeight; y++)\n {\n for(var x = 0; x < mapWidth; x++)\n {\n if (revealAll == true || fogmask[((y*mapWidth)+x)] != 1)\n {\n //Revealed area\n switch(map[((y*mapWidth)+x)])\n {\n case 0:\n canvas.fillStyle = \"#ffffff\";\n break;\n case 1:\n canvas.fillStyle = \"#444444\";\n break;\n case 4:\n canvas.fillStyle = \"#ffab00\";\n break;\n case 5:\n canvas.fillStyle = \"#00c853\";\n break;\n case 8:\n canvas.fillStyle = \"#03adfc\";\n break;\n case 9:\n canvas.fillStyle = \"#f50057\";\n break;\n default:\n canvas.fillStyle = \"#000000\";\n break; \n }\n }\n //Covered by fog\n else\n {\n switch(map[((y*mapWidth)+x)])\n {\n case 0:\n canvas.fillStyle = \"#bbbbbb\";\n break;\n case 1:\n canvas.fillStyle = \"#444444\";\n break;\n default:\n canvas.fillStyle = \"#bbbbbb\";\n break; \n }\n }\n \n //Draw the Tile\n canvas.fillRect(x*tileWidth, y*tileHeight, tileWidth, tileHeight);\n }\n }\n}", "function animate() {\n // request another frame\n requestAnimationFrame(animate);\n\n // calc elapsed time since last loop\n now = Date.now();\n elapsed = now - then;\n\n // if enough time has elapsed, draw the next frame\n if (elapsed > fpsInterval) {\n then = now - (elapsed % fpsInterval);\n\n // Put your drawing code here\n buildBoard();\n headSnake();\n drawPlayer();\n //checkPoint();\n drawPoints();\n }\n}", "function generateMap()\r\n{\r\n\tif(ctx==null)\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\tfor(var y = 0; y < mapH; y++)\r\n\t{\r\n\t\tfor(var x = 0; x < mapW; x++)\r\n\t\t{\r\n\t\t\tfor(var i = 0; i < gameTiles.length;i++)\r\n\t\t\t{\r\n\t\t\t\tswitch(gameTiles[((y*mapW)+x)].type)\r\n\t\t\t\t{\r\n\t\t\t\t\tcase 0:\r\n\t\t\t\t\t\tctx.fillStyle=\"green\";\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 1:\r\n\t\t\t\t\t\tctx.fillStyle=\"purple\";\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 2:\r\n\t\t\t\t\t\tctx.fillStyle=\"blue\";\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 3:\r\n\t\t\t\t\t\tctx.fillStyle=\"red\";\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tctx.fillStyle=\"black\";\r\n\t\t\t\t}\r\n\t\t\t\tctx.fillRect(x*tileW, y*tileH, tileW, tileH);\r\n\t\t\t}\t\r\n\t\t}\r\n\t}\r\n\trequestAnimationFrame(generateMap);\r\n}", "function renderTiles() {\n var map_index = 0;\n\n // increment by actual TILE_SIZE to avoid multiplying on every iteration\n for (var top = 0; top < MAP.height; top += TILE_SIZE) {\n for (var left = 0; left < MAP.width; left += TILE_SIZE) {\n\n // if statement to draw the correct sprite to the correct idx position on the tile map\n if (MAP.tiles[map_index] === 0) {\n\n // draw background\n ctx.drawImage(background, left, top);\n\n } else if (MAP.tiles[map_index] === 2) {\n\n // draw platform\n ctx.drawImage(platform, left, top);\n\n new Obstacle(100, 100, left, top);\n\n } else if (MAP.tiles[map_index] === 3) {\n\n // draw ring\n ctx.drawImage(ring, left, top);\n //new Obstacle(100, 100, left, top);\n\n } else if (MAP.tiles[map_index] === 1) {\n\n // draw floor\n ctx.drawImage(floor, left, top);\n } else if (MAP.tiles[map_index] === 4) {\n\n ctx.drawImage(floor, left, top);\n new Obstacle(100, 100, left, top);\n }\n\n map_index++;\n }\n }\n}", "function draw() {\n // BG\n clear_to_color(canvas,makecol(255,85, 85));\n\n // TILES\n // iterate over all tiles and draw them\n // j=y, i=x\n for (var j = 0; j < MAP_HEIGHT; j++) {\n for (var i = 0; i < MAP_WIDTH; i++) {\n var tileimg;\n switch (map[j][i]['type']) {\n case '#':\n tileimg = img_movchair;\n break;\n case '@':\n tileimg = img_rotchair;\n break;\n default:\n tileimg = ' ';\n }\n if (tileimg != ' ') {\n rotate_sprite(canvas, tileimg, \n coord2pos(i)+map[j][i]['tweenx'], coord2pos(j)+map[j][i]['tweeny'],\n map[j][i]['angle']+map[j][i]['tweenrot']);\n }\n }\n }\n\n // PLAYER\n rotate_sprite(canvas, img_player,\n coord2pos(player['x'])+player['tweenx'], coord2pos(player['y'])+player['tweeny'],\n int2dir(player['dir']));\n}", "function tween_tiles() {\n for (j=0; j<MAP_HEIGHT; j++) {\n for (i=0; i<MAP_WIDTH; i++) {\n var tile = map[j][i];\n if (map[j][i]['type'] !== ' ') {\n // tween the tiles until they reach their destination\n // MOVEMENT TWEENING\n if (tile['newx'] !== tile['x']) {\n var diffx = Math.abs(tile['x'] - tile['newx']);\n if (tile['newx'] > tile['x']) {\n tile['tweenx'] += TWEENSPEED;\n }\n else if (tile['newx'] < tile['x']) {\n tile['tweenx'] -= TWEENSPEED;\n }\n }\n if (tile['newy'] !== tile['y']) {\n var diffy = Math.abs(tile['y'] - tile['newy']);\n if (tile['newy'] > tile['y']) {\n tile['tweeny'] += TWEENSPEED;\n }\n else if (tile['newy'] < tile['y']) {\n tile['tweeny'] -= TWEENSPEED;\n }\n }\n // swap tiles when they have completed their movement\n // (if they moved at all)\n if (tile['tweenx'] !== 0 || tile['tweeny'] !== 0) {\n if (Math.abs(tile['tweenx']) > TILESIZE * diffx) {\n // swap tile and lava\n swap_tiles(i, j, tile['newx'], tile['newy']);\n }\n if (Math.abs(tile['tweeny']) > TILESIZE * diffy) {\n // swap tile and lava\n swap_tiles(i, j, tile['newx'], tile['newy']);\n }\n }\n // ROTATION TWEENING\n if (tile['newangle'] !== tile['angle']) {\n tile['tweenrot'] += TWEENSPEED;\n }\n if (tile['tweenrot'] !== 0) {\n // done rotating\n if (Math.abs(tile['tweenrot']) >= 90) {\n tile['angle'] = tile['newangle'];\n tile['tweenrot'] = 0;\n shift_barriers(i, j);\n }\n }\n\n }\n }\n }\n}", "function drawSmiles() {\n SmilesDrawer.apply();\n}", "function animate() {\n requestAnimFrame( animate );\n game.background.draw();\n game.tardis.move();\n}", "function animate() {\n requestAnimFrame( animate );\n game.background.draw();\n game.tardis.move();\n}", "function tiles_FX() {\n var delta_time,\n path_tiles;\n b += 1;\n if (b < n_c.length) {\n\n misc.s_cl(n_c[b], \"point path\");\n misc.s_ti(n_c[b], b + 1);\n\n if (!!n_c[b].getAttribute(\"data-direction\")) {\n n_c[b].innerHTML = n_c[b].getAttribute(\"data-direction\");\n } else {\n n_c[b].innerHTML = comparer(n_c[b], AI.v.sf.finish);\n }\n\n } else {\n delta_time = AI.v.time_end - AI.v.time_start;\n path_tiles = misc.slc(\".point.path\").length;\n misc.s_cl(misc.gid(e[0] + \"_\" + e[1]), \"point end white smiley\");\n\n title.innerHTML =\n \"Path Finding<br><sub style='color:white'>Calculated in \" + delta_time +\n \" ms | \" + path_tiles + \" steps between start - finish</sub>\";\n\n title.style.background = \"deepskyblue\";\n btn.innerHTML = \"Finished\";\n rebuild_btn.disabled = 0;\n clear_btn.disabled = 0;\n AI.v.traceback = 0;\n clearInterval(a);\n }\n }", "drawScene() {\n const positions = this.getTilePositions();\n this.updateTileSpecs();\n if (debug) {\n this.redrawStarted = Date.now();\n this.redrawnTiles = 0;\n }\n this.drawTiles(positions);\n if (debug) {\n const elapsed = Date.now() - this.redrawStarted;\n if (elapsed > 5) {\n console.log(`Took ${elapsed} msecs to redraw for ${positions.startXTile} ${positions.startYTile} (redrawnTiles: ${this.redrawnTiles})`);\n }\n }\n }", "function game_drawBoard(){\n\tvar x=GLOBAL['gamevars'].xoffset;\n\tvar y=GLOBAL['gamevars'].yoffset;\n\tvar w=gametilesize+6;\n\t//draw a square for each tile\n\tfor(var i=0;i<GLOBAL['board'].length;i++){\n\t\tfor(var j=0;j<GLOBAL['board'][i].length;j++){\n\t\t\tvar tile=GLOBAL['board'][i][j];\n\t\t\tif(tile.type>0){\n\t\t\t\tif(tile.type==2&&GLOBAL['state']=='gameinit'){\n\t\t\t\t\tgamectx.fillStyle='white';\n\t\t\t\t}else if(tile.type>0&&GLOBAL['state']=='gameinit'){\n\t\t\t\t\tgamectx.fillStyle='grey';\n\t\t\t\t}else if(GLOBAL['state']=='game'){\n\t\t\t\t\tvar hue=tile.color;\n\t\t\t\t\tgamectx.fillStyle='rgba('+hue+','+hue+','+hue+',.5)';\n\t\t\t\t}\n\t\t\t\tgamectx.fillRect(x+((w)*i),y+((w)*j),w,w);\n\t\t\t\tif(GLOBAL['state']=='game'&&tile.highlight){\n\t\t\t\t\tif(tile.highlight=='selected'||tile.highlight=='selectedAtk'){\n\t\t\t\t\t\tgamectx.fillStyle='white';\n\t\t\t\t\t}else if(tile.highlight=='move1'){\n\t\t\t\t\t\tgamectx.fillStyle='green';\n\t\t\t\t\t}else if(tile.highlight=='move2'){\n\t\t\t\t\t\tgamectx.fillStyle='limegreen';\n\t\t\t\t\t}else if(tile.highlight=='atk1'){\n\t\t\t\t\t\tgamectx.fillStyle='#A10000';\n\t\t\t\t\t}else if(tile.highlight=='atk2'){\n\t\t\t\t\t\tgamectx.fillStyle='#A10000';\n\t\t\t\t\t}\n\t\t\t\t\tgamectx.fillRect(x+((w)*i),y+((w)*j),w,w);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(typeof(tile.entity)!=='undefined'){\n\t\t\t//has an entity\n\tif(typeof(gamedragtile)!='undefined'&&gamedragtile.type=='field'&&gamedragtile.globalid==tile.entity.globalid){\n\t\t\t\t\t//ignore entity if its currently being dragged somewhere.\n\t\t\t\t}else{\n\t\t\t\t\tvar drawx=x+3+((w)*i);\n\t\t\t\t\tvar drawy=y+3+((w)*j);\n\t\t\t\t\tvar dataid=getEntity(tile.entity.globalid).id;\n\t\t\t\t\tgame_drawTile(drawx,drawy,dataid,tile.entity.n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(tile.type==3){\n\t\t\t\tgamectx.drawImage(data_credit,x+((w)*i)+10,y+((w)*j)+10);\n\t\t\t}\n\t\t\tif(tile.highlight=='selectedAtk'&&GLOBAL['gamevars'].turn!='ai'){\n\t\t\t\tgamectx.fillStyle='white';\n\t\t\t\tgamectx.fillText(tile.highlightVal,x+(w*i)+30,y+(w*j)+15);\n\t\t\t}\n\t\t}\n\t}\n}", "function draw() {\n\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n for (c = 0; c < tileColumnCount; c++) {\n for (r = 0; r < tileRowCount; r++) {\n rect(tiles[c][r].x, tiles[c][r].y, tileW, tileH, tiles[c][r].state);\n }\n }\n\n}", "function drawTiles()\n{\n\tfor(var y = 0; y < BOARD_HEIGHT; y++)\n\t{\n\t\tfor(var x = 0; x < BOARD_WIDTH; x++)\n\t\t{\n let drawX = x * TILE_WIDTH;\n let drawY = y * TILE_HEIGHT;\n\n //Draw the tiles, but not the ones off the screen\n if(drawX + TILE_WIDTH > -camera.xOffset && drawX < -camera.xOffset + width)\n {\n if(drawY + TILE_HEIGHT > -camera.yOffset && drawY < -camera.yOffset + height)\n {\n tiles[x][y].draw(ctx, camera);\n }\n }\n\t\t}\n\t}\n}", "function animate() {\n\t\tcontext.fillStyle = \"black\";\n\t\tcontext.fillRect(0, 0, canvas.width, canvas.height);\n\n\t\tif (iteration%2 == 1) {\n\t\t\tpacmanMouth = !pacmanMouth;\n\t\t\tghostOndulation = !ghostOndulation;\n\t\t\tif (next_attack_in <= 30) {\n\t\t\t\tblinking = !blinking\n\t\t\t} else {\n\t\t\t\tblinking = false\n\t\t\t}\n\t\t}\n\t\titeration++\n\n\t\tdrawGrid(context, quantum)\n\n\t\tfor (var i = 0; i < pacmans.length; i++) {\n\t\t\tdrawPacman(context, quantum, pacmans[i], pacmanMouth)\n\t\t}\n\t\tfor (var i = 0; i < ghosts.length; i++) {\n\t\t\tdrawGhost(context, quantum, ghosts[i], i, ghostOndulation, blinking)\n\t\t}\n\n\t\tcontext.font = quantum + \"px Bangers, cursive\";\n\t\tcontext.fillStyle = \"#F9C328\";\n\t\tcontext.textAlign=\"center\";\n\t\tcontext.fillText(\"Score : \" + pacmans[0].score,context.canvas.width/2,context.canvas.height - 1.2*quantum);\n\n\t}", "function render() {\n loop(function (row, col) {\n x = (col * tileSize);\n y = (row * tileSize);\n\n // draw placements\n if (map[row][col] == 1) {\n context.fillStyle = \"#aa0000\";\n context.fillRect(x + tileOffset, y + tileOffset, tileSize - tileOffset, tileSize - tileOffset);\n }\n });\n }", "step() {\n let cells = this.board.tick();\n this.drawCells(cells);\n }", "draw() {\n if (this.imgLoaded) {\n if (this.isGrounded) {\n let frameStr = '';\n this.currentInvincibility == 0\n ? frameStr = `frame${this.currentFrame}`\n : frameStr = `frame${this.currentFrame + 4}`;\n engine.gfxController.drawSprite(\n this.img,\n this.spriteCoordinates[frameStr][0],\n this.spriteCoordinates[frameStr][1],\n 72,\n 128,\n this.x,\n this.y,\n this.spriteWidth,\n this.spriteHeight\n );\n \n if (!this.isStopped) {\n this.waitFrames--;\n if (this.waitFrames < 1) {\n this.currentFrame++;\n if (this.currentFrame > 4) {\n this.currentFrame = 1;\n }\n this.waitFrames = this.maxWaitFrames;\n }\n }\n } else {\n let jumpStr = (this.jumpDirection > 0)\n ? \"jumpUp\"\n : \"jumpDown\";\n if (this.currentInvincibility != 0) {\n jumpStr += \"Hit\";\n } \n engine.gfxController.drawSprite(\n this.img,\n this.spriteCoordinates[jumpStr][0],\n this.spriteCoordinates[jumpStr][1],\n 72,\n 128,\n this.x,\n this.y,\n this.spriteWidth,\n this.spriteHeight);\n }\n }\n }", "_drawFrame () {\n \n\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)\n for (let x = 0; x < this.sizeX; x++) {\n for (let y = 0; y < this.sizeY; y++) {\n if (this.matrix[x][y] === -1) {\n this._drawBackgroundSquare(x, y, this.tileWidth, this.deathTileColor)\n this.matrix[x][y] = 0\n } else if (this.matrix[x][y] === 1) {\n this._drawSquare(x, y, this.tileWidth, this.tileColor)\n }\n }\n }\n this._drawMouse()\n }", "function MeligineGameScreenRender(){\r\n\tMeligineCleanTheScreen();\r\n\tactualCell=0;\r\n\t\r\n\tfor(var i=0;i<rows;i++){\r\n\t\t//where is the acctual cell on y\r\n\t\tactualY=i;\r\n\t\tif(actualY>playerY-cellsToDrawAroundPlayer+2 && actualY<playerY+cellsToDrawAroundPlayer-2){\r\n\t\t\tfor(var u=0;u<cellsPerRow;u++){\r\n\t\t\t\tactualX=u;\r\n\t\t\t\tif(actualX>playerX-cellsToDrawAroundPlayer && actualX<playerX+cellsToDrawAroundPlayer){\r\n\t\t\t\t//declare tile image\r\n\t\t\t\t\r\n\t\t\t\tvar tilesetImage= new Image();\r\n\t\t\t\tif(tilesetToUse==1){\r\n\t\t\t\ttilesetImage.src=tileset1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t//where is the acctual cell on x\r\n\t\t\t\t\r\n\t\t\t\t//cell repositioning due to player moving\r\n\t\t\t\tcellReplaceX=(playerScreenPadX+actualX*cellSizeZoom)-cellSizeZoom/2;\r\n\t\t\t\tcellReplaceY=(playerScreenPadY+actualY*cellSizeZoom)-cellSizeZoom/2;\r\n\t\t\t\t\r\n\t\t\t\t//ctx.strokeStyle=\"rgb(100,100,100)\";\r\n\t\t\t\t//ctx.strokeRect(cellReplaceX,cellReplaceY,cellSizeZoom,cellSizeZoom);\r\n\t\t\t\t\r\n\t\t\t\ttilesetTileOnY=Math.floor(allCells[actualCell]/tilesetTilesOnWidth);\r\n\t\t\t//\ttilesetTileOnY=1;\r\n\t\t\t\ttilesetTileOnX=allCells[actualCell]-tilesetTileOnY*tilesetTilesOnWidth;\r\n\t\t\t//\ttilesetTileOnX=9;\r\n\t\t\t\t//set the tilesets on x and y to know from where to pick\r\n\t\t\t\ttilesetX=tilesetTileOnX*tilesetTileSize;\r\n\t\t\t\ttilesetY=tilesetTileOnY*tilesetTileSize;\r\n\t\t\t\t\r\n\t\t\t\tctx.drawImage(tilesetImage,tilesetX,tilesetY,tilesetTileSize,tilesetTileSize,cellReplaceX,cellReplaceY,cellSizeZoom,cellSizeZoom);\r\n\t\t\t\tctx.fillStyle=\"rgb(255,0,255)\";\r\n\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\tactualCell++;\r\n\t\t\t\t}else{\r\n\t\t\t\tactualCell++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}else{\r\n\t\tactualCell+=cellsPerRow;\r\n\t\t}\r\n\t}\r\n\tMeligineDrawThePlayer();\r\n}", "function animate() {\n\trequestAnimFrame( animate );\n\tgame.background.draw();\n\tgame.ship.move();\n\tgame.ship.bulletPool.animate();\n\tgame.enemyPool.animate();\n\tgame.enemyBulletPool.animate();\n displayStats();\n}", "function draw() {\r\n requestAnimationFrame(draw);\r\n if (numberOfMissiles < 50) {\r\n missileGeneration();\r\n }\r\n moveMissile();\r\n TWEEN.update();\r\n renderer.render(scene,camera);\r\n}" ]
[ "0.7226908", "0.70082825", "0.6970953", "0.6858111", "0.6821993", "0.6760133", "0.6760034", "0.66750056", "0.6672165", "0.66682374", "0.66538596", "0.6637454", "0.6632285", "0.6614243", "0.6607741", "0.6602935", "0.6602935", "0.64913267", "0.6472996", "0.64635205", "0.6459503", "0.64446664", "0.64364", "0.64314705", "0.64303637", "0.64253396", "0.64221656", "0.64069223", "0.63981414", "0.63969016" ]
0.716197
1
Select the current staff member.
function selectStaffMember(member, index) { vm.isSelected = false; vm.selectedMemberIndex = index; vm.selectedMember = angular.isDefined(member) ? member : vm.staffMembers[0]; if (!$mdSidenav('left').isLockedOpen()) { $mdSidenav('left').close(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fnselectMember(){\r\n\tastrMemberName=fngetElementsByClass('btn_assign_unassign',document,'div'); \r\n\tfnteamStatus();\r\n}", "function select ( menuId ) {\r\n // self.selected = angular.isNumber(menuId) ? $scope.users[user] : user;\r\n self.toggleList();\r\n }", "function activate() {\n return StaffService.getAllStaffMembers().then(function (data) {\n vm.staffMembers = data;\n vm.selectedMember = data[0];\n loggerFactory.info('Staff Members: ', data);\n }, function (err) {\n loggerFactory.error('Get Staff Members: ', err);\n });\n }", "function selectUser(user) {\n\t vm.currentUser = user;\n\t\t}", "function getMemberIndex(index){\n selectedMemberIndex = index;\n\n}", "function selectUser() {\n var userSel = document.getElementById(\"user-sel\");\n if (userSel.value == \"null\") {\n searchMemberKey = null;\n } else {\n searchMemberKey = userSel.value\n }\n\n checkGroupsSidebar(true);\n getAllGroups();\n}", "function selectUserFromCollaboratorList(email) {\n var parentUl = $('#panel-collaborators').children('ul');\n var users = parentUl.children('li');\n var user = users.get(0);\n\n // Set user to select..\n for(var i = 0; i < users.length; i++) {\n user = users.get(i);\n if(user.id == email) {\n user.setAttribute(\"style\", \"background-color: #c3c3c3; cursor: pointer;\");\n selectedCollaboratorIndex = i;\n selectedCollaboratorEmail = email;\n }\n else {\n user.setAttribute(\"style\", \"cursor: pointer;\");\n }\n }\n}", "function markUserSelected(){\n\tif(document.getElementById('selectUser').value==0){\n\t\talert(\"please select a user\");\n\t}else{\n\t\tCURRENT_USER_=document.getElementById('selectUser').value;\n\t\t//\n\t\tdocument.getElementById('projectBioContainer').style.display='block';\n\t}\n}", "function multiselectModalEditStaffList() {\n\tmultiselectModal(\"editStaffList\", $('#FFSEditStaffList_AvailableAndAssignedStaffSVIDs > option').length, 'Select Assigned Staff', $(window).height() - (240));\n}", "select(id) { this._updateActiveId(id, false); }", "function selectUser ( user ) {\n self.selected = angular.isNumber(user) ? $scope.users[user] : user;\n }", "function selectUser ( user ) {\n self.selected = angular.isNumber(user) ? $scope.users[user] : user;\n self.toggleList();\n self.loadDataFromFirebase();\n // console.log(self.selected);\n }", "selectCurrent()\n {\n this.select(this.currentSelectedIndex);\n }", "approveMember() {\n MemberActions.approveUser(this.props.memberID);\n this.props.unselect();\n }", "function select_meal_in_meal_list(meal_id) {\n // Only do this if not in edit mode\n if (!is_edit_mode) {\n // Chage the current meal to the newly selected/clicked meal\n set_current_meal(meal_id);\n\n current_meal.is_calendar_meal = false;\n\n // Populate the meal editor with the current meal\n populate_meal_editor(current_meal);\n\n // Set that you're selecting a meal from the meal list\n is_selected_meal_from_meal_list = true;\n\n // Highlight the selected/clicked meal\n highlight_current_meal(meal_id, true);\n }\n}", "onStaffSelect(event){\n let staffId = { key: \"staffMemberId\", value: event.target.value == '' ? -1 : event.target.value };\n this.onCheckoutEditorChange(staffId);\n }", "select() { this.selected = true; }", "function SP_SelectOriginatorLaunched()\n{\n \tvar oListOriginator = document.getElementById(\"mastercontrol.task.originator\"); \n\tvar sCurrentUser = document.getElementById(\"mastercontrol.form.currentuser\").value.toLowerCase();\n\tvar i;\n\tvar sItemValue = \"\";\n\tfor (i=0; i<oListOriginator.length;i++)\n\t{\n\t\tsItemValue = oListOriginator[i].value;\n\t\tif (sItemValue.toLowerCase() === sCurrentUser)\n\t\t{\n oListOriginator.selectedIndex = i;\n\t\t\t break; \n }\n\t} \n}", "function onCreateNewStaffClick() {\n $('#modal-register-staff').modal('show');\n }", "function select_member(){\n var div = document.querySelector(\"div#selected_members\");\n var swap = document.querySelector(\"div#selected_members .swapable\");\n var new_div = this.cloneNode(true);\n new_div.querySelector(\"input\").checked = true;\n var new_div_name = JSON.parse(new_div.querySelector(\"p.data\").innerText)[\"name\"];\n if(!compile_div_names().includes(new_div_name)){\n new_div.classList.add(\"selected\");\n if(div.childElementCount < 3){\n div.appendChild(new_div);\n new_div.click();\n } else {\n div.replaceChild(new_div, swap);\n swapable_member();\n new_div.click();\n };\n };\n}", "function SelectMember(Member) {\n $(\"#txtMemberId\").val($(Member).parent().parent().find(\".MemberId\").text());\n $(\"#txtFirstName\").val($(Member).parent().parent().find(\".FirstName\").text());\n $(\"#txtLastName\").val($(Member).parent().parent().find(\".LastName\").text());\n $(\"#txtMobileNo\").val($(Member).parent().parent().find(\".MobileNumber\").text());\n ClosingPopup(\"#modal-membersearch\");\n}", "function selectUser(event) {\n var editBtn = $(event.target);\n editIndex = editBtn.attr(\"id\").split('-')[1];\n selectedUserId = users[editIndex]._id;\n try {\n userService.findUserById(selectedUserId)\n .then(function (userInfo) {\n console.log(\"userInfo from findUserById\", userInfo);\n $usernameFld.val(userInfo.username);\n $passwordFld.val(userInfo.password);\n $firstNameFld.val(userInfo.firstName);\n $lastNameFld.val(userInfo.lastName);\n $roleFld.val(userInfo.role);\n selectedUser = userInfo;\n });\n }\n catch (err) {\n console.log(err.name + \": \" + err.message);\n }\n }", "async setCurrentUser() {\n const response = await this.client.get('currentUser')\n this.currentUser = response.currentUser\n }", "function selecionarEmpleadoStaff(id){\n\tvar url =$('.staff_empleado_url').attr('id');\n\turl = url+'?empleadoStaff='+id;\n\n\t$.post(url, function( data ) {\n\t\tdata.forEach( function(valor, indice, array) {\n\t\t\t$('#staff_empleado').val(valor.empleado_codigo).trigger('change');\n\t\t\t$('#staff_tarea').val(valor.tarea_codigo).trigger('change');\n\t\t\t$('#estado_staff_empleado').val(valor.activo).trigger('change');\n\t\t\t$('#id_staff').val(id);\n\n\n\t\t});\n\t});\n}", "function createIsStaffSelector(resourceSelector) {\n return createSelector(\n createUserUnitRoleSelector(resourceSelector),\n uiUnitRole => getIsUnitStaff(uiUnitRole),\n );\n}", "function reportSetSelectedStaffMemberName(reportName) {\n\t$(\".reportCurrentStaffMemberName\").each(function () {\n\t\tif (reportName == \"FUNDINGHISTORY\") {\n\t\t\t$(this).text(\"ALL\");\n\t\t} else {\n\t\t\t$(this).text($(\"#AssignedStaffList option:selected\").text());\n\t\t}\n\t});\n}", "function selectUser(index) {\n vm.user = vm.users[index];\n }", "select () {\n this.selected = true;\n }", "function SelectMember(Member) {\n $(\"#TransferMemberId\").val($(Member).parent().parent().find(\".MemberId\").text());\n $(\"#TransferMemberName\").val($(Member).parent().parent().find(\".FirstName\").text() + \" \" + $(Member).parent().parent().find(\".LastName\").text());\n $(\"#modal-membersearch\").modal(\"hide\");\n}", "function activate() {\n teamMember.member.lead = (teamMember.member.name === 'Jett');\n }" ]
[ "0.6085138", "0.60093236", "0.5921727", "0.5857276", "0.5638627", "0.5568501", "0.551495", "0.5491164", "0.54646754", "0.5442988", "0.5425162", "0.54168624", "0.5379206", "0.53753644", "0.5370801", "0.53613", "0.5348411", "0.5306193", "0.52819854", "0.523915", "0.5230852", "0.52296746", "0.5226338", "0.52184504", "0.52173555", "0.5212509", "0.51776785", "0.51663303", "0.51555336", "0.5146705" ]
0.71720594
0
Checks for validity of common search params (non resource specific).
function validateCommonParams(params, onSuccess, onError) { var countRegExp = /^\d+$/; var errors = []; // validate _count if (params._count) { // _count should be an integer if (!countRegExp.test(params._count)) { errors.push(validationErrors.INVALID_COUNT); } } // FHIR _sort param takes different forms (_sort=propName, _sort:asc=propName, _sort:desc=propName) // this is reflected in the query as three different query parameters. if (hasMoreThanOneSortParameter(params)) { // FHIR supports multiple _sort parameters but JDS does not, so we allow only one _sort query parameter. errors.push(validationErrors.TOO_MANY_SORT_PARAMS); } if (errors.length > 0) { onError(errors); } else { onSuccess(); // all common parameters passed validation } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkSearchParam(search) {\n check(search, String);\n }", "function check_params(params){\n for(var i=0; i < params.length; i ++){\n if(!params_search[params[i]]){\n return false\n }\n }\n return true;\n }", "function searchParams() {\n let searchLang = lang.value;\n let devLoc = devLocation.value;\n let minRepo = minimumRepos.value;\n\n // test\n // console.log(searchLang);\n // console.log(devLoc);\n // console.log(minRepo);\n //check\n\n // validate client request data here with Joi \n // make API request\n\n // \n apiRequest.getProfiles(searchLang, devLoc, minRepo)\n .then(data => {\n\n uiResults.renderResults(data);\n\n });\n\n}", "function notSearchParam(key) {\n\t\t\t\t\treturn fromAndToState.params[key].location != \"search\";\n\t\t\t\t}", "function notSearchParam(key) {\n\t return fromAndToState.params[key].location != \"search\";\n\t }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location != \"search\";\n }", "function notSearchParam(key) {\n return fromAndToState.params[key].location !== \"search\";\n }", "_entityVerify (entity, params, inputSearch) {\n\t\treturn params.reduce((valid, param) => {\n\t\t\tif (!valid)\n\t\t\t\treturn false\n\n\t\t\tif (param.operator === '$' && param.descriptor.type === String)\n\t\t\t\tparam.operator = '$in'\n\n\t\t\tlet attrValue\n\n\t\t\tif (entity instanceof Array && param.attr.match(/\\./)) {\n\t\t\t\tconst attr = param.attr.split('.').slice(1).join('.')\n\t\t\t\tattrValue = entity.genres.map(g => this._getAttr(attr, entity))\n\t\t\t} else {\n\t\t\t\tattrValue = entity[param.attr]\n\t\t\t}\n\n\t\t\tif (param.descriptor.searchSepAnd && inputSearch.match(param.descriptor.searchSepAnd)) {\n\t\t\t\tconst values = param.value.split(param.descriptor.searchSepAnd)\n\t\t\t\t\t.map(value => this._verify(attrValue, param.operator, value))\n\n\t\t\t\treturn values.reduce((p, valid) => p && valid, true)\n\t\t\t} else if (param.descriptor.searchSepOr && inputSearch.match(param.descriptor.searchSepOr)) {\n\t\t\t\tconst values = param.value.split(param.descriptor.searchSepOr)\n\t\t\t\t\t.map(value => this._verify(attrValue, param.operator, value))\n\n\t\t\t\treturn values.reduce((p, valid) => p || valid, false)\n\t\t\t}\n\n\t\t\treturn this._verify(attrValue, param.operator, param.value)\n\t\t}, true)\n\t}", "_entityVerifyOr (entity, params, inputSearch) {\n\t\treturn params.reduce((valid, and) => {\n\t\t\tif (valid) return true\n\t\t\treturn this._entityVerify(entity, and, inputSearch)\n\t\t}, false)\n\t}", "function checkParams(cb) {\n if (Array.isArray(request.params)) {\n\t //since were limiting to two request we're only taking first two items from params array\n makeRequests(request.params.slice(0, 2));\n } else {\n if (typeof request.params === 'string') {\n makeSingleRequest(request.params);\n }\n }\n}", "function paramQuerySearch() {\n var params = getParam(\"paramQuery\");\n parameterSearch(params);\n}", "searchIsValid(search) {\n if (search) {\n return true;\n }\n return false;\n }", "function systemVmGetSearchParams() {\n var moreCriteria = [];\t\n\n\tvar searchInput = $(\"#basic_search\").find(\"#search_input\").val();\t \n if (searchInput != null && searchInput.length > 0) {\t \n moreCriteria.push(\"&keyword=\"+todb(searchInput));\t \n } \n\n\tvar $advancedSearchPopup = getAdvancedSearchPopupInSearchContainer();\n\tif ($advancedSearchPopup.length > 0 && $advancedSearchPopup.css(\"display\") != \"none\" ) {\t \n\t\tvar state = $advancedSearchPopup.find(\"#adv_search_state\").val();\n\t\tif (state!=null && state.length > 0) \n\t\t\tmoreCriteria.push(\"&state=\"+todb(state));\t\t\n\t\t\t\t\n\t\tvar zone = $advancedSearchPopup.find(\"#adv_search_zone\").val();\t\n\t if (zone!=null && zone.length > 0) \n\t\t\tmoreCriteria.push(\"&zoneId=\"+zone);\t\n\t\t\n\t\tif ($advancedSearchPopup.find(\"#adv_search_pod_li\").css(\"display\") != \"none\") {\t\n\t\t var pod = $advancedSearchPopup.find(\"#adv_search_pod\").val();\t\t\n\t if (pod!=null && pod.length > 0) \n\t\t\t moreCriteria.push(\"&podId=\"+pod);\n } \n\t} \t\n\t\n\treturn moreCriteria.join(\"\"); \n}", "function searchHelper() {\r\n let searchValue = searchField.value;\r\n if (searchValue.length) search(searchValue);\r\n else getAll();\r\n }", "function cmdValidate(value, msg, args) {\n return value == \"search\" || value == \"details\";\n}", "async checkSearch(input, searchby) {\n\n if (await this.clientsPage.Search(input, searchby)) {\n await this.clientsPage.ValidateSearchResults(input, searchby)\n }\n\n return\n\n }" ]
[ "0.7056248", "0.67399013", "0.6473527", "0.63690734", "0.63413846", "0.62511694", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.62457293", "0.61709464", "0.58834416", "0.5808703", "0.58033156", "0.5786613", "0.5770642", "0.5767571", "0.5763222", "0.56778556", "0.5655151" ]
0.7054256
1
Returns a date range query that includes the missing date specificity (if any). A date that specifies year, month, date but not time will search for a range within that day (from 00:00 to 23:59), a date that specifies year, month, but not date, will search for a range within that month (from 1st day to the last), and so forth. Note: JDS has a granularity of minutes. Ex. 20150126T01:23:45 Exact search 20150126 Between 20150126T00:00 and 20150126T23:59 (inclusive) 201501 Between 20150101T00:00 and 20150131T23:59 (inclusive) 2015 Between 20150101T00:00 and 20151231T23:59 (inclusive)
function buildImplicitDateRangeQuery(dateStr, jdsProperty, isNegated, ignoreTime, includeSeconds) { var query = ''; if (YYYY_MM_DD_HH_MM_SS_Regex.test(dateStr)) { // this is an exact match search query = getExactDateQuery(new Date(dateStr), jdsProperty, isNegated, ignoreTime, true); } else { query = getDateRangeQuery(getDateRange(dateStr), jdsProperty, isNegated, ignoreTime, includeSeconds); } return query; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setupDateQuery( params ) {\n if( 'all' !== params.dateFrom ) {\n // we will not always provide a time range\n if( !params.duration && !params.dateTo ) {\n params.duration = 'day';\n }\n\n if( 'now' === params.dateFrom ) {\n params.dateFrom = moment();\n } else if( 'today' === params.dateFrom ) {\n params.dateFrom = moment().startOf( 'day' );\n }\n\n if( params.duration ) {\n params.dateFrom = moment( params.dateFrom );\n if( !params.dateFrom.isValid() ) {\n return false;\n }\n }\n }\n return true;\n }", "filterBySearchDate(fieldName, operator, searchTerms, version) {\n let query = '';\n let searchValues;\n if (Array.isArray(searchTerms) && searchTerms.length > 1) {\n searchValues = searchTerms;\n if (operator !== OperatorType.rangeExclusive && operator !== OperatorType.rangeInclusive) {\n operator = this._gridOptions.defaultFilterRangeOperator;\n }\n }\n // single search value\n if (!Array.isArray(searchValues) && Array.isArray(searchTerms) && searchTerms.length === 1 && searchTerms[0]) {\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchTerms[0], true));\n if (searchValue1) {\n return `${fieldName} ${this.mapOdataOperator(operator)} ${searchValue1}`;\n }\n }\n // multiple search value (date range)\n if (Array.isArray(searchValues) && searchValues.length === 2 && searchValues[0] && searchValues[1]) {\n // date field needs to be UTC and within DateTime function\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[0], true));\n const searchValue2 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[1], true));\n if (searchValue1 && searchValue2) {\n if (operator === OperatorType.rangeInclusive) {\n // example:: (Finish >= DateTime'2019-08-11T00:00:00Z' and Finish <= DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} ge ${searchValue1} and ${fieldName} le ${searchValue2})`;\n }\n else if (operator === OperatorType.rangeExclusive) {\n // example:: (Finish > DateTime'2019-08-11T00:00:00Z' and Finish < DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} gt ${searchValue1} and ${fieldName} lt ${searchValue2})`;\n }\n }\n }\n return query;\n }", "filterBySearchDate(fieldName, operator, searchTerms, version) {\n let query = '';\n let searchValues;\n if (Array.isArray(searchTerms) && searchTerms.length > 1) {\n searchValues = searchTerms;\n if (operator !== OperatorType.rangeExclusive && operator !== OperatorType.rangeInclusive) {\n operator = this._gridOptions.defaultFilterRangeOperator;\n }\n }\n // single search value\n if (!Array.isArray(searchValues) && Array.isArray(searchTerms) && searchTerms.length === 1 && searchTerms[0]) {\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchTerms[0], true));\n if (searchValue1) {\n return `${fieldName} ${this.mapOdataOperator(operator)} ${searchValue1}`;\n }\n }\n // multiple search value (date range)\n if (Array.isArray(searchValues) && searchValues.length === 2 && searchValues[0] && searchValues[1]) {\n // date field needs to be UTC and within DateTime function\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[0], true));\n const searchValue2 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[1], true));\n if (searchValue1 && searchValue2) {\n if (operator === OperatorType.rangeInclusive) {\n // example:: (Finish >= DateTime'2019-08-11T00:00:00Z' and Finish <= DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} ge ${searchValue1} and ${fieldName} le ${searchValue2})`;\n }\n else if (operator === OperatorType.rangeExclusive) {\n // example:: (Finish > DateTime'2019-08-11T00:00:00Z' and Finish < DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} gt ${searchValue1} and ${fieldName} lt ${searchValue2})`;\n }\n }\n }\n return query;\n }", "function dateWithinRange(date) {\n \n var currentDate = new Date(date);\n \n var minDate = new Date(startDate);\n var maxDate = new Date(endDate);\n\n if (currentDate > minDate && currentDate < maxDate ){ // checks if dates are within range\n return true;\n }\n\n if(isNaN(minDate.valueOf() || maxDate.valueOf )){ //if no contraints are entered, return all dates\n return true;\n }\n else{\n return false;\n } \n }", "function getDateCriteria(dateRange) {\n switch (dateRange) {\n case \"Daily\":\n return new Date(Date.now() - 24 * 60 * 60 * 1000);\n break;\n case \"Weekly\":\n return new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"Monthly\":\n return new Date(Date.now() - 4 * 7 * 24 * 60 * 60 * 1000);\n break;\n case \"Annual\":\n return new Date(Date.now() - 12 * 4 * 7 * 24 * 60 * 60 * 1000);\n break;\n }\n}", "function DateRange(start, end) {\n if (start === void 0) {\n start = null;\n }\n if (end === void 0) {\n end = null;\n }\n this.start = start;\n this.end = end;\n }", "function getCreationDateRangeQuery(prefix, prop, fromDate, toDate)\r\n{\r\n var luceneQuery = \" +@\"+prefix+\"\\\\:\"+prop+\":[\";\r\n if (fromDate !== null && ! isNaN(fromDate.getTime()))\r\n {\r\n luceneQuery += getLuceneDateString(fromDate);\r\n }\r\n else\r\n {\r\n luceneQuery += \"1970\\\\-01\\\\-01T00:00:00\";\r\n }\r\n luceneQuery += \" TO \";\r\n if (toDate !== null && ! isNaN(toDate.getTime()))\r\n {\r\n luceneQuery += getLuceneDateString(toDate);\r\n }\r\n else\r\n {\r\n luceneQuery += \"3000\\\\-12\\\\-31T00:00:00\";\r\n }\r\n luceneQuery += \"] \";\r\n return luceneQuery;\r\n}", "findRangeofDates(){ \n\t\tlet min=new Date(2030,1,1); \n\t\tlet max=new Date(1990,1,1);\n\t\tconst ar=this.props.data;\n\t\tfor(let i=0;i<ar.length;i++){\n\t\t\tif(ar[i].start<min)\n\t\t\t\tmin=ar[i].start;\n\t\t\tif(ar[i].end>max)\n\t\t\t\tmax=ar[i].end;\n\t\t}\n\t\tthis.min=min;\n\t\tthis.max=max;\n\t}", "findShallowIntersectingRange(date1, date2) {\n const thisRange = date1.toRange();\n const otherRange = date2.toRange(); // Start with infinite start and end dates\n\n let start = null;\n let end = null; // This start date exists\n\n if (thisRange.start) {\n // Use this definite start date if other start date is infinite\n if (!otherRange.start) {\n start = thisRange.start;\n } else {\n // Otherwise, use the earliest start date\n start = thisRange.start < otherRange.start ? thisRange.start : otherRange.start;\n } // Other start date exists\n\n } else if (otherRange.start) {\n // Use other definite start date as this one is infinite\n start = otherRange.start;\n } // Assign end date to this one if it is valid\n\n\n if (thisRange.end && (!start || thisRange.end >= start)) {\n end = thisRange.end;\n } // Assign end date to other one if it is valid and before this one\n\n\n if (otherRange.end && (!start || otherRange.end >= start)) {\n if (!end || otherRange.end < end) end = otherRange.end;\n } // Return calculated range\n\n\n return {\n start,\n end\n };\n }", "findShallowIntersectingRange(date1, date2) {\n const thisRange = date1.toRange();\n const otherRange = date2.toRange(); // Start with infinite start and end dates\n\n let start = null;\n let end = null; // This start date exists\n\n if (thisRange.start) {\n // Use this definite start date if other start date is infinite\n if (!otherRange.start) {\n start = thisRange.start;\n } else {\n // Otherwise, use the earliest start date\n start = thisRange.start < otherRange.start ? thisRange.start : otherRange.start;\n } // Other start date exists\n\n } else if (otherRange.start) {\n // Use other definite start date as this one is infinite\n start = otherRange.start;\n } // Assign end date to this one if it is valid\n\n\n if (thisRange.end && (!start || thisRange.end >= start)) {\n end = thisRange.end;\n } // Assign end date to other one if it is valid and before this one\n\n\n if (otherRange.end && (!start || otherRange.end >= start)) {\n if (!end || otherRange.end < end) end = otherRange.end;\n } // Return calculated range\n\n\n return {\n start,\n end\n };\n }", "function restrictPassedDate(){\n let date = new Date(),\n day = date.getDate(),\n month = date.getMonth()+1,\n year = date.getFullYear();\n if(day < 10){\n day = `0${day}`;\n }\n if(month < 10){\n month = `0${month}`;\n }\n dateStart.min = `${year}-${month}-${day}`;\n dateEnd.min = `${year}-${month}-${day}`;\n}", "resetDateRange() {\n var beg, end;\n beg = Data.toDateStr(Data.begDay, Data.monthIdx);\n end = Data.advanceDate(beg, Data.numDays - 1);\n return this.res.dateRange(beg, end, this.resetRooms);\n }", "function prepareQueryDates() {\n var userProperties = PropertiesService.getUserProperties();\n var configurationData = userProperties.getProperties();\n\n var startDateHTML = isoToDate(configurationData.StartDate);\n var endDateHTML = isoToDate(configurationData.EndDate);\n\n var startDate = new Date(startDateHTML);\n var endDate = new Date(endDateHTML);\n\n var startDateMil = startDate.getTime();\n var endDateMil = endDate.getTime();\n\n // Set the unit values in milliseconds.\n var msecPerMinute = 1000 * 60;\n var msecPerHour = msecPerMinute * 60;\n var msecPerDay = msecPerHour * 24;\n var daysInData = (endDate - startDate) / msecPerDay;\n\n var dateObj = {\n startDate: startDate,\n startDateHTML: startDateHTML,\n startDateMil: startDateMil,\n endDate: endDate,\n endDateHTML: endDateHTML,\n endDateMil: endDateMil,\n daysInData: daysInData,\n msecPerDay: msecPerDay\n };\n\n return dateObj;\n\n}", "function createESQueryFromDate(mustQueryTerms, mustNotQueryTerms, date) {\n var mustQueryTermsWithDate = addDateRangeToQueries(mustQueryTerms, date);\n return {\n size: 5000,\n query: {\n bool: {\n must: mustQueryTermsWithDate,\n must_not: mustNotQueryTerms\n }\n }\n };\n }", "function getDateRestriction (dateReport){\n\tvar restriction = \" gp.date_start <= #Date%\" + dateReport + \"% AND gp.date_end >= #Date%\" + dateReport + \"%\";\n\treturn restriction;\n}", "function get_publication_date_query(){\n let query = [];\n\n let minDate = document.getElementById(\"minDate\").value;\n let maxDate = document.getElementById(\"maxDate\").value;\n let tmp = 0;\n\n if ((new Date(minDate).getTime() > new Date(maxDate).getTime())){\n tmp = minDate;\n minDate = maxDate;\n maxDate = tmp\n }\n\n query.push(\"minDate=\"+minDate);\n query.push(\"maxDate=\"+maxDate);\n console.log(query);\n return query.join(\"&\");\n}", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n return date;\n}", "function getDateRangeFrom(request) {\n var qs = (request && request.query) ? request.query : {};\n var from = moment(new Date(qs.from));\n var to = qs.to ? moment(new Date(qs.to)) : from.isValid() ? from : moment();\n var som = (from.isValid() ? from.clone() : to.clone()).startOf('month');\n var eom = som.clone().endOf('month');\n\n if (qs.tz) {\n var dt = moment()\n .subtract(qs.monthsAgo || 0, 'months')\n .subtract(qs.daysAgo || 0, 'days');\n\n if (qs.from)\n dt = moment(new Date(qs.from));\n\n from = moment.tz(dt, qs.tz).startOf('day');\n to = moment.tz(dt, qs.tz).endOf('day');\n som = moment.tz(dt, qs.tz).startOf('month');\n eom = moment.tz(dt, qs.tz).endOf('month');\n }\n\n if (request && request.monthRange) {\n from = som;\n to = eom;\n }\n\n return {\n 'from': from.toISOString(),\n 'to': to.toISOString(),\n 'startOfMonth': som.toISOString(),\n 'endOfMonth': eom.toISOString()\n };\n}", "function datesSearch() {\n let error = false;\n\n dateFrom = $('#dateFrom').val();\n dateTo = $('#dateTo').val();\n\n if (dateFrom.length !== 0) {\n $('#dateFrom').removeClass('error');\n } else {\n $('#dateFrom').addClass('error');\n error = true;\n }\n if (dateTo.length !== 0) {\n $('#dateTo').removeClass('error');\n } else {\n $('#dateTo').addClass('error');\n error = true;\n }\n if (error) {\n $('#dateLengthErr').show();\n } else {\n $('#dateLengthErr').hide();\n }\n\n let dateFromMoment = moment(dateFrom, \"YYYY-MM-DD\");\n if (dateFromMoment.isAfter(dateTo)) {\n $('#dateFrom').addClass('error');\n $('#dateError').show();\n error = true;\n } else {\n $('#dateError').hide();\n }\n\n if (error) {\n return;\n }\n\n // Custom datatable search function to only return rows that are between the 2 dates\n $.fn.dataTableExt.afnFiltering.push(\n function(oSettings, aData, iDataIndex) {\n let dateFrom = parseDateValue($('#dateFrom').val());\n let dateTo = parseDateValue($('#dateTo').val());\n\n let evalDate = parseDateValue(aData[1]);\n\n if (evalDate >= dateFrom && evalDate <= dateTo) {\n return true;\n } else {\n return false;\n }\n }\n );\n\n // Once the table has been searched it must be redrawn to show the filtered results\n datatable.draw();\n\n sumTableData();\n updateChart();\n}", "function dt_add_rangedate_filter(begindate_id, enddate_id, dateCol) {\n $.fn.dataTableExt.afnFiltering.push(\n function( oSettings, aData, iDataIndex ) {\n\n var beginDate = Date_from_syspref($(\"#\"+begindate_id).val()).getTime();\n var endDate = Date_from_syspref($(\"#\"+enddate_id).val()).getTime();\n\n var data = Date_from_syspref(aData[dateCol]).getTime();\n\n if ( !parseInt(beginDate) && ! parseInt(endDate) ) {\n return true;\n }\n else if ( beginDate <= data && !parseInt(endDate) ) {\n return true;\n }\n else if ( data <= endDate && !parseInt(beginDate) ) {\n return true;\n }\n else if ( beginDate <= data && data <= endDate) {\n return true;\n }\n return false;\n }\n );\n}", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n\n return date;\n }", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n return date;\n }", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n return date;\n }", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n return date;\n }", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n return date;\n }", "function constrainMarkerToRange(date, range) {\n if (range.start != null && date < range.start) {\n return range.start;\n }\n\n if (range.end != null && date >= range.end) {\n return new Date(range.end.valueOf() - 1);\n }\n\n return date;\n }", "function executeAssociatedDateCondition(options) {\n const filterSearchType = options && (options.filterSearchType || options.fieldType) || FieldType.dateIso;\n const FORMAT = mapMomentDateFormatWithFieldType(filterSearchType);\n const searchTerms = Array.isArray(options.searchTerms) && options.searchTerms || [];\n let isRangeSearch = false;\n let dateSearch1;\n let dateSearch2;\n // return when cell value is not a valid date\n if (searchTerms.length === 0 || searchTerms[0] === '' || searchTerms[0] === null || !moment$3(options.cellValue, FORMAT, true).isValid()) {\n return false;\n }\n // cell value in moment format\n const dateCell = moment$3(options.cellValue, FORMAT, true);\n if (searchTerms.length === 2 || (searchTerms[0].indexOf('..') > 0)) {\n isRangeSearch = true;\n const searchValues = (searchTerms.length === 2) ? searchTerms : searchTerms[0].split('..');\n const searchValue1 = (Array.isArray(searchValues) && searchValues[0] || '');\n const searchValue2 = (Array.isArray(searchValues) && searchValues[1] || '');\n const searchTerm1 = moment$3(searchValue1, FORMAT, true);\n const searchTerm2 = moment$3(searchValue2, FORMAT, true);\n // return if any of the 2 values are invalid dates\n if (!moment$3(searchTerm1, FORMAT, true).isValid() || !moment$3(searchTerm2, FORMAT, true).isValid()) {\n return false;\n }\n dateSearch1 = moment$3(searchTerm1, FORMAT, true);\n dateSearch2 = moment$3(searchTerm2, FORMAT, true);\n }\n else {\n // return if the search term is an invalid date\n if (!moment$3(searchTerms[0], FORMAT, true).isValid()) {\n return false;\n }\n dateSearch1 = moment$3(searchTerms[0], FORMAT, true);\n }\n // run the filter condition with date in Unix Timestamp format\n if (isRangeSearch) {\n const isInclusive = options.operator && options.operator === OperatorType.rangeInclusive;\n const resultCondition1 = testFilterCondition((isInclusive ? '>=' : '>'), parseInt(dateCell.format('X'), 10), parseInt(dateSearch1.format('X'), 10));\n const resultCondition2 = testFilterCondition((isInclusive ? '<=' : '<'), parseInt(dateCell.format('X'), 10), parseInt(dateSearch2.format('X'), 10));\n return (resultCondition1 && resultCondition2);\n }\n return testFilterCondition(options.operator || '==', parseInt(dateCell.format('X'), 10), parseInt(dateSearch1.format('X'), 10));\n}", "dateShallowIncludesDate(date1, date2) {\n // First date is simple date\n if (date1.isDate) {\n if (date2.isDate) {\n return date1.dateTime === date2.dateTime;\n }\n\n if (!date2.startTime || !date2.endTime) {\n return false;\n }\n\n return date1.dateTime === date2.startTime && date1.dateTime === date2.endTime;\n } // Second date is simple date and first is date range\n\n\n if (date2.isDate) {\n if (date1.start && date2.date < date1.start) {\n return false;\n }\n\n if (date1.end && date2.date > date1.end) {\n return false;\n }\n\n return true;\n } // Both dates are date ranges\n\n\n if (date1.start && (!date2.start || date2.start < date1.start)) {\n return false;\n }\n\n if (date1.end && (!date2.end || date2.end > date1.end)) {\n return false;\n }\n\n return true;\n }", "dateShallowIncludesDate(date1, date2) {\n // First date is simple date\n if (date1.isDate) {\n if (date2.isDate) {\n return date1.dateTime === date2.dateTime;\n }\n\n if (!date2.startTime || !date2.endTime) {\n return false;\n }\n\n return date1.dateTime === date2.startTime && date1.dateTime === date2.endTime;\n } // Second date is simple date and first is date range\n\n\n if (date2.isDate) {\n if (date1.start && date2.date < date1.start) {\n return false;\n }\n\n if (date1.end && date2.date > date1.end) {\n return false;\n }\n\n return true;\n } // Both dates are date ranges\n\n\n if (date1.start && (!date2.start || date2.start < date1.start)) {\n return false;\n }\n\n if (date1.end && (!date2.end || date2.end > date1.end)) {\n return false;\n }\n\n return true;\n }", "function withinDate(d, m, y) {\n\n startDateArray = $('#startDate').val().split(\" \");\n endDateArray = $('#endDate').val().split(\" \");\n\n var startDay = parseInt(startDateArray[0]);\n var startMonth2 = monthNames.indexOf(startDateArray[1]) + 1;\n if (startMonth2 < 10){\n startMonth2 = \"0\" + startMonth2;\n }\n var startMonth = parseInt(startMonth2);\n var startYear = parseInt(startDateArray[2]);\n\n var endDay = parseInt(endDateArray[0]);\n var endMonth2 = monthNames.indexOf(endDateArray[1]) + 1;\n if (endMonth2 < 10){\n endMonth2 = \"0\" + endMonth2;\n }\n var endMonth = parseInt(endMonth2);\n var endYear = parseInt(endDateArray[2]);\n\n var d1 = [startMonth, startDay, startYear];\n var d2 = [endMonth, endDay, endYear];\n var c = [m, d, y];\n\n var from = new Date(d1); // -1 because months are from 0 to 11\n var to = new Date(d2);\n var check = new Date(c);\n\n return(check >= from && check <= to);\n }" ]
[ "0.60283846", "0.5931526", "0.5931526", "0.5898166", "0.5627309", "0.56107116", "0.5594415", "0.5552875", "0.5550687", "0.5550687", "0.5547632", "0.549748", "0.54855233", "0.53691137", "0.5366445", "0.53458875", "0.5334486", "0.53310484", "0.5328851", "0.5316035", "0.53124607", "0.52606565", "0.52606565", "0.52606565", "0.52606565", "0.52581644", "0.52526397", "0.52349156", "0.52349156", "0.52299845" ]
0.68885946
0
Returns true if there's a sort parameter specified and its criteria has a mapped property.
function isSortCriteriaValid(params, fhirToJDSSortMap) { if (nullchecker.isNotNullish(params._sort)) { return nullchecker.isNotNullish(fhirToJDSSortMap[params._sort]); } else if (nullchecker.isNotNullish(params['_sort:asc'])) { return nullchecker.isNotNullish(fhirToJDSSortMap[params['_sort:asc']]); } else if (nullchecker.isNotNullish(params['_sort:desc'])) { return nullchecker.isNotNullish(fhirToJDSSortMap[params['_sort:desc']]); } else { return true; // there's no _sort parameter, thus it is not invalid } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "isSortingRequired() {\n const entriesType = this.getEntriesType();\n const { isSortingRequired = false } = this.props.state.entries[entriesType];\n\n return isSortingRequired;\n }", "_isSorted() {\n return this._sort.active == this.id &&\n (this._sort.direction === 'asc' || this._sort.direction === 'desc');\n }", "_isSorted() {\n return this._sort.active == this.id &&\n (this._sort.direction === 'asc' || this._sort.direction === 'desc');\n }", "function isSortable(object){\n\treturn !!object.sort; \n}", "get isSorting() {\r\n return this.i.cf;\r\n }", "function someProperties(map, predicate) {\n for (var key in map) {\n if (!predicate || predicate(map[key], key))\n return true;\n }\n return false;\n }", "function truthCheck(collection, pre) {\n var counter = 0;\n for (var c in collection) {\n if (collection[c].hasOwnProperty(pre) && (collection[c][pre])) {\n counter++;\n }\n }\n \n return counter == collection.length;\n }", "hasProperty(aProperty){\n for(let i = 0; i < this._properties.length; i++){\n let prop = this._properties[i];\n if(aProperty.matches(prop)){\n return true;\n }\n }\n return false;\n }", "static isComparable(prop, root) {\n const virtual = prop.persist === false;\n const inverse = prop.reference === enums_1.ReferenceType.ONE_TO_ONE && !prop.owner;\n const discriminator = prop.name === root.discriminatorColumn;\n const collection = prop.reference === enums_1.ReferenceType.ONE_TO_MANY || prop.reference === enums_1.ReferenceType.MANY_TO_MANY;\n return !virtual && !collection && !inverse && !discriminator && !prop.version;\n }", "function canBeSorted() {\n return true;\n }", "function validateSort(sort) {\n if (typeof sort !== 'string') {\n return false;\n }\n\n return sorts.includes(sort);\n}", "compareBy(a, b) {\n const { key, order } = this.state.sort;\n\n if (key && order) {\n if (a[key] < b[key]) return -1;\n if (a[key] > b[key]) return 1;\n return 0;\n }\n\n return false;\n }", "function isSortable(o) {\n if (o && // o is not null, undefined, etc.\n typeof o === \"object\" && // o is an object\n typeof o.sort === \"function\") // o.sort is a function\n return true; // Then o is array-like\n else\n return false; // Otherwise it is not\n}", "function isSortable(o) {\n if (o && // o is not null, undefined, etc.\n typeof o === \"object\" && // o is an object\n typeof o.sort === \"function\") // o.sort is a function\n return true; // Then o is array-like\n else\n return false; // Otherwise it is not\n}", "canUp() {\n if (!this.parent) {\n return false;\n }\n const props = this.parent.order ? this.parent.order : Object.keys(this.parent.properties);\n const index = props.indexOf(this.name);\n if (index >= 0) {\n return index > 0;\n }\n else {\n for (const p of props) {\n if (Array.isArray(p)) {\n if (p.indexOf(this.name) >= 0) {\n return p.indexOf(this.name) > 0;\n }\n }\n }\n }\n }", "function truthCheck(collection, pre) {\r\n\t\tfor (var i = 0; i < collection.length; i++) {\r\n\t\t\tif (!collection[i].hasOwnProperty(pre)) {\r\n\t\t\t\treturn false;\r\n\t\t\t} else {\r\n\t\t\t\tif (!collection[i][pre]) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}", "function isSortedMap(maybeSortedMap) {\n return isMap(maybeSortedMap) && isSorted(maybeSortedMap);\n}", "prepareSort(orderBy, allowed_cols, tableAlias, excludeOrder = false, validatedAggAliases) {\n let column_names = this.column_names.slice(0);\n const throwErr = () => {\n throw \"\\nInvalid orderBy option -> \" + JSON.stringify(orderBy) +\n \"\\nExpecting { key2: false, key1: true } | { key1: 1, key2: -1 } | [{ key1: true }, { key2: false }] | [{ key1: 1 }, { key2: -1 }]\";\n }, parseOrderObj = (orderBy, expectOne = false) => {\n if (!isPlainObject(orderBy))\n return throwErr();\n if (expectOne && Object.keys(orderBy).length > 1)\n throw \"\\nInvalid orderBy \" + JSON.stringify(orderBy) +\n \"\\nEach orderBy array element cannot have more than one key\";\n /* { key2: bool, key1: bool } */\n if (!Object.values(orderBy).find(v => ![true, false].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: Boolean(orderBy[key]) }));\n }\n else if (!Object.values(orderBy).find(v => ![-1, 1].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: orderBy[key] === 1 }));\n }\n else if (!Object.values(orderBy).find(v => ![\"asc\", \"desc\"].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: orderBy[key] === \"asc\" }));\n }\n else\n return throwErr();\n };\n if (!orderBy)\n return \"\";\n let allowedFields = [];\n if (allowed_cols) {\n allowedFields = this.parseFieldFilter(allowed_cols);\n }\n let _ob = [];\n if (isPlainObject(orderBy)) {\n _ob = parseOrderObj(orderBy);\n }\n else if (typeof orderBy === \"string\") {\n /* string */\n _ob = [{ key: orderBy, asc: true }];\n }\n else if (Array.isArray(orderBy)) {\n /* Order by is formed of a list of ascending field names */\n let _orderBy = orderBy;\n if (_orderBy && !_orderBy.find(v => typeof v !== \"string\")) {\n /* [string] */\n _ob = _orderBy.map(key => ({ key, asc: true }));\n }\n else if (_orderBy.find(v => isPlainObject(v) && Object.keys(v).length)) {\n if (!_orderBy.find(v => typeof v.key !== \"string\" || typeof v.asc !== \"boolean\")) {\n /* [{ key, asc }] */\n _ob = Object.freeze(_orderBy);\n }\n else {\n /* [{ [key]: asc }] | [{ [key]: -1 }] */\n _ob = _orderBy.map(v => parseOrderObj(v, true)[0]);\n }\n }\n else\n return throwErr();\n }\n else\n return throwErr();\n if (!_ob || !_ob.length)\n return \"\";\n let bad_param = _ob.find(({ key }) => !(validatedAggAliases || []).includes(key) &&\n (!column_names.includes(key) ||\n (allowedFields.length && !allowedFields.includes(key))));\n if (!bad_param) {\n return (excludeOrder ? \"\" : \" ORDER BY \") + (_ob.map(({ key, asc }) => `${tableAlias ? pgp.as.format(\"$1:name.\", tableAlias) : \"\"}${pgp.as.format(\"$1:name\", key)} ${asc ? \" ASC \" : \" DESC \"}`).join(\", \"));\n }\n else {\n throw \"Unrecognised orderBy fields or params: \" + bad_param.key;\n }\n }", "function truthCheck(collection, pre) {\n //set counter variable\n var counter = 0;\n //check for each object\n for(var c in collection) {\n //check if it has the property and is true\n if(collection[c].hasOwnProperty(pre) && Boolean(collection[c][pre])) {\n counter++;\n }\n }\n //check to see if it is truthy and return true or false\n return counter == collection.length;\n}", "get isDataPreSorted() {\r\n return this.i.k9;\r\n }", "function truthCheck(collection, pre) {\n // For every object in collection\n for (var object of collection) {\n // If the (pre) property of that object returns false - return false \n if (!object[pre]) return false;\n }\n // All objects have properties (pre) with a truthy value - return true\n return true;\n }", "function isPropFiltered(propertyKey) {\n let filtered = false;\n filtered = Object.keys(propertyKey).some((propertyValue) => !propertyKey[propertyValue][0]);\n return filtered;\n }", "function dynamicSort(property) {\n\n var sortOrder = -1;\n\n return function (a,b) {\n // if first of properties to sort is undefined, push it to the end\n if (!a[property]) {\n return 1;\n // if second of properties to sort is undefined, push it to the end\n } else if (!b[property]) {\n return -1; \n } else { \n // compare the selected property of each person\n if (sortOrder == -1) {\n return b[property].localeCompare(a[property]);\n } else {\n return a[property].localeCompare(b[property]);\n } \n }\n }\n}", "function hasProperty(selected) {\n return (property && (selected[property] !== undefined)) ||\n (method && (typeof selected[method] === 'function'));\n }", "_checkParam() {\n if (this.datascales && this.dataInfo.entity_items && Object.keys(this.dataInfo.entity_items)) {\n this.datascales.range = this.datascales.range || 24\n this.datascales.aggregate = this.datascales.aggregate || \"last\"\n return true\n }\n return false\n }", "hasProps(obj) {\n const size = this.size;\n\n for (let i = 0; i < size; ++i) {\n const prop = this.getProp(obj, i);\n\n if (prop === null || prop === undefined) {\n return false;\n }\n }\n\n return true;\n }", "get shouldDisplayParams() {\n let params = this.args.item?.params || [];\n\n return params.some((p) => p.description || p.name.includes('.'));\n }", "getSortCriteria(args) {\n var al = args.length, props;\n \n if (args.length == 1) {\n var firstParameter = args[0];\n if (_.isString(firstParameter) && firstParameter.search(/,|\\s/) > -1)\n return this.parseSortBy(firstParameter);\n }\n\n if (al > 1) {\n // passing multiple property names sortBy(a, \"aa\", \"bb\", \"cc\");\n var a = _.toArray(args);\n props = _.map(a, x => {\n return this.normalizeSortByValue(x, true);\n });\n } else {\n // expect a single string; or an object\n props = this.normalizeSortByValue(args[0]);\n }\n return props;\n }", "function HasProperty(O, P) { // eslint-disable-line no-unused-vars\n\t\t// Assert: Type(O) is Object.\n\t\t// Assert: IsPropertyKey(P) is true.\n\t\t// Return ? O.[[HasProperty]](P).\n\t\treturn P in O;\n\t}", "hasSuggestions() {\n return this.filteredAirports && Object.keys(this.filteredAirports).length > 1;\n }" ]
[ "0.6573961", "0.6372966", "0.6372966", "0.59564346", "0.5885027", "0.569908", "0.5341275", "0.53161395", "0.52838004", "0.5260939", "0.51858646", "0.5172329", "0.51653075", "0.51653075", "0.51466787", "0.51355976", "0.51302564", "0.51179063", "0.510106", "0.5091016", "0.5077008", "0.4989091", "0.49870053", "0.49852154", "0.49627548", "0.49620554", "0.49433503", "0.49276003", "0.49120867", "0.4909593" ]
0.6775237
0
Delete All Items with Sweet Alert Library
function del_all_item(){ Swal.fire({ title: 'Are you sure?', text: "You Want to Delete Whole TODO List!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { li.innerHTML=""; Swal.fire( 'Deleted!', 'Your TODO List Has Been Deleted.', 'success' ) } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function postDelete() {\n console.log('item deleted');\n swal({\n title: \"Dare Approved!\",\n icon: \"success\",\n button: \"Done\"\n })\n .then( () => {\n location.reload();\n })\n }", "handleDeleteButtonClick() {\n Alert.alert(\"Hold on!\", \"Are you sure you want to clear all data?\", [\n {\n text: \"Cancel\",\n onPress: () => null,\n style: \"cancel\"\n },\n { text: \"YES\", onPress: () => this.deleteAll() }\n ]);\n return true;\n }", "function alDelete(id) {\n swal({\n title: \"Bạn chắc muốn xóa bỏ?\",\n // text: \"Bạn sẽ không thể khôi phục lại bản ghi này!!\",\n type: \"warning\",\n showCancelButton: true,\n confirmButtonColor: \"#DD6B55\",\n cancelButtonText: \"Không\",\n confirmButtonText: \"Có\",\n // closeOnConfirm: false,\n },\n function (isConfirm) {\n if (isConfirm) {\n $.ajax({\n type: \"delete\",\n url: \"/report/market/\" + id,\n success: function (res) {\n if (!res.error) {\n toastr.success('Đã xóa!');\n $('#data-' + id).remove();\n }\n },\n error: function (xhr, ajaxOptions, thrownError) {\n toastr.error(thrownError);\n }\n });\n } else {\n toastr.error(\"Hủy bỏ thao tác!\");\n }\n });\n}", "function swalCancelDelete() {\n return swalWithBootstrapBtns.fire(\n 'Cancelled',\n 'Your imaginary data is safe :)',\n 'error'\n )\n}", "function DeleteI(id) {\nswal({\ntitle: 'Deseas Eliminar el Registro?',\ntext: \"Recueda,Una vez eliminado no se puede Recuperar\",\ntype: 'warning',\nshowCancelButton: true,\nconfirmButtonColor: '#3085d6',\ncancelButtonColor: '#d33',\nconfirmButtonText: 'Si,Eliminarlo!'\n}).then(function () {\n$.post(\"../../model/items/delete.php\", {\nid: id\n},\nfunction (data, status) {\nreadRecordsI();\n}\n);\n})\n}", "function deleteAlert(text) {\n swal({\n title: \"Warning\",\n text: text,\n type: \"warning\",\n showCancelButton: true,\n confirmButtonText: \"Delete\",\n cancelButtonText: \"Cancel\",\n closeOnConfirm: false\n }, function (result) {\n if (result === true) {\n //if (language === 'cy' && !(path.match(/\\/bulletins\\//) || path.match(/\\/articles\\//))) {\n if (language === 'cy') {\n path = path + '/data_cy.json';\n }\n deleteContent(collectionId, path, function () {\n viewCollectionDetails(collectionId);\n swal({\n title: \"Page deleted\",\n text: \"This page has been deleted\",\n type: \"success\",\n timer: 2000\n });\n }, function (error) {\n handleApiError(error);\n }\n );\n }\n });\n }", "function swalSuccessDelete() {\n return swalWithBootstrapBtns.fire(\n 'Deleted!',\n 'Your data has been deleted.',\n 'success'\n )\n}", "'click #remove'() {\n var id_listItem = this._id;\n swal({ \n title: \"Your task will be deleted!\", \n text: \"Are you sure to proceed?\", \n icon: \"warning\", \n buttons: [\n 'No, cancel it!',\n 'Yes, I am sure!'\n ],\n dangerMode: true,\n }).then(function(isConfirm)\n { \n if (isConfirm) \n { \n Meteor.call(\"task_list_remove\",id_listItem,function(error,result){\n if(error){\n alert(\"ERROR,THERE IS SOMETHING WRONG\");\n }\n else{\n swal({\n text : \"Your Task deleted\",\n icon : \"success\",\n });\n }\n }); \n } \n else{ \n swal(\"Your task is safe\"); \n } \n });\n }", "function delete_selected_user_reviews(message) {\n swal({\n text: message,\n icon: \"warning\",\n buttons: true,\n buttons: [sweetalert_cancel, sweetalert_ok],\n dangerMode: true,\n }).then(function (willDelete) {\n if (willDelete) {\n\n var review_ids = [];\n $(\"input[name='checkbox-table']:checked\").each(function () {\n review_ids.push(this.value);\n });\n var data = {\n 'review_ids': review_ids,\n };\n data[csfr_token_name] = $.cookie(csfr_cookie_name);\n $.ajax({\n type: \"POST\",\n url: base_url + \"admin_controller/delete_selected_user_reviews\",\n data: data,\n success: function (response) {\n location.reload();\n }\n });\n\n }\n });\n}", "function delete_post_list_item_database(item_id, post_type, message) {\n swal({\n text: message,\n icon: \"warning\",\n buttons: [sweetalert_cancel, sweetalert_ok],\n dangerMode: true,\n }).then(function (willDelete) {\n if (willDelete) {\n var data = {\n 'item_id': item_id,\n 'post_type': post_type\n };\n data[csfr_token_name] = $.cookie(csfr_cookie_name);\n $.ajax({\n type: \"POST\",\n url: base_url + \"post_controller/delete_post_list_item_post\",\n data: data,\n success: function (response) {\n $('#panel_list_item_' + item_id).remove();\n }\n });\n }\n });\n}", "function delete_task(url){\n swal({\n title: \"Are you sure?\",\n text: \"Once deleted, you will not be able to recover this labour task!\",\n icon: \"warning\",\n buttons: true,\n dangerMode: true,\n })\n .then((willDelete) => {\n if (willDelete) {\n\n $.LoadingOverlay(\"show\");\n $.ajax({\n url: url,\n type: \"DELETE\",\n \n data:{ \"_token\": $('meta[name=\"csrf-token\"]').attr('content')},\n success: function (data) {\n $.LoadingOverlay(\"hide\");\n toastr.success('Labour task successfully deleted.', 'Success', {timeOut: 5000});\n daily_task_management_table.ajax.reload(null, false);\n },\n error: function(jqXHR, textStatus, errorThrown) {\n $.LoadingOverlay(\"hide\");\n var response=jqXHR.responseJSON;\n var status=jqXHR.status;\n if(status=='404'){\n toastr.error('Invalid URL', 'Error', {timeOut: 5000});\n }else{\n toastr.error('Internal server error.', 'Error', {timeOut: 5000});\n }\n }\n });\n\n \n\n\n } \n });\n\n }", "removeAlert(id) {\n console.log('Remove Alert');\n swal({\n title: \"Are you sure?\",\n text: \"Once deleted, you will not be able to recover this project file!\",\n icon: \"warning\",\n buttons: true,\n dangerMode: true,\n })\n .then((willDelete) => {\n if (willDelete) {\n { this.removeProject(id) };\n swal(\"Poof! Your project file has been deleted!\", {\n icon: \"success\",\n\n });\n } else {\n swal(\"Your project file is safe!\");\n }\n });\n }", "function deleteconfirm(title,text,location)\n{\n swal({\n title: title,\n text: text,\n type: \"warning\",\n showCancelButton: true,\n confirmButtonText: \"OK\",\n closeOnConfirm: false,\n confirmButtonColor: \"#DD6B55\"\n },\n function(){\n window.location = location\n });\n}", "function excluir(obj){\n swal({\n title: 'Você está certo disso?',\n text: \"Ação irreversivel!\",\n type: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#3085d6',\n cancelButtonColor: '#d33',\n confirmButtonText: 'Sim, tenho certeza!',\n cancelButtonText: 'Cancelar...'\n }).then((result) => \n { if (result.value) \n { \n fetch(URL_BASE +obj,{\n method:'DELETE'\n })\n //Na primera promisse nao tem o json\n //.then(response => console.log(response))\n .then(response => response.json())\n .then(json => swal(json.mensagem ))\n .then(json => printTela(json))\n }\n })\n \n \n \n}", "function acceptDelete() {\n var x = $('#data-google-drive:checkbox:checked').length;\n if (x != 0) {\n swal({\n title: 'Confirm To Delete',\n text: \"Are you sure you want to delete?\",\n type: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#3085d6',\n cancelButtonColor: '#d33',\n confirmButtonText: 'Yes, delete it!'\n }).then((result) => {\n if (result.value) {\n var ids = $('tbody input[type=checkbox]:checked').map(function () {\n return $(this).val();\n }).get();\n deleteFile(ids);\n }\n });\n } else {\n swal({\n title: 'Warning',\n text: \"You have not selected file!\",\n type: 'warning',\n });\n }\n}", "function delete_selected_products_permanently(message) {\n swal({\n text: message,\n icon: \"warning\",\n buttons: true,\n buttons: [sweetalert_cancel, sweetalert_ok],\n dangerMode: true,\n }).then(function (willDelete) {\n if (willDelete) {\n var product_ids = [];\n $(\"input[name='checkbox-table']:checked\").each(function () {\n product_ids.push(this.value);\n });\n var data = {\n 'product_ids': product_ids,\n };\n data[csfr_token_name] = $.cookie(csfr_cookie_name);\n $.ajax({\n type: \"POST\",\n url: base_url + \"product_admin_controller/delete_selected_products_permanently\",\n data: data,\n success: function (response) {\n location.reload();\n }\n });\n }\n });\n}", "function removeCustomAlert() {\n console.log(\"function: removeCustomAlert\");\n\n let alertElements = $(\".customAlert\")\n\n for (let i=0; i<alertElements.length; i++){\n alertElements[i].remove();\n }\n}", "function removeAlert() {\n $.uikitNotify.remove($alert);\n }", "function deleteAllNotices() {\n axios({\n method: 'DELETE',\n url: '/deleteAllNotices'\n }).then(function () {\n store.dispatch(setNoticeDisplay(0));\n window.location.reload();\n })\n .catch(function (error) {\n console.log(error);\n })\n .then(function () {\n // always executed\n });\n}", "function contentDelete(id){\n Swal.fire({\n title: 'Are you sure?',\n text: \"You won't be able to revert this!\",\n icon: 'warning',\n showCancelButton: true,\n confirmButtonText: 'Yes, delete it!',\n customClass: {\n confirmButton: 'btn btn-primary',\n cancelButton: 'btn btn-outline-danger ml-1'\n },\n buttonsStyling: false\n }).then(function (result) {\n if (result.value) {\n $.ajax({\n url: './contents/delete/' + id,\n type: 'DELETE',\n dataType: 'json',\n contentType: 'application/json; charset=utf-8',\n success: function (data) {\n if( id != null){\n Swal.fire({\n icon: 'success',\n title: \"Deleted!\",\n text: data.message,\n customClass: {\n confirmButton: 'btn btn-success'\n }\n });\n resetForm()\n }else{\n Swal.fire({\n icon: 'error',\n title: \"Error\",\n text: data.message,\n customClass: {\n confirmButton: 'btn btn-success'\n }\n });\n }\n },\n error: function (err) {\n Swal.fire({\n icon: 'error',\n title: \"Error\",\n text: \"An error occurred during the delete operation\",\n customClass: {\n confirmButton: 'btn btn-success'\n }\n });\n console.log(err)\n }\n })\n }\n });\n}", "function deleteIt(){\n \tupdateDB(\"delete\", pageElements.alertText.dataset.id);\n }", "deleteMotocycle(maSP){\n Alert.alert(\"Xác nhận!\", \"Bạn có chắc chắn muốn xóa dữ liệu?\", [\n {text: \"Hủy\", onPress: ()=>console.log(\"Cancel tapped\")},\n {text: \"Đồng ý\", onPress: ()=> this.deleteData(maSP)},\n ],\n {cancelable: false});\n }", "function delete_li(rm){\nrm.parentNode.remove()\nsweetAlertSuccessMsg(\"Deleted Successfully\")\n}", "function DeleteConfirmAlert(me, first_messages, final_messages, datatable_name){\n $.confirm({\n title: 'Confirmation',\n content: first_messages,\n icon: 'fa fa-exclamation-triangle',\n animation: 'scale',\n closeAnimation: 'scale',\n opacity: 0.5,\n buttons: {\n 'confirm': {\n text: 'Proceed',\n btnClass: 'btn-blue',\n action: function(){\n $.confirm({\n title: 'This maybe critical',\n content: final_messages,\n icon: 'fa skull-crossbones',\n animation: 'scale',\n closeAnimation: 'zoom',\n buttons: {\n confirm: {\n text: 'Yes, sure!',\n btnClass: 'btn-danger',\n action: function(){\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n var url = me.data('url');\n $.ajax({\n url: url,\n type: 'DELETE',\n dataType: 'json',\n data: {method: '_DELETE', submit: true},\n success: function(data){\n var session = data.msg;\n if(data.status == 'success'){\n $(datatable_name).DataTable().draw(false);\n if (session != \"\"){\n Swal.fire({\n title: 'Good job!',\n text: session,\n type: 'success',\n // confirmButtonText: 'Deposit Funds'\n }).then(function() {\n // window.location = \"https://cryptolico.com/portal/deposit-fund\";\n });\n }\n }else{\n if (session != \"\"){\n Swal.fire({\n title: 'Sorry!',\n text: session,\n type: 'warning',\n })\n }\n }\n \n }\n })\n }\n },\n cancel: function(){\n //$.alert('you clicked on <strong>cancel</strong>');\n }\n }\n });\n }\n },\n cancel: function(){\n //$.alert('you clicked on <strong>cancel</strong>');\n },\n \n }\n });\n\n}", "function delete_user(url){\nswal({\ntitle: \"Are you sure?\",\ntext: \"Once deleted, you will not be able to recover this unit!\",\nicon: \"warning\",\nbuttons: true,\ndangerMode: true,\n})\n.then((willDelete) => {\nif (willDelete) {\n\n $.LoadingOverlay(\"show\");\n $.ajax({\n url: url,\n type: \"DELETE\",\n data:{ \"_token\": $('meta[name=\"csrf-token\"]').attr('content')},\n success: function (data) {\n\n units_table.ajax.reload(null, false);\n $.LoadingOverlay(\"hide\");\n toastr.success('Unit successfully deleted.', 'Success', {timeOut: 5000});\n },\n error: function(jqXHR, textStatus, errorThrown) {\n $.LoadingOverlay(\"hide\");\n var response=jqXHR.responseJSON;\n var status=jqXHR.status;\n if(status=='404'){\n toastr.error('Invalid URL', 'Error', {timeOut: 5000});\n }else if(status=='400'){\n if(response.message){\n toastr.error(response.message, 'Error', {timeOut: 5000});\n }else{\n toastr.error('Server error', 'Error', {timeOut: 5000});\n }\n \n }else{\n toastr.error('Internal server error.', 'Error', {timeOut: 5000});\n }\n }\n });\n\n} \n});\n\n}", "function deleteSession() {\n\n swal({\n title: '?אתה בטוח רוצה לצאת מהאתר',\n type: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#3085d6',\n cancelButtonColor: '#d33',\n confirmButtonText: 'כן, תוציא אותי',\n cancelButtonText: 'ביטול',\n confirmButtonClass: 'btn btn-success btn-lg',\n cancelButtonClass: 'btn btn-danger btn-lg',\n buttonsStyling: false\n }).then(function () {\n $.ajax({\n type: 'POST',\n url: endSessionBuyer,\n data: {},\n success: function (response) {\n localStorage.clear();\n window.location.href = \"http://buy-with-friends.com\";\n }\n });\n })\n}", "function deleteAllCompletedTodos() {\n // Write your code here...\n}", "function deleteAllCompletedTodos() {\n // Write your code here...\n}", "function deleteAllCompletedTodos() {\n // Write your code here...\n}", "function deleteWishlistItem(id) {\n // alert(id);\n\n var wishlist = JSON.parse(localStorage.getItem('wishlistObj'));\n wishlist.splice(id, 1);\n localStorage.setItem('wishlistObj',JSON.stringify(wishlist)); \n console.log(JSON.parse(localStorage.getItem('wishlistObj')));\n\n Swal.fire({\n title: \"<i>SUCCESS</i>\", \n html: \"item successfully removed from the <b>WISHLIST</b>\", \n confirmButtonText: \"<u>close</u>\", \n });\n\n}" ]
[ "0.6923511", "0.6760819", "0.6533076", "0.65206444", "0.6511105", "0.6489903", "0.6449423", "0.6402988", "0.6351242", "0.6327346", "0.63090575", "0.62964463", "0.62917703", "0.6267454", "0.6261281", "0.6260393", "0.6259438", "0.6249951", "0.62380636", "0.62273246", "0.6222594", "0.62101537", "0.62064946", "0.6189411", "0.61868924", "0.6183827", "0.6179959", "0.6179959", "0.6179959", "0.6170409" ]
0.8119842
0
This function is to remove a data source
static async removeDataSource(email, dataSourceID) { return new Promise((resolve, reject) => { Database.sendQuery('DELETE FROM datasource WHERE ( email = $1) AND ( ID = $2);', [email, dataSourceID]) .then((result) => resolve(result.rows)) .catch((result) => reject(result)); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "removeSource(source) {\n const sourceIdx = this._sources.findIndex((s) => s === source);\n if (sourceIdx > -1) {\n arrayRemoveAt(this._sources, sourceIdx);\n source.dispose();\n }\n }", "function deleteSource(oid)\n{\n $.parse.delete('sources/' + oid, function(json){\n $(\"[oid='\" + oid + \"']\").parent(\".source\").remove();\n });\n}", "function deleteDynamicSource(sourceName, bindingName)\r\n{\r\n var siteURL = dw.getSiteRoot();\r\n \r\n if (siteURL.length)\r\n {\r\n //For localized object name\r\n if (sourceName != \"URL\")\r\n {\r\n sourceName = \"URL\";\r\n }\r\n\r\n dwscripts.deleteListValueFromNote(siteURL, sourceName, bindingName);\r\n }\r\n}", "switchDataSource(dataSource) {\n // tslint:disable-next-line:no-unbound-method\n if (this._dataSource && typeof this._dataSource.disconnect === 'function') {\n this.dataSource.disconnect(this);\n }\n if (this.dataSubscription) {\n this.dataSubscription.unsubscribe();\n this.dataSubscription = null;\n }\n // Remove the all dataNodes if there is now no data source\n if (!dataSource) {\n this.nodeOutlet.viewContainer.clear();\n }\n this._dataSource = dataSource;\n if (this.nodeDefs) {\n this.observeRenderChanges();\n }\n }", "removeSources(contents) {}", "removeSource(id){\n this.map.getStyle().layers.forEach((layer)=>{\n if (layer.source === id) {\n this.map.removeLayer(layer.id);\n }\n });\n this.map.removeSource(id);\n }", "reset_graphs() {\n d3.selectAll(\".sourcegraph-container\").remove()\n }", "on_desklet_removed() {\n Mainloop.source_remove(this.updateID);\n }", "delete () {\n Api.delete(null, ApiUrls.sources, this.id);\n }", "function removeData(chart, timeline) {\n chart.data.datasets[0].data = data_traffic_chart[timeline];\n chart.update();\n}", "removeUselessSourceButtons() {\n this.$groupButtons.each((_, button) => {\n if (!this.connectsToCollection($(button).data('source'))) {\n $(button).remove();\n }\n });\n }", "function removeData(graph) {\n //Clears all datasets\n graph.data.datasets = [];\n\n //Updates the chart to display to changes\n graph.update();\n}", "function removeSourceAndLayer(name) {\n if (map.getLayer(name)) {\n map.removeLayer(name);\n }\n if (map.getSource(name)) {\n map.removeSource(name);\n }\n }", "_switchDataSource(dataSource) {\n this._data = [];\n if (Object(_angular_cdk_collections__WEBPACK_IMPORTED_MODULE_2__[\"isDataSource\"])(this.dataSource)) {\n this.dataSource.disconnect(this);\n }\n // Stop listening for data from the previous data source.\n if (this._renderChangeSubscription) {\n this._renderChangeSubscription.unsubscribe();\n this._renderChangeSubscription = null;\n }\n if (!dataSource) {\n if (this._dataDiffer) {\n this._dataDiffer.diff([]);\n }\n this._rowOutlet.viewContainer.clear();\n }\n this._dataSource = dataSource;\n }", "remove() {\n //remove handlers of any atomic data defined here\n const {source, handler} = this.events;\n source.remove();\n //reset `this.events` \n this.events = {};\n }", "remove() {\n //remove handlers of any atomic data defined here\n const {source, handler} = this.events;\n source.remove();\n //reset `this.events` \n this.events = {};\n }", "function cleanUp()\n{\n if ($(\"#dataWindow\").length)\n $(\"#dataWindow\").remove();\n}", "function removeOldChart() {\n var oldChart = document.getElementById('DB')\n if (oldChart != undefined) {\n var parent = oldChart.parentNode\n parent.removeChild(oldChart)\n }\n\n}", "function destoryDataTable(){\r\n\toTable.fnDestroy();\t\t\r\n\t// destroy doesn't really work. This next line removes extra html that gets inserted when the datatable\r\n\t// is initialized multiple times.\r\n\t$('#list table tr th').each(function(){\r\n\t\t$(this).html($(this).children('div').html());\r\n\t});\t\r\n}", "function deleteSource(id){\n var i;\n for(i = 0; i < sources.length; i++){\n if(sources[i].id == id){\n if(sources.length == 1){\n document.getElementById(\"input\").innerHTML = sourceDataChangeForm();\n document.getElementById(\"meiOutput\").value = createMEIOutput();\n createSVGOutput();\n return;\n }\n else if(i != 0){\n currentSID = sources[i - 1].id;\n currentSource = sources[i - 1];\n }\n else{\n currentSID = sources[i + 1].id;\n currentSource = sources[i + 1];\n }\n sources.splice(i, 1);\n }\n }\n for(i = 0; i < syllables.length; i++){\n for(var j = 0; j < syllables[i].neumes.length; j++){\n if(Array.isArray(syllables[i].neumes[j])){\n for(var k = 0; k < syllables[i].neumes[j].length; k++){\n if(syllables[i].neumes[j][k].sourceID == id){\n syllables[i].neumes[j].splice(k, 1);\n }\n }\n }\n else{\n for(var l = 0; l < syllables[i].neumes[j].pitches.length; l++){\n if(Array.isArray(syllables[i].neumes[j].pitches[l])){\n for(var k = 0; k < syllables[i].neumes[j].pitches[l].length; k++){\n if(syllables[i].neumes[j].pitches[l][k].sourceID == id){\n syllables[i].neumes[j].pitches[l].splice(k, 1);\n }\n }\n }\n }\n }\n }\n }\n document.getElementById(\"input\").innerHTML = sourceDataChangeForm();\n document.getElementById(\"meiOutput\").value = createMEIOutput();\n createSVGOutput();\n}", "function remove(){\n const index = this.parentNode.dataset.index;\n myLibrary.splice(index, 1);\n \n refresh();\n}", "removeFromLayers(){\n if (this.map.getSource(window.SRC_FROM_POLYGONS)) this.removeSource(window.SRC_FROM_POLYGONS);\n if (this.map.getSource(window.SRC_FROM_POINTS)) this.removeSource(window.SRC_FROM_POINTS);\n }", "_removeCallback() {\n this._renderCallback()\n this._viewer.dcContainer.removeChild(this._delegate)\n this._state = DC.LayerState.REMOVED\n }", "function clearDataDisplay() {\n body.removeChild(data_display);\n}", "_onAfterRemovingElement() {\n this.setState({\n rowToDelete : null,\n dataSource : this.state.dataSource.cloneWithRows(this._data)\n });\n }", "function onDragEnd(e) {\n\n //clearing the source\n sourceParent = \"\";\n sourceIndex = -1;\n }", "function stopSources() {\n for (var i = 0; i < SOURCES.length; i++) {\n var source = SOURCES[i];\n source.noteOff(0);\n }\n SOURCES = [];\n}", "function remove_point(vectorSource){\n vectorSource.clear();\n}", "delete() {\n const source = internal(this).source;\n const model = internal(source).model;\n internal(model).connections.remove(this);\n }", "function clickedDelete()\n{\n\tvar selectedObj = dw.databasePalette.getSelectedNode();\n\tif (selectedObj && selectedObj.objectType==\"Connection\")\n\t{\n\t\tvar connRec = MMDB.getConnection(selectedObj.name);\n\t\tif (connRec) \n\t\t{\n\t\t\tif( MMDB.deleteConnection(selectedObj.name) )\n\t\t\t{\n\t\t\t if (isDisplayingColdfusionConnections())\n\t\t\t {\n\t\t\t \tdeleteDSN(selectedObj.name);\n\t\t\t }\n\t\t\t clickedRefresh();\n\t\t\t}\n\t\t}\n\t}\n}" ]
[ "0.6923161", "0.63919204", "0.62256336", "0.62021405", "0.6170509", "0.6117001", "0.607311", "0.60380137", "0.6021545", "0.6016487", "0.5956192", "0.5955829", "0.5945504", "0.59348667", "0.5897498", "0.5897498", "0.5660677", "0.5658116", "0.5651361", "0.5644043", "0.5628527", "0.5621928", "0.56195885", "0.56168836", "0.5586174", "0.5545699", "0.5535544", "0.5532098", "0.55301255", "0.5513058" ]
0.647706
1
This function removes a dashboard.
static async removeDashboard(email, dashboardID) { return new Promise((resolve, reject) => { Database.sendQuery('DELETE FROM Dashboard WHERE ( email = $1 ) AND ( ID = $2);', [email, dashboardID]) .then((result) => resolve(result.rows)) .catch((result) => reject(result)); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function clearDashboard() {\n \n while (dashboard.firstChild) {\n dashboard.removeChild(dashboard.firstChild);\n }\n}", "function deleteCreation(id){\n $(\"#currentCreation\").remove();\n $(\"#making\").slideUp(\"slow\");\n var widget=GetWidget(id);\n var idPanel= widget.panel;\n var panel=GetPanel(idPanel) \n panel.deleteElement(widget)\n}", "function dashboard_clear() {\n d3.select(\"#dashboard\").selectAll(\"svg\").remove();\n}", "function deleteNewDashboardMonitor2(idx) {\n ctrl.newDashboardMonitor2es.splice(idx, 1);\n }", "function deleteDashboardMonitor2(idx) {\n deletedDashboardStatuses.push(\n ctrl.dashboardMonitor2es.splice(idx, 1)[0]\n );\n }", "function hide() {\n\t\tdashboardContent.empty();\n\n\t}", "removePanel(id) {\n // remove from dom\n this.getPropertyValue(id, '$panel').remove();\n const temp = this.service.panels.filter((panel) => !panel[id]);\n this.service.panels.splice(0, this.service.panels.length, ...temp);\n }", "function deleteSWinBoard(id) {\n $(\".swimlane[data-id='\" + id + \"']\").remove();\n $(\"#kanban th[data-id='\" + id + \"']\").remove();\n $(\"#kanban td[data-id='\" + id + \"']\").remove();\n recalibrate();\n $(\".window-content\").perfectScrollbar(\"update\");\n}", "function deleteLoginArea(){\n removeLoginArea();\n}", "remove_widget(widget_id) {\n delete this.data[widget_id];\n }", "function deleteBoard(){\n\tif(grid != null){\n \t\tdocument.body.removeChild(grid);\n \t}\n}", "static async removeGraph(email, dashboardID, graphID) {\n\t\tlet query = 'DELETE FROM Graph as g WHERE (g.dashboardid in ( SELECT d.id from dashboard as d WHERE (d.email = $1) AND (d.id = $2))) AND (g.ID = $3);';\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tDatabase.sendQuery(query, [email, dashboardID, graphID])\n\t\t\t\t.then((result) => resolve(result.rows))\n\t\t\t\t.catch((result) => reject(result));\n\t\t});\n\t}", "destroy() {\n this.panel.remove();\n }", "function removeWidget(widget) {\r\n storage.get(\"tiles\", function(storage_data) {\r\n var widgets = storage_data.tiles;\r\n\r\n delete widgets[widget];\r\n\r\n storage.set({\"tiles\": widgets})\r\n });\r\n}", "function emptyDashboard(){\n $(\"#dashboard_tab .value_td span\",main_tabs_context).html(spinner);\n}", "function emptyDashboard(){\n $(\"#dashboard_tab .value_td span\",main_tabs_context).html(spinner);\n}", "function removeDiv() {\n $('.whiteOverlay').remove();\n}", "function removePanel(panel) {\n\t // remove from grister 'silently' (don't reorganize after)\n\t gridster.remove_widget(panel.$el);\n\n\t // destroy the scope\n\t panel.$scope.$destroy();\n\n\t panel.$el.removeData('panel');\n\t panel.$el.removeData('$scope');\n\t }", "function dashboardClicked() {\n $(\".container-fluid\").find('main')\n .load(\"dashboard.html\").find('');\n}", "function removeit(){\n\n removeData.remove();\n\n window.location.replace(\"index.html\");\n\n}", "function removeTab(data){\n var header = $(data).closest(\"li\");\n var index = $(\"#chat-area ul li\").index(header);\n $(\"#chat-area\").tabs(\"remove\", index);\n $(\"#chat-area\").tabs( \"refresh\" );\n}", "function deleteIt(){\n \tupdateDB(\"delete\", pageElements.alertText.dataset.id);\n }", "function deleteEntry(ENTRY){\n ENTRY_LIST.splice(ENTRY.id,1)\n updateUI()\n}", "function deleteListPanel() {\n var listPlayerPanel = document.getElementById(\"current-player-panel\");\n while (listPlayerPanel.hasChildNodes()) {\n listPlayerPanel.removeChild(listPlayerPanel.firstChild);\n }\n}", "function deletePlane(elem) {\n elem.remove();\n}", "function removeUser(offline) {\n if($(\"#online_\" + offline.id).length) {\n $(\"#online_\" + offline.id).remove();\n }\n}", "function handleDeleteActivity(event){\n let activityId = event.target.id\n event.target.parentElement.remove()\n deleteActivity(activityId)\n // activitiesDiv.remove()\n // console.log(activityCard)\n // activityCard.remove()\n}", "function removeWall() {\n\tvar i= planComponents.walls.indexOf(wallSelected);\n\t\n\tif (i!=-1)\n\t\tplanComponents.walls.splice(i,1);\n\t\n\treturn 1;\n}", "removeLink(index) {\n let list = this.state.card;\n let db = this.state.data;\n list.splice(index, 1);\n db.splice(index, 1);\n // remove card in local storage\n localStorage.clear();\n db.forEach(function(elem, index) {\n localStorage.setItem(index, elem);\n });\n \n this.setState({ list, db });\n\n if (!this.state.card.length) {\n document.querySelector('.dashboard').style.height = '100vh';\n }\n }", "function removeClimb() {\n fetch(`${url}`, {\n method: 'DELETE'\n }).then(res => res.json()).then((results) => alert(`Deleted Climb: ${results.confirmation._id}`))\n\n history.goBack()\n }" ]
[ "0.7051651", "0.6123528", "0.6077937", "0.5962638", "0.5910711", "0.5885954", "0.5751077", "0.57187843", "0.56767976", "0.5627682", "0.56218934", "0.5583366", "0.5539705", "0.5539109", "0.5530348", "0.5530348", "0.5527614", "0.55030346", "0.5488734", "0.5474143", "0.5470423", "0.54630035", "0.5456363", "0.54410166", "0.5433523", "0.54250664", "0.54194885", "0.5405848", "0.539982", "0.5397897" ]
0.74165434
0
This function is used to add a graph to a dashboard.
static async addGraph(email, dashboardID, title, options, metadata) { let query = 'INSERT INTO GRAPH as g (dashboardid, title, metadata, options) (SELECT $1,$2,$3,$4 WHERE EXISTS (SELECT $5 FROM dashboard AS d WHERE (d.email = $5) AND (d.ID = $1)) ) RETURNING g.*'; return new Promise((resolve, reject) => { Database.sendQuery(query, [dashboardID, title, JSON.stringify(metadata), JSON.stringify(options), email]) .then((result) => { // console.log(result); if (result.rows.length > 0) resolve(result.rows[0]); else reject(result); }) .catch((result) => reject(result)); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addToGraphs() {\n if (data.getNumberOfRows() >= 5) {\n\t\tdata.removeRow(0);\n\t\tdataViaAjax();\n\t\tdrawChart();\n\t }\n\t }", "function updateDashboard() {\n setGraph1();\n setGraph2();\n setGraph3();\n}", "function createGraph()\n\t{\n\t\tgraph = that.add('graph', {\n\t\t\tw: that.size,\n\t\t\th: that.size,\n\t\t\tinputCount: that.inputCount,\n\t\t\teq: [{eq:that.eq.eq, color: style.eqColor}],\n\t\t\txRange: that.axis.x,\n\t\t\tyRange: that.axis.y,\n\t\t\tlabelSkip: that.axis.skip,\n\t\t\tusePiLabels: that.axis.usePiLabels\n\t\t}, {\n\t\t\ttop: that.id + ' top ' + style.margin,\n\t\t\tleft: that.id + ' left ' + style.margin\n\t\t});\n\t}", "function makegraph() {\n\tchart = new CanvasJS.Chart(\"graphDiv\", {\n\t\taxisX: {\n\t\t\ttitle: _(\"Cycle number\"),\n\t\t\t/** x axis label */\n\t\t\ttitleFontSize: 22,\n\t\t\t/** Chart font size */\n\t\t\tlabelFontSize: 18,\n\t\t\tminimum: 0,\n\t\t\tinterval: 2\n\t\t},\n\t\taxisY: {\n\t\t\ttitle: _(\"Amount of DNA\"),\n\t\t\ttitleFontSize: 22,\n\t\t\tlabelFontSize: 18,\n\t\t\tminimum: 0\n\t\t},\n\t\tshowInLegend: false,\n\t\tdata: [{\n\t\t\tcolor: \"red\",\n\t\t\ttype: \"line\",\n\t\t\tmarkerType: \"circle\",\n\t\t\tlineThickness: 3,\n\t\t\tdataPoints: dataplotArray /** Datapoints to be plot, stored in the array */\n\t\t}]\n\t});\n\tchart.render();\n\tchain_reaction_stage.update();\n}", "function createGraph(graphData) {\n Highcharts.chart('graph', {\n chart: {\n zoomType: 'x',\n type: 'line'\n },\n title: {\n text: graphData.title\n },\n tooltip: {\n valueDecimals: 2\n },\n xAxis: {\n type: 'datetime',\n title: {\n text: graphData.xAxisTitle\n }\n },\n yAxis: {\n type: 'linear',\n title: {\n text: graphData.yAxisTitle\n }\n },\n series: graphData.series,\n exporting: {\n buttons: {\n contextButton: {\n menuItems: ['viewFullscreen', 'separator', 'downloadPNG', 'downloadJPEG', 'downloadSVG']\n }\n }\n }\n });\n }", "function addDataToGraph(theData) {\n const theDataHistorial = theData.historial; //obtener historial del JSON de la tienda\n setGraphData({\n labels: theDataHistorial.map((aName) => aName.fecha), //labels con las fechas de actualización\n datasets: [\n {\n label: \"Quantity of the store\",\n data: theDataHistorial.map((item) => item.cantidadAnterior), //datos con la cantidad anterior en la actualizacion\n fill: false,\n backgroundColor: \"rgb(255, 255, 255)\",\n borderColor: \"#1d2d44\",\n },\n ],\n });\n }", "function attachGraphToPlaceholder (inputObjectWithData) {\n // Build the Graph chart\n if (!inputObjectWithData || !inputObjectWithData.elementId || !inputObjectWithData.graphData) {\n return;\n }\n Highcharts.chart(inputObjectWithData.elementId, inputObjectWithData.graphData);\n }", "function drawGraph(){\n if(graphData.length != 0){\n google.charts.load('current', {'packages':['corechart']});\n google.charts.setOnLoadCallback(drawChart);\n function drawChart() {\n var data = new google.visualization.DataTable();\n data.addColumn('number', 'Steps');\n data.addColumn('number', 'Time taken (in ms)');\n data.addRows(graphData);\n var options = {\n title: 'Algorithm Performance',\n vAxis: { title: \"Time taken (in ms)\" },\n hAxis: { title: \"Number of steps\" },\n legend: { position: 'bottom' }\n };\n var chart = new google.visualization.LineChart(document.getElementById('algograph'));\n chart.draw(data, options);\n }\n }\n}", "async _showChart(node, parentId, typeChart, isFromEdge = false, secondNode = null, isFromCluster = false, isFromHC = false, newQuery = null) {\n let title, chartNode, viewChild, link, convertData;\n var parentPosition = await this.getPosition();\n var childId = \"chart-\" + state.indexChart;\n let _viewChild = select(this._dashboard.shadowRoot.querySelector(\".graph\")).append(\"mge-view\")\n .attr(\"x\", parentPosition.x + 30)\n .attr(\"y\", parentPosition.y + 30)\n .attr(\"dataset-name\", \"data-\" + state.indexQueryData)\n .attr(\"type-vis\", typeChart)\n .attr(\"id-view\", childId);\n chartNode = await _viewChild.node().getChart();\n await chartNode.setData(node, state._data[this.datasetName], secondNode, isFromEdge, isFromCluster, isFromHC);\n convertData = await chartNode.setData();\n viewChild = _viewChild.node();\n if (newQuery)\n title = newQuery.name;\n else\n title = await this.generateTitle(node, convertData, typeChart, parentId, isFromEdge, secondNode, isFromCluster, isFromHC);\n await viewChild.setTitle(title);\n link = await this._dashboard._addLink(this.element, viewChild);\n await this._dashboard.addChart(parentId, {\n id: childId, title: title, typeChart: viewChild.typeVis, hidden: false,\n x: viewChild.x, y: viewChild.y, view: viewChild, link: link\n });\n await this._dashboard.refreshLinks();\n if (typeChart == state.typeChart.histogram) {\n if (node.cluster) {\n alert(\"Not implemented!!\");\n return;\n }\n }\n return _viewChild;\n }", "function loaded(){\n graph([]);\n pieChart([],[],[],[]);\n}", "function drawGraph () {\n var model = modelConnect();\n var drawGraphAPI = \"showData(\\\"Sample Data\\\",[{name:\\\"A Chart\\\",type: \\\"chart\\\",xLabel: \\\"Chart x-axis\\\",yLable: \\\"Chart y-axis\\\",Legend: \\\"top\\\",horizontalGrid: true, verticalGrid: true,xType:\\\"Numeric\\\",xData: [1,2,3,4,5], data:[{data: [1,4,9,16,25],type:\\\"line\\\",name:\\\"Energy\\\",},{data: [1,2,3,4,5],type:\\\"line\\\", name:\\\"Cost\\\"}] }])\";\n model.postMessage(drawGraphAPI,\"*\");\n}", "function updateChart(_graph) {\r\n\r\n\t\t//get the name and dashboard and plot data, \r\n\t\t//the chart id matches the dashboard_graphname key\r\n\t\t//as it is created in this way in the template\r\n\t\t//for now, just alert the data\r\n\t\t//alert(\"you updated the graph, it is: \"+ JSON.stringify(graph));\r\n\t\tvar graph = JSON.parse(_graph)\r\n\t\tvar containerID = \"\"+graph.dashboard +\"_\"+graph.name;\r\n\r\n\t\t//var test = false; \r\n\t\t//alert(\"xplot: \"+graph.xplot)\t\r\n\t\t///alert(\"yplot: \"+graph.yplot)\r\n\t\t//create the chart\r\n\t\t\r\n\t\t//alert(\"updateChart container id for set up: \" + containerID)\r\n\t\t//alert(graph.graph)\r\n\t\t//containerID, type, xTitle, yTitle, startDate, endDate, source\r\n\t\t//var chart = setUpChart(containerID, graph.graph.toString(), graph.startDate, graph.endDate, \"Webtrends\")\r\n\t\tvar chart = setUpChart(containerID, graph.graph.toString())\r\n\r\n\t\r\n\t\t//Fill in the data into the chart\r\n\t\t\r\n\t\t/*\r\n\t\t\r\n\t\t//update management Chart\r\n\t\t//if(!test){\r\n\t var jqueryAdress = \"#\"+containerID;\r\n\t\t\r\n\t\t//var chart=$(containerID).highcharts();\r\n\t\t\r\n\t\t//var chart=$(jqueryAdress).highcharts();\r\n\t\t\r\n\t\t\r\n\t\t//} else {\t\r\n\t\t\t//update chart 1\r\n\t\t//var chart=$(\"#containerChAnalyticsGraph1\").highcharts();\r\n\t\t//}\r\n\t\t//alert(\"id 1: \"+containerID)\r\n\t\t//alert(\"data in update chart \"+JSON.stringify(graph))\r\n\t\t//var gr = JSON.stringify(graph)\r\n\t\t//var _containerID = \"#\"+gr.dashboard+\"_\"+gr.selectedName;\r\n\t\t//alert(\"chart \"+chart.type)\r\n\t\t//alert(\"chart type \"+chart.type)\r\n\t\t//var integerArray = [ JSON.parse(data).yAxis ];*/\r\n\t\ttry{\r\n\t\t\tvar str = graph.yplot.toString();\r\n\t\t\t//alert(\"y in update \"+str)\r\n\t\t\tvar _res = str.split(\",\");\r\n\t\t\tvar res = [];\r\n\t\t\t//alert(\"res1: \"+res)\r\n\t\t\t//alert(\"str.split 1 \"+str);\t\r\n\t\t\t//alert(\"iArray1: \"+integerArray);\t\t\t\r\n\t\t\tfor( var i = 0; i < _res.length; i++ ) {\r\n\t\t\t\tres.push(parseInt( _res[i], 10 ));\r\n\t\t\t}\r\n\t\t\t//alert(\"after split: \"+res);\t\t\t\r\n\t\t\t//http://jsfiddle.net/4tuvC/\r\n\t\t\t//chart.xAxis[0].setCategories(data[0]);\r\n\t\t\t//chart[0].xAxis[0].update(data[\"xAxis\"], true);\r\n\t\t\t\r\n\t\t\t//chart.series[0].setData( res ,true);\r\n\t\t\t\t\t\r\n\t\t\tchart.addSeries({\r\n\t data: res\r\n\t })\r\n\t\t\t\r\n\t\t\t/*\r\n\t\t\t////////////////////////////////////////////////////////\r\n\t\t\t//plot labels\r\n\t\t\t////////////////////////////////////////////////////////\r\n\t\t\t//var stringArray = [ JSON.parse(data).xAxis ];\r\n\t\t\tstr = graph.xplot.toString()\r\n\t\t\t//str = JSON.parse(graph).xplot.toString();\r\n\t\t\t//alert(\"xplot in try: \" + str)\r\n\t\t\tvar _res = str.split(\",\");\r\n\t\t\t//alert(\"str.split: 2\" + _res)\r\n\t\t\t/*alert(\"res1: \"+res)*/\t\t\r\n\t\t\t//http://jsfiddle.net/4tuvC/\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t//chart.xAxis[0].setCategories(_res);\r\n\t\t\t//chart[0].xAxis[0].update(res, true);\r\n\t\t\t\r\n\t\t} catch (e){\r\n\t\t\t//alert(\"made a mistake\")\r\n\t\t}\r\n}", "addDataVisuals () {\n }", "async function updateDashboardPlots() {\r\n\tawait createDashboardPlot();\r\n}", "function show_graph(graph_config, graph_div) {\n var graph_type = graph_config.graph_type || \"ColumnChart\";\n if(graph_type === 'Table') {\n var data = new google.visualization.DataTable(graph_config.data);\n data = new google.visualization.DataView(data);\n if(graph_config.view) {\n data.setColumns(graph_config.view);\n }\n }\n else {\n var data = new google.visualization.arrayToDataTable(graph_config.data);\n }\n var chart = new google.visualization[graph_type](document.getElementById(graph_div));\n chart.draw(data, graph_config.options);\n \n }", "static setNewGraph(graphData = null) {\n exports.graph = new GraphCustom(graphData);\n }", "function GraphNewCtrl(Graph, $scope, $location) {\r\n $scope.$emit('updatePath', '/graphs/');\r\n $scope.$emit('updateMenu', 'graphs');\r\n var graph = Graph.get();\r\n $scope.graph = graph;\r\n\r\n $scope.save = function (graph) {\r\n graph.$create();\r\n $location.path('/graphs/');\r\n };\r\n\r\n\r\n}", "function push(chart) {\n charts.push(chart);\n }", "function graphCreate(id) {\n ctx = document.getElementById(id).getContext(\"2d\");\n myLine = new Chart(ctx)\n myLineChart = myLine.Line(producersIds[id].data, {\n tooltipTemplate: \"<%if (label){%><%=label%>: <%}%><%= value %>kb\",\n });\n producersIds[id].canvas = ctx;\n producersIds[id].myLine = myLine;\n producersIds[id].myLineChart = myLineChart;\n\n}", "function addGraphTabs() {\n const graphContainer = document.getElementById(\"graphs-container\");\n const graphListTarget = document.querySelector(\"#graph-btn\");\n\n // Add buttons to display graphs\n graphContainer.childNodes.forEach(element => {\n if (element.nodeType !== Node.TEXT_NODE) {\n const button = document.createElement(\"button\");\n button.classList.add(\"btn\", \"btn-sm\", \"btn-outline-secondary\");\n button.textContent = element.dataset.graphName;\n graphListTarget.appendChild(button);\n\n button.addEventListener(\"click\", (e) => {\n document.querySelectorAll(\"#graph-btn button\").forEach((otherBtn) => {\n otherBtn.classList.remove('active');\n });\n e.target.classList.add('active');\n document.querySelectorAll(\".graph-display\").forEach((otherGraph) => {\n otherGraph.classList.add(\"hidden\");\n });\n\n element.classList.remove(\"hidden\");\n });\n }\n });\n\n document.querySelector(\"#graph-btn button\").classList.add('active');\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'X');\n data.addColumn('number', 'Price');\n \n data.addRows(graphData)\n\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.LineChart(document.getElementById('chart_div'));\n chart.draw(data, fullWidthOptions);\n }", "function make_graph() {\n $.get(\"/user_progress_analytics\",function (data, status) {\n let pc = document.getElementById('progressBarGraph').getContext('2d');\n let myChart = new Chart(pc, {\n type: 'bar',\n data: {\n labels: [\"Completed\", \"Uncompleted\"],\n datasets: [{\n label: '# of Tasks',\n data: data,\n backgroundColor: [\n 'rgba(75, 192, 192, 0.2)', // GREEN\n 'rgba(255, 99, 132, 0.2)', // RED\n\n // 'rgba(54, 162, 235, 0.2)', // BLUE\n // 'rgba(255, 206, 86, 0.2)', // YELLOW\n // 'rgba(153, 102, 255, 0.2)', // PURPLE\n // 'rgba(255, 159, 64, 0.2)' // Orange\n ],\n borderColor: [\n 'rgba(75, 192, 192, 1)',\n 'rgba(255,99,132,1)',\n //\n // 'rgba(54, 162, 235, 1)',\n // 'rgba(255, 206, 86, 1)',\n // 'rgba(153, 102, 255, 1)',\n // 'rgba(255, 159, 64, 1)'\n ],\n borderWidth: 1\n }]\n },\n options: {\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero:true\n }\n }]\n },\n title: {\n display: true,\n text: 'Overall Project Progress Based On Tasks Completed To Tasks Uncompleted'\n }\n }\n });\n });\n}", "function showGraph() {\n if ($('.about-graph').length !== 0) {\n var aboutGraph = new Graph('.about-graph', '/js/graph-data', {\n clickActiveElements: []\n });\n\n $('#aboutGraph').on('click', function() {\n if (!$(this).hasClass('active')) {\n aboutGraph.update('/js/graph-data', {\n removeElements: [],\n clickActiveElements: []\n });\n\n $('.about-graph-buttons a').each(function() {\n if ($(this).hasClass('active')) {\n $(this).removeClass('active');\n }\n\n if ($(this).hasClass('skills')) {\n $(this).addClass('active');\n }\n });\n }\n\n $(this).toggleClass('active');\n $('.about-toggle-button').toggleClass('active');\n\n $('.hideaway-content').slideToggle('middle');\n\n $('.showing-content').slideToggle('middle');\n });\n\n $('.about-graph-buttons a.skills').on('click', function () {\n aboutGraph.update('/js/graph-data', {\n removeElements: [],\n clickActiveElements: []\n });\n });\n\n $('.about-graph-buttons a.education').on('click', function () {\n aboutGraph.update('/js/second-graph-data', {\n removeElements: [\n 'xAxis',\n 'pathArea',\n 'yAxis',\n 'tooltips'\n ],\n extendedTooltip: true\n });\n });\n\n $('.about-graph-buttons a').on('click', function() {\n $('.about-graph-buttons a').removeClass('active');\n $(this).addClass('active');\n });\n\n\n addWidth();\n\n $window.resize(function () {\n addWidth();\n });\n }\n /**\n * Function to add width to graph parent container when window width less than 767px.\n */\n function addWidth() {\n if (window.innerWidth <= 767) {\n $('.about-graph').width(window.innerWidth - 100);\n } else {\n $('.about-graph').removeAttr('style');\n }\n }\n }", "function showGraph() {\n if ($('.about-graph').length !== 0) {\n var aboutGraph = new Graph('.about-graph', '/js/graph-data', {\n clickActiveElements: []\n });\n\n $('#aboutGraph').on('click', function() {\n if (!$(this).hasClass('active')) {\n aboutGraph.update('/js/graph-data', {\n removeElements: [],\n clickActiveElements: []\n });\n\n $('.about-graph-buttons a').each(function() {\n if ($(this).hasClass('active')) {\n $(this).removeClass('active');\n }\n\n if ($(this).hasClass('skills')) {\n $(this).addClass('active');\n }\n });\n }\n\n $(this).toggleClass('active');\n $('.about-toggle-button').toggleClass('active');\n\n $('.hideaway-content').slideToggle('middle');\n\n $('.showing-content').slideToggle('middle');\n });\n\n $('.about-graph-buttons a.skills').on('click', function () {\n aboutGraph.update('/js/graph-data', {\n removeElements: [],\n clickActiveElements: []\n });\n });\n\n $('.about-graph-buttons a.education').on('click', function () {\n aboutGraph.update('/js/second-graph-data', {\n removeElements: [\n 'xAxis',\n 'pathArea',\n 'yAxis',\n 'tooltips'\n ],\n extendedTooltip: true\n });\n });\n\n $('.about-graph-buttons a').on('click', function() {\n $('.about-graph-buttons a').removeClass('active');\n $(this).addClass('active');\n });\n\n\n addWidth();\n\n $window.resize(function () {\n addWidth();\n });\n }\n /**\n * Function to add width to graph parent container when window width less than 767px.\n */\n function addWidth() {\n if (window.innerWidth <= 767) {\n $('.about-graph').width(window.innerWidth - 100);\n } else {\n $('.about-graph').removeAttr('style');\n }\n }\n }", "function setGraph() {\r\n\tchartBusyProc();\r\n\tvar lyrId = $(\"#chartLayer\").val();\r\n\t// console.log(lyrId);\r\n\tif (lyrId == 'x') {\r\n\t\tif (typeof chartFun == 'undefined') {\r\n\t\t\t// chartBusyDone();\r\n\t\t\tchartError('Selection required to display graph');\r\n\t\t}\r\n\t\teval(chartFun+'(\"'+ newUrl+'\")');\r\n\t} else { /// assuming wms layer\r\n\t\tvar lyr = map.getLayer(lyrId);\r\n\t\tif (typeof markers == 'undefined') {\r\n\t\t\t// chartBusyDone();\r\n\t\t\tchartError(\"A location on the map needs to be selected.\");\r\n\t\t} else {\r\n\t\t\tWMSFeatInfo(lyr);\r\n\t\t} \r\n\t}\r\n}", "drawGraph() {\n logger.debug('ParticipantScore: drawGraph', this.props.graphType);\n const chart = this.chart;\n\n const timelineData = this.props.graphDatasets[GraphDatasetTypes.UTTERANCE_TIMELINE].data;\n logger.debug('ParticipantScore: timelineData', { timelineData });\n\n // Is this component trying to visualise an empty dataset?\n const emptyDataset = timelineData.utts.length === 0;\n if (emptyDataset) {\n chart.hide();\n this.props.dashboardGraphLoaded(this.props.graphType);\n return;\n }\n chart.show();\n\n const chartData = this.getGraphData();\n chart.data = chartData;\n }", "function createDashboard(data, labelsParam, from, to, ajaxUrlParam) {\n labels = labelsParam;\n ajaxUrl = ajaxUrlParam;\n if (data[0] == undefined) {\n //No data to show, so just stop here\n $(\"detailDataContainer\").show();\n return;\n }\n board = new DcDashboard();\n // Set dashboard width same as div width\n // var width = $(\".dashboardContainer\").css(\"width\").replace(\"px\", \"\");\n // board.setDashboardWidth(+width);\n charts = new Object();\n var dataCounts = getDataCounts(data);\n showUniqueValues(dataCounts, data, labels);\n\n // BROWSER FILTER\n var browser = board.allData.dimension(function (d) {\n return \"\" + d['browser'];\n });\n var browserGroup = browser.group().reduceSum(function (d) {\n return d['count']\n });\n var browserLabelAccessor = function (d) {\n return labels['browser'] ? labels['browser'][d.key] : d.key;\n };\n var browserPie = board.addPieChart('dcChart', 'browser-chart', browser, browserGroup, browserLabelAccessor);\n\n browserPie.title(function (d) {\n var label = labels['browser'] ? labels['browser'][d.key] : d.key;\n return label + \": \" + d.value;\n });\n charts[\"browser-chart\"] = browserPie;\n\n // MEDIATYPE FILTER\n var mediaType = board.allData.dimension(function (d) {\n return \"\" + d['mediaType'];\n });\n var mediaTypeGroup = mediaType.group().reduceSum(function (d) {\n return d['count']\n });\n var mediaTypeLabelAccessor = function (d) {\n return d.key\n };\n charts[\"mediaType-chart\"] = board.addPieChart('dcChart', 'mediaType-chart', mediaType, mediaTypeGroup, mediaTypeLabelAccessor);\n\n // SUBTYPE FILTER\n var subtype = board.allData.dimension(function (d) {\n return \"\" + d['subtype'];\n });\n var subtypeGroup = subtype.group().reduceSum(function (d) {\n return d['count'];\n });\n var subtypeLabelAccessor = function (d) {\n return d.key\n };\n charts[\"subtype-chart\"] = board.addPieChart('dcChart', 'subtype-chart', subtype, subtypeGroup, subtypeLabelAccessor);\n\n // PAGE FILTER\n var page = board.allData.dimension(function (d) {\n return \"\" + d['page'];\n });\n var pageGroup = page.group().reduceSum(function (d) {\n return d['count'];\n });\n var pageLabelAccessor = function (d) {\n return labels['page'] ? labels['page'][d.key] : d.key\n };\n var pagePie = board.addPieChart('dcChart', 'page-chart', page, pageGroup, pageLabelAccessor);\n pagePie.title(function (d) {\n var label = labels['page'] ? labels['page'][d.key] : d.key;\n return label + \": \" + d.value;\n });\n charts[\"page-chart\"] = pagePie;\n\n //JOBGROUP FILTER\n var jobGroup = board.allData.dimension(function (d) {\n return \"\" + d['jobGroup']\n });\n var jobGroupGroup = jobGroup.group().reduceSum(function (d) {\n return d['count'];\n });\n var jobGroupLabelAccessor = function (d) {\n if (d.key < 0) {\n return \"undefined\"\n }\n return labels['jobGroup'] ? labels['jobGroup'][d.key] : \"\" + d.key\n };\n var jobGroupPie = board.addPieChart('dcChart', 'jobGroup-chart', jobGroup, jobGroupGroup, jobGroupLabelAccessor);\n jobGroupPie.title(function (d) {\n var label = labels['jobGroup'] ? labels['jobGroup'][d.key] : d.key;\n return label + \": \" + d.value;\n });\n charts[\"jobGroup-chart\"] = jobGroupPie;\n\n // MEASURED EVENT FILTER\n var measuredEvent = board.allData.dimension(function (d) {\n return \"\" + d['measuredEvent'];\n });\n var measuredEventGroup = measuredEvent.group().reduceSum(function (d) {\n return d['count'];\n });\n var measuredEventLabelAccessor = function (d) {\n if (d.key < 0) {\n return \"undefined\"\n }\n return labels['measuredEvent'] ? labels['measuredEvent'][d.key] : \"\" + d.key\n };\n var measuredEventPie = board.addPieChart('dcChart', 'measuredEvent-chart', measuredEvent, measuredEventGroup, measuredEventLabelAccessor);\n measuredEventPie.title(function (d) {\n var label = labels['measuredEvent'] ? labels['measuredEvent'][d.key] : d.key;\n return label + \": \" + d.value;\n });\n charts[\"measuredEvent-chart\"] = measuredEventPie;\n\n // HOST FILTER\n if (dataCounts['host'] > 1) {\n var host = board.allData.dimension(function (d) {\n return \"\" + d['host'];\n });\n var hostGroup = host.group().reduceSum(function (d) {\n return d['count'];\n });\n var hostLabelAccessor = function (d) {\n return d.key\n };\n charts[\"host-chart\"] = board.addRowChart('dcChart', 'host-chart', host, hostGroup, dataCounts['host'], hostLabelAccessor);\n }\n\n var loadingIndicatorGlobal = document.getElementById(\"loadingIndicatorGlobal\");\n loadingIndicatorGlobal.style.display = 'none';\n var detailDataContainer = document.getElementById(\"detailDataContainer\");\n detailDataContainer.style.display = 'block';\n\n // Show count of selected data\n board.addDataCount('dcChart', 'dc-data-count');\n\n // ### BEGIN LINE CHARTS\n var date_Dimension = board.allData.dimension(function (d) {\n return d.date;\n });\n\n var loadTime_ttfb_avg = date_Dimension.group().reduce(\n //add\n function (p, v) {\n p.count += v['count'];\n p.loadTimeSum += v['loadTimeMs_avg'] * v['count'];\n p.loadTimeAvg = p.count ? d3.round((p.loadTimeSum / p.count), 2) : 0;\n p.ttfbSum += v['ttfb_avg'] * v['count'];\n p.ttfbAvg = p.count ? d3.round((p.ttfbSum / p.count), 2) : 0;\n p.downloadTimeSum += v['downloadTime_avg'] * v['count'];\n p.downloadTimeAvg = p.count ? d3.round((p.downloadTimeSum / p.count), 2) : 0;\n p.sslTimeSum += v['sslTime_avg'] * v['count'];\n p.sslTimeAvg = p.count ? d3.round((p.sslTimeSum / p.count), 2) : 0;\n p.connectTimeSum += v['connectTime_avg'] * v['count'];\n p.connectTimeAvg = p.count ? d3.round((p.connectTimeSum / p.count), 2) : 0;\n p.dnsTimeSum += v['dnsTime_avg'] * v['count'];\n p.dnsTimeAvg = p.count ? d3.round((p.dnsTimeSum / p.count), 2) : 0;\n p.bytesInSum += v['bytesIn_avg'] * v['count'];\n p.bytesInAvg = p.count ? d3.round((p.bytesInSum / p.count), 2) : 0;\n p.bytesOutSum += v['bytesOut_avg'] * v['count'];\n p.bytesOutAvg = p.count ? d3.round((p.bytesOutSum / p.count), 2) : 0;\n return p;\n },\n //remove\n function (p, v) {\n p.count -= v['count'];\n p.loadTimeSum -= v['loadTimeMs_avg'] * v['count'];\n p.loadTimeAvg = p.count ? d3.round((p.loadTimeSum / p.count), 2) : 0;\n p.ttfbSum -= v['ttfb_avg'] * v['count'];\n p.ttfbAvg = p.count ? d3.round((p.ttfbSum / p.count), 2) : 0;\n p.downloadTimeSum -= v['downloadTime_avg'] * v['count'];\n p.downloadTimeAvg = p.count ? d3.round((p.downloadTimeSum / p.count), 2) : 0;\n p.sslTimeSum -= v['sslTime_avg'] * v['count'];\n p.sslTimeAvg = p.count ? d3.round((p.sslTimeSum / p.count), 2) : 0;\n p.connectTimeSum -= v['connectTime_avg'] * v['count'];\n p.connectTimeAvg = p.count ? d3.round((p.connectTimeSum / p.count), 2) : 0;\n p.dnsTimeSum -= v['dnsTime_avg'] * v['count'];\n p.dnsTimeAvg = p.count ? d3.round((p.dnsTimeSum / p.count), 2) : 0;\n p.bytesInSum -= v['bytesIn_avg'] * v['count'];\n p.bytesInAvg = p.count ? d3.round((p.bytesInSum / p.count), 2) : 0;\n p.bytesOutSum -= v['bytesOut_avg'] * v['count'];\n p.bytesOutAvg = p.count ? d3.round((p.bytesOutSum / p.count), 2) : 0;\n return p;\n },\n //init\n function (p, v) {\n return {\n count: 0,\n loadTimeAvg: 0,\n loadTimeSum: 0,\n ttfbAvg: 0,\n ttfbSum: 0,\n downloadTimeAvg: 0,\n downloadTimeSum: 0,\n sslTimeAvg: 0,\n sslTimeSum: 0,\n connectTimeAvg: 0,\n connectTimeSum: 0,\n dnsTimeAvg: 0,\n dnsTimeSum: 0,\n bytesInAvg: 0,\n bytesInSum: 0,\n bytesOutAvg: 0,\n bytesOutSum: 0\n };\n });\n\n // Accessors for reductio min and max\n var minValueAccessor = function (d) {\n if (d.value.min)\n return d.value.min;\n else\n return null;\n };\n var maxValueAccessor = function (d) {\n if (d.value.max)\n return d.value.max;\n else\n return null;\n };\n\n var loadTimeGroup_min = reductio().min(function (d) {\n return +d['loadTimeMs_min']\n })(date_Dimension.group());\n var loadTimeGroup_max = reductio().max(function (d) {\n return +d['loadTimeMs_max']\n })(date_Dimension.group());\n var ttfbGroup_min = reductio().min(function (d) {\n return +d['ttfb_min']\n })(date_Dimension.group());\n var ttfbGroup_max = reductio().max(function (d) {\n return +d['ttfb_max']\n })(date_Dimension.group());\n var downloadTimeGroup_min = reductio().min(function (d) {\n return +d['downloadTime_min']\n })(date_Dimension.group());\n var downloadTimeGroup_max = reductio().max(function (d) {\n return +d['downloadTime_max']\n })(date_Dimension.group());\n var sslTimeGroup_min = reductio().min(function (d) {\n return +d['sslTime_min']\n })(date_Dimension.group());\n var sslTimeGroup_max = reductio().max(function (d) {\n return +d['sslTime_max']\n })(date_Dimension.group());\n var connectTimeGroup_min = reductio().min(function (d) {\n return +d['connectTime_min']\n })(date_Dimension.group());\n var connectTimeGroup_max = reductio().max(function (d) {\n return +d['connectTime_max']\n })(date_Dimension.group());\n var dnsTimeGroup_min = reductio().min(function (d) {\n return +d['dnsTime_min']\n })(date_Dimension.group());\n var dnsTimeGroup_max = reductio().max(function (d) {\n return +d['dnsTime_max']\n })(date_Dimension.group());\n var bytesInGroup_min = reductio().min(function (d) {\n return +d['bytesIn_min']\n })(date_Dimension.group());\n var bytesInGroup_max = reductio().max(function (d) {\n return +d['bytesIn_max']\n })(date_Dimension.group());\n var bytesOutGroup_min = reductio().min(function (d) {\n return +d['bytesOut_min']\n })(date_Dimension.group());\n var bytesOutGroup_max = reductio().max(function (d) {\n return +d['bytesOut_max']\n })(date_Dimension.group());\n\n var composite = board.getCompositeChart('dcChart', 'line-chart');\n\n var allGraphs = {};\n\n var colorScale = d3.scale.category10();\n\n function createLineChart(jobFilter, label, name, valueAccessor, unit) {\n var group = remove_empty_bins(jobFilter, valueAccessor);\n allGraphs[name] = board.createLineChart(composite, date_Dimension, group, colorScale(label), label, valueAccessor, unit);\n }\n\n // avg graph loadTime\n createLineChart(loadTime_ttfb_avg, \"LoadTimeMs Avg\", \"loadTimeAvg\", function (d) {\n return d.value.loadTimeAvg;\n });\n\n // avg graph ttfb\n createLineChart(loadTime_ttfb_avg, \"TTFB Avg\", \"ttfbAvg\", function (d) {\n return d.value.ttfbAvg;\n });\n\n // avg graph downloadTime\n createLineChart(loadTime_ttfb_avg, \"Download Time Avg\", \"downloadTimeAvg\", function (d) {\n return d.value.downloadTimeAvg;\n });\n\n // avg graph sslTime\n createLineChart(loadTime_ttfb_avg, \"SSL Time Avg\", \"sslTimeAvg\", function (d) {\n return d.value.sslTimeAvg;\n });\n // avg graph connectTime\n createLineChart(loadTime_ttfb_avg, \"Connect Time Avg\", \"connectTimeAvg\", function (d) {\n return d.value.connectTimeAvg;\n });\n // avg graph dnsTime\n createLineChart(loadTime_ttfb_avg, \"DNS Time Avg\", \"dnsTimeAvg\", function (d) {\n return d.value.dnsTimeAvg;\n });\n // avg graph bytesIn\n createLineChart(loadTime_ttfb_avg, \"Bytes In Avg\", \"bytesInAvg\", function (d) {\n return d.value.bytesInAvg;\n }, \"bytes\");\n // avg graph bytesOut\n createLineChart(loadTime_ttfb_avg, \"Bytes Out Avg\", \"bytesOutAvg\", function (d) {\n return d.value.bytesOutAvg;\n }, \"bytes\");\n\n // min graph loadTime\n createLineChart(loadTimeGroup_min, \"LoadTimeMs Min\", \"loadTimeMin\", minValueAccessor);\n // min graph ttfb\n createLineChart(ttfbGroup_min, \"TTFB Min\", \"ttfbMin\", minValueAccessor);\n // min graph downloadTime\n createLineChart(downloadTimeGroup_min, \"Download Time Min\", \"downloadTimeMin\", minValueAccessor);\n // min graph sslTime\n createLineChart(sslTimeGroup_min, \"SSL Time Min\", \"sslTimeMin\", minValueAccessor);\n // min graph connectTime\n createLineChart(connectTimeGroup_min, \"Connect Time Min\", \"connectTimeMin\", minValueAccessor);\n // min graph dnsTime\n createLineChart(dnsTimeGroup_min, \"DNS Time Min\", \"dnsTimeMin\", minValueAccessor);\n // min graph bytesIn\n createLineChart(bytesInGroup_min, \"Bytes In Min\", \"bytesInMin\", minValueAccessor, \"bytes\");\n // min graph bytesOut\n createLineChart(bytesInGroup_min, \"Bytes Out Min\", \"bytesOutMin\", minValueAccessor, \"bytes\");\n\n // max graph loadTime\n createLineChart(loadTimeGroup_max, \"LoadTimeMs Max\", \"loadTimeMax\", maxValueAccessor);\n // max graph ttfb\n createLineChart(ttfbGroup_max, \"TTFB Max\", \"ttfbMax\", maxValueAccessor);\n // max graph ttfb\n createLineChart(downloadTimeGroup_max, \"Download Time Max\", \"downloadTimeMax\", maxValueAccessor);\n // max graph ttfb\n createLineChart(sslTimeGroup_max, \"SSL Time Max\", \"sslTimeMax\", maxValueAccessor);\n // max graph ttfb\n createLineChart(connectTimeGroup_max, \"Connect Time Max\", \"connectTimeMax\", maxValueAccessor);\n // max graph dns\n createLineChart(dnsTimeGroup_max, \"DNS Time Max\", \"dnsTimeMax\", maxValueAccessor);\n // max graph bytesIn\n createLineChart(bytesInGroup_max, \"Bytes In Max\", \"bytesInMax\", maxValueAccessor, \"bytes\");\n // max graph bytesOut\n createLineChart(bytesOutGroup_max, \"Bytes Out Max\", \"bytesOutMax\", maxValueAccessor, \"bytes\");\n\n // 24 = [loadTime, ttfb, ..., bytesIn]*[avg,min,max]\n board.addCompositeChart('dcChart', 'line-chart', from, to, 24);\n redrawCompositeChart();\n\n // ### END LINE CHARTS\n\n // ### BEGIN TIME CHART\n var timeDimension = board.allData.dimension(function (d) {\n return d.date;\n });\n\n var timeGroup = timeDimension.group().reduceSum(function (d) {\n return d['count'];\n });\n board.addTimeChart('dcChart', 'timeChart', timeDimension, timeGroup, from, to);\n // ### END TIME CHART\n\n // Add data to dashboard\n var p1 = new Promise(\n function (resolve, reject) {\n board.addData(data);\n }\n );\n\n // Add onClick Listener\n $(document).on('change', 'input:checkbox[name=\"measurementCheckbox\"]', function (event) {\n $(this).parent().toggleClass(\"btn-primary\");\n $(this).parent().toggleClass(\"btn-default\");\n redrawCompositeChart();\n $(this).parent().removeClass(\"focus\");\n });\n\n $(document).keyup(function (e) {\n if (e.keyCode == 27) {\n $(\".card-modal\").hide();\n $(\"#preselectedValuesContainer\").hide();\n }\n });\n\n $('.card-modal').click(function () {\n $(\".card-modal\").hide();\n $(\"#preselectedValuesContainer\").hide();\n });\n $('.card-header .close').click(function () {\n $(\".card-modal\").hide();\n $(\"#preselectedValuesContainer\").hide();\n });\n\n $('.card-modal-inner').click(function (e) {\n e.stopPropagation();\n });\n\n function redrawCompositeChart() {\n board.setAnimationTime(500);\n\n var showAvg = document.getElementById(\"avg\").checked;\n var showMax = document.getElementById(\"max\").checked;\n var showMin = document.getElementById(\"min\").checked;\n var visibleGraphs = [];\n\n function handleValueTypeCheckbox(avgName, minName, maxName) {\n if (showAvg)\n visibleGraphs.push(allGraphs[avgName]);\n\n if (showMin)\n visibleGraphs.push(allGraphs[minName]);\n if (showMax)\n visibleGraphs.push(allGraphs[maxName]);\n }\n\n if (document.getElementById(\"loadTimeMs\").checked) {\n handleValueTypeCheckbox(\"loadTimeAvg\", \"loadTimeMin\", \"loadTimeMax\");\n }\n if (document.getElementById(\"ttfb\").checked) {\n handleValueTypeCheckbox(\"ttfbAvg\", \"ttfbMin\", \"ttfbMax\");\n }\n if (document.getElementById(\"downloadTime\").checked) {\n handleValueTypeCheckbox(\"downloadTimeAvg\", \"downloadTimeMin\", \"downloadTimeMax\");\n }\n if (document.getElementById(\"sslTime\").checked) {\n handleValueTypeCheckbox(\"sslTimeAvg\", \"sslTimeMin\", \"sslTimeMax\");\n }\n if (document.getElementById(\"connectTime\").checked) {\n handleValueTypeCheckbox(\"connectTimeAvg\", \"connectTimeMin\", \"connectTimeMax\");\n }\n if (document.getElementById(\"dnsTime\").checked) {\n handleValueTypeCheckbox(\"dnsTimeAvg\", \"dnsTimeMin\", \"dnsTimeMax\");\n }\n if (document.getElementById(\"bytesIn\").checked) {\n handleValueTypeCheckbox(\"bytesInAvg\", \"bytesInMin\", \"bytesInMax\");\n }\n if (document.getElementById(\"bytesOut\").checked) {\n handleValueTypeCheckbox(\"bytesOutAvg\", \"bytesOutMin\", \"bytesOutMax\");\n }\n\n\n board.getCompositeChart('dcChart', 'line-chart').compose(visibleGraphs);\n dc.renderAll();\n addOnClickListeners();\n hideDataTable();\n board.setAnimationTime(700);\n }\n}", "function addTab(title) {\n var tab_title = (title.length==0)?'Graph '+tab_counter:title;\n var panelId = 'graphTab'+tab_counter++;\n\n var tabsLength = $(common.mustache(templates.graphTab, {\n title: tab_title,\n href: panelId\n }))\n .appendTo($graphTabs.find('.ui-tabs-nav'))\n .find('li').length;\n $graphTabs.append(common.mustache(templates.graphDiv, {\n panelId: panelId\n }));\n $graphTabs\n .tabs(\"refresh\")\n .tabs( \"option\", \"active\", tabsLength-1)\n .find('li.graph-tab span.ui-icon-close').off().click(removeTab);\n\n //this causes problem when deleting tabs\n $graphTabs.find( \".ui-tabs-nav\" ).sortable({ axis: \"x\", distance: 10 });\n $(\".ui-tabs-selected a\").each(function(){$(this).attr(\"title\", $(this).html())});\n resizeCanvas();\n\n //in revised layout, show only if graph tabs and search tables are shown $(\"#show-hide-pickers\").show();\n $('#graph-tabs a:last').click(function(){\n hideGraphEditor()\n });\n return panelId;\n}", "function showDashboard() {\r\n\t\t$('#container img').remove();\r\n\t\t$('#login-form').remove();\r\n\t\t//TODO:cleanup after this part\r\n\t\t$('<div/>').attr('id', 'chart-container').appendTo($('#container'));\r\n\t\t$('<div/>').addClass('chart-options').attr('id', 'chart-options-container').appendTo($('#center'));\r\n\t\t\r\n\t\tvar chartparent = $('#chart-options-container');\r\n\t\taddChartOptions([\r\n\t\t {\r\n\t\t \t src : './images/column-chart.png',\r\n\t\t \t type : 'column',\r\n\t\t \t parent : chartparent\r\n\t\t }, {\r\n\t\t \t src : './images/chart-line.png',\r\n\t\t \t type : 'line',\r\n\t\t \t parent : chartparent\r\n\t\t },{\r\n\t\t \t src : './images/chart-bar.png',\r\n\t\t \t type : 'bar',\r\n\t\t \t parent : chartparent\r\n\t\t }, {\r\n\t\t \t src : './images/chart-area.png',\r\n\t\t \t type : 'area',\r\n\t\t \t parent : chartparent\r\n\t\t }, {\r\n\t\t \t src : './images/chart-pie.png',\r\n\t\t \t type : 'pie',\r\n\t\t \t parent : chartparent\r\n\t\t }]);\r\n\t\tvar sPref = readCookie('sm-dash-chart');\r\n\t\tsPref = (sPref == null ? 'column' : sPref);\r\n\t\tplotCommonChart( sPref );\r\n\t\twriteCookie('sm-dash-chart', sPref, 1);\r\n\t\t$('<a/>').html(\"Workspace\").attr('href', \"services.htm\").appendTo($('<li/>').appendTo('#menu'));\r\n\t}", "function afficherGraphe() {\n\t\n\t\n\t\t// Création du graphe\n\t\tvar chart = new AmCharts.AmSerialChart();\n\t\tchart.dataProvider = chartData;\n\t\tchart.categoryField = \"country\";\n\t\tvar graph = new AmCharts.AmGraph();\n\t\tgraph.valueField = \"visits\";\n\t\tgraph.type = \"column\";\n\t\tchart.addGraph(graph);\n\t\tchart.write('statistiques');\n\n\n}" ]
[ "0.6496089", "0.6370459", "0.6365461", "0.6352829", "0.6338957", "0.63205457", "0.6247306", "0.6183056", "0.6176735", "0.6126419", "0.606333", "0.604698", "0.6016476", "0.59790146", "0.59727335", "0.5968875", "0.59336907", "0.59187734", "0.58724236", "0.58718795", "0.5847641", "0.57842326", "0.5766701", "0.5766701", "0.57550865", "0.57549596", "0.57475746", "0.5739126", "0.5726901", "0.570666" ]
0.63741547
1
A submap node should be positioned in the place of average visibility and average evolution (!). The evolution is averaged from all the components included in submap, regardless of whether they are or are not visible. The visibility is calculated from components visible on a given map and is map specific. We do not want to make too much mess here.
function getSubmapPositions(mongooseObjects, nodeIds, impact) { let Node = mongooseObjects.Node; let positions = { evolutionSum: 0, evolutionCount: 0, maps: {} /* mapId : { nodeVisiblityCount : number, visibilitySum : number } */ }; // actually calculate submap position return Node.find({ _id: { $in: nodeIds } }).exec() .then(function(nodes) { // iterate over submapped nodes. Sum and count evolution of all nodes, // sum and count visibility *per map* for (let i = 0; i < nodes.length; i++) { let analysedNode = nodes[i]; for (let j = 0; j < analysedNode.visibility.length; j++) { // create a record if necessary if (!positions[analysedNode.visibility[j].map]) { positions.maps[analysedNode.visibility[j].map] = { nodeVisiblityCount: 0, visibilitySum: 0, }; } positions.maps[analysedNode.visibility[j].map].nodeVisiblityCount++; positions.maps[analysedNode.visibility[j].map].visibilitySum += analysedNode.visibility[j].value; } positions.evolutionSum += analysedNode.evolution; positions.evolutionCount++; } return positions; }) .then(function(position) { // normalise - calculate averages - we want to get a nice result let result = { evolution: (position.evolutionSum / position.evolutionCount), visibility: {} }; for (let key in position.maps) { if (position.maps.hasOwnProperty(key)) { result.visibility[key] = (position.maps[key].visibilitySum / position.maps[key].nodeVisiblityCount); } } return result; }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "applyLayoutVisibility() {\n const { visible } = this;\n const { mbMap } = this.mapboxLayer;\n\n if (!mbMap) {\n return;\n }\n\n const style = mbMap.getStyle();\n\n if (!style) {\n return;\n }\n\n if (this.styleLayersFilter) {\n const visibilityValue = visible ? 'visible' : 'none';\n for (let i = 0; i < style.layers.length; i += 1) {\n const styleLayer = style.layers[i];\n if (this.styleLayersFilter(styleLayer)) {\n if (mbMap.getLayer(styleLayer.id)) {\n mbMap.setLayoutProperty(\n styleLayer.id,\n 'visibility',\n visibilityValue,\n );\n }\n }\n }\n }\n }", "function updatePrecipVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "onChangeVisible() {\n const { mbMap } = this.mapboxLayer;\n if (!mbMap) {\n return;\n }\n const currentLayer = this.getCurrentLayer();\n const filterRegex = new RegExp(`^ipv_(${currentLayer})$`);\n this.getDvLayers()?.forEach((stylelayer) => {\n mbMap.setLayoutProperty(\n stylelayer.id,\n 'visibility',\n filterRegex.test(getTrafimageFilter(stylelayer)) ? 'visible' : 'none',\n );\n });\n }", "function formASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact) {\n let Node = mongooseObjects.Node;\n let Workspace = mongooseObjects.Workspace;\n\n let positionsAntipaternVariable = null;\n\n return getSubmapPositions(mongooseObjects, nodesInSubmap, impact).then(function(positions){\n positionsAntipaternVariable = positions;\n return createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact)\n .then(function(submap){\n return {\n positions: positions,\n submap: submap\n };\n });\n })\n .then(function(arg) {\n return createSubmapNode(mongooseObjects, arg, impact, workspace, name, responsiblePerson);\n })\n .then(function(node) {\n let nodeId = getId(node);\n // and the heavy part. get everyone depending on a submap to really depend on it\n return replaceIncomingDependencies(mongooseObjects, nodeId, impact.nodesThatDependOnFutureSubmap, nodesInSubmap).then(function(irrelevantStuff){\n \t let changedMaps = [];\n \t for (let key in positionsAntipaternVariable.visibility) {\n \t if (positionsAntipaternVariable.visibility.hasOwnProperty(key)) {\n \t \tchangedMaps.push(key);\n \t }\n \t }\n \t return changedMaps;\n });\n });\n}", "flattenVisible() {\n EventBus.$emit(\"try-flatten-visible-layers\");\n }", "function update() {\n\t\n\t// SCATTERPLOT\n\tdots = sp_svg.selectAll(\".dot\")\n\t\t.data(nba_data).transition(400)\n\t\t.attr(\"cx\", xMap)\n\t\t.attr(\"cy\", yMap)\n\t\t.attr(\"r\", function(d) { return radii[d[season+\"PO\"]];})\n\t\t.style(\"stroke-width\", function(d) { return border_weights[d[season+\"PO\"]];})\n\t\t.style(\"stroke-dasharray\", function(d) { return dasharrays[d[season+\"PO\"]];});\n\t\n\t// TREEMAP\n\t// Delete the old treemap.\n\t$(\".chart\").remove();\n\t\n\t// Create the spot for the new treemap.\n\ttm_div = d3.select(\"#tm_vis\").append(\"div\")\n\t\t.attr(\"class\", \"chart\")\n\t\t.style(\"width\", (width + margin.left + margin.right) + \"px\")\n\t\t.style(\"height\", (height + margin.top + margin.bottom) + \"px\")\n\t .append(\"svg:svg\")\n\t\t.style(\"width\", (width) + \"px\")\n\t\t.style(\"height\", (height) + \"px\")\n\t .append(\"svg:g\")\n\t\t.attr(\"transform\", \"translate(.5,.5)\");\n\t\n\t// Draw an invisible map (opacity=0)\n\tdraw_treemap(0);\t\n\t\n\t// Zoom in on the appropriate region and make it visible\n\tif(zoomed) {\n\t\tzoom_level--;\n\t\tif(zoom_level == 0) zoomed = false;\n\t\tzoom(zoomed_node, 0);\n\t} else {\n\t\tzoomed = true;\n\t\tzoom_level = 2;\n\t\tzoom(x_root, 0);\n\t}\n}", "_applySubBasePositions() {\n if (this._subBasePositions.length === 0) {\n return;\n }\n getCentroid(this._subBasePositions, this._worldPosition);\n this._subBasePositions.length = 0;\n }", "readjust_subtask_opacities() {\n for (const st_key in this.subtasks) {\n let sliderval = jquery_default()(\"#tb-st-range--\" + st_key).val();\n jquery_default()(\"div#canvasses__\" + st_key).css(\"opacity\", sliderval/100);\n }\n }", "function createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodes, impact) {\n let Node = mongooseObjects.Node;\n let WardleyMap = mongooseObjects.WardleyMap;\n return workspace.createAMap({\n name: name,\n responsiblePerson: responsiblePerson\n }, workspace.nowId, /*mark as submap */ true)\n .then(function(newlyCreatedMap) {\n //inSubmapDependencies those deps have to be copied\n //and nodes, of course\n return Node.find({\n _id: {\n $in: nodes\n }\n }).exec().then(function(nodes) {\n let promises = [];\n for (let i = 0; i < nodes.length; i++) {\n let processedNode = nodes[i];\n // for each node that was pushed to a submap\n\n\n //1. set parent map\n processedNode.parentMap = [getId(newlyCreatedMap)];\n\n //2. adjust visibility - steal it from current map\n // if for some reason it is not missing, take the first available one\n let bestVisibility = processedNode.visibility[0];\n for (let j = 0; j < processedNode.visibility.length; j++) {\n let analysedVisibility = processedNode.visibility[j];\n if (getId(analysedVisibility.map).equals(getId(mapId))) {\n bestVisibility = analysedVisibility;\n }\n }\n bestVisibility.map = getId(newlyCreatedMap);\n processedNode.visibility = [bestVisibility];\n\n //3. sort out dependencies, only those presented on a map will stay\n //for now, in the future we may have some cross maps dependencies possible\n processedNode.dependencies = [];\n for (let j = 0; j < impact.inSubmapDependencies.length; j++) {\n let processedDependency = impact.inSubmapDependencies[j];\n if (getId(processedDependency.node).equals(getId(processedNode))) {\n processedNode.dependencies = processedNode.dependencies.concat(processedDependency.deps);\n }\n }\n // 3.a ensure dependencies are visible when they should be\n for (let j = 0; j < processedNode.dependencies.length; j++) {\n processedNode.dependencies[j].visibleOn = [getId(newlyCreatedMap)];\n }\n //4. save, piece of cake\n promises.push(processedNode.save());\n }\n return q.all(promises).then(function() {\n return WardleyMap.findById(getId(newlyCreatedMap)).populate('nodes').exec();\n });\n });\n });\n}", "_zoomEndEvent(){\n\t\tlet zoom = this.map.getZoom();\n\n\t\tObject.keys(this.layers).forEach(layer => {\n\t\t\tlet el = this.layers[layer].options.pane;\n\n\t\t\tif(zoom >= 4){\n\t\t\t\tPrototypeElement.removeClassName(el, 'half');\n\t\t\t}\n\t\t\telse if(zoom < 4 && zoom >= 2){\n\t\t\t\tPrototypeElement.removeClassName(el, 'quarter');\n\t\t\t\tPrototypeElement.addClassName(el, 'half');\n\t\t\t}\n\t\t\telse if(zoom < 2 && zoom >= 1){\n\t\t\t\tPrototypeElement.removeClassName(el, 'half');\n\t\t\t\tPrototypeElement.removeClassName(el, 'invis');\n\t\t\t\tPrototypeElement.addClassName(el, 'quarter');\n\t\t\t}\n\t\t\telse if(zoom < 1){\n\t\t\t\tPrototypeElement.removeClassName(el, 'quarter');\n\t\t\t\tPrototypeElement.addClassName(el, 'invis');\n\t\t\t}\n\n\t\t\t// i hate this.\n\t\t\tif(['map_label', 'sector_label'].includes(layer)){\n\t\t\t\tObject.keys(el.children).forEach(c => {\n\t\t\t\t\tlet origin = window.getComputedStyle(el.children[c]).perspectiveOrigin.split(' ');\n\n\t\t\t\t\tel.children[c].style.left = '-'+origin[0];\n\t\t\t\t\tel.children[c].style.top = '-'+origin[1];\n\t\t\t\t});\n\t\t\t}\n\n\t\t});\n\n\t}", "function updateVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n domStyle.set(\"btn_\" + lName[1] + \"_\" + mapID, {\n background: \"white\",\n color: \"#64acf7\"\n });\n } else {\n dynamicMapSerives[lName[1]].hide();\n domStyle.set(\"btn_\" + lName[1] + \"_\" + mapID, {\n background: \"#64acf7\",\n color: \"black\"\n });\n }\n }", "function updateVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n domStyle.set(\"btn_\" + lName[1] + \"_\" + mapID, {\n background: \"white\",\n color: \"#64acf7\"\n });\n } else {\n dynamicMapSerives[lName[1]].hide();\n domStyle.set(\"btn_\" + lName[1] + \"_\" + mapID, {\n background: \"#64acf7\",\n color: \"black\"\n });\n }\n }", "function updateRelVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function updateCarbonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function mapVisibility() {\n\n if (itemMap.isTaken === true) {\n\n document.getElementById(\"map2\").style.visibility = \"visible\";\n\n document.getElementById(\"map1\").style.visibility = \"hidden\";\n\n } else { \n\n document.getElementById(\"map2\").style.visibility = \"hidden\";\n\n }\n\n }", "function e(e,n,i){if(n.flatten((({sublayers:e})=>e)).length!==e.length)return!0;return!!e.some((e=>e.originIdOf(\"minScale\")>i||e.originIdOf(\"maxScale\")>i||e.originIdOf(\"renderer\")>i||e.originIdOf(\"labelingInfo\")>i||e.originIdOf(\"opacity\")>i||e.originIdOf(\"labelsVisible\")>i||e.originIdOf(\"source\")>i))||!r(e,n)}", "_visibilityOfLayerByZoom() {\n let mainLayer = this.get('mainLayer');\n if (Ember.isNone(mainLayer) || Ember.isNone(mainLayer._leafletObject)) {\n return;\n }\n\n if (!this._checkAndSetVisibility(mainLayer)) {\n mainLayer.get('innerLayers').forEach((layer) => {\n if (this._checkAndSetVisibility(layer)) {\n return;\n }\n });\n }\n }", "function updateSubplots(viewBox) {\n\t var j;\n\t var plotinfos = fullLayout._plots,\n\t subplots = Object.keys(plotinfos);\n\t\n\t for(var i = 0; i < subplots.length; i++) {\n\t\n\t var subplot = plotinfos[subplots[i]],\n\t xa2 = subplot.xaxis,\n\t ya2 = subplot.yaxis,\n\t editX = ew && !xa2.fixedrange,\n\t editY = ns && !ya2.fixedrange;\n\t\n\t if(editX) {\n\t var isInX = false;\n\t for(j = 0; j < xa.length; j++) {\n\t if(xa[j]._id === xa2._id) {\n\t isInX = true;\n\t break;\n\t }\n\t }\n\t editX = editX && isInX;\n\t }\n\t\n\t if(editY) {\n\t var isInY = false;\n\t for(j = 0; j < ya.length; j++) {\n\t if(ya[j]._id === ya2._id) {\n\t isInY = true;\n\t break;\n\t }\n\t }\n\t editY = editY && isInY;\n\t }\n\t\n\t var xScaleFactor = editX ? xa2._length / viewBox[2] : 1,\n\t yScaleFactor = editY ? ya2._length / viewBox[3] : 1;\n\t\n\t var clipDx = editX ? viewBox[0] : 0,\n\t clipDy = editY ? viewBox[1] : 0;\n\t\n\t var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0,\n\t fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0;\n\t\n\t var plotDx = xa2._offset - fracDx,\n\t plotDy = ya2._offset - fracDy;\n\t\n\t fullLayout._defs.selectAll('#' + subplot.clipId)\n\t .call(Drawing.setTranslate, clipDx, clipDy)\n\t .call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);\n\t\n\t subplot.plot\n\t .call(Drawing.setTranslate, plotDx, plotDy)\n\t .call(Drawing.setScale, xScaleFactor, yScaleFactor)\n\t\n\t // This is specifically directed at scatter traces, applying an inverse\n\t // scale to individual points to counteract the scale of the trace\n\t // as a whole:\n\t .select('.scatterlayer').selectAll('.points').selectAll('.point')\n\t .call(Drawing.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor);\n\t }\n\t }", "update(map)\n {\n if (this.container === null)\n {\n this.init(map);\n }\n\n this.coins.graphics.clear();\n this.treasures.graphics.clear();\n const info_arr = map.eData();\n const size_x = map.SIZE_X;\n const size_y = map.SIZE_Y;\n\n for (let i = 0; i < size_x; i++)\n {\n const screen_y = this.size * i;\n for (let j = 0; j < size_y; j++)\n {\n const screen_x = this.size * j;\n if (info_arr[i][j] === BaseMapInfo.getElementsByTagName(\"gold\"))\n {\n this.paintCoin(screen_x, screen_y);\n }\n else if (info_arr[i][j] === BaseMapInfo.getElementsByTagName(\"end\"))\n {\n this.paintFinish(screen_x, screen_y);\n }\n }\n }\n }", "function _updateLayers() {\n for(var i in map._layers) {\n\tif(map._layers[i]._latlng) {\n\t if(map._layers[i]._latlng.level) {\n\t if(map._layers[i]._latlng.level == map.getLevel()) {\n\t if(map._layers[i].setOpacity) {\n\t map._layers[i].setOpacity(1);\n\t } else if(map._layers[i]._container) {\n\t $(map._layers[i]._container).show();\n\t }\n } else {\n\t if(map._layers[i].setOpacity) {\n\t map._layers[i].setOpacity(0);\n\t } else if(map._layers[i]._container) {\n\t $(map._layers[i]._container).hide();\n\t }\n\t }\n\t }\n\t}\n }\n }", "function mapLayerChanged(e) {\n\t // console.log(e.type + \" \" + e.layer.name + \" \" + e.property);\n\t if (vectors) vectors.removeAllFeatures();\n\t if (e.layer && document.getElementById('overlayRadio' + e.layer.name))\n\t document.getElementById('overlayRadio' + e.layer.name).checked = true;\n\t setResults();\n\t }", "function showMapPart() {\n g.selectAll(\".map:not(.q8-9)\")\n .transition(\"visibility\")\n .duration(600)\n .delay(function (d, i) {\n return 10 * (i + 1);\n })\n .attr(\"opacity\", 0);\n\n g.selectAll(\".q8-9\")\n .transition()\n .duration(600)\n .attr(\"opacity\", 1.0);\n\n g.selectAll(\".linelabel\")\n .transition()\n .duration(0)\n .attr(\"opacity\", 0);\n\n g.selectAll(\".curtain\")\n .transition()\n .duration(0)\n .attr('x', -1 * width);\n\n g.selectAll(\".curtain\")\n .transition()\n .duration(30)\n .attr(\"opacity\", 0);\n\n // create a shared transition for anything we're animating\n var t = g.transition()\n .delay(750)\n .duration(6000)\n .ease('linear')\n .each('end', function() {\n d3.select('line.guide')\n .transition()\n .style('opacity', 0)\n .remove()\n });\n\n t.select('rect.curtain')\n .attr('x', -1 * width);\n t.select('line.guide')\n .attr('transform', 'translate(' + width + ', 0)');\n\n g.selectAll(\".axis\")\n .transition()\n .duration(0)\n .attr(\"opacity\", 0);\n\n g.selectAll('.line')\n .transition()\n .duration(0)\n .attr(\"opacity\", 0);\n }", "function showOverviewMap() {\r\n $('.county-container').addClass('hide');\r\n $('#mapBusyPanel').addClass('hide');\r\n $('.overview-container').removeClass('hide');\r\n removePreviousAvenzaViewer();\r\n}", "function updateRadonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function updateRadonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function updateRadonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function updateRadonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "function updateRadonVisibility(evt) {\n evt = evt || window.event;\n //get the layer index from the element id\n var lName = evt.target.id.split(\"_\");\n //If radio button is checked show Map layer\n if (dom.byId(evt.target.id).checked) {\n dynamicMapSerives[lName[1]].show();\n } else {\n dynamicMapSerives[lName[1]].hide();\n }\n }", "checkVisible() {\r\n let squares = this.state.squares;\r\n let mapLevel = this.state.mapLevel;\r\n let p = this.state.playerIndex;\r\n let n = 20;\r\n let visible = [];\r\n const aura = [p, p-2, p-1, p+1, p+2, p+3, p-3,\r\n p-n, p-n-2, p-n-1, p-n+1, p-n+2,\r\n p+n, p+n-2, p+n-1, p+n+1, p+n+2,\r\n p-n*2, p-n*2-1, p-n*2+1,\r\n p+n*2, p+n*2-1, p+n*2+1,\r\n p-4, p+4];\r\n\r\n //only set visible what is on grid and eliminate overflow to other rows\r\n for (let i=0; i<aura.length; i++) {\r\n if (Math.abs(aura[i] % n - p % n) < 4 && aura[i] >= 0 && aura[i] < squares[mapLevel].length) {\r\n visible.push(aura[i]);\r\n }\r\n }\r\n let hidden = [];\r\n for (let i=0; i<squares[mapLevel].length; i++) {\r\n if (!visible.includes(i)) {\r\n hidden.push(i);\r\n }\r\n }\r\n this.setHidden(hidden);\r\n this.setVisible(visible);\r\n }", "function addMinimalProjectionChangedListener(map, currentBubble){\n google.maps.event.addListener(map, 'tilesloaded', function(){\n \tOVERLAYVIEW.drawOverviewMarker(currentBubble);\n });\n}" ]
[ "0.5155607", "0.5108502", "0.5017218", "0.4999723", "0.49637577", "0.49426314", "0.49350336", "0.4899641", "0.48742247", "0.48171225", "0.480886", "0.480886", "0.4788675", "0.47885686", "0.47782236", "0.47715354", "0.47700462", "0.47681093", "0.4760436", "0.4745325", "0.47267002", "0.4719209", "0.47171047", "0.46932125", "0.46932125", "0.46932125", "0.46932125", "0.46932125", "0.469052", "0.4689007" ]
0.5816436
0
every node that depends on a node injected into the submap, has to switch dependency to a node representing that submap. Which should be as simple as: remove all deps (constistent across all submaps) Further required work: [ ] ensure consistency across all the maps
function replaceIncomingDependencies(mongooseObjects, targetNodeId, nodesThatDependOnFutureSubmap, nodesInSubmap) { let results = []; for (let i = 0; i < nodesThatDependOnFutureSubmap.length; i++) { let analysedNode = nodesThatDependOnFutureSubmap[i]; console.log('what about here', analysedNode); let atLeastOneMigrated = false; for (let j = analysedNode.dependencies.length - 1; j >= 0; j--) { let analysedDependency = analysedNode.dependencies[j]; let isForSubmappedNode = false; for (let k = 0; k < nodesInSubmap.length; k++) { if (getId(nodesInSubmap[k]).equals(getId(analysedDependency.target))) { isForSubmappedNode = true; } } if (isForSubmappedNode) { //we have to do something with current dependency if (atLeastOneMigrated) { // we have at least one dependency migrated earlier, we do not want to duplicate them, // so just discard it analysedNode.dependencies.splice(j, 1); j--; //index should be shifted after the number of dependencies is reduced } else { //blatantly switch the first dependency that can be switched analysedDependency.target = targetNodeId; atLeastOneMigrated = true; // j--; } } } if (atLeastOneMigrated) { console.log('being saved', analysedNode); results.push(analysedNode.save()); } } return q.allSettled(results); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodes, impact) {\n let Node = mongooseObjects.Node;\n let WardleyMap = mongooseObjects.WardleyMap;\n return workspace.createAMap({\n name: name,\n responsiblePerson: responsiblePerson\n }, workspace.nowId, /*mark as submap */ true)\n .then(function(newlyCreatedMap) {\n //inSubmapDependencies those deps have to be copied\n //and nodes, of course\n return Node.find({\n _id: {\n $in: nodes\n }\n }).exec().then(function(nodes) {\n let promises = [];\n for (let i = 0; i < nodes.length; i++) {\n let processedNode = nodes[i];\n // for each node that was pushed to a submap\n\n\n //1. set parent map\n processedNode.parentMap = [getId(newlyCreatedMap)];\n\n //2. adjust visibility - steal it from current map\n // if for some reason it is not missing, take the first available one\n let bestVisibility = processedNode.visibility[0];\n for (let j = 0; j < processedNode.visibility.length; j++) {\n let analysedVisibility = processedNode.visibility[j];\n if (getId(analysedVisibility.map).equals(getId(mapId))) {\n bestVisibility = analysedVisibility;\n }\n }\n bestVisibility.map = getId(newlyCreatedMap);\n processedNode.visibility = [bestVisibility];\n\n //3. sort out dependencies, only those presented on a map will stay\n //for now, in the future we may have some cross maps dependencies possible\n processedNode.dependencies = [];\n for (let j = 0; j < impact.inSubmapDependencies.length; j++) {\n let processedDependency = impact.inSubmapDependencies[j];\n if (getId(processedDependency.node).equals(getId(processedNode))) {\n processedNode.dependencies = processedNode.dependencies.concat(processedDependency.deps);\n }\n }\n // 3.a ensure dependencies are visible when they should be\n for (let j = 0; j < processedNode.dependencies.length; j++) {\n processedNode.dependencies[j].visibleOn = [getId(newlyCreatedMap)];\n }\n //4. save, piece of cake\n promises.push(processedNode.save());\n }\n return q.all(promises).then(function() {\n return WardleyMap.findById(getId(newlyCreatedMap)).populate('nodes').exec();\n });\n });\n });\n}", "resolveNodes() {\n const {\n map,\n _cstAliases\n } = this;\n Object.keys(map).forEach(a => {\n map[a] = map[a].resolved;\n });\n\n _cstAliases.forEach(a => {\n a.source = a.source.resolved;\n });\n\n delete this._cstAliases;\n }", "resolveNodes() {\n const {\n map,\n _cstAliases\n } = this;\n Object.keys(map).forEach(a => {\n map[a] = map[a].resolved;\n });\n\n _cstAliases.forEach(a => {\n a.source = a.source.resolved;\n });\n\n delete this._cstAliases;\n }", "resolveNodes() {\n const {\n map,\n _cstAliases\n } = this;\n Object.keys(map).forEach(a => {\n map[a] = map[a].resolved;\n });\n\n _cstAliases.forEach(a => {\n a.source = a.source.resolved;\n });\n\n delete this._cstAliases;\n }", "resolveNodes() {\n const {\n map,\n _cstAliases\n } = this;\n Object.keys(map).forEach(a => {\n map[a] = map[a].resolved;\n });\n\n _cstAliases.forEach(a => {\n a.source = a.source.resolved;\n });\n\n delete this._cstAliases;\n }", "resolveNodes() {\n const {\n map,\n _cstAliases\n } = this;\n Object.keys(map).forEach(a => {\n map[a] = map[a].resolved;\n });\n\n _cstAliases.forEach(a => {\n a.source = a.source.resolved;\n });\n\n delete this._cstAliases;\n }", "cleanupDeps () {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "cleanupDeps() {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "function formASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact) {\n let Node = mongooseObjects.Node;\n let Workspace = mongooseObjects.Workspace;\n\n let positionsAntipaternVariable = null;\n\n return getSubmapPositions(mongooseObjects, nodesInSubmap, impact).then(function(positions){\n positionsAntipaternVariable = positions;\n return createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact)\n .then(function(submap){\n return {\n positions: positions,\n submap: submap\n };\n });\n })\n .then(function(arg) {\n return createSubmapNode(mongooseObjects, arg, impact, workspace, name, responsiblePerson);\n })\n .then(function(node) {\n let nodeId = getId(node);\n // and the heavy part. get everyone depending on a submap to really depend on it\n return replaceIncomingDependencies(mongooseObjects, nodeId, impact.nodesThatDependOnFutureSubmap, nodesInSubmap).then(function(irrelevantStuff){\n \t let changedMaps = [];\n \t for (let key in positionsAntipaternVariable.visibility) {\n \t if (positionsAntipaternVariable.visibility.hasOwnProperty(key)) {\n \t \tchangedMaps.push(key);\n \t }\n \t }\n \t return changedMaps;\n });\n });\n}", "cleanupDeps () {\n var i = this.deps.length;\n while (i--) {\n var dep = this.deps[i];\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this);\n }\n }\n var tmp = this.depIds;\n this.depIds = this.newDepIds;\n this.newDepIds = tmp;\n this.newDepIds.clear();\n tmp = this.deps;\n this.deps = this.newDeps;\n this.newDeps = tmp;\n this.newDeps.length = 0;\n }", "cleanupDeps () {\n let i = this.deps.length\n while (i--) {\n const dep = this.deps[i]\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this)\n }\n }\n let tmp = this.depIds\n this.depIds = this.newDepIds\n this.newDepIds = tmp\n this.newDepIds.clear()\n tmp = this.deps\n this.deps = this.newDeps\n this.newDeps = tmp\n this.newDeps.length = 0\n }", "purgeSets() {\n this.children.forEach((subTrie) => {\n subTrie.wordSet.clear();\n subTrie.purgeSets();\n });\n }", "function changeMap(clickedElement) {\n markerLocs.positions.forEach(function (value) {\n if (value.id === clickedElement) {\n value.markerRef.setMap(null);\n }\n });\n\n return;\n}", "function step2(map) {\n\tconst root = { name: '/', nodes: [] };\n\treturn (function next(map, parent, level) {\n\t\tObject.keys(map).forEach(key => {\n\t\t\tlet val = map[key];\n\t\t\tlet node = { name: key };\n\t\t\tif (typeof val === 'object') {\n\t\t\t\tnode.nodes = [];\n\t\t\t\tnode.open = level < 1;\n\t\t\t\tnext(val, node, level + 1);\n\t\t\t} else {\n\t\t\t\tnode.src = val;\n\t\t\t}\n\t\t\tparent.nodes.push(node);\n\t\t});\n\t\treturn parent;\n\t})(map, root, 0);\n}", "_prune_empty_ancestors() {\n if (this.size() > 0 || !this._parent_map) return;\n let map = this,\n key = null;\n while (map.size() == 0) {\n if (!map._parent_map) break;\n key = map._parent_key;\n map = map._parent_map;\n }\n map._map.delete(key);\n }", "[_placeDep] (dep, node, edge, peerEntryEdge = null) {\n if (!edge.error && !this[_updateNames].includes(edge.name))\n return []\n\n // top nodes should still get peer deps from their parent or fsParent\n // if possible, and only install locally if there's no other option,\n // eg for a link outside of the project root.\n const start = edge.peer && !node.isRoot\n ? node.resolveParent || node\n : node\n\n let target\n let canPlace = null\n for (let check = start; check; check = check.resolveParent) {\n const cp = this[_canPlaceDep](dep, check, edge, peerEntryEdge)\n // anything other than a conflict is fine to proceed with\n if (cp !== CONFLICT) {\n canPlace = cp\n target = check\n } else\n break\n\n // nest packages like npm v1 and v2\n // very disk-inefficient\n if (this[_legacyBundling])\n break\n }\n\n if (!target) {\n throw Object.assign(new Error('unable to resolve dependency tree'), {\n package: edge.name,\n spec: edge.spec,\n type: edge.type,\n requiredBy: node.package._id,\n location: node.path,\n })\n }\n\n // Can only get KEEP here if the original edge was valid,\n // and we're checking for an update but it's already up to date.\n if (canPlace === KEEP) {\n dep.parent = null\n return []\n }\n\n // figure out which of this node's peer deps will get placed as well\n const virtualRoot = dep.parent\n\n const placed = [dep]\n const oldChild = target.children.get(edge.name)\n if (oldChild) {\n // if we're replacing, we should also remove any nodes for edges that\n // are now invalid, and where this (or its deps) is the only dependent,\n // and also recurse on that pruning. Otherwise leaving that dep node\n // around can result in spurious conflicts pushing nodes deeper into\n // the tree than needed in the case of cycles that will be removed\n // later anyway.\n const oldDeps = []\n for (const [name, edge] of oldChild.edgesOut.entries()) {\n if (!dep.edgesOut.has(name) && edge.to) {\n oldDeps.push(edge.to)\n }\n }\n dep.replace(oldChild)\n this[_pruneForReplacement](dep, oldDeps)\n } else\n dep.parent = target\n\n // If the edge is not an error, then we're updating something, and\n // MAY end up putting a better/identical node further up the tree in\n // a way that causes an unnecessary duplication. If so, remove the\n // now-unnecessary node.\n if (edge.valid && edge.to.parent !== target && dep.canReplace(edge.to)) {\n edge.to.parent = null\n }\n\n // visit any dependents who are upset by this change\n for (const edge of dep.edgesIn) {\n if (!edge.valid)\n this[_depsQueue].push(edge.from)\n }\n\n // in case we just made some duplicates that can be removed,\n // prune anything deeper in the tree that can be replaced by this\n if (this.idealTree) {\n\n for (const node of this.idealTree.inventory.query('name', dep.name)) {\n if (node !== dep &&\n node.isDescendantOf(target) &&\n !node.inShrinkwrap &&\n !node.inBundle &&\n node.canReplaceWith(dep)) {\n\n // don't prune if the is dupe necessary!\n // root (a, d)\n // +-- a (b, c2)\n // | +-- b (c2) <-- place c2 for b, lands at root\n // +-- d (e)\n // +-- e (c1, d)\n // +-- c1\n // +-- f (c2)\n // +-- c2 <-- pruning this would be bad\n\n const mask = node.parent !== target &&\n node.parent.parent !== target &&\n node.parent.parent.resolve(dep.name)\n\n if (!mask || mask === dep || node.canReplaceWith(mask))\n node.parent = null\n }\n }\n }\n\n // also place its unmet or invalid peer deps at this location\n // note that dep has now been removed from the virtualRoot set\n // by virtue of being placed in the target's node_modules.\n if (virtualRoot) {\n for (const peerEdge of dep.edgesOut.values()) {\n if (peerEdge.peer && !peerEdge.valid) {\n const peer = virtualRoot.children.get(peerEdge.name)\n const peerPlaced = this[_placeDep](\n peer, dep, peerEdge, peerEntryEdge || edge)\n placed.push(...peerPlaced)\n }\n }\n }\n\n return placed\n }", "function unFreeze(node){\n node.fixed = false;\n for( var i = 0; i < node.get('transitions').length; i++ ) {\n var childNode = idMap[node.get('transitions')[i].target];\n unFreeze(childNode);\n }\n }", "function _walkDeps(depsMap, id, file, entryDepsSet, isParentOurs, lastDirectDeps, parentDepsMap) {\n\t\t\tvar deps;\n\t\t\tif (!file) { // since for external module, the `file` is always `false`\n\t\t\t\tdeps = depsMap[id];\n\t\t\t\tif (parentDepsMap && !deps) {\n\t\t\t\t\tdeps = parentDepsMap[id];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeps = depsMap[file];\n\t\t\t\tdeps = deps ? deps : depsMap[id];\n\t\t\t\tif (parentDepsMap && !deps) {\n\t\t\t\t\tdeps = parentDepsMap[file] ? parentDepsMap[file] : parentDepsMap[id];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!deps && !{}.hasOwnProperty.call(i18nModuleNameSet, id)) {\n\t\t\t\tlog.error('Can not walk dependency tree for: ' + id +\n\t\t\t\t', missing depended module or you may try rebuild all bundles');\n\t\t\t\tlog.info(parentDepsMap[id]);\n\t\t\t\tlog.info('i18nModuleNameSet: ' + JSON.stringify(i18nModuleNameSet, null, ' '));\n\t\t\t\tgutil.beep();\n\t\t\t}\n\t\t\tif (!deps) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t_.forOwn(deps, function(depsValue, depsKey) {\n\t\t\t\tvar isRelativePath = _.startsWith(depsKey, '.');\n\n\t\t\t\tif (!isRelativePath) {\n\t\t\t\t\t// require id is a module name\n\t\t\t\t\tvar isOurs = isParentOurs && !packageUtils.is3rdParty(depsKey);\n\t\t\t\t\tif ({}.hasOwnProperty.call(entryDepsSet, depsKey)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tentryDepsSet[depsKey] = isParentOurs ? true : lastDirectDeps;\n\t\t\t\t\tif (isOurs) {\n\t\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, true, null, parentDepsMap);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, false, depsKey, parentDepsMap);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// require id is a local file path\n\t\t\t\t\t_walkDeps(depsMap, depsKey, depsValue, entryDepsSet, isParentOurs, lastDirectDeps, parentDepsMap);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "removeToChangeLayers(){\n if (this.map && !this.map.isStyleLoaded()) return;\n this.props.statuses.forEach(status => {\n if (status.key !== 'no_change'){\n status.layers.forEach(layer => {\n if (this.map.getLayer(layer)) {\n this.map.removeLayer(layer);\n }\n });\n }\n });\n }", "_updateBitMapIfNeeded() {\n var _this$consumer2;\n\n if (this.isolated) return;\n\n if ((_this$consumer2 = this.consumer) !== null && _this$consumer2 !== void 0 && _this$consumer2.isLegacy) {\n // this logic is not needed in Harmony, and we can't just remove the component as it may have\n // lanes data\n const componentMapExistWithSameVersion = this.bitMap.isExistWithSameVersion(this.component.id);\n\n if (componentMapExistWithSameVersion) {\n if (this.existingComponentMap && // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!\n this.existingComponentMap !== _constants().COMPONENT_ORIGINS.NESTED && this.origin === _constants().COMPONENT_ORIGINS.NESTED) {\n return;\n }\n\n this.bitMap.removeComponent(this.component.id);\n }\n } // @ts-ignore this.component.componentMap is set\n\n\n this.component.componentMap = this.addComponentToBitMap(this.component.componentMap.rootDir);\n }", "getDelayedMappedDependencies() {\n let graph = new DependencyGraph();\n let tagPrefix = TemplateMap.tagPrefix;\n\n graph.addNode(tagPrefix + \"all\");\n\n let userConfigCollections = this.getUserConfigCollectionNames();\n\n // Add tags from named user config collections\n for (let tag of userConfigCollections) {\n graph.addNode(tagPrefix + tag);\n }\n\n for (let entry of this.map) {\n if (this.isPaginationOverAllCollections(entry)) {\n continue;\n }\n\n let paginationTagTarget = this.getPaginationTagTarget(entry);\n if (paginationTagTarget && this.isUserConfigCollectionName(paginationTagTarget)) {\n if (!graph.hasNode(entry.inputPath)) {\n graph.addNode(entry.inputPath);\n }\n graph.addDependency(entry.inputPath, tagPrefix + paginationTagTarget);\n\n if (!entry.data.eleventyExcludeFromCollections) {\n // Populates into collections.all\n graph.addDependency(tagPrefix + \"all\", entry.inputPath);\n\n this.addTagsToGraph(graph, entry.inputPath, entry.data.tags);\n }\n\n this.addDeclaredDependenciesToGraph(\n graph,\n entry.inputPath,\n entry.data.eleventyImport?.collections\n );\n }\n }\n\n return graph;\n }", "function refreshAndInitMap() {\n // Remove all added layer:\n removeAllLayers();\n // Remove all source:\n removeAllSources();\n}", "removeNode(id) {\n let node = this.getNode(id);\n if (!node) { return; }\n\n this.checkTransactionStart();\n\n let toRemove = [];\n for (let i = 0; i < this.edges.length; i++) {\n var edge = this.edges[i];\n if ((edge.from.node === node.id) || (edge.to.node === node.id)) {\n toRemove.push(edge);\n }\n }\n for (let j = 0; j < toRemove.length; j++) {\n var edge = toRemove[j];\n this.removeEdge(edge.from.node, edge.from.port, edge.to.node, edge.to.port);\n }\n\n toRemove = [];\n for (let k = 0; k < this.initializers.length; k++) {\n var initializer = this.initializers[k];\n if (initializer.to.node === node.id) {\n toRemove.push(initializer);\n }\n }\n for (let i1 = 0; i1 < toRemove.length; i1++) {\n var initializer = toRemove[i1];\n this.removeInitial(initializer.to.node, initializer.to.port);\n }\n\n toRemove = [];\n for (let j1 = 0; j1 < this.exports.length; j1++) {\n var exported = this.exports[j1];\n if (this.getPortName(id) === exported.process) {\n toRemove.push(exported);\n }\n }\n for (let k1 = 0; k1 < toRemove.length; k1++) {\n var exported = toRemove[k1];\n this.removeExport(exported.public);\n }\n\n toRemove = [];\n for (var pub in this.inports) {\n var priv = this.inports[pub];\n if (priv.process === id) {\n toRemove.push(pub);\n }\n }\n for (let i2 = 0; i2 < toRemove.length; i2++) {\n pub = toRemove[i2];\n this.removeInport(pub);\n }\n\n toRemove = [];\n for (pub in this.outports) {\n var priv = this.outports[pub];\n if (priv.process === id) {\n toRemove.push(pub);\n }\n }\n for (let j2 = 0; j2 < toRemove.length; j2++) {\n pub = toRemove[j2];\n this.removeOutport(pub);\n }\n\n for (let k2 = 0; k2 < this.groups.length; k2++) {\n let group = this.groups[k2];\n if (!group) { continue; }\n let index = group.nodes.indexOf(id);\n if (index === -1) { continue; }\n group.nodes.splice(index, 1);\n }\n\n this.setNodeMetadata(id, {});\n\n if (-1 !== this.nodes.indexOf(node)) {\n this.nodes.splice(this.nodes.indexOf(node), 1);\n }\n\n this.emit('removeNode', node);\n\n return this.checkTransactionEnd();\n }", "function removeChildMapping(mapping, field) {\n\tvar removals = [];\n\tfor (var map in mapping) {\n\t\tvar lookField = field + \".\";\n\t\tif (map.includes(lookField)) {\n\t\t\tremovals.push(map);\n\t\t\tdelete mapping[map];\n\t\t}\n\t}\n\treturn removals;\n}", "function removeChildMapping(mapping, field) {\n\tvar removals = [];\n\tfor (var map in mapping) {\n\t\tvar lookField = field + \".\";\n\t\tif (map.includes(lookField)) {\n\t\t\tremovals.push(map);\n\t\t\tdelete mapping[map];\n\t\t}\n\t}\n\treturn removals;\n}", "_reload() {\n const { uiKey, rootNodes } = this.props;\n //\n this.context.store.dispatch(this.dataManager.receiveData(uiKey, new Immutable.Map({})));\n if (!rootNodes || rootNodes.length === 0) {\n return;\n }\n rootNodes.forEach(rootNode => {\n if (!rootNode.isMoreLink && !this._isLeaf(rootNode) && rootNode.toggled) {\n this._onToggle(rootNode, rootNode.toggled);\n }\n });\n }", "constructByDegree(){\n let id = bagDegrees[bagDegrees.length-1].id;\n let edges = cr.edges().remove();\n let collection = new Array();\n let notId = true;\n let index = 0;\n cr.nodes().forEach(n=>console.log(\"node davor\", n.id()))\n while(notId){\n let node = cr.nodes()[index]\n if(id !== node.id()){\n console.log(\"id \", node.id())\n let remove = node.remove()\n collection.push( remove );\n }\n \n else notId = false;\n }\n \n collection.forEach(n => console.log(\"node in collection \",n.id()))\n collection.forEach(n => n.restore())\n cr.nodes().forEach(n=>console.log(\"node nach add \", n.id()))\n edges.restore();\n }", "_removeCorrespondingXrefs(tx, node) {\n let manager;\n if (node.isInstanceOf(Reference.type)) {\n manager = this._referenceManager;\n } else if (node.isInstanceOf(Footnote.type)) {\n manager = this._footnoteManager;\n } else {\n return;\n }\n manager._getXrefs().forEach(xref => {\n const index = xref.refTargets.indexOf(node.id);\n if (index > -1) {\n tx.update([xref.id, 'refTargets'], { type: 'delete', pos: index });\n }\n });\n }", "removeDependency(key, dependencyKey) {\n var _a;\n let existingNode = this.nodes[key];\n let idx = ((_a = existingNode === null || existingNode === void 0 ? void 0 : existingNode.dependencies) !== null && _a !== void 0 ? _a : []).indexOf(dependencyKey);\n if (existingNode && idx > -1) {\n existingNode.dependencies.splice(idx, 1);\n this.addOrReplace(key, existingNode.dependencies);\n }\n }", "async removeMapData() {\n\n\t\tawait Utils.applyFunctoDataArray(Object.keys(this.layerIds), this.map.removeLayer);\n\n\t\tthis.layerIds = {};\n\n\t\tawait Utils.applyFunctoDataArray(Object.keys(this.sourceIds), this.map.removeSource);\n\n\t\tthis.sourceIds = {};\n\n\t}" ]
[ "0.6814995", "0.6181101", "0.6181101", "0.6181101", "0.6181101", "0.60917664", "0.60319054", "0.59357166", "0.59333426", "0.58866113", "0.586727", "0.5751134", "0.5572706", "0.55113435", "0.5486648", "0.5405267", "0.5387291", "0.538418", "0.53830135", "0.5381048", "0.537357", "0.52926636", "0.52801955", "0.5274717", "0.5274717", "0.5270838", "0.52464", "0.5246101", "0.5218809", "0.52121884" ]
0.7088818
0
Forms a submap and returns a list of modified maps
function formASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact) { let Node = mongooseObjects.Node; let Workspace = mongooseObjects.Workspace; let positionsAntipaternVariable = null; return getSubmapPositions(mongooseObjects, nodesInSubmap, impact).then(function(positions){ positionsAntipaternVariable = positions; return createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodesInSubmap, impact) .then(function(submap){ return { positions: positions, submap: submap }; }); }) .then(function(arg) { return createSubmapNode(mongooseObjects, arg, impact, workspace, name, responsiblePerson); }) .then(function(node) { let nodeId = getId(node); // and the heavy part. get everyone depending on a submap to really depend on it return replaceIncomingDependencies(mongooseObjects, nodeId, impact.nodesThatDependOnFutureSubmap, nodesInSubmap).then(function(irrelevantStuff){ let changedMaps = []; for (let key in positionsAntipaternVariable.visibility) { if (positionsAntipaternVariable.visibility.hasOwnProperty(key)) { changedMaps.push(key); } } return changedMaps; }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function demo008(){\n var obj = {\n subObject: {\n subKey: 'subvalue',\n subSubObject: {\n subSubKey: 'subSubValue'\n }\n }\n } ;\n const originalMap = Immutable.fromJS(obj) ;\n const newMap = originalMap.setIn(['subObject','subKey'],'ha ha!') ;\n console.info(newMap.toJS()) ;\n // {subObject:{subKey:'ha ha!', subSubObject:{subSubKey:'subSubValue'}}}\n const newerMap2 = originalMap.setIn(\n ['subObject', 'subSubObject', 'subSubKey'],\n 'ha ha ha!');\n console.info(newerMap2.toJS()) ;\n //// {subObject:{subKey:'subvalue', subSubObject:{subSubKey:'ha ha ha!'}}}\n}", "function createASubmap(mongooseObjects, workspace, mapId, name, responsiblePerson, nodes, impact) {\n let Node = mongooseObjects.Node;\n let WardleyMap = mongooseObjects.WardleyMap;\n return workspace.createAMap({\n name: name,\n responsiblePerson: responsiblePerson\n }, workspace.nowId, /*mark as submap */ true)\n .then(function(newlyCreatedMap) {\n //inSubmapDependencies those deps have to be copied\n //and nodes, of course\n return Node.find({\n _id: {\n $in: nodes\n }\n }).exec().then(function(nodes) {\n let promises = [];\n for (let i = 0; i < nodes.length; i++) {\n let processedNode = nodes[i];\n // for each node that was pushed to a submap\n\n\n //1. set parent map\n processedNode.parentMap = [getId(newlyCreatedMap)];\n\n //2. adjust visibility - steal it from current map\n // if for some reason it is not missing, take the first available one\n let bestVisibility = processedNode.visibility[0];\n for (let j = 0; j < processedNode.visibility.length; j++) {\n let analysedVisibility = processedNode.visibility[j];\n if (getId(analysedVisibility.map).equals(getId(mapId))) {\n bestVisibility = analysedVisibility;\n }\n }\n bestVisibility.map = getId(newlyCreatedMap);\n processedNode.visibility = [bestVisibility];\n\n //3. sort out dependencies, only those presented on a map will stay\n //for now, in the future we may have some cross maps dependencies possible\n processedNode.dependencies = [];\n for (let j = 0; j < impact.inSubmapDependencies.length; j++) {\n let processedDependency = impact.inSubmapDependencies[j];\n if (getId(processedDependency.node).equals(getId(processedNode))) {\n processedNode.dependencies = processedNode.dependencies.concat(processedDependency.deps);\n }\n }\n // 3.a ensure dependencies are visible when they should be\n for (let j = 0; j < processedNode.dependencies.length; j++) {\n processedNode.dependencies[j].visibleOn = [getId(newlyCreatedMap)];\n }\n //4. save, piece of cake\n promises.push(processedNode.save());\n }\n return q.all(promises).then(function() {\n return WardleyMap.findById(getId(newlyCreatedMap)).populate('nodes').exec();\n });\n });\n });\n}", "function entries(map) {\n var array = [];\n for (var k in map) {\n var v = map[k];\n array.push({key: k, values: (v instanceof Array) ? v : entries(v)});\n }\n ;\n return array;\n }", "function getSubset(map, keyList) {\n var subsetMap = {};\n for (var i in map) {\n\n for (var j in keyList) {\n if (keyList[j] == i) {\n subsetMap[i] = map[i];\n break;\n }\n }\n }\n\n return subsetMap;\n }", "function getSubConcepts(kv_mapping) {\n var sub_concepts = [];\n for(var key in kv_mapping) {\n sub_concepts.push(kv_mapping[key]);\n }\n return sub_concepts;\n}", "function buildSelectionMap() {\n _.each($variations, function (index, variant) {\n var mxid = getOptionIdentityMatrix(variant.selected_options);\n $optionsMap[mxid.data.join('')] = { index: index, data: mxid.data };\n $skuMap[variant.sku] = index;\n $hasSubscription = $hasSubscription || variant.subscription_plan;\n });\n }", "function reverseContigMap(contigMap) {\n var ary = [];\n _underscore2['default'].each(contigMap, function (index, name) {\n ary[index] = name;\n });\n return ary;\n}", "function initMappingSublist(form) {\n\t// Definition of sublist area to hold mapping lines before submitting\n\tvar sublist = form.addSubList('custpage_sublist_cncoa_mapping',\t'inlineeditor', displayLbl.mappingLbl);// adds a sublist area to the bottom of the screen\n\n\t// Column definition of sublist\n\t// columns for names\n\tsublist.addField('custpage_is_mapping_selected', 'checkbox',\n\t\t\tdisplayLbl.selected);\n\tsublist.addField('custpage_china_acc_name', 'text', displayLbl.chinaAcntNameLbl)\n\t\t.setDisplayType('disabled');\n\tsublist.addField('custpage_ns_acc', 'text', displayLbl.nsAccountLbl)\n\t\t.setDisplayType('disabled');\n\tsublist.addField('custpage_sbsdry_name', 'text', displayLbl.sbsdryNameLbl)\n\t\t.setDisplayType('disabled');\n\tsublist.addField('custpage_mapping2many', 'checkbox',displayLbl.one2manyChckBoxLbl)\n\t\t.setDisplayType('disabled');\n\tsublist.addField('custpage_deptmnt_name', 'text', displayLbl.departmentNameLbl)\n\t\t.setDisplayType('disabled');\n//\tsublist.addField('custpage_lctn_name', 'text', displayLbl.locationNameLbl)\n//\t\t.setDisplayType('disabled');\n\tsublist.addField('custpage_cls_name', 'text', displayLbl.classNameLbl)\n\t\t.setDisplayType('disabled');\n\n\t\n\t\n\t// columns for ids\n\tsublist.addField('custpage_china_acc', 'text', displayLbl.chinaAcntLbl)\n\t\t.setDisplayType('hidden');\n\tsublist.addField('custpage_ns_acc_id', 'text', displayLbl.accountIdLbl)\n\t\t.setDisplayType('hidden');\n\tsublist.addField('custpage_sbsdry', 'text', displayLbl.sbsdryLbl)\n\t\t.setDisplayType('hidden');\n\tsublist.addField('custpage_deptmnt', 'text', displayLbl.departmentLbl)\n\t\t.setDisplayType('hidden');\n//\tsublist.addField('custpage_lctn', 'text', displayLbl.locationLbl)\n//\t\t.setDisplayType('hidden');\n\tsublist.addField('custpage_cls', 'text', displayLbl.classLbl)\n\t\t.setDisplayType('hidden');\n\n\treturn sublist;\n}", "function makeListFromMap(map){\n var myList = [];\n\n map.forEach(function(value){\n myList.push(value);\n });\n\n return myList;\n}", "function initializeMap(list) {\n var result = {};\n for (var i = 0; i < list.length; i += 2) {\n // Call asFirstClass() here to prevent, for example, a toxic\n // function being used as the toString property of an object\n // literal.\n\tsetPub(result, list[$A$Num(i)], asFirstClass(list[$A$Num(i + 1)]));\n }\n return result;\n }", "function cloneListForMapAndSample(original, excludeDimensions) {\n var allDimensions = original.dimensions;\n var list = new List(zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked\n\n transferProperties(list, original);\n var storage = list._storage = {};\n var originalStorage = original._storage; // Init storage\n\n for (var i = 0; i < allDimensions.length; i++) {\n var dim = allDimensions[i];\n\n if (originalStorage[dim]) {\n // Notice that we do not reset invertedIndicesMap here, becuase\n // there is no scenario of mapping or sampling ordinal dimension.\n if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {\n storage[dim] = cloneDimStore(originalStorage[dim]);\n list._rawExtent[dim] = getInitialExtent();\n list._extent[dim] = null;\n } else {\n // Direct reference for other dimensions\n storage[dim] = originalStorage[dim];\n }\n }\n }\n\n return list;\n}", "function cloneListForMapAndSample(original, excludeDimensions) {\n var allDimensions = original.dimensions;\n var list = new List(zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked\n\n transferProperties(list, original);\n var storage = list._storage = {};\n var originalStorage = original._storage; // Init storage\n\n for (var i = 0; i < allDimensions.length; i++) {\n var dim = allDimensions[i];\n\n if (originalStorage[dim]) {\n // Notice that we do not reset invertedIndicesMap here, becuase\n // there is no scenario of mapping or sampling ordinal dimension.\n if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {\n storage[dim] = cloneDimStore(originalStorage[dim]);\n list._rawExtent[dim] = getInitialExtent();\n list._extent[dim] = null;\n } else {\n // Direct reference for other dimensions\n storage[dim] = originalStorage[dim];\n }\n }\n }\n\n return list;\n}", "function cloneListForMapAndSample(original, excludeDimensions) {\n var allDimensions = original.dimensions;\n var list = new List(zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked\n\n transferProperties(list, original);\n var storage = list._storage = {};\n var originalStorage = original._storage; // Init storage\n\n for (var i = 0; i < allDimensions.length; i++) {\n var dim = allDimensions[i];\n\n if (originalStorage[dim]) {\n // Notice that we do not reset invertedIndicesMap here, becuase\n // there is no scenario of mapping or sampling ordinal dimension.\n if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {\n storage[dim] = cloneDimStore(originalStorage[dim]);\n list._rawExtent[dim] = getInitialExtent();\n list._extent[dim] = null;\n } else {\n // Direct reference for other dimensions\n storage[dim] = originalStorage[dim];\n }\n }\n }\n\n return list;\n}", "function cloneListForMapAndSample(original, excludeDimensions) {\n var allDimensions = original.dimensions;\n var list = new List(zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked\n\n transferProperties(list, original);\n var storage = list._storage = {};\n var originalStorage = original._storage; // Init storage\n\n for (var i = 0; i < allDimensions.length; i++) {\n var dim = allDimensions[i];\n\n if (originalStorage[dim]) {\n // Notice that we do not reset invertedIndicesMap here, becuase\n // there is no scenario of mapping or sampling ordinal dimension.\n if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {\n storage[dim] = cloneDimStore(originalStorage[dim]);\n list._rawExtent[dim] = getInitialExtent();\n list._extent[dim] = null;\n } else {\n // Direct reference for other dimensions\n storage[dim] = originalStorage[dim];\n }\n }\n }\n\n return list;\n}", "function cloneListForMapAndSample(original, excludeDimensions) {\n var allDimensions = original.dimensions;\n var list = new List(zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked\n\n transferProperties(list, original);\n var storage = list._storage = {};\n var originalStorage = original._storage; // Init storage\n\n for (var i = 0; i < allDimensions.length; i++) {\n var dim = allDimensions[i];\n\n if (originalStorage[dim]) {\n // Notice that we do not reset invertedIndicesMap here, becuase\n // there is no scenario of mapping or sampling ordinal dimension.\n if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {\n storage[dim] = cloneDimStore(originalStorage[dim]);\n list._rawExtent[dim] = getInitialExtent();\n list._extent[dim] = null;\n } else {\n // Direct reference for other dimensions\n storage[dim] = originalStorage[dim];\n }\n }\n }\n\n return list;\n}", "map(predicate) {\n const tuples = this.toArray().map(([component, value]) => {\n const newValue = predicate(value, component);\n return [component.id.toString(), [component, newValue]];\n });\n return new ComponentMap(new Map(tuples));\n }", "get mapIn() {\n\t return _objectSpread({}, sanitizeExternalDrops(this.props.mapIn), {\n\t [this.rootKey]: internalMapIn\n\t });\n\t }", "_get2Groups(map) {\n let group1 = [],\n group2 = [];\n\n let keys = [...map.keys()];\n keys.forEach(k => map.get(k) == 1 ? group1.push(k) : group2.push(k))\n return [group1, group2];\n }", "function createNestedMap(base, names, value) {\n let currentBase = base;\n\n for(let name of names) {\n\n // Does key exist on map?\n if (!currentBase.has(name)){\n // Create key\n currentBase.set(name, new Map());\n }\n\n // Update the currentBase\n currentBase = currentBase.get(name);\n\n }\n\n // Set the value in the final position\n let finalName = names[names.length - 1];\n currentBase.set(finalName, value);\n\n}", "function rebuildMapBounds() {\n bounds = new google.maps.LatLngBounds();\n for (var person in people) {\n bounds.extend(people[person].marker.getPosition());\n }\n }", "function contents(map, tight) {\n var minDepth = Infinity\n var index = -1\n var length = map.length\n var table\n\n // Find minimum depth.\n while (++index < length) {\n if (map[index].depth < minDepth) {\n minDepth = map[index].depth\n }\n }\n\n // Normalize depth.\n index = -1\n\n while (++index < length) {\n map[index].depth -= minDepth - 1\n }\n\n // Construct the main list.\n table = list()\n\n // Add TOC to list.\n index = -1\n\n while (++index < length) {\n insert(map[index], table, tight)\n }\n\n return table\n}", "function pagesMap2Array(input) {\n\t\t\tvar output = Object.keys(input).map(function(key) {\n\t\t\t\tvar page = input[key];\n\t\t\t\t//add the key to the array for reference\n\t\t\t\t//page[\"id\"] = key;\n\t\t\t\t//Recursive call for nested pages\n\t\t\t\tif (page.pages) {\n\t\t\t\t\tpage.pages = pagesMap2Array(page.pages);\n\t\t\t\t}\n\t\t\t\treturn input[key];\n\t\t\t});\n\t\t\treturn output;\n\t\t}", "function reverseContigMap(contigMap: {[key:string]: number}): Array<string> {\n var ary = [];\n _.each(contigMap, (index, name) => {\n ary[index] = name;\n });\n return ary;\n}", "function buildMapFromArray(myMap) {\r\n var num = myMap.length;\r\n// alert(num+\" \"+myMap+\" \"+myMap[0][1]);\r\n \r\n var ret = new Array();\r\n for (var i = 0; i < num; i++) {\r\n var city = new Object();\r\n city.index = i;\r\n city.x = cityRad+myMap[i][0];\r\n city.y = cityRad+myMap[i][1];\r\n ret.push(city);\r\n }\r\n return ret;\r\n}", "function demo014(){\n var obj = [{v: 0}, {v: 1}, {v: 1}, {v: 0}, {v: 1}] ;\n const data = Immutable.fromJS(obj) ;\n data.groupBy(x=>x.get('v')) ;\n //// Map {0: [{v: 0},{v: 0}], 1: [{v: 1},{v: 1},{v: 1}]}\n}", "groupBy(toKey) {\n const map = new Map();\n for (const value of this) {\n const key = toKey(value);\n map_1.multiMapAdd(map, key, value);\n }\n return map;\n }", "flatten(){\n\n let scope = this;\n\n const result = new Map();\n const appliedValves = new Map();\n\n for(const [key, value] of scope._dataMap){\n result.set(key, value);\n }\n\n while(scope = scope._parent){\n\n const dataList = scope._dataMap;\n const valves = scope._valveMap;\n const mirrors = scope._mirrorMap;\n\n if(!dataList.size)\n continue;\n\n // further restrict valves with each new scope\n\n if(valves.size){\n if(appliedValves.size) {\n for (const key of appliedValves.keys()) {\n if(!valves.has(key))\n appliedValves.delete(key);\n }\n } else {\n for (const [key, value] of valves.entries()) {\n appliedValves.set(key, value);\n }\n }\n }\n\n const possibles = appliedValves.size ? appliedValves : dataList;\n\n for(const key of possibles.keys()) {\n if (!result.has(key)) {\n\n const data = mirrors.get(key) || dataList.get(key);\n if (data)\n result.set(key, data);\n }\n }\n\n }\n\n return result;\n\n }", "function cloneMap(map) {\n var clone = new Map();\n map.forEach(function (value, key) {\n clone.set(key, value);\n });\n return clone;\n }", "mapGenerate() {\n for (let i = 0; i < this.ySize; i++) {\n this.map[i] = [];\n for (let j = 0; j < this.xSize; j++) {\n let mapValue = this.empty;\n this.map[i].push(mapValue);\n }\n }\n }", "function flattenTreemap(rawtreemap) {\n var flattreemap = [];\n var i, j;\n\n for (i = 0; i < rawtreemap.length; i++) {\n for (j = 0; j < rawtreemap[i].length; j++) {\n flattreemap.push(rawtreemap[i][j]);\n }\n }\n\n return flattreemap;\n } // squarify - as per the Bruls paper" ]
[ "0.5581962", "0.5565545", "0.5322298", "0.53130573", "0.5299694", "0.520975", "0.51403564", "0.50976515", "0.50889266", "0.5065186", "0.5063049", "0.5063049", "0.5063049", "0.5063049", "0.5063049", "0.5055614", "0.50455725", "0.5003599", "0.50008327", "0.49989545", "0.49857882", "0.49398547", "0.4938279", "0.49173927", "0.49122345", "0.4909435", "0.49058756", "0.48876363", "0.4880237", "0.48790023" ]
0.5777071
0
II. handle the gateway proxy response (called in http.request and https.request for proxy_clientReq request in I. above) define the gateway proxy_clientReq's responsehandler callback method Note: proxy_Res parameter is an instance of type http.IncomingMessage
function processRes(proxy_Res) { logger.trace(req.transactionId+'-Handling proxy response received, for proxy request sent with options: ', options); var proxyResponseStatusCode = proxy_Res.statusCode; logger.trace(req.transactionId+'-Proxy client request returned proxy response statusCode: ', proxyResponseStatusCode); var responseAttachmentAudit; var isResAuditInitialized = false; // get the file size from the http 'Content-Length' header received in proxy client response var uploadedSize = 0; var fileSizeStr = proxy_Res.headers['content-length']; var fileSize = 0; if (!_.isUndefined(fileSizeStr)) { fileSize = parseInt(fileSizeStr); } // if file buffering set for this configured route if (route.buffer) { try { // create write stream named 'tmpFile' to the temporary file in tmpdir // fs.createWriteStream() returns a new stream.Writable object var tmpFile = fs.createWriteStream(tmpPath); // where 'tmpFile' is a 'stream.Writable' instance, // if a tmpFile.write(chunk) call returns false, then the 'drain' event then emitted // will indicate when it is appropriate to begin writing more data to the stream. tmpFile.on('drain', function () { // begin writing more data to the stream proxy_Res.resume(); }); } catch (e) { logger.error(req.transactionId+'-tmpFile write stream creation section threw an error..., re-throwing...'); throw e; } } // handle proxy client response body when present proxy_Res.on('data', function (chunk) { logger.trace(req.transactionId+'-Response data is being written to proxy client, where chunk length (in bytes): ', chunk.length); //logger.trace('Data:', chunk.toString('utf8')); // first time - initialize and perform unstructured audit logging of the proxy response body file if config set if (!isResAuditInitialized && route.audit && route.audit.unstructured && route.audit.unstructured.auditResponse) { var key = req.transactionId + '-RES'; res.key = key; logger.trace('Unstructured response auditing with transactionId-based key: ', key); // initialize and write the first text logger.trace(req.transactionId+'-Initializing unstructured response body audit'); responseAttachmentAudit = initializeAudit(key, route.audit.unstructured.options); var type = getContentType(proxy_Res); var ext = getExtension(type); var beforeAttachmentText = getBeforeAttachment(key, key + '.' + ext, type); logger.trace(req.transactionId+'-Writing unstructured response before attachment text');//: ", beforeAttachmentText); responseAttachmentAudit.write(beforeAttachmentText, 'binary'); isResAuditInitialized = true; } else { logger.trace(req.transactionId+'-There is NO unstructured response auditing for this response'); } // continue the current unstructured audit logging of the proxy response body file if (!_.isUndefined(responseAttachmentAudit)) { logger.trace(req.transactionId+'-Writing unstructured response audit chunk... '); responseAttachmentAudit.write(chunk, 'binary'); } // keep track of the actual file size in bytes received for both // the optional file size verification and optional file // stream buffering when configured uploadedSize += chunk.length; // if file buffering set for this configured route if (route.buffer) { uploadProgress = (uploadedSize / fileSize) * 100; logger.trace(req.transactionId+'- '+Math.round(uploadProgress) + "%" + " downloaded\n"); // write some data (i.e. 'chunk') to the underlying system // the return value 'bufferStore' indicates if you // should continue writing right now or not: if the data had // to be buffered internally, then 'tmpFile.write()' will return false, else true. // Note: this return value is strictly advisory: it MAY continue // to write, even if it returns false; however, writes will be buffered // in memory, so it is best not to do this excessively. Instead, wait // for the 'drain' event (defined above) before writing more data. logger.trace(req.transactionId+'-Writing proxy response stream received to buffer... '); var bufferStore = tmpFile.write(chunk); if (bufferStore == false) { // pause writing to the stream to wait for internal memory buffering, // until the 'drain' event is emmitted to resume writing to the stream logger.trace(req.transactionId+'-Proxy response stream\'s buffer writing paused to wait for internal memory buffering... '); proxy_Res.pause(); } } else { // write the binary chunk of the received file without buffering, i.e. directly // to the gateway response logger.trace(req.transactionId+'-Proxy response stream writing directly... '); res.write(chunk, 'binary'); } }); // end handling of proxy client response body (when present) proxy_Res.on('end', function (data) { // stop unstructured audit logging of proxy response body if happening (if initialized) if (isResAuditInitialized && !_.isUndefined(responseAttachmentAudit)) { var endAttachmentText = getEndAttachment(res.key); logger.trace(req.transactionId+'-End unstructured response chunk write to Audit');//:', endAttachmentText); responseAttachmentAudit.end(endAttachmentText); } logger.trace(req.transactionId+'-End response chunk write to client, returning gateway response from proxy client'); var errState = false; // if file length verification is set for this configured route if (route.strictLength) { logger.trace(req.transactionId+'-Received file length comparison : Received HTTP header Content-Length value:' + fileSize + ' bytes, received actual file UploadedSize:' + uploadedSize + ' bytes'); // if HTTP header Content-Length value does not match the actual file size received if (fileSize != uploadedSize) { // return an error gateway response, set errState to true logger.error(req.transactionId+'-HTTP Header Content-Length does not match received file size, Content-Length:' + fileSize + ' bytes; Uploaded Size: ' + uploadedSize + ' bytes'); var resBodyTxt = 'HTTP 1.1 500/Internal Server Error: HTTP Header Content-Length value does not match received file size.'; var resLength = resBodyTxt.length; res.writeHead(500, 'HTTP Header Content-Length does not match received file size, Content-Length:' + fileSize + ' bytes; Uploaded Size: ' + uploadedSize + ' bytes', { 'Content-Type' : 'text/plain', 'Content-Length' : resLength }); res.end(resBodyTxt); resDateTime = moment().format(); errState = true; } } // if file buffering set for this configured route if (route.buffer) { if (!errState) { // write the buffered file received to the gateway response stream, // now that buffering has completed without error, and // pass through the proxy response headers received logger.trace(req.transactionId+'-Writing gateway response stream from buffer... '); res.writeHead(proxy_Res.statusCode, proxy_Res.headers); try { fs.createReadStream(tmpPath).pipe(res); } catch (e) { logger.error(req.transactionId+'-fs.createReadStream call threw an error..., re-throwing...'); throw e; } } // release the tmp file in the tmp directory fs.unlink(tmpPath, function (err) { if(err) { logger.error(req.transactionId+'-Could not unlink file:' + tmpPath + ", where error:",err, err.stack); } }); } else { // no file buffering // if no errors occurred if (!errState) { // mark the gateway response as complete logger.trace(req.transactionId+'-Marking gateway response as finished.'); res.end(); resDateTime = moment().format(); } } // perform gateway request, gateway response, proxy response structured audit logging if config set if (route.audit && route.audit.structured && route.audit.structured.auditRequestResponse) { logger.trace(req.transactionId+'-Structured auditing gateway request and response (and proxy client\'s proxy_Res)');//, req, res); audit(route.audit.structured.options, req, res, proxy_Res, reqDateTime, resDateTime, '', function(auditRes) {}); } }); // handle error experienced when processing proxy client response body (when present) proxy_Res.on('error', function (err) { logger.error(req.transactionId+'-Error emitted from proxy client response processing, where error: ', err, err.stack); logger.trace(req.transactionId+'-Returning 500/Internal Server Error gateway response due to proxy client response processing error'); var resBodyTxt = 'HTTP 1.1 500/Internal Server Error'; var resLength = resBodyTxt.length; res.writeHead(500, 'Internal Server Error', { 'Content-Type' : 'text/plain', 'Content-Length' : resLength }); res.end(resBodyTxt); resDateTime = moment().format(); // stop unstructured audit logging of proxy response attachment received if occurring if (isResAuditInitialized && !_.isUndefined(responseAttachmentAudit)) { logger.trace(req.transactionId+'-End unstructured response chunk write to audit service, where error:', err); //logger.trace('End response chunk write to Audit');//: ', endAttachmentText); var endAttachmentText = getEndAttachment(res.key); responseAttachmentAudit.end(endAttachmentText); } // perform gateway request, gateway response, proxy response, and proxy response processing error structured audit logging if config set if (route.audit && route.audit.structured && route.audit.structured.auditRequestResponse) { logger.trace(req.transactionId+'-Structured auditing gateway request and response (and proxy client\'s proxy_Res, and proxy client\'s response processing error)');//, req, res); audit(route.audit.structured.options, req, res, proxy_Res, reqDateTime, resDateTime, err, function(auditRes) {}); } // if file buffering set for this configured route if (route.buffer) { // release the tmp file in the tmp directory fs.unlink(tmpPath, function (er) { if(er) { logger.error(req.transactionId+'-Could not unlink file:' + tmpPath + ', where error: ',er, er.stack); } }); } }); // if file buffering set for this configured route if (route.buffer) { // Allow empty config } else { // no file buffering // write the gateway response headers using the proxy response headers logger.trace(req.transactionId+'-Writing gateway response (no-response-file-buffering) headers...'); if (!res.headersSent) { res.writeHead(proxy_Res.statusCode, proxy_Res.headers); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function proxy_reply(res, code, headers, ret) {\n\t\tif (headers) {\n\t\t\tres.set(t.deployer.copy_headers(headers));\t\t\t\t\t// copy headers for our response\n\t\t}\n\t\tif (!ret) {\n\t\t\treturn res.status(code).send();\n\t\t} else {\n\t\t\treturn res.status(code).send(ret);\n\t\t}\n\t}", "function Proxy () {\n log.info('Proxy constructor');\n var self = this;\n\n this.proxy = httpProxy.createProxyServer({});\n this.proxy.on('error', function (err, req/*, proxiedRes */) {\n var res = req.res;\n var logData = {\n tx: true,\n err: err,\n req: req\n };\n log.error(logData, 'proxy.on error');\n /**\n * we need to keep the didError logic. sometimes (not sure why) but we try to proxy the same\n * request twice (in some network cases) and navi will crash saying you can't send on a request\n * that is already ended\n */\n if (!req.didError) {\n req.didError = true;\n var errorUrl = errorPage.generateErrorUrl('unresponsive', {\n shortHash: req.shortHash,\n elasticUrl: req.elasticUrl\n });\n var targetHost = getHostAndAugmentReq(req, errorUrl);\n log.trace(put({\n targetHost: targetHost,\n errorUrl: errorUrl\n }, logData), 'proxy.on error !req.didError');\n self.proxy.web(req, res, { target: targetHost });\n } else {\n log.trace(logData, 'proxy.on error req.didError');\n }\n });\n\n /**\n * Listen to proxy events for timing logs\n */\n this.proxy.on('proxyReq', function () {\n log.trace({\n tx: true\n }, 'proxy.on proxyReq');\n });\n\n this.proxy.on('proxyRes', function (proxyRes, req, proxiedRes) {\n var res = req.res;\n var targetInstanceName = keypather.get(req, 'targetInstance.attrs.name');\n log.trace({\n tx: true,\n targetInstanceName: targetInstanceName,\n res: res\n }, 'proxy.on proxyRes');\n self._addHeadersToRes(req, proxyRes, targetInstanceName);\n self._streamRes(proxyRes, proxiedRes, res, keypather.get(req, 'naviEntry.redirectEnabled'));\n });\n}", "_responseStrategy(data) {\n var _a, _b, _c, _d, _e;\n try {\n const documentElement = this._parser.parseFromString((0, iconv_lite_1.decode)(data, dbgp_1.ENCODING), 'application/xml').documentElement;\n const isSuccessful = documentElement.getAttribute('success') === '1';\n const error = documentElement.firstChild;\n if (isSuccessful && documentElement.nodeName === 'proxyinit') {\n this._isRegistered = true;\n this.emit('log_response', this.msgs.registerSuccess);\n (_a = this._resolveFn) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n else if (isSuccessful && documentElement.nodeName === 'proxystop') {\n this._isRegistered = false;\n this.emit('log_response', this.msgs.deregisterSuccess);\n (_b = this._resolveFn) === null || _b === void 0 ? void 0 : _b.call(this);\n }\n else if (error && error.nodeName === 'error' && error.firstChild && error.firstChild.textContent) {\n this._socket.emit('error', error.firstChild.textContent);\n (_c = this._rejectFn) === null || _c === void 0 ? void 0 : _c.call(this, new Error(error.firstChild.textContent));\n }\n else {\n this._socket.emit('error', this.msgs.defaultError);\n (_d = this._rejectFn) === null || _d === void 0 ? void 0 : _d.call(this, new Error(this.msgs.defaultError));\n }\n }\n catch (error) {\n (_e = this._rejectFn) === null || _e === void 0 ? void 0 : _e.call(this, new Error(`Proxy read error ${error}`));\n }\n }", "function proxy(client_req, client_res) {\n client_res.setHeader('Access-Control-Allow-Origin', '*') // Avoid CORS issues\n const options = {\n hostname: CONFIG.FES_HOST,\n port: CONFIG.FES_PORT,\n path: client_req.url,\n method: client_req.method,\n headers: client_req.headers\n }\n console.log(`Proxy: ${options.hostname}:${options.port}${options.path}`)\n const proxy = http.request(options, (res) => {\n client_res.writeHead(res.statusCode, res.headers)\n res.pipe(client_res, {\n end: true\n })\n })\n client_req.pipe(proxy, {\n end: true\n })\n client_req.on('error', (error) => {\n console.log(`ERROR: ${client_req.url}: ${error.message}`)\n })\n proxy.on('error', (error) => {\n console.log(`ERROR: ${client_req.url}: ${error.message}`)\n })\n proxy.on('finish', () => {\n console.log(`End: ${client_req.url}`);\n })\n}", "function respond (next) {\n return function sendResult (error, proxyObj) {\n if (error) { return next(error); }\n\n // TESTING HELPER ONLY\n if (proxyObj.options.shortCircuit) {\n return proxyObj.res.send({\n result: 'proxy-express set to short circuit. If this is not expected, please check your config'\n });\n }\n\n let proxyError = proxyObjErrors(proxyObj);\n if (proxyError) {\n return next(new Error(proxyError));\n } else if (!(proxyObj.result && proxyObj.result.response)) {\n return next(new Error('Proxy to ' + proxyObj.reqOpts.url + ' failed for an unkown reason'));\n } else {\n proxyObj.res.status(proxyObj.result.response.statusCode || 400).send(proxyObj.result.body);\n }\n };\n}", "function pepResponse(req, res) {\n const headers = req.headers;\n headers['x-forwarded-for'] = getClientIp(req);\n\n got(PROXY_URL + req.url, {\n method: req.method,\n headers,\n body: req.body,\n allowGetBody: true,\n throwHttpErrors: false,\n retry: 0\n })\n .then((response) => {\n debug(req.user ? 'Permitted.' : 'Public path.');\n res.statusCode = response.statusCode;\n res.headers = response.headers;\n if (response.headers['content-type']){\n res.type(response.headers['content-type'])\n }\n return response.body ? res.send(response.body) : res.send();\n })\n .catch((error) => {\n return internalError(res, error, 'Proxy');\n });\n}", "function handleResponse(apiResponse) {\n // Copy the status code and headers from our proxy response.\n res.statusCode = apiResponse.statusCode;\n for (let i = 0; i < apiResponse.rawHeaders.length; i += 2) {\n res.setHeader(apiResponse.rawHeaders[i], apiResponse.rawHeaders[i + 1]);\n }\n\n // Send the body to our actual response.\n apiResponse.pipe(res);\n }", "function onRequest(c_req, c_res) {\n \n var parsedURL = url.parse(c_req.url);\n //console.log(\"parsed\")\n var reqOptions = {\n host: options.server,\n path: parsedURL.path,\n port: options.port,\n localport: options.local_port,\n //header: {}\n };\n console.log('Method used: ' + c_req.method);\n \n if (c_req.method == 'GET') { // When the request method is 'GET'\n \n console.log('Path used: ' + reqOptions.path);\n\n var webProxyServer = http.request(reqOptions, function (res) { // A proxy to send a request to the target server\n console.log('Requesting from: ' + reqOptions.host + reqOptions.path);\n \n if (res.statusCode >= 300 && res.statusCode <= 399) { \n console.log('300 Level Status Code.');\n c_res.end('Redirect error: ' + res.statusCode); \n } else { \n console.log('Returning response: ' + res.statusCode); // Pipe the whole server response to the client response\n res.pipe(c_res, { end: true }); \n }\n });\n // pipe the proxy to the client request\n c_req.pipe(webProxyServer, { end: true });\n console.log('Piping content...');\n } else {\n // Any request method other than 'GET' will be rejected\n c_res.end('Not \\'GET\\' method.');\n console.log('Not \\'GET\\' method requested.');\n }\n}", "function responseHandler(srcResponse, numer)\n{\n camz[numer].headers = srcResponse.headers;\n srcResponse.on('data', function(chunk) {dataHandler(chunk, numer)});\n}", "function proxy(req, res) {\n var queryString = req.originalUrl.split('?')[1];\n var path = '/v1' + req.path + (queryString ? '?' + queryString : '');\n console.log(\n req.method + ' ' + req.path + ' proxied to ' +\n options.mlHost + ':' + options.mlHttpPort + path);\n var mlReq = http.request({\n hostname: options.mlHost,\n port: options.mlHttpPort,\n method: req.method,\n path: path,\n headers: req.headers,\n auth: getAuth(options, req.session)\n }, function(response) {\n\n res.statusCode = response.statusCode;\n\n // [GJo] (#67) forward all headers from MarkLogic\n for (var header in response.headers) {\n res.header(header, response.headers[header]);\n }\n\n response.on('data', function(chunk) {\n res.write(chunk);\n });\n response.on('end', function() {\n res.end();\n });\n });\n\n if (req.body !== undefined) {\n mlReq.write(JSON.stringify(req.body));\n mlReq.end();\n }\n\n mlReq.on('error', function(e) {\n console.log('Problem with request: ' + e.message);\n });\n}", "function messageHandler(req, res) {\n let agent = new WebhookClient({'request': req, 'response': res});\n console.log(\"ORIGINAL REQUEST: \" + agent.originalRequest);\n agent.handleRequest(intentMap);\n}", "onRequest(request, reply) {\n const { events } = this;\n\n events.emit('onRequest', request, reply);\n\n reply.from(request.url, {\n onResponse: (request, reply, res) => {\n events.emit('onProxyResponse', request, reply, res);\n reply.send(res);\n },\n });\n }", "function do_proxy(req, res) {\n\t\treq.path2use = req.path2use.replace(/\\$iid/gi, (ev.CRN.instance_id || 'iid-not-set'));\t// replace placeholder iid with the real iid\n\t\tlogger.info('[deployer apis] - attempting a deployer proxy request', req.method, t.misc.get_host(ev.DEPLOYER_URL), req.path2use);\n\n\t\tconst opts = {\n\t\t\tmethod: req.method,\n\t\t\tbaseUrl: encodeURI(t.misc.format_url(ev.DEPLOYER_URL)),\t\t\t\t\t\t\t\t// url to deployer\n\t\t\turl: encodeURI(req.path2use),\n\t\t\tbody: req.body ? JSON.stringify(req.body) : null,\t\t\t\t\t\t\t\t\t// body for deployer\n\t\t\theaders: t.deployer.copy_headers(req.headers),\n\t\t\ttimeout: ev.DEPLOYER_TIMEOUT\n\t\t};\n\n\t\tt.request(opts, (err, resp) => {\n\t\t\tlet ret = resp ? resp.body : null;\n\t\t\tlet dep_resp_headers = resp ? resp.headers : null;\n\t\t\tlet code = t.ot_misc.get_code(resp);\n\t\t\tif (err) {\n\t\t\t\tlogger.error('[deployer apis] - [2] unable to contact deployer', err);\n\t\t\t\tif (err.toString().indexOf('TIMEDOUT') >= 0) {\n\t\t\t\t\tcode = 408;\n\t\t\t\t\tlogger.error('[deployer apis] - [1] timeout was:', opts.timeout);\n\t\t\t\t}\n\t\t\t\treturn proxy_reply(res, code, dep_resp_headers, err);\n\t\t\t} else {\n\t\t\t\tif (t.ot_misc.is_error_code(code)) {\n\t\t\t\t\tlogger.error('[deployer apis] - [2] deployer responded with error code', code, ret);\n\t\t\t\t\treturn proxy_reply(res, code, dep_resp_headers, ret);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.info('[deployer apis] - [2] successful deployer response', code);\n\n\t\t\t\t\t// running the deployer response through parse/stringify will decode unicode characters\n\t\t\t\t\t// (seen in the ldap.URL field of a \"/type/ca\" response)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tret = JSON.stringify(JSON.parse(ret));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// ignore parsing errors\n\t\t\t\t\t}\n\n\t\t\t\t\t// redact CA enroll id/secret data if not a manager\n\t\t\t\t\tconst lc_authorized_actions = t.middleware.getActions(req);\n\t\t\t\t\tif (req.path.includes('/type/ca/') && (!lc_authorized_actions || !lc_authorized_actions.includes(ev.STR.C_MANAGE_ACTION))) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst obj = JSON.parse(ret);\n\t\t\t\t\t\t\t// only redact the inner registry fields, else other (non-sensitive) fields will get redacted\n\t\t\t\t\t\t\tobj.configs.ca.registry = t.comp_fmt.redact_enroll_details(obj.configs.ca.registry);\n\t\t\t\t\t\t\tobj.configs.tlsca.registry = t.comp_fmt.redact_enroll_details(obj.configs.tlsca.registry);\n\t\t\t\t\t\t\tret = JSON.stringify(obj);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\t// ignore parsing or dot nav errors\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// store response in cache\n\t\t\t\t\tif (ev.PROXY_CACHE_ENABLED === true && req._cache_this_req === true) {\n\t\t\t\t\t\tconst data2cache = {\n\t\t\t\t\t\t\tcode: code,\n\t\t\t\t\t\t\theaders: dep_resp_headers,\n\t\t\t\t\t\t\tdata: ret,\n\t\t\t\t\t\t\tkey_src: req._key_src,\n\t\t\t\t\t\t\tcached_ts: Date.now(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tt.proxy_cache.set(req._key, data2cache, 10 * 60);\t// expiration is in sec\n\t\t\t\t\t}\n\t\t\t\t\treturn proxy_reply(res, code, dep_resp_headers, ret);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function warehouse_proxy(req, reply){\n //logger.request(req);\n\n reception.emit('digger:warehouse', req, reply);\n }", "function onResponse(ctx, callback)\n{\n const resp_headers = ctx.serverToProxyResponse.headers;\n const req_headers = ctx.clientToProxyRequest.headers;\n\n // !!!! todo: for now we remove the csp header\n // delete resp_headers['content-security-policy'];\n\n /* The Expect-CT header allows sites to opt in to reporting\n * and/or enforcement of Certificate Transparency\n * requirements, which prevents the use of misissued\n * certificates for that site from going unnoticed.\n */\n delete resp_headers['expect-ct'];\n\n\n // note: headers converted to lowercase by nodejs\n const is_html = 'content-type' in resp_headers &&\n resp_headers['content-type'].startsWith('text/html');\n const is_xhr = ('x-requested-with' in req_headers);\n const is_cors = ('origin' in req_headers);\n\n ctx.must_inject = (ENABLE_INJECTION && is_html && !ctx.no_inject &&\n !is_xhr && !is_cors);\n\n\n if (ctx.must_inject)\n {\n delete resp_headers['content-length'];\n const csp = resp_headers['content-security-policy'];\n const default_csp = csp;\n\n delete resp_headers['etag'];\n delete resp_headers['last-modified'];\n\n if (csp){\n const policy = new Policy(csp);\n const script_src = policy.get('script-src');\n const frm_src = policy.get('frame-src');\n const default_src = policy.get('default-src');\n\n // inject script as inline content\n if (SHARED_STORE_IFRAME_URL.length){\n const ifr_url = new URL(SHARED_STORE_IFRAME_URL);\n\n if (!frm_src && default_src){\n policy.set('frame-src', default_src);\n }\n policy.add('frame-src', ifr_url.origin);\n }\n\n let script_inject_data;\n if (INJECTION_METHOD === 'url'){\n const url = new URL(INJECTED_SCRIPT_URL);\n script_inject_data = url.origin;\n }else{\n //\n const sha256 = getInjectedHash();\n script_inject_data = \"'\"+sha256+\"'\";\n }\n\n\n if (!script_src && default_src){\n policy.set('script-src', default_src);\n }\n policy.add('script-src', script_inject_data);\n\n let modified_csp = policy.toString();\n console.log(\"\\n\\n### orig csp: %s\", default_csp);\n console.log(\"### modified csp: %s\", modified_csp);\n resp_headers['content-security-policy'] = modified_csp;\n }//end if csp\n }// end if must_inject\n return callback();\n}", "function proxyError(res, message){\n\tres.send(\"Proxy error \" + (message || ''),500);\n}", "userResDecorator(proxyRes, proxyResData, userReq, userRes) {\n // console.log(userRes);\n // return proxyResData;\n try {\n // get, parse, and transform the data if possible\n\n const dataString = proxyResData.toString('utf8');\n let data;\n try {\n // try for json data\n data = JSON.parse(proxyResData.toString('utf8'));\n } catch {\n console.log(\"couldn't parse data\");\n // otherwise just use the stringified data\n data = proxyResData.toString('utf8');\n }\n const modified = interceptor(data, userReq, userRes);\n // return transformed data to client\n return JSON.stringify(modified);\n } catch (e) {\n console.log(\"couldn't parse data, again! recieved error\", e);\n // on error, pass the data forward\n return proxyResData;\n }\n }", "handleSocks4FinalHandshakeResponse() {\n const data = this._receiveBuffer.get(8);\n if (data[1] !== constants_1.Socks4Response.Granted) {\n this._closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);\n }\n else {\n // Bind response\n if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.bind) {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const remoteHost = {\n port: buff.readUInt16BE(),\n host: ip.fromLong(buff.readUInt32BE())\n };\n // If host is 0.0.0.0, set to proxy host.\n if (remoteHost.host === '0.0.0.0') {\n remoteHost.host = this._options.proxy.ipaddress;\n }\n this.state = constants_1.SocksClientState.BoundWaitingForConnection;\n this.emit('bound', { socket: this._socket, remoteHost });\n // Connect response\n }\n else {\n this.state = constants_1.SocksClientState.Established;\n this.removeInternalSocketHandlers();\n this.emit('established', { socket: this._socket });\n }\n }\n }", "static handleRequest(virtualRequest, request, response, loggingFunction, fallbackResponder) {\n return __awaiter(this, void 0, void 0, function* () {\n const proxy = yield this.getProxy(virtualRequest, request, loggingFunction, fallbackResponder);\n if (!(proxy instanceof OutgoingRequestHandler)) {\n throw new Error('unable to handle request: no matching handler found');\n }\n return proxy.handleRequestConcrete(virtualRequest, request, response);\n });\n }", "responseHandler(data) {\n if(this.build) {\n if(data.length + this.curResponse.accumulated > this.curResponse.size) {\n throw new Error('Ending response length did match reported size');\n } else {\n this.curResponse.data = Buffer.concat([this.curResponse.data, data]);\n this.curResponse.accumulated += data.length;\n }\n\n if(this.curResponse.accumulated === this.curResponse.size) {\n this.build = false;\n let correlationMethod = this.getCorrelation(this.curResponse.header.correlationId);\n correlationMethod(null, this.curResponse.data);\n }\n return;\n }\n\n var header, offset, size;\n\n [size, offset] = types.decodeInt32(data, 0);\n\n [header, offset] = parser.decode(Header.response, data, offset);\n\n if(this.requestCount < header.correlationId) {\n return this.onError(new Error('Unknown correlation id received from broker'));\n }\n\n let bufLength = data.length - types.INT32_SIZE;\n if(size !== bufLength) {\n this.build = true;\n this.curResponse = {\n header: header,\n size: size,\n accumulated: bufLength,\n data: data.slice(offset)\n };\n } else {\n this.build = false;\n let correlationMethod = this.getCorrelation(header.correlationId);\n correlationMethod(null, data.slice(offset));\n }\n }", "on_REPLY (e, callback) {\n\n\t\tif (e.target.status >= 200 && e.target.status < 400) {\n\t\t\t\n\t\t\tvar response = e.target.response;\n\n\t\t\t// convert to object if request is a JSON string\n\t\t\tif (typeof response === 'string') {\n\t\t\t\tresponse = JSON.parse(e.target.response);\n\t\t\t}\n\n\t\t\t// Go ahead and pass the response to the caller\n\t\t\tcallback(response);\n\n\t\t} else {\n\t\t\t\n\t\t\tconsole.log('Error: There was an error loading the JSON. -- Status:', e.target.status);\n\t\t}\n\t}", "function onresponse (res) {\n var code = res.statusCode;\n\n // assign a Date to this response for the \"Cache-Control\" delta calculation\n res.date = new Date();\n res.parsed = parsed;\n\n debug('got %o response status code', code);\n\n // any 2xx response is a \"success\" code\n var type = (code / 100 | 0);\n\n // check for a 3xx \"redirect\" status code\n var location = res.headers.location;\n if (3 == type && location) {\n if (!opts.redirects) opts.redirects = [];\n var redirects = opts.redirects;\n\n if (redirects.length < maxRedirects) {\n debug('got a \"redirect\" status code with Location: %o', location);\n\n // flush this response - we're not going to use it\n res.resume();\n\n // hang on to this Response object for the \"redirects\" Array\n redirects.push(res);\n\n var newUri = url.resolve(parsed, location);\n debug('resolved redirect URL: %o', newUri);\n\n var left = maxRedirects - redirects.length;\n debug('%o more redirects allowed after this one', left);\n\n // check if redirecting to a different protocol\n var parsedUrl = url.parse(newUri);\n if (parsedUrl.protocol !== parsed.protocol) {\n opts.http = parsedUrl.protocol === 'https:' ? https : undefined;\n }\n\n return get(parsedUrl, opts, fn);\n }\n }\n\n // if we didn't get a 2xx \"success\" status code, then create an Error object\n if (2 != type) {\n var err;\n if (304 == code) {\n err = new NotModifiedError();\n } else if (404 == code) {\n err = new NotFoundError();\n } else {\n // other HTTP-level error\n var message = http.STATUS_CODES[code];\n err = new Error(message);\n err.statusCode = code;\n err.code = code;\n }\n\n res.resume();\n return fn(err);\n }\n\n if (opts.redirects) {\n // store a reference to the \"redirects\" Array on the Response object so that\n // they can be inspected during a subsequent call to GET the same URI\n res.redirects = opts.redirects;\n }\n\n fn(null, res);\n }", "function requestRemote(requestOptions, req, res, proxy) {\n\n var headers;\n var body;\n var remoteRequest = http.request(requestOptions, function(remoteResponse) {\n remoteResponse.headers['proxy-agent'] = 'Proxy Agent';\n headers = res._header;\n // write out headers to handle redirects\n res.writeHead(remoteResponse.statusCode, '', remoteResponse.headers);\n // change resonse here\n remoteResponse.pipe(res);\n // send the connection\n res.pipe(remoteResponse);\n });\n remoteRequest.on('error', function(e) {\n console.log('error in request: failed to fetch');\n res.writeHead(502, 'Proxy fetch failed');\n res.end();\n remoteRequest.end();\n });\n\n req.pipe(remoteRequest);// to the server.\n res.on('close', function() {\n remoteRequest.abort();\n });\n\n }", "callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n const servername = opts.servername || opts.host;\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket({ writable: false });\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }", "callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n const servername = opts.servername || opts.host;\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket({ writable: false });\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }", "function proxyReq (proxyObj, callback) {\n let proxyError = proxyObjErrors(proxyObj);\n if (proxyError) { return callback(new Error(proxyError)); }\n\n if (proxyObj.options.log) { logReqOpts(proxyObj.reqOpts); }\n\n // TESTING HELPER ONLY\n if (proxyObj.options.shortCircuit) { return callback(null, proxyObj); }\n\n // unless explicitly set, ignore encoding\n // THIS IS A HACK THAT MAY CAUSE ISSUES. I DON'T\n // KNOW OF AN IMMEDIATE WORKAROUND TO FIX IT.\n if (!proxyObj.options['accept-encoding']) {\n delete proxyObj.reqOpts.headers['accept-encoding'];\n }\n\n // Check for Form Post Parameters\n if (proxyObj.req.body && (proxyObj.reqOpts.method === 'POST' || proxyObj.reqOpts.method === 'PUT')) {\n proxyObj.reqOpts.form = proxyObj.req.body;\n }\n\n // make request\n request(proxyObj.reqOpts, function (error, response, body) {\n if (proxyObj.options.log) { logResponse(response, body); }\n\n // transfer result to resulting o\n proxyObj.res.set(helpers.defaultHeaders(proxyObj.options.response.headers, response ? response.headers : {}));\n\n proxyObj.result = {\n response : response,\n body : body\n };\n\n return callback(error, proxyObj);\n });\n}", "callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n const servername = opts.servername || opts.host;\n if (!servername) {\n throw new Error('Could not determine \"servername\"');\n }\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket();\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }", "callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n const servername = opts.servername || opts.host;\n if (!servername) {\n throw new Error('Could not determine \"servername\"');\n }\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket();\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }", "callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n const servername = opts.servername || opts.host;\n if (!servername) {\n throw new Error('Could not determine \"servername\"');\n }\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket();\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }", "function relayResponse(request, handler){\n\tif(request.readyState == 4){\n\t\tif(request.status == 200){\n\t\t\tvar responseText = request.responseText;\n\t\t\t\n\t\t\t// ugly hack for international pages adding extra HTML\n\t\t\tvar index = responseText.indexOf(\"<!DOCTYPE\");\n\t\t\tif(index != -1){\n\t\t\t\tresponseText = responseText.substring(0, index);\n\t\t\t}\n\t\t\t\n\t\t\t// success, give response text to handler function\n\t\t\thandler(true, responseText);\n\t\t}\n\t\telse{\n\t\t\t// page returned error code (such as 404)\n\t\t\thandler(false, 'Ajax page returned error code ' + request.status + '.');\n\t\t}\n\t}\n}" ]
[ "0.6411474", "0.63302225", "0.6319571", "0.6254568", "0.6204309", "0.60719407", "0.6065553", "0.6017493", "0.5974821", "0.5893247", "0.5864908", "0.5829232", "0.5816578", "0.58152676", "0.5791078", "0.57828575", "0.57771933", "0.5762546", "0.575762", "0.575564", "0.56961447", "0.5693808", "0.5692204", "0.56806797", "0.56806797", "0.56575006", "0.5644568", "0.5644568", "0.5644568", "0.5641088" ]
0.7489599
0
'fix' security options in configOptions parameter
function configureOptions(configOptions) { logger.trace("Fixing server SSL options");//, configOptions); var options = {}; options.https = {}; logger.trace("Fixing SSL key: ", JSON.stringify(configOptions.https.key)); if (!_.isUndefined(configOptions.https.key) && _.isString(configOptions.https.key)) { logger.trace("Loading SSL key file: ", configOptions.https.key); options.https.key = fs.readFileSync(configOptions.https.key); } if (!_.isUndefined(configOptions.https.cert) && _.isString(configOptions.https.cert)) { logger.trace("Loading SSL cert file: ", configOptions.https.cert); options.https.cert = fs.readFileSync(configOptions.https.cert); } if (!_.isUndefined(configOptions.https.pfx) && _.isString(configOptions.https.pfx)) { logger.trace("Loading SSL pfx file: ", configOptions.https.pfx); options.https.pfx = fs.readFileSync(configOptions.https.pfx); } options.https.requestCert = configOptions.https.requestCert; options.https.rejectUnauthorized = configOptions.https.rejectUnauthorized; options.https.agent = configOptions.https.agent; if (!_.isUndefined(configOptions.https.ca) && Array.isArray(configOptions.https.ca)) { options.https.ca = []; for (var i = 0; i < configOptions.https.ca.length; i++) { logger.trace("Loading SSL ca file: ", configOptions.https.ca[i]); options.https.ca[i] = fs.readFileSync(configOptions.https.ca[i]); } } options.https.passphrase = configOptions.https.passphrase; return options; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function initConfig(ctx) {\n return __awaiter(this, void 0, void 0, function* () {\n const isTrusted = stateUtils_1.getFromWorkspaceState(WORKSPACE_IS_TRUSTED_KEY, false);\n if (isTrusted !== defaultConfig.workspaceIsTrusted()) {\n defaultConfig.toggleWorkspaceIsTrusted();\n }\n ctx.subscriptions.push(vscode.commands.registerCommand('go.workspace.isTrusted.toggle', toggleWorkspaceIsTrusted));\n if (isTrusted) {\n return;\n }\n const ignored = ignoredWorkspaceConfig(vscode.workspace.getConfiguration('go'), SECURITY_SENSITIVE_CONFIG);\n if (ignored.length === 0) {\n return;\n }\n const ignoredSettings = ignored.map((x) => `\"go.${x}\"`).join(',');\n const val = yield vscode.window.showWarningMessage(`Some workspace/folder-level settings (${ignoredSettings}) from the untrusted workspace are disabled ` +\n `by default. If this workspace is trusted, explicitly enable the workspace/folder-level settings ` +\n `by running the \"Go: Toggle Workspace Trust Flag\" command.`, 'OK', 'Trust This Workspace', 'More Info');\n switch (val) {\n case 'Trust This Workspace':\n yield toggleWorkspaceIsTrusted();\n break;\n case 'More Info':\n vscode.env.openExternal(vscode.Uri.parse(`https://github.com/golang/vscode-go/blob/master/docs/settings.md#security`));\n break;\n default:\n break;\n }\n });\n}", "function manipulateOptions(opts) {\n\t opts.blacklist.push(\"regenerator\");\n\t}", "function manipulateOptions(opts) {\n\t opts.blacklist.push(\"regenerator\");\n\t}", "get advancedSecurityOptionsInput() {\n return this._advancedSecurityOptions;\n }", "function safeConfig(config) {\n // access control is shallow references only\n var readOnly = new Set(['httpEndpoint', 'abiCache']);\n var readWrite = new Set(['verbose', 'debug', 'broadcast', 'logger', 'sign']);\n var protectedConfig = {};\n\n Object.keys(config).forEach(function (key) {\n Object.defineProperty(protectedConfig, key, {\n set: function set(value) {\n if (readWrite.has(key)) {\n config[key] = value;\n return;\n }\n throw new Error('Access denied');\n },\n\n get: function get() {\n if (readOnly.has(key) || readWrite.has(key)) {\n return config[key];\n }\n throw new Error('Access denied');\n }\n });\n });\n return protectedConfig;\n}", "function manipulateOptions(opts) {\n opts.blacklist.push(\"regenerator\");\n}", "get configuration () {\n // Always returns a copy of the authentication configuration\n return Object.assign({}, defaultOptions, this.app.get(this.configKey));\n }", "function configureSecurity() {\n app.use(helmet());\n app.use(cookieParser());\n app.use(helmet.noCache());\n app.enable('trust proxy');\n if (!isLocal) {\n app.use(express_enforces_ssl());\n }\n}", "function configure(user_options) {\n\t options = inherit(options, user_options);\n\t }", "function configure(user_options) {\n\t options = inherit(options, user_options);\n\t }", "function configure(user_options) {\n\t options = inherit(options, user_options);\n\t }", "function configure(user_options) {\n\t options = inherit(options, user_options);\n\t }", "function configure(user_options) {\n\t options = inherit(options, user_options);\n\t }", "function configure(user_options) {\n options = inherit(options, user_options);\n}", "function SecurityConfigurationProvider() {\n\n /**\n * Configuration with defaults.\n */\n var config = {\n\n /**\n * Name of the cache that is used for the authenticated user details. \n */\n cacheName : 'authCache',\n\n /**\n * Name of the cache key under which the authenticated user details are stored.\n */\n userCacheKey : 'user',\n\n /**\n * URL of the web-service for the user authentication resource, this is effectively a\n * \"login\" * when valid credentials are supplied.\n * \n * A GET request is issued to this secured URL end-point to establish the server\n * security context and return authenticated user details.\n */\n authenticationUrl : '/user',\n\n /**\n * URL of the web-service used to logout the currently authenticated user. \n */\n logoutUrl : '/logout',\n\n /**\n * View state to change to when a login is required.\n */\n loginState : '/login',\n\n /**\n * Default view state to change to after a successful login.\n */\n afterLoginState : '/home',\n\n /**\n * Name of the request parameter that is used to set the new view state after a\n * successful login.\n * \n * Use of this parameter enables switching to the originally requested view state after\n * a successful login (e.g. as a result of deep-linking).\n * \n * This configuration parameter is optional, if it is not set then after a login the\n * view-state will always change to the configured 'afterLoginState' value.\n * \n * This request parameter and the target view state value will be visible in the\n * browser address bar while on the login page - this is unavoidable.\n */\n afterLoginParameter: 'then',\n\n /**\n * View state to change to after a successful logout.\n */\n afterLogoutState : '/home',\n\n /**\n * View state to change to when the current user requests a resource that they are not\n * authorised to access.\n */\n notAuthorisedState : '/not-authorised',\n\n /**\n * View state to change to when some other unhandled error response is returned.\n * \n * This is for e.g. 500 errors rather than authorisation errors.\n */\n errorState : '/error' // FIXME maybe a dedicated 404 error page too?\n\n };\n\n this.cacheName = function(value) {\n config.cacheName = value;\n };\n \n this.userCacheKey = function(value) {\n config.userCacheKey = value;\n };\n\n this.authenticationUrl = function(value) {\n config.authenticationUrl = value;\n };\n\n this.logoutUrl = function(value) {\n config.logoutUrl = value;\n };\n\n this.loginState = function(value) {\n config.loginState = value;\n };\n\n this.afterLoginState = function(value) {\n config.afterLoginState = value;\n };\n\n this.afterLoginParameter = function(value) {\n config.afterLoginParameter = value;\n };\n\n this.afterLogoutState = function(value) {\n config.afterLogoutState = value;\n };\n\n this.notAuthorisedState = function(value) {\n config.notAuthorisedState = value;\n };\n\n this.errorState = function(value) {\n config.errorState = value;\n };\n\n this.$get = function configProviderFactory() {\n return config;\n };\n\n}", "function manipulateOptions(opts) {\n opts.blacklist.push(\"react\");\n}", "function configure(user_options) {\n options = inherit$1(options, user_options);\n }", "function manipulateOptions(opts) {\n\t opts.blacklist.push(\"react\");\n\t}", "function manipulateOptions(opts) {\n\t opts.blacklist.push(\"react\");\n\t}", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "normalizeContextOptions(givenContextOptions) {\n\n let cOptions = givenContextOptions || {};\n\n // by default we do not bypass authentication\n cOptions.bypassAuth = u.thisOrThat(cOptions.bypassAuth, false);\n\n // decode html enntities for this call?\n cOptions.decodeHtmlEntities = u.thisOrThat(cOptions.decodeHtmlEntities,\n this._userConfig.decodeHtmlEntities);\n\n // how many attempts left do we have to retry an endpoint?\n\n // use the given retryAttemptsLeft, or the retryAttempts passed in the\n // context options if not specified\n cOptions.retryAttemptsLeft = u.thisOrThat(cOptions.retryAttemptsLeft,\n cOptions.retryAttempts);\n\n // use the given retryAttemptsLeft, or the retryAttempts passed in the\n // user configuration\n cOptions.retryAttemptsLeft = u.thisOrThat(cOptions.retryAttemptsLeft,\n this._userConfig.retryAttempts);\n\n // delay between retrying an endpoint\n cOptions.retryDelay = u.thisOrThat(cOptions.retryDelay,\n this._userConfig.retryDelay);\n\n // milliseconds before a request times out\n cOptions.requestTimeout = u.thisOrThat(cOptions.requestTimeout,\n this._userConfig.requestTimeout);\n\n // how many reauthentication attempts do we have left?\n cOptions.reauthAttemptsLeft = u.thisOrThat(cOptions.reauthAttemptsLeft,\n cOptions.retryAttemptsLeft);\n\n return cOptions;\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }", "function configure(user_options) {\n options = inherit(options, user_options);\n }" ]
[ "0.58123785", "0.5586632", "0.5586632", "0.5542212", "0.554184", "0.55275524", "0.5465999", "0.54581815", "0.5453196", "0.5453196", "0.5453196", "0.5453196", "0.5453196", "0.5434075", "0.54136807", "0.54118866", "0.5411763", "0.5382656", "0.5382656", "0.53799045", "0.53791094", "0.53637844", "0.53637844", "0.53637844", "0.53637844", "0.53637844", "0.53637844", "0.53637844", "0.53637844", "0.53637844" ]
0.59409773
0
creates the summary object for the months changes
function aggregateMonthChanges(changes) { const updatedChanges = { add: 0, death: 0, theft: 0, sale: 0 }; // accumulate the different changes for the month changes.forEach(change => { if (!updatedChanges[change.reasonForChange]) { updatedChanges[change.reasonForChange] = change.animalsMoved; } else { updatedChanges[change.reasonForChange] += change.animalsMoved; } }); return updatedChanges; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function CalculateTotalsMonthToDate() {\n //use temp variables to prevent multiple dom updates\n var wt = 0; //written total\n var dt = 0; //delivered total\n var gt = 0; //goals total\n for (var i = 0; i < vm.territorySalesNumbers.length; i++) {\n wt += vm.territoryWritten[i];\n dt += vm.territoryDelivered[i];\n }\n\n var indexMonth = (vm.currentYear == vm.maxYear) ? vm.thisMonth:11; //this holds the month (as a 0-based integer) that will be used to loop through and add all the goals together\n\n\n for (var i = 0; i <= indexMonth; i++) {\n gt += vm.goals[i];\n }\n\n vm.writtenTotal = Round(wt, 2);\n vm.deliveredTotal = Round(dt, 2);\n vm.goalsTotal = Round(gt, 2);\n vm.goalsWrittenDifference = Round(vm.writtenTotal - vm.goalsTotal, 2);\n\n if (vm.goalsWrittenDifference > 0)\n vm.goalsWrittenDifference = '+' + vm.goalsWrittenDifference;\n }", "function dataSalesPerMonth(obj) {\n for (var i = 0; i < obj.length; i++) {\n var formattedData = moment(obj[i].date, \"DD/MM/YYYY\");\n var currentMonth = formattedData.format(\"MMMM\");\n var employeeSale = obj[i].amount;\n months[currentMonth] += employeeSale;\n }\n labelTotalSales = Object.keys(months);\n dataTotalSales = Object.values(months);\n for (var j = 0; j < Object.keys(months).length; j++) {\n optionMonth.value = Object.keys(months)[j];\n $(\".months\").append(selectTemplate(optionMonth));\n }\n}", "function monthly(monthName, income, food, rent) {\n this.monthName = monthName\n this.income = income;\n this.food = food;\n this.rent = rent;\n this.calculateExcess = function() {\n var totalExpenses = this.food + this.rent;\n return this.income - totalExpenses;\n };\n}", "compareProfitOnPriceChange(amount) {\n let report = {};\n this._monthNames.map((element, index) => {\n const days = this.getDaysInMonth(index + 1);\n const previousRate = this.totalProduction() * days;\n const newRate = this.totalProduction(amount) * this.getDaysInMonth(index + 1);\n const difference = newRate - previousRate;\n const profitOrLoss = difference > 0 ? 'Profit' : 'Loss';\n report[element] = {\n previousRate,\n newRate,\n profitOrLoss\n };\n });\n return report;\n }", "function calcMonthView(data) {\n var new_data = [];\n var new_month = [];\n var current_day = data[0];\n var current_month = data[0].date.getMonth();\n for(var i = 1; i < data.length; ++i) {\n if(data[i].date.getMonth() == current_month) {\n new_month.push(data[i]);\n } else {\n new_data.push(new_month);\n new_month = [];\n current_month = data[i].date.getMonth();\n }\n }\n new_data.push(new_month);\n return new_data;\n}", "function calculateMonth(last, data, date) {\n let churn_per_month = Math.round(data.get('churn') / 100 * last.get('total_sales'))\n // Last month's sales plus percentage growth minus total churn this month\n let sales_per_month = Math.round(last.get('sales_per_month') + data.get('perc') / 100 * last.get('sales_per_month'))\n let total_sales = last.get('total_sales') + sales_per_month - churn_per_month\n let net = last.get('total_revenue') + sales_per_month * data.get('rev') + churn_per_month * -data.get('rev') - data.get('burn')\n\n return fromJS({\n date: date\n , cash: last.get('cash') + net\n , net: net\n , total_sales: total_sales\n , sales_per_month: sales_per_month\n , revenue_per_month: sales_per_month * data.get('rev')\n , cpa_per_month: sales_per_month * -data.get('cpa')\n , total_revenue: last.get('total_revenue') + sales_per_month * data.get('rev') + churn_per_month * -data.get('rev')\n , churn_amount: churn_per_month * -data.get('rev')\n , churn_per_month: churn_per_month\n })\n}", "getMonthDetail() {\n var y = this.currentDate.getFullYear(),\n m = this.currentDate.getMonth();\n var firstDay = new Date(y, m, 1);\n var lastDay = new Date(y, m + 1, 0);\n return {\n date: this.currentDate,\n month: this.currentDate.getMonth(),\n firstDay: firstDay,\n lastDay: lastDay,\n year: y\n };\n }", "months() {\n return _monthLabels.map((ml, i) => ({\n label: ml,\n label_1: ml.substring(0, 1),\n label_2: ml.substring(0, 2),\n label_3: ml.substring(0, 3),\n number: i + 1,\n }));\n }", "function MonthView(date) {\n this.date = date;\n this.WEEKS_PER_MONTH = 5;\n this.DAYS_PER_WEEK = 7;\n }", "function creatMonthsArray(month, daysCount) {\n console.log(daysCount);\n debugger;\n var month2 = new Object({\n Week1: { days: new Array(7).fill(0), tatal: 0 },\n Week2: { days: new Array(7).fill(0), tatal: 0 },\n Week3: { days: new Array(7).fill(0), tatal: 0 },\n });\n if (daysCount === 31) {\n month2.Week4 = { days: new Array(10).fill(0), tatal: 0 };\n } else if (daysCount === 30) {\n month2.Week4 = { days: new Array(9).fill(0), tatal: 0 };\n } else if (daysCount === 29) {\n month2.Week4 = { days: new Array(8).fill(0), tatal: 0 };\n } else if (daysCount === 28) {\n month2.Week4 = { days: new Array(7).fill(0), tatal: 0 };\n }\n\n switch (month) {\n case 1:\n console.log(jan, 'month');\n jan = month2;\n break;\n case 2:\n Feb = month2;\n break;\n case 3:\n Mar = month2;\n break;\n case 4:\n aprile = month2;\n break;\n case 5:\n may = month2;\n break;\n case 6:\n jun = month2;\n break;\n case 7:\n jul = month2;\n break;\n case 8:\n ogst = month2;\n break;\n case 9:\n sept = month2;\n break;\n case 10:\n oct = month2;\n break;\n case 11:\n nov = month2;\n break;\n case 12:\n dec = month2;\n break;\n }\n}", "function getSalesByMonth(data) {\n\n var months = new Array(12).fill(0);\n\n for (var i = 0; i < data.length; i++) {\n var d = data[i];\n\n var monthNum = moment(d.date, \"DD-MM-YYYY\").month();\n var amount = Number(d.amount);\n\n months[monthNum] += amount;\n\n }\n return months;\n}", "_setInfo() {\n let { year: currentYear, month: currentMonth } = this.currentMonthInfo; \n \n this.prevMonthInfo = { \n year: currentMonth == 0 ? currentYear - 1 : currentYear,\n month: currentMonth == 0 ? 11 : currentMonth - 1,\n day: null\n };\n \n this.nextMonthInfo = {\n year: currentMonth == 11 ? currentYear + 1 : currentYear,\n month: currentMonth == 11 ? 0 : currentMonth + 1,\n day: null\n }\n }", "analyzeAccount () {\r\n let resultsArray = [];\r\n\r\n // Apply the following code for each transaction in this account\r\n this._transactionList.forEach( transaction =>{\r\n // Group transactions by month\r\n let transactionYearMonth = transaction.date.slice(0,7);\r\n let monthIndex = -1;\r\n for(let i = 0; i < resultsArray.length; i++){\r\n if (resultsArray[i].yymm.toString() === transactionYearMonth.toString()){\r\n monthIndex = i;\r\n break;\r\n }\r\n }\r\n /* If the month entry for this transaction was not found, generate a new one\r\n for that month */\r\n if (monthIndex === -1) {\r\n resultsArray.push({\r\n yymm: transactionYearMonth, //The month name is in yyyy-mm format\r\n expense: 0, // Total of all expense transactions\r\n income: 0, // Total of all income transactions\r\n balance: 0, // income total - expense total\r\n num: 0, // number of all transactions this month (income and expense)\r\n // each category expense and income transactions\r\n cat: {expense:{}, income:{}}\r\n }) ;\r\n monthIndex = resultsArray.length - 1;\r\n }\r\n\r\n // Update expense or income total (based on the transaction type)\r\n resultsArray[monthIndex][transaction.type] += parseFloat(transaction.amount);\r\n\r\n /* Update the category expense or income total\r\n (based on the transaction type and category) */\r\n if (typeof resultsArray[monthIndex].cat[transaction.type][transaction.category] === 'undefined'){\r\n resultsArray[monthIndex].cat[transaction.type][transaction.category] = 0;\r\n }\r\n resultsArray[monthIndex].cat[transaction.type][transaction.category] +=\r\n parseFloat(transaction.amount);\r\n\r\n // Update the month's balance\r\n resultsArray[monthIndex].balance =\r\n parseFloat(resultsArray[monthIndex].income) -\r\n parseFloat(resultsArray[monthIndex].expense);\r\n\r\n // Increase the number of transactions for this month\r\n resultsArray[monthIndex].num += 1;\r\n });\r\n\r\n // Sort the analysis array by recent month first\r\n resultsArray.sort( (monthA, monthB) => {\r\n return new Date(monthB.yymm+'-01') - new Date(monthA.yymm+'-01');\r\n });\r\n this._analysis = resultsArray;\r\n }", "updateMonth() {\n O('month-label').innerHTML = MONTHS[this.month];\n }", "function nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth) {\n if (startPriceOld >= startPriceNew) {\n return [0, Math.floor(startPriceOld - startPriceNew)];\n }\n \n let months = 0;\n let totalSaving = 0;\n let depreciatedPriceNew = startPriceNew;\n let depreciatedPriceOld = startPriceOld;\n let lossPercentage = percentLossByMonth; \n while ((totalSaving + depreciatedPriceOld) < depreciatedPriceNew) {\n months += 1;\n if (months % 2 === 0) {\n lossPercentage += 0.5; \n }\n totalSaving += savingperMonth;\n depreciatedPriceOld -= depreciatedPriceOld * (lossPercentage / 100);\n depreciatedPriceNew -= depreciatedPriceNew * (lossPercentage / 100);\n }\n return [months, Math.round(totalSaving + depreciatedPriceOld - depreciatedPriceNew)];\n }", "function nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth){\n \n // Case 1 : the old man has enough money\n \n // We return 0 for the number of month and the difference between the two prices\n if(startPriceOld >= startPriceNew) {return [0, Math.round(startPriceOld - startPriceNew)];}\n \n \n // Case 2 : the old man doesn't have enough money\n \n // We initiate two variables, months for the number of months he's been waiting\n // and total for the total money he has\n var months = 0, total = startPriceOld;\n \n // As long as the old man doesn't have enough money, we loop again for a new month\n while(total < startPriceNew) {\n // We add the savingperMonth for the new month\n total += savingperMonth;\n \n // We adjust the price of the old car\n total -= startPriceOld * percentLossByMonth / 100;\n \n \n // Applying the interest rate on the new car price and \n startPriceNew -= startPriceNew * percentLossByMonth / 100;\n startPriceOld -= startPriceOld * percentLossByMonth / 100;\n \n // We increase the month counter\n months++;\n \n // Increasing the rate for all the even months (we use the increased rate immediately after month 1)\n // So each time the numbers of passed months is odd, we increase the rate\n months % 2 !== 0 ? percentLossByMonth += 0.5 : percentLossByMonth;\n \n } // end while\n \n // Returning the number of months and what the old man has left after the purchase (rounded to units)\n return [months, Math.round(total - startPriceNew)];\n \n}", "function Month(parent){var _this=_super.call(this,parent)||this;_this.dayNameFormat='wide';_this.viewClass='e-month-view';_this.isInverseTableSelect=false;_this.monthDates={};return _this;}", "function changeByMonth(month, year, back) {\n back = back || false;\n var numDaysInMo,\n addend = 1;\n if (back) {\n addend = -1;\n }\n month = month + addend;\n if ((month < 0) || (month === 12)) {\n month = (month < 0) ? (month = 11) : month = 0;\n year = year + addend;\n }\n numDaysInMo = daysInMonth(month, year);\n return {month: month, year: year, numDaysInMo: numDaysInMo};\n }", "function FormMonthlyData(data) {\n var janArray = [];\n var febArray = [];\n var marArray = [];\n var aprArray = [];\n var mayArray = [];\n var junArray = [];\n var julArray = [];\n var augArray = [];\n var sepArray = [];\n var octArray = [];\n var novArray = [];\n var decArray = [];\n\n for (var i = 0; i < data.length; i++) {\n if(i < 743) {\n janArray.push(data[i]);\n }\n if(i > 744 && i < 1441) {\n febArray.push(data[i]);\n }\n if(i > 1442 && i < 2162) {\n marArray.push(data[i]);\n }\n if(i > 2163 && i < 2907) {\n aprArray.push(data[i]);\n }\n if(i > 2908 && i < 3628) {\n mayArray.push(data[i]);\n }\n if(i > 3629 && i < 4373) {\n junArray.push(data[i]);\n }\n if(i > 4374 && i < 5094) {\n julArray.push(data[i]);\n }\n if(i > 5095 && i < 5839) {\n augArray.push(data[i]);\n }\n if(i > 5840 && i < 6560) {\n sepArray.push(data[i]);\n }\n if(i > 6561 && i < 7305) {\n octArray.push(data[i]);\n }\n if(i > 7306 && i < 8026) {\n novArray.push(data[i]);\n }\n if(i > 8027 && i < 8771) {\n decArray.push(data[i]);\n }\n }\n return [janArray,febArray,marArray,aprArray,mayArray,junArray,julArray,augArray,sepArray,octArray,novArray,decArray];\n}", "getCreditCardMonths(startMonth) {\n let data = [];\n // build an array for \"Month\" dropdown list\n // - start at current month and loop until\n for (let theMonth = startMonth; theMonth <= 12; theMonth++) {\n // .push adds theMonth to the data array\n data.push(theMonth);\n }\n // the of operator from rxjs will wrap an object as an Observable!\n return of(data);\n }", "listMonths () {\n const currentYear = this.year\n const min = this.minMoment\n const max = this.maxMoment\n const inMinYear = currentYear === min.year()\n const inMaxYear = currentYear === max.year()\n const months = []\n Moment.months().forEach((name, m) => {\n if ((!inMinYear || m >= min.month()) && (!inMaxYear || m <= max.month())) {\n months.push({ text: name, value: m })\n }\n })\n return months\n }", "function monthChange(btn){\n let newMonth = Toolbar.curTime.getMonth() + Number(btn.getAttribute(\"data-dir\"));\n let newYear = Toolbar.curTime.getFullYear();\n if(newMonth<0){\n newMonth = 11;\n newYear--;\n }\n else if(newMonth > 11){\n newMonth = 0;\n newYear++;\n }\n Toolbar.curTime.setMonth(newMonth);\n Toolbar.curTime.setFullYear(newYear);\n genDateTable();\n}", "function updateViz(val){\r\n d3.select('#month').html(listMonths[val-1]);\r\n drawMap(currentMonth, currentYear); \r\n }", "generateSelectMonths() {\n let allRecords = this.props.allRecords\n let months = []\n let key = \"\"\n\n if (allRecords.length !== 0) {\n let startDate = allRecords.sort((a, b) => (new Date(a.date) - new Date(b.date)))[0].date\n let { startMonth, startYear, currentMonth, currentYear } = this.getDatesSelect(startDate)\n\n for (let year = startYear; year <= currentYear; year++) {\n for (let month = startMonth; month <= currentMonth; month++) {\n month = (month < 10) ? ('0' + month) : month\n key = `${month}/${year}`\n months.push(key)\n }\n }\n }\n return months;\n }", "function overviewChartMonthDisplay() {\n\t\tlet monthDisplay = document.getElementById('overviewChartMonth');\n\t\t\n\t\t// Year Display\n\t\tlet currentDate = new Date();\n\t\t\n\t\t// If month is December then show only the current year \n\t\tif(currentDate.getMonth() == 11) {\n\t\t\tmonthDisplay.innerText = currentDate.getFullYear();\n\t\t} else {\n\t\t\tmonthDisplay.innerText = (Number(currentDate.getFullYear()) - 1) + ' - ' + currentDate.getFullYear()\n\t\t}\n\t}", "function showMonth(target, delta) {\n var state = $.data(target, 'calendar');\n var opts = state.options;\n opts.month += delta;\n if (opts.month > 12) {\n opts.year++;\n opts.month = 1;\n } else if (opts.month < 1) {\n opts.year--;\n opts.month = 12;\n }\n show(target, state);\n\n var menu = $(target).find('.calendar-menu-month-inner');\n menu.find('td.calendar-selected').removeClass('calendar-selected');\n menu.find('td:eq(' + (opts.month - 1) + ')').addClass('calendar-selected');\n }", "function getDistinctMonths(allData) {\n var distinctMonths = {};\n allData.forEach(function(d) {\n if(d.OrderYear > 0 && d.OrderMonth > 0)\n distinctMonths[d.OrderYear + \"-\" + d.OrderMonth] = { OrderYear: d.OrderYear, OrderMonth: d.OrderMonth };\n })\n \n\n return Object.keys(distinctMonths).sort(function (x, y) {\n var isGreater;\n if (distinctMonths[x].OrderYear == distinctMonths[y].OrderYear) isGreater = distinctMonths[x].OrderMonth > distinctMonths[y].OrderMonth;\n else isGreater = distinctMonths[x].OrderYear > distinctMonths[y].OrderYear;\n\n return isGreater ? 1 : -1;\n });;\n }", "constructor(year, month) {\n let _y = parseInt(+year), _m = parseInt(+month);\n if (isNaN(_y) || isNaN(_m) || _m < 1 || _m > 12) {\n if (process.env.NODE_ENV !== 'production') {\n throw new TypeError('MonthObject constructor should receive a valid number!');\n }\n }\n this._year = _y;\n this._month = _m;\n this._isLeap = ((month == 2) && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0));\n this._dayCount = [1, -2, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1][month - 1] + 30 + this._isLeap;\n }", "function monthPredicted(){\n var tempdata = \"\";\n var flag = 1;\n if (inspectedItem.funding_status === \"seed\"){\n tempdata = process_data_numeric(seed_to_a);\n }else if (inspectedItem.funding_status === \"series_a\"){\n tempdata = process_data_numeric(a_to_b);\n }else{\n flag = 0;\n tempdata = process_data(monthRateDefault);\n }\n var ans = [];\n if (flag === 1){\n for (var i in tempdata){\n if (tempdata[i].name === inspectedItem.name){\n const entries = Object.entries(tempdata[i])\n let id = 0;\n ans = entries.map(function(item){\n var info = {\n \"key\": id,\n \"period\": item[0],\n \"success_rate\": item[1],\n }\n id++;\n return info;\n })\n ans.shift()\n ans.shift()\n stateX = []\n stateX.push(ans.pop())\n stateX.push(ans.pop())\n stateX.push(ans.pop())\n stateX.push(ans.pop())\n stateX.push(ans.pop())\n }\n }\n return ans;\n }else{\n return tempdata;\n }\n }", "setMonthTable(state, {ledger}) {\n ledger.bill.forEach(e => {\n let item = {year: e.year, month: e.month, monthKey: e.monthKey};\n if(e.month && e.year && ledger.monthTable.findIndex(i => (i.year === e.year && i.month === e.month)) < 0) {\n ledger.monthTable.push(item);\n }\n });\n }" ]
[ "0.63781214", "0.6243058", "0.6224361", "0.61561763", "0.6020074", "0.60071856", "0.59950596", "0.5955951", "0.5841789", "0.57974535", "0.57925195", "0.57576716", "0.57401246", "0.5680722", "0.5643301", "0.56413084", "0.55726916", "0.55608064", "0.5555992", "0.55387586", "0.55229956", "0.5514194", "0.5501975", "0.5489673", "0.547193", "0.5469441", "0.54670054", "0.543055", "0.54279166", "0.54262817" ]
0.6885843
0
calculates the closing total
function getClosingTotal(monthsChanges, openingTotal) { let closingTotal = openingTotal; for (let i = 0; i < monthsChanges.length; i++) { closingTotal += monthsChanges[i].animalsMoved; } return closingTotal; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function finalTotalAmountOfThisOrder()\n {\n return (nanCheck(parseFloat(subTotalWithoutShippingCost())) + nanCheck(parseFloat(shippingCostOfThisMainOrder()))).toFixed(2);\n }", "close(monowave) {\n\t\tthis.dateEnd\t= monowave.timeEnd;\n\t\tthis.valueEnd\t= monowave.valueEnd;\n\t\tvar deltaPrice \t= this.valueEnd - this.valueStart;\n\t\tvar deltaTime \t= this.dateEnd - this.dateStart;\n\t\tthis.ratio\t\t= deltaPrice / deltaTime;\n\t}", "setearTotal() {\n this.setState({\n subtotalCalculate: this.props.total,\n totalCalculate: parseFloat(\n this.props.total -\n this.state.discountCalculate -\n this.state.cuponCalculate\n ).toFixed(2)\n });\n }", "function calcTotalDayAgain() {\n var eventCount = $this.find('.this-month .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }", "function calculateTotal() {\n const firstClassCount = getInputValue('first-class');\n const economyCount = getInputValue('economy');\n\n const subTotal = firstClassCount * 150 + economyCount * 100;\n document.getElementById('sub-total').innerText = '$' + subTotal;\n\n const vat = subTotal * 0.1;\n document.getElementById('vat').innerText = '$' + vat;\n\n const total = subTotal + vat;\n document.getElementById('total').innerText = '$' + total;\n}", "function calcSubtotal() {\n const sub = Object.keys(lineStates)\n .reduce((acum, lineKey) => {\n if (lineKey === 'shippingState') {\n return acum;\n } else {\n const {liveQuantity, unitPrice} = lineStates[lineKey].getState();\n const nextAcum = acum + (liveQuantity * unitPrice);\n return nextAcum;\n }\n }, 0);\n getElements.subtotalPrice().innerHTML = formatMoney(sub, theme.moneyFormat);\n return sub;\n}", "function subTotal(amount) {\n var subTotal = numPizzas * PRICEPIZZA - DISCOUNTRATE;\n return subTotal;\n}", "function calcTotals() {\n var incomes = 0;\n var expenses = 0;\n var budget;\n // calculate total income\n data.allItems.inc.forEach(function(item) {\n incomes+= item.value;\n })\n //calculate total expenses\n data.allItems.exp.forEach(function(item) {\n expenses+= item.value;\n })\n //calculate total budget\n budget = incomes - expenses;\n // Put them in our data structure\n data.total.exp = expenses;\n data.total.inc = incomes;\n //Set Budget\n data.budget = budget;\n }", "function getTotalAmountFinanced(){\n\t\treturn parseInt(localStorage.pSlider)-parseInt(localStorage.dPayment);\t\t\n\t}", "function subTotalAmountOfThisOrder()\n {\n var sum = 0;\n $('.cr_getSubtotalClass').each(function(){\n sum += parseFloat($(this).text());\n });\n return parseFloat(sum).toFixed(2);\n }", "forAllDays() {\n if (this.breakDown() !== 'No Information to display') {\n let totalCost = this.breakDown().reduce((acc, item) => acc += item.totalCost, 0)\n return totalCost || 0;\n }\n }", "function total(){\n\tvar TotalPrice=CakeSizePrice() +FilingPrice()+ CandlePrice()+InscriptionPrice() ;\n\n\t//final result\n\tdocument.getElementById(\"display\").innerHTML=\"total price $\"+TotalPrice;\n}", "total () {\n\t\treturn this.subtotal() - this.discounts();\n\t}", "getTotalCalories() {\n return this.state.breakfast.reduce((accumulator, elem) => parseInt(elem.calories) + accumulator, 0)\n + this.state.lunch.reduce((accumulator, elem) => parseInt(elem.calories) + accumulator, 0)\n + this.state.dinner.reduce((accumulator, elem) => parseInt(elem.calories) + accumulator, 0)\n + this.state.snacks.reduce((accumulator, elem) => parseInt(elem.calories) + accumulator, 0);\n }", "function calculateTotal(){\n \n var childPrice = (getageGroupPrice() * getlengthOfDayInput()) * \n getdaysperweekInput() * gettimeframeInput() +\n summerClassPrice() + nonstudentfeeInput();\n\n// Display the results\n var grandTotal = document.getElementById('totalPrice');\n grandTotal.style.display='block';\n grandTotal.innerHTML = \"Total price for this child is $\"+childPrice.toFixed(2);\n}", "function calculatePrice() {\n const priceTotal = priceCalculation();\n innerChanger('sum', priceTotal);\n innerChanger('sum-footer', priceTotal);\n}", "function totalCalculation() {\n const firstClassTicketCount = getTicketInput('firstClass');\n const economyTicketCount = getTicketInput('economy');\n const subTotal = firstClassTicketCount * 150 + economyTicketCount * 100;\n document.getElementById('subTotal').innerText = subTotal;\n const vat = subTotal / 10;\n document.getElementById('vat').innerText = vat;\n const total = subTotal + vat;\n document.getElementById('total').innerText = total;\n document.getElementById('confirmAmount').innerText = total;\n}", "function normalizeYesterdayClose() {\n var yClose = $('#id_close-1').val(),\n yOpen = $('#id_open-1').val(),\n nYClose = 0;\n\n nYClose = (yClose - yOpen) / yClose;\n nYClose = isNaN(nYClose) ? 0 : nYClose;\n\n $('#id_n_close-1').val(nYClose);\n\n console.log(\"Normalized Yesterday Close: \" + nYClose);\n }", "function updateTotal(){\n\t\tvar sum = 0;\n\t\t$(\".cart_items>.item\").each(function(i,v){\n\t\t\tsum += $(v).data(\"price\") * $(v).find(\".cart_cloth_num\").text();\n\t\t});\n\t\t$(\".cart_total\").text(sum);\n\t}", "function closeStatus(output, totalCashInDrawer) {\n output.status = STATUS.close;\n output.change = totalCashInDrawer;\n return output;\n}", "function total(cost) {\n var total = subtotal * '.08';\n return total;\n}", "calcTotal(){\n\t\t\tlet length = this.sales.length;\n\t\t\tthis.paidCommissionTotal = 0;\n\t\t\tthis.commissionTotal = 0;\n\t\t\tfor(let i = 0; i < length; ++i){\n\t\t\t\t\tthis.commissionTotal += this.sales[i].commission;\n\t\t\t\t\tif(this.sales[i].paid == true){\n\t\t\t\t\t\tthis.paidCommissionTotal += this.sales[i].commission;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tthis.sales.length;\n\t\t}", "function calculateTotal(){\n\t\tlet basketTotalContainer = document.querySelector('#basket-total');\n\t\tlet basketCount = document.querySelector('#basket-count');\n\t\tlet minibasketTotal = document.querySelector('#mini-basket-total');\n\t\tbasketTotalContainer.innerHTML = '';\n\t\tbasketCount.innerHTML = '';\n\t\tminibasketTotal.innerHTML = '';\n\t\tlet basket = document.querySelector('.basket tbody'), basketTotalVal = 0, basketTotalItems = 0, basketTotalValCurrency;\n\t\tfor(let i = 0; i < (basket.rows.length); i++){\n\t\t\tlet rowTotal = Number(basket.rows[i].cells[2].innerHTML);\n\t\t\tlet itemsTotal = Number(basket.rows[i].cells[1].childNodes[0].innerHTML);\n\t\t\tbasketTotalVal = basketTotalVal + rowTotal;\n\t\t\tbasketTotalValCurrency = basketTotalVal.toFixed(2);\n\t\t\tbasketTotalItems = basketTotalItems + itemsTotal;\t\t\n\t\t};\n\t\tbasketTotalContainer.innerHTML = basketTotalValCurrency;\n\t\tbasketCount.innerHTML = basketTotalItems;\n\t\tminibasketTotal.innerHTML = basketTotalValCurrency;\n\t\t// avoid 'undefined' if basket is empty\n\t\tif (basketTotalValCurrency == null){\n\t\t\tbasketTotalContainer.innerHTML = '';\n\t\t\tminibasketTotal.innerHTML = '';\n\t\t}\n\t}", "function update_escrow_amount() {\n // Sum the total amount of funding outputs we haven't used yet\n var total = 0;\n for (var i = 0; i < funding_outputs.length; i++) {\n if (funding_outputs[i].output_state != OUTPUT_STATES.DEPLETED)\n {\n total += funding_outputs[i].satoshis;\n }\n }\n escrow_amount = total - fee;\n coin_width = escrow_amount / 100;\n\n // Don't let the coin_width get too low\n if (coin_width < price_per_second)\n {\n coin_width = price_per_second;\n }\n console.log(\"coin_width: \" + coin_width);\n}", "function calc_cart_total() {\n shopping_cart_total = calc_total();\n set_cart_total_dom();\n update_shipping_icons();\n update_tax_dom();\n}", "function calculateSubTotal(){\n const firstCount = getInputValue('first')\n const economyCount = getInputValue('economy')\n const subTotalPrice = firstCount*150 + economyCount*100; //sub total Calculation\n document.getElementById('sub-Total').innerText = '$' + subTotalPrice;\n\n const tax = subTotalPrice * .1 //tax Calculation\n document.getElementById('tax-Amount').innerText = '$' + tax;\n const grandTotal = tax + subTotalPrice;\n document.getElementById('grand-Total').innerText = '$' + grandTotal; //grand total Calculation\n}", "function belowCloseF(stock, stockAwayPctF) { \n \n if (stock.pcls < stock.opn) {\n return true;\n }\n }", "totalStockValue()\n {\n return this.shares*this.price;\n }", "function calculateTotal() {\n const firstCount = getInputValue('first');\n const economyCount = getInputValue('economy');\n\n const totalPrice = firstCount * 150 + economyCount * 100;\n document.getElementById('total-price').innerText = totalPrice;\n\n const tax = totalPrice * 0.1;\n document.getElementById('tax-amount').innerText = tax;\n\n const finalTotal = totalPrice + tax;\n document.getElementById('final-total').innerText = finalTotal\n}", "function calculateTotal () {\n const fistClassQuantity = getQuantityNumber('first-class');\n\n const economyQuantity = getQuantityNumber('economy');\n\n const subtotal = fistClassQuantity * 150 + economyQuantity * 100;\n document.getElementById('subtotal').innerText = subtotal;\n document.getElementById('show-subtotal').innerText = subtotal;\n\n const vat = Math.floor(subtotal * 0.1);\n document.getElementById('vat').innerText = vat;\n document.getElementById('show-vat').innerText = vat;\n\n const total = subtotal + vat;\n document.getElementById('total').innerText = total;\n document.getElementById('show-total').innerText = total;\n}" ]
[ "0.6102411", "0.56489104", "0.5648566", "0.55740833", "0.5551331", "0.5542211", "0.5503885", "0.54976916", "0.54424524", "0.5420663", "0.5413911", "0.5407438", "0.5402365", "0.54008365", "0.53891134", "0.5364391", "0.53439355", "0.5342617", "0.5325134", "0.53202355", "0.53146416", "0.53118557", "0.5307898", "0.530061", "0.5300081", "0.52958304", "0.52907944", "0.5287003", "0.5285251", "0.5279056" ]
0.66610575
0
updateUserType(): update type and company
async function updateUserHire(user, type, company) { user.type = type; user.company = company; return getParticipantRegistry('org.pow.app.User').then(function(registry) { return registry.update(user) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "updateUserType(userType) {\n \n }", "async function handleUserTypeValueSave() {\n updateIsSaving(true);\n\n await updateInstance({\n variables: {\n actionId: UPDATE_USER_TYPE_FOR_APP_SPEC_ACTION_ID,\n executionParameters: JSON.stringify({\n value: userTypeValue,\n instanceId: userType.id,\n }),\n },\n refetchQueries,\n });\n\n updateIsEditMode(false);\n updateIsSaving(false);\n }", "editUserType({ idUser }, { idType }, result) {\r\n let query = `update uZvFiNMuwF.user set idType = ${idType}`;\r\n query += ` where idUser = ${idUser}`;\r\n\r\n sql.query(query, (err, rows, fields) => {\r\n if (err) {\r\n result(err, rows);\r\n return;\r\n }\r\n\r\n result(null, rows);\r\n });\r\n }", "function handleUserTypeValueChange(e) {\n updateUserTypeValue(e.target.value);\n }", "async update(id, user, type) {\n\t\tconst dto = await this.entityDto.domain()\n\t\tuser.id = id\n\t\tuser = morphism(dto, user)\n\t\tif (type == 'password') {\n\t\t\tconst salt = await bcrypt.genSalt(10)\n\t\t\tuser.password = await bcrypt.hash(user.password, salt)\n\t\t\treturn this.usersRepository.updatePassword(id, user)\n\t\t}\n\t\treturn this.usersRepository.updateUsername(id, user)\n\t}", "function updateProfileHandler(type, value) {\n if (type === 'address' || type === 'phone' || type === 'hours') {\n setUserProfile(() => ({\n ...userProfile,\n contactInfo: {\n ...userProfile.contactInfo,\n [type]: value\n }\n }));\n }\n else {\n setUserProfile(() => ({\n ...userProfile,\n [type]: value\n }));\n }\n }", "updateType() {\n this.incorrectTypeAttributes = false;\n // Since we can just change name and do not touch attributes\n // this is safety check to not touch existing array of attributes\n if(!Array.isArray(this.type.attrs)) {\n this.type.attrs = this.getAttributes();\n }\n\n if(this.incorrectTypeAttributes) {\n this.toastr.error('Attributes must be separated by comma without spaces', 'Error');\n return;\n }\n\n this.TypeService.updateType(this.type)\n .then(this.handleFormSuccess.bind(this, 'Type was updated'))\n .catch(this.handleFormErrors.bind(this));\n }", "function updateUserIdInDB(userId, userType) {\n var condition = \"type = '\" + userType + \"'\";\n var data = \"value = '\" + userId + \"'\";\n /**\n * We create the final query.\n * @type {string}\n */\n paramsInQuery = \"UPDATE TR_LastUserId SET \" + data + \" WHERE \" + condition;\n console.log(\"Query: \" + paramsInQuery);\n /**\n * We update the data.\n */\n connectionVariable.query(paramsInQuery, function (err, data) {\n if (err) throw err;\n });\n}", "async updateUser () {\n\t// add the team's ID to the user's teamIds array, and the company ID to the companyIds array\n\t\tconst op = {\n\t\t\t$addToSet: {\n\t\t\t\tcompanyIds: this.attributes.companyId,\n\t\t\t\tteamIds: this.model.id\n\t\t\t},\n\t\t\t$unset: {\n\t\t\t\tcompanyName: true\n\t\t\t},\n\t\t\t$set: {\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t}\n\t\t};\n\t\tthis.updateUserJoinMethod(this.user, op);\n\t\tthis.transforms.userUpdate = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.users,\n\t\t\tid: this.user.id\n\t\t}).save(op);\n\t}", "function saveBookingType(type) {\n if (type === 'phone') {\n $scope.editBookingPhone = false;\n }\n else if (type === 'email') {\n $scope.editBookingEmail = false;\n }\n else if (type === 'website') {\n $scope.editBookingUrl = false;\n }\n\n saveBookingInfo();\n }", "setUserData(field, value) {\r\n\r\n // Get all user data\r\n var userData = this.getUserData()\r\n\r\n // Set new field\r\n userData[field] = value\r\n\r\n // Update entity\r\n Entities.editEntity(this.id, JSON.stringify(userData))\r\n\r\n }", "typeOfUser(type) {\n this.setState({userType:type})\n }", "function User_Update_Types_de_personne_Liste_des_types_de_personne0(Compo_Maitre)\n{\n var Table=\"typepersonne\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tp_type=GetValAt(49);\n if (!ValiderChampsObligatoire(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tp_type=\"+(tp_type==\"\" ? \"null\" : \"'\"+ValiderChaine(tp_type)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function set_update_type(type, form){\n\ttry{\n\tvar p = document.createElement(\"input\");\n\n\t// Add the new element to our form. \n\tform.appendChild(p);\n\tp.name = \"update\";\n\tp.type = \"hidden\";\n\tp.value = type;\n\t}\n\tcatch(e) {\n\t\t//alert(\"Error Caught: 260\");\n\t\tlog(\"profile.js\", e.lineNumber, e);\n\t}\n}", "typeUpdate( context, data )\n\t\t{\n\t\t\treturn fetch( `/api/types/${data.id}`, {\n\t\t\t\theaders: {\n\t\t\t\t\t'X-Requested-With': 'XMLHttpRequest',\n\t\t\t\t\t'X-CSRF-token': window.token,\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'Accept': 'application/json',\n\t\t\t\t\t'Authorization': `Bearer ${sessionStorage.getItem('token')}`\n\t\t\t\t},\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbody: JSON.stringify( data )\n\t\t\t})\n\t\t\t\t.then( response => response.json() )\n\t\t\t\t.then( response => {\n\t\t\t\t\tif( response.errors ) {\n\t\t\t\t\t\tcontext.commit( 'errors', response.errors );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcontext.commit( 'errors', []);\n\t\t\t\t\t}\n\t\t\t\t\tcontext.commit( 'message', response.message );\n\t\t\t\t\tcontext.commit( 'success', response.success );\n\t\t\t\t})\n\t\t\t\t.catch( error => console.error( 'typeUpdate', error ) );\n\t\t}", "function alterarTipoGerencia(){\n\tvar unidade = DWRUtil.getValue(\"comboUnidade\"); \n\tvar tipoGerencia = DWRUtil.getValue(\"comboGerencia\"); \n\tFacadeAjax.alterarGerencia(unidade,tipoGerencia);\n}", "function User_Update_Types_de_lien_Liste_des_types_de_lien_entre_personne0(Compo_Maitre)\n{\n var Table=\"typelien\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tl_libelle=GetValAt(45);\n if (!ValiderChampsObligatoire(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle))\n \treturn -1;\n var tl_description=GetValAt(46);\n if (!ValiderChampsObligatoire(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tl_libelle=\"+(tl_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_libelle)+\"'\" )+\",tl_description=\"+(tl_description==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_description)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function setAccountTypeData() \n {\n var pageData = GetPageData();\n setPageData(pageData, \"accounttype\", \"mailaccount\",false);\n setPageData(pageData, \"accounttype\", \"newsaccount\", false);\n // Other account type, e.g. Movemail\n setPageData(pageData, \"accounttype\", \"otheraccount\", true);\n }", "function updateTypeOfVehicle(type){\r\n if ( type == tCar)\r\n isCar = true;\r\n else if ( type == tTruck )\r\n isTruck = true;\r\n else if ( type == tTw )\r\n isTw = true;\r\n }", "set_type(new_type){\n if(new_type){\n this.type = new_type;\n }\n else{\n this.invalid();\n }\n }", "_onEdit(type) {\n this.refs.screen.updateValues(type);\n this.refs.advanced.updateValues(type);\n this.refs.misc.updateValues(type);\n }", "function add_new_user_selection(type){\n\tif(type==0){\n\t\t$(\"#add_professor_option\").prop(\"checked\", false);\n\t\t$(\"#aem_tr\").show();\n\t\t$(\"#add_user_type\").val('0');\n\t}else{\n\t\t$(\"#add_student_option\").prop(\"checked\", false);\n\t\t$(\"#aem_tr\").hide();\n\t\t$(\"#add_user_type\").val('1');\n\t}\n}", "function UserType({\n userType,\n parentId,\n selected,\n updateInstance,\n deleteInstance,\n refetchQueries,\n onSelect,\n // ns__custom_start unit: appSpec, comp: UserType, loc: addedProps\n // ns__custom_end unit: appSpec, comp: UserType, loc: addedProps\n}) {\n const [userTypeValue, updateUserTypeValue] = useState(userType.value);\n const [isEditMode, updateIsEditMode] = useState(false);\n const [isSaving, updateIsSaving] = useState(false);\n const [isDeleteMode, updateIsDeleteMode] = useState(false);\n const [isDeleting, updateIsDeleting] = useState(false);\n // ns__custom_start unit: appSpec, comp: UserType, loc: beginning\n\n const styles = useStyles();\n // ns__custom_end unit: appSpec, comp: UserType, loc: beginning\n\n const screenData =\n userType.children &&\n userType.children.find((child) => child.typeId === TYPE_SCREEN_ID);\n const screens = screenData ? screenData.instances : [];\n // ns__custom_start unit: appSpec, comp: UserType, loc: beforeReturn\n // ns__custom_end unit: appSpec, comp: UserType, loc: beforeReturn\n\n // ns__start_replacement notSelected\n if (selected) {\n return (\n <UserTypeStyleWrapper onClick={() => onSelect(userType.id)}>\n {userTypeValue}\n </UserTypeStyleWrapper>\n );\n }\n // ns__end_replacement notSelected\n\n // ns__start_section change\n function handleUserTypeValueChange(e) {\n updateUserTypeValue(e.target.value);\n }\n // ns__end_section change\n\n // ns__start_section save\n async function handleUserTypeValueSave() {\n updateIsSaving(true);\n\n await updateInstance({\n variables: {\n actionId: UPDATE_USER_TYPE_FOR_APP_SPEC_ACTION_ID,\n executionParameters: JSON.stringify({\n value: userTypeValue,\n instanceId: userType.id,\n }),\n },\n refetchQueries,\n });\n\n updateIsEditMode(false);\n updateIsSaving(false);\n }\n // ns__end_section save\n\n // ns__start_section cancel\n function handleCancelEdit() {\n updateIsEditMode(false);\n }\n // ns__end_section cancel\n\n // ns__start_section isEdit\n if (isEditMode) {\n return (\n <UserTypeStyleWrapper>\n <EditInstanceForm\n id={userType.id}\n label='UserType Value:'\n value={userTypeValue}\n onChange={handleUserTypeValueChange}\n onSave={handleUserTypeValueSave}\n onCancel={handleCancelEdit}\n disabled={isSaving}\n />\n </UserTypeStyleWrapper>\n );\n }\n // ns__end_section isEdit\n\n // ns__start_section delete\n async function handleDelete() {\n updateIsDeleting(true);\n\n try {\n await deleteInstance({\n variables: {\n actionId: DELETE_USER_TYPE_FOR_APP_SPEC_ACTION_ID,\n executionParameters: JSON.stringify({\n parentInstanceId: parentId,\n instanceId: userType.id,\n }),\n },\n refetchQueries,\n });\n } catch (e) {\n updateIsDeleting(false);\n }\n }\n // ns__end_section delete\n\n // ns__start_section cancelDelete\n function handleCancelDelete() {\n updateIsDeleteMode(false);\n }\n // ns__end_section cancelDelete\n\n // ns__start_section isDelete\n if (isDeleteMode) {\n return (\n <UserTypeStyleWrapper selected={selected} isDeleting={isDeleting}>\n {userTypeValue}\n <DeleteInstanceMenu\n onDelete={handleDelete}\n onCancel={handleCancelDelete}\n disabled={isDeleting}\n />\n </UserTypeStyleWrapper>\n );\n }\n // ns__end_section isDelete\n\n // ns__start_section functionReturn\n return (\n <UserTypeStyleWrapper selected={selected}>\n {/* ns__start_replacement instanceValue */}\n\n <InputLabel className={styles.titleLabel}>User Type</InputLabel>\n <TitleWrapper>\n {userTypeValue}\n <div>\n <Button type='button' onClick={() => updateIsEditMode(true)}>\n &#9998;\n </Button>\n <Button type='button' onClick={() => updateIsDeleteMode(true)}>\n &#128465;\n </Button>\n </div>\n </TitleWrapper>\n\n {/* ns__end_replacement instanceValue */}\n\n {/* ns__start_replacement childrenList */}\n\n <Screens\n screens={screens}\n userTypeId={userType.id}\n label={userTypeValue}\n refetchQueries={refetchQueries}\n />\n\n {/* ns__end_replacement childrenList */}\n\n {/* ns__custom_start unit: appSpec, comp: UserType, loc: renderEnding */}\n {/* ns__custom_end unit: appSpec, comp: UserType, loc: renderEnding */}\n </UserTypeStyleWrapper>\n );\n // ns__end_section functionReturn\n}", "function updateUFMap(typeMap) {\r\n\tfor(type in typeMap) ufMap[type] = ufMap[type] ? ufMap[type] + 1 : 1;\r\n}", "function fillAndShowUpdateProfileModal(data, userType) {\n var profileDetails;\n if (userType === 'supervisor') {\n profileDetails = data[0];\n } else if (userType === 'supervisee') {\n profileDetails = data;\n }\n\n $('#user-name').val(\"\");\n $(\".update-profile-pic\").attr('src',profileDetails.image);\n $(\".supervisor-name-label\").each(function(index, value) {\n if (index === 1) {\n $(this).val(profileDetails.first_name + \" \" + profileDetails.last_name);\n }\n })\n $(\".supervisor-email-label\").each(function(index, value) {\n if (index === 1) {\n $(this).val(profileDetails.email);\n }\n })\n $(\".supervisor-role-label\").each(function(index, value) {\n if (index === 1) {\n $(this).val(profileDetails.role);\n }\n })\n $(\".supervisor-address-label\").each(function(index, value) {\n if (index === 1) {\n $(this).val(profileDetails.location);\n }\n })\n modal.modalOverlay.fadeIn(200);\n $(window).scrollTop(0);\n $('body').addClass('fixed');\n modal.updateProfileModal();\n }", "function setEntityType() {\n var new_type = $(this).attr('label')\n var edits = [];\n $(\".entity.ui-selected\").each(function() {\n var eid = this.id;\n edits.push({action:'change_entity_type', id:eid, old_type:entities[eid].type, new_type:new_type});\n });\n if (edits.length > 0) makeEdits(edits);\n return false;\n }", "function changeAccountType() {\n //Creates and sends an AJAX request\n fetch(\"/user/changeUserType\", {\n method: \"PUT\",\n })\n .then(() => {\n location.reload(true);\n alert(\"You've changed your account type\");\n })\n .catch((err) => {\n console.log(err);\n });\n}", "updateSignUpDeveloperCname(state, value) {\n state.signUp.developer.CompanyName = value;\n }", "function addUserToTable(username, userType, userId) {\n users.set(userId, {username: username, userType: userType})\n refreshUserTable();\n}", "function determineAndApplyUpdate(fieldType, stringObjects, addOrDelete, userFriendAppId, bofffsSpecificData, bofffsData)\n{\n\tTi.API.info(\"determineUpdateType\");\n\t\n\t// TODO: Replace this with return statement\n\tif(contact == null) alert(\"Contact must be initialized ya beheema !\");\n\t\n\t// TODO: Handle if addOrDelete\n\tswitch(fieldType) {\n\t\t\n\t\tcase \"phone_number\":\n\t\tcase \"mails\":\n\t\tcase \"social_links\":\n\t\t{\n\t\t\t// Create the type and key strings\n\t\t\t// TODO: Should be replaced on the server with the approperiate key\n\t\t\tvar type, key;\n\t\t\tif(fieldType == \"phone_number\") {\n\t\t\t\ttype = \"phone\";\n\t\t\t\tkey = \"mobile\";\n\t\t\t}\n\t\t\telse if(fieldType == \"mails\") {\n\t\t\t\ttype = \"email\";\n\t\t\t\tkey = \"work\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttype = \"url\";\n\t\t\t\tkey = \"home\";\n\t\t\t}\n\t\t\t\n\t\t\tif(addOrDelete == 'add') UpdateAddableField(type, key, stringObjects[fieldType]);\n\t\t\telse DeleteAddableField(type, stringObjects[fieldType]);\n\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase \"job_title\":\n\t\tcase \"birthday_date\":\n\t\tcase \"company\":\n\t\t// TODO: Adding nickname if needed\n\t\t// TODO: Note if needed\n\t\t{\n\t\t\tvar type;\n\t\t\tif(fieldType == \"job_title\") type = \"jobTitle\";\n\t\t\telse if(fieldType == \"birthday_date\") type = \"birthday\";\n\t\t\telse type = \"company\";\n\t\t\t\n\t\t\tUpdateNonAddableField(type, stringObjects[fieldType]);\n\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tcase \"residence\":\n\t\t\t// TODO: Unimplemented\n\t\t\tbreak;\n\t\t\n\t\tdefault:\n\t\t{\n\t\t\talert(\"ERROR: Field type is not recongnizable.\");\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t\n\t\t/* TODO: It could be done like the first code to remove these if and else statements\n\t\t * but it's better that these names are used to put the updates on the server and when that happens,\n\t\t * there will be no need for these if and else statements\n\t\t */\n\t}\n}" ]
[ "0.8273181", "0.6726988", "0.66048133", "0.65727586", "0.6209959", "0.6169125", "0.60411185", "0.5779423", "0.57591254", "0.56994724", "0.5686445", "0.5627551", "0.5609914", "0.5605066", "0.55989826", "0.55763876", "0.5547815", "0.5544743", "0.55432266", "0.551386", "0.5490869", "0.548787", "0.548097", "0.5479709", "0.54713184", "0.5463851", "0.5404091", "0.5398936", "0.53833", "0.5371777" ]
0.6883742
1
modify the text and flip the cards as necessary to enter the new mode
transitionToNewMode() { console.log('transition'); if (this.card != null) { switch (this.currMode) { case _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].voting: { this.cardText.nativeElement.textContent = ""; this.transitionCardToFace("front"); if (this.votingPhraseText == null) { this.cardText.nativeElement.textContent = "vote above !"; } else { this.cardText.nativeElement.textContent = this.votingPhraseText; } break; } case _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].waiting: { this.cardText.nativeElement.textContent = ""; this.transitionCardToFace("front"); this.cardText.nativeElement.textContent = "waiting ..."; break; } case _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].myTurn: { this.cardText.nativeElement.textContent = ""; this.transitionCardToFace("back"); this.cardText.nativeElement.textContent = this.cardData.card_text; break; } } this.disableCardChooseButton(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function flipCard(card) {\n //Change the question (for now)\n if (card.className !== \"card flipped\") {\n card.children[1].textContent = BTQuestions[counter++];\n if (counter === BTQuestions.length) {\n BTQuestions = shuffle(BTQuestions);\n counter = 0\n }\n }\n card.classList.toggle(\"flipped\");\n}", "function flipCard(card) {\n\tif (card.getAttribute('data-card') === 'queen') {\n\t\tcard.innerHTML = '<img src=\"queen.png\" alt=\"queen\" />';\n\t\t// cardElement.innerHTML = '<img src=\"my_king.png\" alt=\"King of Spades\" />';.\n\t} else {\n\t\tcard.innerHTML = '<img src= \"king.png\" alt=\"king\"/>';\n\t}\n}", "function mirrorText(clickedCard){\n\n//checks clickedCard for class selectedCard\t\nif (clickedCard.classList.contains(\"selectedCard\")){\n//checks clickedCard for the bio class and replaces the innerHTML input.value\t\n\tclickedCard.querySelector(\".bio\").innerHTML = input.value;\n\t}\n\t\n\t\n}", "function flipCard(event) {\n\t// when the card is clicked it flips to the other side\n\t// have the definition side be hidden (toggle) and on click/flip hide the term\n\tterm.classList.toggle('hidden');\n\tdefinition.classList.toggle('hidden');\n}", "function flipCard(){\n if(cardSide == \"QuestionSide\"){\n cardSide = \"AnswerSide\";\n $(\".card-title-question\").hide();\n $(\".card-text-answer\").show();\n console.log(\"show Q\")\n }else{\n $(\".card-title-question\").show();\n $(\".card-text-answer\").hide();\n console.log(\"show A\");\n cardSide = \"QuestionSide\"\n }\n }", "function flipFlashCard(el) {\n el.parentNode.parentNode.querySelector(\".answer\").style.opacity = \"1\";\n el.parentNode.querySelector(\".correct-answer\").disabled = false;\n el.parentNode.querySelector(\".wrong-answer\").disabled = false;\n\n textToSpeech();\n}", "function flipCard() {\n\n\tfor(var i = 0; i <= 5; i++)\n\t{\n\t\tif($('#card' + (i + 1)).text() == 'L') {\n\t\t\tvar c = Math.floor((Math.random() * largeValues.length));\n\t\t\tcards.push(largeValues[c]);\n\t\t}else {\n\t\t\tvar c = Math.floor((Math.random() * smallValues.length));\n\t\t\tcards.push(smallValues[c]);\n\t\t}\n\t\t$('#card' + (i + 1)).text(cards[i]);\n\t}\n}", "function updateFront(){\r\n\t\t\tdocument.getElementById(\"flashcard-content-front\").innerHTML = currentText;\r\n\t\t\t\r\n\t\t}", "function flipCard(card_index) \n{\n if(speelveld[card_index].classList.contains('flipped')) {\n speelveld[card_index].classList.remove('flipped');\n speelveld[card_index].children[CARD_FRONT].innerHTML = \"\";\n } else {\n speelveld[card_index].children[CARD_FRONT].innerHTML = getCardImageTag(card_index);\n speelveld[card_index].classList.add('flipped');\n }\n}", "function changeText() {\n\t\tflipDisableOption();\n\t\trunning = true;\n\t\tcurrentFrames = $(\"text-area\").value;\n\t\tcurrentInterval = setInterval(insertFrame, currentSpeed);\n\t}", "function showBack() {\n // return all words that are not on the front of the card and that have a value for their key\n const backWords = ['english', 'kana', 'kanji']\n .map(k => k !== CURRENT_CARD.front && CURRENT_CARD[k])\n .filter(j => !!j);\n const innerText = `<p style=\"font-size:28px\" align=\"center\">${backWords.join('<br><br>')}</p>`;\n\n CURRENT_CARD.showingFront = false;\n document.getElementById('flashcard').innerHTML = innerText;\n\n}", "function flipEasyCard() {\n var easyCardId = this.getAttribute('data-id'); \n easyCardsSelected.push(kittenCardsEasy[easyCardId].name);\n easyCardsSelectedId.push(easyCardId);\n this.setAttribute('src', kittenCardsEasy[easyCardId].img);\n this.setAttribute('alt', kittenCardsEasy[easyCardId].name);\n if (easyCardsSelected.length === 2) {\n checkEasyMatch(); \n } else if (easyCardsSelected.length > 2) {\n this.setAttribute('src', './assets/images/kitten-card-back.png');\n }\n easyCardsSelected.length = Math.min(easyCardsSelected.length, 2);\n}", "function flippCard(){\n\n /* Flipp is a boolean variable that stores whether we need to flip the card or to not. */\n flipp = !flipp;\n\n /* save the tranform attribute value to rotate the card in temp variable */\n let temp = \"rotateY(180deg)\";\n\n /* If the flipp stores false that means User dont want to flip the card or want to undo it so remove the attribute from temp */\n if(!flipp){\n temp = \"\"; /* Overwriting the temp to forget prev value */\n }\n\n /* As decided: update the transform attribute of the front-card element to temp */\n document.getElementById(\"front-card\").style.transform = temp;\n}", "function drawFlipCard(cards) {\n\n _.each(cards, function(card) {\n\n var $tmplFlipCard = $($(\"#templateFlipCard\").html());\n\n // Set the name of the card for Google Analytics\n $(\"#data-cardname\", $tmplFlipCard).html(card.name);\n\n // Set the question for the front of the card\n $(\".question\", $tmplFlipCard).html(card.question)\n\n // Set the back content of the card\n $(\".back1\", $tmplFlipCard).html(card.back1);\n $(\".back2\", $tmplFlipCard).html(card.back2);\n $(\".back3\", $tmplFlipCard).html(card.back3);\n $(\".back4\", $tmplFlipCard).html(card.back4);\n $(\".back5\", $tmplFlipCard).html(card.back5);\n\n\n\n\n $(\"img.background-image\", $tmplFlipCard).attr(\"src\", \"img/training/\" + card.image);\n\n // _NOW_ we add this template to the training page\n $(\"#flipCardList\").append($tmplFlipCard);\n\n });\n\n // Flip Cards Flipping Script\n // ====================================\n $('.flip').on('click', function(event) {\n $(event.target).parents('.card').toggleClass('flipped');\n });\n\n}", "cardFlip(card) {\n if (this.allowedToFlip(card)) {\n this.soundControl.flip();\n this.totalClicks++;\n this.ticktok.innerText = this.totalClicks;\n card.classList.add('visible');\n\n if(this.verifyCard) {\n this.checkForCardMatch(card);\n } else {\n this.verifyCard = card;\n }\n }\n }", "function flipCard(cardElem) {\n // Count flip\n data.flips += 1;\n\n cardElem.classList.add(FLIP);\n\n // Update aria label to symbol\n cardElem.setAttribute('aria-label', cardElem.dataset.symbol);\n }", "function nextCard()\r\n\t\t{\r\n\t\t\tvar length = questions.length;\r\n\r\n\t\t\tif(questionNumber<length-1)\r\n\t\t\t\tquestionNumber++;\r\n\t\t\telse\r\n\t\t\t\tquestionNumber=0;\r\n\t\t\t\r\n\t\t\tif(cardState==0){\r\n\t\t\t\tcurrentText = questions[questionNumber];\r\n\t\t\t\tupdateFront();\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tflipCard();\r\n\t\t\t\tflashcard.classList.toggle('flipped');\r\n\t\t\t\tupdateText();\r\n\t\t\t}\r\n\r\n\t\t}", "function flipBack() {\n $('.card').filter($('.open')).toggleClass('open');\n OpenCards = [];\n numOfmoves = numOfmoves + 1;\n $('.moves').text(numOfmoves);\n }", "function flipCard() {\r\n //this - whatever card we have clicked \r\n //we're getting the card clicked id and store to the cardsArray arrayChosen but only the name \r\n let cardId = this.getAttribute('data-id')\r\n cardsChosen.push(cardsArray[cardId].name)\r\n cardsChosenIds.push(cardId)\r\n\r\n //flip the card when clicked\r\n this.setAttribute('src', cardsArray[cardId].img)\r\n\r\n //revert if two selected aren't the same\r\n if (cardsChosen.length === 2) {\r\n setTimeout(checkForMatch, 500)\r\n\r\n }\r\n\r\n }", "function flipCardKeyboard(card) {\n\t\tif (!cards[card].classList.contains('open', 'show', 'match') && chosenCards.length !== 2) {\n\t\t\t\tcards[card].classList.add('open');\n\t\t\t\taddChosenCard(cards[card]);\n\t\t\t\tif (timer === false && pairsRemain > 0) {\n\t\t\t\t\t\ttimerOn();\n\t\t\t\t}\n\t\t\t\tsetTimeout(showCard, 300, cards[card]);\n\t\t}\n}", "function turnCard() {\n\tcount++;\n\tif (count % 2 === 0) {\n\t\tthis.innerText = 'X';\n\t} else {\n\t\tthis.innerText = 'O';\n\t}\n\n}", "function unFlipCard(str) {\n document.getElementById(\"chosen-one\").style = \"transform: rotateY(180);\";\n document.getElementById(\"chosen-two\").style = \"transform: rotateY(180);\";\n\n document.getElementById(\"chosen-one\").id = \"\";\n document.getElementById(\"chosen-two\").id = \"\";\n clickCount = 0;\n}", "function changeCard() {\n $(\".questions\").hide();\n $(\"#question\" + next).show();\n $(\".feedback_containers\").fadeOut();\n $(\".incorrect\").hide();\n $(\".correct\").hide();\n $(\".notification\").fadeOut();\n $(\"#test_card\").css({left: to}).animate({left: \"0%\"});\n }", "function showFront() {\n // Just update the text with the current card's front word\n const innerText = `<p style=\"font-size:32px\" align=\"center\">${CURRENT_CARD[CURRENT_CARD.front]}</p>`;\n\n CURRENT_CARD.showingFront = true;\n document.getElementById('flashcard').innerHTML = innerText;\n}", "function flip(card){\r\ncard.target.classList.add(\"open\");\r\ncard.target.classList.add(\"show\");\r\n\r\n}", "function flipCard(card_index)\n{\n if(speelveld[card_index].classList.contains('flipped')) {\t// Bevat de kaart al de css class flipped?\n /*\n Ja!\n Dan gaan de kaart weer terugdraaien door de css class flipped weer weg te halen\n */\n speelveld[card_index].classList.remove('flipped');\t\t\t// Hier halen we de css class flipped weg\n speelveld[card_index].children[CARD_FRONT].innerHTML = \"\";\t// We gaan de img-tag ook weer verwijderen\n } else {\n /*\n Nee!\n Dan draaien we de kaart om zodat de afbeelding zichtbaar wordt.\n Dit doen we door de css class flipped toe te voegen aan de kaart en de tweede div\n in de kaart te vullen met de img-tag van de echte afbeelding\n */\n speelveld[card_index].children[CARD_FRONT].innerHTML = getCardImageTag(card_index);\t// Toon de afbeelding\n speelveld[card_index].classList.add('flipped');\t\t\t\t\t\t\t\t\t\t// Voeg de css class flipped toe.\n }\n}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCard) return;\n this.classList.add('flip');\n if (!hasFlippedCard) {\n //first card clicked\n hasFlippedCard = true;\n firstCard = this;\n return;\n }\n //second card clicked\n hasFlippedCard = false;\n secondCard = this;\n checkForMatch();\n\n if (checkWin()){\n stopCheck.stop(`/memory-solution-saver/${gameId}`);\n }\n\n\n }", "function flipCard(card) {\n //if there is no card clicked\n if(flippedCard === null){\n flippedCard = card;\n flippedCard.classList.toggle(\"active\");\n //if there is a card already clicked\n } else if(secondCardFlipped === null) {\n secondCardFlipped = card;\n secondCardFlipped.classList.toggle(\"active\");\n \n //if cards have different content:\n if(flippedCard.textContent.trim() !== secondCardFlipped.textContent.trim()) {\n setTimeout(\n function(){\n flippedCard.classList.remove(\"active\");\n secondCardFlipped.classList.remove(\"active\"); \n //Back to the original\n flippedCard = null;\n secondCardFlipped = null;\n }, 2000\n );\n } else {\n //if cards have the same content\n //Back to the original\n flippedCard = null;\n secondCardFlipped = null;\n }\n } \n}", "function flipNeutralCard (cardRank) {\n lastNeutralCard = cardRank;\n $('.upcard').empty();\n $( ` <div class=\"card rank-${cardRank} diams\">\n <span class=\"rank\">${cardRank}</span>\n <span class=\"suit\">&diams;</span>\n </div>` ).appendTo( \".upcard\" );\n }", "function startAbout(){\n $(\"#flippy_A1\").text(\"A\");\n $(\"#flippy_B1\").text(\"B\");\n $(\"#flippy_B2\").text(\"O\");\n $(\"#flippy_B3\").text(\"U\");\n $(\"#flippy_C2\").text(\"T\");\n }" ]
[ "0.6693379", "0.6615352", "0.6580999", "0.65573806", "0.6531578", "0.644659", "0.6374866", "0.63484454", "0.6326378", "0.6326366", "0.62626284", "0.62561923", "0.6254042", "0.6251482", "0.6244136", "0.6243179", "0.6217477", "0.621517", "0.62074244", "0.6166291", "0.61537254", "0.61172587", "0.6098115", "0.6079678", "0.6074274", "0.6074091", "0.6066125", "0.60575306", "0.6023183", "0.6022347" ]
0.664673
1
disable the choice button to select a card when it is not a player's turn
disableCardChooseButton() { let choiceButtonIsDisabled = this.choiceButton.nativeElement.classList.contains('disabled'); if ((this.currMode == _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].voting && !choiceButtonIsDisabled) || (this.currMode == _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].myTurn && choiceButtonIsDisabled) || (this.currMode == _entity_data_structures_card_modes__WEBPACK_IMPORTED_MODULE_1__["cardMode"].waiting && !choiceButtonIsDisabled)) { this.choiceButton.nativeElement.classList.toggle('disabled'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function selectCard (card) {\n humanPlayer.hand.tradeIns[card] = !humanPlayer.hand.tradeIns[card];\n \n if (humanPlayer.hand.tradeIns[card]) {\n dullCard(HUMAN_PLAYER, card);\n } else {\n fillCard(HUMAN_PLAYER, card);\n }\n}", "function disableCorrectCards(){\n $(selectedCards[0]).find('.card-front').attr('src','images/done-card-back.png');\n $(selectedCards[1]).find('.card-front').attr('src','images/done-card-back.png');\n $(selectedCards[0]).find('.card-front').removeClass('active');\n $(selectedCards[1]).find('.card-front').removeClass('active');\n $(selectedCards[0]).off('click');\n $(selectedCards[1]).off('click');\n flipCardsBackDown();\n}", "function buttondisable1 () {\n $('#playcard').prop('disabled', false)\n}", "function disableCardClick() {\n setTimeout(() => {\n $(\".matched\").off(\"click\", clearCardInPlay);\n }, 500);\n }", "function onDisableCards(e) {\n\t\tuserInterface.disableRestartBtn();\n\n\t\tcards.forEach(card => {\n\t\t\tcard.disableMe();\n\t\t});\n\t}", "function disableCards() {\n app.lockBoard = true;\n setTimeout(() => {\n app.firstCard.style.pointerEvents = \"none\";\n app.secondCard.style.pointerEvents = \"none\";\n resetBoard();\n }, 500);\n}", "function disableCards() {\n firstCard.removeEventListener('click', flipCard);\n secondCard.removeEventListener('click', flipCard);\n resetBoard();\n winner();\n }", "function playercardturn(player){\n //show cards\n //ask to select cards to play\n //push them into action slot\n }", "function disable() {\n Array.prototype.filter.call(cards, function(cards) {\n card.classList.add(\"disable\");\n });\n }", "function disable(){\n [].filter.call(allCardsGame, function(card) {\n card.classList.add('disabled');\n });\n}", "function start_turn(){\n\tif(dbg){\n\t\tdebug(\"Start turn\");\n\t}\n\t\n\t//enable selection buttons\n\tvar x = document.getElementsByClassName(\"select\");\n\tfor (i=0; i < x.length; i++){\n\t\tx[i].disabled = false;\n\t}\n}", "function disableCards(){\n let name = secondCard.dataset.name;\n player.innerHTML = name;\n firstCard.removeEventListener(\"click\", flipCard);\n secondCard.removeEventListener(\"click\", flipCard);\n player.classList.add(\"active\");\n resetBoard();\n setTimeout(gameFinished,1000);\n setTimeout(()=>{\n player.classList.remove(\"active\");\n },2000)\n}", "function disable() {\n Array.prototype.filter.call(cards, function (card) {\n if (card.className === 'card') {\n card.className += ' disabled';\n }\n });\n}", "function disableCLick() {\n openCards.forEach(function (card) {\n card.off('click');\n });\n}", "function enableCardOrNot(){\n let transferenciaELEM = document.getElementById(\"selectorDatosCuenta\");\n let sel = document.getElementById(\"selectorTarjeta\");\n let tarjetaELEM = document.getElementById(\"tarjeta\");\n let esTarjeta = tarjetaELEM.checked;\n if(esTarjeta){\n transferenciaELEM.disabled = true;\n sel.disabled = false;\n } else {\n transferenciaELEM.disabled = false;\n sel.disabled = true;\n }\n}", "function chosenClick() {\n if (core || all || career) { // If any other tab is currently open, set them to false and show user's chosen courses\n setAll(false);\n setCore(false);\n setCareer(false);\n setChosen(true);\n }\n }", "function handleChoiceCardType(e) {\n if (currentPage == \"cardservice/create/visa/card-unlock\") {\n handleChoiceCardTypeClose();\n if ((e.selectedValue1 != undefined) && (e.selectedValue1 != null)) {\n var tagAccNo = document.getElementById(\"open-card-lock-type\");\n if (tagAccNo.nodeName == \"INPUT\") {\n tagAccNo.value = e.selectedValue1;\n }\n else {\n tagAccNo.innerHTML = e.selectedValue1;\n }\n }\n if ((e.selectedValue2 != undefined) && (e.selectedValue2 != null)) {\n if(pCardTypeSelected != e.selectedValue2) {\n document.getElementById(\"open-card-lock-no\").value = CONST_STR.get('COM_TXT_SELECTION_PLACEHOLDER');\n }\n pCardTypeSelected = e.selectedValue2;\n\n //disable if do not card\n document.getElementById(\"open-card-lock-no\").disabled = 'disable';\n for(var i=0; i< gTrans.carUnLockArr.length; i++) {\n var tmpCard = gTrans.carUnLockArr[i];\n if(tmpCard.LOAI_THE == pCardTypeSelected) {\n document.getElementById(\"open-card-lock-no\").disabled = '';\n break;\n }\n }\n }\n }\n }", "function freezeEnBoard() {\n setTimeout(() => {\n if (enCardInPlay >= 1) {\n $(\".game-card-en\").off(\"click\", playGame);\n }\n }, 100);\n }", "function disable() {\n openCards[0].classList.add('disabled');\n openCards[1].classList.add('disabled');\n allCards.forEach(function(card) {\n card.classList.add('disabled');\n });\n}", "function setChoosingStateOn() {\n\t\tplayerIsChoosing = true;\n\t}", "enableAll(){\n let guessedCards = this.state.guessedCards;\n guessedCards = guessedCards.flat();\n let clickedCards = this.state.clickedCards;\n clickedCards = clickedCards.flat();\n $('button').each(function(){\n this.disabled = false;\n });\n }", "function disableCards() {\n firstCard.removeEventListener('click', flipCard);\n secondCard.removeEventListener('click', flipCard);\n\n resetBoard();\n }", "function lockChoice(){\r\n $(\"input\").attr(\"disabled\", true);\r\n}", "function end_turn(){\n\tif(dbg){\n\t\tdebug(\"ending turn\");\n\t}\n\tupdate_hand();\n\tvar x = document.getElementsByClassName(\"actions\");\n\tfor (i=0; i < x.length; i++){\n\t\tx[i].disabled = true;\n\t}\n}", "function noPair () {\n openCards[0].classList.add(\"noPair\");\n openCards[1].classList.add(\"noPair\");\n /*stops the possibility of clicking a third card*/\n disable();\n /*delay of animation after clicking two cards*/\n setTimeout (function(){\n openCards[0].classList.remove(\"show\", \"open\", \"noPair\");\n openCards[1].classList.remove(\"show\", \"open\", \"noPair\");\n /*when it isnt a match, allow player to click again on the cards*/\n enable();\n openCards = [];\n /*time of animation*/\n },600);\n }", "function notMatched() {\n let selected = document.querySelectorAll('.selected');\n selected.forEach(function(card) {\n card.classList.add('unmatched');\n });\n disable();\n guessesReset();\n}", "function disableCards() {\n firstCard.removeEventListener('click', flipCard);\n secondCard.removeEventListener('click', flipCard);\n resetBoard();\n}", "function disableCards() {\n firstCard.removeEventListener('click', flipCard);\n secondCard.removeEventListener('click', flipCard);\n ++score;\n checkForWin();\n resetBoard();\n}", "function handleSelection(choice) {\n // document.getElementById('usertype').disabled=false;\n document.getElementById(choice).style.display=\"block\";\n \n}", "function forbiden(){\n\tdocument.getElementById(\"sub\").disabled = true;\n\tdocument.getElementById(\"A_choice\").disabled = true;\n\tdocument.getElementById(\"B_choice\").disabled = true;\n\tdocument.getElementById(\"C_choice\").disabled = true;\n\tdocument.getElementById(\"D_choice\").disabled = true;\n}" ]
[ "0.68734705", "0.680857", "0.6636066", "0.6599548", "0.6596022", "0.6585438", "0.6512607", "0.650694", "0.64482456", "0.6443079", "0.6438787", "0.6417244", "0.63575923", "0.63459194", "0.6343458", "0.63352144", "0.6319061", "0.6315705", "0.6285187", "0.62676185", "0.6257512", "0.6222807", "0.62098765", "0.6205584", "0.6185723", "0.61408895", "0.61317956", "0.6131728", "0.61310744", "0.61206704" ]
0.7814878
0
get list of all players excluding this current one
getAllOtherPlayersList(allPlayers) { console.log("all players: " + allPlayers); var output = []; allPlayers.forEach((player) => { if (player.Id != this.socket.id) { output.push(player); } }); console.log("all other players: " + output); return output; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getBluePlayers() {\r\n\treturn room.getPlayerList().filter(p => p.team == 2);\r\n}", "function getRedPlayers() {\r\n\treturn room.getPlayerList().filter(p => p.team == 1);\r\n}", "getAllPlayers() {\n return Player.find({}).exec();\n }", "function removeAllPlayers() {\n listPlayers.splice(0, listPlayers.length);\n saveListPlayers();\n buildPlayerPanel();\n rebuilt_list_player();\n hideGame(false);\n}", "function getOthers(id) {\n var players = [];\n Object.keys(io.sockets.connected).forEach(function (socketID) {\n var player = io.sockets.connected[socketID].player;\n if (player && player.id != id) {\n players.push(player);\n }\n })\n return players;\n}", "getAllPlayers(){\n var allPlayers = [];\n for(var i = 0; i < this.teams.length; i++){\n var team = this.teams[i];\n for(var j = 0; j < team.players.length; j++){\n var player = team.players[j];\n allPlayers.push(player);\n }\n }\n return allPlayers;\n }", "fetchPlayers() {\n if(this.players.length === 0) { return []; }\n return this.players.map((value) => value._player);\n }", "playersAdressed() {\n let senderID = parseFloat(this.transfer.senderID);\n let players = [];\n if (!isNaN(senderID)) {\n players = this.bank.players.filter(p => p.id !== senderID);\n }\n\n return players.sort((a, b) => a.name.localeCompare(b.name));\n }", "getFilteredPlayers() {\n const {players, filter} = this.state;\n if (players.length < 1 || filter.length < 1) {\n return players;\n } else {\n return players.filter(player=>{\n return (player.first_name + \" \" + player.last_name).toLowerCase()\n .indexOf(filter.toLowerCase()) > -1;\n })\n }\n }", "remove(player) {\n this.players = this.players.filter(p => p.id !== player.id);\n }", "getDisqualifiedPlayerIds() {}", "function getPlayers() {\n $.get(\"/api/standardPlayers\", function (data) {\n console.log(\"get\");\n players = _.filter(data, function (player) {\n return player.TeamId === null \n });\n\n createPlayerRow(null);\n\n });\n }", "function removePlayer(){\r\n\tfor(player of allPlayers.values()){\r\n\t\tif(player.remove){\r\n\t\t\tallPlayers.delete(player.id);\r\n\t\t}\r\n\t}\r\n}", "static findPlayersStillAlive() {\n return Character.instances.filter((player) => {\n player.state === \"Playing\";\n });\n }", "remoteNonMembers() {\n if (!this.data) {\n return [];\n }\n\n return (this.data.out_of_channel || []).\n filter((profile) => this.filterProfile(profile)).\n map((profile) => ({\n type: Constants.MENTION_NONMEMBERS,\n ...profile,\n }));\n }", "getPlayers() {\n\t\treturn this.lobbyPlayers;\n\t}", "getPlayers () {\n return this.#players\n }", "function getPlayers(filter) {\n currentPlayers = []\n\n var endpoint = \"/player\";\n switch (filter.timespan) {\n case \"This month\": endpoint += \"/month\"; break;\n case \"This week\": endpoint += \"/week\"; break;\n case \"Today\": endpoint += \"/today\"; break;\n }\n\n getPlayersFilter(endpoint);\n\n var aux = [];\n\n if (filter.search) {\n currentPlayers.forEach(function (current) {\n if (current.username.toLowerCase().includes(filter.search.toLowerCase())) {\n aux.push(current);\n return;\n }\n });\n\n currentPlayers = aux;\n }\n}", "function compactPlayers() {\n\tfor (var id in players) {\n\t\tvar compactPlayers = {}\n\t\tif (players[id] == null || players[id] == undefined) continue\n\t\tcompactPlayers[id] = players[id]\n\t\tplayers = compactPlayers\n\t}\n}", "function stopAndHidePlayers(except){\n\t\t\n\t\tvar arrPlayers = [\"youtube\", \"vimeo\", \"html5\", \"soundcloud\", \"wistia\"];\n\t\tfor(var index in arrPlayers){\n\t\t\tvar player = arrPlayers[index];\n\t\t\tif(player == except)\n\t\t\t\tcontinue;\n\t\t\tswitch(player){\n\t\t\t\tcase \"youtube\":\t\t\t\t\t\n\t\t\t\t\tg_youtubeAPI.pause();\n\t\t\t\t\tg_youtubeAPI.destroy();\t\n\t\t\t\t\tg_objYoutube.hide();\n\t\t\t\tbreak;\n\t\t\t\tcase \"vimeo\":\n\t\t\t\t\tg_vimeoAPI.pause();\n\t\t\t\t\tg_vimeoAPI.destroy();\n\t\t\t\t\tg_objVimeo.hide();\n\t\t\t\tbreak;\n\t\t\t\tcase \"html5\":\n\t\t\t\t\tg_html5API.pause();\n\t\t\t\t\tg_objHtml5.hide();\n\t\t\t\tbreak;\n\t\t\t\tcase \"soundcloud\":\n\t\t\t\t\tg_soundCloudAPI.pause();\n\t\t\t\t\tg_soundCloudAPI.destroy();\n\t\t\t\t\tg_objSoundCloud.hide();\n\t\t\t\tbreak;\n\t\t\t\tcase \"wistia\":\n\t\t\t\t\tg_wistiaAPI.pause();\n\t\t\t\t\tg_objWistia.hide();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t}", "getPlayers() {\n\t\treturn this.players;\n\t}", "function removeAllPlayer() {\n //hide all player name\n $('#rightPlayerName').css(\"display\", \"none\");\n $('#leftPlayerName').css(\"display\", \"none\");\n $('#topPlayerName').css(\"display\", \"none\");\n\n //hide all player card\n $('#rightPlayerCards').css(\"display\", \"none\");\n $('#leftPlayerCards').css(\"display\", \"none\");\n $('#topPlayerCards').css(\"display\", \"none\");\n\n //remove all ready\n $('#rightPlayerReady').css(\"display\", \"none\");\n $('#leftPlayerReady').css(\"display\", \"none\");\n $('#topPlayerReady').css(\"display\", \"none\");\n\n //remove all uno\n $('#rightPlayerUno').css(\"display\", \"none\");\n $('#leftPlayerUno').css(\"display\", \"none\");\n $('#topPlayerUno').css(\"display\", \"none\");\n}", "function _getThePeople() {\n\tconst match = _storage.getState().Match;\n\tconst { uid } = _storage.getState().Main.user;\n\treturn Object.keys(match.players).map(_pid => {\n\t\tconst pl = match.players[_pid];\n\t\tif (pl.status !== 'D') {\n\t\t\treturn Div({className: 'player-box'}, [\n\t\t\t\t(match.id === uid && _pid !== uid)\n\t\t\t\t? Div({ className: 'delete-btn', onclick: kick })\n\t\t\t\t: Div(),\n\t\t\t\tSpan({}, pl.displayName),\n\t\t\t\tDiv({ className: 'score' }, [Span({}, `x${pl.score}`), Span({className: 'score-coin'})])\n\t\t\t])\n\t\t}\n\t\treturn;\n\t})\n}", "getAlivePlayers(id) {\n return this.getRoom(id).players.filter((player) => player.alive === true);\n }", "function players() {\n return Object.assign({}, homeTeam().players, awayTeam().players);\n}", "function getAllDevsExceptThoseInActiveDevGroup() {\n \n //holds the developers who are NOT in the current active developer group \n var inactiveDevs = [];\n \n //grab each of the developer objects from the hash table\n for (var devId in allDevelopers) {\n \n //if this is a developer property\n if (allDevelopers.hasOwnProperty(devId)) {\n \n //if the dev is not in the active dev group\n if(!currentDeveloperGroup.memberIds.includes(devId)) {\n \n //add the inactive dev to the list\n inactiveDevs.push(allDevelopers[devId]);\n } \n }\n }\n \n return inactiveDevs;\n}", "get players() {\n return this._players;\n }", "function stopPlayers() {\n\tgroupPlayer.forEach(\n\t\tfunction(player) {\n\t\t\tplayer.body.velocity.x = 0;\n\t\t\tplayer.body.velocity.y = 0;\n\t\t\tplayer.body.gravity.y = 0;\n\t\t}\n\t)\n}", "getOtherPlayer(basePlayer = this.currentPlayer) {\n return this.players.find((player) => player.color !== basePlayer.color);\n }", "function getPlayersFilter(endpoint) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", endpoint, false);\n xhr.onreadystatechange = function () {\n if (this.status === 200 && this.readyState === 4) {\n JSON.parse(this.responseText).players.forEach(function (r) {\n currentPlayers.push(r);\n });\n }\n }\n xhr.send();\n}" ]
[ "0.660605", "0.6592557", "0.6487351", "0.64639515", "0.64142793", "0.636623", "0.6298725", "0.627018", "0.6214694", "0.61836666", "0.61701465", "0.61569387", "0.6130434", "0.61053574", "0.6086726", "0.6076323", "0.60375464", "0.59678966", "0.5960814", "0.59538", "0.5928698", "0.58566946", "0.58263505", "0.58261114", "0.58043104", "0.58023524", "0.57515854", "0.57421565", "0.5739148", "0.573053" ]
0.70125395
0
signal to the server that a card was picked
pickCard(card) { this.socket.emit('clientPickedCard', this.connectedRoom, card); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "moveCardFromHandToDiscard(card) {\n this.socket.emit(\"moveCardFromHandToDiscard\", card.uniqueName);\n }", "function playercardturn(player){\n //show cards\n //ask to select cards to play\n //push them into action slot\n }", "function selectCard(evt) {\n console.log(\"select card\", evt);\n // retrieve .card element\n var card = $(evt.target);\n if(card.hasClass(\"symbol\")) {\n card = card.parent(\".card\");\n }\n // toggle selected state\n card.toggleClass(\"selected\");\n // if 3 selected cards: stop selection mode and send selection action\n var selection = $.map($(\".card.selected\"), function(e) {return Number.parseInt(e.id.substr(5))});\n if(selection.length == 3) {\n stopTrioSelection(\"Wait\", null);\n send({'type': 'select_trio', 'selection': selection});\n }\n}", "function selectCard (card) {\n humanPlayer.hand.tradeIns[card] = !humanPlayer.hand.tradeIns[card];\n \n if (humanPlayer.hand.tradeIns[card]) {\n dullCard(HUMAN_PLAYER, card);\n } else {\n fillCard(HUMAN_PLAYER, card);\n }\n}", "getPickedCard() {\n let observable = new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this.socket.on('serverSendCardPicked', (cardObject) => {\n if (cardObject) {\n observer.next(cardObject.card_text);\n }\n else {\n observer.next(null);\n }\n });\n return () => {\n this.disconnectSocket();\n };\n });\n return observable;\n }", "function pickupBeforeStage(event) {\n\tvar pickUpLink = event.data.replace(\"pickupBeforeStage\", \"\");\n\t$(\"#extra1\").attr(\"src\", \"http://\"+ ip + pickUpLink);\n\tgetCurrHand();\n\tvar cardTracker = 0;\n\tfor (var i = 0; i < handCardSRC.length; i++) {\n\t\tvar tempCardLink = handCardSRC[i].replace(\"http://\"+ip,\"\");\n\t\ttempCardLink = tempCardLink.split('%20').join(' ');\n\t\tif (tempCardLink != \"/resources/images/all.png\")\n\t\t\tcardTracker++;\n\t}\n\t\n\tnumCards = cardTracker;\n\tif (cardTracker > 12) {\n\t\tdocument.getElementById(\"doneEquipment\").disabled = true;\n\t\tvar serverMsg = document.getElementById(\"serverMsg\");\n\t\tserverMsg.value += \"\\n> you must choose a card to continue (or right-click to discard) when it is your turn\";\n\t}\n}", "function firstcardselected() {\n var cardposition = memory_tile_ids[0]; //change position later\n // ADD FUNCTION FROM FRONTEND TO GET CARD POSITION\n socket.emit('firstcardselected', {cardposition: cardposition} //CHANGE TO VAR SELECTEDPOSITION\n );\n}", "function onScan(card, req) {\n recordAccess(req);\n if (card.secure && card.deactivate) {\n email.sendDeactivated(card);\n secure.deactivateCard(card);\n }\n else if (card.deactivate) {\n let res = moveId(card);\n let id = res.id;\n email.sendMoved(id, card);\n }\n}", "function grab(boolean) {\n if (boolean) {\n socket.emit(\"grab\", { grabbedCard: currentGrabbedCard});\n }\n else {\n // keep cards selected until menu is closed\n if (isBattleMenuOpen === false) {\n socket.emit(\"release\");\n }\n }\n }", "function pickCard(numberSent) {\n if (cardsontable > 0) {\n hideCard(numberSent);\n deck.push(numberSent);\n cardsontable--;\n table[numberSent] = false; //remember that card is no longer on the table\n }\n}", "function pick(playerClicked){\r\n pPick = playerClicked;\r\n cPick = computerChooses();\r\n countdown();\r\n}", "function PickupCards(newCards) {\n\tvar testBonus = false;\n\tgetCurrHand();\n\tif (newCards.startsWith(\"PickupCardsProsperity\")) {\n\t\twhichEvent = \"Prosperity\";\n\t\tnewCards = newCards.replace(\"PickupCardsProsperity\", \"\");\n\t}\n\tif(newCards.startsWith(\"PickupCardsTestBonus\")) {\n\t\tnewCards = newCards.replace(\"PickupCardsTestBonus\",\"\");\n\t\ttestBonus = true;\n\t}\n\tif(newCards.startsWith(\"PickupCardsQueensFavor\")) {\n\t\twhichEvent = \"Queens Favor\";\n\t\tnewCards = newCards.replace(\"PickupCardsQueensFavor\",\"\");\n\t}\n\tif(newCards==\"null\") return;\n\tnewCards = newCards.split(\";\");\n\tnewCards.pop();\n\tvar numNewCards = newCards.length;\n\tfor (var i = 0; i < handCardID.length; i++) {\n\t\tif (handCardSRC[i] == \"http://\"+ip+\"/resources/images/all.png\") {\n\t\t\tvar imageId = handCardID[i];\n\t\t\tif(testBonus) { var tempLink = getLinkFromName(newCards.pop()) } else {\n\t\t\t\tvar tempLink = newCards.pop();\n\t\t\t}\n\t\t\t\n\t\t\t$(\"#\" + imageId).attr(\"src\",\n\t\t\t\t\t\"http://\"+ ip + tempLink);\n\t\t\tif (newCards.length == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvar cardTracker = 0;\n\tfor (var i = 0; i < handCardSRC.length; i++) {\n\t\tvar tempCardLink = handCardSRC[i].replace(\"http://\"+ip, \"\");\n\t\ttempCardLink = tempCardLink.split('%20').join(' ');\n\t\tif (tempCardLink != \"/resources/images/all.png\")\n\t\t\tcardTracker++;\n\t}\n\n\tcardTracker += numNewCards;\n\tnumCards = cardTracker;\n\tif (cardTracker > 12) {\n\t\tvar serverMsg = document.getElementById('serverMsg');\n\t\tserverMsg.value += \"\\n> right click to remove extra cards to continue (for discard)\";\n\t\tif (isAI == true) {\n\t\t\tvar data = JSON.stringify({\n\t\t\t\t'AICommand' : 'DiscardChoice',\n\t\t\t\t'numCards' : (cardTracker - 12),\n\t\t\t\t'name' : PlayerName\n\t\t\t})\n\t\t\tsocketConn.send(data);\n\t\t\treturn;\n\t\t}\n\n\t\tdiscard();\n\t}\n\t\n\tif(numCards <= 12 && whichEvent == \"Queens Favor\") {\n\t\tconsole.log(\"sending queens favor\");\n\t\tvar data = JSON.stringify({\n\n\t\t\t'doneEventQueensFavor' : 0\n\t\t})\n\t\tsetTimeout(function(){ socketConn.send(data); }, 1000);\n\t}\n\t\n\tif(numCards <= 12 && whichEvent == \"Prosperity\") {\n\t\tconsole.log(\"sending prosperity\");\n\t\tvar data = JSON.stringify({\n\n\t\t\t'doneEventProsperity' : 0\n\t\t})\n\t\tsetTimeout(function(){ socketConn.send(data); }, 1000);\n\t}\n\n}", "function handleDeckCardClick(id) {\n setCardInUse(id)\n console.log(cardInUse)\n setCardAddStatus(cardAddStatus + 1)\n }", "function hit(e) {\n\n if (BlackJack['isStand'] === false) {\n BlackJack['turnsOver'] = false;\n let card = randomCards();\n showCard(YOU, card);\n updateResult(YOU, card);\n showCount(YOU);\n BlackJack[\"isHit\"] = true;\n }\n\n}", "function selectCard() {\n chosenCard = $(this).text();\n $(\"#selectCardMenu\").text(chosenCard);\n choseCardType = true;\n}", "function onSelectImageCard(socket, clientId, move) {\n\tconst gameId = clientGameMap[clientId];\n\tconst game = games[gameId];\n\n\tgame._selectImageCard(move.playerId, move.cardId);\n\n\tsocket.emit('sync', game);\n\tsocket.broadcast.to(gameId).emit('sync', game);\n}", "function myCard(response) {\n pokeSelect = response.name;\n pokeHP = response.hp;\n fillCard(response,\"#my-card\");\n $(\"start-btn\").classList.remove(\"hidden\");\n $(\"start-btn\").onclick = gameRequest;\n }", "function makeChoice(sign) {\n if(sign === 'o' || sign === 'x')\n socket.emit('choose', { sign: sign })\n else\n console.log('makeChoice error: podano zly znak!');\n}", "function selectCard(e){\n selectedId = e.id;\n var card=null;\n for (var i=0; i<cardList.length; i++){\n if (cardList[i].id==selectedId) card=cardList[i];\n }\n if (card!=null){\n $( \"#paramForm .carNumber\").val( card.car.carNumber );\n $( \"#paramForm .ttnNumber\").val( card.car.ttnNumber );\n $( \"#paramForm .culture\").val( card.car.nomenclature );\n $( \"#paramForm .firstName\").val( card.car.driver.firstName );\n $( \"#paramForm .lastName\").val( card.car.driver.lastName );\n $( \"#paramForm .organization\").val( card.car.driver.organization );\n $( \"#paramForm .mobileNumber\").val( card.car.driver.mobileNumber );\n $( \"#paramForm .sampleName\").val( card.car.cargo.sample.name );\n $( \"#paramForm .nomenclature\").val( card.car.cargo.sample.nomenclature );\n $( \"#paramForm .class\").val( card.car.cargo.sample.cultureClass );\n $( \"#paramForm .siloNumber\").val( card.car.siloNumber );\n $( \"#paramForm .humidity\").val( card.car.cargo.sample.humidity );\n $( \"#paramForm .cardId\").val( card.id );\n //alert($( \"#paramForm .queueId option:selected\").text());\n $( \"#paramForm .queueId\").val(-1); \n if (card.car.destination!=\"\" && card.car.destination!=null) {\n $(\"#paramForm .queueId :contains('\" + card.car.destination + \"')\").prop(\"selected\", true);\n }\n }\n $(\".selected\").removeClass(\"selected\");\n e.classList.add(\"selected\");\n}", "handleCopyCard(listId, cardId) {}", "exchangeGainCard(card) {\n this.cards.push(card);\n ++this.numCards;\n }", "pickUp() {\n if(this.addToInventory(this.Target)) {\n this.emit(\"Player.Environment.Interacted\", \"You picked up a \"+this.Target.name+\".\");\n this.generateEnvironment();\n this.save();\n } else {\n this.emit(\"Player.Environment.Interacted\", \"You do not have room in your inventory.\");\n }\n }", "takeCard(deck){\n this.hand.push(deck.dealCard());\n }", "async function drawCard(event){\n //console.log(\"Drawing x1 card\");\n\n var request = {\n \"player\" : null\n }\n\n let drawCardUrl = '/game/' + gameId + '/drawCard';\n const response = await fetch(drawCardUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n // body data type must match \"Content-Type\" header\n body: JSON.stringify({ msg: 'drawing a card' }) \n });\n\n let { playedCard } = await response.json();\n //console.log('playedCard:', playedCard);\n\n if(playedCard == undefined){\n notify('err', 'error', ('Error drawing the card'));\n return;\n }\n\n addCard({ \n id: playedCard.id,\n number: playedCard.number,\n color: playedCard.color,\n type: playedCard.type\n });\n\n}", "function get_card(newCard){\n if(dbg){\n\t\tdebug(\"Get card\");\n\t}\n\tcard4 = newCard;\n\tupdate_hand();\n\tenable_discard();\n}", "handlepick() {\n\t\talert('i was clicked');\n\t}", "selectCard(e) {\n if (this.state.time.s > 0 && this.state.isIdle === false) {\n this.setState({\n prevCard: '',\n p1Select: e})\n }\n }", "gainCard(card) {\n this.cards.push(card);\n this.out = false;\n if (this.numCards < 2) {\n ++this.numCards;\n }\n }", "async function selectTops(e) {\r\n //Will not let the player change cards once the game has started\r\n if (!game_started) {\r\n var this_value = $(e).attr(\"alt\");\r\n if (this_value !== \"deck\") {\r\n $(\".start-menu\").css(\"display\", \"none\");\r\n var temp = players[0].top.filter(val => val !== this_value);\r\n players[0].top = temp;\r\n players[0].hand.push(this_value);\r\n $(e).attr(\"src\", \"images/deck_01.svg\");\r\n $(e).attr(\"alt\", \"deck\");\r\n newCards();\r\n }\r\n }\r\n }", "function handleChoiceCardNo(e) {\n if (currentPage == \"cardservice/create/visa/card-unlock\") {\n handleChoiceCardNoClose();\n if ((e.selectedValue1 != undefined) && (e.selectedValue1 != null)) {\n pCardNoSelected = e.selectedValue1;\n var tagAccNo = document.getElementById(\"open-card-lock-no\");\n if (tagAccNo.nodeName == \"INPUT\") {\n tagAccNo.value = e.selectedValue1;\n }\n else {\n tagAccNo.innerHTML = e.selectedValue1;\n }\n }\n }\n }" ]
[ "0.6337688", "0.623733", "0.62235826", "0.6184626", "0.6156489", "0.5931886", "0.592926", "0.5880617", "0.5833592", "0.57898045", "0.5785704", "0.57522863", "0.5659242", "0.5627489", "0.5591926", "0.55628574", "0.5544106", "0.5543729", "0.5534355", "0.5523758", "0.5520991", "0.5516832", "0.54873925", "0.54828686", "0.54657555", "0.545432", "0.5441748", "0.5414297", "0.54142463", "0.5408802" ]
0.80335593
0
Adds a DataPoint to |this| with the specified time and value. DataPoints are assumed to be received in chronological order.
addPoint(timeTicks, value) { const time = new Date(timeTicks); this.dataPoints_.push(new DataPoint(time, value)); if (this.dataPoints_.length > MAX_STATS_DATA_POINT_BUFFER_SIZE) { this.dataPoints_.shift(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function DataPoint(ts, value) {\n // Timestamp of the DataPoint [Date]\n this.t = ts;\n // Value [Number]\n this.v = value;\n}", "function addDataPoint() {\n // add a new data point to the dataset\n // var now = vis.moment();\n // dataset.add({\n // x: now,\n // y: y(now / 1000)\n // });\n\n // remove all data points which are no longer visible\n //var range = graph2d.getWindow();\n //var interval = range.end - range.start;\n // var oldIds = dataset.getIds({\n // filter: function (item) {\n // return item.x < range.start - interval;\n // }\n // });\n //dataset.remove(oldIds);\n\n //setTimeout(addDataPoint, DELAY);\n}", "at(time, value) {\n const timeInTicks = new TransportTimeClass(this.context, time).toTicks();\n const tickTime = new TicksClass(this.context, 1).toSeconds();\n const iterator = this._events.values();\n let result = iterator.next();\n while (!result.done) {\n const event = result.value;\n if (Math.abs(timeInTicks - event.startOffset) < tickTime) {\n if (isDefined(value)) {\n event.value = value;\n }\n return event;\n }\n result = iterator.next();\n }\n // if there was no event at that time, create one\n if (isDefined(value)) {\n this.add(time, value);\n // return the new event\n return this.at(time);\n }\n else {\n return null;\n }\n }", "addPoint(point) {\n this.dataset.push(point);\n this.draw();\n }", "function addDataPoint() {\n // add a new data point to the dataset\n let now = vis.moment();\n datasetGraph.add({\n x: now,\n y: y(now / 1000,function (data) {\n return data;\n }),\n group:0\n });\n // datasetGraph.add({\n // x: now,\n // y: y(now / 500),\n // group:1\n // });\n // datasetGraph.add({\n // x: now,\n // y: y(now / 750),\n // group:2\n // });\n // datasetGraph.add({\n // x: now,\n // y: y(now / 123),\n // group:3\n // });\n // // remove all data points which are no longer visible\n // var range = graph2d.getWindow();\n // var interval = range.end - range.start;\n // var oldIds = datasetGraph.getIds({\n // filter: function (item) {\n // return item.x < range.start - interval;\n // }\n // });\n // datasetGraph.remove(oldIds);\n\n setTimeout(addDataPoint, DELAY);\n}", "add(value) {\n this.data[this.length] = value;\n this.length++;\n }", "function addData(data) {\n var dps = data.item;\n for (var i = 0; i < dps.length; i++) {\n //Memasukan value get kedalam array dataPoints\n dataPoints.push({\n x: new Date(dps[i][0]),\n y: dps[i][1],\n label : direction(dps[i][1])\n });\n }\n chart.render();\n }", "function plotTemperature(timeValue, value){\n console.log(timeValue);\n var x = new Date(timeValue*1000).getTime();\n console.log(x);\n var y = Number(value);\n if(chartT.series[0].data.length > 40) {\n chartT.series[0].addPoint([x, y], true, true, true);\n } else {\n chartT.series[0].addPoint([x, y], true, false, true);\n }\n}", "addPoint(point) {\n this._points.push(point);\n }", "function plotHumidity(timeValue, value){\n console.log(timeValue);\n var x = new Date(timeValue*1000).getTime();\n console.log(x);\n var y = Number(value);\n if(chartH.series[0].data.length > 40) {\n chartH.series[0].addPoint([x, y], true, true, true);\n } else {\n chartH.series[0].addPoint([x, y], true, false, true);\n }\n}", "setTimeWrite ( value ) {\n this.time = value;\n }", "function startDataTime() {\n TimeHandler.addEventInterval(updateDataTime, 25, Infinity, data.time);\n}", "addData(key, value) {\n this.Serialize.addData(key, value);\n }", "setTime(time) {\n this.time.setTime(time);\n }", "addData(datum) {\n this.data.push(datum);\n }", "addData(datum) {\n this.data.push(datum);\n }", "addTimeStamp(key, timeSince) {\n if (!timeSince) {\n timeSince = this.startTime;\n }\n let currentTime = Date.now();\n this.attributes[key] = currentTime - timeSince;\n }", "function addValueAndForm() {\n\tvar n = $('#inputNumber').val();\n\tif (n != '') {\n\t\tvar d = new Date();\n\t\tvar time = {minutes: d.getMinutes(), seconds: d.getSeconds(), milliseconds: d.getMilliseconds()};\n\t\taddForm(time,n);\n\t\tvar timeMs = time.minutes*60*1000 + time.seconds*1000 + time.milliseconds*1;\n\t\tData.push({'timeMs': +timeMs, 'value': +n});\n\t\tlocalStorage.setItem(+timeMs,+n);\n\t\tdrawPlot();\n\t}\n}", "set time(value) {}", "function addPoint() {\n\t\tvar fixedIndex = randomIntFromInterval(0, fixedPoints.length - 2), // pick random fixed point (excluding the one in add area)\n\t\t\tselectedFixed = fixedPoints[fixedIndex],\n\t\t\tlastPoint = data[data.length - 1],\n\t\t\tnewPoint = {};\n\n\t\tif (lastPoint.x >= selectedFixed.x) {\n\t\t\tnewPoint.x = selectedFixed.x + (lastPoint.x - selectedFixed.x) / 2;\n\t\t} else {\n\t\t\tnewPoint.x = lastPoint.x + (selectedFixed.x - lastPoint.x) / 2;\n\t\t}\n\t\tif (lastPoint.y >= selectedFixed.y) {\n\t\t\tnewPoint.y = selectedFixed.y + (lastPoint.y - selectedFixed.y) / 2;\n\t\t} else {\n\t\t\tnewPoint.y = lastPoint.y + (selectedFixed.y - lastPoint.y) / 2;\n\t\t}\n\t\tdata.push(newPoint); \n\t\tupdate(data);\n\t}", "add(value) {\n if (!this.has(value)) {\n this.set.push(value);\n }\n }", "get valueTime () {\r\n\t\treturn this._valueTime;\r\n\t}", "push(value) {\n this.data.unshift(value);\n }", "function DataPoint ( pRawValueX, pRawValueY, pNsats ) {\n this.x = pRawValueX ;\n this.y = pRawValueY ; \n this.n = pNsats ;\n}", "function addDataTimeline(chart, dataElement) {\n dataset = {\n label: dataElement.type,\n data: dataElement.data.data,\n title: dataElement.data.title,\n pointRadius: 7,\n backgroundColor: dataElement.background,\n borderColor: dataElement.border,\n };\n chart.data.datasets.push(dataset);\n chart.update();\n}", "function setTime( t ){\n\n this.time = t;\n\n }", "function PointWithTime(drawnAtPosition, timeDrawn) {\n this.position = drawnAtPosition;\n this.timestamp = (!timeDrawn) ? new Date().getTime() : timeDrawn;\n}", "function appendTimeData(data) {\n let startTime = moment(new Date().setHours(9, 30, 0, 0))\n let endTime = moment(new Date().setHours(15, 0, 0, 0))\n let middleClose = moment(new Date().setHours(11, 30, 0, 0))\n let middleOpen = moment(new Date().setHours(13, 0, 0, 0))\n let dataLastTime = moment(data[data.length - 1].x)\n\n while (dataLastTime < endTime) {\n dataLastTime.add(1, 'm')\n\n if (dataLastTime >= middleClose && dataLastTime < middleOpen) {\n dataLastTime = middleOpen\n data.push({\n x: dataLastTime.valueOf(),\n })\n } else {\n data.push({\n x: dataLastTime.valueOf(),\n })\n }\n }\n}", "add(v) {\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tthis.x += arguments[i].x\n\t\t\tthis.y += arguments[i].y\n\t\t}\n\n\t\treturn this;\n\t}", "set point(value) {}" ]
[ "0.63708514", "0.61181086", "0.58761024", "0.584897", "0.578221", "0.5456121", "0.53846174", "0.5295532", "0.5280697", "0.52230346", "0.5213346", "0.5185427", "0.51432675", "0.51043075", "0.5094851", "0.5094851", "0.50717664", "0.50651485", "0.50619066", "0.50361395", "0.49778214", "0.496484", "0.49499977", "0.49398935", "0.49244246", "0.49141032", "0.49107692", "0.49077678", "0.48983535", "0.4886412" ]
0.74504495
0