query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
global Image, Blob, URL, createImageBitmap, location / Loads images asynchronously image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous' returns a promise tracking the load
function loadImage(url, opts) { url = pathPrefix ? pathPrefix + url : url; if (typeof Image === 'undefined') { // In a web worker // XMLHttpRequest throws invalid URL error if using relative path // resolve url relative to original base url = new URL(url, location.pathname).href; return (0, _browserRequestFile.requestFile)({ url: url, responseType: 'arraybuffer' }).then(function (arraybuffer) { var blob = new Blob([new Uint8Array(arraybuffer)]); return createImageBitmap(blob); }); } return new Promise(function (resolve, reject) { try { var image = new Image(); image.onload = function () { return resolve(image); }; image.onerror = function () { return reject(new Error("Could not load image ".concat(url, "."))); }; image.crossOrigin = opts && opts.crossOrigin || 'anonymous'; image.src = url; } catch (error) { reject(error); } }); }
[ "load() {\n return new Promise((function(resolve, reject) {\n let img = null;\n /* Determine the image to use */\n if (this.emote) {\n /* Effect wants an emote used */\n img = this._host.twitchEmote(this.emote);\n } else if (this.imageUrl) {\n /* Effect gave a URL */\n img = this._host.image(this.imageUrl);\n }\n\n /* Resolve when ready */\n img.onload = (function(ev) {\n this._image = img;\n this.fire(\"load\", this);\n this.initialize();\n resolve(ev);\n }).bind(this);\n\n /* Reject on error */\n img.onerror = (function(ev) {\n Util.Error(ev);\n reject(ev);\n }).bind(this);\n }).bind(this));\n }", "function loadImageHtml(url, rect, done) {\n\n var img = new Image();\n\n // Allow cross-domain image loading.\n // This is required to be able to create WebGL textures from images fetched\n // from a different domain. Note that setting the crossorigin attribute to\n // 'anonymous' will trigger a CORS preflight for cross-domain requests, but no\n // credentials (cookies or HTTP auth) will be sent; to do so, the attribute\n // would have to be set to 'use-credentials' instead. Unfortunately, this is\n // not a safe choice, as it causes requests to fail when the response contains\n // an Access-Control-Allow-Origin header with a wildcard. See the section\n // \"Credentialed requests and wildcards\" on:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\n img.crossOrigin = 'anonymous';\n\n var x = rect && rect.x || 0;\n var y = rect && rect.y || 0;\n var width = rect && rect.width || 1;\n var height = rect && rect.height || 1;\n\n done = once(done);\n\n img.onload = function() {\n if (x === 0 && y === 0 && width === 1 && height === 1) {\n done(null, new StaticImageAsset(img));\n }\n else {\n x *= img.naturalWidth;\n y *= img.naturalHeight;\n width *= img.naturalWidth;\n height *= img.naturalHeight;\n\n var canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n var context = canvas.getContext('2d');\n\n context.drawImage(img, x, y, width, height, 0, 0, width, height);\n\n done(null, new StaticCanvasAsset(canvas));\n }\n };\n\n img.onerror = function() {\n // TODO: is there any way to distinguish a network error from other\n // kinds of errors? For now we always return NetworkError since this\n // prevents images to be retried continuously while we are offline.\n done(new NetworkError('Network error: ' + url));\n };\n\n img.src = url;\n\n function cancel() {\n img.onload = img.onerror = null;\n img.src = '';\n done.apply(null, arguments);\n }\n\n return cancel;\n\n}", "function init() {\n var img = new Image();\n img.name = url;\n img.onload = setDimensions;\n img.src = url;\n }", "async function getImage(imgProxyURL) {\n const image = await Axios({\n url: imgProxyURL,\n method: 'GET',\n responseType: 'stream'\n });\n\n return image; \n}", "decodeFromImageUrl(url){return __awaiter$1(this,void 0,void 0,function*(){if(!url){throw new ArgumentException('An URL must be provided.');}const element=BrowserCodeReader$1.prepareImageElement();// loads the image.\nelement.src=url;try{// it waits the task so we can destroy the created image after\nreturn yield this.decodeFromImageElement(element);}finally{// we created this element, so we destroy it\nBrowserCodeReader$1.destroyImageElement(element);}});}", "function setupLoadingAsynchronousImages()\n{\n // for each object with class \"asyncImgLoad\"\n $('.asyncImgLoad').each(\n function()\n { \n // save handle to loader - caintainer which we gona insert loaded image \n var loader = $(this);\n // get image path from loader title attribute\n var imagePath = loader.attr('title');\n // create new image object\n var img = new Image();\n // set opacity for image to maximum\n // value 0.0 means completly transparent\n $(img).css(\"opacity\", \"0.0\")\n // next we set function wich gona be caled then\n // image load is finished \n .load(\n function() \n {\n // insert loaded image to loader object \n // and remove unnecessary title attribute\n loader.append(this).removeAttr('title');\n // for inserted image we set margin to zero\n // opacity to max and fire up 500ms opacity animation \n $(this)\n .css(\"margin\", \"0px\")\n .css(\"opacity\", \"0.0\")\n .animate({opacity: 1.0}, 500,\n function()\n {\n // after animation we remove loader background image \n loader.css(\"background-image\", \"none\");\n }\n );\n }\n // set new value for attribute src - this means: load image from imagePath \n ).attr('src', imagePath); \n }\n );\n}", "addImage(url) {\n \n }", "function getUserPicture( URL ) {\n $.ajax({\n type: \"GET\",\n url: \"/convert?image_url=\" + URL\n }).done( function( data ) {\n var canvas = document.createElement('canvas');\n canvas.height = window.innerHeight;\n canvas.width = window.innerWidth;\n var context = canvas.getContext('2d');\n var imgSrc = \"data:image/png;base64, \" + data;\n var threeImage = document.createElement('img');\n threeImage.src = imgSrc;\n userTexture = new THREE.Texture( threeImage );\n\n threeImage.onload = function() {\n userTexture.needsUpdate = true;\n }\n userImageSpinny();\n });\n}", "imageLoaded(){}", "async loadImages() {\n const resources = Array.from(this._resources.entries());\n\n console.info(`[ImageManager] Loading ${resources.length} image assets.`);\n\n await Promise.all(resources.map(([iKey, iValue]) => {\n console.info(`[ImageManager] Loading image ${iValue}.`);\n\n const img = new Image();\n img.src = iValue;\n\n return new Promise((resolve) => img.addEventListener('load', () => {\n this._images.set(iKey, img);\n resolve();\n }))\n }));\n\n this._loaded = true;\n\n console.info('[ImageManager] Images loaded.');\n }", "_decodeOnLoadImage(element){return __awaiter$1(this,void 0,void 0,function*(){const isImageLoaded=BrowserCodeReader$1.isImageLoaded(element);if(!isImageLoaded){yield BrowserCodeReader$1._waitImageLoad(element);}return this.decode(element);});}", "load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }", "function loadCanvas (dataURL,x,y,w,h) {\n\tvar imageObj = new Image();\n\timageObj.onload = function () {\n\t\tconsole.log(imageObj);\n\t\tctx.drawImage(imageObj,x,y,w,h);\n\t};\n\timageObj.src = dataURL;\n\t//console.log(imageObj);\n}", "function loadImage(src, callback){\n\n var img = $('<img>').on('load', function(){\n \t\tcallback.call(img);\n \t});\n\n \timg.attr('src',src);\n }", "function load_image( href ) {\n\t\t\tvar image = new Image();\n\t\t\timage.onload = function() {\n\t\t\t\treveal( '<img src=\"' + image.src + '\">' );\n\t\t\t}\n\t\t\timage.src = href;\n\t\t}", "function fetchDogImages() {\n fetch(imgUrl)\n .then(function(resp) {\n return resp.json()\n })\n .then(function(json) {\n renderDogImages(json)\n })\n}", "function preLoadImages() {\n var args_len = arguments.length;\n for (var i = args_len; i--;) {\n var cacheImage = document.createElement('img');\n cacheImage.src = arguments[i];\n __cache.push(cacheImage);\n }\n }", "decodeFromImageElement(source){return __awaiter$1(this,void 0,void 0,function*(){if(!source){throw new ArgumentException('An image element must be provided.');}const element=BrowserCodeReader$1.prepareImageElement(source);// onLoad will remove it's callback once done\n// we do not need to dispose or destroy the image\n// since it came from the user\nreturn yield this._decodeOnLoadImage(element);});}", "function createImage(imgPath) {\n return new Promise(function (resolve, reject) {\n const image = document.createElement(\"img\");\n image.src = imgPath;\n\n // Listen for successful load\n image.addEventListener(\"load\", function () {\n imgContainer.append(image);\n resolve(image);\n });\n\n // Listen for load error\n image.addEventListener(\"error\", function () {\n reject(new Error(`Unable to load image ${imgPath}`));\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send shuffled card order to server
function sendOrder(order) { $.ajax({ url: "/shuffle", type: "POST", traditional: true, /*- make the array send as an array -*/ data: {order: order}, success:function(resp) { if (resp.gameID != -1){ $('#game').html('Game ID: ' + resp.gameID); $("#side_txt").html("Group: " + resp.side); side = resp.side; } } }); }
[ "function updateDeck() {\n\tshuffledCardsArray = shuffle(cards); // Calls shuffle function\n\tcreateDeck(shuffledCardsArray); // Calls createDeck function (that takes shuffled array as an argument)\n}", "function shuffle(deck) {\n\t// Shuffle\n\tfor (let i=0; i<1000; i++) {\n\t // Swap two randomly selected cards.\n\t let pos1 = Math.floor(Math.random()*deck.length);\n\t let pos2 = Math.floor(Math.random()*deck.length);\n\n\t // Swap the selected cards.\n\t [deck[pos1], deck[pos2]] = [deck[pos2], deck[pos1]];\n\t}\n\n }", "function shuffleAction() {\n const shuffledList = cards.slice().sort(() => Math.random() - 0.5);\n return createCard(shuffledList);\n}", "function recvOrder(order)\n {\n $.ajax({\n url: \"/shuffle\",\n type: \"GET\",\n success: function(resp) {\n\n syncCards(resp.order); /*- sync card order with ctrler order -*/\n window.clearInterval(recvOrderID); \n flipMsgID = setInterval( function () {\n flipMsg(\"Ready\");\n }, 1000);\n\n startSound(1);\n\n setTimeout(function () {\n\n gameStartTime = new Date();\n window.clearInterval(flipMsgID);\n $('#game').html('Game ID: ' + resp.gameID);\n $(\"#side_txt\").html(\"Group: \" + resp.side);\n side = resp.side;\n\n if (resp.isEnemy == 1) \n updateState(WAIT);\n else {\n $(\"#waiting\").html('Take Control!');\n turnStartTime = 0;\n updateState(CTRL);\n setTimeout(clearWaitMsg, 3000);\n }\n\n recvAnsID = setInterval(recvAns, 1000); \n recvKnowID = setInterval(recvKnow, 1000); \n updateTimeID = setInterval(updateTime, 1000); \n\t\t\t\t\t$('#restart').button();\n\t\t\t\t\t$('#restart').button('disable');\n\n }, 5000);\n }\n }); \n }", "shuffleElements() { \n this.deck.shuffle();\n }", "function shuffleCards(array){\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tlet randomIndex = Math.floor(Math.random()*array.length);\r\n\t\tlet temp = array[i];\r\n\t\tarray[i] = array[randomIndex];\r\n\t\tarray[randomIndex] = temp;\r\n\t}\r\n}", "function shuffle(deck) {\n deck = deck.sort(() => Math.random() - 0.5)\n let i = 0\n while(i !== deck.length) {\n pile.player.push(deck[i]);\n pile.comp.push(deck[i+1]);\n i+=2;\n }\n}", "function selectCards() {\r\n dealerCard = dealerDeck.splice(Math.floor(Math.random() * dealerDeck.length), 1);\r\n playerCard = playerDeck.splice(Math.floor(Math.random() * playerDeck.length), 1);\r\n }", "function shuffleCards() {\n for (var j = 0; j < cards.length; j++) {\n cards[j].classList.remove('open', 'show', 'match')\n };\n\n allCards = shuffle(allCards)\n for (var i = 0; i < allCards.length; i++) {\n deck.innerHTML = ''\n for (const e of allCards) {\n deck.appendChild(e)\n }\n }\n}", "function dealCardsToPlayer(player, numberOfCards = 1) {\n // We want to keep track of how many cards are left to deal if the deck\n // needs to be shuffled.\n for (let cardsLeftToDeal = numberOfCards; cardsLeftToDeal >= 1; cardsLeftToDeal--) {\n const cardToDeal = rooms[player.roomCode].deck.drawPile.shift();\n\n if (cardToDeal) {\n // Move the card to player's hand array.\n player.addCardToHand(cardToDeal);\n\n // Send the card to the player's client.\n io.to(player.id).emit('add card to hand', cardToDeal);\n\n // Notify all clients how many cards a player has.\n io.in(player.roomCode).emit('update hand count', player, player.hand.length);\n }\n else {\n // No cards left to draw, shuffle and try again.\n rooms[player.roomCode].deck.shuffleDeck();\n\n // Notify the players that the deck is being shuffled.\n io.in(player.roomCode).emit('shuffle deck');\n\n // If there are no cards left in the draw pile, stop.\n if (rooms[player.roomCode].deck.drawPile.length === 0) {\n return;\n }\n else {\n // Retry dealing a card to the player.\n cardsLeftToDeal++;\n }\n }\n }\n}", "function display(shuffled) {\n $deck.empty()\n initTime()\n // shuffled = shuffle(cards);\n\n for (let i = 0; i < shuffled.length; i++) {\n $card = memoryCard(shuffled[i]);\n $deck.append($card);\n }\n}", "data_PassOutCards() {\n // ----------------------------------\n // hand out cards\n while (this.masterDeck.length != 0) {\n // ----------------------------------\n // append first card of master deck to playerDeck\n // remove the first card of master deck --> repeat\n for (let deck in this.playerDecks) {\n this.playerDecks[deck].push(this.masterDeck[0]);\n this.masterDeck.splice(0, 1);\n }\n }\n }", "function startGame() {\r\n let shuffledCards = shuffle(cards);\r\n for (var i = 0; i < shuffledCards.length; i++) {\r\n [].forEach.call(shuffledCards, function (item) {\r\n cardContainer.appendChild(item);\r\n })\r\n shuffledCards[i].classList.remove(\"show\", \"match\", \"disabled\");\r\n shuffledCards[i].classList.add(\"unflipped\");\r\n }\r\n\r\n tryCounter = 0;\r\n tries.textContent = 0;\r\n}", "function takeCardAndReplenish(db, card) {\n const rank = card.rank;\n const cards = db.get(['game', 'cards' + rank]);\n let index = -1;\n for(let i = 0; i < cards.length; i ++) {\n if(cards[i].key == card.key) {\n index = i;\n break;\n }\n }\n if(index < 0) {\n return;\n }\n const nextCard = db.get(['game', 'deck' + rank, 0]);\n if(nextCard) {\n db.set(['game', 'cards' + rank, index], nextCard);\n db.set(['game', 'cards' + rank, index, 'status'], 'board');\n } else {\n db.set(['game', 'cards' + rank, index], {\n status: 'empty'\n });\n }\n db.shift(['game', 'deck' + rank]);\n}", "dealRandomCardsFromDeck(nb) {\n\n let out = new Array(nb);\n let temp = new Card();\n\n for(var i = 0; i < nb; i++) {\n do {\n temp = this.deck.randomCardObject();\n } while(this.cardsDealt.includes(temp));\n\n // Add the card to the cards dealt and to the output array\n this.cardsDealt.push(temp);\n out[i] = temp;\n }\n\n return out;\n }", "function selectFavorCard() { \n if(selectedCards.length < 1) return;\n const { lobbyID } = context;\n\n if(selectedCards[0] >= 0){\n Socket.send(\"give_favor_card\", {lobbyID: lobbyID, to: gameState.favorTarget, card: gameState.playerCards[selectedCards[0]]});\n //this.setState({favorTarget: undefined});\n //setFavorTarget(undefined);\n setGameState({favorTarget: undefined});\n setSelectedCards([]);\n }\n }", "static async newMajorDeck() {\n try {\n console.log(\"Generating deck...\")\n const response = await Axios.get(`${API}/cards`);\n let deck = response.data\n console.log(\"Deck complete.\");\n \n //The first 22 cards returned are the major arcana, we drop the rest.\n deck.splice(22)\n \n // Swap cards around to shuffle them.\n for (let i = 0; i < deck.length; i++) {\n let rand = Math.floor(Math.random() * 22);\n [deck[i], deck[rand]] = [deck[rand], deck[i]];\n }\n \n for (let card of deck) {\n this.prepCard(card);\n }\n return deck; \n\n } catch(error) {\n console.error(error);\n };\n }", "_shuffle() {\n\tif (!this.currentQuestion) throw \"No questions to shuffle.\";\n\tthis.orderChoices = [\n\t this.currentQuestion.correctAnswer,\n\t this.currentQuestion.wrongAnswer\n\t];\n\tif (Math.floor(Math.random() * 2) == 0) {\n\t this.orderChoices.reverse();\n\t}\n }", "function shuffle(size) {\n if (size < 2) return 'invalid deck'\n if (size === 2) return 1\n let calcSize = size\n if (size % 2 === 1) {\n calcSize++\n }\n // we only have to pay attention to one card (the card at index 1 is a good choice) to solve this problem. let's start by \"shuffling\" that one card once.\n let originalIndex = 1\n let tempIndex = 2\n let count = 1\n while (tempIndex !== originalIndex) {\n count++\n if (tempIndex < calcSize / 2) {\n tempIndex = tempIndex * 2\n }\n else {\n tempIndex = tempIndex - (calcSize - tempIndex - 1)\n }\n }\n return count\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the editor is already destroyed.
get isDestroyed() { var _a; // @ts-ignore return !((_a = this.view) === null || _a === void 0 ? void 0 : _a.docView); }
[ "detectDestroy() {\n if(this.parent === null) {\n this.destroy();\n return true;\n }\n return false;\n }", "static isDetached() {\n return !this.isAttached();\n }", "isDetached() {\n return !this.isAttached();\n }", "isEditor(value) {\n if (!isPlainObject(value)) return false;\n var cachedIsEditor = IS_EDITOR_CACHE.get(value);\n\n if (cachedIsEditor !== undefined) {\n return cachedIsEditor;\n }\n\n var isEditor = typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && typeof value.deleteForward === 'function' && typeof value.deleteFragment === 'function' && typeof value.insertBreak === 'function' && typeof value.insertFragment === 'function' && typeof value.insertNode === 'function' && typeof value.insertText === 'function' && typeof value.isInline === 'function' && typeof value.isVoid === 'function' && typeof value.normalizeNode === 'function' && typeof value.onChange === 'function' && typeof value.removeMark === 'function' && (value.marks === null || isPlainObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && Node$1.isNodeList(value.children) && Operation.isOperationList(value.operations);\n IS_EDITOR_CACHE.set(value, isEditor);\n return isEditor;\n }", "destroy() {\n // Prevent multiple destruction of entities.\n if (this._destroyed === true) return;\n\n this._destroyed = true;\n\n this.onDestroy();\n }", "hideEditor() {\n if (this._editor.active) {\n this._editor.active = false;\n\n $('#monaco').hide();\n\n $('#file-tabs-placeholder').show();\n $('#editor-placeholder').show();\n }\n }", "remove () {\n if (this.wrap && this.parent) {\n return !!this.parent.removeChild(this.wrap)\n }\n\n return !!console.log('Has not found \"Keypad\" that needed to be removed.')\n }", "willDestroyElement() {\n this._super(...arguments);\n this.set('destroyHasBeenCalled', true);\n }", "function isDestroyable(x) {\n return x && 'destroy' in x;\n}", "function editorsLoaded() {\n return editorsLoaded;\n}", "get destroyed() {\n return this.#state === kSocketDestroyed;\n }", "onHideEditorPanel()\n\t{\n\t\tthis.#postInternalCommand('onHideEditorPanel');\n\t}", "destroy()\n {\n //first remove it from the scene.\n this.#scene.remove(this);\n //then destroy all components.\n while(this.#components.length > 0)\n {\n let currentComponent = this.#components.pop();\n currentComponent.destroy();\n }\n }", "function useHandleEditorUnmount(editorSharedConfigRef) {\n React.useEffect(function () {\n // Need to keep this reference in order to make \"react-hooks/exhaustive-deps\" eslint rule happy\n var editorSharedConfig = editorSharedConfigRef;\n // Will unmount\n return function () {\n if (!editorSharedConfig.current) {\n return;\n }\n var _a = editorSharedConfig.current, eventDispatcher = _a.eventDispatcher, editorView = _a.editorView;\n if (eventDispatcher) {\n eventDispatcher.destroy();\n }\n if (editorView) {\n // Prevent any transactions from coming through when unmounting\n editorView.setProps({\n dispatchTransaction: function (_tr) { },\n });\n // Destroy the state if the Editor is being unmounted\n var editorState_1 = editorView.state;\n editorState_1.plugins.forEach(function (plugin) {\n var state = plugin.getState(editorState_1);\n if (state && state.destroy) {\n state.destroy();\n }\n });\n editorView.destroy();\n }\n };\n }, [editorSharedConfigRef]);\n}", "destroy() {\n\t\tthis._unbindInput()\n\t\tthis.timepicker.overlay.remove()\n\t\tdelete this.input[MDTP_DATA]\n\t}", "destroy() {\n //console.log('destroy');\n if (this.scene !== undefined) {\n this.scene.time.removeEvent(this.shootEvent);\n }\n if (this.body !== undefined){\n this.body.enable = false;\n }\n\n super.destroy();\n }", "function OnScriptDestroyed()\n{\n //No cleaning atm.\n}", "destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }", "isComplete() {\n return this.selection != null;\n }", "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dump to the js console (xulrunner jsconsole)
function jsdump(str) { Components.classes['@mozilla.org/consoleservice;1'] .getService(Components.interfaces.nsIConsoleService) .logStringMessage(str); }
[ "dump() {\n\t\tconsole.log(`\\n\"${this.constructor.name}\": ${JSON.stringify(this, null, 4)}`);\n\t}", "function dumpHTMLContent()\n{\n\t// the functional code is in the page dump.html\n\twindow.open(PATH_Lib + \"/Common/Test/Lib/dump.html\",\"sourceWindow\",\"resizable=yes scrollbars=no menubar=no\");\n\treturn false;\n}", "function printConsoleText(text) {\n var console = document.getElementById(\"console\");\n console.innerHTML = text;\n}", "function dumpConsoles() {\n if (gPendingOutputTest) {\n console.log(\"dumpConsoles start\");\n for (let [, hud] of HUDService.consoles) {\n if (!hud.outputNode) {\n console.debug(\"no output content for\", hud.hudId);\n continue;\n }\n\n console.debug(\"output content for\", hud.hudId);\n for (let elem of hud.outputNode.childNodes) {\n dumpMessageElement(elem);\n }\n }\n console.log(\"dumpConsoles end\");\n\n gPendingOutputTest = 0;\n }\n}", "function consOut( mssg ) {\n\tif (window.debug) {\n\t\tconsole.log(mssg);\n\t}\n}", "executeJavaScriptInDevTools(code) {\n return ipcRenderer.send('call-devtools-webcontents-method', 'executeJavaScript', code);\n }", "function consoleOut(msg) {\n console.log(msg);\n console_log += msg + \"\\n\";\n}", "function dbugScripts(G,E){var D=document.cookie.match(\"(?:^|;)\\\\s*jsdebug=([^;]*)\");var C=D?unescape(D[1]):false;if(window.location.href.indexOf(\"basePath=this\")>0){var F=G.substring(G.substring(7,G.length).indexOf(\"/\")+8,G.length);var A=window.location.href;G=A.substring(A.substring(7,A.length).indexOf(\"/\")+8,A.length)}if(window.location.href.indexOf(\"jsdebug=true\")>0||window.location.href.indexOf(\"jsdebugCookie=true\")>0||C==\"true\"){for(var B=0;B<E.length;B++){document.write('<script src=\"'+G+E[B]+'\" type=\"text/javascript\"><\\/script>')}return true}return false}", "_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n\n this.extensionConfig.installDependencies = true;\n }", "function debug() {\n // Nothing to test, yay :D\n}", "function injectJs(js) {\r\n\tvar prom = lcdwindow.webContents\r\n\t\t.executeJavaScript(js)\r\n\t\t.then((value) => {\r\n\t\t\tconsole.log('Javascript Injected');\r\n\t\t})\r\n\t\t.catch((error) => {\r\n\t\t\tconsole.log('Error injecting JS');\r\n\t\t\tconsole.log('Error: ' + (error ? error : '<empty>'));\r\n\t\t});\r\n\r\n\treturn prom;\r\n}", "static serializeToJs(unit) {\n if (!unit.isLoaded) {\n throw new Error(\"serializeToJs can be used on loaded units only!\");\n }\n const serializer = new JavaScriptSerializer(unit);\n serializer.schedule(unit);\n return serializer.source();\n }", "Dump() {\n console.log(\"Turtle params:\", this.currentParams);\n }", "function debug(text){\n stats.setContent(stats.getContent()+\"<br>\"+text);\n}", "_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n this.fs.copy(this.sourceRoot() + '/typings', context.name + '/typings');\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/installTypings.js', context.name + '/installTypings.js', context);\n\n this.extensionConfig.installDependencies = true;\n }", "function ola('Javascript'){\n\t\tconsole.log('Hello world!')\n\t}", "function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}", "function webideCli() { }", "debug(entry) {\n this.write(entry, 'DEBUG');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
!md addmedia Add a CODEC to the SDP object.
addmedia( sdp, codec ) { switch( codec ) { case "pcmu": { sdp.m[ 0 ].payloads.push( 0 ); sdp.m[ 0 ].rtpmap[ "0" ] = { encoding: "PCMU", clock: "8000" }; break; } case "pcma": { sdp.m[ 0 ].payloads.push( 8 ); sdp.m[ 0 ].rtpmap[ "8" ] = { encoding: "PCMA", clock: "8000" }; break; } case "722": { sdp.m[ 0 ].payloads.push( 9 ); break; } case "ilbc": { sdp.m[ 0 ].payloads.push( 97 ); sdp.m[ 0 ].rtpmap[ "97" ] = { encoding: "iLBC", clock: "8000" }; if( !( "fmtp" in sdp.m[ 0 ] ) ) sdp.m[ 0 ].fmtp = {}; sdp.m[ 0 ].fmtp[ "97" ] = "mode=20"; break; } /* rfc 2833 - DTMF*/ case "2833": { sdp.m[ 0 ].payloads.push( 101 ); sdp.m[ 0 ].rtpmap[ "101" ] = { encoding: "telephone-event", clock: "8000" }; if( !( "fmtp" in sdp.m[ 0 ] ) ) sdp.m[ 0 ].fmtp = {}; sdp.m[ 0 ].fmtp[ "101" ] = "0-16"; break; } } }
[ "addMedia() {\n\n this.mediaFrame.open();\n }", "addMedia(mediaType, uid, url, options) {\n console.log(`add media ${mediaType} ${uid} ${url}`);\n let media = this.data.media || [];\n\n if (mediaType === 0) {\n //pusher\n media.splice(0, 0, {\n key: options.key,\n type: mediaType,\n uid: `${uid}`,\n holding: false,\n url: url,\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n } else {\n //player\n media.push({\n key: options.key,\n rotation: options.rotation,\n type: mediaType,\n uid: `${uid}`,\n holding: false,\n url: url,\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n }\n\n media = this.syncLayout(media);\n return this.refreshMedia(media);\n }", "static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}", "function srs_publiser_get_codec(\n vcodec, acodec,\n sl_cameras, sl_microphones, sl_vcodec, sl_profile, sl_level, sl_gop, sl_size, sl_fps, sl_bitrate,\n sl_acodec\n) {\n acodec.codec = $(sl_acodec).val();\n acodec.device_code = $(sl_microphones).val();\n acodec.device_name = $(sl_microphones).text();\n \n vcodec.device_code = $(sl_cameras).find(\"option:selected\").val();\n vcodec.device_name = $(sl_cameras).find(\"option:selected\").text();\n \n vcodec.codec = $(sl_vcodec).find(\"option:selected\").val();\n vcodec.profile = $(sl_profile).find(\"option:selected\").val();\n vcodec.level = $(sl_level).find(\"option:selected\").val();\n vcodec.fps = $(sl_fps).find(\"option:selected\").val();\n vcodec.gop = $(sl_gop).find(\"option:selected\").val();\n vcodec.size = $(sl_size).find(\"option:selected\").val();\n vcodec.bitrate = $(sl_bitrate).find(\"option:selected\").val();\n}", "addDevice() {\n const device = {\n deviceId: '',\n kind: 'videoinput',\n label: '',\n groupId: '',\n };\n device.__proto__ = MediaDeviceInfo.prototype;\n this.devices_.push(device);\n if (this.deviceChangeListener_) {\n this.deviceChangeListener_();\n }\n }", "static appendMediaEntry(mixEntryId, mediaEntryId){\n\t\tlet kparams = {};\n\t\tkparams.mixEntryId = mixEntryId;\n\t\tkparams.mediaEntryId = mediaEntryId;\n\t\treturn new kaltura.RequestBuilder('mixing', 'appendMediaEntry', kparams);\n\t}", "set media(aValue) {\n this._logService.debug(\"gsDiggEvent.media[set]\");\n this._media = aValue;\n }", "static addFromUrl(mediaEntry, url){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.url = url;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromUrl', kparams);\n\t}", "function PlayerAsMedia(player) {\n this._player = player; \n}", "static addFromFlavorAsset(sourceFlavorAssetId, mediaEntry = null){\n\t\tlet kparams = {};\n\t\tkparams.sourceFlavorAssetId = sourceFlavorAssetId;\n\t\tkparams.mediaEntry = mediaEntry;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromFlavorAsset', kparams);\n\t}", "static addContent(entryId, resource = null){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('media', 'addContent', kparams);\n\t}", "onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n this.id3Track = this.media.addTextTrack('metadata', 'id3');\n this.id3Track.mode = 'hidden';\n }", "static createBinaryBitmapFromMediaElem(mediaElement){const canvas=BrowserCodeReader$1.createCanvasFromMediaElement(mediaElement);return BrowserCodeReader$1.createBinaryBitmapFromCanvas(canvas);}", "setMediaFile() {\n if (!this.creative()) {\n return this;\n }\n\n this.$media = bestMedia(this.creative().mediaFiles().all());\n\n if (!this.media()) {\n console.warn('No media.');\n\n return this;\n }\n\n const virtual = document.createElement('textarea');\n virtual.innerHTML = this.$media.source();\n this.$media.$source = virtual.value.trim();\n\n\n this.$hasAds = true;\n\n return this;\n }", "static addFromUploadedFile(mediaEntry, uploadTokenId){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromUploadedFile', kparams);\n\t}", "function Codec(src, encode, decode) {\n if (src instanceof Codec)\n return src;\n\n if (!(this instanceof Codec))\n return new Codec(src, code, decode);\n\n src = Object(src, codec_defaults);\n\n this.src = src;\n this.encode = encode || identity;\n this.decode = decode || identity;\n}", "static addMediaEntry(mediaEntry, uploadTokenId, emailProfId, fromAddress, emailMsgId){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tkparams.emailProfId = emailProfId;\n\t\tkparams.fromAddress = fromAddress;\n\t\tkparams.emailMsgId = emailMsgId;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'addMediaEntry', kparams);\n\t}", "function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {\n var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);\n\n // Map ICE parameters (ufrag, pwd) to SDP.\n sdp += SDPUtils.writeIceParameters(\n transceiver.iceGatherer.getLocalParameters());\n\n // Map DTLS parameters to SDP.\n sdp += SDPUtils.writeDtlsParameters(\n transceiver.dtlsTransport.getLocalParameters(),\n type === 'offer' ? 'actpass' : dtlsRole);\n\n sdp += 'a=mid:' + transceiver.mid + '\\r\\n';\n\n if (transceiver.rtpSender && transceiver.rtpReceiver) {\n sdp += 'a=sendrecv\\r\\n';\n } else if (transceiver.rtpSender) {\n sdp += 'a=sendonly\\r\\n';\n } else if (transceiver.rtpReceiver) {\n sdp += 'a=recvonly\\r\\n';\n } else {\n sdp += 'a=inactive\\r\\n';\n }\n\n if (transceiver.rtpSender) {\n var trackId = transceiver.rtpSender._initialTrackId ||\n transceiver.rtpSender.track.id;\n transceiver.rtpSender._initialTrackId = trackId;\n // spec.\n var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +\n trackId + '\\r\\n';\n sdp += 'a=' + msid;\n // for Chrome. Legacy should no longer be required.\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +\n ' ' + msid;\n\n // RTX\n if (transceiver.sendEncodingParameters[0].rtx) {\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +\n ' ' + msid;\n sdp += 'a=ssrc-group:FID ' +\n transceiver.sendEncodingParameters[0].ssrc + ' ' +\n transceiver.sendEncodingParameters[0].rtx.ssrc +\n '\\r\\n';\n }\n }\n // FIXME: this should be written by writeRtpDescription.\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +\n ' cname:' + SDPUtils.localCName + '\\r\\n';\n if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +\n ' cname:' + SDPUtils.localCName + '\\r\\n';\n }\n return sdp;\n}", "static addFromSearchResult(mediaEntry = null, searchResult = null){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.searchResult = searchResult;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromSearchResult', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the markup for items in the cart.
function renderCart() { // Get variables. var cartEl = document.querySelector('#cart .cart__content'), cartItem = '', items = ''; cart.items.forEach(function (item) { // Use template literal to create our cart item content. cartItem = `<div id="item${item.id}" class="cart__row cart-item text--black"> <div class="cart-col--1 flex align-center"> <img src="${item.image}" alt="${item.name}" class="cart-item__image"> <h3 class="cart-item__heading">${item.name}</h3> </div> <div class="cart-col--2"> <span class="cart-item__price">$${item.price}</span> </div> <div class="cart-col--3"> <div class="increment flex justify-between"> <button class="button button--outline text--aluminum minus" type="button">&minus;</button> <label for="cart-${item.id}" class="hide-text">Quantity</label> <input class="qty" type="number" id="cart-${item.id}" name="cart-${item.id}" value="${item.quantity}"> <button class="button button--outline text--aluminum plus" type="button">&plus;</button> </div> </div> <div class="cart-col--4"> <span class="cart-item__total">$${item.quantity * item.price}</span> </div> <div class="cart-col--5"> <button type="button" class="button button--close button--remove"> <span class="hide-text">Remove</span> <span class="close close--1"></span> <span class="close close--2"></span> </button> </div> </div>`; items += cartItem; }); // Add the item to the cart. cartEl.innerHTML = items; }
[ "render() {\n\t\tif (orinoco.cart.products.length !== 0) {\n\t\t\tthis.domTarget.innerHTML = this.templateCartList();\n\t\t\tnew Form({ name: \"form\" }, document.querySelector(\"#order-form\"));\n\t\t}\n\t\telse this.domTarget.innerHTML = this.templateEmptyCart();\n\t}", "function showCart() {\n console.log(chalk.green(\"Your cart currently contains: \"));\n for (q = 0; q < customerCart.length; q++) {\n console.log(\"Product ID:\" + customerCart[q].id + chalk.magenta(\" | \") + \"Product Name: \" + customerCart[q].name + chalk.magenta(\" | \") + \"Quantity: \" + customerCart[q].quantityDesired + chalk.magenta(\" | \") + \"Total Cost: \" + customerCart[q].totalCost);\n }\n afterCart();\n}", "function renderShoppingList() {\n console.log('`renderShoppingList` ran');\n console.log(STORE);\n const shoppingList = generateShoppingList(STORE);\n\n // inserts the HTML into the DOM\n $('.container').html(shoppingList);\n}", "function renderBasket() {\n // clear the existing basket\n basketItemsElement.innerHTML = '';\n // render the items\n basket.items.forEach((basketItem) => {\n basketItemsElement.appendChild(basketItem.render());\n });\n // bind event listeners to the `.basket-delete-one-button`s created above\n bindOnClickWithId('.basket-delete-one-button', (id) => {\n basket.deleteOne(id);\n renderBasket();\n });\n // update the basket quantity\n basketQuantityElement.textContent = basket.totalQuantity.toString();\n // if the basket is empty, disable the purchase and clear buttons and show a note\n // otherwise enable them and hide the note\n // @TODO probably could be better\n if (basket.isEmpty()) {\n basketEmptyNote.classList.remove('is-hidden');\n basketPurchaseButton.setAttribute('disabled', 'disabled');\n basketClearButton.setAttribute('disabled', 'disabled');\n } else {\n basketEmptyNote.classList.add('is-hidden');\n basketPurchaseButton.removeAttribute('disabled');\n basketClearButton.removeAttribute('disabled');\n }\n // shake the basket link up and down to signify a change\n basketLink.animate([\n { transform: 'scale(0.9)' },\n { transform: 'scale(1.1)' },\n ],\n {\n duration: 200,\n });\n}", "function updateCart() {\n\tsaveFormChanges();\n\trenderCart();\n}", "function renderShoppingList() {\n //check for filters\n let currentFilter = STORE.filter;\n STORE.filteredItems = [...STORE.items];\n\n //check if on nocheckeditems\n if (currentFilter === 'noCheckedItems'){\n STORE.filteredItems=STORE.items.filter((item)=> item.checked === false);\n }\n\n //check if search term given\n if (currentFilter !== 'noFilter' && currentFilter !== 'noCheckedItems'){\n STORE.filteredItems = STORE.items.filter((item)=> item.name === currentFilter);\n }\n \n // render the shopping list in the DOM\n const shoppingListItemsString = generateShoppingItemsString(STORE.filteredItems);\n\n // insert that HTML into the DOM\n $('.js-shopping-list').html(shoppingListItemsString);\n}", "function updateCartItems(){\n\tvar totalItems = 0;\n\tvar productTotal = 0;\n\t$('.numbers :input').each(function(){\n\t\tproductTotal += getPrice($(this).attr('id'),parseInt($(this).val(), 10));\n\t\ttotalItems += parseInt($(this).val(), 10);\n\t});\n\t$('#total').html('$' + productTotal.toFixed(2));\n\t$('#cart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n\t$('#sidecart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n}", "render () {\n //get products info from products on the srote's state based on productIds currently in the cart\n return (\n <div>\n <Cart\n handleChange={this.handleChange}\n handleCheckout={this.handleCheckout}\n handleUpdate={this.props.updateQuant}\n productsInCart={this.props.productsInCart}\n cart={this.props.cart} />\n {\n this.state.showCheckout ? \n <Checkout handleSubmit={this.handleSubmit}/> : \n null \n }\n \n </div>\n )\n }", "function render(items) {\n // LOOP\n // var item = ...\n // $(\"div#target\").append(\"<p>\" + item.message + \"</p>\")\n //\n }", "function generateCart() {\n // const cartButton = document.querySelector(\".cart-btn\");\n // const closeButton = document.querySelector(\".close-cart\");\n const clearButton = document.querySelector(\".clear-cart\");\n const cartDOM = document.querySelector(\".cart\");\n const cartOverlay = document.querySelector(\".cart-overlay\");\n const cartItems = document.querySelector(\".cart-items\");\n // const cartTotal = document.querySelector(\".cart-total\");\n const cartContent = document.querySelector(\".cart-content\");\n let numberProducts = 1;\n const itemQuantity = document.querySelector(\".item-amount\");\n\n $(\".cart-button\").on(\"click\", function() {\n cartOverlay.classList.add(\"transparentBcg\");\n cartDOM.classList.add(\"showCart\");\n });\n\n $(\".close-cart\").on(\"click\", function() {\n cartOverlay.classList.remove(\"transparentBcg\");\n cartDOM.classList.remove(\"showCart\");\n });\n\n function increaseQuantity() {\n numberProducts++;\n $(itemQuantity).text(numberProducts);\n console.log(numberProducts);\n }\n\n function decreaseQuantity() {\n numberProducts--;\n $(itemQuantity).text(numberProducts);\n console.log(numberProducts);\n }\n\n $(\".fa-chevron-up\").on(\"click\", function() {\n increaseQuantity();\n $(cartItems).text(numberProducts);\n });\n\n $(\".fa-chevron-down\").on(\"click\", function() {\n decreaseQuantity();\n $(cartItems).text(numberProducts);\n });\n\n $(clearButton).on(\"click\", function() {\n $(cartContent).empty();\n });\n}", "function renderInventory() {\n\tconsole.log(\"Rendering inventory\");\n\tpopulateDistributors();\n\tpopulateInventory();\n}", "function renderItems(items) {\n // ------------============ Start Here ============------------\n const jsonStr = JSON.stringify(items);\n localStorage.setItem(\"items\", jsonStr);\n populateList(items, itemsList);\n\n // ------------============ End Here ==============------------\n}", "function addRecipeItemsToBody() {\n\n let htmlCardDisplay = \"\";\n\n for (let j = 0; j < recipeCollection.recipe.length; j++) {\n htmlCardDisplay += addHtmlForm(recipeCollection.recipe[j]);\n }\n \n cardParent.innerHTML = htmlCardDisplay;\n}", "html(items) {\n return (`\n <ul class='card'>\n <li class='highlight expense-name' data-id=${this.id}>\n ${this.name}\n </li>\n <table>\n <tr>\n <th>Item</th>\n <th>Price</th>\n <th>Quantity</th>\n <th>Category</th>\n </tr>\n <div class=\"items-container\">\n ${items}\n </div>\n\n </table>\n <button id=\"add-item-button\">Add Item</button>\n <form class='item-card' id=\"new-item-form\" data-id=${this.id}>\n <label>Item name: </label>\n <input type=\"text\" id=\"new-item-name\" placeholder=\"Item name\">\n <br>\n <label>Item cost: </label>\n <input type=\"text\" id=\"new-item-price\" placeholder=\"Item cost\" />\n <br>\n <label>Item quantity: </label>\n <input type=\"text\" id=\"new-item-quantity\" placeholder=\"Item quantity\" />\n <br>\n <label>Item category: </label>\n <input type=\"text\" id=\"new-item-category\" placeholder=\"Item category\" />\n <br>\n <input type=\"submit\" id=\"item-submit\" value=\"Submit\" />\n </form>\n </ul>\n `)\n }", "function purchaseItems() {\n\t// check for atleast one sessionStorage object\n\tif (sessionStorage.itemName) {\n\t\tlet openModal = document.getElementsByClassName('modal')[0]\n\t\topenModal.style.display = 'block'\n\t\tgrandTotal()\n\t} else {\n\t\talert('Please Add An Item To Your Cart.')\n\t\twindow.location.href = '../html/store.html'\n\t}\n}", "function handleAddToCartPress() {\n productID = $(this).attr(\"product-id\");\n console.log(\"cart item id: \" + productID);\n\n productName = $(this).attr(\"name-id\");\n console.log(\"cart product name: \" + productName);\n $(\"#productSelected\").text(productName);\n\n productPrice1 = $(this).attr(\"price-id1\");\n console.log(\"unformatted price: \" + productPrice1);\n\n productPrice2 = $(this).attr(\"price-id2\");\n console.log(\"formatted price: \" + productPrice2);\n\n $(\"#productPrice\").text(productPrice2);\n\n stockQuantity = $(this).attr(\"stock-quantity\");\n console.log(\"stock quantity: \" + stockQuantity);\n\n $(\".view-cart-button-container\").show();\n }", "render() {\n const {\n title, imgUrl, style, price,\n isFreeShipping, pieces, description,\n currencyId, currencyFormat, availableSizes\n } = this.state.currentProduct;\n return (\n <div className={classes.wrapper}>\n <h1>\n {title}\n </h1>\n <img src={imgUrl} alt={description} />\n <h4>\n {isFreeShipping ? 'free shipping' : null}\n </h4>\n <p>{style}</p>\n <p>{currencyFormat}{price} {currencyId}</p>\n <p>Available pieces : {pieces}</p>\n <p>\n Available sizes:\n {\n availableSizes.map(size => <span key={size} style={{ margin: '5px' }}>{size}</span>)\n }\n </p>\n </div>\n\n )\n }", "function startOver() {\n cart = {\n name: null,\n address1: null,\n address2: null,\n zip: null,\n phone: null,\n items: [] //empty array\n }; //cart data\n\n renderCart(cart, $('.template-cart'), $('.cart-container'));\n}", "function updateCartOnLoad(){\n\tconsole.log(\"updateCartOnLoad()\");\n\tvar cookieString = getCookie('ListingID');\n\tif(cookieString == \"\") {\n\t\treturn;\n\t}\n\tvar ids = cookieString.split('|');\n\tvar i;\n\tfor(i = 0; i < ids.length; i++) {\n\t\tupdateCart(ids[i]);\n\t}\n\tdocument.getElementById(\"cart_quantity\").innerHTML = cartQuantity;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the distance from the point (x, y) to the furthest corner of a rectangle.
function distanceToFurthestCorner(x, y, rect) { const distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right)); const distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom)); return Math.sqrt(distX * distX + distY * distY); }
[ "function findBestCorner() {\n\t\t\n\t}", "function findCorner() {\n\t\tvar availTiles = emptyTiles(board);\n\t\t\n\t\tvar corner = availTiles.filter(tile => tile == 0 || tile == 2 || tile == 6 || tile == 8);\n\n\t\treturn corner;\n\t}", "function furthestDistance(arr){\n let m = 0;\n for (var [x1,y1] of arr)\n for (var [x2,y2] of arr)\n m = Math.max(m, Math.hypot(Math.abs(x1-x2),Math.abs(y1-y2)))\n \n return +m.toFixed(2);\n}", "getDistance(x, y) {\n return Math.sqrt(Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2));\n }", "function getCornersOfRect(rect) {\n return [\n {x: rect.x, y: rect.y},\n {x: rect.x + rect.width, y: rect.y},\n {x: rect.x + rect.width, y: rect.y + rect.height},\n {x: rect.x, y: rect.y + rect.height},\n ]\n}", "static getFurthestOffScreenPoint(currPoint){\n\t\tconst midPoint = [window.innerWidth >> 1, window.innerHeight >> 1];\n\t\tif((currPoint[0] < midPoint[0]) && (currPoint[1] < midPoint[1])){\n\t\t\treturn [window.innerWidth + 200, window.innerHeight + 200];\n\t\t} \n\t\telse if((currPoint[0] < midPoint[0]) && (currPoint[1] > midPoint[1])){\n\t\t\treturn [window.innerWidth + 200, - 200];\n\t\t} \n\t\telse if((currPoint[0] > midPoint[0]) && (currPoint[1] > midPoint[1])){\n\t\t\treturn [-200, -200];\n\t\t} \n\t\treturn \t[-200, window.innerHeight + 200]\n\t}", "getMaxRect(x, y, aspect) {\n return Rect.getMax(Math.abs(this.locked[0] - x), Math.abs(this.locked[1] - y), aspect)\n }", "function _getQuadrantOfPiece(topLeft, n, piece) {\n let xBoundary = topLeft.x + Math.pow(2, n - 1) - 1;\n let yBoundary = topLeft.y + Math.pow(2, n - 1) - 1;\n\n if (piece.x <= xBoundary && piece.y <= yBoundary) {\n return 1;\n }\n else if (piece.x <= xBoundary) {\n return 4;\n }\n else if (piece.y <= yBoundary) {\n return 2;\n }\n else {\n return 3;\n }\n}", "function largestRectangle(h) {\n\n let stack = [];\n let mx = -1;\n stack.push(0);\n for (let i = 1; i < h.length; i++) {\n let last_index = stack.slice(-1)[0];\n let stack_h = h[last_index];\n let curr_h = h[i];\n if (curr_h > stack_h || stack.length == 0) {\n stack.push(i);\n }\n else {\n let anchor = i;\n while (curr_h <= stack_h && stack.length > 0) {\n last_index = stack.pop();\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n stack_h = h[last_index];\n }\n }\n }\n\n let anchor = h.length;\n let curr_h = h[h.length - 1];\n let stack_h = h[stack.slice(-1)[0]];\n while (curr_h >= stack_h && stack.length > 0) {\n let last_index = stack.pop();\n stack_h = h[last_index];\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n\n }\n\n return mx;\n}", "sqDistTo(other) {\n const dx = other.x - this.x;\n const dy = other.y - this.y;\n return dx * dx + dy * dy;\n }", "getRightCornerPos() {\n return new THREE.Vector3(\n (CLOTH_SIZE * this.guiOptions.particle_distance) / 2,\n CLOTH_SIZE * this.guiOptions.particle_distance + CLOTH_TO_FLOOR_DISTANCE,\n 0\n );\n }", "function triangle_area(x1,y1,x2,y2,x3,y3){\n var Area = (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))/2\n Area = Math.abs(Area)\n return Area;\n }", "oppositeCorner(corner)\n\t{\n\t\tif (this.start === corner)\n\t\t{\n\t\t\treturn this.end;\n\t\t}\n\t\telse if (this.end === corner)\n\t\t{\n\t\t\treturn this.start;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconsole.log('Wall does not connect to corner');\n\t\t\treturn null;\n\t\t}\n\t}", "function findZoneRectangle(circlesInZone,circlesOutZone) {\n\n\tvar pointsInZone = findSufficientPointsInZone(circlesInZone,circlesOutZone);\n\t\n\tif(pointsInZone.length == 0) {\n\t\treturn new Rectangle(0,0,0,0);\n\t}\n\tvar biggestRectangle;\n\tvar biggestArea = 0;\n\tfor (var i = 0; i < pointsInZone.length; i++) {\n\t\tvar rectangle = findRectangle(pointsInZone[i],circlesInZone,circlesOutZone);\n\t\tif(rectangle.width*rectangle.height > biggestArea) {\n\t\t\tbiggestRectangle = rectangle;\n\t\t\tbiggestArea = rectangle.width*rectangle.height;\n\t\t}\n\t}\n\treturn biggestRectangle;\n}", "function determineDiameter() {\n var height = square_div_array[0].clientHeight;\n var width = square_div_array[0].clientWidth;\n // how to return most correct size circle?\n return (lessThan(height, width)-5)+'px';\n}", "function getFirstVisibleRect(element) {\n // find visible clientRect of element itself\n var clientRects = element.getClientRects();\n for (var i = 0; i < clientRects.length; i++) {\n var clientRect = clientRects[i];\n if (isVisible(element, clientRect)) {\n return {element: element, rect: clientRect};\n }\n }\n // Only iterate over elements with a children property. This is mainly to\n // avoid issues with SVG elements, as Safari doesn't expose a children\n // property on them.\n if (element.children) {\n // find visible clientRect of child\n for (var j = 0; j < element.children.length; j++) {\n var childClientRect = getFirstVisibleRect(element.children[j]);\n if (childClientRect) {\n return childClientRect;\n }\n }\n }\n return null;\n}", "function calculateDistance(fov) {\n // Calculate longest edge of the image, to make sure we pull back far enough from it\n var longestEdge = Math.max(Math.abs(extents[0] - extents[1]), Math.abs(extents[2] - extents[3]));\n return 3 * longestEdge / Math.sin(fov); // Multiplying by 2 would ensure the bounds of the image would touch the\n // bounds of the canvas. Multiplying by 3 means it takes only 2/3 the canvas.\n}", "calculateDimensions() {\r\n let leftMostCoordinate = this.transformedPolygon[0][0],\r\n rightMostCoordinate = this.transformedPolygon[0][0],\r\n topMostCoordinate = this.transformedPolygon[0][1],\r\n bottomMostCoordinate = this.transformedPolygon[0][1];\r\n\r\n for(let i=0; i<this.transformedPolygon.length; i++) {\r\n if(this.transformedPolygon[i][0] < leftMostCoordinate) {\r\n leftMostCoordinate = this.transformedPolygon[i][0];\r\n } else if(this.transformedPolygon[i][0] > rightMostCoordinate) {\r\n rightMostCoordinate = this.transformedPolygon[i][0];\r\n }\r\n\r\n if(this.transformedPolygon[i][1] < topMostCoordinate) {\r\n topMostCoordinate = this.transformedPolygon[i][1];\r\n } else if(this.transformedPolygon[i][1] > bottomMostCoordinate) {\r\n bottomMostCoordinate = this.transformedPolygon[i][1];\r\n }\r\n }\r\n\r\n this.width = Math.abs(rightMostCoordinate - leftMostCoordinate);\r\n this.height = Math.abs(bottomMostCoordinate - topMostCoordinate);\r\n }", "function getZ(x, y) {\n // We assume that the plane equation is up-to-date\n // with the current polygon.\n return -(A * x + B * y + D) / C;\n }", "function objDistSq(obj1, obj2) {\n return Math.pow(obj2.x - obj1.x, 2) + Math.pow(obj2.y - obj1.y, 2);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
will highlight all items with color
function highlightItems(color, items){ items.style({"stroke":color, "opacity": "1"}); }
[ "function highlightFromList(index) {\n\t\t$('.' + column + '-result-li').css({ 'background':'#fff' });\n\t\t$('.' + column + '-result-li').eq(index).css({ 'background': '#eee'});\n\t}", "function theClickedItem(item) {\n setHighlightItem(item);\n }", "function setColorHighlight( color ){\n \n if(color.r > 0.5) color.r = (color.r * 1.005);\n if(color.g > 0.5) color.g = (color.g * 1.005);\n if(color.b > 0.5) color.b = (color.b * 1.005);\n}", "function highlighter(selected){\n //return all circles to default\n d3.selectAll(\".market\")\n .attr(\"fill\", defaultColor)\n .attr(\"fill-opacity\", \"0.5\")\n\n //if there is anything selected, highlight it.\n if(selected.length != 0){\n //converted the selected list to a css selector string.\n var selector = \".\" + selected.join('.')\n d3.selectAll(selector)\n .attr(\"fill\", selectColor)\n // .attr(\"r\", 4)\n .attr(\"fill-opacity\", \"1\")\n .moveToFront()\n }\n\n}", "function highlightRow(name) {\n var row = document.getElementById('basket-item-' + name);\n row.style.backgroundColor = 'rgba(0, 128, 0, 0.39)';\n row.scrollIntoView();\n setTimeout(function() {\n row.style.backgroundColor = 'rgba(0, 0, 0, 0)'\n }, 500);\n}", "onLayerHighlight() {}", "function HighlightRow(chkB) {\n /* var oItem = chkB.children;\n xState=oItem.item(0).checked; */\n var xState = chkB.checked;\n if(xState)\n {chkB.parentElement.parentElement.style.backgroundColor=backgroundColorSel;\n // grdEmployees.SelectedItemStyle.BackColor\n chkB.parentElement.parentElement.style.color=colorSel; \n // grdEmployees.SelectedItemStyle.ForeColor\n }else \n {chkB.parentElement.parentElement.style.backgroundColor=backgroundColorDef;\n //grdEmployees.ItemStyle.BackColor\n chkB.parentElement.parentElement.style.color=colorDef; \n //grdEmployees.ItemStyle.ForeColor\n }\n }", "highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }", "function setColor() {\n for(let i = 0; i < boxes.length; i++) {\n boxes[i].style.backgroundColor = color[i];\n } \n}", "highlight() {\n this.model.set('isSelected', true);\n }", "function applyBasicColor() {\n var type;\n basicColorMenu.forEach(function (element) {\n for (i = 0; i < currentColorData.length; i++) {\n if (element.id === currentColorData[i].id) {\n type = element.type;\n element.elements.forEach(function (element) {\n setClassColor(element, currentColorData[i].color, type);\n });\n }\n }\n });\n showClassOnHover();\n}", "function navGraphicsHighlightSearchOn(){\n $(\"#search_icon\").animate({\"background-color\":\"white\"});\n}", "function highlightGrid(object) {\n if(hoverGrid) hoverGrid.style.backgroundColor = \"\";\n\n for (var i = 0; i < grids.length; i++) {\n if (withinIt(object, grids[i])) {\n hoverGrid = grids[i];\n hoverGrid.style.backgroundColor = \"rgb(75, 88, 98)\";\n break;\n }\n }\n }", "function highlight(elems, marker) {\n\tconsole.log('highlight', elems, marker);\n\telems.forEach(function(e) {\n\t\tvar names = getClassNames(e);\n\t\tsetVisibility(e, names.indexOf(marker) != -1);\n\t});\n}", "drawIconHighlight(ctx) {}", "function highlight() {\n if (count === 0 && goesFirst === 2) {\n $('.x, .o').toggleClass('highlight');\n }\n }", "setDateItemColor() {\n\t\t\tconst firstIndex = 0;\n\n\t\t\tlet distinct = [];\n\t\t\tlet tempSchedule = this.state.schedule.filter((item) => {\n\t\t\t\tif (distinct.includes(item.start)) return false;\n\t\t\t\tdistinct.push(item.start);\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\t\ttempSchedule = tempSchedule.sort((a, b) => new Date(a.start) - new Date(b.start));\n\n\t\t\tconst lastIndex = tempSchedule.length - 1;\n\n\t\t\t$(`.fc-day`).css({\n\t\t\t\tbackgroundColor: \"\",\n\t\t\t});\n\n\t\t\ttempSchedule.forEach((item, index) => {\n\t\t\t\titem.start = moment(item.start).format(\"YYYY-MM-DD\");\n\n\t\t\t\tif (item.status == \"end\" && index == lastIndex) {\n\t\t\t\t\t$(`.fc-day[data-date=${item.start}]`).css({\n\t\t\t\t\t\tbackgroundColor: this.backgroundColor.redDark,\n\t\t\t\t\t});\n\t\t\t\t} else if (index == firstIndex) {\n\t\t\t\t\t$(`.fc-day[data-date=${item.start}]`).css({\n\t\t\t\t\t\tbackgroundColor: this.backgroundColor.green,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t$(`.fc-day[data-date=${item.start}]`).css({\n\t\t\t\t\t\tbackgroundColor: this.backgroundColor.orange,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function selectAllZw(oll, coll, c)\r\n{\r\n var collMap = zbllMap[oll][coll];\r\n for (var zbll in collMap) if (collMap.hasOwnProperty(zbll))\r\n {\r\n collMap[zbll][\"c\"] = c;\r\n // change color\r\n if (c)\r\n document.getElementById( idItemZbll(oll, coll, zbll) ).style.backgroundColor = colorAll;\r\n else\r\n document.getElementById( idItemZbll(oll, coll, zbll) ).style.backgroundColor = colorNone();\r\n }\r\n updateZwHeader(oll, coll);\r\n}", "changeColor() {\n this.currentColor = this.intersectingColor;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Quick check that indicates the platform may be Cordova
function _isLikelyCordova() { return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined'; }
[ "function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}", "function IsPC() {\n var userAgentInfo = navigator.userAgent\n var Agents = [\"Android\", \"iPhone\", \"SymbianOS\", \"Windows Phone\", \"iPad\", \"iPod\"]\n var devType = 'PC'\n for (var v = 0; v < Agents.length; v++) {\n if (userAgentInfo.indexOf(Agents[v]) > 0) {\n // Determine the system platform used by the mobile end of the user\n if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {\n //Android mobile phone\n devType = 'Android'\n } else if (userAgentInfo.indexOf('iPhone') > -1) {\n //Apple iPhone\n devType = 'iPhone'\n } else if (userAgentInfo.indexOf('Windows Phone') > -1) {\n //winphone\n devType = 'winphone'\n } else if (userAgentInfo.indexOf('iPad') > -1) {\n //Pad\n devType = 'iPad'\n }\n break;\n }\n }\n docEl.setAttribute('data-dev-type', devType)\n }", "_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }", "function detectPlatform () {\n var type = os.type();\n var arch = os.arch();\n\n if (type === 'Darwin') {\n return 'osx-64';\n }\n\n if (type === 'Windows_NT') {\n return arch == 'x64' ? 'windows-64' : 'windows-32';\n }\n\n if (type === 'Linux') {\n if (arch === 'arm' || arch === 'arm64') {\n return 'linux-armel';\n }\n return arch == 'x64' ? 'linux-64' : 'linux-32';\n }\n\n return null;\n}", "get isNativePlugin() {}", "function isPluginEnabled() {\n return cordova && cordova.plugins && cordova.plugins.permissions;\n }", "SetCompatibleWithAnyPlatform() {}", "function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}", "SetCompatibleWithPlatform() {}", "set isNativePlugin(value) {}", "function platform() {\n\tvar s = process.platform; // \"darwin\", \"freebsd\", \"linux\", \"sunos\" or \"win32\"\n\tif (s == \"darwin\") return \"mac\"; // Darwin contains win, irony\n\telse if (s.starts(\"win\")) return \"windows\"; // Works in case s is \"win64\"\n\telse return \"unix\";\n}", "function isRBMPlatform (currentPlatform) {\n return currentPlatform == HIGH_DIMENSIONAL_DATA[\"rbm\"].platform ? true : false;\n}", "function DetectPalmOS()\n{\n if (uagent.search(devicePalm) > -1)\n location.href='http://www.kraftechhomes.com/home_mobile.php';\n else\n return false;\n}", "function hasNavigator(){return typeof navigator!=='undefined';}", "function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}", "function refreshPlatforms(platforms) {\n if(platforms === undefined) return;\n deleteDirSync(\"platforms\");\n\n if(platforms.indexOf(\"a\") !== -1)\n runShell(\"npx ionic cordova platform add android\");\n\n if(platforms.indexOf(\"i\") !== -1)\n if (OS.platform() === \"darwin\") runShell(\"npx ionic cordova platform add ios\");\n else consoleOut(`(set_brand.js) did not add ios-platform on the operating system \"${OS.platform()}\"`);\n}", "showBrowserWarning () {\n let showWarning = false\n let version = ''\n\n // check firefox\n if (window.navigator.userAgent.indexOf('Firefox') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3).replace(/\\./g, ''))\n\n // lower than 19?\n if (version < 19) showWarning = true\n }\n\n // check opera\n if (window.navigator.userAgent.indexOf('OPR') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower than 9?\n if (version < 9) showWarning = true\n }\n\n // check safari, should be webkit when using 1.4\n if (window.navigator.userAgent.indexOf('Safari') !== -1 && window.navigator.userAgent.indexOf('Chrome') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3))\n\n // lower than 1.4?\n if (version < 400) showWarning = true\n }\n\n // check IE\n if (window.navigator.userAgent.indexOf('MSIE') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower or equal than 6\n if (version <= 6) showWarning = true\n }\n\n // show warning if needed\n if (showWarning) $('#showBrowserWarning').show()\n }", "function isVendorSupported() {\n if (vendorSupport != null) {\n return Promise.resolve(vendorSupport);\n }\n return getGoVersion().then(function (version) {\n if (!version) {\n return process.env['GO15VENDOREXPERIMENT'] === '0' ? false : true;\n }\n switch (version.major) {\n case 0:\n vendorSupport = false;\n break;\n case 1:\n vendorSupport = (version.minor > 6 || ((version.minor === 5 || version.minor === 6) && process.env['GO15VENDOREXPERIMENT'] === '1')) ? true : false;\n break;\n default:\n vendorSupport = true;\n break;\n }\n return vendorSupport;\n });\n}", "function isDistAvailable(logger) {\n let arch;\n const detectedArch = detectArch_1.detectArch(logger);\n switch (detectedArch) {\n case \"x64\":\n arch = \"x64\" /* x64 */;\n break;\n default:\n if (logger) {\n logger.error(`System arch \"${detectedArch}\" not supported. Must build from source.`);\n }\n return false;\n }\n let platform;\n switch (os.platform()) {\n case \"win32\":\n case \"cygwin\":\n platform = \"windows\" /* WINDOWS */;\n break;\n case \"darwin\":\n platform = \"macos\" /* MACOS */;\n break;\n case \"linux\":\n if (detectLibc_1.detectLibc().isNonGlibcLinux) {\n platform = \"linux-musl\" /* LINUX_MUSL */;\n }\n else {\n platform = \"linux\" /* LINUX */;\n }\n break;\n default:\n if (logger) {\n logger.error(`System platform \"${os.platform()}\" not supported. Must build from source.`);\n }\n return false;\n }\n return {\n platform,\n arch\n };\n}", "IsRemoteConfigured() {\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the basket object from a cookie.
function getBasket() { var str = getCookie(cookieName); return str ? JSON.parse(str) : {}; }
[ "function saveBasket(objBasket) {\n var str = JSON.stringify(objBasket);\n setCookie(cookieName, str);\n }", "async getOrCreateBasket() {\n const customerBaskets = await api.shopperCustomers.getCustomerBaskets({\n parameters: {customerId: customer?.customerId}\n })\n\n if (Array.isArray(customerBaskets?.baskets)) {\n return setBasket(customerBaskets.baskets[0])\n }\n\n // Back to using ShopperBaskets for all basket interaction.\n const newBasket = await api.shopperBaskets.createBasket({})\n setBasket(newBasket)\n }", "function getCookie(){\r\n\t// get items cookie\r\n\tvar items = \"\";\r\n\tvar name = \"items=\";\r\n\tvar ca = document.cookie.split(';');\r\n\tfor(var i=0; i<ca.length; i++) {\r\n\t\tvar c = ca[i].trim();\r\n\t \tif (c.indexOf(name) == 0) {\r\n\t \t\tvar items = c.substring(name.length, c.length);\r\n\t \t}\r\n\t}\r\n\r\n\t// add each item to list\r\n\titems = items.split(\"|\");\r\n\tfor (var i = 0; i < items.length; i++){\r\n\t\taddItem(items[i], false);\r\n\t}\r\n}", "function cookieGetSettings() {\n return JSON.parse($.cookie(cookie));\n }", "function getCart () {\n return cart\n}", "function get_cookie(request){\n console.log(request.headers.get('Cookie'));\n if (request.headers.get('Cookie')) {\n const pattern = new RegExp('variant=([10])');\n let match = request.headers.get('Cookie').match(pattern);\n if (match) { \n return match[1]; \n }\n }\n return null\n}", "function getCookie(name) {\n var index = document.cookie.indexOf(name + \"=\")\n if (index == -1) { return \"undefined\"}\n index = document.cookie.indexOf(\"=\", index) + 1\n var end_string = document.cookie.indexOf(\";\", index)\n if (end_string == -1) { end_string = document.cookie.length }\n return unescape(document.cookie.substring(index, end_string))\n} // Based on JavaScript provided by Peter Curtis at www.pcurtis.com -->", "function loadCookies() {\n document.getElementById('name').value = getCookie('name');\n document.getElementById('brand').selectedIndex = getCookie('brand');\n document.getElementById('Type').selectedIndex = getCookie('type');\n document.getElementById('target').selectedIndex = getCookie('target');\n document.getElementById('condition').selectedIndex = getCookie('condition');\n document.getElementById('location').selectedIndex = getCookie('location');\n}", "function getOrders(){\n return JSON.parse(localStorage.getItem(\"orders\"));\n}", "function getTokenInCookie(){\n let token = document.cookie.slice(document.cookie.lastIndexOf(\"=\")+1);\n return token;\n}", "function getStocks(){\n return JSON.parse(localStorage.getItem(STOCK_STORAGE_NAME));\n}", "function getCookieInfo () {\n // return the contact cookie to be used as an Object\n return concurUtilHttp.getDeserializedQueryString($.cookie('concur_contact_data'));\n }", "function setCookie(){\r\n\tvar items = document.getElementsByClassName(\"list-group-item\");\r\n\tvar itemText = new Array();\r\n\tfor (var i = 0; i < items.length; i++){\r\n\t\titemText[i] = items[i].id;\r\n\t}\r\n\tdocument.cookie = \"items=\" + itemText.join(\"|\");\r\n}", "function getDate(){\n var cookieArray = document.cookie.split(' ');\n return cookieArray[1];\n}", "function bakeCookies() {\n\n}", "static async getForCheckout(userId) {\n const bucket = await this.where({ id_users: userId, status_bucket: BucketStatus.ADDED }).fetch({\n withRelated: ['promo', 'items.product', 'items.shipping'],\n });\n if (!bucket) throw getBucketError('bucket', 'not_found');\n return bucket;\n }", "static getCookie(name) {\n var arg = name + \"=\";\n var alen = arg.length;\n var clen = document.cookie.length;\n var i = 0;\n while (i < clen) {\n var j = i + alen;\n if (document.cookie.substring(i, j) == arg) {\n return CookieUtil.getCookieVal(j);\n }\n i = document.cookie.indexOf(\" \", i) + 1;\n if (i == 0) break;\n }\n return null;\n }", "function getCookies()\n {\n var retPromise = q.defer();\n\n var options = {\n url: REST_URL,\n method: \"GET\",\n };\n request(options, function(error, response, body) {\n // console.log(\"Response: \", response);\n\n console.log(\"Cookies: \".green,response.headers['set-cookie']);\n var cookies = (response.headers['set-cookie']).toString();\n var jsessionid = cookies.split(';');\n jsessionid = jsessionid[0];\n console.log(\"My Cookie:\",jsessionid);\n\n var options = {\n url: BASE_URL+ jsessionid,\n method: \"POST\"\n };\n request(options, function(error, response, body) {\n retPromise.resolve(body);\n });\n // console.log(\"Response Body: \".yellow,body);\n });\n\n return retPromise.promise;\n }", "function restoreOrder(sortable, cookieName) {\n var list = $(sortable);\n if (!list) {\n return;\n }\n\n // fetch the saved cookie\n var cookie = $.cookie(cookieName);\n if (!cookie) {\n return;\n }\n\n // create array from cookie\n var IDs = cookie.split(\",\"),\n\n // fetch current order\n items = list.sortable(\"toArray\"),\n\n // create associative array from current order\n current = [];\n for (var v = 0; v < items.length; v++) {\n current[items[v]] = items[v];\n }\n\n for (var i = 0, n = IDs.length; i < n; i++) {\n // item id from saved order\n var itemID = IDs[i];\n\n if (itemID in current) {\n // select the item according to the saved order and reappend it to the list\n $(sortable).append($(sortable).children(\"#\" + itemID));\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete meeting with id from this user's meeting list
deleteMeeting(id){ this.meetings = this.meetings.filter( (meeting) => { return meeting.id !== id; } ) }
[ "async deleteAppointment(id) {\n return Appointment.destroy({where:{id}})\n }", "function delUserForMeeting( data, callback ) {\n\t\t\tvar url = '/meetingdelusers';\n\n\t\t\tnew IO({\n\t\t\t\turl: url,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: data,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t\tcallback(data);\n\t\t\t\t}\n\t\t\t});\n\n\t\t}", "function handleDelete(event) {\n\tlet id = event.target.id;\n\n\tlet output = [];\n\n\toutput = db_appointments.filter(function (value) {\n\t\treturn value.idPengunjung !== id;\n\t});\n\n\tdb_appointments = output;\n\n\tevent.target.parentElement.remove();\n}", "function remove(id) {\n return db(\"todos\")\n .where({ id })\n .del();\n}", "delete(id) {\n return this.send(\"DELETE\", `events/${id}`);\n }", "function removeAttendeeHour(id) {\n $('tr[data-id=' + id + ']').remove();\n}", "function deleteReminder(req, res) \n{\n\tfindReminder(req, res, function(item) \n\t{\n\t\titem.remove(function (err) \n\t\t{\n\t\t\tif (err) return reportError(err, res)\n\n\t\t\tres.status(204).end();\n\t\t})\n\t})\n}", "function destroy(id) {\n return apiWithAuth.delete(`/notifications/${id}`);\n}", "async remove (id, params) {\n //need to use this in different scope\n const self = this;\n const roomId = id;\n //prolly get user model maybe (why is it caps???)\n const users = this.sequelizeClient.model.Users;\n //get user to be removed\n const {user} = params;\n //remove roomId from users \"rooms\" array (ide says i need an await here but i dont think i do)\n await users.update({'rooms': Sequelize.fn('array_remove', Sequelize.col('rooms'), roomId)},\n {'where': {'id': user}});\n //if user is connected to the rooms/roomId channel remove them\n self.app.channel(`rooms/${roomId}`).connections.forEach(function (connection){\n if(connection.user.id === user){\n self.app.channel(`room/${roomId}`).leave(connection);\n }\n });\n\n return id;\n }", "function deleteTask(){\n // TODO: IF program.task exists you should use mongoose's .remove function\n // on the model to remove the task with {name: program.task}\n\n // YOUR CODE HERE\n if(program.task){\n ToDoItem.remove({ name: program.task }, function (err) {\n if (err) return console.error(err);\n console.log(\"Deleted task with name: \" + program.task);\n mongoose.connection.close();\n });\n } else {\n console.log(\"No task specified\");\n mongoose.connection.close();\n }\n}", "deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }", "deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }", "function destroy(id) {\n\treturn db.none(`DELETE FROM tours WHERE id=$1`, [id]);\n}", "function deleteLoan(id) {\n let element = document.getElementById(id);\n element.parentNode.removeChild(element);\n}", "function deleteEmail(id) {\n $.ajax({\n url: apiUrl + 'contact?id=' + id,\n type: 'DELETE',\n success: () => {\n $('#email_' + id).remove();\n }\n });\n}", "function remove_event_from_fullcalendar(eventId) {\n\ttimetableCalend.fullCalendar('removeEvents', eventId);\n}", "function deleteTask(){\n // get indx of tasks\n let mainTaskIndx = tasksIndxOf(delTask['colName'], delTask['taskId']);\n // del item\n tasks.splice(mainTaskIndx, 1);\n // close modal\n closeModal();\n // update board\n updateBoard();\n // update backend\n updateTasksBackend();\n}", "deleteAppointment(date,time)\n {\n if (this.map.has(date)) {\n\n for (let i=0; i<this.map.get(date).length; i++)\n {\n if (this.map.get(date)[i].date == date && this.map.get(date)[i].time == time) {\n this.map.get(date).splice(i,1);\n break;\n }\n }\n }\n }", "'click .delete'() {\n\t\tMeteor.call('tasks.remove', this._id, (error) => {\n\t\t\tif (error)\n\t\t\t\tBert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );\n\t\t\telse\n\t\t\t\tBert.alert( 'Task removed successfully!', 'success', 'growl-top-right' );\n\t\t});\n\t}", "function deleteUser(id) {\n // if it is NOT the same id return a list of all the users without that ID\n const updatedUsers_forDelete = usersInDanger_resc.filter(user => user.userID !== id);\n const deletedUser = usersInDanger_resc.filter(user => user.userID === id);\n setUsersInDanger_resc(updatedUsers_forDelete);\n console.log(deletedUser[0].userID);\n props.markSafe(deletedUser[0].userID);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the copy for the user to the copydata of the element when clicked
function copyToClipboard() { const el = document.createElement('textarea'); el.value = event.target.getAttribute('copy-data'); el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); }
[ "function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}", "function CopySongData() {\n document.querySelector('#songDataHolder').value = JSON.stringify(songData, null, 2);\n document.querySelector('#songDataHolder').select();\n document.execCommand('copy');\n}", "function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }", "copyToClipboard(e){\n e.preventDefault();\n var copyTextarea = document.getElementById('post');\n copyTextarea.select();\n try{\n document.execCommand('copy');\n console.log(\"Post copied succesfully.\");\n }\n catch(err){\n console.log(\"Unable to copy the post. Please, do it manually selecting the text and pressing Crtl + C keys.\");\n console.log(err)\n }\n }", "function initShareButton() {\n // share button clicked. copy the link to the clipboard\n $('#share-copy').click(() => {\n var aux = document.createElement(\"input\"); \n aux.setAttribute(\"value\", window.location.href); \n document.body.appendChild(aux); \n aux.select();\n document.execCommand(\"copy\"); \n document.body.removeChild(aux);\n\n alert(\"The share link has been copied to your clipboard.\");\n });\n}", "copyActiveDataToClipboard() {\n const { activeData } = this.state;\n const cleanData = encounterDataUtils.formatEncounterData(activeData);\n NotificationManager.info('Copied Current Data', undefined, 1000);\n copyToClipboard(JSON.stringify(cleanData));\n }", "function dc_copy_to_clipboard(div) {\n let copyText = document.getElementById(div).innerText;\n //console.log(copyText);\n /* Copy the text inside the text field */\n navigator.clipboard.writeText(copyText);\n}", "function handleDescriptionCopy() {\n var copyText = document.getElementById(\"part-descriptions\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }", "function copy_json() {\n\tdocument.getElementById(\"json_box\").select();\n\tdocument.execCommand(\"copy\");\n}", "copyDataListToClipboard() {\n const { dataList } = this.state;\n const cleanList = encounterDataUtils.formatEncounterList(dataList);\n NotificationManager.info('Copied All Data', undefined, 1000);\n copyToClipboard(JSON.stringify(cleanList));\n }", "handleCopyCut(event) {\n event.stopPropagation();\n let activeNode = this.getActiveNode();\n if(!activeNode) return;\n\n // If nothing is selected, say \"nothing selected\" for cut\n // or copy the clipboard to the text of the active node\n if(this.selectedNodes.size === 0) {\n if(event.type == 'cut') {\n this.say(\"Nothing selected\");\n return;\n } else if(event.type == 'copy') {\n this.clipboard = this.cm.getRange(activeNode.from, activeNode.to);\n }\n // Otherwise copy the contents of selection to the buffer, first-to-last\n } else {\n let sel = [...this.selectedNodes].sort((a, b) => poscmp(a.from, b.from));\n this.clipboard = sel.reduce((s,n) => s + this.cm.getRange(n.from, n.to)+\" \",\"\");\n }\n\n this.say((event.type == 'cut'? 'cut ' : 'copied ') + this.clipboard);\n this.buffer.value = this.clipboard;\n this.buffer.select();\n try {\n document.execCommand && document.execCommand(event.type);\n } catch (e) {\n console.error(\"execCommand doesn't work in this browser :(\", e);\n }\n // if we cut selected nodes, clear them\n if (event.type == 'cut') { this.deleteSelectedNodes(); } // delete all those nodes if we're cutting\n else { activeNode.el.focus(); } // just restore the focus if we're copying\n }", "onButtonSaveStateClick(){\n let hiddenInput = document.createElement(\"input\");\n hiddenInput.setAttribute(\"value\",JSON.stringify(this.state.radios));\n document.body.appendChild(hiddenInput);\n hiddenInput.select();\n document.execCommand(\"copy\");\n document.body.removeChild(hiddenInput);\n }", "function copy_element_to_clipboard(element, strip_html){\n if (!element){\n alert('Element not found for copy action in copy_element_to_clipboard.');\n return false;\n }\n\n if (typeof(element.selectedIndex) != \"undefined\"){\n // select box.\n\n if (element.multiple){\n var selected_options = new Array();\n for(var i = 0; i < element.options.length; i++){\n if ( element.options[i].selected ){\n selected_options.push(element.options[i].value);\n }\n }\n // Join on \"|~~|\". Perhaps use a parameter in the future.\n // Did not want to add in this early version, though.\n return copy_text_to_clipboard(selected_options.join(\"|~~|\"), strip_html);\n }else if (element.selectedIndex < 0){\n alert ('No selection in select box.');\n return false;\n }\n // standard select of size 1.\n return copy_text_to_clipboard(element.options[element.selectedIndex].value, strip_html);\n }else if (element.value){\n // Simple text/textarea input.\n return copy_text_to_clipboard(element.value, strip_html);\n }else if(element.innerText && strip_html){\n // no need to run strip_html here. innerText handles that.\n return copy_text_to_clipboard(element.innerText, 0);\n\n // Mozilla's .textContent returns all whitespace, rather\n // than what the text looks like when displayed in browser.\n // So let's not use it, and use innerHTML instead.\n // Use the copy_text_to_clipboard function if you need that\n // functionality.\n }else if(element.innerHTML){\n // NOTE: The value here may not be the original HTML!\n return copy_text_to_clipboard(element.innerHTML, strip_html);\n }else{\n alert(\"Your browser does not support copying of elements. Please upgrade to the latest version of Mozilla FireFox or Internet Explorer\");\n }\n\n return false;\n}", "unsuccessfulCopy () {\n this.labelTarget.innerHTML = 'Press Ctrl+C to copy!';\n }", "copyLnglat () {\n const lnglat = `${this.clickLatlng.lng}, ${this.clickLatlng.lat}`\n if (this.copyToClipboard(lnglat)) {\n this.showSuccess(this.$t('mapLeftClick.lnglatCopied'), { timeout: 2000 })\n }\n }", "function copyToClipboard() {\n var el = document.createElement('textarea');\n el.value = loremIpsumText.textContent;\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}", "function resetCopyButton(clickedBtnID) {\n var i;\n var listButtons = document.getElementsByClassName(\"btn-copy\");\n for (i = 0; i < listButtons.length; i++) {\n listButtons[i].textContent = \"Copy\";\n listButtons[i].classList.remove(\"copied\");\n }\n\n var clickedBtn = document.getElementById(clickedBtnID);\n clickedBtn.textContent = \"Copied!\";\n clickedBtn.classList.add(\"copied\");\n}", "constructor() {\n this.securityAndPermissionsClipboard();\n }", "function copy()\n{\n var params = arguments;\n var paramsLength = arguments.length;\n var e = params[0];\n var c = params[paramsLength-1];\n if($(e).length < 1)\n {\n var uniqueid = unique_id();\n var textareaId = \"__temp_textarea__\"+uniqueid;\n var element = $(\"<textarea id='\"+textareaId+\"'></textarea>\");\n element.appendTo('body')\n .each(function(){\n $(this).val(e)\n $(this).select()\n })\n }else\n {\n $(e).select();\n }\n\n try {\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n console.log('Copying text was ' + msg);\n if($(e).length < 1)\n {\n $(this).remove();\n }\n if(typeof c == 'function')\n {\n c()\n }\n } catch (err) {\n console.error('Oops, unable to copy');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the array of RSSI samples
function updateRssiArray(sample) { for(var receiverTemp in $scope.receivers) { var updated = false; var seconds = $scope.rssiSeconds; // Try to update the rssi corresponding to the receiver. for(var cRadio = 0; cRadio < sample[$scope.transmitterId].radioDecodings.length; cRadio++) { if(sample[$scope.transmitterId].radioDecodings[cRadio].identifier.value === receiverTemp) { var rssi = sample[$scope.transmitterId].radioDecodings[cRadio].rssi; if($scope.rssiSamples[receiverTemp]) { $scope.rssiSamples[receiverTemp].push({ seconds: seconds, rssi: rssi }); } else { $scope.rssiSamples[receiverTemp] = []; $scope.rssiSamples[receiverTemp].push({ seconds: seconds, rssi: rssi }); } updated = true; break; } } // If it failed to be updated, push 0 as default. if(!updated) { if($scope.rssiSamples[receiverTemp]) { $scope.rssiSamples[receiverTemp].push({ seconds: seconds, rssi: 0 }); } else { $scope.rssiSamples[receiverTemp] = []; $scope.rssiSamples[receiverTemp].push({ seconds: seconds, rssi: 0 }); } } // If it has reached the maximum number of samples, drop the oldest one. if($scope.rssiSamples[receiverTemp].length > $scope.maxNumberOfSamples) { $scope.rssiSamples[receiverTemp].shift(); } } }
[ "function updateRssiSamples(sample) {\n for(var transmitterTemp in $scope.transmitters) {\n if(!(transmitterTemp in $scope.rssiSamples)) {\n $scope.rssiSamples[transmitterTemp];\n $scope.rssiSamples[transmitterTemp] = [];\n }\n if(sample[transmitterTemp]) {\n for(var cRadio = 0;\n cRadio < sample[transmitterTemp].radioDecodings.length;\n cRadio++) {\n var radioDecodingReceiver = sample[transmitterTemp].radioDecodings[cRadio].identifier.value;\n if(radioDecodingReceiver === $scope.receiverId) {\n var rssi = sample[transmitterTemp].radioDecodings[cRadio].rssi;\n $scope.rssiSamples[transmitterTemp].push(rssi);\n updated = true;\n break;\n }\n }\n }\n else {\n $scope.rssiSamples[transmitterTemp].push(0);\n }\n if($scope.rssiSamples[transmitterTemp].length > $scope.maxNumberOfSamples) {\n $scope.rssiSamples[transmitterTemp].shift();\n }\n }\n }", "function update() {\n // populate the analyser buffer with frequency bytes\n analyser.getByteFrequencyData(buffer);\n // look for trigger signal\n for (var i = 0; i < analyser.frequencyBinCount; i++) {\n var percent = buffer[i] / 256;\n // TODO very basic / naive implementation where we only look\n // for one bar with amplitude > threshold\n // proper way will be to find the fundamental frequence of the square wave\n if (percent > config.threshold) {\n events.dispatch('signal');\n return;\n }\n }\n}", "updateSampleDataArray () {\n\n // Update the state with the new array.\n this.setState({\n sampleFrequencyDataArray: this.updateSampleFrequencyDataArray(),\n sampleTimeDataArray: this.updateSampleTimeDataArray(),\n });\n\n // Recurse when available.\n requestAnimationFrame(() => this.updateSampleDataArray());\n\n }", "updateThreshold() {\n\n if (this.suppressed == null) {\n return;\n }\n\n // Do double threshold\n const context = this.canvas.getContext('2d');\n let imgData = context.getImageData(0, 0, 200, 200);\n\n let temp = new Array2D([...this.suppressed.data], this.suppressed.width, this.suppressed.height, this.suppressed.channels);\n\n doubleThreshold(temp, this.state.hiThreshold, this.state.loThreshold);\n fillArray(imgData.data, temp.data, imgData.data.length);\n context.putImageData(imgData, 0, 0);\n }", "function requestAllRSSI() {\n request_counter++;\n for(address in xbeeAddress) {\n requestRSSI(xbeeAddress[address]);\n }\n}", "function updateReceivers(sample) {\n for(var cRadio = 0;\n cRadio < sample[$scope.transmitterId].radioDecodings.length;\n cRadio++) {\n var receiverTemp = sample[$scope.transmitterId].radioDecodings[cRadio].identifier.value;\n if(!(receiverTemp in $scope.receivers)) {\n var colorTemp = COLORS_ARRAY[cCOlOR_TRANSMITTER++ % COLORS_ARRAY.length];\n $scope.receivers[receiverTemp] = { color: colorTemp, isDrawn: false, isDisplayed: true, latest: 0, receiverId: receiverTemp };\n }\n }\n }", "function fillStatPointsArray(){\n stat_points_per_level.push(0);\n for(var i=1;i<185;i++){\n stat_points_per_level.push(stat_points_per_level[i-1]+calcStatGain(i+1));\n }\n}", "function initializeFrequencyArray()\n{\n for(var i=0; i<history_size; i++)\n {\n freq_amp_arr[i] = new Array(frequencyBinCount);\n freq_amp_arr[i].fill(0);\n }\n}", "function updateTransmitters(sample) {\n for(var transmitterTemp in sample) {\n if(!(transmitterTemp in $scope.transmitters) && ($scope.numTransmitters < $scope.maxNumberOfTransmitters)) {\n $scope.transmitters[transmitterTemp]; // Adding new transmitters as they come.\n $scope.transmitters[transmitterTemp] = { value : transmitterTemp};\n $scope.numTransmitters++; // Incrementing the number of receivers.\n }\n }\n }", "function mapBeaconRSSI(rssi)\n{\n\tif (rssi >= 0) return 1; // Unknown RSSI maps to 1.\n\tif (rssi < -100) return 100; // Max RSSI\n\treturn 100 + rssi;\n}", "update() {\n for (let device of this.devices) {\n device.update();\n }\n }", "startThermsReading() {\n setInterval(() => {\n for (let i = 0; i < this.pins.length; i++) { \n this.board.analogRead(this.pins[i], (value) => {\n this.therms.push(value);\n });\n }\n }, 100);\n }", "set PreserveSampleRate(value) {}", "function handleHeartRateNotifications(event) {\n // In Chrome 50+, a DataView is returned instead of an ArrayBuffer.\n let value = event.target.value;\n value = value.buffer ? value : new DataView(value);\n let id = event.target.service.device.id;\n let timestamp = new Date().getTime();\n let flags = value.getUint8(0);\n let rate16Bits = flags & 0x1;\n let result = {};\n let index = 1;\n if (rate16Bits) {\n result.heartRate = value.getUint16(index, /*littleEndian=*/true);\n index += 2;\n } else {\n result.heartRate = value.getUint8(index);\n index += 1;\n }\n\n heartRateText.innerHTML = 'HR: ' + result.heartRate + ' bpm';\n heartRateValues.push(result.heartRate);\n\n if (result.heartRate > maxHRVal) {\n maxHRVal = result.heartRate;\n }\n if (result.heartRate < minHRVal) {\n minHRVal = result.heartRate;\n }\n let heartRateRange = maxHRVal - minHRVal;\n var heartRatePlotValues = heartRateValues.map(function(element) {\n return (element - minHRVal)/heartRateRange;\n });\n\n\n if (heartRateValues.length > 45) {\n heartRateValues.shift();\n }\n\n drawWaves(heartRatePlotValues, heartRateCanvas, 1, 60, 70);\n}", "function calculateDistance1(rssi) {\n return Math.pow(10, (4 - rssi)/20);\n}", "set OverrideSampleRate(value) {}", "updateFrequency() {\n const freq = this.channel.frequencyHz;\n const block = this.channel.block;\n const fnum = this.channel.fnumber;\n // key scaling (page 29 YM2608J translated)\n const f11 = fnum.bit(10), f10 = fnum.bit(9), f9 = fnum.bit(8), f8 = fnum.bit(7);\n const n4 = f11;\n const n3 = f11 & (f10 | f9 | f8) | !f11 & f10 & f9 & f8;\n const division = n4 << 1 | n3;\n\n // YM2608 page 26\n if (this.freqMultiple === 0) {\n this.frequency = freq / 2;\n } else {\n this.frequency = freq * this.freqMultiple;\n }\n\n this.keyScalingNote = block << 2 | division;\n\n const FD = this.freqDetune & 3;\n const detune = DETUNE_TABLE[this.keyScalingNote][FD] * MEGADRIVE_FREQUENCY / 8000000;\n if (this.freqDetune & 4) {\n this.frequency -= detune;\n } else {\n this.frequency += detune;\n }\n }", "update_sample(state, { sampleId, data }) {\n let index = -1;\n\n if (sampleId) {\n index = state.samples.findIndex((sample) => sample.id === sampleId);\n }\n\n // For new samples we depend on an internal timestamp\n if (index === -1) {\n index = state.samples.findIndex(\n (sample) => sample.creationstamp === data.creationstamp\n );\n // state.samples[index].stored = true;\n }\n\n if (index !== -1) {\n state.samples[index].updateValues({ data });\n // state.samples[index].stored = true;\n }\n }", "function updateSampleGrid(){\n binnedSamplePairs = getBinnedSamplePairs();\n previewControl.forceRedraw();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Description for Creates the artifacts for web site, or a deployment slot.
async function deploysWorkflowArtifactsSlot() { const subscriptionId = process.env["APPSERVICE_SUBSCRIPTION_ID"] || "34adfa4f-cedf-4dc0-ba29-b6d1a69ab345"; const resourceGroupName = process.env["APPSERVICE_RESOURCE_GROUP"] || "testrg123"; const name = "testsite2"; const slot = "testsSlot"; const workflowArtifacts = { appSettings: { eventHub_connectionString: "Endpoint=sb://example.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=EXAMPLE1a2b3c4d5e6fEXAMPLE=", }, files: { connectionsJson: { managedApiConnections: {}, serviceProviderConnections: { eventHub: { displayName: "example1", parameterValues: { connectionString: "@appsetting('eventHub_connectionString')", }, serviceProvider: { id: "/serviceProviders/eventHub" }, }, }, }, "test1/workflowJson": { definition: { $schema: "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", actions: {}, contentVersion: "1.0.0.0", outputs: {}, triggers: { When_events_are_available_in_Event_hub: { type: "ServiceProvider", inputs: { parameters: { eventHubName: "test123" }, serviceProviderConfiguration: { operationId: "receiveEvents", connectionName: "eventHub", serviceProviderId: "/serviceProviders/eventHub", }, }, splitOn: "@triggerOutputs()?['body']", }, }, }, kind: "Stateful", }, }, }; const options = { workflowArtifacts, }; const credential = new DefaultAzureCredential(); const client = new WebSiteManagementClient(credential, subscriptionId); const result = await client.webApps.deployWorkflowArtifactsSlot( resourceGroupName, name, slot, options ); console.log(result); }
[ "createSiteScript(title, description, content) {\n return SiteScriptsCloneFactory(this, `CreateSiteScript(Title=@title,Description=@desc)?@title='${encodePath(title)}'&@desc='${encodePath(description)}'`)\n .run(content);\n }", "function createDeployment_() {\r\n progress = cli.progress('Creating VM');\r\n utils.doServiceManagementOperation(channel, 'createDeployment', dnsPrefix, dnsPrefix,\r\n role, deployOptions, function(error, response) {\r\n progress.end();\r\n if (!error) {\r\n logger.info('OK');\r\n } else {\r\n cmdCallback(error);\r\n }\r\n });\r\n }", "createSiteDesign(creationInfo) {\n return SiteDesignsCloneFactory(this, \"CreateSiteDesign\").run({ info: creationInfo });\n }", "function deployApplication(envName, shouldDeploy, cb){\n if(shouldDeploy){\n mess.warning(\"EB deployment can take time - will timeout after 30 minutes if incomplete\");\n mess.load(\"Deploying release branch to EB Environment: \" + envName);\n perf.start(\"EB Deploy\");\n eb.deploy(envName, (success) => {\n mess.stopLoad(true);\n perf.end(\"EB Deploy\");\n if(success){\n mess.success(\"Finished deploying to elastic beanstalk!!\");\n return cb(true);\n }else{\n mess.error(\"Failed to deploy to elastic beanstalk --OR-- timed out\");\n return cb(false);\n }\n })\n }else{\n mess.load(\"Simulating EB deployment process - 2 secs\")\n setTimeout(() => {\n mess.stopLoad(true);\n mess.success(\"Successfully simulated eb deployment\");\n return cb(true);\n }, 2000);\n }\n}", "async add(Title, Url, Description = \"\", WebTemplate = \"STS\", Language = 1033, UseSamePermissionsAsParentSite = true) {\n const postBody = request_builders_body({\n \"parameters\": {\n Description,\n Language,\n Title,\n Url,\n UseSamePermissionsAsParentSite,\n WebTemplate,\n },\n });\n const data = await spPost(Webs(this, \"add\"), postBody);\n return {\n data,\n web: Web([this, odataUrlFrom(data).replace(/_api\\/web\\/?/i, \"\")]),\n };\n }", "function deployDirectory() {\n console.log(chalk.bold('Deploying to BitBucket'));\n _command('npm run deploy-demo', (result) => {\n console.log(chalk.bold('Deployed!'));\n console.log('Site will be visible on ' + chalk.cyan(opts.demoUrl) + ' shortly.');\n\n done();\n });\n }", "async function deployIBM(params, func, funcFirstUpperCase, testName) {\n\treturn new Promise(async (resolve, reject) => {\n\n\t\tlet start = now();\n\n\t\tcurrentLogStatusIBM += '<h5>IBM Cloud (sequential deployment)</h5>';\n\t\tcurrentLogStatusIBM += '<ul stlye=\"list-style-position: outside\">';\n\t\tcurrentLogStatusIBMEnd += '</ul>';\n\t\trunningStatusIBM = true;\n\n\t\tif(params.node == 'true') {\n\t\t\tawait deployFunction(constants.IBM, constants.NODE, func, 'node_' + func, 'node_' + func, '', 'nodejs:10', '', '', '/ibm/src/node/' + func + '/', 'Node.js', ' ', 'json', params.ram, params.timeout);\n\t\t}\n\t\tif(params.python == 'true') {\n\t\t\tawait deployFunction(constants.IBM, constants.PYTHON, func, 'python_' + func, 'python_' + func, '', 'python:3.7', '', '', '/ibm/src/python/' + func + '/main.py', 'Python', ' ', 'json', params.ram, params.timeout);\n\t\t}\n\t\tif(params.go == 'true') {\n\t\t\tawait deployFunction(constants.IBM, constants.GO, func, 'go_' + func, 'go_' + func, '', 'go:1.11', '', '', '/ibm/src/go/' + func + '/' + func + '.go', 'Go', ' ', 'json', params.ram, params.timeout);\n\t\t}\n\t\tif(params.dotnet == 'true') {\n\t\t\tawait deployFunction(constants.IBM, constants.DOTNET, func, 'dotnet_' + func, 'dotnet_' + func, '', 'dotnet:2.2', '', '', '/ibm/src/dotnet/' + funcFirstUpperCase + '/', '.NET', ' --main ' + funcFirstUpperCase + '::' + funcFirstUpperCase + '.' + funcFirstUpperCase + 'Dotnet::Main', 'json', params.ram, params.timeout)\n\t\t}\n\n\t\tlet end = now();\n\t\tcurrentLogStatusIBM += 'Completed ' + millisToMinutesAndSeconds((end-start).toFixed(3));\n\n\t\trunningStatusIBM = false;\n\t\tresolve();\n\t});\n}", "_createDeployFile() {\n\n if (this.options.generateDeployFile) {\n\n // Write the deploy message to the deploy.txt\n fs.writeFile(`${this.buildPath}/deploy.txt`, this.deployMessage, (error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n this.log(`deploy.txt was unable to be created.`, 'ERROR');\n process.exit(0);\n }\n\n this.log('deploy.txt was created.');\n });\n }\n }", "function deploy(params, cb) {\n params.resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + \"/data_sources/:id/deploy\", params);\n params.method = \"POST\";\n params.data = params.dataSource;\n\n mbaasRequest.admin(params, cb);\n}", "function CreateCraftingRecipe (section, result, ingredients, table, name, entity) {\n var crafting_item = $.CreatePanel(\"Panel\", section, result)\n crafting_item.section_name = name\n crafting_item.itemname = result\n crafting_item.ingredients = ingredients\n crafting_item.table = table\n crafting_item.entity = entity\n crafting_item.BLoadLayout(\"file://{resources}/layout/custom_game/crafting/crafting_recipe.xml\", false, false);\n}", "function createPackage() {\n\t\tDataSvc.createPackage(vm.packageName, vm.quotesAdded).then(function() {\n\t\t\t$scope.home.closeForm();\n\t\t}, function(err) {\n\t\t\tconsole.log('error creating package:', err);\n\t\t});\n\t}", "setDescription(description) {\n this.description = description;\n }", "function createApi(opts){\n var deferred = Q.defer(),\n params = {\n name : opts.name,\n description : opts.description\n };\n\n apigateway.createRestApi(params, function(err, data) {\n if (err) deferred.reject(err);\n else deferred.resolve(data);\n });\n\n return deferred.promise;\n }", "function createMeta() {\n\t\ttry {\n\t\t\tvar manifestData = chrome.runtime.getManifest();\n\t\t\tvar obj = {\n\t\t\t\tversion: manifestData.version, // set in manifest\n\t\t\t\tinstall: {\n\t\t\t\t\tdate: moment().format(),\n\t\t\t\t\tprompts: 0 // number prompts given to user\n\t\t\t\t},\n\t\t\t\tuserLoggedIn: false,\n\t\t\t\tuserOnline: navigator.onLine,\n\t\t\t\tserver: {\n\t\t\t\t\tlastChecked: 0,\n\t\t\t\t\tonline: 1,\n\t\t\t\t\tresponseMillis: -1\n\t\t\t\t},\n\t\t\t\tcurrentAPI: \"production\", // default to production on new installation\n\t\t\t\tapi: T.options.production.api,\n\t\t\t\twebsite: T.options.production.website,\n\t\t\t\tbrowser: Environment.getBrowserName(),\n\t\t\t\tlocation: {}\n\t\t\t};\n\n\t\t\treturn obj;\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}", "function createManifest () {\n fs.writeFile(manifestPath + 'manifest.json', JSON.stringify(manifest))\n}", "function createGalleryWithDescription(body) {\n\t\t\tjQuery.ajax({\n\t\t\t\turl: options.descriptionFile,\n\t\t\t\tdataType: 'json',\n\t\t\t\terror: function () {\n\t\t\t\t\t// As a failback, create simple gallery\n\t\t\t\t\tcreateSimpleGallery(body);\n\t\t\t\t},\n\t\t\t\tsuccess: function(description) {\n\t\t\t\t\t// Check if description has a list of items\n\t\t\t\t\tif(!description.items) {\n\t\t\t\t\t\tdescription = buildDescription(description);\n\t\t\t\t\t}\n\t\t\t\t\trenderGallery(body, description);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function Deployment(props) {\n return __assign({ Type: 'AWS::ApiGateway::Deployment' }, props);\n }", "function showDescriptionTemplate(body) {\n\t\t\tvar description = buildDescription();\n\t\t\tdescription.title = '';\n\t\t\tdescription.subtitle = '';\n\t\t\tdescription.items.forEach(function(item) {\n\t\t\t\titem.title = '';\n\t\t\t\titem.description = '';\n\t\t\t});\n\n\t\t\tcleanUpPage(body);\n\t\t\tvar header = createAddElement('p', body);\n\t\t\theader.innerHTML = 'This is a template for ' + options.descriptionFile + ' file. <a href=\"?\">Go to gallery content</a>';\n\t\t\tvar textArea = createAddElement('textarea', body, {\n\t\t\t\trows: 30,\n\t\t\t\tcols: 90\n\t\t\t});\n\t\t\ttextArea.value = JSON.stringify(description, null, 4);\n\t\t}", "function deploy(cb) {\n console.log(\"deploying with the role name 'assigner' in metadata ...\");\n var req = {\n fcn: \"init\",\n args: [],\n metadata: \"assigner\"\n };\n if (networkMode) {\n req.chaincodePath = \"github.com/asset_management_with_roles/\";\n } else {\n req.chaincodeName = \"asset_management_with_roles\";\n }\n var tx = admin.deploy(req);\n tx.on('submitted', function (results) {\n console.log(\"deploy submitted: %j\", results);\n });\n tx.on('complete', function (results) {\n console.log(\"deploy complete: %j\", results);\n chaincodeID = results.chaincodeID;\n return assign(cb);\n });\n tx.on('error', function (err) {\n console.log(\"deploy error: %j\", err.toString());\n return cb(err);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that checks if all questions are answered
function allAreAnswered(questions){ if(questions.status===1){ return true } }
[ "function isAnswersCountValidOnSubmit() {\n var countValues = 0;\n for( var i=0; i < $scope.form.masterAnswers.length; i++ ) {\n if ($scope.form.masterAnswers[i].checked == true) {\n countValues++;\n }\n }\n if (countValues < 2) {\n return false;\n }else {\n return true;\n }\n }", "function allQuestionsAnswered() {\n clearTimeout(countdown);\n}", "function q1to5(){\n alert('Welcome! Question after this would require only (y/n) or (yes/no) as response ');\n //Show prompt until user enter correct answers ;Q1-Q5\n for(i; i<5;i++)\n {\n do{\n response = prompt(questionArray[i]);\n response = response.toLowerCase();\n //if corrent input isn't inserted then shows user a alert\n if(response!=='y'&&response!=='n'&&response!=='yes'&&response!=='no')\n {\n alert('Plese enter either (y/n) or (yes/no) as response');\n }\n }while(response!=='y'&&response!=='n'&&response!=='yes'&&response!=='no');\n //loggin user's response\n console.log('For'+ questionArray[i] + ' User responded: ' + response);\n // to check the reponses from user if submitted response is true or false\n if(i%2===0)\n {\n if(response==='y'||response==='yes')\n {\n alert('Sorry! Incorrect!!');\n }\n else\n {\n alert('Correct');\n correctCount++;\n //tracking the quetions which were correct\n correctAnswer.push(i+1);\n }//end of inner if-else loop\n }\n else\n {\n if(response==='y'||response==='yes')\n {\n alert('Correct!');\n correctCount++;\n }\n else\n {\n alert('Incorrect!!');\n }//end of if-else iner looop\n }//end of if-else outter loop\n }// end of for loop\n//start of 6th Question\n}", "function isAnswer() {\r\n\tif (!answer.branches)\r\n\t\treturn false;\r\n\t\t\r\n\tvar i = 0;\r\n\tfor (i in answer.branches) {\r\n\t\tvar branch = answer.branches[i];\r\n\t\tbranch.any = true;\r\n\t\tif (branch.words) {\r\n\t\t\tvar nb = compareSet(branch,userInput.list);\r\n\t\t\t/* console.log(\"branch: \" + branch.words,\r\n\t\t\t\t\t\t\"input: \" + userInput.list,\r\n\t\t\t\t\t\t\"matched: \" + nb); */\r\n\t\t\tif(nb >= 0.5) {\r\n\t\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!answer.wait){\r\n\t\tanswer = {};\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}", "moreQuestionsAvailable() {\n\treturn (this.progress.qAnswered < this.progress.qTotal);\n }", "function checkQuestionnaires(game) {\n var names = [];\n var positions;\n var questions;\n for (var questionnaireName in game.questionnaires) {\n names.push(questionnaireName);\n // Positions array must exist and have only numiercal entries\n if (game.questionnaires[questionnaireName].positions) {\n positions = game.questionnaires[questionnaireName].positions;\n if (typeof positions === \"object\") {\n // Go through all postions\n if (positions.length) {\n for (var p = 0; p < positions.length; p++) {\n if (typeof positions[p] !== \"number\") {\n errors.push(\"Questionnaire \" + questionnaireName + \": \" + \"A position can only be a numerical value. \");\n break;\n }\n }\n } else {\n errors.push(\"Questionnaire \" + questionnaireName + \": \" + \"At least one position must be defined\");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The positions parameter must be an array. \");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"Every questionnaire must define the positions array. \");\n }\n // A questionnaire must define a questions array\n if (game.questionnaires[questionnaireName].questions) {\n questions = game.questionnaires[questionnaireName].questions;\n if (typeof questions === \"object\") {\n // A questionnaire must define at least one question\n if (questions.length) {\n // Go through all questions\n var answer;\n var questionName;\n var questionText;\n for (var q = 0; q < questions.length; q++) {\n answer = questions[q].answer;\n // Answer attribute must be \"string\", \"number\" or array\n if (answer === \"string\" || answer === \"number\" || \n typeof answer === \"object\") {\n if (typeof answer === \"object\") {\n if (!answer.length) {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"A predefined answer must give at least one option:\");\n }\n }\n }\n else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+'answer must be \"string\", \"number\" or an array');\n }\n // The attribute questionName must be a string\n questionName = questions[q].questionName;\n if (typeof questionName !== \"string\") {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questionName must be of type String. \");\n }\n // The attribute questionText must be a string\n questionText = questions[q].questionText;\n if (typeof questionText !== \"string\") {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questionText must be of type String. \");\n }\n }\n }\n else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\n \"A questionnaire must define at least one question. The questionnare object must be an array.\");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"The questions parameter must be an array. \");\n }\n } else {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+\"A questionnaire must define the questions array. \");\n }\n // end for\n }\n names.sort();\n for (var n = 0; n < names.length; n++) {\n if (names[n] === names[n + 1]) {\n errors.push(\"Questionnaire \"+questionnaireName+\": \"+ \"is not unique. All questionnaire names must be unique\");\n }\n }\n }", "function review () { \n\tfor (var i = 0; i < questions.length; i++) {\n\t\tvar userChoice = $(\"input[name = 'question-\" + i +\"']:checked\");\n\t\tif (userChoice.val() == questions[i].correctAnswer) {\n\t\t\tcorrectAnswers++; \n\n\t\t\t} else {\n\t\t\t\tincorrectAnswers++;\n\t\t\t\t\n\t\t}\n\t}\n\t$(\"#correctAnswers\").append(\" \" + correctAnswers);\n\t$(\"#incorrectAnswers\").append(\" \" + incorrectAnswers); \n}", "function validateInstructionChecks() {\n \n hideElements(); \n instructionChecks = $('#instr').serializeArray();\n\n var ok = true;\n for (var i = 0; i < instructionChecks.length; i++) {\n // check for incorrect responses\n if(instructionChecks[i].value != \"correct\") {\n alert('At least one answer was incorrect; please read the instructions and try again.');\n ok = false;\n break;\n }\n // check for empty answers \n if (instructionChecks[i].value === \"\") {\n alert('Please fill out all fields.');\n ok = false;\n break; \n }\n }\n\n // where this is the number of questions in the instruction check\n if (instructionChecks.length != 3) {\n alert('You have not answered all of the questions; please try again.');\n ok = false;\n }\n\n // goes to next section\n if (!ok) {\n showSecondInstructions(); \n } else {\n hideElements();\n getReady(); \n }\n}", "function checkProvidedAnswer(question, answer){\n var checked = false\n if(answer.answerId == question.providedAnswer){\n checked = true\n }\n return checked\n }", "function isValidWhoQuesion(answer, verb) {\n var ans = answer.split(' ');\n count = 0;\n for (var a of ans) {\n if (a == verb) {\n count += 1;\n }\n if (count > 1) {\n return false;\n }\n }\n return true;\n}", "function f() {\n if (validateAll([\"q1\",\"q2\",\"q3\",\"q4\",\"q5\",\"q6\"]) === true) {\n x= Math.ceil(Math.random() * 3);\n newPage = \"euclid\"+ x +\".html\";\n window.location = newPage;\n }\n else {\n alert(\"Please answer every question.\");\n }\n}", "function validateAnswer(){\n let userChoice = this.value\n let correctAnswer = questions[questionIndex].answer\n if (userChoice !== correctAnswer){\n timeRemaining -=10\n }\n questionIndex++\n generateQuestion();\n}", "function checkAllInputs() {}", "function validateUserAnswer(planet, id) {\n const position = planetToNumber(planet); // find planet position in array\n const userAnswer = $(\"input[name=user-answers]:checked\").parent('label').text().trim(); // find what answer the user picked\n let correctAnswer = ''; // placeholder for correct answer\n if (STORE.questionNumber === 0) {\n return true;\n }\n else {\n for (let i = 0; i <= 2; i++) { // loop through array until question is found\n currId = STORE.planets[position][planet][i].id; // current id to look at\n if (currId === id) { // if it matches passed id\n correctAnswer = STORE.planets[position][planet][i].correct; // set correct answer\n }\n }\n\n if (userAnswer === correctAnswer) { // if user answer is right return true, if it is not return false\n return true;\n }\n else\n return false;\n }\n\n}", "function evaluate(userAnswer)\n{\n let correctAnswer = QUIZQUESTIONS[start].correct;\n\n if (userAnswer == correctAnswer)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "function isBlank() {\n // Gather the answer containers from the quiz\n const answerContainers = quizContainer.querySelectorAll('.answers');\n\n // Find the selected answer\n const answerContainer = answerContainers[currentSlide];\n const selector = 'input[name=question'+currentSlide+']:checked';\n const userAnswer = (answerContainer.querySelector(selector) || {}).value;\n\n if(userAnswer === undefined) {\n return true;\n } else {\n return false;\n }\n}", "function setAvailableQuestions(){\n\tconst totalQuestions=quiz.length;\n\tfor(let i=0;i<totalQuestions; i++){\n\t\tavailableQuestions.push(quiz[i])\n\t}\n}", "function promptAnswer() {\n r = printRandQuestion();\n let answer = prompt('Whats the correct answer?');\n\n // Check if player wants to exit\n if (answer !== 'exit') {\n\n // Check answer and display result plus total score, then start again\n questions[r].checkAnswer(parseInt(answer));\n promptAnswer();\n\n }\n }", "function questionPresent(uid,id){\n let found = false\n questions.forEach(function (question){\n if (question.id === id && question.uid === uid){\n found = true;\n }\n })\n return found;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads light properties from the light to the shader Transforms light position according to provided matrix or according to the identity matrix if no matrix is provided. Light properties are expected to appear on same object as light locations
function setLight(light, matrix) { var mv; if (arguments.length == 1) mv = mat4(); else mv = matrix; gl.uniform3fv(light.diffuseLoc, light.diffuse); gl.uniform3fv(light.ambientLoc, light.ambient); gl.uniform3fv(light.specularLoc, light.specular); gl.uniform4fv(light.positionLoc, mult(mv,light.position)); //EXERCISE 2: send attenuation coefficients to shader gl.uniform3fv(light.attenuationLoc, light.attenuation); }
[ "uploadNormalMatrixToShader() {\r\n mat3.fromMat4(this.nMatrix,this.mvMatrix);\r\n mat3.transpose(this.nMatrix,this.nMatrix);\r\n mat3.invert(this.nMatrix,this.nMatrix);\r\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, this.nMatrix);\r\n }", "function setMaterial(mat)\n{\n gl.uniform3fv(material.diffuseLoc, mat.diffuse);\n gl.uniform3fv(material.specularLoc, mat.specular);\n gl.uniform3fv(material.ambientLoc, mat.diffuse);\n gl.uniform1f(material.shininessLoc, mat.shininess);\n}", "function uploadNormalMatrixToShader(){\n mat3.fromMat4(nMatrix,mvMatrix);\n mat3.transpose(nMatrix,nMatrix);\n mat3.invert(nMatrix,nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadModelViewMatrixToShader() \n{\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function setupLight(){\r\n\r\n\t//an ambient light for \"basic\" illumination\r\n\tambientLight = new THREE.AmbientLight( 0x444444 );\r\n\tscene.add( ambientLight );\r\n\r\n\t//a directional light for some nicer additional illumination\r\n\tdirectionalLight = new THREE.DirectionalLight( 0xffeedd );\r\n\tdirectionalLight.position.set( 0, 0, 1 ).normalize();\r\n\tscene.add( directionalLight );\r\n\r\n\t//set up the point light but without adding it to the scene\r\n\tpointlight = new THREE.PointLight( 0x444444, 2, 30 );\r\n\tpointLight.position.set( 0, 0, 37 );\r\n\r\n}", "function setUpAttributesAndUniforms() {\n // finds the index of the variables in the program\n ctx.aVertexPositionId = gl.getAttribLocation(ctx.shaderProgram, \"aVertexPosition\");\n ctx.aVertexColorId = gl.getAttribLocation(ctx.shaderProgram, \"aVertexColor\");\n ctx.aVertexNormalId = gl.getAttribLocation(ctx.shaderProgram, \"aVertexNormal\");\n\n ctx.uModelMatId = gl.getUniformLocation(ctx.shaderProgram, \"uModelMat\");\n ctx.uNormalMatrixId = gl.getUniformLocation(ctx.shaderProgram, \"uNormalMatrix\");\n ctx.uProjectionMatId = gl.getUniformLocation(ctx.shaderProgram, \"uProjectionMat\");\n\n ctx.uEnableLightingId = gl.getUniformLocation(ctx.shaderProgram, \"uEnableLighting\");\n ctx.uLightPositionId = gl.getUniformLocation(ctx.shaderProgram, \"uLightPosition\");\n ctx.uLightColorId = gl.getUniformLocation(ctx.shaderProgram, \"uLightColor\");\n}", "applyColor(_materialComponent) {\n let colorPerPosition = [];\n for (let i = 0; i < this.vertexCount; i++) {\n colorPerPosition.push(_materialComponent.Material.Color.X, _materialComponent.Material.Color.Y, _materialComponent.Material.Color.Z);\n }\n WebEngine.gl2.bufferData(WebEngine.gl2.ARRAY_BUFFER, new Uint8Array(colorPerPosition), WebEngine.gl2.STATIC_DRAW);\n }", "function setMV() {\r\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix) );\r\n normalMatrix = inverseTranspose(modelViewMatrix) ;\r\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix) );\r\n}", "uploadUniforms() {\n const gl = EngineToolbox.getGLContext();\n if (!this.shaderProgram) {\n return;\n }\n\n // pass uniforms to shader only if defined\n gl.useProgram(this.shaderProgram);\n this.uniforms.modelViewMatrix.value &&\n uniformMatrix4fv(this.uniforms.modelViewMatrix);\n this.uniforms.projectionMatrix.value &&\n uniformMatrix4fv(this.uniforms.projectionMatrix);\n this.uniforms.normalMatrix.value &&\n uniformMatrix4fv(this.uniforms.normalMatrix);\n this.uniforms.directLightDirection.value &&\n uniform3fv(this.uniforms.directLightDirection);\n this.uniforms.directLightColor.value &&\n uniform3fv(this.uniforms.directLightColor);\n this.uniforms.directLightValue.value &&\n uniform1fv(this.uniforms.directLightValue);\n this.uniforms.ambientLightColor.value &&\n uniform3fv(this.uniforms.ambientLightColor);\n this.uniforms.ambientLightValue.value &&\n uniform1fv(this.uniforms.ambientLightValue);\n this.uniforms.useVertexColor.value &&\n uniform1iv(this.uniforms.useVertexColor);\n this.uniforms.color0Sampler.value &&\n uniform1iv(this.uniforms.color0Sampler);\n this.uniforms.color1Sampler.value &&\n uniform1iv(this.uniforms.color1Sampler);\n this.uniforms.normal0Sampler.value &&\n uniform1iv(this.uniforms.normal0Sampler);\n this.uniforms.useColor0.value && uniform1iv(this.uniforms.useColor0);\n this.uniforms.useColor1.value && uniform1iv(this.uniforms.useColor1);\n this.uniforms.useNormal0.value && uniform1iv(this.uniforms.useNormal0);\n this.uniforms.useEmission.value && uniform1iv(this.uniforms.useEmission);\n this.uniforms.mapOffsetX.value && uniform1fv(this.uniforms.mapOffsetX);\n this.uniforms.mapOffsetY.value && uniform1fv(this.uniforms.mapOffsetY);\n this.uniforms.mapTilingX.value && uniform1fv(this.uniforms.mapTilingX);\n this.uniforms.mapTilingY.value && uniform1fv(this.uniforms.mapTilingY);\n }", "function buildTraficLights(scene) {\n var zCrossRoad = -500;\n widthRoad = 60;\n\n\n var loader = new THREE.GLTFLoader();\n loader.load('models/TrafficLight/scene.gltf', function(gltf) {\n light = gltf.scene.children[0];\n light.scale.set(0.2, 0.1, 0.1);\n light.position.x = widthRoad/2;\n light.position.y = 25;\n light.position.z = zCrossRoad + widthRoad/2 + 10;\n //light.rotation.z -= Math.PI;\n scene.add(light);\n });\n\n /*loader.load('models/TrafficLight/scene.gltf', function(gltf) {\n light = gltf.scene.children[0];\n light.scale.set(0.2, 0.1, 0.1);\n light.position.x = widthRoad/2 + 10;\n light.position.y = 25;\n light.position.z = zCrossRoad - widthRoad;\n light.rotation.z += Math.PI/2;\n scene.add(light);\n });\n\n loader.load('models/TrafficLight/scene.gltf', function(gltf) {\n light = gltf.scene.children[0];\n light.scale.set(0.2, 0.1, 0.1);\n light.position.x = - widthRoad/2 - 10;\n light.position.y = 25;\n light.position.z = zCrossRoad + widthRoad/2;\n light.rotation.z -= Math.PI/2;\n scene.add(light);\n });\n\n loader.load('models/TrafficLight/scene.gltf', function(gltf) {\n light = gltf.scene.children[0];\n light.scale.set(0.2, 0.1, 0.1);\n light.position.x = - widthRoad;\n light.position.y = 25;\n light.position.z = zCrossRoad - widthRoad/2 - 10;\n light.rotation.z += Math.PI;\n scene.add(light);\n });*/\n}", "function StandardMaterial(name,scene){var _this=_super.call(this,name,scene)||this;/**\n * The color of the material lit by the environmental background lighting.\n * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example\n */_this.ambientColor=new BABYLON.Color3(0,0,0);/**\n * The basic color of the material as viewed under a light.\n */_this.diffuseColor=new BABYLON.Color3(1,1,1);/**\n * Define how the color and intensity of the highlight given by the light in the material.\n */_this.specularColor=new BABYLON.Color3(1,1,1);/**\n * Define the color of the material as if self lit.\n * This will be mixed in the final result even in the absence of light.\n */_this.emissiveColor=new BABYLON.Color3(0,0,0);/**\n * Defines how sharp are the highlights in the material.\n * The bigger the value the sharper giving a more glossy feeling to the result.\n * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.\n */_this.specularPower=64;_this._useAlphaFromDiffuseTexture=false;_this._useEmissiveAsIllumination=false;_this._linkEmissiveWithDiffuse=false;_this._useSpecularOverAlpha=false;_this._useReflectionOverAlpha=false;_this._disableLighting=false;_this._useObjectSpaceNormalMap=false;_this._useParallax=false;_this._useParallaxOcclusion=false;/**\n * Apply a scaling factor that determine which \"depth\" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.\n */_this.parallaxScaleBias=0.05;_this._roughness=0;/**\n * In case of refraction, define the value of the indice of refraction.\n * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions\n */_this.indexOfRefraction=0.98;/**\n * Invert the refraction texture alongside the y axis.\n * It can be usefull with procedural textures or probe for instance.\n * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions\n */_this.invertRefractionY=true;/**\n * Defines the alpha limits in alpha test mode.\n */_this.alphaCutOff=0.4;_this._useLightmapAsShadowmap=false;_this._useReflectionFresnelFromSpecular=false;_this._useGlossinessFromSpecularMapAlpha=false;_this._maxSimultaneousLights=4;_this._invertNormalMapX=false;_this._invertNormalMapY=false;_this._twoSidedLighting=false;_this._renderTargets=new BABYLON.SmartArray(16);_this._worldViewProjectionMatrix=BABYLON.Matrix.Zero();_this._globalAmbientColor=new BABYLON.Color3(0,0,0);// Setup the default processing configuration to the scene.\n_this._attachImageProcessingConfiguration(null);_this.getRenderTargetTextures=function(){_this._renderTargets.reset();if(StandardMaterial.ReflectionTextureEnabled&&_this._reflectionTexture&&_this._reflectionTexture.isRenderTarget){_this._renderTargets.push(_this._reflectionTexture);}if(StandardMaterial.RefractionTextureEnabled&&_this._refractionTexture&&_this._refractionTexture.isRenderTarget){_this._renderTargets.push(_this._refractionTexture);}return _this._renderTargets;};return _this;}", "function lightingSetUp(){\n\n keyLight = new THREE.DirectionalLight(0xFFFFFF, 1.0);\n keyLight.position.set(3, 10, 3).normalize();\n keyLight.name = \"Light1\";\n\n fillLight = new THREE.DirectionalLight(0xFFFFFF, 1.2);\n fillLight.position.set(0, -5, -1).normalize();\n fillLight.name = \"Light2\";\n\n backLight = new THREE.DirectionalLight(0xFFFFFF, 0.5);\n backLight.position.set(-10, 0, 0).normalize();\n backLight.name = \"Light3\";\n\n scene.add(keyLight);\n scene.add(fillLight);\n scene.add(backLight);\n}", "function updateLight(properties) {\n print(\"Lifx: Updating monument light color now\");\n\n // Configurations and custom headers to send to the API\n options.uri = 'https://api.lifx.com/v1beta1/lights/' + id + '/state';\n options.method = 'PUT';\n options.body = JSON.stringify(properties);\n\n // PUT http request to update the hue color\n request(options, function(error, response, body) {\n if(response.statusCode.toString().charAt(0) != 2)\n print(\"Lifx Update Monument Light Error: \" + JSON.stringify(error,null,2));\n }); // end of request\n}", "function PBRMaterial(name,scene){var _this=_super.call(this,name,scene)||this;/**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */_this.directIntensity=1.0;/**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */_this.emissiveIntensity=1.0;/**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the refelction for shiny ones.\n */_this.environmentIntensity=1.0;/**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */_this.specularIntensity=1.0;/**\n * Debug Control allowing disabling the bump map on this material.\n */_this.disableBumpMap=false;/**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */_this.ambientTextureStrength=1.0;/**\n * Defines how much the AO map is occluding the analytical lights (point spot...).\n * 1 means it completely occludes it\n * 0 mean it has no impact\n */_this.ambientTextureImpactOnAnalyticalLights=PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;/**\n * The color of a material in ambient lighting.\n */_this.ambientColor=new BABYLON.Color3(0,0,0);/**\n * AKA Diffuse Color in other nomenclature.\n */_this.albedoColor=new BABYLON.Color3(1,1,1);/**\n * AKA Specular Color in other nomenclature.\n */_this.reflectivityColor=new BABYLON.Color3(1,1,1);/**\n * The color reflected from the material.\n */_this.reflectionColor=new BABYLON.Color3(1.0,1.0,1.0);/**\n * The color emitted from the material.\n */_this.emissiveColor=new BABYLON.Color3(0,0,0);/**\n * AKA Glossiness in other nomenclature.\n */_this.microSurface=1.0;/**\n * source material index of refraction (IOR)' / 'destination material IOR.\n */_this.indexOfRefraction=0.66;/**\n * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.\n */_this.invertRefractionY=false;/**\n * This parameters will make the material used its opacity to control how much it is refracting aginst not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */_this.linkRefractionWithTransparency=false;/**\n * If true, the light map contains occlusion information instead of lighting info.\n */_this.useLightmapAsShadowmap=false;/**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */_this.useAlphaFromAlbedoTexture=false;/**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */_this.forceAlphaTest=false;/**\n * Defines the alpha limits in alpha test mode.\n */_this.alphaCutOff=0.4;/**\n * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.\n */_this.useSpecularOverAlpha=true;/**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */_this.useMicroSurfaceFromReflectivityMapAlpha=false;/**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */_this.useRoughnessFromMetallicTextureAlpha=true;/**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */_this.useRoughnessFromMetallicTextureGreen=false;/**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */_this.useMetallnessFromMetallicTextureBlue=false;/**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */_this.useAmbientOcclusionFromMetallicTextureRed=false;/**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */_this.useAmbientInGrayScale=false;/**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */_this.useAutoMicroSurfaceFromReflectivityMap=false;/**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).\n * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.\n */_this.useRadianceOverAlpha=true;/**\n * Allows using an object space normal map (instead of tangent space).\n */_this.useObjectSpaceNormalMap=false;/**\n * Allows using the bump map in parallax mode.\n */_this.useParallax=false;/**\n * Allows using the bump map in parallax occlusion mode.\n */_this.useParallaxOcclusion=false;/**\n * Controls the scale bias of the parallax mode.\n */_this.parallaxScaleBias=0.05;/**\n * If sets to true, disables all the lights affecting the material.\n */_this.disableLighting=false;/**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */_this.forceIrradianceInFragment=false;/**\n * Number of Simultaneous lights allowed on the material.\n */_this.maxSimultaneousLights=4;/**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */_this.invertNormalMapX=false;/**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */_this.invertNormalMapY=false;/**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */_this.twoSidedLighting=false;/**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */_this.useAlphaFresnel=false;/**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */_this.useLinearAlphaFresnel=false;/**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part.\n */_this.environmentBRDFTexture=null;/**\n * Force normal to face away from face.\n */_this.forceNormalForward=false;/**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */_this.enableSpecularAntiAliasing=false;/**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */_this.useHorizonOcclusion=true;/**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */_this.useRadianceOcclusion=true;/**\n * If set to true, no lighting calculations will be applied.\n */_this.unlit=false;_this._environmentBRDFTexture=BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);return _this;}", "setup() {\n this.material = new THREE.ShaderMaterial({\n uniforms: this.uniforms.uniforms,\n fragmentShader: this.shaders.fragment_shader,\n vertexShader: this.shaders.vertex_shader\n });\n }", "buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }", "function uploadRotateMatrixToShader(rotateMat){\r\n gl.uniformMatrix4fv(gl.getUniformLocation(shaderProgram, \"uRotateMat\"), false, rotateMat);\r\n}", "function computeDiffuse(color, normal, lightDirection) {\n let diffuse = [];\n for (let c = 0; c < 3; c++) {\n diffuse[c] = (color[c] / 255) * (light.color[c] / 255) *\n Math.max(0, vec3.dot(normal, lightDirection));\n }\n return diffuse;\n}", "_readUniformLocationsFromLinkedProgram() {\n const {gl} = this;\n this._uniformSetters = {};\n this._uniformCount = this._getParameter(GL.ACTIVE_UNIFORMS);\n for (let i = 0; i < this._uniformCount; i++) {\n const info = this.gl.getActiveUniform(this.handle, i);\n const {name, isArray} = parseUniformName(info.name);\n const location = gl.getUniformLocation(this.handle, name);\n this._uniformSetters[name] = getUniformSetter(gl, location, info, isArray);\n }\n this._textureIndexCounter = 0;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Function name]f_ProcessJSONData_Main [Description]function to analyse input frame data in order to execute the appropriate processing [inputs]frame : frame to be processed [jQuery]NO
function f_ProcessJSONData_Main(frame){ // log AppID received //f_RADOME_log(frame.AppID); //Check AppID and do what fit with that var id = parseInt(frame.AppID); switch(id) // inspect id found to dispatch the appropriate processing { case APP_ID.LIST: // load JSON data (into 'frame') to update and fill the select '$(he_SelectRADOMECmds)' f_GUI_Update_Select(frame, $(he_SelectRADOMECmds)); break; case APP_ID.VERSION: // load data json to populate the angular model "$scope.versionInfo" f_RADOME_log("load data json to populate the angular model $scope.versionInfo"); f_GUI_Update_Version(frame); break; // if process is "CAN" case APP_ID.CAN1: case APP_ID.CAN2: case APP_ID.CAN3: case APP_ID.CAN4: case APP_ID.CAN5: //Update GUI for the 'gauge' element f_ProcessJSONData_CAN(frame); // TO DO : simulate click on concerned tab menu //$("#menu2").click(); break; case APP_ID.VIDEO: // Update GUI elements concerned // TO DO : simulate click on concerned tab menu //$("#menu3").click(); break; case APP_ID.AUDIO: // Update GUI elements concerned f_GUI_Update_Select(frame, $(he_SelectRADOMEAudio)); // TO DO : simulate click on concerned tab menu //$("#menu4").click(); break; case APP_ID.NAVIG: // Update GUI elements concerned // TO DO : simulate click on concerned tab menu //$("#menu5").click(); f_RADOME_log("load data json to populate the angular model $scope.RADOME_NavigInfo"); f_GUI_Update_Nav(frame); break; case APP_ID.DEMO: // load data json to populate the angular model "$scope.RADOME_DemoInfo" f_RADOME_log("load data json to populate the angular model $scope.RADOME_DemoInfo"); f_GUI_Update_Demo(frame); break; default: // unknown id f_RADOME_log("Unknown APP ID found : " + frame.AppID); break; } }
[ "function f_ProcessJSONData_CAN(frame_can){\n\t//Check AppID and do what fit with that\n\tvar id = parseInt(frame_can.AppID);\n\n\tswitch(id)\n\t{\n\t\tcase APP_ID.CAN1:\n\t\t\t//Update GUI for the 'gauge' element\n\t\t\tgauge.setValue(frame_can.DataValue);\n\t\t\tgauge.draw();\t\n\t\t\tgRADOME_Conf.GUI_BarGraph[0] = frame_can.DataValue;\n\t\t\tf_JSONDraw_Graph_CAN(gRADOME_Conf.GUI_BarGraph);\n\n\t\t\tbreak;\n\n\t\tcase APP_ID.CAN2:\n\t\t\t// Update GUI elements concerned \n\t\t\tgRADOME_Conf.GUI_BarGraph[1] = frame_can.DataValue;\n\t\t\tf_JSONDraw_Graph_CAN(gRADOME_Conf.GUI_BarGraph);\n\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.CAN3:\n\t\t\t// Update GUI elements concerned \n\t\t\tgRADOME_Conf.GUI_BarGraph[2] = frame_can.DataValue;\n\t\t\tf_JSONDraw_Graph_CAN(gRADOME_Conf.GUI_BarGraph);\n\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.CAN4:\n\t\t\t// Update GUI elements concerned \n\t\t\tgRADOME_Conf.GUI_BarGraph[3] = frame_can.DataValue;\n\t\t\tf_JSONDraw_Graph_CAN(gRADOME_Conf.GUI_BarGraph);\n\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.CAN5:\n\t\t\tgRADOME_Conf.GUI_BarGraph[4] = frame_can.DataValue;\n\t\t\tf_JSONDraw_Graph_CAN(gRADOME_Conf.GUI_BarGraph);\n\t\t\tbreak;\t\n\t\n\t\tdefault:\n\t\t\t// unknown id\n\t\t\tf_RADOME_log(\"Unknown APP ID found : \" + frame_can.AppID);\n\t\t\tbreak;\t\n\t}\n}", "function uploadJSON() {\r\n\r\n}", "function mapCaseJsonToUi(data){\n\t//\n\t// This gives me ONE object - The root for test cases\n\t// The step tag is the basis for each step in the Steps data array object.\n\t// \n\tvar items = []; \n\tvar xdata = data['step'];\n\tif (!jQuery.isArray(xdata)) xdata = [xdata]; // convert singleton to array\n\n\n\t//console.log(\"xdata =\" + xdata);\n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html(\"\"); // Start with clean slate\n\titems.push('<table class=\"case_configuration_table table-striped\" id=\"Step_table_display\" width=\"100%\" >');\n\titems.push('<thead>');\n\titems.push('<tr id=\"StepRow\"><th>#</th><th>Driver</th><th>Keyword</th><th>Description</th><th>Arguments</th>\\\n\t\t<th>OnError</th><th>Execute</th><th>Run Mode</th><th>Context</th><th>Impact</th><th>Other</th></tr>');\n\titems.push('</thead>');\n\titems.push('<tbody>');\n\tfor (var s=0; s<Object.keys(xdata).length; s++ ) { // for s in xdata\n\t\tvar oneCaseStep = xdata[s]; // for each step in case\n\t\t//console.log(oneCaseStep['path']);\n\t\tvar showID = parseInt(s)+1;\n\t\titems.push('<tr data-sid=\"'+s+'\"><td>'+showID+'</td>'); // ID \n\t\t// -------------------------------------------------------------------------\n\t\t// Validation and default assignments \n\t\t// Create empty elements with defaults if none found. ;-)\n\t\t// -------------------------------------------------------------------------\n\t\tfillStepDefaults(oneCaseStep);\n\t\titems.push('<td>'+oneCaseStep['@Driver'] +'</td>'); \n\t\tvar outstr; \n\t\titems.push('<td>'+oneCaseStep['@Keyword'] + \"<br>TS=\" +oneCaseStep['@TS']+'</td>'); \n\t\toutstr = oneCaseStep['Description'];\n\t\titems.push('<td>'+outstr+'</td>'); \n\n\t\tvar arguments = oneCaseStep['Arguments']['argument'];\n\t\tvar out_array = [] \n\t\tvar ta = 0; \n\t\tfor (xarg in arguments) {\n\n\t\t\tif (!arguments[xarg]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar argvalue = arguments[xarg]['@value'];\n\t\t\tconsole.log(\"argvalue\", argvalue);\n\t\t\t\tif (argvalue) {\n\t\t\t\tif (argvalue.length > 1) {\n\t\t\t\t\tvar xstr = arguments[xarg]['@name']+\" = \"+arguments[xarg]['@value'] + \"<br>\";\n\t\t\t\t\t//console.log(xstr);\n\t\t\t\t\tout_array.push(xstr); \n\t\t\t\t\t}\n\t\t\t\tta = ta + 1; \n\t\t\t\t}\n\t\t\t}\n\t\toutstr = out_array.join(\"\");\n\t\t//console.log(\"Arguments --> \"+outstr);\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\toutstr = oneCaseStep['onError']['@action'] \n\t\t\t//\"Value=\" + oneCaseStep['onError']['@value']+\"<br>\"; \n\t\titems.push('<td>'+oneCaseStep['onError']['@action'] +'</td>'); \n\t\toneCaseStep['Execute']['@ExecType'] = jsUcfirst( oneCaseStep['Execute']['@ExecType']);\n\t\toutstr = \"ExecType=\" + oneCaseStep['Execute']['@ExecType'] + \"<br>\";\n\t\tif (oneCaseStep['Execute']['@ExecType'] == 'If' || oneCaseStep['Execute']['@ExecType'] == 'If Not') {\n\t\t\toutstr = outstr + \"Condition=\"+oneCaseStep['Execute']['Rule']['@Condition']+ \"<br>\" + \n\t\t\t\"Condvalue=\"+oneCaseStep['Execute']['Rule']['@Condvalue']+ \"<br>\" + \n\t\t\t\"Else=\"+oneCaseStep['Execute']['Rule']['@Else']+ \"<br>\" +\n\t\t\t\"Elsevalue=\"+oneCaseStep['Execute']['Rule']['@Elsevalue'];\n\t\t}\n\t\t \n\t\t\t\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\titems.push('<td>'+oneCaseStep['runmode']['@type']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['context']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['impact']+'</td>'); \n\t\tvar bid = \"deleteTestStep-\"+s+\"-id-\"\n\t\titems.push('<td><i title=\"Delete\" class=\"fa fa-trash\" theSid=\"'+s+'\" id=\"'+bid+'\" katana-click=\"deleteCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"editTestStep-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Edit\" class=\"fa fa-pencil\" theSid=\"'+s+'\" value=\"Edit/Save\" id=\"'+bid+'\" katana-click=\"editCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"addTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-plus\" theSid=\"'+s+'\" value=\"Insert\" id=\"'+bid+'\" katana-click=\"addCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"dupTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-copy\" theSid=\"'+s+'\" value=\"Duplicate\" id=\"'+bid+'\" katana-click=\"duplicateCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t}\n\n\titems.push('</tbody>');\n\titems.push('</table>'); // \n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html( items.join(\"\"));\n\tkatana.$activeTab.find('#Step_table_display tbody').sortable( { stop: testCaseSortEventHandler});\n\t\n\tfillCaseDefaultGoto();\n\tkatana.$activeTab.find('#default_onError').on('change',fillCaseDefaultGoto );\n\n\t/*\n\tif (jsonCaseDetails['Datatype'] == 'Custom') {\n\t\t$(\".arguments-div\").hide();\n\t} else {\n\n\t\t$(\".arguments-div\").show();\n\t}\n\t*/\n\t\n} // end of function ", "function processJSON( data ) { \r\n \r\n // this will be used to keep track of row identifiers\r\n var next_row = 1;\r\n \r\n // iterate matches and add a row to the result table for each match\r\n $.each( data.matches, function(i, item) {\r\n var row_id = 'result_row_' + next_row++;\r\n \r\n // append new row to end of table\r\n $('<tr/>', { \"id\" : row_id } ).appendTo('tbody');\r\n\r\n });\r\n \r\n // show results section that was hidden\r\n $('#results').show();\r\n}", "function widgetFrameLoaded(id) {\n\n //iframe DOM object\n var frameObj = document.getElementById(\"customFieldFrame_\" + id);\n\n // flag to show or hide console logs\n var enableLog = false;\n\n // if the iframe not full rendered don't do anything at it first\n if ( !frameObj.hasClassName('custom-field-frame-rendered') ) {\n enableLog && console.log('Not rendered yet for', id);\n return;\n }\n\n //register widget to JCFServerCommon object\n //useful while debugging forms with widgets\n JCFServerCommon.frames[id] = {};\n JCFServerCommon.frames[id].obj = frameObj;\n var src = frameObj.src;\n\n JCFServerCommon.frames[id].src = src;\n JCFServerCommon.submitFrames = [];\n\n //to determine whether submit message passed form submit or next page\n var nextPage = true;\n //to determine which section is open actually\n var section = false;\n\n //we are changing iframe src dynamically\n //at first load iframe does not have src attribute that is why it behaves like it has form's URL\n //to prevent dublicate events if it is form url return\n // if(src.match('/form/')) {\n // console.log(\"returning from here\");\n // return;\n // }\n\n var referer = src;\n //form DOM object\n var thisForm = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n\n //detect IE version\n function getIEVersion() {\n var match = navigator.userAgent.match(/(?:MSIE |Trident\\/.*; rv:)(\\d+)/);\n return match ? parseInt(match[1]) : undefined;\n }\n\n // check a valid json string\n function IsValidJsonString(str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n }\n\n //send message to widget iframe\n function sendMessage(msg, id, to) {\n\n var ref = referer;\n if(to !== undefined) { //to option is necesaary for messaging between widgets and themes page\n ref = to;\n }\n\n if (document.getElementById('customFieldFrame_' + id) === null) {\n return;\n }\n if (navigator.userAgent.indexOf(\"Firefox\") != -1) {\n XD.postMessage(msg, ref, getIframeWindow(window.frames[\"customFieldFrame_\" + id]));\n } else {\n if (getIEVersion() !== undefined) { //if IE\n XD.postMessage(msg, ref, window.frames[\"customFieldFrame_\" + id]);\n } else {\n XD.postMessage(msg, ref, getIframeWindow(window.frames[\"customFieldFrame_\" + id]));\n }\n }\n }\n\n window.sendMessage2Widget = sendMessage;\n\n //function that gets the widget settings from data-settings attribute of the iframe\n function getWidgetSettings() {\n var el = document.getElementById('widget_settings_' + id);\n return (el) ? el.value : null;\n }\n\n // function to check if a widget is required\n function isWidgetRequired(id) {\n var classNames = document.getElementById('id_' + id).className;\n return classNames.indexOf('jf-required') > -1;\n }\n\n //send message to widget iframe and change data-status to ready\n function sendReadyMessage(id) {\n\n var background = navigator.userAgent.indexOf(\"Firefox\") != -1 ? window.getComputedStyle(document.querySelector('.form-all'), null).getPropertyValue(\"background-color\") : getStyle(document.querySelector('.form-all'), \"background\");\n var fontFamily = navigator.userAgent.indexOf(\"Firefox\") != -1 ? window.getComputedStyle(document.querySelector('.form-all'), null).getPropertyValue(\"font-family\") : getStyle(document.querySelector('.form-all'), \"font-family\");\n //send ready message to widget\n //including background-color, formId, questionID and value if it is edit mode (through submissions page)\n\n var msg = {\n type: \"ready\",\n qid: id + \"\",\n formID: document.getElementsByName('formID')[0].value,\n required: isWidgetRequired(id),\n background: background,\n fontFamily: fontFamily\n };\n\n // if settings not null, include it\n var _settings = getWidgetSettings();\n if ( _settings && decodeURIComponent(_settings) !== '[]' ) {\n msg.settings = _settings;\n }\n\n // data-value attribute is set if form is in editMode.\n var wframe = document.getElementById('customFieldFrame_' + id);\n\n // helper function\n function _sendReadyMessage(id, msg) {\n // put a custom class when ready\n $(document.getElementById('customFieldFrame_' + id)).addClassName('frame-ready');\n\n // send ready message\n sendMessage(JSON.stringify(msg), id);\n }\n\n // make sure we get the data first before sending ready message, only when msg.value undefined\n var isEditMode = ((document.get.mode == \"edit\" || document.get.mode == \"inlineEdit\" || document.get.mode == 'submissionToPDF') && document.get.sid);\n if ( isEditMode ) {\n // if edit mode do some polling with timeout\n // interval number for each check in ms\n var interval = 50;\n // lets give the check interval a timeout in ms\n var timeout = 5000;\n // will determine the timeout value\n var currentTime = 0;\n\n var editCheckInterval = setInterval(function(){\n // clear interval when data-value attribute is set on the iframe\n // that means the 'getSubmissionResults' request has now the question data\n if ( wframe.hasAttribute('data-value') || (currentTime >= timeout) ) {\n // clear interval\n clearInterval(editCheckInterval);\n\n // renew value, whether its empty\n msg.value = wframe.getAttribute(\"data-value\");\n\n // send message\n enableLog && console.log('Ready message sent in', currentTime, msg);\n _sendReadyMessage(id, msg);\n }\n\n currentTime += interval;\n }, interval);\n } else {\n // set value\n msg.value = wframe.getAttribute(\"data-value\");\n\n // send message\n enableLog && console.log('Sending normal ready message', msg);\n _sendReadyMessage(id, msg);\n }\n }\n\n // expose ready message function\n window.JCFServerCommon.frames[id]['sendReadyMessage'] = sendReadyMessage;\n\n //bind receive message event\n //a message comes from form\n XD.receiveMessage(function(message) {\n\n // don't parse some unknown text from third party api of widgets like google recapthca\n if ( !IsValidJsonString(message.data) ) {\n return;\n }\n\n //parse message\n var data = JSON.parse(message.data);\n\n // filter out events from other frames which cause form hang up\n // specially if there are multiple widgets on 1 form\n if ( parseInt(id) !== parseInt(data.qid) ) {\n return;\n }\n\n //sendSubmit\n if (data.type === \"submit\") {\n enableLog && console.log('widget submit', document.getElementById(\"input_\" + data.qid));\n // make sure thats its not an oEmbed widget\n // oEmbed widgets has no hidden input to read\n if ( document.getElementById(\"input_\" + data.qid) )\n {\n if (typeof data.value === 'number') {\n data.value = data.value + \"\";\n }\n var required = $(document.getElementById(\"input_\" + data.qid)).hasClassName('widget-required') || $(document.getElementById(\"input_\" + data.qid)).hasClassName('validate[required]');\n var input_id_elem = document.getElementById(\"input_\" + data.qid);\n\n // if the element/question was set to required, we do some necessary validation to display and error or not\n if (required) {\n if ( (data.hasOwnProperty('valid') && data.valid === false) && JotForm.isVisible(document.getElementById(\"input_\" + data.qid))) {\n input_id_elem.value = \"\";\n\n // put a custom error msg if necessary, only if error object is present\n var req_errormsg = \"This field is required\";\n if ( typeof data.error !== 'undefined' && data.error !== false ) {\n req_errormsg = ( data.error.hasOwnProperty('msg') ) ? data.error.msg : req_errormsg;\n }\n\n JotForm.errored(input_id_elem, req_errormsg);\n //return;\n } else {\n JotForm.corrected(input_id_elem);\n if (data.value !== undefined) {\n input_id_elem.value = data.value;\n } else {\n input_id_elem.value = \"\";\n }\n }\n } else {\n\n // if not required and value property has a value set\n // make it as the hidden input value\n if (data && data.hasOwnProperty('value') && data.value !== false) {\n input_id_elem.value = data.value;\n } else {\n input_id_elem.value = '';\n input_id_elem.removeAttribute('name');\n }\n }\n }\n\n // flag the iframe widget/oEmbed widget already submitted\n if ( JCFServerCommon.submitFrames.indexOf(parseInt(data.qid)) < 0 ) {\n JCFServerCommon.submitFrames.push(parseInt(data.qid));\n }\n\n // check for widget required/errors and prevent submission\n var allInputs = $$('.widget-required, .widget-errored');\n var sendSubmit = true;\n for (var i = 0; i < allInputs.length; i++) {\n if (allInputs[i].value.length === 0 && JotForm.isVisible(allInputs[i])) {\n sendSubmit = false;\n }\n }\n //if widget is made required by condition\n // var requiredByConditionInputs = document.getElementsByClassName(\"form-widget validate[required]\");\n // console.log(\"requiredByConditionInputs\". requiredByConditionInputs.length);\n\n // for(var i=0; i<requiredByConditionInputs.length; i++) {\n // if(requiredByConditionInputs[i].value.length === 0 && JotForm.isVisible(requiredByConditionInputs[i])) {\n // sendSubmit = false;\n // }\n // }\n\n if (!nextPage) {\n enableLog && console.log('next page', nextPage);\n if (JotForm.validateAll() && sendSubmit) {\n enableLog && console.log('sendSubmit', nextPage, sendSubmit);\n var tf = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n // Don't submit if form has Stripe. Stripe submits the form automatically after credit card is tokenized\n var isEditMode = [\"edit\", \"inlineEdit\", \"submissionToPDF\"].indexOf(document.get.mode) > -1;\n if (!(typeof Stripe === \"function\" && JotForm.isPaymentSelected() && !isEditMode)) {\n // we will submit the form if all widgets already submitted\n // because some widgets need to do their own processes before sending submit\n // check if all frames submitted a message, thats the time we fire a form submit\n if ( $$('.custom-field-frame').length === JCFServerCommon.submitFrames.length ) {\n enableLog && console.log('All frames submitted', JCFServerCommon.submitFrames);\n _submitLast.submit(tf, 50); //submit form with 50 ms delay, submitting only the last call\n } else {\n enableLog && console.log('Not all frames submitted', JCFServerCommon.submitFrames);\n }\n }\n }\n } else {\n\n // var proceedSection = true;\n // section.select(\".widget-required\").each(function(inp) {\n // if (inp.value.length === 0) {\n // proceedSection = false;\n // }\n // });\n\n // //@diki\n // //validate current section\n // var sectionValidated = true;\n // section.select('*[class*=\"validate\"]').each(function(inp) {\n // if (inp.validateInput === undefined) {\n // return; /* continue; */\n // }\n // if (!( !! inp.validateInput && inp.validateInput())) {\n // sectionValidated = JotForm.hasHiddenValidationConflicts(inp);\n // }\n // });\n\n // if (proceedSection && sectionValidated) {\n // if (window.parent && window.parent != window) {\n // window.parent.postMessage('scrollIntoView', '*');\n // }\n // if (JotForm.nextPage) {\n // JotForm.backStack.push(section.hide()); // Hide current\n // JotForm.currentSection = JotForm.nextPage.show();\n // //Emre: to prevent page to jump to the top (55389)\n // if (typeof $this !== \"undefined\" && !$this.noJump) {\n // JotForm.currentSection.scrollIntoView(true);\n // }\n // JotForm.enableDisableButtonsInMultiForms();\n // } else if (section.next()) { // If there is a next page\n // if(section.select(\".widget-required\").length > 0) {\n // JotForm.backStack.push(section.hide()); // Hide current\n // // This code will be replaced with condition selector\n // JotForm.currentSection = section.next().show();\n // JotForm.enableDisableButtonsInMultiForms();\n // }\n // }\n // JotForm.nextPage = false;\n // }\n }\n }\n\n //sendData\n if (data.type === \"data\") {\n document.getElementById(\"input_\" + data.qid).value = data.value;\n JotForm.triggerWidgetCondition(data.qid);\n JotForm.triggerWidgetCalculation(data.qid);\n }\n\n //show/hide form errors\n if ( data.type === \"errors\" ) {\n var inputElem = document.getElementById(\"input_\" + data.qid);\n // check the action\n if ( data.action === 'show' ) {\n // show error\n if ( JotForm.isVisible(inputElem) ) {\n JotForm.corrected(inputElem);\n inputElem.value = '';\n inputElem.addClassName('widget-errored');\n JotForm.errored(inputElem, data.msg);\n }\n } else if ( data.action === 'hide' ) {\n // hide error\n inputElem.removeClassName('widget-errored');\n JotForm.corrected(inputElem);\n }\n }\n\n //requestFrameSize\n if (data.type === \"size\") {\n var width = data.width,\n height = data.height;\n\n if (width !== undefined && width !== null) {\n if (width === 0 || width === \"0\") {\n width = \"auto\";\n } else {\n width = width + \"px\";\n }\n document.getElementById('customFieldFrame_' + data.qid).style.width = width;\n }\n if (height !== undefined && height !== null) {\n document.getElementById('customFieldFrame_' + data.qid).style.height = height + \"px\";\n //for IE8 : also update height of li element\n if ( getIEVersion() !== undefined ) {\n document.getElementById('cid_' + data.qid).style.height = height + \"px\";\n }\n }\n }\n\n //replaceWidget\n if (data.type === \"replace\") {\n var inputType = data.inputType,\n isMobile = data.isMobile;\n\n var parentDiv = $(\"customFieldFrame_\" + data.qid).up(),\n inputName = $(\"input_\" + data.qid).readAttribute(\"name\");\n\n //remove frame\n $(\"customFieldFrame_\" + data.qid).remove();\n $(\"input_\" + data.qid).up().remove();\n var newInput = \"\";\n switch (inputType) {\n case \"control_fileupload\":\n var tf = (JotForm.forms[0] == undefined || typeof JotForm.forms[0] == \"undefined\") ? $($$('.jotform-form')[0].id) : JotForm.forms[0];\n tf.setAttribute('enctype', 'multipart/form-data');\n\n if (!isMobile) {\n newInput = '<input class=\"form-upload validate[upload]\" type=\"file\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\" file-accept=\"pdf, doc, docx, xls, xlsx, csv, txt, rtf, html, zip, mp3, wma, mpg, flv, avi, jpg, jpeg, png, gif\"' +\n 'file-maxsize=\"10240\">';\n }\n // console.log(\"widget is mobile\", widget.isMobile);\n parentDiv.insert(newInput);\n break;\n case \"control_textbox\":\n newInput = '<input class=\"form-textbox\" type=\"text\" data-type-\"input-textbox\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\">';\n parentDiv.insert(newInput);\n break;\n case \"control_textarea\":\n newInput = '<textarea class=\"form-textarea\" type=\"text\" id=\"input_' + data.qid +\n '\" name=\"' + inputName + '\" cols=\"40\" rows=\"6\"></textarea>';\n parentDiv.insert(newInput);\n break;\n default:\n break;\n }\n }\n\n }, document.location.protocol + '//' + frameObj.src.match(/^(ftp:\\/\\/|https?:\\/\\/)?(.+@)?([a-zA-Z0-9\\.\\-]+).*$/)[3]);\n\n // immediately send the settings to widget\n enableLog && console.log('sending settings', getWidgetSettings(), (new Date()).getTime());\n sendMessage(JSON.stringify({\n type: \"settings\",\n settings: getWidgetSettings()\n }), id);\n\n //if widget is not visible do not send ready message (it may be on next page)\n //instead send ready message on next page click\n var widgetSection = JotForm.getSection(frameObj);\n\n if (frameObj && JotForm.isVisible(widgetSection) && JotForm.isVisible(frameObj) && typeof frameObj.up('.form-section-closed') === 'undefined') {\n sendReadyMessage(id);\n }\n\n //on form submit\n Event.observe(thisForm, 'submit', function(e) {\n if (document.getElementById('customFieldFrame_' + id) === null) {\n return;\n }\n Event.stop(e);\n nextPage = false;\n sendMessage(JSON.stringify({\n type: \"submit\",\n qid: id + \"\"\n }), id + \"\");\n });\n\n //on pagebreak click\n $$(\".form-pagebreak-next\").each(function(b, i) {\n\n $(b).observe('click', function(e) {\n\n //get the section where the button is clicked\n //this is to identify what section we were previously in\n //so that we only need to send the submit message to that previous widget from the previous page\n section = this.up('.form-section');\n nextPage = true;\n if (section.select(\"#customFieldFrame_\" + id).length > 0) {\n enableLog && console.log('Sending submit message for iframe id', id, \"from section\", this.up('.form-section'), \"and iframe\", frameObj);\n sendMessage(JSON.stringify({\n type: \"submit\",\n qid: id + \"\"\n }), id + \"\");\n Event.stop(e);\n }\n\n //send ready message to the next widget of the page only if the section is fully visible\n //we need to get the actual frameobj and section of the next widget on the next page\n //for us to send the ready for that widget\n var checkIntevarl = setInterval(function(){\n\n // get the actual widget attach to this event\n frameObj = document.getElementById(\"customFieldFrame_\" + id);\n if ( frameObj ) {\n // get its form section\n section = $(frameObj).up('.form-section');\n\n if (frameObj && JotForm.isVisible(section) && JotForm.isVisible(frameObj)) {\n // if fframe and section is visible\n // throw ready message to every widget that was inside of it\n clearInterval(checkIntevarl);\n enableLog && console.log('Sending ready message for iframe id', id, \"from section\", section);\n sendReadyMessage(id);\n }\n } else {\n // missing iframe - it was replace by a normal question field\n // usually happens on ie8 browsers - for widgets that using JFCustomWidget.replaceWidget method\n clearInterval(checkIntevarl);\n }\n }, 100);\n });\n });\n}", "function handleJsonImport(evt) {\r\n\t\t// Loop through the FileList and render image files as thumbnails.\r\n\t\t//project = new Project();\r\n\t\tvar files = evt.target.files; // FileList object\r\n\t\tfor (var i = 0, f; f = files[i]; i++) {\r\n\t\t\tvar reader = new FileReader();\r\n\t\t\treader.onload = (function(theFile) {\r\n\t\t\t\treturn function(e) {\r\n\t\t\t\t\t//console.log('handleJsonImport->'+theFile.name);\r\n\t\t\t\t\tloadImportProject(e.target.result,theFile.name);\r\n\t\t\t\t};\r\n\t\t\t})(f);\r\n\t\t\tif (i == files.length - 1)\r\n\t\t\t{\r\n\t\t\t\treader.onloadend = importProjectJsons;\r\n\t\t\t}\r\n\t\t\treader.readAsText(f, 'UTF-8');//readAsDataURL(f);//, 'UTF-8');\r\n\t\t}\r\n\t}", "function processJSON(JSONquery, fn) {\r\n var ajax = new XMLHttpRequest();\r\n // Set the function to be run, which will have access to this.responseText\r\n ajax.onload = fn;\r\n // It is a get request, to address, and async is true. \r\n ajax.open(\"GET\", JSONquery, true);\r\n ajax.send();\r\n return;\r\n}", "function handleJson(rawData) {\r\n\tparsed = JSON.parse(rawData).data;\r\n\tsortIOSAndroid(parsed);\r\n\tparsedIOS.forEach(app => {\r\n\t\taddDistinct(\"IOS\", app.identifier ? app.identifier : \"missing\");\r\n\t});\r\n\tiOSPackages.forEach(packageName => {\r\n\t\tvar maxCounter = 0;\r\n\t\tparsedIOS.forEach(app => {\r\n\t\t\tif (app.identifier == packageName) {\r\n\t\t\t\tapp.counter > maxCounter ? maxCounter = app.counter : null;\r\n\t\t\t};\r\n\t\t});\r\n\t\tparsedIOS.forEach(app => {\r\n\t\t\tif (app.identifier == packageName && app.counter < maxCounter - maxAllowedApps) {\r\n\t\t\t\tappID = app.id;\r\n\t\t\t\tappIdentifier = app.identifier;\r\n\t\t\t\tvar postString = `{\"id\": \"${appID}\", \"identifier\": \"${appIdentifier}\"}`;\r\n\t\t\t\tconsole.log(postString + \"FROM LOOP\");\r\n\t\t\t\tpostStringArr.push(postString);\r\n\t\t\t};\r\n\t\t});\r\n\t});\r\n\tparsedAndroid.forEach(app => {\r\n\t\taddDistinct(\"Android\", app.identifier ? app.identifier : \"missing\");\r\n\t});\r\n\tandroidPackages.forEach(packageName => {\r\n\t\tvar maxCounter = 0;\r\n\t\tparsedAndroid.forEach(app => {\r\n\t\t\tif (app.identifier == packageName) {\r\n\t\t\t\tapp.counter > maxCounter ? maxCounter = app.counter : null;\r\n\t\t\t};\r\n\t\t});\r\n\t\tparsedAndroid.forEach(app => {\r\n\t\t\tif (app.identifier == packageName && app.counter < maxCounter - maxAllowedApps) {\r\n\t\t\t\tappID = app.id;\r\n\t\t\t\tappIdentifier = app.identifier;\r\n\t\t\t\tvar postString = `{\"id\": \"${appID}\", \"identifier\": \"${appIdentifier}\"}`;\r\n\t\t\t\tconsole.log(postString + \"FROM LOOP\");\r\n\t\t\t\tpostStringArr.push(postString);\r\n\t\t\t};\r\n\t\t});\r\n\t});\r\n\tsendDeletePosts();\r\n}", "function processJSONBody(req, controller, methodName) {\n let body = [];\n req.on('data', chunk => {\n body.push(chunk);\n }).on('end', () => {\n try {\n // we assume that the data is in the JSON format\n if (req.headers['content-type'] === \"application/json\") {\n controller[methodName](JSON.parse(body));\n }\n else \n response.unsupported();\n } catch(error){\n console.log(error);\n response.unprocessable();\n }\n });\n }", "function iFrameUpload(fieldId, fieldTypeId, contentTypeId, resultdata)\n{\n\tvar field = {id:fieldId, fieldtypeid:fieldTypeId, contenttypeid:contentTypeId};\n\tvar data = jQuery.parseJSON(resultdata);\n\t\n\t// test for error\n\tif(data['error'] == '')\n\t{\n\t\tif(fieldTypeId == 18) // Image Gallery\n\t\t{\n\t\t\taddImageGalleryRow(fieldId, data);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsetPreview(field, data);\n\t\t}\t\n\t}\n\telse\n\t{\n\t\talert(data['error']);\n\t}\t\n\t\n\tjQuery.unblockUI();\n}", "function init_info_model(Tableau_model_temp)\n// function init_Tableau_model(response)\n{\n // var Tableau_calcul_temp = eval('[' + response + ']');\n if (Tableau_model_temp)\n { \n Tableau_model = Tableau_model_temp ;\n\t//alert(array2json(Tableau_model))\n\tvar taille_Tableau=Tableau_model_temp.length;\n \tfor(i=0; i<taille_Tableau; i++) {\n\t //alert(Object.prototype.toString.apply(Tableau_model_temp[i]));\n\t for (var key in Tableau_model_temp[i]) {\n\t\tif(key == 'mesh'){\n\t\t Tableau_id_model = Tableau_model[i][key];\n\t\t //alert(Tableau_id_model);\n\t\t //strtemp = $.toJSON(Tableau_pieces);\n\t\t //alert(strtemp);\n\t\t}\n\t\telse if(key == 'groups_elem'){\n\t\t Tableau_pieces = Tableau_model[i][key];\n\t\t //alert($.toJSON(Tableau_pieces));\n\t\t //strtemp = $.toJSON(Tableau_pieces);\n\t\t //alert(strtemp);\n\t\t}\n\t\telse if(key == 'groups_inter'){\n\t\t Tableau_interfaces = Tableau_model[i][key];\n\t\t //strtemp = $.toJSON(Tableau_interfaces);\n\t\t //alert(strtemp);\n\t\t}\n\t\telse if(key == 'groups_bord'){\n\t\t Tableau_bords = Tableau_model[i][key];\n\t\t //strtemp = $.toJSON(Tableau_interfaces);\n\t\t //alert(strtemp);\n\t\t}\n\t }\n \t}\n }\n else\n {\n Tableau_model[0] = new Array();\n Tableau_model[0]['name'] = 'nouveau calcul';\n\tTableau_model[0]['type'] = 'statique';\n\tTableau_model[0]['description'] = 'nouvelle description';\n }\n affiche_Tableau_piece();\n affiche_Tableau_interface();\n affiche_Tableau_bord();\n //object_temp = array2object(Tableau_model); \n //strtemp = $.toJSON(Tableau_model);\n //alert(strtemp);\n}", "function prepareDataForTable(data){\n\n // Return variable:\n var data_json = [];\n\n // Looping through the submitted documents\n $.each(data, (index, study) => {\n\n // data with one row in the data table:\n var tmp = {};\n\n // Skipping study if already processed:\n if (jQuery.inArray(study.id, study_ids) == -1){\n study_ids.push(study.id);\n }\n\n // Save study ID for further checks in global variable:\n\n\n // Do we need to add genotyping icon:\n var genotypingIcon = \"\";\n if ((study.genotypingTechnologies.indexOf(\"Targeted genotyping array\") > -1) ||\n (study.genotypingTechnologies.indexOf(\"Exome genotyping array\") > -1)) {\n genotypingIcon = \"<span style='font-size: 12px' class='glyphicon targeted-icon-GWAS_target_icon context-help'\" +\n \" data-toggle='tooltip'\" +\n \"data-original-title='Targeted or exome array study'></span>\";\n }\n\n // Is summary stats available:\n var linkFullPValue = \"NA\";\n if (study.fullPvalueSet == 1) {\n var a = (study.authorAscii_s).replace(/\\s/g, \"\");\n const ftpdir = getDirectoryBin(study.accessionId);\n var dir = a.concat(\"_\").concat(study.pubmedId).concat(\"_\").concat(study.accessionId);\n var ftplink = \"<a href='http://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/\".concat(ftpdir).concat('/').concat(study.accessionId).concat(\"' target='_blank'</a>\");\n linkFullPValue = ftplink.concat(\"FTP Download\");\n }\n\n // Is study loaded to the summary stats database:\n if (loadedStudies.indexOf(study.accessionId) > -1) {\n if (linkFullPValue === \"NA\") {\n linkFullPValue = \"<a href='http://www.ebi.ac.uk/gwas/summary-statistics/docs' target='_blank'>API access</a>\";\n } else {\n linkFullPValue = linkFullPValue.concat(\"&nbsp;&nbsp;or&nbsp;&nbsp;<a href='http://www.ebi.ac.uk/gwas/summary-statistics/docs' target='_blank'>API access</a>\");\n }\n }\n tmp['link'] = linkFullPValue;\n\n // Adding author:\n tmp['Author'] = study.author_s ? study.author_s : \"NA\";\n\n // Number Associations:\n tmp['nr_associations'] = study.associationCount ? study.associationCount : 0;\n\n // Publication date:\n var publication_date_full = study.publicationDate;\n var publication_date = publication_date_full.split('T')[0];\n tmp['publi'] = publication_date;\n\n // AccessionID:\n tmp['study'] = '<a href=\"' + gwasProperties.contextPath + 'studies/' + study.accessionId + '\">' + study.accessionId + '</a>' + genotypingIcon;\n\n // Journal:\n tmp['Journal'] = study.publication;\n\n // Title:\n tmp['Title'] = '<a href=\"' + gwasProperties.contextPath + 'publications/' + study.pubmedId + '\">' + study.title + '</a>';\n\n // Reported trait:\n tmp['reported_trait'] = study.traitName_s;\n\n // Mapped trait:\n tmp['mappedTraits'] = setTraitsLink(study);\n\n // Mapped background trait:\n tmp['mappedBkgTraits'] = setBackgroundTraitsLink(study);\n\n // Initial sample desc\n var splitDescription = [];\n var descriptionToDisplay = [];\n var initial_sample_text = '-';\n if (study.initialSampleDescription) {\n // Split after each sample number, splitDescription[0] is an empty string\n splitDescription = study.initialSampleDescription.split(/([1-9][0-9]{0,2}(?:,[0-9]{3})*)/);\n for (var i = 1; i < splitDescription.length; i++) {\n if (i % 2 == 0) {\n // Join the sample number and it's description as one item\n var item = splitDescription[i - 1] + splitDescription[i].replace(/(,\\s+$)/, \"\");\n descriptionToDisplay.push(\" \".concat(item));\n }\n }\n initial_sample_text = displayArrayAsList(descriptionToDisplay);\n if (splitDescription.length > 3) {\n initial_sample_text = initial_sample_text.html();\n }\n }\n tmp['initial_sample_text'] = initial_sample_text;\n\n // Replicate sample desc\n var replicate_sample_text = '-';\n if (study.replicateSampleDescription) {\n replicate_sample_text = displayArrayAsList(study.replicateSampleDescription.split(', '));\n if (study.replicateSampleDescription.split(', ').length > 1)\n replicate_sample_text = replicate_sample_text.html()\n }\n tmp['replicate_sample_text'] = replicate_sample_text;\n\n // ancestryLinks\n var initial_ancestral_links_text = '-';\n var replicate_ancestral_links_text = '-';\n if (study.ancestryLinks) {\n var ancestry_and_sample_number_data = displayAncestryLinksAsList(study.ancestryLinks);\n initial_ancestral_links_text = ancestry_and_sample_number_data.initial_data_text;\n replicate_ancestral_links_text = ancestry_and_sample_number_data.replicate_data_text;\n if (typeof initial_ancestral_links_text === 'object') {\n initial_ancestral_links_text = initial_ancestral_links_text.html();\n }\n if (typeof replicate_ancestral_links_text === 'object') {\n replicate_ancestral_links_text = replicate_ancestral_links_text.html();\n }\n }\n tmp['initial_ancestral_links_text'] = initial_ancestral_links_text;\n tmp['replicate_ancestral_links_text'] = replicate_ancestral_links_text;\n\n data_json.push(tmp)\n });\n\n return(data_json)\n}", "function proccessResults() {\n // console.log(this);\n var results = JSON.parse(this.responseText);\n if (results.list.length > 0) {\n resetData();\n for (var i = 0; i < results.list.length; i++) {\n geoJSON.features.push(jsonToGeoJson(results.list[i]));\n }\n drawIcons(geoJSON);\n }\n }", "function makeChart(data1) {\n var i, j;\n\n titles = data1.columns;\n titles.shift(); // Since we dont need the 'timestamp' column\n //console.log(data1);\n //console.log(titles);\n\n // Pushing the object skeletons into the 'data' array object\n for (i = 0; i < titles.length; i++) {\n var data_obj = {};\n data_obj.Title = titles[i];\n data_obj.Type = types[i];\n data_obj.Options = options[i];\n data_obj.Responses = [];\n // console.log(data_obj);\n data.push(data_obj);\n }\n\n // Sorting out the responses\n // If we see the multiple responses, they are strings of the form 'Response1, Response2'\n // So they can be split into arrays using the string.split(', ') method\n for (i = 0; i < data1.length; i++) {\n for (j = 0; j < data.length; j++) {\n var res = [];\n // console.log(data1[i][titles[j]].split(\", \"));\n res.push(data1[i][titles[j]].split(\", \"));\n // console.log(res[0]);\n if (j == 1) {\n data[j].Responses.push(res[0]); // Always push the response array for CHECKBOX type\n } else {\n if (res[0].length == 1) {\n // If there is only 1 response, just push the string, no the array\n data[j].Responses.push(res[0][0]); \n } else {\n data[j].Responses.push(res[0]); // If there are multiple responses, push the array\n }\n }\n }\n }\n\n console.log(data);\n\n // EXECUTING THE ABOVE FUNCTIONS BY ITERATING THROUGH THE DATA ELEMENTS\n //window.onload = () => {\n data.forEach((item) => {\n switch (item.Type) {\n case LIST:\n listProcessing(item);\n break;\n case MCQ:\n mcqProcessing(item);\n break;\n case CHECKBOX:\n checkboxProcessing(item);\n break;\n }\n });\n //};\n}", "function read_JSON_drop(evt) {\n evt.stopPropagation();\n evt.preventDefault();\n\n var files = evt.dataTransfer.files; // FileList object.\n\n var text = d3.select(\"#menuL9\")\n\n text.html(function() {\n return \"Loading \" + files[0].name + \"...\";\n });\n\n setTimeout(function() {\n text.html(\"drop webweb json here\")\n }, 2000);\n\n console.log(\"FILES\");\n console.log(files);\n\n read_JSON(files);\n}", "function jsonify(pipeline, pipeinfo) {\n\n //print(\"json pipeline is \" + pipeline);\n var stream = new java.io.ByteArrayOutputStream();\n cocoon.processPipelineTo( pipeline, pipeinfo, stream );\n var theVal = stream.toString() + \"\";\n\t\t\n\t//print(\"serviceVal is \" + theVal);\n var checkpos = -1;\n\t/* \tthis probably doesn't have to be in a try/catch block\n\t\tbut i had a problem with one range where it was an odd\n\t\tcharacter. \n\t*/\t\n\ttry {\n\t\tcheckpos = theVal.indexOf(prob1);\n\t\tif (checkpos != -1)\n\t\t\ttheVal = fixCollection(theVal,prob1);\n\t\tcheckpos = theVal.indexOf(prob2);\n \tif (checkpos != -1)\n \ttheVal = theVal.substring(0,checkpos);\n\t\tcheckpos = theVal.indexOf(prob3);\n\t\tif (checkpos != -1) {\n\t\t\ttheVal = theVal.replace(/,\\{\\\"url/g,'},{\\\"url') + \"\";\n\t\t\ttheVal = theVal.replace(/\\\"\\]/g,'\\\"}]');\n\t\t\t//print(\"now -> \" + theVal + \"<-\");\n\t\t}\n\t} catch (problem) {\n\t\tprint(\"nasty char issue \" + problem);\n\t}\n\n\tvar theEval = jsonEval(theVal);\n\n\treturn theEval;\n\n}//jsonify", "function jsonArray(mdJson, jASchema ) {\r\n\t\r\n var newArray =[];\r\n\r\n try {\r\n\r\n\t\tif ( mdJson.length > 0 ) {\r\n\r\n\t for (var i = 0; i < mdJson.length; i++) {\r\n\r\n\t \t// recursively handle objects in array\r\n\r\n\t \tif ( typeof(jASchema) !== \"undefined\" && typeof(jASchema)==\"object\" ) {\r\n\t \t \tvar tjO = {};\r\n\t \t \tvar subData = mdJson[i];\r\n\t \t \tvar trail;\r\n\t \t \ttjO = SubObjectBuilder(subData, trail, jASchema, i); \r\n\t \t \ttjO.array_index = i;\r\n\t \t \tif ( typeof(mdJson[i].datatype) !== \"validationonly\" ) {\r\n\t \t \t\tif ( typeof(mdJson[i].validation) !== \"undefined\" ) {\r\n\t \t \t\t\ttjO.validateonly = mdJson[i].validation.toString();\r\n\t \t \t\t} else {\r\n\t \t \t\t\ttjO.validateonly = \"true\";\r\n\t \t \t\t}\r\n\t \t \t} \r\n\t \t \tnewArray.push(tjO);\r\n\t \t} else {\r\n\t \t \t var tjs = {};\r\n\t \t \ttjs = JSON.parse(JSON.stringify(jASchema)); // cheap copy\r\n\t \ttjs.value = mdJson[i].name;\r\n\t \ttjs.array_index = i; \r\n\r\n\t \t \tif ( typeof(mdJson[i].datatype) !== \"validationonly\" ) {\r\n\t \t \t\tif ( typeof(mdJson[i].validation) !== \"undefined\" ) {\r\n\t \t \t\t\ttjO.validateonly = mdJson[i].validation;\r\n\t \t \t\t} else {\r\n\t \t \t\t\ttjO.validateonly = \"true\";\r\n\t \t \t\t}\r\n\t \t \t}\r\n\t\t\t\t \tnewArray.push(tjs);\r\n\t \t}\r\n\t \r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Build empty array item\r\n\t\t newArray.push(jASchema);\r\n\t\t newArray[i].name = \"default\";\r\n\t\t\tnewArray[i].array_index = 0;\r\n\t\t}\r\n\r\n\t} catch (e) {\r\n \tconsole.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> JSON Array Error ' + JSON.stringify(e) );\r\n\t}\r\n\r\n\treturn newArray;\r\n}", "function JSONChecker()\n{\n}", "function _processDataToSend(tabName, fields) {\n var retorno = [];\n\n for (var i = 0; i < _tabs.length; i++) {\n if (_tabs[i].tabName === tabName) {\n var item = {};\n item['tabName'] = _tabs[i].tabName.toLowerCase();\n\n for (var key in fields) {\n for (var f = 0; f < _tabs[i].fields.length; f++) {\n if (_tabs[i].fields[f].name === key) {\n if (_tabs[i].fields[f].type === \"combo\") {\n //find comboName\n var name = _tabs[i].fields[f].comboNames[_tabs[i].fields[f].comboIds.indexOf(fields[key])];\n\n item[key] = {\n \"id\": fields[key],\n \"name\": name\n };\n } else if (_tabs[i].fields[f].type === \"typeahead\") {\n item[key] = {\n \"text\": fields[key]\n };\n }\n }\n }\n }\n\n retorno.push(item);\n }\n }\n\n return retorno;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an Array of form elements that are children of the DIV element with id = the given divId string.
function getDetailFormElements(divId) { var detailElements = new Array(); var detailDiv = getObject(divId); //to be canceled var allFormElements = detailDiv.document.forms[0].elements; var detailIdx = 0; for (var i = 0; i < allFormElements.length; i++) { if (isNodeChildOfId(allFormElements[i], divId)) { detailElements[detailIdx++] = allFormElements[i]; } } return detailElements; }
[ "function formToFieldList(formID) {\n let form = document.getElementById(formID).elements;\n let formValues = [];\n\n for (let i = 0; i < form.length; i++) {\n if (form[i].type === 'text') {\n formValues.push(form[i].value)\n }\n if (form[i].type === 'checkbox') {\n formValues.push(form[i].checked)\n }\n }\n return formValues;\n}", "function _getTabsForFormID(formId) {\n var retorno;\n\n if (formId === \"F21\") {\n retorno = [];\n } else if (formId === \"F22\") {\n retorno = ['tabEvent_standard'];\n } else if (formId === \"F23\") {\n retorno = ['tabEvent_ud_arc_standard'];\n } else if (formId === \"F24\") {\n retorno = ['tabEvent_ud_arc_rehabit'];\n } else if (formId === \"F25\") {\n retorno = [];\n } else if (formId === \"F27\") {\n retorno = ['tabGallery'];\n } else if (formId === \"F51\" || formId === \"F52\" || formId === \"F53\" || formId === \"F54\" || formId === \"F55\" || formId === \"F56\" || formId === \"F57\") {\n retorno = [];\n } else {\n retorno = ['tabInfo'];\n }\n\n return retorno;\n } //****************************************************************", "function divShowOnly(divHideList,divId) {\n //console.log('divShow('+divHideList+','+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tvar divHideArray = divHideList.split(\",\");\n\t\tfor(var i=0; i<divHideArray.length; i++){\n\t\t\tdivHide(divHideArray[i]);\n\t\t}\n\t\tdivShow(divId);\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}", "function getCheckboxesFrom(targetElement)\n{\n\tvar result = [];\n\tvar targetInputElements = targetElement.getElementsByTagName('INPUT');\n for (var i = 0; i < targetInputElements.length; i++)\n {\n if (targetInputElements[i].type.toUpperCase()=='CHECKBOX') // Only add checkboxes.\n {\n\t\t\tresult.push( targetInputElements[i] );\n \t// DEBUG // targetInputElements[i].addEventListener('click', function(){ console.log(\"id: \" + this.id + \" checked: \" + this.checked ); });\t\t\t\t\n }\n }\n return result;\n}", "function divContent(divId,divContent) {\n //console.log('divContent('+divId+','+divContent+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).innerHTML = divContent;\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}", "function getFormByFormId(id) {\n var formId;\n var formName;\n var formParent;\n var availableTabs;\n var docSelectorForWebForms;\n\n if (id === \"F16\") {\n formId = 'F16';\n formName = 'INFO_GENERIC';\n formParent = 'formInfo';\n } else if (id === \"F21\") {\n formId = id;\n formName = 'VISIT';\n formParent = 'formInfo';\n } else if (id === \"F22\" || id === \"F23\" || id === \"F24\") {\n formId = id;\n formName = 'EVENT_FORM';\n formParent = 'formInfo';\n } else if (id === \"F25\") {\n formId = id;\n formName = 'VISIT_MANAGER';\n formParent = 'formInfo';\n } else if (id === \"F27\") {\n formId = id;\n formName = 'GALLERY';\n formParent = 'formInfo';\n } else if (id === \"F51\") {\n formId = id;\n formName = 'REVIEW_UD_ARC';\n formParent = 'formReview';\n } else if (id === \"F52\") {\n formId = id;\n formName = 'REVIEW_UD_NODE';\n formParent = 'formReview';\n } else if (id === \"F53\") {\n formId = id;\n formName = 'REVIEW_UD_CONNEC';\n formParent = 'formReview';\n } else if (id === \"F54\") {\n formId = id;\n formName = 'REVIEW_UD_GULLY';\n formParent = 'formReview';\n } else if (id === \"F55\") {\n formId = id;\n formName = 'REVIEW_WS_ARC';\n formParent = 'formReview';\n } else if (id === \"F56\") {\n formId = id;\n formName = 'REVIEW_WS_NODE';\n formParent = 'formReview';\n } else if (id === \"F57\") {\n formId = id;\n formName = 'REVIEW_WS_CONNEC';\n formParent = 'formReview';\n } else {\n formId = 'F11';\n formName = 'INFO_UD_NODE';\n formParent = 'formInfo';\n elementSelectorForWebForms = 'v_ui_element_x_node';\n docSelectorForWebForms = 'v_ui_doc_x_node';\n }\n\n var retorn = {};\n retorn.formId = formId;\n retorn.formName = formName;\n retorn.formParent = formParent;\n retorn.formTabs = _getTabsForFormID(formId);\n return retorn;\n }", "function validate_form_div(a,divid)\n\t{\n\t\tvar z=a.split(',');\n\t\tnum_data = z.length;\n\t\tvar msg = 'Error! The following fields are empty<br>';\n\t\tvar err=0;\n\t\t//alert(a);\n\t\tfor(var i=0; i<num_data; i++)\n\t\t\t{\n\t\t\t\t//alert(z[i]);\n\t\t\t\tif(document.getElementById(z[i]).value=='')\n\t\t\t\t\t{\n\t\t\t\t\t\tmsg=msg+z[i]+'<br>';\n\t\t\t\t\t\terr++;\n\t\t\t\t\t}\n\t\t\t}\n\t\tif(err!=0)\n\t\t\t{\n\t\t\t\tdocument.getElementById(divid).innerHTML=msg;\n\t\t\t\treturn false;\n\t\t\t}\n\t\telse return true;\t\t\n\t\t\n\t}", "function loopEls(elements){\n //An empty array to push the values into\n var valuesNew = [];\n // loops through the form elements and gets their values\n for (var i = 0; i < elements.length; i++) {\n valuesNew.push(elements[i].value);\n };\n \n values = valuesNew;\n return valuesNew; \n \n \t}", "function divShowOnlyInline(divHideList,divId) {\n //console.log('divShow('+divHideList+','+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tvar divHideArray = divHideList.split(\",\");\n\t\tfor(var i=0; i<divHideArray.length; i++){\n\t\t\tdivHide(divHideArray[i]);\n\t\t}\n\t\tdivShowInline(divId);\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}", "function getWebForms(formIdentifier, layer, pol_id, id_name, tabName, cb) {\n _self.emit(\"log\", \"form.js\", \"getWebForms(\" + formIdentifier + \",\" + layer + \",\" + pol_id + \",\" + id_name + \",\" + tabName + \")\", \"info\");\n\n var dataToSend = {};\n dataToSend.layer = layer;\n dataToSend.device = _device;\n dataToSend.form = formIdentifier;\n dataToSend.pol_id = pol_id;\n dataToSend.id_name = id_name;\n dataToSend.tabName = tabName;\n dataToSend.token = _token;\n dataToSend.expected_api_version = _expected_api_version;\n dataToSend.what = 'ELEMENTS';\n axios.post(_baseHref + '/ajax.sewernet.php', dataToSend).then(function (response) {\n _self.emit(\"log\", \"forms.js\", \"getWebForms\", \"success\", response.data.message);\n\n if (response.data.status === \"Accepted\") {\n cb(null, response.data.message);\n } else {\n cb(response.data.code, response.data.message);\n }\n })[\"catch\"](function (error) {\n _self.emit(\"log\", \"form.js\", \"getWebForms\", \"error\", error);\n });\n }", "function findFormsByUserID (userId) {\n userId_temp = userId;\n var userForms = [];\n for (var i in forms) {\n if (userId == forms[i].userId) {\n userForms.push(forms[i]);\n }\n }\n return userForms;\n }", "function createDivs(problemObject) {\n\n var i, j;\n var div = '';\n for (i = 0; i < problemObject.arguments.length; i++) {\n var argumentID = $('#' + i + 'box');\n div += '<div class =\"row numberDiv\">';\n div += '<div id=\"tens' + i + '\" class=\"col-9 numberDiv\" > ';\n\n div += '<div class=\"row numberDiv-drag\">';\n for (j = 0; j < 5; j++) {\n //should be <div id=2_tens0....9)\n div += '<div class=\"col numberDiv\" id =\"' + i + '_tens' + j + '\"></div>';\n\n }\n div += '</div>';\n\n div += '<div class=\"row numberDiv-drag\">';\n for (j = 5; j < 10; j++) {\n //should be <div id=2_tens0....9)\n div += '<div class=\"col numberDiv\" id =\"' + i + '_tens' + j + '\"></div>';\n\n }\n div += '</div> </div>';\n\n\n\n\n // same for one's \n //except we only need 10 stacked\n div += '<div id=\"ones' + i + '\" class=\"col-3 numberDiv\" > ';\n\n //div += '<div class=\"row numberDiv-drag\">';\n // for (j = 0; j < 5; j++) {\n // //should be <div id=2_tens0....9)\n // div += '<div class=\"col numberDiv\" id =\"' + i + '_ones' + j + '\"></div>';\n\n // }\n //div += '</div>';\n\n // div += '<div class=\"row numberDiv-drag\">';\n // div += '<div class=\"col-8 numverDiv\"> </div>'\n // div += '<div class=\"col-2 hidden numberDiv\" id=\"' + i + '_ones\"> </div>'\n //for (j = 0; j < 10; j++) {\n //should be <div id=2_tens0....9)\n // div += '<div class=\"row numberDiv\" id =\"' + i + '_ones' + j + '\"></div>';\n\n // }\n div += '</div></div> </div>';\n\n argumentID.append(div);\n //now clear div?\n div = '';\n\n //make canvas for ten's\n\n for (j = 0; j < 10; j++) {\n containerDiv = $('#' + i + '_tens' + j);\n var box_width = containerDiv.width() - 5;\n var box_height = containerDiv.height() - 5;\n\n var stage = new Konva.Stage({\n container: i + '_tens' + j,\n width: box_width,//$('#tens_box').innerWidth(),\n height: box_height//box_height//box_height //$('#tens_box').innerHeight()\n });\n\n var layer = new Konva.Layer();\n\n var rectX = stage.getWidth(); // 2 //- 25;\n var rectY = stage.getHeight();// 2// - 30;\n\n console.log(\"this is recy/10 \" + rectY / 10);\n console.log(\"this is rectY \", rectY);\n\n var box1 = new Konva.Rect({\n x: 1,\n y: 0,\n width: (box_width-10),\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box2 = new Konva.Rect({\n x: 1,\n y: 10,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box3 = new Konva.Rect({\n x: 1,\n y: 20,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box4 = new Konva.Rect({\n x: 1,\n y: 30,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box5 = new Konva.Rect({\n x: 1,\n y: 40,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box6 = new Konva.Rect({\n x: 1,\n y: 50,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box7 = new Konva.Rect({\n x: 1,\n y: 60,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box8 = new Konva.Rect({\n x: 1,\n y: 70,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box9 = new Konva.Rect({\n x: 1,\n y: 80,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box10 = new Konva.Rect({\n x: 1,\n y: 90,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n layer.add(box1);\n layer.add(box2);\n layer.add(box3);\n layer.add(box4);\n layer.add(box5);\n layer.add(box6);\n layer.add(box7);\n layer.add(box8);\n layer.add(box9);\n layer.add(box10);\n stage.add(layer);\n /*\n function fitStageIntoParentContainer() {\n var container = i + '_tens' + j; //document.querySelector('#stage-parent');\n \n // now we need to fit stage into parent\n var containerWidth = container.offsetWidth;\n // to do this we need to scale the stage\n var scale = containerWidth / box_width;\n \n \n \n stage.width(stageWidth * scale);\n stage.height(stageHeight * scale);\n stage.scale({ x: scale, y: scale });\n stage.draw();\n box_width = containerDiv.width() - 5;\n }\n \n fitStageIntoParentContainer();\n // adapt the stage on any window resize\n window.addEventListener('resize', fitStageIntoParentContainer ); \n \n */\n\n\n }\n\n //same for one's\n containerDiv = $('#ones' + i);\n var box_width = containerDiv.width() - 5;\n var box_height = containerDiv.height() - 5;\n\n var stage = new Konva.Stage({\n container: 'ones'+i,\n width: box_width,//$('#tens_box').innerWidth(),\n height: box_height//box_height//box_height //$('#tens_box').innerHeight()\n\n });\n onesStages.push(stage);\n onesStagesValues.push(0);\n var layer = new Konva.Layer();\n\n var rectX = stage.getWidth(); // 2 //- 25;\n var rectY = stage.getHeight();// 2// - 30;\n\n console.log(\"this is recy/10 \" + rectY / 10);\n console.log(\"this is rectY \", rectY);\n\n var box1 = new Konva.Rect({\n x: 1,\n y: box_height-30,\n width: box_width/2,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n layer.add(box1);\n stage.add(layer);\n\n\n\n\n\n }\n\n\n //iterate through all of the arguments \n //add a tens box\n\n //the konvajs stages\n\n\n\n\n //append divs to screen and build konvajs modal\n //problem_div.append(div);\n\n //now create the canvas \n\n\n\n\n\n}", "function getFocusables(el){return[].slice.call($(focusableElementsString,el)).filter(function(item){return item.getAttribute('tabindex')!=='-1'//are also not hidden elements (or with hidden parents)\n&&item.offsetParent!==null;});}", "function hideAllBoxes(){\n\tfor (var i = 0; i < divArray.length; i++)\n\t\tdocument.getElementById(divArray[i]).style.display = \"none\";\n}", "function obtenerListaIdsInput() {\r\n\tvar fields = $(\":input\");\r\n\tvar ids = [];\r\n\t$(fields).each(function() {\r\n\t\tif (this.type != \"button\") {\r\n\t\t\tids.push(this.id);\r\n\t\t}\r\n\t})\r\n\treturn ids;\r\n}", "function getElements() {\n // logic\n var domEls = [];\n for (var i = 0; i < classNamesArray.length; i++) {\n domEls.push(document.getElementsByClassName(classNamesArray[i]));\n }\n return domEls;\n}", "function getInputs() {\n var allInputArea = document.getElementsByTagName('input')\n var results = []\n\n for (var i = 0; i < allInputArea.length; i++) {\n results.push(allInputArea[i])\n }\n return results\n}", "static listByFormId(form_id) {\n return this.queryByFormId(form_id).then((rows) => rows.map((row) => new this(row, false)));\n }", "function hideAllExcept(elementId) {\n var containerDivs = ['firstContainerDiv', 'secondContainerDiv', 'thirdContainerDiv', 'popUpWindow'];\n for (var containerDiv of containerDivs) {\n document.getElementById(containerDiv).style.display = containerDiv != elementId ? 'none' : 'flex';\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get transaction action creator
function getTransactionActionCreator(data) { return { type: GETTRANS, payload: {transactions: data} } }
[ "function actionCreator(action){\n return action\n}", "function getAction() {\r\n\r\n return( action );\r\n\r\n }", "function createAction(type) {\n function actionCreator(payload) {\n return {\n type: type,\n payload: payload\n };\n }\n\n actionCreator.toString = function () {\n return \"\".concat(type);\n };\n\n actionCreator.type = type;\n return actionCreator;\n}", "getActionIdentifier() {\n return this._actionIdentifier;\n }", "function getActions() {\n return db('actions');\n}", "function addAction(action) {\n return db('actions')\n .insert(action)\n .then(ids => ({id: ids[0]}));\n}", "function __generateActionName(name) {\n\t return 'action:' + name;\n\t}", "function getStoreCredit() {\n return (dispatch) => makeStoreCreditRequest(dispatch);\n}", "function buyCake() {\n return {\n type: BUY_CAKE,\n info: \"FIrst Redux Action\",\n };\n}", "function getTrigger() {\n let { eventName, payload } = github.context;\n const payload_action = payload.action;\n console.info(`Trigger -> ${eventName} - ${payload_action}`);\n switch (eventName) {\n case 'push':\n return 'commit';\n case 'pull_request':\n if (payload_action === \"opened\")\n return 'pull-request';\n if (payload_action === \"synchronize\")\n return 'pull-request-sync';\n return 'pull-request-other';\n // case 'pull_request_review_comment':\n // return 'pr-comment';\n case 'workflow_dispatch':\n return 'manual';\n default:\n console.warn(\"Event trigger not of type: commit, pull request or manual.\");\n throw new Error(\"Invalid trigger event\");\n }\n}", "_buildSemanticAction(semanticAction) {\n if (!semanticAction) {\n return null;\n }\n\n // Builds a string of args: '$1, $2, $3...'\n let parameters = [...Array(this.getRHS().length)]\n .map((_, i) => `$${i + 1}`)\n .join(',');\n\n const handler = CodeUnit.createHandler(parameters, semanticAction);\n\n return (...args) => {\n // Executing a handler mutates $$ variable, return it.\n handler(...args);\n return CodeUnit.getSandbox().$$;\n };\n }", "createTipo ({\n commit\n }, tipo) {\n ApiService.postTipo(tipo).then((response) => {\n tipo.idTipo = response.data.idTipo // retorna el nuevo identificador creado por el servidor\n\n commit('ADD_TIPO', tipo)\n }).catch(error => {\n console.log('ERROR:', error.message)\n })\n }", "addNewWorkspaceTransaction(){\n var self = this;\n let transaction = new Workspace_Transaction(this,self.currentObj(self.updatePrev()));\n this.tps.addTransaction(transaction);\n self.forColorModel();\n \n }", "crudify(modelName, action, opt) {\n const formletObj = this.model(modelName);\n if (typeof opt !== 'object' || !opt) opt = {};\n if (!opt.name) {\n opt.name = modelName.code;\n }\n if (['create', 'read', 'update', 'delete', 'find', 'count'].indexOf(action) === -1) {\n console.error(`Crudify action for model ${modelName} is not valid.`);\n return;\n }\n const actionObj = crudify[action](formletObj, opt);\n if (!actionObj) {\n logger.warn(`Crudify ${action} for model ${modelName} was not registered.`);\n return;\n }\n thorin.on(thorin.EVENT.RUN, 'store.' + this.name, () => {\n thorin.dispatcher.addAction(actionObj);\n });\n return actionObj;\n }", "async function makeSimpleTx() {\n await t.wait(erc20.transfer(userAFunnel, userAAmount, overrides),\n 'erc20 transfer');\n\n // User A Deposit Token.\n const userADepositToken = new Deposit({\n token: 1,\n owner: userA,\n blockNumber: utils.bigNumberify(await t.getBlockNumber()).add(1),\n value: userAAmount,\n });\n const userADepositTokenTx = await t.wait(contract.deposit(userA, erc20.address, overrides),\n 'token deposit', Fuel.errors);\n\n // Set fee stipulations.\n let feeToken = 1;\n let fee = opts.signatureFee || utils.parseEther('.000012');\n let noFee = utils.bigNumberify(fee).lte(0);\n\n // Build the transaction in question.\n return await tx.Transaction({\n override: true,\n chainId: 0,\n witnesses: [\n userAWallet,\n ],\n metadata: [\n tx.MetadataDeposit({\n blockNumber: userADepositToken.properties.blockNumber().get(),\n token: userADepositToken.properties.token().get(),\n }),\n ],\n data: [\n userADepositToken.keccak256(),\n ],\n inputs: [\n tx.InputDeposit({\n owner: userADepositToken.properties\n .owner().get(),\n }),\n ],\n signatureFeeToken: feeToken,\n signatureFee: fee,\n signatureFeeOutputIndex: noFee ? null : 0,\n outputs: [\n tx.OutputTransfer({\n noshift: true,\n token: '0x01',\n owner: producer,\n amount: utils.parseEther('1000.00'),\n }),\n ],\n contract,\n });\n }", "function wrapAction(name, action) {\r\n return function () {\r\n setActivePinia(pinia);\r\n const args = Array.from(arguments);\r\n const afterCallbackList = [];\r\n const onErrorCallbackList = [];\r\n function after(callback) {\r\n afterCallbackList.push(callback);\r\n }\r\n function onError(callback) {\r\n onErrorCallbackList.push(callback);\r\n }\r\n // @ts-expect-error\r\n triggerSubscriptions(actionSubscriptions, {\r\n args,\r\n name,\r\n store,\r\n after,\r\n onError,\r\n });\r\n let ret;\r\n try {\r\n ret = action.apply(this && this.$id === $id ? this : store, args);\r\n // handle sync errors\r\n }\r\n catch (error) {\r\n triggerSubscriptions(onErrorCallbackList, error);\r\n throw error;\r\n }\r\n if (ret instanceof Promise) {\r\n return ret\r\n .then((value) => {\r\n triggerSubscriptions(afterCallbackList, value);\r\n return value;\r\n })\r\n .catch((error) => {\r\n triggerSubscriptions(onErrorCallbackList, error);\r\n return Promise.reject(error);\r\n });\r\n }\r\n // trigger after callbacks\r\n triggerSubscriptions(afterCallbackList, ret);\r\n return ret;\r\n };\r\n }", "static transactionWithOutputs(senderWallet,outputs) {\r\n\t\tconst transaction = new this();\r\n\t\ttransaction.outputs.push(...outputs);\r\n\t\tTransaction.signTransaction(transaction,senderWallet);\r\n\t\treturn transaction;\r\n\t}", "getActions() {\n return Object.keys(this.actions)\n .map(a => this.actions[a]);\n }", "function paymentFactory() {\n\tvar payment = {\n\t\tcNumber: \"\",\n\t\tcType: \"\",\n\t\tCName: \"\",\n\t\tcExp: \"\",\n\t\tcCvv: \"\"\n\t}\n\treturn payment;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: docEdits.mergeCodeBlocks DESCRIPTION: Looks at the last 2 elements of the new srcArray that's being built. Let's call them block1 and block2. Preconditions: block1 and block2 are both enclosed by openDelim and closeDelim block1 and block2 may be safely merged into one block Merges block1 and block2, and stuffs any whitespace between block1's closeDelim and block2's openDelim at the end of the combined block. Pushes the combined block back into the srcArray, in place of the 2 original blocks. ARGUMENTS: RETURNS: nothing
function docEdits_mergeCodeBlocks(srcArray, openDelim, closeDelim) { var pattern, myRe, match, whiteSpace, innerWhiteSpace, retval = ""; var eolCount = 0, i; var block2 = srcArray.pop(); var block1 = srcArray.pop(); var before = ""; var block1New = ""; pattern = "(\\s*)" + dwscripts.escRegExpChars(closeDelim) + "([\\s|(?:&nbsp;)]*)$"; myRe = new RegExp(pattern, "i"); match = block1.match(myRe); if (match) { innerWhiteSpace = match[1]; whiteSpace = match[2]; i = block1.lastIndexOf(openDelim); before = block1.substring(0, i); block1New = block1.substring(i, match.index); pattern = "^([\\s|(?:&nbsp;)]*)" + dwscripts.escRegExpChars(openDelim) + "(\\s*)"; myRe = new RegExp(pattern, "i"); match = block2.match(myRe); if (match) { whiteSpace += match[1]; innerWhiteSpace += match[2]; //ensure separation of at least 2 newlines between code blocks for (i = 0; i < innerWhiteSpace.length; i++) { var tempChar = innerWhiteSpace.charAt(i); if (tempChar == "\n" || tempChar == "\r") { eolCount++; // If using windows style newline, "\r\n", need to step past '\n'. if ( tempChar == "\r" && (i + 1 < innerWhiteSpace.length) && innerWhiteSpace.charAt(i + 1) == "\n" ) { ++eolCount; } } } for (i = eolCount; i < 2; i++) { innerWhiteSpace += dwscripts.getNewline(); } retval = before + whiteSpace + block1New + innerWhiteSpace + block2.substring(match[0].length); srcArray.push(retval); } } // If we couldn't merge, push the two blocks back onto the array if (!retval) { srcArray.push(block1); srcArray.push(block2); } }
[ "function docEdits_deleteCodeBlock(srcArray, docEditNode)\n{\n var pattern, myRe, pos;\n\n var whiteSpace = \" \\f\\n\\r\\t\\v\";\n\n var bPutCloseDelim = false;\n var bPutOpenDelim = false;\n\n var bPutStartingEOL = true\n var bPutEndingEOL = true;\n\n var node = docEditNode.priorNode;\n var thisNode = dwscripts.getOuterHTML(node);\n\n var openDelim = docEditNode.mergeDelims[0];\n var closeDelim = docEditNode.mergeDelims[1];\n\n // Deal with the open delimiter\n\n var lastChunk = srcArray.pop();\n\n pattern = dwscripts.escRegExpChars(openDelim) + \"\\\\s*$\";\n myRe = new RegExp (pattern, \"i\");\n\n pos = lastChunk.search(myRe);\n if (pos == -1)\n {\n // Starting delim was not found at the end of the previous block,\n // so we try to figure out which spaces and new lines to preserve\n\n pos = lastChunk.length - 1;\n\n // Preserve spaces and tabs up to the first newline after the participant's\n // insert text. Strip all other whitespace after that.\n\n // backup until we hit a character that is not a new line\n while ((pos >= 0) && (\"\\r\\n\".indexOf( lastChunk.charAt(pos) ) != -1))\n {\n pos--;\n }\n\n // if we found this position, add the last chuck back,\n // without the new lines\n if (pos > -1)\n {\n srcArray.push(lastChunk.substring(0, pos+1));\n }\n\n // Indicate that we need the close delim, becuase\n // we did not remove the opening delim\n bPutCloseDelim = true;\n\n // now look for the delim at the start of the node we are deleting from\n pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(openDelim) + \"(\\\\s*)\";\n if (thisNode.search(new RegExp(pattern,\"i\")) != -1 &&\n RegExp.$1.indexOf(\"\\n\") == -1 &&\n RegExp.$1.indexOf(\"\\r\") == -1\n )\n {\n // we found the open delim, and there are newlines after it\n bPutEndingEOL = false;\n }\n }\n else\n {\n // We found the end delim at the end of the previous block\n\n if (pos > 0)\n {\n // add the chunk back, minus the opening delim\n srcArray.push(lastChunk.substring(0, pos));\n }\n else\n {\n // If pos equals zero, do nothing, becuase the entire previous\n // block should be removed\n }\n }\n\n\n // Deal with the close delimiter\n\n var nodeRange = dwscripts.getNodeOffsets(node);\n var afterParticipant = docEdits.allSrc.substring(docEditNode.replacePos, nodeRange[1]);\n\n pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(closeDelim) + \"\\\\s*$\";\n myRe = new RegExp (pattern, \"i\");\n\n pos = afterParticipant.search(myRe);\n if (pos == -1)\n {\n // the close delim was not the only thing found\n // after the code we are removing\n while (whiteSpace.indexOf( this.allSrc.charAt(docEditNode.replacePos) ) != -1 && docEditNode.replacePos <= this.allSrc.length)\n {\n docEditNode.replacePos++;\n }\n\n // Need an open delim, becuase we did not remove the close delim\n bPutOpenDelim = true;\n\n // search for the close delim at the end of the the block\n // we are updating\n pattern = \"(\\\\s*)\" + dwscripts.escRegExpChars(closeDelim) + \"\\\\s*$\";\n if (afterParticipant.search(new RegExp(pattern,\"i\"))!= -1 &&\n RegExp.$1.indexOf(\"\\n\") == -1 &&\n RegExp.$1.indexOf(\"\\r\") == -1\n )\n {\n // there were newlines before the close delim, so\n // add one back.\n bPutStartingEOL = false;\n }\n }\n else\n {\n // Only the close delim was found after this, so set the replace pos\n // to after the current node.\n docEditNode.replacePos = nodeRange[1];\n }\n\n\n\n if (bPutCloseDelim && bPutOpenDelim)\n {\n // neither operation removed a delim, so just add newlines\n srcArray.push(docEdits.strNewlinePref + docEdits.strNewlinePref);\n }\n else if (bPutCloseDelim)\n {\n // we need a close delim, becuase the open was not removed,\n // but the close was\n var eol = bPutEndingEOL ? docEdits.strNewlinePref : \" \";\n srcArray.push(eol + closeDelim);\n }\n else if (bPutOpenDelim)\n {\n // we need an open delim, becuase the close was not removed,\n // but the open was\n var eol = bPutStartingEOL ? docEdits.strNewlinePref : \" \";\n srcArray.push(openDelim + eol);\n }\n}", "function docEdits_canMergeBlock(insertText)\n{\n var retVal = null;\n\n var dom = dw.getDocumentDOM();\n var delimInfo = dom.serverModel.getDelimiters();\n var myDelim;\n\n // Create the mergePattern and noMergePatterns\n\n var mergePattern = \"^\\\\s*(?:\";\n var noMergePattern = \"^\\\\s*(\";\n var len1 = mergePattern.length;\n var len2 = noMergePattern.length;\n\n if (delimInfo && delimInfo.length && insertText && insertText.length)\n {\n for (var i=0; i < delimInfo.length; i++)\n {\n myDelim = delimInfo[i];\n if (myDelim.participateInMerge)\n {\n if (mergePattern.length > len1)\n {\n mergePattern += \"|\";\n }\n mergePattern += \"(?:(\" + myDelim.startPattern + \")[\\\\S\\\\s]*(\" + myDelim.endPattern + \"))\";\n }\n else\n {\n if (noMergePattern.length > len2)\n {\n noMergePattern += \"|\";\n }\n noMergePattern += \"(\" + myDelim.startPattern + \"[\\\\S\\\\s]*\" + myDelim.endPattern + \")\";\n }\n }\n\n // Check the insertText to determine if it can participate in a merge\n\n var mergeRe = null;\n var noMergeRe = null;\n\t\n\tif( mergePattern.length > len1 ){\n\t\ttry{\t\n\t\t\tmergePattern += \")\\\\s*$\";\n\t\t\tmergeRe= new RegExp (mergePattern, \"i\");\n\t\t} \n\t\tcatch(e){\n\t\t\talert( e.description );\n\t\t\tmergeRe = null;\n\t\t}\n\t}\n\tif( noMergePattern.length > len2 ){\n\t\ttry{\t\n\t\t\tnoMergePattern += \")\\\\s*$\";\n\t\t\tnoMergeRe= new RegExp (noMergePattern, \"i\");\n\t\t} \n\t\tcatch(e){\n\t\t\talert( e.description );\n\t\t\tnoMergeRe = null;\n\t\t}\n\t}\n\n if (mergeRe != null && (noMergeRe == null || !noMergeRe.test(insertText))) //exclude non-mergeable blocks\n {\n var match = insertText.match(mergeRe); //try to extract delims\n if (match)\n {\t\t\t\n for (var i=0; i < delimInfo.length; i++)\n {\n //check the sub-expression pairs stating at item 1\n if (match[2*i+1] && match[2*i+2] && match[2*i+1].length > 0 && match[2*i+2].length > 0)\n {\n var retVal = new Array();\n retVal.push(match[2*i+1]);\n retVal.push(match[2*i+2]);\n break;\n }\n }\n }\n }\n }\n\n return retVal;\n}", "function handleBlock(startArr, startOffsetM, startOffsetNextM, destArr, destOffsetM, destOffsetNextM, undefined){\n\n // slice out the block we need\n var startArrTemp = startArr.slice(startOffsetM, startOffsetNextM || undefined)\n , destArrTemp = destArr.slice( destOffsetM, destOffsetNextM || undefined)\n\n var i = 0\n , posStart = {pos:[0,0], start:[0,0]}\n , posDest = {pos:[0,0], start:[0,0]}\n\n do{\n\n // convert shorthand types to long form\n startArrTemp[i] = simplyfy.call(posStart, startArrTemp[i])\n destArrTemp[i] = simplyfy.call(posDest , destArrTemp[i])\n\n // check if both shape types match\n if(startArrTemp[i][0] != destArrTemp[i][0] || startArrTemp[i][0] == 'M') {\n\n // if not, convert shapes to beziere\n startArrTemp[i] = toBeziere.call(posStart, startArrTemp[i])\n destArrTemp[i] = toBeziere.call(posDest , destArrTemp[i])\n\n } else {\n\n // only update positions otherwise\n startArrTemp[i] = setPosAndReflection.call(posStart, startArrTemp[i])\n destArrTemp[i] = setPosAndReflection.call(posDest , destArrTemp[i])\n\n }\n\n // we are at the end at both arrays. stop here\n if(++i == startArrTemp.length && i == destArrTemp.length) break\n\n // destArray is longer. Add one element\n if(i == startArrTemp.length){\n startArrTemp.push([\n 'C',\n posStart.pos[0],\n posStart.pos[1],\n posStart.pos[0],\n posStart.pos[1],\n posStart.pos[0],\n posStart.pos[1],\n ])\n }\n\n // startArr is longer. Add one element\n if(i == destArrTemp.length){\n destArrTemp.push([\n 'C',\n posDest.pos[0],\n posDest.pos[1],\n posDest.pos[0],\n posDest.pos[1],\n posDest.pos[0],\n posDest.pos[1]\n ])\n }\n\n\n }while(true)\n\n // return the updated block\n return {start:startArrTemp, dest:destArrTemp}\n}", "changedRange(blockToCompare) {\n let startIndex = 0;\n let differencesFound = false;\n while (startIndex < this.tokens.length &&\n startIndex < blockToCompare.tokens.length) {\n if (!this.tokens[startIndex].contentEquals(\n blockToCompare.tokens[startIndex])) {\n differencesFound = true;\n break;\n }\n ++startIndex;\n }\n if (!differencesFound) {\n if (this.tokens.length !== blockToCompare.tokens.length) {\n return [startIndex, this.tokens.length,\n startIndex, blockToCompare.tokens.length];\n }\n return null;\n }\n let endOffset = 0;\n while (this.tokens[this.tokens.length - endOffset - 1].contentEquals(\n blockToCompare.tokens[blockToCompare.tokens.length - endOffset - 1])) {\n if (endOffset === this.tokens.length - 1 ||\n endOffset === blockToCompare.tokens.length - 1) {\n break;\n }\n ++endOffset;\n }\n if (this.tokens.length - endOffset <= startIndex ||\n blockToCompare.tokens.length - endOffset <= startIndex) {\n endOffset = Math.min(this.tokens.length - startIndex - 1,\n blockToCompare.tokens.length - startIndex - 1);\n }\n return [startIndex, this.tokens.length - endOffset,\n startIndex, blockToCompare.tokens.length - endOffset];\n }", "function check_blockquote(blocks) {\n var patt = /^>\\s(.*)$/;\n var match;\n\n for (var b = 0; b < blocks.length; b++) {\n if (blocks[b].tag == null) {\n var content = blocks[b].content;\n for (var l = 0; l < content.length; l++) {\n if ((match = patt.exec(content[l])) != null) {\n var inner_content = '';\n var same_block = true; //Keeps track of inner blockquote blocks\n for (var end = l; end < content.length; end++) {\n if ((match = patt.exec(content[end])) != null) {\n inner_content += match[1] + '\\n';\n same_block = true;\n }\n else if (content[end].trim().length == 0) { //End of block may mean end of blockquote\n inner_content += '\\n';\n same_block = false;\n } else if (same_block) { inner_content += content[end] + '\\n'; }\n else { break; }\n }\n inner_content = parse_blocks(inner_content, false);\n\n var raw1 = {content:content.slice(0,l)};\n var blockquote = {tag:'blockquote', content:inner_content};\n var raw2 = {content:content.slice(end,content.length)};\n\n blocks.splice(b, 1, raw1, blockquote, raw2);\n b++;\n break;\n }\n }\n }\n }\n}", "function DocEdit_formatForMerge()\n{\n if (!this.dontFormatForMerge && !this.dontMerge && !this.preventMerge &&\n this.mergeDelims && this.mergeDelims.length &&\n (!this.weight || this.weight.indexOf(\"nodeAttribute\") == -1)\n )\n {\n var escStartDelim = dwscripts.escRegExpChars(this.mergeDelims[0]);\n var escEndDelim = dwscripts.escRegExpChars(this.mergeDelims[1]);\n\n // Preserve spaces and tabs before the first newline before the end delimeter.\n var pattern = \"^\\\\s*\" + escStartDelim + \"\\\\s*([\\\\S\\\\s]*[^\\\\r\\\\n])\\\\s*\" + escEndDelim + \"\\\\s*$\";\n this.text = this.text.replace(new RegExp(pattern,\"i\"),\n this.mergeDelims[0] + docEdits.strNewlinePref +\n \"$1\" + docEdits.strNewlinePref + this.mergeDelims[1]);\n }\n}", "placeBlocks(blocks) {\n\t\tblocks.forEach(b => this.placeBlockAt(b));\n\t}", "function applyTransformationRuleMultilineDelThenIns (diff) {\n let transformedDiff = []\n\n const B_ADDED = 'added'\n const B_REMOVED = 'removed'\n const B_SAME = 'same'\n\n let previousBlockType = null\n let currentBlockType = null\n let previousBlockWasMultiline = false\n let currentBlockIsMultiline = false\n\n // iterate the input tokens to create the intermediate representation\n diff.forEach((currentBlock) => {\n previousBlockType = currentBlockType\n previousBlockWasMultiline = currentBlockIsMultiline\n currentBlockType = (currentBlock.added ? B_ADDED : (currentBlock.removed ? B_REMOVED : B_SAME))\n currentBlockIsMultiline = isMultilineDiffBlock(currentBlock)\n\n // transform rule 1 applys when:\n // the previous block was a del and had multiple lines\n // the current block is an ins\n if (previousBlockType === B_REMOVED && currentBlockType === B_ADDED && previousBlockWasMultiline) {\n // split the first line from the current block\n let currentBlockSplit = splitMultilineDiffBlock(currentBlock)\n\n // pop the previous diff entry\n let previousBlock = transformedDiff.pop()\n\n // split the first line from the previous block\n let previousBlockSplit = splitMultilineDiffBlock(previousBlock)\n\n // now add the blocks back, interleaving del and ins blocks\n for (let i = 0; i < Math.max(previousBlockSplit.length, currentBlockSplit.length); i++) {\n if (i < previousBlockSplit.length) {\n transformedDiff.push(previousBlockSplit[i])\n }\n if (i < currentBlockSplit.length) { transformedDiff.push(currentBlockSplit[i]) }\n }\n } else {\n // otherwise, we just add the current block to the transformed list\n transformedDiff.push(currentBlock)\n }\n })\n\n return transformedDiff\n}", "function EndTextBlock() {\n\tif (arguments.length != 0) {\n\t\terror('Error 110: EndTextBlock(); must have empty parentheses.');\n\t}\n\telse if (EDITOR_OBJECT == null ) {\n\t\terror(\t'Error 111: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if ( !(EDITOR_OBJECT instanceof text_block) ) {\n\t\terror(\t'Error 112: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if (!ERROR_FOUND) {\n\t\tvar current_text_block = EDITOR_OBJECT;\n\t\tvar block_html = \t'<span class=\"' + \n\t\t\t\t\t\t\tcurrent_text_block.class + \n\t\t\t\t\t\t\t'\" ' + \n\t\t\t\t\t\t\tcurrent_text_block.html + '\">';\n\n\t\tfor (j = 0; j < current_text_block.content.length; j++) {\n\t\t\tvar item = current_text_block.content[j];\n\t\t\tblock_html += item.html;\n\t\t}\n\n\t\tcurrent_text_block.html = block_html + '</span>';\n\t\tEDITOR_OBJECT = EDITOR_STACK.pop();\n\t\tconsole.log(block_html);\n\t}\n}", "function docEdits_apply()\n{\n // DEBUG var DEBUG_FILE = dw.getSiteRoot() + \"dwscripts_DEBUG.txt\";\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits_apply()\\n-----------------\\n\");\n var maintainSelection = arguments[0] || false; //optional: if true we will attempt maintain the current selection\n var dontReformatHTML = arguments[1] || false; //optional: if true we will prevent the code reformatter from running\n var tagSelection = null;\n\n var dom = dw.getDocumentDOM();\n\n docEdits.allSrc = dom.documentElement.outerHTML;\n docEdits.strNewlinePref = dwscripts.getNewline();\n \n try\n {\n if (maintainSelection)\n {\n tagSelection = extUtils.getTagSelection();\n }\n\n // Make sure weights are in order\n docEdits.sortWeights();\n\n // Process the queued edits\n for (var i=0; i < docEdits.editList.length; i++) //with each object with something to insert\n {\n var editObj = docEdits.editList[i];\n\n // set the properties of the DocEdit object needed for apply\n editObj.processForApply(i);\n \n } // end loop\n\n // We are now ready to create the new outerHTML string\n\n if (docEdits.editList.length > 0)\n {\n // Make sure our edits are in order\n docEdits.sortInserts();\n\n dw.useTranslatedSource(false);\n\n newSrc = new Array();\n\n var info = new Object();\n info.lastInsert = 0;\n info.bPendingMerge = false;\n info.bDoMergeNow = false;\n\n for (var i=0; i < docEdits.editList.length; i++)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"] = \" + docEdits.editList[i].toString() + \"\\n--\\n\",\"append\");\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"].weight = \" + docEdits.editList[i].weight + \"\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos != null)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"insert at \"+info.lastInsert+\",\"+docEdits.editList[i].insertPos+\":\"+docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos)+\": plus :\"+ docEdits.editList[i].text+ \"\\n\\ndontPreprocessText = \" + docEdits.editList[i].dontPreprocessText + \"\\n\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos > info.lastInsert)\n {\n // add the text between the end of the last edit, and our new edit\n var betweenEditsStr = docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos);\n \n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (betweenEditsStr.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n\n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(betweenEditsStr);\n\n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n info.bPendingMerge = false;\n }\n }\n\n if (!docEdits.editList[i].text && docEdits.editList[i].mergeDelims)\n {\n info.bDoMergeNow = false;\n\n docEdits.deleteCodeBlock(newSrc, docEdits.editList[i]);\n }\n else\n {\n // set the bPendingMerge and bDoMergeNow flags\n docEdits.analyzeMerge(info, i);\n }\n\n\n if (docEdits.editList[i].text.length > 0)\n {\n // When inserting HTML along with server markup, attempt to\n // convert to XHTML if necessary. The \"if necessary\" part is \n // determined by four criteria, each of which must be met:\n // 1. The doctype of the user's document is XHTML Transitional\n // or XHTML Strict;\n // The weight of the edit we're performing:\n // 2. Must NOT be aboveHTML;\n // 3. Must NOT be nodeAttribute;\n // 4. Must NOT be belowHTML.\n // (Any of the above weights indicates server code, which must\n // not be converted because characters such as \" will be entity-\n // encoded.)\n \n // Get the weight of the edit\n var weight = docEdits.editList[i].weight;\n if (!weight) weight = \"\";\n \n // Sometimes it's a word that follows the plus\n // sign, not a number. Check for that case.\n var plus = weight.indexOf('+');\n if (plus != -1)\n weight = weight.substring(0,plus);\n \n // Do a final check for any digits or + signs (e.g., \"aboveHTML+30\"\n // will become \"aboveHTML\")\n var weightType = weight.replace(/[\\d\\+]/g,\"\");\n\n //DEBUG DWfile.write(DEBUG_FILE,\"\\n--\\ndocEdits.editList[i].weight = \" + docEdits.editList[i].weight + \"\\nweightType = \" + weightType + \"\\n--\\n\",\"append\"); \n if (newSrc.length == 0)\n {\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n // if we are adding the first text to newSrc, then remove\n // any newlines from the start of the text.\n var insertStr = docEdits.editList[i].text.replace(/^[\\r\\n]+/, \"\");\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" +insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n RegExp.multiline = oldMultiline;\n }\n else\n {\n var insertStr = docEdits.editList[i].text;\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" + insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n }\n }\n\n\n if (info.bDoMergeNow)\n {\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[i].mergeDelims[0], docEdits.editList[i].mergeDelims[1]);\n }\n\n if (docEdits.editList[i].replacePos)\n {\n info.lastInsert = docEdits.editList[i].replacePos;\n }\n else\n {\n info.lastInsert = docEdits.editList[i].insertPos;\n }\n }\n\n } // end loop\n\n if (info.lastInsert < docEdits.allSrc.length)\n {\n // add the rest of the original source\n var restOrigSource = docEdits.allSrc.substring(info.lastInsert);\n\n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (restOrigSource.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n \n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(restOrigSource);\n\n \n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n }\n }\n \n // DEBUG\n // alert(\"The new document source is:\\n\\n\" + newSrc.join(\"\"));\n \n //dom.documentElement.outerHTML = newSrc.join(\"\");\n if (dontReformatHTML)\n dom.setOuterHTML(newSrc.join(\"\"), false);\n else\n\t\tdom.setOuterHTML(newSrc.join(\"\"), true);\n\n\n // alert(\"After source formatting:\\n\\n\" + dom.documentElement.outerHTML );\n\n if (tagSelection)\n {\n extUtils.setTagSelection(tagSelection);\n }\n }\n }\n finally\n {\n // The commit of edits is complete or we encountered an exception. In either case,\n // clear out the class members to prepare for the next set of edits.\n docEdits.clearAll();\n }\n}", "function splitMultilineDiffBlock ({added, removed, value}) {\n let lines = value.split('\\n')\n let blocks = []\n// lines = lines.filter(line=>line.length>0)\n lines.forEach((line, index) => {\n blocks.push({added, removed, value: line})\n if (index < lines.length - 1) blocks.push({value: '\\n'})\n })\n\n return blocks\n}", "function applyTransformationRuleBreakUpDelIns (diff) {\n let transformedDiff = []\n\n const B_ADDED = 'added'\n const B_REMOVED = 'removed'\n const B_SAME = 'same'\n let blockType = null\n let blockIsMultiline = false\n\n // iterate the input tokens to create the intermediate representation\n diff.forEach((block) => {\n blockType = (block.added ? B_ADDED : (block.removed ? B_REMOVED : B_SAME))\n blockIsMultiline = isMultilineDiffBlock(block)\n\n // transform rule applys when:\n // the current block is an ins or del and is multiline\n if ((blockType === B_REMOVED || blockType === B_ADDED) && blockIsMultiline) {\n // split the first line from the current block\n let blockSplit = splitMultilineDiffBlock(block)\n\n blockSplit.forEach(blockSplitLine => transformedDiff.push(blockSplitLine))\n } else {\n // otherwise, we just add the current block to the transformed list\n transformedDiff.push(block)\n }\n })\n\n return transformedDiff\n}", "function mergeFormats(formats) {\n if (mergeFormats.formats === formats) {\n return mergeFormats.newFormats;\n }\n\n var newFormats = formats ? [format].concat(Object(__WEBPACK_IMPORTED_MODULE_1__babel_runtime_helpers_esm_toConsumableArray__[\"a\" /* default */])(formats)) : [format];\n mergeFormats.formats = formats;\n mergeFormats.newFormats = newFormats;\n return newFormats;\n } // Since the formats parameter can be `undefined`, preset", "function parseBlock() {\n var label = t.identifier(getUniqueName(\"block\"));\n var blockResult = null;\n var instr = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n label = identifierFromToken(token);\n eatToken();\n } else {\n label = t.withRaw(label, \"\"); // preserve anonymous\n }\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n\n if (lookaheadAndCheck(_tokenizer.keywords.result) === true) {\n eatToken();\n blockResult = token.value;\n eatToken();\n } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // Instruction\n instr.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in block body of type\" + \", given \" + tokenToString(token));\n }();\n }\n\n maybeIgnoreComment();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.blockInstruction(label, instr, blockResult);\n }", "function populateWithCodeblocks(element) {\r\n // Clear the select of any pre-existing options.\r\n element.html(\"\");\r\n\r\n // Iterate over the codeblocks and add one for each codeblock.\r\n jQuery.each(codeblocks, function(key, value) {\r\n if (value) {\r\n element.append(jQuery('<option>', {\r\n value : key\r\n }).text(value.block_name));\r\n }\r\n });\r\n}", "function getBlocks(args) {\n // Get all blocks (avoid deprecated warning).\n var blocks = select('core/block-editor').getBlocks(); // Append innerBlocks.\n\n var i = 0;\n\n while (i < blocks.length) {\n blocks = blocks.concat(blocks[i].innerBlocks);\n i++;\n } // Loop over args and filter.\n\n\n for (var k in args) {\n blocks = blocks.filter(function (block) {\n return block.attributes[k] === args[k];\n });\n } // Return results.\n\n\n return blocks;\n } // Data storage for AJAX requests.", "insertNewUnstyledBlock(editorState) {\n const selection = editorState.getSelection();\n let newContent = Modifier.splitBlock(\n editorState.getCurrentContent(),\n selection,\n );\n const blockMap = newContent.getBlockMap();\n const blockKey = selection.getStartKey();\n const insertedBlockKey = newContent.getKeyAfter(blockKey);\n\n const newBlock = blockMap\n .get(insertedBlockKey)\n .set('type', BLOCK_TYPE.UNSTYLED);\n\n newContent = newContent.merge({\n blockMap: blockMap.set(insertedBlockKey, newBlock),\n });\n\n return EditorState.push(editorState, newContent, 'split-block');\n }", "function combine(first, second, offset) {\n let blocksInFirst = cleaner.listLength(first[\"blocks\"]);\n let output = first;\n if (first[\"palette\"] && second[\"palette\"]) {\n let secondBlocksLength = cleaner.listLength(second[\"blocks\"]);\n for (let i = 0; i < secondBlocksLength; i++) {\n second[\"blocks\"][i][\"state\"] = add(second[\"blocks\"][i][\"state\"], first[\"palette\"].length);\n for (let k = 0; k < 3; k++)\n second[\"blocks\"][i][\"pos\"][k] = add(second[\"blocks\"][i][\"pos\"][k], offset[k]);\n }\n output[\"palette\"] = first[\"palette\"].concat(second[\"palette\"]);\n output[\"blocks\"] = cleaner.concatLists(first[\"blocks\"], second[\"blocks\"]);\n }\n else {\n first = makeMultiple(first);\n second = makeMultiple(second);\n\n let secondBlocksLength = cleaner.listLength(second[\"blocks\"]);\n for (let i = 0; i < secondBlocksLength.length; i++) {\n second[\"blocks\"][i][\"state\"] = add(second[\"blocks\"][i][\"state\"], first[\"palettes\"][0].length);\n for (let k = 0; k < 3; k++)\n second[\"blocks\"][i][\"pos\"][k] = add(second[\"blocks\"][i][\"pos\"][k], offset[k]);\n }\n output[\"blocks\"] = cleaner.concatLists(first[\"blocks\"], second[\"blocks\"]);\n\n let firstPalettes = first[\"palettes\"];\n output[\"palettes\"] = [];\n //no need to check for empty; palettes should always have at least 1 element\n for (let i = 0; i < firstPalettes.length; i++)\n for (let k = 0; k < second[\"palettes\"].length; k++)\n output[\"palettes\"].push(firstPalettes[i].concat(second[\"palettes\"][k]));\n }\n let secondEntitiesLength = cleaner.listLength(second[\"entities\"]);\n for (let i = 0; i < secondEntitiesLength.length; i++) {\n for (let k = 0; k < 3; k++) {\n second[\"entities\"][i][\"pos\"][k] = add(second[\"entities\"][i][\"pos\"][k], offset[k]);\n second[\"entities\"][i][\"blockPos\"][k] = add(second[\"entities\"][i][\"blockPos\"][k], offset[k]);\n }\n }\n output[\"entities\"] = cleaner.concatLists(output[\"entities\"], second[\"entities\"]);\n\n if (blocksInFirst > 0) {\n let positions = [];\n let outputBlocksLength = cleaner.listLength(output[\"blocks\"]);\n for (let i = blocksInFirst; i < outputBlocksLength.length; i++) {\n positions.push(output[\"blocks\"][i][\"pos\"]);\n }\n //remove collisions\n for (let i = blocksInFirst - 1; i >= 0; i--)\n if (positions.find((item) =>\n item[0] == output[\"blocks\"][i][\"pos\"][0] &&\n item[1] == output[\"blocks\"][i][\"pos\"][1] &&\n item[2] == output[\"blocks\"][i][\"pos\"][2])) {\n output[\"blocks\"].splice(i, 1);\n }\n }\n\n return output;\n}", "function buildProblemBlocks(problemFormat, blocks, container, ids, placeholders, sample_text) {\n var placeholder_height = false;\n if(placeholders) {\n var max_vertical_blocks = blocks.length;\n for(var b = 0; b < blocks.length; b++) {\n if(typeof blocks[b] === \"object\") {\n max_vertical_blocks += blocks[b].height - 1;\n }\n }\n placeholder_height = 100/max_vertical_blocks;\n }\n //Go through the vertical pieces one by one\n for(var b = 0; b < blocks.length; b++) {\n var block = blocks[b];\n if(typeof block === \"string\") { //This is a basic block\n var id = BLOCK_ID[block.toLowerCase()];\n var block_div = null;\n if(ids) {\n block_div = document.getElementById(id);\n }\n block_div = block_div || document.createElement(\"div\");\n block_div.className = \"problem-block\";\n //Set its id so we can fill its contents later\n if(ids) {\n block_div.id = id;\n } else if(block == \"hints\") {\n //because this only executes for ids == false, it won't run on actual problems\n //hints have a specific font just for them, because reasons\n $(block_div).addClass(\"hint\");\n $(block_div).addClass(\"hint-content\");\n }\n //Set extra style defined in problemFormat, if there is any\n if(problemFormat[block]) {\n for(var style_prop in problemFormat[block]) {\n block_div.style[style_prop] = problemFormat[block][style_prop];\n }\n }\n //The block below would make it lay out as if it were full-sized,\n // but it made the text too small to really see...\n // if(sample_text) {\n // var font_size = parseInt(block_div.style.fontSize || \"16px\");\n // block_div.style.fontSize = (font_size/3) + \"px\";\n // }\n if(placeholders) {\n block_div.style.height = placeholder_height + \"%\";\n if(!sample_text) {\n //These images make seeing the text very hard\n block_div.style.backgroundImage = \"url('images/QuickAuthPlaceholder-\" + id + \".png')\";\n block_div.style.backgroundSize = \"100% 100%\";\n }\n }\n if(sample_text) {\n block_div.innerHTML = block + \" ipsum<br/>dolor sit amet\";\n block_div.style.overflow = \"hidden\";\n }\n container.appendChild(block_div);\n } else { //This is a pair of columns\n buildProblemColumn(problemFormat, block.right, container, \"columnR\",\n 100-block.width, block.height, ids, placeholder_height, sample_text);\n buildProblemColumn(problemFormat, block.left, container, \"columnL\",\n block.width, block.height, ids, placeholder_height, sample_text);\n //Add a clear element at the bottom to force everything afterwards to be below the columns\n var clear = document.createElement(\"div\");\n clear.className = \"clear\";\n container.appendChild(clear);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checkShipToAddress update ship to address checkbox UI to checked state
function checkShipToAddress() { updateSelectedCheckboxView($.ship_to_address_checkbox); }
[ "function checkShipToStore() {\n updateSelectedCheckboxView($.ship_to_current_store_checkbox);\n}", "toggleCheckbox() {\n this.setState({\n saveShippingInfo: !this.state.saveShippingInfo\n });\n }", "function changeStateCheckBox() {\n checkedElements = [];\n // add items which are checked\n for (id of CHECKBOX_NAMES) {\n if (isChecked(id)) {\n checkedElements.push(id);\n }\n }\n updateBoard();\n}", "function markCheckboxes() {\n let check = (id) => {\n if (settings[id] == 'true') {\n $('#' + id).prop('checked', true);\n }\n }\n check('hide-hr-value');\n check('hide-upgrade-log');\n check('value-with-quantity');\n check('only-show-equipped');\n }", "slaveCheckboxChanged() {\n const allCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']\"\n ).length;\n const checkedCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']:checked\"\n ).length;\n\n let masterCheckbox = document.querySelector(\"input[name='all']\");\n masterCheckbox.checked = allCheckboxesLength === checkedCheckboxesLength;\n\n // make button visible if any checkbox is checked\n this.setState({\n masterCheckboxVisibility: Boolean(checkedCheckboxesLength),\n });\n }", "function alert_state() {\n var cb = document.getElementById('add_marker_CBX');\n \n console.log(cb.checked);\n}", "async setShippingAddress(address) {\n const response = await api.shopperBaskets.updateShippingAddressForShipment({\n body: address,\n parameters: {\n basketId: basket.basketId,\n shipmentId: 'me',\n useAsBilling: !basket.billingAddress\n }\n })\n\n setBasket(response)\n }", "handleCheckboxChange(friendId, event){\n this.setState({ checkboxChecked: event.target.checked});\n if(event.target.checked)\n this.props.addFriendToInviteList(friendId);\n else\n this.props.removeFriendFromInviteList(friendId);\n }", "function tiendaDisableShippingAddressControls(checkbox, form)\r\n{\r\n \r\n\tvar disable = false;\r\n if (checkbox.checked){\r\n disable = true;\r\n tiendaGetShippingRates( 'onCheckoutShipping_wrapper', form );\r\n }\r\n \r\n var fields = \"address_name;address_id;title;first_name;middle_name;last_name;company;tax_number;address_1;address_2;city;country_id;zone_id;postal_code;phone_1;phone_2;fax\";\r\n var fieldList = fields.split(';');\r\n\r\n// for(var index=0;index<fieldList.length;index++){\r\n// shippingControl = document.getElementById('shipping_input_'+fieldList[index]);\r\n// if(shippingControl != null){\r\n// shippingControl.disabled = disable;\r\n// }\r\n// }\r\n \r\n for(var index=0;index<fieldList.length;index++){\r\n \tbillingControl = document.getElementById('billing_input_'+fieldList[index]);\r\n shippingControl = document.getElementById('shipping_input_'+fieldList[index]);\r\n if(shippingControl != null){\r\n \t\tshippingControl.disabled = disable; \r\n if(billingControl != null)\r\n {\r\n \tif( fieldList[index] == 'zone_id' ) // special care for zones\r\n \t{\r\n \t\tif( disable )\r\n \t\t\ttiendaDoTask( 'index.php?option=com_tienda&format=raw&controller=checkout&task=getzones&prefix=shipping_input_&disabled=1&country_id='+document.getElementById('billing_input_country_id').value+'&zone_id='+document.getElementById('billing_input_zone_id').value, 'shipping_input_zones_wrapper', '');\r\n \t\telse\r\n \t\t\tshippingControl.disabled = false;\r\n \t}\r\n \telse // the rest of fields is OK the way they are handled now\r\n \t\t{\r\n \t\t\tif( shippingControl.getAttribute( 'type' ) != 'hidden' )\r\n \t\t\t\tshippingControl.value = disable ? billingControl.value : ''; \t\t\r\n \t\t}\r\n }\r\n }\r\n }\r\n \r\n tiendaDeleteGrayDivs();\r\n}", "handleIpv6Add() {\n if (this.state.ipv6LinkClicked === 0) {\n MY_GLOBAL.headersSelected.push(\"IPv6\");\n this.setState((prev) => ({\n headersCheckboxed: [...prev.headersCheckboxed, false],\n ipv6LinkClicked: 1,\n }));\n }\n }", "function updateEmailMarkList() {\n\tvar isAllChecked = true;\n var chkBoxId = this.name;\n var partialchkBoxId = chkBoxId.substring(0,chkBoxId.indexOf('_'));\n var emailAllDivs = document.getElementsBySelector(\"span.citation-send\");\n\tfor(var i=0;i<emailAllDivs.length;i++){\n\t\tvar emailAll = emailAllDivs[i].getElementsByTagName(\"INPUT\")[0];\n if (\"sendAllEmailOption\" != emailAll.id) {\n var partialId = emailAll.name.substring(0,emailAll.name.indexOf('_'));\n if (partialchkBoxId == partialId) {\n if (emailAll.checked == false){\n isAllChecked = false;\n break;\n }\n }\n }\n }\n\t$(\"#sendAllEmailOption\").attr('checked', isAllChecked);\n}", "function setCheckdiv(clicked,check) {\n var checkbox =$(clicked).find(\".checkdiv-checkbox\");\n // Flip state if set_state is unspecified:\n if (check===undefined) {\n check = !(checkbox.data(\"state\"));\n }\n //console.log(\"check: \" + check);\n //console.log(checkbox.data(\"state\"));\n checkbox.data(\"state\",check);\n //console.log(checkbox.data(\"state\"));\n // Apply appropriate styles to checkbox:\n if (check) {\n //console.log(\"check did exist\");\n checkbox.css(\"background-color\",\"#808080\");\n }\n else {\n //console.log(\"check didn't exist\");\n checkbox.css(\"background-color\",\"#F1F1F1\");\n }\n}", "function toggleInputsStates(inputs,checkedState) {\n\tinputs.each(function() {\n\t\t$(this).prop(\"checked\",checkedState);\n\t});\t\n}", "function handleCheck(e) {\n\t\tsetIsComplete(e.target.checked)\n\t}", "function ShippingAddress() {\n const { values } = useFormikContext();\n const sectionFormikData = useFormikMemorizer(SHIPPING_ADDR_FORM);\n const isBillingSame = !!_get(values, billingSameAsShippingField);\n const shippingOtherOptionSelected = _get(\n values,\n shippingAddrOtherOptionField\n );\n const { formSectionValues, formSectionErrors, isFormSectionTouched } =\n sectionFormikData;\n const streetError = _get(formSectionErrors, 'street');\n\n if (streetError) {\n _set(\n formSectionErrors,\n 'street[0]',\n __('%1 is required', 'Street Address')\n );\n }\n\n const shippingFormikData = useMemo(\n () => ({\n ...sectionFormikData,\n isBillingSame,\n formSectionErrors,\n shippingOtherOptionSelected,\n shippingValues: formSectionValues,\n isBillingFormTouched: isFormSectionTouched,\n selectedRegion: sectionFormikData.formSectionValues?.region,\n selectedCountry: sectionFormikData.formSectionValues?.country,\n }),\n [\n isBillingSame,\n sectionFormikData,\n formSectionValues,\n formSectionErrors,\n isFormSectionTouched,\n shippingOtherOptionSelected,\n ]\n );\n\n return <ShippingAddressMemorized formikData={shippingFormikData} />;\n}", "updateCheck() {\r\n this.setState((oldState) => {\r\n return {\r\n checked: !oldState.checked,\r\n };\r\n });\r\n this.updateChart(this.state.checked)\r\n }", "onRememberChange(checked) {}", "function updateEmailAllMarkList()\t{\n var chkBoxId = this.name;\n var partialchkBoxId = chkBoxId.substring(0,chkBoxId.indexOf('_'));\n // Check for total number of Marked & capture the status of each marked Checkboxes.\n\tvar emailAllDivs = document.getElementsBySelector(\"span.citation-send\");\n\tfor(var i=0;i<emailAllDivs.length;i++){\n\t\tvar emailAll = emailAllDivs[i].getElementsByTagName(\"INPUT\")[0];\n if (\"sendAllEmailOption\" != emailAll.id) {\n var partialId = emailAll.name.substring(0,emailAll.name.indexOf('_'));\n if (partialchkBoxId == partialId) {\n if (this.checked ==true) { // If CheckAll is True, makes all of them as Checked.\n emailAll.checked = true;\n } else {\n emailAll.checked = false;\n }\n }\n }\n }\n}", "function checkBox4CopyGrid() {\r\n var cb1 = document.getElementById('makeAcopy');\r\n cb1.checked = true;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current logged in LoL user's summoner name
static getCurrentSummonerName() { return new Promise(async (accept, reject) => { const [err, data] = await to(this.getCurrentSummoner()); if (err) { log.debug('Failed to get current summoner name: %s', err); reject(err); } // data.displayName is summonername with caps and spaces // data.internalname is summonername lowercase no space if (data && data.displayName) { log.debug('current summoner name is %s', data.displayName); accept(data.displayName); } log.debug('LoL client api data does not contain summoner name'); reject(); }); }
[ "function getCurrentOnCallUsername() {\n\tlet user = \"\"\n\t// Get the rotation that has an onCall user.\n\tfor (let i in this.raw.schedule) {\n\t\tlet sched = this.raw.schedule[i]\n\t\tif (sched.onCall) {\n\t\t\tuser = sched.onCall\n\t\t}\n\t}\n\n\t// Return Error if no user is on call.\n\tif (!user) {\n\t\treturn new Error(\"No user seems to currently be On Call.\")\n\t}\n\n\tlet overrides = this.raw.overrides\n\tuser = checkOverrides(user, overrides)\n\n\treturn user\n}", "function getUsername() {\r\n \r\n // get's user email:\r\n var email = Session.getActiveUser().getEmail()\r\n // emails in form <username> @ mail.domain\r\n // split --> parse_emial = ['username','mail.com']\r\n var parse_email = email.split(\"@\")\r\n var username = parse_email[0]\r\n \r\n return username\r\n}", "function getUser(){\n if(!mixpanelUid){\n mixpanelUid = Date.now();\n identifyUser(mixpanelUid);\n }\n return mixpanelUid;\n}", "function loadName() {\n const currentUser = localStorage.getItem(USER_LS);\n if (currentUser === null) {\n askForName();\n } else {\n paintGreeting(currentUser);\n }\n}", "getOwner() {\n this.logger.debug(GuildService.name, this.getOwner.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getOwner.name, \"Getting owner and exiting.\");\n return this.guild.owner.user;\n }", "async function findMyName() {\n try {\n return cross_spawn_1.default.sync('git', ['config', '--get', 'user.name']).stdout.toString().trim();\n }\n catch {\n return '';\n }\n}", "function getPlayer(name, callback) {\n\tvar url = `https://www.speedrun.com/api/v1/users?max=1&lookup=${name}`;\n\n\tgetAPIData(url, (err, resp) => {\n\t\tif (!resp.body.data.length) return callback(); // Cannot find player.\n\n\t\tvar data = resp.body.data[0];\n\t\tvar player = {};\n\t\tplayer.id = data.id;\n\t\tplayer.name = data.names.international;\n\t\tif (data.twitch && data.twitch.uri)\n\t\t\tplayer.twitch = data.twitch.uri.split('/')[data.twitch.uri.split('/').length-1];\n\t\tif (data.twitter && data.twitter.uri)\n\t\t\tplayer.twitter = data.twitter.uri.split('/')[data.twitter.uri.split('/').length-1];\n\t\tif (data.location && data.location.country)\n\t\t\tplayer.country = data.location.country.code;\n\n\t\tcallback(player);\n\t});\n}", "function getFightLogVarname() {\r\n return \"estiah_pvp_fight_log_\" + getUsername();\r\n}", "function getNickName() {\r\n \r\n return $(\"#loggedin\").text().substring(9);\r\n \r\n \r\n }", "function checkSummoner(res, name, regionNum, callback) {\n\t\tlolapi.Summoner.getByName(name, regions[regionNum], function (err, summoners) {\n\t\tif (err) { // ERROR summoner not found\n\t\t\trenderError(res, \"Summoner not found\", err);\n\t\t} else if (summoners == {}) { // ERROR summoner not found\n\t\t\trenderError(res, \"Summoner not found\", {\"status\": 404, \"stack\":\"\"});\n\t\t} else { // summoner name exists on Riot server\n\t\t\tvar summoner = summoners[name];\n\n\t\t\t// QUERY check if summoner id exists already (namechange?)\n\t\t\tsummonerDB.find({\"id\": summoner.id, \"region\": regionNum}).toArray(function (err2, summoners2) {\n\t\t\t\tif (err2) { // ERROR db\n\t\t\t\t\trenderError(res, \"Server Error\", err2);\n\t\t\t\t} else if (summoners2.length) { // summoner id exists in db (summoner made a namechange)\n\t\t\t\t\tupdateSummonerDB(res, summoners2[0], { $set: { \"name\": summoner.name, \"namel\": summoner.name.toLowerCase().replace(/ /g, ''), \"icon\": summoner.profileIconId } }, callback);\n\t\t\t\t} else { // name and summoner id does not exist in db (new user)\n\t\t\t\t\tcreateSummonerDB(res, summoner.name, summoner.id, regionNum, summoner.profileIconId, callback);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "function getUserInfo() {\n return user;\n }", "function querySummoner(name, client, done){\n\n var queryString = \"SELECT summoner_id FROM summoner WHERE base_name='\" + name + \"'\";\n client.query(queryString, function(err, result){\n if(err){\n console.log('error querying from querySummoner');\n done();\n }\n else {\n if(result.rowCount === 0){\n //summoner not in database, need to fetch api\n console.log('summoner not found in DB');\n riotSeeder.getSummonerID(name)\n .then(function(id){\n console.log('rp promise: ' + id);\n if(id !== -1){\n //request API to get recent games associated with the summonerID\n querySummonerMatches(id);\n }\n })\n .catch(function(err){\n console.log(err)\n io.emit('summoner not found', err);\n });\n\n }\n else {\n var summonerID = result.rows[0].summoner_id;\n //75% of the time, directly query summoner matches, but %25 of the time do query the summoner result once more in case user has changed summoner icon etc.\n if(Math.random() >= 0.25){\n //request API to get recent games associated with the summonerID\n querySummonerMatches(summonerID);\n }\n else {\n riotSeeder.getSummonerID(name)\n .then(function(id){\n console.log('rp promise: ' + id);\n if(id !== -1){\n //request API to get recent games associated with the summonerID\n querySummonerMatches(id);\n }\n })\n .catch(function(err){\n console.log(err)\n io.emit('summoner not found', err);\n });\n }\n }\n //close db connection\n done();\n }\n });\n }", "function getOtherUserId() {\n var currentTrade = Session.get('realTime');\n\n if (currentTrade) {\n var myId = Meteor.userId();\n\n if (currentTrade.user1Id === myId) {\n return currentTrade.user2Id;\n } else if (currentTrade.user2Id === myId) {\n return currentTrade.user1Id;\n }\n }\n}", "function findUserName() {\n var thisENV = process.env,\n possibleVariables = ['USER', 'USERNAME'],\n i;\n for (i = 0; i < possibleVariables.length; i += 1) {\n if (possibleVariables[i]) {\n return thisENV[possibleVariables[i]];\n }\n }\n return null;\n}", "function getUsername(req) {\n if (isAuthenticated(req)) {\n return req.virtuallyNoTag_authenticationInformation.response.username;\n }\n return null;\n}", "function askForName() {\n var name = \"\";\n\n // Ensure name is valid\n while(name === \"\" || name === null) {\n name = window.prompt(\"Please enter a display name.\", \"\");\n }\n\n console.log(\"Player name set to \" +name+ \".\");\n return name;\n }", "function getDisplayName(generatorName) {\n // Breakdown of regular expression to extract name (group 3 in pattern):\n //\n // Pattern | Meaning\n // -------------------------------------------------------------------\n // (generator-)? | Grp 1; Match \"generator-\"; Optional\n // (polymer-init)? | Grp 2; Match \"polymer-init-\"; Optional\n // ([^:]+) | Grp 3; Match one or more characters != \":\"\n // (:.*)? | Grp 4; Match \":\" followed by anything; Optional\n return generatorName.replace(/(generator-)?(polymer-init-)?([^:]+)(:.*)?/g, '$3');\n}", "getHintName(levelName, player, hintNr){\n var fields = this.levels[levelName].fields;\n var playerField = null;\n for(var i = 0; i < fields.length; i++){\n if(fields[i].playerName === player){\n playerField = fields[i];\n }\n }\n\n if(playerField === null){\n return \"NA\";\n }\n\n var hint = playerField.hintList[hintNr];\n\n if(hint){\n for(var i = 0; i < playerField.trapList.length; i++){\n var f = playerField.trapList[i];\n if(f){\n if(f.position[0] === hint[0] && f.position[1] === hint[1]){\n return f.name;\n }\n }\n\n }\n }\n\n\n\n return \"NA\";\n }", "whoAmI () {\n return this._apiRequest('/user/me')\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if this HED tag has the 'unitClass' attribute.
get hasUnitClass() { return this._memoize('hasUnitClass', () => { if (!this.schema.entries.definitions.has('unitClasses')) { return false } if (this.takesValueTag === null) { return false } return this.takesValueTag.hasUnitClasses }) }
[ "function is_valid_ucum_unit(unit) {\n if (unitValidityCache[unit] != null) {\n return unitValidityCache[unit];\n } else {\n try {\n ucum.parse(ucum_unit(unit));\n unitValidityCache[unit] = true;\n return true;\n } catch (error) {\n unitValidityCache[unit] = false;\n return false;\n }\n }\n}", "function ensureHasClass(element, statedClass) {\n if (!element.classList.contains(statedClass)) {\n throw new Error(`Element does not have ${statedClass} class`);\n }\n}", "get unitClasses() {\n return this._memoize('unitClasses', () => {\n if (this.hasUnitClass) {\n return this.takesValueTag.unitClasses\n } else {\n return []\n }\n })\n }", "function isMember(element, classname)\r\n\t{\r\n\t\tvar classes = element.className; // Get a list of the classes\r\n\t\t\r\n\t\tif (!classes) \r\n\t\t\treturn false;\r\n\t\tif ( classes == classname )\r\n\t\t\treturn true;\r\n\t\t\t\r\n\t\t// We didn't match exactly, so if there is no whitespace, then\r\n\t\t// this element is not a member of the class.\r\n\t\tvar whitespace = /\\s+/;\r\n\t\tif (!whitespace.test(classes))\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t// If we get here, the element is a member of more than one class and\r\n\t\t// we've got to check them individually.\r\n\t\tvar c = classes.split(whitespace); // Split with whitespace delimiter.\r\n\t\tfor( var i=0; i < c.length; i++ )\r\n\t\t{\r\n\t\t\tif ( c[i] == classname )\r\n\t\t\t\treturn true; \r\n\t\t}\r\n\t\treturn false; // None of the classes matched.\r\n\t}", "function shouldSendUnit(name, query) {\n /* eslint-disable no-multi-spaces */\n var includeSysUnits = query ? (query.includeSystemUnits === 'true') : false;\n var includeAnnouncers = query ? (query.includeAnnouncers === 'true') : false;\n var includeLoadbalancers = query ? (query.includeLoadbalancers === 'true') : false;\n /* eslint-enable no-multi-spaces */\n\n if (!includeSysUnits && name.match(/^paz\\-*/)) {\n return false;\n }\n\n if (!includeAnnouncers && name.match(/\\-announce/)) {\n return false;\n }\n\n if (!includeLoadbalancers && name.match(/\\-loadbalancer/)) {\n return false;\n }\n\n return true;\n}", "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}", "function hasSomeParentTheClass(element, classname) {\n element = element.target;\n if (element.className.split(' ').indexOf(classname)>=0) return true;\n return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);\n}", "static reflectClass() {\n if (this.classList.contains('complete') !== this.complete) {\n this.classList.toggle('complete');\n }\n }", "get isSetup() {\n return this.system.hasInstance(this);\n }", "function is_unit_visible(punit)\n{\n if (punit == null || punit['tile'] == null) return;\n\n var u_tile = index_to_tile(punit['tile']);\n var r = map_to_gui_pos(u_tile['x'], u_tile['y']);\n var unit_gui_x = r['gui_dx'];\n var unit_gui_y = r['gui_dy'];\n\n if (unit_gui_x < mapview['gui_x0'] || unit_gui_y < mapview['gui_y0']\n || unit_gui_x > mapview['gui_x0'] + mapview['width'] \n || unit_gui_y > mapview['gui_y0'] + mapview['height']) {\n return false;\n } else {\n return true;\n }\n\n}", "function isBaseClassOf(apiItem) {\n return apiItem.hasOwnProperty(_releaseTag);\n }", "get defaultUnit() {\n return this._memoize('defaultUnit', () => {\n const defaultUnitsForUnitClassAttribute = 'defaultUnits'\n if (!this.hasUnitClass) {\n return ''\n }\n const tagDefaultUnit = this.takesValueTag.getNamedAttributeValue(defaultUnitsForUnitClassAttribute)\n if (tagDefaultUnit) {\n return tagDefaultUnit\n }\n const firstUnitClass = this.unitClasses[0]\n return firstUnitClass.getNamedAttributeValue(defaultUnitsForUnitClassAttribute)\n })\n }", "function isEntry(target)\n{\n return $(target).hasClass(\"entry\");\n}", "isValidType() {\n return Menu.getPizzaTypesSet().has(this.type.toLowerCase());\n }", "function isClass(target) {\n return isES6Class(target)\n || target.prototype\n && !(target.prototype instanceof Function)\n && !compareSetValues(\n Object.getOwnPropertyNames(target.prototype), noopProtoKeys)\n}", "function unit_type(unit)\n{\n return unit_types[unit['type']];\n}", "function noMatchClass(card) {\n\tlet classes = card.classList;\n\tlet noMatch = true;\n\n\tclasses.forEach(function(value) {\n\t\tif ((value === \"match\"))\n\t\t\tnoMatch = false;\n\t});\n\n\treturn noMatch;\n}", "function isWidgetRequired(id) {\n var classNames = document.getElementById('id_' + id).className;\n return classNames.indexOf('jf-required') > -1;\n }", "function checkAttributes(attributes) {\n const badgeEl = rootEl.shadowRoot.getRootNode().querySelector(\".badge\");\n const textEl = rootEl.shadowRoot.getRootNode().querySelector(\".text\");\n\n expect(badgeEl).toBeDefined();\n expect(textEl).toBeDefined();\n expect(textEl.innerText).toBe(attributes.text);\n expect(rgbToHex(badgeEl.style.color)).toBe(attributes[\"text-color\"]);\n expect(rgbToHex(badgeEl.style.backgroundColor)).toBe(\n attributes[\"background-color\"]\n );\n if (attributes[\"border-color\"] === \"transparent\") {\n expect(badgeEl.style.borderColor).toBe(attributes[\"border-color\"]);\n } else {\n expect(rgbToHex(badgeEl.style.borderColor)).toBe(\n attributes[\"border-color\"]\n );\n }\n\n if (attributes[\"has-animation\"] === \"true\") {\n expect(badgeEl.classList.contains(\"animated\")).toBeTrue();\n } else {\n expect(badgeEl.classList.contains(\"animated\")).toBeFalse();\n }\n\n expect(badgeEl.classList.contains(attributes.position)).toBeTrue();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list of programyear objectives, sorted by position.
get sortedProgramYearObjectives() { return this._programYearObjectives?.slice().sort(sortableByPosition); }
[ "function sortYear() {\r\n document.querySelector('#yearH').addEventListener('click', function (e) {\r\n const year = paintings.sort((a, b) => {\r\n return a.YearOfWork < b.YearOfWork ? -1 : 1;\r\n })\r\n displayPaint(year);\r\n })\r\n }", "iYearToJYear(iYear) {\n // console.log('** iYearToJYear ' + iYear + ' **');\n const jYears1 = []; // fill with tuple(s) of (startYear, eraCode) for matching era(s), then sort it\n const jYears2 = []; // fill this with tuple(s) of (eName, jName, eraYear)\n if ((iYear<this.minYear) || (iYear>this.maxYear+1)) {return jYears2;} // return blank if out of range\n for (const [eraCode, oneEra] of Object.entries(this.yDict)) {\n // console.log( 'iYear for ' + oneEra.getEraCode());\n if (oneEra.isIYearInEra(iYear)) {\n jYears1.push([oneEra.getStartYear(), eraCode]);\n }\n }\n jYears1.sort(function(a, b){return a[0]-b[0];}); // sort in order by start year\n for (const [startYear, eraCode] of jYears1) {\n jYears2.push([this.yDict[eraCode].getEName(), this.yDict[eraCode].getJName(),\n this.yDict[eraCode].iYearToEraYear(iYear)]);\n }\n // console.log(jYears2);\n return jYears2;\n }", "function laureatesByYear(year) {\n let result = [];\n // for (let i = 0; i < nobels.prizes.length; i++)\n // if (nobels.prizes[i].year == year) {\n // result = result.concat(nobels.prizes[i].laureates);\n // }\n // return result;\n\n return nobels.prizes.map(function(myObj) {\n if (myObj.year == year) {\n return myObj.laureates;\n }\n });\n}", "function filterByDebut (year) {\n let arr = []\n for (const i of players)\n {\n if (i.debut == year)\n {\n arr.push(i)\n } \n }\n return arr\n}", "function parse_years() {\n var raw_years = year_date_textbox.getValue();\n var years_to_list = raw_years.split(\"-\");\n return years_to_list;\n}", "function getLaureates(year, category) {\n let result = [];\n for (let i = 0; i < nobels.prizes.length; i++)\n if (nobels.prizes[i].year == year) {\n if(nobels.prizes[i].category == category) {\n result = result.concat(nobels.prizes[i].laureates);\n }\n }\n return result;\n}", "function showSort(x) {\n var cmp = function(a,b){\n if (a > b) {return +1};\n if (a < b) {return -1};\n return 0;\n }\n x.sort(function(a,b) {\n return cmp(a.modelName,b.modelName) || cmp(a.modelYear,b.modelYear)\n })\n for(let iter = 0 ; iter < x.length ; iter ++){\n console.log(x[iter].modelYear + ' ' + x[iter].modelName);\n }\n}", "function getYears(cbFinals) {\n const finalYears = [];\n const years = cbFinals(fifaData).map(function(element){\n finalYears.push(element.Year);\n })\n return finalYears;\n}", "function sortFilterArrays()\n\t {\n\t\t \tyearsArray.sort(function(a, b) {return b - a});\n\t \t\tauthorsArray.sort(function(a, b) {return b[1] - a[1]});\n\n\t\t\tif (NUMBER_OF_TIMES_IN_FILTER <= yearsArray.length)\n\t\t\t\tOLDER_TEXT = \"< \" + yearsArray[NUMBER_OF_TIMES_IN_FILTER - 1]\n\t }", "listYearly() {\n const tenYearBefore = dateService.getYearsBefore(10);\n return this.trafficRepository.getYearlyData(tenYearBefore)\n .then(data => {\n data = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(tenYearBefore.getFullYear(), 10);\n const valuesToAdd = range.filter(x => !data.find(item => item.group === x));\n return data.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }", "sortCourses() {\n this.courses = Object.entries(this.props.getCoursesList());\n this.courses.sort(([A, valA], [B, valB]) => (valA.code < valB.code ? -1 : 1));\n }", "function SortByNamexOlderThan(age) {\n let choosenPlayers = []\n for (const player of players) {\n if (player.age >= age) {\n let sortedAwards = player.awards\n sortedAwards.sort((award1, award2) => {\n if (award1.year > award2.year) {\n return -1\n } else {\n return 1\n }\n })\n\n player.awards = sortedAwards\n choosenPlayers.push(player)\n }\n }\n\n choosenPlayers.sort((player1, player2) => {\n if (player1.name > player2.name) {\n return 1\n } else {\n return -1\n }\n })\n return choosenPlayers\n}", "function persiana_year(jd) {\n var guess = jd_to_gregorian(jd)[0] - 2;\n\n for (var lastEq = tehran_equinox_jd(guess); lastEq > jd;)\n lastEq = tehran_equinox_jd(--guess);\n\n for (var nextEq = lastEq - 1; lastEq > jd || jd >= nextEq;) {\n lastEq = nextEq;\n nextEq = tehran_equinox_jd(++guess);\n }\n\n return [\n round((lastEq - PERSIAN_EPOCH) / TropicalYear) + 1,\n lastEq\n ];\n}", "function getYears(getFinals) {\n return getFinals(fifaData).map(function(data){\n return data[\"Year\"];\n });\n\n}", "function createYearsArray(size,year) {\n\t// Validate parameter value\n\tif (size+\"\" == \"undefined\" || size == null) \n\t\treturn null;\t\n\tthis.length = size;\n\tfor (var i = 0; i < size; i++) {\n\t\tthis[i] = year++; \n\t}\n\treturn this;\n}", "function generateEndYears(selectedDatabaseMask) {\n var stringYear = $(\"input[name='stringYear']\");\n if (typeof stringYear == 'undefined') {\n console.warn(\"stringYear value could not be set!\");\n return;\n }\n\n var sy = calStartYear(selectedDatabaseMask, stringYear.val());\n var ey = calEndYear(selectedDatabaseMask);\n\n var years = new Array();\n var idx = 0;\n for (var j = ey; j >= sy; j--) {\n if (j == ey) years[idx++] = {\"label\": j, \"value\": j, \"selected\": true};\n else years[idx++] = {\"label\": j, \"value\": j};\n }\n return years\n\n }", "static view() {\n const coursesByDepartment = getCoursesByDepartment(\n courses.list,\n selectedDepartment,\n );\n return getUniqueYears(coursesByDepartment).map(year =>\n m(expandableContent, { name: `Year ${year}`, level: 0 }, [\n getUniqueLecturesByYear(\n coursesByDepartment,\n year,\n ).map(lecture =>\n m(\n expandableContent,\n { name: lecture, level: 1 },\n coursesByDepartment\n .filter(course => course.lecture.year === year)\n .filter(course => course.lecture.title === lecture)\n .map(displayCard),\n ))]));\n }", "function generateStartYears(selectedDatabaseMask) {\n var stringYear = $(\"input[name='stringYear']\");\n if (typeof stringYear == 'undefined') {\n console.warn(\"stringYear value could not be set!\");\n return;\n }\n\n var sy = calStartYear(selectedDatabaseMask, stringYear.val());\n var ey = calEndYear(selectedDatabaseMask);\n var dy = calDisplayYear(selectedDatabaseMask, stringYear.val());\n\n var years = new Array();\n var idx = 0;\n for (var j = sy; j <= ey; j++) {\n if (j == dy) years[idx++] = {\"label\": j, \"value\": j, \"selected\": true};\n else years[idx++] = {\"label\": j, \"value\": j};\n }\n return years\n }", "function storeYArray(a, startYear, endYear) {\n var i = 0, year = startYear;\n //while(year <= endYear) {\n while(year < endYear) {\n a[i] = year;\n year++\n i++;\n }\n return a;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changes data to the chart if new 'paystationID' otherwise add new dataset
function changeChartData(plotData,payStationId, hover) { if (hover) { title = 'Pay Station' + payStationId; } else { title = 'Pay Station Hover'; } var dataArray=[]; dataArray[0]=title; dataArray.push.apply(dataArray, plotData); console.log(dataArray); chart.load({ columns: [ dataArray ], type: 'bar' }); }
[ "function addDataToCharts(data)\n{\n\t// Probably a better way to do this\n\tif (data.length != 0) {\n\tif (data[data.length-1].timekey.substring(11,16) == totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)\n\t{\n\t\t/*console.log(\"den siste labelen er : \" + totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)*/\n\t\ttotalChart.update();\n\t}\n\telse\n\t{\n\t\ttotalChart.addData([data[data.length-1].total],data[data.length-1].timekey.substring(11,16));\n\t\tvar totalDataLength = totalChart.datasets[0].points.length-2;\n\t\ttotalChart.datasets[0].points[totalDataLength].value = data[data.length-2].total;\n\t\ttotalChart.update();\n\t\t/*totalChart.removeData();*/\n\t}\n}\n\t//FABFIVE: try to update labels automatically when new data arrives.\n\t//updateLabels(data);\n}", "add (station) {\n let position\n\n // update existing\n if (this.first && this.first.id === station.id || this.second && this.second.id === station.id) {\n if (this.active !== station.id) {\n this.chart.shadow(this.active)\n this.chart.bringToFront(station.id)\n }\n } else {\n if (this.first) {\n if (this.second) this.chart.remove(this.second.id)\n this.second = station\n this.chart.shadow(this.first.id)\n } else {\n this.first = station\n if (this.second) this.chart.shadow(this.second.id)\n }\n\n this.load(station.id, this.year)\n }\n\n this.header.show(station, this.first === station ? 0 : 1)\n this.chart.show()\n this.map.highlight(station.id)\n this.active = station.id\n }", "function updateBidChart() {\r\n\t\t\t\t\tupdateBidChart2();\r\n\t\t\t\t}", "function updateDatapoints() {\n\t\t//remove all markers from the map in order to be able to do a refresh\n\t\tmarkers.clearLayers();\n\t\tmarkers_list = {};\n\t\t//for every datapoint\n\t\tbyId.top(Infinity).forEach(function(p, i) {\n\t\t\t//create a marker at that specific position\n\t\t\tvar marker = L.circleMarker([p.latitude,p.longitude]);\n\t\t\tmarker.setStyle({fillOpacity: 0.5,fillColor:'#0033ff'});\n\t\t\t//add the marker to the map\n\t\t\tmarkers.addLayer(marker);\n\t\t});\n\t}", "function updateChartValue(){\r\n myChart.data.datasets[0].data[0] = sumNo;\r\n myChart.data.datasets[0].data[1] = sumYes;\r\n myChart.update()\r\n}", "function dataset_put(ds) {\n const newds = (ds.id) \n ? topStack().datasets.map(d => d.id === ds.id ? { ...d, ...ds } : d)\n : [ ...topStack().datasets, { \n id: topStack().datasets.length + 1,\n notes: [], \n ...ds,\n } ];\n // validate here\n pushNext({ \n ...topStack(), \n datasets: newds, \n });\n}", "loadGraph(){\n\n var current = this;\n var servicePathAPI = baseURL+'/api/transactions/all/'+ this.dataToken;\n \n $.getJSON(servicePathAPI, function (data) {\n\n var result = data;\n if(result){ \n \n var series = [];\n var categories = [];\n for(var i=0;i < result.length;i++){\n var item = result[i];\n var transDate = new Date(item[0]);\n var transAmount = item[1];\n categories.push( moment( transDate.getTime() ).format(\"MM/DD/YYYY\") );\n current._chartData.push( [ transDate, transAmount] );\n }\n\n }\n\n // Create the transactions chart\n this._transactionChart = Highcharts.chart('mainChart', {\n rangeSelector : {\n selected : 1,\n allButtonsEnabled: true\n },\n chart: {\n zoomType: 'x',\n alignTicks: false\n },\n title : {\n text : 'Transaction Volume'\n },\n xAxis: {\n type: 'datetime',\n categories: categories\n },\n yAxis: {\n title: {\n text: 'USD'\n }\n },\n tooltip: {\n formatter: function() {\n return 'Date: <b>' + moment(this.x).format(\"MM/DD/YYYY\") + '</b> <br/> Amount: <b>$' + accounting.format(this.y) + '</b>';\n }\n },\n series : [{\n name : 'Transactions',\n fillColor : {\n linearGradient : {\n x1: 0,\n y1: 0,\n x2: 0,\n y2: 1\n },\n stops : [\n [0, Highcharts.getOptions().colors[0]],\n [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]\n ]\n },\n data : current._chartData\n }]\n\n });\n\n });\n }", "init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }", "function updateChart(x,y) {\n // add new point\n var style = 'point { size: 10; fill-color: #4a148c; }' ;\n var point=[ x , y , style ];\n data.addRow([ x, y, style ]);\n // if too many points, remove oldest one\n var numPoints = data.getNumberOfRows();\n if (numPoints > 1) data.removeRow(0);\n // redraw chart\n chart.draw(data, options);\n}", "addSeries(id, param) {\n if (typeof id !== 'string') {\n throw new Error('[EVUI][ERROR][ChartDataStore]-Not found series id value.');\n }\n\n if (typeof param !== 'object') {\n throw new Error('[EVUI][ERROR][ChartDataStore]-Not found input series object.');\n }\n\n const skey = Object.keys(this.seriesList);\n\n let series;\n const defaultSeries = {\n name: param.name || `series-${this.sIdx++}`,\n color: param.color || this.chartOptions.colors[skey.length],\n show: param.show === undefined ? true : param.show,\n min: null,\n max: null,\n minIndex: null,\n maxIndex: null,\n seriesIndex: this.seriesList.length,\n data: [],\n insertIndex: -1,\n dataIndex: 0,\n startPoint: 0,\n highlight: {\n pointSize: param.highlight ? (param.highlight.size || 5) : 5,\n },\n groupIndex: null,\n stackIndex: null,\n isExistGrp: false,\n };\n\n if (this.getSeriesExtends) {\n series = this.getSeriesExtends(defaultSeries, param);\n }\n\n if (!this.seriesList[id]) {\n this.seriesList[id] = series;\n }\n\n if (!this.graphData[id] && this.chartOptions.type !== 'pie') {\n this.graphData[id] = [];\n }\n }", "function chartUpdate(config) {\n // Is it valid?\n if (config == null)\n return;\n\n // Generate the URL\n var base_url = config.data_url || window.location + \"/data.json\";\n var call_url = base_url + \"?resume=\" + config.resume\n if (config.last_id != \"\") {\n call_url = call_url + \"&last=\" + config.last_id;\n }\n if (config.points_limit != undefined) {\n call_url += \"&limit=\" + config.points_limit\n }\n\n // Do the API call\n $.getJSON(call_url).success(function(data){\n if (config.chart.series[0].data.length == 0) {\n var chartData = [];\n\n for (var i = data.length-1; i >= 0; i--)\n chartData.push([data[i].date*1000, data[i].result]);\n\n var chart = $(config.container).highcharts();\n chart.series[0].setData(chartData);\n }\n else {\n for (var i = 0; i < data.length-1; i++) {\n // Do we need to remove the first point in the chart?\n if ((config.points_limit != undefined) && (config.chart.series[0].data.count > config.points_limit))\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false, true);\n else\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false);\n }\n }\n\n // If there is data received, save the lastest id.\n if (data.length > 0)\n config.last_id = data[0].id;\n\n // 10 msec later, print the latest point.\n // This code is to solve a bug with the rangeSelector of HighStock\n setTimeout(function() {\n if (data.length > 0)\n config.chart.series[0].addPoint([data[data.length-1].date*1000, data[data.length-1].result], false);\n\n config.chart.redraw();\n config.chart.hideLoading();\n }, 10);\n });\n\n // Redraw the chart\n config.chart.redraw();\n}", "function updateChart (data, days=7) {\n var rsiSensitivity = Number($('#rsi').val()) || DEFAULT_RSI;\n var start = performance.now();\n var dataLows = getLocalExtrema(data, \"min\");\n var dataHighs = getLocalExtrema(data, \"max\");\n var regressionAll = getLinearRegression(data, days);\n var regressionLow = getLinearRegression(dataLows, days);\n var regressionHigh = getLinearRegression(dataHighs, days);\n var movingAverageN = Number($('#moving-average-n').val()) || DEFAULT_MOVING_AVERAGE_N;\n var movingAverageM = Number($('#moving-average-m').val()) || DEFAULT_MOVING_AVERAGE_M;\n var movingAverage = getMovingAverage(data, movingAverageN, days);\n var movingAverageLong = getMovingAverage(data, movingAverageM, days);\n var rsi = getRSI(data, rsiSensitivity, days);\n var pricingCtx = $(\"#pricing-chart\");\n var rsiCtx = $(\"#rsi-chart\");\n var end = performance.now();\n\n var pricingChart = new Chart(pricingCtx, {\n 'type': 'scatter',\n 'data': {\n 'datasets': [\n {\n 'label': `Moving Average 1`,\n 'data': convertDataForChart(movingAverage),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 255, 0, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': `Moving Average 2`,\n 'data': convertDataForChart(movingAverageLong),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 0, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression',\n 'data': generateDataFromRegression(regressionAll, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 0, 0, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression Highs',\n 'data': generateDataFromRegression(regressionHigh, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 0, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression Lows',\n 'data': generateDataFromRegression(regressionLow, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Pricing History',\n 'data': convertDataForChart(getRecentData(data, days)),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 0, 0.9)',\n 'borderWidth': 3,\n 'lineTension': 0\n }\n ]\n },\n 'options': {\n 'maintainAspectRatio': false,\n 'layout': {\n 'padding': 20\n },\n 'legend': {\n 'labels': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n }\n },\n 'tooltips': {\n 'mode': 'nearest',\n 'callbacks': {\n 'label': function (toolTipItem, data) {\n var x = `${moment().subtract((days - toolTipItem.xLabel) * 24, 'hours', true).format('MMM Do ha')}`\n var y = `$${toolTipItem.yLabel.toFixed(2)}`;\n return `${x}, ${y}`\n }\n } \n },\n 'scales': {\n 'scaleLabel': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n },\n 'xAxes': [{\n 'ticks': {\n 'min': 0,\n 'callback': function (value, index, values) {\n return moment().subtract(days - value, 'days').format('MMM Do');\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n },\n }],\n 'yAxes': [{\n 'ticks': {\n 'callback': function (value, index, values) {\n return `$${value.toFixed(2)}`;\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n }\n }]\n }\n }\n })\n\n var rsiChart = new Chart(rsiCtx, {\n 'type': 'scatter',\n 'data': {\n 'datasets': [\n {\n 'label': `RSI`,\n 'data': convertDataForChart(rsi),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 0, 0.9)',\n 'borderWidth': 3,\n 'lineTension': 0\n }\n ]\n },\n 'options': {\n 'maintainAspectRatio': false,\n 'layout': {\n 'padding': 20\n },\n 'legend': {\n 'labels': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n }\n },\n 'tooltips': {\n 'mode': 'nearest',\n 'callbacks': {\n 'label': function (toolTipItem, data) {\n var x = `${moment().subtract((days - toolTipItem.xLabel) * 24, 'hours', true).format('MMM Do ha')}`\n var y = `${toolTipItem.yLabel.toFixed(2)}`;\n return `${x}, ${y}`\n }\n } \n },\n 'scales': {\n 'scaleLabel': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n },\n 'xAxes': [{\n 'ticks': {\n 'min': 0,\n 'callback': function (value, index, values) {\n return moment().subtract(days - value, 'days').format('MMM Do');\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n },\n }],\n 'yAxes': [{\n 'ticks': {\n 'beginAtZero': true,\n 'max': 100\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n }\n }]\n }\n }\n })\n\n return {pricingChart, rsiChart};\n}", "function updateDatasets(filter) {\n if (!(ocean.period in ocean.variables[ocean.variable].plots[ocean.plottype])){\n ocean.period = ocean.variables[ocean.variable].variable['periods'][0];\n filterOpts('period', ocean.variables[ocean.variable].plots[ocean.plottype]);\n selectFirstIfRequired('period');\n }\n\n var datasets = ocean.variables[ocean.variable].plots[ocean.plottype][ocean.period];\n\n if (filter) {\n datasets = $.grep(datasets, filter);\n }\n\n /* sort by rank */\n datasets.sort(function (a, b) {\n var ar = 'rank' in ocean.datasets[a] ? ocean.datasets[a].rank : 0;\n var br = 'rank' in ocean.datasets[b] ? ocean.datasets[b].rank : 0;\n\n return br - ar;\n });\n\n /* FIXME: check if the datasets have changed */\n\n var dataset = getValue('dataset');\n $('#dataset option').remove();\n\n $.each(datasets, function (i, dataset) {\n $('<option>', {\n value: dataset,\n text: ocean.datasets[dataset].name\n }).appendTo('#dataset');\n });\n\n /* select first */\n// if (dataset is null) {\n // $(\"#dataset\").val($(\"#dataset option:first\").val());\n// }\n setValue('dataset', dataset);\n selectFirstIfRequired('dataset');\n}", "addStockToChart(symbol, data) {\n this.stockChart.addSeries({\n name: symbol,\n data: data\n });\n }", "function updateData(payerObj, pointSpent) {\r\n data[payerObj.payer] -= pointSpent;\r\n}", "function addSeries(id) {\n //check apakah sudah ada di series\n if (mySeries[id]) {\n //sudah ada\n mySeries[id].showAllSeries(true);\n } else {\n //belum ada\n //tarik json\n $.getJSON(base_url + \"compare/get_tree/\" + id, function (d) {\n //d is the root, could be a leaf as well\n mySeries[id] = new NodeSeries(d)\n mySeries[id].showAllSeries(true);\n });\n }\n }", "function trend_periodically_update_graph () {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/dashboard/trend_data',\n\t\tdataType: 'json',\n\t\tsuccess: trend_generate_graph\n\t});\n}", "function updateGraph(graph, newDataValues){\n for (var i = 0; i < newDataValues.length; i++){\n (graph.data.datasets[i].data).splice(0,1); \n (graph.data.datasets[i].data).push(newDataValues[i]);\n }\n graph.update(); //Chart.js redraw graph\n}", "function updateTillNow() {\r\n\tfor(var j = 0; j < activeGraphs.length; j++) {\r\n\t\tif(activeGraphs[j].keepUpdated) {\r\n\t\t\tactiveGraphs[j].canvas.data.datasets = [];\r\n\t\t\tactiveGraphs[j].canvas.update();\r\n\r\n\t\t\tfor(var i = 0; i < activeGraphs[j].graphs.length; i++) {\r\n\t\t\t\tpushGraphData(activeGraphs[j].id, i)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper for getting ISO image value
function iso_image_value(mod) { var cdimage_chooser = $('#id_iso-image'); if (cdimage_chooser.length) { var cdimage2_chooser = $('#id_iso2-image'); var cdimage_once = $('#id_iso-image-once').prop('checked'); var iso = cdimage_chooser.val(); var ret = [iso, cdimage_once, null]; // Save last choice if not checked if (!cdimage_once && iso) { mod.data('last_cdimage', iso); } else { mod.data('last_cdimage', ''); } if (cdimage2_chooser.length) { ret[2] = cdimage2_chooser.val(); } return ret; } return [false, undefined, undefined]; }
[ "function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}", "function iso_image_value_restore(mod) {\n if (mod.data('last_cdimage')) {\n $('#id_iso-image').val(mod.data('last_cdimage'));\n $('#id_iso-image-once').prop('checked', false);\n }\n}", "function calculateImageSize(value) {\r\n\r\n}", "get src() {\n this._logService.debug(\"gsDiggThumbnailDTO.src[get]\");\n return this._src;\n }", "function processImageToString(image) {\n\treturn image.toString();\n}", "function getImagePath(source){\n\tvar urlPath = url.parse(source).path;\n\tvar lastPath = _.last(urlPath.split(\"/\"));\n\tvar savePath = ORGINAL_IMAGE_PATH + lastPath;\n\treturn savePath;\n}", "function escogerImagen(objeto)\n{\n var imagen=\"\";\n\n if(objeto.estado == \"Clear\")\n {\n imagen=\"sol.png\";\n }\n else if(objeto.estado == \"Rain\")\n {\n imagen=\"lluvia.png\";\n }\n else if(objeto.estado == \"Clouds\")\n {\n imagen=\"nublado.png\";\n }\n else\n {\n imagen=\"nevado.png\";\n }\n\n return imagen;\n}", "function makeImageHtmlStringFromXMLObject(obj) {\n if ($(obj)[0] && $(obj)[0].data) {\n let data = $(obj)[0].data;\n data = data.replace(/\\\\/g, \"/\");\n let name = data.substr(data.lastIndexOf('/') + 1);\n let path = '<ac:image>' +\n '<ri:attachment ri:filename=\"' + name + '\" >' +\n '<ri:page ri:content-title=\"' + space.homepage.title + '\"/>' +\n '</ri:attachment>' +\n '</ac:image>';\n return path;\n };\n return \"\"\n }", "function getImage(direction){\r\n\t\r\n\tswitch(direction){\r\n\t\tcase 1:\r\n\t\t\timage = BS_N;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 2:\r\n\t\t\timage = BS_NE;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 3:\r\n\t\t\timage = BS_E;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 4:\r\n\t\t\timage = BS_SE;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 5:\r\n\t\t\timage = BS_S;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 6:\r\n\t\t\timage = BS_SW;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 7:\r\n\t\t\timage = BS_W;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 8:\r\n\t\t\timage = BS_NW;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tdefault:\r\n\t\t\timage = BS_E;\r\n\t}\r\n\treturn image;\r\n}", "function getCharImage(characterValue) { \r\n \r\n var filmValue = $StarWarsFilms.val();\r\n \r\n if (characterValue === '87'){\r\n return '<img src=\"Images/char' + characterValue + '.png\" />';\r\n }\r\n else if (filmValue === '7' && characterValue === '14')\r\n {\r\n return '<img src=\"Images/HanForceAwakens.jpg\" />';\r\n } \r\n else {\r\n return '<img src=\"Images/char' + characterValue + '.jpg\" />';\r\n } \r\n }", "cardName() {\n\t\tlet v = this.value()\n\t\tlet t = this.type()\n\t\treturn `assets/images/cards/${[VALUES_NAME[v], TYPES_NAME[t]].join('_of_')}.png`\n\t}", "function getTiffFromFile() {\n GeoTIFF.fromFile(\"D:/wxy/Node/nc-tiff-tool/public/tiff/test/variable-pratesfc_time-1609113600.tif\")\n .then(async (tiff) => {\n const image = await tiff.getImage();\n //console.log(`image+${image}`)\n // const width = image.getWidth();\n // const height = image.getHeight();\n // const tileWidth = image.getTileWidth();\n // const tileHeight = image.getTileHeight();\n // const samplesPerPixel = image.getSamplesPerPixel();\n // const origin = image.getOrigin();\n // const resolution = image.getResolution();\n const bbox = image.getBoundingBox();\n //const imageData = await tiff.readRasters();\n const data = await image.readRasters();\n console.log(data)\n const getFileDirectory = image.getFileDirectory()\n const noData = image.getGDALNoData()\n console.log(Number(noData))\n console.log(getFileDirectory)\n })\n}", "function IMNGetHeaderImage()\n{\n return \"imnhdr.gif\";\n}", "function getImageNameByJsonType(jsonType) {\n\tjsonType = jsonType.trim();\n\tvar imageName = \"\";\n\tif(jsonTypeConstant.BLACKHAWK === jsonType) {\n\t\timageName = \"reloadit\";\n\t} else if(jsonTypeConstant.PRECASH === jsonType) {\n\t\timageName = \"evolvepb-logo_small\";\n\t} else if(jsonTypeConstant.INCOMM === jsonType) {\n\t\timageName = \"biller_logo_icon\";\n\t} else {\n\t\timageName = \"logo\";\n\t}\n\treturn imageName;\n}", "function getISODate(date) {\n let isoDate = '';\n let d = new Date(date);\n\n // If date is valid get ISO format\n if (!isNaN( d.getTime())) {\n isoDate = d.toISOString().substring(0,10);\n }\n \n return isoDate;\n }", "get originalWidth() {\n this._logService.debug(\"gsDiggThumbnailDTO.originalWidth[get]\");\n return this._originalWidth;\n }", "function getBestQuality (photo) {\n if (photo.hasOwnProperty(\"photo_2560\")) return photo.photo_2560\n if (photo.hasOwnProperty(\"photo_1280\")) return photo.photo_1280\n if (photo.hasOwnProperty(\"photo_807\")) return photo.photo_807\n if (photo.hasOwnProperty(\"photo_604\")) return photo.photo_604\n if (photo.hasOwnProperty(\"photo_130\")) return photo.photo_130\n if (photo.hasOwnProperty(\"photo_75\")) return photo.photo_75\n }", "function getIllustration(weatherIcon) {\n let temp = (props.iconCode.temperature);\n let illustrationImg = \"\";\n switch (weatherIcon) {\n case \"01d\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgSunny;\n }\n break;\n case \"01n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgNight;\n }\n break;\n case \"02d\":\n case \"02n\":\n case \"03d\":\n case \"03n\":\n case \"04d\":\n case \"04n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgCloudy;\n }\n break;\n case \"09d\":\n case \"09n\":\n case \"10d\":\n case \"10n\":\n illustrationImg = ImgRain;\n break;\n case \"11d\":\n case \"11n\":\n illustrationImg = ImgThunder;\n break;\n case \"13d\":\n case \"13n\":\n illustrationImg = ImgSnow;\n break;\n case \"50d\":\n case \"50n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgMisty;\n }\n break;\n default: illustrationImg = ImgCloudy;\n }\n return illustrationImg;\n }", "get contentType() {\n this._logService.debug(\"gsDiggThumbnailDTO.contentType[get]\");\n return this._contentType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function, `deepDup(arr)`, that will perform a "deep" duplication of the array and any interior arrays. A deep duplication means that the array itself, as well as any nested arrays (no matter how deeply nested) are duped and are completely different objects in memory than those in the original array.
function deepDup(arr) { let duped = []; for (let i = 0; i < arr.length; i++) { let ele = arr[i]; if (Array.isArray(ele)) { duped.push(deepDup(ele)); } else { duped.push(ele); } } return duped; }
[ "function deepClone(array) {\n return JSON.parse(JSON.stringify(array));\n}", "function duplicate(arr){\n arr.forEach(item => arr.push(item))\n return arr;\n}", "function duplicates(arr) {\n \n // our hash table to store each element\n // in the array as we pass through it\n var hashTable = [];\n \n // store duplicates\n var dups = [];\n \n // check each element in the array\n for (var i = 0; i < arr.length; i++) {\n \n // if element does not exist in hash table\n // then insert it\n if (hashTable[arr[i].toString()] === undefined) {\n hashTable[arr[i].toString()] = true;\n } \n \n // if element does exist in hash table\n // then we know it is a duplicate\n else { dups.push(arr[i]); }\n \n }\n \n return dups;\n \n}", "function dupelements(arr,a,b){\n\tvar dup = []; \n for(var i=a+1;i<b;i++){\n\tdup.push(arr[i]);\n}\nreturn dup;}", "function deepClone(el) {\r\n var clone = el.cloneNode(true);\r\n copyStyle(el, clone);\r\n var vSrcElements = el.getElementsByTagName(\"*\");\r\n var vDstElements = clone.getElementsByTagName(\"*\");\r\n for (var i = vSrcElements.length; i--;) {\r\n var vSrcElement = vSrcElements[i];\r\n var vDstElement = vDstElements[i];\r\n copyStyle(vSrcElement, vDstElement);\r\n }\r\n return clone;\r\n}", "function checkDuplicate(arr){\n return (new Set(arr)).size !== arr.length\n}", "function deepCopy (obj, up, level) { //** With changes made to deepUpdate, is this now the same as deepProto??? ****I think it's a little different... I think the copy has no prototype at the top level, so a shallowClear will result in an empty object.\r\n\t//**I think there's a problem here now. Changing <obj> will change the copy.... ****I think we need to bring back the old deepUpdate that doesn't use deepProto... we want to keep the new version to. How do we name them?\r\n\t//**For deep copy... first use new deepUpdate, then re-update the result with the old deepUpdate. Or maybe deepUpdate should do both of these always??? No... I don't think so...\r\n\t\tvar copy = deepUpdate({}, obj);\t\t\r\n\t\treturn up?\r\n\t\t\tdeepUpdate(copy, up, level):\r\n\t\t\tcopy;\r\n\t}", "function remove_duplicates(arr) {\n console.log(\"Duplicates removed from array\");\n}", "deepAssign(orig,obj) {\n var v;\n for( var key in obj ) {\n v=obj[key];\n if( typeof v===\"object\" ) {\n orig[key]=Array.isArray(v)?[]:{};\n this.deepAssign(orig[key],v);\n } else {\n orig[key]=v;\n }\n }\n }", "function deepClone(o, visited){\n\t\tif(!visited){\n\t\t\tvisited = [];\n\t\t}\n\t\tvar newitem = clone(o);\n\t\tfor(var key in newitem){\n\t\t\tvar child = newitem[key];\n\t\t\tif($.inArray(child, visited) || child === getGlobal()){ //try to prevent circular or runaway\n\t\t\t\tcontinue; //skip this value\n\t\t\t}\n\t\t\tvisited.push(child);\n\t\t\tnewitem[key] = deepClone(child, visited);\t\t\t\t\n\t\t}\n\t\treturn newitem;\n\t}", "function mirror(arr) {\n\tconst a = arr;\n\tfor (let i = arr.length - 2; i >= 0; i--) {\n\t\ta.push(arr[i]);\n\t}\n\treturn a;\n}", "function unique(arr) {\n return Array.from(new Set(arr));\n }", "function hasDuplicateValue(array) {\n let steps = 0;\n for (let i = 0; i < array.length; i++) {\n for (let j = 0; j < array.length; j++) {\n steps++;\n if (i !== j && array[i] === array[j]) {\n return true;\n }\n }\n }\n console.log(`total steps(nested loop): ${steps}`);\n return false;\n}", "function allSame (arr) {\n\t if (!Array.isArray(arr)) {\n\t return false\n\t }\n\t if (!arr.length) {\n\t return true\n\t }\n\t var first = arr[0]\n\t return arr.every(function (item) {\n\t return item === first\n\t })\n\t}", "function unique(A) {\n if (A instanceof NdArray) {\n A = A.toArray();\n }\n\n var hash = {}, result = [];\n for ( var i = 0, l = A.length; i < l; ++i ) {\n if ( !hash.hasOwnProperty(A[i]) ) { \n hash[ A[i] ] = true;\n result.push(A[i]);\n }\n }\n return result;\n }", "function decycle(obj) {\n var seen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();\n\n if ( !obj || _typeof$1(obj) !== 'object') {\n return obj;\n }\n\n if (seen.has(obj)) {\n return '[Circular]';\n }\n\n var newSeen = seen.add(obj);\n\n if (Array.isArray(obj)) {\n return obj.map(function (x) {\n return decycle(x, newSeen);\n });\n }\n\n return Object.fromEntries(Object.entries(obj).map(function (_ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n\n return [key, decycle(value, newSeen)];\n }));\n }", "function removeDuplicatePlaces(array) {\n var a = array.concat();\n for (var i = 0; i < a.length; ++i) {\n for (var j = i + 1; j < a.length; ++j) {\n if (a[i].placeId === a[j].placeId) {\n a[j].destroy();\n a.splice(j--, 1);\n }\n }\n }\n return a;\n }", "function mirror(arr) {\n\tlet obj = {};\n\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tobj[arr[i]] = arr[i];\n\t}\n\n\treturn obj;\n}", "function isunique(arr)\n {\n var charecterValue1 = 0;\n var charecterValue2 = 0;\n var hasdup = false;\n do\n {\n for(i = 0; i <= arr.length; i++)\n {\n \n for(j = i; j < arr.length; j++)\n { \n charecterValue1 = parseInt($(arr[i]).attr(\"value\"));\n charecterValue2 = parseInt($(arr[j]).attr(\"value\"));\n if(i != j && charecterValue1 == charecterValue2)\n {\n $(arr[j]).attr(\"value\", genRandomNum(1, 12));\n isunique(imageIds);\n hasdup = true;\n }\n else\n {\n hasdup = false;\n }\n }\n }\n } while (hasdup == true); \n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to check if cllick position is inside a card in the play area
function isInside(x, y, card) { let w = card.image.width let h = card.image.height let cx = card.x let cy = card.y if ( x > cx && x < ( cx + w ) && y > cy && y < ( cy + h ) && card.state == 'table') { return {w: w, h: h, cx: cx, cy: cy} } else { return false } }
[ "function checkColision(cactus){\n const dinoY = dino.style.bottom.split('px')[0]\n const cactusX = cactus.offsetLeft;\n \n if(cactusX <= divSize && cactusX >= -divSize && dinoY<= divSize){\n //log(true)\n inGame = false;\n }else{\n //log(false);\n }\n}", "function isOpenPos(x, y) {\n\tif (x < 0 && x >= canvasWidth / pieceSize) {\n\t\treturn false;\n\t}\n\tif (y < 0 && y >= canvasHeight / pieceSize) {\n\t\treturn false;\n\t}\n\n\tswitch(board[y][x]) {\n\t\tcase 3: // Wall\n\t\t\treturn false;\n\t\tcase 2: // Monster\n\t\t\treturn false;\n\t\tcase 1: // Player\n\t\t\treturn false;\n\t\tcase 0: // Empty\n\t\t\treturn true;\n\t}\n}", "function checkPosition() {\n\tconst heart = document.getElementById(\"profile-heart\");\n\tconst cross = document.getElementById(\"profile-cross\");\n\tconst qmark = document.getElementById(\"qmark\");\n\n\tif (this.x > 0) {\n\t\tcross.style.opacity = 0;\n\t\theart.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\theart.style.animationPlayState = \"running\";\n\t}\n\tif (this.x < 0) {\n\t\theart.style.opacity = 0;\n\t\tcross.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\tcross.style.animationPlayState = \"running\";\n\t}\n}", "checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }", "function isPriorCardOnScreen(_cardNum) {\n var priorCardNum = activeCardNum - 1;\n\n // Adapted from https://docs.mapbox.com/mapbox-gl-js/example/scroll-fly-to/\n var element = document.querySelector(\"div[data-index='\" + String(priorCardNum) + \"']\")\n var bounds = element.getBoundingClientRect();\n\n return bounds.bottom > window.innerHeight / 2;\n}", "canPlaceBelow(card) {\n return card.suit.oppositeColor(this.suit) && this.cardVal.canPlaceBelow(card.cardVal);\n }", "function isNextCardOnScreen() {\n\n var nextCardNum = activeCardNum + 1;\n\n if (activeCardNum == cardData.length - 1) {\n return false;\n }\n // Adapted from https://docs.mapbox.com/mapbox-gl-js/example/scroll-fly-to/\n var element = document.querySelector(\"div[data-index='\" + String(nextCardNum) + \"']\")\n var bounds = element.getBoundingClientRect();\n\n return bounds.top < window.innerHeight / 2;\n}", "reachedTargetPosition() {\n if (this.target !== undefined) {\n let targetCenter = this.getTargetCenter();\n let ownCenter = this.getCenter();\n // console.log(ownCenter);\n // console.log(targetCenter);\n var distance = Phaser.Math.Distance.Between(\n ownCenter.x,\n ownCenter.y,\n targetCenter.x,\n targetCenter.y\n );\n if (distance < 10) {\n return true;\n }\n // console.log(distance);\n }\n return false;\n }", "canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}", "function is_captured() {\n if (Math.abs(hero.pos.x - zombie.pos.x) < char_size) {\n if (Math.abs(hero.pos.y - zombie.pos.y) < char_size) {\n return true;\n }\n }\n return false;\n }", "function checkCollision(x, y, w, h) {\n if( (chickenX + chickenSize) >= x && \n (chickenY + chickenSize) >= y && \n (chickenX) <= (x + w) && \n (chickenY) <= (y + h)){\n return true;\n } else {\n return false;\n }\n}", "function checkColision(){\n return obstacles.obstacles.some(obstacle => {\n if(obstacle.y + obstacle.height >= car.y && obstacle.y <= car.y + car.height){\n if(obstacle.x + obstacle.width >= car.x && obstacle.x <= car.x + car.width){\n console.log(\"colision\")\n return true;\n }\n }\n return false;\n });\n}", "collide(rect) {\n return (this.left < rect.right && this.right > rect.left &&\n this.top < rect.bottom && this.bottom > rect.top);\n }", "has_ace() {\n if (this.mycards.includes(1)) return true;\n return false;\n }", "function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}", "function isInside(rw, rh, rx, ry, x, y)\n{\n return x <= rx+rw && x >= rx && y <= ry+rh && y >= ry // Get Click Inside a Bush\n}", "function cardOnHand() {\n if (player.selectedCarte.visible) return 1;\n else if (playerHand.selectedCarte.visible) return 2;\n else if (playerBoard.selectedCarte.visible) return 3;\n else if (playerPower.selectedCarte.visible) return 4;\n else return 0;\n}", "hasBlockAt(position) {\n\t\tconst xVals = this.blocks.get(position.y);\n\t\treturn (xVals && xVals.has(position.x)) || false;\n\t}", "static boardCheck(card, board) {\n var cardFound = false;\n // Goes though entire deck and makes cardFound true if card is found\n for (let cardTest of board) {\n if (card.shape == cardTest.shape && card.color == cardTest.color &&\n card.shading == cardTest.shading && card.number == cardTest.number) {\n cardFound = true;\n }\n }\n return cardFound;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trims a timeline so that objects only exist within a specified time period.
trimTimeline(timeline, trim) { // The new resolved objects. let newObjects = {}; // Iterate through resolved objects. Object.keys(timeline.objects).forEach((objId) => { const obj = timeline.objects[objId]; const resultingInstances = []; obj.resolved.instances.forEach(instance => { // Whether to insert this object into the new timeline. let useInstance = false; let newInstance = Object.assign({}, instance); // clone // If trimming the start time. if (trim.start) { // If the object ends after the trim start time. if ((instance.end || Infinity) > trim.start) { useInstance = true; if (newInstance.start < trim.start) { newInstance.start = trim.start; } } } // If trimming the end time. if (trim.end) { // If the object starts before the trim end time. if (instance.start < trim.end) { useInstance = true; if ((newInstance.end || Infinity) > trim.end) { newInstance.end = trim.end; } } } if (!trim.start && !trim.end) { useInstance = true; } if (useInstance && newInstance.start < (newInstance.end || Infinity)) { resultingInstances.push(newInstance); } }); // If there isn't a resolved object for the new instance, create it. if (!newObjects[objId]) { let newObject = { content: obj.content, enable: obj.enable, id: obj.id, layer: obj.layer, resolved: { instances: [], levelDeep: obj.resolved.levelDeep, resolved: obj.resolved.resolved, resolving: obj.resolved.resolving } }; newObjects[objId] = newObject; } newObjects[objId].resolved.instances = resultingInstances; }); return { classes: timeline.classes, layers: timeline.layers, objects: newObjects, options: timeline.options, statistics: timeline.statistics, state: timeline.state, nextEvents: timeline.nextEvents }; }
[ "function validateTimeline(timeline, strict) {\n var uniqueIds = {};\n _.each(timeline, function (obj) {\n validateObject0(obj, strict, uniqueIds);\n });\n}", "checkStartTimes() {\n if (Object.keys(this.startTimes).length > 0) { // Are there any startTimes to check?\n let thisDate = new Date();\n for (var i=0, keys=Object.keys(this.startTimes); i < keys.length; i++) {\n let startDate = this.startTimes[keys[i]], endDate = this.endTimes[keys[i]];\n if (!this.groupStatus[keys[i]].collecting) { // Is the group already collecting then skip check.\n if (thisDate > startDate && (!endDate || (endDate && startDate < endDate)) ) this.toggle(keys[i]);\n } else { // Group is collecting and has a start time so check end time\n if (!endDate) { delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n else if (endDate && endDate < thisDate) { this.toggle(keys[i]); delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n }\n startDate = null; endDate = null;\n }\n thisDate = null;\n }\n }", "function deletePastVacationDays(){\n\tvar l = U.profiles.length;\n\t//console.log(\"We have \" + l + \" profiles to check.\");\n\tfor(i=0;i<l;i++){\n\t\t//Attend to vacationDays in each profile\n\t\tvar v = U.profiles[i].vacationDays.length;\n\t\t//console.log(\"====>The profile \" + U.profiles[i].profileName + \" has \" + v + \" vacation days.\");\n\t\t\n\t\tif(v > 0){\n\t\t\t//If there are any vacationDays, loop through them and delete any that are past\n\t\t\tfor(x=0;x<v;x++){\n\t\t\t\tvar vacationDayToTest = U.profiles[i].vacationDays[0];\n\t\t\t\t//console.log(\"Testing the vacation day \" + U.profiles[i].vacationDays[0]);\n\t\t\t\tif(new Date(U.profiles[i].vacationDays[0]).getTime() < new Date(today.toDateString()).getTime()){\n\t\t\t\t\t//console.log(\"That vacation day is in the past! Removing it...\");\n\t\t\t\t\tU.profiles[i].vacationDays.splice(0,1);\n\t\t\t\t}else{\n\t\t\t\t\t//console.log(\"That vacation day checks out fine. We're done checking this profile.\");\n\t\t\t\t\t//Vacation days are ordered chronologically, so once we find one that is not past, we know the rest will be fine too\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function filterTweets (twits, callback) {\n var tmpArr = [];\n async.each(twits.statuses, function(item, callback){\n if(moment().subtract(1, 'day').format() <= item.created_at) {\n tmpArr.push(item);\n }\n callback();\n },function(err){\n if(err) callback(err);\n else callback(null, tmpArr);\n })\n}", "function resetTimelines() {\n // clear `currentTimeline`\n if (V.Navigation) {\n V.Navigation.currentTimeline = null;\n }\n\n // get all `V.Timelines` keys\n var keys = Object.keys(V.Timelines);\n\n for (var i = 0, iMax = keys.length; i < iMax; i++) {\n // check that this key represents a timeline\n if (V.Timelines[keys[i]].elementsSelector) {\n // clear inline styles from timelines\n TweenLite.set(V.Timelines[keys[i]].elementsSelector, {clearProps: 'all'});\n V.Timelines[keys[i]].needsRebuild = true;\n }\n }\n }", "unschedule (runner) {\r\n var index = this._runnerIds.indexOf(runner.id);\r\n if (index < 0) return this\r\n\r\n this._runners.splice(index, 1);\r\n this._runnerIds.splice(index, 1);\r\n\r\n runner.timeline(null);\r\n return this\r\n }", "function filterByTime(time) {\n return statuses => {\n return statuses.filter(\n status => moment(status.created_at, \"ddd MMM DD HH:mm:ss ZZ YYYY\") >= time\n );\n };\n}", "function moveToCurrentTime() {\r\n timeline.setVisibleChartRangeNow();\r\n}", "deleteAppointment(date,time)\n {\n if (this.map.has(date)) {\n\n for (let i=0; i<this.map.get(date).length; i++)\n {\n if (this.map.get(date)[i].date == date && this.map.get(date)[i].time == time) {\n this.map.get(date).splice(i,1);\n break;\n }\n }\n }\n }", "function removeDeadUsers() {\n users = users.filter(function(user) {\n return Math.round((Date.now()-user.time)) < 20000;});\n console.log(\"Removed dead users\");\n}", "function adjustVisibleTimeRangeToAccommodateAllEvents() {\r\n timeline.setVisibleChartRangeAuto();\r\n}", "function MM_timelineStop(tmLnName) { //v1.2\n //Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004 Macromedia, Inc. All rights reserved.\n if (document.MM_Time == null) MM_initTimelines(); //if *very* 1st time\n if (tmLnName == null) //stop all\n for (var i=0; i<document.MM_Time.length; i++) document.MM_Time[i].ID = null;\n else document.MM_Time[tmLnName].ID = null; //stop one\n}", "function RemoveOutOfDateRangeGroups(groups) {\n \n for (var i = groups.length - 1; i >= 0; i--) {\n if (groups[i].cases === 0 && groups[i].deaths === 0) {\n groups.splice(i, 1);\n }\n }\n}", "function clampTimeRange(range, within) {\n if (within) {\n if (range.overlaps(within)) {\n var start = range.start < within.start ?\n range.start > within.end ?\n within.end :\n within.start : range.start;\n var end = range.end > within.end ?\n range.end < within.start ?\n within.start :\n within.end : range.end;\n if (start > end) {\n [start, end] = [end, start];\n }\n return moment.range(start, end);\n } else {\n return null;\n }\n } else {\n return range;\n }\n}", "function pruneUtts(utts) {\n if (Object.keys(utts).length < 10) return utts\n\n const slicedKeys = Object.keys(utts).sort((a, b) => {\n const aTime = parseInt(utts[a][0].timestamp, 10)\n const bTime = parseInt(utts[b][0].timestamp, 10)\n if (aTime < bTime) {\n return 1\n } else if (bTime < aTime) {\n return -1\n } else {\n return 0\n }\n }).slice(0, 7)\n\n const newUtts = {}\n for (const key of slicedKeys)\n newUtts[key] = utts[key]\n\n return newUtts\n}", "adjustTaskStartTime(index) {\n if(index < this._taskArr.length && index > 0) {\n let curr = this._taskArr[index];\n let prev = this._taskArr[index - 1];\n if(prev.endTime.compareTo(curr.endTime) >= 0) {\n this.removeAtIndex(index);\n } else {\n curr.setStartTime(prev.endTime);\n }\n }\n }", "#removeExpiredTimestamps(key) {\n const timestampsArray = this.#apiCallTimeStamps[key]\n const now = Date.now()\n const oneMinuteAgo = now - 1000\n let index = 0\n while (index < timestampsArray.length && timestampsArray[index] <= oneMinuteAgo) {\n index += 1\n }\n\n timestampsArray.splice(0, index)\n }", "async pruneFrames() {\n let entries;\n try {\n entries = await webext.webNavigation.getAllFrames({\n tabId: this.tabId\n });\n } catch(ex) {\n }\n if ( Array.isArray(entries) === false ) { return; }\n const toKeep = new Set();\n for ( const { frameId } of entries ) {\n toKeep.add(frameId);\n }\n const obsolete = Date.now() - 60000;\n for ( const [ frameId, { t0 } ] of this.frames ) {\n if ( toKeep.has(frameId) || t0 >= obsolete ) { continue; }\n this.frames.delete(frameId);\n }\n }", "removeFront() {\n this._taskArr.shift();\n /*\n if(this._taskArr.length === 1) {\n \n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[0];\n let next = this._taskArr[1];\n next.setStartTime(curr.startTime);\n this._taskArr.shift();\n }\n */\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the value back to the default.
clear() { this.set(this.DEFAULT_VALUE); }
[ "reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}", "_clearDate() {\n this.value = undefined;\n this.display = '';\n }", "clearDisplay() {\n\t\tconst {displayValue} = this.state\n\t\tthis.setState({\n\t\t\tdisplayValue: '0'\n\t\t})\n\t}", "function inputClear(){\n display.value = \"\";\n}", "_onClearButtonClick() {\n this.value = '';\n this._inputValue = '';\n this.validate();\n this.dispatchEvent(new CustomEvent('change', { bubbles: true }));\n }", "reset() {\n this.tag = this.default;\n }", "function promptengine_resetValueField (\r\n form,\r\n valueID)\r\n{\r\n valueField = form[valueID];\r\n valueField.value = \"\";\r\n}", "function clear(event) {\n\tevent.preventDefault();\n\tfirstInput.value = null;\n}", "function clearScreen() {\n calculator.displayValue = '0';\n calculator.firstOperand = null;\n calculator.waitForNextOperand = false;\n calculator.operator = null;\n calculator.inBaseTen = true;\n}", "function resetPlainTypedValues() {\n scope.valueStore.lang.setData('');\n scope.valueStore.dtype.setData('');\n scope.lang = '';\n scope.type = '';\n }", "function clearElementValue ( id )\n {\n\tvar elt = myGetElement(id);\n\n\tif ( elt && elt.type && elt.type == \"checkbox\" )\n\t elt.checked = 0;\n\n\telse if ( elt )\n\t elt.value = \"\";\n }", "function clearEntry() {\n changeDisplay('0');\n }", "function resetInputField(field) {\n field.value=\"\";\n}", "resetAll () {\n this.data = this.defaults\n }", "function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }", "function dropdownEmpty() {\n $('.languageValue,.originValue').val(\"\");\n }", "restoreOriginalState() {\n\n\t\t\tconst originalValueOffset = this.valueSize * 3;\n\t\t\tthis.binding.setValue( this.buffer, originalValueOffset );\n\n\t\t}", "function answerBoxClear(){\n $(\"#answerBox\").val('');\n}", "_clearSavedSelection() {\n this._savedSelection = null;\n }", "function reset_form_input_reward_tensor(){\n document.getElementById(\"reward_tensor\").value=\"\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task 6 Find max product of triplets
function findMaxProduct(array) { }
[ "function MaximumProductOfThree(arr) {\n let maxArr = [];\n for (let i = 0; i < arr.length; i++) {\n let maxNum = Math.max(...arr);\n maxArr.push(maxNum);\n if (maxArr.length === 3) {\n return maxArr[0] * maxArr[1] * maxArr[2];\n }\n }\n return \"error\";\n}", "function bruteForceMaxSubarray(numbers) {\n let n = numbers.length; \n let res = 0; \n\n for (let i = 0; i < n; ++i) {\n let sum = 0; \n for (let j = i; j < n; ++j) {\n // for every subarray [i ... j]\n sum += numbers[j]; \n res = Math.max(res, sum);\n }\n }\n return res; \n }", "function largestMult(x,y,grid,directions){\n let largest = 0\n directions.forEach((e)=>{\n let localRes = mult(x,y,grid,e[0],e[1])\n // console.log(localRes)\n if (localRes>largest){\n largest = localRes\n }\n })\n return largest\n}", "function highestProduct2(arr){\nvar point1 = 0;\nvar point2 = 0;\n}", "function findMaxNegProd(arr) {\n if ((arr.filter(item => Array.isArray(item))).length === 0) {\n console.log(\"Invalid argument\");\n return;\n }\n const filterMinus = (arr.map(item => item.filter(item => item < 0)));\n const filterEmptyArr = filterMinus.filter(item => item.length !== 0);\n if (filterEmptyArr.length === 0) {\n console.log(\"No negatives\");\n return;\n }\n const maxMinus = filterEmptyArr.map(item => Math.max.apply(null, item));\n const product = maxMinus.reduce((a,b) => a*b);\n console.log(product);\n}", "function findOptimalCombination(cities, i, j) {\n\n var m_profits = cities[i][j].profits_array;\n var e_profits = cities[i][j - 1].profits_array;\n var o_profits = cities[i][j - 2].profits_array;\n var g_profits = cities[i][j - 3].profits_array;\n var n_profits = cities[i][j - 4].profits_array;\n\n var biggest_sum = 0;\n var optimal_combination = [0, 0, 0, 0, 0];\n\n var new_sum;\n\n for (var m = 0; m < m_profits.length; m++) {\n\n for (var e = 0; e < e_profits.length; e++) {\n\n for (var o = 0; o < o_profits.length; o++) {\n\n for (var g = 0; g < g_profits.length; g++) {\n\n for (var n = 0; n < n_profits.length; n++) {\n\n new_sum = m_profits[m] + e_profits[e] + o_profits[o] + g_profits[g] + n_profits[n];\n\n if (\n (new_sum > biggest_sum) &&\n ((m != e || e == 4) && (m != o || o == 3) && (m != g || g == 2) && (m != n || n == 1)) &&\n ((e != o || o == 3) && (e != g || g == 2) && (e != n || n == 1)) &&\n ((o != g || g == 2) && (o != n || n == 1)) &&\n ((g != n || n == 1))\n ) {\n biggest_sum = new_sum;\n optimal_combination[4] = m;\n optimal_combination[3] = e;\n optimal_combination[2] = o;\n optimal_combination[1] = g;\n optimal_combination[0] = n;\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n cities[i][j].optimal_combination = optimal_combination;\n\n}", "function highestProductOf3(array) {\n //check that array has at least 3 elements\n if (array.length < 3) {throw new Error('Less than 3 items!')}\n\n // start at the 3rd item (index 2)\n // so pre-populate highest and lowest based on\n // the first 2 items\n\n let highest = Math.max(array[0], array[1]);\n let lowest = Math.min(array[0], array[1]);\n\n let highestProductOf2 = array[0] * array[1];\n let lowestProductOf2 = array[0] * array[1];\n\n let highestProductOf3 = array[0] * array[1] * array[2];\n\n //walk thorugh the items, starting at index 2\n for (let i = 2; i < array.length ; i++) {\n let current = array[i]\n\n //do we have a highest product of 3?\n // it's either the current highest,\n // or the current times the highest prod of 2\n // or the current times the lowest prod of 2\n highestProductOf3 = Math.max(\n highestProductOf3,\n current * highestProductOf2,\n current * lowestProductOf2\n );\n\n // do we have a new highest product of two?\n highestProductOf2 = Math.max(\n highestProductOf2,\n current * highest,\n current * lowest\n );\n\n lowestProductOf2 = Math.min(\n lowestProductOf2,\n current * highest,\n current * lowest\n )\n\n // do we have a new highest?\n highest = Math.max(highest, current);\n\n //do we have a new lowest?\n lowest = Math.min(lowest, current);\n }\n return highestProductOf3;\n}", "function maxLoot_(arr){\n let n = arr.length;\n if(n==0)\n return 0;\n let value1 = arr[0];\n if(n==1)\n return value1;\n \n let value2 = Math.max(arr[0] , arr[1]);\n if(n == 2)\n return value2;\n let maxValue = 0;\n for(let i = 2 ; i < n ; i++){\n maxValue = Math.max(arr[i]+ value1 , value2);\n value1= value2;\n value2 = maxValue;\n }\n return maxValue;\n}", "function largest_palindrome(min, max) {\n var i, j, product, answer = 0;\n\n for (i = min; i < max; i++) {\n for (j = i; j < max; j++) {\n product = i * j;\n if (product > answer && isPalindrome(product)) { answer = product; }\n }\n }\n return answer\n}", "function adjacentElementsProduct(inputArray)\n{\n const size = inputArray.length;\n if(size < 2) {\n return NaN;\n }\n let max = inputArray[0] * inputArray[1];\n for(let i = 1; i < size - 1; ++i) {\n if(inputArray[i] * inputArray[i + 1] > max) {\n max = inputArray[i] * inputArray[i + 1];\n }\n }\n return max;\n}", "function find_desire_sum() {\n products = new Set();\n const MAX_ITER = 362880;\n for (let i = 0; i < MAX_ITER; i++) {\n let num = get_permutation_by_index(i, 9);\n if (\n parseInt(num.slice(0, 2)) * parseInt(num.slice(2, 5)) ===\n parseInt(num.slice(5)) ||\n parseInt(num.slice(0, 3)) * parseInt(num.slice(3, 5)) ===\n parseInt(num.slice(5)) ||\n parseInt(num.slice(0, 1)) * parseInt(num.slice(1, 5)) ===\n parseInt(num.slice(5)) ||\n parseInt(num.slice(0, 4)) * parseInt(num.slice(4, 5)) ===\n parseInt(num.slice(5))\n )\n products.add(parseInt(num.slice(5)));\n }\n sum = 0;\n products.forEach((element) => {\n sum += element;\n });\n return sum;\n}", "function maxLoot(arr) {\n let n = arr.length;\n //base case \n if (n == 0) // if any house are not exist\n return 0;\n if (n == 1) // if only one house are exist then loot that house \n return 1;\n if (n == 2) // if two house are exist then loot with maximux profit \n return Math.max(arr[0], arr[0]);\n\n //if there was more then two house then loot are carying from the dp table\n let dp = new Array(n);\n //fill the first and second value of dp\n dp[0] = arr[0];\n dp[1] = Math.max(arr[0], arr[1]);\n for (let i = 2; i < n; i++) {\n dp[i] = Math.max(dp[i - 2] + arr[i], dp[i - 1]);\n }\n console.log(arr[n-1]);\n return dp[n - 1];\n\n}", "function maximumToys(prices, budget) {\n prices = prices.sort((a, b) => a - b);\n let priceTotal = 0;\n let totalToys = 0;\n // assign index for while loop\n let index = 0;\n\n // // SOLUTION USING FOR EACH\n // prices.forEach((toy, index) => {\n // priceTotal += toy;\n // if (priceTotal <= budget) {\n // totalToys = index + 1;\n // }\n // });\n\n while (priceTotal <= budget && index < prices.length) {\n priceTotal += prices[index++];\n if (priceTotal <= budget) {\n totalToys += 1;\n }\n }\n return totalToys;\n}", "function findC(g, b) {\n // first sort the grants and get total\n // nlogn time\n g.sort(function compareNumbers(a, b) {\n return b - a;\n })\n console.log(g)\n var total = 150\n var neededCuts = total-b\n var runningTotal = 0\n \n for(var i=0; i<g.length; i++){\n var currentMax = g[i]\n if((g[i] - g[i+1]) >= neededCuts){\n return g[i] - neededCuts\n }\n console.log('current max: '+currentMax)\n console.log('difference: '+ (g[i] - g[i+1]))\n \n runningTotal += (g[i] - g[i+1])*(i+1)\n console.log('runningTotal: '+ runningTotal)\n console.log('----')\n\n if(runningTotal >= neededCuts){\n return (g[0]-g[i])+Math.floor(((runningTotal-neededCuts)/(i+1)))+1\n }\n \n // reduce max to next max or new budget, recursive\n // reduce 54 -> 32 += 18 of 30 needed\n // needs 12 more\n // reduce 32 -> 23 += 2x(9) = 18 above what is needed, c is above next max \n // and below current max\n }\n \n}", "function dynamicProgramming(shop, weight) {\n if (shop.length < 1 || weight < 1) return 0\n const table = [...Array(shop.length)].map(e => Array(weight + 1).fill(0))\n // for 0 weight capacity, the max value we can get is always 0\n for (let i = 0; i < shop.length; i++) {\n table[i][0] = 0\n }\n // if there's only 1 item, then it's just a matter of whether the capacity weight\n // can pick this item\n for (let i = 0; i < table[0].length; i++) {\n if (i < shop[0].weight) {\n table[0][i] = 0\n } else {\n table[0][i] = shop[0].value\n }\n \n }\n for (let row = 1; row < table.length; row++) {\n for (col = 1; col < table[row].length; col++) {\n if (col < shop[row].weight) {\n table[row][col] = table[row-1][col]\n } else {\n table[row][col] = Math.max(\n table[row-1][col],\n table[row-1][col - shop[row].weight] + shop[row].value\n )\n }\n }\n }\n return table[table.length-1][table[0].length-1]\n}", "function sumOrProduct(array, n) {\n array.sort(function(a, b){ \n return b - a;\n }) \n let sum = 0;\n let prod = 1; \n for (i = 0; i < n; i++) {\n sum = sum + array[i]; \n prod = prod * array[(array.length-1)-i]; \n }\n if (sum === prod) {\n return ('same');\n } else if (sum > prod) {\n return ('sum');\n } else {\n return ('product');\n }\n}", "function max_subarray(A){\n let max_ending_here = A[0]\n let max_so_far = A[0]\n\n for (let i = 1; i < A.length; i++){\n max_ending_here = Math.max(A[i], max_ending_here + A[i])\n // console.log(max_ending_here)\n max_so_far = Math.max(max_so_far, max_ending_here)\n // console.log(max_so_far)\n } \n\n return max_so_far\n}", "function multiplyAll(arr) {\n var product = 1;\n \n for (let i =0; i < arr.length; i++){\n for (let j=0; j < arr[i].length; j++){\n product*=arr[i][j]\n }\n }\n \n return product;\n }", "function maxofThree(a,b,c){\n return max(max(a,b),c);\n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recompute this DepItem, calling the callback given in the constructor.
recompute() { this._priority = 0; this._callback.call(this._context); }
[ "itemsChanged() {\n this._processItems();\n }", "_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }", "_invalidateSortCache() {\n this._sorted = {};\n }", "function onRecalculationPhase() {\n if (p.recalcQueued) {\n p.recalcPhase = 0;\n recalculateDimensions();\n } else if (p.recalcPhase == 1 && p.lastLocus) {\n p.recalcPhase = 2;\n p.flipper.moveTo(p.lastLocus, onRecalculationPhase, false);\n } else {\n Monocle.defer(afterRecalculate);\n }\n }", "callbackOrig(data) {\n this.state.extSetState({ origCollectionId: data.smart_collection.id });\n }", "constructor(item_list) {\n this.item_list = item_list\n this._resetLocalCache()\n }", "function redata(params, onUpdate) {\n // console.log('redata()', params);\n // If should not reload the data.\n if (!shouldReload(params)) {\n console.log('will not reload');\n // Inform any subscriber.\n onUpdate && onUpdate(ctx.lastData);\n\n // Resolve with last data.\n return Promise.resolve(ctx.lastData);\n }\n console.log('will reload');\n // Data not valid, will load new data and subscribe to its updates.\n // Reset lastData, since it is no longer valid.\n ctx.lastData = _extends({}, defaultInitialData);\n // debugger;\n // Update any subscriber about new data.\n onUpdate && onUpdate(ctx.lastData);\n\n // Store promise reference in order to check which is the last one if multiple resolve.\n ctx.promise = load(ctx, loader, params, onUpdate);\n // console.log('storing ctx promise', ctx.promise);\n ctx.promise.loader = loader;\n return ctx.promise;\n }", "recharge(additional_mp){\n\t\tthis.stats.mp.current = Math.max(\n\t\t\tMath.min(\n\t\t\t\tthis.stats.mp.current + additional_mp,\n\t\t\t\tthis.stats.mp.max\n\t\t\t),\n\t\t\t0\n\t\t);\n\n\t\treturn this;\n\t}", "setDirty() {\r\n this.onDirties.forEach(cb => cb());\r\n }", "_update() {\n if (this.hydrateOnUpdate()) {\n return super._update().then((model) => {\n Object.assign(this, model);\n return this;\n });\n }\n\n return super._update();\n }", "updateCustomerList() {\r\n this.customers = this.calculateCustomerInfo(this.orders);\r\n }", "setNeedsUpdate() {\n if (this.internalState) {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n }", "renderedCallback() {\n if (this.initialRender) {\n if (!this.disableAutoScroll) {\n this.setAutoScroll();\n }\n }\n this.initialRender = false;\n }", "function itemCallback(data){\n subtotal(data.salePrice);\n}", "recycle() {\n\t\tQuadTree.pool.push(this)\n\t\tthis.idx = 0 // array stays allocated, but points inside it are ignored\n\t\tif (this.nw) this._recycle()\n\t}", "modelDidReconstruct() {}", "function applyInitialDiscount() {\n var dis = __defaultDiscount();\n if (dis) {\n // do this after a timeout, because discountApply calls out into parent code, which expects\n // to have a fully-initialized CheckoutDiscount object at that point. We might be able to\n // eliminate this after we knockout-ize discountApply.\n setTimeout(function () {\n discountApply(dis, null, false);\n }, 0);\n }\n }", "clear() {\n this._storage.clear();\n this._allDependenciesChanged();\n this._updateLength();\n }", "apply(state) {\n let newCanvas = state.canvas.clone().drawStep(this)\n return new State(state.target, newCanvas, this.distance)\n }", "static detachListener(cb) {\n firebase.database().ref(BASE).off(\"value\", cb);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return if A is an ancestor of B.
function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } instB = getParent(instB); } return false; }
[ "function hasNodeAsAncestor(self, candidate) {\n\t\t\t\twhile ((self.parent != null) && (self.parent != candidate)) {\n\t\t\t\t\tself = self.parent;\n\t\t\t\t}\n\t\t\t\treturn ((self.parent == candidate) && (candidate != null));\n\t\t\t}", "function is_ancestor(node, target)\r\n{\r\n while (target.parentNode) {\r\n target = target.parentNode;\r\n if (node == target)\r\n return true;\r\n }\r\n return false;\r\n}", "isAncestor(path, another) {\n return path.length < another.length && Path.compare(path, another) === 0;\n }", "function hasAncestor(l, ance) {\n var tick, ancestor, ancestors = [1, 2, 3, 4, 5];\n\n if (typeof ance === 'string') {\n ancestor = queryDOM(ance);\n } else {\n ancestor = ance;\n }\n\n ancestors[0] = l.parentNode;\n ancestors[1] = ancestors[0].parentNode;\n\n if (!!ancestors[1].parentNode) {\n ancestors[2] = ancestors[1].parentNode;\n }\n if (!!ancestors[2].parentNode) {\n ancestors[3] = ancestors[2].parentNode;\n }\n if (!!ancestors[3].parentNode) {\n ancestors[4] = ancestors[3].parentNode;\n }\n //For inspection....\n // var dir = {};\n // dir.ance = ance;\n // dir.l = l;\n // dir.ancestor = ancestor;\n // dir.ancestors = ancestors;\n //\n // console.log(dir);\n\n tick = 0;\n\n for (var i = 0; i < ancestors.length; i++) {\n if (ancestors[i] === ancestor) tick++;\n }\n if (tick > 0) return true;\n\n else return false;\n}", "isAncestor(descendentHash, ancestorHash) {\n return Objects.ancestors(descendentHash).indexOf(ancestorHash) !== -1;\n }", "function isInclusiveAncestor(ancestor, descendant) {\n return ancestor === descendant || isAncestor(ancestor, descendant);\n}", "isAncestor(value) {\n return isPlainObject(value) && Node$1.isNodeList(value.children);\n }", "function isDescendantOf(a, b){\n\tif (a === b) return true\n\tif (descendantsLookup[b]) {\n\t\tif (descendantsLookup[b].indexOf(a) >= 0) return true;\n\t}\n\treturn false;\n}", "function isInclusiveDescendant(descendant, ancestor) {\n return descendant === ancestor || isDescendant(descendant, ancestor);\n}", "_hasScrolledAncestor(el, deltaX, deltaY) {\n if (el === this.scrollTarget || el === this.scrollTarget.getRootNode().host) {\n return false;\n } else if (\n this._canScroll(el, deltaX, deltaY) &&\n ['auto', 'scroll'].indexOf(getComputedStyle(el).overflow) !== -1\n ) {\n return true;\n } else if (el !== this && el.parentElement) {\n return this._hasScrolledAncestor(el.parentElement, deltaX, deltaY);\n }\n }", "function ancestorHasId(el, id) {\n var outcome = (el.id === id);\n while (el.parentElement && !outcome) {\n el = el.parentElement;\n outcome = (el.id === id);\n }\n return outcome;\n}", "function question2(pairs, A, B) {\n let indegree = new Map();\n let parentMap = new Map();\n for (let pair of pairs) {\n let parent = pair[0];\n let child = pair[1];\n\n if (!indegree.has(parent)) indegree.set(parent, 0);\n indegree.set(child, (indegree.get(child) || 0) + 1);\n\n let parentSet = parentMap.get(child) || [];\n parentSet.push(parent);\n parentMap.set(child, parentSet);\n }\n\n if (indegree.get(A) === 0 || indegree.get(B) === 0) return false;\n\n let ancestorOfA = new Set();\n getAncestor(A, ancestorOfA);\n let ancestorOfB = new Set();\n getAncestor(B, ancestorOfB);\n\n for (let el of ancestorOfA) {\n if (ancestorOfB.has(el)) return true;\n }\n\n return false;\n\n function getAncestor(child, list) {\n let queue;\n queue = parentMap.get(child);\n list.add(child);\n\n while (queue.length) {\n let curr = queue.shift();\n list.add(curr);\n let currParents = parentMap.get(curr) || [];\n for (let el of currParents) {\n queue.push(el);\n }\n }\n }\n}", "closest( child, ancestor ) {\n while ( child ) {\n if ( child === ancestor ) { return child; }\n child = child.parentNode;\n }\n\n return false;\n }", "function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }", "function commonAncestor(pathA, pathB, debug = false) {\n // make sure there are absolute\n if (pathA) pathA = path.resolve(pathA) \n if (pathB) pathB = path.resolve(pathB)\n if (!pathA) return pathB\n if (!pathB) return pathA\n let cnt = 0 // nb of common ancestor\n const a = split(pathA)\n const b = split(pathB)\n /* max common ancestor is defined by the shortest path */\n const max = a.length < b.length ? a.length : b.length\n /* nb of actual common ancestor */\n for (cnt = 0; cnt < max; cnt++) if (a[cnt] !== b[cnt]) break\n /* rebuild path */\n const ancestor = a.slice(0, cnt)\n if (debug) {\n console.log(pathA)\n console.log(pathB)\n console.log(join(ancestor, debug))\n }\n if (ancestor.length < 1) return null\n return join(ancestor)\n}", "isParent(path, another) {\n return path.length + 1 === another.length && Path.compare(path, another) === 0;\n }", "isDescendant(path, another) {\n return path.length > another.length && Path.compare(path, another) === 0;\n }", "hasInheritance(node) {\n let inherits = false;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (match_1.default(child, 'extends', 'implements')) {\n inherits = true;\n }\n }\n return inherits;\n }", "function isPartiallyContained(node, range) {\n var cond1 = isAncestorContainer(node, range.startContainer);\n var cond2 = isAncestorContainer(node, range.endContainer);\n return (cond1 && !cond2) || (cond2 && !cond1);\n}", "function intersect(a,b) {\n // find end node\n var endNode;\n while (a) {\n endNode = a;\n a = a.next;\n }\n // if a and b intersect, when I loop through b, it should also reach the same endNode at some point;\n while (b) {\n if (b === endNode) {\n return true;\n }\n b = b.next;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the toast manager state, finds the toast that matches the id and return its position and index
function findToast(toasts, id) { var position = getToastPosition(toasts, id); var index = position ? toasts[position].findIndex(toast => toast.id === id) : -1; return { position, index }; }
[ "function getValidIndex () {\n return $toasts.get().findIndex(toast => toast.key === toastId)\n }", "posById(id){\n let slot = this._index[id];\n return slot ? slot[1] : -1\n }", "modifyToast(index)\n {\n this.setState({toasts:this.state.toasts.slice(0,index+1)});\n }", "function getIndexOfMenuItem(truckID, name) {\n\t//aey - make sure truck exists\n\tif(doesTruckExist(truckID) == false) {\n\t\treturn -1;\n\t}\n\t//aey - make sure menu exists\n\tvar truck = getTruckWithID(truckID);\n\tif(isArrayEmpty(truck.menu)){\n\t\treturn -1;\n\t}\n\t\n\tif(doesMenuItemExist(truckID, name)) {\n\t\tfor(let i = 0; i < truck.menu.length; i++){\n\t\t\tif(truck.menu[i].name == name){ //aey - if found return index\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1; //aey - otherwise return -1 if error\n\t}\n}", "getIndex(id, data){\n for(let i=0; i<data.length; i++){\n if(id === data[i].id){\n return i;\n }\n }\n console.log(\"No match found\");\n return 0;\n }", "function extractPositionFromId(id,type) {\n \n var decal = (type == \"canvas\") ? 0 : 1; \n \n var virgulePosition = _virgulePosition(id)\n var i = +(id.substring(0,virgulePosition));\n var j = +(id.substring(virgulePosition+1,id.length-decal));\n \n return {\"i\":i,\"j\":j};\n}", "focusTransaction(transactionIdToFocus) {\n\t\tconst delay = 50;\n\t\tlet targetIndex;\n\n\t\t// Find the transaction by it's id\n\t\tangular.forEach(this.transactions, (transaction, index) => {\n\t\t\tif (isNaN(targetIndex) && transaction.id === transactionIdToFocus) {\n\t\t\t\ttargetIndex = index;\n\t\t\t}\n\t\t});\n\n\t\t// If found, focus the row\n\t\tif (!isNaN(targetIndex)) {\n\t\t\tthis.$timeout(() => this.tableActions.focusRow(targetIndex), delay);\n\t\t}\n\n\t\treturn targetIndex;\n\t}", "function db_get_player_pos(_uuid, cb){\r\n r.table(\"players\").filter({uuid : _uuid}).run(players_db_conn, function(err, cursor){\r\n cursor.next(function(err, row){\r\n if(err){\r\n //console.log(err);\r\n if(err.msg == \"No more rows in the cursor.\"){\r\n }\r\n } else{\r\n console.log(\"Player with matching uuid:\");\r\n console.log(row);\r\n let position = {};\r\n try{\r\n position = row[\"position\"];\r\n console.log(\"Found player pos\");\r\n console.log(position);\r\n cb(position);\r\n } catch(e){\r\n console.log(e);\r\n }\r\n // cb();\r\n }\r\n });\r\n });\r\n}", "function getPosition(id){\n\treturn isDigital(id)?\"Port \"+id.charAt(0)+\" Pin \"+id.charAt(1):getName(id);\n}", "getUserIndex(){\n var i;\n\n // For each user, check if UUID matches id in the usersPlaying array\n for (i = 0; i < this.props.usersPlaying.length; i++) {\n if(this.props.usersPlaying[i] == this.props.pubnubDemo.getUUID()) {\n return i;\n break;\n }\n }\n return -1;\n }", "getIndexForPositionString (positionString = 'a1') {\n const { row, column } = this.getCoordinatesForPositionString(positionString)\n let index = Math.abs(column - 8) + (row * 8)\n index = Math.abs(index - 64)\n return index\n }", "function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}", "function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}", "get activeManifestIndex() {\n if (this.manifest && this.manifest.items && this.activeId) {\n for (var index in this.manifest.items) {\n if (this.manifest.items[index].id === this.activeId) {\n return parseInt(index);\n }\n }\n }\n return -1;\n }", "function findTruckWithID (truckID) {\n\tif(isArrayEmpty(localTruckArray)) return -2; // aey - if no trucks\n\tfor(let i = 0; i < localTruckArray.length; i++) {\n\t\tif(localTruckArray[i].id == truckID) return i; // aey - id was found, return where it was found\n\t}\n\treturn -1;\n}", "function findWordIndex(word) {\n\t\tfor (var i = 1; i <= 3; i++) {\n\t\t\tfor (var j = 0; j < 16; j++) {\n\t\t\t\tvar menu_item = \"#\" + i + \"_\" + j + \"\";\n\t\t\t\t// might be item.target.text\n\t\t\t\tif($(menu_item).text() === word) {\n\t\t\t\t\t// return menu_item;\n\t\t\t\t\treturn j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// return \"#none\";\n\t\treturn -1;\n\t}", "function extractItem(items, id) {\n for (var i = 0; i < items.length; i++)\n if (items[i].id == id)\n return items.splice(i, 1)[0];\n }", "function getPointId(uniqueId) {\n var markersCount = markers.length - 1;\n for (var j = markersCount; j > -1; j--) {\n if (markers[j].listId == uniqueId) {\n return j;\n }\n }\n}", "function findMatchingTouch(touches, id) {\n for (var i = 0; i < touches.length; i++) {\n if (touches[i].identifier === id) {\n return touches[i];\n }\n }\n\n return undefined;\n }", "function addToast (toast) {\n var type = toast.type; \n\n toast.type = mergedConfig['alert-classes'][type];\n toast.icon = mergedConfig['icon-classes'][type]; \n\n if (!toast.type) {\n toast.type = mergedConfig['alert-class'];\n }\n if (!toast.icon) {\n toast.icon = mergedConfig['icon-class'];\n }\n\n id++;\n angular.extend(toast, { id: id });\n\n if (mergedConfig['time-out'] > 0) {\n setTimeout(toast, mergedConfig['time-out']);\n }\n\n\n if (mergedConfig['newest-on-top'] === true) {\n scope.toasters.unshift(toast);\n }\n else {\n scope.toasters.push(toast);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abstract method changing Result
updateResult() { }
[ "set result(newResult) {\n this._result = newResult;\n setValue(`cmi.interactions.${this.index}.result`, newResult);\n }", "setResult(result) {\n console.log('result: ', result);\n if (null != this.config.getCacheHook()) {\n this.data = this.config.getCacheHook().put(result);\n }\n else {\n this.data = result;\n }\n }", "function resultUpdate() {\n\n\t\t$.each(results, function(test, value) {\n\t\t\tif(typeof allTotal === 'number') {\n\t\t\t\t$.each(folders, function(index, folder) {\n\t\t\t\t\tif (test == folder) {\n\t\t\t\t\t\tallTotal = allTotal + parseInt(value);\n\t\t\t\t\t}\n\t\t\t\t});\t\n\t\t\t}\n\n\t\t\tif($('#'+test+'Result').length) {\n\t\t\t\t$('#'+test+'Result').html(value);\n\t\t\t} else {\n\t\t\t\t$('.'+test+'Result').html(value);\n\t\t\t}\n\n\t\t\t\n\t\t});\n\n\t\tif (allTotal) {\n\t\t\t$('#allResult').html(allTotal);\n\t\t}\n\t\tallTotal = null;\n\t}", "function editresult()\n{\n matrix = savematriz(2,matrizResultante);\n dom(\"mresult\").hidden=true;\n escreveMatriz(math.size(matrizResultante)._data,0,matrix,false);\n \n}", "map(result) {\n return this.em.map(this.entityName, result);\n }", "invert() {\n\t\tif(this.isOk) {\n\t\t\treturn new Err(this.value);\n\t\t} else {\n\t\t\treturn new Ok(this.value);\n\t\t}\n\t}", "set code(code) {\n this.result.code = code;\n }", "function setResult(context, value) {\n return new Promise(function (resolve) {\n context.result = value;\n context.hasResult = true;\n resolve(context);\n });\n }", "function displayResult() {}", "function addResult( $result ) {\n\t\tif ( Util.elementCount( $result ) === 0 ) { return };\n\t\t$results = $results.add( $result );\n\t}", "async replayFightResult(metaResult) {\n this.setState({\n loading: true,\n });\n\n let result;\n\n try {\n result = await this.state.contractFacade.replay(\n metaResult.seed,\n metaResult.selection_lhs,\n metaResult.selection_rhs,\n metaResult.variants_lhs,\n metaResult.variants_rhs,\n metaResult.commander_lhs,\n metaResult.commander_rhs);\n } catch (error) {\n console.log(error);\n return this.setState({\n ...this.defaultLoadedState,\n toastOpen: true,\n toastContent: 'Transaction failed (Replay Fight).',\n });\n }\n\n this.setState({\n mode: Modes.Combat,\n trainingSelfSelection: result.selection_lhs,\n trainingSelfCommander: result.commander_lhs,\n trainingOpponentSelection: result.selection_rhs,\n trainingOpponentCommander: result.commander_rhs,\n trainingResult: result,\n loading: false,\n });\n }", "compute() {\n // so to compute we have already settled that both prev and main result must have a value in our operationChoice method\n let computation\n const prev = parseFloat(this.prevResult)\n const main = parseFloat(this.mainResult)\n\n if(isNaN(prev) || isNaN(main)) return\n\n switch(this.operation){\n case '+':\n computation = prev + main\n break\n case '-':\n computation = prev - main\n break\n case '*':\n computation = prev * main\n break\n case '/':\n computation = prev / main\n break\n default:\n return\n }\n //when the equals buttonis clicked, the operand memory is removed..wow! that is by setting operand to undefined\n this.mainResult = computation\n this.operation = undefined \n this.prevResult = ''\n }", "onTestResult(result) {\n this.results = this.results.concat(result);\n ResultDbAgent.newTest(this.frameworkid, result.test, (testid) => {\n delete result.test;\n for (var i in result) {\n ResultDbAgent.newResult(testid, i, i.toUpperCase(), roundFloat(result[i], 7));\n }\n this.testsComplete++;\n this.sendProgress();\n this.nextTest();\n });\n }", "createOrGetResult( label) {\n\t\tif ( !this.RESULTS[label])\n\t\t\tthis.RESULTS[label] = new Result(label);\n\t\treturn this.RESULTS[label];\n\t}", "static NormalizeToRef(vector, result) {\n result.copyFrom(vector);\n result.normalize();\n }", "function resultado(result){\n if((calculadora.innerHTML === 0 || calculadora.innerHTML === \"0\") && valor2 === 0){\n console.log(\"debe ingresar un numero o realizar una operacion\");\n }else{\n if(operation === \"sum\"){\n sumar();\n }\n if(operation === \"rest\"){\n restar();\n }\n if(operation === \"div\"){\n dividir();\n }\n if(operation === \"multi\"){\n multiplicar();\n }\n }\n}", "addResult(result){\n this.results.push(result.state);\n }", "divideToRef(otherVector, result) {\n return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n }", "function resultElements(element, resultClass, resultNumber, resultTitle, newElement) {\n //show numbers for correct, incorrect, and unanswered\n element = $(\"<div>\").addClass(resultClass).append(\"<h2>\" + resultNumber + \"</h2><h4>\" + resultTitle + \"</h4>\");\n newElement = $(\"<div>\").addClass(\"total\").append(element);\n $(finalResults).append(newElement);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MARK SVG path specification functions flatFlowPathMaker(f): Returns an SVG path drawing a parallelogram between 2 nodes. Used for the "d" attribute on a "path" element when curvature = 0 OR when there is no curve to usefully draw (i.e. the flow is ~horizontal).
function flatFlowPathMaker(f) { const sx = f.source.x + f.source.dx, // source's trailing edge tx = f.target.x, // target's leading edge syTop = f.source.y + f.sy, // source flow top tyBot = f.target.y + f.ty + f.dy; // target flow bottom f.renderAs = 'flat'; // Render this path as a filled parallelogram // This SVG Path spec means: // [M]ove to the flow source's top; draw a [v]ertical line down, // a [L]ine to the opposite corner, a [v]ertical line up, // then [z] close. return `M${ep(sx)} ${ep(syTop)}v${ep(f.dy)}` + `L${ep(tx)} ${ep(tyBot)}v${ep(-f.dy)}z`; }
[ "function curvedFlowPathFunction(curvature) {\n return (f) => {\n const syC = f.source.y + f.sy + f.dy / 2, // source flow's y center\n tyC = f.target.y + f.ty + f.dy / 2, // target flow's y center\n sEnd = f.source.x + f.source.dx, // source's trailing edge\n tStart = f.target.x; // target's leading edge\n\n // Watch out for a nearly-straight path (total rise/fall < 2 pixels OR\n // very little horizontal space to work with).\n // If we have one, make this flow a simple 4-sided shape instead of\n // a curve. (This avoids weird artifacts in some SVG renderers.)\n if (Math.abs(syC - tyC) < 2 || Math.abs(tStart - sEnd) < 12) {\n return flatFlowPathMaker(f);\n }\n\n f.renderAs = 'curved'; // Render this path as a curved stroke\n\n // Make the curved path:\n // Set up a function for interpolating between the two x values:\n const xinterpolate = d3.interpolateNumber(sEnd, tStart),\n // Pick 2 curve control points given the curvature & its converse:\n xcp1 = xinterpolate(curvature),\n xcp2 = xinterpolate(1 - curvature);\n // This SVG Path spec means:\n // [M]ove to the center of the flow's start [sx,syC]\n // Draw a Bezier [C]urve using control points [xcp1,syC] & [xcp2,tyC]\n // End at the center of the flow's target [tx,tyC]\n return (\n `M${ep(sEnd)} ${ep(syC)}C${ep(xcp1)} ${ep(syC)} `\n + `${ep(xcp2)} ${ep(tyC)} ${ep(tStart)} ${ep(tyC)}`\n );\n };\n}", "function layFlat(p) {\n\tcurrentZ = new CSG.Connector([0,0,0],[0,0,1],[1,0,0]);\n\treturn p.connectTo(p.properties._originalZ, currentZ, false, 0);\n}", "function Path(spec, colorfunction) {\n\tvar points = spec.split(',')\n\tthis.colorfunction = colorfunction\n\tthis.path = new Array(points.length)\n\tthis.path[0] = this.translate(points[0])\n\tthis.start = this.end = null\n\t\n\tfor(var i = 1; i < points.length; i++) {\n\t\tthis.path[i] = this.step(points[i], this.path[i-1])\n\t}\n\tthis.length = this.computeLength()\n}", "static serializePath(startPos, path, color = \"orange\") {\n let serializedPath = \"\";\n let lastPosition = startPos;\n this.circle(startPos, color);\n for (let position of path) {\n if (position.roomName === lastPosition.roomName) {\n new RoomVisual(position.roomName).line(position, lastPosition, {color: color, lineStyle: \"dashed\"});\n serializedPath += lastPosition.getDirectionTo(position);\n }\n lastPosition = position;\n }\n return serializedPath;\n }", "function diagonalShapeGenerator2(source, descendant){\n\t\treturn \"M\" + project(source.x, source.y)\n\t\t\t+ \"C\" + project(source.x, (source.y + descendant.y) / 2)\n\t\t\t+ \" \" + project(descendant.x, (source.y + descendant.y) / 2) \n\t\t\t+ \" \" + project(descendant.x, descendant.y);\n\t}", "function createGraphFlow() {\n const info = {\n version: { major:1, minor:2, patch:1, release: new Date(2014, 11, 27) },\n created: new Date(2014, 11, 25),\n authors: [\"Miguel Angelo\"]\n };\n var GF = GraphFlow;\n GF.info = info;\n GF.Error = gfError;\n GF.Result = gfResult;\n GF.Arguments = gfArguments;\n GF.NoOp = NoOp;\n GF.End = finalFunc(End);\n GF.finalFunc = finalFunc;\n GF.defaultCombinator = defaultCombinator;\n GF.defaultInherit = defaultInherit;\n GF.createContext = createContext;\n GF.executor = executor;\n GF.distinct = distinct;\n GF.sequence = sequence;\n GF.alternate = alternate;\n GF.combine = combine;\n var push = Array.prototype.push;\n function GraphFlow() {\n var fs = distinct(normalize(argumentsToArray(arguments)));\n return alternativesCombinator(fs);\n }\n function gfError(value, ctx) {\n this.value = value;\n this.ctx = ctx;\n }\n function gfResult(value, ctx) {\n this.value = value;\n this.ctx = ctx;\n }\n function gfArguments(args) {\n this.args = argumentsToArray(args);\n }\n function finalFunc(f) {\n f.isFinalFunc = true;\n return f;\n }\n function End() {\n }\n function NoOp() {\n return function NoOp() {\n // return all arguments to the next function in the chain\n return new gfArguments(arguments);\n }\n }\n function distinct(array) {\n // http://stackoverflow.com/a/16065720/195417\n return array.filter(function (a, b, c) {\n // keeps first occurrence\n return c.indexOf(a) === b;\n });\n }\n function concat(a, b) {\n return a.concat(b);\n }\n function normalize(fs) {\n return fs\n .map(function(f) {\n return typeof f === 'function' && typeof f.funcs === 'function'\n ? f.funcs()\n : [f];\n })\n .reduce(concat, [])\n .map(function(f){\n return f === null ? NoOp() : f;\n });\n }\n function normalizeArgs(args) {\n return args\n .map(function(arg) {\n return arg instanceof gfArguments\n ? arg.args\n : [arg];\n })\n .reduce(concat, []);\n }\n function argumentsToArray(args) {\n return [].slice.call(args);\n }\n function defaultCombinator(g, argsFn, f) {\n function GoF() {\n var args = argsFn.apply(this, arguments);\n return g.apply(this, args);\n };\n if (g.hasOwnProperty('inherit'))\n GoF.inherit = g.inherit;\n return GoF;\n }\n function defaultInherit(gof, g, f) {\n // `gof` inherits properties owned by `g`, if `gof` does not\n // already own a property with the same name from `g`.\n for (var k in g)\n if (!gof.hasOwnProperty(k) && g.hasOwnProperty(k))\n gof[k] = g[k];\n }\n function createContext(fn, mc) {\n return {};\n }\n function executor(fn, ctx, args, mc) {\n try {\n var ResultClass = fn.Result || mc&&mc.Result || this.Result || gfResult;\n return new ResultClass(fn.apply(ctx, args), ctx);\n }\n catch (ex) {\n var ErrorClass = fn.Error || mc&&mc.Error || this.Error || gfError;\n return new ErrorClass(ex, ctx);\n }\n }\n function sequence() {\n var funcs = argumentsToArray(arguments);\n if (funcs.length) {\n var prev = GraphFlow;\n for (var it = 0; it < funcs.length; it++)\n prev = prev(funcs[it]);\n return prev;\n }\n else\n return NoOp();\n }\n function alternate() {\n return GraphFlow.apply(null, arguments);\n }\n function combine() {\n var funcs = argumentsToArray(arguments);\n if (funcs.length > 1) {\n var gf = GraphFlow.apply(null, funcs\n .map(function(f, i) {\n var mc = GraphFlow(f),\n nextFns = funcs.filter(function(el, idx, arr) { return idx !== i; });\n return GraphFlow(f, mc(combine.apply(null, nextFns)));\n }));\n return gf;\n }\n else if (funcs.length == 1)\n return GraphFlow(funcs[0]);\n else\n return GraphFlow();\n }\n function alternativesCombinator(fs) {\n fs = distinct(fs);\n var fn = function MultiCombinator() {\n //debugger;\n var gs = distinct(normalize(argumentsToArray(arguments)));\n var gofs = fs\n .map(function(f) {\n if (typeof f === 'function') f = [f];\n f = normalize(f);\n\n var someIsFinal = f.some(function(ff) { return ff.isFinalFunc; });\n if (someIsFinal) {\n if (f.length == 1)\n return f[0];\n throw new Error(\"Cannot group functions with 'isFinalFunc' flag.\");\n }\n\n var result = gs\n .map(function(g) {\n var gargsFn = function() {\n var _this = this,\n fargs = arguments;\n return normalizeArgs(\n f.map(function(ff) {\n return ff.apply(_this, fargs);\n }));\n }\n\n var combinator = g.combinator || GF.defaultCombinator || defaultCombinator;\n var gof = combinator.call(GF, g, gargsFn, f);\n if (gof) {\n var inherit = gof.inherit || GF.defaultInherit || defaultInherit;\n inherit.call(GF, gof, g, f);\n }\n\n return gof;\n })\n .filter(function(gof){return gof;});\n\n return result;\n })\n .reduce(concat, []);\n return alternativesCombinator(gofs);\n };\n fn.callAll = function() {\n var _this = this,\n ctxCreator = this.createContext || GF&&GF.createContext || createContext,\n exec = this.executor || GF&&GF.executor || executor,\n args = normalizeArgs(argumentsToArray(arguments));\n return fs\n .map(function(f) {\n var ctx = (f.createContext || ctxCreator).call(GF, f, _this);\n return (f.executor || exec).call(GF, f, ctx, args, _this);\n });\n };\n fn.funcs = function() {\n return fs;\n };\n return fn;\n }\n return GF;\n}", "function gotoPath(rawNodes, pathList) {\n\t console.log(Math.floor(Date.now() / 1000), \"start gotoPath\", rawNodes, pathList);\n\t \n\t try {\n\t \n\t if (pathList) {\n\n\t\t\t// use list to to generate new node graph\n\t\t\tvar pathNodes = []\n\t\t\tfor (var n=0; n<pathList.length; n++) {\n\t\t\t\tvar _id = pathList[n] ;\n\t\t\t\t// console.log('_id',_id)\n\t\t\t\tvar _node = getNodeById(rawNodes,_id) ;\n\t\t\t\t// console.log('_node',_node)\n\t\t\t\tpathNodes.push(_node) ;\n\t\t\t}\n\t\t\tconsole.log('pathNodes',pathNodes,pathNodes.length)\n\t\t\t\n\t\t\t\n\t\t\t// // create edges between path nodes - NEED TO MAKE MORE COMPLETE BY LOOP THROUGH PROPERTIES OF NODES\n\t\t\t// var pathEdges = []\n\t\t\t// if (pathNodes.length>0) {\n\t\t\t// for (var p=0; p<pathNodes.length-1; p++) {\t\t\t\t\t\t// only loop length - 1 \n\t\t\t// \tvar _nd1 = pathNodes[p] ;\t\t\t\t\tconsole.log('_nd1',_nd1)\n\t\t\t// \tvar _id1 = _nd1['@id']; ;\t\t\t\t\tconsole.log('_id1',_id1)\n\t\t\t// \tvar _nd2 = pathNodes[p+1] ;\t\t\t\t\tconsole.log('_nd2',_nd2)\n\t\t\t// \tvar _id2 = _nd2['@id'] ;\t\t\t\t\tconsole.log('_id2',_id2)\n\t\t\t\t\n\t\t\t// \tvar pathEdge = {};\n\t\t\t// \tpathEdge.arrows = {\"to\":\"true\"};\n\t\t\t// \tpathEdge.from = _id1;\n\t\t\t// \tpathEdge.to = _id2;\n\t\t\t// \tpathEdge.label = 'related to';\n\t\t\t\t\t\t\n\t\t\t// \tpathEdges.push(pathEdge);\n\t\t\t// }\n\t\t\t// }\n\t\t\t// console.log('pathEdges',pathEdges)\n\n\t\t\t// redrawn with path nodes and edges\n\t\t\t// setNetwork(pathNodes, pathEdges)\n\t\t\tvar startId = pathNodes[0] ;\n\t\t\t\n\t\t\tgotoNode(startId,pathNodes)\n\n\t }\n\t \n\t }\n\t\tcatch(e) {\n\t\t console.error(Math.floor(Date.now() / 1000), e)\n\t\t} \n\t\tfinally {\n\t\t\t// stop spinner\n\t\t\t// if (spinner) spinner.stop() ; \n\t\t\t// console.log(Math.floor(Date.now() / 1000), 'spinner stop',spinner)\n\t\t\t\n\t\t\tconsole.log(Math.floor(Date.now() / 1000), 'finish gotoPath')\n\t\t}\n\t} // end gotoPath", "path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }", "function computePath( startingNode, endingNode ) {\n // First edge case: start is the end:\n if (startingNode.id === endingNode.id) {\n return [startingNode];\n }\n\n // Second edge case: two connected nodes\n if ( endingNode.id in startingNode.next ) {\n return [startingNode, endingNode];\n }\n\t\n var path = [];\n var n = endingNode;\n while ( n && n.id !== startingNode.id ) {\n // insert at the beggining\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\n if ( n.id !== endingNode.id ) {\n path.unshift( n );\n }\n n = n.prev;\n }\n\n if ( path.length ) {\n path.unshift( startingNode );\n path.push( endingNode );\n }\n\n return path;\n}", "function serializePaths(){\r\n var paths = extractSelectedPaths();\r\n var data = [];\r\n\r\n var MARGIN_TOP = 50;\r\n var MARGIN_LEFT = 25;\r\n \r\n var top_left = getTopLeftOfPaths(paths);\r\n var top = top_left[0] + MARGIN_TOP;\r\n var left = top_left[1] - MARGIN_LEFT;\r\n \r\n for(var i = paths.length - 1; i >= 0; i--){\r\n var r = [\"@\"]; // \"@\" is a mark that means the beginning of a path\r\n var p = paths[i];\r\n \r\n r.push(p.closed ? \"1\" : \"0\");\r\n\r\n r.push([p.filled ? \"1\" : \"0\",\r\n serializeColor(p.fillColor)]);\r\n \r\n r.push([p.stroked && p.strokeColor.typename != \"NoColor\" ? \"1\" : \"0\",\r\n _f2s(p.strokeWidth),\r\n serializeColor(p.strokeColor)]);\r\n\r\n for(var j = 0, jEnd = p.pathPoints.length; j < jEnd; j++){\r\n var ppt = p.pathPoints[j];\r\n var anc = ppt.anchor;\r\n r.push([_f2s(anc[0] - left), _f2s(anc[1] - top),\r\n _f2s(ppt.rightDirection[0] - anc[0]),\r\n _f2s(ppt.rightDirection[1] - anc[1]),\r\n _f2s(ppt.leftDirection[0] - anc[0]),\r\n _f2s(ppt.leftDirection[1] - anc[1])]);\r\n // ignore pointType becauses paper js doesn't have this property\r\n }\r\n \r\n data[data.length] = r;\r\n }\r\n \r\n // \"data\" is passed to callback function as a comma separated string\r\n return data;\r\n}", "function generatePaths(numberofNodes, nodes) {\n // console.log(numberofNodes);\n // console.log(nodes);\n // Init a map to represent a given node as the key and list of connected nodes as the value\n const pathMap = {};\n for (let i = 0; i < numberofNodes; i++) {\n pathMap[i] = [];\n }\n \n // Populate the pathMap with the connected nodes\n for (let i = 0; i < nodes.length; i++) {\n const [source, destination] = nodes[i].replace(' ', '').split(',');\n pathMap[source].push(destination); \n }\n \n // console.log(pathMap);\n \n // Recursively generate the paths\n\n // Recursive helper function\n function generateNodePath(root) {\n const paths = pathMap[root];\n // Base case\n if (paths.length === 0) return root;\n \n // Generate paths for all connected nodes\n for (let i = 0; i < paths.length; i++) {\n // TODO: This only returns the path for the first item completely.\n // Need to save the result and only return once all paths for each\n // node in the loop is generated.\n return root.toString() + '->' + generateNodePath(paths[i]);\n }\n }\n \n const pathMapKeys = Object.keys(pathMap);\n for (let i = 0; i < pathMapKeys.length; i++) {\n const path = generateNodePath(pathMapKeys[i]);\n console.log(path);\n }\n}", "function reflectPath(lines, vector, ditchOrig) {\n \n var result = ditchOrig ? [] : utils.extend(true, [], lines);\n var n = utils.normalize(vector)\n var length = lines.length- (utils.isArc(lines.peek()) ? 2 : 1);\n for (var x=length; x>=0; x--) {\n\tif(lines[x].br || lines[x].fr) {\n\t result.push(lines[x])\n\t} else {\n\t var d = utils.dot(lines[x],n);\n\t result.push ({\n\t\tx:lines[x].x -2 * d * n.y\n\t\t, y:lines[x].y -2 * d * n.x\n\t })\n\t}\n }\n return result;\n}", "function generateArcPoints(length, elevation, sx, sy, hdg, curvature, lateralOffset) {\n\n\tvar points = [];\n\tvar heading = [];\n\tvar tOffset = [];\n\tvar sOffset = [];\t// sOffset from the beginning of the curve, used for distribute error\n\tvar currentHeading = hdg;\n\tvar prePoint, x, y, z;\n\n\tif (!elevation) {\n\t\televation = {s:0,a:0,b:0,c:0,d:0};\n\t}\n\n\t// s ranges between [0, length]\n\tvar s = 0;\n\tvar preS = 0;\n\n\tdo {\n\t\t\n\t\tif (s == 0) {\n\t\t\tpoints.push(new THREE.Vector3(sx, sy, elevation.a));\t\t\n\t\t\theading.push(currentHeading);\n\t\t\tif (lateralOffset) tOffset.push(lateralOffset.a);\n\t\t\tsOffset.push(s);\n\t\t\ts += step;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (s > length || Math.abs(s - length) < 1E-4) {\t\t\n\t\t\ts = length;\n\t\t}\n\n\t\tprePoint = points[points.length - 1];\n\n\t\tx = prePoint.x + (s - preS) * Math.cos(currentHeading + curvature * (s - preS) / 2);\n\t\ty = prePoint.y + (s - preS) * Math.sin(currentHeading + curvature * (s - preS) / 2);\n\t\tz = cubicPolynomial(s, elevation.a, elevation.b, elevation.c, elevation.d);\n\n\t\tcurrentHeading += curvature * (s - preS);\n\t\t\n\t\tpreS = s;\n\t\ts += step;\n\n\t\tpoints.push(new THREE.Vector3(x, y, z));\n\t\theading.push(currentHeading);\n\t\tif (lateralOffset) tOffset.push(cubicPolynomial(preS, lateralOffset.a, lateralOffset.b, lateralOffset.c, lateralOffset.d));\n\t\tsOffset.push(preS);\n\n\t} while (s < length + step);\n\n\t// apply lateral offset along t, and apply superelevation, crossfalls if any\n\tif (lateralOffset) {\n\n\t\tvar svector, tvector, hvector;\n\n\t\t// shift points at central clothoid by tOffset to get the parallel curve points\n\t\tfor (var i = 0; i < points.length; i++) {\n\n\t\t\tvar point = points[i];\n\t\t\tvar t = tOffset[i];\n\t\t\tvar currentHeading = heading[i];\n\t\t\tvar ds = sOffset[i];\n\n\t\t\tsvector = new THREE.Vector3(1, 0, 0);\n\t\t\tsvector.applyAxisAngle(new THREE.Vector3(0, 0, 1), currentHeading);\n\t\t\ttvector = svector.clone();\n\t\t\ttvector.cross(new THREE.Vector3(0, 0, -1));\n\n\t\t\thvector = svector.clone();\n\t\t\thvector.cross(tvector);\n\n\t\t\ttvector.multiplyScalar(t);\n\t\t\thvector.multiplyScalar(0);\t// no height\n\n\t\t\tpoint.x += tvector.x + hvector.x;\n\t\t\tpoint.y += tvector.y + hvector.y;\n\t\t\tpoint.z += tvector.z + hvector.z;\n\t\t}\n\t}\n\n\treturn {points: points, heading: heading};\n}", "function build_path(p_orig, p_dest){\n var res = new Array();\n\n if(p_orig.x == p_dest.x){\n if(p_orig.y < p_dest.y){\n // Vertical path, going downwards.\n for(var y = p_orig.y + 1; y <= p_dest.y; y++){\n res.push({x: p_orig.x, y: y});\n }\n } else {\n // Vertical path, going upwards.\n for(var y = p_orig.y - 1; y >= p_dest.y; y--){\n res.push({x: p_orig.x, y: y});\n }\n }\n } else if(p_orig.y == p_dest.y){\n if(p_orig.x < p_dest.x){\n // Horizontal path, going to the right.\n for(var x = p_orig.x + 1; x <= p_dest.x; x++){\n res.push({x: x, y: p_orig.y});\n }\n } else {\n // Horizontal path, going to the left.\n for(var x = p_orig.x - 1; x >= p_dest.x; x--){\n res.push({x: x, y: p_orig.y});\n }\n }\n } else {\n res.push(p_dest); // TODO properly handle diagonal paths.\n }\n\n return res;\n}", "function genPathways(waypoints) \n{\n\t// Define a dashed line symbol using SVG path notation, with an opacity of 1.\n\tvar lineSymbol = {path: \"M 0,-1 0,1\", strokeOpacity: 1, scale: 2}\n\n\tvar pathColors = [\"#ff6600\", \"#f40696\", \"#FF0000\", \"#d39898\", \"#00FF00\", \"#FFA500\", \"#0000FF\"];\n\tvar pcSize = pathColors.length \n\n\tJSbldPathways(waypoints, pathways);\n\n\tvar nx = 0;\t// Index for path names in array\n\tvar px = 0;\t// Color index\n\n\tfor (pw in pathways)\n\t{\n\t\tif(LOG_PW == true)\n\t\t{\n\t\t\tconsole.log(pathways[pw]);\n\t\t}\n\t\n\t\tnewPath = new google.maps.Polyline({\n\t\t\tpath: pathways[pw],\n\t\t\tgeodesic: true,\n\t\t\tstrokeColor: pathColors[px++],\n\t\t\tstrokeOpacity: 0,\n\t\t\ticons: [{icon: lineSymbol,offset: '0',repeat: '10px'}],\n\t\t\tstrokeWeight: 1});\n\t\t\n\t\tnewPath.setMap(map);\n\t\tptNames[nx++] = newPath;\n\n\t\tpx = (px >= pcSize ? 0 : px);\n\t}\n}", "function chooseRighthandPath(fromX, fromY, nodeX, nodeY, ax, ay, bx, by) {\n var angleA = geom.signedAngle(fromX, fromY, nodeX, nodeY, ax, ay);\n var angleB = geom.signedAngle(fromX, fromY, nodeX, nodeY, bx, by);\n var code;\n if (angleA <= 0 || angleB <= 0) {\n if (angleA <= 0) {\n debug(' A orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, ax, ay));\n }\n if (angleB <= 0) {\n debug(' B orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, bx, by));\n }\n // TODO: test against \"from\" segment\n if (angleA > 0) {\n code = 1;\n } else if (angleB > 0) {\n code = 2;\n } else {\n code = 0;\n }\n } else if (angleA < angleB) {\n code = 1;\n } else if (angleB < angleA) {\n code = 2;\n } else if (isNaN(angleA) || isNaN(angleB)) {\n // probably a duplicate point, which should not occur\n error('Invalid node geometry');\n } else {\n // Equal angles: use fallback test that is less sensitive to rounding error\n code = chooseRighthandVector(ax - nodeX, ay - nodeY, bx - nodeX, by - nodeY);\n }\n return code;\n}", "function setVerticalPathData(pathEl, x1, x2, y1, y2, adjustment) {\n // x coordinate is fixed for vertical line, considering x1 i.e. start x as fixed x coordinate throught the line\n var fixed_x = x1;\n // x2 is to decide in which quadrant line is being drawn so as to flip the beveled shapes\n \n // flip drawn line only if buffer limit is crossed\n if (x2 < x1-adjustment) {\n // line in quadrant II or III\n fixed_x += adjustment;\n pathEl.attr({\n \"marker-start\": \"url(#up_left_arrow)\",\n \"marker-end\": \"url(#down_left_arrow)\",\n });\n } else {\n // line in quadrant I or IV\n fixed_x -= adjustment;\n pathEl.attr({\n \"marker-start\": \"url(#up_right_arrow)\",\n \"marker-end\": \"url(#down_right_arrow)\",\n });\n }\n\n // decide starting point as hightes y point among previous and current point\n var voltage_path_data = '';\n if (y1 < y2) {\n voltage_path_data = \"M\" + fixed_x + ',' + y2 + ' L' + fixed_x + ',' + y1;\n } else {\n voltage_path_data = \"M\" + fixed_x + ',' + y1 + ' L' + fixed_x + ',' + y2;\n }\n\n pathEl.attr({\n \"d\": voltage_path_data,\n });\n }", "function trianglePath(triangles){\n var path = \"M \" + xScale(triangles[0].x) + \",\" + yScale(triangles[0].y);\n path += \" L \" + xScale(triangles[1].x) + \",\" + yScale(triangles[1].y);\n path += \" L \" + xScale(triangles[2].x) + \",\" + yScale(triangles[2].y) + \" Z\";\n\n return path;\n}", "function drawFlights(summary, airportCode) {\n // referenced www.tnoda.com\n\n if (airportCode) {\n summary = summary.filter(item => {\n return (item.arrival === airportCode || item.departure === airportCode)\n });\n }\n\n const flights = groups.flights;\n // flights.attr(\"opacity\", 1);\n\n const path = d3.geoPath(projection);\n const planeScale = d3.scaleSqrt()\n .domain(d3.extent(summary, d => d.flights))\n .range([0.3, 2]);\n\n\n function fly(departure, arrival, flightCount) {\n\n var route = flights.append(\"path\")\n .datum({ type: \"LineString\", coordinates: [departure, arrival] })\n .attr(\"class\", \"route\")\n .attr(\"d\", path);\n\n var plane = flights.append(\"path\")\n .attr(\"class\", \"plane\")\n .attr(\"d\", \"m25.21488,3.93375c-0.44355,0 -0.84275,0.18332 -1.17933,0.51592c-0.33397,0.33267 -0.61055,0.80884 -0.84275,1.40377c-0.45922,1.18911 -0.74362,2.85964 -0.89755,4.86085c-0.15655,1.99729 -0.18263,4.32223 -0.11741,6.81118c-5.51835,2.26427 -16.7116,6.93857 -17.60916,7.98223c-1.19759,1.38937 -0.81143,2.98095 -0.32874,4.03902l18.39971,-3.74549c0.38616,4.88048 0.94192,9.7138 1.42461,13.50099c-1.80032,0.52703 -5.1609,1.56679 -5.85232,2.21255c-0.95496,0.88711 -0.95496,3.75718 -0.95496,3.75718l7.53,-0.61316c0.17743,1.23545 0.28701,1.95767 0.28701,1.95767l0.01304,0.06557l0.06002,0l0.13829,0l0.0574,0l0.01043,-0.06557c0,0 0.11218,-0.72222 0.28961,-1.95767l7.53164,0.61316c0,0 0,-2.87006 -0.95496,-3.75718c-0.69044,-0.64577 -4.05363,-1.68813 -5.85133,-2.21516c0.48009,-3.77545 1.03061,-8.58921 1.42198,-13.45404l18.18207,3.70115c0.48009,-1.05806 0.86881,-2.64965 -0.32617,-4.03902c-0.88969,-1.03062 -11.81147,-5.60054 -17.39409,-7.89352c0.06524,-2.52287 0.04175,-4.88024 -0.1148,-6.89989l0,-0.00476c-0.15655,-1.99844 -0.44094,-3.6683 -0.90277,-4.8561c-0.22699,-0.59493 -0.50356,-1.07111 -0.83754,-1.40377c-0.33658,-0.3326 -0.73578,-0.51592 -1.18194,-0.51592l0,0l-0.00001,0l0,0z\");\n\n transition(plane, route, flightCount);\n }\n\n function transition(plane, route, flightCount) {\n const l = route.node().getTotalLength();\n // console.log(route.node())\n plane.transition()\n .duration(l * 50)\n .attrTween(\"transform\", delta(route.node(), flightCount))\n .on(\"end\", () => { route.remove(); })\n .remove();\n }\n\n function delta(arc, flightCount) {\n var l = arc.getTotalLength();\n\n return function(i) {\n return function(t) {\n\n var p = arc.getPointAtLength(t * l);\n\n var t2 = Math.min(t + 0.05, 1);\n var p2 = arc.getPointAtLength(t2 * l);\n\n var x = p2.x - p.x;\n var y = p2.y - p.y;\n var r = 90 - Math.atan2(-y, x) * 180 / Math.PI;\n var s = Math.min(Math.sin(Math.PI * t) * 0.7, 0.3) * 1.3;\n\n // let s;\n // if (t <= 0.5) {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * t) + 0.2;\n // } else {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * (1 - t)) + 0.2;\n // };\n\n return `translate(${p.x}, ${p.y}) scale(${s}) rotate(${r})`;\n }\n }\n }\n\n let i = 0;\n window.refreshIntervalId = setInterval(function() {\n if (i > summary.length - 1) {\n i = 0;\n }\n var pair = summary[i];\n\n // fly(summary);\n fly(pair.departure_coords, pair.arrival_coords, pair.flights);\n\n i++;\n }, 150);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bring login status from local storage (PC)
function loginStatusToStorage() { localStorage.loggedIn = loggedIn; localStorage.loggedInID = loggedInID; }
[ "function loginStatusToVars() {\n\tloggedIn = localStorage.loggedIn;\n\tloggedInID = localStorage.loggedInID;\n}", "onLoginStart () {\n this.loggingIn = true\n this.loggedIn = false\n }", "function loadLoginData () {\n let savedUsername = config.get('username')\n let savedPassword = config.get('password')\n let savedRememberUsername = config.get('rememberUsername')\n let savedRememberPassword = config.get('rememberPassword')\n\n document.querySelector('#login-remember-name').checked = savedRememberUsername\n document.querySelector('#login-remember-password').checked = savedRememberPassword\n\n if (savedUsername) {\n document.querySelector('#login-name').value = savedUsername\n }\n\n if (savedPassword) {\n document.querySelector('#login-password').value = decrypt(savedPassword)\n }\n}", "function initLocalStorage(){\n if (!localStorage.hasOwnProperty('closeLoginWarning')){\n localStorage['closeLoginWarning'] = false;\n }\n \n if (!localStorage.hasOwnProperty('list')){\n localStorage['list'] = JSON.stringify([DEFAULT_ITEM]);\n }\n \n if (!localStorage.hasOwnProperty('loginStatus')){\n localStorage['loginStatus'] = false;\n }\n}", "localLogin(authResult) {\n this.idToken = authResult.idToken;\n this.profile = authResult.idTokenPayload;\n\n // convert the JWT expiry time from seconds to milliseconds\n this.tokenExpiry = new Date(this.profile.exp * 1000);\n\n // save the access token\n this.accessToken = authResult.accessToken;\n this.accessTokenExpiry = new Date(Date.now() + authResult.expiresIn * 1000);\n\n localStorage.setItem(localStorageKey, \"true\");\n\n this.emit(loginEvent, {\n loggedIn: true,\n profile: this.profile,\n state: authResult.appState || {}\n });\n }", "function performTasksOnSuccessfulLogin() {\n exports.changePasswordAtNextLogon = null;\n exports.loggedInAccountDisplayText = null;\n\n //spWebService.setHeader('X-ReadiNow-Client-Version', spAppSettings.initialSettings.platformVersion); // For information purposes only\n\n if (exports.isSignedIn() &&\n exports.accountId) {\n\n spConsoleService.getSessionInfo().then(function (sessionInfo) {\n spAppSettings.setSessionInfo(sessionInfo);\n });\n\n spEntityService.getEntity(exports.accountId, 'changePasswordAtNextLogon, accountHolder.name, k:defaultNavSection.name, k:defaultNavElement.{ name, k:resourceInFolder*.{ name, isOfType.alias} }', { hint: 'checklogin', batch: true }).then(function (account) {\n if (account) {\n exports.defaultUserLandingInfo = exports.defaultUserLandingInfo || {};\n exports.defaultUserLandingInfo.defaultNavSection = account.defaultNavSection;\n exports.defaultUserLandingInfo.defaultNavElement = account.defaultNavElement;\n\n // Check to see if the user must change the password at login time and caches it locally.\n exports.changePasswordAtNextLogon = account.changePasswordAtNextLogon;\n\n // if the current user account is linked to an accountholder then use the accountholder name else use username for display text\n var accountHolder = account.getLookup('core:accountHolder');\n if (accountHolder && accountHolder.idP) {\n exports.accountHolderId = accountHolder.idP;\n }\n if (accountHolder && accountHolder.name) {\n exports.loggedInAccountDisplayText = accountHolder.name;\n }\n else {\n exports.loggedInAccountDisplayText = exports.getAuthenticatedIdentity().username;\n }\n }\n });\n }\n }", "function mpLogIn() {\n mixpanel.identify(mixpanel.cookie.props.distinct_id)\n mixpanel.people.set({\"last page\":window.location.href});\n mixpanel.people.set_once({\"account created\":Date.now()});\n}", "componentDidMount() {\n if (localStorage.getItem('user') && localStorage.getItem('password')) {\n this.setState({ loggedIn: true });\n } else {\n this.setState({ loggedIn: false });\n }\n }", "save() {\n var string = JSON.stringify(this[PINGA_SESSION_STATE]);\n\n localStorage.setItem(this.userId, string);\n }", "function updateUIAfterLogin(email) {\n sessionStorage.setItem('SENDER-MAIL', email);\n setUserStatus(true);\n getAndUpdateUsernameFromFirebaseDB(email);\n $('#email-area').text(email);\n getAndUpdateUsersFromFirebaseDB(email);\n}", "function setupUser(loginScreenName) {\n if (userScreenName == null || userScreenName != loginScreenName)\n {\n userScreenName = loginScreenName;\n localStorage.setItem(\"user-screenname\",userScreenName);\n dbConnectionObject.set(userScreenName);\n setupChatRef();\n }\n}", "@action\n async login() {\n await this.auth.ensureLogin(this.selectedProvider);\n await this.storeCommunicator.fetchTypeIndexes(this.auth.webId);\n await this.profile.fetchProfileInfo();\n }", "function toggleLoginLogout(){\n console.log(\"Checking login status\");\n if (localStorage.getItem(\"loggedInAs\") != null){\n $(\"#logoutLink\").show();\n $(\"#menuBarLogin\").hide();\n $(\"#cartButton\").show();\n $(\"#accountButton\").show();\n } else {\n $(\"#logoutLink\").hide();\n $(\"#menuBarLogin\").show();\n $(\"#cartButton\").hide();\n $(\"#accountButton\").hide();\n }\n}", "function SessionState()\n{\n if(localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDIN) \n {\n if(localStorage.getItem(\"idname\")==\"admin\") {\n window.location.href = MY_VALUES.ADMIN;\n return false;\n }\n else {\n window.location.href = MY_VALUES.TEACHER;\n return false;\n }\n }\n else if (localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDINHOD) {\n window.location.href =MY_VALUES.HOD;\n return false;\n }\n else if (localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDINSTUDENT) {\n window.location.href = MY_VALUES.STUDENT;\n return false;\n }\n}", "onLogin() {}", "sendLoginInfo(info) {\n localStorage.setItem('login-info', JSON.stringify(info));\n this.subjectLogin.next({\n response: info\n });\n }", "function logIn(){\r\n\t\t// username and password are what user types in, newuser is checked if the user\r\n\t\t// is creating a new account. newuser is boolean\r\n\t\tlet username = document.getElementById(\"username\").value;\r\n\t\tlet password = document.getElementById(\"password\").value;\r\n\t\tlet newuser = document.getElementById(\"newuser\").checked;\r\n\t\t\r\n\r\n\t\tif (newuser){ // if user making a new account\r\n\t\t\tlet url = \"https://nathon-breakout.herokuapp.com/?mode=oneuser\";\r\n\t\t\tfetch(url)\r\n\t\t\t\t\t.then(checkStatus)\r\n\t\t\t\t\t.then(function(responseText){\r\n\t\t\t\t\t\t\tlet json = JSON.parse(responseText);\r\n\t\t\t\t\t\t\tlet users = json[\"users\"]; // users = list of curr user objects\r\n\t\t\t\t\t\t\tlet usernames = []; // array to hold all current usernames.\r\n\t\t\t\t\t\t\tlet passwords = []; // array to hold all current passwords.\r\n\t\t\t\t\t\t\t// This for loop will get all usernames and passwords\r\n\t\t\t\t\t\t\tfor (let i = 0; i < users.length; i++){\r\n\t\t\t\t\t\t\t\tusernames.push(users[i][\"username\"]);\r\n\t\t\t\t\t\t\t\tpasswords.push(users[i][\"password\"]);\t\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (usernames.includes(username)){ // cheks if username taken or not\r\n\t\t\t\t\t\t\t\tdocument.getElementById(\"retry\").innerHTML = \"username taken!\";\r\n\t\t\t\t\t\t\t} else{\r\n\t\t\t\t\t\t\t\tdocument.getElementById(\"retry\").innerHTML = \"\";\r\n\t\t\t\t\t\t\t\taddUser(username, password); \r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.catch(function(error){\r\n\t\t\t\t\t\tconsole.log(error);\r\n\t\t\t\t\t});\r\n\r\n\t\t} else{ // this path taken if user exists and is logging in\r\n\t\t\tlet url = \"https://nathon-breakout.herokuapp.com/?mode=oneuser\";\r\n\t\t\tfetch(url)\r\n\t\t\t\t\t.then(checkStatus)\r\n\t\t\t\t\t.then(function(responseText){\r\n\t\t\t\t\t\t\tlet json = JSON.parse(responseText);\r\n\t\t\t\t\t\t\tlet users = json[\"users\"]; // users is a list of user objects\r\n\t\t\t\t\t\t\tlet found = false;\r\n\t\t\t\t\t\t\t// loops through users and checks each username and password\r\n\t\t\t\t\t\t\tfor (let i = 0; i < users.length; i++){\r\n\t\t\t\t\t\t\t\tlet tempUser = users[i][\"username\"];\r\n\t\t\t\t\t\t\t\tlet tempPass = users[i][\"password\"];\r\n\t\t\t\t\t\t\t\tlet tempScore = users[i][\"gamescore\"];\r\n\t\t\t\t\t\t\t\tif (username == tempUser){ // if username is the entered one\r\n\t\t\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\t\t\tif (password == tempPass){ // if password is correct\r\n\t\t\t\t\t\t\t\t\t\tloggedIn = true; // changes logged in status\r\n\t\t\t\t\t\t\t\t\t\tmaxScore = tempScore;\r\n\t\t\t\t\t\t\t\t\t\toverallUsername = username;\r\n\r\n\t\t\t\t\t\t\t\t\t\t// updates page elements to reflect user information\r\n\t\t\t\t\t\t\t\t\t\tdocument.getElementById(\"inputs\").innerHTML = \"User: \" +\r\n\t\t\t\t\t\t\t\t\t\tusername;\r\n\t\t\t\t\t\t\t\t\t\tlet scores = document.createElement(\"p\");\r\n\t\t\t\t\t\t\t\t\t\tscores.innerHTML = \"Recent Score: \" + userscore + \"<br>\";\r\n\t\t\t\t\t\t\t\t\t\tscores.innerHTML += \"Best Score: \" + tempScore;\r\n\t\t\t\t\t\t\t\t\t\tscores.id = \"scorekeeper\";\r\n\t\t\t\t\t\t\t\t\t\tlet button = document.createElement(\"button\");\r\n\t\t\t\t\t\t\t\t\t\tbutton.innerHTML = \"log out\";\r\n\t\t\t\t\t\t\t\t\t\tbutton.onclick = resetLogin;\r\n\t\t\t\t\t\t\t\t\t\tdocument.getElementById(\"inputs\").innerHTML += \"<br>\";\r\n\t\t\t\t\t\t\t\t\t\tdocument.getElementById(\"inputs\").appendChild(scores);\r\n\t\t\t\t\t\t\t\t\t\tdocument.getElementById(\"inputs\").appendChild(button);\r\n\r\n\t\t\t\t\t\t\t\t\t} else{\r\n\t\t\t\t\t\t\t\t\t\tdocument.getElementById(\"retry\").innerHTML =\r\n\t\t\t\t\t\t\t\t\t\t\"Incorrect Password!\";\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\t\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (!found){\r\n\t\t\t\t\t\t\t\tdocument.getElementById(\"retry\").innerHTML = \"Invalid Username!\";\r\n\t\t\t\t\t\t\t}\t\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.catch(function(error){\r\n\t\t\t\t\t\tconsole.log(error);\r\n\t\t\t\t\t});\r\n\r\n\t\t}\r\n\r\n\t}", "async setInfo(isSaving){\n try {\n\n if(isSaving){\n await AsyncStorage.setItem('ip', this.state.ip);\n await AsyncStorage.setItem('login', this.state.login);\n } else {\n await AsyncStorage.removeItem('ip');\n await AsyncStorage.removeItem('login'); \n }\n } catch (error) {\n console.log(\"AsyncStorage error: \"+ error);\n }\n }", "function doWhenLoggedIn() {\n console.log(\"in doWhenLoggedIn appUser: \" + JSON.stringify(appUser));\n if (appUser.firstName !== \"\" && appUser.lastName !== \"\") {\n addUserToDb();\n }\n\n // empty current stock ticker\n $(\"#stock-input\").val(\"\");\n\n // check user watchlist\n renderUserWatchlist();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if text exceeds the 17 character limit
function limitText(){ var str = primaryOutput.innerHTML; var textLimit = 17; str.split(""); //If text exceeds limit and is less than 4 extra, reduce font size //If text exceeds limit between 5 and 9 characters reduce font size more //If text exceeds limit by more than 9 characters print message to screen if (str.length > textLimit && str.length <= (textLimit + 3)){ primaryOutput.style.fontSize = ".9em"; } else if (str.length > (textLimit + 3) && str.length <= (textLimit + 8)){ primaryOutput.style.fontSize = ".7em"; } else if (str.length > (textLimit + 8)){ primaryOutput.innerHTML = "Exceeded limit"; } }
[ "static validateShortTextExceedsLength(pageClientAPI, dict) {\n\n //New short text length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ShortTextLength');\n\n if (libThis.evalShortTextLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ShortTextNote'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }", "static evalShortTextLengthWithinLimit(dict, limit) {\n return (dict.ShortTextNote.length <= Number(limit));\n }", "function checkTextArea(textArea, max){\r\n\tvar numChars, chopped, message;\r\n\tif (!checkLength(textArea.value, 0, max)) {\r\n\t\tnumChars = textArea.value.length;\r\n\t\tchopped = textArea.value.substr(0, max);\r\n\t\tmessage = 'You typed ' + numChars + ' characters.\\n';\r\n\t\tmessage += 'The limit is ' + max + '.';\r\n\t\tmessage += 'Your entry will be shortened to:\\n\\n' + chopped;\r\n\t\talert(message);\r\n\t\ttextArea.value = chopped;\r\n\t}\r\n}", "function setMaxCharacterCount() {\n if ($(\".word\").width() <= 335) {\n return 8;\n } else if ($(\".word\").width() <= 425) {\n return 9;\n } else if ($(\".word\").width() <= 490) {\n return 10;\n } else if ($(\".word\").width() <= 510) {\n return 11;\n } else {\n return 12;\n }\n }", "overflown() {\n let _this = this;\n\n return this.result.split('\\n').some((line) => {\n return line.length > _this.config['max-len'];\n });\n }", "function longWord (input) {\n return input.some(x => x.length > 10);\n}", "function strLength(x){\n if (typeof x === \"string\" && x.length >= 8){\n return true;\n }\n return false;\n }", "function shorten(string) {\n \n // MAX CHARACTER LIMIT\n var max_length = 25;\n \n // CHECK IF THE STRING IS LONGER THAN 22 CHARACTERS\n if (string.length > max_length) {\n\n // ALLOW THE FIRST 20 CHARACTERS AND TAG ON THE TRIPLEDOT\n string = string.substring(0, (max_length - 3));\n string += '...';\n }\n\n return string;\n}", "function passwordLongEnough(password){\n if(password.length>=15)return true \n return false\n}", "function isLineOverlong(text) {\n\t\tvar checktext;\n\t\tif (text.indexOf(\"\\n\") != -1) { // Multi-line message\n\t\t\tvar lines = text.split(\"\\n\");\n\t\t\tif (lines.length > MAX_MULTILINES)\n\t\t\t\treturn true;\n\t\t\tfor (var i = 0; i < lines.length; i++) {\n\t\t\t\tif (utilsModule.countUtf8Bytes(lines[i]) > MAX_BYTES_PER_MESSAGE)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (text.startsWith(\"//\")) // Message beginning with slash\n\t\t\tchecktext = text.substring(1);\n\t\telse if (!text.startsWith(\"/\")) // Ordinary message\n\t\t\tchecktext = text;\n\t\telse { // Slash-command\n\t\t\tvar parts = text.split(\" \");\n\t\t\tvar cmd = parts[0].toLowerCase();\n\t\t\tif ((cmd == \"/kick\" || cmd == \"/msg\") && parts.length >= 3)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 2);\n\t\t\telse if ((cmd == \"/me\" || cmd == \"/topic\") && parts.length >= 2)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 1);\n\t\t\telse\n\t\t\t\tchecktext = text;\n\t\t}\n\t\treturn utilsModule.countUtf8Bytes(checktext) > MAX_BYTES_PER_MESSAGE;\n\t}", "splitText(text, max_chars = 38, max_lines = 2) {\n const words = text.split(' ');\n const ellipsis = '...';\n let newText = '';\n let lines = 1;\n let lineLength = 0;\n for (let i = 0; i < words.length; i++) {\n if (lineLength + String(words[i]).length > max_chars) {\n if (String(words[i]).length > 16) {\n words[i] =\n words[i].substr(0, Math.floor(String(words[i]).length / 2)) +\n '—' +\n '\\n' +\n words[i].substr(Math.floor(String(words[i]).length / 2));\n //lines++;\n }\n lineLength = 0;\n lines++;\n\n if (lines > max_lines) {\n newText += ellipsis;\n break;\n }\n newText += '\\n';\n }\n newText += ' ' + words[i];\n lineLength += words[i].length + 1;\n }\n return newText;\n }", "function isCorrectLength(s,l) {\n var i;\n if(lengthInUtf8Bytes(s) > l) return false;\n else return true;\n}", "function checkSMSLength( address, subject, text, placeHolder ) {\n var staticLength = subject.length + text.length - placeHolder.length,\n extraLength = 0,\n LIMIT = 138;\n\n if( LIMIT < staticLength + address.length ) {\n extraLength = (staticLength + address.length) - LIMIT;\n if( 0 < extraLength ) {\n address = address.substr( 0, address.length - extraLength );\n Y.log( 'createSMSBody: text after cut=' + text, 'debug', NAME );\n }\n }\n text = text.replace( placeHolder, address );\n return text;\n }", "static validateReadingExceedsLength(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //New reading length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ReadingLength');\n\n if (libThis.evalReadingLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }", "static evalReadingLengthWithinLimit(dict, limit) {\n return (dict.ReadingSim.toString().length <= Number(limit));\n }", "function varCharLimit(id, limit) {\n var input = document.getElementById('varchar_size_' + id);\n var value = input.value;\n if (value < limit) {\n input.value = limit;\n }\n}", "checkForcedWidth() {\n var maximum_string_width = 0;\n\n for(var i=0;i<this.dispatcher.split_words.length;i++) {\n var block = this.dispatcher.split_words[i];\n if(block.match(/^\\s+$/)) { // только строка из пробелов совершает word-break, так что её не проверяем\n continue;\n }\n if(maximum_string_width < this.getStringWidth(block)) {\n maximum_string_width = this.getStringWidth(block);\n }\n }\n\n for(var i=0;i<99;i++) {\n var proposed_width = i * this.border_size;\n if(proposed_width > maximum_string_width) {\n this.forced_width = i;\n break;\n }\n }\n }", "function comprobarTextoSin(campo, size){\r\n\t//Obtenemos el valor que contiene el campo\r\n\tvar valor = campo.value;\r\n\t//Comprobamos que el campo sea texto y no tenga espacios en blanco\r\n\tif( valor.length>size || /\\s/.test(valor)) {\r\n\t elementoInvalido(campo);\r\n\t return false;\r\n\t \r\n\t}\r\n\t//Si cumple las condiciones anteriores es texto sin espacios retornamos true\r\n\telse{\r\n\t elementoValido(campo);\r\n\t return true;\r\n\t}\r\n\t\r\n}", "function isStringTooLong(str,maxlen)\n{\n if (str==null || str==\"\")\n\t\treturn 0;\n \n var len = str.toString().length;\n if (len > maxlen)\n\treturn 1;\n else\n return 0;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spawn an seperate process to kill the parent and the mongod instance to ensure "mongod" gets stopped in any case
_launchKiller(parentPid, childPid) { this.debug(`_launchKiller: Launching Killer Process (parent: ${parentPid}, child: ${childPid})`); // spawn process which kills itself and mongo process if current process is dead const killer = (0, child_process_1.fork)(path.resolve(__dirname, '../../scripts/mongo_killer.js'), [parentPid.toString(), childPid.toString()], { detached: true, stdio: 'ignore', // stdio cannot be done with an detached process cross-systems and without killing the fork on parent termination }); killer.unref(); // dont force an exit on the fork when parent is exiting this.emit(MongoInstanceEvents.killerLaunched); return killer; }
[ "function killMongorestore( collectionName, callback ) {\n var\n cmdKILL = 'kill ',\n exec = require( 'child_process' ).exec;\n\n mongorestoreCheck( collectionName, function( err, pid ) {\n if( err ) {\n return callback( err );\n }\n if( pid ) {\n Y.log( 'killMongorestore: mongorestore is running, killing the process ' + pid, 'debug', NAME );\n exec( cmdKILL + pid, callback );\n } else {\n callback();\n }\n } );\n }", "async closeDatabase() {\n await mongoose.connection.close();\n await mongoDb.stop();\n }", "kill() {\n children.forEach( (child) => {\n child.stdin.pause();\n child.kill();\n });\n }", "function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}", "_terminate() {\n if (this._instance) {\n this._instance.close();\n this._instance = null;\n this._stopListeningForTermination();\n this._options.onStop(this);\n }\n\n process.exit();\n }", "function krnKillProcess(pid)\n{ \n _Scheduler.removeFromSchedule(_CPU, parseInt(pid,10));\n}", "_closeMongos(){\n this._mongoAliases.forEach(alias => {\n delete this[alias]\n })\n\n this._mongoDbNames.forEach((refName)=>{\n if (this[refName] == null)\n return\n\n this._closePromises.push(this[refName].close().then(()=>{\n self._logger.info(`Mongo/${refName} connection closed`)\n delete this[refName]\n })\n .catch(()=>{\n self._logger.info.log(`Mongo/${refName} connection close error`)\n delete this[refName]\n return Promise.resolve() // resolve anyway\n }))\n })\n }", "killChromeInstance() {\n this.chromeInstance.kill()\n }", "disconnectDB() {\n mongoose.disconnect(this.database);\n }", "stopTale(tale) {\n const self = this;\n return new Promise((resolve, reject) => {\n if (tale.instance) {\n if (tale.instance.status === 2) {\n // TODO: Previous instance creation failed, proceed with caution\n } else if (tale.instance.status === 0) {\n // TODO: Instance is still launching... wait and then shut down\n }\n \n // TODO: Create Job to destroy/cleanup instance\n self.set('deletingInstance', true);\n const model = tale.instance;\n model.destroyRecord({\n reload: true,\n backgroundReload: false\n }).then((response) => {\n // TODO replace this workaround for deletion with something more robust\n self.get('store').unloadRecord(model);\n tale.set('instance', null);\n resolve(response);\n });\n \n } \n });\n }", "_terminateProcess(code, signal) {\n if (signal !== undefined) {\n return process.kill(process.pid, signal);\n }\n if (code !== undefined) {\n return process.exit(code);\n }\n throw new Error('Unable to terminate parent process successfully');\n }", "function respawn(args) {\n var filename = path.resolve(__dirname, \"../../bin/tl.js\")\n var flags = args.unknown.concat([filename])\n\n if (args.color != null) flags.push(args.color ? \"--color\" : \"--no-color\")\n if (args.config != null) flags.push(\"--config\", args.config)\n if (args.cwd != null) flags.push(\"--cwd\", args.cwd)\n\n args.require.forEach(function (file) {\n flags.push(\"--require\", file)\n })\n\n // It shouldn't respawn again in the child process, but I added the flag\n // here just in case. Also, don't try to specially resolve anything in the\n // respawned local CLI.\n flags.push(\"--no-respawn\", \"--force-local\", \"--\")\n flags.push.apply(flags, args.files)\n\n // If only there was a cross-platform way to replace the current process\n // like in Ruby...\n require(\"child_process\").spawn(process.argv[0], flags, {stdio: \"inherit\"})\n .on(\"exit\", function (code) { if (code != null) process.exit(code) })\n .on(\"close\", function (code) { if (code != null) process.exit(code) })\n .on(\"error\", function (e) {\n console.error(e.stack)\n process.exit(1)\n })\n}", "killPollResponderTasks() {\n this.Poller.kill({ namespace: 'email.domain.email.responder' });\n }", "pid() {\n return cluster.isMaster ? process.pid : cluster.worker.process.pid;\n }", "function startCleanup(mongo, redis, data) {\n var deferred = q.defer();\n var tasks = [];\n _.each(data, function (docName) {\n tasks.push(function (callback) {\n cleanDoc(mongo, redis, docName, callback);\n });\n });\n async.parallelLimit(tasks, 2, function (err) {\n if (err) {\n deferred.reject(err);\n } else {\n deferred.resolve();\n }\n });\n return deferred.promise;\n}", "_stopListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.removeListener(eventName, this._terminate);\n });\n }", "function restartPhantom(crawl, e) {\n if (e) {\n console.log(\"Phantom Error:\", e);\n try {\n console.log(\"try to kill: \", crawl.processId);\n process.kill(crawl.processId);\n } catch (err) {\n //\n }\n }\n\n removeFromArray(crawl.processId);\n crawl.websites = crawl.websites.slice(crawl.index);\n initPhantom(crawl.websites, crawl.crawlStatus);\n}", "_killRover (roverName: string) {\n const { pid } = this._rovers[roverName]\n this._logger.info(`Killing rover '${roverName}', PID: ${pid}`)\n try {\n process.kill(pid, 'SIGHUP')\n } catch (err) {\n this._logger.warn(`Error while killing rover '${roverName}', PID: ${pid}, error: ${errToString(err)}`)\n }\n }", "stop(){\n let cron = this.cron\n Object.keys(cron).map((cronName)=>{\n cron[cronName].stop()\n })\n return true\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the HTML input element for the csrfToken which is used by the Crawlspace server to validate the user
function createValidationToken() { const token = document.createElement('input') // Hide the input element within the form token.type = 'hidden' // Assign the value of the csrfToken based on the global variable generated and loaded inline script in the crawl.html token.value = csrfToken token.name = 'csrfmiddlewaretoken' return token }
[ "static async getCsrfToken() {\n return new Promise((resolve, reject) => {\n if (typeof window === 'undefined') {\n return reject(Error('This method should only be called on the client'))\n }\n\n let xhr = new XMLHttpRequest()\n xhr.open('GET', '/auth/csrf', true)\n xhr.onreadystatechange = () => {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n const responseJson = JSON.parse(xhr.responseText)\n resolve(responseJson.csrfToken)\n } else {\n reject(Error('Unexpected response when trying to get CSRF token'))\n }\n }\n }\n xhr.onerror = () => {\n reject(Error('XMLHttpRequest error: Unable to get CSRF token'))\n }\n xhr.send()\n })\n }", "function createFieldToken(field, id, type){\n \n // Get field value and token container\n \n let value = $(field).val();\n let container = $(field).siblings('.token-container');\n let tokenNo = $(container).find('.token').length + 1;\n \n // If token container doesn't exist, create it\n \n if(container.length == 0){\n \n // Create token container\n \n container = $('<div></div>');\n $(container).addClass('token-container');\n \n // Add token container after field\n \n $(field).after(container);\n \n }\n \n if(id == '' || $(container).find('input[value=\"' + id + '\"]').length == 0){\n \n // Create token\n \n let token = $('<span></span>');\n $(token).addClass('token');\n \n // Add HTML\n \n let html = value + '<button type=\"button\" class=\"exit\"></button>';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-id\" value=\"' + id + '\">';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-type\" value=\"' + type + '\">';\n $(token).html(html);\n \n // Add token to end of token container\n \n $(container).append(token);\n \n // Set event handlers\n \n setTokenHandlers(token);\n \n }\n \n // Clear field value and focus on field\n \n $(field).val('');\n $(field).focus();\n $(field).siblings('.autocomplete-list').hide();\n \n}", "function submitToken() {\n var token = document.getElementById('tokenField').value;\n var nDay = 14;\n var date = new Date();\n date.setTime(date.getTime() + (nDay * 24 * 60 * 60 * 1000))\n var expires = \"; expires=\" + date.toGMTString();\n document.cookie = \"staticReader\" + \"=\" + token + expires + \";\";\n colorGreen('tokenButton');\n accessToken = \"access_token=\" + token;\n gistQuery = gitAPI + gistID + \"?\" + accessToken;\n}", "function buildCardTitleForm() {\n\t\t\tvar node = document.createElement('form')\n\t\t\tnode.innerHTML =\n\t\t\t\t'<div class=\"newitem-title-wrapper\">' +\n\t\t\t\t'<textarea class=\"trello-new-card-title-input\" type=\"text\"></textarea>' +\n\t\t\t\t'<input class=\"trello-new-card-title-submit\" type=\"submit\" value=\"Add\">' +\n\t\t\t\t'</div>'\n\t\t\tnode.style.display = 'none'\n\t\t\treturn node;\n\t\t}", "function getTokenIDInput() {\n var tokenAddressField = document.getElementById(\"tokenId\")\n\n var tokenId = tokenAddressField.value.trim()\n\n return cleanTokenInput(tokenId)\n }", "function renderTokenMissingPage()\n{\n // Compose the page structure\n webix.ui({\n id: 'token_missing_form',\n view: 'form',\n width: 325,\n elements: [\n {view: 'label', label: '<strong>No access token found</strong>'},\n {view: 'label', label: 'Follow <a href=\"https://github.com/settings/tokens/new\" id=\"token_missing_link\">this link</a> to create one and paste it below:'},\n {view: 'text', placeholder: 'Paste access token here', id: 'token_missing_input'},\n {view: 'label', label: '<span class=\"red\">The suplied token is not valid</strong>', id: 'token_missing_notification', hidden: true},\n {view: 'button', value: 'Save', type: 'form', click: 'tokenMissingSave'}\n ]\n });\n\n // Open a new tab when user click on a link\n document.getElementById('token_missing_link').onclick = function()\n {\n chrome.tabs.create({url: this.href});\n };\n}", "function genInput(name, value) {\n var input = document.createElement('input');\n input.name = name;\n input.value = value;\n return input;\n }", "_createToken() {\n const that = this;\n let icon;\n const fragment = document.createDocumentFragment(),\n lastSelectedIndex = that.selectedIndexes[that.selectedIndexes.length - 1];\n\n if (that.selectionDisplayMode === 'plain' && (that.selectionMode === 'one' || that.selectionMode === 'zeroOrOne' || that.selectionMode === 'radioButton')) {\n icon = '';\n }\n else {\n if (that.selectionDisplayMode === 'tokens') {\n if (that.selectedIndexes.length === 1 && (['oneOrManyExtended', 'oneOrMany', 'one', 'radioButton'].indexOf(that.selectionMode) > -1)) {\n icon = '';\n }\n else {\n icon = '&#10006';\n }\n }\n else {\n icon = that.selectedIndexes.length === 1 ? '' : ',';\n }\n }\n\n const selectedIndexes = that.selectedIndexes,\n items = that.$.listBox._items;\n\n for (let i = 0; i < selectedIndexes.length; i++) {\n const selectedIndex = selectedIndexes[i];\n\n if (items[selectedIndex]) {\n fragment.appendChild(that._applyTokenTemplate(items[selectedIndex].label, that.selectionDisplayMode !== 'tokens' && selectedIndex === lastSelectedIndex ? '' : icon));\n }\n }\n\n return fragment;\n }", "function createInputField() {\n var inputAnswer = document.createElement('input');\n inputAnswer.setAttribute('id','inputAnswer');\n inputAnswer.setAttribute('placeholder','answer');\n inputAnswer.style.width = \"160px\";\n return inputAnswer;\n}", "function checkGToken() {\n var val = document.getElementById(\"groupToken\").value;\n\n if (!val || !val.length) {\n a3 = false;\n $(\"#gcreate-button\").attr(\"disabled\", true);\n }\n\n if (val.length > 30) {\n document.getElementById(\"groupToken\").classList.remove(\"valid\");\n document.getElementById(\"groupToken\").classList.add(\"invalid\");\n a3 = false;\n a6 = false;\n } else {\n document.getElementById(\"groupToken\").classList.remove(\"invalid\");\n document.getElementById(\"groupToken\").classList.add(\"valid\");\n a3 = true;\n a6 = true;\n }\n\n checkGForm();\n}", "function createPubID() {\n const pubID = document.createElement('input')\n // Hide the input element within the form\n pubID.type = 'hidden'\n pubID.value = pubPlaceID\n pubID.name = 'place_id'\n return pubID\n }", "function createFieldToken(field){\n \n createFieldToken(field, '', '');\n \n}", "function createErrorElement () {\n const errorMessage = document.createElement(\"span\");\n errorMessage.className = \"validation-message\";\n errorMessage.style.display = \"none\";\n return(errorMessage);\n}", "function createPubText() {\n const pubText = document.createElement('input')\n pubText.value = pubName\n // Hide the input element within the form\n pubText.type = 'hidden'\n pubText.name = 'pub_name'\n return pubText\n }", "forbidden () {\n Logger.debug('CSRF token verification failed')\n throw Boom.forbidden()\n }", "function getDomVariables() {\n // the form\n registerFormDiv = document.querySelector('#log-in_form'); // the inputs\n\n usernameInput = document.querySelector('#username');\n emailInput = document.querySelector('#email');\n passwordInput = document.querySelector('#password');\n passwordBisInput = document.querySelector('#password-bis'); // the spans to display errors\n\n usernameErrorSpan = document.querySelector('label[for=\"username\"] span.msg-error');\n emailErrorSpan = document.querySelector('label[for=\"email\"] span.msg-error');\n passwordErrorSpan = document.querySelector('label[for=\"password\"] span.msg-error');\n passwordBisErrorSpan = document.querySelector('label[for=\"password-bis\"] span.msg-error'); // array including inputs and error spans\n\n inputsAndSpans = [['username', usernameInput, usernameErrorSpan], ['email', emailInput, emailErrorSpan], ['password', passwordInput, passwordErrorSpan], ['password-bis', passwordBisInput, passwordBisErrorSpan]]; // the clickable question marks to display input rule helps\n\n usernameQuestionMark = document.querySelector('#username-help');\n passwordQuestionMark = document.querySelector('#password-help');\n passwordBisQuestionMark = document.querySelector('#password-bis-help'); // array including question marks and text to display\n\n helpers = [[usernameQuestionMark, usernameHelp], [passwordQuestionMark, passwordHelp], [passwordBisQuestionMark, passwordBisHelp]];\n} // check the value of the input", "function updateEngineToken(value, input) {\n var defaultTokenModel = mvc.Components.getInstance(\"default\"),\n submittedTokenModel = mvc.Components.getInstance(\"submitted\", {create: true});\n\n _([\"mysql\", \"postgres\", \"oracle\", \"sqlserver\"]).each(function(n) {\n defaultTokenModel.unset(n);\n submittedTokenModel.unset(n);\n });\n\n if(value.length < 1) { return; }\n\n var engines,\n allEngines = input.settings.get(\"rdsEngines\") || {};\n\n if(value.indexOf(\"*\") > -1) {\n engines = _(allEngines).values();\n } else {\n engines = _(value).map(function(v) {\n return allEngines[v];\n });\n }\n\n _.each(_.uniq(_.compact(engines)), function(n) {\n if(n === \"mariadb\") { n = \"mysql\"; }\n else if(n.indexOf(\"oracle\") > -1) { n = \"oracle\"; }\n else if(n.indexOf(\"sqlserver\") > -1) { n = \"sqlserver\"; }\n\n defaultTokenModel.set(n, true);\n // on page load, the \"depends\" tokens are read\n // from submitted token model\n submittedTokenModel.set(n, true);\n });\n }", "function getToken(){\n const stringUrl = URL.split(`=`)\n const token = stringUrl[1];\n console.log(token);\n if (token === undefined) {\n document.getElementById('submitNewPasswordForm').style.display=\"none\"\n } else {\n localStorage.setItem('Authorization', token);\n document.getElementById('sumbitEmailForm').style.display=\"none\"\n }\n}", "function AskUserForToken() {\n $(\"div#overlay-header\").html(\"Github Token\");\n $(\"div#overlay-body\").html($(\"div#overlay-templates div.overlay-user-token\").html());\n $(\"div#force-overlay\").css(\"display\", \"block\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save interval therapy info
function handleSaveIntervalTherapyInfo(agent) { const descrizione = agent.parameters.descrizione; const farmaco = agent.parameters.farmaco; const giorni = agent.parameters.giorni; const orario = agent.parameters.orario; // Test ok const senderID = getSenderID(); // Ottengo la posizione dei contatori delle terapie intervallari let intervalTerapyCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/terapieIntervallo'); return intervalTerapyCounterPath.once('value').then((snapshot) => { // Controllo quante terapie intervallari ha inserito il paziente let intervalTerapyCounterForUser = snapshot.val(); console.log('terapie intervallari gia\' espresse: ' + intervalTerapyCounterForUser); // Test sender id console.log('SenderID: ' + senderID); // Creo path con id pari a quantita' di terapie intervallari espresse let terapyPath = admin.database().ref('pazienti/' + senderID + '/terapie/intervallare/' + intervalTerapyCounterForUser); const terapia = { descrizione:descrizione, farmaco:farmaco, giorni:giorni, orario:orario }; terapyPath.set(terapia); // Incremento il numero di terapie intervallari di una unita' let intervalTerapyCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/terapieIntervallo'); intervalTerapyCounterPath.set(intervalTerapyCounterForUser + 1); }); }
[ "function doInterval() {\n getAddress();\n getAmountEth();\n getAmountToken();\n}", "function handleSaveDailyTherapyInfo(agent) {\n const descrizione = agent.parameters.descrizione;\n const farmaco = agent.parameters.farmaco;\n const orario = agent.parameters.orario;\n\n // Test ok\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle terapie giornaliere\n let dailyTherapyCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/terapieGiornaliere');\n return dailyTherapyCounterPath.once('value').then((snapshot) => {\n // Controllo quante terapie giornaliere ha inserito il paziente\n let dailyTherapyCounterForUser = snapshot.val();\n console.log('terapie giornaliere gia\\' espresse: ' + dailyTherapyCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di terapie giornaliere espresse\n let therapyPath = admin.database().ref('pazienti/' + senderID + '/terapie/giornaliera/' + dailyTherapyCounterForUser);\n\n const terapia = {\n descrizione:descrizione,\n farmaco:farmaco,\n orario:orario\n };\n\n therapyPath.set(terapia);\n\n // Incremento il numero di terapie giornaliere di una unita'\n let dailyTherapyCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/terapieGiornaliere');\n dailyTherapyCounterPath.set(dailyTherapyCounterForUser + 1);\n });\n }", "function SaveHourInfo(hour, data){\n localStorage.setItem(hour, data);\n}", "function save_patient_changes(){\n\tpatient_config.max_patients = parseFloat($(\"#patient-creation-limit\").val())\n\tpatient_config.batch_arrival_min = parseFloat($(\"#patient-batch-min\").val())\n\tpatient_config.batch_arrival_max = parseFloat($(\"#patient-batch-max\").val())\n\tpatient_config.batch_arrival_lambda = parseFloat($(\"#patient-batch-lambda\").val())\n}", "function saveDB(){\n clearInterval( intervalId );\n setInterval( saveDB, 60*60*1000 );\n PostsService.save();\n //$rootScope.postCount = $rootScope.postCount + 1;\n $rootScope.posthacked = [];\n }", "function startHR() {\nheartRateArray = new Array();\nwindow.webapis.motion.start(\"HRM\", function onSuccess(hrmInfo) {\n if (hrmInfo.heartRate > 0) \n HR = hrmInfo.heartRate;\n});\n//sendingInterval = setInterval(sendHR, 5000);\nsendingInterval = setInterval(makeJsonHR, 5000);\n}", "function manageWebParametersSave(socket) {\n\tsocket.on('save', function(data) {\n\t\tsetParam( \"TEMP_FAN\", TEMP_FAN );\n\t\tsetParam( \"TEMP_ATTENUATION\", TEMP_ATTENUATION );\n\t\tsetParam( \"ATTENUATION_SCALE\", ATTENUATION_SCALE );\n\t\tsetParam( \"CHECK_PERIOD\", CHECK_PERIOD );\n\t\tsetParam( \"TPS\", TPS );\n\t\tsetParam( \"NB_RAMPES\", NB_RAMPES );\n\t\tsetParam( \"SERVER_PORT\", SERVER_PORT );\n\t\tsetParam( \"ON\", ON );\n\t\tsetParam( \"OFF\", OFF );\n\t\tsetParam( \"DEBUG\", DEBUG );\n\t\tsetParam( \"LOG\", LOG );\n\t\tjsonfile.writeFileSync(file, parameters);\n\t\tif (DEBUG) { console.log( jsonfile.readFileSync(file) ); }\n\t});\n}", "function saveConfiguration() {\n console.log(\"saveConfiguration\");\n // save the current configuration in the \"chair\" object\n const chosenColors = view.getChairColors();\n model.updateChairObject(chosenColors);\n // update local storage\n model.updateLocalStarage(\"chair\", model.chair);\n console.log(model.chair);\n}", "function saveCurrentStation() {\n if (band) {\n selectedStations['currentBand'] = band.getName();\n selectedStations['bands'][band.getName()] = getFrequency();\n chrome.storage.local.set({'currentStation': selectedStations});\n }\n }", "function saveSchedules() {\n\t\tlocalStorage.setItem(\"aPossibleSchedules\", JSON.stringify(aPossibleSchedules));\n\t}", "function update(hour, data) {\n planData[\"hour\" + hour] = data;\n localStorage.setItem(\"planData\", JSON.stringify(planData));\n }", "function getWgTemp(){\n\t$.post( \"http://192.168.0.109:3000/wg_Temp\", function( dataWG ) {\n\t\t$( \"#widget\" ).html( dataWG);\n\n\t\t\tvar tempInterval = setInterval(function(){\n\n\t\t\t\t$.post( \"http://192.168.0.109:3000/Temp\", function( data ) {\n\t\t\t\t\tif(document.getElementById('wg_temp') !== null){\n\t\t\t\t\t\tvar ResTemp = jQuery.parseJSON(data);\n\t\t\t\t\t\t$(\"#varTemp\" ).html( ResTemp.TEMP);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//alert('Am schimbat content-ul');\n\t\t\t\t\t\tclearInterval(tempInterval);\n\t\t\t\t\t}\n\t\t\t\t}); //End Post din Interval\n\n\t\t\t}, 5000) //End setInterval\n\n\n\t});\n\n\n}", "getSaveTimeInterval() {\n let settings_url = \"/setting?setting_key=\".concat(this._save_time_interval_key);\n\n let save_time_interval = this._default_save_time_interval;\n\n $.ajax({url: settings_url, type: 'GET', contentType: \"application/json\"})\n // On failure inform user and stop\n .fail(error => this.informUser(\n 2, \"Fatal error: cannot get setting value: \" + error))\n .done((response) => {\n if (response.value != 'None') {\n save_time_interval = response.value;\n }\n else {\n this.informUser(1, \"Warning: save_time_interval was not set correctly. \" +\n \"Default time value of \" + this._default_save_time_interval.toString() + \"will be set.\");\n }\n });\n return save_time_interval;\n }", "function SaveAddTimeperiode(Number){\r\n\tvar StartTime = $(\"#StartTime\"+Number).val();\r\n\tvar StopTime = $(\"#StopTime\"+Number).val();\r\n\tvar timePeriode = $(\"#TimePeriode\"+Number).text();\r\n\t\r\n\twriteAddData(StartTime,StopTime,timePeriode,Number, function(Data){\r\n\t\tif (Data.write == 'success'){\r\n\t\t\t$(\"#tableCleaningInterval div\").remove();\r\n\t\t\tupdateTableafterChange();\r\n\t\t\t}\r\n\t});\t\r\n}", "function saveFitness() {\n}", "function setSchedule(hour){\n localStorage.setItem(hour, $(\"#hour\"+hour).val());\n}", "function saveDuration(number){\r\n durationArray.push(number);\r\n localStorage.setItem(\"durationLocal\", JSON.stringify(durationArray));\r\n}", "function timeHandler(timeAry) {\n if (timeAry[1] === dataObj.everySecondTrig) {\n everySecond(timeAry[1]);\n if (timeAry[1] === 59) {\n dataObj.everySecondTrig = 0;\n } else {\n dataObj.everySecondTrig++; \n }\n } else if (Math.abs(timeAry[1] - dataObj.everySecondTrig) >= 2) {\n dataObj.everySecondTrig = timeAry[1] + 1;\n }\n \n //everyMinute(timeAry[2]);\n \n if (timeAry[1] % 30 === 0) {\n if (dataObj.computationReady) {\n everyThirty(timeAry[1]);\n dataObj.computationReady = false;\n } else {\n //console.log(\"Already computered.\");\n }\n } else {\n if (dataObj.computationReady === false) {\n dataObj.computationReady = true;\n }\n }\n}", "function handleSaveTheatrePrefInfo(agent) {\n const genere = agent.parameters.genere;\n const titolo = agent.parameters.titolo;\n const autore = agent.parameters.autore;\n\n // Test ok\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle preferenze\n let theatreTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/teatro');\n\n return theatreTasteCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti gusti teatrali ha inserito il paziente\n let theatreTasteCounterForUser = snapshot.val();\n console.log('Num gusti teatro gia\\' espressi: ' + theatreTasteCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di preferenze espresse\n let theatreTastePath = admin.database().ref('pazienti/' + senderID + '/preferenze/teatro/' + theatreTasteCounterForUser);\n\n const musica = {\n genere:genere,\n titolo:titolo,\n autore:autore\n };\n\n // Salvo il gusto teatrale\n theatreTastePath.set(musica);\n\n // Incremento il numero di gusti teatrali di una unita'\n let theatreTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/teatro');\n theatreTasteCounterPath.set(theatreTasteCounterForUser + 1);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region max end computation
function computeMaxEnd(node) { var maxEnd = node.end; if (node.left !== SENTINEL) { var leftMaxEnd = node.left.maxEnd; if (leftMaxEnd > maxEnd) { maxEnd = leftMaxEnd; } } if (node.right !== SENTINEL) { var rightMaxEnd = node.right.maxEnd + node.delta; if (rightMaxEnd > maxEnd) { maxEnd = rightMaxEnd; } } return maxEnd; }
[ "function max_subarray(A){\n let max_ending_here = A[0]\n let max_so_far = A[0]\n\n for (let i = 1; i < A.length; i++){\n max_ending_here = Math.max(A[i], max_ending_here + A[i])\n // console.log(max_ending_here)\n max_so_far = Math.max(max_so_far, max_ending_here)\n // console.log(max_so_far)\n } \n\n return max_so_far\n}", "function findMaximumValue(array) {\n\n}", "function make_max_Ediff()\n{\n var i, beleg;\n var max;\n\n for (i=0; i<struct_len; i++)\n {\n if (BP_Pos_Nr[i] == -1)\n beleg = 4;\n else if (i == BP_Order[BP_Pos_Nr[i]][1]) //closing bracket\n beleg = 6;\n else\n beleg = 0;\n\n if (beleg != 0)\n {\n max = MaxiVec(Ediff[i], beleg);\n max_Ediff[i] = max[1];\n }\n else\n max_Ediff[i] = MIN_INT;\n }\n}", "findMax() { \n if(this.isEmpty()) return Number.MIN_VALUE;\n return this.heap[0];\n }", "get temporalRangeMax() {\n return this.temporalRange[1];\n }", "function calculateMaxScore () {\n\t\t\tfor (var i=0; i <= game.maxturn-1; i++) {\n\t\t\t\tgame.discrete.maxScore += game.discrete.optimalCrops[i]\n\t\t\t}\n\n\t\t\treturn game.discrete.maxScore;\n\t\t}", "max() {\n for(let i = this.array.length - 1; i >= 0; i--){\n const bits = this.array[i];\n if (bits) {\n return BitSet.highBit(bits) + i * bitsPerWord;\n }\n }\n return 0;\n }", "function findMaxProduct(array) {\n\n}", "function getHeight() {\n return maxy + 1;\n }", "function maximumSpreadRate (ros0, phiEw) {\n return ros0 * (1 + phiEw)\n}", "function print_max_Ediff()\n{\n var i;\n outln(\"max_Ediff:\");\n for (i=0; i<struct_len; i++)\n {\n out(i + \" \");\n out(max_Ediff[i] + \"\\n\");\n }\n}", "MaxValue(dataKey, data) {\r\n if (data.length == 0)\r\n {\r\n return \"0\";\r\n }\r\n else\r\n {\r\n var chartValues=[];\r\n // data.\r\n var count=data.length;\r\n for(var i=0;i<count;i++)\r\n {\r\n var temp=data[i];\r\n chartValues.push(temp[dataKey]);\r\n }\r\n\r\n return Math.max.apply(0,chartValues).toFixed(2);\r\n } \r\n }", "cummax(options) {\n const ops = { inplace: false, ...options };\n return this.cumOps(\"max\", ops);\n }", "maximum(other) {\n if (this.dtypes[0] == \"string\") ErrorThrower.throwStringDtypeOperationError(\"maximum\");\n\n const newData = _genericMathOp({ ndFrame: this, other, operation: \"maximum\" });\n return new Series(newData, {\n columns: this.columns,\n index: this.index\n });\n }", "function bruteForceMaxSubarray(numbers) {\n let n = numbers.length; \n let res = 0; \n\n for (let i = 0; i < n; ++i) {\n let sum = 0; \n for (let j = i; j < n; ++j) {\n // for every subarray [i ... j]\n sum += numbers[j]; \n res = Math.max(res, sum);\n }\n }\n return res; \n }", "getMaxY(){ return this.y + this.height }", "function maxFinderFunction(receivingGivingNumber) {\n // Assigning a hypothetic possibly-giving constraint\n let maxNumber = -1000000;\n// Looping through the given number array to iterate and search\n for(i = 0; i < receivingGivingNumber.length; i++) {\n if(receivingGivingNumber[i] > maxNumber) {\n maxNumber = receivingGivingNumber[i];\n }\n }\n // Returning result after looping completion\n console.log(maxNumber);\n return maxNumber;\n}", "function maxLoot_(arr){\n let n = arr.length;\n if(n==0)\n return 0;\n let value1 = arr[0];\n if(n==1)\n return value1;\n \n let value2 = Math.max(arr[0] , arr[1]);\n if(n == 2)\n return value2;\n let maxValue = 0;\n for(let i = 2 ; i < n ; i++){\n maxValue = Math.max(arr[i]+ value1 , value2);\n value1= value2;\n value2 = maxValue;\n }\n return maxValue;\n}", "function _getMax(allowedCards){\n\t\tvar max = 0;\n\t\tfor(var i in allowedCards){\n\t\t\tif(cardPrefixesAndLengths[allowedCards[i]].max > max){\n\t\t\t\tmax = cardPrefixesAndLengths[allowedCards[i]].max;\n\t\t\t}\n\t\t}\n\t\treturn max;\n\t}", "function findC(g, b) {\n // first sort the grants and get total\n // nlogn time\n g.sort(function compareNumbers(a, b) {\n return b - a;\n })\n console.log(g)\n var total = 150\n var neededCuts = total-b\n var runningTotal = 0\n \n for(var i=0; i<g.length; i++){\n var currentMax = g[i]\n if((g[i] - g[i+1]) >= neededCuts){\n return g[i] - neededCuts\n }\n console.log('current max: '+currentMax)\n console.log('difference: '+ (g[i] - g[i+1]))\n \n runningTotal += (g[i] - g[i+1])*(i+1)\n console.log('runningTotal: '+ runningTotal)\n console.log('----')\n\n if(runningTotal >= neededCuts){\n return (g[0]-g[i])+Math.floor(((runningTotal-neededCuts)/(i+1)))+1\n }\n \n // reduce max to next max or new budget, recursive\n // reduce 54 -> 32 += 18 of 30 needed\n // needs 12 more\n // reduce 32 -> 23 += 2x(9) = 18 above what is needed, c is above next max \n // and below current max\n }\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 231 Create a function that takes a sentence and turns every "i" into "wi" and "e" into "we", and add "owo" at the end.
function owofied(sentence) { const a = sentence.replace(/i/g, "wi"); const b = a.replace(/e/g, "we"); return b + " owo"; }
[ "function encodeConsonantWord(word) {\n\n \n word = word.toLowerCase();\n let firstletter = word[0];\n let cons_phrase = \"-\";\n \n\n while\n (firstletter !== \"a\" || \n firstletter !== \"e\" || \n firstletter !== \"i\" || \n firstletter !== \"o\" || \n firstletter !== \"u\")\n {\n \n cons_phrase += word[0];\n word = word.slice(1);\n firstletter = word[0];\n \n\n if(firstletter == \"a\" || \n firstletter == \"e\" || \n firstletter == \"i\" || \n firstletter == \"o\" || \n firstletter == \"u\" ){\n\n return word + cons_phrase + \"ay\";\n\n\n }\n\n \n }\n\n return word; // replace this!\n}", "function translate (phrase) {\n var newPhrase = \" \";\n for (var count = 0; count < phrase.length; count++) {\n var letter = phrase[count];\n if (cleanerIsVowel(letter) || letter === \" \") {\n newPhrase += letter;\n } else {\n newPhrase += letter + \"o\" + letter;\n }\n return newPhrase;\n}\n\n translate(\"these are some words\");\n}", "function encodeWord(word) {\n\n if (word[0].toLowerCase() === \"a\" ||\n word[0].toLowerCase() === \"e\" ||\n word[0].toLowerCase() === \"i\" ||\n word[0].toLowerCase() === \"o\" ||\n word[0].toLowerCase() === \"u\" )\n {\n return encodeVowelWord(word);\n \n }\n return encodeConsonantWord(word); // replace this!\n}", "function toWeirdCase(string){\n return string.split(\" \")\n .map(word => word.split(\"\").map((word, ind) => ind%2 == 0 ? word.toUpperCase() : word).join(\"\"))\n . join(\" \")\n}", "function evenCaps(sentence) {\n\n\n // Create a variable using split that splits the sentence up by character\n let splitSentence = sentence.split('');\n\n // Create an array to store our updated words\n let wordArray = [];\n\n // Loop through our split up sentence BY CHARACTER using .length\n for (let i = 0; i < splitSentence.length; i ++) {\n\n //Create a condition that checks the remainder, if there is a remainder, push it into our array and make it uppercase, if there is not a remainder, push it in, but dont make it uppercase.\n if (!(i % 2)) {\n wordArray.push(splitSentence[i].toUpperCase());\n } else {\n wordArray.push(splitSentence[i]);\n }\n }\n // Create a variable that rejoins our array joined back together\n let wordArrayJoined = wordArray.join('');\n\n return wordArrayJoined;\n\n}", "function weave(strings) {\n let phrase = ('coding iz hard')\n let string = phrase.split('')\n let nth = 4;\n let replace = 'x';\n for (i = nth - 1; i < string.length; i += nth) {\n string[i] = replace;\n }\n return string.join('');\n}", "function solve(s) {\n\tlet result = \"\";\n\tlet regex = /[aeiou]/;\n\tlet consonants = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn !regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tlet vowels = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tif (consonants.length > vowels.length) {\n\t\tfor (let i = 0; i < consonants.length; i++) {\n\t\t\tif (!vowels[i]) {\n\t\t\t\tresult += consonants[consonants.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += consonants[i];\n\t\t\tresult += vowels[i];\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < vowels.length; i++) {\n\t\t\tif (!consonants[i]) {\n\t\t\t\tresult += vowels[vowels.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += vowels[i];\n\t\t\tresult += consonants[i];\n\t\t}\n\t}\n\tif (result.length !== s.length) {\n\t\treturn \"failed\";\n\t} else {\n\t\treturn result;\n\t}\n}", "function swap(text) {\n let words = [];\n text.split(\" \").forEach(word => words.push(switchLetters(word)));\n console.log(words.join(\" \"));\n}", "function polybius (text) {\n let result = '';\n let alpha = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';\n\n for (char of text) {\n if (alpha.includes(char) || char === 'J') {\n let index = alpha.indexOf(char);\n if (char === 'J') index = alpha.indexOf('I');\n result += Math.floor(index / 5) + 1;\n result += index % 5 + 1;\n } else result += char;\n }\n\n return result;\n}", "function translatePigLatin(str) {\n var tab = str.split('');\n if (tab[0] == 'a' || tab[0] =='e' || tab[0] =='o' || tab[0] == 'i' || tab[0] =='u' || tab[0] == 'y') {\n var endOfWord = 'way';\n tab.push(endOfWord);\n return tab.join('');\n } else {\n var firstOfWord = '';\n do {\n firstOfWord += tab.shift();\n }\n while (tab[0] != 'a' && tab[0] !='e' && tab[0] !='o' && tab[0] != 'i' && tab[0] !='u' && tab[0] != 'y');\n var endClassic = 'ay';\n tab.push(firstOfWord,endClassic);\n return tab.join('');\n }\n}", "flip(input){\n // Set a temp string\n let output = \"\";\n // Look at each character in the string\n for(let i = 0; i < input.length; i++) {\n // If character is a \"A\", change it to a \"Z\" and save in a new string\n if (input[i] === \"A\") {\n output += \"Z\";\n // If charachter is a \"Z\", change it to an \"A\" and save in new string\n } else {\n output += \"A\";\n }\n }\n // Output the new string\n return output;\n }", "function makeHappy(arr){\n let result = arr.map(word => \"Happy \" + word)\n return result\n}", "function plusOut(str, word)\n{\n let result = \"\";\n let temp = \"\";\n let j = 0;\n for(let i = 0; i < str.length; i++){\n if(str.charAt(i) != word.charAt(j)){\n result = result + \"+\";\n if(temp.length!=0){\n for(let k = 0; k < temp.length; k++){\n result = result + \"+\";\n }\n }\n temp = \"\";\n j = 0;\n } \n else {\n temp = temp + str.charAt(i);\n if(word.length == temp.length){\n result = result + temp;\n j = 0;\n temp = \"\";\n } \n else {\n j++;\n }\n }\n }\n return result;\n}", "shifter(str) {\n\t\tlet newString = '';\n\t\tfor (const char of str) {\n\t\t\tnewString += /[a-z]/.test(char) ? String.fromCharCode(((char.charCodeAt(0) - 18) % 26) + 97) : char;\n\t\t}\n\t\treturn newString;\n\t}", "function replaceThe(str) {\n\tconst a = [];\n\tfor (let i = 0; i < str.split(\" \").length; i++) {\n\t\tif (str.split(\" \")[i] === \"the\" && /[aeiou]/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"an\");\n\t\t} else if (str.split(\" \")[i] === \"the\" && /([b-df-hj-np-tv-z])/.test(str.split(\" \")[i+1][0])) {\n\t\t\ta.push(\"a\");\n\t\t} else a.push(str.split(\" \")[i])\n\t}\n\treturn a.join(\" \");\n}", "function alternatingCaps(s) {\n\treturn s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]());\n}", "function wordPlay(){\n\tlet sentence = document.querySelector(\"#input\").value \n\tlet newArr = []\n\tsentence.split(\" \").forEach((element, index, arr) => element.length >= 3? newArr.push(element.split(\"\").reverse().join(\"\")): newArr)\n\tlet toAdd = document.querySelector(\"#addHere\");\n\ttoAdd.innerText = \"sentence: \"+sentence+\"\\nReversed: \" + newArr.join(\" \");\n}", "function reducer(sentence) {\nlet splittedArray = sentence.split(' ');\nlet newWord = splittedArray.reduce(function(initialValue, currentValue){\n\tif(splittedArray(currentValue).length === 3) {\n\t\tinitialValue += ' ';\n\t\treturn initialValue;\n\t}\n\telse {\n\t\tinitialValue += splittedArray(currentValue).charAt(currentValue.length-1).toUpperCase();\n\t\treturn initialValue;\n\t}\n\t}, '');\nreturn newWord;\n}", "function capitalWords(word) {\n word = word.charAt(0).toUpperCase() + word.slice(1);\n return word;\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A lookup table for atob(), which converts an ASCII character to the corresponding sixbit number.
function atobLookup(chr) { if (/[A-Z]/.test(chr)) { return chr.charCodeAt(0) - "A".charCodeAt(0); } if (/[a-z]/.test(chr)) { return chr.charCodeAt(0) - "a".charCodeAt(0) + 26; } if (/[0-9]/.test(chr)) { return chr.charCodeAt(0) - "0".charCodeAt(0) + 52; } if (chr === "+") { return 62; } if (chr === "/") { return 63; } // Throw exception; should not be hit in tests }
[ "hashFuncUnicodeKeyType(key){\n let hashValue = 0;\n const keyValueString = `${key}${typeof key}`;\n for ( let index = 0; index < keyValueString.length; index++){\n const keyCodeChar = keyValueString.charCodeAt(index);\n hashValue += keyCodeChar << (index * 8);\n }\n return hashValue;\n }", "function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9 \n }", "improvedHashFunc(key){\n let hashValue = 0;\n const keyValueString = key.toString();\n for (let index = 0; index < keyValueString.length; index++){\n // Get Unicode value for a character at index.\n const keyCodeChar = keyValueString.charCodeAt(index);\n // Add specific unicode\n hashValue += keyCodeChar;\n }\n return hashValue;\n }", "function siiB(e) {\r\n\treturn Math.round(parseInt(e)).toString(36);\r\n}", "function buildCharMapIndex() {\n // Unicode Blocks\n let basicLatin = []; // Block: 00..7E; Subset: 20..7E\n let latin1 = []; // Block: 80..FF; Subset: A0..FF\n let latinExtendedA = []; // Block: 100..17F; Subset: 152..153\n let generalPunctuation = []; // Block: 2000..206F; Subset: 2018..2022\n let currencySymbols = []; // Block: 20A0..20CF; Subset: 20AC..20AC\n let privateUseArea = []; // Block: E000..F8FF; Subset: E700..E70C\n let specials = []; // Block: FFF0..FFFF; Subset: FFFD..FFFD\n for (let k of Object.keys(charMap).sort((a,b) => a-b)) {\n let v = charMap[k];\n if (v.start === null) {\n continue;\n }\n if (0x20 <= k && k <= 0x7E) {\n basicLatin[k-0x20] = v;\n } else if (0xA0 <= k && k <= 0xFF) {\n latin1[k-0xA0] = v;\n } else if (0x152 <= k && k <= 0x153) {\n latinExtendedA[k-0x152] = v;\n } else if (0x2018 <= k && k <= 0x2022) {\n generalPunctuation[k-0x2018] = v;\n } else if (0x20AC <= k && k <= 0x20AC) {\n currencySymbols[k-0x20AC] = v;\n } else if (0xE700 <= k && k <= 0xE70C) {\n privateUseArea[k-0xE700] = v;\n } else if (0xFFFD <= k && k <= 0xFFFD) {\n specials[k-0xFFFD] = v;\n }\n }\n let puaIndexStr = privateUseArea.length<1 ? '' : `\n\n// Index to Unicode Private Use Area block glyph patterns (UI sprites)\nconst PRIVATE_USE_AREA: [u16; ${privateUseArea.length}] = [\n ${privateUseArea.map(v => v.start + \", // \" + v.name).join(\"\\n \")}\n];`;\n let puaMatchStr = privateUseArea.length<1 ? '' : `\n 0xE700..=0xE70C => PRIVATE_USE_AREA[(c as usize) - 0xE700] as usize,`;\n let indexStr = `\n/// Return offset into DATA[] for start of pattern depicting glyph for character c\npub fn get_glyph_pattern_offset(c: char) -> usize {\n match c as u32 {\n 0x20..=0x7E => BASIC_LATIN[(c as usize) - 0x20] as usize,\n 0xA0..=0xFF => LATIN_1[(c as usize) - 0xA0] as usize,\n 0x152..=0x153 => LATIN_EXTENDED_A[(c as usize) - 0x152] as usize,\n 0x2018..=0x2022 => GENERAL_PUNCTUATION[(c as usize) - 0x2018] as usize,\n 0x20AC..=0x20AC => CURRENCY_SYMBOLS[(c as usize) - 0x20AC] as usize,${puaMatchStr}\n _ => SPECIALS[(0xFFFD as usize) - 0xFFFD] as usize,\n }\n}\n\n// Index to Unicode Basic Latin block glyph patterns\nconst BASIC_LATIN: [u16; ${basicLatin.length}] = [\n ${basicLatin.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Latin 1 block glyph patterns\nconst LATIN_1: [u16; ${latin1.length}] = [\n ${latin1.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Latin Extended A block glyph patterns\nconst LATIN_EXTENDED_A: [u16; ${latinExtendedA.length}] = [\n ${latinExtendedA.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to General Punctuation block glyph patterns\nconst GENERAL_PUNCTUATION: [u16; ${generalPunctuation.length}] = [\n ${generalPunctuation.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Currency Symbols block glyph patterns\nconst CURRENCY_SYMBOLS: [u16; ${currencySymbols.length}] = [\n ${currencySymbols.map(v => v.start + \", // '\" + v.chr +\"'\").join(\"\\n \")}\n];${puaIndexStr}\n\n// Index to Unicode Specials block glyph patterns\nconst SPECIALS: [u16; ${specials.length}] = [\n ${specials.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n`;\n return indexStr.trim();\n}", "function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }", "function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}", "function hex2bigIntKey(s){ return bigInt2bigIntKey(hex2bigInt(removeWhiteSpace(s))); }", "static bytes26(v) { return b(v, 26); }", "static bytes6(v) { return b(v, 6); }", "function ak2uy ( akstr )\n{\n var tstr = \"\" ;\n for ( i = 0 ; i < akstr.length ; i++ ) {\n code = akstr.charCodeAt(i) ;\n if ( code < BPAD || code >= BPAD + akmap.length ) {\n tstr = tstr + akstr.charAt(i) ; \n continue ;\n }\n\n code = code - BPAD ; \n\n if ( code < akmap.length && akmap[code] != 0 ) {\n tstr = tstr + String.fromCharCode ( akmap[code] ) ;\n } else {\n tstr = tstr + akstr.charAt(i) ; \n }\n }\n\n return tstr ;\n}", "function prefixToBase(c)\n\t{\n\t\tif (c === CP_b || c === CP_B) {\n\t\t\t/* 0b/0B (binary) */\n\t\t\treturn (2);\n\t\t} else if (c === CP_o || c === CP_O) {\n\t\t\t/* 0o/0O (octal) */\n\t\t\treturn (8);\n\t\t} else if (c === CP_t || c === CP_T) {\n\t\t\t/* 0t/0T (decimal) */\n\t\t\treturn (10);\n\t\t} else if (c === CP_x || c === CP_X) {\n\t\t\t/* 0x/0X (hexadecimal) */\n\t\t\treturn (16);\n\t\t} else {\n\t\t\t/* Not a meaningful character */\n\t\t\treturn (-1);\n\t\t}\n\t}", "static uint72(v) { return n(v, 72); }", "function initCharCodeToOptimizedIndexMap() {\n if ((0, utils_1.isEmpty)(charCodeToOptimizedIdxMap)) {\n charCodeToOptimizedIdxMap = new Array(65536);\n for (var i = 0; i < 65536; i++) {\n /* tslint:disable */\n charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n /* tslint:enable */\n }\n }\n}", "function bigInt2hex(i){ return i.toString(16); }", "function hexAsciiToStr(hexAscii)\n{\n\t// Force conversion of hexAscii to string\n\tvar hex = hexAscii.toString();\n\tvar str = '';\n\tfor (var i = 0; i < hex.length; i=i+2)\n\t\tstr += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n\treturn str;\n}", "function getCodeFromLetter(str){\n return str.charCodeAt(0)-96;\n}", "function getLetterFromCode(num){\n return String.fromCharCode(num+96);\n}", "function IATAConverter(iata) {\n switch (iata) {\n case 'MZG':\n return 'makung';\n case 'KHH':\n return 'kaohsiung';\n case 'TSA':\n return 'taipei-sung-shan';\n case 'RMQ':\n return 'taichung';\n default:\n return 'null';\n break;\n }\n}", "function Hex(n) {\n n=Math.round(n);\n if (n < 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return n.toString(16).toUpperCase();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `TransitionProperty`
function CfnBucket_TransitionPropertyValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); if (typeof properties !== 'object') { errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties))); } errors.collect(cdk.propertyValidator('storageClass', cdk.requiredValidator)(properties.storageClass)); errors.collect(cdk.propertyValidator('storageClass', cdk.validateString)(properties.storageClass)); errors.collect(cdk.propertyValidator('transitionDate', cdk.validateDate)(properties.transitionDate)); errors.collect(cdk.propertyValidator('transitionInDays', cdk.validateNumber)(properties.transitionInDays)); return errors.wrap('supplied properties not correct for "TransitionProperty"'); }
[ "function checkProperty(previous, property) {\n console.log(\"[EVT] Checking if property \" + property.key + \" changed to \" + property.value + \" \" + JSON.stringify(previous));\n\n if (previous[property.key]) {\n console.log(\"[EVT] Property present\");\n if (previous[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n else if ((property.key === 'x') || (property.key === 'y')) {\n console.log(\"[EVT] Checking x, y values from Hue\");\n if (previous.color.cie1931[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n }\n }\n return true;\n}", "function CfnRoute_GrpcRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"GrpcRouteActionProperty\"');\n}", "function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}", "hasUniformTransition() {\n var _this$internalState;\n\n return ((_this$internalState = this.internalState) === null || _this$internalState === void 0 ? void 0 : _this$internalState.uniformTransitions.active) || false;\n }", "function CfnRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}", "function CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}", "function CfnGatewayRoute_HttpGatewayRouteHeaderMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteHeaderMatchProperty\"');\n}", "function CfnBucket_NoncurrentVersionTransitionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('newerNoncurrentVersions', cdk.validateNumber)(properties.newerNoncurrentVersions));\n errors.collect(cdk.propertyValidator('storageClass', cdk.requiredValidator)(properties.storageClass));\n errors.collect(cdk.propertyValidator('storageClass', cdk.validateString)(properties.storageClass));\n errors.collect(cdk.propertyValidator('transitionInDays', cdk.requiredValidator)(properties.transitionInDays));\n errors.collect(cdk.propertyValidator('transitionInDays', cdk.validateNumber)(properties.transitionInDays));\n return errors.wrap('supplied properties not correct for \"NoncurrentVersionTransitionProperty\"');\n}", "function CfnRoute_HttpRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"HttpRouteActionProperty\"');\n}", "function CfnRoute_TcpRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"TcpRouteActionProperty\"');\n}", "function CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rewrite', CfnGatewayRoute_GrpcGatewayRouteRewritePropertyValidator)(properties.rewrite));\n errors.collect(cdk.propertyValidator('target', cdk.requiredValidator)(properties.target));\n errors.collect(cdk.propertyValidator('target', CfnGatewayRoute_GatewayRouteTargetPropertyValidator)(properties.target));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteActionProperty\"');\n}", "function CfnRoute_GrpcRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMatchProperty\"');\n}", "function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}", "function CfnRoute_HttpRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('headers', cdk.listValidator(CfnRoute_HttpRouteHeaderPropertyValidator))(properties.headers));\n errors.collect(cdk.propertyValidator('method', cdk.validateString)(properties.method));\n errors.collect(cdk.propertyValidator('path', CfnRoute_HttpPathMatchPropertyValidator)(properties.path));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('queryParameters', cdk.listValidator(CfnRoute_QueryParameterPropertyValidator))(properties.queryParameters));\n errors.collect(cdk.propertyValidator('scheme', cdk.validateString)(properties.scheme));\n return errors.wrap('supplied properties not correct for \"HttpRouteMatchProperty\"');\n}", "function CfnGatewayRoute_HttpGatewayRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rewrite', CfnGatewayRoute_HttpGatewayRouteRewritePropertyValidator)(properties.rewrite));\n errors.collect(cdk.propertyValidator('target', cdk.requiredValidator)(properties.target));\n errors.collect(cdk.propertyValidator('target', CfnGatewayRoute_GatewayRouteTargetPropertyValidator)(properties.target));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteActionProperty\"');\n}", "function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}", "function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}", "function CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnRoute_MatchRangePropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMetadataMatchMethodProperty\"');\n}", "function hasProperties(json, properties) {\n return properties.every(property => {\n return json.hasOwnProperty(property);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do we need to repeat the image on the Xaxis? Most likely you'll want to set this to false / Helper function which normalizes the coords so that tiles can repeat across the Xaxis (horizontally) like the standard Google map tiles.
function getNormalizedCoord(coord, zoom) { if (!repeatOnXAxis) return coord; var y = coord.y; var x = coord.x; // tile range in one direction range is dependent on zoom level // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc var tileRange = 1 << zoom; // don't repeat across Y-axis (vertically) if (y < 0 || y >= tileRange) { return null; } // repeat across X-axis if (x < 0 || x >= tileRange) { x = (x % tileRange + tileRange) % tileRange; } return { x: x, y: y }; }
[ "rescaleTiles() {}", "wrapx()\n\t{\n\t\t//if the right hand edge of the sprite is less than the left edge of screen\n\t\t//then position its left edge to the right hand side of the screen\n\t\tif (this.right < 0)\n\t\t\tthis.pos.x += this.screensize.width + this.size.width;\n\t\t//if the left hadn edge is off the right hand side of the screen then\n\t\t//position it so its right hand edge is to the left of the screen\n\t\telse if (this.left >= this.screensize.width)\n\t\t\tthis.pos.x -= this.screensize.width + this.size.width;\n\t}", "function duplicateOnMinimap(from,newscale){\n//\tif (globalDeviceType == \"Mobile\"){\n//\t\treturn;\n//\t}\n\twindow['variable' + dynamicMinimap[pageCanvas]].clear().clearCache();\n/*******************************CLONE CANVAS*******************************/\n\tif(from != \"scale\"){\n\t\tvar miniLayerCloned = window['variable' + dynamicLayer[pageCanvas]].clone();\n\t\tvar scle = 0.1*window['globalNavigator'+ pageCanvas]['Scale'];\n\t\tminiLayerCloned.setScale(scle);\n\t}\n/*******************************CREATE RECTANGLE***************************/\n\tvar rectnglLayer = new Kinetic.Layer();\n\tvar rectngl = new Kinetic.Rect({\n\t\twidth: gblCanvasWidth * 0.1,\n\t\theight: gblCanvasHeight * 0.1,\n\t\tfill: 'transparent',\n\t\tstroke: 'black',\n\t\tstrokeWidth: 1,\n\t\tdraggable: true\n\t});\t\n\trectnglLayer.add(rectngl);\n/*******************************DRAG RECTANGLE*****************************/\n\n\trectngl.on('dragend', function() {\n\t\twindow['globalNavigator'+ pageCanvas]['fromNavigator'] = \"rectangle\";\t\t\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['rectX'] = -this.getX();\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['rectY'] = -this.getY();\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['dragX'] = ((window['globalNavigator'+ pageCanvas]['MiniMap']['rectX']) - (-window['globalNavigator'+ pageCanvas]['MiniMap']['srectX'])) *10;\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['dragY'] = ((window['globalNavigator'+ pageCanvas]['MiniMap']['rectY']) - (-window['globalNavigator'+ pageCanvas]['MiniMap']['srectY'])) *10;\n\t\twindow['variable' + dynamicLayer[pageCanvas]].setAttrs({x: window['globalNavigator'+ pageCanvas]['Stage']['dragX'], y:window['globalNavigator'+ pageCanvas]['Stage']['dragY']});\n\t\tdrawImage(\"true\");\n\t\twindow['variable' + dynamicLayer[pageCanvas]].draw();\n\n\t});\n/***************************SET INITIAL POSITION*******************************/\n\tif(from != \"scale\" && window['globalNavigator'+ pageCanvas]['fromNavigator'] == \"\"){\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(rectnglLayer).setPosition(window['globalNavigator'+ pageCanvas]['MiniMap']['rectX'],window['globalNavigator'+ pageCanvas]['MiniMap']['rectY']);\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(miniLayerCloned);\n\t}\n/**************************ON DRAG SET NEW POSITION***************************/\n\tif(from == \"true\"){\n\t\trectngl.setPosition(-(window['globalNavigator'+ pageCanvas]['MiniMap']['rectX']), -(window['globalNavigator'+ pageCanvas]['MiniMap']['rectY']));\n\t\trectnglLayer.clear().add(rectngl);\n\t\tminiLayerCloned.setAttrs({x:0,y:0});\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(rectnglLayer);\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(miniLayerCloned);\n\t\twindow['globalNavigator'+ pageCanvas]['fromNavigator'] = \"rectangle\";\t\t\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['pdragX'] = window['globalNavigator'+ pageCanvas]['Stage']['dragX'];\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['pdragY'] = window['globalNavigator'+ pageCanvas]['Stage']['dragY'];\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['prectX'] = window['globalNavigator'+ pageCanvas]['MiniMap']['rectX'];\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['prectY'] = window['globalNavigator'+ pageCanvas]['MiniMap']['rectY'];\n\t\treturn;\n\t}\n/*************************ON ZOOM SET POSITION*******************************/\n\tif(from == \"scale\"){\n\t\tpdragX = window['globalNavigator'+ pageCanvas]['Stage']['pdragX'];\n\t\tpdragY = window['globalNavigator'+ pageCanvas]['Stage']['pdragY'];\n\t\tdragX = window['globalNavigator'+ pageCanvas]['Stage']['dragX'];\n\t\tdragY = window['globalNavigator'+ pageCanvas]['Stage']['dragY'];\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['rectX'] = ((dragX - pdragX) * .1);\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['rectY'] = ((dragY - pdragY) * .1);\n\t\twindow['globalNavigator'+ pageCanvas]['Scale'] = newscale;\n\t\tvar miniLayerCloned = window['variable' + dynamicLayer[pageCanvas]].clone();\n\t\tscl = 0.1*window['globalNavigator'+ pageCanvas]['Scale'];\n\t\tminiLayerCloned.setScale(scl);\n\t\trectngl.setPosition(-(window['globalNavigator'+ pageCanvas]['MiniMap']['rectX']),-(window['globalNavigator'+ pageCanvas]['MiniMap']['rectY']));\n\t\trectnglLayer.clear().add(rectngl);\n\t\tminiLayerCloned.setAttrs({x:0, y:0});\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(rectnglLayer);\n\t\twindow['variable' + dynamicMinimap[pageCanvas]].add(miniLayerCloned);\n\t\twindow['globalNavigator'+ pageCanvas]['fromNavigator'] = \"zoom\";\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['pdragX'] = window['globalNavigator'+ pageCanvas]['Stage']['dragX'];\n\t\twindow['globalNavigator'+ pageCanvas]['Stage']['pdragY'] = window['globalNavigator'+ pageCanvas]['Stage']['dragY'];\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['prectX'] = window['globalNavigator'+ pageCanvas]['MiniMap']['rectX'];\n\t\twindow['globalNavigator'+ pageCanvas]['MiniMap']['prectY'] = window['globalNavigator'+ pageCanvas]['MiniMap']['rectY'];\n\t\treturn;\n\t}\n\n}", "setStartPosition() {\n this.position = [Math.floor(pixelAmount / 2), Math.floor(pixelAmount / 2)];\n }", "localClipped (x, y) {\n if (x !== null && (x < 0 || x >= this.Config.size.width)) return true;\n if (y !== null && (y < 0 || y >= this.Config.size.height)) return true;\n return false;\n }", "function validTile(x, y) {\n if (x > (xmax - 1) || (x < 0)) {\n return false;\n }\n\n if (y > (ymax - 1) || (y < 0)) {\n return false;\n }\n return true;\n}", "resetPosition() {\n if (this.hasGoneOffScreen()) {\n this.x = this.canvas.width;\n }\n }", "function renderContinuous() {\n\n mctx.clearRect(0, 0, mcanvas.width, mcanvas.height );\n\n for (var el in map) {\n mctx.drawImage( map[el].buffer, \n map[el].ref.x - map[el].ref.width/2, \n map[el].ref.y - map[el].ref.height/2 );\n };\n }", "function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}", "longitudeToPixelX(longitude, zoom) {\n return (longitude + 180) / 360 * (this.TileSize << zoom);\n }", "pixelXToTileX(pixelX, zoom) {\n return Math.min(Math.max(pixelX / this.TileSize, 0), Math.pow(2, zoom) - 1);\n }", "function generateCoordinates () {\n direction = Math.floor(Math.random() * 10) % 2 === 1 ? 'vertical' : 'horizontal'\n locationX = Math.floor(Math.random() * (sizeX - 1))\n locationY = Math.floor(Math.random() * (sizeY - 1))\n if (direction === 'horizontal') {\n if ((locationX + shipSize) >= sizeX) {\n generateCoordinates()\n }\n } else {\n if ((locationY + shipSize) >= sizeY) {\n generateCoordinates()\n }\n }\n }", "function populateGrid(coords) {\n let patternedGrid = makeGrid(width, height);\n coords.forEach((coord) => {\n let [x, y] = coord;\n patternedGrid[x][y] = true;\n });\n\n setGrid(patternedGrid);\n }", "function resetTiles() {\n\t\tvar positions = createPositionArray(xCount, yCount, diameter);\n\t\t\n\t\tfor(var i = 0; i < tiles.length; i++){\n\t\t\ttiles[i].setPosition(positions.pop());\n\t\t}\n\t\trotateTiles();\n\t\tgroupTiles();\n\t}", "CoordinateTransform(FakePosition) {\n const { x, y } = FakePosition;\n return { x: x * this.GridSize.x, y: y * this.GridSize.y };\n }", "function reset() {\n var browserWidth = $(window).width();\n if(browserWidth <= 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(11);\n } else if(browserWidth > 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(12);\n }\n }", "addMinimapCutout(posX, posY, minimapWidth, minimapHeight) {\n let cutout = new Phaser.GameObjects.Graphics(this);\n cutout.fillRect(posX, posY, minimapWidth, minimapHeight);\n // let mask = new Phaser.Display.Masks.GeometryMask(this, cutout);\n let mask = new Phaser.Display.Masks.BitmapMask(this, cutout);\n // mask.invertAlpha = true;\n // lowerPanel.mask = mask;\n this.lowerPanelBackground.setMask(mask);\n this.lowerPanelBackground.mask.invertAlpha = true;\n }", "tileXToPixelX(tileX) {\n return tileX * this.TileSize;\n }", "positionElementsOnResize() {\n this.spritePlane.position.x = this.width / 2;\n this.spritePlane.position.y = this.height / 2;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function handles the error of the call that informs installation has been selected for the installable product
handleUpdateInstallationError(error) { this.$refs.spinner.hideSpinner(); this.$emit('add-installation-error'); }
[ "function onSetupError () {\n\n popup\n .showConfirm('Something went wrong while loading the video, try again?')\n .then(function (result) {\n if (true === result) {\n $state.reload();\n }\n });\n\n vm.loading = false;\n $timeout.cancel(loadingTimeout);\n }", "function LookupOASCapableFailed(result, context) {\n var action='', msf='', oldZipcode='', question='';\n if (context!=null && context!='') {\n\t var qs = context.split('|')\n oldZipcode = qs[2];\n }\n document.getElementById('zip_code').value = oldZipcode;\n\n alert('LookupOASCapable Failed: ' + result.status + ' ' + result.statusText);\n //there needs to be more than an alert\n}", "function LookupOASCapableOnHomePageFailed(result, context) {\n var oldZipcode='', question='', controlName='';\n if (context!=null && context!='') {\n\t var qs = context.split('|')\n oldZipcode = qs[0];\n controlName = qs[2];\n }\n document.getElementById(controlName).value = oldZipcode;\n\n alert('LookupOASCapableOnHomePage Failed: ' + result.status + ' ' + result.statusText);\n //there needs to be more than an alert\n return false;\n}", "function OnFailure(sender, args) {\n alert(\"Error occurred at UpdateListItem. See console for details.\");\n console.log('Request failed at UpdateListItem :' + args.get_message() + '\\n' + args.get_stackTrace());\n }", "function errorConfirm() {\n vm.onErrorConfirm();\n }", "setTermsOfServiceLoadError() {\n // Disable the accept button, hide the iframe, show warning icon.\n this.uiState = TermsOfServiceScreenState.ERROR;\n\n this.acceptButtonDisabled_ = true;\n this.backButtonDisabled_ = false;\n }", "errorHandler(err, invokeErr) {\n const message = err.message && err.message.toLowerCase() || '';\n if (message.includes('organization slug is required') || message.includes('project slug is required')) {\n // eslint-disable-next-line no-console\n console.log('Sentry [Info]: Not uploading source maps due to missing SENTRY_ORG and SENTRY_PROJECT env variables.')\n return;\n }\n if (message.includes('authentication credentials were not provided')) {\n // eslint-disable-next-line no-console\n console.warn('Sentry [Warn]: Cannot upload source maps due to missing SENTRY_AUTH_TOKEN env variable.')\n return;\n }\n invokeErr(err);\n }", "static handleSetSelectedAddressResponseFailure(response, contextIdentifier){\n ContextualErrorActions.receiveErrors(contextIdentifier, response.errors);\n }", "function editError(){\n\tdisplayMessage(\"There has been an error submitting your art.\\nSave your work locally and try again later.\",\n\t\t removePrompt(),removePrompt(),false,false);\n}", "function showExpenditurePeriodicityErrorIfPresent(error) {\n\tif (!isEmpty(error)) {\n\t\t$(\"#expenditurePeriodicityError\").text(error);\n\t}\n}", "function appxEncodingError(encoding) {\r\n var message = appx_session.language.alerts.encodingFrontError + encoding + appx_session.language.alerts.encodingBackError;\r\n //alert(message);\r\n appxSetStatusText(message, 2);\r\n}", "function reviewUpdateError (data, status, headers, config) {\n alert(data.message);\n }", "function defaultDataError(error) {\n// console.log(error+\" error \"+JSON.stringify(error))\n var errorNumber = parseFloat(error.error_code);\n if (schneider.util.inArray(errorNumber, [21327, 21334, 21335, 21336])) {\n self._deferFailedRequests(obj);\n } else if (schneider.util.inArray(errorNumber, [21305, 21332, 21333])) {\n self.logout();\n } else if (errorNumber == 20006 && error.error.indexOf(\"@\") == -1) {\n self.logout();\n }\n schneider.util.unmask();\n }", "function pwUpdateError(){\n\tdisplayMessage(\"There was an error updating the password. The previous\\npassword will still be used to access the tile edit feature\\nand any edits you have made have been saved. Try to reset\\nthe password for this tile again later\", removePrompt(),\n\t\t\t\t\tremovePrompt(),false,false);\n}", "function incrementoError()\n\t{\n\t\tif(presente === false)\n\t\t{\n\t\t\tmasUnError();//Instanciar la función que aumenta los fallos acumulados.\n\t\t}\n\t}", "function error(msg,header,execFunc) {\n\t$(\".ui-popup\").popup(\"close\");\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$('#errorPromptHeader').empty().append(header);\n\t\t$('#errorPromptBody').empty().append(msg);\n\t}else{\n\t\t$('#errordialogheader').empty().append(header);\n\t\t$('#errordialogbody').empty().append(msg);\n\t}\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$('#errorPrompt').popup( {create: function(){}});\n\t\tsetTimeout(function(){\n\t \t\t$('#errorPrompt').show().popup(\"open\");\n\t\t\t$(document).on('click','#errorPromptOk', function(){\n\t\t\t\tif(execFunc!=undefined){\n \t\t\t\teval(execFunc);\n\t\t\t\t\texecFunc = \"\";\n \t\t\t}\n\t\t\t\t$('#errorPrompt').popup(\"close\").hide();\n\t\t\t});\n\t\t},200);\n\t}else{\n\t\t$( \"#errordialog\" ).dialog({\n\t\t\tmodal: true,\n\t\t\tautoResize:true,\n\t\t\twidth: 400,\n\t\t\theight: 200,\n\t\t});\t\t\n\t\t$('#errordialog').dialog(\"open\");\n\t}\n\tif(globalDeviceType != \"Mobile\"){\n\t\t$(document).on('click','#errordialogtOk', function(){\n\t\t\t$('#errordialog').dialog('destroy');\n\t\t});\n\t}\n}", "function handleCommandProcessingError(error, command, socket) {\n LOGGER.warn(\n `CMDPROCERR user=${command.userId ? command.userId : 'n/a'} room=${\n command.roomId ? command.roomId : 'n/a'\n } commandName=${command.name ? command.name : 'n/a'} ${error.message}`\n );\n\n sendEvents(\n [\n {\n restricted: true, // command rejected event is only sent to the one socket that sent the command\n name: 'commandRejected',\n id: uuid(),\n correlationId: command.id,\n roomId: command.roomId,\n payload: {\n command: command,\n reason: error.message\n }\n }\n ],\n command.roomId,\n socket\n );\n }", "function showProjectLoadTypeFailDialogue() {\n showDialog({\n title: 'WARNING: Incorrect project type',\n text: 'Reselect a <b>DSS-Risk-Analysis-</b>&lt;ProjectTitle&gt;.json file:\\nCurrent project unchanged'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "function getProductFailed(error) {\n $log.error('Request failed for getProduct.\\n' + angular.toJson(error.data, true));\n return $q.reject(error);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders a detailed view of a specific dog walking client's info
function renderDogOwnerDetails(dogOwner) { $('main').html(` <div id="dogOwner-details" dogOwner-id-data="${dogOwner.id}"> <ul class="client-details"> <li class="dogOwner-card-header"><h3>${dogOwner.firstName} ${dogOwner.lastName}</h3></li> <li class="dogOwner-card-dogName">Dog(s): ${dogOwner.dogNames}</li> <li>Address: ${dogOwner.address}</li> <li>Days Walk Needed: ${checkforEmptyValues(dogOwner.walkDays)}</li> <li>Walk Time Window: ${checkforEmptyValues(dogOwner.walkTimeRange)}</li> <li>Phone Number: ${checkforEmptyValues(dogOwner.phoneNumber)}</li> <li>Email: ${checkforEmptyValues(dogOwner.email)}</li> <li>Notes: ${dogOwner.notes}</li> </ul> </div> `); }
[ "function renderDogOwnersList(dogOwners) {\n $('#client-info-list').html(dogOwners.map(dogOwnerToHtml));\n\n // Takes each individual dog owner and displays the requested info\n function dogOwnerToHtml(dogOwner) {\n let notesShorten = dogOwner.notes;\n if (notesShorten.length > 120) {\n notesShorten = `${dogOwner.notes.substring(0, 120)}...`;\n }\n return `\n <div id=\"dogOwner-card\" class=\"dogOwner-card\" dogOwner-id-data=\"${dogOwner.id}\">\n <ul class=\"client-info\">\n <div class=\"row client-header\">\n <div class=\"col-3\">\n <li class=\"dogOwner-card-header dogOwner-name\">${dogOwner.firstName} ${dogOwner.lastName}</li>\n </div>\n <div class=\"col-3\"\n <li><button id=\"delete-dogOwner-btn\" class=\"delete-btn\">Delete</button></li>\n </div>\n </div>\n <li class=\"dogOwner-card-dogName\">Dog(s): ${dogOwner.dogNames}</li>\n <li class=\"dogOwner-card-address\">Address: ${dogOwner.address}</li>\n <li class=\"dogOwner-card-notes\">Notes: ${notesShorten}</li>\n </ul>\n </div>\n `;\n }\n}", "function DogDetails({ dogs }) {\n const { name } = useParams();\n const dog = dogs.find(d => d.name.toLowerCase() === name.toLowerCase())\n\n if (!dog) return <Redirect to=\"/dogs\" />\n\n return (\n <div>\n <h2>{`${dog.name}`}\n <small>\n {` - age: ${dog.age}`}\n </small>\n </h2>\n <img src={dog.src} alt={dog.name} />\n <ul> Facts:\n {dog.facts.map((f) => (\n <li>{f}</li>\n ))}\n </ul>\n </div>\n );\n}", "function showHotelDetails(view, hotelView) {\n\t// render the hotel details view, passing in the hotel view so details view knows where to display from and which hotel to show\n\tview.views['hotel-details'].render(hotelView);\n}", "function renderDietInfo(diet) {\n var template = $('#dietInfoTemplate').html();\n var rendered = Mustache.render(template,\n diet\n );\n $('#dietInfo').html(rendered);\n $('#exercisesInfo').html(diet.exercises);\n}", "function displayTruckInfo(truckId){\n let foundTruck = trucks.find(truck => truck.objectid === truckId)\n let foundMarker = markers.find(marker => marker.id === truckId)\n \n clickMarker(foundMarker)\n\n truckInfo.innerHTML = `<div id=\"more-info\">\n <h3>${foundTruck.applicant}</h3>\n <p>${foundTruck.address}</p>\n <a href=\"https://www.google.com/maps/search/?api=1&query=${foundTruck.location.coordinates[1]},${foundTruck.location.coordinates[0]}\">Get Directions</a>\n <p>${foundTruck.fooditems}</p>\n </div>\n `\n\n window.scrollTo(0, document.body.scrollHeight)\n}", "function getDogs() {\n fetch(dogsURL)\n .then(resp => resp.json())\n .then(renderDogs)\n}", "showInfo() {\n let sp = 25; // Spacing\n push();\n // Vertical offset to center text with the image\n translate(this.x * 2, this.y - 50);\n textAlign(LEFT);\n textSize(20);\n textStyle(BOLD);\n text(movies[this.id].title, 0, 0);\n textStyle(NORMAL);\n text(\"Directed by \" + movies[this.id].director, 0, 0 + sp);\n text(\"Written by \" + movies[this.id].writer, 0, 0 + sp * 2);\n text(\"Year: \" + movies[this.id].year, 0, 0 + sp * 3);\n text(\"Running time: \" + movies[this.id].time + \" min\", 0, 0 + sp * 4);\n // Index of the movie / total movies in the dataset\n text(\"(\" + (this.id + 1) + \"/\" + nMovies + \")\", 0, 0 + sp * 5);\n pop();\n }", "async renderCarView(req, res) {\n const carData = await HmkitServices.getData(req.session);\n const [diagnosticsResponse, doorsResponse] = carData.multiStates;\n const diagnostics = diagnosticsResponse.data.diagnostics;\n const doorsData = doorsResponse.data.doors;\n\n const tires = diagnostics.tirePressures ? diagnostics.tirePressures.map(tirePressure => {\n const location = tirePressure.data.location;\n const pressure = tirePressure.data.pressure;\n\n const tireTemperatureResponse = diagnostics.tireTemperatures && diagnostics.tireTemperatures.find(\n tempData => tempData.data.location.value === location.value\n );\n const wheelRpmResponse = diagnostics.wheelRPMs && diagnostics.wheelRPMs.find(\n rpmData => rpmData.data.location.value === location.value\n );\n\n const temperature = tireTemperatureResponse ? tireTemperatureResponse.data.temperature : {};\n const RPM = wheelRpmResponse ? wheelRpmResponse.data.RPM : {};\n\n return {\n location,\n pressure,\n temperature,\n RPM\n };\n }) : [];\n \n const doors = doorsData.positions ? doorsData.positions.filter(pos => {\n return !(pos && pos.data.location.value === 'all')\n }).map(doorData => {\n const location = doorData.data.location;\n const position = doorData.data.position;\n const currentLock = doorsData.locks.find(lock => lock.data.location.value === location.value);\n\n return {\n location,\n position,\n lock: currentLock ? currentLock.data.lockState : null\n };\n }) : [];\n\n res.render('pages/car.ejs', { diagnostics, doors, tires });\n }", "function apiShow(req, res) {\n //console.log('GET /api/breed/:name');\n // return JSON object of specified breed\n db.Breed.find({name: req.params.name}, function(err, oneBreed) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: oneBreed});\n }\n });\n}", "function showOne(req, res) {\n var walkId = req.params.walkId;\n db.Walks.findById(walkId, function(err, foundWalk) {\n res.json(foundWalk);\n });\n}", "function renderDogs() {\n fetchDogs()\n .then((dogs) => dogs.forEach(dog => {\n renderDog(dog);\n }));\n}", "function viewDetail(id) {\n container.style.visibility = \"visible\";\n wrapper.style.visibility = \"visible\";\n\n // room detail\n fetch(apiRoom)\n .then((response) => response.json())\n .then(function (rooms) {\n\t let roomData = rooms.filter((allRooms) => {\n\t\treturn (allRooms.id == id);\n\t }).map((data) => {\n\t\treturn `<div class=\"info-header\">\n\t <h1>${data.name}<button class=\"close-btn\" onclick=\"hideDetail()\">&times;</button></h1>\n\t <div class=\"main-info\">\n\t <div class=\"name\">\n\t <i class=\"name-icon\"></i>\n\t <div class=\"name-text\">${data.houseOwner}</div>\n\t </div>\n\t <div class=\"phone\">\n\t <i class=\"phone-icon\"></i>\n\t <div class=\"phone-text\">${data.ownerPhone}</div>\n\t </div>\n\t <div class=\"address\">\n\t <i class=\"address-icon\"></i>\n\t <div class=\"address-text\">${data.address}</div>\n\t </div>\n\t </div>\n\t <h2>${data.price}</h2>\n\t </div>\n\t <div class=\"info\">\n\t <div class=\"info-type\">\n\t <h3>Loại phòng</h3>\n\t <p>${data.category}</p>\n\t </div>\n\t <div class=\"info-area\">\n\t <h3>Diện tích</h3>\n\t <p>${data.area}</p>\n\t </div>\n\t <div class=\"info-deposit\">\n\t <h3>Đặt cọc</h3>\n\t <p>${data.deposit}</p>\n\t </div>\n\t <div class=\"info-capacity\">\n\t <h3>Sức chứa</h3>\n\t <p>${data.capacity}</p>\n\t </div>\n\t <div class=\"info-electric\">\n\t <h3>Tiền điện</h3>\n\t <p>${data.electricPrice}</p>\n\t </div>\n\t <div class=\"info-water\">\n\t <h3>Tiền nước</h3>\n\t <p>${data.waterPrice}</p>\n\t </div>\n\t <div class=\"info-fee\">\n\t <h3>Chi phí khác</h3>\n\t <p>${data.otherPrice}</p>\n\t </div>\n\t <div class=\"info-status\">\n\t <h3>Tình trạng</h3>\n\t <p>${data.status}</p>\n\t </div>\n\t <div class=\"info-description\">\n\t <h3>Mô tả chi tiết</h3>\n\t <p>${data.description}</p>\n\t </div>\n\t </div>`;\n \t });\n\t container.innerHTML = \"\";\n\t container.innerHTML = roomData; \n\t});\n}", "function renderMain(response) {\n\tBurger.getAllBurgers()\n\t\t.then((burgers) => {\n\t\t\tburgers = burgers.map( el => {\n\t\t\t\treturn {\n\t\t\t\t\tid: el.id,\n\t\t\t\t\tburger_name: el.name,\n\t\t\t\t\tdevoured: el.devoured\n\t\t\t\t};\n\t\t\t} )\n\t\t\t// render the page\n\t\t\tresponse.render(\"index\", { burgers: burgers });\n\t\t});\n}", "function showStrategyPage() {\n\n\t// Apply strategy styles\n\t$(\"body, header, .door\").addClass(\"strategy\");\n\n\t$(\".door span\").empty().append(\"1/3\");\n\t$(\"header h1\").append(\"<em> Strategy</em>\");\n\n\t$(\"div.strategy\").removeClass(\"hidden\");\n\t$text.fadeIn();\n\t$doorContainer.fadeIn();\n}", "async show(req, res) {\n // Get all oportunities\n const { data } = await pipedrive_api.get();\n // Array to filter which data receive\n const oportunities = [];\n\n if (data.data) {\n data.data.forEach(client => {\n let {\n title,\n value,\n status,\n won_time,\n person_id: { name },\n } = client;\n oportunities.push({ title, value, status, won_time, name });\n });\n }\n return res.json(oportunities);\n }", "function userView(targetid, user){\n apply_template(targetid, \"user-detail-template\", user);\n}", "function catsOrDogs() {\n let sec = jsgui.section();\n\n let catPic = jsgui.img(\"cat.jpg\", \"a black cat\");\n let dogPic = jsgui.img(\"dog.jpg\", \"a shaggy Newfoundland dog\");\n\n let catPeople = animalDetail(\"Cat people\", catPic,\n \"Some people like cats. Cats are quiet, playful, soft, and sweet.\");\n\n let dogPeople = animalDetail(\"Dog people\", dogPic,\n \"Some people like dogs: loyal friends and quick with a trick.\");\n\n let grid = jsgui.grid(2);\n jsgui.addToGrid(grid, 1, catPeople);\n jsgui.addToGrid(grid, 2, dogPeople);\n jsgui.append(sec,\n jsgui.h2(\"Cats and Dogs\"),\n jsgui.p(\"Do you prefer cats or dogs?\"),\n grid,\n jsgui.hr());\n\n return sec;\n\n}", "function drawCivInfo(ctx, civs) {\r\n ctx.font = me.style.fontSize.civ + ' ' + me.style.font;\r\n for (var i = 0, len = civs.length; i < len; i++) {\r\n var civ = civs[i];\r\n var msg = '(' + civ.owners.map(function(x) { return x.name; }).join(', ') + ')';\r\n ctx.fillText(msg, civ.x, civ.y + halfCellH + 27);\r\n }\r\n }", "function moviedescription(data, idNumber) {\n document.getElementById(\"moviedescription\").innerHTML =\n data[idNumber].fields.opening_crawl;\n document.getElementById(\"moviedirector\").innerHTML = \"Directed by: \" + data[idNumber].fields.director + \".\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Next we define the setState function where we will set the value to something different and force rerendering of our component in our reimplementation of the useState Hook. For actual Hooks this would have been dealt with internally
function setState(nextValue) { values[hookIndex] = nextValue; // value = nextValue; ReactDOM.render(<App />, document.getElementById('root')) }
[ "safeSetState(newState) {\n if (this.mounted) {\n this.setState(newState);\n } else {\n Object.assign(this.state, newState);\n }\n }", "handleSetStatesToDefault() {\n this.setState({\n gridData: {},\n gridLoadToggle: false,\n noError: true,\n currentStudent: {},\n currentProject: {},\n errorMessage: \"\",\n showStudent: false,\n showProject: false,\n studentPriorityValue: 20,\n helpToggle: false,\n legendToggle: false\n });\n }", "_onChange ( value ) {\n this.setState({ value });\n\n this._endTimeout();\n this._startTimeout( value );\n }", "function setState(param,cb) {\n if(_.isFunction(param)) {\n this.state = param(this.state,this.props);\n } else {\n this.state = Object.assign({},this.state,param)\n if(!_.isNil(cb)) {\n cb(this.state)\n }\n }\n \n if(this.state.mouseOver && this.state.mouseClicked) {\n this.props.onClickHandler(this.props._id, this.state.mouseBtn) \n }\n \n \n \n if(shouldUpdate) {\n this.render()\n }\n \n \n return this.state\n }", "updateBlue(event) {\n\n this.setState({\n blue: event.target.value\n });\n \n return true;\n }", "if (nextProps.appFocusedCount !== this.state.appFocusedCount) {\n this.setState({\n appFocusedCount: nextProps.appFocusedCount,\n })\n this.props.getFuseStatus()\n }", "_handleRChange(e) {\n e.persist();\n let newRed = e.target.value;\n this.setState({r: newRed});\n this.updateRed();\n }", "setStudentPriority(value) {\n this.setState({studentPriorityValue: value});\n }", "doOnChange() {\n const { onChange } = this.props;\n const { value } = this.state;\n if (onChange && typeof onChange === 'function') {\n onChange(value);\n }\n\n this.updateSuggestions();\n }", "componentDidUpdate(prevProps, prevState) {\n if (prevState.current !== this.state.current) {\n this.slider.set(this.state.current);\n this.updateHandleVisibility();\n }\n\n // Pass range changes off to noUiSlider\n if (prevState.start !== this.state.start || prevState.end !== this.state.end) {\n this.slider.updateOptions({\n range: {\n min: this.state.start,\n max: this.state.end\n }\n });\n\n // Update pip scaling\n // Not supported via updateOptions.\n // See https://github.com/leongersen/noUiSlider/issues/594\n this.slider.pips(this.getPips(this.state.start, this.state.end));\n\n // Make sure the handle is (in)visible based on whether\n // or not it's in the updated range, and that it fits frame sizes\n this.updateHandleVisibility();\n this.updateHandleWidth();\n }\n }", "function updateValue(value) {\n try {\n // allow functional updates, similar to useState\n const newValue = value instanceof Function ? value(privateValue) : value;\n\n window.localStorage.setItem(key, newValue);\n setPrivateValue(newValue);\n } catch (error) {\n console.error('localStorage error:', error);\n }\n }", "_placeChange() {\n if (DEBUG) {\n console.log('[*] ' + _name + ':_placeChange ---');\n }\n\n // Store place in LocalStoreApi\n LocalStoreApi.setItem('place', getPlaceState());\n\n this.setState({\n place: getPlaceState()\n });\n }", "updateCheck() {\r\n this.setState((oldState) => {\r\n return {\r\n checked: !oldState.checked,\r\n };\r\n });\r\n this.updateChart(this.state.checked)\r\n }", "updateValue() {\n [...this.template.querySelectorAll('lightning-input')].forEach(\n (element) => {\n element.value = this._value;\n }\n );\n\n this._updateProxyInputAttributes('value');\n\n /**\n * @event\n * @name change\n * @description The event fired when the value changes.\n * @param {number} value\n */\n this.dispatchEvent(\n new CustomEvent('change', {\n detail: {\n value: this._value\n }\n })\n );\n this.showHelpMessageIfInvalid();\n }", "componentWillReceiveProps ( props ) {\n this.setState({ value: props.value });\n }", "updateClicked(classID, value) {\n this.setState(prevState => {\n let clicked = prevState.clicked;\n clicked[classID] = value;\n return clicked;\n });\n }", "handleIssueType(value) {\n this.setState({issueType: value});\n }", "handleOutageType(value) {\n this.setState({outageType: value});\n }", "handleUIStateChange(key, value){\n\t this.props.setPGTtabUIState({\n\t\t[key]: {$set: value}\n\t });\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize the video embed.
resizeEmbed() { Object.keys(this.videoEmbeds).forEach((key) => { const embed = this.videoEmbeds[key]; fastdom.measure(() => { const newWidth = embed.floated ? embed.parent.offsetWidth : this.element.offsetWidth; fastdom.mutate(() => { embed.iframe.setAttribute( 'height', newWidth * embed.iframe.dataset.aspectRatio ); embed.iframe.setAttribute('width', newWidth); }); }); }); }
[ "setupEmbed() {\n Object.keys(this.videoEmbeds).forEach((key) => {\n const embed = this.videoEmbeds[key];\n\n embed.iframe.setAttribute(\n 'data-aspect-ratio',\n `${embed.iframe.height / embed.iframe.width}`\n );\n embed.iframe.removeAttribute('height');\n embed.iframe.removeAttribute('width');\n });\n\n this.resizeEmbed();\n window.addEventListener('resize', this.resizeEmbed);\n }", "function videoResize() {\n if (window.innerWidth <= 600) {\n video.width = 320;\n video.height = 240;\n wallpaper.src=\"Images/whitney-houston-vertical-image.jpg\";\n } else {\n video.width = 640;\n video.height = 480;\n wallpaper.src=\"Images/whitney-houston-horizontal-image.jpg\"\n }\n}", "function onVideoResized(vs, isPreview, size) {\n // notify the AVComponent that the video window size has changed\n pcAV.invoke('SetVideoWindowSize', vs._id(), vs.source.sink._videoWindow(), isPreview, size.width, size.height);\n }", "function aspectScale() {\n $(\".media-container\").each(function () {\n var container = $(this);\n container.find(\"img, video\").each(function () {\n var dims = {\n w: this.naturalWidth || this.videoWidth || this.clientWidth,\n h: this.naturalHeight || this.videoHeight || this.clientHeight\n },\n space = {\n w: container.width(),\n h: container.height()\n };\n if (dims.w > space.w || dims.h > space.h) {\n $(this).css({width: \"\", height: \"\"}); // Let CSS handle the downscale\n } else {\n if (dims.w / dims.h > space.w / space.h) {\n $(this).css({width: \"100%\", height: \"auto\"});\n } else {\n $(this).css({width: \"auto\", height: \"100%\"});\n }\n }\n });\n });\n }", "async resize (width, height) {\n this.page.set('viewportSize', {width, height})\n }", "function unzoom(video, cw, ch) {\n // It would be better to somehow trigger YouTube's standard video sizing, but\n // in the absence of a way to trigger that, we'll just do this.\n \n var vs = video.style\n var video_aspect = video.videoWidth/video.videoHeight\n var containing_aspect = cw/ch\n \n // Don't unzoom if the endscreen is showing\n if(!video.ended) {\n debug_log(\"Unzooming video.\")\n \n // Usually the player is sized to fit the video exactly in default view,\n // but not for narrow videos, which are pillarboxed with white bars. Rarely,\n // the player defaults to 16:9 for all videos, so that wide videos are\n // letterboxed with white bars.\n // \n // In theater mode and full-screen mode, the player has a fixed aspect and\n // the video is letter- or pillarboxed with black bars if it doesn't fit\n // exactly.\n // \n // To avoid black bars in default view, we must size the video to fill the\n // container in the video's longest dimension only. (Otherwise we could\n // just size it to fill the container in both dimensions.)\n var w, h, t, l\n if(video_aspect == containing_aspect) {\n // video that fits the container exactly\n w = cw; h = ch; t = 0; l = 0\n } else if(video_aspect > containing_aspect) {\n // letterboxed video\n w = cw; l = 0\n h = cw / video_aspect\n t = (ch - h) / 2\n } else {\n // pillarboxed video\n h = ch; t = 0\n w = ch * video_aspect\n l = (cw - w) / 2\n }\n \n vs.width = w + \"px\"\n vs.height = h + \"px\"\n vs.top = t + \"px\"\n vs.left = l + \"px\"\n } else {\n debug_log(\"Video has ended. Not unzooming. (Otherwise we mess with the endscreen.)\")\n }\n}", "function resizeAndPositionPlayer() {\n $player = element.children().eq(0);\n\n element.css({\n width: parentDimensions.width + 'px',\n height: parentDimensions.height + 'px'\n });\n\n var options = {\n zIndex: 1,\n position: 'absolute',\n width: playerDimensions.width + 'px',\n height: playerDimensions.height + 'px',\n left: parseInt((parentDimensions.width - playerDimensions.width)/2, 10) + 'px',\n top: parseInt((parentDimensions.height - playerDimensions.height)/2, 10) + 'px'\n };\n if (!scope.allowClickEvents) {\n options.pointerEvents = 'none';\n }\n $player.css(options);\n }", "function maxStageSize() {\n scene.setAttr('scaleX', 1);\n scene.setAttr('scaleY', 1);\n scene.setAttr('width', maxStageWidth);\n scene.setAttr('height', maxStageHeight);\n // document.getElementById(\"iframe\").style.transform = 1;\n // document.getElementById(\"iframe\").style.width = maxStageWidth;\n scene.draw();\n}", "function resizedw(){\n loadSlider(slider);\n }", "function _applyWidth(width) {\n if(self._applying_dimensions) return;\n\n if(self.layout() == \"video\") {\n // for video, a given width implies a specific height, so just set it and done\n if(width < VIDEO_MIN_WIDTH || width > VIDEO_MAX_WIDTH) {\n // width invalid, don't apply it\n return;\n }\n var height = _videoHeight(width);\n self.height(height);\n self.width(width);\n self._applying_dimensions = true;\n self.input_height(height);\n self._applying_dimensions = false;\n return;\n }\n\n var sizekey = self.sizekey();\n var defaults = DEFAULT_SIZES[sizekey];\n \n if(width < defaults.min_width || width > defaults.max_width) {\n return;\n }\n // extra special min width for smallart players\n if(self.size() == \"large\" && self.artwork_option() != \"large\" && width < STANDARD_SMALLART_WIDTH_MIN) {\n return;\n }\n\n // passed the check, so use this width in the embed\n self.width(width);\n\n if ( width == \"100%\" ) {\n // if the width is set to \"100%\", continue as if the width\n // was set to defaults.min_width, since you can't do a height\n // calculation with the string \"100%\"\n width = defaults.min_width;\n }\n\n // calculate range of allowable heights\n var range = self.heightRange(width);\n var inp_height = self.input_height();\n\n // by default, update input_height to the closest value in its allowed range\n var new_height = pin(inp_height, range);\n\n // however, if we are showing a tracklist, default the height to\n // show exactly DEFAULT_NUM_LIST_ITEMS list items by default (unless there are fewer tracks\n // than that, in which case, default to the number of tracks).\n // Calculate this by knowing that range.min shows MIN_LIST_ITEMS, so add\n // enough height for an additional 1 or 2 if appropriate\n if(self.size() == \"large\" && self.layout() != \"minimal\" && self.show_tracklist()) {\n var nitems = Math.min(DEFAULT_NUM_LIST_ITEMS, opts.num_tracks || 0);\n if(nitems > MIN_LIST_ITEMS) {\n Log.debug(\"showing \" + nitems + \" tracks by default\");\n new_height = range.min + LIST_ITEM_HEIGHT * (nitems - MIN_LIST_ITEMS);\n }\n }\n\n if(new_height != inp_height) {\n self.height(new_height);\n self._applying_dimensions = true;\n self.input_height(new_height);\n self._applying_dimensions = false;\n }\n }", "function resize(){\n const width = window.innerWidth - 100;\n const topHeight = d3.select(\".top\").node().clientHeight\n const height = window.innerHeight - topHeight - 50\n console.log(width, height)\n \n self.camera.aspect = width / height;\n self.camera.updateProjectionMatrix();\n self.renderer.setSize(width, height);\n render()\n\n }", "function set_zoom_to_movie_player(video, zoom=true) {\n if(!document.fullscreenElement) {\n // The movie_player is the grandparent node of the video element.\n // Open question: Is it more likely for the ID of the relevant element to\n // change (so that selecting it as the grandparent is the best strategy), or\n // for its position in the DOM tree to change (so that selecting it by ID is\n // the best strategy)?\n if(zoom) {\n apply_player_aspect(true)\n set_zoom(video,\n video.parentNode.parentNode.clientWidth,\n video.parentNode.parentNode.clientHeight)\n } else {\n unzoom(video,\n video.parentNode.parentNode.clientWidth,\n video.parentNode.parentNode.clientHeight)\n }\n } else {\n apply_player_aspect(false)\n \n // In full-screen mode, the movie-player is not necessarily the same size as\n // the screen, which can cause a slight offset. Use set_zoom_to_window instead\n // for this case.\n set_zoom_to_window(video, zoom)\n }\n zoom_button.update()\n}", "resize() {\n this.createCanvas();\n }", "function video_height(){\r\n var _height = $('.gallery-image').height();\r\n $('.video-item').height(_height);\r\n }", "function resize() {\n\n var mapratio= parseInt(d3.select(tag_id).style('width'));\n\n if (width > 8*height) {\n mapratio = width /5;\n } else if (width > 6*height) {\n mapratio = width /4;\n } else if(width>4*height){\n mapratio = width /3;\n } else if(width> 2*height){\n mapratio = width/2;\n } else if(width >= height){\n mapratio = width;\n }\n\n projection.scale([mapratio]).translate([width/2,height/2]);\n }", "set width(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.width[set]\");\n this._width = aValue;\n }", "resizeAxisCanvas() {\n const desiredWidth = this.visualizer.canvas.width;\n const desiredHeight = this.visualizer.canvas.height;\n\n if (this.canvas.width !== desiredWidth || this.canvas.height !== desiredHeight) {\n this.canvas.width = desiredWidth;\n this.canvas.height = desiredHeight;\n }\n }", "_thumbnailsBoxResized() {\n this._updateSize();\n this._redisplay();\n }", "function resize() {\n map_width = sky_map.width();\n map_height = sky_map.height();\n font_height = map_height / 25;\n axis_size.x = map_width / 20;\n var x = sky_map.css('font-size', font_height).measureText({\n text: '888888'\n });\n if (x.width > axis_size.x) {\n font_height = font_height * axis_size.x / x.width;\n x = sky_map.css('font-size', font_height).measureText({\n text: '888888'\n });\n }\n axis_size.x = x.width;\n axis_size.y = x.height * 5 / 4;\n font_height = x.height;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::VirtualService.VirtualServiceSpec` resource
function cfnVirtualServiceVirtualServiceSpecPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnVirtualService_VirtualServiceSpecPropertyValidator(properties).assertSuccess(); return { Provider: cfnVirtualServiceVirtualServiceProviderPropertyToCloudFormation(properties.provider), }; }
[ "function cfnVirtualServiceVirtualServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualNode: cfnVirtualServiceVirtualNodeServiceProviderPropertyToCloudFormation(properties.virtualNode),\n VirtualRouter: cfnVirtualServiceVirtualRouterServiceProviderPropertyToCloudFormation(properties.virtualRouter),\n };\n}", "function cfnVirtualServiceVirtualRouterServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualRouterServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualRouterName: cdk.stringToCloudFormation(properties.virtualRouterName),\n };\n}", "function cfnGatewayRouteGatewayRouteVirtualServicePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GatewayRouteVirtualServicePropertyValidator(properties).assertSuccess();\n return {\n VirtualServiceName: cdk.stringToCloudFormation(properties.virtualServiceName),\n };\n}", "function cfnVirtualServiceVirtualNodeServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualNodeServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualNodeName: cdk.stringToCloudFormation(properties.virtualNodeName),\n };\n}", "constructor(scope, id, props) {\n super(scope, id, { type: CfnVirtualService.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_appmesh_CfnVirtualServiceProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnVirtualService);\n }\n throw error;\n }\n cdk.requireProperty(props, 'meshName', this);\n cdk.requireProperty(props, 'spec', this);\n cdk.requireProperty(props, 'virtualServiceName', this);\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.attrMeshName = cdk.Token.asString(this.getAtt('MeshName', cdk.ResolutionTypeHint.STRING));\n this.attrMeshOwner = cdk.Token.asString(this.getAtt('MeshOwner', cdk.ResolutionTypeHint.STRING));\n this.attrResourceOwner = cdk.Token.asString(this.getAtt('ResourceOwner', cdk.ResolutionTypeHint.STRING));\n this.attrUid = cdk.Token.asString(this.getAtt('Uid', cdk.ResolutionTypeHint.STRING));\n this.attrVirtualServiceName = cdk.Token.asString(this.getAtt('VirtualServiceName', cdk.ResolutionTypeHint.STRING));\n this.meshName = props.meshName;\n this.spec = props.spec;\n this.virtualServiceName = props.virtualServiceName;\n this.meshOwner = props.meshOwner;\n this.tags = new cdk.TagManager(cdk.TagType.STANDARD, \"AWS::AppMesh::VirtualService\", props.tags, { tagPropertyName: 'tags' });\n }", "function cfnVirtualGatewayVirtualGatewaySpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewaySpecPropertyValidator(properties).assertSuccess();\n return {\n BackendDefaults: cfnVirtualGatewayVirtualGatewayBackendDefaultsPropertyToCloudFormation(properties.backendDefaults),\n Listeners: cdk.listMapper(cfnVirtualGatewayVirtualGatewayListenerPropertyToCloudFormation)(properties.listeners),\n Logging: cfnVirtualGatewayVirtualGatewayLoggingPropertyToCloudFormation(properties.logging),\n };\n}", "function cfnVirtualNodeVirtualServiceBackendPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualServiceBackendPropertyValidator(properties).assertSuccess();\n return {\n ClientPolicy: cfnVirtualNodeClientPolicyPropertyToCloudFormation(properties.clientPolicy),\n VirtualServiceName: cdk.stringToCloudFormation(properties.virtualServiceName),\n };\n}", "function cfnVirtualRouterVirtualRouterSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualRouter_VirtualRouterSpecPropertyValidator(properties).assertSuccess();\n return {\n Listeners: cdk.listMapper(cfnVirtualRouterVirtualRouterListenerPropertyToCloudFormation)(properties.listeners),\n };\n}", "function cfnVirtualNodeVirtualNodeSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeSpecPropertyValidator(properties).assertSuccess();\n return {\n BackendDefaults: cfnVirtualNodeBackendDefaultsPropertyToCloudFormation(properties.backendDefaults),\n Backends: cdk.listMapper(cfnVirtualNodeBackendPropertyToCloudFormation)(properties.backends),\n Listeners: cdk.listMapper(cfnVirtualNodeListenerPropertyToCloudFormation)(properties.listeners),\n Logging: cfnVirtualNodeLoggingPropertyToCloudFormation(properties.logging),\n ServiceDiscovery: cfnVirtualNodeServiceDiscoveryPropertyToCloudFormation(properties.serviceDiscovery),\n };\n}", "function CfnVirtualService_VirtualServiceSpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('provider', CfnVirtualService_VirtualServiceProviderPropertyValidator)(properties.provider));\n return errors.wrap('supplied properties not correct for \"VirtualServiceSpecProperty\"');\n}", "function cfnVirtualRouterPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualRouterPropsValidator(properties).assertSuccess();\n return {\n MeshName: cdk.stringToCloudFormation(properties.meshName),\n Spec: cfnVirtualRouterVirtualRouterSpecPropertyToCloudFormation(properties.spec),\n MeshOwner: cdk.stringToCloudFormation(properties.meshOwner),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n VirtualRouterName: cdk.stringToCloudFormation(properties.virtualRouterName),\n };\n}", "function cfnVirtualNodePropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNodePropsValidator(properties).assertSuccess();\n return {\n MeshName: cdk.stringToCloudFormation(properties.meshName),\n Spec: cfnVirtualNodeVirtualNodeSpecPropertyToCloudFormation(properties.spec),\n MeshOwner: cdk.stringToCloudFormation(properties.meshOwner),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n VirtualNodeName: cdk.stringToCloudFormation(properties.virtualNodeName),\n };\n}", "function cfnVirtualNodeBackendPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_BackendPropertyValidator(properties).assertSuccess();\n return {\n VirtualService: cfnVirtualNodeVirtualServiceBackendPropertyToCloudFormation(properties.virtualService),\n };\n}", "function cfnVirtualGatewayPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGatewayPropsValidator(properties).assertSuccess();\n return {\n MeshName: cdk.stringToCloudFormation(properties.meshName),\n Spec: cfnVirtualGatewayVirtualGatewaySpecPropertyToCloudFormation(properties.spec),\n MeshOwner: cdk.stringToCloudFormation(properties.meshOwner),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n VirtualGatewayName: cdk.stringToCloudFormation(properties.virtualGatewayName),\n };\n}", "function cfnVirtualNodeDnsServiceDiscoveryPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_DnsServiceDiscoveryPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cdk.stringToCloudFormation(properties.hostname),\n IpPreference: cdk.stringToCloudFormation(properties.ipPreference),\n ResponseType: cdk.stringToCloudFormation(properties.responseType),\n };\n}", "function cfnVirtualGatewayVirtualGatewayListenerPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayListenerPropertyValidator(properties).assertSuccess();\n return {\n ConnectionPool: cfnVirtualGatewayVirtualGatewayConnectionPoolPropertyToCloudFormation(properties.connectionPool),\n HealthCheck: cfnVirtualGatewayVirtualGatewayHealthCheckPolicyPropertyToCloudFormation(properties.healthCheck),\n PortMapping: cfnVirtualGatewayVirtualGatewayPortMappingPropertyToCloudFormation(properties.portMapping),\n TLS: cfnVirtualGatewayVirtualGatewayListenerTlsPropertyToCloudFormation(properties.tls),\n };\n}", "function CfnVirtualServicePropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('meshName', cdk.requiredValidator)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshName', cdk.validateString)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshOwner', cdk.validateString)(properties.meshOwner));\n errors.collect(cdk.propertyValidator('spec', cdk.requiredValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('spec', CfnVirtualService_VirtualServiceSpecPropertyValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.requiredValidator)(properties.virtualServiceName));\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.validateString)(properties.virtualServiceName));\n return errors.wrap('supplied properties not correct for \"CfnVirtualServiceProps\"');\n}", "function cfnVirtualGatewayVirtualGatewayClientPolicyPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayClientPolicyPropertyValidator(properties).assertSuccess();\n return {\n TLS: cfnVirtualGatewayVirtualGatewayClientPolicyTlsPropertyToCloudFormation(properties.tls),\n };\n}", "function cfnVirtualGatewayVirtualGatewayConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualGatewayVirtualGatewayHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualGatewayVirtualGatewayHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I need to reference all the elements that are "inDistance" To determine if they have block or player class, if they do movement is not possible
function isInDistance (player, block) { const firstCondition = (Math.abs(block.dataset['x'] - player.position.x) <= 3) && (block.dataset['y'] === player.position.y); const secondCondition = (Math.abs(block.dataset['y'] - player.position.y) <= 3) && (block.dataset['x'] === player.position.x); return (firstCondition || secondCondition); }
[ "function getEnemy(x, y, distance) {\n const enemyUnits = enemies1.getChildren().concat(enemies2.getChildren());\n for (let i = 0; i < enemyUnits.length; i++) {\n if (enemyUnits[i].active && Phaser.Math.Distance.Between(x, y, enemyUnits[i].x, enemyUnits[i].y) <= distance) {\n return enemyUnits[i];\n }\n }\n return false;\n}", "reachedTargetPosition() {\n if (this.target !== undefined) {\n let targetCenter = this.getTargetCenter();\n let ownCenter = this.getCenter();\n // console.log(ownCenter);\n // console.log(targetCenter);\n var distance = Phaser.Math.Distance.Between(\n ownCenter.x,\n ownCenter.y,\n targetCenter.x,\n targetCenter.y\n );\n if (distance < 10) {\n return true;\n }\n // console.log(distance);\n }\n return false;\n }", "function getMoveable() {\n let re = []\n $('.tile').each((index, element) => {\n if (element.id != \"tileEmpty\") {\n isMoveable(element) ? re.push(element) : null;\n }\n });\n return re;\n}", "getDistance(){\n\t\tif(this.TargetPlanet!== null){\n\t\t\treturn Math.abs(this.Group.position.y - this.TargetPlanet.y);\n\t\t}\n\t\telse return 0;\n\t}", "function isSpaceOccupied(entity, distance, x, y){\n\tif(entity !== 'tree'){\n\t\tfor(var i in treeList){\n\n\t\t\tif(distanceBetweenCoords(treeList[i].x,treeList[i].y,x,y) < distance){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tif(entity !== 'berryBush'){\n\t\tfor(var i in berryBushList){\n\n\t\t\tif(distanceBetweenCoords(berryBushList[i].x,berryBushList[i].y,x,y) < distance){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tif(entity !== 'villager'){\n\t\tfor(var i in villagerList){\n\n\t\t\tif(distanceBetweenCoords(villagerList[i].x,villagerList[i].y,x,y) < distance){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tif(entity !== 'depot'){\n\t\tfor(var i in depotList){\n\n\t\t\tif(distanceBetweenCoords(depotList[i].x,depotList[i].y,x,y) < distance){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}", "function whoCanGo(dist) {\n return myArmy.filter(function (value) {\n return value.distanceAvailable > dist; });\n}", "getNearestHostileInLOS() {\n this.targetSearchLoop = setTimeout(this.getNearestHostileInLOS.bind(this), this.targetSearchRate);\n if (this.target !== null) return;\n\n if (this.direction === this.Directions.UP) this.target = this.getNearestHostileInLOSUp();\n else if (this.direction === this.Directions.DOWN) this.target = this.getNearestHostileInLOSDown();\n else if (this.direction === this.Directions.LEFT) this.target = this.getNearestHostileInLOSLeft();\n else this.target = this.getNearestHostileInLOSRight();\n }", "function checkCollision(location, collisionDistance) {\n //first have to project...\n var locationProj = getScreenCoords(location);\n if (!locationProj)\n return true;\n\n var hitTestResult = ge.getView().hitTest(locationProj[0], ge.UNITS_PIXELS, locationProj[1], ge.UNITS_PIXELS, ge.HIT_TEST_BUILDINGS);\n //var hitTestResult = ge.getView().hitTest(0.5, ge.UNITS_FRACTION, 0.75, ge.UNITS_FRACTION, ge.HIT_TEST_BUILDINGS); //0.75 is a guestemate. Not worth calculating\n if (hitTestResult) {\n var charGLat = new GLatLng(me.characterLla[0], me.characterLla[1]);\n var distFromResult = charGLat.distanceFrom(new GLatLng(hitTestResult.getLatitude(), hitTestResult.getLongitude()));\n if (distFromResult < DISTANCE_FROM_COLLISION) {\n currentSpeed = 0;\n return true;\n }\n }\n return false;\n}", "function filterByDistance() {\r\n //filter by Distance will only show \"pins\" within 1 mile of users location\r\n }", "function eachSpaceAround(target, callback) {\n let pos = target.pos;\n for(let xDir = -1; xDir <= 1; xDir++) {\n for(let yDir = -1; yDir <= 1; yDir++) {\n let x = pos.x + xDir;\n let y = pos.y + yDir;\n if((xDir != 0 || yDir != 0) && target.room.lookForAt(LOOK_TERRAIN, x, y) != \"wall\") {\n if(callback({ x: x, y: y })) {\n return true;\n }\n }\n }\n }\n}", "function findReachablePositions(player, position) { // PARAMETERS : player, position\n\n reachs = []; // vider le tableau des cases atteignables\n\n var surrounds = findSurroundingPositions(position); // create a variable to define surrounding positions\n var range = 0; // set distance tested to zero\n\n // Define reachable positions : top\n\n while ( // WHILE...\n (surrounds[1] !== null) && // ...the position above exist (not outside of the board)\n (squares[surrounds[1]].player === 0) && // ... AND the position above is not occupied by a player\n (squares[surrounds[1]].obstacle === 0) && // ... AND the position above is not occupied by an obstacle\n (range < 3) // ... AND the tested position distance from player position is below 3\n ) { // THEN\n var reach = Object.create(Reach); // create an object reach\n reachFight = isLeadingToFight(player, surrounds[1]); // define is the reachable position is a fighting position\n reach.initReach(player, surrounds[1], -10, (range + 1), reachFight); // set properties\n reachs.push(reach); // push object in array\n range++; // increase range of position tested\n surrounds = findSurroundingPositions(position - (10 * range)); // move forward the test\n }\n\n // Define reachable positions : right\n\n range = 0; // reset range for next test\n surrounds = findSurroundingPositions(position); // reset surrounds for next test\n\n while (\n (surrounds[4] !== null) &&\n (squares[surrounds[4]].player === 0) &&\n (squares[surrounds[4]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[4]);\n reach.initReach(player, surrounds[4], +1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (1 * range));\n }\n\n // Define reachable positions : bottom\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[6] !== null) &&\n (squares[surrounds[6]].player === 0) &&\n (squares[surrounds[6]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[6]);\n reach.initReach(player, surrounds[6], +10, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (10 * range));\n }\n\n // Define reachable positions : left\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[3] !== null) &&\n (squares[surrounds[3]].player === 0) &&\n (squares[surrounds[3]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[3]);\n reach.initReach(player, surrounds[3], -1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position - (1 * range));\n }\n\n return reachs; // return array\n\n}", "function isNeighbors(tile1, tile2) {\r\n\t\tvar left1 = parseInt(window.getComputedStyle(tile1).left);\r\n\t\tvar top1 = parseInt(window.getComputedStyle(tile1).top);\r\n\t\tvar left2 = parseInt(window.getComputedStyle(tile2).left);\r\n\t\tvar top2 = parseInt(window.getComputedStyle(tile2).top);\r\n\t\tif (Math.abs(left1 + top1 - left2 - top2) == 100) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "hasReachedDestination() {\r\n\t\tvar destinationTiles = this.levelGrid.getDestination();\r\n\t\tfor (var i = 0; i < destinationTiles.length; i++) {\r\n\t\t\tvar destinationRow = destinationTiles[i].row;\r\n\t\t\tvar destinationColumn = destinationTiles[i].column;\r\n\t\t\tif ( this.currentTileRow === destinationRow\r\n\t\t\t\t && this.currentTileColumn === destinationColumn ) {\r\n\t\t\t\tthis.speed = 0;\r\n\t\t\t\treturn true;\r\n\t\t\t} \t\t\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "function getClosestElement() {\n var $list = sections\n , wt = contTop\n , wh = contentBlockHeight\n , refY = wh\n , wtd = wt + refY - 1\n ;\n\n if (direction == 'down') {\n $list.each(function() {\n var st = $(this).position().top;\n if ((st > wt) && (st <= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n } else {\n wtd = wt - refY + 1;\n $list.each(function() {\n var st = $(this).position().top;\n if ((st < wt) && (st >= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n }\n\n return target;\n\n}", "CheckDistance(sourceObject, destinationObject) {\n let distance = Phaser.Math.Distance.Between(sourceObject.x, sourceObject.y, destinationObject.x, destinationObject.y);\n\n return distance;\n }", "playerDist() {\n return this.playerDistTo(this.getPos());\n }", "function checkPos(car){\n for(let i = 0; i < car.length; i++){\n if(car[i].position.y > maxH + carH){\n atBottom = true;\n carsPassed++;\n if(car[i].getSpeed() > 20){\n setMovement(car[i], - 10);\n } else {\n setMovement(car[i], mode);\n }\n }\n }\n}", "function distanceTravelledInFeet(startBlock, endBlock) {\n totalBlocks = Math.abs(startBlock-endBlock)\n return totalBlocks * 264\n }", "function playerHit (){\n playShipOptions.forEach(ship => {\n ship.hit.forEach(location => { \n playerCells[location].classList.add('hit')\n })\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7.2 Find the name of the account with the largest balance
function top_balance() { var largest_balance = 0; for (var i in accounts) { if (accounts[i].amount > largest_balance) { largest_balance = accounts[i].amount; richest = accounts[i].name; } } console.log("Holder of biggest balance: " + richest); }
[ "function top_personal_balance() {\n var largest_balance = 0;\n for (var i in accounts) {\n if (accounts[i].type === \"personal\") {\n if (accounts[i].amount > largest_balance) {\n largest_balance = accounts[i].amount;\n richest = accounts[i].name;\n }\n }\n }\n console.log(\"Holder of biggest personal balance: \" + richest);\n}", "function biggestCompanyName() {\n return _.reverse(_.sortBy(groupByCompany(), ['users.length'])).splice(0, 1)[0].name\n}", "function topSalary(salaries) {\n let max = 0;\n let maxName = null;\n\n for (let [name, salary] of Object.entries(salaries)) {\n if (max < salary) {\n max = salary;\n maxName = name;\n }\n }\n return maxName;\n}", "function lowest_balance() {\n var smallest_balance = accounts[0].amount;\n for (var i in accounts) {\n if (accounts[i].amount < smallest_balance) {\n smallest_balance = accounts[i].amount;\n poorest = accounts[i].name;\n }\n }\n console.log(\"Holder of smallest balance: \" + poorest);\n}", "function maximumWealth(accounts) {\n let men = {};\n for(let [i, money] of accounts.entries()) {\n men[i] = money.reduce((a, b) => a + b);\n };\n return Object.values(men).reduce((a, b) => Math.max(a, b));\n}", "function extractMax(table, studentArray, houseName) {\n let currentRank = table.getRank(houseName, studentArray[0]);\n let newRank = 0;\n // the highest rank \"bubbles\" to the end of the array\n for (let i = 0; i < studentArray.length - 1; i++) {\n newRank = table.getRank(houseName, studentArray[i + 1]);\n if (currentRank > newRank) {\n let temp = studentArray[i];\n studentArray[i] = studentArray[i + 1];\n studentArray[i + 1] = temp;\n } else {\n currentRank = newRank;\n }\n }\n let student = studentArray.pop();\n return student;\n}", "get mostActiveUser() {\n let userNames = issues.map(obj => obj.user.login);\n let counters = {};\n userNames.forEach(id => {\n if (!counters.hasOwnProperty(id)) {\n counters[id] = 0;\n };\n counters[id]++;\n });\n let activeUserNames = Object.keys(counters);\n return activeUserNames.reduce((topUserName, userName) => topUserName =\n counters[userName] > counters[topUserName] ? userName : topUserName);\n }", "function longestName(arr){\n var ruselt =arr.reduce(function(str,elm,i){\n //str=arr[0].name.first+\"\"+arr[0].name.last\n elm=arr[i].name.first+\"\"+arr[i].name.last\n if (str.length > elm.length) {\n return elm=str\n }return elm\n }\n ) \n return ruselt\n}", "function findMaxOpponentHealth(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let healthValues = []\n let biggestValue = 0\n for(let i=0; i<opponentCards.length; i++) {\n healthValues.push(opponentCards[i].children[1].children[0].innerText);\n }\n for(let i=0; i<healthValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[1].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = healthValues.indexOf(biggestValue);\n healthValues.splice(index, 1);\n for(let i=0; i<healthValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[1].children[0].innerText;\n }\n }\n }\n for(let i=0; i<opponentCards.length; i++) {\n if(opponentCards[i].children[1].children[0].innerText == biggestValue) {\n return opponentCards[i]\n }\n }\n return true\n}", "function findMaxPlayerHealth(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('.player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let healthValues = []\n let biggestValue = 0\n for(let i=0; i<alliedCards.length; i++) {\n healthValues.push(alliedCards[i].children[1].children[0].innerText);\n }\n for(let i=0; i<healthValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[1].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = attackValues.indexOf(biggestValue);\n attackValues.splice(index, 1);\n for(let i=0; i<healthValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[1].children[0].innerText;\n }\n }\n }\n for(let i=0; i<alliedCards.length; i++) {\n if(alliedCards[i].children[1].children[0].innerText == biggestValue) {\n return alliedCards[i]\n }\n }\n return true\n}", "function sortByRichest() {\n // Sorting the users object - by the money property\n users.sort((a, b) => {\n // want this to be descending - so we do b - a instead of a - b\n return b.money - a.money;\n });\n\n // Update the DOM\n updateDOM();\n}", "function get_largest_id(obj, current_largest) {\n if (_underscore2.default.isUndefined(current_largest)) current_largest = 0;\n if (_underscore2.default.isUndefined(obj)) return current_largest;\n return Math.max.apply(null, Object.keys(obj).map(function (x) {\n return parseInt(x);\n }).concat([current_largest]));\n }", "balance() {\n\t\tif (this.dead) {\n\t\t\tthrow new BankError('Account is shut down');\n\t\t} else {\n\t\t\treturn this.credits + this.investments.reduce((s,i) => s += i.principle, 0);\n\t\t}\n\t}", "function findMaxPlayerAttack(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('.player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let attackValues = []\n let biggestValue = 0\n for(let i=0; i<alliedCards.length; i++) {\n attackValues.push(alliedCards[i].children[0].children[0].innerText);\n }\n for(let i=0; i<attackValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[0].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = attackValues.indexOf(biggestValue);\n attackValues.splice(index, 1);\n biggestValue = 0;\n for(let i=0; i<attackValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[0].children[0].innerText;\n }\n }\n }\n for(let i=0; i<alliedCards.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText == biggestValue) {\n return alliedCards[i]\n }\n }\n return true\n}", "function findMaxOpponentAttack(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let attackValues = []\n let biggestValue = 0\n for(let i=0; i<opponentCards.length; i++) {\n attackValues.push(opponentCards[i].children[0].children[0].innerText);\n }\n for(let i=0; i<attackValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[0].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = attackValues.indexOf(biggestValue);\n attackValues.splice(index, 1);\n biggestValue = 0;\n for(let i=0; i<attackValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[0].children[0].innerText;\n }\n }\n }\n for(let i=0; i<opponentCards.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText == biggestValue) {\n return opponentCards[i]\n }\n }\n return true\n}", "findMinRaiseAmount(lineup, dealer, lastRoundMaxBet, state) {\n if (!lineup || dealer === undefined) {\n throw new Error('invalid params.');\n }\n const lastRoundMaxBetInt = parseInt(lastRoundMaxBet, 10);\n // TODO: pass correct state\n const max = this.getMaxBet(lineup, state);\n if (max.amount === lastRoundMaxBetInt) {\n throw new Error('can not find minRaiseAmount.');\n }\n // finding second highest bet\n let secondMax = lastRoundMaxBetInt;\n for (let i = max.pos + 1; i < lineup.length + max.pos; i += 1) {\n const pos = i % lineup.length;\n const last = (lineup[pos].last) ? this.rc.get(lineup[pos].last).amount.toNumber() : 0;\n if (last > secondMax && last < max.amount) {\n secondMax = last;\n }\n }\n return max.amount - secondMax;\n }", "function getGoals(data) {\n\n//returns team name with the highest average\n}", "function maxID(){\n var res = 0;\n for(var i = 0; i < employees.length; i++){\n if(employees[i].id > res){\n res = employees[i].id;\n }\n }\n return res;\n}", "limit(maxStats) {\n let stats = new BirdStats({});\n this.forEachStat((name, value) => {\n if (value > maxStats[name]) {\n stats[name] = maxStats[name];\n } else {\n stats[name] = value;\n }\n });\n return stats;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function in charge to execute the handler function if it was not fired
function requestHandle() { if (!isHandled) { isHandled = true; vueInst.$nextTick(() => { isHandled = false; handler(); }); } }
[ "handleNoChangeEvent() {\n \n }", "handleLoaded(itemName) {\n this.toLoad = this.toLoad.filter(item => item !== itemName);\n\n if (this.toLoad.length === 0) {\n this.callbacks.onLoaded();\n }\n }", "function runLoadHandlers() {\n while (loadHandlers.length) {\n loadHandlers.shift()();\n }\n // And, if someone tries to add another, just run it right away\n sergis.addLoadHandler = function (handler) {\n handler();\n };\n // Now, tell the server that we're ready\n sergis.socket.emit(\"contentLoaded\");\n }", "_dispatchEvents() {\n //todo: this doesnt let us specify order that events are disptached\n //so we will probably have to check each one\n //info here: https://stackoverflow.com/a/37694450/10232\n for (let handler of this._eventHandlers.values()) {\n handler.dispatch();\n }\n }", "hasCallback() {}", "async on_trigger() {\n // wakeup the caller and wait for it to ack back\n this.notifier.wakeup();\n await this.holder.wait();\n\n this.counter += 1;\n\n // wakeup the caller and wait for it to ack back\n this.notifier.wakeup();\n await this.holder.wait();\n\n // fail only after the last ack so the caller can be ready\n if (this.fail) {\n throw error_utils.stackless(new Error('TEST ERROR INJECTION'));\n }\n }", "function determine_handler( param_handler_setting, type)\n{\n\tif (param_handler_setting)\n\t{\n\t\treturn (param_handler_setting == 'none') ? null : param_handler_setting ;\n\t}\n\t// neither a custom or global handler is defined, so set to null\n\telse\n\t{\n\t\tthrow new Error(\"ERROR: undefined \" + type + \" handler function. AJAX connection not established\") ;\n\t}\t\n}", "preAction(evt) {\n // Validate: Check Serverless version\n if (parseInt(S._version.split(\".\")[1], 10) < 5) {\n SCli.log(\n \"WARNING: This version of the Serverless Wrapper Plugin \" +\n \"will not work with a version of Serverless that is less or greater than than v0.5.x\"\n );\n }\n\n // Get function\n const project = S.getProject();\n const func = project.getFunction(evt.options.name);\n\n const funcConfig = func.custom;\n const projConfig = project.custom;\n\n if (funcConfig && funcConfig.wrapper === false) {\n // If wrapper.path exists and is 'false', skip wrapping\n return Promise.resolve(evt);\n } else if (funcConfig && funcConfig.wrapper && funcConfig.wrapper.path) {\n return this._wrapHandler(project, func, evt, funcConfig.wrapper.path);\n } else if (projConfig && projConfig.wrapper && projConfig.wrapper.path) {\n return this._wrapHandler(project, func, evt, projConfig.wrapper.path);\n }\n\n // If we can't handle this event, just pass it through\n return Promise.resolve(evt);\n }", "function runPreAjaxCallbackHandlers($data) {\n return runGenericHandlers($data, preAjaxCallbackHandlers);\n }", "function checkHandler(handler, functionName) {\n if (typeof handler !== 'function') throw new TypeError(functionName, 'requires a handler that is a function!');\n}", "function fireWhenReady(callback) {\n if (!displayOnEvent || slideIsReady) {\n callback();\n } else {\n slideReadyCallbacks.push(callback);\n }\n }", "function callRegistrationHandler(isAuthenticated) {\n // Call the registration handler if the user is new and the handler\n // is defined.\n if (isAuthenticated && (!user.meta.isRegistered) &&\n registrationHandler) {\n // Using $timeout to give angular a chance to update the view.\n // $timeout returns a promise equivalent to the one returned by\n // registrationHandler.\n return $timeout(registrationHandler, 0)\n .then(function () {\n return isAuthenticated;\n });\n } else {\n return isAuthenticated;\n }\n }", "onEventHandlerHas(room, handler, identifier) {\n return (this.handlers.hasOwnProperty(handler)\n && this.handlers[handler].hasOwnProperty(identifier));\n }", "handleReRunEvent() {\n \n }", "_beforeHandleRoute() {\n this._afterHandleRouteCalled = false;\n }", "shouldRunMessageCallback(this_frame) {\n const subscription = this._subscribed_to[this_frame.headers.destination];\n if (this_frame.headers.destination !== null && subscription !== null) {\n if (subscription.enabled && subscription.callback !== null && typeof(subscription.callback) == 'function') {\n subscription.callback(this_frame.body, this_frame.headers);\n }\n }\n }", "function ConventionalHandler() {\r\n}", "function checkFinished () {\n console.log(fileLoadCount+\" files loaded\")\n if (fileLoadCount == fileLoadThreshold) {\n console.log(\"basicFileLoader - callback: \"+cFunc.name);\n cFunc();\n }\n }", "function handleResponse(request, responseHandler) {\n if (request.readyState == 4 && request.status == 200) {\n responseHandler(request);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a valid github repository url and parses it, returning an object of type `ParsedGithubUrl`
function parseGithubUrl(urlStr) { let match; for (const pattern of githubPatterns) { match = urlStr.match(pattern); if (match) { break; } } if (!match) throw new Error(invalidGithubUrlMessage(urlStr)); let [, auth, username, reponame, treeish = `master`] = match; treeish = treeish.replace(/[^:]*:/, ``); return { auth, username, reponame, treeish }; }
[ "function cleanRepoGitHubUrl(url) {\n return url.replace('https://api.github.com/repos', 'https://github.com');\n}", "function cleanGitHubUrl(url) {\n return url.replace('https://api.github.com', 'https://github.com');\n}", "function isGithubUrl(url) {\n return url ? githubPatterns.some(pattern => !!url.match(pattern)) : false;\n}", "function parseURL(url) {\n parsed_url = {}\n\n if (url == null || url.length == 0)\n return parsed_url;\n\n protocol_i = url.indexOf('://');\n parsed_url.protocol = url.substr(0, protocol_i);\n\n remaining_url = url.substr(protocol_i + 3, url.length);\n domain_i = remaining_url.indexOf('/');\n domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;\n parsed_url.domain = remaining_url.substr(0, domain_i);\n parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);\n\n //a domain can have multiple configuration (google.com, www.google.com, plus.google.com...), this sorts it out for the parsed url\n domain_parts = parsed_url.domain.split('.');\n switch (domain_parts.length) {\n case 2:\n parsed_url.subdomain = null;\n parsed_url.host = domain_parts[0];\n parsed_url.tld = domain_parts[1];\n break;\n case 3:\n parsed_url.subdomain = domain_parts[0];\n parsed_url.host = domain_parts[1];\n parsed_url.tld = domain_parts[2];\n break;\n case 4:\n parsed_url.subdomain = domain_parts[0];\n parsed_url.host = domain_parts[1];\n parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];\n break;\n }\n\n parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;\n\n return parsed_url;\n}", "function parseLink( rawLink ) {\n if ( rawLink && rawLink.length ) {\n rawLink = rawLink[ 0 ];\n return {\n phrase: rawLink.match( urlPhraseRegex )[ 2 ],\n url: rawLink.match( urlLinkRegex )[ 2 ]\n };\n }\n\n return null;\n }", "async function getConfigFromPackageJson() {\n const { repository } = await utils_1.loadPackageJson();\n if (!repository) {\n return;\n }\n const { owner, name } = parse_github_url_1.default(typeof repository === \"string\" ? repository : repository.url) || {};\n if (!owner || !name) {\n return;\n }\n return {\n repo: name,\n owner,\n };\n}", "parse(_stUrl) {\n Url.parse(_stUrl, true);\n }", "function GitHub(config) {\n if (config == null) {\n config = {};\n }\n this.config = config;\n \n if (config.timeout == null) {\n config.timeout = 20000;\n }\n if (config.beforeSend != null) {\n config.beforeSend = function() {};\n }\n if (config.complete != null) {\n config.complete = function() {};\n }\n if (config.rootUrl == null) {\n config.rootUrl = \"https://api.github.com/\";\n } else if (!config.rootUrl.endsWith(\"/\")) {\n config.rootUrl = config.rootUrl + \"/\";\n }\n if (config.userAgent != null) {\n config.userAgent = \"Ceylon-Web-Runner-1.2.0\";\n }\n if (config.maxRequests == null) {\n config.maxRequests = 5;\n }\n \n this._etags = {};\n this._cache = {};\n this.rateLimitRemaining = null;\n this.rateLimitLimit = null;\n }", "function parseResolved(entry) {\n const resolved = entry.resolved;\n if (resolved) {\n const tokens = resolved.split(\"#\");\n entry.url = tokens[0];\n entry.sha1 = tokens[1];\n }\n}", "function clone(githubUrl) {\n const cloned = callShellExec(`git clone ${githubUrl}`)\n if (cloned.code !== 0) {\n throw {code: cloned.code, message: cloned.stderr}\n } else return cloned\n}", "function _parse(info) {\n if (typeof info !== 'string') {\n throw new TypeError('expecting string transport uri');\n }\n\n var uri = url.parse(info);\n\n if (!(uri.port > 0)) {\n throw new Error('expected valid transport uri');\n }\n\n return {\n host: uri.hostname,\n port: uri.port\n };\n}", "function Milestone(github, data) {\n this.github = github;\n this.data = data;\n var url = data.url;\n if (url == null) {\n throw \"Missing required `data.url`\";\n }\n var p = url.indexOf(\"/repos/\");\n if (p >= 0) {\n url = url.substring(p + 1);\n }\n this.apiurl = url;\n }", "function Issue(github, data) {\n this.github = github;\n this.data = data;\n var url = data.url;\n if (url == null) {\n throw \"Missing required `data.url`\";\n }\n var p = url.indexOf(\"/repos/\");\n if (p >= 0) {\n url = url.substring(p + 1);\n }\n this.apiurl = url;\n }", "_githubRequest(url, callback) {\n return request({url: url, headers: {'User-Agent': 'request'}, json: true}, callback);\n }", "function processGitHubData(data) {\n const { login, id } = data;\n // only works with two names\n return {\n username: login,\n id: id\n };\n}", "function parseLink(response, body, _url) {\n\t\tif (response.statusCode === 200) {\n\t\t\t\tvar links = $('a', body),\n\t\t\t\t\tcurLink,\n\t\t\t\t\tshaAlgo,\n\t\t\t\t\tshaOfLink,\n\t\t\t\t\tvalidUrl,\n\t\t\t\t\tprotocol;\n\t\t\t\tshaAlgo = hasher.createHash('sha1');\n\t\t\t\tshaAlgo.update(_url);\n\t\t\t\tshaOfLink = shaAlgo.digest('hex');\n\t\t\t\t_this.repository[shaOfLink] = _url;\n\t\t\t\t_this.totalIndexed += 1 + links.length;\n\t\t\t\tfor(var i=0; i<links.length; i++) {\n\t\t\t\t\tcurLink = $(links[i]).attr('href');\n\t\t\t\t\tif(curLink) {\n\t\t\t\t\t\t//resolve the relative paths\n\t\t\t\t\t\tif(!(/^http\\:\\/\\/|https\\:\\/\\//.test(curLink))) {\n\t\t\t\t\t\t\tvalidUrl = urlLib.resolve(_url, curLink);\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tvalidUrl = curLink;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tshaAlgo = hasher.createHash('sha1');\n\t\t\t\t\t\tshaAlgo.update(validUrl);\n\t\t\t\t\t\tshaOfLink = shaAlgo.digest('hex');\n\t\t\t\t\t\tprotocol = urlLib.parse(validUrl).protocol;\n\t\t\t\t\t\t// visit only http urls ignoring others like mailto:\n\t\t\t\t\t\tif(protocol==='http:' || protocol==='https:') {\n\t\t\t\t\t\t\tif(!(shaOfLink in _this.repository)) {\n\t\t\t\t\t\t\t\t_this.repository[shaOfLink] = validUrl;\n\t\t\t\t\t\t\t\t_this.visitableList.push(validUrl);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(_this.visitableList.length && continueVisit) {\n\t\t\t\t\tvar linkToVisit = _this.visitableList.pop();\n\t\t\t\t\tvisitNextPage(linkToVisit);\n\t\t\t\t}else {\n\t\t\t\t\t_this.emit('complete',_this.repository, _this.totalIndexed, _this.totalVisit);\n\t\t\t\t}\n\t\t}\n\t\telse {\n\t\tif(_this.visitableList.length && continueVisit) {\n\t\t\t\t\tvar linkToVisit = _this.visitableList.pop();\n\t\t\t\t\tvisitNextPage(linkToVisit);\n\t\t\t\t\t_this.emit('error', \"status :\"+response.statusCode, _url);\n\t\t\t\t}else {\n\t\t\t\t\t_this.emit('complete', _this.repository, _this.totalIndexed, _this.totalVisit);\n\t\t\t\t}\n\t\t}\n\t}", "async function fetchLatestRelease (repo) {\n return await new Promise((resolve, reject) => {\n https.get({\n auth: this.credentials.login + ':' + this.credentials.password,\n headers: {'User-Agent': this.credentials.login},\n host: 'api.github.com',\n path: '/repos/' + repo + '/releases/latest',\n port: '443'\n }, (res) => {\n // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)\n res.setEncoding('utf8');\n\n // incrementally capture the incoming response body\n var data = '';\n res.on('data', function (d) {\n data += d;\n });\n\n try {\n res.on('end', async () => {\n try {\n // console.log(res);\n var parsed = JSON.parse(data);\n } catch (err) {\n console.error(res.headers);\n console.error('Unable to parse response as JSON');\n return {};\n }\n\n resolve({tag_name: parsed.tag_name, published_at: parsed.published_at});\n });\n } catch (err) {\n console.log(err);\n reject(new Error());\n }\n });\n });\n}", "function getRepos(userHandle) {\n const searchURL = `https://api.github.com/users/${userHandle}/repos`\n \n\n fetch(searchURL)\n .then(response => {\n if (response.ok) return response.json()\n return response.json().then((e) => Promise.reject(e))\n })\n .then(responseJson => displayResults(responseJson))\n .catch(error => {\n console.error(error)\n\n alert(error.message)\n });\n}", "function Label(github, data) {\n this.github = github;\n this.data = data;\n var url = data.url;\n if (url == null) {\n throw \"Missing required `data.url`\";\n }\n var p = url.indexOf(\"/repos/\");\n if (p >= 0) {\n url = url.substring(p + 1);\n }\n this.apiurl = url;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update tarefa details. PUT or PATCH tarefas/:id
async update ({ params, request, response }) { const tarefa = await Tarefa.findOrFail(params.id); const dados = request.only(["descricao", "titulo", "status"]); tarefa.fill({ id : tarefa.id, ...dados }); await tarefa.save(); }
[ "updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }", "static async edit(id, titulo, descripcion, avatar, color) {\n // comprobar que ese elemento exista en la BD\n const trackTemp = await this.findById(id);\n if (!trackTemp) throw new Error(\"El track solicitado no existe!\");\n\n // crear un DTO> es un objeto de trancicion\n const modificador = {\n titulo,\n descripcion,\n avatar,\n color\n };\n // findOneAndUpdate > actualizara en base a un criterio\n const result = await this.findOneAndUpdate(\n {\n _id: id\n },\n {\n $set: modificador\n }\n );\n // retornar un resultado\n return result;\n }", "function UpdateTrainee() {\n let traineeToUpdate = {\n First_Name: $(\"#first_name\").val(), // firstName\n Last_Name: $(\"#last_name\").val(), // lastName\n User_Name: $(\"#user_name\").val(), // userName\n Trainee_Id: $(\"#id\").val(), // id\n Password: $(\"#password\").val(), // password\n Phone_Number: $(\"#phone_number\").val(), // phoneNumber\n Date_Of_Birth: $(\"#b_date\").val(), // birth date\n Gender: $(\"#gender option:selected\").text() == 'זכר' ? true : false, // gender\n Height: $(\"#height\").val(), // height\n Weight: $(\"#weight\").val(), // weight\n Address: $(\"#address\").val(), // address\n Amount_Of_Training_Per_Week: objUpdate.Amount_Of_Training_Per_Week,\n Perform_Exercises: objUpdate.Perform_Exercises,\n Training_Goal: objUpdate.Training_Goal,\n Fitness_Level: objUpdate.Fitness_Level,\n Body_Problem: objUpdate.Body_Problem\n };\n\n $.ajax({\n dataType: \"json\",\n url: \"/api/Trainee\",\n contentType: \"application/json\",\n method: \"PUT\",\n data: JSON.stringify(traineeToUpdate),\n success: function (data) {\n GetTrainee();\n },\n error: function (err) {\n if (err == false) {\n alert(\"שגיאה\");\n }\n }\n });\n\n // function get Trainee details\n function GetTrainee() {\n $.ajax({\n dataType: \"json\",\n url: `/api/Trainee/${$(\"#id\").val()}/${$(\"#password\").val()}`,\n contentType: \"application/json\",\n method: \"GET\",\n //data: JSON.stringify(),\n success: function (data) {\n let userObj = JSON.stringify({\n firstName: data.f_name,\n lastName: data.l_name,\n userName: data.user_name,\n id: data.id,\n password: data.password,\n phoneNumber: data.phone_number,\n birthDate: data.date_Of_birth,\n height: data.height,\n weight: data.weight,\n gender: data.gender,\n address: data.address,\n Amount_Of_Training_Per_Week: data.Amount_Of_Training_Per_Week,\n Perform_Exercises: data.Perform_Exercises,\n Training_Goal: data.Training_Goal,\n Fitness_Level: data.Fitness_Level,\n Body_Problem: data.Body_Problem\n });\n sessionStorage.setItem(\"userTrainee\", userObj); \n window.location.href = '../HomeScreenTrainee/HomeScreenTrainee.html';\n },\n error: function (err) {\n if (err.status == ERROR) {\n alert(\"שגיאה\");\n }\n }\n });\n }\n\n //console.log('alive');\n}", "function UpdateTrackById(req, res) {\n// Updates the artist by ID, get ID by req.params.artistId\n}", "update(numTarjeta, modificaciones) {\n return this.findOneAndUpdate({ numTarjeta: numTarjeta }, modificaciones, { multi: true });\n }", "function editLibraryMethod(req, res, libraryEncontrado, body) {\n updateLibrary(libraryEncontrado.id, body)\n .then((libraryUpdated) => {\n libraryUpdated ? RESPONSE.success(req, res, libraryUpdated, 200) : RESPONSE.error(req, res, 'No se puede modificar este libro.', 404);\n })\n .catch((err) => {\n console.log(err);\n return RESPONSE.error(req, res, 'Error Interno', 500);\n });\n}", "static async apiUpdatePostit(req, res, next) {\n try {\n const postitId = req.body._id;\n const title = req.body.title;\n const content = req.body.content;\n const deadline = req.body.deadline;\n const date = new Date();\n\n const postitEditRes = await PostitsDAO.editPostit(\n postitId,\n title,\n content,\n deadline,\n date,\n );\n \n var {error} = postitEditRes;\n if(error){\n res.status(400).json({error});\n }\n res.json({ status: \"Postit updated successfully !\" });\n } catch (e) {\n res.status(500).json({ error: e.message });\n }\n }", "update(req, res) {\n Origin.update(req.body, {\n where: {\n id: req.params.id\n }\n })\n .then(function (updatedRecords) {\n res.status(200).json(updatedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }", "function putToDos(id, data) {\n\n var defer = $q.defer();\n\n $http({\n method: 'PUT',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id,\n data: data\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n toastr.success('Updated ToDo List Item!');\n } else {\n defer.reject(response);\n //error if found but empty\n toastr.warning('Failure! </br>' + response.config.url);\n }\n },\n // failure\n function(error) {\n //error if the file isn't found\n defer.reject(error);\n $log.error(error);\n toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);\n });\n\n return defer.promise;\n }", "async update ({ params, request, response }) {\n const requestAll = request.all()\n\n const find = await Vagas.find(params.id)\n\n if(!find){\n response.status(404)\n return HelpersStatusCode.status404()\n }\n\n find.merge({...requestAll})\n\n await find.save()\n\n return HelpersStatusCode.status200()\n }", "async editMateri(req, res){\n try{\n const {fields} = await parseForm(req);\n await prisma.materi.update({\n where: { id: +req.params.id },\n data: {\n bagian: fields.bagian ?? undefined,\n judul: fields.judul ?? undefined,\n deskripsi: fields.deskripsi ?? undefined,\n embed: fields.embed ?? undefined\n }\n });\n res.json({message: 'Edit success'});\n }\n catch(err){\n console.log(err);\n res.status(500).json({message: 'Edit fail'});\n }\n }", "function put() {\n\n // Create a url for the ajax request.\n $.each(editObject, function(index, value) {\n if(index == 'id') {\n url += index+\"=\"+value;\n } else {\n url += \"&\"+index+\"=\"+value;\n }\n });\n\n $.ajax({\n url: 'api/?'+url,\n method: 'PUT',\n data: editObject,\n success: function() {\n // Log a message apon success.\n console.log(\"Item updated in inventory.\");\n\n // Reload the search from's select dropdowns and the table body.\n reloadSelectDropdowns();\n get();\n\n // Clear the url string.\n url = \"\";\n },\n error: function (xhr, ajaxOptions, thrownError) {\n // Log any error messages.\n console.log(xhr.status);\n console.log(thrownError);\n }\n });\n}", "static updateCustomer (id, body) {\n return axios.put(`${url}/${id}`, body)\n }", "function editFlightAddAssistant(id, changes) {\n return db(\"flight_info as f\")\n .where({ id })\n .update(changes);\n}", "function showTripDetailsToEdit(tripId) {\n\t$.ajax({\n\t\tmethod: 'GET',\n\t\turl: `/trips/${tripId}`,\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${authToken}`\n\t\t},\n\t\tcontentType: 'application/json',\n\t\tsuccess: function(trip) {\n\t\t\tconst startDate = formatDate(trip.startDate);\n\t\t\tconst endDate = formatDate(trip.endDate);\n\t\t\tconst content = `\n\t\t\t<div class=\"edit-trip-box \">\n\t\t\t\t<form class=\"edit-trip-form\" data-id=\"${trip._id}\">\n\t\t\t\t\t<fieldset>\n\t\t\t\t\t\t<legend>Edit Trip</legend>\n\t\t\t\t\t\t<label for=\"tripname\">Trip Name</label>\n\t\t\t\t\t\t<input type=\"text\" name=\"tripname\" value=\"${trip.name}\" class=\"trip-name\"><br>\n\t\t\t\t\t\t<label for=\"startdate\">Start Date</label>\n\t\t\t\t\t\t<input type=\"date\" name=\"startdate\" value=\"${startDate}\" class=\"start-date\"><br>\n\t\t\t\t\t\t<label for=\"enddate\">End Date</label>\n\t\t\t\t\t\t<input type=\"date\" name=\"enddate\" value=\"${endDate}\" class=\"end-date\"><br>\n\t\t\t\t\t\t<label for=\"country\">Country</label>\n\t\t\t\t\t\t<input type=\"text\" name=\"country\" value=\"${trip.country}\" class=\"country\"><br>\n\t\t\t\t\t\t<p class=\"trip-description\">\n\t\t\t\t\t\t\t<label for='trip-desc'>Trip Description</label>\n\t\t\t\t\t\t\t<textarea id=\"trip-desc\" rows=\"9\" cols=\"50\" class=\"description\">${trip.description}</textarea>\n\t\t\t\t\t\t</p>\n\t\t\t\t\t\t<input type=\"submit\" class=\"update-trip-button form-button\" value=\"Update\">\n\t\t\t\t\t\t<input type=\"button\" class=\"cancel-edit-trip form-button\" value=\"Cancel\">\n\t\t\t\t\t</fieldset>\n\t\t\t\t</form>\t\n\t\t\t</div>\n\t\t`\n\t\t$('main').html(content);\n\n\t\t},\n\t\terror: function(err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t})\t\n}", "async update(req,res){\n try {\n\n let params = req.allParams();\n let attr = {};\n if(params.name){\n attr.name = params.name;\n }\n if(params.description){\n attr.description = params.description;\n }\n \n const departmentById = await Department.update({\n id: req.params.department_id\n }, attr);\n return res.ok(departmentById);\n\n } catch (error) {\n return res.serverError(error);\n }\n }", "async sendUpdateTodo (context, todo) {\n console.log(todo)\n try {\n const response = await fetch('https://ap-todo-list.herokuapp.com/updateTodo', {\n method: 'PATCH',\n body: JSON.stringify(todo),\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n await response\n } catch (error) {\n console.error(error)\n }\n }", "update(req, res) {\n return Education\n .find({\n where: {\n id: req.params.educationId,\n resumeId: req.params.resumeId,\n },\n })\n .then(education => {\n if (!education) {\n return res.status(404).send({\n message: 'education Not Found',\n });\n }\n \n return education\n .update(req.body, { fields: Object.keys(req.body) })\n\n .then(updatedEducation => res.status(200).send(updatedEducation))\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n }", "async function update(req, res) {\n await Habit.findByIdAndUpdate(req.params.id, req.body, {\n new: true\n }, function (err, habit) {\n res.json(habit);\n\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the following are useful functions for making it easy to display an applet
function drawApplet(id, archive, mainClass, params, width, height) { var str=''; str+='<!--[if !IE]>--><object id="' + id + '" classid="java:' + mainClass + '.class"'; str+=' type="application\/x-java-applet"'; str+=' archive="' + archive + '"'; str+=' height="' + height + '" width="' + width + '" >'; str+=' <!-- Konqueror browser needs the following param -->'; str+=' <param name="archive" value="' + archive + '" \/>'; str+= params str+=' <!--<![endif]-->'; str+=' <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"'; str+=' id="' + id + '" height="' + height + '" width="' + width + '" >'; str+=' <param name="code" value="' + mainClass + '" \/>'; str+=' <param name="archive" value="' + archive + '" \/>'; str+= params str+=' <\/object>'; str+=' <!--[if !IE]>-->'; str+=' <\/object>'; str+=' <!--<![endif]-->'; document.write(str); }
[ "function showConfig() {\n\ttheApplet.showConfiguration();\n}", "function invokejava(img)\n{\n var par = img.parentNode;\n var p = document.createElement('div');\n p.innerHTML = '<applet code=\"' + img.alt\n + '\" width=\"' + img.width + '\" height=\"' + img.height + '\"></applet>';\n par.replaceChild(p, img);\n}", "function applet_setup() {\n for (key in applet_subs) {\n sub = applet_subs[key];\n if (typeof(applet[sub]) == 'undefined') {\n eval('applet.' + sub + '=function() {};');\n }\n }\n}", "function iefixNindexi1f1() {\r\n document.write('<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"100%\" height=\"100%\">\\n')\r\n document.write(' <param name=\"movie\" value=\"lab1.swf\">\\n')\r\n document.write(' <param name=\"quality\" value=\"high\">\\n')\r\n document.write(' <embed src=\"lab1.swf\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"100%\" height=\"100%\"></embed></object>\\n')\r\n\r\n}", "function showembed(){\n document.getElementById('hideembed').style.visibility=\"hidden\";\n document.getElementById('hideembed').style.display=\"none\";\n document.getElementById('showembed').style.display=\"block\";\n document.getElementById('showembed').style.visibility=\"visible\";\n document.getElementById('embed').innerHTML=\"<a style=\\\"cursor:pointer;\\\" onClick=\\\"hideembed()\\\"><img src=\\\"addons/mw_eclipse/skin/images/icons/icon_share.png\\\" align=\\\"absmiddle\\\" />&nbsp;Share / Embed<\\/a>\";\n\n}", "display()\r\n {\r\n image(this.image,this.x, this.y, this.w,this.h);\r\n }", "function mySnippet(){\n\t//The local-independent name (aka \"key string\") for the \n\t//Layout context menu is \"$ID/RtMouseLayout\".\n\tvar myLayoutContextMenu = app.menus.item(\"$ID/RtMouseLayout\");\n\t//Create the event handler for the \"beforeDisplay\" event of the Layout context menu.\n\tvar myBeforeDisplayListener = myLayoutContextMenu.addEventListener(\"beforeDisplay\", myBeforeDisplayHandler, false);\n\t//This event handler checks the type of the selection.\n\t//If a graphic is selected, the event handler adds the script menu action to the menu.\n\tfunction myBeforeDisplayHandler(myEvent){\n\t\t//Check for open documents is a basic sanity check--\n\t\t//it should never be needed, as this menu won't be\n\t\t//displayed unless an item is selected. But it's best\n\t\t//to err on the side of safety.\n\t\tif(app.documents.length != 0){\n\t\t\tif(app.selection.length > 0){\n\t\t\t\tvar myObjectList = new Array;\n\t\t\t\t//Does the selection contain any graphics?\n\t\t\t\tfor(var myCounter = 0; myCounter < app.selection.length; myCounter ++){\n\t\t\t\t\tswitch(app.selection[myCounter].constructor.name){\n\t\t\t\t\t\tcase \"PDF\":\n\t\t\t\t\t\tcase \"EPS\":\n\t\t\t\t\t\tcase \"Image\":\n\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"Rectangle\":\n\t\t\t\t\t\tcase \"Oval\":\n\t\t\t\t\t\tcase \"Polygon\":\n\t\t\t\t\t\t\tif(app.selection[myCounter].graphics.length != 0){\n\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter].graphics.item(0));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(myObjectList.length > 0){\n\t\t\t\t\t//Add the menu item if it does not already exist.\n\t\t\t\t\tif(myCheckForMenuItem(myLayoutContextMenu, \"Create Graphic Label\") == false){\n\t\t\t\t\t\tmyMakeLabelGraphicMenuItem();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//Remove the menu item, if it exists.\n\t\t\t\t\tif(myCheckForMenuItem(myLayoutContextMenu, \"Create Graphic Label\") == true){\n\t\t\t\t\t\tmyLayoutContextMenu.menuItems.item(\"Create Graphic Label\").remove();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfunction myCheckForMenuItem(myMenu, myString){\n\t\t\tvar myResult = false;\n\t\t\ttry{\n\t\t\t\tvar myMenuItem = myMenu.menuItems.item(myString);\n\t\t\t\tmyMenuItem.name;\n\t\t\t\tmyResult = true\n\t\t\t}\n\t\t\tcatch(myError){}\n\t\t\treturn myResult;\n\t\t}\n\t\tfunction myCheckForScriptMenuItem(myString){\n\t\t\tvar myResult = false;\n\t\t\ttry{\n\t\t\t\tvar myScriptMenuAction = app.scriptMenuActions.item(myString);\n\t\t\t\tmyScriptMenuAction.name;\n\t\t\t\tmyResult = true\n\t\t\t}\n\t\t\tcatch(myError){}\n\t\t\treturn myResult;\t\t\t\n\t\t}\n\t\tfunction myMakeLabelGraphicMenuItem(){\n\t\t\tif(myCheckForScriptMenuItem(\"Create Graphic Label\") == false){\n\t\t\t\tvar myLabelGraphicMenuAction = app.scriptMenuActions.add(\"Create Graphic Label\");\n\t\t\t\tvar myLabelGraphicEventListener = myLabelGraphicMenuAction.eventListeners.add(\"onInvoke\", myLabelGraphicEventHandler, false);\n\t\t\t}\n\t\t\tvar myLabelGraphicMenuItem = app.menus.item(\"$ID/RtMouseLayout\").menuItems.add(app.scriptMenuActions.item(\"Create Graphic Label\"));\n\t\t\tfunction myLabelGraphicEventHandler(myEvent){\n\t\t\t\tif(app.selection.length > 0){\n\t\t\t\t\tvar myObjectList = new Array;\n\t\t\t\t\t//Does the selection contain any graphics?\n\t\t\t\t\tfor(var myCounter = 0; myCounter < app.selection.length; myCounter ++){\n\t\t\t\t\t\tswitch(app.selection[myCounter].constructor.name){\n\t\t\t\t\t\t\tcase \"PDF\":\n\t\t\t\t\t\t\tcase \"EPS\":\n\t\t\t\t\t\t\tcase \"Image\":\n\t\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"Rectangle\":\n\t\t\t\t\t\t\tcase \"Oval\":\n\t\t\t\t\t\t\tcase \"Polygon\":\n\t\t\t\t\t\t\t\tif(app.selection[myCounter].graphics.length != 0){\n\t\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter].graphics.item(0));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(myObjectList.length > 0){\n\t\t\t\t\t\tmyDisplayDialog(myObjectList);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Function that adds the label.\n\t\t\t\tfunction myAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyleName, myLayerName){\n\t\t\t\t\tvar myLabelLayer;\n\t\t\t\t\tvar myDocument = app.documents.item(0);\n\t\t\t\t\tvar myLabel;\n\t\t\t\t\tmyLabelStyle = myDocument.paragraphStyles.item(myLabelStyleName);\n\t\t\t\t\tvar myLink = myGraphic.itemLink;\n\t\t\t\t\ttry{\n\t\t\t\t\t\tmyLabelLayer = myDocument.layers.item(myLayerName);\n\t\t\t\t\t\t//If the layer does not exist, trying to get the layer name will cause an error.\n\t\t\t\t\t\tmyLabelLayer.name;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (myError){\n\t\t\t\t\t\tmyLabelLayer = myDocument.layers.add(myLayerName); \n\t\t\t\t\t} \n\t\t\t\t\t//Label type defines the text that goes in the label.\n\t\t\t\t\tswitch(myLabelType){\n\t\t\t\t\t\t//File name\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tmyLabel = myLink.name;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//File path\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tmyLabel = myLink.filePath;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//XMP description\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tmyLabel = myLink.linkXmp.description;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch(myError){\n\t\t\t\t\t\t\t\tmyLabel = \"No description available.\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//XMP author\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tmyLabel = myLink.linkXmp.author\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch(myError){\n\t\t\t\t\t\t\t\tmyLabel = \"No author available.\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tvar myFrame = myGraphic.parent;\n\t\t\t\t\tvar myX1 = myFrame.geometricBounds[1]; \n\t\t\t\t\tvar myY1 = myFrame.geometricBounds[2] + myLabelOffset; \n\t\t\t\t\tvar myX2 = myFrame.geometricBounds[3]; \n\t\t\t\t\tvar myY2 = myY1 + myLabelHeight;\n\t\t\t\t\tvar myTextFrame = myFrame.parent.textFrames.add(myLabelLayer, undefined, undefined,{geometricBounds:[myY1, myX1, myY2, myX2], contents:myLabel}); \n\t\t\t\t\tmyTextFrame.textFramePreferences.firstBaselineOffset = FirstBaseline.leadingOffset; \n\t\t\t\t\tmyTextFrame.paragraphs.item(0).appliedParagraphStyle = myLabelStyle;\t\t\t\t\n\t\t\t\t}\n\t\t\t\tfunction myDisplayDialog(myObjectList){\n\t\t\t\t\tvar myLabelWidth = 100;\n\t\t\t\t\tvar myStyleNames = myGetParagraphStyleNames(app.documents.item(0));\n\t\t\t\t\tvar myLayerNames = myGetLayerNames(app.documents.item(0));\n\t\t\t\t\tvar myDialog = app.dialogs.add({name:\"LabelGraphics\"});\n\t\t\t\t\twith(myDialog.dialogColumns.add()){\n\t\t\t\t\t\t//Label type\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Type\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelTypeDropdown = dropdowns.add({stringList:[\"File name\", \"File path\", \"XMP description\", \"XMP author\"], selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Text frame height\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Height\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelHeightField = measurementEditboxes.add({editValue:24, editUnits:MeasurementUnits.points});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Text frame offset\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Offset\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelOffsetField = measurementEditboxes.add({editValue:0, editUnits:MeasurementUnits.points});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Style to apply\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Style\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelStyleDropdown = dropdowns.add({stringList:myStyleNames, selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Layer\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Layer:\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLayerDropdown = dropdowns.add({stringList:myLayerNames, selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvar myResult = myDialog.show();\n\t\t\t\t\tif(myResult == true){\n\t\t\t\t\t\tvar myLabelType = myLabelTypeDropdown.selectedIndex;\n\t\t\t\t\t\tvar myLabelHeight = myLabelHeightField.editValue;\n\t\t\t\t\t\tvar myLabelOffset = myLabelOffsetField.editValue;\n\t\t\t\t\t\tvar myLabelStyle = myStyleNames[myLabelStyleDropdown.selectedIndex];\n\t\t\t\t\t\tvar myLayerName = myLayerNames[myLayerDropdown.selectedIndex];\n\t\t\t\t\t\tmyDialog.destroy();\n\t\t\t\t\t\tvar myOldXUnits = app.documents.item(0).viewPreferences.horizontalMeasurementUnits;\n\t\t\t\t\t\tvar myOldYUnits = app.documents.item(0).viewPreferences.verticalMeasurementUnits;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;\n\t\t\t\t\t\tfor(var myCounter = 0; myCounter < myObjectList.length; myCounter++){\n\t\t\t\t\t\t\tvar myGraphic = myObjectList[myCounter];\n\t\t\t\t\t\t\tmyAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyle, myLayerName);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.horizontalMeasurementUnits = myOldXUnits;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.verticalMeasurementUnits = myOldYUnits;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tmyDialog.destroy();\n\t\t\t\t\t}\n\t\t\t\t\tfunction myGetParagraphStyleNames(myDocument){\n\t\t\t\t\t\tvar myStyleNames = myDocument.paragraphStyles.everyItem().name;\n\t\t\t\t\t\treturn myStyleNames;\n\t\t\t\t\t}\n\t\t\t\t\tfunction myGetLayerNames(myDocument){\n\t\t\t\t\t\tvar myLayerNames = new Array;\n\t\t\t\t\t\tvar myAddLabelLayer = true;\n\t\t\t\t\t\tfor(var myCounter = 0; myCounter<myDocument.layers.length; myCounter++){\n\t\t\t\t\t\t\tmyLayerNames.push(myDocument.layers.item(myCounter).name);\n\t\t\t\t\t\t\tif (myDocument.layers.item(myCounter).name == \"Labels\"){\n\t\t\t\t\t\t\t\tmyAddLabelLayer = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(myAddLabelLayer == true){\n\t\t\t\t\t\t\tmyLayerNames.push(\"Labels\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn myLayerNames;\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}", "function displayStrawCup1() {\n image(strawCup1Img, 0, 0, 1000, 500);\n}", "function displayInstructions() {\n textAlign(CENTER);\n textSize(12);\n textFont('Georgia');\n \n fill(\"white\");\n text(\"DIG FOR TREASURE! PRESS 'T' TO SWITCH TOOLS - FIND ALL TREASURE BEFORE YOU RUN OUT OF ENERGY\", width/2, height - 30);\n}", "function happycol_presentation_theShow(args){\n\tif(args.stageManager==true){\n\t\thappycol_stageManager(args);\n\t}\n}", "function drawIntro(){\n\t\n}", "function displayIntro() {\n image(introImages[introIndex], 0, 0, windowWidth, windowHeight);\n}", "static show()\n {\n let aeComputers = Component.getElementsByClass(document, PCx86.APPCLASS, \"computer\");\n for (let iComputer = 0; iComputer < aeComputers.length; iComputer++) {\n let eComputer = aeComputers[iComputer];\n let parmsComputer = Component.getComponentParms(eComputer);\n let computer = /** @type {Computer} */ (Component.getComponentByType(\"Computer\", parmsComputer['id']));\n if (computer) {\n\n /*\n * Clear new flag that Component functions (eg, notice()) should check before alerting the user.\n */\n computer.flags.unloading = false;\n\n if (DEBUG) computer.printf(\"onShow(%b,%b)\\n\", computer.flags.initDone, computer.flags.powered);\n\n if (computer.flags.initDone && !computer.flags.powered) {\n /*\n * Repower the computer, notifying every component to continue running as-is.\n */\n computer.powerOn(Computer.RESUME_REPOWER);\n }\n }\n }\n }", "function GameScreenAssistant() { }", "function null_painter(frame){\n // nothing-to-do\n}", "function displayPaddle(paddle) {\n rect(paddle.x, paddle.y, paddle.w, paddle.h);\n}", "function showAttributions() {\n document.body.innerHTML = '';\n document.body.appendChild(createAttributionContent());\n}", "function displayInfoElement()\n{\n\t//info element\n\tvar IEsquare = new createjs.Shape();\n\tIEsquare.graphics.beginStroke(\"Black\").drawRect(0, 0, 350, 46);\n\tIEsquare.x = 325;\n\tIEsquare.y = 0;\n\tIEsquare.name = \"IEsquare\";\n\tstage.addChild(IEsquare);\n\tupdateInfoText();\n}", "function addGraphicsToLayout()\r{\r var xmlElement = app.activeDocument.xmlElements[0];\r var pageLinkTags = xmlElement.evaluateXPathExpression(\"/Root/page\");\r $.writeln(\"# of tags: \" + pageLinkTags.length);\r for (var x = 0; x < pageLinkTags.length; x++)\r {\r var xmlElement = pageLinkTags[x];\r var tagName = xmlElement.markupTag.name;\r $.writeln(\"xml tag: \" + tagName);\r var pageNameTags = xmlElement.evaluateXPathExpression(\"/page/pageName\");\r if (pageNameTags.length > 0) {\r var pageNameTag = pageNameTags[0];\r var pageNumber = pageNameTag.contents;\r $.writeln(\"page#: \" + pageNumber);\r var page = app.activeDocument.pages.itemByName(pageNumber);\r if (page.textFrames.length > 0) {\r var myTextFrame = page.textFrames[0];\r } else {\r $.writeln(\"ERROR: No Text Frame on page\");\r }\r var imageLinkTags = xmlElement.evaluateXPathExpression(\"/page/graphic/imageLink\");\r for (var y = 0; y < imageLinkTags.length; y++)\r {\r var imageLinkTag = imageLinkTags[y];\r $.writeln(\"imageLink: \" + xmlElement.contents);\r // TO DO !!! UN Hard Code the following path\r var imagePath = \"/Users/scottrichards/Documents/BIP/\" + docData.selectedDocFileName + \"/\" + imageLinkTag.contents;\r $.writeln(\"placing image: \" + imagePath);\r myTextFrame.insertionPoints.item(-1).place(imagePath); \r }\r } \r }\r}", "function show_icn_pad() {\n if (wiki_items.length==0 && news_items.length==0)\n\treturn;\n $('#icn_pad').toggle(300);\n $('#icn_ticker_tape').toggle();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply vat on existing paragraphs
function vat_on_paragraphs () { $('p.vat:not(:has(.vat-disclaimer))').each(function(){ startingPrice = parseFloat($(this).attr('data-price')); if(! isNaN(startingPrice)) { text = $(this).text(); match = text.match(/([0-9]{1,3}[,.])+[0-9]+/g); text = text.split(match[0]); if (!vat['show']) { startingPrice = startingPrice * vat['quote']; } price = (startingPrice).toFixed(2).split('.'); price[0] = digitNumberFormat(price[0]); dec = ',' + price[1]; if ($(this).hasClass('noDec') && price[1] < 1) { dec = ''; } price = price[0] + dec; $(this).text(text[0] + price + text[1]); } }); }
[ "function generateParagraph() {\n // Clear the current text\n $('#content').text('');\n // Generate ten sentences for our paragraph\n // (Output is an array)\n let sentenceArray = markov.generateSentences(20);\n // Turn the array into a single string by joining with spaces\n let sentenceText = sentenceArray.join(' ');\n // Put the new text onto the page\n $('#content').append(sentenceText);\n}", "function changePara() {\n\tlet x = document.getElementsByTagName('P');\n\tfor (let i = 0; i < x.length; i++) {\n\t\tx[i].style.fontFamily = \"lato\";\n\t}\n}", "function createPara(inrTxt,t = false) {\r\n const elem = document.createElement(`p`);\r\n elem.innerText = `${inrTxt}`;\r\n elem.contentEditable = t;\r\n active.paragraphs.push({\r\n e: elem\r\n });\r\n }", "function addParagraph(text) {\n // code goes here\n const paraGraph = document.createElement('p');\n paragraphListElement.appendChild(paraGraph).innerText = `${text}`;\n}", "function styles_ptags(){\n $(\"#modu_main\").find(\"p\").each(function(){\n if($(this).attr(\"class\")===undefined)\n {\n $(this).css(\"padding\",\"0px\");\n $(this).css(\"margin\",\"0px\");\n }else{\n if($(this).attr(\"class\").search(\"bexi_editor\")!==-1){\n $(this).css(\"padding\",\"0px\");\n $(this).css(\"margin\",\"0px\");\n }\n }\n });\n}", "function readParagraphs() \n{\n if ((xhrContent.readyState === 4) && (xhrContent.status === 200)) \n {\n let MyContent = JSON.parse(xhrContent.responseText);\n let paragraphs = MyContent.paragraphs;\n paragraphs.forEach(function (paragraph) \n {\n let paragraphElements = document.getElementById(paragraph.id);\n //Searches element ids and aligns them with suitable paragraphs in the html\n if(paragraphElements) \n {\n paragraphElements.innerHTML = paragraph.content;\n } \n }, this);\n }\n}", "function generateLoremIpsum() {\n var number = parseInt(numOfParagraphs.value);\n var text = lorem.generateParagraphs(number);\n loremIpsumText.innerText = text;\n}", "function changeFirstParagraph() {\n $(document).ready(function() {\n $(\"div#test5 p\").eq(0).css(\"font-family\",\"Times New Roman, Times, serif\");\n $(\"div#test5 p\").eq(0).css(\"font-size\",\"20px\");\n });\n}", "function approveClassForPara(documentId, classId, paraId) {\n //get a filtered list\n var terms = LHSModel.getParagraphsForClass(classId, paraId);\n return documentService.updateTerms(documentId, terms);\n }", "function Phrase(options) {\r\n\r\n\tthis.lire = function () {\r\n\t\treturn this.corps;\r\n\t};\r\n\r\n\tthis.__assembler = function (texte) {\r\n\t\tvar resultat = texte.join(\" \");\r\n\t\tvar point = probaSwitch(Grimoire.recupererListe(\"PF\"), this.PROBA_POINT_FINAL);\r\n\t\tresultat = resultat.replace(/ \\,/g, \",\");\r\n\t\tresultat = resultat.replace(/' /g, \"'\");\r\n\t\tresultat = resultat.replace(/à les /g, \"aux \");\r\n\t\tresultat = resultat.replace(/à le /g, \"au \");\r\n\t\tresultat = resultat.replace(/ de ([aeiouhéèêàùäëïöü])/gi, \" d'$1\");\r\n\t\tresultat = resultat.replace(/ de les /g, \" des \");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([aeiouéèêàîïùyh])/gi, \" d'$2\");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([^aeiouéèêàîïùyh])/gi, \" de $2\");\r\n\t\tresultat = resultat.replace(/ de d'/g, \" d'\");\r\n\t\tresultat = resultat.replace(/ de (le|du) /g, \" du \");\r\n\t\tresultat = resultat.replace(/^(.*)je ([aeiouéèêàîïùyh])/i, \"$1j'$2\");\r\n\t\tresultat = resultat.replace(/£/g, \"h\").replace(/µ/g, \"Y\");\r\n\t\tresultat = resultat.substr(0, 1).toUpperCase() + resultat.substr(1) + point;\r\n\t\treturn resultat;\r\n\t};\r\n\r\n\toptions || (options = {});\r\n\tthis.PROBA_POINT_FINAL = [8, 1, 1];\r\n\r\n\tthis.structure = options.memeStr || Grimoire.genererStructure();\r\n\tthis.mots = [];\r\n\r\n\tvar posVerbe = -1, posVerbe2 = -1, posModal = -1, posDe = -1, posQue = -1, posPR = -1;\r\n\tvar personne = 0, temps = -1;\r\n\tvar premierGN = false, advPost = false, flagNoNeg = false;\r\n\r\n\t/* --- BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tfor (var i = 0, iMax = this.structure.length; i < iMax; ++i) {\r\n\t\tif (this.structure[i].substr(0, 1) == \"§\") {\r\n\t\t\tvar litteral = this.structure[i].substr(1);\r\n\t\t\tif (litteral.indexOf(\"/\") > -1) {\r\n\t\t\t\tlitteral = litteral.split(\"/\")[(de(2) - 1)];\r\n\t\t\t}\r\n\t\t\tthis.mots.push(litteral);\r\n\t\t\tif (litteral == \"sans\") {\r\n\t\t\t\tflagNoNeg = true;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvar mot;\r\n\t\t\tif (this.structure[i] == \"GN\") {\r\n\t\t\t\tif (options.sujetChoisi && !premierGN) {\r\n\t\t\t\t\tmot = options.sujetChoisi;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\t\tmot = Generateur.groupeNominal(premierGN);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpremierGN = true;\r\n\t\t\t} else if (this.structure[i] == \"CO\") {\r\n\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\tmot = Generateur.complementObjet(personne);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t}\r\n\t\t\tvar posPersonne = mot.indexOf(\"@\");\r\n\t\t\tif (posPersonne > -1) {\r\n\t\t\t\tpersonne = (personne > 0) ? personne : parseInt(mot.substr(posPersonne + 1), 10);\r\n\t\t\t\tmot = mot.substr(0, posPersonne);\r\n\t\t\t}\r\n\t\t\tthis.mots.push(mot);\r\n\t\t}\r\n\t\tvar verbesNonMod = [\"VT\", \"VN\", \"VOA\", \"VOD\", \"VOI\", \"VTL\", \"VAV\", \"VET\", \"VOS\"];\r\n\t\tvar verbesMod = [\"VM\", \"VD\", \"VA\"];\r\n\t\tif (verbesNonMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tif (posVerbe > -1) {\r\n\t\t\t\tif (posModal > -1) {\r\n\t\t\t\t\tposVerbe2 = i;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tposModal = posVerbe;\r\n\t\t\t\t\tposVerbe = i;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tposVerbe = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (verbesMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tposModal = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"§que\") {\r\n\t\t\tposQue = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"CT\") {\r\n\t\t\tvar posTemps = this.mots[i].indexOf(\"€\");\r\n\t\t\tif (posTemps > -1) {\r\n\t\t\t\ttemps = parseInt(this.mots[i].substr(posTemps + 1), 10);\r\n\t\t\t\tthis.mots[i] = this.mots[i].substr(0, posTemps);\r\n\t\t\t}\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"AF\")) {\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t\twhile (this.mots[i].indexOf(\"+\") > -1) {\r\n\t\t\t\tvar posPlus = this.mots[i].indexOf(\"+\");\r\n\t\t\t\tvar fem = this.mots[i].charAt(posPlus + 1) == \"F\";\r\n\r\n\t\t\t\tvar nom, ok;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tok = true;\r\n\t\t\t\t\tnom = Generateur.GN.nomsCommuns.puiser();\r\n\t\t\t\t\tif (nom.indexOf(\"_\") > -1) {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"_\");\r\n\t\t\t\t\t\tvar genre = nom.charAt(pos + 1);\r\n\t\t\t\t\t\tif (!fem && (genre == \"F\") || (fem && genre == \"H\")) {\r\n\t\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tnom = nom.split(\"_\")[0];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"%\");\r\n\t\t\t\t\t\tif (nom.substr(pos + 1).length == 1) {\r\n\t\t\t\t\t\t\tnom = nom.replace(/(.*)%e/, \"$1%$1e\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnom = nom.split(\"%\")[((fem) ? 1 : 0)];\r\n\t\t\t\t\t}\r\n\t\t\t\t} while ((!ok) || (nom === undefined));\r\n\t\t\t\tnom = Generateur.accordPluriel(nom, false);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\+[FH]/, nom);\r\n\t\t\t}\r\n\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"CT\") || (this.structure[i] == \"AF\")) {\r\n\t\t\tvar nombre;\r\n\t\t\twhile (this.mots[i].indexOf(\"&\") > -1) {\r\n\t\t\t\tnombre = de(10) + 1;\r\n\t\t\t\tif (this.mots[i].indexOf(\"&0\") > -1) {\r\n\t\t\t\t\tnombre = (nombre * 10) - 10;\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mots[i].indexOf(\"&00\") > -1) {\r\n\t\t\t\t\tnombre *= 10;\r\n\t\t\t\t}\r\n\t\t\t\tnombre = nombre.enLettres();\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/&(0){0,2}/, nombre);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.structure[i].split(\"_\")[0] == \"PR\") {\r\n\t\t\tposPR = i;\r\n\t\t}\r\n\t}\r\n\t/* --- FIN DE LA BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tif (temps == -1)\r\n\t\ttemps = (de(2) > 1) ? 2 : de(3);\r\n\r\n\tif (posQue > -1) {\r\n\t\tthis.mots[posQue] = (this.mots[posQue + 1].voyelle()) ? \"qu'\" : \"que\";\r\n\t}\r\n\tif (posPR > -1) {\r\n\t\tvar tPers = 2;\r\n\t\tif ((/^s(\\'|e )/).test(this.mots[posPR])) {\r\n\t\t\ttPers = [2, personne];\r\n\t\t}\r\n\t\tvar neg1 = \"\", neg2 = \"\";\r\n\t\tif ((!flagNoNeg) && (de(9) > 8)) {\r\n\t\t\tneg1 = (this.mots[posPR].voyelle()) ? \"n'\" : \"ne \";\r\n\t\t\tneg2 = \" \" + probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t}\r\n\t\tthis.mots[posPR] = \"en \" + neg1 + Grimoire.conjuguer(this.mots[posPR], 4, tPers) + neg2;\r\n\t}\r\n\r\n\tif (posModal > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posModal], temps, personne);\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posModal] = baseVerbe;\r\n\r\n\t\tif (this.mots[posVerbe].indexOf(\"#\") > -1) {\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].split(\"#\")[0];\r\n\t\t}\r\n\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe])) {\r\n\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\tif ((this.mots[posVerbe].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t}\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].replace(/s(\\'|e )/, pr);\r\n\t\t}\r\n\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tthis.mots[posVerbe] = \"ne \" + neg2 + \" \" + this.mots[posVerbe];\r\n\t\t}\r\n\t\tif (posVerbe2 > -1) {\r\n\t\t\tif (this.mots[posVerbe2].indexOf(\"#\") > -1) {\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].split(\"#\")[0];\r\n\t\t\t}\r\n\t\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe2])) {\r\n\t\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\t\tif ((this.mots[posVerbe2].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].replace(/s(\\'|e )/, pr);\r\n\t\t\t}\r\n\t\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\t\tthis.mots[posVerbe2] = \"ne \" + neg2 + \" \" + this.mots[posVerbe2];\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (posVerbe > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posVerbe], temps, personne);\r\n\t\tif (baseVerbe === undefined)\r\n\t\t\treturn new Phrase(options);// et sa copine\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posVerbe] = baseVerbe;\r\n\t}\r\n\r\n\tthis.corps = this.__assembler(this.mots);\r\n\treturn this;\r\n}", "function vat_on_span () {\n $('span.vat:not(.related):not(.relative)').each(function(){\n var obj = $(this);\n\n if(obj.hasClass('on-length')){\n if(obj.closest('.length, .configurator, .summary').length){\n var price = obj.get_price('data-price-length-unit');\n }else{\n var price = obj.get_price();\n }\n }else{\n var price = obj.get_price();\n }\n\n\n if(price == 0)\n return ;\n\n $(this).html(create_vatted_price(price, check_prices_follow_ups(obj), obj.hasClass('noDec')));\n });\n\n $('span.vat.related').each(function () {\n var obj = $(this),\n percent = $('.vat_percent[data-relation=\"' + obj.attr('data-relation') + '\"]'),\n relative_from = $('[data-relation=\"' + obj.attr('data-relation') + '\"][data-role=\"from\"]'),\n relative_to = $('[data-relation=\"' + obj.attr('data-relation') + '\"][data-role=\"to\"]'),\n priceFrom = relative_from.get_price('data-target'),\n priceTo = (priceFrom * vat_quote).toFixed(2);\n\n obj.text($.imperial_to_metric((priceFrom * parseFloat((vat_quote - 1))).toFixed(2)));\n relative_to.text($.imperial_to_metric(priceTo));\n\n if(percent.length){\n var vat_percent = vat_quote * 100 - 100;\n percent.text(vat_percent);\n }\n });\n }", "function updateParagraph() {\n // get all of the input values\n let textColor = document.getElementById('textColor').value;\n let fontSize = document.getElementById('fontSize').value;\n let backgroundColor = document.getElementById('backgroundColor').value;\n let fontStyle = document.getElementById('fontStyle').value;\n let fontWeight = document.getElementById('fontWeight').value;\n\n funParagraph.style.color = textColor ? textColor : '';\n funParagraph.style.fontSize = fontSize ? fontSize : '';\n funParagraph.style.backgroundColor = backgroundColor ? backgroundColor : '';\n funParagraph.style.fontStyle = fontStyle ? fontStyle : '';\n funParagraph.style.fontWeight = fontWeight ? fontWeight : '';\n}", "function DocEdit_processNewEdit(index)\n{\n var dom = dw.getDocumentDOM();\n var allSBs = dw.serverBehaviorInspector.getServerBehaviors();\n\n\n if (this.weight==\"beforeNode\")\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n\n this.insertPos = nodeOffsets[0];\n this.replacePos = nodeOffsets[0];\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight==\"replaceNode\")\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n\n this.insertPos = nodeOffsets[0];\n this.replacePos = nodeOffsets[1];\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight==\"afterNode\")\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n\n this.insertPos = nodeOffsets[1];\n this.replacePos = nodeOffsets[1];\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight.indexOf(\"firstChildOfNode\") == 0)\n {\n if (this.node.nodeType == Node.ELEMENT_NODE)\n {\n if (this.node.hasChildNodes())\n {\n var childNodeOffsets = dwscripts.getNodeOffsets(this.node.childNodes[0]);\n this.insertPos = childNodeOffsets[0];\n this.replacePos = childNodeOffsets[0];\n }\n else\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n var nodeHTML = dwscripts.getOuterHTML(this.node);\n var tagName = dwscripts.getTagName(this.node);\n var pos = nodeHTML.search(RegExp(\"<\\\\/\"+tagName+\">\",\"i\"));\n if (pos == -1)\n {\n pos = nodeHTML.indexOf(\"</\");\n }\n pos += nodeOffsets[0];\n this.insertPos = pos;\n this.replacePos = pos;\n }\n }\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight.indexOf(\"lastChildOfNode\") == 0)\n {\n if (this.node.nodeType == Node.ELEMENT_NODE)\n {\n if (this.node.hasChildNodes())\n {\n var last = this.node.childNodes.length - 1;\n var childNodeOffsets = dwscripts.getNodeOffsets(this.node.childNodes[last]);\n this.insertPos = childNodeOffsets[1];\n this.replacePos = childNodeOffsets[1];\n }\n else\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n var nodeHTML = dwscripts.getOuterHTML(this.node);\n var tagName = dwscripts.getTagName(this.node);\n var pos = nodeHTML.search(RegExp(\"<\\\\/\"+tagName+\">\",\"i\"));\n if (pos == -1)\n {\n pos = nodeHTML.indexOf(\"</\");\n }\n pos += nodeOffsets[0];\n this.insertPos = pos;\n this.replacePos = pos;\n }\n }\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight.indexOf(\"nodeAttribute\") == 0)\n {\n //nodeAttribute+ATTRIB (not numerically positioned)\n if (this.weightInfo && this.weightInfo.length)\n {\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n\n //get pos of attrib value\n var pos = extUtils.findAttributePosition(this.node, this.weightInfo);\n if (!pos) //if attrib doesn't exist\n {\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n pos = new Array();\n pos[0] = nodeOffsets[0] + dwscripts.getTagName(this.node).length + 1; //skip <tag\n pos[1] = pos[0];\n\n // change text to include entire attribute. use single quotes\n // if this is an ASP.NET document.\n if (dw.getDocumentDOM().documentType.indexOf(\"ASP.NET\") != -1){\n this.text = \" \" + this.weightInfo + \"='\" + this.text + \"'\";\n }else{ \n this.text = ' ' + this.weightInfo + '=\"' + this.text + '\"';\n }\n }\n\n //DEBUG alert(\"pos[0] = \" + pos[0] + \"\\ndwscripts.getNodeOffsets(this.node)[0] = \" + dwscripts.getNodeOffsets(this.node)[0] + \"\\npos[0] - pos of this.node[0] = \" + (pos[0]-dwscripts.getNodeOffsets(this.node)[0]) + \"\\n\" + dwscripts.getOuterHTML(this.node).charAt(pos[0] - (dwscripts.getNodeOffsets(this.node)[0]+1)));\n\n // if the attribute already exists, and its current value is surrounded by double\n // quotes, they need to be changed to single quotes if this is an ASP.NET document.\n if (dw.getDocumentDOM().documentType.indexOf(\"ASP.NET\") != -1 \n && dwscripts.getOuterHTML(this.node).charAt(pos[0] - (dwscripts.getNodeOffsets(this.node)[0]+1)) == '\"'){\n this.text = \"'\" + this.text + \"'\";\n this.insertPos = pos[0]-1;\n this.replacePos = pos[1]+1;\n }else{\n this.insertPos = pos[0];\n this.replacePos = pos[1];\n }\n }\n else //must be numbered position\n {\n //inserts into node tag. For example, you may want to change <option> to <option<%= if (foo)..%>>\n var nodeOffsets = dwscripts.getNodeOffsets(this.node);\n var pos = new Array();\n pos[0] = nodeOffsets[0] + dwscripts.getTagName(this.node).length + 1; //skip <tag\n pos[1] = pos[0];\n this.insertPos = pos[0];\n this.replacePos = pos[1];\n this.text = \" \" + dwscripts.trim(this.text); //precede with a space\n }\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.node, false);\n }\n }\n else if (this.weight==\"beforeSelection\")\n {\n sel = extUtils.getSelTableRowOffsets();\n if (!sel || sel.length == 0)\n {\n sel = dom.getSelection();\n }\n\n\tif (!sel || sel.length == 0)\n {\n this.insertPos = 0;\n\t this.replacePos = 0;\n }\n else\n {\n this.insertPos = sel[0];\n this.replacePos = sel[0];\n }\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, null, false);\n }\n }\n else if (this.weight==\"replaceSelection\")\n {\n sel = extUtils.getSelTableRowOffsets();\n if (!sel || sel.length == 0)\n {\n sel = dom.getSelection();\n }\n \n if (!sel || sel.length == 0)\n {\n\t this.insertPos = 0;\n\t this.replacePos = 0;\n\t}\n\telse\n\t{\n sel = this.removeSpaceFromTableCell(sel);\n\n this.insertPos = sel[0];\n this.replacePos = sel[1];\n }\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, null, false);\n }\n }\n else if (this.weight==\"afterSelection\")\n {\n sel = extUtils.getSelTableRowOffsets();\n if (!sel || sel.length == 0)\n {\n sel = dom.getSelection();\n }\n if (!sel || sel.length == 0)\n {\n\t this.insertPos = 0;\n\t this.replacePos = 0;\n\t}\n\telse\n\t{\n sel = this.removeSpaceFromTableCell(sel);\n\n this.insertPos = sel[0];\n this.replacePos = sel[1];\n }\n\n this.insertPos = sel[1];\n this.replacePos = sel[1];\n\n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, null, false);\n }\n }\n else if (this.weightType.indexOf(\"HTML\") != -1) //insert above or below HTML tag\n {\n // DEBUG alert(\"!inserting item of weight \"+this.weight+\":\\n\"+this.text);\n\n //This code was added to preserve the order of nodes with the same weight,\n //and requires that the caller add \"dummy\" nodes with null text: x.add(null,priorNode,weight).\n //If the node being added is followed by dummy nodes with the same weight,\n //stops before the next sibling. Look forward, and stop at the next node with the same weight.\n var stoppingNode = null;\n var stoppingNodeOffset = null;\n var foundStop = false;\n for (var i=index+1; i < docEdits.editList.length; i++) //with each object with something to insert\n {\n if (docEdits.editList[i].priorNode) //advance to next placeholder node\n {\n if (this.weight == docEdits.editList[i].weight)\n {\n stoppingNode = docEdits.editList[i].priorNode;\n stoppingNodeOffset = docEdits.editList[i].matchRangeMax;\n }\n break;\n }\n }\n\n var lighterWeight = 0;\n var lighterNode = 0;\n var lighterNodeOffset = null;\n\n //detect if there's an existing node with a lower weight, and add after it\n if (this.weightNum && index>0)\n {\n for (var i=0; i<index; i++) //with each object before this one\n {\n //if preceeded by a dummy node with a smaller weight of same type (above or belowHTML)\n if (docEdits.editList[i].priorNode &&\n docEdits.editList[i].weight &&\n docEdits.editList[i].weight.indexOf(this.weightType) == 0)\n {\n var partWeight = extUtils.getWeightNum(docEdits.editList[i].weight);\n\n //if that weight is smaller than mine, make that the lighter node\n if (partWeight < this.weightNum)\n {\n lighterWeight = partWeight;\n lighterNode = docEdits.editList[i].priorNode;\n lighterNodeOffset = docEdits.editList[i].matchRangeMax;\n }\n }\n }\n }\n\n //Search other participants for lighter nodes to add after\n for (var i=0; i < allSBs.length; i++)\n {\n // Guard against SB objects which do not have the properties we expect.\n if (allSBs[i].getParticipants)\n {\n //find insertion node\n var sbParts = allSBs[i].getParticipants();\n for (var k=0; k < sbParts.length; k++)\n {\n var partNodeSeg = sbParts[k].getNodeSegment();\n \n // Check if the given node segment is actually located above or below\n // the HTML tag in the document\n if (partNodeSeg.node && dw.nodeExists(partNodeSeg.node) &&\n dwscripts.isInsideTag(partNodeSeg.node,\"HTML\"))\n {\n continue; // we do not want to consider this node if it is located in the HTML\n }\n \n var partWeight = String(sbParts[k].getWeight());\n if (partWeight == String(parseInt(partWeight)))\n {\n partWeight = \"aboveHTML+\" + partWeight;\n }\n if ( stoppingNode && (partNodeSeg.node == stoppingNode)\n && (partNodeSeg.matchRangeMax == stoppingNodeOffset)\n )\n {\n foundStop = true; //don't go beyond stopping node\n continue;\n }\n else if (partWeight.indexOf(this.weightType)==0)\n { //if same type, keep looking for node above me\n var newWeight = extUtils.getWeightNum(sbParts[k].getWeight());\n\n //DEBUG alert(\"Checking part \"+k+\": \"+lighterWeight+\" (lighter) <= \"+newWeight+\" (new) <= \"+this.weightNum+\" (my weight)?\");\n\n if (newWeight && lighterWeight <= newWeight && (newWeight < this.weightNum\n || (!foundStop && newWeight == this.weightNum))) //heavier than LW, lighter than me\n {\n lighterWeight = newWeight;\n lighterNode = partNodeSeg.node;\n lighterNodeOffset = partNodeSeg.matchRangeMax;\n //DEBUG alert(\"Changing lighter weight to (new) \"+lighterWeight+\"\\n\"+unescape(lighterNode.orig));\n }\n }\n }\n }\n else\n { // Handle UD1 and UD4 Server Behavior objects\n //Search other participants for lighter nodes to add after\n for (k=0; k<allSBs[i].weights.length; k++) { //find insertion node\n var partWeight = String(allSBs[i].weights[k]);\n if (partWeight == String(parseInt(partWeight))) partWeight = \"aboveHTML+\" + partWeight;\n if (stoppingNode && allSBs[i].participants[k] == stoppingNode) { //don't go beyond stopping node\n foundStop = true;\n continue;\n } else if (partWeight.indexOf(this.weightType)==0) { //if same type, keep looking for node above me\n newWeight = extUtils.getWeightNum(allSBs[i].weights[k]);\n //DEBUG alert(\"Checking part \"+k+\": \"+lighterWeight+\" (lighter) <= \"+newWeight+\" (new) <= \"+editObj.weightNum+\" (my weight)?\");\n if (newWeight && lighterWeight <= newWeight && (newWeight < this.weightNum\n || (!foundStop && newWeight == this.weightNum))) { //heavier than LW, lighter than me\n lighterWeight = newWeight;\n lighterNode = allSBs[i].participants[k];\n lighterNodeOffset = 0;\n //DEBUG alert(\"Changing lighter weight to (new) \"+lighterWeight+\"\\n\"+unescape(lighterNode.orig));\n } } }\n }\n }\n\n if (lighterNode)\n {\n var nodeOffsets = dwscripts.getNodeOffsets(lighterNode);\n this.insertPos = nodeOffsets[1];\n\n var proposedInsertPos = lighterNodeOffset + nodeOffsets[0];\n\n if ( this.insertPos > proposedInsertPos )\n {\n //possibly inserting in middle of node\n var insertMergeDelims = null;\n if (!this.dontMerge)\n {\n insertMergeDelims = docEdits.canMergeBlock(this.text);\n }\n var existingMergeDelims = null;\n if (docEdits.canMergeNode(lighterNode))\n {\n existingMergeDelims = docEdits.canMergeBlock(extUtils.convertNodeToString(lighterNode));\n }\n this.bDontMergeTop = true;\n\n if (insertMergeDelims && existingMergeDelims\n && insertMergeDelims[0].toLowerCase() == existingMergeDelims[0].toLowerCase()\n && insertMergeDelims[1].toLowerCase() == existingMergeDelims[1].toLowerCase())\n {\n var escStartDelim = dwscripts.escRegExpChars(insertMergeDelims[0]);\n var escEndDelim = dwscripts.escRegExpChars(insertMergeDelims[1]);\n\n // Preserve spaces and tabs before the first newline before the end delimeter.\n var pattern = \"^\\\\s*\" + escStartDelim + \"\\\\s*([\\\\S\\\\s]*[^\\\\r\\\\n])\\\\s*\" + escEndDelim + \"\\\\s*$\";\n this.text = docEdits.strNewlinePref + docEdits.strNewlinePref + this.text.replace(new RegExp(pattern, \"i\"), \"$1\");\n this.insertPos = proposedInsertPos;\n this.bDontMergeBottom = true;\n }\n else if (!existingMergeDelims)\n {\n //do nothing - insert after this node\n }\n else\n {\n //need to split up nodes, maybe\n var partAfter = docEdits.allSrc.substring(proposedInsertPos, this.insertPos);\n var pattern = \"[\\r\\n]\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[1]) + \"\\\\s*$\";\n if (partAfter.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = docEdits.strNewlinePref + existingMergeDelims[1] + docEdits.strNewlinePref + this.text\n + docEdits.strNewlinePref + existingMergeDelims[0] + docEdits.strNewlinePref;\n this.splitDelims = existingMergeDelims;\n this.insertPos = proposedInsertPos;\n // remove the white space from the partAfter\n if (partAfter.search(/^(\\s*)/) != -1)\n {\n this.replacePos = this.insertPos + String(RegExp.$1).length;\n }\n this.bDontMergeBottom = true;\n }\n else\n {\n //do nothing - insert after this node\n }\n }\n }\n }\n else // lighter node not found\n {\n if (this.weightType == \"belowHTML\")\n {\n this.insertPos = dwscripts.getNodeOffsets(dom.documentElement)[1];\n if (this.insertPos == 0) //if document w/o HTML, add after everything\n {\n this.insertPos = dom.documentElement.outerHTML.length;\n }\n }\n else //aboveHTML, first item\n {\n this.insertPos = 0;\n }\n }\n }\n}", "function setPara() {\n var name = document.getElementById(\"para\")\n name.innerText = \"Hello this is an example\"\n}", "function splitParagraph(text){\n\n\tvar fragments = [];\n\n\twhile( text != ''){\n\t\tif (text.charAt(0) == \"*\"){\n\t\t\tfragments.push({type: 'emphasized',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(1,takeUpTo('*',text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\t//we add 1 because we want to remove the string added\n\t\t\t//PLUS the character at the end which may be } or *\n\t\t\ttext = text.slice(takeUpTo('*',text)+1);\n\t\t} else if (text.charAt(0) == \"{\"){\n\t\t\tfragments.push({type: 'footnote',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(1,takeUpTo('}',text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\ttext = text.slice(takeUpTo('}',text)+1);\n\t\t} else {\n\t\t\tfragments.push({type: 'normal',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(0,takeNormal(text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\ttext = text.slice(takeNormal(text));\n\t\t}\n\t}\n\n\treturn fragments;\n}", "function addExcerpt(chart, text)\n{\n var excerpt = chart.selectAll(\".excerpt\")\n .data(text)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"excerpt\")\n .style(\"fill\", \"white\")\n .text(conditional_clip(text, 50))\n .attr('transform', function(d, i) {\n var horz = 200;\n var vert = 150; \n return 'translate(' + horz + ',' + vert + ')';\n });\n}", "function processAndHighlightText( sValue, sOT, sTag, sCT, bInBox )\n{\n\tvar sRegExp, regExp;\n\t// <pre lang=\"cpp\">using</pre>\n\t\n\t// setting global variables\n\tsGlobOT = sOT;\n\tsGlobCT = sCT;\n\tsGlobTag = sTag;\n\tbGlobCodeInBox=bInBox;\n\t\t\n\t// building regular expression\n\tsRegExp = sGlobOT \n\t\t+\"\\\\s*\"\n\t\t+ sGlobTag\n\t\t+\".*?\"\n\t\t+sGlobCT\n\t\t+\"((.|\\\\n)*?)\"\n\t\t+sGlobOT\n\t\t+\"\\\\s*/\\\\s*\"\n\t\t+sGlobTag\n\t\t+\"\\\\s*\"\n\t\t+sGlobCT;\n\n\tregExp=new RegExp(sRegExp, \"gim\");\n\n\t// render pre\n\treturn sValue.replace( regExp, function( $0, $1 ){ return replaceByCode( $0, $1 );} );\n}", "display_raw_text(div, raw_text, word_lists=[], colors=[], positions=false) {\n div.classed('lime', true).classed('text_div', true);\n div.append('h3').text('Text with highlighted words');\n let highlight_tag = 'span';\n let text_span = div.append('span').text(raw_text);\n let position_lists = word_lists;\n if (!positions) {\n position_lists = this.wordlists_to_positions(word_lists, raw_text);\n }\n let objects = []\n for (let i of range(position_lists.length)) {\n position_lists[i].map(x => objects.push({'label' : i, 'start': x[0], 'end': x[1]}));\n }\n objects = sortBy(objects, x=>x['start']);\n let node = text_span.node().childNodes[0];\n let subtract = 0;\n for (let obj of objects) {\n let word = raw_text.slice(obj.start, obj.end);\n let start = obj.start - subtract;\n let end = obj.end - subtract;\n let match = document.createElement(highlight_tag);\n match.appendChild(document.createTextNode(word));\n match.style.backgroundColor = colors[obj.label];\n try {\n let after = node.splitText(start);\n after.nodeValue = after.nodeValue.substring(word.length);\n node.parentNode.insertBefore(match, after);\n subtract += end;\n node = after;\n }\n catch (err){\n }\n }\n }", "function textParallax() {\r\n\tvar myScroll = $(this).scrollTop();\r\n\t$('.page-header-wrap .container').css({\r\n\t\t'opacity': 1 - (myScroll / 200)\r\n\t});\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set app container width and height on landing size
function setLandingSize() { appContainer_Ls.css({ 'width' : appContainerWidth_Ls, 'height' : appContainerHeight_Ls, 'margin-top': appContainer_marginTop_Ls }); }
[ "function setFullSize() {\r\n\tappContainer_Fs.css({\r\n\t\t'width' : appContainerWidth_Fs,\r\n\t\t'height' : appContainerHeight_Fs,\r\n\t\t'margin-top': appContainer_marginTop_Fs\r\n\t});\r\n\tappContent.css({\r\n\t\t'width' : appContentWidth,\r\n\t\t'height' : appContentHeight,\r\n\t});\t\r\n}", "function ResizeHandler() {\n setMaxWindowWidth((window.innerWidth - 800) / 2);\n setMaxWindowHeight((window.innerHeight - 700) / 2);\n }", "setWindowDimensions() {\n this.windowWidth = window.innerWidth;\n this.windowHeight = window.innerHeight;\n }", "static updateScreenDimensions() {\n this.div.style.width = Engine.Graphics.screenWidth + 'px';\n this.div.style.height = Engine.Graphics.screenHeight + 'px';\n }", "function setBgSize() {\n var width = $window.width();\n var height = $window.height();\n var value = height;\n if (width >= height) {\n value = width;\n }\n $background.height(value + 'px');\n $background.width(value + 'px');\n }", "function resize(){\n const width = window.innerWidth - 100;\n const topHeight = d3.select(\".top\").node().clientHeight\n const height = window.innerHeight - topHeight - 50\n console.log(width, height)\n \n self.camera.aspect = width / height;\n self.camera.updateProjectionMatrix();\n self.renderer.setSize(width, height);\n render()\n\n }", "async resize (width, height) {\n this.page.set('viewportSize', {width, height})\n }", "function updateDimensions() {\n theight = templateHeight();\n cheight = containerHeight();\n vpheight = viewPortHeight();\n }", "configure(width, height)\n {\n // use the width passed by the user\n // but check the height, each team should have at least 200 px of space\n this.width = width\n let len = Object.keys(this.teams).length;\n if (len * 200 > height)\n {\n this.height = len * 200 + 100;\n }\n else\n {\n this.height = height;\n }\n\n this.app.renderer.autoResize = true;\n this.app.renderer.resize(this.width, this.height);\n }", "onResize() {\n App.bus.trigger(TRIGGER_RESIZE, document.documentElement.clientWidth, document.documentElement.clientHeight);\n }", "function _initApp() {\n\n this.containers.forEach(function(containerObj, i) {\n\n var offsetModifier = new Modifier({\n size: [this.options.appWidth, this.options.appHeight],\n transform: Transform.translate(-containerObj.offset.x, -containerObj.offset.y, 0)\n });\n\n var app = new this.options.app({\n transitionables: this.options.transitionables\n });\n\n containerObj.container.add(offsetModifier).add(app);\n\n }.bind(this));\n}", "function setPopUpSize() {\r\r\n\t\tif(document.documentElement.clientWidth <= 640) {\r\r\n\t\t\tpopUpwidth = 320;\r\r\n\t\t\tpopUpHeight = 460;\r\r\n\t\t}\r\r\n\t\telse {\r\r\n\t\t\tpopUpwidth = 550;\r\r\n\t\t\tpopUpHeight = 420;\r\r\n\t\t}\r\r\n\t}", "setTopHalf() {\n let viewPort = {};\n viewPort.x = 0;\n viewPort.y = 0;\n viewPort.width = global.screen_width;\n viewPort.height = global.screen_height / 2;\n this._setViewPort(viewPort);\n this._screenPosition = GDesktopEnums.MagnifierScreenPosition.TOP_HALF;\n }", "function keepFullSize(canvas) {\n function resize() {\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n }\n window.onresize = resize;\n resize();\n }", "_resizeWindowManager() {\n const kMargin = 200;\n let required_height = 0;\n let required_width = 0;\n for (let i in this.windows_) {\n const element = this.windows_[i];\n const top = parseInt(element.style.top);\n const left = parseInt(element.style.left);\n if (top > 0 && left > 0) {\n required_height = Math.max(required_height, top + element.offsetHeight);\n required_width = Math.max(required_width, left + element.offsetWidth);\n }\n }\n this.parent_.style.height = (required_height + kMargin) + \"px\";\n this.parent_.style.width = (required_width + kMargin) + \"px\";\n }", "function resize(){\r\n\t$('#map').css(\"height\", ($(window).height() - navBarMargin));\r\n\t$('#map').css(\"width\", ($(window).width())); \r\n}", "autoSizeSceneGraph() {\n if (this.rootLayout) {\n const aabb = this.getBlocksAABB();\n this.sceneGraph.width = Math.max(aabb.right, kT.minWidth);\n this.sceneGraph.height = Math.max(aabb.bottom, kT.minHeight) + kT.bottomPad;\n this.sceneGraph.updateSize();\n }\n }", "function fitWindowSize() {\n // fit mainContainer to body size\n document.getElementById(\"mainContainer\").style.height = $('body').height() - 41 + 'px';\n \n //alert($('body').height() + ' ' + document.getElementById('mainContainer').style.height);\n \n // refresh mainTabs\n $('#mainTabs').tabs('resize');\n \n // select the tab again to complete the resizing the tab\n var tab = $('#mainTabs').tabs('getSelected');\n $('#mainTabs').tabs('select', tab.panel('options').title);\n}", "function appViewLayout(){\n\tvar appViewStatus = Number(document.getElementById(\"appsViewStatusOp\").value);\n\t\n\tif(appViewStatus === 0){\n\t\t\n\t\t// Size of HTML document (same as pageHeight/pageWidth in screenshot).\n\t\tvar indention = 65;\n\t\tvar totalWidth = Number(document.documentElement.clientWidth) - indention;\n\t\t\n\t\tdocument.getElementById(\"appsViewStatusOp\").value = \"1\";\n\t\tdocument.getElementById(\"changeTabSet\").setAttribute(\"class\", \"icon mif-enlarge\");\n\t\tdocument.getElementById(\"tabButton\").setAttribute(\"title\", \"Fullscreen View\");\n\t\t\n\t\tAnimate('appBaseArea', indention, '0', totalWidth, '100%', '', 500, '');\n\t\t\n\t}\n\telse{\n\t\tdocument.getElementById(\"appsViewStatusOp\").value = \"0\";\n\t\t\n\t\tdocument.getElementById(\"changeTabSet\").setAttribute(\"class\", \"icon mif-keyboard-tab\");\n\t\tdocument.getElementById(\"tabButton\").setAttribute(\"title\", \"Tab View\");\n\t\t\n\t\tAnimate('appBaseArea', '0', '0', '100%', '100%', '', 500, '');\n\t}\n\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Depends on Khronos Debug support module being imported via "luma.gl/debug" Helper to get shared context data
function getContextData(gl) { gl.luma = gl.luma || {}; return gl.luma; } // Enable or disable debug checks in debug contexts
[ "function createGLContext() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n opts = Object.assign({}, contextDefaults, opts);\n var _opts = opts,\n canvas = _opts.canvas,\n width = _opts.width,\n height = _opts.height,\n throwOnError = _opts.throwOnError,\n manageState = _opts.manageState,\n debug = _opts.debug; // Error reporting function, enables exceptions to be disabled\n\n function onError(message) {\n if (throwOnError) {\n throw new Error(message);\n } // log.log(0, message)();\n\n\n return null;\n }\n\n var gl;\n\n if (_utils.isBrowser) {\n // Get or create a canvas\n var targetCanvas = (0, _createCanvas.getCanvas)({\n canvas: canvas,\n width: width,\n height: height,\n onError: onError\n }); // Create a WebGL context in the canvas\n\n gl = (0, _createBrowserContext.createBrowserContext)({\n canvas: targetCanvas,\n opts: opts\n });\n } else {\n // Create a headless-gl context under Node.js\n gl = (0, _createHeadlessContext.createHeadlessContext)({\n width: width,\n height: height,\n opts: opts,\n onError: onError\n });\n }\n\n if (!gl) {\n return null;\n } // Install context state tracking\n\n\n if (manageState) {\n (0, _trackContextState.default)(gl, {\n copyState: false,\n log: function log() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _utils.log.log.apply(_utils.log, [1].concat(args))();\n }\n });\n } // Add debug instrumentation to the context\n\n\n if (_utils.isBrowser && debug) {\n gl = (0, _debugContext.makeDebugContext)(gl, {\n debug: debug\n }); // Debug forces log level to at least 1\n\n _utils.log.priority = Math.max(_utils.log.priority, 1); // Log some debug info about the context\n } // Log context information\n\n\n logInfo(gl); // Add to seer integration\n\n return gl;\n}", "get isDevContext() {\n if (this.mIsDevContext !== undefined) {\n return this.mIsDevContext;\n }\n return Inspect.isDevContext();\n }", "function getContext(){\n \n if(!domain.active || !domain.active.context){\n if(this.mockContext) return this.mockContext\n \n logger.error(\"getContext called but no active domain\", domain.active);\n logger.error(\"Caller is \", arguments.callee && arguments.callee.caller && arguments.callee.caller.name, arguments.callee && arguments.callee.caller );\n throw \"Context not available. This may happen if the code was not originated by Angoose\"; \n } \n \n return domain.active.context;\n}", "_getAttributeManager() {\n const context = this.context;\n return new _attribute_attribute_manager__WEBPACK_IMPORTED_MODULE_1__[\"default\"](context.gl, {\n id: this.props.id,\n stats: context.stats,\n timeline: context.timeline\n });\n }", "constructor() {\n this.gl = checkNull(WebGLHandler.initializeContext());\n }", "getContext() {\n let ctx = {};\n if (this.server) {\n const serverDescription = this.server.describe();\n ctx = Object.assign({ \n /* Main Server */\n server: this.server }, serverDescription.context);\n }\n // Return the repl context\n return Object.assign(Object.assign({}, ctx), { clear: this.clear.bind(this), help: this.help.bind(this) });\n }", "getApplicationContext() {\n let context = \"\";\n // figure out the context we need to apply for where the editing creds\n // and API might come from\n // beaker is a unique scenario\n if (typeof DatArchive !== typeof undefined) {\n context = \"beaker\"; // implies usage of BeakerBrowser, an experimental browser for decentralization\n } else {\n switch (window.HAXCMSContext) {\n case \"published\": // implies this is to behave as if it is completely static\n case \"nodejs\": // implies nodejs based backend, tho no diff from\n case \"php\": // implies php backend\n case \"11ty\": // implies 11ty static site generator\n case \"demo\": // demo / local development\n case \"desktop\": // implies electron\n case \"local\": // implies ability to use local file system\n case \"userfs\": // implies hax.cloud stylee usage pattern\n context = window.HAXCMSContext;\n break;\n default:\n // we don't have one so assume it's php for now\n // @notice change this in the future\n context = \"php\";\n break;\n }\n }\n return context;\n }", "function WebGLNetworkDevice() {}", "get contexts()\n\t{\n\t\tvar priv = PRIVATE.get(this);\n\t\treturn priv.contextsContainer.array;\n\t}", "function setupDebug(){\n debug = new DEBUGTOOL(false,null,[8,8,16]);\n}", "function getCachedMountContext(blockchain_or_datastore_id, full_app_name) {\n\n var userData = getUserData();\n assert(userData);\n\n assert(blockchain_or_datastore_id, 'No blockchain ID given');\n assert(full_app_name, 'No app name given');\n\n var cache_key = blockchain_or_datastore_id + '/' + full_app_name;\n\n if (!userData.datastore_contexts) {\n console.log(\"No datastore contexts defined\");\n return null;\n }\n\n if (!userData.datastore_contexts[cache_key]) {\n console.log('No datastore contexts for ' + blockchain_or_datastore_id + ' in ' + full_app_name);\n return null;\n }\n\n var ctx = userData.datastore_contexts[cache_key];\n if (!ctx) {\n console.log('Null datastore context for ' + blockchain_or_datastore_id + ' in ' + full_app_name);\n return null;\n }\n\n return ctx;\n}", "function ScopedModule(){\n Module.apply(this, arguments);\n this.locals = {};\n this.context = this.parent ? this.parent.context : global;\n}", "function useFeatureIntroControlInternalContext() {\n return React.useContext(FeatureIntroControlContext);\n}", "getChildContext() {\n return {\n store: this.store,\n };\n }", "splitExternalContext() {\n\n // see properties.createProperty /\n // namespace setting in QMLBinding with(...) -s / QObject.$noalias.createChild / components.js.createChild :\n // we use \"this\", $pageElements and loader context in evaluation, as all the variable names other than elements\n // are either in \"this\"(and supers) or in parent(ie loader) context,\n\n // #scope hierarchy:\n // very precise code don't change this ::\n // see also QMLComponent.init\n\n const old = this.$externalContext;\n\n this.$externalContext = {};\n\n QmlWeb.helpers.mergeProtoInPlace(this.$externalContext, old);\n }", "static initCache(context) {\n this.context = context;\n }", "GetPlatformData() {}", "function setFlags() {\n\n var WEBGL_VERSION = 2\n var WASM_HAS_SIMD_SUPPORT = false\n var WASM_HAS_MULTITHREAD_SUPPORT = false\n var WEBGL_CPU_FORWARD = true\n var WEBGL_PACK = true\n var WEBGL_FORCE_F16_TEXTURES = false\n var WEBGL_RENDER_FLOAT32_CAPABLE = true\n var WEBGL_FLUSH_THRESHOLD = -1\n var CHECK_COMPUTATION_FOR_ERRORS = false\n\n wasmFeatureDetect.simd().then(simdSupported => {\n if (simdSupported) {\n // alert(\"simd supported\")\n WASM_HAS_SIMD_SUPPORT = true\n } else {\n // alert(\"no simd\")\n }\n });\n wasmFeatureDetect.threads().then(threadsSupported => {\n if (threadsSupported) {\n // alert(\"multi thread supported\")\n WASM_HAS_MULTITHREAD_SUPPORT = true;\n } else {\n // alert(\"no multi thread\")\n }\n });\n switch (getOS()) {\n case 'Mac OS':\n // alert('Mac detected')\n WEBGL_VERSION = 1\n break;\n case 'Linux':\n // alert('linux detected')\n break;\n case 'iOS':\n // alert('ios detected')\n WEBGL_VERSION = 1\n WEBGL_FORCE_F16_TEXTURES = true //use float 16s on mobile just incase \n WEBGL_RENDER_FLOAT32_CAPABLE = false\n break;\n case 'Android':\n WEBGL_FORCE_F16_TEXTURES = true\n WEBGL_RENDER_FLOAT32_CAPABLE = false\n line_width = 3\n radius = 4\n // alert('android detected')\n break;\n default:\n // alert('windows detected')\n break;\n\n }\n\n var flagConfig = {\n WEBGL_VERSION: WEBGL_VERSION,\n WASM_HAS_SIMD_SUPPORT: WASM_HAS_SIMD_SUPPORT,\n WASM_HAS_MULTITHREAD_SUPPORT: WASM_HAS_MULTITHREAD_SUPPORT,\n WEBGL_CPU_FORWARD: WEBGL_CPU_FORWARD,\n WEBGL_PACK: WEBGL_PACK,\n WEBGL_FORCE_F16_TEXTURES: WEBGL_FORCE_F16_TEXTURES,\n WEBGL_RENDER_FLOAT32_CAPABLE: WEBGL_RENDER_FLOAT32_CAPABLE,\n WEBGL_FLUSH_THRESHOLD: WEBGL_FLUSH_THRESHOLD,\n CHECK_COMPUTATION_FOR_ERRORS: CHECK_COMPUTATION_FOR_ERRORS,\n }\n\n setEnvFlags(flagConfig)\n\n}", "GetShaderEngine () {\n return this.ShaderEngine\n }", "function RenderFrameContext( o )\r\n{\r\n\tthis.width = 0; //0 means the same size as the viewport, negative numbers mean reducing the texture in half N times\r\n\tthis.height = 0; //0 means the same size as the viewport\r\n\tthis.precision = RenderFrameContext.DEFAULT_PRECISION; //LOW_PRECISION uses a byte, MEDIUM uses a half_float, HIGH uses a float, or directly the texture type (p.e gl.UNSIGNED_SHORT_4_4_4_4 )\r\n\tthis.filter_texture = true; //magFilter: in case the texture is shown, do you want to see it pixelated?\r\n\tthis.format = GL.RGB; //how many color channels, or directly the texture internalformat \r\n\tthis.use_depth_texture = true; //store the depth in a texture\r\n\tthis.use_stencil_buffer = false; //add an stencil buffer (cannot be read as a texture in webgl)\r\n\tthis.num_extra_textures = 0; //number of extra textures in case we want to render to several buffers\r\n\tthis.name = null; //if a name is provided all the textures will be stored in the ONE.ResourcesManager\r\n\r\n\tthis.generate_mipmaps = false; //try to generate mipmaps if possible (only when the texture is power of two)\r\n\tthis.adjust_aspect = false; //when the size doesnt match the canvas size it could look distorted, settings this to true will fix the problem\r\n\tthis.clone_after_unbind = false; //clones the textures after unbinding it. Used when the texture will be in the 3D scene\r\n\r\n\tthis._fbo = null;\r\n\tthis._color_texture = null;\r\n\tthis._depth_texture = null;\r\n\tthis._textures = []; //all color textures (the first will be _color_texture)\r\n\tthis._cloned_textures = null; //in case we set the clone_after_unbind to true\r\n\tthis._cloned_depth_texture = null;\r\n\r\n\tthis._version = 1; //to detect changes\r\n\tthis._minFilter = gl.NEAREST;\r\n\r\n\tif(o)\r\n\t\tthis.configure(o);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! MIT License KeySpline use bezier curve for transition easing function
function KeySpline (mX1, mY1, mX2, mY2) { this.get = function(aX) { if (mX1 === mY1 && mX2 === mY2) { return aX; } // linear return CalcBezier(GetTForX(aX), mY1, mY2); }; function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function C(aA1) { return 3.0 * aA1; } // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. function CalcBezier(aT, aA1, aA2) { return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT; } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. function GetSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1); } function GetTForX(aX) { // Newton raphson iteration var aGuessT = aX; for (var i = 0; i < 4; ++i) { var currentSlope = GetSlope(aGuessT, mX1, mX2); if (currentSlope === 0.0) { return aGuessT; } var currentX = CalcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } }
[ "function bezier(p1x, p1y, p2x, p2y) {\n var bezier = new unitbezier(p1x, p1y, p2x, p2y);\n return function (t) {\n return bezier.solve(t);\n };\n }", "get curve() {}", "function bezierCurve(u, q){\n\tvar B = bern3;\n\tvar n = 4;\n\n\tvar p = vec3(0,0,0);\n\n\tfor(var i=0; i<n; i++){\n\t\tp = add(p, scale(B(i, u), q[i]));\n\n\t}\n\n\treturn p;\n}", "function BackEase(/** Defines the amplitude of the function */amplitude){if(amplitude===void 0){amplitude=1;}var _this=_super.call(this)||this;_this.amplitude=amplitude;return _this;}", "static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n // tslint:disable-next-line:no-parameter-reassignment\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n const bez = new Array();\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 +\n 3.0 * t * (1.0 - t) * (1.0 - t) * val1 +\n 3.0 * t * t * (1.0 - t) * val2 +\n t * t * t * val3;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3_1$2.Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n }", "continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }", "function bezierSurface(u,v, q){\n\n\tvar B = bern3;\n\tvar n=4;\n\n\tvar p = vec3(0,0,0);\n\n\tfor(var i=0; i<n; i++){\n\t\tp = add(p, scale(B(i,u), bezierCurve(v, q[i])));\n\t}\n\n\treturn p;\n}", "shakyLine(x0, y0, x1, y1) {\n // Let $v = (d_x, d_y)$ be a vector between points $P_0 = (x_0, y_0)$\n // and $P_1 = (x_1, y_1)$\n const dx = x1 - x0;\n const dy = y1 - y0;\n\n // Let $l$ be the length of $v$\n const l = Math.sqrt(dx * dx + dy * dy);\n\n // Now we need to pick two random points that are placed\n // on different sides of the line that passes through\n // $P_1$ and $P_2$ and not very far from it if length of\n // $P_1 P_2$ is small.\n const K = Math.sqrt(l) / 1.5;\n const k1 = Math.random();\n const k2 = Math.random();\n const l3 = Math.random() * K;\n const l4 = Math.random() * K;\n\n // Point $P_3$: pick a random point on the line between $P_0$ and $P_1$,\n // then shift it by vector $\\frac{l_1}{l} (d_y, -d_x)$ which is a line's normal.\n const x3 = x0 + dx * k1 + dy / l * l3;\n const y3 = y0 + dy * k1 - dx / l * l3;\n\n // Point $P_3$: pick a random point on the line between $P_0$ and $P_1$,\n // then shift it by vector $\\frac{l_2}{l} (-d_y, d_x)$ which also is a line's normal\n // but points into opposite direction from the one we used for $P_3$.\n const x4 = x0 + dx * k2 - dy / l * l4;\n const y4 = y0 + dy * k2 + dx / l * l4;\n\n // Draw a bezier curve through points $P_0$, $P_3$, $P_4$, $P_1$.\n // Selection of $P_3$ and $P_4$ makes line 'jerk' a little\n // between them but otherwise it will be mostly straight thus\n // creating illusion of being hand drawn.\n this.ctx.moveTo(x0, y0);\n this.ctx.bezierCurveTo(x3, y3, x4, y4, x1, y1);\n }", "function cubicInterp_deriv(t, a, b, aprime = 0, bprime = 0) {\n return (2 * a - 2 * b + aprime + bprime) * t * t * t + (3 * b - 3 * a - 2 * aprime - bprime) * t * t + aprime * t + a;\n}", "static CreateHermiteSpline(p1, t1, p2, t2, nbPoints) {\n const hermite = new Array();\n const step = 1.0 / nbPoints;\n for (let i = 0; i <= nbPoints; i++) {\n hermite.push(Vector3_1$2.Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n }", "getCurve( startX, startY, endX, endY ) {\n let middleX = startX + (endX - startX) / 2;\n return `M ${startX} ${startY} C ${middleX},${startY} ${middleX},${endY} ${endX},${endY}`;\n }", "function drawBezierCurve(context, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y, lines) {\r\n const bezierMatrix = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]];\r\n const pointVectorX = [p1x, p2x, p3x, p4x];\r\n const pointVectorY = [p1y, p2y, p3y, p4y];\r\n\r\n const cx = multiplyMatrixByVector(bezierMatrix, pointVectorX);\r\n const cy = multiplyMatrixByVector(bezierMatrix, pointVectorY);\r\n\r\n step = 1/lines;\r\n for(let t = 0; Math.floor((t+step)*100)/100 <= 1; t+=step) {\r\n let startX = calculateCurvePoint(cx, 1-t);\r\n let startY = calculateCurvePoint(cy, 1-t);\r\n let endX = calculateCurvePoint(cx, 1-(t+step));\r\n let endY = calculateCurvePoint(cy, 1-(t+step));\r\n\r\n drawLine(context, startX, startY, endX, endY);\r\n if(Math.floor((t+step)*100)/100 === 1)\r\n break\r\n }\r\n}", "function drawCornerCurve (xFrom, yFrom, xTo, yTo, bendDown, attr, doubleCurve, shiftx1, shifty1, shiftx2, shifty2 ) {\n var xDistance = xTo - xFrom;\n var yDistance = yFrom - yTo;\n\n var dist1x = xDistance/2;\n var dist2x = xDistance/10;\n var dist1y = yDistance/2;\n var dist2y = yDistance/10;\n\n var curve;\n\n if (bendDown) {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom + dist1x) + ' ' + (yFrom + dist2y) +\n ' ' + (xTo + dist2x) + ' ' + (yTo + dist1y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n } else {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom - dist2x) + ' ' + (yFrom - dist1y) +\n ' ' + (xTo - dist1x) + ' ' + (yTo - dist2y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n }\n\n if (doubleCurve) {\n var curve2 = curve.clone().toBack();\n curve .transform('t ' + shiftx1 + ',' + shifty1 + '...');\n curve2.transform('t ' + shiftx2 + ',' + shifty2 + '...');\n }\n}", "decompose() {\n let Q = this.decomposeU();\n // Using Q, create Bezier strip surfaces. These are individual BSurf objects\n // Their u curve will be bezier, but will still be expressed as BSpline\n // Their v curve will still be bspline\n let L = 2 * (this.u_degree + 1);\n let u_bez_knots = common_1.empty(L);\n for (let i = 0; i < this.u_degree + 1; i++) {\n u_bez_knots.set(i, 0);\n u_bez_knots.set(L - i - 1, 1);\n }\n let bezStrips = [];\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezStrips.push(new BSplineSurface(this.u_degree, this.v_degree, u_bez_knots, this.v_knots, cpoints));\n }\n let bezSurfs = [];\n // Decompose each bezier strip along v\n for (let bezStrip of bezStrips) {\n let Q = bezStrip.decomposeV();\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezSurfs.push(new BezierSurface(this.u_degree, this.v_degree, cpoints));\n }\n }\n return bezSurfs;\n }", "function lerp(x1,y1,x2,y2,y3) {\n\treturn ((y2-y3) * x1 + (y3-y1) * x2)/(y2-y1);\n}", "function transition() {\n\n linePath.transition()\n .duration(90000)\n .attrTween(\"stroke-dasharray\", tweenDash)\n .each(\"end\", function() {\n d3.select(this).call(transition); // infinite loop\n })\n } //end transition", "flyAway() {\n const tween = new TWEEN.Tween({\n x:176270.75252929013,\n y:-26073.99366690377,\n z:39148.29418709834\n }).to({x: 491010.04088835354, y: 317950.63986114773, z: 100720.7299043877}, 6000).easing(TWEEN.Easing.Linear.None).onUpdate((e)=> {\n this.camera.position.set(e.x, e.y, e.z);\n });\n \n tween.delay(500);\n tween.start();\n }", "function curvedFlowPathFunction(curvature) {\n return (f) => {\n const syC = f.source.y + f.sy + f.dy / 2, // source flow's y center\n tyC = f.target.y + f.ty + f.dy / 2, // target flow's y center\n sEnd = f.source.x + f.source.dx, // source's trailing edge\n tStart = f.target.x; // target's leading edge\n\n // Watch out for a nearly-straight path (total rise/fall < 2 pixels OR\n // very little horizontal space to work with).\n // If we have one, make this flow a simple 4-sided shape instead of\n // a curve. (This avoids weird artifacts in some SVG renderers.)\n if (Math.abs(syC - tyC) < 2 || Math.abs(tStart - sEnd) < 12) {\n return flatFlowPathMaker(f);\n }\n\n f.renderAs = 'curved'; // Render this path as a curved stroke\n\n // Make the curved path:\n // Set up a function for interpolating between the two x values:\n const xinterpolate = d3.interpolateNumber(sEnd, tStart),\n // Pick 2 curve control points given the curvature & its converse:\n xcp1 = xinterpolate(curvature),\n xcp2 = xinterpolate(1 - curvature);\n // This SVG Path spec means:\n // [M]ove to the center of the flow's start [sx,syC]\n // Draw a Bezier [C]urve using control points [xcp1,syC] & [xcp2,tyC]\n // End at the center of the flow's target [tx,tyC]\n return (\n `M${ep(sEnd)} ${ep(syC)}C${ep(xcp1)} ${ep(syC)} `\n + `${ep(xcp2)} ${ep(tyC)} ${ep(tStart)} ${ep(tyC)}`\n );\n };\n}", "_setTransforms () {\n this.transforms = {\n 'effect-1-2': {\n 'next': [\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n ],\n 'prev': [\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, -${win.height / 4 + 5}px, 0)`,\n `translate3d(${win.width / 4 + 5}px, 0, 0)`,\n\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n `translate3d(-${win.width / 4 + 5}px, 0, 0)`,\n `translate3d(0, ${win.height / 4 + 5}px, 0)`,\n ]\n },\n };\n }", "interpolateY(x) { // input x (real-number)\n var index = this.bisection(x);\n \n if(this.arySrcX[index] === x)\n return this.arySrcY[index];\n else\n return this.doCubicSpline(x, index);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======================= RATING AND TRACK INFO END ========================== DEFINE CLASS ButtonUI for RATING
function ButtonUI_R() { this.y = 10; this.x = 10; this.width = imgw; this.height = imgh; this.setx = function(x){ this.x = x; } this.Paint = function(gr, button_n, y) { this.y = y; var rating_to_draw = (rating_hover_id!==false?rating_hover_id:g_infos.rating); this.img = ((rating_to_draw - button_n) >= 0) ? img_rating_on : img_rating_off; if(button_n!=1) gr.DrawImage(this.img, this.x, this.y, this.width, this.height, 0, 0, this.width, this.height, 0); } this.MouseMove = function(x, y, i) { if (g_infos.metadb) { var half_rating_space = Math.ceil(rating_spacing/2)+1; if (x > this.x - half_rating_space && x < this.x + this.width + half_rating_space && y > this.y && y < this.y + this.height) { rating_hover_id = i; if(g_cursor.getActiveZone()!="rating"+i) { g_cursor.setCursor(IDC_HAND,"rating"+i); } return true; } else if(g_cursor.getActiveZone()=="rating"+i) { g_cursor.setCursor(IDC_ARROW,4); } } return false; } this.MouseUp = function(x, y, i) { if (g_infos.metadb) { var half_rating_space = Math.ceil(rating_spacing/2)+1; if (x > this.x - half_rating_space && x < this.x + this.width + half_rating_space && y > this.y && y < this.y + this.height) { var derating_flag = (i == g_infos.rating ? true : false); g_avoid_metadb_updated = true; if (derating_flag) { if(g_infos.album_infos) { g_infos.rating = rateAlbum(0,g_infos.rating-1, new FbMetadbHandleList(g_infos.metadb))+1; } else { g_infos.rating = rateSong(0,g_infos.rating-1, g_infos.metadb)+1; } } else { if(g_infos.album_infos) { g_infos.rating = rateAlbum(i-1,g_infos.rating-1, new FbMetadbHandleList(g_infos.metadb))+1; } else { g_infos.rating = rateSong(i-1,g_infos.rating-1, g_infos.metadb)+1; } } } } } }
[ "styleButtons () {\n // Check if it was rated\n if (this.props.wasPositive !== null) {\n // Previous rating positive\n if (this.props.wasPositive) {\n // Is this a positive rating button\n return (this.props.isPositive) ? 'green' : 'grey'\n } else {\n // Previous rating was negative\n // Is this a negative rating button\n return (!(this.props.isPositive)) ? 'red' : 'grey'\n }\n } else { // There was no previous rating\n return (this.props.isPositive) ? 'lightgreen' : 'lightred'\n }\n }", "function addButtons() {\n target.css({\n 'border-width': '5px'\n });\n //console.log(\"INSIDE addButtons, thisID: \" + thisId + \" and thisKittenId: \" + thisKittenId);\n // append the delete and edit buttons, with data of metric document id, and kitten document id\n target.append(\"<button type='button' class='btn btn-default btn-xs littleX' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>\");\n target.append(\"<button type='button' class='btn btn-default btn-xs littleE' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button>\");\n // set boolean to true that delete and edit buttons exist\n littleButton = true;\n }", "function makeCoralImportanceButton() {\n\n // Create the clickable object\n coralImportanceButton = new Clickable();\n \n coralImportanceButton.text = \"Why are coral reefs important?\";\n coralImportanceButton.textColor = \"#365673\"; \n coralImportanceButton.textSize = 25; \n\n coralImportanceButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralImportanceButton.width = 420;\n coralImportanceButton.height = 62;\n\n // places the button \n coralImportanceButton.locate( width * (1/32) , height * (7/8));\n\n // // Clickable callback functions, defined below\n coralImportanceButton.onPress = coralImportanceButtonPressed;\n coralImportanceButton.onHover = beginButtonHover;\n coralImportanceButton.onOutside = beginButtonOnOutside;\n}", "function formatToVote(){\n votedStatus = false;\n $('#vote').html('Yay Curricula!').addClass('btn-success').removeClass('btn-default');\n }", "static get miniButtonRight() {}", "function _btnWeight() {\n //Working\n console.log(\"doing something\");\n }", "maxBetButtonClickAction () {}", "function updateMainButton() {\n if ($('#main-button').data('state') == 'start') {\n $('#main-button').text('START NEW GAME');\n }\n else if ($('#main-button').data('state') == 'drawing') {\n $('#main-button').text('DRAWING READY');\n }\n else if ($('#main-button').data('state') == 'disabled') {\n $('#main-button').text('PLEASE WAIT');\n }\n else if ($('#main-button').data('state') == 'upload-hiscore') {\n $('#main-button').text('UPLOAD HISCORE');\n }\n }", "function vote(a_Button, a_SongHash, a_VoteType, a_VoteValue)\n{\n\t// Highlight and disable the button for a while:\n\ta_Button.style.opacity = '0.5';\n\ta_Button.enabled = false\n\tsetTimeout(function()\n\t{\n\t\ta_Button.style.opacity = '1';\n\t\ta_Button.enabled = false;\n\t}, 1000);\n\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function()\n\t{\n\t\tif ((this.readyState === 4) && (this.status === 200))\n\t\t{\n\t\t\t// TODO: Update the relevant song's rating\n\t\t\t// document.getElementById(\"demo\").innerHTML = this.responseText;\n\t\t}\n\t};\n\txhttp.open(\"POST\", \"api/vote\", true);\n\txhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txhttp.send(\"songHash=\" + a_SongHash + \"&voteType=\" + a_VoteType + \"&voteValue=\" + a_VoteValue);\n}", "function setupBtnsSensorData() {\n\n //select the sensor data buttons\n $(\"#sensorDataBtns button\").click(function () {\n \n var btn = $(this);\n\n //check for current class on button\n if (!btn.hasClass(\"current\")) //if not then\n {\n $(\"#sensorDataBtns button.current\").removeClass(\"current\"); //find and remove current of buttons\n btn.addClass(\"current\"); //add current to this one\n }\n changeChartData(\"data-graph-data\", btn.attr(\"data-graph-data\")); //change the chart data and refresh the chart.\n });\n}", "static set miniButtonRight(value) {}", "function __createIncDecButton(){\n\t\tvar incDecBtnImg = new CAAT.Foundation.SpriteImage().initialize( game._director.getImage('incre_decre_btn'), 1, 2);\n\t\tvar iniVelIncBtn = new CAAT.Foundation.Actor().\n\t\t\t\t\t\t\t\tsetId('iniVelInc').\n\t\t\t\t\t\t\t\tsetAsButton(incDecBtnImg.getRef(), 0, 0, 1, 1, function(button){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}).setLocation(375, 20);\n\t\tvar iniVelDecBtn = new CAAT.Foundation.Actor().\n\t\t\t\t\t\t\t\tsetId('iniVelDec').\n\t\t\t\t\t\t\t\tsetAsButton(incDecBtnImg.getRef(), 1, 1, 1, 1, function(button){\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}).setLocation(374, 48);\n\t\t\t\t\t\t\t\t\n\t\t\t// if (\"ontouchstart\" in document.documentElement)\n\t\t\t// {\n \t\t\t\t\tdashBG.addChild(iniVelIncBtn);\n\t\t\t\t\tdashBG.addChild(iniVelDecBtn);\n\t\t\n\t\t//the increment and decrement buttons MouseDown functions are called when long press\n\t\t\t\t\tiniVelIncBtn.mouseDown = game.incDecMDown;\n\t\t\t\t\tiniVelIncBtn.mouseUp = game.incDecMUp;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t//the increment and decrement buttons MouseDown functions are called when long press\n\t\t\t\t\tiniVelDecBtn.mouseDown = game.incDecMDown;\n\t\t\t\t\tiniVelDecBtn.mouseUp = game.incDecMUp;\n\t\t\t// }\n\t}", "static ariaLabelForRestaurantButton(restaurant) {\r\n return (`View Details of ${restaurant.name} restaurant`)\r\n }", "initRecordingButton() {\n const selector = $('#toolbar_button_record');\n\n UIUtil.setTooltip(selector, 'liveStreaming.buttonTooltip', 'right');\n\n selector.addClass(this.baseClass);\n selector.attr(\"data-i18n\", \"[content]\" + this.recordingButtonTooltip);\n APP.translation.translateElement(selector);\n }", "function drawButton(btn) {\n // Move text down 1 pixel and lighten background colour on mouse hover\n var textOffset;\n if (btn.state === 1) {\n btn.instances.current.background[3] = 0.8;\n textOffset = 1;\n } else {\n btn.instances.current.background[3] = 1.;\n textOffset = 0;\n }\n // Draw button rectangle\n mgraphics.set_source_rgba(btn.instances.current.background);\n mgraphics.rectangle(btn.rect);\n mgraphics.fill();\n // Draw button text\n mgraphics.select_font_face(MPU.fontFamily.bold);\n mgraphics.set_font_size(MPU.fontSizes.p);\n // Calculate text position\n var Xcoord = MPU.margins.x + (btn.rect[2] / 2) - (mgraphics.text_measure(btn.instances.current.text)[0] / 2);\n var Ycoord = MPU.margins.y + btn.rect[1] + (mgraphics.font_extents()[0] / 2) + textOffset;\n mgraphics.move_to(Xcoord, Ycoord);\n mgraphics.set_source_rgba(btn.instances.current.color);\n mgraphics.text_path(btn.instances.current.text);\n mgraphics.fill();\n}", "createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }", "function ButtonEvent(status, data1, data2) {\n this.status = status;\n this.data1 = data1;\n this.data2 = data2;\n}", "function makeOctopusButton() {\n\n // Create the clickable object\n octopusButton = new Clickable();\n \n octopusButton.text = \"\";\n\n octopusButton.image = images[21]; \n\n // makes the image transparent\n octopusButton.color = \"#00000000\";\n octopusButton.strokeWeight = 0; \n\n // set width + height to image size\n octopusButton.width = 290; \n octopusButton.height = 160;\n\n // places the button \n octopusButton.locate( width * (13/16) - octopusButton.width * (13/16), height * (1/2) - octopusButton.height * (1/2));\n\n // Clickable callback functions, defined below\n octopusButton.onPress = octopusButtonPressed;\n octopusButton.onHover = beginButtonHover;\n octopusButton.onOutside = animalButtonOnOutside;\n}", "function makeCoralReefButton() {\n\n // Create the clickable object\n coralReefButton = new Clickable();\n \n coralReefButton.text = \"Click here to see your coral reef!\";\n coralReefButton.textColor = \"#365673\"; \n coralReefButton.textSize = 37; \n\n coralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralReefButton.width = 994;\n coralReefButton.height = 90;\n\n // places the button on the page \n coralReefButton.locate( width/2 - coralReefButton.width/2 , height * (3/4));\n\n // // Clickable callback functions, defined below\n coralReefButton.onPress = coralReefButtonPressed;\n coralReefButton.onHover = beginButtonHover;\n coralReefButton.onOutside = beginButtonOnOutside;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: extGroup.getParticipantNames DESCRIPTION: Gets a list of participant names for an extGroup. If a searchLocation is given, only returns participant names that use that location. ARGUMENTS: groupName ext dat group file name insertLocation (optional) ext data participant location RETURNS: array of Participant names
function extGroup_getParticipantNames(groupName, insertLocation) { var partNames = dw.getExtDataArray(groupName, "groupParticipants"); var retPartNames = new Array(); for (var i=0; i < partNames.length; i++) { if (!insertLocation || extPart.getLocation(partNames[i]).indexOf(insertLocation) == 0) { retPartNames.push(partNames[i]); } } return retPartNames; }
[ "function extGroup_getSelectParticipant(groupName)\n{\n return dw.getExtDataValue(groupName, \"groupParticipants\", \"selectParticipant\");\n}", "function extGroup_getInsertStrings(groupName, paramObj, insertLocation)\n{\n var retVal = new Array();\n var partNames = extGroup.getParticipantNames(groupName);\n for (var i=0; i < partNames.length; i++)\n {\n theStr = extPart.getInsertString(groupName, partNames[i], paramObj, insertLocation);\n if (theStr)\n {\n retVal.push(theStr);\n }\n }\n\n return retVal;\n}", "function extGroup_find(groupName, title, sbConstructor, participantList)\n{\n var sbList = new Array(); //array of ServerBehaviors\n\n var partList = (participantList) ? participantList : dw.getParticipants(groupName);\n\n if (extGroup.DEBUG) {\n if (partList) {\n for (var i=0; i < partList.length; i++) {\n var msg = new Array();\n msg.push(\"Participant \" + i);\n msg.push(\"\");\n msg.push(\"participantName = \" + partList[i].participantName);\n msg.push(\"\");\n msg.push(\"parameters = \");\n for (var j in partList[i].parameters) {\n msg.push(\" \" + j + \" = \" + partList[i].parameters[j] + \" (typeof \" + typeof partList[i].parameters[j] + \")\");\n }\n msg.push(\"\");\n msg.push(\"participantText = \");\n if (partList[i].participantNode)\n {\n var nodeHTML = dwscripts.getOuterHTML(partList[i].participantNode);\n msg.push(nodeHTML.substring(partList[i].matchRangeMin,partList[i].matchRangeMax));\n }\n else\n {\n msg.push(\"ERROR: null participantNode\");\n }\n\n alert(msg.join(\"\\n\"));\n }\n } else {\n alert(\"no participants found for group: \" + this.name);\n }\n }\n\n // Get group title. If no title is defined in the extension data, use the passed\n // in title. If, in addition, no title is passed in, use the groupName.\n var groupTitle = extGroup.getTitle(groupName);\n if (!groupTitle)\n {\n if (title)\n {\n groupTitle = title;\n }\n else\n {\n groupTitle = groupName;\n }\n }\n\n if (partList)\n {\n //sort participants for correct matching into groups later\n partList.sort( extGroup_participantCompare );\n\n //pull out extra information for each part\n for (var i=0; i < partList.length; i++)\n {\n //set the parts position within the master partList\n partList[i].position = i;\n\n //extract node parameter information\n extPart.extractNodeParam(partList[i].participantName, partList[i].parameters,\n partList[i].participantNode);\n\n }\n\n //now match up the found parts to create a list of part groups\n var partGroupList = extGroup.matchParts(groupName, partList);\n\n //now walk the partGroupList and create ServerBehaviors\n for (var i=0; i < partGroupList.length; i++)\n {\n var partGroup = partGroupList[i];\n\n // create a ServerBehavior\n var serverBehavior = null;\n if (sbConstructor == null)\n {\n serverBehavior = new ServerBehavior(groupName);\n }\n else\n {\n serverBehavior = new sbConstructor(groupName);\n }\n\n //sort the partGroup, so that the insert code finds the participant nodes\n // in the correct document order\n partGroup.sort(new Function(\"a\", \"b\", \"return a.position - b.position\"));\n\n //add the participant information to the ServerBehavior\n for (var j=0; j < partGroup.length; j++)\n {\n if (extPart.getVersion(partGroup[j].participantName) >= 5.0)\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n partGroup[j].matchRangeMin, partGroup[j].matchRangeMax,\n partGroup[j].parameters);\n }\n else\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n 0, 0,\n partGroup[j].parameters);\n }\n serverBehavior.addParticipant(sbPart);\n\n //set the selected node\n if (partGroup[j].participantName == extGroup.getSelectParticipant(groupName))\n {\n serverBehavior.setSelectedNode(partGroup[j].participantNode);\n }\n }\n\n //set the title\n serverBehavior.setTitle(extUtils.replaceParamsInStr(groupTitle,\n serverBehavior.getParameters(false)));\n\n //set the family\n serverBehavior.setFamily(extGroup.getFamily(groupName, serverBehavior.getParameters(false)));\n\n //check the ServerBehavior for completeness\n var partNames = extGroup.getParticipantNames(groupName);\n for (var j=0; j < partNames.length; j++)\n {\n var isOptional = extPart.getIsOptional(groupName, partNames[j]);\n sbPart = serverBehavior.getNamedSBPart(partNames[j]);\n var partNode = null;\n if (sbPart)\n {\n partNode = sbPart.getNodeSegment().node;\n }\n\n //if this is not an optional participant, check the ServerBehavior for completeness\n if (!isOptional && extPart.getWhereToSearch(partNames[j]) && partNode == null)\n {\n serverBehavior.setIsIncomplete(true);\n\n if (extGroup.DEBUG)\n {\n alert(\"setting record #\" + i + \" to incomplete: missing part: \" + partNames[j]);\n }\n }\n }\n\n // Make the sb object backward compatible with the UD4 sb object.\n serverBehavior.makeUD4Compatible();\n\n //add it to the list of ServerBehaviors\n sbList.push(serverBehavior);\n }\n }\n\n return sbList;\n}", "function getGroupNames(){\n var ret = [];\n for (var i = 0; i < this.groups.length; i++) {\n ret.push(this.groups[i].name);\n }\n return ret;\n}", "function extGroup_findInString(groupName, theStr)\n{\n var sbList = new Array();\n\n var foundMatch = false;\n var serverBehavior = new ServerBehavior(groupName);\n\n var partNames = extGroup.getParticipantNames(groupName);\n for (var i=0; i < partNames.length; i++)\n {\n var parameters = extPart.findInString(partNames[i], theStr);\n if (parameters != null)\n {\n serverBehavior.setParameters(parameters);\n foundMatch = true;\n }\n }\n\n if (foundMatch)\n sbList.push(serverBehavior);\n\n return sbList;\n}", "function extGroup_partPositionMatchesGroup(groupName, partGroup, part, partList)\n{\n var retVal = true;\n\n for (var i=0; retVal && i < partGroup.length; i++)\n {\n var groupPart = partGroup[i];\n\n //only check parts which are both selection relative inserts or aboveHTML and\n // whose search locations match (so we can use the nodeNumber property)\n // Note that for 'aboveHTML' insert locations, we ONLY care if the location weights\n // are the same too.\n if ( (extPart.getIsSelectionRel(part.participantName) && extPart.getIsSelectionRel(groupPart.participantName))\n || (extPart.getIsAroundNode(part.participantName) && extPart.getIsAroundNode(groupPart.participantName))\n || ( extPart.getLocation(part.participantName).indexOf(\"aboveHTML\") != -1\n && extPart.getLocation(part.participantName) == extPart.getLocation(groupPart.participantName)\n )\n )\n {\n //assign the partBefore to the groupPart. This function is probably\n //being called in the group file order, which means the new part\n //would be after any previous parts most of the time.\n var partBefore = groupPart;\n var partAfter = part;\n\n // if they have the same insert location, check their order in the file\n var groupPartLoc = extPart.getLocation(groupPart.participantName);\n var partLoc = extPart.getLocation(part.participantName);\n if (partLoc == groupPartLoc)\n {\n var names = extGroup.getParticipantNames(groupName);\n for (var j=0; j < names.length; j++)\n {\n if (names[j] == groupPart.participantName)\n {\n break;\n }\n else if (names[j] == part.participantName)\n { //swap the order\n partBefore = part;\n partAfter = groupPart;\n break;\n }\n }\n }\n else\n {\n //because the locations are different,\n // use [before, replace, after] as the order.\n if (groupPartLoc.indexOf(\"after\") != -1 ||\n (groupPartLoc.indexOf(\"replace\") != -1 &&\n partLoc.indexOf(\"before\") != -1) )\n {\n partBefore = part;\n partAfter = groupPart;\n }\n }\n\n //check to see if partBefore is between partAfter and the node before it,\n // and partAfter is between partBefore and the node after it\n if ( partBefore.position != null && partAfter.position != null\n && partBefore.position < partAfter.position\n )\n {\n //now check that if parts of the same kind are between them, they are paired\n var count = 0;\n for (var j=partBefore.position + 1; j < partAfter.position; j++)\n {\n if (partList[j].participantName == partBefore.participantName)\n {\n count++;\n }\n if (partList[j].participantName == partAfter.participantName)\n {\n count--;\n }\n if (count < 0)\n { //found partAfter first, bad position\n retVal = false;\n break;\n }\n }\n if (retVal && count != 0)\n { //parts did not match, bad position\n retVal = false;\n }\n\n }\n else\n {\n retVal = false;\n }\n }\n }\n\n return retVal;\n}", "function extPart_findInString(partName, theStr, findMultiple)\n{\n var retVal = null;\n var searchPatts = extPart.getSearchPatterns(partName);\n var quickSearch = extPart.getQuickSearch(partName);\n if (extUtils.findPatternsInString(theStr, quickSearch, searchPatts, findMultiple))\n {\n retVal = extUtils.extractParameters(searchPatts);\n }\n else if (extPart.DEBUG)\n {\n var MSG = new Array();\n MSG.push(\"match failed for participant: \" + partName);\n MSG.push(\"\");\n MSG.push(\"against string:\");\n MSG.push(theStr);\n MSG.push(\"\");\n MSG.push(\"using pattern:\");\n if (quickSearch && theStr.indexOf(quickSearch) == -1) {\n MSG.push(quickSearch);\n }\n else\n {\n for (var j=0; j < searchPatts.length; j++) {\n if (!searchPatts[j].match || !searchPatts[j].match.length) {\n MSG.push(searchPatts[j].pattern);\n }\n }\n }\n alert(MSG.join(\"\\n\"));\n }\n\n return retVal;\n}", "function extPart_getPartType(groupName, partName)\n{\n var retVal = \"\";\n\n if (groupName)\n {\n retVal = dw.getExtDataValue(groupName, \"groupParticipants\", partName, \"partType\");\n }\n\n return retVal;\n}", "function extGroup_getDataSourceFileName(groupName)\n{\n return dw.getExtDataValue(groupName, \"dataSource\");\n}", "function dwscripts_getSBGroupNames(serverBehaviorName)\n{\n //get the group ids matcing that name\n var groupNames = dw.getExtGroups(serverBehaviorName,\"serverBehavior\");\n\n //walk the list of groupNames, and eliminate groups that do not\n // define any information for the current server model\n for (var i=groupNames.length-1; i >= 0; i--) //walk the list backward for removals\n {\n var hasData = false;\n var partNames = dw.getExtDataArray(groupNames[i],\"groupParticipants\");\n\n for (var j=0; j < partNames.length; j++)\n {\n if (dw.getExtDataValue(partNames[j], \"insertText\"))\n {\n hasData = true;\n break;\n }\n }\n if (!hasData)\n {\n groupNames.splice(i,1); // remove this item from the array\n }\n }\n\n return groupNames;\n}", "function returnName(people){\n\tvar arrayOfNames = [];\n\tfor (var i = 0; i < people.length; i++){\n\t\tarrayOfNames.push(people[i].name.first + ' ' + people[i].name.last);\n\t}\n\treturn arrayOfNames;\n}", "function SBParticipant_getName()\n{\n return this.name;\n}", "function extGroup_getWrapsSelection(groupName)\n{\n var retVal = false;\n\n var foundStart = false;\n\n //walk the list of participants\n var partNames = extGroup.getParticipantNames(groupName);\n for (var i=0; i < partNames.length; i++)\n {\n var partWeight = extPart.getWeight(partNames[i]);\n\n if (partWeight == \"wrapSelection\")\n {\n retVal = true;\n break;\n }\n else if (partWeight == \"beforeSelection\")\n {\n foundStart = true;\n }\n else if (partWeight == \"afterSelection\")\n {\n if (foundStart)\n {\n retVal = true;\n break;\n }\n }\n }\n\n return retVal;\n}", "function dwscripts_findGroup(groupName, title, sbConstructor)\n{\n // get the list of server behavior objects\n var sbObjList = extGroup.find(groupName, title, sbConstructor);\n\n return sbObjList;\n}", "function getFamilyNames() {\n\treturn new Promise(async(resolve, reject) => {\n\t\tlet retVal = {};\n\t\t\n\t\tlet request = {\n\t\t\ttable: \"Users\",\n\t\t\tcols: [\"group_concat(firstName || ' ' || lastName, ', ') AS names\", \"familyId\"],\n\t\t\tgroup: \"familyId\"\n\t\t}\n\n\t\ttry {\n\t\t\tlet rows = await db.get(request);\n\t\t\treturn resolve(rows);\n\t\t} catch(err) {\n\t\t\treject(err);\n\t\t}\n\t});\n}", "function getMemberNames() {\n\t\n\tvar args;\n\t\n\tif(arguments.length == 1) {\n\t\tif(arguments[0].constructor === Array) {\n\t\t\targs = arguments[0];\n\t\t} else {\n\t\t\targs = arguments;\n\t\t}\n\t} else {\n\t\targs = arguments;\n\t}\n\t\n\treturn new Promise(async (resolve, reject) => {\n\t\tlet resJson = {};\n\t\t\n\t\tlet filter;\n\t\tif(args.length) {\n\t\t\tfilter = {col: \"userId\", operator: \"IN\", value: \"(\" + args.join(\",\") + \")\"};\n\t\t}\n\t\ttry{\n let rows = await db.get({\n table: \"Users\",\n cols: [\"userId\", \"firstName\", \"lastName\"],\n filter: filter\n });\n\t\t\treturn resolve(rows);\n\t\t} catch(err) {\n\t\t\treturn reject(\"Unable to retrieve necessary data from the server. Please try again later, or contact your server admin if the problem persists.\");\n\t\t}\n\t});\n}", "function extUtils_extractParameters(searchPatterns)\n{\n var parameters = new Object();\n\n //find all the parameters in the current participant,\n for (var i=0; i < searchPatterns.length; i++)\n {\n //check if we have parameters and that a match list was created\n if (searchPatterns[i].paramNames && searchPatterns[i].match)\n {\n //get the list of parameters to extract for this pattern\n var paramList = searchPatterns[i].paramNames.split(\",\");\n\n //get the match information\n var match = searchPatterns[i].match;\n var isMultiple = (match.length > 0 && typeof match[0] == \"object\");\n\n //now, extract the parameters from this pattern\n for (var j=0; j < paramList.length; j++)\n {\n var paramName = paramList[j];\n\n //skip over blank parameter names\n if (paramName)\n {\n if (!isMultiple)\n {\n if (match.length > j+1)\n {\n parameters[paramName] = match[j+1];\n }\n else\n {\n alert(dwscripts.sprintf(MM.MSG_NoMatchForParameter, paramName));\n parameters[paramName] = \"\";\n }\n }\n else\n {\n parameters[paramName] = new Array();\n for (var k=0; k < match.length; k++)\n {\n if (match[k].length > j+1)\n {\n parameters[paramName].push(match[k][j+1]);\n }\n else\n {\n alert(errMsg(MM.MSG_NoMatchForParameter, paramName));\n parameters[paramName].push(\"\");\n }\n }\n }\n }\n }\n }\n }\n\n return parameters;\n}", "function extPart_getWhereToSearch(partName)\n{\n return dw.getExtDataValue(partName, \"searchPatterns\", \"whereToSearch\");\n}", "personListPersonsInAPersonGroupGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonListPersonsInAPersonGroupGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonListPersonsInAPersonGroupGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonListPersonsInAPersonGroupGetPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/persons', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createAuthHandler returns a route middleware to be used by restify. It executes auth.checkSession which another module needs to provide. auth.checkSession needs to determine whether a user has access to a route, based on the users sessionId and authentication info stored for the route.
function createAuthHandler(authRouteInfo) { return function(req, res, next) { var sessionId = req.headers['session-id']; if (!sessionId) { return res.send(403, 'Not logged in.'); } return virgilio.execute( 'auth.checkSession', sessionId, authRouteInfo) .then(function(response) { //Result has the following format: // { result: false, reason: 'I dont like you.' } if (response.result) { req.session = response.session; next(); } else { res.send(403, response.reason); } }) .catch(defaultError) .done(); }; }
[ "configureRoute(app) {\n const storeIssuer = (req, res, next) => {\n const host = req.headers['x-forwarded-host'] || req.headers.host;\n res.locals.issuer = `${req.protocol}://${host}/auth/${this.loginName}`;\n next();\n };\n // configure username/password route\n var v = this.verify.bind(this);\n this.authLib.log.info('adding route to app');\n const loginRoute = '/auth/' + this.loginName + '/verify';\n app.use(loginRoute, storeIssuer);\n app.post(loginRoute, v);\n\n // configure refreshtoken route\n if(this.verifyRefresh) {\n this.authLib.log.info('configuring refresh token route');\n var vr = this.verifyRefresh.bind(this);\n const refreshRoute = '/auth/' + this.loginName + '/token';\n app.use(refreshRoute, storeIssuer);\n app.post(refreshRoute, vr);\n }\n\n // configure well known routes if signing algorithm is RS256\n if(this.authLib.opts.signAlg === 'RS256') {\n this.authLib.log.info('adding openid + jwks routes');\n app.get(\n '/auth/' + this.loginName + '/.well-known/openid-configuration',\n this.openIDConfiguration.bind(this)\n );\n app.get(\n '/auth/' + this.loginName + '/.well-known/jwks.json',\n this.getKeySet.bind(this)\n );\n }\n }", "configureSecurityRoutes(router) {\n const secret = '7ad58489-4781-4049-b136-d6b1744b358e';\n router.post('/authenticate', (req, res) => {\n const username = req.body.username;\n const password = req.body.password;\n if (!username || !password) {\n res.json({});\n }\n else {\n user_1.User.findOne({ username: username }, (err, user) => {\n if (err || !user || user.password !== password) {\n return res.json({});\n }\n let token = jwt.sign(user, secret, {\n expiresIn: 1000\n });\n res.json({\n success: true,\n lifeTime: 1000,\n token: token\n });\n });\n }\n });\n // this.express.use((req: Request, res: Response, next: NextFunction) => {\n // let token = req.body.token || req.query.token || req.headers['x-access-token'];\n // debug('token :' + token);\n // if (!token) {\n // if (req.path === '/authenticate') {\n // next();\n // return;\n // }\n // return res.json(403, {\n // success: false,\n // message: 'No token provided.' });\n // } else {\n // jwt.verify(token, secret, function (err, decoded) {\n // if (err) {\n // return res.json({ success: false, message: 'Not authenticated' });\n // }\n // next();\n // });\n // }\n // });\n }", "function authenticationMiddleware() {\n return (req, res, next) => {\n // console.log(`req.session.passport.user: ${JSON.stringify(req.session.passport)}`);\n //to check if the cookie is still alive and this is done by passport if valid allow to run the next middleware in line\n if(req.isAuthenticated()) {\n return next();\n }\n //else redirect to the register page since it didn't validated\n console.log('cookie not available so you are not allowed to access restricted resources');\n res.redirect('/');\n }\n}", "function authMiddleware(next){\n return function(msg, replier){\n var params = JSON.parse(msg);\n tokenAuthentication(params.token, function(valid){\n if (!valid) {\n return replier(JSON.stringify({ok: false, error: \"invalid_auth\"}));\n } else {\n next(msg, replier);\n }\n });\n }\n}", "function createRoute(req, res) {\n User\n .findOne({email: req.body.email})\n .then((user) =>{\n console.log(user);\n if(!user || !user.validatePassword(req.body.password)){\n req.flash('danger', 'Email or password is incorrect');\n res.status(401).render('sessions/index', {message: 'Wrong credentials'});\n }\n req.session.userId = user.id;\n console.log(req.session);\n\n res.redirect('/films');\n });\n}", "initializeMiddleware() {\n if (this.hasInitialized) throw new Error('authenticated view middleware already initialized');\n this.hasInitialized = true;\n\n const {\n htmlDirectory,\n htmlFilename,\n } = this.configuration;\n\n const trshcmpctrClientRouter = express.Router();\n\n trshcmpctrClientRouter.get('/', [\n handleRenderAuthenticated.bind(null, htmlDirectory, htmlFilename),\n // Redirect to login if not authenticated\n handleRedirect.bind(null, '/login')\n ]);\n\n // Serve application static assets\n trshcmpctrClientRouter.use(express.static(htmlDirectory));\n trshcmpctrClientRouter.use(handleError);\n\n this.router = trshcmpctrClientRouter;\n }", "function authAware(req, res, next) {\n if (req.session.oauth2tokens) {\n req.oauth2client = getClient();\n req.oauth2client.setCredentials(req.session.oauth2tokens);\n }\n\n next();\n\n // Save credentials back to the session as they may have been\n // refreshed by the client.\n if (req.oauth2client) {\n req.session.oauth2tokens = req.oauth2client.credentials;\n }\n }", "_registerAuthHandlers () {\n expose('authenticate', this.authenticate.bind(this), {postMessage: this.postMessage})\n expose('createLink', this.createLink.bind(this), {postMessage: this.postMessage})\n }", "requireAuth(req, res, next) {\n if (!req.session.userId) {\n return res.redirect('/signin');\n }\n next();\n }", "function authenticationProcess(req, res, next) {\n var retries = config.getConfig().authentication.retries || 3,\n attempts = 0;\n\n function processFlow(callback) {\n async.series([\n apply(authenticate, req, res),\n apply(extractRoles, req, res)\n ], callback);\n }\n\n function retry(error, result) {\n if (error && error.name === 'PEP_PROXY_AUTHENTICATION_REJECTED' && attempts < retries) {\n logger.debug('Authentication attempt number %d failed. Retrying.', attempts);\n attempts++;\n process.nextTick(processFlow.bind(null, retry));\n } else if (error) {\n logger.error('[VALIDATION-GEN-003] Error connecting to Keystone authentication: %s', error);\n next(error);\n } else {\n logger.debug('Authentication success after %d attempts', attempts);\n next(null, result);\n }\n }\n\n processFlow(retry);\n}", "static isAuthenticated(req, res, next) {\n const Authorization = req.get('Authorization');\n\n if (Authorization) {\n const token = Authorization.replace('Bearer ', '');\n try {\n // JWTSECRET=some long secret string\n const payload = jwt.verify(token, process.env.JWTSECRET);\n\n // Attach the signed payload of the token (decrypted of course) to the request.\n req.jwt = {\n payload\n };\n\n next();\n } catch {\n // The JSON Web Token would not verify.\n res.sendStatus(401);\n }\n } else {\n // There was no authorization.\n res.sendStatus(401);\n }\n }", "function userOrBackendAuthorization(req, res, next) {\n if (configUtil.getRequireAuth() === false) return next();\n\n const token = getToken(req);\n const adminToken = configUtil.getAdminToken();\n if (req.isAuthenticated()) return next();\n else if (adminToken && token === adminToken) return next();\n else\n return passport.authenticate('jwt', { session: false }, (_err, jwtPayload) =>\n checkScopes(req, res, next, jwtPayload)\n )(req, res, next);\n}", "function createHandler(handlerObject, path) {\n handlerObject = extendHandlerObject(handlerObject, path);\n return function(req, res) {\n var handlerObject = this;\n Promise.cast(req)\n .bind(virgilio)\n .then(handlerObject.validate)\n .then(handlerObject.transform)\n .then(handlerObject.handler)\n .then(function(response) {\n return handlerObject.respond.call(this, response, res);\n })\n .catch(function(error) {\n if (error instanceof virgilio.ValidationError) {\n return handlerObject\n .validationError.call(this, error, res);\n } else {\n return handlerObject.error.call(this, error, res);\n }\n }).done();\n }.bind(handlerObject);\n }", "loginRoute (app) {\n app.post('/' + this.Config.loginPage, this.processLogin);\n }", "function ssoSession(req, res, next, config) {\n var ssoToken = 'ssoSessionId'; // name of sso session ID parameter\n\n // if we have a session, everything is fine\n console.log('check if session is there ...'); // FIXME debugging output\n // check if session is there\n if (req.session && req.session.username) {\n console.log(' --> YES, session there!'); // FIXME debugging output\n next();\n return;\n }\n\n // no session there => SSO process kicks in ...\n\n // check if we got an SSO token\n console.log('check for SSO token ...'); // FIXME debugging output\n if (req.query[ssoToken]) {\n console.log(' --> YES, got SSO token: ' + req.query[ssoToken]); // FIXME debugging output\n\n // fetch user info\n console.log(' --> fetching user info ...'); // FIXME debugging output\n request(config.identityProvider.getIdUrl.replace('${SSO_TOKEN}', req.query[ssoToken]), function(err, response, data) {\n console.log(' --> response from id.json: ' + JSON.stringify(data)); // FIXME debugging output\n if (!err && response.statusCode == 200) {\n console.log(' --> GOT user info: ' + JSON.stringify(data)); // FIXME debugging output\n data = JSON.parse(data);\n req.session.username = 'USER' + data.username;\n } else {\n console.log(' --> ERROR at fetching user info (status code: ' + response.statusCode + ') with SSO token ' + req.query[ssoToken]); // FIXME debugging output\n }\n\n next();\n return;\n });\n\n } else {\n // no SSO token and no session => ask SSO identity provider for identity\n console.log('no SSO token => redirect to SSO auth ...'); // FIXME debugging output\n res.redirect(config.identityProvider.authUrl.replace('${TARGET}', encodeURIComponent(config.appTarget)));\n }\n}", "function initTokenSession(req, res, next) {\n const provider = getProviderToken(req.path);\n return user.createSession(req.user._id, provider, req)\n .then(function(mySession) {\n return Promise.resolve(mySession);\n })\n .then(function (session) {\n session.delivered = Date.now();\n res.status(200).json(session);\n }, function (err) {\n return next(err);\n });\n }", "static create() {\n return new FastHttpMiddlewareHandler();\n }", "static Authorize(req, res, role) {\n return __awaiter(this, void 0, void 0, function* () {\n // Checks if a token is provided\n const token = req.header('x-access-token');\n if (!token) {\n return false;\n }\n const verify = this.verify(token, process.env.TOKEN_SECRET, role);\n if (!verify) {\n return false;\n }\n else if (verify) {\n return true;\n }\n });\n }", "async created () {\n // Create a new instance of OIDC client using members of the given options object\n this.oidcClient = new Oidc.UserManager({\n userStore: new Oidc.WebStorageStateStore(),\n authority: options.authority,\n client_id: options.client_id,\n redirect_uri: redirectUri,\n response_type: options.response_type,\n scope: options.scope\n })\n\n try {\n // If the user is returning to the app after authentication..\n if (\n window.location.hash.includes('id_token=') &&\n window.location.hash.includes('state=') &&\n window.location.hash.includes('expires_in=')\n ) {\n // handle the redirect\n await this.handleRedirectCallback()\n onRedirectCallback()\n }\n } catch (e) {\n this.error = e\n } finally {\n // Initialize our internal authentication state\n this.user = await this.oidcClient.getUser()\n this.isAuthenticated = this.user != null\n this.loading = false\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wikipedia.js wikipedia.org API used to augment the Marvel API search by querying wikipedia.org for content Note: it provides two apis, one for a general query for when the query is generalized and not specific page is in mind. The second is a direct search to an exact known page. Source: performWikiSearch(topic) uses the passed parameter to run a query against the wikipedia API performs an open search on a listed topic and runs a deep search on the first match this is good for those times when you aren't sure of what you are looking for wikipedia is open sourced and does not require an API key to query, bless their hearts.
function performWikiTopicSearch(topic) { // First of two required ajaz calls to get the topics matching our topic search $.ajax({ type: "GET", url: "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + topic + "&callback=?", contentType: "application/json; charset=utf-8", async: false, dataType: "json", noimages: true, success: function (data) { console.log("--------- performWikiSearch() response data ------------"); console.log(data); console.log("----------------------------------------------------------"); // Launch another ajax query using the first named MediaWiki element found $.each(data, function (i, item) { if (i == 1) { var searchData = item[0]; performWikiPageSearch(searchData); } }); }, error: function (errorMessage) { console.log(errorMessage); } }); }
[ "function searchWikipedia (term) {\n\t$results.empty();\n\treturn $.ajax({\n\t url: 'http://en.wikipedia.org/w/api.php',\n\t dataType: 'jsonp',\n\t data: {\n\t\taction: 'opensearch',\n\t\tformat: 'json',\n\t\tsearch: global.encodeURI(term)\n\t }\n\t}).promise();\n }", "function WikipediaAPI() {\n this.baseUrl = 'http://en.wikipedia.org/w/api.php?callback=?';\n this.params = {\n 'action': 'query',\n 'format': 'json',\n 'prop': 'pageimages',\n 'list': 'geosearch',\n 'generator': 'geosearch',\n 'piprop': 'thumbnail|name',\n 'pithumbsize': '144',\n 'pilimit': '2',\n 'gscoord': '40.77|-73.96',\n 'gsradius': '10000',\n 'gslimit': '10',\n 'ggscoord': '40.77|-73.96'\n };\n}", "function searchwiki(marker) {\n var baseUrl = 'https://en.wikipedia.org/w/api.php?action=query&prop=coordinates%7Cpageimages%7Cpageterms&colimit=50&piprop=thumbnail&pithumbsize=144&pilimit=50&wbptterms=description&generator=geosearch&ggscoord=';\n var pos = marker.position;\n var lat = pos.lat();\n var long = pos.lng();\n var restUrl = lat + '%7C+' + long + '&ggsradius=10000&ggslimit=50&format=json';\n return queryWiki(baseUrl + restUrl);\n}", "wiki(title, elClass = \"wiki\"){\r\n const url = `https://en.wikipedia.org/w/api.php?action=query&titles=${title}&prop=extracts&explaintext=1&exintro&exlimit=2&format=json&formatversion=2&origin=*`;\r\n fetch(url)\r\n .then(data => data.json())\r\n .then(function (data){\r\n const wikiNodes = document.getElementsByClassName(elClass);\r\n //iterate over HTMLCollection javascript https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements\r\n [].forEach.call(wikiNodes, function(wikiNode) {\r\n wikiNode.innerHTML = data.query.pages[0].extract\r\n });\r\n // alert(data.query.pages[0].extract)\r\n console.log(data)\r\n return true\r\n })\r\n .catch(function(err){\r\n alert('Error on Loadin Wikipedia data')\r\n return false}); \r\n\r\n\r\n \r\n}", "function sendRequest(url) {\n var userAgentString = navigator.userAgent;\n var xmlhttp = new XMLHttpRequest();\n \n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {\n var data = JSON.parse(xmlhttp.responseText);\n document.getElementById(\"searchQ\").value = \"\";\n \n // get heading: data[1][0]\n // get description: data[2][0]\n // get url link: data[3][0]\n \n var WikiData = {};\n WikiData.heading = data[1][0];\n WikiData.description = data[2][0];\n WikiData.link = data[3][0];\n \n displayResult(WikiData);\n \n }\n };\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.setRequestHeader(\"Content-Type\", \"application/json; charset=UTF-8\");\n xmlhttp.send();\n}", "function req_wiki_category (string) {\r\n var url =\r\n \"https://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:\"+string+\"&cmlimit=100&cmsort=sortkey&format=json&callback=?\"; \r\n $.ajax({\r\n url: url,\r\n type: \"GET\",\r\n async: false,\r\n dataType: \"jsonp\",\r\n success: function(data)\r\n {\r\n \r\n var i = 0;\r\n var ar = new Array();\r\n for(i; i<21; i++) \r\n { \r\n \r\n //funzione per avere elementi random sulla home\r\n var item = data['query']['categorymembers'][Math.floor(Math.random()*data['query']['categorymembers'].length)];\r\n\r\n if(jQuery.inArray(item.title, ar) != -1)\r\n {\r\n while(jQuery.inArray(item.title, ar) != -1)\r\n {\r\n item = data['query']['categorymembers'][Math.floor(Math.random()*data['query']['categorymembers'].length)];\r\n }\r\n }\r\n else {\r\n ar.push(item.title);\r\n }\r\n \r\n $('#categories').append('<div class=\"col-lg-4\"><img id=\"img'+i+'\" class=\"rounded-circle\" width=\"140\" height=\"140\"><h2>'+item.title+'</h2><p><a class=\"btn btn-secondary\" id=\"cat_btn\" name=\"'+item.title+'\" href=\"http://marullo.cs.unibo.it:8000/home/search:'+item.title+'\" role=\"button\">View page &raquo;</a></p></div>'); \r\n get_img_title(item.title,item.pageid, i);\r\n }\r\n },\r\n error: function() \r\n {\r\n alert('Error: req_wiki_category');\r\n }\r\n });\r\n }", "function getWikipediaSearchResults(term) {\n return Observable.create(function forEach(observer) { \n let cancelled = false;\n const encodeTerm = encodeURIComponent(term);\n const url = `https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${encodeTerm}&callback=?`;\n $.getJSON(url,(data) => {\n observer.onNext(data[1]);\n observer.onCompleted();\n }); // getJSON \n return function dispose() {\n cancelled = true;\n }; // dispose\n });\n}", "function searchWikimedia(name, titles) {\n\treturn axios({\n\t\tmethod: 'get',\n\t\turl: searchImagesUrl(titles)\n\t})\n\t\t.then((results) => {\n\t\t\tconst pages = results.data.query.pages;\n\t\t\tconst output = {\n\t\t\t\timgUrl: '',\n\t\t\t\timgInfo: '',\n\t\t\t\tname\n\t\t\t};\n\n\t\t\tfor (const pageid in pages) {\n\t\t\t\tconst page = pages[pageid];\n\n\t\t\t\tif (page.imageinfo && page.imageinfo.length) {\n\t\t\t\t\toutput.imgUrl = page.imageinfo[0].thumburl;\n\t\t\t\t\toutput.imgInfo = page.imageinfo[0].descriptionshorturl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn output;\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.log('Error searching wikimedia:\\n', error);\n\t\t\tthrow error;\n\t\t});\n}", "function marvelWikiSearch(msg, characterName){\n\n // add the character name to the Marvel wiki search url\n marvelWikiUrl = \"http://marvel.com/universe3zx/index.php?ns0=1&search=\" + characterName + \"&title=Special%3ASearch&fulltext=Advanced+search\";\n request(marvelWikiUrl, function (error, response, html) {\n // if no errors and good status code\n // else send an error message because the Marvel sites may be down\n if (!error && response.statusCode < 300){\n // load the page html with cheerio\n $ = cheerio.load(html);\n\n // if a character was found and a result comes back, get the title of the character and url\n // else character might not exist or suggest spelling is checked and try again\n if($('#Page_title_matches + h2 + ul.mw-search-results li:first-of-type').length > 0){\n $('#Page_title_matches + h2 + ul.mw-search-results li:first-of-type').filter(function(){\n marvelWikiPageLink = $(this).find('a').attr('href');\n marvelWikiPageTitle = $(this).find('a').attr('title');\n msg.send(\"I had to do some digging, but I found \" + marvelWikiPageTitle + \" on http://www.marvel.com\" + marvelWikiPageLink + \" . Hope that's the right character.\");\n });\n }else{\n msg.send(\"I couldn't find anything for \"+ characterName +\". Are you sure they are a Marvel character? Can you check the spelling and try again?\");\n }\n }else{\n msg.send(\"Marvel's sites might be down right now, please try again later.\");\n }\n return false;\n }); // end of request\n}", "function makeQueryURL(size, numPages, pagesParams) {\n var queryURL = 'http://en.wikipedia.org/w/api.php?action=query&' +\n 'format=json&redirects&prop=pageimages&pithumbsize='+ size +\n 'px&pilimit=' + numPages + '&titles=' + pagesParams + '&callback=?';\n return queryURL;\n}", "function searchNamesUrl(names) {\n\treturn 'https://en.wikipedia.org/w/api.php?' + querystring.stringify({\n\t\taction: 'query',\n\t\tformat: 'json',\n\t\tprop: 'images',\n\t\ttitles: names.join('|'),\n\t\tredirects: 1,\n\t\timlimit: '500'\n\t});\n}", "function makeExtractURL(numPages, pageParams) {\n var extractURL = 'http://en.wikipedia.org/w/api.php?action=query&' +\n 'prop=extracts&format=json&exsentences=3&explaintext=&exintro=&' +\n 'exlimit=' + numPages + '&titles=' + pageParams + '&callback=?';\n return extractURL;\n}", "function searchElContent(title,content) {\n var match = content.match(templates[targetTemplate].regex);\n if(match) {\n templates[targetTemplate].path(match, function(targetPath){\n if(targetPath) {\n var wpSuggestion = {\n url: wikihost + '/wiki/' +\n encodeURIComponent(title.replace(/ /g,'_'))\n };\n var targetSuggestion = {\n url: templates[targetTemplate].hostname + targetPath\n };\n targetSuggestion.notes='WELP ' + title\n +'\\nCapture: ' + match[0];\n \n var parend = title.match(/^(.*) \\((.*)\\)$/);\n if(parend){\n var scope = parend[2];\n //Easy way to knock out MANY of these scope parentheticals\n if(scope.match(/film$/) || scope.match(/TV series$/)){\n wpSuggestion.scope = scope;\n wpSuggestion.topic = parend[1];\n targetSuggestion.scope = scope;\n targetSuggestion.topic = parend[1];\n } else {\n //I'll probably delete the paren in the title in revision (ie. if it's \"musical\"),\n //but it might be part of the name (ie. some title that ends with parentheses)\n //in which case I'll delete the scope\n wpSuggestion.scope = scope;\n wpSuggestion.topic = title;\n targetSuggestion.scope = scope;\n targetSuggestion.topic = title;\n }\n } else {\n wpSuggestion.topic = title;\n targetSuggestion.topic = title;\n }\n suggest(wpSuggestion);\n suggest(targetSuggestion);\n } else {\n console.log('! WELP:NOID '+title+' | '+match[0]);\n }\n });\n } else {\n console.log('! WELP:TNIEL '+title);\n }\n}", "function searchResult(buton, langId, topicId, materialId)\n{\n\tbuton.addEventListener(\"click\", function(e)\n\t{\n\t\t$(\"#drop_notes\").show();\n\t\t$(\"#material_info\").show();\n\t\t$(\"#download_button\").show();\n\t\tDownloadReq(materialId);\n\t\t/**\n\t\t * Doing the download requirement check for the download button\n\t\t *\n\t\t */\n\t\tvar url = \"downloadPermissionsUM?user_id=\" + user_id + \"&material_id=\" + materialId;\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\tdataType: 'json',\n\t\t\turl: url\n\t\t}).then(function (data) {\n\t\t\ttry {\n\t\t\t\tvar permision = data.content[0].content.permission;\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t}\n\t\t\tif(permision == false)\n\t\t\t{\n\t\t\t\t$(\"#download_button\").hide();\n\t\t\t}\n\t\t\telse if ( permision == true)\n\t\t\t{\n\t\t\t\tvar download = document.getElementById(\"download_button\");\n\t\t\t\t$(\"#download_button\").show();\n\t\t\t\tdownload.href = data.content[0].content.material.link;\n\t\t\t\tdownload.setAttribute('download','');\n\t\t\t}\n\t\t});\n\n\n\n\t\tvar materialCont = document.getElementById(\"material\");\n\t\tvar searchCont = document.getElementById(\"search-container\");\n\t\ttry\n\t\t{\n\t\t\twhile(searchCont.childElementCount!=0)\n\t\t\t{\n\t\t\t\tsearchCont.removeChild(searchCont.childNodes[0]);\n\t\t\t}\n\t\t}\n\t\tcatch (e)\n\t\t{\n\n\t\t}\n\t\t$(\"#myCarousel\").hide();\n\t\t$(\"#material\").show();\n\n\t\tvar AddTopic = document.getElementById('Topics');\n\t\twhile (AddTopic.childElementCount != 0) {\n\t\t\ttry {\n\t\t\t\tAddTopic.removeChild(AddTopic.childNodes[0]);\n\t\t\t}\n\t\t\tcatch (e) {\n\n\t\t\t}\n\t\t}\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\tdataType: 'json',\n\t\t\turl: \"technologies/\" + langId + \"/topics\"\n\t\t}).then(function (data) {\n\t\t\tfor (i of data.content) {\n\t\t\t\tvar topic = document.createElement(\"button\");\n\t\t\t\tvar topic_id= i.content.topic_id;\n\t\t\t\ttopic.className=\"btn btn-primary\";\n\t\t\t\ttopic.type=\"button\";\n\t\t\t\ttopic.name = i.content.name;\n\t\t\t\ttopic.value = topic_id;\n\t\t\t\ttopic.innerHTML = i.content.name;\n\t\t\t\thandleelement(topic_id,topic,langId);\n\t\t\t\tAddTopic.appendChild(topic);\n\t\t\t}\n\t\t});\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\tdataType: 'json',\n\t\t\turl: \"technologies/\" + langId + \"/topics/\" + topicId + \"/materials/\" + materialId\n\t\t}).then(function (data) {\n\n\t\t\tvar showMaterial = document.getElementById('material');\n\t\t\tshowMaterial.style.display = \" initial\";\n\t\t\tshowMaterial.removeChild(showMaterial.childNodes[0]);\n\t\t\tvar material_name= document.getElementById('Material_name');\n\t\t\tvar material_desc= document.getElementById('Material_Desc');\n\t\t\tmaterial_name.innerHTML = data.content.title;\n\t\t\tmaterial_desc.innerHTML = data.content.description;\n\t\t\tshowMaterial.style.display = \" initial\";\n\t\t\tvar type = data.content.type;\n\t\t\tvar source = data.content.link;\n\t\t\tif( type==0 )\n\t\t\t{\n\t\t\t\tvar material = document.createElement(\"img\");\n\t\t\t\tmaterial.name = \"material\"\n\t\t\t\tmaterial.innerHTML = \" test\";\n\t\t\t\tmaterial.src = source;\n\t\t\t\tmaterial.oncontextmenu=\"return false;\"\n\t\t\t\tshowMaterial.appendChild(material);\n\t\t\t}\n\t\t\telse if ( type == 1)\n\t\t\t{\n\t\t\t\tvar material = document.createElement(\"video\");\n\t\t\t\tmaterial.autoplay= true;\n\t\t\t\tmaterial.controls = true;\n\t\t\t\tmaterial.width=\"600\";\n\t\t\t\tmaterial.height=\"360\";\n\t\t\t\tmaterial.src=source;\n\t\t\t\tmaterial.oncontextmenu=\"return false;\";\n\t\t\t\tshowMaterial.appendChild(material);\n\t\t\t}\n\t\t\telse if ( type == 2 )\n\t\t\t{\n\t\t\t\tvar material = document.createElement(\"iframe\");\n\t\t\t\tmaterial.width=\"1000px\";\n\t\t\t\tmaterial.height=\"600px\";\n\t\t\t\tsource = source + \"#toolbar=0&navpanes=0&statusbar=0&view=Fit;readonly=true; disableprint=true;\";\n\t\t\t\tmaterial.src=source;\n\t\t\t\tmaterial.oncontextmenu=\"return false;\";\n\t\t\t\tshowMaterial.appendChild(material);\n\t\t\t}\n\n\t\t\t$(\"myCarousel\").show();\n\t\t\tvar container = document.getElementById('search-container');\n\t\t\tcontainer.style.display=\"none\";\n\t\t});\n\n\t});\n\n}", "function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }", "function searchRequest(query_terms)\n{\n $.ajax\n ({\n type: \"GET\",\n url: \"/search/\",\n data: {'q' : query_terms},\n success: paginateResults\n });\n}", "function getQuery(winControl) { // getQuery() extracts the user's search query from the Millennium searchtool. winControl is the optional parameter used to select an alternate link display.\nvar searchQuery = \"\";\nif (!document.searchtool) { // This section applies when form name=\"searchtool\" does not exist. This case occurs on a \"no hit\" heading browse display, e.g., a subject search on mcrowave.\n\tvar searchArg = document.getElementsByName('searcharg'); // getting the user's search term\n \tfor (var i=0; i<searchArg.length; i++) {\n\t\tsearchQuery = searchArg[i].value;\n \t\t}\n\t\t\n\tif (document.forms[1]){ // this section changes the value of <option value=\"Y\"> KEYWORD</option> from \"Y\" to \"X\" (because I do not use the \"Y\" searchpage option, srchhelp_Y). Because the \"searchtool\" form is unnamed, I am using the DOM structure to address the option value. Because there is no guarantee that the structure will be stable with new software releases, this manipulation may not always work.\n\tif (document.forms[1].elements[0]){\n\tif (document.forms[1].elements[0].options[0]){\n\tif (document.forms[1].elements[0].options[0].value == \"Y\"){ \n\tdocument.forms[1].elements[0].options[0].value = \"X\";\n\t}}}}\n}\n\nelse { // document.searchtool exists on item browse and bib record displays\n\tsearchQuery = document.searchtool.searcharg.value; // get the search term\n\t\nvar testForSearchtype = document.searchtool.searchtype; // this section changes the searchtype Option value from Y to X. For our OPAC, \"Y\" (srchhelp_Y.html, keyword search) is an unnecessary duplicate, and I make this page automatically nav to /search. This caused a problem when customers used searchtool to perform a KW that retrieved no hits; users were taken to opacmenu.html with no No Entries Found message. This code is my workaround solution to this problem.\nif (typeof testForSearchtype != \"undefined\"){\n\t\tfor (var j=0; j<document.searchtool.searchtype.options.length; j++){\n\t\t\tif (document.searchtool.searchtype.options[j].value == \"Y\"){\n\t\t\t\tdocument.searchtool.searchtype.options[j].value = \"X\";\n\t\t\t\t}\n\t\t\t}\t\n\t}\n} // end of else\n\nif (searchQuery.length > 0) { // what to do if there is a search term\n\tvar WSCheck = searchQuery.search(/\\s/);\n\tif (WSCheck != -1) { // what to do if there is a whitespace character in the search term, indicating a multi-term query\n\t\t//searchQuery = searchQuery.replace(/(\\S+)(\\s.*)/, \"$1\"); // retains the first string of characters, and throws away the following whitespace and any subsequent characters \n\t\t//searchQuery = searchQuery.replace(/^(\\S+)(\\s)(\\S+)((\\s.*)?)/, \"$1$3\"); // removes the first whitespace, and throws away an characters following a second whitespace\n\t\tsearchQuery = searchQuery.replace(/^(\\S+)(\\s)(\\S+)(\\s)(\\S+)((\\s.*)?)/, \"$1$3$5\"); // removes the first and second whitespace, and throws away the third whitespace and any subsequent characters.\n\t\t}\n\tif (searchQuery != \"***\") { // Again, what to do next with the search term - but filtering out instances in which the search term is \"***\"\n\t\tvar termArg = \"insertionPoint\"; // \"insertionPoint\" is the id value of the placeholder tag that will eventually display the targetURL (e.g., see bib_display.html).\n\t\tvar termID = document.getElementById(termArg);\n\t\t\tif (!termID) {}\n\t\t\telse { // looking for the condition of the page having a tag with id=\"insertionPoint\".\n\t\t\tvar linkStringfromDocTarget = getDocTarget(searchQuery,winControl); // pass searchQuery to getDocTarget() function, and return a value (a targetURL/linkString)\n\t\t\tif (linkStringfromDocTarget != \"\") { // what to do if there is a OneSearch link to offer\n\t\t\t\ttermID.innerHTML = linkStringfromDocTarget; // replace the HTML of the insertionPoint tag with the targetURL/linkString. NOTE that this only affects the FIRST instance of \"insertionPoint\" on the page. Other instances are ignored.\n\t\t\t\tvar termArg2 = \"displaySwitchforMultisearch\"; // These several lines manage the display of the link to the Library's Multisearch. I want to hide this link when a OneSearch link exists so that it does not compete with the OneSearch link. This display management is performed with a span id=\"displaySwitchforMultisearch\", which is used on srchhelp_X, and the WebBridge resource definition for Multisearch.\n\t\t\t\tvar termID2 = document.getElementById(termArg2);\n\t\t\t\tif (!termID2) {}\n\t\t\t\telse {\n\t\t\t\t\ttermID2.style.display = \"none\"; \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} // end searchQuery.length check condition \n} // end getQuery()", "function WikibaseRdfHint($, mod) {\n\t(function (mod) {\n\t\tif (typeof exports == 'object' && typeof module == 'object') { // CommonJS\n\t\t\tmod(require('codemirror'));\n\t\t} else if (typeof define == 'function' && define.amd) { // AMD\n\t\t\tdefine(['codemirror'], mod);\n\t\t} else { // Plain browser env\n\t\t\tmod(CodeMirror);\n\t\t}\n\t})(function (CodeMirror) {\n\t\t'use strict';\n\n\t\tvar ENTITY_TYPES = {\n\t\t\t\t'http://www.wikidata.org/prop/direct/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/novalue/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/statement/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/statement/value/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/qualifier/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/qualifier/value/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/reference/': 'property',\n\t\t\t\t'http://www.wikidata.org/prop/reference/value/': 'property',\n\t\t\t\t'http://www.wikidata.org/wiki/Special:EntityData/': 'item',\n\t\t\t\t'http://www.wikidata.org/entity/': 'item'\n\t\t\t},\n\t\t\tENTITY_SEARCH_API_ENDPOINT = 'https://www.wikidata.org/w/api.php?action=wbsearchentities&'\n\t\t\t\t+ 'search={term}&format=json&language=en&uselang=en&type={entityType}&continue=0';\n\n\t\tCodeMirror.registerHelper('hint', 'sparql', function (editor, callback, options) {\n\t\t\tif (wikibase_sparqlhint) {\n\t\t\t\twikibase_sparqlhint(editor, callback, options);\n\t\t\t}\n\n\t\t\tvar currentWord = getCurrentWord(getCurrentLine(editor), getCurrentCurserPosition(editor)),\n\t\t\t\tprefix,\n\t\t\t\tterm,\n\t\t\t\tentityPrefixes;\n\n\t\t\tif (!currentWord.word.match(/\\S+:\\S*/)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tprefix = getPrefixFromWord(currentWord.word);\n\t\t\tterm = getTermFromWord(currentWord.word);\n\t\t\tentityPrefixes = extractPrefixes(editor.doc.getValue());\n\n\t\t\tif (!entityPrefixes[prefix]) { // unknown prefix\n\t\t\t\tvar list = [{text: term, displayText: 'Unknown prefix \\'' + prefix + ':\\''}];\n\t\t\t\treturn callback(getHintCompletion(editor, currentWord, prefix, list));\n\t\t\t}\n\n\t\t\tif (term.length === 0) { // empty search term\n\t\t\t\tvar list = [{text: term, displayText: 'Type to search for an entity'}];\n\t\t\t\treturn callback(getHintCompletion(editor, currentWord, prefix, list));\n\t\t\t}\n\n\t\t\tif (entityPrefixes[prefix]) { // search entity\n\t\t\t\tsearchEntities(term, entityPrefixes[prefix]).done(function (list) {\n\t\t\t\t\tcallback(getHintCompletion(editor, currentWord, prefix, list));\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\tCodeMirror.hint.sparql.async = true;\n\t\tCodeMirror.defaults.hintOptions = {};\n\t\tCodeMirror.defaults.hintOptions.closeCharacters = /[]/;\n\t\tCodeMirror.defaults.hintOptions.completeSingle = false;\n\n\t\tfunction getPrefixFromWord(word) {\n\t\t\treturn word.split(':').shift();\n\t\t}\n\n\t\tfunction getTermFromWord(word) {\n\t\t\treturn word.split(':').pop();\n\t\t}\n\n\t\tfunction getCurrentLine(editor) {\n\t\t\treturn editor.getLine(editor.getCursor().line);\n\t\t}\n\n\t\tfunction getCurrentCurserPosition(editor) {\n\t\t\treturn editor.getCursor().ch;\n\t\t}\n\n\t\tfunction getHintCompletion(editor, currentWord, prefix, list) {\n\t\t\tvar completion = {list: []};\n\t\t\tcompletion.from = CodeMirror.Pos(editor.getCursor().line, currentWord.start + prefix.length + 1);\n\t\t\tcompletion.to = CodeMirror.Pos(editor.getCursor().line, currentWord.end);\n\t\t\tcompletion.list = list;\n\n\t\t\treturn completion;\n\t\t}\n\n\t\tfunction searchEntities(term, type) {\n\t\t\tvar entityList = [],\n\t\t\t\tdeferred = $.Deferred();\n\n\t\t\t$.ajax({\n\t\t\t\turl: ENTITY_SEARCH_API_ENDPOINT.replace('{term}', term).replace('{entityType}', type),\n\t\t\t\tdataType: 'jsonp'\n\t\t\t}).done(function (data) {\n\t\t\t\t$.each(data.search, function (key, value) {\n\t\t\t\t\tentityList.push({\n\t\t\t\t\t\tclassName: 'wikibase-rdf-hint',\n\t\t\t\t\t\ttext: value.id,\n\t\t\t\t\t\tdisplayText: value.label + ' (' + value.id + ') ' + value.description + '\\n'\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t\t\t\tdeferred.resolve(entityList);\n\t\t\t});\n\n\t\t\treturn deferred.promise();\n\t\t}\n\n\t\tfunction getCurrentWord(line, position) {\n\t\t\t// TODO This will not work for terms containing a slash, for example 'TCP/IP'\n\t\t\tvar leftColon = line.substring(0, position).lastIndexOf(':'),\n\t\t\t\tleft = line.substring(0, leftColon).lastIndexOf(' '),\n\t\t\t\trightSlash = line.indexOf('/', position),\n\t\t\t\trightSpace = line.indexOf(' ', position),\n\t\t\t\tright,\n\t\t\t\tword;\n\n\t\t\tif (rightSlash === -1 || rightSlash > rightSpace) {\n\t\t\t\tright = rightSpace;\n\t\t\t} else {\n\t\t\t\tright = rightSlash;\n\t\t\t}\n\n\t\t\tif (left === -1) {\n\t\t\t\tleft = 0;\n\t\t\t} else {\n\t\t\t\tleft += 1;\n\t\t\t}\n\t\t\tif (right === -1) {\n\t\t\t\tright = line.length;\n\t\t\t}\n\t\t\tword = line.substring(left, right);\n\t\t\treturn {word: word, start: left, end: right};\n\t\t}\n\n\t\tfunction extractPrefixes(text) {\n\t\t\tvar prefixes = {},\n\t\t\t\tlines = text.split('\\n'),\n\t\t\t\tmatches;\n\n\t\t\t$.each(lines, function (index, line) {\n\t\t\t\t// PREFIX wd: <http://www.wikidata.org/entity/>\n\t\t\t\tif (matches = line.match(/(PREFIX) (\\S+): <([^>]+)>/)) {\n\t\t\t\t\tif (ENTITY_TYPES[matches[3]]) {\n\t\t\t\t\t\tprefixes[matches[2]] = ENTITY_TYPES[matches[3]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn prefixes;\n\t\t}\n\n\t});\n}", "function getRandomArticle(callback) {\n const url = 'https://ja.wikipedia.org/w/api.php?format=json&action=query&generator=random&grnnamespace=0&prop=info&inprop=url&indexpageids';\n \n axios.get(url)\n .then(res => {\n const item = res.data;\n \n // 取得したページのIDを取得\n const pageID = item.query.pageids;\n // ページのタイトルを取得\n const pageTitle = item.query.pages[pageID].title;\n // ページのURLを取得\n const pageUrl = item.query.pages[pageID].fullurl;\n \n // リプライ用のテキスト生成\n const replyText = 'こんな記事はどう😆!?'+'\\n' + \n '【'+pageTitle +'】'+'\\n' +\n pageUrl;\n \n callback(replyText);\n })\n .catch(err => {\n callback(\"ごめん!失敗した!!\");\n console.log(err);\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sustained_clock_speed computed: true, optional: false, required: false
get sustainedClockSpeed() { return this.getNumberAttribute('sustained_clock_speed'); }
[ "updateSpeedPhysics() {\n let speedChange = 0;\n const differenceBetweenPresentAndTargetSpeeds = this.speed - this.target.speed;\n\n if (differenceBetweenPresentAndTargetSpeeds === 0) {\n return;\n }\n\n if (this.speed > this.target.speed) {\n speedChange = -this.model.rate.decelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n\n if (this.isOnGround()) {\n speedChange *= PERFORMANCE.DECELERATION_FACTOR_DUE_TO_GROUND_BRAKING;\n }\n } else if (this.speed < this.target.speed) {\n speedChange = this.model.rate.accelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n speedChange *= extrapolate_range_clamp(0, this.speed, this.model.speed.min, 2, 1);\n }\n\n this.speed += speedChange;\n\n if (abs(speedChange) > abs(differenceBetweenPresentAndTargetSpeeds)) {\n this.speed = this.target.speed;\n }\n }", "getSpeed() {\n return this.model ? this.model.getCurrentSpeedKmHour() : null;\n }", "function calculateSpeed(distance, time){\n return distance / time;\n}", "_calculateTargetedSpeed() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedSpeedDuringLanding();\n }\n\n switch (this.mcp.speedMode) {\n case MCP_MODE.SPEED.OFF:\n return this._calculateLegalSpeed(this.speed);\n\n case MCP_MODE.SPEED.HOLD:\n return this._calculateLegalSpeed(this.mcp.speed);\n\n // future functionality\n // case MCP_MODE.SPEED.LEVEL_CHANGE:\n // return;\n\n case MCP_MODE.SPEED.N1:\n return this._calculateLegalSpeed(this.model.speed.max);\n\n case MCP_MODE.SPEED.VNAV: {\n const vnavSpeed = this._calculateTargetedSpeedVnav();\n\n return this._calculateLegalSpeed(vnavSpeed);\n }\n\n default:\n console.warn('Expected MCP speed mode of \"OFF\", \"HOLD\", \"LEVEL_CHANGE\", \"N1\", or \"VNAV\", but ' +\n `received \"${this.mcp[MCP_MODE_NAME.SPEED]}\"`);\n return this._calculateLegalSpeed(this.speed);\n }\n }", "get speedVariation() {}", "setDefaultSpeed_() {\r\n const {gameSpeed} = this.gameConfig_;\r\n\r\n this.gameSpeed_ = gameSpeed;\r\n this.board_.setBoardSpeed(this.gameSpeed_);\r\n }", "calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }", "increaseSpeed(speedup){\n return this.speed = this.speed + speedup;\n\n }", "notify_speed_update() {\n this.speed_update = true;\n }", "function speedCalc() {\n\t\t\treturn (0.4 + 0.01 * (50 - invadersAlive)) * difficulty;\n\t\t}", "function slower () {\n\tvar extra = speed * 0.3;\n\tif (speed - extra < 0.000002) {\n\t\tspeed = 0.000002;\n\t} else {\n\t\tspeed -= extra;\n\t}\n\ttempSpeed = speed;\n}", "speedCheck () {\r\n if (this.nextVertex.roadWorks) {\r\n this.speed = 1\r\n } else (this.speed = this.masterSpeed)\r\n if(this.nextVertex.speed && this.nextVertex.speed < this.speed) {\r\n this.speed = this.nextVertex.speed\r\n } \r\n \r\n }", "incrementSpeed() {\n\t\t\tswitch (this.speed)\n\t\t\t{\n\t\t\t\tcase 1000:\n\t\t\t\t\tthis.speed = 2000;\n\t\t\t\tbreak;\n\t\t\t\tcase 2000:\n\t\t\t\t\tthis.speed = 5000;\n\t\t\t\tbreak;\n\t\t\t\tcase 5000:\n\t\t\t\t\tthis.speed = 10000;\n\t\t\t\tbreak;\n\t\t\t\tcase 10000:\n\t\t\t\t\tthis.speed = 20000;\n\t\t\t\tbreak;\n\t\t\t\tcase 20000:\n\t\t\t\t\tthis.speed = 50000;\n\t\t\t\tbreak;\n\t\t\t\tcase 50000:\n\t\t\t\t\tthis.speed = 60000; // one second is one minute\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthis.speed = 1000; // one second is one second\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "function motorGetSpeed() {\n return currentSpeedRpm;\n}", "increaseSpeed(value){\r\n this.speed += value;\r\n }", "updateGroundSpeedPhysics() {\n // TODO: Much of this should be abstracted to helper functions\n\n // Calculate true air speed vector\n const indicatedAirspeed = this.speed;\n const trueAirspeedIncreaseFactor = this.altitude * ENVIRONMENT.DENSITY_ALT_INCREASE_FACTOR_PER_FT;\n const trueAirspeed = indicatedAirspeed * (1 + trueAirspeedIncreaseFactor);\n const flightThroughAirVector = vscale(vectorize2dFromRadians(this.heading), trueAirspeed);\n\n // Calculate ground speed and direction\n const windVector = AirportController.airport_get().getWindVectorAtAltitude(this.altitude);\n const flightPathVector = vadd(flightThroughAirVector, windVector);\n const groundSpeed = vlen(flightPathVector);\n let groundTrack = vradial(flightPathVector);\n\n // Prevent aircraft on the ground from being blown off runway centerline when too slow to crab sufficiently\n if (this.isOnGround()) {\n // TODO: Aircraft crabbing into the wind will show an increase in groundspeed after they reduce to slower than\n // the wind speed. This should be corrected so their groundspeed gradually reduces from touchdown spd to 0.\n groundTrack = this.targetGroundTrack;\n }\n\n // Calculate new position\n const hoursElapsed = TimeKeeper.getDeltaTimeForGameStateAndTimewarp() * TIME.ONE_SECOND_IN_HOURS;\n const distanceTraveled_nm = groundSpeed * hoursElapsed;\n\n this.positionModel.setCoordinatesByBearingAndDistance(groundTrack, distanceTraveled_nm);\n\n this.groundTrack = groundTrack;\n this.groundSpeed = groundSpeed;\n this.trueAirspeed = trueAirspeed;\n }", "function setSpeed(s)\r\n{\r\n \r\n ballSpeed = s;\r\n}", "setHightSpeed_() {\r\n this.gameSpeed_ = CONSTANTS.requestAnimationHighSpeed;\r\n\r\n this.board_.setBoardSpeed(this.gameSpeed_);\r\n }", "ms () { return this.now() - this.startMS }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solitary Tap events are simple Responses: RRR TTT TapDowns are part of Responses. RRRRRRR DDD TTT TapCancels are part of Responses, which seems strange. They always go with scrolls, so they'll probably be merged with scroll Responses. TapCancels can take a significant amount of time and account for a significant amount of work, which should be grouped with the scroll IRs if possible. RRRRRRR DDD CCC
function handleTapResponseEvents(modelHelper, sortedInputEvents) { var protoExpectations = []; var currentPE = undefined; forEventTypesIn(sortedInputEvents, TAP_TYPE_NAMES, function(event) { switch (event.typeName) { case INPUT_TYPE.TAP_DOWN: currentPE = new ProtoExpectation( ProtoExpectation.RESPONSE_TYPE, TAP_IR_NAME); currentPE.pushEvent(event); protoExpectations.push(currentPE); break; case INPUT_TYPE.TAP: if (currentPE) { currentPE.pushEvent(event); } else { // Sometimes we get Tap events with no TapDown, sometimes we get // TapDown events. Handle both. currentPE = new ProtoExpectation( ProtoExpectation.RESPONSE_TYPE, TAP_IR_NAME); currentPE.pushEvent(event); protoExpectations.push(currentPE); } currentPE = undefined; break; case INPUT_TYPE.TAP_CANCEL: if (!currentPE) { var pe = new ProtoExpectation(ProtoExpectation.IGNORED_TYPE); pe.pushEvent(event); protoExpectations.push(pe); break; } if (currentPE.isNear(event, INPUT_MERGE_THRESHOLD_MS)) { currentPE.pushEvent(event); } else { currentPE = new ProtoExpectation( ProtoExpectation.RESPONSE_TYPE, TAP_IR_NAME); currentPE.pushEvent(event); protoExpectations.push(currentPE); } currentPE = undefined; break; } }); return protoExpectations; }
[ "function CLC_SR_SpeakFocus_EventAnnouncer(event){ \r\n if (!CLC_SR_Query_SpeakEvents()){\r\n return true;\r\n }\r\n //Announce the URL bar when focused\r\n if (event.target.id==\"urlbar\"){\r\n CLC_SR_SpeakEventBuffer = event.target.value;\r\n CLC_SR_SpeakEventBuffer = CLC_SR_MSG0010 + CLC_SR_SpeakEventBuffer; \r\n CLC_SR_Stop = true; \r\n window.setTimeout(\"CLC_Shout(CLC_SR_SpeakEventBuffer,1);\", 0);\r\n return true;\r\n } \r\n //Not sure about the rest - none for now\r\n return true;\r\n }", "function CLC_SR_SpeakARIAWidgetEvents_EventAnnouncer(event){\r\n if (!CLC_SR_Query_SpeakEvents()){\r\n return;\r\n }\r\n //For an element that the user has to be focused on to control,\r\n //then if the user has speak events turned on it means that the \r\n //element will be the CLC_SR_CurrentAtomicObject since that is\r\n //updated when a focused object is spoken. Therefore, if the\r\n //event target is the same as CLC_SR_CurrentAtomicObject,\r\n //then an attr change was probably caused by the user and the \r\n //change should be announced.\r\n if ( (CLC_SR_CurrentAtomicObject == event.target) && \r\n ((event.attrName == \"checked\") || (event.attrName == \"valuenow\") || (event.attrName == \"activedescendant\")) ){\r\n CLC_SR_SpeakEventBuffer = CLC_GetStatusFromRole(event.target);\r\n CLC_SR_Stop = true; \r\n window.setTimeout(\"CLC_Shout(CLC_SR_SpeakEventBuffer,1);\", 0);\r\n }\r\n\r\n //Try to do something more elegant with tree items, but this works for now.\r\n if (event.attrName == \"expanded\"){\r\n CLC_SR_GoToAndRead(event.target);\r\n }\r\n }", "function botSays(activity) {\n let startTime = Date.now();\n console.log(\"Subscribe event: \" + activity.replyToId + \" from: \" + activity.from.id + \" message: \" + activity.text);\n //console.log(util.inspect(activity, false, null));\n\n // When you only have exactly 1 bot response per user request you can safely do this - otherwise you'll need to support\n // multiple messages coming back from the bot. However, if message is a user prompt - then we don't want to delay\n if ((process.env.useMultipleResponses == 'false' || activity.inputHint == 'expectingInput') && activity.replyToId in responses) {\n msgParts[activity.replyToId] = [activity];\n var reply = createAlexaReply(activity);\n responses[activity.replyToId].push(reply);\n\n let alexaResponseDuration = Date.now() - startTime;\n console.log(\"Alexa Response Duration: \" + alexaResponseDuration);\n\n sendReply(activity.replyToId);\n return;\n }\n\n if (activity.replyToId in msgParts) {\n // Back once again for the renegade master - store additional responses but send them when they've all had chance to come in\n msgParts[activity.replyToId].push(activity);\n }\n else {\n msgParts[activity.replyToId] = [activity];\n\n // Max time to wait for all bot responses to come back before we ship them off to Alexa\n // You can play with the timeout value depending on how long your responses take to come back from your\n // bot in the case of long running processes. However, you must get something back to Alexa within <8 secs\n setTimeout(function () {\n\n var reply = createAlexaReply(activity);\n\n // Double check we've got the original request message - otherwise we have nothing to respond to and it's gameover for this message\n if (activity.replyToId in responses) {\n responses[activity.replyToId].push(reply);\n\n let alexaResponseDuration = Date.now() - startTime;\n console.log(\"Alexa Response Duration: \" + alexaResponseDuration);\n\n sendReply(activity.replyToId);\n }\n else {\n // Didn't receive this one in time :(\n console.log(\"Missed message (not received before timeout): \" + activity.replyToId + \": \" + activity.text);\n }\n }, process.env.multipleResponsesTimeout);\n }\n}", "_onTap(x,y){\n console.log('tap!', x, y)\n //save screen coordinates normalized to -1..1 (0,0 is at center and 1,1 is at top right)\n this._tapEventData = [\n x / window.innerWidth,\n y / window.innerHeight\n ]\n }", "parseEvent() {\n\t\tlet addr = ppos;\n\t\tlet delta = this.parseDeltaTime();\n\t\ttrackDuration += delta;\n\t\tlet statusByte = this.fetchBytes(1);\n\t\tlet data = [];\n\t\tlet rs = false;\n\t\tlet EOT = false;\n\t\tif (statusByte < 128) { // Running status\n\t\t\tdata.push(statusByte);\n\t\t\tstatusByte = runningStatus;\n\t\t\trs = true;\n\t\t} else {\n\t\t\trunningStatus = statusByte;\n\t\t}\n\t\tlet eventType = statusByte >> 4;\n\t\tlet channel = statusByte & 0x0F;\n\t\tif (eventType === 0xF) { // System events and meta events\n\t\t\tswitch (channel) { // System message types are stored in the last nibble instead of a channel\n\t\t\t// Don't really need these and probably nobody uses them but we'll keep them for completeness.\n\n\t\t\tcase 0x0: // System exclusive message -- wait for exit sequence\n\t\t\t\t// console.log('sysex');\n\t\t\t\tlet cbyte = this.fetchBytes(1);\n\t\t\t\twhile (cbyte !== 247) {\n\t\t\t\t\tdata.push(cbyte);\n\t\t\t\t\tcbyte = this.fetchBytes(1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 0x2:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0x3:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0xF: // Meta events: where some actually important non-music stuff happens\n\t\t\t\tlet metaType = this.fetchBytes(1);\n\t\t\t\tlet len;\n\t\t\t\tswitch (metaType) {\n\t\t\t\tcase 0x2F: // End of track\n\t\t\t\t\tthis.skip(1);\n\t\t\t\t\tEOT = true;\n\t\t\t\t\t// console.log('EOT');\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0x51:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tdata.push(this.fetchBytes(len)); // All one value\n\t\t\t\t\tif (this.firstTempo === 0) {\n\t\t\t\t\t\t[this.firstTempo] = data;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x58:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t\tif (this.firstBbar === 0) {\n\t\t\t\t\t\tthis.firstBbar = data[0] / 2 ** data[1];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\t// console.log('Mlen = '+len);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teventType = getIntFromBytes([0xFF, metaType]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tconsole.log('parser error');\n\t\t\t}\n\t\t\tif (channel !== 15) {\n\t\t\t\teventType = statusByte;\n\t\t\t}\n\t\t\tchannel = -1; // global\n\t\t} else {\n\t\t\tswitch (eventType) {\n\t\t\tcase 0x9:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tif (data[1] === 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet ins;\n\t\t\t\t// var ins = currentInstrument[channel]; // Patch out percussion splitting\n\t\t\t\t// TODO: Patch back in, in a new way\n\t\t\t\tif (channel === 9) {\n\t\t\t\t\tthis.trks[tpos].hasPercussion = true;\n\t\t\t\t\t[ins] = data;\n\t\t\t\t} else {\n\t\t\t\t\tins = currentInstrument[channel];\n\t\t\t\t}\n\t\t\t\tlet note = new Note(trackDuration, data[0], data[1], ins, channel);\n\t\t\t\tif ((data[0] < this.trks[tpos].lowestNote && !this.trks[tpos].hasPercussion)\n || this.trks[tpos].lowestNote === null) {\n\t\t\t\t\t[this.trks[tpos].lowestNote] = data;\n\t\t\t\t}\n\t\t\t\tif (data[0] > this.trks[tpos].highestNote && !this.trks[tpos].hasPercussion) {\n\t\t\t\t\t[this.trks[tpos].highestNote] = data;\n\t\t\t\t}\n\t\t\t\tthis.trks[tpos].notes.push(note);\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedInstruments, ins)) {\n\t\t\t\t\tthis.trks[tpos].usedInstruments.push(ins);\n\t\t\t\t}\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedChannels, channel)) {\n\t\t\t\t\tthis.trks[tpos].usedChannels.push(channel);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0xC:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\t// console.log(tpos+': '+data[0]);\n\t\t\t\tcurrentLabel = getInstrumentLabel(data[0]);\n\t\t\t\t// The last instrument on a channel ends where an instrument on the same channel begins\n\t\t\t\t// this.usedInstruments[tpos].push({ins: data[0], ch: channel, start: trackDuration});\n\t\t\t\t// if(notInArr(this.usedInstruments,data[0])){this.usedInstruments.push(data[0])} // Do this for now\n\t\t\t\t[currentInstrument[channel]] = data;\n\t\t\t\tbreak;\n\t\t\tcase 0xD:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t}\n\t\t\tfor (let i = 0; i < noteDelta.length; i++) {\n\t\t\t\tnoteDelta[i] += delta;\n\t\t\t}\n\t\t\tif (eventType === 0x9 && data[1] !== 0) {\n\t\t\t\t// console.log(bpbStuff);\n\t\t\t\tfor (let i = 1; i <= 16; i++) {\n\t\t\t\t\tlet x = (i * noteDelta[channel]) / this.timing;\n\t\t\t\t\tlet roundX = Math.round(x);\n\t\t\t\t\t// console.log(\"Rounded by: \" + roundX-x);\n\t\t\t\t\tthis.trks[tpos].quantizeErrors[i - 1] += Math.round(Math.abs((roundX - x) / i) * 100);\n\t\t\t\t}\n\t\t\t\tnoteDelta[channel] = 0;\n\t\t\t\tthis.noteCount++;\n\t\t\t}\n\t\t}\n\t\tthis.trks[tpos].events.push(new MIDIevent(delta, eventType, channel, data, addr));\n\t\t// console.log('+'+delta+': '+eventType+' @'+channel);\n\t\t// console.log(data);\n\t\t// this.debug++;\n\t\tif (this.debug > 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn EOT;// || this.debug>=4;\n\t}", "function CLC_SR_SpeakMenus_EventAnnouncer(event){\r\n if (!CLC_SR_Query_SpeakEvents()){\r\n return;\r\n }\r\n //Firefox started reporting the <OPTION> element as DOMMenuItemActive at some point;\r\n //this breaks key echo as it creates another event and causes Fire Vox to say \"null\".\r\n //For right now, the decision is that only browser chrome windows should be spoken\r\n //should be spoken by this function. This decision may revisited later with speaking\r\n //SELECT box handled here instead of by keyecho.\r\n if (event.target.localName && event.target.localName.toLowerCase()==\"option\"){\r\n return;\r\n }\r\n \r\n CLC_SR_SpeakEventBuffer = event.target.getAttribute('label');\r\n\r\n if (event.target.getAttribute('type') == 'checkbox'){\r\n if (event.target.getAttribute('checked') == 'true'){\r\n CLC_SR_SpeakEventBuffer = CLC_SR_SpeakEventBuffer + CLC_SR_MSG0009;\r\n } \r\n else { \r\n CLC_SR_SpeakEventBuffer = CLC_SR_SpeakEventBuffer + CLC_SR_MSG0017;\r\n } \r\n }\r\n if (event.target.getAttribute('disabled')){\r\n CLC_SR_SpeakEventBuffer = CLC_SR_SpeakEventBuffer + CLC_SR_MSG0005;\r\n } \r\n if (event.target.getElementsByTagName('menupopup').length > 0){\r\n CLC_SR_SpeakEventBuffer = CLC_SR_SpeakEventBuffer + CLC_SR_MSG0006;\r\n }\r\n CLC_SR_Stop = true; \r\n window.setTimeout(\"CLC_Shout(CLC_SR_SpeakEventBuffer,1);\", 0); \r\n }", "async function getMissedEvents(){\n try {\n let missedToggles = [];\n let timeline = await mySense.getTimeline()\n timeline.items.map(event => {\n if (event.type == \"DeviceWasOn\" && Date.parse(event.start_time) > deviceList[event.device_id].lastOn){\n tsLogger(`Missed toggle event detected for ${event.device_name} (${event.device_id})`);\n missedToggles.push(event.device_id);\n deviceList[event.device_id].lastOn = new Date().getTime();\n }\n })\n\n //Post missed events to SmartThings so we can toggle those on and off\n if (missedToggles.length > 0){\n let options = postOptions;\n postOptions.data = {\"toggleIds\": missedToggles}\n await axios(options)\n }\n } catch (error) {\n tsLogger(`Error getting missed events: ${error.message}`);\n }\n}", "function handlePinchEvents(modelHelper, sortedInputEvents) {\n var protoExpectations = [];\n var currentPE = undefined;\n var sawFirstUpdate = false;\n var modelBounds = modelHelper.model.bounds;\n forEventTypesIn(sortedInputEvents, PINCH_TYPE_NAMES, function(event) {\n switch (event.typeName) {\n case INPUT_TYPE.PINCH_BEGIN:\n if (currentPE &&\n currentPE.isNear(event, INPUT_MERGE_THRESHOLD_MS)) {\n currentPE.pushEvent(event);\n break;\n }\n currentPE = new ProtoExpectation(\n ProtoExpectation.RESPONSE_TYPE, PINCH_IR_NAME);\n currentPE.pushEvent(event);\n currentPE.isAnimationBegin = true;\n protoExpectations.push(currentPE);\n sawFirstUpdate = false;\n break;\n\n case INPUT_TYPE.PINCH_UPDATE:\n // Like ScrollUpdates, the Begin and the first Update constitute a\n // Response, then the rest of the Updates constitute an Animation\n // that begins when the Response ends. If the user pauses in the\n // middle of an extended pinch gesture, then multiple Animations\n // will be created.\n if (!currentPE ||\n ((currentPE.irType === ProtoExpectation.RESPONSE_TYPE) &&\n sawFirstUpdate) ||\n !currentPE.isNear(event, INPUT_MERGE_THRESHOLD_MS)) {\n currentPE = new ProtoExpectation(\n ProtoExpectation.ANIMATION_TYPE, PINCH_IR_NAME);\n currentPE.pushEvent(event);\n protoExpectations.push(currentPE);\n } else {\n currentPE.pushEvent(event);\n sawFirstUpdate = true;\n }\n break;\n\n case INPUT_TYPE.PINCH_END:\n if (currentPE) {\n currentPE.pushEvent(event);\n } else {\n var pe = new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);\n pe.pushEvent(event);\n protoExpectations.push(pe);\n }\n currentPE = undefined;\n break;\n }\n });\n return protoExpectations;\n }", "function addHammerRecognizer(theElement) {\n // We create a manager object, which is the same as Hammer(), but without \t //the presetted recognizers.\n //alert(\"dfadfad\");\n var mc = new Hammer.Manager(theElement);\n \n \n // Tap recognizer with minimal 2 taps\n mc.add(new Hammer.Tap({\n event: 'doubletap',\n taps: 2,\n threshold:5,\n posThreshold:30\n }));\n // Single tap recognizer\n mc.add(new Hammer.Tap({\n event: 'singletap',\n taps:1,\n threshold:5\n }));\n \n \n // we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized.\n mc.get('doubletap').recognizeWith('singletap');\n // we only want to trigger a tap, when we don't have detected a doubletap\n mc.get('singletap').requireFailure('doubletap');\n \n \n mc.on(\"singletap\", function (ev) {\n //alert(\"sfdsfad\");\n //console.log(\"ev\"+ev);\n showDetails(ev);\n \n });\n mc.on(\"doubletap\", function (ev) {\n //showDynamicMap(ev);\n loadPage(\"mapPage\");\n showDynamicMap(ev);\n });\n \n}", "function Tapper() {\n this.rolling = false;\n this.unbounded = false;\n this.tapped = 0;\n this.lastTapped = 0;\n this.interval = 0;\n this.previous = null;\n this.defalutGap = 60;\n this.minInterval = 16;\n this.maxInterval = 3000;\n }", "function handleResponse(event) {\n let elementClicked = event.target; // returns the list element \"<li>3</li>\" that was clicked on\n \n // Record user selection.\n let questionObject;\n\n // Find the questionObject that corresponds to the question the user responded to.\n for (i = 0; i < questionObjects.length; i++) {\n if (document.getElementsByTagName(\"p\")[0].innerText == questionObjects[i].question) {\n questionObjects[i].userResponse = Array.from(elementClicked.parentNode.children).indexOf(elementClicked);\n break;\n }\n }\n // Ask next question if questions are left to be asked. Otherwise, get results.\n if (questionsAlreadyAsked.length == questionObjects.length) {\n document.getElementsByTagName(\"ul\")[0].removeEventListener(\"click\", handleResponse);\n getResults();\n } else {\n askNextQuestion();\n }\n}", "handleBreakClipStarted(event) {\n let data = {};\n this.breakClipStarted = true;\n this.breakClipId = event.breakClipId;\n this.breakClipLength =\n this.breakManager.getBreakClipDurationSec();\n this.qt1 = this.breakClipLength / 4;\n this.qt2 = this.qt1 * 2;\n this.qt3 = this.qt1 * 3;\n\n data.id = this.breakClipId;\n data.action = event.type;\n\n // Adobe Agent specific values.\n data.position = event.index;\n data.length = this.breakClipLength;\n\n\n this.sendData(data);\n }", "function presses(phrase) {\n var phraseArr = phrase.split('');\n var clicks = 0;\n for(var x in phraseArr){\n phraseArr[x] = phraseArr[x].toUpperCase();\n switch(phraseArr[x]){\n case 'A':\n clicks = clicks + 1;\n break;\n\n case 'B':\n clicks = clicks + 2;\n break;\n\n case 'C':\n clicks = clicks + 3;\n break;\n\n case 'D':\n clicks = clicks + 1;\n break;\n\n case 'E':\n clicks = clicks + 2;\n break;\n\n case 'F':\n clicks = clicks + 3;\n break;\n\n case 'G':\n clicks = clicks + 1;\n break;\n\n case 'H':\n clicks = clicks + 2;\n break;\n\n case 'I':\n clicks = clicks + 3;\n break;\n\n case 'J':\n clicks = clicks + 1;\n break;\n\n case 'K':\n clicks = clicks + 2;\n break;\n\n case 'L':\n clicks = clicks + 3;\n break;\n\n case 'M':\n clicks = clicks + 1;\n break;\n\n case 'N':\n clicks = clicks + 2;\n break;\n\n case 'O':\n clicks = clicks + 3;\n break;\n\n case 'P':\n clicks = clicks + 1;\n break;\n\n case 'Q':\n clicks = clicks + 2;\n break;\n\n case 'R':\n clicks = clicks + 3;\n break;\n\n case 'S':\n clicks = clicks + 4;\n break;\n\n case 'T':\n clicks = clicks + 1;\n break;\n\n case 'U':\n clicks = clicks + 2;\n break;\n\n case 'V':\n clicks = clicks + 3;\n break;\n\n case 'W':\n clicks = clicks + 1;\n break;\n\n case 'X':\n clicks = clicks + 2;\n break;\n\n case 'Y' :\n clicks = clicks + 3;\n break;\n\n case 'Z':\n clicks = clicks + 4;\n break;\n case '0':\n clicks = clicks + 2;\n break;\n case '1':\n clicks = clicks + 1;\n break;\n case '2':\n clicks = clicks + 4;\n break;\n case '3':\n clicks = clicks + 4;\n break;\n case '4':\n clicks = clicks + 4;\n break;\n case '5':\n clicks = clicks + 4;\n break;\n case '6':\n clicks = clicks + 4;\n break;\n case '7':\n clicks = clicks + 5;\n break;\n case '8':\n clicks = clicks + 4;\n break;\n case '9':\n clicks = clicks + 5;\n break;\n\n default:\n clicks =clicks + 1;\n }\n }\nreturn clicks;\n}", "function registerClick(e) {\n var desiredResponse = copy.shift();\n var actualResponse = $(e.target).data('tile');\n active = (desiredResponse === actualResponse);\n checkLose();\n }", "function handleSentenceTwoIntent(session, response) {\n var speechText = \"\";\n var repromptText = \"\";\n\n\n if (session.attributes.stage = session.attributes.sentence) { // = session.attributes.sentence\n if (session.attributes.stage === 1) {\n //Retrieve the first sentence setup text.\n speechText = session.attributes.sentence;\n\n //Advance the stage of the dialogue.\n session.attributes.stage = 2;\n var sentenceID = Math.floor(Math.random() * SENTENCE_LIST.length);\n session.attributes.sentenceTwo = SENTENCE_LIST[sentenceID].sentenceTwo;\n speechText = session.attributes.sentenceTwo;\n repromptText = \"Repeat after me\" + speechText;\n \n } else {\n session.attributes.stage = 1;\n speechText = \"That's not how you say it! It is\" + session.attributes.sentence;\n\n repromptText = \"You can say, skip or repeat please.\"\n }\n } else {\n\n //If the session attributes are not found, the sentence must restart. \n speechText = \"Sorry, I couldn't understand the statement. \"\n + \"You can say, tell me a sentence!\";\n\n repromptText = \"You can say, tell me a sentence!\";\n }\n\n var speechOutput = {\n speech: '<speak>' + speechText + '</speak>',\n type: AlexaSkill.speechOutputType.PLAIN_TEXT\n };\n var repromptOutput = {\n speech: '<speak>' + repromptText + '</speak>',\n type: AlexaSkill.speechOutputType.PLAIN_TEXT\n };\n response.ask(speechOutput, repromptOutput);\n}", "function call_control_gather_using_speak(f_call_control_id, f_tts_text, f_gather_digits, f_gather_max, f_client_state_s) {\n\n var l_cc_action = 'gather_using_speak';\n var l_client_state_64 = null;\n\n if (f_client_state_s)\n l_client_state_64 = Buffer.from(f_client_state_s).toString('base64');\n\n var options = {\n url: 'https://api.telnyx.com/calls/' +\n f_call_control_id +\n '/actions/' +\n l_cc_action,\n auth: {\n username: f_telnyx_api_key_v1,\n password: f_telnyx_api_secret_v1\n },\n form: {\n payload: f_tts_text,\n voice: g_ivr_voice,\n language: g_ivr_language,\n valid_digits: f_gather_digits,\n max: f_gather_max,\n client_state: l_client_state_64 //if lobby level >> null\n }\n };\n\n request.post(options, function (err, resp, body) {\n if (err) {\n return console.log(err);\n }\n console.log(\"[%s] DEBUG - Command Executed [%s]\", get_timestamp(), l_cc_action);\n console.log(body);\n });\n}", "function cmdQCPause_ClickCase10() {\n console.log(\"cmdQCPause_ClickCase10\");\n if (config.strSkipWOTrackingPrompt) {\n setupPauseCase20();\n } else {\n var answer = false;\n $.confirm({\n title: 'Confirm!',\n content: \"Confirm to pause QC?\",\n buttons: {\n confirm: function () {\n answer = true;\n },\n cancel: function () {\n $.alert('Canceled!');\n }\n }\n });\n\n //var answer = confirm(\"Confirm to pause QC?\");\n //todo to implement, trackingdefault ok in model so that default button can change\n //if (config.TrackingDefaultOK) {\n // productionPauseCase20();\n //} else {\n // if (answer) {\n // productionPauseCase20();\n // }\n //}\n\n if (answer) {\n cmdQCPause_ClickCase20();\n }\n }\n }", "function listenForEVRYTHNGEvents() {\n //We search for the TTS enabled thngs based on the identifiers\n var filterString = 'identifiers.tts=*';\n evrythng.thng().read({\n params: {\n filter: filterString\n }\n }).then(function (thngs) {\n\n thngs.forEach(function (thng) {\n subscribeToThng(thng);\n });\n });\n}", "_SurveyQuestionLoop() {\n if (this.survey_run_status == SURVEY_SKIPPING) {\n return Scheduler.Event.NEXT;\n }\n\n let continueRoutine = true;\n switch (this.trialStage) {\n // Haven't asked question, render current input\n case 0:\n this.question.setAutoDraw(true);\n this.currentInput.setAutoDraw(true);\n this.trialStage = this.currentInput.name == \"CONTINUOUS\" ? \n TAKING_CONTINUOUS : TAKING_DISCRETE;\n break;\n // Waiting for user input on discrete input\n case TAKING_DISCRETE: {\n let input = this.psychoJS.eventManager.getKeys({keyList: this.currentInput.getKeys()});\n if (input.length > 0) {\n let key = input[0].name || input[0];\n let behavior = this.currentInput.optionSelected(key);\n if (this.currentData.choice == null) {\n this.currentData.choice = key;\n this.currentData.RT = this.clock.getTime();\n this.currentData.value = behavior.value;\n } else {\n this.currentData.specify.push({\n question: this.question.text,\n choice: key,\n RT: this.clock.getTime(),\n value: behavior.value\n });\n }\n this.specify = behavior.specify;\n if (behavior.skip) {\n this.skipIndex = behavior.skip.index;\n }\n this.trialStage = DISPLAY_RESPONSE;\n this.clock.reset();\n }\n }\n break;\n // User answered, taking specification input\n case TAKING_CONTINUOUS: {\n let input = this.psychoJS.eventManager.getKeys({keyList: this.currentInput.getKeys()});\n for (const key of input) {\n let keyName = input[0].name || input[0];\n if (keyName === 'return' || keyName === 'enter') {\n let behavior = this.currentInput.optionSelected();\n if (this.currentData.choice == null) {\n this.currentData.choice = undefined;\n this.currentData.RT = this.clock.getTime();\n this.currentData.value = behavior.value;\n } else {\n this.currentData.specify.push({\n question: this.question.text,\n choice: undefined,\n RT: this.clock.getTime(),\n value: behavior.value\n });\n }\n this.specify = behavior.specify;\n this.trialStage = DISPLAY_RESPONSE;\n this.clock.reset();\n break;\n } else {\n this.currentInput.keyIn(keyName);\n }\n }\n }\n break;\n // User answered, show what they answered\n case DISPLAY_RESPONSE:\n if (this.clock.getTime() >= this.linger) {\n this.currentInput.reset();\n // If no more specifies, the switch is done\n if (!this.specify) {\n // Check if skip was set\n if (this.skipIndex != \"none\") {\n this.survey_run_status = SURVEY_BEGIN_SKIP;\n }\n this.trialStage = -1;\n // Otherwise, reset the loop to the beginning\n } else {\n this._buildLoopStimuli(this.specify);\n this.psychoJS.eventManager.clearEvents();\n this.trialStage = 0;\n }\n }\n break;\n // Done with question\n default:\n this.question.setAutoDraw(false);\n continueRoutine = false;\n break;\n }\n\n if (continueRoutine) {\n return Scheduler.Event.FLIP_REPEAT;\n } else {\n return Scheduler.Event.NEXT;\n }\n }", "function calendarAppointment(results, calendarId) { // results is returned from getResults()\r\n for (i = 0; i < results.length; i++) {\r\n // Set start and end times based on results inputted to Google Forms\r\n let time = results[i][3]; // Format: '2021-02-04 15:00'\r\n let timeStart = time.substring(0,10) + 'T' + time.substring(11,16) + ':00'; // Format: '2021-02-04T15:00'\r\n let timeEnd = time.substring(0,10) + 'T' + time[11] + (parseInt(time[12]) + 1).toString() + ':00:00'; // 1 hour after start\r\n \r\n // Create the Google Calendar event\r\n let event = {\r\n \"summary\": 'This is the Google Calendar event for your tutoring appointment.',\r\n  \"start\": {\r\n    \"dateTime\": timeStart,\r\n \"timeZone\": \"America/New_York\"\r\n    },\r\n \"end\": {\r\n   \"dateTime\": timeEnd,\r\n \"timeZone\": \"America/New_York\",\r\n   },\r\n    \"conferenceData\": {\r\n   \"createRequest\": {\r\n     \"conferenceSolutionKey\": {\r\n      \"type\": \"hangoutsMeet\"\r\n   }, \r\n     \"requestId\": generateId()\r\n    }\r\n }\r\n   };\r\n \r\n // Add the event to the Google Calendar\r\n event = Calendar.Events.insert(event, calendarId, {\"conferenceDataVersion\": 1});\r\n \r\n // Display Google Meet link\r\n Logger.log(event.hangoutLink)\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
player turn that do addTroops, attack and move
function turn (player_id){ var num_troops = player_id.count_territory()/3; for (var i=0;i<num_troops;i++){ addTroops( player_id, territory); } attack (player_id, from, to); move(player_id, from, to, number); }
[ "pursueDo() {\n // always try to face\n this.facePlayer();\n this.noAttack();\n // if not close enough to attack, also pursue\n if (!this.alivePlayerInRange(this.getParams().attackRange)) {\n this.moveForward();\n }\n }", "function opponentTurn(){\n\t\tif(matchProceed)\n\t\t{\n\t\t\tattack(enemyP, playerC);\n\t\t}\n\t\telse {\n\t\t\tcheckGame();\n\t\t\tconsole.log(\"Game is over.\");\n\t\t}\n\t\topponentLock = false;\n\t\t\n\t}", "move(tile) {\r\n if (this.player === this.map.cp) {\r\n if (!this.player.moved) {\r\n this.tile.unit = null\r\n this.tile = tile;\r\n tile.unit = this;\r\n this.mapX = tile.mapX;\r\n this.mapY = tile.mapY;\r\n this.hasFocus = false;\r\n this.pos = tile.pos;\r\n this.player.moved = true;\r\n if (tile.village) {\r\n if (tile.village.owner !== this.player) {\r\n tile.village.enemyStartTurn = this.map.turnCount;\r\n tile.village.attackedBy = this.player;\r\n } else {\r\n tile.village.enemyStartTurn = null;\r\n tile.village.attackedBy = null;\r\n }\r\n }\r\n }\r\n }\r\n }", "function oteleport(err) {\n var tmp;\n if (err) {\n if (rnd(151) < 3) {\n /*\n 12.4.5 - you shouldn't get trapped in solid rock with WTW\n */\n if (player.WTW == 0) {\n updateLog(`You are trapped in solid rock!`)\n died(264, false); /* trapped in solid rock */\n }\n else {\n updateLog(`You feel lucky!`)\n }\n }\n }\n\n if (player.TELEFLAG == 0 && level != 0) {\n changedDepth = millis(); // notify when depth changes to '?'\n }\n\n player.TELEFLAG = 1; /* show ? on bottomline if been teleported */\n if (level == 0) {\n tmp = 0;\n } else if (level < MAXLEVEL) {\n tmp = rnd(5) + level - 3;\n if (tmp >= MAXLEVEL)\n tmp = MAXLEVEL - 1;\n if (tmp < 1)\n tmp = 1;\n } else {\n tmp = rnd(3) + level - 2;\n if (tmp >= MAXLEVEL + MAXVLEVEL)\n tmp = MAXLEVEL + MAXVLEVEL - 1;\n if (tmp < MAXLEVEL)\n tmp = MAXLEVEL;\n }\n player.x = rnd(MAXX - 2);\n player.y = rnd(MAXY - 2);\n if (level != tmp) {\n newcavelevel(tmp);\n }\n positionplayer();\n}", "function playerAttack(light, medium, heavy, magic)\n {\n if (light)\n {\n $(\"#attackLight\").click(function()\n {\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getLightWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getLightWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getLightDmgTotal()*doubleDamage*doubleLight*critical)));\n });\n }\n if (medium)\n {\n $(\"#attackMedium\").click(function()\n {\n mediumAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getMediumWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getMediumWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getMediumDmgTotal()*doubleDamage*doubleMedium*critical)));\n });\n }\n if (heavy)\n {\n $(\"#attackHeavy\").click(function()\n {\n heavyAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getHeavyWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getHeavyWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getHeavyDmgTotal()*doubleDamage*doubleHeavy*critical)));\n });\n }\n if (magic)\n {\n $(\"#attackMagic\").click(function()\n {\n magicAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getMagic()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getMagic()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getMagicDmgTotal()*doubleDamage*critical)));\n });\n }\n }", "function attack() {\n\tplayer_attack += 5;\n\topponent_hp -= getRandNum();\n}", "pass() {\n // in progress: getting the canPass functionality to work.\n // send info to server --> fact that player did not play cards\n //if (this.canPass) {\n //}\n //;else (document.getElementById(\"error_message_game\").innerHTML = \"you cannot pass on the first turn\");\n\n\t document.getElementById(\"error_message_game\").innerHTML = \"\";\n play_cards();\n }", "function takeAIturn () {\n const ships = state.shipArray.filter(s => s.owner === state.playerTurn)\n const viewHexes = Object.entries(getUpdatedViewMask(state)).filter(([k, v]) => v > 1).map(([k, v]) => Hex.getFromID(k))\n\n ships.forEach(ship => {\n for (let i = 0; i < 5; i++) {\n const { attacks, moves } = findPossibleActions(ship.hex, ship)\n if (attacks.length && Math.random() > 0.5) {\n const attack = attacks[Math.floor(Math.random() * attacks.length)]\n applyDamage(ship, getShipOnHex(attack), true, getTerrainDefVal(getShipOnHex(attack), attack))\n state.history[subTurn()].push({ type: 'attack', rand: Math.random(), path: [attack, ship.hex] })\n } else if (moves.length && Math.random() > 0.5) {\n const [move, ...hist] = moves[Math.floor(Math.random() * moves.length)]\n if (!getTerrainDamage(ship, move) || Math.random() > 0.5) {\n ship.hex = move\n applyTerrainDamage(ship, getTerrainDamage(ship, move))\n state.history[subTurn()].push({ type: 'move', rand: Math.random(), path: [move, ...hist] })\n }\n }\n }\n })\n\n const tech = data.techs[Math.floor(Math.random() * data.techs.length)]\n const player = state.playerData[state.playerTurn]\n\n if (!player.tech[tech.tech] && player.money >= tech.cost && Math.random() > 0.5) {\n player.tech[tech.tech] = true\n player.money -= tech.cost\n }\n\n viewHexes.forEach(hex => {\n const menu = makeBuildBar(hex)\n if (menu.length && Math.random() > 0.5) {\n const choice = menu[Math.floor(Math.random() * menu.length)]\n onTopPanelItemClicked(choice, hex)\n }\n })\n}", "function moveSomething(e) {\n\t\t\tfunction moveLeftRight(xVal){\n\t\t\t\tvar newX = xVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = newX;\n\t\t\t\tboard.player.y = board.player.y;\n\t\t\t\tboard.position[newX][board.player.y] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction moveUpDown(yVal){\n\t\t\t\tvar newY = yVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = board.player.x;\n\t\t\t\tboard.player.y = newY;\n\t\t\t\tboard.position[board.player.x][newY] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction enemiesMove(){\n\t\t\t\tif (!board.enemy1.enemyDead)\n\t\t\t\t\tenemy1Move.makeMove();\n\t\t\t\tif (!board.enemy2.enemyDead)\n\t\t\t\t\tenemy2Move.makeMove();\n\t\t\t\tif (!board.enemy3.enemyDead)\n\t\t\t\t\tenemy3Move.makeMove();\n\t\t\t}\n\t\t\tfunction checkForWin(){\n\t\t\t\tif (board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\t\t\tconsole.log(\"You Win!!!!! *airhorn*\" )\n\t\t\t\t\tboard.player.eraseThis();\n\t\t\t\t\t//board.potion1.eraseThis();\n\t\t\t\t\t//board.potion2.eraseThis();\n\t\t\t\t\tctx.beginPath();\n\t\t\t\t\tctx.font = \"128px Georgia\";\n\t\t\t\t\tctx.fillStyle = \"#00F\";\n\t\t\t\t\tctx.fillText(\"You Win!!\", 40, 320);\n\t\t\t}\n\t\t\t}\n\t\t\tfunction restoreHealth(xVal,yVal){\n\t\t\t\tvar x = xVal;\n\t\t\t\tvar y = yVal;\n\t\t\t\tif (board.position[x][y] == 5){\n\t\t\t\t\tboard.player.restoreHealth();\n\t\t\t\t\tif(board.potion1.x == x && board.potion1.y == y)\n\t\t\t\t\t\tboard.potion1.eraseThis()\n\t\t\t\t\telse \n\t\t\t\t\t\tboard.potion2.eraseThis();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!board.player.playerDead || board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\tswitch(e.keyCode) {\n\t\t\t\tcase 37:\n\t\t\t\t\t// left key pressed\n\t\t\t\t\tvar newX = board.player.x - 1;\n\t\t\t\t\tif(board.player.x == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Left was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 38:\n\t\t\t\t\t// up key \n\t\t\t\t\tvar newY = board.player.y - 1;\n\t\t\t\t\tif(board.player.y == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t console.log(\"Up was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\t// right key pressed\n\t\t\t\t\tvar newX = board.player.x + 1;\n\t\t\t\t\tif(board.player.x == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Right was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 40:\n\t\t\t\t\t// down key pressed\n\t\t\t\t\tvar newY = board.player.y + 1;\n\t\t\t\t\tif(board.player.y == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Down was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \n\t\t\t}\n\t\t\t//console.log(\"heres our current player position in moveSomething \"+board.player.x + board.player.y);\n\t\t\t}\t//console.log(\"heres our previous player position in moveSomething \"+board.player.xPrev + board.player.yPrev);\t\t\n\t\t}", "function execute(rover, commands, turn){\n \n switch(commands[turn]){\n\n case \"f\":\n moveForward(rover);\n break;\n\n case \"b\":\n moveBackward(rover);\n break;\n\n case \"l\":\n turnLeft(rover);\n break;\n\n case \"r\":\n turnRight(rover);\n break;\n\n case undefined:\n //There is not more turns for this rover\n break;\n }\n}", "function playerTurn() {\n setMessage(turn + \"'s turn\");\n }", "fight(d){\n // check player range\n if(this.canAttack(30,50,d)){\n damagePlayer(attackDamage);\n // this.bump(player,15);\n player.impactForce.x+=Math.min(Math.max(this.x-player.x,-d),d);\n this.attackAndCool();\n }\n this.regen();\n }", "do_cpu_move() {\n if (this.current_player == this.opening.player_colour) {\n throw new Error(\"it is not the CPUs turn\");\n }\n setTimeout(function() {\n this.make_move(this.get_next_move());\n }.bind(this), CPU_MOVE_DELAY);\n }", "attack(opponent) {\n \n // console.log which character was attacked and how much damage was dealt\n console.log(`${this.name} attacked ${opponent.name}`);\n // Then, change the opponent's hitPoints to reflect this\n opponent.hitPoints -= this.strength;\n\n }", "cpuAttack(gameboard){\n let row, column;\n let attackHit = null;\n if(this.lastHit.coords != null){\n if(this.enemyShipsRemaining.slice(-1) == this.lastHit.coords.length){\n this.lastHit.backtracked = true;\n } else {\n [row, column] = this.lastHit.coords[0].split(' ');\n row = parseInt(row);\n column = parseInt(column);\n if(this.lastHit.horizontal || this.lastHit.horizontal === null){\n // Try attacking the left if you haven't already\n if(!(column == 0 || this.playHistory.includes([row, column - 1].join(\"\")))){\n attackHit = this.sendAttack(row, column - 1, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row, column - 1].join(' '));\n this.lastHit.horizontal = true;\n }\n // otherwise try attacking to the right if you haven't already\n } else if(!(column + 1 == gameboard.height || this.playHistory.includes([row, column + 1].join(\"\")))){\n attackHit = this.sendAttack(row, column + 1, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row, column + 1].join(' '));\n this.lastHit.horizontal = true;\n }\n } else if(this.lastHit.horizontal && this.lastHit.backtracked === false){\n // This branch handles the event where you KNOW the current ship is horizontal\n // and you have reached a dead end.\n // Here backTrackColumn is used to find the next end that is still in the grid and has not been\n // attacked.\n // First checks left, then checks right.\n\n // This is pretty darn ugly, but it guarantees that the CPU will finish every ship it starts\n // attacking.\n\n // However, it also guarantees it will always fire an extra shot for every ship.\n let backTrackColumn = column - 1;\n // If the tile to the left of the current tile was a hit, that means your most recent shot\n // was to the right and was a miss.\n // So you want to access this.lastHit.coords to find the first shot from the sequence and shoot to\n // the left.\n // If the tile to the left is not in lastHit.coords at all, that means you want to check all the way\n // to the right\n this.lastHit.backtracked = true;\n if(this.lastHit.coords.includes([row, backTrackColumn].join(' '))){\n backTrackColumn = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[1]) - 1;\n } else {\n backTrackColumn = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[1]) + 1;\n }\n // If the opposite side's tile is already attacked, this ship is sunk, so you want to move on\n if(backTrackColumn >= 0 && backTrackColumn < gameboard.width && !this.playHistory.includes([row, backTrackColumn].join(\"\"))){\n attackHit = this.sendAttack(row, backTrackColumn, gameboard);\n if(attackHit){\n this.lastHit.coords.push([row, backTrackColumn].join(' '));\n this.lastHit.coords.reverse();\n }\n }\n }\n }\n // If the current target is not horizontally placed AND you have not fired an attack yet\n if(!this.lastHit.horizontal && attackHit === null){\n // Try attacking above if you haven't already\n if(!(row == 0 || this.playHistory.includes([row - 1, column].join(\"\")))){\n attackHit = this.sendAttack(row - 1, column, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row - 1, column].join(' '));\n this.lastHit.horizontal = false;\n }\n // otherwise try attacking below if you haven't already\n } else if(!(row + 1 == gameboard.height || this.playHistory.includes([row + 1, column].join(\"\")))){\n attackHit = this.sendAttack(row + 1, column, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row + 1, column].join(' '));\n this.lastHit.horizontal = false;\n }\n } else if(this.lastHit.horizontal === false && this.lastHit.backtracked === false){\n // If you cannot attack directly above or below, try attacking the opposite end of the current line.\n // If it is a miss, then you know that the ship targeted by lastHit is fully sunk.\n this.lastHit.backtracked = true;\n let backTrackRow = row - 1;\n if(this.lastHit.coords.includes([backTrackRow, column].join(' '))){\n backTrackRow = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[0]) - 1;\n } else {\n backTrackRow =parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[0]) + 1;\n }\n if(backTrackRow >= 0 && backTrackRow < gameboard.height && \n !this.playHistory.includes([backTrackRow, column].join(\"\"))){\n attackHit = this.sendAttack(backTrackRow, column, gameboard);\n if(attackHit){\n this.lastHit.coords.push([backTrackRow, column].join(' '));\n this.lastHit.coords.reverse();\n }\n }\n }\n }\n }\n }\n // If you made it through the code above and attackHit is still null, attack randomly.\n if(attackHit === null){\n if(this.lastHit.backtracked){\n this.enemyShipsRemaining.splice(this.enemyShipsRemaining.indexOf(this.lastHit.coords.length), 1);\n }\n // For now, if you make it through the 4 previous and can't take a shot, that means you have already\n // shot all of the surrounding tiles.\n // Reset lastHit\n this.lastHit.coords = null;\n this.lastHit.horizontal = null;\n this.lastHit.backtracked = false;\n attackHit = this.randomAttack(gameboard);\n }\n return attackHit;\n }", "movePiece(p_index, t_index) {\n // Pull variables out of loop to expand scope\n let piece = null;\n let o_tile = null;\n let t_tile = null;\n\n // Look for old and new tiles by index\n for (let line of this.board) {\n for (let tile of line) {\n if (tile.index === p_index) {\n // Grap piece and old tile\n piece = tile.piece;\n o_tile = tile;\n }\n if (tile.index === t_index) {\n // Grab target tile\n t_tile = tile;\n }\n }\n }\n\n // Only move piece if old tile has one to move and move id valid\n // Make sure you can't take out your own pieces\n if (o_tile.piece && t_tile.valid) {\n if (o_tile.piece.color === this.turn) {\n if (t_tile.piece) {\n if (o_tile.piece.color !== t_tile.piece.color) {\n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n } else { \n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n }\n }\n\n // Reset all valid tags\n for (let line of this.board) {\n for (let tile of line) {\n tile.valid = false;\n }\n }\n }", "moving() {\n\n let divId = this.piece.id\n this.totalMoves++\n\n if (this.totalMoves > 1) {\n this.currentTile++\n }\n\n //If the token hasn't made a full round, do not allow it into a color zone\n if (this.currentTile > TILE_BEFORE_ROLLEROVER && this.totalMoves <= COMPLETE_ROUND_TILE_COUNT) {\n this.currentTile = 1\n }\n\n //If token moved 51 places, it can now enter it's colored zone\n if (this.totalMoves == TILE_BEFORE_ROLLEROVER) {\n this.currentTile = this.zoneTile\n }\n\n //If token reaches winning tile, put it in the center box and set win, if not, play normal\n if (this.currentTile == (this.endTile + 1)) {\n let classOfWin = this.piece.classList[0]\n this.piece.classList.add('win')\n $('#'+divId).detach().appendTo($('#'+classOfWin))\n this.inPlay = false\n message.textContent = 'You got a token to the end!'\n checkWin()\n } else {\n $('#'+divId).detach().appendTo($('.box[data-tile-number=\"'+ this.currentTile +'\"]'))\n }\n }", "function playFight(p1, p2) {\n\tvar manaSpent = 0;\n\tvar turnCounter = 0;\n\twhile (true) {\n\t\t// player turn\n\t\t// run effects TODO\n\t\trunEffects(currentEffects, p1, p2);\n\t\t// age/expire effects TODO\n\t\tturnCounter++;\n\t\t// get decision\n\t\tconsole.log(p1, p2);\n\t\tvar decision = makePlayerDecision(p1, p2);\n\t\tconsole.log(decision);\n\t\tif (decision.mana > p1.mana)\n\t\t\treturn -manaSpent;\n\t\tmanaSpent += decision.mana;\n\t\tp1.mana -= decision.mana;\n\t\tif (decision.type === 'immediate') {\n\t\t\t// perform damage/heal/etc TODO\n\t\t\tif (decision.damage) { p2.hit -= decision.damage; }\n\t\t\tif (decision.heal) { p1.hit += decision.damage; }\n\t\t} else if (decision.type === 'effect') {\n\t\t\t// OR add effect TODO\n\t\t}\n\t\t// check for death TODO\n\t\tif (p1.hit <= 0) return -manaSpent;\n\n\t\t// boss turn\n\t\t// run effects TODO\n\t\t// age/expire effects TODO\n\t\tturnCounter++;\n\t\t// attack \n\t\tp1.hit -= calcDamage(p2, p1);\n\n\t\t// check for death\n\t\tif (p2.hit <= 0) return manaSpent;\n\t}\n\tif (true) {\n\t\tconsole.log(manaSpent);\n\t}\n}", "attackAndCool(){\n this.animate(1);\n this.nextAttack = this.counter+this.attackInterval;\n this.attackTimeout=setTimeout(function(tar){tar.animate(0);},400,this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches markers from the backend and adds them to the map.
function fetchMarkers() { fetch('/markers').then(response => response.json()).then((markers) => { markers.forEach( (marker) => { createMarkerForDisplay(marker.lat, marker.lng, marker.content)}); }); }
[ "function fetchMarkers(){\n fetch('/markers')\n .then((response) => response.json())\n .then((markers) => {\n markers.forEach((marker,i) => {\n addDisplayMarker(marker.lat, marker.lng, marker.content, marker.landmark, marker.ratings);\n });\n });\n}", "function addMarkers(map) {\n // create AJAX request\n var xhttp = new XMLHttpRequest();\n\n // define behaviour for a response\n xhttp.onreadystatechange = function() {\n if(this.readyState == 4 && this.status == 200) {\n hotels = JSON.parse(xhttp.responseText);\n for(i=0; i<hotels.length; i++) {\n // convert parts of the hotels address variables and concatenate them\n var address = hotels[i].number + \" \" + hotels[i].street + \", \" + hotels[i].suburb + \", \" + hotels[i].city + \", \" + hotels[i].state + \", \" + hotels[i].country;\n var markerTitle = \"Hotel Name: \" + hotels[i].hotelName + \"\\nPrice: \" + hotels[i].price;\n\n // geocode address variable\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode({\"address\":address}, function(results,status) {\n // if valid location\n if(status = \"OK\") {\n var marker = new google.maps.Marker({\n position: results[0].geometry.location,\n title: markerTitle\n });\n marker.setMap(map)\n }\n });\n }\n } \n }\n\n // initiate connection\n xhttp.open(\"GET\", \"hotels.json\", true);\n\n // send request\n xhttp.send();\n}", "addMarkerToDatabase(newObservation, map) {\n\n let configObj = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify(newObservation)\n };\n\n fetch(this.baseURL, configObj)\n .then(function(response) {\n return response.json()\n })\n .then(json => {\n let obs = json.data\n let observation = new Observation(obs.id, obs.attributes.name, obs.attributes.description, obs.attributes.category_id, obs.attributes.latitude, obs.attributes.longitude)\n observation.renderMarker(map)\n })\n .catch(function(error) {\n alert(\"ERROR! Please Try Again\");\n console.log(error.message);\n });\n }", "function populateSitesOnMap() {\n\tclearMap();\n $.when(loadSites()).done(function(results) {\n for (var s in sites) {\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(sites[s].location.x, sites[s].location.y),\n map: map,\n // label: \"A\",\n icon: {url: 'http://maps.gstatic.com/mapfiles/markers2/marker.png'},\n //animation: google.maps.Animation.DROP,\n title: sites[s].name\n });\n\n markers.push(marker);\n marker.setMap(map);\n bindInfoWindow(marker, map, infowindow, sites[s]);\n }\n });\n}", "async function updateMarkers() {\n if (markerListCache.length > 0) {\n markerListCache.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n } else {\n $.ajax({\n type: 'GET',\n url: `${baseRemoteURL}markers`,\n dataType: 'json',\n async: true,\n cache: true,\n success(data) {\n markerListCache = data;\n data.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n },\n });\n }\n jQuery('.time-marker').on('click', function () {\n jumpToTime(this.text);\n johng.updateClock();\n johng.play();\n });\n}", "function createMarkers(result) {\n // console.log(result); \n for (var i=0; i < result.length; i++) {\n\n var latLng = new google.maps.LatLng (result[i].lot_latitude, result[i].lot_longitude); \n\n var marker = new google.maps.Marker({\n position: myLatlng,\n title: result [i].lot_name,\n customInfo: {\n name: result[i].lot_name,\n address: result[i].lot_address,\n available: result[i].spot_id\n };\n });\n\n// To add the marker to the map, call setMap();\nmarker.setMap(map);\n\ncreateMarkers(result);\n };\n }", "function loadMap(clickedMap,callback){\n // Get id value of item\n var selectedID = clickedMap.children(\"td\").attr(\"id\");\n // Get the complete data for the selected item\n var txn, req, store, idx, dataArray = []; \n // Request the index for the specified objectStore\n txn = db.instance.transaction('zipcodeData', 'readonly');\n store = txn.objectStore('zipcodeData');\n // Request the record by ID\n req = store.get(selectedID);\n req.onsuccess = function(e){\n // Add the locationData to the dataArray\n dataArray.push(e.target.result);\n txn = db.instance.transaction('locationData', 'readonly');\n store = txn.objectStore('locationData');\n // Request the record by ID\n req = store.get(selectedID);\n req.onsuccess = function(e){\n dataArray.push(e.target.result);\n // Display the results\n callback(dataArray);\n };\n };\n }", "function passToMap() {\n let startBar = [STORE.brewList[0].longitude, STORE.brewList[0].latitude];\n let otherBars = [];\n STORE.brewList.forEach((bar) => {\n otherBars.push([bar.longitude, bar.latitude, bar.name]);\n });\n removeMarkers();\n recenter(startBar);\n addMarker(otherBars);\n}", "function updateMap() {\n\tif (myKeyWords == \"\") {\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\treturn ;\n\t}\n\t$.post(\"/search/\", {\n\t\tuserPos:myMarker.getPosition().toUrlValue(),\n\t\tkeyWords:myKeyWords,\n\t}, function(data, status){\n\t\t/* Cancel all the old k-near-markers */\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\t\n\t\t/* Return result from django backend */\n\t\tvar dataJSON = $.parseJSON(data);\n\t\t\n\t\t$(\"#BestMap\").attr(\"src\", dataJSON.BestMap);\n\t\t\n\t\t/* Display the new k-near-markers*/\n\t\t$.each(dataJSON.Pos, function(i, item){\n\t\t\tif (i < MAX_K){\n\t\t\t\t//alert(item.Lat + ';' + item.Lng);\n\t\t\t\tkNearMarkers[i].setPosition({lat:item.Lat, lng:item.Lng});\n\t\t\t\tkNearMarkers[i].setVisible(true);\n\t\t\t\tkNearMarkers[i].setTitle(item.Name + \"\\nAddr: \" + item.Addr \n\t\t\t\t+ \".\\nPCode: \" + item.Pcode);\n\t\t\t\t\n\t\t\t\tif (i < MAX_PANEL) {\n\t\t\t\t\t$(\"#name\"+i).text(item.Name);\n\t\t\t\t\t$(\"#info\"+i).text(\"Address: \" + item.Addr + \". PCode: \" + item.Pcode);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t//$( \"#rtnMsg\" ).text( data );\n\t});\n\t//$( \"#test_input\" ).text( this.value );\n}", "function add_markers(img_id, lat, lng){\n\t\tvar marker = new google.maps.Marker({\n\t\t\ttitle: \"car\",\n\t\t\ticon: images[img_id]\n\t\t});\n\n\t\tvar latlng = new google.maps.LatLng(lat, lng);\n\t\tmarker.setPosition(latlng);\n\t\tmarker.setMap($scope.map);\n\n\t\tmarkers.push(marker);\t\t\t\n\t}", "refreshMap() {\n this.removeAllMarkers();\n this.addNewData(scenarioRepo.getAllEvents(currentScenario));\n this.showAllMarkers();\n }", "function updateDatapoints() {\n\t\t//remove all markers from the map in order to be able to do a refresh\n\t\tmarkers.clearLayers();\n\t\tmarkers_list = {};\n\t\t//for every datapoint\n\t\tbyId.top(Infinity).forEach(function(p, i) {\n\t\t\t//create a marker at that specific position\n\t\t\tvar marker = L.circleMarker([p.latitude,p.longitude]);\n\t\t\tmarker.setStyle({fillOpacity: 0.5,fillColor:'#0033ff'});\n\t\t\t//add the marker to the map\n\t\t\tmarkers.addLayer(marker);\n\t\t});\n\t}", "function initMapWithCoords() {\n // First reset map\n setMapOnAll(null);\n\n var marker;\n\n // Call addMarker for each user in users\n // Create a marker for each user in users\n for (var user in users) {\n console.log(user);\n console.log(users[user][\"lat\"] + \" \" + users[user][\"lon\"]);\n\n marker = new google.maps.Marker({\n position: new google.maps.LatLng(users[user][\"lat\"], users[user][\"lon\"]),\n map: map,\n label: users[user][\"uid\"]\n });\n markerStore.push(marker);\n\n if (users[user][\"uid\"] === initials) {\n map.setCenter(marker.getPosition());\n }\n\n if (zoom_counter === 0){\n map.setZoom(15);\n zoom_counter++;\n }\n\n console.log(\"Called\");\n }\n}", "function addMarker(cache)\n{\n\ticonOptions.iconUrl = RESOURCES_DIR + cache.kind + \".png\";\n\ticonOptions.shadowUrl = RESOURCES_DIR + (cache.status == \"A\" \n && filters[\"Archived\"]\n && document.getElementById(\"datepicker\").value >= cache.last_log\n ? \"Archived\" : \"Alive\") + \".png\";\n\tvar marker = L.marker([cache.latitude, cache.longitude], {icon: L.icon(iconOptions)});\n markers.push(marker);\n\tmarker\n\t\t.bindPopup(\"<b>Code</b>: \" + cache.code + \"<br />\" +\n \"<b>Owner</b>: \" + cache.owner + \"<br />\" +\n \"<b>Latitude</b>: \" + cache.latitude + \"<br />\" +\n \"<b>Longitude</b>: \" + cache.longitude + \"<br />\" +\n \"<b>Altitute</b>: \" + cache.altitude + \"<br />\" +\n \"<b>Kind</b>: \" + cache.kind + \"<br />\" +\n \"<b>Size</b>: \" + cache.size + \"<br />\" +\n \"<b>Difficulty</b>: \" + cache.difficulty + \"<br />\" +\n \"<b>Terrain</b>: \" + cache.terrain + \"<br />\" +\n \"<b>Favorites</b>: \" + cache.favorites + \"<br />\" +\n \"<b>Founds</b>: \" + cache.founds + \"<br />\" +\n \"<b>Not_Founds</b>: \" + cache.not_founds + \"<br />\" +\n \"<b>State</b>: \" + cache.state + \"<br />\" +\n \"<b>County</b>: \" + cache.county + \"<br />\" +\n \"<b>Publish</b>: \" + cache.publish + \"<br />\" +\n \"<b>Status</b>: \" + cache.status + \"<br />\" +\n \"<b>Last_Log</b>: \" + cache.last_log + \"<br />\")\n\t\t\t.bindTooltip(cache.name)\n\t\t\t\t.addTo(map);\n}", "updateItineraryAndMapByArray(places){\n let newMarkerPositions = [];\n this.setState({placesForItinerary: places});\n places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));\n this.setState({markerPositions: newMarkerPositions});\n this.setState({reverseGeocodedMarkerPositions: []});\n }", "function refreshMarkers(data) {\n\n // remove all currently visible markers\n clearMarker(markersArray);\n\n // parse the AIS data to extract the vessels\n var vessels = parseXml(data);\n\n // create and return GoogleMaps markers for each of the extracted vessels\n jQuery.extend(true, markersArray, convertToGoogleMarkers(map,vessels));\n\n}", "function markMap()\n\t{\n\t\tstrResult=req.responseText;\n\n\t\tfltLongitude=getValue(\"<Longitude>\",\"</Longitude>\",11);\n\t\tfltLatitude=getValue(\"<Latitude>\",\"</Latitude>\",10);\n\t\tif( fltLongitude==\"\" || fltLatitude==\"\")\n\t\t{\n\t\t\tshowSearchResultsError('No information found',\"WARNING\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// First Clear any Previous Error Messages \t\n\t\t\tdocument.getElementById(\"divMapErrorBox\").innerHTML=\"\";\n\t\t\tdocument.getElementById(\"divMapErrorBox\").style.visibility=\"visible\";\n\t\t\t\n\t\t\t// Create Html \n\t\t\tstrHtml=\"<table cellspacing=0 cellpadding=0 border=0>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Longitude:</b></td><td width=5></td><td>\"+fltLongitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Latitude:</b></td><td width=5></td><td>\"+fltLatitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"</table>\";\n\t\t\t\n\t\t\t// Save Location in Global Variables \n\t\t\t//G_CURRENT_POINT=new YGeoPoint(fltLatitude,fltLongitude);\n\t\t\t\n\t\t\t//Show Marker \n\t \t showMarker(fltLatitude, fltLongitude,13,\"\",strHtml);\n\t \t \n\t \t //document.getElementById('mapContainer').innerHTML=\"Problems ..........\";\n\t\t} \n\t}", "function addMarker(rest_add,count){\n var address = rest_add;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location,\n icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+ (count+1) +'|e74c3c|000000'\n });\n markers.push(marker);\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n\n}", "function getLocations() {\n // Initialize the geocoder.\n var geocoder = new google.maps.Geocoder();\n var coords = [];\n\n // Geocode the address for the neighbor homes\n for (var i=0, len=homes.length; i<len; i++) {\n var addr = homes[i].address + ', ' + homes[i].cityStateZip;\n geocoder.geocode({\n address: addr,\n componentRestrictions: { locality: 'Missouri' }},\n function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n coords.push(results[0].geometry.location);\n if (coords.length == homes.length) {\n createMarkers(coords);\n ko.applyBindings(new MyView());\n }\n } else {\n window.alert('Error from geocode API (' + status + ') address: ' + addr)\n }\n });\n }\n}", "function addStadiums() {\n\n var stadiumMarkers = stadiums.map(function(stadium, i){\n \n // Add marker for each stadium\n var marker = new google.maps.Marker({\n map: stadiumMap,\n draggable: false,\n animation: google.maps.Animation.DROP,\n position: stadium.location,\n title: stadium.name,\n icon: 'assets/images/rugby_ball.png'\n });\n\n // Add info bubble\n var infowindow = new google.maps.InfoWindow({\n content: stadium.info,\n maxWidth: 200\n });\n\n // When user clicks on the marker, show info bubble and update hotel map\n marker.addListener('click', function () {\n closeOtherInfo();\n \n // Show the Stadium name bubble\n infowindow.open(stadiumMap, marker);\n otherInfo[0] = infowindow;\n\n // Perform hotel search for this stadium\n updateHotelsMap(i);\n });\n\n return marker;\n });\n\n // Add the markers\n var stadiumMarkerCluster = new MarkerClusterer(stadiumMap, stadiumMarkers,{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the full type for %%name%%.
encodeType(name) { const result = this.#fullTypes.get(name); (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, "name", name); return result; }
[ "function getTypeIdentifier(Repr) {\n\t return Repr[$$type] || Repr.name || 'Anonymous';\n\t }", "createOrReplaceType(name) {\n\t\treturn this.declareType(name);\n\t}", "function getTypeName(type) {\n // property is other type or Kite Module, pass the original type to this filter function\n // so it can create right objects\n // if type is already in args, use the existing one, else create a new arg\n let idx = args.indexOf(type);\n let typename;\n if (idx === -1) {\n typename = '_' + type.name;\n // if another type has a same name, but prototype is different, give it a new name\n // this may happen in namespaces, two diferent namespaces both have the same object, \n // `type.name` only give the name\n if (argnames.includes(typename)) {\n typename += argnames.length;\n }\n argnames.push(typename);\n args.push(type);\n }\n else {\n typename = argnames[idx];\n }\n return typename;\n }", "_createType (name) {\n\n\t\tif ( name !== undefined) AssertUtils.isString(name);\n\n\t\tconst getNoPgTypeResult = NoPgUtils.get_result(NoPg.Type);\n\n\t\treturn async data => {\n\n\t\t\tdata = data || {};\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tdata.$name = '' + name;\n\t\t\t}\n\n\t\t\tconst rows = await this._doInsert(NoPg.Type, data);\n\n\t\t\tconst result = getNoPgTypeResult(rows);\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tawait this.setupTriggersForType(name);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t};\n\n\t}", "function getBlockType(name) {\n return blockTypes[name] || false;\n }", "function createCustomTypeName(type, parent) {\n var parentType = parent ? parent.key : null;\n var words = type.split(/\\W|_|\\-/);\n if (parentType) words.unshift(parentType);\n words = words.map(function (word) {\n return word[0].toUpperCase() + word.slice(1);\n });\n return words.join('') + 'Type';\n}", "enterSimpleTypeName(ctx) {\n\t}", "nameFormat(name) {\n return name;\n }", "function TTypeParam(name) {\n this.name = name;\n}", "function resolveKind(id) {\n \t\t\t\t var k=resolveKindFromSymbolTable(id);\n \t\t\t\t\t\tif (!k) {\n \t\t\t\t\t\t\tif (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t k=\"CLASS_NAME\";\n \t\t\t\t\t\t } else if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t k=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t}\n \t\t\t\t\t }\n \t\t\t\treturn k;\n \t\t }", "function longSpecType( )\n{\n var stype = \"Onbekend\";\n\n if(respecConfig.specType != null) \n {\n var stype = respecParams.validSpecTypes[respecConfig.specType].txt;\n }\n console.log(\"\\t\\tLong SpecType is [\" + stype + \"]\");\n return( stype );\n}", "function resolveKind(id) {\n \t\t\t\t var k=resolveKindFromSymbolTable(id);\n \t\t\t\t\t\tif (!k) {\n \t\t\t\t\t\t if (options.exprType) {\n \t\t\t\t\t\t\t if (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t\t\t k=\"CLASS_NAME\";\n \t\t\t\t\t\t\t } else if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t\t k=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t }\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t\tk=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t } else if (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t\t\tk=\"CLASS_NAME\";\n \t\t\t\t\t\t\t }\n \t\t\t\t\t\t\t}\n\n \t\t\t\t\t }\n \t\t\t\t\t\treturn k;\n \t\t }", "visitImplementation_type_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function findTheType(someVar) {\n return typeof someVar;\n}", "_typeExists(name) {\n\t\tlet self = this;\n\t\tif (_.isString(name) && self._cache.types.hasOwnProperty(name)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn do_select(self, NoPg.Type, name).then(function(types) {\n\t\t\treturn (types.length >= 1) ? true : false;\n\t\t});\n\t}", "function updateUserType(name)\n {\n var userType = USER_TYPE.normal;\n \n // Update userList\n for (var i = 0; i < userList.length; i++)\n {\n if (name == userList[i].name)\n {\n // Check if name is in admin list\n if (adminList.indexOf(name) != -1)\n {\n userList[i].userType = USER_TYPE.admin;\n userType = USER_TYPE.admin;\n break;\n }\n \n // Check if name is in mod list\n if (modList.indexOf(name) != -1)\n {\n userList[i].userType = USER_TYPE.mod;\n userType = USER_TYPE.mod;\n break;\n }\n }\n }\n \n // Update userInfo\n for (var i = 0; i < userInfo.length; i++)\n {\n if (name == userInfo[i].name)\n {\n userInfo[i].userType = userType;\n break;\n }\n }\n \n syncUserList();\n \n // Tell user about new type\n var id = socketIdByName(name);\n io.sockets.socket(id).emit('userTypeSync', userType);\n \n return userType;\n }", "getTranslationString(type) {\n let userString;\n let tts = this.get('typeToString');\n userString = tts[type];\n\n if (userString === undefined) {\n for (let ts in tts) {\n if (type.toLowerCase().indexOf(ts) !== -1) {\n userString = tts[ts];\n break;\n }\n }\n }\n\n if (userString === undefined) {\n userString = type;\n }\n\n return userString;\n }", "get computeTypeName() {\n return this.getStringAttribute('compute_type_name');\n }", "function type () {\n // Find the maximum number of characters in code file so as not to go over\n maxIndex = typerCode.length;\n\n // Set up typeHelper call intervals to be letterTiming, or the timing between each\n // letter being printed\n setInterval (typeHelper, letterTiming);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watch and update style.css for debugging
function watchCSS() { fs.watch(path.join(paths.client, "/style.css"), updateCSS); }
[ "function update_style() {\n\tvar style = get_style();\n\tif (style !== null) {\n\t\tvar cssName = \"chroma_\" + style + \".css\";\n\t\tvar cssPath = \"inc/css/\" + cssName;\n\t\tvar elem = document.getElementById(\"chroma_style\");\n\t\telem.href = cssPath;\n\t}\n}", "function watchFiles() {\n watch(\n ['static/scss/*.scss', 'static/scss/**/*.scss'],\n { events: 'all', ignoreInitial: false },\n series(sassLint, buildStyles)\n );\n}", "function injectCSS() {\r\n\t\tvar styleTag = document.createElement(\"style\");\r\n\t\tstyleTag.innerText = css;\r\n\t\tdocument.head.appendChild(styleTag);\r\n\t\tcssInjected = true;\r\n\t}", "function css() {\n const sassStream = gulp.src('app/style/app.scss')\n .pipe(sass().on('error', sass.logError));\n\n const files = bowerData.appInstalls.css\n .map(item => `bower_components/${item}`);\n files.push('app/style/**/*.css');\n\n return merge(sassStream, gulp.src(files))\n .pipe(gulpif(isProduction, cleanCss({ rebase: false })))\n .pipe(concat('project.css', { newLine: '\\n' }))\n .pipe(getStreamOutput('css'));\n}", "reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }", "function watchFiles() {\n gulp.watch(assets.scss + '/**/*.scss', gulp.series(css, jekyllBuild, browserSyncReload));\n gulp.watch(assets.js + '/src/**/*.js', gulp.series(scripts, jekyllBuild, browserSyncReload));\n gulp.watch(assets.img + '/**/*', images);\n gulp.watch(assets.sprites + '/**', gulp.series(sprites, renameSprites, cleanSprites));\n gulp.watch(['*.html', '_includes/*.html', '_layouts/*.html', '_posts/*'], gulp.series(jekyllBuild, browserSyncReload));\n}", "function updateStyle() {\r\n\tif (settings.darkThemeSettings) {\r\n\t\t//dark theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#0F0F0F\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#a53737\");\r\n\t} else {\r\n\t\t//light theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#000000\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#f55555\");\r\n\t}\r\n}", "function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }", "function ensureCSSAdded() {\n\t if (!cssNode) {\n\t cssNode = document.createElement(\"style\");\n\t cssNode.textContent = \"/* ProseMirror CSS */\\n\" + accumulatedCSS;\n\t document.head.insertBefore(cssNode, document.head.firstChild);\n\t }\n\t}", "function changeCSS(oldCss,newCss){\n //changeCSS(\"main.css\",\"main2.css\");\n\n var oldLink = $('link[rel=stylesheet][href*=\"'+oldCss+'\"]');\n if(oldLink.length < 1){\n console.log(\"computer said nnnoooo\");\n return;\n }\n //get path of old css\n var path = oldLink.attr(\"href\");\n var pathArray = path.split('/');\n var filename = pathArray.pop();\n path = pathArray.join(\"/\")+\"/\";\n\n //remove old css\n $('link[rel=stylesheet][href=\"'+path+oldCss+'\"]').remove();\n\n //add new css\n var script_tag = document.createElement('link');\n script_tag.setAttribute(\"href\",path+newCss);\n script_tag.setAttribute(\"type\",\"text/css\");\n script_tag.setAttribute(\"rel\",\"stylesheet\");\n\n var headElement = (document.getElementsByTagName(\"head\")[0] || document.documentElement);\n headElement.appendChild(script_tag);\n\n}", "function addStyles() {\n\t styles.use();\n\t stylesInUse++;\n\t}", "function css() {\n return src(settings.source + '/scss/*.scss')\n .pipe(sass())\n .on('error', gutil.log)\n .pipe(autoprefixer('last 1 version', 'ie 9', 'ios 7'))\n .pipe(rename({ suffix: '.min' }))\n .pipe(cleanCss({ level: 2 }))\n .pipe(dest(settings.build + '/assets/css'))\n .pipe(dest(settings.umbraco + '/assets/css'));\n}", "function add_update_style_event_listener() {\n\twindow.addEventListener(\"message\", function(event) {\n\t\tif (event.data == \"update_style\") {\n\t\t\tupdate_style();\n\t\t}\n\t});\n}", "function watchTask() {\n // watch(\n // [files.cssPath, files.jsPath, files.imgPath],\n // parallel(cssTask, jsTask, imgSquash)\n // );\n watch([files.cssPath, files.jsPath], parallel(cssTask, jsTask));\n}", "function send_update_style_event() {\n\tfor (i = 0; i < frames.length; i++) {\n\t\tframes[i].window.postMessage(\"update_style\", \"*\");\n\t}\n}", "function style(req, res) {\n\tconsole.log(\"router.style() -> CSS Request URL: \" + req.url)\n\tconsole.log(\"router.style() -> CSS Request Method: \" + req.method)\n\n\tif (req.url.indexOf(\".css\") !== -1) {\n\t\tconsole.log(\" - inside style route\");\n\n renderer.css(\"main\", res);\n res.end();\n }\n}", "function applyStyles() {\n let debugStyles = \"\";\n\n // Generate styles for debug selectors:\n if (options.debugSelectors.length > 0) {\n options.debugSelectors.forEach((debugClass) => {\n if (!isValidClass(debugClass)) {\n return;\n }\n\n var elements = document.querySelectorAll(`.${debugClass}`);\n if (elements.length > 0) {\n elements.forEach((element, index) => {\n /**\n * Check if a debug message has already been appended to this element.\n * This can happen if an element has multiple classes listed for debugging.\n * If true, we need to append the current `debugClass` to the existing message,\n * to avoid creating extra elements that will end up overlapping and become unreadable.\n */\n var existingDebugElement = element.querySelector(\".debug-message\");\n\n if (existingDebugElement) {\n var lineBreak = document.createElement(\"div\");\n existingDebugElement.appendChild(lineBreak);\n existingDebugElement.innerHTML += `.${debugClass}`;\n return;\n }\n\n // Ensure that screenreaders have proper context around the debug messages:\n var a11yMessage = document.createElement(\"span\");\n a11yMessage.setAttribute(\n \"style\",\n \"position:absolute;height:1px;width:1px;overflow: hidden;clip:rect(1px,1px,1px,1px);white-space:nowrap;\"\n );\n a11yMessage.innerHTML = \"Debugging class: \";\n\n // Create a new element with a unique ID to display debug info:\n var debugElement = document.createElement(\"div\");\n debugElement.classList = \"debug-message\";\n var debugID = `debug-message-${index}`;\n debugElement.id = debugID;\n debugElement.appendChild(a11yMessage);\n debugElement.innerHTML += `.${debugClass}`;\n element.appendChild(debugElement);\n\n // Get accurate dimensions of element being debugged:\n var rect = element.getBoundingClientRect();\n var computedStyle = window.getComputedStyle(element, null);\n var height = computedStyle.getPropertyValue(\"height\");\n\n debugStyles += `\n .${debugClass} > .debug-message#${debugID} {\n position: absolute;\n z-index: 100000000;\n background-color: hotpink;\n color: black;\n top: ${rect.top + height}px;\n left: ${rect.left}px;\n opacity: 0.9;\n font-size: 10px;\n font-weight: 400;\n }\n `;\n });\n }\n });\n } else {\n console.log(\"No debug classes provided.\");\n }\n\n // Generate styles for grid selectors:\n if (options.gridSelectors.length > 0) {\n options.gridSelectors.forEach((gridClass) => {\n if (!isValidClass(gridClass)) {\n return;\n }\n\n debugStyles += `\n .${gridClass} {\n outline: 1px solid hotpink;\n }\n `;\n });\n } else {\n console.log(\"No grid classes provided.\");\n }\n\n var style = document.createElement(\"style\");\n style.setAttribute(\"id\", \"debug-styles\");\n style.innerHTML = debugStyles;\n document.head.appendChild(style);\n}", "function useCssVars(getter) {\n if (!inBrowser && !false)\n return;\n var instance = currentInstance;\n if (!instance) {\n warn$2(\"useCssVars is called without current active component instance.\");\n return;\n }\n watchPostEffect(function () {\n var el = instance.$el;\n var vars = getter(instance, instance._setupProxy);\n if (el && el.nodeType === 1) {\n var style = el.style;\n for (var key in vars) {\n style.setProperty(\"--\".concat(key), vars[key]);\n }\n }\n });\n }", "function buildWatch() {\n gulp.watch(`${sourceDirectory}/**/*.${sourceFileExtension}`, { ignoreInitial: false }, buildCode);\n gulp.watch(`${stylesDirectory}/**/*.${stylesExtension}`, { ignoreInitial: false }, buildStyles);\n gulp.watch(\n staticFiles.map((file) => `${sourceDirectory}/${file}`),\n { ignoreInitial: false },\n copyFiles,\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getting degree value of transform property
function getDegreeValue() { var transformValue = ballStyle.transform; var values = transformValue.split('(')[1].split(')')[0].split(','); var a = values[0]; var b = values[1]; var c = values[2]; var d = values[3]; var scale = Math.sqrt(a * a + b * b); var sin = b / scale; return angle = Math.round(Math.atan2(b, a) * (180 / Math.PI)); }
[ "degrees() {\n return (this._radians * 180.0) / Math.PI;\n }", "calculateRotation() {\n const extentFeature = this._extentFeature;\n const coords = extentFeature.getGeometry().getCoordinates()[0];\n const p1 = coords[0];\n const p2 = coords[3];\n const rotation = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180 / Math.PI;\n\n return -rotation;\n }", "getRotationMult(){\n return Math.pow(Math.log10(1 + this.state.distance), 0.5) * this.scale_rotation;\n }", "function toDegree(radian) {\n return (radian * 180) / Math.PI;\n }", "get eulerAngles() { return new Graphic_1.GL.Euler().setFromQuaternion(this).toVector3(); }", "function tan (angle) { return Math.tan(rad(angle)); }", "get DegreesCelsius() {\n return this.degC;\n }", "rotation(value) {\n if (typeof value !== 'number' || isNaN(Number(value)) || !Number.isFinite(value)) {\n return;\n }\n\n let finalDegreeRot = value.mod(360); // this should handle negative rotations automatically (ex: -90 MOD 360 = 270) and over-rotations (ex: 370 MOD 360 = 10)\n this.options.rotation = Math.floor(finalDegreeRot); // see my notes in the Number.mod() function for why I wrote a custom modulo operation instead of using \"%\"\n\n return this;\n }", "function compassDir(degrees) {\n if (degrees == 360) {\n return 'N';\n } else if (degrees >= 337.5) {\n return 'NNW';\n } else if (degrees >= 315) {\n return 'NW';\n } else if (degrees >= 292.5) {\n return 'WNW';\n } else if (degrees >= 270) {\n return 'W';\n } else if (degrees >= 247.5) {\n return 'WSW'\n } else if (degrees >= 225) {\n return 'SW';\n } else if (degrees >= 202.5) {\n return 'SSW';\n } else if (degrees >= 160) {\n return 'S';\n } else if (degrees >= 157.5) {\n return 'SSE';\n } else if (degrees >= 135) {\n return 'SE';\n } else if (degrees >= 112.5) {\n return 'ESE';\n } else if (degrees >= 90) {\n return 'E';\n } else if (degrees >= 67.5) {\n return 'ENE';\n } else if (degrees >= 45) {\n return 'NE';\n } else if (degrees >= 22.5) {\n return 'NNE';\n } else {\n return 'N';\n }\n}", "translateX() {\n if (this.slider.style.transform) {\n return parseInt(this.slider.style.transform.replace(/[^-.0-9]/g, ''));\n }\n\n return 0;\n }", "arg() {\n if (this.equalTo(0)) {\n return undefined;\n }\n\n if (this.re < 0 && y == 0) {\n return Math.PI;\n }\n\n return 2 * Math.atan(this.im / (this.abs() + this.re));\n }", "function mod_0_360(x) {return mod0Real(360, x);}", "_updateInitialRotation() {\n this.arNodeRef.getTransformAsync().then((retDict)=>{\n let rotation = retDict.rotation;\n let absX = Math.abs(rotation[0]);\n let absZ = Math.abs(rotation[2]);\n \n let yRotation = (rotation[1]);\n \n // if the X and Z aren't 0, then adjust the y rotation.\n if (absX > 1 && absZ > 1) {\n yRotation = 180 - (yRotation);\n }\n this.setState({\n rotation : [0,yRotation,0],\n nodeIsVisible: true,\n });\n });\n }", "function getOrientation() {\n return window.screen.orientation.angle;\n}", "function convertDeviceOrientationToDegrees(orientation) {\n switch (orientation) {\n case SimpleOrientation.rotated90DegreesCounterclockwise:\n return 90;\n case SimpleOrientation.rotated180DegreesCounterclockwise:\n return 180;\n case SimpleOrientation.rotated270DegreesCounterclockwise:\n return 270;\n case SimpleOrientation.notRotated:\n default:\n return 0;\n }\n}", "function getTranslateX(element) {\r\n\t var style, transform, r, match, k;\r\n\t if (!element) {\r\n\t return 0;\r\n\t }\r\n\t if (cssTransitionsSupported) {\r\n\t style = element.style || element;\r\n\t transform = style.webkitTransform;\r\n\t if (typeof transform === \"string\") {\r\n\t r = new RegExp(\"translate(3d|X|)\\\\(-*(\\\\d+)\");\r\n\t match = r.exec(transform);\r\n\t if (match) {\r\n\t k = parseFloat(match[1]);\r\n\t if (isFinite(k)) {\r\n\t return k;\r\n\t }\r\n\t }\r\n\t }\r\n\t }\r\n\t else {\r\n\t var k = parseInt($(element).css(\"left\"));\r\n\t if (isFinite(k)) {\r\n\t return k;\r\n\t }\r\n\t }\r\n\t return 0;\r\n\t}", "function addDegrees(moon, degreeIncrement){\n\t\tvar newAngle = moon.data('angle') + degreeIncrement;\t\n\t\tmoon.data('angle', newAngle);\n\n\t\treturn moonCoords(newAngle);\n\t}", "computeRotate(angle){\n ghost.yRotate += angle;\n\n this.speedXAfterRotate = this.speedXAfterRotate*Math.cos(utils.degToRad(angle)) -\n this.speedZAfterRotate*Math.sin(utils.degToRad(angle));\n this.speedZAfterRotate = this.speedZAfterRotate*Math.cos(utils.degToRad(angle)) +\n this.speedXAfterRotate*Math.sin(utils.degToRad(angle));\n }", "angle(v) {\n let d = this.dot(v);\n let m = this.mag() * v.mag();\n return Math.acos(d/m);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Keep incrementing the current day until it is no longer a hidden day. If the initial value of `date` is not a hidden day, don't do anything. Pass `isExclusive` as `true` if you are dealing with an end date. `inc` defaults to `1` (increment one day forward each time)
function skipHiddenDays(date, inc, isExclusive) { inc = inc || 1; while ( isHiddenDayHash[ ( date.getDay() + (isExclusive ? inc : 0) + 7 ) % 7 ] ) { addDays(date, inc); } }
[ "function advanceDate(date, length, WFLAG=0) {\n date = new Date(date);\n if(WFLAG) length *= 7;\n new_date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + length);\n\n return new_date;\n}", "function updateModalDate() {\n\tvar date = document.getElementById('date');\n\tdate.value = todaysDate(activeDate);\n}", "function activateDateField(){\n $('[type=\"checkbox\"]').click(function(){\n if (this.checked===true){\n $(this).nextAll('[type=\"date\"]').slice(0,2).prop( \"disabled\",false);\n }\n else\n $(this).nextAll('[type=\"date\"]').slice(0,2).prop(\"disabled\",true);\n });\n}", "function addDate () {\n\taddDateBtn.disabled = true;\n\tdate = new Date();\n\tnoteDate = true;\n\talert(date);\n}//end date function", "function setNextMeeting() {\n var today = new Date();\n console.log('Today is ' + today + '.');\n\n // Get date of meeting from this month.\n var date = getMeetingOfYearMonth(today.getFullYear(), today.getMonth());\n console.log('Meeting this month is ' + date + '.');\n\n // If meeting this month is over, take the one from the next month.\n if (date.getTime() < today.getTime()) {\n console.log('Meeting this month is over.');\n date = getMeetingOfYearMonth(today.getFullYear(), today.getMonth() + 1);\n }\n\n console.log('Next meeting is: ' + date + '.');\n document.getElementById('nextMeeting').innerHTML = date;\n}", "function addDays(date, days) {\n var value = date.valueOf();\n value += 86400000 * days;\n return new Date(value);\n}", "function addOneDay(dateString) {\n const result = new Date(dateString);\n result.setDate(result.getDate() + 1);\n return result.toISOString().split('T')[0];\n }", "function incr(key, done) {\n const _done = _.isFunction(done) ? done : _.noop;\n hit(key, 1, false, _done);\n }", "function updateChosenDate(inputDate){\n setChosenDate(inputDate);\n }", "function toggleDate(timestamp, noCount)\n{\n\ttry {\n\n\t\tif(noCount)\n\t\t{\n\t\t\tvar noCountDateArray = getSubDates();\n\t\t\n\t\t\t//Secondary dates. Store many hooray\n\t\t\tvar sidx = noCountDateArray.indexOf(timestamp);\n\t\t\n\t\t\tif(sidx != -1)\n\t\t\t{\n\t\t\t\tnoCountDateArray.splice(sidx, 1); //Remove if found\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//...add if not found.\n\t\t\t\tnoCountDateArray.push(timestamp);\n\t\t\t}\n\t\t\t\n\t\t\tnoCountDateArray.sort();\n\t\t\t\n //trackEvent(\"Interaction\", \"Sub date changed\", timestamp);\n\t\t\t\n\t\t\t//This is the new solution!\n\t\t\tdates.subDateArray = noCountDateArray;\n\t\t\tpersistDatesToStorage(dates);\n\t\t\t\t\t\t\n\t\t\tlog(\"Sub date array changed\", noCountDateArray);\n\t\t\t\t\n\t\t\t\n\t\t}\n\t\telse //The main one. Store just that.\n\t\t{\n\t\t\tvar dateArray = getDates();\n\t\t\t\n\t\t\tvar idx = dateArray.indexOf(timestamp);\n\t\t\t\n\t\t\tif(idx != -1)\n\t\t\t{\n\t\t\t\tdateArray = []; // Clear out\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdateArray = [timestamp]; //Set\n\t\t\t}\n\t\t\t\n\t\t\t//This is the new solution!\n\t\t\tdates.mainDateArray = dateArray;\n\t\t\tpersistDatesToStorage(dates);\n\t\t\t\n\t\t\t\n\t\t\tlog(\"Date array changed\", dateArray); //Log it\t\n\t\t}\n\t\t\t\n\t}\n\tcatch(e)\n\t{\n\t\thandleError(\"Functions toggleDate\", e);\n\t}\n\t\n}", "updateDateField(dateField) {\n const me = this;\n\n dateField.on({\n change({ userAction, value }) {\n if (userAction && !me.$isInternalChange) {\n me._isUserAction = true;\n me.value = value;\n me._isUserAction = false;\n }\n },\n thisObj : me\n });\n }", "async function reseqDateMovs(movDate) {\n var updateQuery = 'update movements t1 ' \n + ' set mov_num = ((mov_date - date \\'2000-01-01\\') * 10000) + 1 + '\n + ' + (select count(*) from movements t2 where t2.mov_date = t1.mov_date and t2.mov_num < t1.mov_num) '\n + ' where mov_date = $1 ';\n updateQuery += ' RETURNING id, mov_num, mov_date, description, amount, real_pot_id, acc_pot_id, mov_group_id ';\n result = await to(client.query(updateQuery, [movDate]));\n blueLog('Movs with the same date resequenced', movDate);\n return result;\n}", "setTodayDate(date) {\n let todayDate = new Date(+date);\n this.setProperties({ value: todayDate }, true);\n super.todayButtonClick(null, todayDate, true);\n }", "setNextMonth() {\n let {month, year} = this.getMonth('next');\n this.setDate(new Date(year, month, 1));\n }", "function isInteractive(day, displayMonth, props) {\n var toDate = props.toDate, fromDate = props.fromDate, enableOutsideDaysClick = props.enableOutsideDaysClick, originalProps = props.originalProps;\n var outside = isOutside(day, displayMonth);\n if (props.mode !== 'uncontrolled' && !outside) {\n return true;\n }\n var hasInteractiveProps = 'onDayClick' in originalProps;\n if (props.mode !== 'uncontrolled') {\n return true;\n }\n else if (hasInteractiveProps) {\n return true;\n }\n // The day is NOT interactive if not in the range specified in the `fromDate`\n // and `toDate` (these values are set also by `fromDay/toDay` and\n // `fromYear/toYear` in the main component.)\n var isAfterToDate = Boolean(toDate && isAfter(day, toDate));\n var isBeforeFromDate = Boolean(fromDate && isBefore(day, fromDate));\n var isOutsideInteractive = outside\n ? Boolean(enableOutsideDaysClick)\n : false;\n var interactive = !isAfterToDate && !isBeforeFromDate && isOutsideInteractive;\n return interactive;\n}", "function btnNextYearClick() {\n\t\terase();\n\t\tyearCheck = yearCheck + 1;\n\t\tconsole.log(monthCheck);\n\t\tsetData();\n\t\tsetMonths();\n\t\tsetYears();\n\t}", "inc(val) {\n if ((val && !Number.isFinite(val)) || (val !== undefined && isNaN(val))) {\n throw new TypeError(`Value is not a valid number: ${val}`);\n }\n if (val && val < 0) {\n throw new Error('It is not possible to decrease a cumulative metric');\n }\n const incValue = val === null || val === undefined ? 1 : val;\n this.value += incValue;\n }", "function minusDays(date, days){\n let result = new Date(date);\n result.setTime(result.getTime() - days * 86400000);\n return result;\n }", "function _employeeAssignedMoreThanOnceOnDate(date, employeePk) {\r\n var fullCalEvents = $fullCal.fullCalendar(\"clientEvents\");\r\n var assignmentCount = 0;\r\n for (var i=0; i<fullCalEvents.length; i++) {\r\n var start = moment(fullCalEvents[i].start);\r\n var eventDate = start.format(DATE_FORMAT);\r\n if (date == eventDate && fullCalEvents[i].employeePk == employeePk) {\r\n assignmentCount += 1;\r\n }\r\n }\r\n if (assignmentCount > 1) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "toggleUnreconciledOnly(unreconciledOnly, direction, fromDate, transactionIdToFocus) {\n\t\tif (!this.reconciling) {\n\t\t\t// Store the setting for the current account\n\t\t\tthis.accountModel.unreconciledOnly(this.context.id, unreconciledOnly);\n\t\t\tthis.unreconciledOnly = unreconciledOnly;\n\t\t\tthis.transactions = [];\n\t\t\tthis.getTransactions(direction || \"prev\", fromDate, transactionIdToFocus);\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method starts the game looping if media files are loaded in
function startGame() { if(mediaCount.image == 0 && mediaCount.audio==0 && canStart==1) { //Initiate the game gameRestart();//initiate the game //Start the game gameLoop();//this sets automatically the game looping //var interval = setInterval(gameLoop, 30); //runs gameLoop ciclicly } else { console.log("Wait for " + (canStart==1?"media":"Main") ); } }
[ "static loadBeginning()\n {\n var path = game.load.path;\n\n game.load.path = 'assets/audio/music/';\n game.load.audio('beginning', 'beginning.mp3');\n\n game.load.path = path;\n }", "function playEventHandler() {\n if ($rootScope.playing === false) {\n play(); \n }\n }", "function checkImages(){ //Check if the images are loaded.\n\n if(game.doneImages >= game.requiredImages){ //If the image loads, load the page to the DOM.\n\n init();\n }else{ //loop until the images are loaded.\n\n setTimeout(function(){\n checkImages();\n },1);\n\n }\n }", "play() {\n // rewind when user clicks play on ended scene\n this.goToStartIfEnded();\n this.disablePlayButtonUntilPlaybackStarts();\n this.waitForCanPlayAll().then(() => {\n this.videoElements.forEach(e => e.play());\n });\n }", "function ManageMusic() {\r\n music.src = BGMusics[0].SRC;\r\n music.volume = 0.01;\r\n music.play();\r\n music.loop = true;\r\n}", "function loop() {\n\n game_step_settings()\n\n road_loop_settings();\n\n cloud_loop_settings();\n\n cactus_loop_settings();\n\n collision_settings();\n\n score_settings()\n\n }", "play(){\n //console.log(\"Playing\", this.id);\n if (this.playing === false){\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if(typeof this.mediaSourceListeners[i].play === 'function')this.mediaSourceListeners[i].play(this);\n } \n }\n this.playing = true;\n }", "start() {\n \n //Start the game loop\n this.gameLoop();\n }", "static load()\n {\n // load non-phaser audio elements for pausing and unpausing\n this.pauseAudio = new Audio('assets/audio/sfx/ui/pause.mp3');\n this.resumeAudio = new Audio('assets/audio/sfx/ui/checkpoint.mp3');\n\n var path = game.load.path;\n game.load.path = 'assets/audio/sfx/levels/';\n\n game.load.audio('open_door', 'open_door.mp3');\n game.load.audio('begin_level', '../ui/begin_level.mp3');\n\n game.load.path = path;\n }", "function soundBg(){\n\t\tif (typeof MainTheme.loop == 'boolean')\n\t\t{\n\t\t\tMainTheme.loop = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// play main theme song in case loop is not supported\n\t\t\tMainTheme.addEventListener('ended', function() {\n\t\t\t\tthis.currentTime = 0;\n\t\t\t\tthis.play();\n\t\t\t}, false);\n\t\t\t\n\t\t}\n\t\tMainTheme.play();\n\t}", "function countOnload(argMedia)\n {\n if(argMedia==\"image\")\n {\n mediaCount.image--;\n }\n if(argMedia==\"audio\")\n {\n mediaCount.audio--;\n }\n \n console.log(\"loaded status image:\"+mediaCount.image+\" audio:\"+mediaCount.audio);\n\n if(mediaCount.image == 0 && mediaCount.audio==0)\n {\n //calculate frame size, when pic has been loaded in\n expW = explPic.width/16;\n startGame();\n }\n }", "function Preload() {\n assets = new createjs.LoadQueue(); // asset container\n util.GameConfig.ASSETS = assets; // make a reference to the assets in the global config\n assets.installPlugin(createjs.Sound); // supports sound preloading\n assets.loadManifest(assetManifest); // load assetManifest\n assets.on(\"complete\", Start); // once completed, call start function\n }", "playRound1() {\r\n this.music1.play();\r\n }", "play () {\n\n this._debug.log(\"Play\");\n // Play the ad player\n if (this._vastPlayerManager) {\n this._vastPlayerManager.play();\n }\n }", "function resumeGame() {\n \t\treturn generateGameLoop();\n \t}", "function groundShot() {\n playSound(\"audioCannonShot\");\n }", "moveToNextGame() {\n this._startGame(this._getNextGame());\n }", "function init() {\n document\n .getElementById(\"game-photo-1\")\n .addEventListener(\"click\", playSound1);\n document\n .getElementById(\"game-photo-2\")\n .addEventListener(\"click\", playSound2);\n document\n .getElementById(\"game-photo-3\")\n .addEventListener(\"click\", playSound3);\n document\n .getElementById(\"game-photo-4\")\n .addEventListener(\"click\", playSound4);\n}", "function initializeGameSounds()\n{\n\twrongAnswerSounds[0] = new Media(\"www/sounds/wrongleft.wav\");\n\twrongAnswerSounds[1] = new Media(\"www/sounds/wrongright.wav\");\n\n\tcloseEnoughSounds[0] = new Media(\"www/sounds/laser.wav\");\n\tcloseEnoughSounds[1] = new Media(\"www/sounds/cashregister.wav\");\n\tcloseEnoughSounds[2] = new Media(\"www/sounds/ching.wav\");\n\tcloseEnoughSounds[3] = new Media(\"www/sounds/arrow.wav\");\n\t\n\tbullseyeSounds[0] = new Media(\"www/sounds/explosion2.wav\");\n\tbullseyeSounds[1] = new Media(\"www/sounds/perfect.wav\");\n\tbullseyeSounds[2] = new Media(\"www/sounds/precise.wav\");\n\tbullseyeSounds[3] = new Media(\"www/sounds/yes.wav\");\n\tbullseyeSounds[4] = new Media(\"www/sounds/onthedot.wav\");\t\n\tbullseyeSounds[5] = new Media(\"www/sounds/immaculate.wav\");\n\tbullseyeSounds[6] = new Media(\"www/sounds/onthemoney.wav\");\n\tbullseyeSounds[7] = new Media(\"www/sounds/supreme.wav\");\n\tbullseyeSounds[8] = new Media(\"www/sounds/ideal.wav\");\t\n\tbullseyeSounds[9] = new Media(\"www/sounds/spotless.wav\");\n\tbullseyeSounds[10] = new Media(\"www/sounds/sublime.wav\");\n\tbullseyeSounds[11] = new Media(\"www/sounds/flawless.wav\");\n\t\n\tnextLevelSounds[0] = new Media(\"www/sounds/cheer.wav\");\n\t\n\tpresidentialLevelSound = new Media(\"www/sounds/hailtothechief.wav\");\n\tmultiplicationLevelSound = new Media(\"www/sounds/mollusk.wav\");\n\t\n\tgameOverSound = new Media(\"www/sounds/gameoversound.wav\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function GetWindowHeight return the client browser height modified by : Manish Sharma modified on : 10032009
function GetWindowHeight() { //return window.innerHeight|| //document.documentElement&&document.documentElement.clientHeight|| //document.body.clientHeight||0; var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; }
[ "getGameHeight() {\n return this.scene.sys.game.config.height;\n }", "function windowDimensions(){\n\tvar win = window;\n\twin.height = $(window).height();\n\twin.width = $(window).width();\n\treturn win;\n}", "_calculateHeight() {\n\t\tif (this.options.height) {\n\t\t\treturn this.jumper.evaluate(this.options.height, { '%': this.jumper.getAvailableHeight() });\n\t\t}\n\n\t\treturn this.naturalHeight() + (this.hasScrollBarX() ? 1 : 0);\n\t}", "function get_actual_scroll_distance() {\n return $document.innerHeight() - $window.height();\n }", "function height() {\n return gl.drawingBufferHeight / scale();\n }", "function resizeWindow () {\n\t\tparent.postMessage($('body').height(), '*');\n\t}", "function calcScrollValues() {\n\t\twindowHeight = $(window).height();\n\t\twindowScrollPosTop = $(window).scrollTop();\n\t\twindowScrollPosBottom = windowHeight + windowScrollPosTop;\n\t} // end calcScrollValues", "setHeight() {\n this.$().outerHeight(this.$(window).height() - this.get('fixedHeight'));\n }", "function vh(v) {\n let h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);\n return (v * h) / 100;\n}", "function GetWindowSize(out = new ImVec2()) {\r\n return bind.GetWindowSize(out);\r\n }", "static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }", "function getheight(){\n var ff = (navigator.userAgent.toLowerCase().indexOf('firefox') != -1);\n var NS = (navigator.userAgent.toLowerCase().indexOf('netscape') != -1);\n var IE = (navigator.userAgent.toLowerCase().indexOf('msie') != -1);\n if(isgE('MET_MediaModule_Half')) \n {\n var height_SpLogo=0;\n var height_adser=0;\n var margincount=0;\n var height_MMhalf=document.getElementById('MET_MediaModule_Half').offsetHeight;\n if(isgE('MET_Adser300x250')){\n var height_adser=document.getElementById('MET_Adser300x250').offsetHeight;\n if (IE){\n margincount=margincount-19\n }\n }\n if(isgE('MET_sponserLogo') && !(isgE('MET_Adser300x250'))){\n height_SpLogo=document.getElementById('MET_sponserLogo').offsetHeight;\n if (ff || NS){\n margincount=margincount+8\n }\n else {\n margincount=margincount+0\n }\n }\n if(isgE('MET_sponserLogo') && isgE('MET_Adser300x250')){\n height_SpLogo=document.getElementById('MET_sponserLogo').offsetHeight;\n if (ff || NS){\n margincount=margincount+16\n }\n else {\n margincount=margincount+8\n }\n }\n if(!(isgE('MET_sponserLogo')) && !(isgE('MET_Adser300x250'))){\n margincount=margincount-16\n }\n var variableHeight = height_SpLogo+height_adser+margincount;\n if (height_MMhalf>=variableHeight)\n {\n \n var Margin_TowerAd= -(height_MMhalf-variableHeight);\n if(document.getElementById('MET_RightTowerAd_float2')){\n document.getElementById('MET_RightTowerAd_float2').style.marginTop = Margin_TowerAd+\"px\";\n }\n else if(document.getElementById('MET_RightTowerAd_float1')){\n document.getElementById('MET_RightTowerAd_float1').style.marginTop = Margin_TowerAd+\"px\";\n }\n }\n \n if(document.getElementById('MET_RightTowerAd_float2')){\n document.getElementById('MET_RightTowerAd_float2').style.visibility = \"visible\";\n }\n else if(document.getElementById('MET_RightTowerAd_float1')){\n document.getElementById('MET_RightTowerAd_float1').style.visibility = \"visible\";\n }\n\n } \n if(isgE('MET_MediaModule_Full')){ \n var height_SpLogo=document.getElementById('MET_sponserLogo_MMFull').offsetHeight;\n var height_MMfull=document.getElementById('MET_MediaModule_Full').offsetHeight;\n var margintop_SLogo;\n if(isgE('sponsorbyText')) {\n margintop_SLogo = 34 \n }\n else {\n margintop_SLogo = 24\n }\n var Top_SponsorLogo = (height_MMfull-margintop_SLogo);\n if (is.isIE){\n document.getElementById('MET_sponserLogo_MMFull').style.marginTop = -(Top_SponsorLogo+7)+\"px\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginBottom = (Top_SponsorLogo-7)+\"px\";\n }\n else{\n document.getElementById('MET_sponserLogo_MMFull').style.position = \"relative\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginTop = -(Top_SponsorLogo)+\"px\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginBottom = (Top_SponsorLogo)+\"px\";\n } \n document.getElementById('MET_sponserLogo_MMFull').style.visibility = \"visible\";\n\n \n } \n}", "function getScreenHeight(percentage = 100) {\r\n return screenHeight * (percentage / 100);\r\n}", "function getHeight() {\n return 2;\n }", "function getBleedHeightInPx() {\n // Creating temporary div with height set in mm and appending it to body\n const tempBleedDiv = document.createElement('div');\n tempBleedDiv.style.height = '8.82mm';\n document.body.appendChild(tempBleedDiv);\n \n // Getting new element's height in px and putting it in a variable\n const bleedHeightInPx = tempBleedDiv.offsetHeight;\n \n // Removing temporary div from the div as we no longer need it\n tempBleedDiv.remove();\n \n // Returning the value in px\n return bleedHeightInPx;\n }", "function GetHeaderHeight() {\n var styleSheetName = SiebelApp.S_App.GetStyleSheetName();\n var headerheight = utils.GetstyleSheetPropVal(styleSheetName, \".siebui .ListAppletHeader\", \"height\");\n\n return headerheight || siebConsts.get(\"DFLT_HEADHGT\");\n }", "function getHeight() {\n return maxy + 1;\n }", "function heightFullscreen() {\n if ($('#jarviswidget-fullscreen-mode').length) {\n\n /**\t\t\t\t\t\t\n * Setting height variables.\n **/\n var heightWindow = $(window).height();\n var heightHeader = $('#jarviswidget-fullscreen-mode').find(self.o.widgets).children(\n 'header').height();\n\n /**\t\t\t\t\t\t\n * Setting the height to the right widget.\n **/\n $('#jarviswidget-fullscreen-mode')\n .find(self.o.widgets)\n .children('div')\n .height(heightWindow - heightHeader - 15);\n }\n }", "function getWindowAdjustedDivDimensions() {\n\t \tvar height = window.innerHeight,\n\t\t\twidth = window.innerWidth,\n\t\t\tdiv_height,\n\t\t\tdiv_width,\n\t\t\tMIN_WINDOW_HEIGHT = 574,\n\t\t\tMIN_WINDOW_WIDTH = 750;\n\n\t\t// restrict map from resizing to a size smaller than its\n\t\t// minimum-allowed size\n\t\tif(height < MIN_WINDOW_HEIGHT && width < MIN_WINDOW_WIDTH) {\n\t\t\theight = MIN_WINDOW_HEIGHT;\n\t\t\twidth = MIN_WINDOW_WIDTH;\n\t\t} else if (height < MIN_WINDOW_HEIGHT) {\n\t\t\theight = MIN_WINDOW_HEIGHT;\n\t\t} else if (width < MIN_WINDOW_WIDTH) {\n\t\t\twidth = MIN_WINDOW_WIDTH;\n\t\t}\n\t\t\n\t\t// calculates new dimensions of divs to fit window size while\n\t\t// maintaining aspect ratio; aspect ratio is determined\n\t\t// by original basemap image size\n\t\tif(width/height > MAP_WIDTH/MAP_HEIGHT) {\n\t\t\tdiv_height = height;\n\t\t\tdiv_width = div_height*MAP_WIDTH/MAP_HEIGHT;\n\t\t} else {\n\t\t\tdiv_width = width;\n\t\t\tdiv_height = div_width*MAP_HEIGHT/MAP_WIDTH;\n\t\t}\n\n\t\treturn [div_width,div_height];\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create FindAndReplaceTransformer object toreplace: a string to be replaced by newtext newtext: a string that replaces the found text timesToReplace: (optional) number of occurrences of toreplace to search for. If not provided, replace all occurences
constructor(toreplace, newtext, timesToReplace) { this.toreplace = toreplace; this.newtext = newtext; this.alreadyProcessed = 0; this.unenqueuedPos = 0; this.prevUnenqueuedText = ""; if (timesToReplace === 0) { //nothing to do. Exit early this.done = true; return; } if (timesToReplace && (timesToReplace > 0)) { this.howmanytimes = timesToReplace; } else { this.howmanytimes = null; } this.done = false; this.kmpTable = this._buildKmpTable(toreplace); this.streamSearchPos = 0; this.findTextSearchPos = 0; this.timesFound = 0; }
[ "function SUBSTITUTE(text, old_text, new_text, occurrence) {\n if (!text || !old_text || !new_text) {\n return text;\n } else if (occurrence === undefined) {\n return text.replace(new RegExp(old_text, 'g'), new_text);\n } else {\n var index = 0;\n var i = 0;\n while (text.indexOf(old_text, index) > 0) {\n index = text.indexOf(old_text, index + 1);\n i++;\n if (i === occurrence) {\n return text.substring(0, index) + new_text + text.substring(index + old_text.length);\n }\n }\n }\n}", "function REPLACE(text, position, length, new_text) {\n\n if (ISERROR(position) || ISERROR(length) || typeof text !== 'string' || typeof new_text !== 'string') {\n return error$2.value;\n }\n return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length);\n}", "function replaceAll(Source,stringToFind,stringToReplace){\n var temp = Source;\n var index = temp.indexOf(stringToFind);\n while(index != -1){\n temp = temp.replace(stringToFind,stringToReplace);\n index = temp.indexOf(stringToFind);\n }\n return temp;\n}", "function strReplace(text,toBeReplaced,toReplace,substituteFirst)\n{\n\tvar newToBeReplaced=\"\";\n\t\n\tfor(var i=0;i<toBeReplaced.length;i++)\n\t{\n\t\t// Elabora caratteri riservati dell'oggetto RegExp\n\t\tswitch (toBeReplaced.substr(i,1))\n\t\t{\n\t\t\tcase \"^\":\n\t\t\tcase \"$\":\n\t\t\tcase \"*\":\n\t\t\tcase \"+\":\n\t\t\tcase \"?\":\n\t\t\tcase \"[\":\n\t\t\tcase \"]\":\n\t\t\tcase \"(\":\n\t\t\tcase \")\":\n\t\t\tcase \"|\": \n\t\t\t\tnewToBeReplaced+=\"\\\\\"+toBeReplaced.substr(i,1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\texcape=/\\\\/g;\n\t\t\t\tnewToBeReplaced=toBeReplaced.replace(excape,\"\\\\\\\\\");\t\n\t\t}\t\n\t}\n\t\n\tif (newToBeReplaced==\"\")\n\t\tnewToBeReplaced=toBeReplaced;\n\t\n\tif (substituteFirst)\n\t\trg=new RegExp(newToBeReplaced)\n\telse\n\t\trg=new RegExp(newToBeReplaced,\"g\");\n\t\n\treturn text.replace(rg,toReplace);\n}", "function replaceString(str, findTok, replaceTok, isOne) {\n\n pos = str.indexOf(findTok);\n valueRet = \"\";\n if (pos == -1) {\n return str;\n }\n valueRet += str.substring(0,pos) + replaceTok;\n if (!isOne && ( pos + findTok.length < str.length)) {\n valueRet += replaceString(str.substring(pos + findTok.length, str.length), findTok, replaceTok);\n } else {\n\t\tvalueRet += str.substring(pos + findTok.length, str.length)\n\t}\n\n return valueRet;\n}", "function replace(string,text,by) {\n // Replaces text with by in string\n\t var i = string.indexOf(text);\n\t var newstr = '';\n\t if ((!i) || (i == -1)) return string;\n\t newstr += string.substring(0,i) + by;\n\n\t if (i+text.length < string.length)\n\t\t newstr += replace(string.substring(i+text.length,string.length),text,by);\n\t \n\t return newstr;\n }", "redact(parameters) {\n // Converted to a promise now\n let promise = this.$q((resolve, reject) => {\n // Setup and defaults\n let replacementChar = parameters.replacementChar || 'X';\n // Here is a little example of type checking variables and defaulting if it isn't as expected.\n let caseSensitive =\n typeof parameters.caseSensitive === typeof true\n ? parameters.caseSensitive\n : true;\n if (parameters.phrases === undefined || parameters.phrases.length === 0) {\n return parameters.inputText;\n }\n\n let phrases = parameters.phrases;\n let searchText = parameters.inputText;\n if (!caseSensitive) {\n phrases = parameters.phrases.map(p => p.toLowerCase());\n searchText = parameters.inputText.toLowerCase();\n }\n\n // loop through the phrases array\n let indicies = [];\n phrases.map(p => {\n // should just use for loop here now\n let pos = -1;\n do {\n pos = searchText.indexOf(p, pos + 1); // use the start index to reduce search time on subsequent searches\n if (pos === -1) break; // No more matches, abandon ship!\n // Track the starting index and length of the redacted area\n indicies.push({ index: pos, length: p.length });\n } while (pos != -1);\n });\n\n // Ok now go replace everything in the original text.\n // Overlapping phrases should be handled properly now.\n // we really need a splice method for strings\n // quick google search and guess what? There is an underscore string library ... neat! Now I don't have to write one.\n let redactedText = parameters.inputText;\n for (let i = 0, len = indicies.length; i < len; i++) {\n redactedText = _string.splice(\n redactedText,\n indicies[i].index,\n indicies[i].length,\n this.buildReplacement(replacementChar, indicies[i].length)\n );\n }\n\n // Go home strings, you're drunk\n resolve(redactedText);\n });\n return promise;\n }", "function _replacement() {\n if (!arguments[0]) return \"\";\n var i = 1, j = 0, $pattern;\n // loop through the patterns\n while ($pattern = _patterns[j++]) {\n // do we have a result?\n if (arguments[i]) {\n var $replacement = $pattern[$REPLACEMENT];\n switch (typeof $replacement) {\n case \"function\": return $replacement(arguments, i);\n case \"number\": return arguments[$replacement + i];\n }\n var $delete = (arguments[i].indexOf(self.escapeChar) == -1) ? \"\" :\n \"\\x01\" + arguments[i] + \"\\x01\";\n return $delete + $replacement;\n // skip over references to sub-expressions\n } else i += $pattern[$LENGTH];\n }\n }", "function jsReplace(inString, find, replace) {\n\n var outString = \"\";\n\n if (!inString) {\n return \"\";\n }\n\n // REPLACE ALL INSTANCES OF find WITH replace\n if (inString.indexOf(find) != -1) {\n // SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find\n t = inString.split(find);\n\n // JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace\n\t\t\n return (t.join(replace));\n }\n else {\n return inString;\n }\n}", "function ReplaceParams() {\n var result = arguments[0];\n for (var iArg = 1; iArg < arguments.length; iArg++) { // Start at second arg (first arg is the pattern)\n var pattern = new RegExp('%' + iArg + '\\\\w*%');\n result = result.replace(pattern, arguments[iArg]);\n }\n return result;\n}", "function replaceInString(data, search, replace) {\n if (Array.isArray(search)) {\n for (var i=0; i<search.length; i++) {\n data = data.replaceAll(search[i], replace[i]);\n }\n return data;\n } else {\n return data.replaceAll(search, replace);\n }\n}", "replaceHTML(firstTokenElement, countToReplace) {\n let startingLine = firstTokenElement.parentElement;\n \n // Next, remove the token elements to be replaced.\n let toBeRemoved = firstTokenElement;\n let removedCount = 0;\n while (removedCount < countToReplace && toBeRemoved !== null) {\n let victim = toBeRemoved;\n toBeRemoved = toBeRemoved.nextSibling;\n victim.parentElement.removeChild(victim);\n ++removedCount;\n }\n let lineToRemove = startingLine.nextSibling;\n if (removedCount >= countToReplace && toBeRemoved !== null) {\n lineToRemove = document.createElement(\"span\");\n lineToRemove.classList.add(\"line\");\n startingLine.parentElement.insertBefore(lineToRemove,\n startingLine.nextSibling);\n while (toBeRemoved !== null) {\n let toMove = toBeRemoved;\n toBeRemoved = toBeRemoved.nextSibling;\n startingLine.removeChild(toMove);\n lineToRemove.appendChild(toMove);\n }\n }\n while (lineToRemove !== null && removedCount +\n lineToRemove.childElementCount <= countToReplace) {\n removedCount += lineToRemove.childElementCount;\n let victim = lineToRemove;\n lineToRemove = lineToRemove.nextSibling;\n victim.parentElement.removeChild(victim);\n }\n if (lineToRemove === null && removedCount < countToReplace) {\n throw \"Invalid arguments to .replaceHTML(): there were not \" +\n countToReplace + \" elements to replace\";\n }\n if (lineToRemove === null) {\n lineToRemove = document.createElement(\"span\");\n lineToRemove.classList.add(\"line\");\n startingLine.parentElement.insertBefore(lineToRemove, null);\n }\n toBeRemoved = lineToRemove.firstChild;\n while (removedCount < countToReplace) {\n let victim = toBeRemoved;\n toBeRemoved = toBeRemoved.nextSibling;\n victim.parentElement.removeChild(victim);\n ++removedCount;\n }\n\n // Now, startingLine and lineToRemove should be adjacent lines, each\n // containing only the remaining tokens (if any).\n const htmlToInsert = this.toHTML();\n if (htmlToInsert.length > 0 && htmlToInsert[0].childElementCount === 0 &&\n startingLine.childElementCount === 0) {\n htmlToInsert.shift();\n }\n if (htmlToInsert.length <= 1) {\n // If there are no lines to insert (or only 1), join the\n // starting/ending lines of the removed section.\n let insertBeforeMe = lineToRemove.firstChild;\n while (lineToRemove.childElementCount !== 0) {\n let elementToMove = lineToRemove.firstChild;\n lineToRemove.removeChild(elementToMove);\n startingLine.appendChild(elementToMove);\n }\n lineToRemove.parentElement.removeChild(lineToRemove);\n // Insert any applicable lines.\n if (htmlToInsert.length === 1) {\n while (htmlToInsert[0].childElementCount > 0) {\n let toMove = htmlToInsert[0].firstChild;\n htmlToInsert[0].removeChild(toMove);\n startingLine.insertBefore(toMove, insertBeforeMe);\n }\n }\n }\n else {\n // Otherwise, if there is more than 1 line to insert, insert the\n // first line on startingLine, the last line on lineToRemove, and\n // all the other lines in between.\n while (htmlToInsert[0].childElementCount > 0) {\n let elementToMove = htmlToInsert[0].firstChild;\n htmlToInsert[0].removeChild(elementToMove);\n startingLine.appendChild(elementToMove);\n }\n for (let i = 1; i < htmlToInsert.length - 1; ++i) {\n lineToRemove.parentElement.insertBefore(htmlToInsert[i], lineToRemove);\n }\n while (htmlToInsert[htmlToInsert.length - 1].childElementCount > 0) {\n let elementToMove = htmlToInsert[htmlToInsert.length - 1].lastChild;\n htmlToInsert[htmlToInsert.length - 1].removeChild(elementToMove);\n lineToRemove.insertBefore(elementToMove, lineToRemove.firstChild);\n }\n }\n }", "function substituteTwitterUrls(text, urls) {\n var restoredText = text;\n urls.forEach(function (urlObj) {\n log.debug(urlObj);\n log.debug('Substituting ' + urlObj.url + ' -> ' + urlObj.expanded_url);\n restoredText = replaceAll(restoredText, urlObj.url, urlObj.expanded_url);\n });\n return restoredText;\n }", "apply(doc) {\n if (this.length != doc.length)\n throw new RangeError(\n 'Applying change set to a document with the wrong length'\n )\n iterChanges(\n this,\n (fromA, toA, fromB, _toB, text) =>\n (doc = doc.replace(fromB, fromB + (toA - fromA), text)),\n false\n )\n return doc\n }", "function pregReplaceElements($regexp, $Elements, $text)\n\t{\n\t\tlet $newElements = array();\n\t\tlet $matches;\n\t\t\n\t\twhile (preg_match($regexp, $text, ($matches = []), 'PREG_OFFSET_CAPTURE'))\n\t\t{\n\t\t\tlet $offset = $matches[0][1];\n\t\t\tlet $before = substr($text, 0, $offset);\n\t\t\tlet $after = substr($text, $offset + strlen($matches[0][0]));\n\t\t\t\n\t\t\t$newElements.push({ 'text': $before });\n\t\t\t\n\t\t\tfor (let $Element of $Elements)\n\t\t\t{\n\t\t\t\t$newElements.push( $Element );\n\t\t\t}\n\t\t\t\n\t\t\t$text = $after;\n\t\t}\n\t\t\n\t\t$newElements.push({ 'text': $text });\n\t\t\n\t\treturn $newElements;\n\t}", "function DocEdit_processPriorNodeEdit(index)\n{\n //only update if new text has been provided\n if (this.text != null)\n {\n //if nodeAttribute, only update the attribute (or tag section)\n if (this.weight.indexOf(\"nodeAttribute\") == 0)\n {\n var pos = extUtils.findAttributePosition(this.priorNode, this.weightInfo);\n if (pos)\n {\n this.insertPos = pos[0];\n this.replacePos = pos[1];\n\n //if positional attribute and removing text\n if (this.weight.indexOf(\",\") != -1 && !this.text)\n {\n //if attribute has space before and after, and removing attribute, strip a space\n if (docEdits.allSrc.charAt(this.insertPos-1) == \" \" &&\n docEdits.allSrc.charAt(this.replacePos) == \" \")\n {\n this.replacePos++;\n }\n }\n }\n }\n else //if not nodeAttribute, do a full replace of the tag\n {\n //if replacing a block tag and the new text\n // starts the same but has no end tag, preserve innerHTML\n if (extUtils.isBlockTag(this.priorNode) &&\n (this.text.search(RegExp(\"\\\\s*<\"+dwscripts.getTagName(this.priorNode),\"i\"))==0) &&\n (this.text.search(RegExp(\"</\"+dwscripts.getTagName(this.priorNode),\"i\"))==-1)\n )\n {\n // This logic is now performed in extPart.queueDocEdit()\n }\n else // if not a block tag\n {\n var priorNodeOffsets = dwscripts.getNodeOffsets(this.priorNode);\n var insertMergeDelims = this.mergeDelims;\n var existingMergeDelims = docEdits.canMergeBlock(dwscripts.getOuterHTML(this.priorNode));\n\n if (this.dontMerge || !existingMergeDelims)\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n }\n else if (this.text == \"\")\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n\n this.mergeDelims = existingMergeDelims;\n }\n else if (insertMergeDelims\n && insertMergeDelims[0].toLowerCase() == existingMergeDelims[0].toLowerCase()\n && insertMergeDelims[1].toLowerCase() == existingMergeDelims[1].toLowerCase())\n {\n var escStartDelim = dwscripts.escRegExpChars(insertMergeDelims[0]);\n var escEndDelim = dwscripts.escRegExpChars(insertMergeDelims[1]);\n\n // Only strip the delimeters if we are not replacing the whole block\n if (this.matchRangeMin != 0 &&\n (priorNodeOffsets[0] + this.matchRangeMax) != priorNodeOffsets[1])\n {\n // Preserve spaces and tabs before the first newline before the end delimeter.\n var pattern = \"^\\\\s*\" + escStartDelim + \"\\\\s*([\\\\S\\\\s]*[^\\\\r\\\\n])\\\\s*\" + escEndDelim + \"\\\\s*$\";\n this.text = this.text.replace(new RegExp(pattern,\"i\"), \"$1\");\n }\n\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n }\n else\n {\n //must split up existing node and insert in between\n var partBefore = docEdits.allSrc.substring(priorNodeOffsets[0], this.matchRangeMin + priorNodeOffsets[0]);\n var partAfter = docEdits.allSrc.substring(this.matchRangeMax + priorNodeOffsets[0], priorNodeOffsets[1]);\n\n var pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[0]) + \"\\\\s*$\";\n if (partBefore && partBefore.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = existingMergeDelims[1] + docEdits.strNewlinePref + this.text;\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n }\n else\n {\n this.insertPos = priorNodeOffsets[0];\n }\n\n pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[1]) + \"\\\\s*$\";\n if (partAfter && partAfter.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = this.text + docEdits.strNewlinePref + existingMergeDelims[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeBottom = true;\n }\n else\n {\n this.replacePos = priorNodeOffsets[1];\n }\n }\n }\n }\n \n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.priorNode, true); // pss true for isUpdate\n } \n }\n}", "function replace(pString, pText, by) {\n try {\n var strLength = pString.length,\n txtLength = pText.length;\n if ((strLength == 0) || (txtLength == 0)) return pString;\n var vIndex = pString.indexOf(pText);\n while (vIndex >= 0) {\n pString = pString.replace(pText, by);\n vIndex = pString.indexOf(pText);\n } //End While\n } catch (e) {}\n return pString;\n}", "function replacePlaceholders(quasisDoc, expressionDocs) {\n if (!expressionDocs || !expressionDocs.length) {\n return quasisDoc;\n }\n\n const expressions = expressionDocs.slice();\n let replaceCounter = 0;\n const newDoc = mapDoc$3(quasisDoc, doc => {\n if (!doc || !doc.parts || !doc.parts.length) {\n return doc;\n }\n\n let {\n parts\n } = doc;\n const atIndex = parts.indexOf(\"@\");\n const placeholderIndex = atIndex + 1;\n\n if (atIndex > -1 && typeof parts[placeholderIndex] === \"string\" && parts[placeholderIndex].startsWith(\"prettier-placeholder\")) {\n // If placeholder is split, join it\n const at = parts[atIndex];\n const placeholder = parts[placeholderIndex];\n const rest = parts.slice(placeholderIndex + 1);\n parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);\n }\n\n const atPlaceholderIndex = parts.findIndex(part => typeof part === \"string\" && part.startsWith(\"@prettier-placeholder\"));\n\n if (atPlaceholderIndex > -1) {\n const placeholder = parts[atPlaceholderIndex];\n const rest = parts.slice(atPlaceholderIndex + 1);\n const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\\s\\S]*)/);\n const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:\n // animation: linear ${time}s ease-out;\n\n const suffix = placeholderMatch[2];\n const expression = expressions[placeholderID];\n replaceCounter++;\n parts = parts.slice(0, atPlaceholderIndex).concat([\"${\", expression, \"}\" + suffix]).concat(rest);\n }\n\n return Object.assign({}, doc, {\n parts\n });\n });\n return expressions.length === replaceCounter ? newDoc : null;\n }", "regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of tenant microservices in current topology.
function getTenantTopology(axios$$1) { return restAuthGet(axios$$1, 'instance/topology/tenant'); }
[ "static getAllTenants() {\n return HttpClient.get(`${IDENTITY_GATEWAY_ENDPOINT}tenants/all`).map(toTenantModel);\n }", "ListOfSubaccounts() {\n let url = `/me/subAccount`;\n return this.client.request('GET', url);\n }", "function commandListSubaccounts() {\n\treturn getActiveInstance()\n\t.then(instance => instance.getSubaccounts())\n\t.then(subaccounts => {\n\t\tsubaccounts.forEach(subaccount => {\n\t\t\tconsole.log(`${subaccount.regionHost}/${subaccount.subaccount}`);\n\t\t});\n\t});\n}", "getElementServicesForProbe (probe) {\n // Retrieve target elements for all models or specified one\n let services = this.app.getElementServices(probe.forecast)\n services = services.filter(service => {\n return probe.elements.reduce((contains, element) => contains || (service.name === probe.forecast + '/' + element), false)\n })\n return services\n }", "function servicesList() {\n connection.query(\"SELECT * FROM servicesList\", function (err, results) {\n\n if (err) throw err;\n \n }\n\n )}", "function discoverTTSDevices() {\n console.log('[TTS] Discovering resources on TTS...');\n var json = JSON.stringify({\n path: '/api/v1/device/list',\n requestID: '1',\n options: {depth: 'all'}\n });\n manageWS.send(json);\n}", "async function getVendors() {\n return Vendor.findAll()\n}", "function getMicroserviceTenantRuntimeState(axios$$1, identifier, tenantToken) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/state');\n }", "function listUserTenants(axios$$1, username, includeRuntimeInfo) {\n var query = '';\n if (includeRuntimeInfo) {\n query += '?includeRuntimeInfo=true';\n }\n return restAuthGet(axios$$1, 'users/' + username + '/tenants' + query);\n }", "getPotentialHosts() {\n return this.getPotentialRegions()\n .map((r) => { return r.host; });\n }", "getConnectedControllers() {\n\n var _thisSvc = this;\n\n var controllerList = [];\n\n for(var controllerId in _thisSvc.controllerInfoCollection) {\n\n var controllerInfo =\n _thisSvc.controllerInfoCollection[controllerId];\n\n controllerList.push({\n controllerId: controllerInfo.controllerId,\n name: controllerInfo.name\n });\n }\n\n return controllerList;\n }", "function listSubscriptions() {\n\n\t// Lists all subscriptions in the current project\n\treturn pubsub.getSubscriptions().then(results => {\n\t\tconst subscriptions = results[0];\n\n\t\tconsole.log('Subscriptions:');\n\t\tsubscriptions.forEach(subscription => console.log(subscription.name));\n\n\t\treturn subscriptions;\n\t});\n}", "agencies(cb) {\n var agencies = [ ];\n\n this._newRequest().query({ command: 'agencyList' }, function(e) {\n switch(e.name) {\n case 'error':\n cb(null, e.data);\n break;\n\n case 'opentag':\n var tag = e.data;\n var attributes = tag.attributes;\n\n if (tag.name === 'agency') {\n agencies.push(attributes);\n }\n break;\n\n case 'end':\n cb(agencies);\n break;\n }\n }.bind(this));\n }", "function getLiveSynclets(service, apps, cbDone) {\n acl.getAppsClasses(Object.keys(apps || {}), function (err, classes) {\n if (err) return cbDone(err);\n cbDone(null, servezas.syncletList(service, classes), classes);\n });\n}", "getAllAdmins() {\n return this.getUserSets('ADMIN');\n }", "_getServicesRecursively (serviceInfo) {\n if (Array.isArray(serviceInfo)) serviceInfo = serviceInfo[0]\n for (let i = 0; i < serviceInfo.service.length; i++) {\n const service = serviceInfo.service[i]\n if ('service' in service) this._getServicesRecursively(service)\n else {\n const srv = new Service(service)\n this.services[srv.name] = srv\n }\n }\n }", "ListOfOrganisations() {\n let url = `/me/ipOrganisation`;\n return this.client.request('GET', url);\n }", "function getNavigators() {\n return new Promise(resolve => {\n xapi.Status.Peripherals.ConnectedDevice.get().then(async devices => {\n var data = devices.filter(device => device.Name.toLowerCase().includes(\"navigator\") && device.Type.toLowerCase().includes(\"touchpanel\"));\n resolve(data);\n });\n });\n}", "getIdentityprovidersOkta() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/identityproviders/okta', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete class, including all assignments, interactions, and enrollments of class
function deleteClassAssignments(classID) { let classDoc = db.collection('classes').doc(classID); let assignRef = classDoc.collection('assignments'); let enrollRef = db.collection('class-enrollment'); return assignRef.get().then(snapshot => { snapshot.forEach(assignSnap => { let assignDoc = assignRef.doc(assignSnap.id); deleteInteractions(assignDoc); assignDoc.delete(); }) enrollRef.where('class', '==', classDoc).get().then(snapshot2 => { snapshot2.forEach(enrollSnap => { enrollRef.doc(enrollSnap.id).delete(); }) classDoc.delete(); }) }) }
[ "function removeModelClasses() {\n modelClasses = null;\n}", "delete () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.delete();\n\n\t\t// Remove all remaining chain links\n\t\twhile (this.chains.length > 0) this.removeLastChain();\n\n\t\t// Clear the class's hook instance.\n\t\tHook.hookElement = null;\n\t}", "async remove() {\n // TODO: Should delete class itself too?\n\n // Ensure model is registered before removing model data\n assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.');\n\n // Ensure this Model instance is stored in database\n assert.isNotNull(this.__id, 'Model must be stored in database to remove.');\n\n // Call internal DB API to remove the data associated with this Model instance by ID\n await this.constructor.__db.removeById(this.constructor, this.__id);\n\n // Nullify internal ID as no longer exists in database\n this.__id = null;\n }", "exitNormalClassDeclaration(ctx) {\n\t}", "function removeClass(obj, cls) {\n //defining variable classNameArray for array, which created by method split\n var classNameArray = obj.className.split(\" \");\n //loop for searching cls in classNumberArray and removing those items\n for (var i = 0; i < classNameArray.length; i++) {\n //defining variable numberClass for saving number index of item, which matches with cls\n var numberClass = classNameArray.indexOf(cls);\n //condition: if numberClass>=0 (some item of classNumberArray matches with cls\n if (numberClass >= 0) {\n //removing 1 item from index=numberClass\n classNameArray.splice(numberClass, 1);\n }\n }\n //joining items in one line with separator \" \"\n obj.className = classNameArray.join(\" \");\n //returning result-object obj with new value of property\n return obj;\n}", "delete() {\n\t\t// Remove all edge relate to vertex\n\t\tthis.vertexMgmt.edgeMgmt.removeAllEdgeConnectToVertex(this)\n\n\t\t// Remove from DOM\n\t\td3.select(`#${this.id}`).remove()\n\t\t// Remove from data container\n\t\t_.remove(this.dataContainer.vertex, (e) => {\n\t\t\treturn e.id === this.id\n\t\t})\n\t}", "async delete() {\n await this.pouchdb.destroy();\n await this.database.removeCollectionDoc(this.dataMigrator.name, this.schema);\n }", "deleteInstance(instance) {\n this.instances.remove(instance)\n }", "function RemoveHSCodeRow(ClassName) {\n DeselectHSCodeNode(ClassName);\n}", "deleteAll() {\n this.forEach(item => {\n this.delete(item);\n });\n }", "function deleteModel() {\n vm.processing = {};\n vm.processing.status = true;\n vm.processing.finished = false;\n vm.processing.undeployedDeregistered = true;\n\n // Undeploy and deregister each node if needed\n vm.deletionPromises = [];\n $(\".jtk-node\").each(function(index, element) {\n var $element = $(element);\n var type = $element.attr('class').toString().split(\" \")[1];\n if ($element.data(\"deployed\")) {\n var promise = undeployComponent(type, $element, false);\n vm.deletionPromises.push(promise);\n } else if ($element.data(\"id\")) {\n var promise = deregisterComponent(type, $element, false);\n vm.deletionPromises.push(promise);\n }\n });\n\n // After all deregistrations and undeployments - delete the model\n $q.all(vm.deletionPromises).then(function() {\n if (vm.processing.undeployedDeregistered) {\n ModelService.DeleteModel(vm.currentModel.name).then(function(response) {\n vm.processing.message = vm.currentModel.name + \" deleted\";\n vm.processing.success = true;\n processingTimeout();\n newModel();\n }, function(response) {\n vm.processing.message = \"Deletion error\";\n vm.processing.success = false;\n processingTimeout();\n });\n } else {\n vm.processing.message = \"Undeployment or deregistration error\";\n vm.processing.success = false;\n processingTimeout();\n }\n });\n }", "deleteMultiple() {}", "function removeSubjectClass(){\n $(\".questionContainer\").removeClass(\"AH LA MA SC SS\");\n}", "function deleteEntities() {\n vm.cesium.deleteEntity( subSolarTrackEntity );\n vm.cesium.deleteEntity( nightsideCenterTrackEntity );\n vm.cesium.deleteEntity( solarTrackEntity );\n }", "destroy() {\n let cityName = this.name, keys = Object.keys( Country.instances ), i,\n country;\n\n // on delete cascade (if a capital is deleted, then the country is too)\n for (i = 0; i < keys.length; i += 1) {\n if (Country.instances[keys[i]] && this.equals(\n Country.instances[keys[i]].capital )) {\n Country.instances[keys[i]].destroy();\n }\n }\n\n // check if city needs to be deleted from a country's cities\n // refresh keys because values might have been deleted\n keys = Object.keys(Country.instances);\n for (i = 0; i < keys.length; i += 1) {\n country = Country.instances[keys[i]];\n if (util.mapContains(country.cities, cityName)) {\n delete country.cities[cityName];\n }\n }\n\n delete City.instances[this.name];\n\n console.log( \"City \" + cityName + \" deleted.\" );\n }", "static async deleteCourse(courseCode){\n await pool.query('DELETE FROM has WHERE coursecode=?',courseCode);\n await pool.query('DELETE FROM course WHERE coursecode=?',courseCode);\n }", "function remove_ingredient_row (class_ing) {\n $('.' + class_ing).parents('tr').remove()\n }", "deleteAllStudents() {\n return this.deleteUsers('STUDENT');\n }", "static unbind(keys, classRef) {\n for (const key of keys) {\n for (const i in listeners[key]) {\n if (listeners[key][i] === classRef) {\n delete listeners[key][i]\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function check the all comments are closed if yes borrower allow to submit for approval
function checkAdminAllCommentsClosed(){ var no_of_comments = $(".commentClass:not(#comment_status_XXX)").length; var no_of_checked_comments = $(".commentClass:not(#comment_status_XXX):checked").length; //~ alert("no_of_comments:"+no_of_comments+" | no_of_checked_comments:"+no_of_checked_comments); if(no_of_comments != no_of_checked_comments) return true; return false; }
[ "function commentsAvailable2 () {\n var m = document.getElementsByClassName(\"YxbmAc\");\n if(m.length > 0){\n console.log('erasure: %s comments are available.', m.length);\n return true;\n }\n return false;\n}", "function requireCom() {\n return this.feedbackType === 'comment';\n}", "function CheckUnCheckAllComments(postid) {\r\n\r\n // loop on all comments row and check (or uncheck) each one\r\n var firstIsChecked = false;\r\n $('.cbxComment_' + postid).each(function (index, value) {\r\n if (index === 0 && $(this).is(':checked'))\r\n firstIsChecked = true;\r\n\r\n if (firstIsChecked === true)\r\n $(this).prop('checked', false);\r\n else\r\n $(this).prop('checked', true);\r\n });\r\n}", "function checkBookingAvailableClosedPassed () {\n\t \t var sliderSeconds = 15*60*parseInt(place_slider_from); // 15 minutes * slider steps\n var sliderSecondsTo = 15*60*parseInt(place_slider_to); // 15 minutes * slider steps\n\n\t var TimeOfTheDatePicker_1970 = +$(\"#datepicker_fe\").datepicker( \"getDate\" ).getTime();\n\t var placeOffset = document.getElementById(\"server_placeUTC\").value;\n\t var dndt = TimeOfTheDatePicker_1970/1000;\n\t var d = new Date();\n\t var utc = d.getTime() + (d.getTimezoneOffset() * 60000);\n\t var nd = new Date(utc + (3600000 * placeOffset));\n\t var ndt = nd.getTime()/1000;\n var diff = ndt - dndt; // seconds passed from the start of the selected date\n if (diff - 60 > sliderSeconds) {\n \t // If less than minute to book return \"place_passed\"\n \t return 1;\n }\n // Else slider is after the place time passed , check if place closed on selected range\n var TimePeriod = sliderSecondsTo - sliderSeconds; // Chosen period of booking\n var endOfBooking = parseInt(sliderSeconds) + parseInt(TimePeriod);\n\t var placeOpen = bookingVars.placeOpen;\n\t var anyOpenRangeValid = false;\n\t for (var ind in placeOpen) { \t\t \n\t\t\t var from = placeOpen[ind].from;\n\t\t\t var to = placeOpen[ind].to;\n\t\t\t if (from <= sliderSeconds && endOfBooking <= to) {\n\t\t\t\t anyOpenRangeValid = true;\n\t\t\t }\n\t }\n\tif(anyOpenRangeValid) {\n\t //Some range valid\n\t return 0;\n\t} else {\n\t // No valid open range\t\n\t return 2;\n\t}\n}", "function checkCommentLength(textareaObj) {\n let key = event.keyCode || event.which;\n //check the number of character in textbox\n if (textareaObj.value.length > 0) {\n $(textareaObj).siblings('.comment-submit').removeAttr('disabled');\n /*I'm not sure if I should add the 'hit enter' feature. Comments are pretty\n detailed and the ability to use Enter might be useful.\n if (key === 13) {\n sendComment($(textareaObj).siblings('.comment-submit'));\n }*/\n }else {\n $(textareaObj).siblings('.comment-submit').attr('disabled', 'disabled');\n }\n\n}", "function bypassCommentBlock(){\n\tisCommenting=true; // set flag true if leave pg was a commenting action\n}", "acceptPledge() {\n this.setPledgeModalToggle();\n this.startPledgeModalToggle();\n this.state.pledge.footprintReduction = Math.round(this.state.pledge.weight * this.state.slider * 10)/10;\n this.props.addPledge(this.state.pledge);\n }", "function check_rev_comment(lines) {\n console.log(lines);\n var title = lines[0];\n // check title\n console.log(\">> checking title line:\" + title);\n if (check_rev_titile(title) != 0) {\n console.log(\">> Title check failed\");\n core.setFailed(\"Title check failed:\" + title);\n return 1;\n } else {\n console.log(\">> Title is OK!\");\n }\n\n // check for mandatory fields\n console.log(\">> checking mandatory fields!\");\n var mand_fields = ['Summary:', 'Test Plan:', 'Reviewed-by:', 'Issue:'];\n mand_fields.forEach(mf => {\n if (lines.find(l => l.startsWith(mf)) == undefined) {\n console.log(\"Missing mandatory field:\" + mf);\n core.setFailed(\"Missing mandatory field '\" + mf + \"' in git log\");\n return 1;\n }\n });\n console.log(\">> All mandatory fields are present\");\n return 0;\n}", "hasUnresolvedComments() {\n return this.json_.unresolved_comment_count !== 0;\n }", "function bidAccepted(bid, contract) {\n console.log('Bid accepted');\n importer.node.account.complete(bid.getValue());\n importer.contracts.push(contract);\n contract.paid(bid.getValue());\n }", "isLockedWork() {\n let userId = userService.getLoggedId();\n let attendance = attendanceService.getAttendance(workToEdit.idAttendance);\n if(!attendance || !attendance.approved)\n return false;\n return true;\n }", "function commentsMobile (ev) {\n var v = require('./comments_events_vars')\n if ($(ev.target).attr('class').indexOf('disagree') !== -1) {\n if (disagreeOpened === false || disagreeOpened === undefined) {\n $(v.commentsMobile[3]).css('display', 'flex')\n $(v.commentsMobile[4]).css('display', 'block')\n $(v.commentsMobile[5]).css('display', 'flex')\n disagreeOpened = true\n } else {\n $(v.commentsMobile[3]).css('display', 'none')\n $(v.commentsMobile[4]).css('display', 'none')\n $(v.commentsMobile[5]).css('display', 'none')\n disagreeOpened = false\n }\n } else {\n if (agreeOpened === false || agreeOpened === undefined) {\n $(v.commentsMobile[0]).css('display', 'flex')\n $(v.commentsMobile[1]).css('display', 'block')\n $(v.commentsMobile[2]).css('display', 'flex')\n agreeOpened = true\n } else {\n $(v.commentsMobile[0]).css('display', 'none')\n $(v.commentsMobile[1]).css('display', 'none')\n $(v.commentsMobile[2]).css('display', 'none')\n agreeOpened = false\n }\n }\n}", "validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }", "function checkForChallengesAllowed() {\n vm.challengesAllowed = true;\n // Check for allowed weekend challenges\n if (!vm.competition.allowWeekendChallenges &&\n ((moment().format('ddd') === 'Fri' && moment().format('H') >= 17) ||\n moment().format('ddd') === 'Sat' ||\n moment().format('ddd') === 'Sun')) {\n vm.challengesAllowed = false;\n }\n }", "checkGoalReached() {\n\t\tthis.afterDeadline();\n\t\tif (amountRaised >= fundingGoal){\n\t\t\tfundingGoalReached = true;\n\t\t\t// emit GoalReached(beneficiary, amountRaised);\n\t\t}\n\t\tcrowdsaleClosed = true;\n\t}", "function abortChecker(){\nvar reqCloseActions=getElementsByClass(\"request-done\")\nvar abcdefg; //Dummy to check undefined... JS is wierd in this manner\n\nfor(var k in reqCloseActions){\nvar token=reqCloseActions[k].href;\n\nreqCloseActions[k].href=\"javascript:void(0);\"; //So as to avoid icky situations with Javascript event bubbling\nreqCloseActions[k].token=token+\"\"; //Store the link in a hidden attribute\nreqCloseActions[k].onclick=function(evt){\nif(confirmReqCloseQuestions[this.innerHTML]&&(confirmReqCloseQuestions[this.innerHTML]!=\"\")){\n\tif(confirm(confirmReqCloseQuestions[this.innerHTML])){ \n\t\tif(this.target==\"_blank\"){\n\t\t\twindow.open(this.token); //Might anger popup blockers, but otherwise clicking on the create! link navigates away from the ts page, and it's rather annoying to get back. Right-clicking is better, but if you have just commented or something you get stuck again.\n\t\t}else{\n\t\t\tdocument.location=this.token;\n\t\t}\n\n\t}\n\n}else{ document.location=this.token; }\t\n\n}\n}\n\n\n//Special Handling for Create! link (As it needs to open the page in a new window)\nif(getElementsByClass('request-req-create')[0]!==abcdefg){\n\tvar createlink=getElementsByClass('request-req-create')[0];\n\tctxt=createlink.innerHTML;\n\tcreatelink.onclick=createLinkHref; //The onclick will be executed _before_ the href attribute is opened, giving us a chance to intercept it\n\t\n}\n}", "function cancel_ques__1(exn) /* (exn : exception) -> bool */ {\n var _x9 = info(exn);\n return (_x9._tag === _tag_Cancel);\n}", "authorCommentedAfterUser(user) {\n var owner = this.json_.owner;\n var filteredMessages = this.getMessages().filter(function(message) {\n if (message.shouldBeIgnored())\n return false;\n return message.isAuthoredBy(user) || message.isAuthoredBy(owner);\n });\n\n var lastMessage = filteredMessages[filteredMessages.length - 1];\n return !lastMessage || lastMessage.isAuthoredBy(owner);\n }", "function checkReview(){\n\tchrome.storage.sync.get(['reviewed','reviewDateDays'], function(r) {\n\t\tif(r.reviewed != true && (r.reviewDateDays !== undefined )){\n\t\t\t//there is a valid date\n\t\t\tvar currDaysNum = convertDateToDays(new Date());\n\t\t\tvar daysBetween = (currDaysNum - r.reviewDateDays);\n\t\t\tif((daysBetween) < 0){\n\t\t\t\t//ask to review\n\t\t\t\taskToReview();\n\t\t\t}else if((daysBetween) >= 7){\n\t\t\t\t//over 1 week\n\t\t\t\taskToReview();\n\t\t\t}else{\n\t\t\t\t//always call, used for testing\n\t\t\t\t//askToReview();\n\t\t\t}\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cancel the word edit and revert back to original state
function cancel() { //i've pressed cancel so don't save changes and tell all clients its open $(document).on('click', '.word-cancel', function () { var id = $(this).data('link_id'); socket.emit('cancelword', id); uiObj.alertsOpen(); }); //response to cancelling the edit socket.on('cancelword', function (word) { var wordC = $('[data-_id-word="' + word._id + '"]'); menu.call(this, word, word.active, wordC, true); var editor = tinymce.get(word._id); editor.getBody().setAttribute('contenteditable',false); editor.getBody().style.backgroundColor = "rgba(0,0,0,0.5)"; if (word.data === undefined) { editor.setContent(''); } else { editor.setContent(word.data); } uiObj.removeEdits(wordC); uiObj.alertsClose(); }); }
[ "revert() {\n this.innerHTML = this.__canceledEdits;\n }", "function cancelEdit() {\n\t\n\tdebug('cancelEdit::Start:editing=:'+editState.editing);\n\t\n\t//careful. removing the tag may trigger the onBlur handler..\n\t\n\tvar aSpan;\n\tvar tmpStart, tmpEnd;\n\tvar parentElem;\n\t\n\tif ((tmpStart = getEditNode()) != null) {\n\t\t//clear this so no additional cancels come in\n\t\tclearInputEventHandlers(tmpStart); \n\t\t\n\t\t//if special edit do this\n\t\tif (editState.editType == SPEAKEREDIT_COMMAND) {\n\t\t\t//remove the input element\n\t\t\tparentElem = tmpStart.parentNode;\n\t\t\tparentElem.removeChild(tmpStart);\n\t\t\t//unhide newspeaker\n\t\t\tparentElem.setAttribute(NEWSPEAKER_ATTR, SHOWSPEAKER_TEXT);\n\t\t\t\n\t\t\tif (editState.editing) {\n\t\t\t\t//clear the \"we are editing\" flag\n\t\t\t\teditState.editing = false;\n\t\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t\t//send the cancel\n\t\t\t\t\tsendCommand(editState.lowerEditRange, editState.upperEditRange, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t\t} //else handle in the ajax response function\n\t\t\t} \n\t\t} else if (editState.editType == \"\") {\n\t\t\t\n\t\t\t//get 1st span in edit range\n\t\t\taSpan = tmpStart.nextSibling;\n\t\t\t\n\t\t\t//remove the input element\n\t\t\ttmpStart.parentNode.removeChild(tmpStart);\n\t\t\t\n\t\t\t//get the first element of edit group\n\t\t\tif (aSpan != null) {\n\t\t\t\ttmpStart = aSpan.id;\n\t\t\t\ttmpEnd = tmpStart;\n\t\t\t\t\n\t\t\t\t//\"unset\" editing while keeping track of end of range so can use later\n\t\t\t\twhile (aSpan != null) {\n\t\t\t\t\tif (spanIsMarkedEditing(aSpan)) {\n\t\t\t\t\t\tunsetSpanEditingFlag(aSpan);\n\t\t\t\t\t\tunsetSpanEditingStyle(aSpan);\n\t\t\t\t\t\ttmpEnd = aSpan.id;\n\t\t\t\t\t\taSpan = aSpan.nextSibling;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//we reached end of editing range\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (editState.editing) {\n\t\t\t\t\t//clear the \"we are editing\" flag\n\t\t\t\t\teditState.editing = false;\n\t\t\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t\t\t//send the cancel\n\t\t\t\t\t\tsendCommand(tmpStart, tmpEnd, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t\t\t} //else handle in the ajax response function\n\t\t\t\t} else {\n\t\t\t\t\t//no longer editing - which means we sent the \n\t\t\t\t\t//edit already and backend is cancelling the edit. No need to cancel lock at this point.\n\t\t\t\t\tdebug(\"canceEdit:: Already sent edit so no unlock command to send.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//clear the \"we are editing\" flag (if editing)\n\t\t\t\teditState.editing = false;\n\t\t\t}\n\t\t}\n\t} else if ((editState.editType == RESTORE_COMMAND) || (editState.editType == SPEAKERDELETE_COMMAND) || (editState.editType == PARADELETE_COMMAND) ) {\n\t\t//remove the dialog box and restore\n\t\tremoveDialog1();\n\t\t\n\t\tif (editState.editing) {\n\t\t\t//clear the \"we are editing\" flag\n\t\t\teditState.editing = false;\n\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t//send the cancel\n\t\t\t\tsendCommand(editState.lowerEditRange, editState.upperEditRange, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t} //else handle in the ajax response function\n\t\t} \n\t} else {\n\t\tdebug(\"cancelEdit:: NO EDIT in progress.\");\n\t}\n\tdebug(\"cancelEdit::done\");\n}", "cancelModification() {\n this.input.value = this.getFormula();\n }", "function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }", "function cancelEditOp(editItem, dispItem, opt_setid) {\r\n switchItem2(editItem, dispItem);\r\n var editwrapper = document.getElementById(editItem);\r\n var inputElems = cbTbl.findNodes(editwrapper,\r\n function (node) {\r\n return node.nodeName.toLowerCase() == 'input' &&\r\n (!node.type || node.type.toLowerCase() != 'hidden') &&\r\n node.value;\r\n });\r\n for (var i = 0; i < inputElems.length; ++i) {\r\n var inputElem = inputElems[i];\r\n var newVal = '';\r\n if (inputElem.id) {\r\n var origElem = document.getElementById(inputElem.id + '.orig');\r\n newVal = (origElem && origElem.value) ? origElem.value : newVal;\r\n }\r\n inputElems[i].value = newVal;\r\n }\r\n set_isset(false, opt_setid);\r\n}", "function _editTextBlockCancel ( /*[Object] event*/ e ) {\n\t\te.preventDefault();\n\t\tcloseEditTextBar();\n\t\tcnv.discardActiveObject();\n\t\treturn false;\n\t}", "function unfocusWord() {\n $('.word').removeClass('word-active');\n\n if (typeof currentPopper.destroy === 'function') {\n currentPopper.destroy();\n }\n\n $('.tools').hide();\n }", "_cancelComment() {\n this._comment = '';\n this._displayFormActions = false;\n }", "function cancelEdit() {\n var currentBurger = $(this).data(\"burger\");\n if (currentBurger) {\n $(this).children().hide();\n $(this).children(\"input.edit\").val(currentBurger.text);\n $(this).children(\"span\").show();\n $(this).children(\"button\").show();\n }\n }", "function stopIndexEditing() {\r\n\r\n var sO = CurStepObj;\r\n\r\n // We are currently editing an index. Change the focus box to something\r\n // else and redraw the current step.\r\n // Note: Do NOT call changeCWInputBox() because it calls stopIndexEditing\r\n // in turn -- which will lead to infinite recursion\r\n //\r\n var boxid = sO.boxExprs.length -1; // TODO: change to previous\r\n sO.focusBoxExpr = sO.boxExprs[boxid]; // focused expr\r\n sO.focusBoxId = boxid; // focused box \r\n setDefaultActiveSpace(sO); // set default space\r\n\r\n // Redraw the current step \r\n //\r\n redrawCurStep();\r\n\r\n}", "function cancel() {\n history.goBack();\n }", "undoAction() {\n this.element.executeOppositeAction(this.details);\n }", "function dwscripts_clearDocEdits()\n{\n docEdits.clearAll();\n}", "function resumeEditing()\r\n{\r\n\twith(currObj);\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\"><img src=\\\"\" + currObj.config['imagePath'] + \"images/page_white_edit.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Resume Editing\\\" alt=\\\"Resume Editing\\\" border=\\\"0\\\" /></a>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\">Resume Editing</a>\";\r\n\t}\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"<img src=\\\"\" + currObj.config['imagePath'] + \"images/working.gif\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Working...\\\" alt=\\\"Working...\\\" border=\\\"0\\\" />\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"Working...\";\r\n\t}\r\n\t\r\n\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\t\r\n\tcurrObj.switchText();\r\n}", "function resetSpellChecker()\r\n{\r\n\twith(currObj);\r\n\tcurrObj.resetAction();\r\n\t\r\n\tcurrObj.objToCheck.value = \"\";\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.objToCheck.disabled = false;\r\n\t\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\tcurrObj.statusSpan.style.display = \"none\";\r\n\t\r\n}", "function revokeCustomTinyMceTextEditorPopup() {\n\thideModel('editorPopUp');\n}", "function invalidWord() {\n // *** crosses off word \n GameDatabase.players[GameDatabase.currentPlayer].removeScore(); // *** update changes score \n}", "function resetAction()\r\n{\r\n\twith(currObj);\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"check_spelling\\\" onclick=\\\"setCurrentObject(\" + currObj.config['varName'] + \"); \" + currObj.config['varName'] + \".spellCheck();\\\"><img src=\\\"\" + currObj.config['imagePath'] + \"images/spellcheck.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Check Spelling &amp; Preview\\\" alt=\\\"Check Spelling &amp; Preview\\\" border=\\\"0\\\" /></a>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"check_spelling\\\" onclick=\\\"setCurrentObject(\" + currObj.config['varName'] + \"); \" + currObj.config['varName'] + \".spellCheck();\\\">Check Spelling &amp; Preview</a>\";\r\n\t}\r\n\r\n\tcurrObj.statusSpan.innerHTML = \"\";\r\n}", "function wordGuessClear() {\n targetWordGuessArea.textContent = \"\";\n censoredWord = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collectable items render and check functions Function to draw collectable objects.
function drawCollectable(t_collectable) { // Draw collectable items fill('#5398BA'); triangle(t_collectable.x_pos, t_collectable.y_pos, t_collectable.x_pos-24, t_collectable.y_pos-30, t_collectable.x_pos+24, t_collectable.y_pos-30); triangle(t_collectable.x_pos, t_collectable.y_pos-40, t_collectable.x_pos-14, t_collectable.y_pos-40, t_collectable.x_pos-10, t_collectable.y_pos-30); triangle(t_collectable.x_pos+14, t_collectable.y_pos-40, t_collectable.x_pos, t_collectable.y_pos-40, t_collectable.x_pos+10, t_collectable.y_pos-30); fill('#68BEE8'); triangle(t_collectable.x_pos, t_collectable.y_pos, t_collectable.x_pos-12, t_collectable.y_pos-30, t_collectable.x_pos+12, t_collectable.y_pos-30); fill('#60AFD6'); triangle(t_collectable.x_pos, t_collectable.y_pos-40, t_collectable.x_pos-12, t_collectable.y_pos-30, t_collectable.x_pos+12, t_collectable.y_pos-30); triangle(t_collectable.x_pos-14, t_collectable.y_pos-40, t_collectable.x_pos-24, t_collectable.y_pos-30, t_collectable.x_pos-8, t_collectable.y_pos-30); triangle(t_collectable.x_pos+14, t_collectable.y_pos-40, t_collectable.x_pos+24, t_collectable.y_pos-30, t_collectable.x_pos+8, t_collectable.y_pos-30); }
[ "function drawEditionElements() {\n if (editionCheckbox.checked) {\n // Draw points\n for (var ptIndex = 0; ptIndex < customPoints.length; ptIndex++) {\n ctx.fillStyle = \"#f00\";\n ctx.fillRect(customPoints[ptIndex].x - (pointWidth / 2), customPoints[ptIndex].y - (pointHeight / 2), pointWidth, pointHeight);\n }\n // Draw lines\n if (polygonInConstruction.length > 0) {\n for (var i = 0; i < polygonInConstruction.length; i++) {\n point1 = findPointForId(polygonInConstruction[i][0]);\n point2 = findPointForId(polygonInConstruction[i][1]);\n ctx.strokeStyle = \"#0f0\";\n ctx.beginPath();\n ctx.moveTo(point1.x,point1.y);\n ctx.lineTo(point2.x, point2.y);\n ctx.stroke();\n }\n }\n // Draw polygons\n if (customPolygons.length > 0) {\n for (var i = 0; i < customPolygons.length; i++) {\n thePoly = []\n for (var j = 0; j < customPolygons[i].length; j++) {\n thePoint = findPointForId(customPolygons[i][j]);\n thePoly.push({x: thePoint.x, y: thePoint.y})\n }\n drawPolygon(thePoly);\n }\n }\n }\n}", "draw() {\n\t\tthis.components.forEach( component => component.draw() );\n\t}", "onRender() {}", "function render(items) {\n // LOOP\n // var item = ...\n // $(\"div#target\").append(\"<p>\" + item.message + \"</p>\")\n //\n }", "makeDrawInfoList() { throw new Error('makeDrawInfoList is not Implemented!!'); }", "function render() {\n\t//clear all canvases for a fresh render\n\tclearScreen();\n\t\n\t//draw objects centered in order\n\tfor (let i = 0; i < objects.length; ++i) {\n\t\tdrawCentered(objects[i].imgName,ctx, objects[i].x, objects[i].y,objects[i].dir);\n\t}\n\t\n\t//finally draw the HUD\n\tdrawHUD();\n}", "function weapon_draw(player_obj, wep, render_batch) {\n\tif (wep.actioning == true) {\n\t\t/*ctx.drawImage(\n\t\t\tweapon_sheet, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].x, wep.animations[player_obj.data.dir][wep.atkIndex].y, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].w, wep.animations[player_obj.data.dir][wep.atkIndex].h,\n\t\t\tplayer_obj.data.x-12, player_obj.data.y-16, \n\t\t\twep.animations[player_obj.data.dir][wep.atkIndex].w, wep.animations[player_obj.data.dir][wep.atkIndex].h\n\t\t);*/\n\t\trender_batch.batch.push({\n\t\t\taction: 1,\n\t\t\tsheet: weapon_sheet, \n\t\t\tsheet_x: wep.animations[player_obj.data.dir][wep.atkIndex].x,\n\t\t\tsheet_y: wep.animations[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tsheet_w: wep.animations[player_obj.data.dir][wep.atkIndex].w, \n\t\t\tsheet_h: wep.animations[player_obj.data.dir][wep.atkIndex].h,\n\t\t\tx: player_obj.data.x-12,\n\t\t\ty: player_obj.data.y-16, \n\t\t\tw: wep.animations[player_obj.data.dir][wep.atkIndex].w,\n\t\t\th: wep.animations[player_obj.data.dir][wep.atkIndex].h\n\t\t\t});\n\t}\n\t\n\tif (wep.buffs.indexOf(\"electric\") > -1) {\n\t\tfor (var i=0; i<wep.target_tiles.length; i++) {\n\t\t\tlightning_tile_draw(wep.target_tiles[i]);\n\t\t}\n\t}\n\t\n\tif (show_hitboxes == true) {\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x+wep.hitbox[player_obj.data.dir][wep.atkIndex].w, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y+wep.hitbox[player_obj.data.dir][wep.atkIndex].h, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t\trender_queue.push({\n\t\t\taction: 2, \n\t\t\tcolor: \"red\", \n\t\t\tx: player_obj.data.x+wep.hitbox[player_obj.data.dir][wep.atkIndex].x+wep.hitbox[player_obj.data.dir][wep.atkIndex].w, \n\t\t\ty: player_obj.data.y+wep.hitbox[player_obj.data.dir][wep.atkIndex].y+wep.hitbox[player_obj.data.dir][wep.atkIndex].h, \n\t\t\tw: 1, \n\t\t\th: 1\n\t\t});\n\t}\n}", "function renderObject(){\n renderMonster();\n renderHearts();\n}", "function viewItems () {\n\t//location variables for each bin \n\tlet landfillX = 900;\n\tlet landfillY = 160;\n\tlet compostX = 400;\n\tlet compostY = 160;\n\tlet recycleX = 400;\n\tlet recycleY = 450;\n\n\t//bin indexes used for sorting and organizing the layout of the bins. \n\tlet landfillIndex = 0;\n\tlet recycleIndex = 0;\n\tlet compostIndex = 0;\n\n\tfor ( let i = 0; i < itemLocations.length; i++ ) {\n\t\tif (itemLocations[i] === \"Landfill\") {\n\t\t\tif (landfillIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY + (landfillIndex * 18));\n\t\t\t}\n\t\t\tlandfillIndex = landfillIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Recycle\") {\n\t\t\tif (recycleIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY + (recycleIndex * 18));\n\t\t\t}\n\t\t\trecycleIndex = recycleIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Compost\") {\n\t\t\tif (compostIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY + (compostIndex * 18));\n\t\t\t}\n\t\t\tcompostIndex = compostIndex +1;\n\t\t}\n\t}\n}", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function Renderable() {\n\tthis.mPos = new Vec2(0, 0);\n\tthis.mSize = new Vec2(0, 0);\n\tthis.mOrigin = new Vec2(0, 0);\n\tthis.mAbsolute = false;\n\t\n\tthis.mDepth = 0;\n\t\n\tthis.mTransformation = new Matrix3();\n\tthis.mScale = new Vec2(1.0, 1.0);\n\tthis.mRotation = 0;\n\tthis.mSkew = new Vec2();\n\tthis.mAlpha = 1.0;\n\tthis.mCompositeOp = \"source-over\";\n\t\n\tthis.mLocalBoundingBox = new Polygon(); // the local bounding box is in object coordinates (no transformations applied)\n\tthis.mGlobalBoundingBox = new Polygon(); // the global bounding box is in world coordinates (transformations applied)\n\t\n\tthis.mLocalMask = new Polygon();\n\tthis.mGlobalMask = new Polygon();\n}", "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "function drawSelected() {\n\tif (itemSelectedByPlayer == selectionPerson.itemf) {\n\t\tctx.drawImage(selectionPerson.itemf, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.hat) {\n\t\tctx.drawImage(selectionPerson.hat, canvas.width / 100 * 45, canvas.height/20 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shirt) {\n\t\tctx.drawImage(selectionPerson.shirt, canvas.width / 100 * 45, -canvas.height/30 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.pants) {\n\t\tctx.drawImage(selectionPerson.pants, canvas.width / 100 * 45, -canvas.height/10 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shoes) {\n\t\tctx.drawImage(selectionPerson.shoes, canvas.width / 100 * 45, -canvas.height/6 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.itemb) {\n\t\tctx.drawImage(selectionPerson.itemb, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\t\n//\tselectArray[0].draw();\n}", "function drawable(inputCreature, inputHTMLBody){\n\n\tif(!inputCreature) { console.log(\"need to input a creature to make drawable\"); return \t} \n\tconsole.log(\" adding drawing ability to creature\");\n\n\tvar my = inputCreature.properties;\n\tvar body = my.body;\n\tvar me = inputCreature;\n\n\tmy.body = {}; // add a body\n\tmy.drawable = true;\n\t\n\t// default body parameters\n\t// my.body.x = 200 ; // upper left\n\t// my.body.y = 200;\n\t// my.body.w = 200 ;\n\t// my.body.h = 200 ;\n\tmy.x = 200 ; // upper left\n\tmy.y = 200;\n\tmy.w = 200 ;\n\tmy.h = 200 ;\n\n\tvar x = my.x ; \n\tvar y = my.y ;\n\tvar w = my.w ;\n\tvar h = my.h ;\n\n\t// The creatures body is an object that can be used to generate an HTML element\n\t// all creatures have rectangle as a body\n\t// var testRect = new Rect(x+20,y+20,20,20,\"black\");\n\t// my.body = new Rect(x,y,w,h); \n\t// my.body = drawRect(my.body , my.name + \"Body\" + my.birthday); // defaultRect\n\t\n\t// The creatures body is an HTML div element - as a bounding box\n\tmy.body = rect( x,y,w,h, \"lightBlue\");\n\tmy.body.id = my.name + \"Body\" + my.birthday.getTime();\n\n\t//js\n\t//body is an html string we pass in \n\tvar testHTML = \"<div> what what </div>\";\n\n\t// If there was an innerHTML string to attach draw it\n\tif(inputHTMLBody){\n\t\tmy.body.innerHTML = inputHTMLBody;\n\t}\n\n\t// test drawing eye elements directly\n\tvar leftEye =rect( 20,20, 40, 40, \"green\");\n\tleftEye.id = my.name+\"leftEye\";\n\tvar rightEye =rect( 200-60, 20, 40, 40, \"red\");\n\trightEye.id = my.name+\"rightEye\";\n\n\t// var torso = rect( -20, 200, 200+40, 150, \"lightBlue\");\n\t// my.body.appendChild (torso);\n\tmy.body.appendChild (leftEye);\n\tmy.body.appendChild (rightEye);\n\t\n\t\n\tmy.body.classList.add('creatureContainer')\n\n\t// Drawing action - just draws the current body\n\tinputCreature.actions.draw = function(){\n\n\t\t// Draw creature's body element\n\t\t// watch(my, \"x\", function(){console.log(\"wwwww\");})\n\n\t\t// Check for updated properties for the creature model\n\n\t\t// make sure a container body is appended i.e. draw\n\t\tif(!document.getElementById(my.body.id)){ \n\t\t\tdocument.body.appendChild(my.body);\n\t\t}\t\n\n\t\tsetX( my.x, my.body);\n\t\tsetY( my.y, my.body);\n\t\tsetW( my.w, my.body);\n\t\tsetH( my.h, my.body);\n\t\t\n\n\t\t// var drawElem = drawRect(my.body , my.name + \"Body\" + my.birthday); // defaultRect\t\n\t}\n}", "function renderAll()\n\t {\n\t \t// Sorting filters arrays.\n\t \tsortFilterArrays();\n\n\t \t// Rendering filters\n\t \trenderFilters();\n\n\t\t// Rendering publications\n\t\trenderPublications();\n\t}", "draw(gameObjects) {\r\n this.ctx.clearRect(0, 0, Helper.FieldSize.WIDTH, Helper.FieldSize.HEIGHT);\r\n for (let i = 0; i < gameObjects.length; i++) {\r\n gameObjects[i].draw(this.ctx);\r\n }\r\n }", "onRender() {\n const users = this.users.length === 1 ? this.users : this.users.filter(user => !user.isMine);\n // Clear the innerHTML if we have rendered something before\n if (this.users.length) {\n this.innerHTML = '';\n }\n\n // Render each user\n this.properties.firstUserIsAnonymous = false;\n if (users.length === 1) {\n this._renderUser(users[0]);\n } else {\n this._sortMultiAvatars().forEach(this._renderUser.bind(this));\n }\n\n // Add the \"cluster\" css if rendering multiple users\n // No classList.toggle due to poor IE11 support\n this.toggleClass('layer-avatar-cluster', users.length > 1 && !this.properties.firstUserIsAnonymous);\n if (users.length === 1 && this.showPresence && Client.isPresenceEnabled) {\n this.createElement('layer-presence', {\n size: this.size === 'larger' ? 'large' : this.size,\n item: users[0],\n name: 'presence',\n parentNode: this,\n classList: ['layer-presence-within-avatar'],\n });\n }\n }", "#runDrawCallbacks() {\n let dont_clear = false;\n if (this.#clear) { this.#context.clearRect(0, 0, this.#canvas.width, this.#canvas.height); }\n this.#context.translate(0.5, 0.5);\n this.#drawables.forEach(drawable => {\n dont_clear = drawable.draw(this.#context, this.#canvas.width, this.#canvas.height, this.#canvas, this.#clear) || dont_clear;\n });\n this.#context.translate(-0.5, -0.5);\n this.#clear = !dont_clear;\n }", "function lvCockpitsItemInvoked(e) {\n e.detail.itemPromise.done(function (item) {\n DataExplorer.drawTile(item.data);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RUTG[] Round Up To Grid 0x7C
function RUTG(state) { if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); } state.round = roundUpToGrid; }
[ "function roundToGrid(numb) {\n\treturn Math.round(numb/10) * 10;\n}", "function rgbToSix(r) {\n return r / 51;\n}", "moveUp() {\r\n let tempGrid = [];\r\n for (let i = 0; i < this.gridSize; i++) {\r\n let tempIx = 0;\r\n let tempList = [];\r\n for (let j = 0; j < this.gridSize; j++) {\r\n tempList.push(this.board[tempIx][i]);\r\n tempIx += 1;\r\n }\r\n let tempListMerged = this.reduceRow(tempList);\r\n tempGrid.push(tempListMerged);\r\n }\r\n\r\n for (let i = 0; i < this.gridSize; i++) {\r\n for (let j = 0; j < this.gridSize; j++) {\r\n this.board[i][j] = tempGrid[j][i];\r\n }\r\n }\r\n this.afterMove();\r\n }", "function sixToRgb(s) {\n return s * 51;\n}", "function snail(grid) {\n\tif (grid.length == 1) {\n\t\treturn grid[0][0] ? [grid[0][0]] : [];\n\t}\n\n\tlet snail = [];\n\tlet l = grid.length;\n\tlet [startR, startC] = [0, 0];\n\tlet [r, c] = [0, 0];\n\n\twhile (grid[r][c] !== null) {\n\t\tsnail.push(grid[r][c]);\n\t\tlet i;\n\t\t// right\n\t\t// we dont want to push the first value since it coinsides with the previous serial\n\t\ti = c + 1;\n\t\tfor (i; i < l - startC; i++) {\n\t\t\tif (grid[r][i] == null) {\n\t\t\t\t// complete\n\t\t\t\treturn snail;\n\t\t\t}\n\t\t\tlog(\"lol\");\n\t\t\tsnail.push(grid[r][i]);\n\t\t\tgrid[r][i] = null;\n\t\t}\n\t\tc = i - 1;\n\t\t// down\n\n\t\ti = r + 1;\n\t\tfor (i; i < l - startR; i++) {\n\t\t\tif (grid[i][c] == null) {\n\t\t\t\treturn snail;\n\t\t\t}\n\t\t\tlog(\"lol\");\n\t\t\tsnail.push(grid[i][c]);\n\t\t\tgrid[i][c] = null;\n\t\t}\n\t\tr = i - 1;\n\t\t// left\n\t\t// we dont want to push the first value since it coinsides with the previous serial\n\t\ti = c - 1;\n\t\tfor (i; i > -1 + startC; i--) {\n\t\t\tif (grid[r][i] == null) {\n\t\t\t\t// complete {\n\t\t\t\treturn snail;\n\t\t\t}\n\t\t\tsnail.push(grid[r][i]);\n\t\t\tgrid[r][i] = null;\n\t\t}\n\n\t\tc = i + 1; // to turn -1 to 0;\n\t\t// up\n\t\ti = r - 1;\n\t\tlog({ i, startR, c });\n\t\tfor (i; i > startR; i--) {\n\t\t\tif (grid[i][c] == null) {\n\t\t\t\t// complete\n\t\t\t\tlog(\"lolUP\");\n\t\t\t\treturn snail;\n\t\t\t}\n\t\t\tif (i === startR && c == startC) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsnail.push(grid[i][c]);\n\t\t\tgrid[i][c] = null;\n\t\t}\n\t\tlog(\"sadjsa\");\n\t\tlog(snail);\n\n\t\tr = i + 1;\n\t\t[startR, startC] = [startR + 1, startC + 1];\n\t\t[r, c] = [startR, startC];\n\t}\n\treturn snail;\n}", "getSurroundingTiles(x, y, data) {\n\n const tile = []; \n \n //up\n if (x > 0) {\n tile.push(data[x - 1][y]);\n } \n //down\n if (x < boardSize - 1) {\n tile.push(data[x + 1][y]);\n } \n //left\n if (y > 0) {\n tile.push(data[x][y - 1]);\n } \n //right\n if (y < boardSize - 1) {\n tile.push(data[x][y + 1]);\n } \n // top left\n if (x > 0 && y > 0) {\n tile.push(data[x - 1][y - 1]);\n } \n // top right\n if (x > 0 && y < boardSize - 1) {\n tile.push(data[x - 1][y + 1]);\n } \n // bottom right\n if (x < boardSize - 1 && y < boardSize - 1) {\n tile.push(data[x + 1][y + 1]);\n } \n // bottom left\n if (x < boardSize - 1 && y > 0) {\n tile.push(data[x + 1][y - 1]);\n } \n \n return tile;\n }", "get gridResolutionZ() {}", "function roundUp(n, up)\n{\n if (n % up == 0)\n return(n);\n else\n return(n + (up - (n % up)));\n}", "function buildDown() {\n\tvar curRow = PascalRow.row; // The current row being worked on\n\n\twhile (curRow.length > 1) {\n\t\tvar nextRow = new Array(curRow.length - 1);\n\t\tfor (var i = 0; i < nextRow.length; i++) {\n\t\t\tnextRow[i] = curRow[i] + curRow[i+1];\n\t\t}\n\t\tcurRow = nextRow;\n\t}\n\t\n\treturn curRow;\n}", "function levelFourGridBox6(j) {\n let box6 = 18;\n let across = 2;\n let nextLine = 12;\n if (\n (j > box6 && j < box6 + across) ||\n (j > box6 + nextLine && j < box6 + nextLine + across)\n ) {\n return true;\n } else {\n return false;\n }\n}", "function checkGrid(rover) {\r\n\tif ( \trover.position[0] < 0 || rover.position[0] > 9 ) {\r\n if (rover.position[0] < 0) {\r\n myRover.position[0]++;\r\n }\r\n if (rover.position[0] > 9) {\r\n myRover.position[0]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse if (rover.position[1] < 0 || rover.position[1] > 9) {\r\n if (rover.position[1] < 0) {\r\n myRover.position[1]++;\r\n }\r\n if (rover.position[1] > 9) {\r\n myRover.position[1]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse {\r\n\t\treturn false;\r\n\t}\r\n}", "rwuToGrid (rwu, axis) {\n let scale;\n if (axis === 'x') {\n scale = this.xScale;\n } else if (axis === 'y') {\n scale = this.yScale;\n }\n return scale(rwu);\n }", "gridCellSize() {\n return (gridCellSizePercent * canvasWidth) / 100;\n }", "function drawBoard(size) {\r\n if (size <= 1) {\r\n alert(\"Specified grid size MUST >= 2!\");\r\n return;\r\n }\r\n \r\n var startx = GAP_SIZE;\r\n var starty = GAP_SIZE;\r\n\r\n for (var row = 0; row < size; ++row) {\r\n for (var col = 0; col < size; ++col) {\r\n drawLine(startx, starty + UNIT_SIZE*row, startx + UNIT_SIZE*(size-1), starty + UNIT_SIZE*row);\r\n drawLine(startx + UNIT_SIZE*col, starty, startx + UNIT_SIZE*col, starty + UNIT_SIZE*(size-1));\r\n }\r\n }\r\n for (var row = 0; row < size; ++row) {\r\n var patch = 0;\r\n if (row >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(row, GAP_SIZE/8*3-patch, GAP_SIZE/7*8+UNIT_SIZE*row);\r\n }\r\n for (var col = 0; col < size; ++col) {\r\n var patch = 0;\r\n if (col >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(col, GAP_SIZE/8*7+UNIT_SIZE*col-patch, GAP_SIZE/3*2);\r\n }\r\n \r\n // mark the center an key positions\r\n var radius = STONE_RADIUS/3;\r\n var color = \"black\";\r\n drawCircle(getCanvasPos(board.getPosition((GRID_SIZE-1)/2, (GRID_SIZE-1)/2)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, GRID_SIZE-WIN_SIZE)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, GRID_SIZE-WIN_SIZE)), radius, color);\r\n}", "function drawGrid(){\r\n\t\r\n\tfor (var i = 0; i < grid.length; i++){\r\n\t\tfor (var j = 0; j < grid[i].length; j++){\r\n\t\t\t//Set the color to the cell's color\r\n\t\t\tctx.fillStyle = grid[i][j].color;\r\n\t\t\t//Offset each reactangle so that they are drawn in a grid\r\n\t\t\tctx.fillRect(10*i, 10*j, grid[i][j].len, grid[i][j].len);\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n}", "function getGridUvs(row, column, totalRows, totalColumns) {\n var columnWidth = 1 / totalColumns;\n var rowHeight = 1 / totalRows;\n\n // create a Map called `uvs` to hold the 4 UV pairs\n uvs[0].set(columnWidth * column, rowHeight * row + rowHeight);\n uvs[1].set(columnWidth * column, rowHeight * row);\n uvs[2].set(columnWidth * column + columnWidth, rowHeight * row);\n uvs[3].set(columnWidth * column + columnWidth, rowHeight * row + rowHeight);\n return uvs;\n}", "moveRight() {\r\n let tempGrid = [];\r\n for (let i = 0; i < this.gridSize; i++) {\r\n let tempIx = this.gridSize - 1;\r\n let tempList = [];\r\n for (let j = 0; j < this.gridSize; j++) {\r\n tempList.push(this.board[i][tempIx]);\r\n tempIx -= 1;\r\n }\r\n let tempListMerged = this.reduceRow(tempList);\r\n tempGrid.push(tempListMerged);\r\n }\r\n\r\n for (let i = 0; i < this.gridSize; i++) {\r\n for (let j = 0; j < this.gridSize; j++) {\r\n this.board[i][j] = tempGrid[i][this.gridSize - 1 - j];\r\n }\r\n }\r\n this.afterMove();\r\n }", "function resetRow(row){\n var currentRow=gridRows[row];\n var prevNumbers=[new Array(), new Array(), new Array()];\n for(i=0;i<9;i++){\n var currentColumn=gridColumns[i];\n var currentSquareIndex=Math.floor(row/3)*3+1+Math.floor(i/3);\n var currentSquare=grid[currentSquareIndex-1];\n currentColumn[row]=0;\n gridColumns[i]=currentColumn;\n //When generating the game, the follow line occasionally generates the error:\n // Uncaught TypeError: Cannot set property '0' of undefined\n currentRow[i]=0;\n var currentPrevNumbers=prevNumbers[Math.floor(i/3)];\n currentPrevNumbers[i%3]=currentSquare[(row%3)*3+i%3];\n prevNumbers[Math.floor(i/3)]=currentPrevNumbers;\n currentSquare[(row%3)*3+i%3]=0;\n grid[currentSquareIndex-1]=currentSquare;\n }\n for(i=0;i<3;i++)\n {\n ii=i;\n refillSetForSquareAtRow(row, i);\n i=ii;\n }\n gridRows[row]=currentRow;\n}", "function drawChessboard(rows, columns) {\n return 28\n}", "function getNormalizedViewbox(index, rows, columns) {\n const viewWidth = 1.0 / columns;\n const viewHeight = 1.0 / rows;\n\n const gridX = index % columns;\n let gridY = (index - gridX) / columns;\n gridY = (rows - 1) - gridY; // Reverse\n\n return [gridX*viewWidth, gridY*viewHeight, viewWidth, viewHeight];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: showStatusMsg Parameters: msg: String containing message to show Returns: None.
function showStatusMsg(msg) { Ext.get('status-msg').update(msg); //Ext.get('status-msg').slideIn(); }
[ "function status(msg) {\n if (_common_platform_js__WEBPACK_IMPORTED_MODULE_2__[\"isMacintosh\"]) {\n alert(msg); // VoiceOver does not seem to support status role\n }\n else {\n insertMessage(statusContainer, msg);\n }\n}", "function BAStatusMsg() {\n\t/** element node not needed.\n\t @type BAElement @private */\n\tthis.node = window.defaultStatus || '';\n\t/** default message of window.status.\n\t @type String @private */\n\tthis.msg = '';\n\t/** default message of window.status.\n\t @type String @private */\n\tthis.defaultMsg = '';\n\t/** time for delaying (ms).\n\t @type Number @private */\n\tthis.delay = 0;\n\t/** time for sustaining (ms).\n\t @type Number @private */\n\tthis.sustain = 0;\n\t/** store point of delay timeout timer.\n\t @type BASetTimeout @private */\n\tthis.delayTimer = null;\n\t/** store point of sustain timeout timer.\n\t @type BASetTimeout @private */\n\tthis.sustainTimer = null;\n}", "function getStatusMessage(status, jsStatus, cssStatus, jqStatus) {\n\tvar ok = dw.loadString(\"Commands/jQM/files/alert/OK\");\n\tvar message = \"\";\n\t\n\tif (jsStatus != ok || cssStatus != ok || jqStatus != ok) {\n\t\tvar jsStr = dw.loadString(\"Commands/jQM/files/jqmJS\");\n\t\tvar cssStr = dw.loadString(\"Commands/jQM/files/jqmCSS\");\n\t\tvar jqStr = dw.loadString(\"Commands/jQM/files/jquery\");\n\t\t\n\t\tvar jsSpacing = \" : \";\n\t\tvar cssSpacing = \" \";\n\t\tvar jqSpacing = \" \";\n\t\t\n\t\t//Tab spacing differs between Mac and Win for alignment\n\t\tif (dwscripts.IS_WIN) {\n\t\t\tcssSpacing += \" \";\n\t\t\tjqSpacing += \" \";\n\t\t}\n\t\t\n\t\tvar colonSpace = \": \";\n\t\tcssSpacing += colonSpace;\n\t\tjqSpacing += colonSpace;\n\t\t\n\t\t//Trim only if it's a file name.\n\t\tif (jsStatus.indexOf(\".js\") != -1) {\n\t\t\tjsStatus = trimFile(jsStatus);\n\t\t\tcssStatus = trimFile(cssStatus);\n\t\t\tjqStatus = trimFile(jqStatus);\n\t\t}\n\t\t\n\t\tjsStr += jsSpacing + jsStatus + \"\\n\";\n\t\tcssStr += cssSpacing + cssStatus + \"\\n\";\n\t\tjqStr += jqSpacing + jqStatus + \"\\n\\n\";\n\t\t\n\t\tmessage = jsStr + cssStr + jqStr;\n\t\t\n\t\tvar msgHead;\n\t\tif (status == \"success\") {\n\t\t\tmsgHead = dw.loadString(\"Commands/jQM/files/alert/fileSuccess\");\n\t\t} else {\n\t\t\tmsgHead = dw.loadString(\"Commands/jQM/files/alert/fileProblem\");\n\t\t}\n\t\tmsgHead += \":\\n\\n\";\n\t\tmessage = msgHead + message;\n\t}\n\t\n\treturn message;\n}", "function codemirrorSetStatus(statusMsg, type, customMsg) {\n switch (type) {\n case \"expected\":\n case \"ok\":\n ok(1, statusMsg);\n break;\n case \"error\":\n case \"fail\":\n ok(0, statusMsg);\n break;\n default:\n info(statusMsg);\n break;\n }\n\n if (customMsg && typeof customMsg == \"string\" && customMsg != statusMsg) {\n info(customMsg);\n }\n}", "function update_display_msg(msg) {\n\tupdate_Display(msg, 0);\n}", "showWarningMessage(msg) {\n return vscode.window.showWarningMessage(Constants.extensionDisplayName + ': ' + msg);\n }", "function SetStatus(strmessage)\n{\n window.status = strmessage;\n}", "function showok(message){\n\t$.messager.show({\n\t\ttitle:'消息',\n\t\tmsg:message == null ? '操作成功!' : message,\n\t\tshowType:'show',\n\t\ttimeout:3000,\n\t\tstyle:{\n\t\t\tright:'',\n\t\t\ttop:document.body.scrollTop + document.documentElement.scrollTop,\n\t\t\tbottom:''\n\t\t}\n\t});\n}", "status(title, status) {\n const statusString = status === false ? symbols.error : symbols.success;\n console.log(Log.fill(`\n [${chalk.yellow(title)}] [FILL] [${statusString}]\n `));\n }", "function setStatus(info, cssClass) {\r\n\tif (!info || info.length == 0) {\r\n\t\t$(\"#status\").hide();\r\n\t}\r\n\telse {\r\n\t\tif (typeof(cssClass) == \"undefined\") {\r\n\t\t\tcssClass = STATUS_SUCCESS;\r\n\t\t}\r\n\t\t$(\"#status\").show().removeClass().addClass(cssClass).text(info);\r\n\t}\r\n}", "function rtwDisplayMessage() {\n var docObj = top.rtwreport_document_frame.document;\n var msg = docObj.getElementById(RTW_TraceArgs.instance.fMessage);\n if (!msg) {\n msg = docObj.getElementById(\"rtwMsg_notTraceable\");\n }\n if (msg && msg.style) {\n msg.style.display = \"block\"; // make message visible\n var msgstr = msg.innerHTML;\n if (RTW_TraceArgs.instance.fBlock) {\n // replace '%s' in message with block name\n msgstr = msgstr.replace(\"%s\",RTW_TraceArgs.instance.fBlock);\n }\n msg.innerHTML = msgstr;\n }\n}", "function myWarning( _msg )\n{\n\tif( _msg.length != 0 )\n\t{\n\t\t$('#alert-warnings').html('<div style=\"margin-top: 6px; margin-bottom: 0px;\" class=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button><strong>Warning!</strong> ' + _msg + '</div>' )\n\t\t$('#alert-warnings').css('display','block')\n\t\t$('#divider-warnings').css('display','block')\n\t}\n\telse\n\t{\n\t\t$('#alert-warnings').css('display','none')\n\t\t$('#divider-warnings').css('display','none')\n\t}\n}", "function displayHelpMsg(msg) {\n\tExt.getCmp('helpIframe').el.update(msg);\n}", "function show_message(page, process_name) {\n // Save info of the opened tab\n msg_or_job = 'Msg';\n ProcessMsgUpdate(page, process_name, true);\n}", "showMessage(type,title,message){\n\t\tsetTimeout(function() {\n\t\t\tvar html = message;\n\t\t\t\t\t\tif(type == \"error\"){\n\t\t\t\t\t\t\tvar html = '<span style=\"color:#ef5350;\">'+message+'</span>'\n\t\t\t\t\t\t}\n\t\t\t\t\t\tM.toast({html: html})\n }, 1000);\n\t}", "function statusStr(obj, online) {\n\tvar myStatStr;\n\n if (!online) {\n myStatStr = 'offline';\n\t\t$(obj).css('color', '#939393');\n } else {\n myStatStr = '<span class=\"sts-online\">online</span>';\n\t\t$(obj).css('color', 'green');\n }\n\treturn myStatStr;\n}\t// statusStr", "function showLoading(message) {\n var msg = message || 'Working...';\n updateDisplay('<em>' + msg + '</em>');\n}", "showInformationMessage(msg, ...items) {\n return vscode.window.showInformationMessage(Constants.extensionDisplayName + ': ' + msg, ...items);\n }", "function printDevMessage(msg, args) {\n\t// Check if developer mode is on\n\tif(dev) {\n\t\t// Print the message\n\t\tserver.print(util.format(msg, args));\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
offer recieved get pc1 stuff handle offer
function handleofferFromPC1(){ var x = document.getElementById('pc1LocalOffer').value; var offerDesc = new RTCSessionDescription(JSON.parse(x)) pc2.setRemoteDescription(offerDesc) pc2.createAnswer(function (answerDesc) { console.log('Created local answer: ', answerDesc) pc2.setLocalDescription(answerDesc) }, function () { console.warn("Couldn't create offer") }, sdpConstraints) }
[ "receiveOffer(pair, desc) {\n var e, offer, sdp;\n try {\n offer = JSON.parse(desc);\n dbg('Received:\\n\\n' + offer.sdp + '\\n');\n sdp = new RTCSessionDescription(offer);\n if (pair.receiveWebRTCOffer(sdp)) {\n this.sendAnswer(pair);\n return true;\n } else {\n return false;\n }\n } catch (error) {\n e = error;\n log('ERROR: Unable to receive Offer: ' + e);\n return false;\n }\n }", "function sendData() {\n\n // Get all PID input data and store to right index of charVal\n for(var i = 1; i <= 18; i++) {\n txCharVal[i] = select(inputMap[i]).value;\n }\n\n // Get all control input data and store to right index of exCharVal\n exCharVal[0] = select('#throttle').value;\n\n // Sending PID data with rxChar over BLE\n writeArrayToChar(txChar, txCharVal)\n .then( () => {\n console.log(\"PID data sent:\", txCharVal);\n\n // Sending throttle data with exChar over BLE\n writeArrayToChar(exChar, exCharVal)\n .then( () => {\n console.log(\"Data sent:\", exCharVal);\n })\n .catch( (error) => {\n console.log('Control data sending failed:', error)\n });\n })\n .catch( (error) => {\n console.log('PID data sending failed:', error)\n });\n}", "async listen() {\n const contract = await this.getContract();\n contract.on('Claimed', async (vendor, phone, amount) => {\n try {\n const otp = Math.floor(1000 + Math.random() * 9000);\n const data = await this.setHashToChain(contract, vendor, phone.toString(), otp.toString());\n\n const message = `A vendor is requesting ${amount} token from your account. If you agree, please provide this OTP to vendor: ${otp}`;\n // eslint-disable-next-line global-require\n const sms = require(`./plugins/sms/${config.get('plugins.sms.service')}`);\n\n // call SMS function from plugins to send SMS to beneficiary\n sms(phone.toString(), message);\n } catch (e) {\n console.log(e);\n }\n });\n console.log('--- Listening to Blockchain Events ----');\n }", "function sendOffer(offers) {\n assert(offers.length > 0);\n // construct content that contains all offers given by the media plugin\n function createOfferOptions(context) {\n var boundary = '9BCE36B8-2C70-44CA-AAA6-D3D332ADBD3F', mediaOffer, options = { nobatch: true };\n if (isConferencing()) {\n if (escalateAudioVideoUri) {\n mediaOffer = Internal.multipartSDP(offers, boundary);\n options = {\n headers: {\n 'Content-Type': 'multipart/alternative;boundary=' + boundary +\n ';type=\"application/sdp\"',\n 'Content-Length': '' + mediaOffer.length\n },\n query: {\n operationId: operationId,\n sessionContext: sessionContext\n },\n data: mediaOffer,\n nobatch: true\n };\n }\n else {\n options.data = Internal.multipartJsonAndSDP({\n offers: offers,\n boundary: boundary,\n operationId: operationId,\n sessionContext: sessionContext,\n threadId: threadId,\n context: context\n });\n options.headers = {\n 'Content-Type': 'multipart/related;boundary=' + boundary +\n ';type=\"application/vnd.microsoft.com.ucwa+json\"'\n };\n }\n }\n else {\n // P2P mode\n options.data = Internal.multipartJsonAndSDP({\n to: remoteUri,\n offers: offers,\n boundary: boundary,\n operationId: operationId,\n sessionContext: sessionContext,\n threadId: threadId,\n context: context\n });\n options.headers = {\n 'Content-Type': 'multipart/related;boundary=' + boundary +\n ';type=\"application/vnd.microsoft.com.ucwa+json\"'\n };\n }\n if (context)\n extend(options.headers, { 'X-MS-RequiresMinResourceVersion': 2 });\n return options;\n }\n return async(getStartAudioVideoLink).call(null).then(function (link) {\n var options = createOfferOptions(link.revision >= 2 && invitationContext), dfdPost, dfdCompleted;\n dfdPost = ucwa.send('POST', link.href, options).then(function (r) {\n // POST to startAudioVideo/addAudioVideo returns an empty response with an AV invitation\n // URI in the Location header. The UCWA stack constructs and returns an empty resource\n // with href set to that URI.\n if (!rAVInvitation)\n rAVInvitation = r;\n });\n // wait for the \"audioVideoInvitation completed\" event that corresponds to the given conversation\n dfdCompleted = ucwa.wait({\n type: 'completed',\n target: { rel: 'audioVideoInvitation' },\n resource: { direction: 'Outgoing', threadId: threadId, operationId: operationId, sessionContext: sessionContext }\n }).then(function (event) {\n if (event.status == 'Failure') {\n // if remote SIP uri is invalid we won't receive \"audioVideoInvitation started\" event,\n // thus we won't have a full rAVInvitation resource cached. It will be either undefined or\n // just an empty resource with an href returned by a response to startAudioVideo POST (if\n // that response arrived before this event). So we cache the invitation resource here,\n // since it may be used by other event handlers.\n rAVInvitation = event.resource;\n // Technically we may need to complete the negotiation if it was started (i.e. if the call\n // reached the remote party and was declined).\n completeNegotiation(event.status, event.reason);\n throw Internal.EInvitationFailed(event.reason);\n }\n completeNegotiation(event.status, event.reason);\n });\n return Task.waitAll([dfdPost, dfdCompleted]);\n });\n }", "function makeCall() {\n callButton.disabled = true;\n hangupButton.disabled = false;\n var servers = null;\n localConnection = new RTCPeerConnection(servers);\n localConnection.onicecandidate = localCandidate;\n \n remoteConnection = new RTCPeerConnection(servers);\n remoteConnection.onicecandidate = remoteCandidate;\n \n remoteConnection.onaddstream = remoteStream;\n \n localConnection.addStream(localStream);\n \n localConnection.createOffer(localDescription, signalError);\n}", "restForBeatsEach(args){\n if(this._peripheral.AllConnected == false)\n return;\n if (this.inActionC1C2C3 == true)\n return;\n\n this.inActionC1C2C3 = true;\n\n beatsEach = this._clampBeats(args.BEATS); \n durationSecEach = this._beatsToDuration(args, beatsEach); \n \n TimeDelay = (durationSecEach * 10) + 30;\n \n return new Promise(resolve => {\n var repeat = setInterval(() => {\n this.inActionC1C2C3 = false;\n clearInterval(repeat);\n resolve();\n }, TimeDelay);\n });\n }", "function onP2PstreamRequest(evt) { \n util.trace('DataChannel opened');\n var chan = evt.channel;\n chan.binaryType = 'arraybuffer';\n var trackWanted = chan.label;\n var cancellable;\n\n chan.onmessage = apply(function(evt) {\n util.trace('Receiving P2P stream request');\n var req = JSON.parse(evt.data);\n if (cancellable) {\n // cancelling previous sending\n clearInterval(cancellable);\n } else {\n S.nbCurrentLeechers += 1;\n }\n var chunkI = req.from;\n\n function sendProgressively() {\n // goal rate: 75 kb/s\n for(var i = 0; chunkI < S.track.length && i < 150; i++) {\n var chunkNum = new Uint32Array(1);\n chunkNum[0] = chunkI;\n var chunkNumInt8 = new Uint8Array(chunkNum.buffer);\n var chunk = util.UInt8concat(chunkNumInt8, new Uint8Array(S.track[chunkI])).buffer;\n var b64encoded = base64.encode(chunk);\n chan.send(b64encoded);\n chunkI++;\n }\n if (chunkI >= S.track.length) {\n clearInterval(cancellable);\n cancellable = null;\n S.nbCurrentLeechers -= 1;\n }\n }\n sendProgressively();\n cancellable = setInterval(apply(sendProgressively), 1000);\n });\n\n chan.onclose = apply(function() {\n util.trace('datachannel closed');\n S.nbCurrentLeechers -= 1;\n });\n\n }", "tellClientswhoIsNext(){\n var next = this.network.getNext();\n if(next === null){\n return;\n }\n var receiver = next.receiver;\n var transmitter = next.transmitter;\n\n var player = this.getPlayer(receiver);\n\n console.log(\"Player Position: \", player.position+1, player.hintList.length);\n\n\n var _nextDict = this.getDictAtPosition(player, player.position+1);\n if(_nextDict != null && (player.position+1 < player.hintList.length)){\n //console.log(\"_ne\", player, player.position+1, _nextDict[0],_nextDict);\n\n var tplayer = this.getPlayer(transmitter);\n this.db.saveLog(new LogPlayerShouldSay(\n this.pId,\n this.condition.conditionId,\n this.condition.condition,\n this.currentLevel,\n tplayer.name,\n receiver,\n _nextDict[0],\n this.getHintName(this.currentLevel, receiver, player.position+1)\n ));\n\n\n this.communicator.serverWhoIsNext(transmitter, receiver, _nextDict[0],_nextDict);\n //If it's the player2's turn, the robot will automatically say the word\n if(tplayer.type == \"robot\" ){\n console.log(\"time for robot to say who is next\");\n setTimeout(function() {\n this.naoComm.start();\n if(tplayer.talk.lookUpDown){\n this.naoComm.lookUp(true);\n }\n this.naoComm.say(tplayer.talk.goTo.replace(\"?word?\", _nextDict[0]));\n this.naoComm.finish().send();\n //this.naoComm.say(tplayer.talk.goTo.replace(\"?word?\", _nextDict[0]));\n //this.tellClientswhoIsNext();\n //clientMultiParticipantSaid(transmitter, receiver, correctness, answer, dictionary)\n }.bind(this), 300);\n }\n console.log(\"next: \", transmitter, receiver);\n\n\n }else{\n this.communicator.serverGameOver();\n console.log(\"game is over\", player.position+1);\n }\n }", "function sendNextProblemInputResponse (arg) {\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector + arg,\n processNextProblemResult)\n}", "function pingFromPlant(){\n\n}", "browse () {\n if (!this.configs.brokerURL) return\n this.mqtt.on('message', (topic, message) => {\n if (topic === MQTTSD_QUERY_TOPIC) {\n const data = JSON.parse(message.toString())\n\n if (data && data.queryId !== this.mqtt.options.clientId) {\n // Received a query message from server, do publish() for ack\n clearTimeout(this.responseQueryTimer)\n this.responseQueryTimer = setTimeout(() => {\n this.publish()\n }, MQTTSD_QUERY_RESPONSE_DELAY)\n }\n } else if (this.configs.browse && topic === MQTTSD_TOPIC) {\n const service = JSON.parse(message.toString())\n const addr = service.addresses[0]\n\n if (!addr) return\n\n service.timestamp = Date.now()\n\n if (service.status === STATUS_UP) {\n this.serviceMap[addr] = (this.serviceMap[addr] || []).filter(srv => srv.fqdn !== service.fqdn)\n this.serviceMap[addr].push(service)\n this.emit('event', { action: STATUS_UP, data: service })\n } else if (service.status === STATUS_DOWN) {\n this.serviceMap[addr] = (this.serviceMap[addr] || []).filter(srv => srv.fqdn !== service.fqdn)\n this.serviceMap[addr].push(service)\n this.emit('event', { action: STATUS_DOWN, data: service })\n }\n }\n })\n }", "recv_hello (h, info) {\n if (info.address) {\n this.address = info.address\n }\n clearTimeout(this.dropConnectionTimer)\n }", "sendInfo() {\n this.sendPlayers();\n this.sendObjects();\n }", "function call_control_gather_using_speak(f_call_control_id, f_tts_text, f_gather_digits, f_gather_max, f_client_state_s) {\n\n var l_cc_action = 'gather_using_speak';\n var l_client_state_64 = null;\n\n if (f_client_state_s)\n l_client_state_64 = Buffer.from(f_client_state_s).toString('base64');\n\n var options = {\n url: 'https://api.telnyx.com/calls/' +\n f_call_control_id +\n '/actions/' +\n l_cc_action,\n auth: {\n username: f_telnyx_api_key_v1,\n password: f_telnyx_api_secret_v1\n },\n form: {\n payload: f_tts_text,\n voice: g_ivr_voice,\n language: g_ivr_language,\n valid_digits: f_gather_digits,\n max: f_gather_max,\n client_state: l_client_state_64 //if lobby level >> null\n }\n };\n\n request.post(options, function (err, resp, body) {\n if (err) {\n return console.log(err);\n }\n console.log(\"[%s] DEBUG - Command Executed [%s]\", get_timestamp(), l_cc_action);\n console.log(body);\n });\n}", "function onTradeOfferSent (tradeofferid)\n{\n TradeOfferID = tradeofferid;\n\n showModal();\n checkTradeOffer();\n}", "function getCapabilities(){\n// Gets available capabilities and update indexes\n getSupervisorCapabilityes(function(err, caps){\n // Just for the ready message\n var descriptions = [];\n // Update indexes\n _.each(caps, function(capsDN , DN){\n capsDN.forEach(function(cap , index){\n var capability = mplane.from_dict(cap);\n //if (!__availableProbes[DN])\n // __availableProbes[DN] = [];\n capability.DN = DN;\n\n // If source.ip4 param is not present we have no way to know where the probe is with respect of our net\n if (_.indexOf(capability.getParameterNames() , PARAM_PROBE_SOURCE) === -1){\n showTitle(\"The capability has no \"+PARAM_PROBE_SOURCE+\" param\");\n }else{\n descriptions.push(\"(\"+DN+\") \" + capability.get_label() + \" : \" +capability.result_column_names().join(\" , \"));\n var sourceParamenter = capability.getParameter(PARAM_PROBE_SOURCE);\n var ipSourceNet = (new mplane.Constraints(sourceParamenter.getConstraints()['0'])).getParam();\n capability.ipAddr= ipSourceNet;\n // Add to the known capabilities\n var index = (__availableProbes.push(capability))-1;\n var netId = ipBelongsToNetId(ipSourceNet);\n if (netId){\n if (!__IndexProbesByNet[netId])\n __IndexProbesByNet[netId] = [];\n __IndexProbesByNet[netId].push(index);\n }\n var capTypes = capability.result_column_names();\n capTypes.forEach(function(type , i){\n if (!__IndexProbesByType[type])\n __IndexProbesByType[type] = [];\n __IndexProbesByType[type].push(index);\n });\n }\n }); // caps of a DN\n });\n info(descriptions.length+\" capabilities discovered on \"+cli.options.supervisorHost);\n descriptions.forEach(function(desc , index){\n info(\"......... \"+desc);\n });\n\n console.log(\"\\n\");\n console.log();\n cli.info(\"--------------------\");\n cli.info(\"INIT PHASE COMPLETED\");\n cli.info(\"--------------------\");\n console.log();\n\n // Periodically scan all the net\n if (cli.options.mode == \"AUTO\"){\n setInterval(function(){\n scan();\n }\n ,configuration.main.scan_period);\n setInterval(function(){\n // Periodically check if results are ready\n checkStatus();\n }\n ,configuration.main.results_check_period);\n }else{\n waitForTriggers();\n }\n });\n}", "function handle_cm_get_payment_card(req, startTime, apiName, fromSubmittPay) {\n this.req = req;\n this.startTime = startTime;\n this.apiName = apiName;\n this.fromSubmittPay = fromSubmittPay;\n}", "async setup() {\n\n // connect to the bulbs\n try {\n if (this.deviceKind === 'TPLink Bulb') {\n this.tplink = TPClient.getBulb({host: this.ip});\n } else if (this.deviceKind === 'TPLink Plug') {\n this.tplink = TPClient.getPlug({host: this.ip});\n }\n } catch (err) {\n // log the error and return false, signaling that the device was not successfully added\n console.log(err);\n this.unavailable = true;\n this.tplink = null;\n return false;\n }\n\n // another check for failure to add\n if (this.tplink === null)\n return false;\n try {\n this.sysinfo = await this.tplink.getSysInfo()\n .catch( function (err) {\n console.log('found the error');\n console.log(err);\n //this.unavailable = true;\n return false;\n }).finally( (ret) => {\n if (ret === undefined || ret == false) {\n this.unavailable = true;\n return false;\n }\n });\n } catch (err) {\n console.log(err); \n this.sysinfo = null;\n return null;\n }\n \n //if null, device isn't currently connected\n if (this.sysinfo === null)\n return false;\n \n //get device state every 5 seconds\n await this.tplink.startPolling(5000);\n\n this.tplink.on('power-on', () => {\n this.lastState = true;\n this.lastStateString = 'on';\n this.logEvent('power-status', 'on');\n });\n this.tplink.on('power-off', () => {\n this.lastState = false;\n this.lastStateString = 'off';\n this.logEvent('power-status', 'off');\n });\n\n this.mac = this.sysinfo.mac;\n this.tpalias = this.sysinfo.alias;\n this.oemid = this.sysinfo.oemId;\n this.tpmodel = this.sysinfo.model;\n this.tpid = this.sysinfo.deviceId;\n this.tptype = this.sysinfo.type;\n this.hwVersion = this.sysinfo.hw_ver;\n this.swVersion = this.sysinfo.sw_ver;\n this.tpname = this.sysinfo.dev_name;\n this.supportsDimmer = this.sysinfo.brightness != null;\n this.unavailable = false;\n\n return true;\n }", "function start(listen_function,get_info_function,reply_ob) {\n listen_function(function(info) {\n\tvar [from, txt] = get_info_function(info)\n\tfrom_reply_ob[from] = reply_ob\n\tprocess_command(txt,from,reply_ob)\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the graph data to the map
function load_graph_to_map(results){ load_markers(results.locations); //draw_lines(results); draw_spanning_tree(results); }
[ "function loadMapData()\r\n{\r\n\t//First clear the old shapes from the editor\r\n\t//This is important in the event that we're either\r\n\t//loading a new layer or a completely new image map\r\n\tclearEditor();\r\n\tloadLayers();\r\n\t//Load the shapes onto the layer\r\n\tvar mapLayer = getLayerById( imageMap, currentLayer );\r\n\tvar shapes = mapLayer.shapes;\r\n\tloadShapes( shapes );\r\n\tdisplayData();\r\n}", "function worldMap(allData) {\n\n // Creates div for the datamap to reside in\n d3v3.select(\"body\")\n .append(\"div\")\n .attr(\"id\", \"container\")\n .style(\"position\", \"relative\")\n .style(\"width\", \"700px\")\n .style(\"height\", \"450px\")\n .style(\"margin\", \"auto\");\n\n // Gets neccesary info from JSON file\n var data = [];\n for (country in datafile) {\n data.push([datafile[country][\"Country code\"],\n datafile[country][\"Happy Planet Index\"],\n datafile[country][\"GDP/capita ($PPP)\"]]);\n }\n\n // Finds specified values and their minimum and maximum\n var dataset = {};\n var score = data.map(function(obj){ return parseFloat(obj[1]); });\n var minValue = Math.min.apply(null, score);\n var maxValue = Math.max.apply(null, score);\n\n // Adds Colour palette based on minimum and maximum\n var paletteScale = d3v3.scale.linear()\n .domain([minValue,maxValue])\n .range([\"#ece7f2\",\"#2b8cbe\"]);\n\n // Converts dataset to appropriate format\n data.forEach(function(item){\n var country = item[0];\n var happy = item[1];\n var gdp = item[2];\n dataset[country] = { HappyPlanetIndex: happy,\n Gdp: gdp,\n fillColor: paletteScale(happy) };\n });\n\n // Renders map based on dataset\n new Datamap({\n element: document.getElementById(\"container\"),\n projection: \"mercator\",\n fills: { defaultFill: \"#F5F5F5\" },\n data: dataset,\n done: function(data) { data.svg.selectAll(\".datamaps-subunit\")\n .on(\"click\", function(geo) {\n scatterPlot(geo.id, datafile); }\n );\n },\n geographyConfig: {\n borderColor: \"#000000\",\n highlightBorderWidth: 2,\n highlightFillColor: function(geo) { return \"#FEFEFE\"; },\n highlightBorderColor: \"#B7B7B7\",\n popupTemplate: function(geo, data) {\n if (!data) { return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>No data available <strong>\", \"</div>\"].join(\"\"); }\n return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>Happy planet index: <strong>\", data.HappyPlanetIndex,\n \"</strong>\",\n \"<br>Gdp: <strong>\", data.Gdp, \"($PPP)</strong>\",\n \"</div>\"].join(\"\");\n }\n }\n });\n }", "function loadMapShapes() {\n // load US state outline polygons from a GeoJson file\n map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/states.js', {\n idPropertyName: 'STATE'\n });\n\n // wait for the request to complete by listening for the first feature to be\n // added\n google.maps.event.addListenerOnce(map.data, 'addfeature', function() {\n google.maps.event.trigger(document.getElementById('census-variable'),\n 'change');\n });\n}", "onGraphLoaded() {\n this.axis = new CGFaxis(this, this.graph.axis_length);\n\n this.loadAmbient();\n this.loadBackground();\n this.initLights();\n\n // Adds lights group.\n this.interface.addLightsGroup(this.graph.light);\n\n // Adds camera options\n this.interface.addCameraOptions(this.graph.views);\n\n // Adds Game options\n this.interface.addGame(this.graph.game);\n\n this.loadCamera();\n this.sceneInited = true;\n\n this.oldtime = 0;\n this.setUpdatePeriod(10);\n }", "function drawDatamap(){\n\n // create promise for json of gdp-data\n d3v5.json(\"gdp_data_clean.json\").then(function(data) {\n\n // create datamap\n var map = new Datamap({element: document.getElementById('container'),\n fills: {\n '>25000': '#1a9641',\n '15000-25000': '#a6d96a',\n '7500-15000': '#ffffbf',\n '3500-7500': '#fdae61',\n '<3500': '#d7191c',\n defaultFill: 'grey'\n },\n data: data,\n geographyConfig: {\n popupTemplate: function(geography, data) {\n return '<div class=\"hoverinfo\">' + geography.properties.name + '<br />' + 'GDP per capita: ' + data.GDP\n }},\n done: function(datamap) {\n datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {\n country = geography.properties.name;\n\n // create promise for suicide data\n d3v5.json(\"suicidedata.json\").then(function(data) {\n objects_interest_order = getObjectsInterest(data, country)\n // suicide data available\n if (objects_interest_order != 1){\n d3v5.select(\"#graph\").remove()\n drawbar(objects_interest_order);\n }\n // no suicide data avaibale\n else{\n d3v5.select('#graph').remove()\n noDataAvailable();\n }\n });\n });\n }\n });\n // draw legend for datamap\n map.legend({\n legendTitle : \"GDP per capita\",\n defaultFillName: \"No data: \",\n labels: {\n q0: \"one\",\n q1: \"two\",\n q2: \"three\",\n q3: \"four\",\n q4: \"five\",\n },\n });\n });\n}", "onGraphLoaded() {\r\n\r\n this.defaultView = this.graph.defaultView;\r\n this.initViews();\r\n\r\n this.camera = this.cameras[this.defaultView];\r\n this.interface.setActiveCamera(this.camera);\r\n\r\n this.axis = new CGFaxis(this, this.graph.referenceLength);\r\n\r\n this.setGlobalAmbientLight(this.graph.ambientSpecs[0], this.graph.ambientSpecs[1], this.graph.ambientSpecs[2], this.graph.ambientSpecs[3]);\r\n this.gl.clearColor(this.graph.backgroundSpecs[0], this.graph.backgroundSpecs[1], this.graph.backgroundSpecs[2], this.graph.backgroundSpecs[3]);\r\n\r\n this.initLights();\r\n // Adds lights group.\r\n this.interface.addLightsGroup(this.graph.lights);\r\n this.interface.addViewsGroup(this.graph.views);\r\n this.interface.addScenesGroup();\r\n this.interface.addMenu();\r\n\r\n this.sceneInited = true;\r\n }", "reload(newData) {\n this.mapData = newData;\n console.log('New Dataset: ', this.mapData);\n console.log('Reloading the map using a new dataset');\n this.render();\n }", "constructor() {\n this.graph = {};\n }", "function initMap() {\n $('#widgetRealTimeMapliveMap .loadingPiwik, .RealTimeMap .loadingPiwik').hide();\n map.addLayer(currentMap.length == 3 ? 'context' : 'countries', {\n styles: {\n fill: colorTheme[currentTheme].fill,\n stroke: colorTheme[currentTheme].bg,\n 'stroke-width': 0.2\n },\n click: function (d, p, evt) {\n evt.stopPropagation();\n if (currentMap.length == 2){ // zoom to country\n updateMap(d.iso);\n } else if (currentMap != 'world') { // zoom out if zoomed in\n updateMap('world');\n } else { // or zoom to continent view otherwise\n updateMap(UserCountryMap.ISO3toCONT[d.iso]);\n }\n },\n title: function (d) {\n // return the country name for educational purpose\n return d.name;\n }\n });\n if (currentMap.length == 3){\n map.addLayer('regions', {\n styles: {\n stroke: colors['region-stroke-color']\n }\n });\n }\n var lastVisitId = -1,\n lastReport = [];\n refreshVisits(true);\n }", "function importGraph() {\r\n\r\n // Clear current graph\r\n clearGraph();\r\n\r\n var file = $(\"#import-data\")[0].files[0];\r\n\r\n // Use FileReader to read contents of file (https://developer.mozilla.org/en-US/docs/Web/API/FileReader)\r\n var reader = new FileReader();\r\n\r\n reader.onload = (function () {\r\n return function (e) {\r\n\r\n // If uploaded file is a .txt file\r\n if (file.type == \"text/plain\") {\r\n\r\n // Parse data from file to get nodes and links\r\n var graphData = e.target.result.trim().split(/\\s+/); // Remove spaces around and split data into lines\r\n\r\n // Get nodes from data\r\n var graphNodes = [];\r\n\r\n for (var l of graphData) {\r\n\r\n // If line starts with \"{\", data represents link\r\n if (l[0] == \"{\") {\r\n var left = \"\";\r\n var right = \"\";\r\n var i = 1;\r\n\r\n // Get left node ID\r\n while (l[i] != \",\") {\r\n if (i > l.length - 4 || isNaN(l[i])) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n left += l[i++];\r\n }\r\n i++;\r\n\r\n // Get right node ID\r\n while (l[i] != \"}\") {\r\n if (i == l.length - 1 || isNaN(l[i])) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n right += l[i++];\r\n }\r\n\r\n graphNodes.push(left);\r\n graphNodes.push(right);\r\n }\r\n\r\n else if (isNaN(l[0])) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n\r\n }\r\n\r\n // Ensure no duplicates in IDs\r\n nodeIDs = graphNodes.filter(function (n, index) {\r\n return graphNodes.indexOf(n) == index;\r\n }).map(function (n) {\r\n return Number(n);\r\n });\r\n\r\n nodeIDs.sort((a, b) => a - b);\r\n\r\n nodeIDs.forEach(function (n) {\r\n if (selectedAlgorithm == 1)\r\n nodes.push({ id: Number(n), degree: 0 });\r\n else if (selectedAlgorithm == 2)\r\n nodes.push({ id: Number(n), degree: 0, capacity: 1 });\r\n else if (selectedAlgorithm == 3)\r\n nodes.push({ id: Number(n), degree: 0 });\r\n });\r\n\r\n // Set capacities or coordinates\r\n for (var l of graphData) {\r\n\r\n // If line does not start with \"{\", data represents capacity\r\n if (!isNaN(l[0])) {\r\n var id = \"\";\r\n var capacity = \"\";\r\n var x = \"\";\r\n var y = \"\";\r\n var i = 0;\r\n\r\n // Get node ID\r\n while (l[i] != \":\") {\r\n if (i > l.length - 3 || isNaN(l[i])) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n id += l[i++];\r\n }\r\n i++;\r\n\r\n // Get corresponding capacity for bipartite graph matching\r\n if (selectedAlgorithm == 1 || selectedAlgorithm == 2) {\r\n while (i != l.length) {\r\n if (isNaN(l[i])) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n capacity += l[i++];\r\n }\r\n }\r\n\r\n // Get corresponding coordinates for general graph matching\r\n else if (selectedAlgorithm == 3) {\r\n\r\n // If line continues with \"(\", data represents coordinates\r\n if (l[i] == \"(\") {\r\n i++;\r\n\r\n // Get x coordinate\r\n while (l[i] != \",\") {\r\n if (i > l.length - 4) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n x += l[i++];\r\n }\r\n i++;\r\n\r\n // Get y coordinate\r\n while (l[i] != \")\") {\r\n if (i == l.length - 1) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n y += l[i++];\r\n }\r\n }\r\n\r\n // Check for validity of data\r\n if (isNaN(x) || isNaN(y) || Number(x) < 0 || Number(y) < 0 || Number(x) > 100 || Number(y) > 100) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n }\r\n\r\n if (selectedAlgorithm == 2 || selectedAlgorithm == 3) {\r\n var node = nodes.filter(function (n) {\r\n return n.id == Number(id);\r\n })[0];\r\n\r\n // Set capacity or coordinates\r\n if (selectedAlgorithm == 2 && typeof node != \"undefined\")\r\n node.capacity = Number(capacity);\r\n else if (selectedAlgorithm == 3 && typeof node != \"undefined\") {\r\n node.rx = Number(x);\r\n node.ry = Number(y);\r\n }\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n // Create edges based on data provided in file\r\n for (var i = 0; i < graphNodes.length; i += 2) {\r\n var source = nodes.filter(function (n) {\r\n return n.id == graphNodes[i];\r\n })[0];\r\n\r\n source.degree++;\r\n\r\n var target = nodes.filter(function (n) {\r\n return n.id == graphNodes[i + 1];\r\n })[0];\r\n\r\n target.degree++;\r\n\r\n // Only add edge if it does not already exist\r\n if (!links.some(function (l) { return l.source == source && l.target == target; }))\r\n links.push({ source: source, target: target });\r\n }\r\n\r\n }\r\n\r\n // If uploaded file is a .json file\r\n else if (file.type == \"application/json\") {\r\n\r\n // Parse data from file to get nodes and links\r\n try {\r\n var jsonData = JSON.parse(e.target.result);\r\n }\r\n catch (e) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n\r\n // Check for validity of data\r\n if (Object.keys(jsonData).length == 0 || Object.keys(jsonData).length > 2 || Object.keys(jsonData).length == 1 && typeof jsonData.links == \"undefined\" || Object.keys(jsonData).length == 2 && (typeof jsonData.links == \"undefined\" || typeof jsonData.nodes == \"undefined\")) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n\r\n var graphData = [];\r\n\r\n for (var l of jsonData.links) {\r\n if (Object.keys(l).length != 2 || typeof l.source == \"undefined\" || typeof l.target == \"undefined\" || !Number.isInteger(l.source) || !Number.isInteger(l.target) || l.source < 0 || l.target < 0) {\r\n $(\"#file-error\").show();\r\n return;\r\n }\r\n graphData.push(l.source);\r\n graphData.push(l.target);\r\n }\r\n\r\n // Get nodes from data\r\n nodeIDs = graphData.filter(function (n, index) {\r\n return graphData.indexOf(n) == index;\r\n }).map(function (n) {\r\n return Number(n);\r\n });\r\n\r\n nodeIDs.sort((a, b) => a - b);\r\n\r\n nodeIDs.forEach(function (n) {\r\n if (selectedAlgorithm == 1)\r\n nodes.push({ id: Number(n), degree: 0 });\r\n else if (selectedAlgorithm == 2)\r\n nodes.push({ id: Number(n), degree: 0, capacity: 1 });\r\n else if (selectedAlgorithm == 3)\r\n nodes.push({ id: Number(n), degree: 0 });\r\n });\r\n\r\n // Set capacities or coordinates\r\n if (typeof jsonData.nodes != \"undefined\") {\r\n for (var n of jsonData.nodes) {\r\n if (typeof n.id == \"undefined\" || !Number.isInteger(n.id) || n.id < 0 || (selectedAlgorithm == 1 || selectedAlgorithm == 2) && (Object.keys(n).length != 2 || typeof n.capacity == \"undefined\" || !Number.isInteger(n.capacity) || n.capacity < 1) || selectedAlgorithm == 3 && (Object.keys(n).length != 3 || typeof n.x == \"undefined\" || typeof n.y == \"undefined\" || isNaN(n.x) || isNaN(n.y) || n.x < 0 || n.y < 0 || n.x > 100 || n.y > 100)) {\r\n $(\"#file-error\").show();\r\n clearGraph();\r\n return;\r\n }\r\n\r\n if (selectedAlgorithm == 2 || selectedAlgorithm == 3) {\r\n var node = nodes.filter(function (x) {\r\n return n.id == x.id;\r\n })[0];\r\n\r\n if (selectedAlgorithm == 2 && typeof node != \"undefined\")\r\n node.capacity = n.capacity;\r\n else if (selectedAlgorithm == 3 && typeof node != \"undefined\") {\r\n node.rx = n.x;\r\n node.ry = n.y;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Create edges based on data provided in file\r\n jsonData.links.forEach(function (l) {\r\n var source = nodes.filter(function (n) {\r\n return l.source == n.id;\r\n })[0];\r\n\r\n source.degree++;\r\n\r\n var target = nodes.filter(function (n) {\r\n return l.target == n.id;\r\n })[0];\r\n\r\n target.degree++;\r\n\r\n // Only add edge if it does not already exist\r\n if (!links.some(function (x) { return x.source == source && x.target == target; }))\r\n links.push({ source: source, target: target });\r\n });\r\n\r\n }\r\n\r\n // Initially place all nodes at center of graph\r\n nodes.forEach(function (n) {\r\n n.x = 0.5 * graphWidth;\r\n n.px = n.x;\r\n n.y = 0.525 * graphHeight;\r\n n.py = n.y;\r\n });\r\n\r\n // Update graph\r\n updateCoordinates = false;\r\n restart();\r\n\r\n var unassigned = []; // Array of nodes that are not linked to any other node\r\n\r\n // If degree of node is 0, push to 'unassigned' array\r\n nodes.forEach(function (n) {\r\n if (n.degree == 0)\r\n unassigned.push(n);\r\n });\r\n\r\n // Remove unassigned nodes\r\n unassigned.forEach(function (n) {\r\n nodes.splice(nodes.indexOf(n), 1);\r\n });\r\n\r\n if (selectedAlgorithm == 1 || selectedAlgorithm == 2)\r\n checkBipartite();\r\n\r\n else if (selectedAlgorithm == 3) {\r\n\r\n // Place nodes with unassigned coordinates in a circular layout for general graph matching\r\n nodes.forEach(function (n, i) {\r\n if (typeof n.rx == \"undefined\" || typeof n.ry == \"undefined\") {\r\n n.rx = 50 + 40 * Math.sin(2 * i * Math.PI / nodes.length);\r\n n.ry = 50 + 40 * Math.cos(2 * i * Math.PI / nodes.length + Math.PI);\r\n }\r\n });\r\n\r\n }\r\n\r\n positionNodes();\r\n updateCoordinates = true;\r\n\r\n // Reset import modal\r\n M.Modal.getInstance($(\"#import-modal\")).close();\r\n $(\"#file-error\").hide();\r\n $(\"#import-text\").val(\"\");\r\n $(\"#import-text\").removeClass(\"valid\");\r\n $(\"#import-data\").val(\"\");\r\n $(\"#import-btn\").addClass(\"disabled\");\r\n }\r\n })(file);\r\n\r\n reader.readAsText(file);\r\n \r\n}", "init() {\n this.worldMap.parseMap();\n }", "function load() {\n _data_id = m_data.load(FIRST_SCENE, load_cb, preloader_cb);\n}", "function loadData( tags , maps, styles ){\n return new Promise(function(resolve, reject) {\n \n MapService.filter( tags, function(mapData){\n var mapPromises = mapData.payload.map( function( thisMap ){\n maps[ thisMap.name ] = thisMap\n return loadStyles( thisMap, styles )\n })\n // Resolve when all the map data has been loaded\n Promise.all( mapPromises ).then(resolve)\n });\n });\n }", "function loadCities() {\n\td3.csv(\"data/City_Coordinates.csv\").then(function(data) {\n\t\tif (data == undefined) {\n\t\t\tconsole.log(\"Failed to load file\");\n\n\t\t\treturn;\n\t\t}\n\t\tdata.forEach(function(d) {\n\t\t\tif (records[d.RegionName] != undefined) {\n\t\t\t\trecords[d.RegionName][\"latitude\"] = d.Latitude != \"\" ? d.Latitude : 0;\n\t\t\t\trecords[d.RegionName][\"longitude\"] = d.Longitude != \"\" ? d.Longitude : 0;\n\t\t\t}\n\t\t});\n\t});\n\n\t// Convert the records object to an array\n\tdata = Object.keys(records).map(function(key) { \n\t\treturn records[key]; \n\t});\n}", "function load_map() {\n\tmap = new L.Map('map', {zoomControl: true});\n\n\t// from osmUrl we can change the looks of the map (make sure that any reference comes from open source data)\n\tvar osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n\t// var osmUrl = 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',\n\t\tosmAttribution = 'Map data &copy; 2012 <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors',\n\t\tosm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});\n\n\n\t// define the center and zoom level when loading the page (zoom level 3 allows for a global view)\n\tmap.setView(new L.LatLng(20, 10), 3).addLayer(osm);\n\n\n\t$.ajax({\n\t\turl: 'js/doe.csv',\n\t\tdataType: 'text/plain',\n\t}).done(successFunction);\n\n\tfunction successFunction(data) {\n\t\tvar planes = data.split('/\\r?\\n|\\r/');\n\t\tconsole.log(planes);\n\n\t\t// for (var i = 0; i < planes.length; i++) {\n\t\t// \tvar markersplit = planes[i].split(',');\n\t\t// \tmarker = new L.marker([markersplit[3],markersplit[4]]).bindPopup(markersplit[0]).addTo(map);\n\t\t// }\n\n\t}\n\n\n\t// variable to allow to read the points from above and pass that to the marker rendering function\n\n\n\n\t// create layer with all the markers to turn on and off (maybe no need for this)\n\t// var overlayMaps = {\n\t// \t\"Cities\" : marker\n\t// }\n\t// L.control.layers(overlayMaps).addTo(map);\n\n\n}", "preloadMap() {\n\n // Read the previously parsed Tiled map JSON\n this.tilemapJson = this.game.cache.getJSON(this.mapName);\n\n // Load the Tiled map JSON as an actual Tilemap\n this.game.load.tilemap(this.mapName, null, this.tilemapJson, Phaser.Tilemap.TILED_JSON);\n\n // Load the tileset images\n this.loadTilesetImages();\n }", "convertDataToGraph() {\n let graph = {nodes: [], links: [], nodeLabelsMap: {}}\n\n if (this.state.data == null) {\n return graph;\n }\n // To ensure we do not render duplicates, we build sets of nodes, relationships and labels.\n let nodesMap = {}\n let nodeLabelsMap = {}\n let linksMap = {}\n\n // First, iterate over the result rows to collect the unique nodes.\n // We handle different types of return objects in different ways.\n // These types are single nodes, arrays of nodes and paths.\n // This also handles finding all unique node labels we have in the entire result set.\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single nodes\n if (value && value[\"labels\"] && value[\"identity\"] && value[\"properties\"]) {\n this.extractNodeInfo(value, nodeLabelsMap, nodesMap);\n }\n // arrays of nodes\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"labels\"] && item[\"identity\"] && item[\"properties\"]) {\n this.extractNodeInfo(item, nodeLabelsMap, nodesMap);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n this.extractNodeInfo(value.start, nodeLabelsMap, nodesMap);\n value.segments.forEach(segment => {\n this.extractNodeInfo(segment.end, nodeLabelsMap, nodesMap);\n });\n }\n })\n });\n\n // Then, also extract the relationships from the result set.\n // We store only unique relationships. where uniqueness is defined by the tuple [startNode, endNode, relId].\n\n // As a preprocessing step, we first sort the relationships in groups that share the same start/end nodes.\n // This is done by building a dictionary where the key is the tuple [startNodeId, endNodeId], and the value\n // is the relationship ID.\n\n // Additionally, preprocess the relationships and sort them such that startNode is always the lowest ID.\n\n // We also store a seperate dict with [startNodeId, endNodeId] as the key, and directions as values.\n\n let relsVisited = {}\n let relsVisitedDirections = {}\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single rel\n if (value && value[\"type\"] && value[\"start\"] && value[\"end\"] && value[\"identity\"] && value[\"properties\"]) {\n this.preprocessVisitedRelationships(value, relsVisited, relsVisitedDirections);\n }\n // arrays of rel\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"type\"] && item[\"start\"] && item[\"end\"] && item[\"identity\"] && item[\"properties\"]) {\n this.preprocessVisitedRelationships(item, relsVisited, relsVisitedDirections);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n value.segments.forEach(segment => {\n this.preprocessVisitedRelationships(segment.relationship, relsVisited, relsVisitedDirections);\n });\n }\n });\n })\n\n // Now, we use the preprocessed relationship data as well as the built nodesMap.\n // With this data, we can build a graph.nodesMap and graph.linksMap object that D3 can work with.\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single rel\n if (value && value[\"type\"] && value[\"start\"] && value[\"end\"] && value[\"identity\"] && value[\"properties\"]) {\n this.extractRelInfo(value, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n }\n // arrays of rel\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"type\"] && item[\"start\"] && item[\"end\"] && item[\"identity\"] && item[\"properties\"]) {\n this.extractRelInfo(item, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n // this.extractNodeInfo(value.start, nodeLabelsMap, nodesMap);\n value.segments.forEach(segment => {\n this.extractRelInfo(segment.relationship, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n });\n }\n });\n })\n\n graph.nodes = Object.values(nodesMap)\n graph.links = Object.values(linksMap)\n graph.nodeLabels = Object.keys(nodeLabelsMap)\n\n\n // Trigger a refresh of the graph visualization.\n this.props.onNodeLabelUpdate(nodeLabelsMap)\n return graph\n }", "function loadActivities() {\n clearCanvas();\n nodesArray = [];\n loadedStory.activities.forEach((a) => {\n addActivityNode(a);\n });\n \n //After we created all nodes we create all outputs and make the connections\n loadedStory.activities.forEach((a, index) => {\n setNodeOutputs(a, nodesArray[index]);\n });\n}", "function loadDefaultElementsOnMap (){\n\n map.on('load', function(){\n\n try {\n\n // source and layer UPZ polygons\n addSourceMap(ID_UPZ_SOURCE, UPZ_POL_LOCAL_PATH, 'geojson');\n addLayerPolygonOnMap(ID_LAYER_UPZ, ID_UPZ_SOURCE, 'none', '#3CB8FB', '#FFFFFF');\n\n // source and layer localities polygons\n addSourceMap(ID_LOCALITIES_SOURCE, LCL_POL_LOCAL_PATH, 'geojson');\n addLayerPolygonOnMap(ID_LAYER_LCL, ID_LOCALITIES_SOURCE, 'none', '#3CB8FB', '#FFFFFF');\n\n addSourceMap(ID_CAT_ZONE_SOURCE, CAT_ZONE_POL_LOCAL_PATH, 'geojson');\n addLayerPolygonOnMap(ID_LAYER_ZC, ID_CAT_ZONE_SOURCE, 'none', '#3CB8FB', '#FFFFFF');\n\n // localities borders\n addLineBorderLayerOnMap (ID_BORDER_LAYER_LCL, ID_LOCALITIES_SOURCE, 'none', '#FFFFFF', 1.2);\n // upz borders\n addLineBorderLayerOnMap (ID_BORDER_LAYER_UPZ, ID_UPZ_SOURCE, 'none', '#FFFFFF', 1.2);\n // catastral zones borders\n addLineBorderLayerOnMap (ID_BORDER_LAYER_ZC, ID_CAT_ZONE_SOURCE, 'none', '#FFFFFF', 1);\n\n // localities names\n addSourceMap(ID_NAMES_LCL_SOURCE, LCL_UNIT_NAMES_PATH, 'geojson');\n addPolygonNamesOnMap (ID_NAMES_LAYER_LCL, ID_NAMES_LCL_SOURCE, 'none', 'NOM_LCL', 0.68, 10, 20);\n\n // upz names\n addSourceMap(ID_NAMES_UPZ_SOURCE, UPZ_UNIT_NAMES_PATH, 'geojson');\n addPolygonNamesOnMap (ID_NAMES_LAYER_UPZ, ID_NAMES_UPZ_SOURCE, 'none', 'UPlNombre', 0.58, 10, 20);\n \n // catastral zones names\n addSourceMap(ID_NAMES_ZC_SOURCE, ZC_UNIT_NAMES_PATH, 'geojson');\n addPolygonNamesOnMap (ID_NAMES_LAYER_ZC, ID_NAMES_ZC_SOURCE, 'none', 'ZC_NOM', 0.5, 13, 22);\n\n // heatmap nuse\n addSourceMap(ID_HEATMAP_NUSE_SOURCE, HEATMAP_NUSE_PATH, 'geojson');\n addSourceMap(ID_HEATMAP_PTS_NUSE_SOURCE, HEATMAP_PTS_NUSE_PATH, 'geojson');\n heatMapNuse();\n \n } catch (error) {\n console.log(error);\n }\n \n\n });\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
on strip move event preload visible images if that option selected
function onThumbsChange(event){ //preload visible images if(g_options.gallery_images_preload_type == "visible" && g_temp.isAllItemsPreloaded == false){ preloadBigImages(); } }
[ "function switch_search_images()\r\n{\r\n search_images = !search_images;\r\n drawControl();\r\n}", "function setThumbnailStrip(pos){\r\n\tbeg = getThumbnailStripBegPos(pos-1);\r\n\tinitThumbnailStrip(beg);\r\n}", "function preload()\r\n{\r\n // Spiderman Mask Filter asset\r\n imgSpidermanMask = loadImage(\"https://i.ibb.co/9HB2sSv/spiderman-mask-1.png\");\r\n\r\n // Dog Face Filter assets\r\n imgDogEarRight = loadImage(\"https://i.ibb.co/bFJf33z/dog-ear-right.png\");\r\n imgDogEarLeft = loadImage(\"https://i.ibb.co/dggwZ1q/dog-ear-left.png\");\r\n imgDogNose = loadImage(\"https://i.ibb.co/PWYGkw1/dog-nose.png\");\r\n}", "function initThumbnailStrip(pos)\r\n{\r\n $(\".main .thumbnail_image_wrapper_iws2\").jCarouselLite(\r\n {\r\n \t btnNext: \".main .next\",\r\n \t btnPrev: \".main .prev\",\r\n \t speed: 10,\r\n \t circular: false,\r\n \t visible: visible_thumbnail_images,\r\n \t scroll: visible_thumbnail_images,\r\n \t start: pos\r\n });\r\n \r\n $(\".thumbnail_image_wrapper_iws2 ul\").css('margin-left','-8px');\r\n $(\".thumbnail_image_wrapper_iws2 ul\").css('padding-left','0px');\r\n $(\".thumbnail_image_wrapper_iws2 ul\").css('padding-top','0px');\r\n $(\".thumbnail_image_wrapper_iws2 ul\").css('margin-top','0px');\r\n}", "onSkippedCrop() {\n const attachment = this.frame.state().get('selection').first().toJSON()\n this.setImageFromAttachment(attachment)\n }", "_configureShipImg(img, size, variant, coords, direction, options = {}) {\n // Clear the initial classes\n img.className = '';\n img.src = `${this._imgSrcRoot}${size}${variant ? variant : ''}.png`;\n img.classList.add('vessel');\n if (direction === GameBoard.Direction.VERTICAL) {\n img.classList.add('vertical');\n }\n if (options.placing) {\n img.classList.add('placing');\n }\n if (options.invalid) {\n img.classList.add('invalid');\n }\n img.style.left = (coords.x + 1) * 50 + 'px';\n img.style.top = (coords.y + 1) * 50 + 'px';\n }", "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "function shuffleSelectionChanged() {\n if(shuffleSelector.value() === 'Shuffle') {\n shuffleStatus = true;\n } else {\n shuffleStatus = false;\n }\n setImage();\n}", "function largeGifAppears(e) {\n let src = $(e).attr('src');\n $chosenGif.attr(\"src\", src); // can i do this\n $chosenGif.show();\n}", "function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }", "function updateSrcs() {\n\t\t$('#img1').attr('src', gifArray[championIndex]);\n\t\t$('#img2').attr('src', gifArray[challengerIndex]);\n\t}", "defaultSlideShow() {\n this.preloadImg()\n utils.css(this.wrapper, \"left\", -this.defaultIndex * this.width);\n }", "function slide() {\n if (r < 4) {\n r++;\n img.src = \"Images/photos/\" + ships[idIndex].name + \"/\" + r + \".jpg\";\n } else {\n r = 1;\n img.src = \"Images/photos/\" + ships[idIndex].name + \"/\" + r + \".jpg\";\n }\n }", "function preload(){\n\thelicopterIMG=loadImage(\"helicopter.png\")\n\tpackageIMG=loadImage(\"package.png\")\n}", "function mostrarPrimeiraImagem() {\n if (slidePosition !== 0) {\n slidePosition = 0; \n }\n\n updateDot();\n updateSlidePosition();\n}", "function preloadImages(code) {\n var re = /SimpleImage\\(\\s*(\"|')(.*?)(\"|')\\s*\\)/g;\n while (ar = re.exec(code)) {\n // Used to screen out data: urls here, but that messed up the .loaded attr, strangely\n var url = ar[2];\n loadImage(url);\n }\n}", "imageLoaded(){}", "function showImage(event) {\n\tresetClassNames(); // Klasu \"selected\" treba da ima onaj link cija je slika trenutno prikazana u \"mainImage\" elementu.\n\t\t\t\t\t // Pre stavljanja ove klase na kliknuti link, treba da sklonimo tu klasu sa prethodno kliknutog linka. To onda\n\t\t\t\t\t // postizemo tako sto sklonimo sve klase sa svih linkova, i time smo sigurni da ce i klasa \"selected\" biti uklonjena.\n\tthis.className = \"selected\"; // Stavljamo klasu \"selected\" na kliknuti link.\n\tmainImage.setAttribute(\"src\", this.getAttribute(\"href\")); // Atribut \"src\" elementa \"mainImage\" menjamo tako da postane jednak \"href\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // atributu kliknutog linka. A kako se u \"href\" atributu linka nalazi putanja\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // ka slici, postavljanjem \"src\" atributa na tu putanju, unutar elementa\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // \"mainImage\" ce se prikazati slika iz linka na koji se kliknulo.\n\tevent.preventDefault(); // Na ovaj nacin sprecavamo defoltno ponasanje browser-a, kojim bi se slika iz linka otvorila zasebno.\n\tscale = 1; // Nakon promene slike treba da vratimo zoom nivo na 1, da novoprikazana slika ne bi bila zumirana.\n\tsetScale(); // Kako smo u liniji iznad promenili vrednost \"scale\" globalne promenljive, potrebno je pozvati funkciju \"setScale\", koja onda\n\t\t\t\t// uzima vrednost promenljive \"scale\" i integrise je u CSS.\n\tleftPos = 0; // Nakon promene slike treba da vratimo sliku u inicijalnu poziciju.\n\tsetPosition(); // Kako smo u liniji iznad promenili vrednost \"leftPos\" globalne promenljive, potrebno je pozvati funkciju \"setPosition\"\n\t\t\t\t // koja onda uzima vrednost promenljive \"leftPos\" i integrise je u CSS.\n}", "function preload()\n{\n\tpaperImage = loadImage(\"paperImage.png\")\n\tdustbinImage = loadImage(\"dustbinWHJ.png\")\n\n}", "function hideSceneImages() {\n for (let i = 0; i < extractImages.length; i++) {\n\n extractImages[i].style.display = 'none'\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter > queries queries > heading, query query > event template, result type, time range
function Query (_name, _event_template, _result_type, _time_range, _max_events, _layout) { this._init (_name, _event_template, _result_type, _time_range, _max_events, _layout); }
[ "function analyze(args){\n let passData = {};\n passData.date = new Date();\n \n if(args.hasArg('date')){\n passData.date = new Date(args.getArg('date'));\n }\n \n if(args.hasArg('groupby')){\n passData.groupby = args.getArg('groupby');\n if(args.hasArg('and')){\n passData.and = args.getArg('and');\n }\n }\n\n var data = model.analyze(passData);\n if(_.isEmpty(data)){\n console.log(\"There are no timers for this date\");\n }else{\n\n console.log(columnify(data, {config: { description: {maxWidth: 30}}}));\n }\n }", "createFilterQuery() {\n const filterType = this.state.filterType;\n const acceptedFilters = ['dropped', 'stale', 'live'];\n\n if (acceptedFilters.includes(filterType)) {\n const liveIDs = this.state.liveIDs;\n if (filterType === 'dropped') return {'events.id': {$nin: liveIDs}};\n if (filterType === 'stale') return {'events.id': {$in: liveIDs}, end_date: {$lt: new Date()}};\n if (filterType === 'live') return {'events.id': {$in: liveIDs}, end_date: {$gte: new Date()}};\n }\n\n return {};\n }", "emitQueryEvent(error) {\n if (!this.startTime) {\n return;\n }\n const eventData = { duration: process.hrtime(this.startTime), ...this.data, error };\n this.client.emitter.emit(this.eventName, eventData);\n }", "function renderTMEvents(startDate, startTime, endDate, endTime, city, state, postalCode, countryCode, radius, maxEvents) {\n\n // We are expecting a valid date and city or else stop....TODO: return a valid error code\n if ((!startDate) || (!endDate) || (!city)) {\n alert(\"Fatal Error - no date or city passed into renderTMEvents\");\n }\n\n // Initialize time to 24 hours if not passed in\n if (!startTime) {\n startTime = \"00:00:00\";\n }\n\n if (!endTime) {\n endTime = \"23:59:59\";\n }\n\n if (!radius) {\n radius = 150;\n\n }\n\n // maximum number of events we want returned from Ticket Master event query\n if (!maxEvents) {\n maxEvents = \"30\";\n }\n\n // construct the TM localStartDateTime needed for the search event TM API\n var localStartDateTime = \"&localStartDateTime=\" + startDate + \"T\" + startTime + \",\" + endDate + \"T\" + endTime;\n //var endDateTime = \"&localStartEndDateTime=\" + endDate + \"T\" + endTime + \"Z\";\n\n // always looking for music events for this app.\n var classificationId = \"&classificationId=KZFzniwnSyZfZ7v7nJ\";\n\n //URL into TM API'\n var url = \"https://app.ticketmaster.com/discovery/v2/events.json?size=\" + maxEvents + \"&apikey=uFdFU8rGqFvKCkO5Jurt2VUNq9H1Wcsx\";\n var queryString = url + localStartDateTime + classificationId + countryCode;\n\n // construct the appropriate parameters needed for TM\n if (city) {\n queryString = queryString + \"&city=\" + city;\n }\n if (radius) {\n queryString = queryString + \"&radius=\" + radius;\n }\n if (postalCode) {\n queryString = queryString + \"&postalCode=\" + postalCode;\n }\n<<<<<<< HEAD\n if (state) {\n queryString = queryString + \"&state=\" + state;\n }\n\n // console log the queryString\n console.log(queryString);\n\n // make the AJAX call into TM\n $.ajax({\n type: \"GET\",\n url: queryString,\n async: true,\n dataType: \"json\",\n success: function (response) {\n // we are here if the AJAX call is successful\n console.log(response);\n var events = createEvents(response);\n return events;\n // console.log(TMEvents);\n },\n error: function (xhr, status, err) {\n // This time, we do not end up here!\n // TODO: return an error code for now just setTMEvent to empty\n TMEvents = \"\";\n console.log(err);\n }\n });\n }", "function epgsearch_json_to_html(data) {\n var html = \"\";\n for (var i = 0, len = data.events.length; i < len; i++) {\n var event = data.events[i];\n\n html += \"<tr class=\\\"event_row visible_event\\\">\";\n\n html += \"<td class=\\\"search_type\\\">\";\n html += \"<!-- event_crid:\" + event.event_crid + \", series_crid:\" + event.series_crid + \", rec_crid:\" + event.rec_crid + \". -->\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_channel\\\">\";\n if (event.channel_name != \"\") {\n html += \"<div>\";\n html += \"<img src=\\\"\" + event.channel_icon_path + \"\\\" width=20 height=20 alt=\\\"\" + escapeHtml(event.channel_name) + \"\\\"/>\";\n html += \"<span>\" + escapeHtml(event.channel_name) + \"</span>\";\n html += \"</div>\";\n }\n html += \"</td>\";\n\n html += \"<td class=\\\"search_title\\\">\";\n html += \"<div>\" + escapeHtml(event.title) + \"</div>\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_synopsis\\\">\";\n html += \"<div>\" + escapeHtml(event.synopsis) + \"</div>\";\n html += \"</td>\";\n\n html += \"<td class=\\\"search_datetime\\\" sval=\\\"\" + event.start + \"\\\">\";\n html += formatDateTime(event.start);\n html += \"</td>\";\n\n html += \"<td class=\\\"search_duration\\\" sval=\\\"\" + event.duration + \"\\\">\";\n html += event.duration + (event.duration == 1 ? \" min\" : \" mins\");\n html += \"</td>\";\n\n html += \"<td class=\\\"search_flags\\\">\";\n if (inventory_enabled) {\n if (event.available) {\n html += \"<a class=\\\"inventory\\\" href=\\\"#\\\"><img src=\\\"images/available.png\\\" width=16 height=16 title=\\\"available\\\"></a>\";\n }\n }\n if (event.repeat_crid_count > 0) {\n html += \" <a class=\\\"repeat\\\" prog_crid=\\\"\" + event.event_crid + \"\\\" href=\\\"#\\\"><img src=\\\"images/repeat.png\\\" width=16 height=16 title=\\\"CRID repeat\\\"></a>\";\n } else if (event.repeat_program_id != -1) {\n html += \" <a class=\\\"dejavu\\\" prog_id=\\\"\" + event.repeat_program_id + \"\\\" href=\\\"#\\\"><img src=\\\"images/dejavu.png\\\" width=16 height=16 title=\\\"d&eacute;j&agrave; vu?\\\"></a>\";\n }\n if (event.ucRecKind == -1) {\n html += \"<img src=\\\"images/175_1_00_Reservation_Watch.png\\\" width=16 height=16 title=\\\"Programme reminder\\\">\";\n } else if (event.ucRecKind == 1) {\n html += \"<img src=\\\"images/175_1_11_Reservation_Record.png\\\" width=16 height=16 title=\\\"Recording programme\\\">\";\n } else if (event.ucRecKind == 2 || event.ucRecKind == 4) {\n html += \"<img src=\\\"images/175_1_11_Series_Record.png\\\" width=28 height=16 title=\\\"Recording series\\\">\";\n } else if (event.crid_ucRecKind == 1) {\n html += \"<img class=\\\"collateral_scheduled\\\" src=\\\"images/175_1_11_Reservation_Record.png\\\" width=16 height=16 title=\\\"Recording another time\\\">\";\n } else if (event.crid_ucRecKind == 2 || event.crid_ucRecKind == 4) {\n html += \"<img class=\\\"collateral_scheduled\\\" src=\\\"images/175_1_11_Series_Record.png\\\" width=28 height=16 title=\\\"Recording another time\\\">\";\n }\n if (event.scheduled_slot != -1) {\n html += \"<a href=\\\"#\\\" class=\\\"cancel_rec\\\" sid=\\\"\" + event.scheduled_slot + \"\\\">\";\n html += \"<img src=\\\"images/schedule.png\\\" width=16 height=16 title=\\\"Schedule\\\">\";\n html += \"</a>\";\n } else {\n var rec = (event.series_crid == \"\" ? 1 : 2);\n html += \"<a href=\\\"#\\\" class=\\\"schedule_rec\\\" xs=\\\"\" + event.service_id + \"\\\" xe=\\\"\" + event.event_id + \"\\\" sch=\\\"0\\\" rec=\\\"\" + rec + \"\\\">\";\n html += \"<img src=\\\"images/schedule.png\\\" width=16 height=16 title=\\\"Schedule\\\">\";\n html += \"</a>\";\n }\n html += \"</td>\";\n\n html += \"</tr>\";\n }\n return $(html);\n }", "prepareTimeline(queryId, queryOutput, dateField) {\n\t\tvar timelineData = [];\n\t\tfor (let key in queryOutput.aggregations) {\n\t\t\tif (key.indexOf(dateField) != -1) {\n\t\t\t\tvar buckets = queryOutput.aggregations[key][dateField].buckets;\n\t\t\t\tbuckets.forEach((bucket) => {\n\t\t\t\t\tvar year = parseInt(bucket.key);\n\t\t\t\t\tif (!(isNaN(year))) {\n\t\t\t\t\t\ttimelineData.push({\"year\": year, \"count\": bucket.doc_count, \"query\": queryId});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconsole.debug(timelineData);\n\t\treturn timelineData;\n\t}", "function getTimesFromFilter(filterParams, data) {\n\tlet openSlide = 0;\n\tlet closeSlide = 0;\n\tlet enabled = false;\n\tlet restaurantData = [];\n\tfor (let key in filterParams) {\n\t\tif (key == \"timesEnable\") enabled = true;\n\n\t\tif (key == \"slider-time\" && enabled) {\n\t\t\tlet split = filterParams[key].split(\",\");\n\t\t\topenSlide = parseFloat(\n\t\t\t\tformatTime(split[0]).split(\":\")[0] +\n\t\t\t\t\t\".\" +\n\t\t\t\t\tformatTime(split[0]).split(\":\")[1]\n\t\t\t);\n\t\t\tcloseSlide = parseFloat(\n\t\t\t\tformatTime(split[1]).split(\":\")[0] +\n\t\t\t\t\t\".\" +\n\t\t\t\t\tformatTime(split[1]).split(\":\")[1]\n\t\t\t);\n\t\t}\n\t}\n\tif (!enabled) {\n\t\treturn data;\n\t} else {\n\t\tfor (key in data) {\n\t\t\tlet open = parseFloat(\n\t\t\t\tdata[key].openingTime.split(\":\")[0] +\n\t\t\t\t\t\".\" +\n\t\t\t\t\tdata[key].openingTime.split(\":\")[1]\n\t\t\t);\n\t\t\tlet close = parseFloat(\n\t\t\t\tdata[key].closingTime.split(\":\")[0] +\n\t\t\t\t\t\".\" +\n\t\t\t\t\tdata[key].closingTime.split(\":\")[1]\n\t\t\t);\n\t\t\tif (open >= openSlide && close <= closeSlide) {\n\t\t\t\trestaurantData.push(data[key]);\n\t\t\t}\n\t\t}\n\n\t\treturn restaurantData;\n\t}\n}", "async function listRecords(req, res) {\n let countQuery;\n let recordQuery;\n\n console.log(req.body);\n\n switch (req.body.queryType) {\n case \"keys\":\n countQuery = queries.keyCount;\n recordQuery = queries.keyRecords;\n break;\n case \"properties\":\n countQuery = queries.propCount;\n recordQuery = queries.propRecords;\n break;\n case \"people\":\n countQuery = queries.peopleCount;\n recordQuery = queries.peopleRecords;\n break;\n default:\n console.log(\"No query type passed to server.\");\n res.status(400).json({ error: \"No query type passed to server.\" });\n return;\n }\n\n //Build queries with WHERE clause, if request body includes an id and a value.\n if (req.body.filter.id && req.body.filter.value) {\n //People view. Requires alias for UNION ALL subselect.\n if (req.body.queryType === \"people\") {\n countQuery +=\n \"WHERE c.\" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE users.\" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n } else if (req.body.queryType === \"properties\") {\n //Properties and Keys views.\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n } else {\n //The key view has a special QR Code input, which will always take\n //a specially formatted string consisting of 4 values\n if (req.body.filter.id === \"qr\") {\n const filterArray = req.body.filter.value.split(\"*\");\n countQuery += `WHERE property_number LIKE ${filterArray[0]} AND\n office_location LIKE '${filterArray[1]}' AND key_type LIKE\n '${filterArray[2]}' AND key_number LIKE ${filterArray[3]} `;\n recordQuery += `WHERE property_number LIKE ${filterArray[0]} AND\n office_location LIKE '${filterArray[1]}' AND key_type LIKE\n '${filterArray[2]}' AND key_number LIKE ${filterArray[3]} `;\n } else if (req.body.filter.id === \"key_status\") {\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"' +\n req.body.filter.value +\n '%\" ';\n } else {\n countQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n recordQuery +=\n \"WHERE \" +\n req.body.filter.id +\n ' LIKE \"%' +\n req.body.filter.value +\n '%\" ';\n }\n }\n }\n\n //Build queries with ORDER BY clause, if request body includes an id\n if (req.body.sorted.length) {\n recordQuery += \"ORDER BY \" + req.body.sorted[0].id + \" \";\n if (req.body.sorted[0].desc) {\n recordQuery += \"DESC \";\n }\n }\n\n //Enable pagination\n let offset = req.body.page * req.body.pageSize;\n recordQuery += `LIMIT ${offset}, ${req.body.pageSize} `;\n\n console.log(recordQuery);\n\n //Query database and build response object\n try {\n const count = await db.dbQuery(countQuery);\n const rows = await db.dbQuery(recordQuery);\n let pageCount = Math.ceil(\n parseFloat(count[0].count) / parseFloat(req.body.pageSize)\n );\n const payload = {\n data: rows,\n pages: pageCount\n };\n res.status(200).json(payload);\n } catch (err) {\n console.log(err);\n res.status(404).json(err);\n }\n}", "function setQuery() {\n\tstartTime = parseStartDate($('#datepicker1').val());\n\tif ( (new Date()).getDate() == (parseStartDate($('#datepicker2').val())).getDate() ) {\n\t\tendTime = new Date();\n\t}\n\telse {\n\t\tendTime = parseEndDate($('#datepicker2').val());\n\t}\n\tvar daysOutputted = daysDisplayed(startTime, endTime);\n\tsetTimeTicks(daysOutputted);\n\tfor (var i in currentItem) {\n\t\tif (d3.select(\".y\" + (Number(i) + 1) + \"Axis\").size()) {\n\t\t\trenderData(data_items[currentItem[i]], Number(i));\n\t\t}\n\t}\n}", "function prepareQuery(hash) {\n\t'use strict';\n\tds.historics.prepare({\n\t\t'hash': hash,\n\t\t'start': startTime,\n\t\t'end': endTime,\n\t\t'sources': 'twitter',\n\t\t'name': 'Example historic query'\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Prepared query: ' + response.id);\n\t\t\tcreateSubscription(response.id);\n\t\t}\n\t});\n}", "async queryContainer() {\n console.log(`Querying container:\\n${config.container.id}`)\n \n // query to return all children in a family\n // Including the partition key value of lastName in the WHERE filter results in a more efficient query\n const querySpec = {\n query: 'SELECT * FROM root r WHERE @Hours - r.Hours <=1',\n parameters: [\n {\n name: '@Hours',\n value: (new Date).getUTCHours()\n },\n {\n name: '@Minutes',\n value: (new Date).getUTCMinutes()\n }\n ]\n }\n \n const { resources: results } = await this.client\n .database(this.databaseId)\n .container(this.containerId)\n .items.query(querySpec)\n .fetchAll()\n return results;\n }", "queryHistoricalInfo(query) {\n const { height } = query;\n if (is.undefined(height)) {\n throw new errors_1.SdkError('block height can not be empty');\n }\n const request = new types.staking_query_pb.QueryHistoricalInfoRequest()\n .setHeight(height);\n return this.client.rpcClient.protoQuery('/cosmos.staking.v1beta1.Query/HistoricalInfo', request, types.staking_query_pb.QueryHistoricalInfoResponse);\n }", "function filterResults(resultAll) {\r\n console.log('filterResults');\r\n let scheduled = [\"Scheduled\"];\r\n let filteredArray = resultAll.result.filter(function(itm) {\r\n return scheduled.indexOf(itm.status.value) > -1;\r\n });\r\n return {result: filteredArray};\r\n}", "function getAll() {\n\t'use strict';\n\tds.historics.get(function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic queries: ' + JSON.stringify(response));\n\t\t\tcheckStatus();\n\t\t}\n\t});\n}", "function queryLoggerData(starttime,endtime,doOnSuccess) {\n\tif(endtime!=\"now\")\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n\telse\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n}", "async function get_all_divvy_stations_log(timeRange, newTimeRangeSelection) {\n var start_datetime_var = new Date();\n var scrollVal;\n\n\n all_docks_found = [];\n\n if(timeRange.includes(PAST_HOUR)){\n if(newTimeRangeSelection){\n isBeginningOfTimeRangeSet = false;\n\n }\n\n if(!isBeginningOfTimeRangeSet){\n\n all_docks_found = [];\n\n isBeginningOfTimeRangeSet = true;\n\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n go_back_in_time_var = start_datetime_var.getHours() - 1;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getMinutes() + 2 ;\n time_stamp_var_4 .setMinutes(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n\n sizeVal = 1000000;\n scrollVal='1s';\n }\n\n }\n\n\n\n else if(timeRange == PAST_24_HOURS ){\n\n if(newTimeRangeSelection){\n isBeginningOfTimeRangeSet = false;\n }\n\n\n if(! isBeginningOfTimeRangeSet){\n\n isBeginningOfTimeRangeSet = true;\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n\n go_back_in_time_var = start_datetime_var.getHours() - 24;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getHours() + 1 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n // Recalculate lower bound for the time-window\n // Take 2 minutes sample on the top of every hour for the past 24 hours\n // This is NOT the best we could do..\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n \n\n sizeVal = 300;\n scrollsize = 10000;\n scrollVal='15s';\n }\n }\n\n\n\n else if(timeRange.includes(PAST_7_DAYS)){\n\n if(newTimeRangeSelection){ \n isBeginningOfTimeRangeSet = false;\n \n }\n\n\n if(! isBeginningOfTimeRangeSet){\n\n isBeginningOfTimeRangeSet = true;\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n\n go_back_in_time_var = start_datetime_var.getHours() - 168;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getHours() + 24 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour of every day for the past 7 days\n // This is NOT the best we could do...\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n sizeVal = 100000;\n scrollVal='15s';\n }\n }\n\n\n\n \n results = await esClient.search({\n index: 'divvy_station_logs',\n type: 'log',\n scroll: scrollVal,\n // search_type : 'scan',\n size: 1000000,\n from: 0,\n body: {\n\n query: {\n \"bool\":{\n \"filter\":\n {\n \"bool\" : {\n \"must\" :[\n {\n \"range\" : {\n \"lastCommunicationTime.keyword\" : {\n \"gte\": time_stamp_var_2,\n \"lt\": time_stamp_var_3\n }\n }\n }\n ]\n }\n }\n }\n }, \"sort\": [\n { \"lastCommunicationTime.keyword\": { \"order\": \"desc\" }},\n\n ]\n }\n });\n\n\n \n // collect all the records\n\n // console.log('results.hits.total = ', results.hits.total);\n\n results.hits.hits.forEach(function (hit) {\n allRecords.push(hit);\n var docks = {\n \"availableDocks\": hit._source.availableDocks,\n \"latitude\": hit._source.latitude,\n \"longitude\": hit._source.longitude\n };\n all_docks_found.push(docks);\n });\n\n\n \n // Adjust lower bound and upper bound for the time-window\n // for data collection for the next round from ElasticSearch\n\n if(timeRange.includes(PAST_HOUR)){\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() + 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n }\n\n\n else if(timeRange == PAST_24_HOURS){\n\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n go_forward_in_time_var = time_stamp_var_4 .getHours() + 1 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour for the past 24 hours\n // This is NOT the best we could do..\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n\n }\n\n\n else if(timeRange == PAST_7_DAYS){\n\n\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n go_forward_in_time_var = time_stamp_var_4 .getHours() + 24 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour of every day for the past 7 days\n // This is NOT the best we could do...\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n \n\n }\n \n\n\n}", "static get queriesHitTriggers() {}", "function printFilterRestrictionHint () {\n console.log(' The \"restriction\" field is used to determine the type of filter. Possible values for restriction are:')\n console.log(' \"after\" - Filters by date')\n console.log(' filter.path must lead to a date string')\n console.log(' filter.value must be a number')\n console.log(' All alerts with dates before the current time + value(hours) will be removed')\n console.log(' \"before\" - Filters by date')\n console.log(' filter.path must lead to a date string')\n console.log(' filter.value must be a number')\n console.log(' All alerts with dates after the current time + value(hours) will be removed')\n console.log(' \"contains\" - Filters by the contents of an array')\n console.log(' filter.path must lead to an array')\n console.log(' filter.value must be a primitive value potentially found in the arrays filter.path leads to')\n console.log(' All alerts with arrays containing value will be kept')\n console.log(' \"has\" - Filters by whether a path exists in the object')\n console.log(' filter.path is the path to try to access in the alert object')\n console.log(' filter.value is true if alerts with valid paths are kept false if alerts are removed')\n console.log(' All alerts with valid paths are kept is value is true false otherwise')\n console.log(' This type of filter is used before the other filters')\n console.log(' \"equals\" - Filters alerts by comparing primitive values')\n console.log(' filter.path is the path to the primitve value to be compare')\n console.log(' filter.value is the value to compare with')\n console.log(' All alerts with values at path equal to the filter value will be kept')\n console.log(' \"matches\" - Filters by testing strings in the alerts for a regex match')\n console.log(' filter.path must lead to a string')\n console.log(' filter.value must be a regex string')\n console.log(' All alerts with strings at path matching value will be kept')\n console.log('\\n Example: remove all alerts that have been overridden by a later alert.')\n console.log(' {')\n console.log(' \"restriction\": \"has\",')\n console.log(' \"path\": \"properties.replacedBy\",')\n console.log(' \"value\": 0')\n console.log(' }')\n}", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'list', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disconnect and ReConnect Pusher
function reconnect() { if (!socket) { console.debug('[Pusher] Unable to reconnect since Pusher instance does not yet exist.'); return; } console.debug('[Pusher] Reconnecting to Pusher'); socket.disconnect(); socket.connect(); }
[ "function wsCloseConnection(){\n\twebSocket.close();\n}", "_cleanUp() {\n this.connected = false;\n if (this.pinger) {\n Stomp.clearInterval(this.pinger);\n }\n if (this.ponger) {\n return Stomp.clearInterval(this.ponger);\n }\n }", "disconnect() {\n\t\tthis.debug('Requesting disconnect from peer');\n\t}", "disconnect() {\n\t\t\tthis.connected = false;\n\t\t\t// Emitting event 'disconnect', 'exit' and finally 'close' to make it similar to Node's childproc & cluster\n\t\t\tthis._emitLocally('disconnect');\n\t\t}", "function disconnect(){\n if(socket.connected){\n socket.disconnect();\n }\n}", "function pushdeRegister()\n{\n\t//kony.print(\"************ JS unregisterFromAPNS() called *********\");\n\tkony.application.showLoadingScreen(\"sknLoading\",\"Deregistering from push notification..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\t\tkony.push.deRegister({});\n\t\taudiencePushSubs=false;\n\t\teditAudience2();\n\t\t\n}", "disconnectBoard(event){\n event.preventDefault();\n setLedBoardColour(this.state.socket, this.state.deviceName, 0, 0, 0);\n this.setState({ boardConnected: false });\n this.props.updateBoardDeviceName(undefined);\n\n clearInterval(this.state.socketPingInterval);\n disconnectWebSocket(this.state.socket);\n this.setState({socket: undefined, socketPingInterval: undefined});\n this.props.updateSocket(undefined);\n }", "destroy(callback) {\n const connections = Object.keys(this.namespace.connected);\n\n\n let self = this;\n this.print(`Disconnecting all sockets`);\n connections.forEach((socketID) => {\n this.print(`Disconnecting socket: ${socketID}`);\n self.namespace.connected[socketID].disconnect();\n });\n\n this.print(`Removing listeners`);\n this.namespace.removeAllListeners();\n callback(this.endpoint);\n }", "reconnect() {\n\t\tsetTimeout(() => {\n\t\t\tif (this.ws.readyState <= WebSocket.OPEN) return;\n\n\t\t\tconsole.log(\"Trying to reconnect\", this.ws.readyState); // debug\n\n\t\t\t// Connect to the WebSocket server.\n\t\t\tthis.connect();\n\n\t\t\t// Ensure that the connection has been made.\n\t\t\tthis.reconnect();\n\t\t}, 3000);\n\t}", "_resetForNewReconnection() {\n this[STATE].shouldReconnect = true;\n this[STATE].reconnectDelay = Constants.RECONNECT_DELAY_MS;\n this[STATE].reconnectAttempts = 0;\n }", "onDisconnect(client){\n\t\tthis.clients.splice(this.clients.indexOf(client),1);\n\t\tif(this.player1 == client) this.player1 = null;\n\t\tif(this.player2 == client) this.player2 = null;\n\t\tif(this.player1 == null || this.player2 == null){\n\t\t\tGame.reset();\n\t\t\tthis.broadcastStatus();\n\t\t}\n\t}", "function DisconnectFromDevice()\n{\n SSHClient.Disconnect()\n return true\n}", "onChromeVoxDisconnect_() {\n this.port_ = null;\n this.log_('onChromeVoxDisconnect', chrome.runtime.lastError);\n }", "teardownWebsocket() {\n if (this.websocket !== undefined) {\n this.websocket.removeAllListeners('open');\n this.websocket.removeAllListeners('close');\n this.websocket.removeAllListeners('error');\n this.websocket.removeAllListeners('message');\n this.websocket = undefined;\n }\n }", "deregister() {\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }", "function detachDevice(deviceId, client, jwt) {\n // [START detach_device]\n const detachTopic = `/devices/${deviceId}/detach`;\n console.log(`Detaching: ${detachTopic}`);\n let detachPayload = '{}';\n if (jwt && jwt !== '') {\n detachPayload = `{ 'authorization' : ${jwt} }`;\n }\n\n client.publish(detachTopic, detachPayload, {qos: 1}, err => {\n if (!err) {\n shouldBackoff = false;\n backoffTime = MINIMUM_BACKOFF_TIME;\n } else {\n console.log(err);\n }\n });\n // [END detach_device]\n}", "onReConnection(listener) {\n this.on('re-connection', listener);\n }", "leavePlayerChannel() {\n this.sendMessage('/playerchannel leave');\n }", "static reconnect_printer() {\n // Send request\n WS.ws.send(COM.payloader(\"RCN\"))\n\n // Wait 1s before checking if connection is established\n setTimeout(() => {\n this.check_connected();\n }, 1000);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if agent is tracking dna. If not, will try to send a FailureResult back to IPC Returns _ipcHasTrack() result
_hasTrackOrFail (agentId, dnaAddress, requestId) { // Check if receiver is known if (this._ipcHasTrack(agentId, dnaAddress)) { log.t(' oooo HasTrack() CHECK OK for (agent) "' + agentId + '" -> (DNA) "' + dnaAddress + '"') return true } // Send FailureResult back to IPC log.e(' #### HasTrack() CHECK FAILED for (agent) "' + agentId + '" -> (DNA) "' + dnaAddress + '"') this._ipcSend('json', { method: 'failureResult', dnaAddress: dnaAddress, _id: requestId, toAgentId: agentId, errorInfo: 'This agent is not tracking DNA: "' + dnaAddress + '"' }) // Done return false }
[ "hasTrack(aTrack){\r\n //const track = this.getTracks().find((tr) => tr.getName() === aTrack.getName());\r\n return this.tracks.includes(aTrack);//track !== undefined;\r\n }", "hasAudioTrack(trackId) {\r\n return this.soundMeta.has(trackId) && this.soundMeta.get(trackId).length > 0;\r\n }", "function askDNTConfirmation() {\n var r = confirm(\"La signal DoNotTrack de votre navigateur est activé, confirmez vous activer \\\n la fonction DoNotTrack?\")\n return r;\n }", "function isYoastAnalyticsObjectAvailable() {\n if (typeof __gaTracker !== 'undefined') {\n return true;\n }\n return false;\n}", "isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }", "function checkStatus() {\n if (supportsAvif !== null && supportsWebp !== null) {\n showOverlay();\n return;\n }\n }", "function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }", "function checkIfMyTurn() {\n console.log(\"in checkIfMyTurn...\");\n if (vm.currentGame.gameInProgress) {\n if ((vm.playerTeam === \"x\") && (vm.currentGame.turn) && (vm.playerName === vm.currentGame.player1) ||\n (vm.playerTeam === \"o\") && (!vm.currentGame.turn) && (vm.playerName === vm.currentGame.player2)){\n return true;\n }\n }\n return false;\n }", "function processTracker() {\n\n\tvar success = true;\n\tconsole.log(\"\\n2. Validating exported metadata\");\n\t\n\t//Configure sharing and metadata ownership\n\tconfigureSharing();\n\tconfigureOwnership();\n\n\t//Remove users from user groups\n\tclearUserGroups();\n\t\t\n\t//Make sure the \"default defaults\" are used\n\tsetDefaultUid();\n\t\n\t//Make sure we don't include orgunit assigment in datasets or users\n\tclearOrgunitAssignment();\n\t\n\t//Verify that all data elements referred in indicators, validation rules,\n\t//predictors are included\n\tif (!validateDataElementReference()) success = false;\n\n\t//Verify that all program indicators referred to in indicators and predictors are included\n\tif (!validateProgramIndicatorReference()) success = false;\n\n\t//Remove invalid references to data elements or indicators from groups\n\t//Verify that there are no data elements or indicators without groups\n\tif (!validateGroupReferences()) success = false;\t\n\t\n\t//Verify that favourites only use relative orgunits\n\tif (!validateFavoriteOrgunits()) success = false;\n\t\n\t//Verify that favourites only use indicators\n\tif (!validateFavoriteDataItems()) success = false;\n\t\n\t//Verify that no unsupported data dimensions are used\n\tif (!validateFavoriteDataDimension()) success = false;\n\n\t//Verify that data sets with section include all data elements\n\tif (!validationDataSetSections()) success = false;\n\n\n\t/** CUSTOM MODIFICATIONS */\n\tif (currentExport.hasOwnProperty(\"_customFuncs\")) {\n\t\tfor (var customFunc of currentExport._customFuncs) {\n\t\t\tvar func = new Function(\"metaData\", customFunc);\n\t\t\tfunc(metaData); \n\t\t}\n\t}\n\t\n\tif (success) {\n\t\tconsole.log(\"✔ Validation passed\");\n\t\tsaveTracker();\n\t}\n\telse {\n\t\tconsole.log(\"\");\n\t\tvar schema = {\n\t\t\tproperties: {\n\t\t\t\tcontinue: {\n\t\t\t\t\tdescription: \"Validation failed. Continue anyway? (yes/no)\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdefault: \"no\",\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tif(args.ignoreerrors)\n\t\t{\n\t\t\tsaveTracker();\n\t\t} else {\n\t\t\tprompt.get(schema, function (err, result) {\t\n\t\t\t\tif (result.continue == \"yes\") saveTracker();\n\t\t\t\telse cancelCurrentExport();\n\t\t\t});\n\t\t}\n\t}\n}", "function beginReporting()\n{\n if (site.serverActivity())\n {\n alert(MSG_CantRun_FileActivity);\n return false;\n }\n return true;\n}", "async evaluatebadDevice() {\n this.badDevice = await DeviceDetails.badDevice();\n if (this.badDevice) {\n this.soundStatus = false;\n }\n }", "function checkTuneGeniePlayerState(e) {\n\t\t\tif (e === true) {\n\t\t\t\tlog('TuneGenie Player is streaming.');\n\t\t\t\tme.start();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tlog('TuneGenie Player has stopped.');\n\t\t\tme.stop();\n\t\t\treturn false;\n\t\t}", "function CheckActiveXAlive()\n{\n var res = true;\n var obj = GE(AxID);\n if (obj != null)\n {\n try\n {\n //if (obj.IsAlive == 0)\n {\n res = false;\n }\n }\n catch (e)\n {}\n }\n return res;\n}", "shouldQuarantine() {\n if (this.passengers.find(passenger =>\n passenger.isHealthy === false )) {\n return true\n } else {\n return false\n }\n }", "function isUniversalAnalyticsObjectAvailable() {\n if (typeof ga !== 'undefined') {\n return true;\n }\n return false;\n}", "checkFailure() {\n\t\tif(this.failureDetector.checkFailure()) {\n\t\t\tthis.requestDisconnect();\n\t\t}\n\t}", "async function isSimulatorAppRunningAsync() {\n try {\n const zeroMeansNo = (await osascript.execAsync('tell app \"System Events\" to count processes whose name is \"Simulator\"')).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n }\n catch (error) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n return true;\n}", "function userHasBeenReferredByPartnerWhoSuppliesPromocodes() {\n for (var i = 0; i < referralPartnersWhoSupplyPromocodes.length; i++) {\n if (linkshareReferrerID == referralPartnersWhoSupplyPromocodes[i]) { // If the referrer is in the list of referral partners who supply voucher codes\n console.log('The user has been referred by a partner who supplies promocodes');\n return true;\n break;\n }\n }\n console.log('The user has not been referred by a partner who supplies coupons.');\n return false; // If the user has not been referred by a partner who supplies coupons, then return false. This means the pixel can still fire.\n }", "function doesNotWantExternalActivity () {\n alert(\"Student does not want the external activity\") ;\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=NO\");\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector,\n processNextProblemResult)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CREATE THE BIDIMENSIONAL ARRAY FOR THE LAYOUT
function create_grid(){ // Create new Array the size of the number of pages LAYOUT_GRID = new Array(_PAGES); for(i=0; i<_PAGES; i++){ LAYOUT_GRID[i] = new Array(NUM_OF_LI_PER_ROW[i]); } }
[ "initialize2dArray(numCols){\n let arr = [];\n for(let i = 0; i < numCols; i++){\n arr.push(new Array(8));\n }\n return arr;\n }", "function bidimensionale(myArray){\r\n var n = Math.sqrt(myArray.length);\r\n var resarray = [];\r\n var row = [];\r\n for (var i = 0; i < myArray.length; i++){\r\n row[row.length] = myArray[i];\r\n if (row.length == n){\r\n resarray.push(row);\r\n row = [];\r\n }\r\n }\r\n return resarray;\r\n}", "function create2dArray(ids_array, ansType_array) {\n var twoD_array = [];\n \n for(var i = 0; i < qid_len; i++) {\n twoD_array.push([ids_array[i], ansType_array[i]]);\n }\n \n return twoD_array;\n}", "function createGameStageArray(){\n let borderSize = getBoardSize();\n let rows = borderSize[0];\n let cols = borderSize[1];\n for(let row=0;row<rows;row++){\n gameStageArch[row] = [];\n for(let col=0;col<cols;col++){\n gameStageArch[row][col] = false;\n }\n }\n}", "function createBrickWall(){\n for(let i=0; i < brickRows; i++){\n brickWall[i]=[];\n for(let j=0; j<brickCols; j++){\n const x = i*(brick.w + brick.padding) +brick.offsetX;\n const y = j*(brick.h + brick.padding) +brick.offsetY;\n brickWall[i][j] = {x, y, ...brick};\n }\n }\n}", "function createAbstractGrid(){\n for(var i = 0;i < width; i++){\n BoardMethods.grid.push([]);\n BoardMethods.grid2.push([]);\n\n for(var i2 = 0;i2 < height; i2++){\n BoardMethods.grid[i].push(false);\n BoardMethods.grid2[i].push(false);\n }\n }\n }", "function initbricks() {\n bricks = new Array(NROWS);\n for (i=0; i < NROWS; i++) {\n bricks[i] = new Array(NCOLS);\n for (j=0; j < NCOLS; j++) {\n bricks[i][j] = 1;\n }\n }\n }", "setBackgroundSizeConfig() {\n let backgroundSizeConfig = [];\n for (let xAxisIndex = 0; xAxisIndex < 4; xAxisIndex++) {\n for (let yAxisIndex = 0; yAxisIndex < 3; yAxisIndex++) {\n backgroundSizeConfig.push((xAxisIndex * this.blockWidth) + 'px ' + (yAxisIndex * this.blockHeight) + 'px ');\n }\n }\n return backgroundSizeConfig;\n }", "assignImgsToCols() {\n let numOfCols = this.calculateCols();\n \n // Init cols\n let cols = [];\n let i;\n for (i = 0; i < numOfCols; i += 1) {\n cols.push({key: i, imgs: []});\n }\n\n let {imgs} = this.props;\n \n // Init colHeights\n let colHeights = [];\n for (i = 0; i < cols.length; i+=1) {\n colHeights[i] = 0;\n };\n\n // Add image to shortest column\n if (cols.length > 0) {\n imgs.forEach((img) => {\n let col = this.findShortestColumn(colHeights);\n cols[col].imgs.push(img);\n let {dimensions} = img.props.img.value;\n colHeights[col] += dimensions.small.maxHeight;\n });\n }\n \n return cols;\n }", "function initCellArray() {\n var gridSize = getGridSize();\n cellArray = []\n for(var i = 0; i < gridSize; i++) {\n var gridRow = []\n for(var j = 0; j < gridSize; j++) {\n gridRow.push({\"free\": true, \"letter\": \"\"})\n }\n cellArray.push(gridRow)\n }\n }", "function createGrid() {\n for (i = 1; i < 1090; i++) {\n var thisDiv = document.createElement('div');\n thisDiv.id = i;\n thisDiv.className = \"col-1-25\";\n container.appendChild(thisDiv);\n }\n createColumns();\n colourGrid();\n }", "function convert4x4(array) {\n currentIndex = 0;\n var newArray = [[null,null,null,null],[null,null,null,null],[null,null,null,null],[null,null,null,null]];\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 4; j++) {\n newArray[i][j] = array[currentIndex];\n currentIndex++;\n }\n }\n return newArray;\n }", "function generateLayoutObject (layoutObjName)\n{\n\tvar tempObj = new SE_Obj ();\n\tvar layout = doAction ('DATA_GETHEADERS', 'GetRow', true, 'ObjectName', layoutObjName).split('\\t');\n\tvar layoutObj = new Array();\n\tfor (var z = 0; z < layout.length; z++)\n\t{\n\t\tif (layout[z])\n\t\t{\n\t\t\tvar test = doActionBDO (\"MPEA_BDO_DESERIALIZE\", \"SerializedBdo\", layout[z]);\n\t\t\tlayoutObj [test.name] = test;\n\t\t}\n\t}\n\treturn layoutObj;\n}", "calculateLayoutSizes() {\n const gridItemsRenderData = this.grid.getItemsRenderData();\n this.layoutSizes =\n Object.keys(gridItemsRenderData)\n .reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: [gridItemsRenderData[cur].width, gridItemsRenderData[cur].height] })), {});\n }", "function createClickableThings(){\n var clickables = new Array(gridDimension);\n \n for (var i = 0; i < gridDimension; i++){\n clickables[i] = new Array(gridDimension);\n for (var j = 0; j < gridDimension; j++){\n //store top left corner of clickable square area of width gridCellSize\n xcoord = i*gridCellSize - (gridCellSize/2) + canvasBorder;\n ycoord = j*gridCellSize - (gridCellSize/2) + canvasBorder;\n clickables[i][j] = [xcoord,ycoord];\n }\n }\n \n return clickables\n}//createClickableThings", "function array6x6() {\n let m = Array.from({length: 6}, e => Array(6).fill({key:true}));\n // let m = Array.from({length: 6}, e => Array(6).fill(0)); \n return m \n }", "function createFractionProblem2DArray()\n{\n\tfor(var denom = 1; denom <= highestDenominator[highestLevel]; denom++){ \n\t\tfractionProblems[denom] = new Array();\n\t\t\n\t\tfor(var numer = 0; numer <= (denom * baseboardMaxPotential); numer++) // this stops fraction being created that are larger than the baseboard\n\t\t{ \t\t\t\n\t\t\tfractionProblems[denom][numer] = new ProblemObject(numer, denom); \n\t\t\t\n\t\t\tif(numer == 0){ \n\t\t\t\tfractionProblems[denom][numer].probability = .3; // sets lower probabilities for 0 in the numerator\n\t\t\t} else if (numer == denom){ \n\t\t\t\tfractionProblems[denom][numer].probability = .3; // sets lower probabilities for all fractions = 1\n\t\t\t} else if (numer == 1){\n\t\t\t\tfractionProblems[denom][numer].probability = .6; // sets high probability for when numer = 1\n\t\t\t} else {\n\t\t\t\tfractionProblems[denom][numer].probability = .5; // the rest are defaulted to .5 probability\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}", "function makeCVNArray() {\n for (var i = 0; i < itemArray.length; i++) {\n clickedArray.push(itemArray[i].clicked);\n viewedArray.push(itemArray[i].viewed);\n nameArray.push(itemArray[i].title);\n }\n }", "function slice () {\n if (settings.vshrink || settings.hshrink) {\n var slices = {};\n if (settings.vshrink) {\n slices['rows'] = getRows();\n }\n if (settings.hshrink) {\n slices['cols'] = getCols();\n }\n return slices;\n }\n else {\n return null;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HashRegistryValue hashes the given registry value
function HashRegistryValue(registryValue) { return HashAll(registryValue.tweak, encodeString(registryValue.data), encodeUint8(registryValue.revision)); }
[ "static hash(domain, types, value) {\n return (0, index_js_2.keccak256)(TypedDataEncoder.encode(domain, types, value));\n }", "static hashStruct(name, types, value) {\n return TypedDataEncoder.from(types).hashStruct(name, value);\n }", "function hashValues(map) {\n\t\tvar vals = [];\n\t\tfor (var o in map) {\n\t\t\tvals.push(map[o]);\n\t\t}\n\t\tvar valString = vals.join('###');\n\t\tvar hash = CryptoJS.SHA256(valString).toString(CryptoJS.enc.Base64);\n\t\treturn hash;\n\t}", "hashStruct(name, value) {\n return (0, index_js_2.keccak256)(this.encodeData(name, value));\n }", "function hash(uuid) {\n var hash = 0, i, chr;\n if (uuid.length === 0) return hash;\n for (i = 0; i < uuid.length; i++) {\n chr = uuid.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n if (hash < 0) {\n hash += 1;\n hash *= -1;\n }\n return hash % constants.localStorage.numBins;\n}", "function hash(obj) {\n return JSON.stringify(obj)\n}", "static encode(domain, types, value) {\n return (0, index_js_4.concat)([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }", "function hashMember(name, value, configuration) {\n if (ok(value, tyArray)) {\n var code = 0;\n /*jslint plusplus: true */\n for (var i = 0; i < value.length; i++) {\n code = code + hashPrimitiveMember(name, value[i], configuration);\n }\n return code;\n }\n return hashPrimitiveMember(name, value, configuration);\n }", "static async hash(data) {\n if (! (\"subtle\" in window.crypto)) {\n return undefined;\n }\n\n let input = new TextEncoder().encode(data);\n let hash = await window.crypto.subtle.digest(\"SHA-512\", input);\n let bytes = new Uint8Array(hash);\n\t let hex = Array.from(bytes).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n\t return hex.slice(0, 32);\n }", "function actualRehashValues() {\n var oldBuckets = currentHashTable.buckets;\n\n actualRehash();\n\n currentHashTable.slots = slots;\n currentHashTable.size = size;\n currentHashTable.buckets = buckets;\n\n //console.log(JSON.stringify(currentHashTable, null, 4));\n\n oldBuckets.map((linkedList) => {\n var node = linkedList.getHead();\n //console.log(node);\n\n while(node !== null) {\n const {key, value} = node.getValue();\n this.set(key, value, false);\n\n node = node.getNext();\n }\n });\n }", "static setSubhash (key, val) {\n\t\tconst nxtHash = Hist.util.setSubhash(window.location.hash, key, val);\n\t\tHist.cleanSetHash(nxtHash);\n\t}", "set(key, value){\n //1. get hash\n const hash = this.hash(key) //creating a hash\n\n //2. make value entry\n const entry = {[key]: value};\n\n //3. set the entry to the hash value in the map\n //3.1 check to see if there is hash there, if not put a LL in\n if(!this.map[hash]){\n this.map[hash] = new LinkedList();\n }\n\n //add the entry\n this.map[hash].add(entry); //add makes add(entry) node the new head\n }", "function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}", "function hashFormData(data) {\n\n var s = data.session_id + '^' +\n MD5HASH + '^' +\n data.x_amount + '^' +\n data.timestamp + '^' +\n dpm.formDataString(data);\n\n return crypto.createHash('md5').update(s).digest('hex');\n }", "function hashParams(params) {\n const hashedParams = {};\n Object.keys(params).map((key) => {\n hashedParams[key] = hash.sha256().update(params[key]).digest('hex');\n });\n return hashedParams;\n}", "getHashCode() {\n let hash = this._m[0] || 0;\n for (let i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this._m[i] || 0);\n }\n return hash;\n }", "function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}", "function rehashWrapper() {\n function actualRehash() {\n slots = slots * 2;\n size = 0;\n buckets = createEmptyBuckets(slots);\n }\n\n /**\n * we need to save the reference to old buckets to iterate over them\n * and setting to new loactions\n */\n function actualRehashValues() {\n var oldBuckets = currentHashTable.buckets;\n\n actualRehash();\n\n currentHashTable.slots = slots;\n currentHashTable.size = size;\n currentHashTable.buckets = buckets;\n\n //console.log(JSON.stringify(currentHashTable, null, 4));\n\n oldBuckets.map((linkedList) => {\n var node = linkedList.getHead();\n //console.log(node);\n\n while(node !== null) {\n const {key, value} = node.getValue();\n this.set(key, value, false);\n\n node = node.getNext();\n }\n });\n }\n\n actualRehashValues.call(this);\n }", "hashCode () {\n\n /* x hash code. */\n const xstr = String(this._x);\n const len0 = xstr.length;\n let xhsh = 0;\n for (let i = 0; i < len0; ++i) {\n xhsh = Math.imul(31, xhsh) ^ xstr.charCodeAt(i) | 0;\n }\n xhsh >>>= 0;\n\n /* y hash code. */\n const ystr = String(this._y);\n const len1 = ystr.length;\n let yhsh = 0;\n for (let j = 0; j < len1; ++j) {\n yhsh = Math.imul(31, yhsh) ^ ystr.charCodeAt(j) | 0;\n }\n yhsh >>>= 0;\n\n /* Composite hash code. */\n let hsh = -2128831035;\n hsh = Math.imul(16777619, hsh) ^ xhsh;\n hsh = Math.imul(16777619, hsh) ^ yhsh;\n return hsh;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
perform the eye dropper for the surrounding art
function surroundingEyeDropper(evt) { // only do this if the eye dropper is the selected tool if (document.getElementById("eyeDropper").checked) { // figure out which canvas you're in and get its context var myCanvas = evt.target; var myContext = myCanvas.getContext("2d"); // get click coordinates in this canvas var dropperCoords = myCanvas.getBoundingClientRect(); var mouseX = evt.clientX - dropperCoords.left; var mouseY = evt.clientY - dropperCoords.top; // do not need to adjust for zoom/pan, because the function that reads // the color data uses the current context, not the pre-zoom/pan context // get the color at that pixel in that region var color = getColorAt(myContext, mouseX, mouseY); // set this as the color choice setColorChoiceInHTML(color); } // else do nothing }
[ "function moveEye(target){\n\t\tvar referencePt1;\n\t\tvar referencePt2;\n\t\tvar cos = Math.cos(angle);\n\t\tvar sin = Math.sin(angle);\n\t\tvar xDist;\n\t\tvar yDist;\n\n\t\tif (target == \"guide\"){ //if not on the eye itself them moves to the guide object\n\t referencePt1 = (pupilGuide.offsetLeft * cos - 0 * sin);\n\t referencePt2 = (pupilGuide.offsetTop * sin + 0 * cos);\n\t xDist = curMouseX - adXCenter;\n\t yDist = curMouseY - adYCenter;\n\t\t} else if (target == \"random\"){\n\t referencePt1 = randRange (-30, 30);\n\t referencePt2 = randRange (-30, 30);\n\t xDist = randRange (0, 400);\n\t yDist = randRange (0, 400);\n\t\t} else {\n\t referencePt1 = curMouseX - 150;\n\t referencePt2 = curMouseY - 125;\n\t xDist = 0;\n\t yDist = 0;\n\t\t}\n\n\t\tTweenLite.to(eyeWhite, 0.5, {\n \tx: (referencePt1 * 0.16),\n \ty: (referencePt2 * 0.16)\n \t});\n \n TweenLite.to(iris, 0.5, {\n\t \tx: referencePt1 * 0.6, // * 0.8 to keep it slightly away from the edge of the white\n\t \ty: referencePt2 * 0.6\n\t });\n \n\t //This is the sleight skew effect on the eye as it looks to the side\n\t TweenLite.to(iris, 0.5, {\n \t \trotationY: referencePt1/2,\n \t \trotationX: -referencePt2/2\n \t});\n \n //doing a sleight zoom on the pupil in accordance with how far away the mouse is.\n var mouseDistance = Math.sqrt((xDist * xDist) + (yDist * yDist));\n if (mouseDistance < 500){\n\t \tTweenLite.to(pupil, 0.2, {\n\t\t scaleX:1 - (mouseDistance/1500),\n\t\t scaleY:1 - (mouseDistance/1500)});\n }\n if (mouseDistance < 300){\n\t \tTweenLite.to(iris, 0.2, {\n\t\t scaleX:1 - (mouseDistance/4000),\n\t\t scaleY:1 - (mouseDistance/4000)});\n }\n\n }", "function mouseReleased(){\n elastic.fly();\n}", "function draw() {\n background (50, 255, 50);\n\n//shape outline\n noStroke()\n\n//kermit image\n imageMode(CENTER);\n image(kermitImage, mouseX, mouseY);\n\n\n // covid 19 movement\n covid19.x = covid19.x + covid19.vx;\n covid19.y = covid19.y + covid19.vy;\n\n if (covid19.x > width) {\n covid19.x = 0;\n covid19.y = random(0,height);\n }\n\n //covid 19 growth\n if (covid19.x < width/1.002){\n covid19.size = covid19.size + 3;\n }\n else {\n covid19.size = 100;\n }\n\n // covid 20 movement\n covid20.x = covid20.x + covid20.vx;\n covid20.y = covid20.y + covid20.vy;\n\n if (covid20.x > width) {\n covid20.x = 0;\n covid20.y = random(0,height);\n }\n\n //covid 20 growth\n if (covid20.x < width/1.002){\n covid20.size = covid20.size + 1;\n }\n else {\n covid20.size = 100;\n }\n\n //user movement\n user.x = mouseX;\n user.y = mouseY;\n\n // check for bumping covid19\n let d = dist(user.x,user.y,covid19.x,covid19.y);\n if (d < covid19.size/2 + user.size/2) {\n noLoop();\n }\n\n // display covid 19\n fill(covid19.fill.r, covid19.fill.g, covid19.fill.b);\n ellipse(covid19.x, covid19.y, covid19.size);\n\n // display covid 20\n fill(covid20.fill.r, covid20.fill.g, covid20.fill.b);\n ellipse(covid20.x, covid20.y, covid20.size);\n\n // display user\n fill(user.fill);\n square(user.x, user.y, user.size);\n\n}", "function displayEliminatePlantIconWithCursor(e) {\n if ( !ambientMode ) { \n var displayIcon = false;\n for ( var i=0; i<plants.length; i++ ) {\n var p = plants[i];\n if ( p.isAlive || (!p.hasCollapsed && !p.hasBeenEliminatedByPlayer) ) {\n for ( var j=0; j<p.segments.length; j++) {\n var s = p.segments[j];\n var xDiffPct1 = pctFromXVal( s.ptE1.cx ) - mouseCanvasXPct;\n var yDiffPct1 = pctFromYVal( s.ptE1.cy ) - mouseCanvasYPct;\n var distancePct1 = Math.sqrt( xDiffPct1*xDiffPct1 + yDiffPct1*yDiffPct1 );\n var xDiffPct2 = pctFromXVal( s.ptE2.cx ) - mouseCanvasXPct;\n var yDiffPct2 = pctFromYVal( s.ptE2.cy ) - mouseCanvasYPct;\n var distancePct2 = Math.sqrt( xDiffPct2*xDiffPct2 + yDiffPct2*yDiffPct2 );\n var selectRadiusPct = selectRadius*100/canvas.width;\n if ( distancePct1 <= selectRadiusPct*2 || distancePct2 <= selectRadiusPct*2 ) {\n displayIcon = true;\n }\n }\n }\n }\n if ( displayIcon ) {\n var xo = selectRadius*0.06; // x offset\n var yo = selectRadius*0.1; // y offset\n ctx.fillStyle = \"rgba(232,73,0,0.5)\";\n ctx.strokeStyle = \"rgba(232,73,0,1)\";\n //circle\n ctx.beginPath();\n ctx.lineWidth = 1;\n ctx.arc( xValFromPct(mouseCanvasXPct), yValFromPct(mouseCanvasYPct-yo), selectRadius, 0, 2*Math.PI );\n ctx.fill();\n ctx.stroke();\n //bar\n ctx.beginPath();\n ctx.lineWidth = selectRadius*0.3;\n ctx.lineCap = \"butt\";\n ctx.moveTo( xValFromPct(mouseCanvasXPct-xo), yValFromPct(mouseCanvasYPct-yo) );\n ctx.lineTo( xValFromPct(mouseCanvasXPct+xo), yValFromPct(mouseCanvasYPct-yo) );\n ctx.fill();\n ctx.stroke();\n }\n }\n}", "function drawRightEye() {\n const x = ($canvas.width / 5) * 2 - 50;\n const y = $canvas.height / 8 + 50;\n const radius = 10;\n const sA = 0;\n const eA = 2 * Math.PI;\n\n ctx.beginPath();\n ctx.arc(x, y, radius, sA, eA);\n ctx.fillStyle = 'black';\n ctx.fill();\n ctx.strokeStyle = 'white';\n ctx.stroke();\n}", "function noWrap()\r\n\t {\r\n\t\timageContext.lineTo(newX, newY);\r\n\t\tturtle.pos.x = newX;\r\n\t\tturtle.pos.y = newY;\r\n\t\tdistance = 0;\r\n\t }", "function eye( transNum, col_x, col_y, col_z ) {\n push();\n\n //white of eyes\n strokeWeight(4);\n fill(255);\n //move to center of body\n translate( bodyArray[1] * transNum, bodyArray[1] * transNum );\n ellipse( 0, 0, bodyArray[1] * 0.33, bodyArray[1] * 0.33 );\n\n //iris\n strokeWeight(2);\n fill( col_x, col_y, col_z );\n ellipse( 0, 0, 20 );\n //pupul\n fill(0);\n ellipse( 0, 0, 8 );\n\n pop();\n\n\n}", "function drawLeftEye() {\n const x = $canvas.width / 5;\n const y = $canvas.height / 8 + 50;\n const radius = 10;\n const sA = 0;\n const eA = 2 * Math.PI;\n\n ctx.beginPath();\n ctx.arc(x, y, radius, sA, eA);\n ctx.fillStyle = 'black';\n ctx.fill();\n ctx.strokeStyle = 'white';\n ctx.stroke();\n}", "function eyeBlink(x,y,eyeSize,pupilSize,color_type){\n\t\n //draw eyelid\n fill(color_type);\n ellipse(x,y,eyeSize,eyeSize);\n \n}", "function setup() {\n\n // Set up the canvas and makes the background into a green colour - Meghan's favorite color\n\n createCanvas(500,500);\n noStroke();\n background(0,190,0);\n fill(0,220,0);\n rect(50,50,400,400);\n fill(0,260,0)\n rect(100,100,300,300);\n\n//Creating the Hair in the Back of the head using Ellipses\nnoStroke();\nfill(89,40,0)\nellipse(180,300,100,300)\nellipse(320,300,100,300)\n\n//Creating the Body and Sweater\n noStroke();\n fill(0,0,0);\n ellipse(250,500,300,400);\n fill(255,216,191);\n\n //Creating the Head and Round Cheeks\n ellipseMode(CENTER);\n ellipse(250,250,200,200);\n ellipse(220,290,150,150);\n ellipse(280,290,150,150);\n\n //One last step: Creating the Sweater Collar\n fill(0,0,0);\n ellipse(250,356,250,50);\n\n//Creating the Hair over my face\n fill(89,40,0)\n ellipse(250,170,185,70)\n\n // Draw the beautiful long eyelashes\n\n stroke(0);\n line(190,230,160,230)\n line(190,230,160,220)\n line(290,230,340,230)\n line(290,230,340,220)\n\n // Draw the white backgrounds of the eyes\n noStroke();\n fill(255);\n ellipse(200,225,50,50);\n ellipse(300,225,50,50);\n\n\n // Draw the pupils, making them green like the real Meghan! And crossed, a unique little quirk of Meghan :)\n fill(0,97,13);\n noStroke();\n ellipse(215,225,20,20);\n ellipse(300,225,20,20);\n\n // Draw the nose\n\n // Nose colour\n fill(255,175,135);\n\n //Triangle as the nose\n triangle(250,230,230,290,270,290);\n\n // Creating A lovely smile!\n //Create the teeth and lip - never a fan of make-up, so thin lip!\n fill(255);\n stroke(255,120,120);\n\n //Creating the curved smile\n curve(250,200,300,310,200,310,100,100);\n\n}", "function eliminatePlants( e, plant ) {\n if ( !ambientMode ) {\n for ( var i=0; i<plants.length; i++ ) {\n var p = plants[i];\n if ( plantsAreBeingEliminated && ( p.isAlive || (!p.hasCollapsed && !p.hasBeenEliminatedByPlayer) ) ) {\n for ( var j=0; j<p.segments.length; j++) {\n var s = p.segments[j];\n var xDiffPct1 = pctFromXVal( s.ptE1.cx ) - mouseCanvasXPct;\n var yDiffPct1 = pctFromYVal( s.ptE1.cy ) - mouseCanvasYPct;\n var distancePct1 = Math.sqrt( xDiffPct1*xDiffPct1 + yDiffPct1*yDiffPct1 ); // distance from seg ext pt 1\n var xDiffPct2 = pctFromXVal( s.ptE2.cx ) - mouseCanvasXPct;\n var yDiffPct2 = pctFromYVal( s.ptE2.cy ) - mouseCanvasYPct;\n var distancePct2 = Math.sqrt( xDiffPct2*xDiffPct2 + yDiffPct2*yDiffPct2 ); // distance from seg ext pt 2\n var selectRadiusPct = selectRadius*100/canvas.width;\n if ( distancePct1 <= selectRadiusPct || distancePct2 <= selectRadiusPct ) {\n s.ptE1.px += distancePct1 > distancePct2 ? 10 : -10; // impact burst effect\n p.energy = p.energy > energyStoreFactor*-1 ? energyStoreFactor*-1 : p.energy; // drops plant energy\n killPlant(p);\n for (var k=0; k<p.segments.length; k++) {\n var s2 = p.segments[k];\n s2.ptE1.mass = s2.ptE2.mass = 15; // increases plant mass for faster collapse\n if (!s2.isBaseSegment) {\n removeSpan(s2.spCdP.id); // downward (l to r) cross span to parent\n removeSpan(s2.spCuP.id); // upward (l to r) cross span to parent\n }\n removeSpan(s2.spCd.id); // downward (l to r) cross span\n removeSpan(s2.spCu.id); // upward (l to r) cross span\n }\n p.hasBeenEliminatedByPlayer = true;\n }\n }\n }\n }\n }\n}", "fountain() {\n // draws the foundation of the fountain\n stroke(51, 54, 51);\n strokeWeight(4);\n fill(81, 82, 81);\n // can I use the matrix and rotation + translation to pull this off in a loop?\n rect(width / 2 - this.pxl, height / 2 - this.pxl * 2, this.pxl * 2, this.pxl);\n rect(width / 2 - this.pxl * 2, height / 2 - this.pxl, this.pxl, this.pxl * 2);\n rect(width / 2 - this.pxl, height / 2 + this.pxl, this.pxl * 2, this.pxl);\n rect(width / 2 + this.pxl, height / 2 - this.pxl, this.pxl, this.pxl * 2);\n // draws the water for the fountain\n stroke(28, 111, 166);\n fill(38, 150, 224);\n rect(width / 2 - this.pxl, height / 2 - this.pxl, this.pxl * 2, this.pxl * 2);\n }", "function draw_detector() {\n ctx.beginPath()\n ctx.strokeStyle = 'black'\n ctx.setLineDash([0, 0])\n ctx.rect(DIFF_PATTERN.x, DIFF_PATTERN.y, DIFF_PATTERN.width, DIFF_PATTERN.height)\n ctx.stroke()\n\n ctx.beginPath()\n ctx.arc(DIFF_PATTERN.x + (DIFF_PATTERN.width / 2), SECOND_XRAY_Y, 3, 0, 2 * Math.PI)\n ctx.fill()\n\n deltaPos = {\n x: passthroughCoords.x - refractedCoords.x,\n y: passthroughCoords.y - refractedCoords.y\n }\n\n ctx.beginPath()\n ctx.arc(DIFF_PATTERN.x + (DIFF_PATTERN.width / 2) - deltaPos.x, SECOND_XRAY_Y - deltaPos.y, 3, 0, 2 * Math.PI)\n\n //Arrow between origin spot and diffracted spot\n //canvas_arrow(ctx,DETECTOR_POSITION + (DETECTOR_WIDTH/2) - 2, SECOND_XRAY_Y - 2 , DETECTOR_POSITION + (DETECTOR_WIDTH/2) - deltaPos.x + 5, SECOND_XRAY_Y - deltaPos.y + 5)\n \n ctx.stroke()\n\n ctx.font = \"bold 16px Verdana\"\n ctx.fillText(\"Diffraction Pattern\", DIFF_PATTERN.x + (0.5 * DIFF_PATTERN.width) - 90, 50)\n \n }", "function swingLeftRight(ctx) \r\n{\r\n\tctx.beginPath();\r\n\tctx.moveTo(eye1_x, eye1_y);\r\n\tctx.arc(eye1_x, eye1_y, eye_radius, 0, Math.PI*2);\r\n\tctx.fill();\r\n\r\n\tctx.beginPath();\r\n\tctx.moveTo(eye2_x, eye2_y);\r\n\tctx.arc(eye2_x, eye2_y, eye_radius, 0, Math.PI*2);\r\n\tctx.fill();\r\n\r\n\teye1_x += eye_speed;\r\n\teye2_x += eye_speed;\r\n\t\r\n\tif(eye1_x >= eye1_centerx + 30)\r\n\t\teye_speed = -eye_speed;\r\n\tif(eye1_x <= eye1_centerx - 30)\r\n\t\teye_speed = -eye_speed;\r\n}", "function kirbyEyes(kirbyTorso) {\r\n var kirbyEyeX = 80;\r\n var kirbyEyeY = 0;\r\n\r\n var kirbyEyes = mat3.create();\r\n mat3.rotate(kirbyEyes, kirbyEyes, (-mouthSlider - 10) * Math.PI / 180);\r\n mat3.multiply(kirbyEyes, kirbyTorso, kirbyEyes);\r\n setTran(kirbyEyes);\r\n\r\n context.beginPath();\r\n context.fillStyle = \"#000000\";\r\n context.ellipse(kirbyEyeX, kirbyEyeY, 10, 20, 0, 0, Math.PI * 2);\r\n context.fill();\r\n context.closePath();\r\n\r\n context.beginPath();\r\n context.fillStyle = \"#007dff\";\r\n context.ellipse(kirbyEyeX, kirbyEyeY, 7, 17, 0, 0, Math.PI * 2);\r\n context.fill();\r\n context.closePath();\r\n\r\n context.beginPath();\r\n context.fillStyle = \"#000000\";\r\n context.arc(kirbyEyeX, kirbyEyeY, 9, 0, Math.PI * 2);\r\n context.fill();\r\n context.closePath();\r\n\r\n context.beginPath();\r\n context.fillStyle = \"#ffffff\";\r\n context.ellipse(kirbyEyeX, kirbyEyeY - 8, 6, 9, 0, 0, Math.PI * 2);\r\n context.fill();\r\n context.closePath();\r\n }", "function moveAliens() {\n for (let i = 0; i < aliens.length; i++) {\n aliens[i].moveIndividualAliens();\n if (aliens[i].y - 25 > height) {\n aliens.shift();\n gameMode = \"game over\";\n resetArrays();\n }\n }\n}", "makeWell() {\n stroke(116, 122, 117);\n strokeWeight(2);\n fill(147, 153, 148);\n ellipse(125, 75, this.pxl, this.pxl);\n fill(0, 0, 255);\n ellipse(125, 75, this.pxl - 10, this.pxl - 10);\n }", "function scaleEliminationCursor() {\n var baseWidthsSum = 0;\n var activePlantCount = 0;\n for ( var i=0; i<plants.length; i++ ) { \n if ( plants[i].sourceSeed.hasGerminated && plants[i].isAlive ) { \n baseWidthsSum += plants[i].spB.l; \n activePlantCount++;\n } \n }\n baseWidthAvg = baseWidthsSum/activePlantCount;\n selectRadius = baseWidthAvg*1.5 > canvas.width*0.015 ? baseWidthAvg*1.5 : canvas.width*0.015 ;\n}", "display() {\n push();\n fill(255,0,0);\n ellipse(this.x, this.y, this.size);\n pop();\n // if (x < 0 || x > width || y < 0 || y > height) {\n // var removed = obstacles.splice(this.index, 1);\n // }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: saveListLinksToCookie() Description: Save list shortent Link to cookies Parameter: None Return: None
function saveListLinksToCookie() { var linkListJson = getShortenLinkListJson(); if(linkListJson != "") { setCookie("ResultsList", linkListJson, 30); } }
[ "function loadListLinksFromCookie() {\n var linkListJson = getCookie(\"ResultsList\");\n var linkListArr = JSON.parse(linkListJson);\n for(let i = linkListArr.length - 1; i >= 0; i--) {\n addResult(linkListArr[i].id, linkListArr[i].original, linkListArr[i].shorten);\n }\n}", "function saveStoredThings(){\n localStorage.setItem('fronter_fixes_links', links);\n}", "function setCookie(){\r\n\tvar items = document.getElementsByClassName(\"list-group-item\");\r\n\tvar itemText = new Array();\r\n\tfor (var i = 0; i < items.length; i++){\r\n\t\titemText[i] = items[i].id;\r\n\t}\r\n\tdocument.cookie = \"items=\" + itemText.join(\"|\");\r\n}", "function saveToCookies()\n{\n const THREE_YEARS_IN_SEC = 94670777;\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"player_id\",\n \"value\": MY_ID,\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_ids_length\",\n \"value\": WHITELISTED_IDS.length.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC)});\n for (let index = 0; index < WHITELISTED_IDS.length; index++) {\n const WHITELISTED_ID = WHITELISTED_IDS[index];\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_id\"+index.toString(),\n \"value\": WHITELISTED_ID.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n }\n}", "function saveLinkList() {\r\n getLinkList(function (items) {\r\n\r\n var link = document.getElementById('newSite').value;\r\n validateUrl(link, function (cleanLink) {\r\n if (cleanLink != \"\" && cleanLink.localeCompare(\"gofuckingwork.com\") != 0) {\r\n console.log(cleanLink + cleanLink.localeCompare(\"gofuckingwork.com\"));\r\n document.getElementById('newSite').value = \"\";\r\n var tempLinkList = items;\r\n console.log(type(tempLinkList) + \": \" + tempLinkList.toString());\r\n tempLinkList.push(cleanLink);\r\n chrome.storage.sync.set({\r\n linkList: tempLinkList\r\n }, function () {\r\n // Update status to let user know options were saved.\r\n\r\n var status = document.getElementById('status');\r\n status.textContent = 'Options saved.';\r\n setTimeout(function () {\r\n status.textContent = '';\r\n }, 750);\r\n });\r\n } else {\r\n var status = document.getElementById('status');\r\n status.textContent = 'Please enter a valid URL';\r\n setTimeout(function () {\r\n status.textContent = '';\r\n }, 750);\r\n\r\n }\r\n });\r\n });\r\n}", "function persistLinks(e) {\n var linksInCache = JSON.parse(CacheService.getPrivateCache().get('links'));\n var documentProperties = PropertiesService.getDocumentProperties();\n var linksInDoc = documentProperties.getProperty('LINKS');\n if(linksInDoc == null) {\n documentProperties.setProperty('LINKS', JSON.stringify(linksInCache));\n }\n else { \n linksInDoc = JSON.parse(documentProperties.getProperty('LINKS'));\n var newLinks = linksInDoc;\n var idsToAdd = Object.keys(linksInCache);\n for (var i = 0; i < idsToAdd.length; i++) {\n if(newLinks[idsToAdd[i]] == undefined) {\n newLinks[idsToAdd[i]] = [];\n }\n /* To avoid creating a new array in the JSON object */\n var nbElem = linksInCache[idsToAdd[i]].length;\n for (var j = 0; j < nbElem; j++) {\n newLinks[idsToAdd[i]].push(linksInCache[idsToAdd[i]][j]);\n }\n }\n documentProperties.setProperty('LINKS', JSON.stringify(newLinks));\n }\n DocumentApp.getUi().alert('Links saved');\n clearLinksInCache(); \n}", "function getCookie(){\r\n\t// get items cookie\r\n\tvar items = \"\";\r\n\tvar name = \"items=\";\r\n\tvar ca = document.cookie.split(';');\r\n\tfor(var i=0; i<ca.length; i++) {\r\n\t\tvar c = ca[i].trim();\r\n\t \tif (c.indexOf(name) == 0) {\r\n\t \t\tvar items = c.substring(name.length, c.length);\r\n\t \t}\r\n\t}\r\n\r\n\t// add each item to list\r\n\titems = items.split(\"|\");\r\n\tfor (var i = 0; i < items.length; i++){\r\n\t\taddItem(items[i], false);\r\n\t}\r\n}", "function writeCookies(hostname, cookies) {\n getCurrentTabUrl(function(url) {\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n\n chrome.cookies.remove({\n \"url\": url,\n \"name\": cookie.name\n });\n chrome.cookies.set({\n \"url\": url,\n \"name\": cookie.name,\n \"value\": cookie.value,\n \"domain\": cookie.domain,\n \"path\": cookie.path,\n \"secure\": cookie.secure,\n \"httpOnly\": cookie.httpOnly,\n \"expirationDate\": cookie.expirationDate,\n \"storeId\": cookie.storeId\n });\n }\n });\n\n chrome.tabs.getSelected(null, function(tab) {\n var code = 'window.location.reload();';\n chrome.tabs.executeScript(tab.id, {code: code});\n });\n}", "function savePizzaState() {\n console.log(\"Saving pizza state\");\n Cookies.set(\"version\", CURRENT_VERSION, { expires: 365, path: '/' });\n Cookies.set(\"pizza\", document.getElementById('id_pizza_style').value, { expires: 365, path: '/' });\n Cookies.set(\"dough_balls\", document.getElementById('id_dough_balls').value, { expires: 365, path: '/' });\n Cookies.set(\"size\", document.getElementById('id_size').value, { expires: 365, path: '/' });\n}", "saveToStore() {\n localStorage.setItem(STORAGE.TAG, JSON.stringify(this.list));\n }", "function saveRank() {\n let rowRankString = [];\n for (let pairs of rank) {\n rowRankString.push(pairs.join('@'));\n }\n rowRankString = rowRankString.join('&');\n setCookie('rank', rowRankString, 7)\n}", "function BookmarkInit(urlValue, ImageUrl, selectedImageUrl) {\n\n // Check to see if bookmark exists, and create an local var with the information (or fresh)\n if (localStorage.getItem(\"bookmarks\") === null) {\n var bookmarks = [];\n } else {\n var bookmarks = JSON.parse(localStorage.getItem(\"bookmarks\"));\n }\n\n // -------- Set the image of the bookmark based on page status -------------\n if(bookmarks.includes(urlValue)) {\n document.getElementById(\"theBookmark\").src = selectedImageUrl;\n // Should be bookmarked\n } else {\n document.getElementById(\"theBookmark\").src = ImageUrl;\n // Should be un-bookmarked\n }\n // -------------------------------------------------------------------------\n\n // ----- If else ladder to determine which bookmark state to display -------\n $(\"#theBookmark\").on(\"click\", function() {\n // If something exists in storage\n if (localStorage.getItem(\"bookmarks\") != null) {\n var removed = JSON.parse(localStorage.getItem(\"bookmarks\"));\n var tester = removed.includes(urlValue);\n if (tester == true) { // Check if current page is in the array\n for (var i = 0; i < removed.length; i++) { // Loop through array to find current page\n if (urlValue === removed[i]) {\n removed.splice(i, 1); // Remove from the array\n removed.sort(); // Sort the array (alphabetically)\n localStorage.setItem(\"bookmarks\", JSON.stringify(removed)); // Send the new array back to storage\n break;\n }\n }\n document.getElementById(\"theBookmark\").src = ImageUrl; // Set bookmark image to true (marked)\n } else { // Does not exist in array ( already been bookmarked )\n var stored = JSON.parse(localStorage.getItem(\"bookmarks\")); // Pull the current array\n stored.push(urlValue); // Add the current page\n stored.sort();\n localStorage.setItem(\"bookmarks\", JSON.stringify(stored)); // Store the new array\n document.getElementById(\"theBookmark\").src = selectedImageUrl; // Set bookmark image to false (un-marked)\n }\n } else { // Nothing exists ( No page has been bookmarked )\n var stored = []; // Create new array\n stored.push(urlValue);\n localStorage.setItem(\"bookmarks\", JSON.stringify(stored));\n document.getElementById(\"theBookmark\").src = selectedImageUrl;\n }\n });\n}", "function saveLoginToken(cookie, sessionId, emailAddress){\n\t\t\tlocalStorage.setItem(\"cookie\", cookie);\n\t\t\tlocalStorage.setItem(\"sessionId\", sessionId);\n\t\t\tlocalStorage.setItem(\"emailAddress\", emailAddress);\n\t\t}", "function saveRealmList() {\n \"use strict\";\n window.gmSetValue(\"realmList2\", realmList);\n}", "function saveStorage() {\r\n //acessando a variavel global localStorage, e inserindo o todo para fucar armazenado\r\n //é nessessário transformar em jason pois o localstorage não entende array\r\n localStorage.setItem(\"list_todo\", JSON.stringify(todos));\r\n}", "function saveUrlsOnWindowClosing(windowId) {\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n}", "function SubmitListLinks(f,pref_attachs,pref_contents,n_attachs,n_contents){\n\n\tvar n_checks = 0; // number of checkboxes checked\n\t\n\t// detect number of checked attachements\n\tfor (var i=0;i < n_attachs; i++){\n\t\tif (eval(\"document.\"+f.name+\".\"+pref_attachs+\"\"+i+\".checked\"))\n\t\t\tn_checks++;\n\t}\n\t\n\t// detect number of checked contents\n\tfor (var i=0;i < n_contents; i++){\n\t\tif (eval(\"document.\"+f.name+\".\"+pref_contents+\"\"+i+\".checked\"))\n\t\t\tn_checks++;\n\t}\n\t\n\t// check if has empty fields, when that is obligatory\n\tif (n_checks == 0)\n\t\talert(\"Must have any checkboxes checked\");\n\telse\n\t\n\t\t// submit data\n\t\tf.submit();\n}", "function storeClassList(classList) {\n chrome.storage.sync.set({'CBEclasses': classList}, function(){\n //Saves classes to variable for persistent storage\n console.debug('Classes saved');\n })\n}", "function saveLangPreference(lang) {\n //alert(\"saveLangPreference | \"+ lang);\n\ttry{\n\t\tvar date = new Date();\n\t\tdate.setTime(date.getTime()+(999*24*60*60*1000));\n \tvar tmp = window.location.href.substr(7) ;\t\t\n\t\tvar SERVER_NAME = tmp.substr(0, tmp.indexOf(\"http://bet.hkjc.com/\")) ;\n\t\tvar domainName = SERVER_NAME.substr(SERVER_NAME.indexOf(\".\")+1) ;\n\t\tsetCookie('jcbwLangPreference', lang,date,'http://bet.hkjc.com/',domainName); \n\t} catch(e) {};\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set value to collection
function setValue(collection, key, value, collectionType) { switch (collectionType) { case detector_1.typeArguments: case detector_1.typeArray: case detector_1.typeObject: collection[key] = value; break; case detector_1.typeMap: collection.set(key, value); break; case detector_1.typeSet: collection.add(value); break; default: } return collection; }
[ "[createFunctionName('set', collection, false)](object) {\n return setObjectToArray(object, self[collection], findField)\n }", "setCollection(coll) {\n\t\t\tthis.collection = coll;\n\t\t\tthis.ids = Object.keys(coll.getAll());\n\t\t}", "setValueToId (item, key, id) {\n debug('setValueToId(%O, %O, %O)', item, key, id)\n let value = this.objFor.get(id)\n if (value) {\n debug('.. set to %o', value)\n item[key] = value\n } else {\n let frs = this.forwardRefs.get(id)\n if (!frs) {\n frs = new Set()\n this.forwardRefs.set(id, frs)\n }\n frs.add({ item, key })\n debug('.. forward refs = %o', frs)\n }\n }", "set(vec) {\n for (var i = 0; i < this.size; i++)\n this.v[i] = vec[i];\n return this;\n }", "cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value)\n else this.map.set(cursor.tree, value)\n }", "setAt(idx, val) {\n if(idx>= this.length||idx<0){\n throw new Error(\"invalid index\");\n }\n let cur=this._get(idx);\n cur.val=val;\n }", "function set_value(vals, val, is_variable) {\n set_head(head(vals), val);\n set_tail(head(vals), is_variable);\n }", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "set_marks(mark) {\n this.V.forEach(v => {\n v.mark = mark;\n });\n }", "set value(val) {\n if (val !== this._value) {\n this._value = val;\n this.notify();\n }\n }", "function Set() {\n this._items = [];\n }", "set(key, value = null) {\n // If only argument is an Object, merge Object with internal data\n if (key instanceof Object && value == null) {\n const updateObj = key;\n Object.assign(this.__data, updateObj);\n this.__fullUpdate = true;\n return;\n }\n\n // Add change to internal updates set\n this.__updates.add(key);\n\n // Set internal value selected by dot-prop key\n DotProp.set(this.__data, key, value);\n }", "$set (path, value) {\n _.set(this._config, path, value)\n return this\n }", "set(propObj, value) {\n propObj[this.id] = value;\n return propObj;\n }", "function setValue(param, value) {\n if (lmsConnected) {\n DEBUG.LOG(`setting ${param} to ${value}`);\n scorm.set(param, value);\n scorm.save();\n } else {\n DEBUG.WARN('LMS NOT CONNECTED');\n }\n}", "set user(aValue) {\n this._logger.debug(\"user[set]\");\n this._user = aValue;\n }", "set value(_) {\n throw \"Cannot set computed property\";\n }", "fillCollection(collection, items, password) {\n for (const key in items) {\n collection.insert(items[key]._item, password);\n }\n }", "onPropertySet(room, property, value, identifier) {\n room[prop] = value;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This routine scrolls the tabs to the left id the tabset id return none Compatibility: IE,NS6
function i2uiScrollTabsLeft(id) { if (document.layers) return; var obj = document.getElementById(id); if (obj != null) { var tablen = obj.rows[0].cells.length; var showid = 0; // show last invisible tab from right for (var i=tablen-3; i>4; i--) { if (obj.rows[0].cells[i].style.display == "none") { showid = i; i -= 3; } else if (showid > 0) { if (showid == 1) i2uiToggleItemVisibility(id+'_tabscrollerright','hide'); else i2uiToggleItemVisibility(id+'_tabscrollerright','show'); obj.rows[0].cells[showid].style.display = ""; obj.rows[0].cells[showid].style.visibility = "visible"; showid--; obj.rows[0].cells[showid].style.display = ""; obj.rows[0].cells[showid].style.visibility = "visible"; showid--; obj.rows[0].cells[showid].style.display = ""; obj.rows[0].cells[showid].style.visibility = "visible"; showid--; obj.rows[0].cells[showid].style.display = ""; obj.rows[0].cells[showid].style.visibility = "visible"; showid--; // show all other tabs for (var j=showid; j>0; j--) { obj.rows[0].cells[j].style.display = ""; obj.rows[0].cells[j].style.visibility = "visible"; } // now hide just enough of those on left i2uiManageTabs(id,null,"front",null,showid+4); break; } } } }
[ "function setScrollers(container) { \n\t\tvar header = $('>div.tabs-header', container); \n\t\tvar tabsWidth = 0; \n\t\t$('ul.tabs li', header).each(function(){ \n\t\t\ttabsWidth += $(this).outerWidth(true); \n\t\t}); \n\t\t \n\t\tif (tabsWidth > header.width()) { \n\t\t\t$('.tabs-scroller-left', header).css('display', 'block'); \n\t\t\t$('.tabs-scroller-right', header).css('display', 'block'); \n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling'); \n\t\t\t \n\t\t\tif ($.boxModel == true) { \n\t\t\t\t$('.tabs-wrap', header).css('left',2); \n\t\t\t} else { \n\t\t\t\t$('.tabs-wrap', header).css('left',0); \n\t\t\t} \n\t\t\tvar width = header.width() \n\t\t\t\t- $('.tabs-scroller-left', header).outerWidth() \n\t\t\t\t- $('.tabs-scroller-right', header).outerWidth(); \n\t\t\t$('.tabs-wrap', header).width(width); \n\t\t\t \n\t\t} else { \n\t\t\t$('.tabs-scroller-left', header).css('display', 'none'); \n\t\t\t$('.tabs-scroller-right', header).css('display', 'none'); \n\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0); \n\t\t\t$('.tabs-wrap', header).width(header.width()); \n\t\t\t$('.tabs-wrap', header).css('left',0); \n\t\t\t \n\t\t} \n\t}", "scrollToTab_() {\n this.anchorScroll_('tabs');\n }", "function setScrollers(container) {\n\t\tvar header = $('>div.tabs-header', container);\n\n\t\tvar tabsWidth = 0;\n\t\t$('ul.tabs li', header).each(function () {\n\t\t\ttabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\tif (tabsWidth > header.width()) {\n\t\t\t$('.tabs-scroller-left', header).css('display', 'block');\n\t\t\t$('.tabs-scroller-right', header).css('display', 'block');\n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling');\n\n\t\t\t//\t\t\tif ($.boxModel == true) {\n\t\t\t//\t\t\t\t$('.tabs-wrap', header).css('left',2);\n\t\t\t//\t\t\t} else {\n\t\t\t//\t\t\t\t$('.tabs-wrap', header).css('left',0);\n\t\t\t//\t\t\t}\n\t\t\t//\t\t\tvar width = header.width()\n\t\t\t//\t\t\t\t- $('.tabs-scroller-left', header).outerWidth()\n\t\t\t//\t\t\t\t- $('.tabs-scroller-right', header).outerWidth();\n\t\t\t//\t\t\t$('.tabs-wrap', header).width(width);\n\t\t\t//\n\t\t\t//\t\t} else {\n\t\t\t//\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\n\t\t\t//\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\n\t\t\t//\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0);\n\t\t\t//\t\t\t$('.tabs-wrap', header).width(header.width());\n\t\t\t//\t\t\t$('.tabs-wrap', header).css('left',0);\n\t\t\t//\n\t\t} else {\n\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\n\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\n\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling');\n\t\t}\n\t}", "function scrollLock(tabs) {\n browser.tabs.sendMessage(tabs[0].id, {\n command: 'lock',\n });\n }", "function pa_tabs_start(id_panel, id_content, active_index, adjust_content_position) {\n\tvar tab_elem = _( id_panel );\n\tvar items = tab_elem.getElementsByClassName('pa-tab-menu-item');\n\tvar i = 0;\n\tvar items_length = items.length;\n\tvar item_width = 1.0 / items_length;\n\twhile ( i < items_length ) {\n\t\tvar item = items[i];\n\t\titem.className += ' pa_width_' + item_width + ' pa_left_' + (i*item_width);\n\t\tpa_add( item );\n\t\t/// bindings\n\t\titem.addEventListener('click', function() {\n\t\t\tpa_tabs_active_tab(tab_elem, this);\n\t\t});\n\t\t++i;\n\t}\n\tpa_tabs_active_tab( tab_elem, items[active_index] );\n\tif ( adjust_content_position === true ) {\n\t\tpa_tabs_adjust_content_div_position( _(id_panel), _(id_content) );\n\t}\n}", "move_horseProfile_TabsHeader(){\n browser.touchAction('//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[12]/android.widget.HorizontalScrollView', ['longPress',\n { action: 'moveTo', x: 0, y: (this.horseProfile_Y_Location_TabHeader-500)}, 'release'\n ])\n }", "function i2uiSyncdScroll(mastertableid, slavetableid)\r\n{\r\n var masterscrolleritem;\r\n var slavescrolleritem;\r\n\r\n if (slavetableid == null)\r\n {\r\n // keep header and data of same table scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(mastertableid+\"_header_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n slavescrolleritem.scrollLeft = masterscrolleritem.scrollLeft;\r\n }\r\n }\r\n else\r\n {\r\n // keep data in different tables scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(slavetableid+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n }\r\n }\r\n}", "startAutoScroll() {\n this.selectNextSibling();\n this.setAutoScroll();\n }", "function toScroll(div, d, flag) {\n\t\t\t\t\t\t\tvar ndiv = $(div);\n\t\t\t\t\t\t\tvar pos = ndiv.scrollLeft();\n\t\t\t\t\t\t\tvar posDelta = 0;\n\t\t\t\t\t\t\tif (d.depth > 4)\n\t\t\t\t\t\t\t\tposDelta = 3 * (flag ? 40 : -40);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tposDelta = d.depth * (flag ? 40 : -40);\n\t\t\t\t\t\t\tndiv.scrollLeft(pos + posDelta);\n\t// var dId = d.id;\n\t// $('#' + dId).focus();\n\t\t\t\t\t\t}", "function switchTabsOnMouseWheel() {\n addEvent(gBrowser.tabContainer, 'wheel', (event) => {\n gBrowser.tabContainer.\n advanceSelectedTab((event.deltaY < 0) ? -1 : 1, true);\n\n event.stopPropagation();\n event.preventDefault();\n }, true);\n}", "onTabClick(event, element) {\n\t\tevent.preventDefault();\n/* The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. */\n\n/* Based on the tab that is clicked, one of the attributes of 'href' corresponding to the tab click will be picked from the element et-hero-tab. */\n\n\t\tlet scrollTop = $(element.attr('href')).offset().top - this.tabContainerHeight + 1;\n /* alert(\"this is Scroll value \"+$(element.attr('href')).offset().top); \n Value of is $(element.attr('href')).offset().top) for first tab is 984 , tabContainerHeight is 70\nThus scrollTop for first tab is 984-70+1 = 915 */\n\n\t\t$('html, body').animate({ scrollTop: scrollTop }, 600);\n\t}", "function getTabLeftPosition(container, tab) { \n\t\tvar w = 0; \n\t\tvar b = true; \n\t\t$('>div.tabs-header ul.tabs li', container).each(function(){ \n\t\t\tif (this == tab) { \n\t\t\t\tb = false; \n\t\t\t} \n\t\t\tif (b == true) { \n\t\t\t\tw += $(this).outerWidth(true); \n\t\t\t} \n\t\t}); \n\t\treturn w; \n\t}", "function getScrolledPosition(element){var position;//is not the window element and is a slide?\nif(element.self!=window&&hasClass(element,SLIDES_WRAPPER)){position=element.scrollLeft;}else if(!options.autoScrolling||options.scrollBar){position=getScrollTop();}else{position=element.offsetTop;}//gets the top property of the wrapper\nreturn position;}", "setCardsScrollLeft() {\n if (this.cardsLeftGlobal) {\n let margin = window.innerWidth >= 1200 ? 62.6 : 52.8;\n const cardWidth = $('.my-card').width() + margin;\n this.$cardTrack.scrollLeft(cardWidth * this.cardsLeftGlobal);\n }\n }", "scrollLeft() {\n let x = this.scrollElement.scrollLeft - this.scrollElement.clientWidth;\n let y = this.scrollElement.scrollTop;\n this._scrollTo(x, y);\n }", "function ScrollingTabsControl($tabsContainer) {\n var stc = this;\n \n stc.$tabsContainer = $tabsContainer;\n \n stc.movableContainerLeftPos = 0;\n stc.scrollArrowsVisible = false;\n stc.scrollToTabEdge = false;\n stc.disableScrollArrowsOnFullyScrolled = false;\n stc.reverseScroll = false;\n stc.widthMultiplier = 1;\n \n stc.scrollMovement = new ScrollMovement(stc);\n stc.eventHandlers = new EventHandlers(stc);\n stc.elementsHandler = new ElementsHandler(stc);\n }", "function scrolltoLeft() {\n /** Initialize 'width' to device screen width */\n var width = window.innerWidth > 0 ? window.innerWidth : screen.width;\n /** Scroll to negative screen width on the x-axis */\n document.getElementById(\"carousel-container\").scrollTo(-width - width, 0);\n}", "function learndashFocusModeSidebarAutoScroll() {\n\t\tif ( jQuery( '.learndash-wrapper .ld-focus' ).length ) {\n\t\t\tvar sidebar_wrapper = jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar-wrapper' );\n\n\t\t\tvar sidebar_curent_topic = jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar-wrapper .ld-is-current-item' );\n\t\t\tif ( ( 'undefined' !== typeof sidebar_curent_topic ) && ( sidebar_curent_topic.length ) ) {\n\t\t\t\tvar sidebar_scrollTo = sidebar_curent_topic;\n\t\t\t} else {\n\t\t\t\tvar sidebar_curent_lesson = jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar-wrapper .ld-is-current-lesson' );\n\t\t\t\tif ( ( 'undefined' !== typeof sidebar_curent_lesson ) && ( sidebar_curent_lesson.length ) ) {\n\t\t\t\t\tvar sidebar_scrollTo = sidebar_curent_lesson;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( ( 'undefined' !== typeof sidebar_scrollTo ) && ( sidebar_scrollTo.length ) ) {\n\t\t\t\tvar offset_top = 0;\n\t\t\t\tif ( jQuery( '.learndash-wrapper .ld-focus .ld-focus-header' ).length ) {\n\t\t\t\t\tvar logo_height = jQuery( '.learndash-wrapper .ld-focus .ld-focus-header' ).height();\n\t\t\t\t\toffset_top += logo_height;\n\t\t\t\t}\n\t\t\t\tif ( jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar .ld-course-navigation-heading' ).length ) {\n\t\t\t\t\tvar heading_height = jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar .ld-course-navigation-heading' ).height();\n\t\t\t\t\toffset_top += heading_height;\n\t\t\t\t}\n\t\t\t\tif ( jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar .ld-focus-sidebar-wrapper' ).length ) {\n\t\t\t\t\tvar container_height = jQuery( '.learndash-wrapper .ld-focus .ld-focus-sidebar .ld-focus-sidebar-wrapper' ).height();\n\t\t\t\t\toffset_top += container_height;\n\t\t\t\t}\n\n\t\t\t\tvar current_item_height = jQuery( sidebar_scrollTo ).height();\n\t\t\t\toffset_top -= current_item_height;\n\n\t\t\t\tsidebar_wrapper.animate( {\n\t\t\t\t\tscrollTop: sidebar_scrollTo.offset().top - offset_top,\n\t\t\t\t}, 1000 );\n\t\t\t}\n\t\t}\n\t}", "focusFirst(){\r\n const tab = this.tabControl.querySelector('.glu_verticalTabs-tab');\r\n if (!tab)\r\n return;\r\n\r\n this.focusTab(tab);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
global context config:configuration repository: sparxEA current repository eaElement: sparxEA selected element eaPackage: sparxEA package of selected element
function Context(config, repository, pckg, element) { var config = config; var repository = repository; var pckg = pckg; var element = element; this.getConfig = function () { return config;}; this.getRepository = function () { return repository;}; this.getPackage = function () { return pckg;}; this.getElement = function () { return element;}; }
[ "function insertProjectComponentInDOM() {\n var oldvalue = \"<b><u>Composant :</u></b> \";\n document.getElementById(\"componentName\").innerHTML = oldvalue + getSelectedComponentsName();\n}", "function eCSearch( dev_obj ){\n /*\n key points\n we are gathering information from a nS about what element to look at\n if it does not exist in its related itO according to list, we add it to the nS or the selectTags if its missing\n if its there we properly update nS and selectTags at that index\n */\n /*\n abelasts\n 1 for select tags\n 1 for nS\n \n */\n \n // .list, desired items\n // .look spot where to look and assert for list, if an object the items should be keys\n // .same indicator to look at the same set of values\n // .order iterableObject on how to create the numbersystem\n // .sT if in use the index to access selectTags from the self\n // .nS if in use the index to access numberSystem from the self\n // make eCSST an iterableObject\n // look through innerHTML, innerText, textContext\n // holds the found elements that meet the query in ultraObject.elementFound\n \n \n /*[addding the dev_obj to ultraObject.args ]*/ //{\n var eCSearch_dev_obj = ultraObject.args.add( {value:ultraObject.iterify( {iterify:dev_obj} ) } )\n // } /**/\n \n if( dev_obj.sT === undefined ){\n \n \n /*[the object handling everything with the choosing tags in addition the numberSystem ]*/ //{\n // make this selectTags +scope +abelast +self\n var eCSSelectTags_0_i = ultraObject.scope.add( {value:ultraObject.selectTags.add( {value:ultraObject.iterableObject()} )} )\n ultraObject.selectTags.abelast.add( {value:ultraObject.scope[eCSSelectTags_0_i]} )\n // } /**/\n \n \n }\n \n /*[if the developer already had the function make the selectTags]*/ //{\n //make this selectTags +scope\n else if( ultraObject.isInt( {type:dev_obj.sT} ) ){\n \n \n var eCSSelectTags_0_i = ultraObject.scope.add( {value:dev_obj.sT} )\n \n \n }\n // } /**/\n \n /* if we had the number system now we can turn this to a loop and start adding data to our database*/ //{\n if( ultraObject.isInt( {type:dev_obj.nS} ) === 'true' ){\n \n \n var eCSNS_0_i = ultraObject.scope.add( {value:dev_obj.nS} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS = 'true'\n \n \n \n }\n // } /**/\n \n \n console.group( 'items needed to search for elements based on keywords' )\n ultraObject.objInvloved(ultraObject.iterify({\n iterify:[\n ultraObject.allTags[ultraObject.scope[dev_obj.aT]],\n ultraObject.misc[ultraObject.scope[dev_obj.list]],\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]]\n ]\n })\n )\n \n /*objIO -self -ablelast */ //{\n ultraObject.objIO.minus( {index:ultraObject.objIO.abelast.length-1} )\n ultraObject.objIO.abelast.minus( {index:ultraObject.objIO.abelast.length-1} )\n // } /**/\n \n console.groupEnd()\n \n /* look at each requirement preFillForm must fill in the document by the end user*/ //{\n var eCSearchFL_0_i = {\n forLoop_0_i:0,\n forLoopLength: ultraObject.misc[ultraObject.scope[dev_obj.list]].length,\n fn:function( dev_obj ){\n \n /*it should start with the first element if none is given*/ //{\n if( dev_obj.nS === undefined ){\n \n \n ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect = 0\n \n \n }\n \n \n else if( dev_obj.nS !== undefined ){\n \n debugger\n ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect = ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ][0]\n \n \n \n }\n // } /**/\n \n /*at this point you need to us the nS to modify indexSelect*/ //{\n // use propertyUndefined to see if the nS is there then receive external output of an updated nS\n // to properly modify indexSelect so elements are not queired again\n eCSearchFL_1_i.forLoop_0_i = ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect\n // } /**/\n \n /* where every tag is looked at in relation to the respective list*/ //{\n return ultraObject.forLoop( eCSearchFL_1_i )\n // } /**/\n },\n args:dev_obj,\n }\n // } /**/\n \n /* where every tag is looked at in relation to the respective list*/ //{\n var eCSearchFL_1_i = {\n forLoop_0_i:ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect,\n forLoopLength:ultraObject.allTags[ultraObject.scope[dev_obj.aT]].length,\n fn:function( dev_obj ){\n \n /* if were looking at the same element*/ //{\n if( eCSearchFL_0_i.forLoop_0_i > 0 && ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i-1 ].eCSIndex === eCSearchFL_1_i.forLoop_0_i ){\n \n \n //if PROBLEM use propertyUndefined to validate the selectedTag for interragtion is there as well as its eCSIndex\n \n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement = 'true'\n \n \n }\n \n \n else if( eCSearchFL_0_i.forLoop_0_i > 0 && ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i-1 ].eCSIndex !== eCSearchFL_1_i.forLoop_0_i ){\n \n \n //if PROBLEM use propertyUndefined to validate the selectedTag for interragtion is there as well as its eCSIndex\n \n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement = 'false'\n \n \n }\n // } /**/\n \n /* possible places to look to fill in the element to satisfy end users query*/ //{\n // PROBLEM if you have scoping problems with this fn look here\n return ultraObject.forLoop( eCSearchFL_2_i )\n // } /**/\n },\n args:dev_obj,\n }\n // } /**/\n /* possible places to look to fill in the element to satisfy end users query*/ //{\n // PROBLEM if you have scoping problems with this fn look here\n var eCSearchFL_2_i = {\n forLoop_0_i:0,\n forLoopLength:ultraObject.misc[ultraObject.scope[dev_obj.look]].length,\n fn:function( dev_obj ){\n \n \n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement ==='true' ){\n \n /* it better be in the scope */ //{\n // im really counting on this to be in the proper spot in the scope if not i have to take it from the scope everytime and get it from the abelast\n var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n // }\n \n if( ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the digits and metadata for the numberSystem*/ //{\n ultraObject.numberSystem({\n operation:'create',\n nS:ultraObject.scope[ eCSNS_0_i ],\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n }),\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n })\n })\n // } /**/\n \n }\n \n\n \n if( ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the ideal select tag for this function*/ //{\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ].add({\n value:ultraObject.iterableObject()\n })\n // } /**/\n \n }\n \n /*adjusting this digits itO to that of the numberSystem */ //{\n ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ].nSM[ eCSearchFL_0_i.forLoop_0_i ][0] ][0] = eCSearchFL_1_i.forLoop_0_i\n //helps change the number when the match is found so the NS doesnt take over\n //if problems look here idk if it supposed to follow the nSM or not\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].item = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].query = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ][ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].xMark = ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].keyword = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].valuePhrase = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][1]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].eCSIndex = eCSearchFL_1_i.forLoop_0_i\n // } /**/\n \n \n return 'premature'\n \n \n }\n \n \n else if( ultraObject.allTags[ ultraObject.scope[dev_obj.aT] ][eCSearchFL_1_i.forLoop_0_i][ ultraObject.misc[ultraObject.scope[dev_obj.look] ][eCSearchFL_2_i.forLoop_0_i][0] ] !== undefined || dev_obj.all === 'true' ){\n \n \n if( ultraObject.allTags[ ultraObject.scope[dev_obj.aT] ][eCSearchFL_1_i.forLoop_0_i][ ultraObject.misc[ultraObject.scope[dev_obj.look] ][eCSearchFL_2_i.forLoop_0_i][0] ].indexOf( ultraObject.misc[ ultraObject.scope[dev_obj.list] ][eCSearchFL_0_i.forLoop_0_i][0] ) !== -1 || dev_obj.all === 'true' ){\n \n /*numberSystem access or creation*/ //{\n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS !== 'true' ){\n \n\n ultraObject.numberSystem({\n operation:'create',\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n }),\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n })\n })\n var eCSNS_0_i = ultraObject.scope.add( {value:ultraObject.nS.abelast[ultraObject.nS.abelast.length-1]} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS = eCSNS_0_i\n // i do this because i need a closure so that all algorithms in the loop can access it\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS = 'true'\n \n \n }\n \n \n else if( ultraObject.isInt({type:dev_obj.nS}) === 'true' ){\n \n \n var eCSNS_0_i = ultraObject.scope.add( {value:dev_obj.nS} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS = eCSNS_0_i\n \n \n }\n \n \n else if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS === 'true'){\n \n \n var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n \n \n }\n // } /**/\n \n if( ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the digits and metadata for the numberSystem*/ //{\n ultraObject.numberSystem({\n operation:'create',\n nS:ultraObject.scope[ eCSNS_0_i ],\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n }),\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n })\n })\n // } /**/\n \n }\n \n \n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the ideal select tag for this function*/ //{\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ].add({\n value:ultraObject.iterableObject()\n })\n // } /**/\n \n }\n \n /*adjusting this digits itO to that of the numberSystem */ //{\n ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ].nSM[ eCSearchFL_0_i.forLoop_0_i ][0] ][0] = eCSearchFL_1_i.forLoop_0_i\n //helps change the number when the match is found so the NS doesnt take over\n //if problems look here idk if it supposed to follow the nSM or not\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].item = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].query = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ][ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].xMark = ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].keyword = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].valuePhrase = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][1]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].eCSIndex = eCSearchFL_1_i.forLoop_0_i\n // } /**/\n return 'premature'\n \n }\n \n \n }\n \n \n },\n args:dev_obj,\n bubble:'true'\n }\n // } /**/\n ultraObject.forLoop( eCSearchFL_0_i )\n delete ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement\n // } /**/\n \n /*selectTags -scope */ //{\n ultraObject.scope.minus( {index:eCSSelectTags_0_i} )\n // } /**/\n \n /*nS */ //{\n // this is a good example when an itO was never accessed by an outer function\n // here you never need to take it out the scope it was never in the scope\n // var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n // ultraObject.scope.minus( {index:eCSNS_0_i} )\n // } /**/\n \n // find the first that matches the condition, and hold it when all four match exit, if the form doesn't like what I did each value must try everything in the allTapgs itO before telling the end user they cant figure out whats going on.grabs three and swaps one\n \n // so like\n /*\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n \n [0,0,0,0] -> [0,0,0,3] -> [0,0,1,0] -> [0,0,1,3] -> [0,0,3,3] -> [0,3,3,3] [1,0,0,0] -> [1,0,0,3] -> [1,3,3,3] -> [3,3,3,3]\n \n to cover every posibility in the table\n \n for this we need to make a number system that allows to cover every item\n */\n }// seaches for elements with the queried filters and does things to them", "function refreshModuleTree(element) {\n\t$('#mtree').tree({\n\t\turl:'src/testscript/testlibtree.php?framework=' + element.value\n\t});\n}", "_startChoose(e) {\n let target = e.target;\n if (target.nodeName !== 'BUTTON') {\n target = target.parentElement;\n }\n this._chosenServer = target.dataset.server;\n let choices = this._state.packages[target.dataset.app];\n let chosen = choices.findIndex(choice => choice.Name === target.dataset.name);\n this._push_selection.choices = choices;\n this._push_selection.chosen = chosen;\n this._push_selection.show();\n }", "visitUsing_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "enterPackageModifier(ctx) {\n\t}", "static findProvider(el) {\n if (isDesignSystemConsumer(el)) {\n return el.provider;\n }\n let parent = (0,_utilities_composed_parent__WEBPACK_IMPORTED_MODULE_2__.composedParent)(el);\n while (parent !== null) {\n if (DesignSystemProvider.isDesignSystemProvider(parent)) {\n el.provider = parent; // Store provider on ourselves for future reference\n return parent;\n }\n else if (isDesignSystemConsumer(parent)) {\n el.provider = parent.provider;\n return parent.provider;\n }\n else {\n parent = (0,_utilities_composed_parent__WEBPACK_IMPORTED_MODULE_2__.composedParent)(parent);\n }\n }\n return null;\n }", "findSelectableElement(event) {\n const path = event.composedPath();\n for (let i = 0; i < path.length; i += 1) {\n const element = path[i];\n if (element === this) {\n return;\n }\n if (this.isSelectableElement(element)) {\n return element;\n }\n }\n }", "function BAElement() { }", "setActiveElement(element) {\n this.project._activeElement = element;\n }", "function selectElement(_) {\n\t\t// _.element - javascript element\n\t\t// _.jelement - jQuery element\n\t\t// _.id - ID of Element\n\n\n\n\t\tif (_===undefined || typeof _!=\"object\" || (_.element===undefined && _.jelement===undefined && _.id===undefined)) return false;\n\t\tif (_.id!==undefined) _.jelement = jQuery('#'+_.id);\n\t\tif (_.element===undefined) _.element=_.jelement[0];\n\t\tif (_.jelement===undefined) _.jelement = jQuery(_.element);\n\t\tif (_.id===undefined) _.id = _.element.id;\n\n\t\tif (_.jelement===undefined) return;\n\n\t\tdeselectAllElement(_.element.id);\n\n\t\tRVS.S.selElements = [];\n\t\tRVS.S.selElements.push({\n\t\t\t\t\tjobj : _.jelement,\n\t\t\t\t\tmultiplemark: _.element.dataset.multiplemark,\n\t\t\t\t\tforms:_.jelement.data('forms'),\n\t\t\t\t\tid:_.element.id,\n\n\t\t\t});\n\n\t\t_.jelement.addClass(\"marked\");\n\n\t}", "get getProjectOnContent() {\n return componentAction.getElement(this.projectOnContent);\n }", "function alertRepo(e) {\n e.preventDefault();\n\n // Get repo information of the repository link that was clicked.\n var $el = $(e.target);\n var repo = $el.data(\"repo\");\n\n // Alert the repository's information\n alert(\n \"Owner: \" + repo.owner + \"\\r\\n\" +\n \"Name: \" + repo.name + \"\\r\\n\" +\n \"Language: \" + repo.language + \"\\r\\n\" +\n \"Followers: \" + repo.followers + \"\\r\\n\" +\n \"URL: https://github.com/\" + repo.owner + \"/\" + repo.name + \"\\r\\n\" +\n \"Description: \" + repo.description\n );\n }", "function setupIconLibrarySelectionListener() {\n $('li[class^=ion]').click(function(e) {\n var originalElement = e.target;\n var imageName = originalElement.classList[0].slice(4);\n $('#IconLibraryModal').modal('hide');\n generateFlatIconFromImage('/img/ionicons/512/' + imageName + '.png');\n });\n}", "function popupFindItem(ui) {\n\n v_global.event.type = ui.type;\n v_global.event.object = ui.object;\n v_global.event.row = ui.row;\n v_global.event.element = ui.element;\n\n switch (ui.element) {\n case \"emp_nm\":\n case \"manager1_nm\":\n case \"manager2_nm\":\n case \"manager3_nm\":\n case \"manager4_nm\": \n {\n var args = { type: \"PAGE\", page: \"DLG_EMPLOYEE\", title: \"사원 선택\"\n \t, width: 700, height: 450, locate: [\"center\", \"top\"], open: true\n };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_EMPLOYEE\",\n param: { ID: gw_com_api.v_Stream.msg_selectEmployee }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"dept_nm\":\n {\n var args = { type: \"PAGE\", page: \"DLG_TEAM\", title: \"부서 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_TEAM\",\n param: { ID: gw_com_api.v_Stream.msg_selectTeam }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"supp_nm\":\n {\n var args = { type: \"PAGE\", page: \"w_find_supplier\", title: \"협력사 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"w_find_supplier\",\n param: { ID: gw_com_api.v_Stream.msg_selectedSupplier }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n default: return;\n }\n}", "choosePaymentModule(belopp){\n let betalning = (`.payment_typelist--component div[class=\"${belopp}\"]`);\n switch(belopp){\n case 'FULL_PAYMENT': //hela beloppet\n browser.click(betalning);\n browser.pause(1000);\n break;\n case 'INSTALLMENT_PAYMENT': //delbelopp\n browser.click(betalning);\n browser.pause(10000);\n console.log('nu ska vi betala');\n this.enterAmount();\n break;\n case 'DEPOSIT_PAYMENT': //anmälningsavgift\n browser.click(betalning);\n browser.pause(1000);\n break; \n }\n \n // var type = Math.floor(Math.random() * (6 - 3 + 1)) + 3;\n // this.choosePaymentType(type);\n // browser.click(''); //klicka på gå vidare till betalningsalternativet\n }", "visitLibrary_editionable(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getTargetProduct() {\n return this.getConfigId().then(() => {\n return this._edge.get(URIs.GET_CONFIGS, [false, false]).then(configs => {\n const config = configs.configurations.find(cfg => cfg.id === this._configId);\n if (config) {\n return config.targetProduct;\n } else {\n logger.error('No security configurations exist for this config ID - ' + this._configId);\n throw `No security configurations exist for this config ID - ${this._configId}`;\n }\n });\n });\n }", "function insertProjectAPIInDOM() {\n var oldvalue = \"<b><u>Dépendances :</u></b> \";\n document.getElementById(\"projectAPI\").innerHTML = oldvalue + getSelectedApiName();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of nodes, remove any member that is contained by another.
function removeSubsets(nodes) { var idx = nodes.length; /* * Check if each node (or one of its ancestors) is already contained in the * array. */ while (--idx >= 0) { var node = nodes[idx]; /* * Remove the node if it is not unique. * We are going through the array from the end, so we only * have to check nodes that preceed the node under consideration in the array. */ if (idx > 0 && nodes.lastIndexOf(node, idx - 1) >= 0) { nodes.splice(idx, 1); continue; } for (var ancestor = node.parent; ancestor; ancestor = ancestor.parent) { if (nodes.includes(ancestor)) { nodes.splice(idx, 1); break; } } } return nodes; }
[ "function arrayRemoveIntersect(a, b){\n var i, j, k, dup = arrayIntersect(a, b);\n for(i = 0, j = dup.length; i < j; i++){\n if ((k = a.indexOf(dup[i])) === -1) continue;\n a.splice(k, 1);\n }\n}", "function excludeInvalidNodes(allNodes, invalidNodes) {\n\tvar toReturn = null;\n\tif(allNodes != null) {\n\t\tif(invalidNodes != null && !invalidNodes.isEmpty()) {\n\t\t\tvar lenght = allNodes.length;\n\t\t\ttoReturn = new Packages.java.util.ArrayList();\n\t\t\tfor (var i = 0; i < lenght; i++) {\n\t\t\t\tvar currentNode = allNodes[i];\n\t\t\t\tif(!invalidNodes.contains(currentNode)) {\n\t\t\t\t\ttoReturn.add(currentNode);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttoReturn = Packages.java.util.Arrays.asList(allNodes);\n\t\t}\n\t}\n\treturn toReturn;\n}", "function removeDuplicateMemberships( memberships ) {\n\n const membershipEqualityTest = function( m ) { return !equalMemberships( m, memberships[i] ); };\n const withAnd = function( a,b ) { return a && b; };\n\n var result = [];\n\n for ( var i = 0; i < memberships.length; i++ ) {\n\n if (\n\n result.map( membershipEqualityTest ).reduce( withAnd, true )\n\n ) {\n\n result.push( memberships[i] );\n\n }\n\n }\n\n return result;\n\n}", "function removeEnemies(names, enemies) {\n\treturn names.filter(x => !enemies.includes(x));\n}", "function delete_all_children() {\n var theRightSide = document.getElementById(\"rightSide\");\n var theLeftSide = document.getElementById(\"leftSide\");\n\n while (theRightSide.firstChild) {\n theRightSide.removeChild(theRightSide.firstChild)\n }\n while (theLeftSide.firstChild) {\n theLeftSide.removeChild(theLeftSide.firstChild)\n }\n}", "unsetNodes(editor, props) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!Array.isArray(props)) {\n props = [props];\n }\n\n var obj = {};\n\n for (var key of props) {\n obj[key] = null;\n }\n\n Transforms.setNodes(editor, obj, options);\n }", "_removeCorrespondingXrefs (tx, node) {\n let manager\n if (INTERNAL_BIBR_TYPES.indexOf(node.type) > -1) {\n manager = this._articleSession.getReferenceManager()\n } else if (node.type === 'footnote') {\n manager = this._articleSession.getFootnoteManager()\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 }", "function removeOrphanedChildren(children, unmountOnly) {\n\tfor (var i = children.length; i--;) {\n\t\tif (children[i]) {\n\t\t\trecollectNodeTree(children[i], unmountOnly);\n\t\t}\n\t}\n}", "function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele != value; }); }", "function remove(items){items=getList(items);for(var i=0;i<items.length;i++){var item=items[i];if(item&&item.parentElement){item.parentNode.removeChild(item);}}}", "function removeLinesOf(node) {\n let newSplits = [];\n lines.splits.forEach(function(spl) {\n if (spl.o.n != node.n && spl.t.n != node.n) {\n newSplits.push(spl);\n } else {\n //console.log(\"Removed splits: \", spl.o.n, \" \", spl.t.n);\n }\n });\n lines.splits = newSplits;\n\n let newMerges = [];\n lines.merges.forEach(function(mrg) {\n if (mrg.o.n != node.n && mrg.t.n != node.n) {\n newMerges.push(mrg);\n } else {\n //console.log(\"Removed merges: \", mrg.o.n, \" \", mrg.t.n);\n }\n });\n lines.merges = newMerges;\n\n let newRenames = [];\n lines.renames.forEach(function(rnm) {\n if (rnm.o.n != node.n && rnm.t.n != node.n) {\n newRenames.push(rnm);\n } else {\n //console.log(\"Removed renames: \", rnm.o.n, \" \", rnm.t.n);\n }\n });\n\n lines.renames = newRenames;\n\n let newEquals = [];\n lines.equals.forEach(function(eql) {\n if (eql.o.n != node.n && eql.t.n != node.n) {\n newEquals.push(eql);\n } else {\n //console.log(\"Removed merges: \", eql.o.n, \" \", eql.t.n);\n }\n });\n lines.equals = newEquals;\n\n let newMoves = [];\n lines.moves.forEach(function(mov) {\n if (mov.o.n != node.n && mov.t.n != node.n) {\n newMoves.push(mov);\n } else {\n //console.log(\"Removed merges: \", mov.o.n, \" \", mov.t.n);\n }\n });\n lines.moves = newMoves;\n\n //console.log(lines);\n}", "prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }", "removeAllChildren() {\n this.__childNodes = [];\n this.repeats = [];\n this.dispatchNodeEvent(new NodeEvent('repeated-fields-all-removed', this.repeats, false));\n }", "function removeElements(elements)\r\n{\r\n for(var i = 0, l = elements.length ; i < l ; ++i) {\r\n orderTree.removeElement(elements[i]);\r\n if(verifyTree && !testFailed) {\r\n var errorNodes = [];\r\n testSubTreeSize(orderTree.root, errorNodes);\r\n if(errorNodes.length > 0) {\r\n console.log(\"step\", i, \"node size error when removing\",\r\n elements[i]);\r\n testFailed = true;\r\n }\r\n checkTree(orderTree);\r\n if(testFailed)\r\n console.log(\"failure in step\", i);\r\n if(!testNoHeap(orderTree)) {\r\n testFailed = true;\r\n console.log(\"no heap count test failure in step\", i);\r\n }\r\n }\r\n }\r\n}", "function stream_remove_all(v, xs) {\n return is_null(xs)\n ? null\n : v === head(xs)\n ? stream_remove_all(v, stream_tail(xs))\n : pair(head(xs), () => stream_remove_all(v, stream_tail(xs)));\n}", "function removeClass(array, target) {\r\n if (array.length > 0) {\r\n for (var i = 0; i < array.length; i++) {\r\n var element = array[i];\r\n if (element.classList.contains(target)) {\r\n element.classList.remove(target);\r\n }\r\n }\r\n }\r\n}", "function remove_all_children(element,args) {\n //\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n}", "function remove(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> list<a> */ {\n return filter(xs, function(x /* 23638 */ ) {\n return !((pred(x)));\n });\n}", "function cleanArcReferences(dataset) {\n var nodes = new NodeCollection(dataset.arcs);\n var map = findDuplicateArcs(nodes);\n var dropCount;\n if (map) {\n replaceIndexedArcIds(dataset, map);\n }\n dropCount = deleteUnusedArcs(dataset);\n if (dropCount > 0) {\n // rebuild nodes if arcs have changed\n nodes = new NodeCollection(dataset.arcs);\n }\n return nodes;\n}", "function remove_duplicates(array)\n{\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\twhile (array.slice(i+1,array.length).indexOf(array[i]) != -1)\n\t\t{\n\t\t\tarray.splice(i,1);\n\t\t}\n\t}\n\treturn array;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load schedule pks that belong to selected date for copying week.
function copyWeekSchedulePks() { $prev_day_clicked = $(".fc-day-clicked"); // Check if a date has been clicked if ($prev_day_clicked.length) { copyBtnActive = 'week'; var date = $addScheduleDate.val(); // Get start and end of week given selected date var selectedDate = moment(date); var dayOfWeek = selectedDate.day(); var startOfWeek = moment(selectedDate).subtract(dayOfWeek, 'days'); var endOfWeek = moment(startOfWeek).add(7, 'days'); // Get dates in week var weekDates = _enumerateDaysBetweenDates(startOfWeek, endOfWeek); // Style copy buttons and tooltips $(".copy-active").removeClass("copy-active"); $copyWeekBtn.addClass("copy-active"); var startDateStr = startOfWeek.format("MMMM Do"); var endDateStr = endOfWeek.subtract(1, 'days').format("MMMM Do"); copyButtonTooltips(startDateStr + " - " + endDateStr); // Find all events with date belonging to any date within selected week var schedulePks = []; var fullCalEvents = $fullCal.fullCalendar("clientEvents"); for (var i=0; i<fullCalEvents.length; i++) { if (fullCalEvents[i].isSchedule) { var start = moment(fullCalEvents[i].start); var eventDate = start.format(DATE_FORMAT); for (var j=0; j<weekDates.length; j++) { if (weekDates[j] === eventDate) { schedulePks.push(fullCalEvents[i].id); break; } } } } copyWeekSchedulePksList = schedulePks; } else { $alertDayNoteModal = $("#noteAlertModal"); $alertDayNoteModal.css("margin-top", Math.max(0, ($(window).height() - $alertDayNoteModal.height()) / 2)); $alertDayNoteModal.modal('show'); } }
[ "function copyDaySchedulePks() {\r\n $prev_day_clicked = $(\".fc-day-clicked\"); // Check if a date has been clicked\r\n if ($prev_day_clicked.length) {\r\n copyBtnActive = 'day';\r\n var date = $addScheduleDate.val();\r\n\r\n // Style copy buttons and tooltips\r\n $(\".copy-active\").removeClass(\"copy-active\");\r\n $copyDayBtn.addClass(\"copy-active\");\r\n var dateStr = moment(date).format(\"dddd, MMMM Do\");\r\n copyButtonTooltips(dateStr);\r\n\r\n\r\n // Find all events with date belonging to selected date\r\n var schedulePks = [];\r\n var fullCalEvents = $fullCal.fullCalendar(\"clientEvents\");\r\n for (var i=0; i<fullCalEvents.length; i++) {\r\n var start = moment(fullCalEvents[i].start);\r\n var eventDate = start.format(DATE_FORMAT);\r\n if (date === eventDate && fullCalEvents[i].isSchedule) {\r\n schedulePks.push(fullCalEvents[i].id);\r\n }\r\n }\r\n copyDaySchedulePksList = schedulePks;\r\n } else {\r\n $alertDayNoteModal = $(\"#noteAlertModal\");\r\n $alertDayNoteModal.css(\"margin-top\", Math.max(0, ($(window).height() - $alertDayNoteModal.height()) / 2));\r\n $alertDayNoteModal.modal('show');\r\n }\r\n }", "function _createCopySchedules(data) {\r\n var info = JSON.parse(data);\r\n $(\"body\").css(\"cursor\", \"default\");\r\n copyConflictSchedules = info[\"schedules\"];\r\n\r\n // Display conflicts if any and remove them from list of schedules to be\r\n // rendered if user does not want to add them.\r\n var availabilities = info['availability'];\r\n if (Object.getOwnPropertyNames(availabilities).length > 0) {\r\n _copyConflicts(availabilities);\r\n } else {\r\n renderCopiedSchedules()\r\n }\r\n\r\n // Update cost display to reflect any cost changes\r\n if (info[\"cost_delta\"]) {\r\n updateHoursAndCost(info[\"cost_delta\"]);\r\n reRenderAllCostsHours();\r\n }\r\n }", "listWeekly() {\n const weekBefore = dateService.getWeekBefore();\n return this.trafficRepository.getWeeklyData(weekBefore)\n .then(data => {\n const mappedData = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(1, 7);\n const valuesToAdd = range.filter(x => !mappedData.find(item => item.group === x));\n\n return mappedData.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }", "_selectWeek() {\n this._weeks.forEach(week => {\n const _week = week;\n const dayInThisWeek = _week.findIndex(item => {\n const date = _CalendarDate.default.fromTimestamp(parseInt(item.timestamp) * 1000);\n return date.getMonth() === this._calendarDate.getMonth() && date.getDate() === this._calendarDate.getDate();\n }) !== -1;\n if (dayInThisWeek) {\n // The current day is in this week\n const notAllDaysOfThisWeekSelected = _week.some(item => item.timestamp && !this.selectedDates.includes(parseInt(item.timestamp)));\n if (notAllDaysOfThisWeekSelected) {\n // even if one day is not selected, select the whole week\n _week.filter(item => item.timestamp).forEach(item => {\n this._addTimestampToSelection(parseInt(item.timestamp));\n });\n } else {\n // only if all days of this week are selected, deselect them\n _week.filter(item => item.timestamp).forEach(item => {\n this._removeTimestampFromSelection(parseInt(item.timestamp));\n });\n }\n }\n });\n this.fireEvent(\"change\", {\n timestamp: this.timestamp,\n dates: this.selectedDates\n });\n }", "function fillDates() {\n\t$.getJSON(\n\t\t'/getScheduleByYear',\n\t\tfunction(data) {\n\t\t\tupdateDate(data);\n\t\t\t$('#season').val($('#date option:selected').data('season'));\n\t\t\t$('#week').val($('#date option:selected').data('week'));\n\t\t\tupdateTimes();\n\t\t\tchangeTeams();\n\t\t\tfillTeamPlayers(true);\n\t\t\tfillTeamPlayers(false);\n\n\t\t\tvar query = getURLParam('success');\n\t\t\tif(query != undefined)\n\t\t\t\tpresetDate();\n\t\t}\n\t);\n}", "function loadWeeklyPeriod (previous) {\n\tif (previous === true) {\n\t\tchartsWeeklyPeriod += 1;\n\t} else {\n\t\tchartsWeeklyPeriod -= 1;\n\t}\n\n\tloadWeeklyCharts();\n}", "function fcnCopyStandingsSheets(ss, shtConfig, RspnWeekNum, AllSheets){\n\n var shtIDs = shtConfig.getRange(17,7,20,1).getValues();\n var ssLgStdIDEn = shtIDs[4][0];\n var ssLgStdIDFr = shtIDs[5][0];\n \n // Open League Player Standings Spreadsheet\n var ssLgEn = SpreadsheetApp.openById(shtIDs[4][0]);\n var ssLgFr = SpreadsheetApp.openById(shtIDs[5][0]);\n \n // Match Report Form URL\n var FormUrlEN = shtConfig.getRange(19,2).getValue();\n var FormUrlFR = shtConfig.getRange(22,2).getValue();\n \n // League Name\n var Location = shtConfig.getRange(3,9).getValue();\n var LeagueTypeEN = shtConfig.getRange(13,2).getValue();\n var LeagueNameEN = Location + ' ' + LeagueTypeEN;\n var LeagueTypeFR = shtConfig.getRange(14,2).getValue();\n var LeagueNameFR = LeagueTypeFR + ' ' + Location;\n \n // Sheet Initialization\n var rngSheetInitializedEN = shtConfig.getRange(34,5);\n var SheetInitializedEN = rngSheetInitializedEN.getValue();\n var rngSheetInitializedFR = shtConfig.getRange(35,5);\n var SheetInitializedFR = rngSheetInitializedFR.getValue();\n \n // Number of Players\n var NbPlayers = shtConfig.getRange(11,2).getValue();\n var LeagueWeekLimit = shtConfig.getRange(83, 2).getValue();\n var WeekSheet = RspnWeekNum + 1;\n \n // Function Variables\n var ssMstrSht;\n var ssMstrShtStartRow;\n var ssMstrShtMaxRows;\n var ssMstrShtNbCol;\n var ssMstrShtData;\n var ssMstrStartDate;\n var ssMstrEndDate;\n var NumValues;\n var ColValues;\n var SheetName;\n \n var ssLgShtEn;\n var ssLgShtFr;\n var WeekGame;\n \n // Loops through tabs 0-9 (Standings, Cumulative Results, Week 1-8)\n for (var sht = 0; sht <= 9; sht++){\n ssMstrSht = ss.getSheets()[sht];\n SheetName = ssMstrSht.getSheetName();\n \n if(sht == 0 || sht == 1 || sht == WeekSheet || AllSheets == 1){\n ssMstrShtMaxRows = ssMstrSht.getMaxRows();\n \n // Get Sheets\n ssLgShtEn = ssLgEn.getSheets()[sht];\n ssLgShtFr = ssLgFr.getSheets()[sht];\n \n // If sheet is Standings\n if (sht == 0) {\n ssMstrShtStartRow = 6;\n ssMstrShtNbCol = 7;\n }\n \n // If sheet is Cumulative Results or Week Results\n if (sht == 1) {\n ssMstrShtStartRow = 5;\n ssMstrShtNbCol = 13;\n }\n \n // If sheet is Cumulative Results or Week Results\n if (sht > 1 && sht <= 9) {\n ssMstrShtStartRow = 5;\n ssMstrShtNbCol = 11;\n }\n \n // Set the number of values to fetch\n NumValues = ssMstrShtMaxRows - ssMstrShtStartRow + 1;\n \n // Get Range and Data from Master\n ssMstrShtData = ssMstrSht.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).getValues();\n \n // And copy to Standings\n ssLgShtEn.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).setValues(ssMstrShtData);\n ssLgShtFr.getRange(ssMstrShtStartRow,1,NumValues,ssMstrShtNbCol).setValues(ssMstrShtData);\n \n // Hide Unused Rows\n if(NbPlayers > 0){\n ssLgShtEn.hideRows(ssMstrShtStartRow, ssMstrShtMaxRows - ssMstrShtStartRow + 1);\n ssLgShtEn.showRows(ssMstrShtStartRow, NbPlayers);\n ssLgShtFr.hideRows(ssMstrShtStartRow, ssMstrShtMaxRows - ssMstrShtStartRow + 1);\n ssLgShtFr.showRows(ssMstrShtStartRow, NbPlayers);\n }\n \n // Week Sheet \n if (sht == WeekSheet){\n Logger.log('Week %s Sheet Updated',sht-1);\n ssMstrStartDate = ssMstrSht.getRange(3,2).getValue();\n ssMstrEndDate = ssMstrSht.getRange(4,2).getValue();\n ssLgShtEn.getRange(3,2).setValue('Start: ' + ssMstrStartDate);\n ssLgShtEn.getRange(4,2).setValue('End: ' + ssMstrEndDate);\n ssLgShtFr.getRange(3,2).setValue('Début: ' + ssMstrStartDate);\n ssLgShtFr.getRange(4,2).setValue('Fin: ' + ssMstrEndDate);\n }\n \n // If the current sheet is greater than League Week Limit, hide sheet\n if(sht > LeagueWeekLimit + 1){\n ssLgShtEn.hideSheet();\n ssLgShtFr.hideSheet();\n }\n }\n \n // If Sheet Titles are not initialized, initialize them\n if(SheetInitializedEN != 1){\n // Standings Sheet\n if (sht == 0){\n Logger.log('Standings Sheet Updated');\n // Update League Name\n ssLgShtEn.getRange(4,2).setValue(LeagueNameEN + ' Standings')\n ssLgShtFr.getRange(4,2).setValue('Classement ' + LeagueNameFR)\n // Update Form Link\n ssLgShtEn.getRange(2,5).setValue('=HYPERLINK(\"' + FormUrlEN + '\",\"Send Match Results\")'); \n ssLgShtFr.getRange(2,5).setValue('=HYPERLINK(\"' + FormUrlFR + '\",\"Envoyer Résultats de Match\")'); \n }\n \n // Cumulative Results Sheet\n if (sht == 1){\n Logger.log('Cumulative Results Sheet Updated');\n WeekGame = ssMstrSht.getRange(2,3,3,1).getValues();\n ssLgShtEn.getRange(2,3,3,1).setValues(WeekGame);\n ssLgShtFr.getRange(2,3,3,1).setValues(WeekGame);\n \n // Loop through Values in columns K and M to translate each value\n // Column K (11)\n ColValues = ssLgShtFr.getRange(ssMstrShtStartRow, 11, NumValues, 1).getValues();\n for (var row = 0 ; row < NumValues; row++){\n if (ColValues[row][0] == 'Active') ColValues[row][0] = 'Actif';\n if (ColValues[row][0] == 'Eliminated') ColValues[row][0] = 'Éliminé';\n }\n ssLgShtFr.getRange(ssMstrShtStartRow, 11, NumValues, 1).setValues(ColValues);\n \n // Loop through Values in columns K and M to translate each value\n // Column M (13)\n ColValues = ssLgShtFr.getRange(ssMstrShtStartRow, 13, NumValues, 1).getValues();\n for (var row = 0 ; row < NumValues; row++){\n if (ColValues[row][0] == 'Yes') ColValues[row][0] = 'Oui';\n if (ColValues[row][0] == 'No') ColValues[row][0] = 'Non';\n }\n ssLgShtFr.getRange(ssMstrShtStartRow, 13, NumValues, 1).setValues(ColValues);\n }\n \n // Set Initialized Value to Config Sheet to skip this part\n if(sht == 9) {\n rngSheetInitializedEN.setValue(1);\n rngSheetInitializedFR.setValue(1);\n }\n }\n }\n}", "function loadWeeklyCharts () {\n\tchartsCurrentLevel = chartsLevel.weekly;\n\tchartsCurrentDays = 7;\n\tchartsDateFormat = '%b %e';\n\n\t// reset the charts monthly period\n\tchartsMonthlyPeriod = 0;\n\n\t// taking care of weird situations when the period might be out of bounds\n\tif (chartsWeeklyPeriod < chartsMinWeeklyPeriod) {\n\t\tchartsWeeklyPeriod = chartsMinWeeklyPeriod;\n\t} else if (chartsWeeklyPeriod > chartsMaxWeeklyPeriod) {\n\t\tchartsWeeklyPeriod = chartsMaxWeeklyPeriod;\n\t}\n\n\tvar todayStr = Util.getDateStr(Util.today());\n\tfor (var i = 0; i < chartsData.days.length; i++) {\n\t\tif (chartsData.days[i] == todayStr) {\n\t\t\tvar sliceStart = i - 1; // start from yesterday\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvar sliceEnd = sliceStart + 7;\n\n\t// if the slice end is 0 then we need to make it (-1 for the above day in the past)\n\tif (sliceEnd === 0) {\n\t\tsliceEnd = chartsData.days.length - 1;\n\t}\n\n\t//console.log(\"Start: %d End: %d\", sliceStart, sliceEnd);\n\t// set the categories and series for all charts\n\tchartsData.currentAxisCategories = chartsData.days.slice(sliceStart, sliceEnd);\n\tchartsData.maxt.currentSeries = chartsData.maxt.data.slice(sliceStart, sliceEnd);\n\tchartsData.mint.currentSeries = chartsData.mint.data.slice(sliceStart, sliceEnd);\n\tchartsData.temperature.currentSeries = chartsData.temperature.data.slice(sliceStart, sliceEnd);\n\tchartsData.qpf.currentSeries = chartsData.qpf.data.slice(sliceStart, sliceEnd);\n\tchartsData.rain.currentSeries = chartsData.rain.data.slice(sliceStart, sliceEnd);\n\tchartsData.et0.currentSeries = chartsData.et0.data.slice(sliceStart, sliceEnd);\n\n\tfor (var programIndex = 0; programIndex < chartsData.programs.length; programIndex++) {\n\t\tchartsData.programs[programIndex].currentSeries = chartsData.programs[programIndex].data.slice(sliceStart, sliceEnd);\n\t\tchartsData.programsFlags[programIndex].currentSeries = chartsData.programsFlags[programIndex].data.slice(sliceStart, sliceEnd);\n\t}\n\n\t// render all charts with the currentAxisCategories and currentSeries\n\tgenerateCharts();\n\n\t//For water gauge show only last week (today - 7)\n\tsetWaterSavedValueForDays(chartsCurrentDays);\n\tgenerateWaterSavedGauge();\n}", "function updateDate(schedule) {\n\tvar option;\n\n\tif(schedule.length != 0) {\n\t\t$('#date').empty();\n\n\t\t$.each(schedule, function(i, week) {\n\t\t\toption = '<option value=\"' + week.date + '\" data-season=\"' + week.season + '\" data-week=\"' + week.week + '\" >';\n\t\t\toption += week.date;\n\t\t\toption += '</option>';\n\n\t\t\t$('#date').append(option);\n\n\t\t\tGAMES[i] = new Array();\n\t\t\tfor(var j = 0; j < week.games.length; j++) {\n\t\t\t\tGAMES[i].push(week.games[j]);\n\t\t\t}\n\t\t});\n\t}\n}", "function loadWorkScheduleScreen(){\n\tvar dayArray = ['mo','tu','we','th','fr','sa','su'];\n\t\n\t//Set the numbers and fill heights for the 7 days of the week\n\tfor(i=0;i<7;i++){\n\t\t$(\"#workScheduleHours-\" + dayArray[i])[0].innerHTML = U.profiles[Profile].workSchedule[dayArray[i]];\n\t\t$(\"#workScheduleDayFill-\" + dayArray[i])[0].style.height = (U.profiles[Profile].workSchedule[dayArray[i]] * 4.7) + \"%\";\n\t}\n\t//Initial set up shows Monday by default\n\t$(\"#workScheduleCurrentDay\")[0].innerHTML = \"Monday\";\n\t$(\"#workScheduleCurrentDayHoursInput\")[0].value = U.profiles[Profile].workSchedule.mo;\n\t$(\".errorDiv\").hide();\n}", "function getTimesheets(d) {\n return d.get(\"timesheets\");\n }", "function getTimecardsByDateLocal(seldate) {\n var timecards = JSON.parse(localStorage.getItem('timecards'));\n var selTimecards = [];\n if (timecards !== null || undefined) {\n for (var i = 0; i < timecards.length; i++) {\n if (seldate == timecards[i].week_starts_on && timecards[i].state == 'Pending') {\n selTimecards.push(timecards[i]);\n }\n }\n return selTimecards;\n } else {\n return selTimecards;\n }\n }", "setWeekDates(){\r\n\t\t$('.day-nav').find('span').each((i, el) => $(el).html(this.week[i]));\r\n\t}", "function renderCopiedSchedules() {\r\n // Create fullcalendar events corresponding to schedules\r\n if (displaySettings[\"unique_row_per_employee\"]) {\r\n var events = _copySchedulesToUniqueRowEvents(copyConflictSchedules);\r\n } else {\r\n var events = _schedulesToEvents(copyConflictSchedules);\r\n $fullCal.fullCalendar(\"renderEvents\", events);\r\n }\r\n }", "function getWorkshopsInstances() {\n EventsService.getInstancesWorkshop()\n .success(function (data) {\n $scope.instances = data;\n\n for (var i = 0; i < $scope.instances.data.length; i++) {\n var d = new Date($scope.instances.data[i].begin_at);\n moment.locale('fr');\n $scope.instances.data[i].dateFormat = moment(d).format(\"L\");\n $scope.instances.data[i].timeFormat = moment(d).format('LT');\n }\n });\n }", "function loadSchedule() {\n firebase.firestore().enablePersistence()\n .then(function() {\n // Initialize Cloud Firestore through firebase\n var db = firebase.firestore();\n var eventList = document.getElementById('cont');\n var count = 0;\n var weekday = new Array(7);\n\n weekday[0] = \"Sun\";\n weekday[1] = \"Mon\";\n weekday[2] = \"Tues\";\n weekday[3] = \"Wed\";\n weekday[4] = \"Thurs\";\n weekday[5] = \"Fri\";\n weekday[6] = \"Sat\";\n\n firebase.auth().onAuthStateChanged(function(user) {\n if(user) {\n var email = user.email.replace('.', '').replace('@', '');\n db.collection(\"users\").get().then(function(querySnapshot) {\n querySnapshot.forEach(function(dc) {\n if(dc.id === email) {\n var team = dc.data().team;\n var counter = 0;\n document.getElementById('eventrow0').style.display = 'none';\n db.collection(\"teams\").doc(team).collection('schedule').get().then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n var clone = document.getElementById('eventrow0').cloneNode(true);\n var startdate = doc.data().startDate.toString();\n var arr = startdate.split('-'); // year, month, day\n console.log(arr[0]+\" - \"+arr[1]+\" - \"+arr[2]);\n var day = new Date(arr[0], arr[1]-1, arr[2]);\n var c_day = new Date();\n if(c_day.getTime() <= day.getTime()){\n if(doc.data().eventType === 'game') {\n clone.querySelector('.eventtitle').innerHTML = 'Game: ' + doc.data().title;\n }\n else {\n clone.querySelector('.eventtitle').innerHTML = 'Event: ' + doc.data().title;\n }\n clone.id = doc.id;\n clone.querySelector('.eventlocation').innerHTML = 'Location: ' + doc.data().location;\n clone.querySelector('.eventstartdate').innerHTML = 'Date: ' + doc.data().startDate;\n clone.querySelector('.eventstarttime').innerHTML = 'Time: ' + doc.data().startTime;\n clone.querySelector('.editevent').name = doc.id;\n clone.querySelector('.deleteevent').name = doc.id;\n document.getElementById('cont').appendChild(clone);\n document.getElementById(doc.id).style.display = 'block';\n }\n });\n });\n }\n\n });\n });\n }\n });\n })\n .catch(function(err) {\n if (err.code == 'failed-precondition') {\n // Multiple tabs open, persistence can only be enabled\n // in one tab at a a time.\n } else if (err.code == 'unimplemented') {\n // The current browser does not support all of the\n // features required to enable persistence\n }\n });\n}", "function transformToSchedule(data){\n let daySessions = []\n let presentations = getPresentations(data)\n let sessions = getSessions(presentations)\n\n for (let i = 0; i < confLength; i++ ){\n daySessions.push(\n sessions.filter( \n d => d[0].session_id.substring(0,2) == confDayStart + i\n ))\n }\n return daySessions\n}", "function pullExistingCron() {\n pool.getConnection(function(err, connection) {\n if(err) { console.log(err); return; }\n var sql = 'select * from f_schedule';\n connection.query(sql, [], function(err, results) {\n\n // if there is a result\n if (results) {\n\n results.forEach(function(result) {\n var report = {accountid:result.accountid,groupid: result.groupid,startdate:result.startdate,enddate:result.enddate, lengthdays:result.lengthdays};\n var schedule = ''+ result.seconds+' '+result.minutes+' '+result.hours+' '+result.dayofmonth+' '+result.months+' '+result.dayofweek+'';\n console.log(report);\n console.log(schedule);\n // creae the job\n var job = new CronJob({\n cronTime: schedule,\n onTick: function() {\n // this is the scheduled task\n pullautoreport(report);\n },\n start: true,\n //timeZone: \"America/Los_Angeles\"\n });\n // start the job\n job.start();\n });\n\n }\n\n connection.release(); // always put connection back in pool after last query\n if(err) { console.log(err); return; }\n });\n });\n\n\n}", "function fillWeekDays(week) {\r\n\tangular.forEach(ref, function(refDay) {\r\n\t\taddIfNotExists(week, refDay);\r\n\t});\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the Meridiem for the hour
_convert_12_hour_method(hour) { // This methods converts the 24 hour method to 12 hour method and meridiem let convertedHour = hour%12 !== 0 ? hour%12 : 12; // Converts 24 hour method to 12 hour method let meridiem = this._getMeridiem(hour); return [convertedHour, meridiem]; }
[ "function getHoursFromTemplate() {\n var hours = parseInt(scope.hours, 10);\n var valid = ( scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);\n if (!valid) {\n return undefined;\n }\n\n if (scope.showMeridian) {\n if (hours === 12) {\n hours = 0;\n }\n if (scope.meridian === meridians[1]) {\n hours = hours + 12;\n }\n }\n return hours;\n }", "function getHoursFromTemplate(){var hours=parseInt(scope.hours,10);var valid=scope.showMeridian?hours>0&&hours<13:hours>=0&&hours<24;if(!valid){return undefined;}if(scope.showMeridian){if(hours===12){hours=0;}if(scope.meridian===meridians[1]){hours=hours+12;}}return hours;}", "get formattedHours() {\n const _hours = this.hours;\n let hours = _hours;\n if (_hours !== null) {\n hours = this.amPm && _hours > HOURS_OF_NOON\n ? _hours - HOURS_OF_NOON : this.amPm && !_hours ? HOURS_OF_NOON : _hours;\n }\n return this.formattedUnit(hours);\n }", "function alignTimeText(hours, mins)\n{ \n let digit_1_px = 12; // pixel amount of digit '1' \n let digit_default_px = 27; // default pixel amount of digits 2..9\n\n /* set default values to each digit of xx:xx format */\n let h1_px = 0; // 1st digit (usually 0 except for hours 10, 11, and 12)\n let h2_px = digit_default_px; \n let m1_px = digit_default_px; \n let m2_px = digit_default_px; \n\n /* get 1st and 2nd digits of hours */\n let h1_digit = Math.floor(((hours)/10) % 10); // math is cool!\n let h2_digit = Math.floor(((hours)/1) % 10);\n\n /* check to see if one of the hour digits is a '1' */\n h1_px = (h1_digit == 1)? digit_1_px: h1_px;\n h2_px = (h2_digit == 1)? digit_1_px: h2_px;\n\n /* get 1st and 2nd digits of mins */\n let m1_digit = Math.floor(((mins)/10) % 10); \n let m2_digit = Math.floor(((mins)/1) % 10); \n\n /* check to see if one of the min digits is a '1' */\n m1_px = (m1_digit == 1)? digit_1_px: m1_px; \n m2_px = (m2_digit == 1)? digit_1_px: m2_px; \n\n let digit_space_count = (h1_px == 0)? 3: 4; // spaces in between 'xx:xx am' text based on hour digits \n let digit_space_px = 9 * digit_space_count; // space pixel = 9, multiplied by how many spaces needed\n let ampm_space_px = 9; // space between xx:xx and 'am' \n let ampm_px = 39; // pixel amount for 'am/pm' text\n\n /* calculates the entire pixel amount for the time and ampm label (including spaces) */\n let time_text_total_px = digit_space_px + h1_px + h2_px + m1_px + m2_px + ampm_space_px + ampm_px;\n\n /* calculates the time and ampm label positions based on the total pixel count (see css for alignment anchor info) */\n let time_label_position = (300 - time_text_total_px) / 2; // centers based on 300px span of versa display\n let ampm_label_position = time_label_position + time_text_total_px; \n\n /* set x coordinates of time and ampm labels, noice */\n time_label.x = time_label_position; \n ampm_label.x = ampm_label_position;\n}", "function pmAdd(hour)\n{\n //hour will be startHour or endHour, in string format\n hour = parseInt(hour);\n //check that it isn't 12pm, otherwise add 12\n if (hour != 12)\n {\n hour = (hour + 12) % 24;\n }\n return hour;\n}", "function convertHourToMilitary() {\n\n if (militaryTime === false) {\n militaryTime = true;\n\n }\n}", "function index2hm(index) {\n var hour = index2dectime(index);\n var whole_hour = Math.floor(hour);\n var rest = hour - whole_hour;\n var minutes = 60 * rest;\n var theTime = zero_pad(whole_hour) + ':' + zero_pad(minutes) + ':00';\n return theTime;\n}", "function parsear_tiempo(tiempo){\n tiempo = tiempo.split(\":\")\n var hora = parseInt(tiempo[0])\n //console.log(hora)\n if ( hora > 12 && hora<22)\n return \"0\"+(hora - 12) + \":\" + tiempo[1] + \" PM\"\n else if (hora < 12) { \n if (hora < 10)\n return \"0\" + hora + \":\" + tiempo[1] + \" AM\"\n else return hora + \":\" + tiempo[1] + \" AM\"\n }\n else if (hora == 12)\n return hora + \":\" + tiempo[1] + \" PM\"\n else if (hora >= 22 && hora < 24) return (hora - 12) + \":\" + tiempo[1] + \" PM\"\n else return \"00:\" + tiempo[1] + \" AM\"\n}", "function updateHours()\n{\n let nowHours = new Date();\n let nowHoursString = \"\";\n\n if (nowHours.getHours() === 0 && militaryTime === 0) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n\n else if (nowHours.getHours() < 10 && nowHours.getHours() != 0 && nowHours.getHours() != 1) {\n hoursMath.innerHTML = `0 + ${nowHours.getHours()} = ${nowHours.getHours()}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHours.getHours()*1);\n }\n\n else if (nowHours.getHours() === 12) {\n hoursMath.innerHTML = `1 + 2 = 12`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 2);\n }\n\n else if (nowHours.getHours() === 13 && militaryTime === 0) {\n hoursMath.innerHTML = `0 + 1 = 1`;\n hours.innerHTML = \"Hour\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, 1);\n }\n\n else if (nowHours.getHours() > 11 && nowHours.getHours() < 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `0 + ${nowHoursString[0]} = ${nowHoursString[0]}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, 0);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[0]*1);\n }\n\n else if (nowHours.getHours() <= 23 && nowHours.getHours() >= 22 && militaryTime === 0) {\n nowHoursString = (nowHours.getHours()-12).toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n \n else {\n nowHoursString = nowHours.getHours().toString();\n hoursMath.innerHTML = `${nowHoursString[0]} + ${nowHoursString[1]} = ${nowHoursString}`;\n hours.innerHTML = \"Hours\";\n ledFirst(hours11, hours12, hours14, hourOnLED, hourOffLED, nowHoursString[0]*1);\n ledSecond(hours21, hours22, hours24, hours28, hourOnLED, hourOffLED, nowHoursString[1]*1);\n }\n\n}", "function MakeMilitary(time) {\n\tvar number = parseInt(time.substring(0,2));\n\tvar minuteRegex = /[:][0-9][0-9]/g\n\tvar minutes = time.match(minuteRegex).toString().substring(1);\n\tif(time.includes(\"p\")) {\n\t\tif(number == 12) {\n\t\t\tvar num = \"12\";\n\t\t\treturn num + minutes;\n\t\t} \n\t\telse {\n\t\t\tnumber += 12; \n\t\t}\n\t}\n\telse { \n\t\tif(number == 12) {\n\t\t\tvar num = \"00\";\n\t\t\treturn num + minutes; \n\t\t}\n\t\tnumber = number.toString().padStart(2,'0');\n\t}\n\tvar time = number + minutes;\n\treturn time.toString();\n}", "function display12HrTime(hour, min, sec){\n document.getElementById(\"clock-time\").innerText = `${(hour % 12 || 12)} : ${min} : ${sec} ${hour < 12 ? 'am' : 'pm'}`;\n setTimeout(getTime, 1000);\n}", "function timeCode(seconds) {\n\tvar delim = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':';\n\n\t// const h = Math.floor(seconds / 3600);\n\t// const m = Math.floor((seconds % 3600) / 60);\n\tvar m = Math.floor(seconds / 60);\n\tvar s = Math.floor(seconds % 3600 % 60);\n\t// const hr = (h < 10 ? '0' + h + delim : h + delim);\n\tvar mn = (m < 10 ? '0' + m : m) + delim;\n\tvar sc = s < 10 ? '0' + s : s;\n\t// return hr + mn + sc;\n\treturn mn + sc;\n}", "function timeAmpmAdd30(timeString){\n\tvar min = parseInt(timeString.substring(timeString.length-2,timeString.length));\n\tvar hour = parseInt(timeString.substring(0,timeString.length-3));\n\t\tif(min+30>=60){\n\t\t\thour ++;\n\t\t\tmin = min-30;\n\t\t}else{\n\t\t\tmin = min+30;\n\t\t}\n\n\t\tif(hour<10){\n \tif(min<10){\n \tresult = \"0\"+hour+\":\"+\"0\"+min; \n \t}else{\n \tresult = \"0\"+hour+\":\"+min; \n \t}\n \t}else{\n \tif(min<10){\n \tresult = hour+\":\"+\"0\"+min; \n \t}else{\n \tresult = hour+\":\"+min; \n \t}\n\t\t}\n\t\n\t// console.log(result);\n\treturn result;\n}", "function timeCode(seconds) {\n\tvar delim = arguments.length <= 1 || arguments[1] === undefined ? ':' : arguments[1];\n\n\t// const h = Math.floor(seconds / 3600);\n\t// const m = Math.floor((seconds % 3600) / 60);\n\tvar m = Math.floor(seconds / 60);\n\tvar s = Math.floor(seconds % 3600 % 60);\n\t// const hr = (h < 10 ? '0' + h + delim : h + delim);\n\tvar mn = (m < 10 ? '0' + m : m) + delim;\n\tvar sc = s < 10 ? '0' + s : s;\n\t// return hr + mn + sc;\n\treturn mn + sc;\n}", "function toJalali() {\n\n const DATE_REGEX = /^((19)\\d{2}|(2)\\d{3})-(([1-9])|((1)[0-2]))-([1-9]|[1-2][0-9]|(3)[0-1])$/;\n\n if (DATE_REGEX.test(mDate)) {\n\n let dt = mDate.split('-');\n let ld;\n\n let mYear = parseInt(dt[0]);\n let mMonth = parseInt(dt[1]);\n let mDay = parseInt(dt[2]);\n\n let buf1 = [12];\n let buf2 = [12];\n\n buf1[0] = 0;\n buf1[1] = 31;\n buf1[2] = 59;\n buf1[3] = 90;\n buf1[4] = 120;\n buf1[5] = 151;\n buf1[6] = 181;\n buf1[7] = 212;\n buf1[8] = 243;\n buf1[9] = 273;\n buf1[10] = 304;\n buf1[11] = 334;\n\n buf2[0] = 0;\n buf2[1] = 31;\n buf2[2] = 60;\n buf2[3] = 91;\n buf2[4] = 121;\n buf2[5] = 152;\n buf2[6] = 182;\n buf2[7] = 213;\n buf2[8] = 244;\n buf2[9] = 274;\n buf2[10] = 305;\n buf2[11] = 335;\n\n if ((mYear % 4) !== 0) {\n day = buf1[mMonth - 1] + mDay;\n\n if (day > 79) {\n day = day - 79;\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = day / 31;\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n if ((mYear > 1996) && (mYear % 4) === 1) {\n ld = 11;\n } else {\n ld = 10;\n }\n day = day + ld;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n } else {\n day = buf2[mMonth - 1] + mDay;\n\n if (mYear >= 1996) {\n ld = 79;\n } else {\n ld = 80;\n }\n if (day > ld) {\n day = day - ld;\n\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = (day / 31);\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n day = day + 10;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n\n }\n\n return year.toString() + \"-\" + Math.floor(month).toString() + \"-\" + day.toString();\n }\n}", "function timeAmpmSubtract30(timeString){\n\tvar min = parseInt(timeString.substring(timeString.length-2,timeString.length));\n\tvar hour = parseInt(timeString.substring(0,timeString.length-3));\n\n\t//calc\n\t\tif(min==0){\n\t\t\tconsole.log(\"yes\");\n\t\t\tconsole.log(\"hour = \"+hour+\"; min =\"+ min);\n\t\t\thour --;\n\t\t\tmin = 30;\n\t\t} else if (min-30<=0){\n\t\t\thour --;\n\t\t\tmin = min+30;\n\t\t}else{\n\t\t\tmin = min-30;\n\t\t}\n\n\t\tif(hour<10){\n \tif(min<10){\n result = \"0\"+hour+\":\"+\"0\"+min; \n \t}else{\n result = \"0\"+hour+\":\"+min; \n } \n }else{\n \t\tif(min<10){\n \t\t\tresult = hour+\":\"+\"0\"+min;\n \t\t}else{\n \t\t\tresult = hour+\":\"+min;\n \t\t}\n\t\t}\n\t\n\treturn result;\n}", "function WhatIsTheTime(timeInMirror){\n\n let mir = timeInMirror.split(':')\n let hour = parseFloat(mir[0])\n let min = parseFloat(mir[1])\n let realHour = 11 - hour\n let realMin = 60 - min\n let realTime\n\n //conditionals if mirrored time hour is 11 or 12 because formula doesn't apply\n if (hour ===12){\n realHour = 11\n }\n else if (hour ===11){\n realHour = 12\n }\n\n //for x:00 times, display mirrored hour rather than i.e 7:60\n if(realMin === 60){\n realHour += 1\n realMin = 0\n }\n\n //single digit times need to concatonate 0 when converted back to string\n if(realHour.toString().length===1){\n realHour = '0'+realHour\n }\n if(realMin.toString().length===1){\n realMin = '0'+realMin\n }\n\n //if 6PM, or 12PM -> realTime is the same, else realTime = realHour + realMin based on calculations\n if (timeInMirror===\"06:00\" || timeInMirror===\"12:00\"){\n realTime = timeInMirror\n } else {\n realTime = realHour + ':' + realMin\n }\n\n return realTime\n}", "function timeStringShortAMPM(minutes, JD) {\n var julianday = JD;\n var floatHour = minutes / 60.0;\n var hour = Math.floor(floatHour);\n var floatMinute = 60.0 * (floatHour - Math.floor(floatHour));\n var minute = Math.floor(floatMinute);\n var floatSec = 60.0 * (floatMinute - Math.floor(floatMinute));\n var second = Math.floor(floatSec + 0.5);\n var PM = false;\n minute += (second >= 30)? 1 : 0;\n if (minute >= 60) {\n minute -= 60;\n hour ++;\n }\n var daychange = false;\n if (hour > 23) {\n hour -= 24;\n daychange = true;\n julianday += 1.0;\n }\n if (hour < 0) {\n hour += 24;\n daychange = true;\n julianday -= 1.0;\n }\n if (hour > 12) {\n hour -= 12;\n PM = true;\n }\n if (hour == 12) {\n PM = true;\n }\n if (hour == 0) {\n PM = false;\n hour = 12;\n }\n var timeStr = hour + \":\";\n if (minute < 10) // i.e. only one digit\n timeStr += \"0\" + minute + ((PM)?\"PM\":\"AM\");\n else\n timeStr += \"\" + minute + ((PM)?\"PM\":\"AM\");\n if (daychange) return timeStr + \" \" + calcDayFromJD(julianday);\n return timeStr;\n}", "getHoursSegment(value) {\n if (this.amPm) {\n if (value === HOURS_OF_NOON && this.isAM()) {\n value = 0;\n }\n if (this.isPM() && value < HOURS_OF_NOON) {\n value += HOURS_OF_NOON;\n }\n }\n return value;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Dependency Tracking build status for an organization
getArchitectDependencytrackingBuild() { return this.apiClient.callApi( '/api/v2/architect/dependencytracking/build', 'GET', { }, { }, { }, { }, null, ['PureCloud OAuth'], ['application/json'], ['application/json'] ); }
[ "function getAutoHostBuildStatus(autoHostLink) {\r\n return new Promise((resolve, reject) => {\r\n dashboardModel.getAutoHostBuildStatus(autoHostLink).then((data) => {\r\n resolve({ code: code.OK, message: '', data: data })\r\n }).catch((err) => {\r\n if (err.message === message.INTERNAL_SERVER_ERROR)\r\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\r\n else\r\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\r\n })\r\n })\r\n}", "postArchitectDependencytrackingBuild() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/architect/dependencytracking/build', \n\t\t\t'POST', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}", "function reportBuildStatus() {\n console.info('----\\n==> ✅ Building production completed (%dms).', (Date.now() - global.BUILD_STARTED));\n process.exit(0);\n}", "function get_inf_status(brand_campaign_id, account_id){\n const reco_inf_profile = campaign.access_influencer_subcollection(brand_campaign_id).doc(account_id);\n return reco_inf_profile.get()\n .then(snapshot => {\n const data = snapshot.data();\n return {inf_status: data.inf_signing_status};\n });\n}", "function getJiraClosedStatusName() {\n toolsService.fetchIntegrationOfTypeByName('TEST_CASE_MANAGEMENT')\n .then(rs => {\n if (rs.success) {\n const jira = rs.data.find((data) => data.name === 'JIRA');\n const setting = jira.settings.find((setting) => setting.param.name === 'JIRA_CLOSED_STATUS');\n\n if (setting) {\n vm.closedStatusName = setting.value ? setting.value.toUpperCase() : null;\n }\n } else {\n messageService.error(rs.message);\n }\n });\n }", "function getProjectInfoForReview(org) {\n let memberProjects = [];\n let nonMemberProjects = [];\n let requiresReview = 0;\n let canReviewAnything = false;\n let canWriteProjects = new Set(org.access).has('project:write');\n\n for (let team of org.teams) {\n for (let project of team.projects) {\n let canReview = false;\n let targetList = nonMemberProjects;\n if (team.isMember) {\n canReview = canWriteProjects;\n targetList = memberProjects;\n }\n targetList.push({\n projectId: project.id,\n projectName: project.name,\n isMember: team.isMember,\n requiresReview: false,\n canReview,\n teamName: team.name,\n callSign: project.callSign || null\n });\n }\n }\n\n return {\n memberProjects,\n nonMemberProjects,\n projects: memberProjects.concat(nonMemberProjects),\n requiresReview,\n canReviewAnything,\n hasNonMemberProjects: nonMemberProjects.length > 0\n };\n}", "function gpJobStatus(jobinfo) {\n //domUtils.show(dom.byId('status'));\n var jobstatus = '';\n switch (jobinfo.jobStatus) {\n case 'esriJobSubmitted':\n jobstatus = 'Submitted...';\n break;\n case 'esriJobExecuting':\n jobstatus = 'Executing...';\n break;\n case 'esriJobSucceeded':\n break;\n }\n console.log(jobstatus);\n }", "function getEnvStatus(env) {\n const URLs = {\n test: process.env.TEST_URL,\n production: process.env.PROD_URL\n };\n\n return rp({\n url: URLs[env] + '/status'\n }).then(response => {\n return JSON.parse(response);\n });\n}", "getV3ProjectsIdBuildsBuildIdTrace(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.getV3ProjectsIdBuildsBuildIdTrace(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "function checkStatus() {\n\t'use strict';\n\tconsole.log('Checking data coverage for our query period');\n\n\tds.historics.status({\n\t\t'start': startTime,\n\t\t'end': endTime\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic status for query period: ' + JSON.stringify(response));\n\t\t\tcompileStream();\n\t\t}\n\t});\n}", "getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit has\n/*let opts = {\n 'ref': \"ref_example\", // String | The ref\n 'stage': \"stage_example\", // String | The stage\n 'name': \"name_example\", // String | The name\n 'all': \"all_example\", // String | Show all statuses, default: false\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions.id, incomingOptions.sha, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function getEnvironmentStatus( environment, commits ) {\n\n\t\tvar isAllPassing = _.every(\n\t\t\tcommits,\n\t\t\tfunction operator( commit ) {\n\n\t\t\t\treturn( commit[ environment ].status === \"pass\" );\n\n\t\t\t}\n\t\t);\n\n\t\t// If all commits are passing, nothing else to check - the environment is\n\t\t// passing on the current deployment.\n\t\tif ( isAllPassing ) {\n\n\t\t\treturn( \"pass\" );\n\n\t\t}\n\n\t\tvar isAnyFailing = _.any(\n\t\t\tcommits,\n\t\t\tfunction operator( commit ) {\n\n\t\t\t\treturn( commit[ environment ].status === \"fail\" );\n\n\t\t\t}\n\t\t);\n\n\t\t// If any of the commits failed, nothing else to check - the environment is\n\t\t// failing on the current deployment.\n\t\tif ( isAnyFailing ) {\n\n\t\t\treturn( \"fail\" );\n\n\t\t}\n\n\t\t// If we made it this far, the environment is still in a pending state for\n\t\t// the current deployment.\n\t\treturn( \"pending\" );\n\n\t}", "getV3ProjectsIdBuildsBuildId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.getV3ProjectsIdBuildsBuildId(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "getVersionTrainingStatus(params) {\n return this.createRequest('', params, 'get');\n }", "waitForBuild({\n build,\n project,\n commit,\n timeout = 10 * 60 * 1000,\n interval = 1000\n }, onProgress) {\n if (commit && !project) {\n throw new Error('Missing project path for commit');\n } else if (!commit && !build) {\n throw new Error('Missing build ID or commit SHA');\n } else if (project) {\n validateProjectPath(project);\n }\n\n let sha = commit && ((0, _utils.git)(`rev-parse ${commit}`) || commit);\n\n let fetchData = async () => build ? (await this.getBuild(build)).data : (await this.getBuilds(project, {\n sha\n })).data[0];\n\n this.log.debug(`Waiting for build ${build || `${project} (${commit})`}...`); // recursively poll every second until the build finishes\n\n return new Promise((resolve, reject) => async function poll(last, t) {\n try {\n let data = await fetchData();\n let state = data === null || data === void 0 ? void 0 : data.attributes.state;\n let pending = !state || state === 'pending' || state === 'processing';\n let updated = JSON.stringify(data) !== JSON.stringify(last); // new data recieved\n\n if (updated) {\n t = Date.now(); // no new data within the timeout\n } else if (Date.now() - t >= timeout) {\n throw new Error('Timeout exceeded without an update');\n } // call progress every update after the first update\n\n\n if ((last || pending) && updated) {\n onProgress === null || onProgress === void 0 ? void 0 : onProgress(data);\n } // not finished, poll again\n\n\n if (pending) {\n return setTimeout(poll, interval, data, t); // build finished\n } else {\n // ensure progress is called at least once\n if (!last) onProgress === null || onProgress === void 0 ? void 0 : onProgress(data);\n resolve({\n data\n });\n }\n } catch (err) {\n reject(err);\n }\n }(null, Date.now()));\n }", "getGeneralSystemStatus() {\n const journey = this.props.spec.journey;\n if (journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC\n && journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n if (journey.steps.SUBPROCESS_LISTEN\n && journey.steps.SUBPROCESS_LISTEN.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n return 'preparation-error';\n }", "function checkStatus() {\n return new Promise((resolve, reject) => {\n getStatusFromCache()\n .then(function(data) {\n resolve(data);\n })\n .catch(function(err) {\n resolve(scrapeStatus());\n });\n });\n}", "async function fetchOrgName() {\n if (!window.org || !window.jwt) return null;\n const orgName = convertOrgName(window.org);\n console.log(`getting orgName for ${orgName}: ${window.org}`)\n const url = `settings/organizations/${orgName}`;\n console.log(url);\n return Promise.all([\n axios(apiConfig(url))\n .then(res => res.data)\n .then(org => org.description)\n ]);\n}", "getProjectAndDeps(name) {\n const project = this.getProject(name);\n return (0, _projects.includeTransitiveProjects)([project], this.allWorkspaceProjects);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }