query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Insert a new paragraph containing the specified text into the specified div node. If present, we set the class attribitue of this div to classAttr.
function insertText(stubDiv, text, classAttr) { var p = document.createElement('p'); if(classAttr) { p.setAttribute('class', classAttr); } p.innerHTML = text; stubDiv.appendChild(p); }
[ "function insertText(stubDiv, text, classAttr) {\n var p = document.createElement('p');\n\n if(classAttr) {\n\tp.setAttribute('class', classAttr);\n }\n\n p.innerHTML = text;\n\n stubDiv.appendChild(p);\n}", "function addParaToTextDiv(input) {\n $(\"<p>\").text(input).appendTo(\".text-div\");\n}", "function createNewParagraph(parentDiv, title, text, targetDiv, paragraphClassName) {\n var wrapper = document.createElement('div');\n wrapper.className = parentDiv;\n var p1 = document.createElement('P');\n p1.className = 'tmgmt-segments-title';\n p1.appendChild(document.createTextNode(title + ':'));\n wrapper.appendChild(p1);\n var p2 = document.createElement('P');\n p2.className = paragraphClassName;\n p2.appendChild(document.createTextNode(text));\n wrapper.appendChild(p2);\n targetDiv.appendChild(wrapper);\n }", "function addParagraph( p_textString, p_class ) {\n //Create paragraph element\n var par = document.createElement(\"p\");\n // Bootstrap class\n par.className = p_class; \n //Add text to paragraph\n par.appendChild(document.createTextNode( p_textString ));\n //Return paragraph\n return par;\n}", "function addParagraph(content){\n let selectingDivs = document.querySelectorAll(\"main div\")\n let firstDiv = selectingDivs[0]\n let newPinsideFirstDiv = document.createElement(\"p\")\n firstDiv.insertAdjacentElement (\"beforeend\", newPinsideFirstDiv )\n newPinsideFirstDiv.innerText = content\n }", "function createParagraph(text, className){\r\n //creating paraghraph element\r\n var paragraph = document.createElement(\"p\");\r\n //creating text for paragraph\r\n var txt = document.createTextNode(text);\r\n //assigning class to element\r\n if (typeof className != undefined){\r\n paragraph.classList.add(className);\r\n }\r\n //appending element to body\r\n document.body.appendChild(paragraph);\r\n //paragraph.setAttribute(\"align\", \"center\");\r\n //appending text to paragraph\r\n paragraph.appendChild(txt);\r\n return paragraph;\r\n }", "function insert_Element() {\n // Creating the p element\n var paragraph1 = document.createElement(\"p\");\n\n // Creating the text content\n var paraText = document.createTextNode(\"Inserting a new element into the page\");\n\n // Appending the text content to the p element\n paragraph1.appendChild(paraText);\n\n // Selecting the div element by ID\n var element = document.getElementById('newDiv');\n\n // Appending the child element to the Div\n element.appendChild(paragraph1);\n}", "function addParagraph(className, classArray, innerText) {\n\tvar paragraph = document.createElement(\"p\");\n\tparagraph.innerText = innerText;\n\tvar addTo = document.getElementsByClassName(className)[classArray];\n\taddTo.appendChild(paragraph);\n}", "function appendNewDiv(className, text) {\n let result = document.createElement(\"div\");\n result.className = className;\n result.innerText = text;\n resultFeed.appendChild(result);\n}", "function create_text_div(text, className) {\n var elem = document.createElement(\"div\");\n elem.classList.add(className);\n var textelem = document.createTextNode(text);\n elem.appendChild(textelem);\n return elem;\n}", "function paragraph({ id, text, cls } = {}) {\n\treturn new Paragraph({ id, text, cls });\n}", "function addParagraph(text) {\n const para = document.createElement(\"p\");\n para.innerHTML = text;\n paragraphListElement.appendChild(para);\n}", "function createDiv(className, content) {\n let pTag = document.createElement('p');\n let divTag = document.createElement('div');\n pTag.textContent = content;\n divTag.classList.add(className);\n divTag.appendChild(pTag);\n // console.log(divTag);\n return divTag;\n }", "function addNewParagraph(temp){\n\tconst div = document.querySelector('#first-div')\n\tdiv.innerHTML += temp\n}", "createParagraph(className, content) {\n const p = document.createElement(\"p\");\n p.className = className;\n p.innerHTML = content;\n return p;\n }", "function createParagraph(text){\n var p = document.createElement(\"p\");\n p.innerHTML = text;\n return p;\n }", "function encloseInDiv( textNode, pos, length, className ) {\n\t\tvar el = document.createElement('div'),\n\t\t\tsecondPart = textNode.splitText(pos),\n\t\t\tthirdPart = secondPart.splitText(length);\n\t\tel.className = className;\n\t\tsecondPart.parentNode.insertBefore(el, secondPart);\n\t\tel.appendChild(secondPart);\n\t\treturn thirdPart;\n\t}", "function domManipTest() {\n // Creates the 'paragraph' element\n var paragaph = document.createElement(\"p\");\n\n var text = document.createTextNode(\"This is a text node that will become a child in the paragraph element. Clicking the button again will add this paragraph again, thus duplicating the text.\");\n\n // Adds the text into the paragraph element\n paragaph.appendChild(text);\n\n // Adds the paragraph to the div for the user to see\n document.getElementById(\"domManip\").appendChild(paragaph);\n}", "function appendParagraph(text, id){\n var para = document.createElement(\"P\");\n var t = document.createTextNode(text);\n para.appendChild(t);\n document.getElementById(id).appendChild(para); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If `str` is in valid 6digit hex format with prefix, returns an RGB color (with alpha 100). Otherwise returns undefined.
function _hex6(str) { if ('#' === str[0] && 7 === str.length && /^#[\da-fA-F]{6}$/.test(str)) { return { r: parseInt(str.slice(1, 3), 16), g: parseInt(str.slice(3, 5), 16), b: parseInt(str.slice(5, 7), 16), a: MAX_COLOR_ALPHA }; } }
[ "function _hex6(str) {\n if ('#' === str[0] && 7 === str.length && /^#[\\da-fA-F]{6}$/.test(str)) {\n return {\n r: parseInt(str.slice(1, 3), 16),\n g: parseInt(str.slice(3, 5), 16),\n b: parseInt(str.slice(5, 7), 16),\n a: MAX_COLOR_ALPHA\n };\n }\n}", "function _hex6(str) {\n if ('#' === str[0] && 7 === str.length && /^#[\\da-fA-F]{6}$/.test(str)) {\n return {\n r: parseInt(str.slice(1, 3), 16),\n g: parseInt(str.slice(3, 5), 16),\n b: parseInt(str.slice(5, 7), 16),\n a: MAX_COLOR_ALPHA\n };\n }\n}", "function isHexaColor(str) {\r\n if (!isString(str))\r\n return false;\r\n else\r\n return hexaColor.test(str);\r\n}", "function HEXToRGB(str) {\n // body...\n function h2r(str) {\n // body...\n return parseInt(str, 16);\n }\n\n function r2h(str) {\n // body...\n return Number(str).toString(16);\n }\n\n if (str.length === 7 && str[0] === \"#\") {\n inner1 = h2r(str.slice(1,3));\n inner2 = h2r(str.slice(3,5));\n inner3 = h2r(str.slice(5,7));\n if (inner1 > 255 || inner2 > 255 || inner3 > 255){\n alert( \"Error HEX value\");\n }else {\n const r = `(${inner1},${inner2},${inner3})`;\n return r;\n }\n } else {\n const splitNum = str.split(\",\");\n const r = splitNum.reduce((acc, num) =>{\n if (num > 255) {\n alert(`${num} is not a valid value`);\n } else if (num < 16) {\n return acc + \"0\" + r2h(num);\n }else{\n return acc + r2h(num) ;\n }\n }, \"#\");\n return r;\n }\n}", "function isColorStringHexRGB(raw) {\n return hexRGBRegex.test(raw);\n}", "function stringToColor(str) {\r\n const r = parseInt(str.substring(0, 2), 16);\r\n const g = parseInt(str.substring(2, 4), 16);\r\n const b = parseInt(str.substring(4, 6), 16);\r\n return [r, g, b];\r\n}", "function colorFromHexString(string) {\n var sub = $.trim(string).substr(0, 1);\n\n if (sub == \"#\") {\n return string;\n }\n else {\n return \"#\" + string;\n }\n }", "function isRGBColor(str) {\r\n if (!isString(str))\r\n return false;\r\n else\r\n return rgbColor.test(str);\r\n}", "function _hex3(str) {\n if ('#' === str[0] && 4 === str.length && /^#[\\da-fA-F]{3}$/.test(str)) {\n return {\n r: parseInt(str[1] + str[1], 16),\n g: parseInt(str[2] + str[2], 16),\n b: parseInt(str[3] + str[3], 16),\n a: MAX_COLOR_ALPHA\n };\n }\n}", "function _hex3(str) {\r\n if ('#' === str[0] && 4 === str.length && /^#[\\da-fA-F]{3}$/.test(str)) {\r\n return {\r\n r: parseInt(str[1] + str[1], 16),\r\n g: parseInt(str[2] + str[2], 16),\r\n b: parseInt(str[3] + str[3], 16),\r\n a: MAX_COLOR_ALPHA\r\n };\r\n }\r\n}", "function parseColor(str) {\n var color = {\n \"r\": 0,\n \"g\": 0,\n \"b\": 0,\n \"a\": 1\n };\n \n if (str.match(/#/)) {\n color = parseHex(str);\n }\n else if (str.match(/rgb/)) {\n color = parseRGB(str);\n }\n else if (str.match(/hsl/)) {\n color = parseHSL(str);\n }\n\n return color;\n }", "function isValidColorCode(str) {\r\n\treturn /^\\#[0-9a-fA-F]{6}$/.test(str);\r\n}", "function seeColor(str){\n if(str.substring(0, 3) === 'red'){\n return 'red';\n }\n else if(str.substring(0,4) === 'blue'){\n return 'blue';\n }\n else\n return '';\n}", "function _hsla(str) {\r\n var match = str.match(/^hsl(a?)\\(([\\d., ]+)\\)$/);\r\n if (match) {\r\n var hasAlpha = !!match[1];\r\n var expectedPartCount = hasAlpha ? 4 : 3;\r\n var parts = match[2].split(/ *, */).map(Number);\r\n if (parts.length === expectedPartCount) {\r\n var rgba = hsl2rgb(parts[0], parts[1], parts[2]);\r\n rgba.a = hasAlpha ? parts[3] * 100 : MAX_COLOR_ALPHA;\r\n return rgba;\r\n }\r\n }\r\n}", "function hslaColor(str) {\n /*\n Split the string by the following 3 characters:\n * (\n * )\n * ,\n This will always leave an empty string as the last item in the array.\n */\n const [type, h, s, l, a, empty] = str.split(/[\\(\\),]/)\n const isHsl = type === 'hsl'\n const error = new TypeError(`\"${str}\" isn't a valid ${type} color.`)\n const getPercentNumAndCheck = val => {\n const num = +val.slice(0, -1)\n if (!/%$/.test(val) || !numCheck(num, 0, 100)) throw error\n return num / 100\n }\n\n // Check for the correct ending and the correct empty string - there's always an empty string.\n if (!str.endsWith(')') || (isHsl ? a : empty) !== '') throw error\n\n const hue = safeHue(h)\n const saturation = getPercentNumAndCheck(s)\n const lightness = getPercentNumAndCheck(l)\n const alpha = isHsl ? 1 : +a\n const alphaOk = numCheck(alpha, 0, 1)\n\n if (isNaN(hue) || !alphaOk) throw error\n\n const results = {h: hue, s: saturation, l: lightness, a: alpha}\n return addHex(addRgb(results))\n}", "function _hsla(str) {\n var match = str.match(/^hsl(a?)\\(([\\d., ]+)\\)$/);\n if (match) {\n var hasAlpha = !!match[1];\n var expectedPartCount = hasAlpha ? 4 : 3;\n var parts = match[2].split(/ *, */).map(Number);\n if (parts.length === expectedPartCount) {\n var rgba = (0,_hsl2rgb__WEBPACK_IMPORTED_MODULE_1__.hsl2rgb)(parts[0], parts[1], parts[2]);\n rgba.a = hasAlpha ? parts[3] * 100 : _consts__WEBPACK_IMPORTED_MODULE_0__.MAX_COLOR_ALPHA;\n return rgba;\n }\n }\n}", "function _rgba(str) {\r\n var match = str.match(/^rgb(a?)\\(([\\d., ]+)\\)$/);\r\n if (match) {\r\n var hasAlpha = !!match[1];\r\n var expectedPartCount = hasAlpha ? 4 : 3;\r\n var parts = match[2].split(/ *, */).map(Number);\r\n if (parts.length === expectedPartCount) {\r\n return {\r\n r: parts[0],\r\n g: parts[1],\r\n b: parts[2],\r\n a: hasAlpha ? parts[3] * 100 : MAX_COLOR_ALPHA\r\n };\r\n }\r\n }\r\n}", "function stringToColor(str) {\n return Float32Array.of(\n parseInt(str.substr(1, 2), 16) / 255.0,\n parseInt(str.substr(3, 2), 16) / 255.0,\n parseInt(str.substr(5, 2), 16) / 255.0\n );\n}", "function stringToColor(str) {\r\n return Float32Array.of(\r\n parseInt(str.substr(1, 2), 16) / 255.0,\r\n parseInt(str.substr(3, 2), 16) / 255.0,\r\n parseInt(str.substr(5, 2), 16) / 255.0\r\n );\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dial to the peer and try to use the most recent Bitswap
_dialPeer (peer, callback) { // Attempt Bitswap 1.1.0 this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => { if (err) { // Attempt Bitswap 1.0.0 this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => { if (err) { return callback(err) } callback(null, conn, BITSWAP100) }) return } callback(null, conn, BITSWAP110) }) }
[ "async _dialPeer (peer) {\n try {\n // Attempt Bitswap 1.1.0\n return {\n conn: await this.libp2p.dialProtocol(peer, BITSWAP110),\n protocol: BITSWAP110\n }\n } catch (err) {\n // Attempt Bitswap 1.0.0\n return {\n conn: await this.libp2p.dialProtocol(peer, BITSWAP100),\n protocol: BITSWAP100\n }\n }\n }", "_dialPeer (peer, callback) {\n // Attempt Bitswap 1.1.0\n this.libp2p.dial(peer, BITSWAP110, (err, conn) => {\n if (err) {\n // Attempt Bitswap 1.0.0\n this.libp2p.dial(peer, BITSWAP100, (err, conn) => {\n if (err) { return callback(err) }\n\n callback(null, conn, BITSWAP100)\n })\n\n return\n }\n\n callback(null, conn, BITSWAP110)\n })\n }", "async _autoDial () {\n const minConnections = this._options.minConnections\n\n // Already has enough connections\n if (this.size >= minConnections) {\n this._autoDialTimeout = retimer(this._autoDial, this._options.autoDialInterval)\n return\n }\n\n // Sort peers on wether we know protocols of public keys for them\n const peers = Array.from(this._libp2p.peerStore.peers.values())\n .sort((a, b) => {\n if (b.protocols && b.protocols.length && (!a.protocols || !a.protocols.length)) {\n return 1\n } else if (b.id.pubKey && !a.id.pubKey) {\n return 1\n }\n return -1\n })\n\n for (let i = 0; i < peers.length && this.size < minConnections; i++) {\n if (!this.get(peers[i].id)) {\n log('connecting to a peerStore stored peer %s', peers[i].id.toB58String())\n try {\n await this._libp2p.dialer.connectToPeer(peers[i].id)\n\n // Connection Manager was stopped\n if (!this._started) {\n return\n }\n } catch (err) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n this._autoDialTimeout = retimer(this._autoDial, this._options.autoDialInterval)\n }", "_dialPeer (peer, callback) {\n // Attempt Paratii 0.0.1\n this.libp2p.dialProtocol(peer, PARATII001, (err, conn) => {\n if (err) {\n // Attempt Paratii 0.0.1\n this.libp2p.dialProtocol(peer, PARATII001, (err, conn) => {\n if (err) { return callback(err) }\n\n callback(null, conn, PARATII001)\n })\n\n return\n }\n\n callback(null, conn, PARATII001)\n })\n }", "_getNewPlainWebPeer (cb) {\n //let wspeers = this._params.webSeeds\n //let wsaddr = utils.getRandom(this._webAddrs)\n let wsaddr = this.webAddrs.findBestAddr();\n if (wsaddr) {\n this.webAddrs.setInUse(wsaddr);\n this._connectPlainWebPeer(wsaddr, cb)\n }\n }", "_connectPeer (cb) {\n cb = cb || this._onConnection.bind(this)\n if (this.closed) return\n if (this.peers.length >= this._numPeers) return\n let getPeerArray = []\n if (!process.browser) {\n if (this._params.dnsSeeds && this._params.dnsSeeds.length > 0) {\n getPeerArray.push(this._connectDNSPeer.bind(this))\n }\n if (this._params.staticPeers && this._params.staticPeers.length > 0) {\n getPeerArray.push(this._connectStaticPeer.bind(this))\n }\n }\n if (this._connectWeb && this._exchange.peers.length > 0) {\n getPeerArray.push(this._exchange.getNewPeer.bind(this._exchange))\n }\n if (this._params.getNewPeer) {\n getPeerArray.push(this._params.getNewPeer.bind(this._params))\n }\n if (getPeerArray.length === 0) {\n this.connecting = false\n if (this.connectTimeout) {\n setTimeout(() => {\n this.connecting = true\n setImmediate(this.connect.bind(this))\n }, this.connectTimeout)\n }\n return this._onConnection(\n Error('No methods available to get new peers'))\n }\n let getPeer = utils.getRandom(getPeerArray)\n debug(`_connectPeer: getPeer = ${getPeer.name}`)\n getPeer(cb)\n }", "autoDial() {\n for (const peer of this.peers) {\n // call a peer if it is not connected\n if (!peer.hasConnection()) {\n peer.startCall()\n .then(this.onStream.bind(this));\n }\n }\n }", "function checkTheNext(peerList) {\n\t// Take one from the list each time, also removing it\n\tvar peer = popRandom(peerList);\n\ttry {\n\t\tvar peerUrl = peer['requests'];\n\t} catch(err) {\n\t\tvar peerUrl = '';\n\t}\n\t\n\treturn isPortAlive(getIpFromEndpoint(peerUrl), getPortFromEndpoint(peerUrl))\n\t.then((res) => {\n\t\tlogger.debug('Find alive peer %s and returning it.', peerUrl);\n\t\treturn peer;\n\n\t}).catch((err) => {\n\t\tlogger.debug('Peer %s is not connected, try next.', peerUrl);\n\t\tif (0 < peerList.length) {\n\t\t\treturn checkTheNext(peerList);\n\t\t} else {\n\t\t\tutil.throwError(logger, err, 'Failed in getting any alive peer, returning nothing.');\n\t\t}\n\t});\n}", "function RPC(opts) {\n\tif (!(this instanceof RPC)) return new RPC(opts)\n\n\tconst self = this\n\n\tlog.m('bitTorrent client warm-up...')\n\n\tif (!opts) {\n\t\t\ttracker.getPeers(torrentAmorce, peers => {\n\t\t\t\t\tself.opts = { peers }\n\t\t\t})\n\t} else {\n\t\tself.opts = opts\n\t}\n\n\tthis.port = this.opts.port || 1 + Math.floor(Math.random() * 65535)\n\tthis.socket = this.opts.socket || dgram.createSocket('udp4')\n\tthis.bootstrap = this.opts.peers || []\n\tthis.socket.on('message', onMessage)\n\tthis.socket.on('error', onError)\n\tthis.socket.on('listening', onListening)\n\tthis.state = 'loading'\n\tthis._buckets = new Nodes()\n\tthis._buckets.once('ready', () => {\n\t\tself.goReady()\n\t\t})\n\tthis._buckets.on('loading', stat => {\n\t\tself.unBlock(stat)\n\t})\n\tthis.errors = []\n\tthis.queries = []\n\tthis._ids = []\n\tthis.reqs = []\n\tthis.peers = []\n\tthis.torrents = []\n\tthis._halveDepth = 0\n\n\tfunction onMessage(buf, rinfo) {\n\t\tconst response = {}\n\t\ttry {\n\t\t\tconst message\t= bencode.decode(buf)\n\n\t\t\tresponse.tid\t\t\t= message.t && message.t.toString()\n\t\t\tresponse.type\t\t\t= message.y && message.y.toString()\n\n\t\t\tif (response.tid) {\n\t\t\t\tresponse.req\t\t\t= self.reqs[response.tid]\n\t\t\t\tresponse.index\t\t= self._ids.indexOf(response.tid)\n\t\t\t} else return\n\n\t\t\tif (response.type === 'q') {\n\t\t\t\tself.queries.push(response)\n\t\t\t\tself.emit('query')\n\t\t\t}\n\n\t\t\tif (response.type === 'r') {\n\t\t\t\tif (!Buffer.isBuffer(message.t)) return\n\n\t\t\t\tresponse.id\t\t\t= message.r.id\n\t\t\t\tresponse.nodes\t\t= message.r.nodes && message.r.nodes\n\t\t\t\tresponse.token\t\t= message.r.token && message.r.token.toString()\n\t\t\t\tresponse.values\t\t= message.r.values && message.r.values\n\t\t\t\tresponse.client\t\t\t= !!message.v && message.v.toString('binary')\n\t\t\t} else if (response.type === 'e') {\n\t\t\t\tif (!Buffer.isBuffer(message.e)) return\n\t\t\t\tself.emit('error', message.e[1].toString())\n\t\t\t}\n\t\t\tif (response.index === -1 || response.tid === 0) {\n\t\t\t\tself.emit('response', message, rinfo)\n\t\t\t\tself.emit('warning', new Error('Response identification failiure'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// opts = {node, ip, port, id}\n\t\t\tconst { ip, port } = response.req\n\t\t\tif (response.req.r === 'ping' && (!!response.id)) {\n\t\t\t// PING\n\t\t\t\tself.addNode({ nodes: response.id, ip, port, id: response.tid })\n\t\t\t} else if (response.req.r === 'find_node') {\n\t\t\t// FIND_NODE\n\t\t\tif (!response.nodes) return\n\t\t\t\tconst ids = self.parseNodes(response.nodes)\n\t\t\t\tif (ids) {\n\t\t\t\t\tids.forEach(c => {\n\t\t\t\t\t\tself.ping(c)\n\t\t\t\t\t})\n\t\t\t\t\tself.emit('find_nodes')\n\t\t\t\t}\n\t\t\t} else if (response.req.r === 'get_peers') {\n\t\t\t// GET_PEERS\n\t\t\t\tif (response.values) {\n\t\t\t\t\tconst values = self.parseValues(response.values)\n\t\t\t\t\tconst token = response.token\n\t\t\t\t\tself.emit('get_peers', values, token)\n\t\t\t\t} else if (response.nodes) {\n\t\t\t\t\tconst ids = self.parseNodes(response.nodes)\n\t\t\t\t\tif (ids && self.torrents.indexOf(response.req.infoHash) !== -1) {\n\t\t\t\t\t\tids.forEach(p => {\n\t\t\t\t\t\t\tself.get_peers(p, response.req.infoHash, null)\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tself.errors.push(e)\n\t\t}\n\t}\n\n\tfunction onError(e) {\n\t\tself.emit('error', e)\n\t}\n\n\tfunction onListening() {\n\t\tself.emit('listening')\n\t}\n\n\ttry {\n\t\tif (this.opts.peers) {\n\t\t\tthis.open()\n\t\t} else {\n\t\t\tconst interVal = setInterval(() => {\n\t\t\t\tif (this.opts.peers){\n\t\t\t\t\tclearInterval(interVal)\n\t\t\t\t\tthis.open()\n\t\t\t\t}\n\t\t\t}, 20000)\n\t\t}\n\t} catch (e) {\n\t\tthis.errors.push(e)\n\t}\n}", "function bt_OnConnect(ok) {\n if (!ok) {\n console.log(\"BT ERROR!\");\n bt.Connect(\"HC-05\"); // Try to reconnect again\n } else if (ok)\n console.log(\"BT Successful\");\n}", "connect(instance) {\n //First start all services : overlay, topology agent...\n var list = this.bootstrapPeerList;\n var sockets = [];\n var client = new Array(list.length);\n var options = {\n rejectUnauthorized: false //TODO\n }\n var isConnected = false;\n let test = new Array(list.length).fill(0);\n for(let i = 0 ; i<list.length; i++)\n {\n test[i]++;\n if(!list[i].name) continue;\n const port = list[i].name.port;\n const addr = list[i].name.address;\n if(isConnected) break;\n let t = this;\n let callBack = function(connection) {\n if(isConnected)\n {\n socket.write('close', '');\n }\n else\n {\n out.info('Connected to the bootstrap peer ('+addr+':'+port+')');\n if(addr != global.addr)\n {\n out.debug('Adding the bootstrap peer as a TURN server');\n global.turns.push(addr);\n }\n out.info('Sending attach request with the local node id.');\n //Attach request to the bootstrap peer\n global.topology.AttachService.attachTo(connection.socket, [connection.stack.nodeID, new ResourceID(addNodeID(t.nodeID.id))], true);\n }\n isConnected = true;\n };\n let onError = function (port, addr, options) {\n if(!isConnected && test[i] < 6)\n {\n out.warning('Retrying in 3 seconds... ('+test[i]+'/5)');\n test[i]++;\n setTimeout(function(){global.connectionManager.connectTo(port, addr, options,callBack,onError)},3000);\n }\n return;\n };\n\n let socket = global.connectionManager.connectTo(port, addr, options, callBack, onError);\n client[i] = socket;\n }\n }", "function call() {\n callBtn.disabled = true;\n hangupBtn.disabled = false;\n\n var servers = null;\n\n // Create the peer connections. Peer1 will be \"us\" and Peer2 will be the mocked peer.\n peer1 = new RTCPeerConnection(servers);\n peer2 = new RTCPeerConnection(servers);\n\n // Add a handler for when there are new ICE candidates\n peer1.onicecandidate = function (e) {\n addCandidate(peer2, e);\n };\n\n peer2.onicecandidate = function (e) {\n addCandidate(peer1, e);\n };\n\n // Add a callback for when we get the remote stream for the 2nd peer so we can see their video\n peer2.onaddstream = function (e) {\n remoteVid.srcObject = e.stream;\n };\n\n // Add our local stream to peer1\n peer1.addStream(localStream);\n\n // Create an offer to connect\n peer1.createOffer(offerConstraints)\n .then(function (desc) {\n // The APIs for setting descriptions are promise-based.\n // For brevity, we aren't adding callbacks.\n peer1.setLocalDescription(desc);\n peer2.setRemoteDescription(desc);\n peer2.createAnswer()\n .then(createAnswerSuccess);\n });\n}", "function install(pbw) {\n card.title('Preparing...');\n card.body('This should take no more than 5 seconds.');\n\n var connection = new WebSocket('ws://localhost:9000');\n connection.binaryType = \"arraybuffer\";\n\n //The connection will close if there is no websocket server running because it is not connected to the wifi\n connection.onclose = function () {\n card.title('Error');\n card.body('Make sure developer connection is enabled and connected to wifi! Otherwise watchface roulette will not work.');\n };\n\n //The connection may recieve an error if the developer connection is disabled\n connection.onerror = function () {\n card.title('Error');\n card.body('Make sure developer connection is enabled! Otherwise watchface roulette will not work.');\n };\n\n //Request and install the app once the connection is opened\n connection.onopen = function () {\n connectionOpened(pbw, connection)\n };\n\n var connectionOpened = function (pbw, connection) {\n //update the status card\n card.title('Requesting Watchface');\n card.body('This may take up to 10 seconds');\n\n //Prepare to request the app\n var request = new XMLHttpRequest();\n\n //Fetch the PBW file\n request.open('get', pbw, true);\n\n //Tell the connection we expect an array buffer\n request.responseType = \"arraybuffer\";\n\n //Send the response to the developer connection to prep it for the watch\n request.onload = function () {\n //Read the data of the pbw\n var buffer = request.response;\n if (buffer) {\n //Convert the buffer to an array of unsigned 8-bit integers\n buffer = new Uint8Array(buffer);\n\n var final_buffer = new Uint8Array(buffer.length + 1);\n //Apply the PBW array starting at index 1\n final_buffer.set(buffer, 1);\n\n //Some endpoint to request an install, which the developer connection understands\n final_buffer.set([4]);\n\n //Send developer connection the bytes of the app\n connection.send(final_buffer);\n\n //Update the card to display the status\n card.title('Installing...');\n card.body('This may take up to 15 seconds');\n }\n };\n\n request.send();\n };\n}", "detectWallet() { \n if (!window.bitcoin) return;\n \n (async () => {\n try {\n await window.bitcoin.enable();\n } catch (e) {/*noop*/ }\n\n await detectWalletCb();\n\n setInterval(async function () {\n await detectWalletCb();\n }, WALLET_CHECK_INTERVAL_MS);\n })();\n\n var detectWalletCb = async () => {\n try {\n var currentAddresses = await bitcoin.request({ method: 'wallet_getAddresses', params: [] })\n var currentAddress = (currentAddresses && currentAddresses.length > 0) ? currentAddresses[0].address : null;\n var currentNetwork = (await bitcoin.request({ method: 'wallet_getConnectedNetwork', params: [] })).name;\n } catch (e) {/*noop*/}\n if (currentNetwork !== this.network) {\n this.network = currentNetwork;\n this.networkChangeDelegates.forEach(d => d(this.network)); \n }\n if (currentAddress !== this.walletAddress) {\n if (currentAddress) { /* add imparters */\n this.addTag(btc_liquality.tag);\n } else { /* remove imparters */\n this.removeTag(btc_liquality.tag);\n } \n this.walletAddress = currentAddress;\n this.fire('onWalletChange', { imparterTag: btc_liquality.tag, isPresent: !!currentAddress });\n if (currentAddress) {\n this.fire('onCredentialsUpdate', { imparterTag: btc_liquality.tag, address: currentAddress });\n }\n }\n }\n }", "function getSocket(){var candidates=[];this.sockets.forEach(function(socket){if(socket.status===C.SOCKET_STATUS_ERROR){return;// continue the array iteration\n}else if(candidates.length===0){candidates.push(socket);}else if(socket.weight>candidates[0].weight){candidates=[socket];}else if(socket.weight===candidates[0].weight){candidates.push(socket);}});if(candidates.length===0){// all sockets have failed. reset sockets status\nthis.sockets.forEach(function(socket){socket.status=C.SOCKET_STATUS_READY;});// get next available socket\ngetSocket.call(this);return;}var idx=Math.floor(Math.random()*candidates.length);this.socket=candidates[idx].socket;}", "renegotiate() {\n // reset variables\n // this._state = HandshakeStates.preparing;\n this._isHandshaking = true;\n this.lastProcessedSeqNum = -1;\n this.lastSentSeqNum = -1;\n this.incompleteMessages = [];\n this.completeMessages = {};\n this.expectedResponses = [];\n this.allHandshakeData = [];\n // this.cscReceived = false;\n // this.serverFinishedPending = false;\n // ==============================\n // start by sending a ClientHello\n const hello = Handshake.ClientHello.createEmpty();\n hello.client_version = new ProtocolVersion_1.ProtocolVersion(~1, ~2);\n hello.random = Random_1.Random.createNew();\n // remember this for crypto stuff\n this.recordLayer.nextEpoch.connectionState.client_random = hello.random.serialize();\n hello.session_id = Buffer.from([]);\n hello.cookie = Buffer.from([]);\n // TODO: dynamically check which ones we can support\n const cipherSuites = this.options.ciphers || [\n \"TLS_PSK_WITH_3DES_EDE_CBC_SHA\",\n \"TLS_PSK_WITH_AES_128_CBC_SHA\",\n \"TLS_PSK_WITH_AES_256_CBC_SHA\",\n \"TLS_PSK_WITH_AES_128_CBC_SHA256\",\n \"TLS_PSK_WITH_AES_256_CBC_SHA384\",\n \"TLS_PSK_WITH_AES_128_GCM_SHA256\",\n \"TLS_PSK_WITH_AES_256_GCM_SHA384\",\n \"TLS_PSK_WITH_AES_128_CCM\",\n \"TLS_PSK_WITH_AES_256_CCM\",\n \"TLS_PSK_WITH_AES_128_CCM_8\",\n \"TLS_PSK_WITH_AES_256_CCM_8\",\n ];\n hello.cipher_suites = new Vector_1.Vector(cipherSuites.map(cs => CipherSuites_1.CipherSuites[cs].id));\n hello.compression_methods = new Vector_1.Vector([ConnectionState_1.CompressionMethod.null]);\n hello.extensions = new Vector_1.Vector();\n this.sendFlight([hello], [\n Handshake.HandshakeType.server_hello_done,\n Handshake.HandshakeType.hello_verify_request,\n ]);\n }", "function versionDongleCallback(){\n no_connectReq=0;\n funcToExec.unshift(getVersionDongle);\n connectToDevice(false,executeTopFunction,null,null,'versionDongle');\n }", "async initiateNextConnection() {\n if (this.state.isTryingConnection) {\n return;\n }\n const connections = Object.keys(this.deviceConnections).filter((deviceId) => !this.deviceConnections[deviceId]);\n if (connections.length < 1) { //everything is already connected\n return;\n }\n let nextAddressToTry;\n if (!this.lastTriedAddress || connections.indexOf(this.lastTriedAddress) < 0) {\n nextAddressToTry = connections[0];\n }\n else {\n const indexOf = connections.indexOf(this.lastTriedAddress);\n if (indexOf + 1 >= connections.length) {\n nextAddressToTry = connections[0];\n }\n else {\n nextAddressToTry = connections[indexOf + 1];\n }\n }\n try {\n if (this.fotaQueue.currentItem?.deviceId !== nextAddressToTry) { //If we're currently doing fota, skip this one\n this.updateState({ isTryingConnection: true });\n await this.bluetoothAdapter.connect(nextAddressToTry);\n }\n }\n catch (error) {\n }\n finally {\n this.lastTriedAddress = nextAddressToTry;\n this.updateState({ isTryingConnection: false });\n }\n }", "function call() {\n callButton.disabled = true;\n hangupButton.disabled = false;\n console.log('Starting call');\n startTime = window.performance.now();\n var videoTracks = localStream.getVideoTracks();\n var audioTracks = localStream.getAudioTracks();\n if (videoTracks.length > 0) {\n console.log('Using video device ' + videoTracks[0].label);\n };\n if (audioTracks.length > 0) {\n console.log('Using audio device ' + audioTracks[0].label);\n };\n var servers = null;\n pc1 = new RTCPeerConnection(servers);\n console.log('Created local peer connection object pc1');\n pc1.onicecandidate = function(e) {\n onIceCandidate(pc1, e);\n };\n pc2 = new RTCPeerConnection(servers);\n console.log('Created remote peer connection object pc2');\n pc2.onicecandidate = function(e) {\n onIceCandidate(pc2, e);\n };\n pc1.oniceconnectionstatechange = function(e) {\n onIceStateChange(pc1, e);\n };\n pc2.oniceconnectionstatechange = function(e) {\n onIceStateChange(pc2, e);\n };\n pc2.ontrack = gotRemoteStream;\n\n localStream.getTracks().forEach(\n function(track) {\n pc1.addTrack(\n track,\n localStream,\n );\n }\n );\n console.log('Added local stream to pc1');\n\n console.log('pc1 createOffer start');\n pc1.createOffer(\n offerOptions\n ).then(\n onCreateOfferSuccess,\n onCreateSessionDescriptionError\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(Int, Bool) > String Returns 'walk' if the user should walk and 'drive' if the user should drive to their destination. The user should walk if it is nice weather and the distance is a quarter mile or less.
function walkOrDrive(miles, isNiceWeather) {}
[ "getDirectionBasedOnDistance(distX, distY){\n\n if (Math.abs(distX) > Math.abs(distY)){\n // we have to choose between right and left in normal mode\n\n if(this.state === \"normal\"){\n return (distX > 0) ? \"right\" : \"left\";\n }\n else{\n return (distX > 0) ? \"left\" : \"right\";\n }\n\n }\n else {\n // we have to choose between up and down\n if(this.state === \"normal\"){\n return (distY > 0) ? \"down\" : \"up\";\n }\n else {\n return (distY > 0) ? \"up\" : \"down\";\n }\n }\n\n\n }", "function getDistanceHint(distance) {\n if (distance < 10) {\n return \"Boiling Hot!\";\n } else if (distance < 20) {\n return \"Really Hot\";\n } else if (distance < 40) {\n return \"Hot\";\n } else if (distance < 80) {\n return \"Warm\";\n } else if (distance < 160) {\n return \"Cold\";\n } else if (distance < 320) {\n return \"Really Cold\";\n } else {\n return \"Freezing\";\n }\n}", "function isValidWalk(walk){\nlet northCount = 0;\nlet eastCount = 0;\nlet southCount = 0;\nlet westCount = 0;\n\nif(walk.length !=10){\n return 'false';\n}\n\nif(walk.length === 10){\n //getting count of each direction\n for(let i=0; i<walk.length;i++){\n if(walk[i] === 'n'){\n northCount = northCount +1;\n }\n else if(walk[i] === 'e'){\n eastCount = eastCount+1;\n }\n else if(walk[i] === 's'){\n southCount = southCount +1;\n }\n else if(walk[i] === 'w'){\n westCount = westCount +1;\n }\n }\n\n //making sure each count equals to opposite\n\n if(northCount === southCount && eastCount === westCount){\n return 'true';\n }\n else {\n return 'false';\n \n }\n}\n}", "function tour(walk, distance) {\n return walk(distance(5));\n}", "function getDistance(){\n if (departure.value == \"dep-auck\" && destination.value == \"dest-taup\" || departure.value == \"dep-taup\" && destination.value == \"dest-auck\"){\n tripDistance = distance.taupAuck;\n }\n else if (departure.value == \"dep-well\" && destination.value == \"dest-taup\" || departure.value == \"dep-taup\" && destination.value == \"dest-well\"){\n tripDistance = distance.wellTaup;\n }\n else if (departure.value == \"dep-well\" && destination.value == \"dest-auck\" || departure.value == \"dep-auck\" && destination.value == \"dest-well\"){\n tripDistance = distance.auckWell;\n }\n }", "function validWalk(directions) {\n let latitude = 0;\n let longitude = 0;\n\n\n for (let i = 0; i < directions.length; i++) {\n let direction = directions[i];\n\n if (direction === 'n') {\n latitude += 1;\n } else if (direction === 's') {\n latitude -= 1;\n } else if (direction === 'e') {\n longitude += 1;\n } else if (direction === 'w') {\n longitude -= 1;\n }\n }\n\n // if (latitude === 0 && longitude === 0 ) {\n // return true;\n // }\n\n // return false;\n\n return latitude === 0 && longitude === 0;\n}", "function isWalkable(targetTile){\r\n if(targetTile === road || targetTile === gems || targetTile === goal){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n}", "function getDirection(bearing){\n var direction = \"?\";\n if(bearing<=10 || bearing>=360){direction = \"N\"}\n else if(bearing>10 && bearing<30){direction = \"NNW\"}\n else if(bearing>=30 && bearing<=60){direction = \"NW\"}\n else if(bearing>60 && bearing<80){direction = \"NWW\"}\n else if(bearing>=80 && bearing<=100){direction = \"W\"}\n else if(bearing>100 && bearing<120){direction = \"SWW\"}\n else if(bearing>=120 && bearing<=150){direction = \"SW\"}\n else if(bearing>150 && bearing<170){direction = \"SSW\"}\n else if(bearing>=170 && bearing<=190){direction = \"S\"}\n else if(bearing>190 && bearing<210){direction = \"SSE\"}\n else if(bearing>=210 && bearing<=240){direction = \"SE\"}\n else if(bearing>240 && bearing<260){direction = \"SEE\"}\n else if(bearing>=260 && bearing<=280){direction = \"E\"}\n else if(bearing>280 && bearing<300){direction = \"NEE\"}\n else if(bearing>=300 && bearing<=330){direction = \"NE\"}\n else if(bearing>330 && bearing<350){direction = \"NNE\"}\n return direction;\n}", "function validWalk(directions) {\n let yAxis = 0;\n let xAxis = 0;\n\n for (let i = 0; i < directions.length; i++) {\n let curr = directions[i];\n\n if (curr.includes('n')) {\n yAxis++;\n } else if (curr.includes('s')) {\n yAxis--;\n } else if (curr.includes(\"e\")) {\n xAxis++;\n } else if (curr.includes('w')) {\n xAxis--;\n }\n }\n\n if (yAxis === 0 && xAxis === 0) {\n return true;\n }\n\n return false;\n}", "function checkDanger(distance) {\r\n\tif (distance < 4) { \t\t\t\t // Hunter is within a minute away\r\n\t\treturn \"Extreme\";\r\n\t} else if (distance <= 8) {\t // Hunter is 1-2 minutes away\r\n\t\treturn \"High\";\r\n\t} else if (distance <= 16) { // Hunter is 2-4 minutes away\r\n\t\treturn \"Moderate\";\r\n\t} else if (distance > 16) { // Hunter is more than 4 minutes away\r\n\t\treturn \"Low\";\r\n\t} else {\r\n\t\treturn \"Error\";\r\n\t}\r\n}", "getMoveMessage(tribute, map){\n var tributePlace = map[tribute.getRow()][tribute.getColumn()];\n if (tribute.getWaterMeter() < 0.33){\n return tribute.getName() + \" is very thirsty.\";\n }\n else if (tribute.getFoodMeter() < 0.2){\n return tribute.getName() + \" is very hungry.\";\n }\n else if (tributePlace.getLocation() == \"cornucopia\"){\n return tribute.getName() + \" is at the cornucopia.\";\n }\n else if (tributePlace.getLocation() == \"grass\"){\n return tribute.getName() + \" is on grass.\";\n }\n else if (tributePlace.getLocation() == \"water\"){\n return tribute.getName() + \" is in the water.\";\n }\n else if (tributePlace.getLocation() == \"sand\"){\n return tribute.getName() + \" is on sand.\";\n }\n else if (tributePlace.getLocation() == \"forest\"){\n return tribute.getName() + \" is in the forest.\";\n }\n else if (tributePlace.getLocation() == \"snow\"){\n return tribute.getName() + \" is in the snow.\";\n }\n else if (tributePlace.getLocation() == \"house\"){\n return tribute.getName() + \" is in the house.\";\n }\n else if (tributePlace.getLocation() == \"kitchen\"){\n return tribute.getName() + \" is in the kitchen.\";\n }\n else if (tributePlace.getLocation() == \"bathroom\"){\n return tribute.getName() + \" is in the bathroom.\";\n }\n else if (tributePlace.getLocation() == \"bedroom\"){\n return tribute.getName() + \" is in the bedroom.\";\n }\n else if (tributePlace.getLocation() == \"game room\"){\n return tribute.getName() + \" is in the game room.\";\n }\n else if (tributePlace.getLocation() == \"playground\"){\n return tribute.getName() + \" is on the playground.\";\n }\n else {\n return tribute.getName() + \" is by the swings.\";\n }\n }", "getWind(wind, direction) {\n if (document.getElementById(\"windTrue\").checked) {\n return \"Wind \" + direction + Math.round(wind) + \"km/h\";\n } else if (document.getElementById(\"windFalse\").checked) {\n return \"\";\n } else {\n return \"No Wind Choice Made\";\n }\n }", "updateDirection() {\n\t\tlet tolerance = this.TURN_SPEED;\n\t\tlet tempDir = this.direction;\n\t\tif (this.direction - this.goalDirection > 180) tempDir = this.direction - 360;\n\t\t// if direction is left of goalDirection by 180 or less\n\t\tif (tempDir < this.goalDirection) {\n\t\t\tthis.left = false;\n\t\t\tthis.right = true;\n\t\t}\n\t\tif (this.direction - this.goalDirection < -180) tempDir = this.direction + 360;\n\t\t// if direction is right of goalDirection by 179 or less\n\t\tif (tempDir > this.goalDirection) {\n\t\t\tthis.left = true;\n\t\t\tthis.right = false;\n\t\t}\n\t\t// if direction is close enough, autocorrect and stop turns\n\t\tif (Math.abs(this.direction - this.goalDirection) < tolerance) {\n\t\t\tthis.direciton = this.goalDirection;\n\t\t\tthis.left = false;\n\t\t\tthis.right = false;\n\t\t}\n\t}", "function useDrivingDestination() {\n return $('#directions-via').attr('data-value') != 'hike';\n}", "function anotherIsValidWalk(walk) {\n var northSouthCount = 0;\n var eastWestCount = 0;\n var i;\n\n if (isValidInput(walk) && walk.length === 10) {\n for (i = 0; i < walk.length; i++) {\n if (walk[i] === 'n') {\n northSouthCount++;\n } else if (walk[i] === 's') {\n northSouthCount--;\n } else if (walk[i] === 'w') {\n northSouthCount++;\n } else {\n northSouthCount--;\n }\n }\n if (northSouthCount === 0 && eastWestCount === 0) {\n return true;\n }\n }\n\n return false;\n}", "function neswDirection(point1, point2) {\r\n\tlet sine = sin(point1, point2);\r\n\tlet cosine = cos(point1, point2);\r\n\tsin45 = 1/Math.sqrt(2);\r\n\tif (sin45 < sine) {\t\r\n\t\treturn \"north\";\r\n\t} else if (sin45 < cosine) {\r\n\t\treturn \"east\"\r\n\t} else if (sine < -sin45) { \r\n\t\treturn \"south\"\r\n\t} else { \r\n\t\treturn \"west\"\r\n\t}\r\n}", "drive(distance){\n this.odometer = this.odometer + distance;\n let fuelUsed = distance / this.mpg;\n this.fuelLevel = this.fuelLevel - fuelUsed;\n\n //mpg; 20\n // level; 10 gallons\n // drive 40 miles\n // use; .5gallons\n }", "function tour(walk, distance) {\n var length = 5;\n return walk(distance(length));\n}", "function onBoardingGuide (dist) {\r\n if (dist > 0 || isGameEnded) {\r\n return;\r\n }\r\n if(distance == -450) {\r\n displayText(\"Jump!\", -50, 5, -Math.PI /4);\r\n } else if (distance == -300) {\r\n displayText(\"Move Left!\", -50, 5, -Math.PI /4);\r\n } else if (distance == -200) {\r\n displayText(\"Move Right!\", -50, 5, -Math.PI /4);\r\n } else if (distance == 0) {\r\n displayText(\"Start\", -30, 5, -Math.PI /4);\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether or not to load a module, Can be used to show/hide modules for non authenticated users. This can be customized to your own taste.
shouldLoadModule(module, req) { if (module.requireAuth) { return req.isAuthenticated(); } return true; }
[ "isModuleLoaded() {\n return !!RNSentry;\n }", "isMainModule(){\r\n return main_module;\r\n }", "hasModule(path){return!!this.store._modules.get(path);}", "static isModuleEnabled(state, moduleId) {\n const isModuleEnabled = ConfigurationManager.getPublicValue(state, `idm.pub.${moduleId}.enabled`);\n if (isModuleEnabled === null) {\n return null;\n }\n return isModuleEnabled === 'true';\n }", "function $IsModule(module) {\n return GetModuleInternalData(module) !== undefined;\n}", "function loadModule(options) {\n if(typeof options.conditionalId === 'undefined' ||\n document.getElementById(options.conditionalId)) {\n modules[options.module]();\n }\n}", "@bind\n isCustom(module) {\n return this.customModules[module] ? true : false\n }", "hasModuleAccess(key) {\n if(key in Vue.$module && Vue.$module[key] !== true) return false;\n\n let module = Vue.$store.state.access.modules[key];\n if(module) {\n if(module === true) {\n return true;\n }\n if(module.access === true) {\n return true;\n }\n }\n return false;\n }", "isTaskModuleEnabled() {\r\n if (\r\n ApplicationUtil.homeBeanData.enableTaskModule == ApplicationConstants.TRUE\r\n ) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "isReviewModuleEnabled() {\r\n if (\r\n ApplicationUtil.homeBeanData.enableReviewModule ==\r\n ApplicationConstants.TRUE\r\n ) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "hasModule (path) {\n return !!this.store._modules.get(path)\n }", "function checkModuleLoad() {\n if (moduleQueueList.length < 1 && inclusionQueue.module.length < 1 && !state.module) {\n dispatchModuleLoadEvent();\n }\n }", "function IsModLoaded(name) {\n\treturn document.getElementById('modscript_' + name) != null;\n}", "function IsModLoaded(name) {\n\treturn (document.getElementById('modscript_' + name) != null);\n}", "function isLoaderVisible(){\n var pth = window.location.pathname.split(\"?\");\n if(pth[0] == \"/index.php\" || pth[0] == \"/portfolioItem.php\" || pth[0] == \"/\"){\n return true;\n } else{\n return false;\n }\n}", "function _canLoadAsFile(modulePath) {\n\treturn fs.existsSync(modulePath) || fs.existsSync(modulePath + \".js\");\n}", "function bridgeAuthModuleRequire(bType) {\r\n\tlet bAModFile = bridgeAuthModulePath(bType);\r\n\tif (!bridgeAuthModule[bType]) {\r\n\t\tlog.info('Requiring ', bAModFile);\r\n\t\tvar bAMod = tryRequire(bAModFile, 0) || tryRequire(bAModFile, 1);\r\n\t\tif (bAMod)\r\n\t\t\tbridgeAuthModule[bType] = bAMod;\r\n\t\telse {\r\n\t\t\tlog.info('No authentication available for bridge type:', bType);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}", "function _defined(moduleName) {\n return _moduleMap[moduleName] ? true : false;\n}", "static loaderIsDisplayed() {\n return !self.loader.classList.contains(appParams.cssClasses.hidden) ? true : false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MAC_UpdateFromResponse ========= MAC_SetInfoboxesAndBtns ================ PR20210208 PR20230110 PR20230714
function MAC_SetInfoboxesAndBtns(response) { console.log("=== MAC_SetInfoboxesAndBtns =====") ; // called by MAC_Save and MAC_UpdateFromResponse // step is increased in MAC_save, response has value when response is back from server const is_response = (typeof response != "undefined"); console.log("......................step", mod_MAC_dict.step) ; console.log(" is_response", is_response) ; console.log(" test_is_ok", mod_MAC_dict.test_is_ok) ; console.log(" verification_is_ok", mod_MAC_dict.verification_is_ok) ; // TODO is_reset const is_reset = mod_MAC_dict.is_reset; // --- info_container, loader, info_verifcode and input_verifcode let msg_info_html = null; let show_loader = false; let show_input_verifcode = false; let show_btn_save = false, show_delete_btn = false; let disable_save_btn = false, save_btn_txt = null; //++++++++ approve mode +++++++++++++++++ if(mod_MAC_dict.is_approve_mode){ if (mod_MAC_dict.step === 0) { if (!is_response){ // step 0: when form opens and request to check is sent to server // text: 'AWP is checking the compensations' msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.checking_compensations + "...</div>"; show_loader = true; } else if (response.approve_msg_html) { msg_info_html = response.approve_msg_html; // response with checked subjects // msg_info_txt is in response show_btn_save = response.test_is_ok; //PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted if (show_btn_save ){ save_btn_txt = loc.Approve_compensations; }; if (mod_MAC_dict.has_already_approved) { show_delete_btn = true; }; }; } else if (mod_MAC_dict.step === 1) { // step 1: after clicked on btn Approve_subjects if (!is_response){ // text: 'AWP is approving the compensations' msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.approving_compensations + "...</div>"; show_loader = true; } else if (response.approve_msg_html) { // step 1: response after clicking on btn Approve_subjects // response with "We have sent an email with a 6 digit verification code to the email address:" // msg_info_html is in response.approve_msg_html msg_info_html = response.approve_msg_html; }; }; } else { //++++++++ submit mode +++++++++++++++++ if (mod_MAC_dict.step === 0) { if (!is_response){ // step 0: when form opens and request to check is sent to server // text: 'AWP is checking the compensations' msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.checking_compensations + "...</div>"; show_loader = true; } else if (response.approve_msg_html) { msg_info_html = response.approve_msg_html; // response with checked subjects // msg_info_txt is in response // text 'You need a 6 digit verification code to submit the Ex form' is in response show_btn_save = response.test_is_ok; //PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted if (show_btn_save ){ save_btn_txt = loc.Request_verifcode; }; }; } else if (mod_MAC_dict.step === 1) { // after clicked on btn Request_verificationcode if (!is_response){ // step 1: when clicked on 'Request verif code // tekst: 'AWP is sending an email with the verification code' msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.sending_verifcode + "</div>"; show_loader = true; } else if (response.approve_msg_html) { // step 1: response after sending request verificationcode // response with "We have sent an email with a 6 digit verification code to the email address:" // msg_info_html is in response.approve_msg_html msg_info_html = response.approve_msg_html; show_btn_save = true; show_input_verifcode = true; disable_save_btn = !el_MAC_input_verifcode.value; save_btn_txt = loc.Submit_compensation_form; }; } else if (mod_MAC_dict.step === 2) { // step 2: after clicking on btn_save 'Submit Ex form' if (!is_response){ msg_info_html = "<div class='p-2 border_bg_transparent'>" + loc.MAC_info.Creating_comp_form + "...</div>"; show_loader = true; } else if (response.approve_msg_html) { msg_info_html = response.approve_msg_html; if (response.verification_is_ok){ } else { }; }; }; }; //////////////////////////////////////// el_MAC_info_container.innerHTML = msg_info_html; add_or_remove_class(el_MAC_info_container, cls_hide, !msg_info_html) add_or_remove_class(el_MAC_loader, cls_hide, !show_loader) add_or_remove_class(el_MAC_input_verifcode.parentNode, cls_hide, !show_input_verifcode); if (show_input_verifcode){set_focus_on_el_with_timeout(el_MAC_input_verifcode, 150); }; // --- show / hide delete btn add_or_remove_class(el_MAC_btn_delete, cls_hide, !show_delete_btn); // - hide save button when there is no save_btn_txt add_or_remove_class(el_MAC_btn_save, cls_hide, !show_btn_save) // --- disable save button till test is finished or input_verifcode has value el_MAC_btn_save.disabled = disable_save_btn; // --- set innerText of save_btn el_MAC_btn_save.innerText = save_btn_txt; // --- set innerText of cancel_btn el_MAC_btn_cancel.innerText = (show_btn_save) ? loc.Cancel : loc.Close; }
[ "function MAC_UpdateFromResponse(response) {\n console.log(\"==== MAC_UpdateFromResponse ====\");\n console.log(\" response\", response);\n console.log(\" mod_MAC_dict\", mod_MAC_dict);\n console.log(\" mod_MAC_dict.step\", mod_MAC_dict.step);\n\n mod_MAC_dict.test_is_ok = !!response.test_is_ok;\n mod_MAC_dict.verificationkey = response.verificationkey;\n mod_MAC_dict.verification_is_ok = !!response.verification_is_ok;\n\n // - if false verfcode entered: try again, dont update mod_MAC_dict.verificationkey\n if (mod_MAC_dict.step === 2 && !mod_MAC_dict.verification_is_ok ){\n mod_MAC_dict.step -= 1;\n el_MAC_input_verifcode.value = null;\n } else {\n mod_MAC_dict.verificationkey = response.verificationkey;\n };\n\n const count_dict = (response.approve_count_dict) ? response.approve_count_dict : {};\n\n mod_MAC_dict.has_already_approved = (!!count_dict.already_approved)\n mod_MAC_dict.submit_is_ok = (!!count_dict.saved)\n\n MAC_SetInfoboxesAndBtns (response);\n\n }", "function MASS_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASS_SetInfoboxesAndBtns =====\") ;\n // called by MASS_Save and MASS_UpdateFromResponse\n\n console.log(\"......................step\", mod_MASS_dict.step) ;\n console.log(\" test_is_ok\", mod_MASS_dict.test_is_ok) ;\n console.log(\" verification_is_ok\", mod_MASS_dict.verification_is_ok) ;\n\n // step is increased in MASS_save, response has value when response is back from server\n\n const is_response = (typeof response != \"undefined\");\n console.log(\" is_response\", is_response) ;\n\n // TODO is_reset\n const is_reset = mod_MASS_dict.is_reset;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_html = null;\n let show_loader = false;\n let show_input_verifcode = false;\n let show_btn_save = false, show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n//++++++++ approve mode +++++++++++++++++\n if(mod_MASS_dict.is_approve_mode){\n if (mod_MASS_dict.step === 0) {\n if (!is_response){\n // step 0: when form opens and request to check is sent to server\n // text: 'The subjects of the candidates are checked'\n const msg_info_txt = (mod_MASS_dict.examperiod === 1) ? loc.MASS_info.checking_studsubj_ex1 : loc.MASS_info.checking_studsubj_ex4;\n msg_info_html = \"<div class='p-2 border_bg_transparent'>\" + msg_info_txt + \"...</div>\";\n show_loader = true;\n\n } else if (response.approve_msg_html) {\n msg_info_html = response.approve_msg_html;\n // response with checked subjects\n // msg_info_txt is in response\n\n show_btn_save = response.test_is_ok;\n //PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted\n if (show_btn_save ){\n save_btn_txt = (mod_MASS_dict.examperiod === 1) ? loc.Approve_subjects : loc.Approve_reex;\n };\n\n if (mod_MASS_dict.has_already_approved) {\n show_delete_btn = true;\n };\n };\n\n } else if (mod_MASS_dict.step === 1) {\n // step 1: after clicked on btn Approve_subjects\n if (!is_response){\n // text: 'AWP is approving the subjects of the candidates'\n const msg_info_txt = (mod_MASS_dict.examperiod === 1) ? loc.MASS_info.approving_studsubj_ex1 : loc.MASS_info.approving_studsubj_ex4;\n msg_info_html = \"<div class='p-2 border_bg_transparent'>\" + msg_info_txt + \"</div>\";\n show_loader = true;\n } else if (response.approve_msg_html) {\n // step 1: response after clicking on btn Approve_subjects\n // response with \"We have sent an email with a 6 digit verification code to the email address:\"\n // msg_info_html is in response.approve_msg_html\n msg_info_html = response.approve_msg_html;\n };\n };\n } else {\n\n//++++++++ submit mode +++++++++++++++++\n if (mod_MASS_dict.step === 0) {\n if (!is_response){\n // step 0: when form opens and request to check is sent to server\n // text: 'The subjects of the candidates are checked'\n const msg_info_txt = (mod_MASS_dict.examperiod === 1) ? loc.MASS_info.checking_studsubj_ex1 : loc.MASS_info.checking_studsubj_ex4;\n msg_info_html = \"<div class='p-2 border_bg_transparent'>\" + msg_info_txt + \"...</div>\";\n show_loader = true;\n\n } else if (response.approve_msg_html) {\n msg_info_html = response.approve_msg_html;\n // response with checked subjects\n // msg_info_txt is in response\n // text 'You need a 6 digit verification code to submit the Ex form' is in response\n show_btn_save = response.test_is_ok;\n //PR2023-07-11 was bug in ex4 ep3 temporary let submit again when submitted\n if (show_btn_save ){\n save_btn_txt = loc.Request_verifcode;\n };\n };\n } else if (mod_MASS_dict.step === 1) {\n // after clicked on btn Request_verificationcode\n if (!is_response){\n // step 1: when clicked on 'Request verif code\n // tekst: 'AWP is sending an email with the verification code'\n msg_info_html = \"<div class='p-2 border_bg_transparent'>\" + loc.MASS_info.sending_verifcode + \"</div>\";\n show_loader = true;\n } else if (response.approve_msg_html) {\n // step 1: response after sending request verificationcode\n // response with \"We have sent an email with a 6 digit verification code to the email address:\"\n // msg_info_html is in response.approve_msg_html\n msg_info_html = response.approve_msg_html;\n show_btn_save = true;\n show_input_verifcode = true;\n disable_save_btn = !el_MASS_input_verifcode.value;\n save_btn_txt = loc.Submit_Ex_form;\n };\n } else if (mod_MASS_dict.step === 2) {\n // step 2: after clicking on btn_save 'Submit Ex form'\n\n if (!is_response){\n const msg_txt = ([2, 3].includes(mod_MASS_dict.examperiod)) ? loc.Creating_Ex4_form : loc.Creating_Ex1_form;\n msg_info_html = \"<div class='p-2 border_bg_transparent'>\" + msg_txt + \"...</div>\";\n show_loader = true;\n } else if (response.approve_msg_html) {\n msg_info_html = response.approve_msg_html;\n if (response.verification_is_ok){\n\n } else {\n\n };\n };\n };\n };\n\n el_MASS_info_container.innerHTML = msg_info_html;\n add_or_remove_class(el_MASS_info_container, cls_hide, !msg_info_html)\n\n add_or_remove_class(el_MASS_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASS_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASS_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASS_btn_delete, cls_hide, !show_delete_btn);\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASS_btn_save, cls_hide, !show_btn_save)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASS_btn_save.disabled = disable_save_btn;\n// --- set innerText of save_btn\n el_MASS_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASS_btn_cancel.innerText = (show_btn_save) ? loc.Cancel : loc.Close;\n }", "function MPUBORD_SetInfoboxesAndBtns(response) {\n console.log(\"=== MPUBORD_SetInfoboxesAndBtns =====\") ;\n console.log(\"response\", response);\n\n const step = mod_MPUBORD_dict.step;\n const is_response = (!!response);\n const has_error = (is_response && response.error);\n console.log(\"has_error\", has_error) ;\n\n console.log(\"step\", step) ;\n console.log(\"response\", response) ;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_html = null, msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false, show_input_sendemail = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.publish_orderlist_msg_html) {\n msg_html = response.publish_orderlist_msg_html;\n };\n //console.log(\"msg_html\", msg_html);\n\n if (step === 0) {\n // step 0: when form opens\n msg_info_txt = [loc.MPUBORD_info.request_verifcode_01,\n loc.MPUBORD_info.request_verifcode_02,\n \" \",\n loc.MPUBORD_info.request_verifcode_03,\n \" \",\n loc.MPUBORD_info.request_verifcode_04,\n loc.MPUBORD_info.request_verifcode_05,\n loc.MPUBORD_info.request_verifcode_06\n ].join(\"<br>\");\n save_btn_txt = loc.Request_verifcode;\n show_input_sendemail = true;\n console.log(\" step === 0 save_btn_txt\", save_btn_txt) ;\n console.log(\" loc\", loc) ;\n\n } else if (step === 1) {\n // when clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MPUBORD_info.sending_verifcode;\n disable_save_btn = true;\n save_btn_txt = loc.Request_verifcode;\n\n } else if (step === 2) {\n // when response 'email sent' is received\n // msg_html is in response\n show_info_request_verifcode = mod_MPUBORD_dict.test_is_ok;\n show_input_verifcode = !has_error;\n disable_save_btn = !el_MPUBORD_input_verifcode.value;\n if (!has_error){save_btn_txt = loc.MPUBORD_info.Publish_orderlist};\n\n show_input_sendemail = true;\n\n } else if (step === 3) {\n // when clicked on 'Publish orderlist'\n msg_info_txt = loc.MPUBORD_info.Publishing_orderlist + \"...\";\n show_loader = true;\n } else if (step === 4) {\n // when response 'orderlist submitted' is received\n // msg_html is in response\n show_loader = false;\n show_input_verifcode = false;\n };\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n if (msg_info_txt){\n msg_html = \"<div class='p-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \"</p></div>\";\n };\n //console.log(\"msg_html\", msg_html) ;\n el_MPUBORD_info_container.innerHTML = msg_html;\n add_or_remove_class(el_MPUBORD_info_container, cls_hide, !msg_html)\n\n add_or_remove_class(el_MPUBORD_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MPUBORD_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MPUBORD_input_verifcode, 150); };\n\n// --- show or hide el_MPUBORD_send_email\n add_or_remove_class(el_MPUBORD_send_email.parentNode, cls_hide, !show_input_sendemail);\n\n// - hide save button when there is no save_btn_txt\n console.log(\"save_btn_txt\", save_btn_txt) ;\n add_or_remove_class(el_MPUBORD_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MPUBORD_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MPUBORD_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MPUBORD_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n// --- add eventlistener to href element\n if (step === 4) {\n const el_MPUBORD_OpenLogfile = document.getElementById(\"id_MPUBORD_OpenLogfile\");\n if(el_MPUBORD_OpenLogfile){\n el_MPUBORD_OpenLogfile.addEventListener(\"click\", function() {MPUBORD_OpenLogfile()}, false);\n };\n };\n\n// --- set innerText of cancel_btn\n }", "function MASE_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASE_SetInfoboxesAndBtns =====\") ;\n\n const step = mod_MASE_dict.step;\n const is_response = (!!response);\n\n console.log(\"......................step\", step) ;\n console.log(\" is_response\", is_response) ;\n console.log(\" test_is_ok\", mod_MASE_dict.test_is_ok) ;\n console.log(\" is_approve_mode\", mod_MASE_dict.is_approve_mode) ;\n console.log(\" verification_is_ok\", mod_MASE_dict.verification_is_ok) ;\n\n // step 0: opening modal\n // step 1 + response : return after check\n // step 1 without response: save clicked approve or request verifcode\n // step 2 + response : return after approve or after email sent\n // step 2 without response: submit Exform wit hverifcode\n // step 3 + response: return from submit Exform\n\n // TODO is_reset\n const is_reset = mod_MASE_dict.is_reset;\n\n//////////////////////////////////////////////////////////\n// --- select_container //\n//////////////////////////////////////////////////////////\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false;\n let show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.approve_msg_html) {\n mod_MASE_dict.msg_html = response.approve_msg_html;\n };\n\n console.log(\" step\", step);\n\n if (step === 0) {\n // step 0: when form opens and request to check is sent to server\n // tekst: 'The subjects of the candidates are checked'\n msg_info_txt = loc.MASE_info.checking_exams;\n show_loader = true;\n } else {\n if (mod_MASE_dict.is_copy_scores){\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = false;\n if (response.total_change){\n save_btn_txt = loc.MASE_info.Copy_wolf_scores;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n // tekst: 'AWP is approving the subjects of the candidates'\n msg_info_txt = loc.MASE_info.Awp_is_copying_wolf_scores;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else if (mod_MASE_dict.is_approve_mode){\n // --- is approve\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = mod_MASE_dict.has_already_approved;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.MASE_info.Approve_exams;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n // tekst: 'AWP is approving the subjects of the candidates'\n msg_info_txt = (is_reset) ? loc.MASE_info.removing_approval_exams : loc.MASE_info.approving_exams;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else {\n // --- is submit\n if (step === 1) {\n // response with checked subjects\n // msg_info_txt is in response\n show_info_request_verifcode = response.has_tobesubmitted_eteexams;\n if (show_info_request_verifcode){\n save_btn_txt = loc.Request_verifcode;\n };\n } else if (step === 2) {\n // clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MASE_info.sending_verifcode;\n show_loader = true;\n } else if (step === 3) {\n // response 'email sent'\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n show_input_verifcode = true;\n disable_save_btn = !el_MASE_input_verifcode.value;\n save_btn_txt = loc.Submit_wolf_exams;\n } else if (step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n show_loader = true;\n } else if (step === 5) {\n // response 'Exform submittes'\n // msg_info_txt is in response\n }\n } // if(mod_MASE_dict.is_approve_mode)\n } // if (step === 0)\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n\n if (msg_info_txt){\n mod_MASE_dict.msg_html = \"<div class='pt-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \" ...</p></div>\";\n }\n\n const hide_info_container = (!msg_info_txt || show_loader)\n add_or_remove_class(el_MASE_info_container, cls_hide, hide_info_container)\n\n el_MASE_msg_container.innerHTML = mod_MASE_dict.msg_html;\n add_or_remove_class(el_MASE_msg_container, cls_hide, !mod_MASE_dict.msg_html)\n\n add_or_remove_class(el_MASE_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASE_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n add_or_remove_class(el_MASE_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n\n if (el_MASE_info_request_msg1){\n el_MASE_info_request_msg1.innerText = loc.MASE_info.need_verifcode +\n ((permit_dict.requsr_role_admin) ? loc.MASE_info.to_publish_exams : loc.MASE_info.to_submit_exams);\n };\n\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASE_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASE_btn_delete, cls_hide, !show_delete_btn);\n\n console.log(\"save_btn_txt\", save_btn_txt) ;\n\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASE_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASE_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MASE_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASE_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n }", "function MAG_SetInfoboxesAndBtns(response) {\n console.log(\"=== MAG_SetInfoboxesAndBtns =====\") ;\n // called by MAG_Save and MAG_UpdateFromResponse\n // response is undefined when opening modal\n\n console.log(\" ====> step\", mod_MAG_dict.step);\n\n // --- get header_txt and subheader_txt\n const header_txt = (mod_MAG_dict.is_approve_mode) ? (mod_MAG_dict.is_examperiod_exemption) ? loc.Approve_exemptions :\n (mod_MAG_dict.examtype == \"se\") ? loc.Approve_grades : loc.Approve_scores :\n (mod_MAG_dict.is_submit_ex2_mode) ? loc.Submit_Ex2_form :\n (mod_MAG_dict.is_submit_ex2a_mode) ? loc.Submit_Ex2A_form : null;\n el_MAG_header.innerText = header_txt;\n const subheader_txt = (mod_MAG_dict.is_approve_mode) ? (mod_MAG_dict.is_examperiod_exemption) ? loc.MAG_info.subheader_approve_exem :\n\n (mod_MAG_dict.examtype == \"se\") ? loc.MAG_info.subheader_approve_grade : loc.MAG_info.subheader_approve_score :\n (mod_MAG_dict.is_submit_ex2_mode) ? loc.MAG_info.subheader_submit_ex2 :\n (mod_MAG_dict.is_submit_ex2a_mode) ? loc.MAG_info.subheader_submit_ex2a : null;\n el_MAG_subheader.innerText = subheader_txt;\n\n const is_response = (!!response);\n mod_MAG_dict.test_is_ok = (response && response.test_is_ok);\n mod_MAG_dict.has_already_approved = (response && response.has_already_approved);\n\n mod_MAG_dict.verification_is_ok = (response && response.verification_is_ok) ? true : false;\n mod_MAG_dict.verificationkey = (response && response.verificationkey) ? response.verificationkey : null;\n\n //console.log(\" is_response: \", is_response) ;\n //console.log(\" test_is_ok\", mod_MAG_dict.test_is_ok) ;\n //console.log(\" verification_is_ok\", mod_MAG_dict.verification_is_ok) ;\n //console.log(\" verificationkey\", mod_MAG_dict.verificationkey) ;\n\n // --- in MAG_Open: show el_MAG_select_container and delete button only in approve mode\n\n let show_loader = false, show_input_verifcode = false, reset_input_verifcode = false;\n let msg_info_html = null, msg_info_txt = null;\n let btn_save_txt = null;\n\n// --- hide delete btn when reset or publish mode\n\n// ++++++++++++++++ step 0 applies to approve and submit ++++++++++++++++\n if (mod_MAG_dict.step === 0) {\n // step 0: when form opens and request to check is sent to server\n msg_info_txt = (mod_MAG_dict.examtype === \"ce\") ? loc.MAG_info.awp_is_checking_scores : loc.MAG_info.awp_is_checking_grades;\n show_loader = true;\n mod_MAG_dict.btn_save_enabled = false;\n mod_MAG_dict.may_show_err_verifcode = false;\n mod_MAG_dict.show_err_verifcode = false;\n\n// ++++++++++++++++ approve mode ++++++++++++++++\n } else if(mod_MAG_dict.is_approve_mode){\n\n if (mod_MAG_dict.step === 1) {\n // msg_info_txt is in response: \"De selectie bevat 1406 cijfers.\"\n if(is_response){\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n if (response.test_is_ok){\n btn_save_txt = (mod_MAG_dict.examtype == \"se\") ? loc.Approve_grades : loc.Approve_scores;\n mod_MAG_dict.btn_save_enabled = true;\n };\n\n } else {\n // after clicking 'Approve'\n msg_info_txt = (mod_MAG_dict.is_reset) ? loc.Removing_approvals :\n (mod_MAG_dict.examtype == \"se\") ? loc.Approving_grades : loc.Approving_scores;\n show_loader = true;\n mod_MAG_dict.btn_save_enabled = false;\n };\n\n //if(response && response.approve_msg_html){\n // msg_info_html = response.approve_msg_html;\n // }\n\n } else if (mod_MAG_dict.step === 2) {\n // response after clicking on 'Approve'\n // if test_is_ok = true : close modal\n // else : show err message\n // tekst: 'AWP is approving the subjects of the candidates'\n\n\n\n //console.log(\" @@@@@@@@@@@@@@@ response.test_is_ok\", response.test_is_ok) ;\n //console.log(\" response.approve_msg_html\", response.approve_msg_html) ;\n\n if(is_response){\n if (response.test_is_ok){\n //console.log(\" ???????????? response.test_is_ok\", response.test_is_ok) ;\n $(\"#id_mod_approve_grade\").modal(\"hide\");\n } else {\n //console.log(\" !!!!!!!!!!!!!!!!! response.test_is_ok\", response.test_is_ok) ;\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n };\n };\n };\n } else {\n\n// ++++++++++++++++ submit mode ++++++++++++++++\n if (mod_MAG_dict.step === 1) {\n // step becomes 1 in MAG_UpdateFromResponse after checking grades\n // msg_info_txt is in response: \"De selectie bevat 1406 cijfers.\"\n // is_response is false after clicking on 'Request_verificationcode'\n if(is_response){\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n if(response.test_is_ok){\n btn_save_txt = loc.Request_verifcode;\n mod_MAG_dict.btn_save_enabled = true;\n };\n } else {\n msg_info_txt = loc.MAG_info.sending_verifcode;\n show_loader = true;\n mod_MAG_dict.btn_save_enabled = false;\n };\n } else if (mod_MAG_dict.step === 2) {\n // step becomes 2 after response on clicking 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n\n if(is_response){\n // msg_info_html: We hebben een e-mail gestuurd met een 6-cijferige verificatiecode naar het e-mail adres\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n // show_input_verifcode only when a verificationkey is received\n show_input_verifcode = !!mod_MAG_dict.verificationkey;\n reset_input_verifcode = show_input_verifcode;\n btn_save_txt = loc.Submit_Ex_form;\n mod_MAG_dict.btn_save_enabled = false;\n\n } else {\n mod_MAG_dict.btn_save_enabled = (el_MAG_input_verifcode.value && el_MAG_input_verifcode.value.length === 6 && (Number(el_MAG_input_verifcode.value) || el_MAG_input_verifcode.value === \"000000\"));\n mod_MAG_dict.show_err_verifcode = (el_MAG_input_verifcode.value && !mod_MAG_dict.btn_save_enabled);\n\n if (mod_MAG_dict.btn_save_enabled){\n msg_info_txt = loc.MAG_info.creating_ex2_form;\n show_loader = true;\n };\n };\n } else if (mod_MAG_dict.step === 3) {\n\n if(is_response){\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n } else {\n show_input_verifcode = !!mod_MAG_dict.verificationkey;\n\n //disable_save_btn = !el_MAG_input_verifcode.value;\n }\n } else if (mod_MAG_dict.step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n\n if(is_response){\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n } else {\n show_loader = true;\n };\n } else if (mod_MAG_dict.step === 5) {\n // response 'Exform submitted'\n // msg_info_txt is in response\n\n if(is_response){\n msg_info_html = (response.approve_msg_html) ? response.approve_msg_html : null;\n }\n };\n };\n if (msg_info_txt){\n msg_info_html = \"<div class='p-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \"</p></div>\";\n };\n\n // --- disable select auth_index after step 1\n if (el_MAG_auth_index){\n //el_MAG_auth_index.disabled = false // (mod_MAG_dict.step > 1);\n };\n\n console.log(\" ===> msg_info_html\", msg_info_html) ;\n el_MAG_info_container.innerHTML = msg_info_html;\n add_or_remove_class(el_MAG_info_container, cls_hide, !msg_info_html)\n\n// --- show el_MAG_info_request_verifcode and el_MAG_input_verifcode =====\n add_or_remove_class(el_MAG_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MAG_input_verifcode, 150)};\n if (reset_input_verifcode) {el_MAG_input_verifcode.value = null};\n\n// --- show el_MAG_info_request_verifcode with text 'You need a 6 digit verification code ...\n // text of el_MAG_info_request_verifcode is embedded in template modapprovegrade\n let show_info_request_verifcode = false;\n if(!mod_MAG_dict.is_approve_mode){\n if (mod_MAG_dict.step === 1) {\n show_info_request_verifcode = mod_MAG_dict.test_is_ok;\n };\n }\n add_or_remove_class(el_MAG_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n\n// --- show / hide loader\n add_or_remove_class(el_MAG_loader, cls_hide, !show_loader)\n\n// --- show / hide error msg of input verifcode\n add_or_remove_class(el_MAG_err_verifcode, cls_hide, !mod_MAG_dict.show_err_verifcode);\n// --- make input field red when error\n add_or_remove_class(el_MAG_input_verifcode, \"border_bg_invalid\", mod_MAG_dict.show_err_verifcode);\n\n// --- show / enable save btn\n el_MAG_btn_save.innerText = btn_save_txt;\n add_or_remove_class(el_MAG_btn_save, cls_hide, !btn_save_txt);\n el_MAG_btn_save.disabled = !mod_MAG_dict.btn_save_enabled;\n\n el_MAG_btn_cancel.innerText = (!btn_save_txt) ? loc.Close : loc.Cancel;\n\n// --- show only the elements that are used in this tab\n const show_class = \"tab_step_\" + mod_MAG_dict.step;\n b_show_hide_selected_elements_byClass(\"tab_show\", show_class, el_mod_approve_grade);\n\n// --- hide delete btn when reset or publish mode\n const show_delete_btn = (mod_MAG_dict.step === 1 && mod_MAG_dict.is_approve_mode && mod_MAG_dict.has_already_approved);\n add_or_remove_class(el_MAG_btn_delete, cls_hide, !show_delete_btn);\n\n}", "function MAG_UpdateFromResponse(response) {\n if (mod_MAG_dict.step === 2 && !response.test_is_ok ){\n // when verifcode not correct: don't incease step\n } else {\n mod_MAG_dict.step += 1;\n };\n MAG_SetInfoboxesAndBtns(response);\n }", "function updateImacSuccess() \n{\n RMPApplication.debug(\"begin updateImacSuccess\");\n\tc_debug(debug.process_btn, \"=> updateImacSuccess\");\n\tvar success_msg = ${P_quoted(i18n(\"updateImacSuccess_msg\", \"Le formulaire a bien été mis à jour!\"))};\n notify_success(success_title_notify, success_msg);\n\n\tRMPApplication.debug(\"end updateImacSuccess\");\t\n\t// return true;\t\t// needed as called by pre-launch script \"Mettre à jour l'IMAC\" button\n}", "function updateImacSuccess() \n{\n RMPApplication.debug(\"begin updateImacSuccess\");\n\tc_debug(debug.process_btn, \"=> updateImacSuccess\");\n\tvar success_msg = ${P_quoted(i18n(\"updateImacSuccess_msg\", \"Le formulaire a bien été mis à jour!\"))};\n notify_success(success_title_notify, success_msg);\n\n RMPApplication.debug(\"end updateImacSuccess\");\n \n\t// return true;\t\t// needed as called by pre-launch script \"Mettre à jour l'IMAC\" button\n}", "function updateInfoBox(module){\n\tvar items = generateDataForTrackingTable(module);\n\tvar infobox = dhtml.getElementById(\"meetingrequest_responses\");\n\tif(items.length >1){\n\t\tvar accepted = 0, tentative = 0, declined = 0;\n\t\tfor(var i=0;i<items.length;i++){\n\t\t\tswitch( parseInt(items[i].recipient_status_num.innerHTML, 10) ) {\n\t\t\t\tcase olResponseTentative: // tentative\n\t\t\t\t\ttentative++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase olResponseAccepted: //accepted\n\t\t\t\t\taccepted++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase olResponseDeclined: // declined\n\t\t\t\t\tdeclined++;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tinfobox.style.display = \"block\";\n\t\tinfobox.innerHTML = NBSP + accepted +\" \"+ _(\"attendee accepted\") +\", \"+ tentative +\" \"+ _(\"tentatively accepted\") +\", \"+ declined +\" \"+ _(\"declined\") +\".\";\n\t}\n}", "function updateImac() \n{\n RMPApplication.debug(\"begin updateImac\");\n c_debug(debug.process_btn, \"=> updateImac\");\n\tupdate_done = false;\n\n\t// validate data before continuing the process or saving the form\n\tsdmoValidation();\n\n\twhile (update_done == false) {\n\t\t// wait until flag update_done is setted to true\n\t}\n\tc_debug(debug.process_btn, \"=> updateImac: before returning TRUE\");\n\tRMPApplication.debug(\"end updateImac\");\n\treturn true;\t\t// needed as called by pre-launch script \"Mettre à jour l'IMAC\" button\t\n\t\n}", "function MASS_UpdateFromResponse(response) {\n console.log(\"==== MASS_UpdateFromResponse ====\");\n console.log(\" response\", response);\n console.log(\" mod_MASS_dict\", mod_MASS_dict);\n console.log(\" mod_MASS_dict.step\", mod_MASS_dict.step);\n\n mod_MASS_dict.test_is_ok = !!response.test_is_ok;\n mod_MASS_dict.verification_is_ok = !!response.verification_is_ok;\n\n // - if false verfcode entered: try again, dont update mod_MASS_dict.verificationkey\n if (mod_MASS_dict.step === 2 && !mod_MASS_dict.verification_is_ok ){\n mod_MASS_dict.step -= 1;\n el_MASS_input_verifcode.value = null;\n } else {\n mod_MASS_dict.verificationkey = response.verificationkey;\n };\n\n const count_dict = (response.approve_count_dict) ? response.approve_count_dict : {};\n\n mod_MASS_dict.has_already_approved = (!!count_dict.already_approved)\n mod_MASS_dict.submit_is_ok = (!!count_dict.saved)\n\n MASS_SetInfoboxesAndBtns(response);\n\n //if (\"updated_studsubj_approve_rows\" in response){\n // RefreshDataRows(\"studsubj\", response.updated_studsubj_approve_rows, studsubj_rows, true);\n //}\n if ( (mod_MASS_dict.is_approve_mode && mod_MASS_dict.step === 3) || (mod_MASS_dict.is_submit_mode && mod_MASS_dict.step === 5)){\n const datalist_request = { setting: {page: \"page_studsubj\"},\n studentsubject_rows: {cur_dep_only: true},\n published_rows: {get: true}\n };\n\n console.log(\"......................datalist_request\", datalist_request) ;\n //DatalistDownload(datalist_request);\n };\n }", "function MENVPR_UpdateFromResponse(response) {\n //console.log(\" ===== MENVPR_UpdateFromResponse =====\");\n //console.log(\"response\", response)\n\n el_MENVPR_loader.classList.add(cls_hide);\n\n mod_MENV_dict.envelopsubject_rows = (response.checked_envelopsubject_rows) ? response.checked_envelopsubject_rows : [];\n mod_MENV_dict.school_rows = (response.checked_envelop_school_rows) ? response.checked_envelop_school_rows : [];\n\n //console.log(\" mod_MENV_dict.school_rows\", mod_MENV_dict.school_rows)\n //console.log(\" mod_MENV_dict.envelopsubject_rows\", mod_MENV_dict.envelopsubject_rows)\n // = (response.sel_examperiod) ? response.sel_examperiod : null;\n //mod_MENV_dict.emod_MENV_dict.sel_examperiodxamperiod_caption = (response.examperiod_caption) ? response.examperiod_caption : \"---\";\n\n //mod_MENV_dict.lvlbase_pk_list = (response.lvlbase_pk_list) ? response.lvlbase_pk_list : [];\n\n // TODO save sel_layout in usersettings\n // el_MENVPR_select_errata.value = (response.sel_layout) ? response.sel_layout : null;\n\n MENVPR_FillTblSchool();\n MENVPR_FillTblExams();\n\n// --- set text on msg_modified\n let modified_text = null;\n if (\"updated_enveloporderlist_modifiedat\" in response){\n const modified_dateJS = parse_dateJS_from_dateISO(response.updated_enveloporderlist_modifiedat);\n const modified_date_formatted = format_datetime_from_datetimeJS(loc, modified_dateJS, true, false, true);\n modified_text = loc.The_orderlist_is_published_at + modified_date_formatted + \". \" + loc.The_published_numbers_willbe_used;\n } else {\n modified_text = loc.The_orderlist_is_not_published + \" \" + loc.The_actual_numbers_willbe_used;\n };\n el_MENVPR_msg_modified.innerText = modified_text;\n\n// --- enable save btn\n MENVPR_EnableBtnSave();\n\n } // MENVPR_UpdateFromResponse", "function e368_SetMAC(macString, devIndx)\n{\n if((e368info[devIndx]).isOld)\n {\n Out.Printf(Out.PriNormal, \"Error: MAC address cannot be set on old e368 boards\\n\\n\");\n return; // Call old boards N/A since they have no IP function\n } \n else {\n var read = new Array;\n e368_SendCommand( (\"setmac \" + macString), read, devIndx );\n // Split the line of reply, delimited by spaces:\n var retLine = (read[1]).split(/\\s/g);\n // Make sure response is what we're looking for- 1st word should be \"Setting\"\n if((retLine[0]).search(\"Saved\") != -1)\n {\n Out.Printf(Out.PriNormal, \"MAC address successfully set!\\n\");\n }\n else {\n Out.Printf(Out.PriNormal, \"Error while saving MAC address. Line read:\\n%s\\n\",read[1]);\n }\n }\n return;\n}", "function updateImacBeforeEnd() \n{\n RMPApplication.debug(\"begin updateImacBeforeEnd\");\n c_debug(debug.process_btn, \"=> updateImacBeforeEnd\");\n\n\t// validate data before continuing the process or saving the form\n\tsdmoValidation();\n\n\tRMPApplication.debug(\"end updateImacBeforeEnd\");\n}", "function imacContentStateUpdate() \n{\n RMPApplication.debug(\"begin imacContentStateUpdate\");\n c_debug(debug.process_btn, \"=> imacContentStateUpdate\");\n\n\tvar sent_state = ${P_quoted(i18n(\"sent_state\", \"Transmise\"))};\n\tvar accepted_state = ${P_quoted(i18n(\"accepted_state\", \"Acceptée\"))};\n\tvar planned_state = ${P_quoted(i18n(\"planned_state\", \"Inter.planifiée\"))};\n\tvar ordered_state = ${P_quoted(i18n(\"ordered_state\", \"Commandée\"))};\n\tvar achieved_state = ${P_quoted(i18n(\"achieved_state\", \"Réalisée\"))};\n\tvar cancelled_state = ${P_quoted(i18n(\"cancelled_state\", \"Annulée\"))};\n\n\tvar states = { \n\t\t\"sent\": sent_state,\n\t\t\"accepted\": accepted_state,\n\t\t\"planned\": planned_state,\n\t\t\"ordered\": ordered_state,\n\t\t\"achieved\": achieved_state,\n\t\t\"cancelled\": cancelled_state\n\t};\n\tvar state_content = \"\";\n\tvar separator = \" - \";\n\tif (id_state.getValue() == \"sent\") {\n\t\tstate_content += ((state_content == \"\") ? \"\" : separator) + states.sent;\n\t}\n\t// state_content += ((state_content == \"\") ? \"\" : separator) + \"<span style=\\'background-color: red; color: white;\\'>\" + states.accepted + \"</span>\";\n\tif (id_imac_accepted.isChecked()) {\n\t\tstate_content += ((state_content == \"\") ? \"\" : separator) + states.accepted;\n\t}\n\tif (id_inter_planned.isChecked()) {\n\t\tstate_content += ((state_content == \"\") ? \"\" : separator) + states.planned;\n\t}\n\tif (id_imac_achieved.isChecked()) {\n\t\tstate_content = states.achieved;\t\t// previous actions are cleared\n\t}\n\tif (id_imac_cancelled.isChecked()) {\n\t\tstate_content = states.cancelled;\t\t// previous actions are cleared\n\t}\n\n\tid_fujitsu_state.setValue(state_content);\n\n\tRMPApplication.debug(\"end imacContentStateUpdate\");\n}", "function MUA_SetMsgElements(response){\n console.log( \"===== MUA_SetMsgElements ========= \");\n // TODO switch to render msg box\n const err_dict = (response && \"msg_err\" in response) ? response.msg_err : {};\n // was const validation_ok = get_dict_value(response, [\"validation_ok\"], false);\n const validation_ok = (response && \"validation_ok\" in response) ? response.validation_ok : false;\n\n\n if(\"user_without_userallowed\" in response){\n\n // --- hide modal\n $(\"#id_mod_user\").modal(\"hide\");\n // function ModConfirmOpen(tblName, mode, el_input, user_without_userallowed) {\n ModConfirmOpen(null, \"user_without_userallowed\", null, response.user_without_userallowed);\n\n } else {\n\n\n const el_msg_container = document.getElementById(\"id_MUA_msg_container\")\n let err_save = false;\n let is_ok = (response && \"msg_ok\" in response);\n if (is_ok) {\n const ok_dict = response.msg_ok;\n document.getElementById(\"id_msg_01\").innerText = get_dict_value(ok_dict, [\"msg01\"]);\n document.getElementById(\"id_msg_02\").innerText = get_dict_value(ok_dict, [\"msg02\"]);\n document.getElementById(\"id_msg_03\").innerText = get_dict_value(ok_dict, [\"msg03\"]);\n document.getElementById(\"id_msg_04\").innerText = get_dict_value(ok_dict, [\"msg04\"]);\n\n el_msg_container.classList.remove(\"border_bg_invalid\");\n el_msg_container.classList.add(\"border_bg_valid\");\n // --- show only the elements that are used in this tab\n b_show_hide_selected_elements_byClass(\"mua_show\", \"mua_ok\");\n\n } else {\n // --- loop through input elements\n if(\"save\" in err_dict){\n\n //console.log( \"err_dict\", err_dict);\n const save_dict = err_dict.save\n //console.log( \"save_dict\", save_dict);\n err_save = true;\n\n document.getElementById(\"id_msg_01\").innerText = get_dict_value(save_dict, [\"msg01\"]);\n document.getElementById(\"id_msg_02\").innerText = get_dict_value(save_dict, [\"msg02\"]);\n document.getElementById(\"id_msg_03\").innerText = get_dict_value(save_dict, [\"msg03\"]);\n document.getElementById(\"id_msg_04\").innerText = get_dict_value(save_dict, [\"msg04\"]);\n\n el_msg_container.classList.remove(\"border_bg_valid\");\n el_msg_container.classList.add(\"border_bg_invalid\");\n // --- show only the elements that are used in this tab\n b_show_hide_selected_elements_byClass(\"mua_show\", \"mua_ok\");\n\n } else {\n const fields = [\"username\", \"last_name\", \"email\"]\n for (let i = 0, field; field = fields[i]; i++) {\n const msg_err = get_dict_value(err_dict, [field]);\n const msg_info = loc.msg_user_info[i];\n //console.log( \"-----------field\", field);\n //console.log( \"msg_err\", msg_err);\n //console.log( \"msg_info\", msg_info);\n let el_input = document.getElementById(\"id_MUA_\" + field);\n\n const must_blur = ( (!!msg_err && !el_input.classList.contains(\"border_bg_invalid\")) ||\n (!msg_err && !el_input.classList.contains(\"border_bg_valid\")) );\n if( must_blur) { el_input.blur() };\n add_or_remove_class (el_input, \"border_bg_invalid\", (!!msg_err));\n add_or_remove_class (el_input, \"border_bg_valid\", (!msg_err));\n\n let el_msg = document.getElementById(\"id_MUA_msg_\" + field);\n add_or_remove_class (el_msg, \"text-danger\", (!!msg_err));\n el_msg.innerText = (!!msg_err) ? msg_err : msg_info\n }\n }\n\n el_MUA_btn_submit.disabled = !validation_ok;\n if(validation_ok){el_MUA_btn_submit.focus()}\n }\n\n // --- show message in footer when no error and no ok msg\n add_or_remove_class(el_MUA_footer_container, cls_hide, !validation_ok )\n\n // --- hide submit btn and delete btnwhen is_ok or when error\n add_or_remove_class(el_MUA_btn_submit, cls_hide, is_ok || err_save)\n add_or_remove_class(el_MUA_btn_delete, cls_hide, is_ok || err_save)\n\n // --- set text on btn cancel\n if (el_MUA_btn_cancel){\n el_MUA_btn_cancel.innerText = ((is_ok || err_save) ? loc.Close : loc.Cancel);\n if(is_ok || err_save){el_MUA_btn_cancel.focus()}\n };\n };\n } // MUA_SetMsgElements", "function ClientService_OnDecode(config, oldResponse, noStrip) {\n //var response = oldResponse[\"response\"];\n if (!oldResponse['response'] || oldResponse['response'].length == 0) {\n console.warn(\n 'AuraInspectorInjectedScript.onDecode received a bad response.',\n oldResponse\n );\n return config['fn'].call(config['scope'], oldResponse, noStrip);\n }\n\n //modify response if we find the action we are watching\n var response = oldResponse['response'];\n var oldResponseText = oldResponse['responseText'];\n var newResponseText = oldResponseText;\n // var responseModified = false;//if we modify the response, set this to true\n // var responseWithError = false;//if we send back error response, set this to true\n // var responseWithIncomplete = false;//if we want to kill the action, set this to true\n\n if (this.hasWatchedActions()) {\n try {\n for (var actionId in actionsWatched) {\n if (!oldResponseText.includes(actionId)) {\n continue;\n }\n\n var actionWatched = actionsWatched[actionId];\n var actionsObj = getActionsFromResponseText(oldResponseText);\n var responseActions = (actionsObj && actionsObj.actions) || [];\n\n var actionFound;\n var restOfActions = responseActions.filter(current => {\n if (current.id === actionId) {\n actionFound = current;\n return false;\n } else {\n return true;\n }\n });\n\n // We have not yet found an action in the existing set we want to modify\n if (!actionFound) {\n continue;\n }\n //we would like to return error response\n if (actionWatched.nextError) {\n actionFound.state = 'ERROR';\n actionFound.error = [actionWatched.nextError];\n actionFound.returnValue = null;\n var actionsEndIndex = oldResponseText.indexOf('context\"');\n newResponseText =\n '{\"actions\":' +\n JSON.stringify(restOfActions.concat(actionFound)) +\n ',\"' +\n oldResponseText.substring(actionsEndIndex, oldResponseText.length);\n //move the actionCard from watch list to Processed\n //this will call AuraInspectorActionsView_OnActionStateChange in AuraInspectorActionsView.js\n $Aura.Inspector.publish('AuraInspector:OnActionStateChange', {\n id: actionId,\n idtoWatch: actionWatched.idtoWatch,\n state: 'RESPONSEMODIFIED',\n sentTime: performance.now() //do we need this?\n });\n\n const newHttpRequest = {\n status: 200,\n response: newResponseText,\n responseText: newResponseText,\n $hasError: true\n };\n\n return config['fn'].call(config['scope'], newHttpRequest, noStrip);\n }\n //we would like to return non-error response\n else if (actionWatched.nextResponse) {\n // var responseModified = Object.assign(\n // actionFound.returnValue,\n // actionWatched.nextResponse\n // );\n // if (responseModified) {\n //actionFound.returnValue = responseModified;\n actionFound.returnValue = actionWatched.nextResponse;\n var actionsEndIndex = oldResponseText.indexOf('context\"');\n newResponseText =\n '{\"actions\":' +\n JSON.stringify(restOfActions.concat(actionFound)) +\n ',\"' +\n oldResponseText.substring(actionsEndIndex, oldResponseText.length);\n\n //move the actionCard from watch list to Processed\n //this will call AuraInspectorActionsView_OnActionStateChange in AuraInspectorActionsView.js\n $Aura.Inspector.publish('AuraInspector:OnActionStateChange', {\n id: actionId,\n idtoWatch: actionWatched.idtoWatch,\n state: 'RESPONSEMODIFIED',\n sentTime: performance.now() //do we need this?\n });\n\n const newHttpRequest = Object.assign($A.util.apply({}, oldResponse), {\n response: newResponseText,\n responseText: newResponseText,\n $isModified: true\n });\n\n return config['fn'].call(config['scope'], newHttpRequest, noStrip);\n //}\n }\n //we would like to kill action, return incomplete\n else {\n //responseWithIncomplete = true;\n //move the actionCard from watch list to Processed\n //this will call AuraInspectorActionsView_OnActionStateChange in AuraInspectorActionsView.js\n $Aura.Inspector.publish('AuraInspector:OnActionStateChange', {\n id: actionId,\n idtoWatch: actionWatched.idtoWatch,\n state: 'RESPONSEMODIFIED',\n sentTime: performance.now(), //do we need this?\n byChaosRun: actionWatched.byChaosRun\n });\n if (actionWatched.byChaosRun) {\n $Aura.Inspector.publish('AuraInspector:OnCreateChaosCard', {\n message:\n 'Drop action ' +\n actionWatched.id +\n ', the old actionId from replay: ' +\n actionWatched.idtoWatch\n });\n if (actionWatched.id === actionWatched.idtoWatch) {\n console.warn(\n 'The action in your replay has the same id as the action being dropped, this will confuse ActionTab, as it use actionId to find and move actionCard around. Please change action id in your replay file to something else, like 9999 :-) '\n );\n }\n }\n\n const newHttpRequest = {\n status: 0,\n $isIncomplete: true\n };\n\n return config['fn'].call(config['scope'], newHttpRequest, noStrip);\n }\n }\n } catch (e) {\n console.warn(\n 'get response we cannot parse with JSON.parse, skip',\n oldResponse,\n e\n );\n return config['fn'].call(config['scope'], oldResponse, noStrip);\n }\n }\n\n //nothing happended, just send back oldResponse\n return config['fn'].call(config['scope'], oldResponse, noStrip);\n }", "_update_server_info(){\n if(this.currentStatus === NVPNMenu.STATUS.CONNECTED){\n let t= this._cmd.exec_sync('current_server_get');\n this.server_info.process(t);\n }\n else{\n this.server_info.reset();\n }\n }", "function MPUBORD_UpdateFromResponse(response) {\n //console.log( \" ==== MPUBORD_UpdateFromResponse ====\");\n //console.log( \"response\", response);\n //console.log(\"mod_MPUBORD_dict\", mod_MPUBORD_dict);\n mod_MPUBORD_dict.step += 1;\n\n mod_MPUBORD_dict.error = !!response.error;\n mod_MPUBORD_dict.verificationkey = response.verificationkey;\n mod_MPUBORD_dict.verification_is_ok = !!response.verification_is_ok;\n\n if (\"log_list\" in response){\n mod_MPUBORD_dict.log_list = response.log_list;\n };\n\n // mod_MPUBORD_dict.submit_is_ok = (!!count_dict.saved)\n //mod_MPUBORD_dict.has_already_published = (!!msg_dict.already_published)\n //mod_MPUBORD_dict.has_saved = !!msg_dict.saved;\n\n MPUBORD_SetInfoboxesAndBtns(response);\n\n if ( (mod_MPUBORD_dict.is_approve && mod_MPUBORD_dict.step === 3) || (mod_MPUBORD_dict.is_submit && mod_MPUBORD_dict.step === 5)){\n const datalist_request = { setting: {page: \"page_studsubj\"},\n //studentsubject_rows: {cur_dep_only: true},\n }\n DatalistDownload(datalist_request);\n };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update d'un madbet (PUT)
function updateMadbet(req, res) { console.log("UPDATE recu madbet : "); console.log(req.body); Madbet.findByIdAndUpdate( req.body._id, req.body, { new: true }, (err, madbet) => { if (err) { console.log(err); res.send(err); } else { res.json({ message: "updated" }); } // console.log('updated ', madbet) } ); }
[ "update(req,res){\r\n res.status(200).json(\r\n {\r\n sucess: true,\r\n messages: 'Estructura base PUT',\r\n errors: null,\r\n data: [{}, {}, {}]\r\n }\r\n );\r\n }", "update(req,res){\n res.status(200).json(\n {\n sucess: true,\n messages: 'Estructura base PUT',\n errors: null,\n data: [{}, {}, {}]\n }\n );\n }", "async function update(req, res) {\n const updatedMantra = await Mantra.findByIdAndUpdate(\n req.params.id,\n req.body,\n { new: true }\n );\n res.status(200).json(updatedMantra);\n}", "PUT() {\n this.execute('PUT');\n }", "function updateMatiere(req, res) {\n console.log(\"UPDATE recu matiere : \");\n console.log(req.body);\n const body = {\n nom: req.body.nom,\n prof: req.body.prof,\n image: req.body.image\n };\n Matiere.findByIdAndUpdate(req.body.id, body, {new: true}, (err, matiere) => {\n if (err) {\n console.log(err);\n res.send(err)\n } else {\n res.json({message: 'modification éffectué'})\n }\n\n \n });\n\n}", "function updateMedico(req, resp) {\n // metodo put ...llega por body\n\n let update = req.body;\n let medicoId = req.params.id;\n\n Medico.findById(medicoId, (err, medicoDB) => {\n\n if (err) {\n return resp.status(500).json({ // internal server\n ok: false,\n mensaje: 'el medico con el id' + medicoId + 'no existe',\n errors: err\n })\n }\n\n if (!medicoDB) {\n return resp.status(400).json({ // bad request\n ok: false,\n mensaje: 'no se pudo actualizar el medico con el id :' + medicoId\n });\n }\n medicoDB.nombre = update.nombre;\n medicoDB.usuario = req.usuario._id; // modificamos el id del usuario que lo modifico \n medicoDB.hospital = update.hospital // recibimos del body todo el hospital \n\n medicoDB.save((err, medicoUpdated) => {\n\n if (err) {\n return resp.status(400).json({ // bad request\n ok: false,\n mensaje: 'error al actualizar el medico',\n error: err\n });\n }\n resp.status(200).json({ // OK\n update: true,\n medico: medicoUpdated\n });\n });\n\n });\n}", "async put(req, res) {\n try {\n await Iem.update(req.body, {\n where: { id: req.params.iemId }\n })\n res.send(req.body)\n } catch (err) {\n res.status(500).send({\n error: 'Error updating IEM info'\n })\n }\n }", "function putUpdate(data){\n $.ajax({\n url: location+'/'+$id,\n type: 'PUT',\n data: data,\n success: function(_data) {\n clearForm();\n updateTableUpdate(_data);\n }\n });\n }", "update(req, res) {\n SimuladoQuestao.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 }", "update(req, res) {\n RegistroEstudo.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 alterarBD(dados){\n var xhr = new XMLHttpRequest();\n xhr.open(\"PUT\", BASE_URL_SERVICO + \"/oportunidadeProblema\", false);\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(dados);\n}", "updateSaber(id, valores, res) {\n const sql = 'update LightSaber set ? where ID = ?';\n conexao.query(sql, [valores, id], (erro, resultados) => {\n if (erro) {\n res.status(400).json(erro);\n }\n else {\n res.status(200).json(resultados);\n }\n });\n }", "async update(request, response, next){\n try{\n const { name, email, whatsapp, city, uf } = request.body;\n const { id } = request.params;\n const contatoID = await connection('contatos').select('*').where({id: id});\n\n if(contatoID != \"\"){\n await connection('contatos')\n .update({ name, email, whatsapp, city, uf })\n .where({ id: id })\n\n return response.json({ \"Status\": \"Alterado com Sucesso!\" });\n }\n \n return response.status(400).json({ \"Status\": \"ID de Contato não encontrado!\" });\n }catch(error){\n next(error)\n }\n }", "function updateEsp(req, res) {\n // metodo put ...llega por body\n\n var update = req.body;\n var espId = req.params.id;\n //console.log('el id que llega ', espId);\n //console.log('lo que llega por el body : ', req.body);\n Esp.findById(espId, (err, espDB) => {\n\n if (err) {\n return res.status(500).json({ // internal server\n ok: false,\n message: 'error al buscar el modulo esp',\n error: err\n })\n }\n\n if (!espDB) {\n return res.status(400).json({ // bad request\n ok: false,\n mensaje: 'el modulo con el id' + espId + 'no existe',\n errors: {\n message: 'no existe un modulo con ese ID'\n }\n });\n }\n\n espDB.lugar = update.lugar;\n espDB.descripcion = update.descripcion;\n espDB.nombre = update.nombre;\n espDB.ssid = update.ssid;\n espDB.estado = update.estado;\n espDB.passwordRouter = update.passwordRouter;\n\n // actualizamos el usuario que lo esta modificando \n espDB.usuario = req.usuario_id;\n\n espDB.save((err, espUpdated) => {\n\n if (err) {\n return res.status(400).json({ // bad request\n ok: false,\n message: 'error al actualizar el modulo',\n error: err\n });\n }\n res.status(200).json({ // OK\n update: true,\n modulo: espUpdated,\n });\n });\n\n });\n}", "static updateCama(req, res) {\n const { descripcion, numeroCama } = req.body\n return Camas\n .findByPk(req.params.id)\n .then((data) => {\n data.update({\n descripcion: descripcion || data.descripcion,\n numeroCama: numeroCama || data.numeroCama \n })\n .then(update => {\n res.status(200).send({\n message: 'Sala actualizado',\n data: {\n \n descripcion: descripcion || update.descripcion,\n numeroCama: numeroCama || update.numeroCama\n }\n })\n })\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n }", "async update(req, res) {\r\n Consulta.updateOne({ _id: req.params.id }, req.body).then(() => {\r\n return res.json({\r\n error: false,\r\n message: \"Consulta editado com sucesso!\"\r\n })\r\n }).catch((err) => {\r\n console.log(err);\r\n return res.status(400).json({\r\n error: true,\r\n message: \"Erro ao editar consulta !\"\r\n })\r\n })\r\n }", "function update(){\n RomService.update({ _id: vm.rom._id }, vm.rom).then(function(data){\n console.log(data);\n console.log(vm.rom);\n },\n function(error){\n console.log(\"Ocorreu um Error: \"+ error);\n });\n }", "function actualizar(req, res, next) {\r\n let id = req.params.id;\r\n let data = {\r\n nombre: req.body.nombre\r\n }\r\n ModeloTema.findByIdAndUpdate(id, data, { new: true }, (err, item) => {\r\n if (err || !item) return errorHandler(err, next, item);\r\n res.json({\r\n result: true,\r\n data: item\r\n })\r\n });\r\n}", "function updateDataRest(jsonObj) {\n jsonObj.method = jsonObj.method || 'put';\n var url = getUrl(jsonObj.module, jsonObj.method);\n if (jsonObj.param) {\n url += jsonObj.param;\n }\n\n return requestHandle({\n method: \"put\",\n url: url,\n params: {\n action: \"edit\"\n },\n data: jsonObj.data,\n headers: getHeaders()\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ammend today's recorded uptime in the database and add 1 to it
function augmentDate(date, newUptime) { const connection = mysql.createConnection(database); connection.connect(); // Update uptime to new value for today's date in the uptime table connection.query(`UPDATE Uptime SET uptime = '${newUptime}' WHERE date = '${date}'`, (error, results) => { if (error) { log.error(error); } log.silly(`Updated database uptime for ${date}, results: ${JSON.stringify(results)}`); connection.end(); }); }
[ "function incrementUptime() {\n wifiuptime++;\n systemUptime++;\n}", "get uptime() {\n return new Date().getTime() - this._startTime.getTime();\n }", "uptime() {\n if (!this.startupDate) { return 0; }\n return new Date() - this.startupDate;\n }", "function uptime(value) {\n if((days = value / 86400) > 1)\n return Math.floor(days) + ' days';\n\n return Math.floor(value / 3600) + ' hours';\n}", "function updatecounter() {\n\t'use strict';\n\tlet now = new Date();\n\tvar mon = now.getMonth() + 1;\n\tvar year = now.getFullYear();\n\tlet offerDate = new Date(`${mon + 1} 1 ${year}`);\n\tlet dif = offerDate - now;\n\tlet day = Math.floor(dif / 1000 / 60 / 60 / 24);\n\tlet hour = Math.floor(dif / 1000 / 60 / 60) % 24;\n\tlet minutes = Math.floor(dif / 1000 / 60) % 60;\n\tlet seconds = Math.floor(dif / 1000) % 60;\n\t$('#day h2').text(() => (day < 10 ? '0' + day : day));\n\t$('#hour h2').text(hour < 10 ? '0' + hour : hour);\n\t$('#minutes h2').text(minutes < 10 ? '0' + minutes : minutes);\n\t$('#second h2').text(seconds < 10 ? '0' + seconds : seconds);\n}", "function udpateTime(){\n if(minutes + 1 === 60)\n setHours((hours + 1) % 24)\n setMinutes((minutes + 1) % 60)\n }", "get uptime() {\n if (this._state === exports.ClientState.ACTIVE\n && this._currentConnectionStartTime) {\n return Date.now() - this._currentConnectionStartTime;\n }\n else {\n return 0;\n }\n }", "function uptimeProcess() {\n var s = process.uptime()\n var date = new Date(null);\n date.setSeconds(s);\n var uptime_bot = date.toISOString().substr(11, 8);\n return uptime_bot\n}", "function incrementBonusTime(){\n\n if (+extraTime.seconds === 59){\n extraTime.seconds = 0\n extraTime.minutes++\n\n if (+extraTime.minutes === 59){\n extraTime.minutes = 0\n extraTime.hours++\n }\n\n } else {\n extraTime.seconds++\n }\n updateExtraTimeClock()\n}", "function uptime_macro() {\n return formatAge((java.lang.System.currentTimeMillis() - this.starttime) / 1000);\n}", "function attendanceIncrement() {\n setTimeout(function() {\n $('.live_attendee.active').each(function() {\n minutes = parseInt($(this).find('td:nth-child(3)').text());\n $(this).find('td:nth-child(3)').text(minutes + 1);\n });\n\n attendanceIncrement();\n }, 60000);\n}", "function updateUptime() {\n // Calculates the total seconds online to something readable\n var hour, min, sec;\n\n day = Math.floor(uptime / (60 * 60 * 24));\n hour = Math.floor(uptime / (60 * 60) - day * 24);\n min = Math.floor(uptime / 60) - hour * 60;\n sec = uptime - hour * 60 * 60 - min * 60;\n\n var string = day + \"d \" + hour + \"h \" + min + \"m \" + sec + \"s\";\n\n $scope.serverUptime = string;\n $scope.$apply();\n }", "uptime() {\n if (!this.connectedDate) {\n return null;\n }\n const now = new Date();\n return (now - this.connectedDate) / 1000;\n }", "function sleepingTime() {\n axios.post('/api/sleep/thisDay', {\n userId: localStorage.getItem('userId'),\n shortDate: `${new Date().getFullYear()}-${getMonth()}-${newDate}`\n })\n .then(res => {\n setSleepingDurationMilliseconds(res.data.map(item => item.sleepingDuration).reduce((a, b) => a + b))\n setSleepingDurationTotal(millisecToHours(res.data.map(item => item.sleepingDuration).reduce((a, b) => a + b)))\n })\n .catch(err => console.log(err))\n }", "calcUptime() {\n lumServer.healthcheck.serverUptime = utils.milliSecsToString(utils.now());\n }", "function DBIncreaseNumberOfFalseParkings(user){\t\n\tvar user_id;\n\tuser_id\t= user.id;\n\t//default\n\t if (user_id === undefined) {\n user_id = 1;\n } \n\t//update user score\n\tconnection.query('UPDATE users SET number_of_false_parkings_for_today = number_of_false_parkings_for_today + 1 WHERE user_id = \"' +user_id+ '\"', function(err, rows, fields) {\n\t\tif (!err) {\n\t\t\tuser.NumberOfFalseParkingForToday += 1; //update user's score\n\t\t\tconsole.log('Number of false parking for today of user ' +user_id+ ' increased by 1.');\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Error while performing Query 17. ', err); \n\t\t}\n\t});\t\n}", "async function dailyIncrement () {\n\tconst now = new Date();\n\n\tlet nowDay = now.getDate();\n\tlet nowMonth = now.getMonth();\n\tlet nowYear = now.getFullYear();\n\n\tlet results = await Habit.find();\n\tfor (habit of results) {\n\t\tlet canonizedDate = canonizeDate(habit['startDate']);\n\t\tlet configuredDate = calculateDaysSinceStart(canonizedDate);\n\n\t\tlet updatedAtDay = habit['updatedAt'].getDate();\n\t\tlet updatedAtMonth = habit['updatedAt'].getMonth();\n\t\tlet updatedAtYear = habit['updatedAt'].getFullYear();\n\n\t\tif (\n\t\t\tnowDay > updatedAtDay ||\n\t\t\tnowMonth > updatedAtMonth ||\n\t\t\tnowYear > updatedAtYear\n\t\t) {\n\t\t\tawait Habit.updateOne(\n\t\t\t\t{ name: habit['name'] },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tdaysSinceStart: configuredDate,\n\t\t\t\t\t\tcheckedInToday: false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t}\n}", "function onlineTime() {\n\tUSERONLINE++;\n\tvar h = Math.floor(USERONLINE/60);\n\tvar m = USERONLINE-h*60;\n\tm<10 ? m=\"0\"+m : '';\n\tonlinetime.html(h+\":\"+m);\n}", "function incTimes() {\n\t\n\tvar privateBrowsing = require(\"private-browsing\");\n var now = new Date();\n var month = now.getMonth() + 1;\n var day = now.getDate();\n var year = now.getFullYear();\n var date = day.toString() + \".\"\n\t+ month.toString() + \".\" \n\t+ year;\n\n var domain = getDomainName(currentTab);\n if(domain && privateBrowsing.isActive == false) {\n\tif(!store[date]) {\n\t store[date] = {}\n\t}\n\tif(!store[date][domain]) {\n\t store[date][domain] = 0;\n\t}\n\t\n\tstore[date][domain]++;\n }\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a ValueExpression pointing to the MetadataTreeNode that corresponds to the currently displayed/selected comment. This helps to cope with the asynchronous nature of page loading in the PreviewPanel. As soon as the ValueExpression returns something different than 'undefined' it is possible to highlight the comment in the PreviewPanel.
function getMetadataNodeForDisplayedCommentVE()/*:ValueExpression*/ {var this$=this; if (!this.metadataNodeForDisplayedCommentVE$Im7w) { this.metadataNodeForDisplayedCommentVE$Im7w = com.coremedia.ui.data.ValueExpressionFactory.createFromFunction(function ()/*:MetadataTreeNode*/ { var comment/*:Comment*/ =AS3.as( this$.displayedContributionVE$Im7w.getValue(), com.coremedia.elastic.social.studio.model.Comment); if (comment) { var metadataTreeRoot/*:MetadataTreeNode*/ = this$.getMetadataService().getMetadataTree().getRoot(); if (metadataTreeRoot) { return metadataTreeRoot.findChildrenBy(function (node/*:MetadataTreeNode*/)/*:Boolean*/ { return node.getProperty(com.coremedia.cms.editor.sdk.preview.MetadataHelper.METADATA_DEFAULT_PROPERTY) === comment; })[0]; } } return undefined; }); } return this.metadataNodeForDisplayedCommentVE$Im7w; }
[ "function nodecommentnodevalue() {\n var success;\n if(checkInitialization(builder, \"nodecommentnodevalue\") != null) return;\n var doc;\n var elementList;\n var commentNode;\n var commentName;\n var commentValue;\n \n var docRef = null;\n if (typeof(this.doc) != 'undefined') {\n docRef = this.doc;\n }\n doc = load(docRef, \"doc\", \"staff\");\n elementList = doc.childNodes;\n\n for(var indexN10040 = 0;indexN10040 < elementList.length; indexN10040++) {\n commentNode = elementList.item(indexN10040);\n commentName = commentNode.nodeName;\n\n \n\tif(\n\t(\"#comment\" == commentName)\n\t) {\n\tcommentValue = commentNode.nodeValue;\n\n assertEquals(\"value\",\" This is comment number 1.\",commentValue);\n \n\t}\n\t\n\t}\n \n}", "function getCommentText() {\n return commentField.value;\n }", "getExpression() {\n return this.value;\n }", "getSelectedComments() {\n\t\treturn this.objectModel.getSelectedComments();\n\t}", "function GetComment(value) {\n if (IsRdfSchema(value.Predicate) && value.Predicate.name === 'comment') {\n if (value.Object.type === 'SchemaString') {\n return { comment: value.Object.value };\n }\n throw new Error(`Unexpected Comment predicate with non-string object: ${value}.`);\n }\n return null;\n}", "@computed get getCommentObject() {\n return this.commentObject;\n }", "get selectedNode()\n {\n if (this.mDOMTree.view.selection.count == 1) {\n var minAndMax = {};\n this.mDOMTree.view.selection.getRangeAt(0, minAndMax, minAndMax);\n return this.getNodeFromRowIndex(minAndMax.value);\n }\n return null;\n }", "getComment(parent, args, content, ast) {\n const feathersParams = convertArgs(args, content, ast);\n return comments.get(args.key, feathersParams).then(extractFirstItem);\n }", "function evaluateComment(comment, colorOnly) {\n var commentBody = getCommentBody(comment);\n var commentText = getCommentText(comment);\n var read = isCommentSeen(comment);\n var guest = isCommentGuest(comment);\n var visible = isCommentVisible(comment);\n\n if(colorOnly === undefined)\n colorOnly = false;\n\n var postType;\n if(guest)\n postType = 'guest ';\n else\n postType = 'member ';\n if(read)\n postType += 'read';\n else\n postType += 'unread';\n\n /* First, make sure the post width is corrected if needed. */\n var preformattedVersion = xpath('div[@class=\"FormattedComment\"]/pre', false, commentText);\n if(preformattedVersion != null) {\n /* makeDynamic ensures that all pre-formatted comments have sister versions that\n * are unformatted.\n */\n var unformattedVersion = xpath('div[@class=\"UnformattedVersion\"]', false, preformattedVersion.parentNode);\n if(unformattedVersion != null) {\n if(switches['fix width']) {\n preformattedVersion.style.display = 'none';\n unformattedVersion.style.display = null;\n }\n else {\n unformattedVersion.style.display = 'none';\n preformattedVersion.style.display = null;\n }\n }\n }\n\n /* Next, set the proper color. */\n var color = colors[postType];\n getCommentTitle(comment).style.background = color;\n comment.style.borderColor = color;\n if(switches['full hilight'])\n commentBody.style.background = color;\n else\n commentBody.style.background = null;\n\n if(colorOnly)\n return;\n\n if((switches['hide guest'] && guest) || (switches['hide read'] && read)) {\n /* The comment should be hidden. */\n var hideButton = xpath('*//input[@value=\"Hide\"]', false, comment);\n if(hideButton)\n /* Make a visible comment hidden. */\n click(hideButton);\n }\n else {\n /* The comment should be visible. */\n var viewButton = xpath('*//input[@value=\"View\"]', false, comment);\n if(viewButton)\n /* Make a hidden comment visible. */\n click(viewButton);\n }\n}", "_getCommentTransform(data) {\n\t\tlet sData = this.sMemento(data);\n\t\treturn (sData.contains('edge_media_to_comment') ? this.topCommentsTransform : this.pagedCommentsTransform);\n\t}", "function previewComment() {\r\n cccp_comment_dom.innerHTML = cccp_comment.value;\r\n mungeComment();\r\n comment.value = cccp_comment_dom.innerHTML;\r\n acp_preview.click();\r\n}", "function getComment(comments, loc) {\n let matchingComment;\n const targetLineEnd = loc.end.line;\n for (const comment of comments) {\n const commentEnd = comment.loc.end.line;\n if (commentEnd === targetLineEnd - 1) {\n return comment.value;\n }\n }\n return matchingComment;\n }", "getExpression() {\r\n return this._getNodeFromCompilerNodeIfExists(this.compilerNode.expression);\r\n }", "function rtvCommentField()\n{\n\tvar commentFrame = getCommentFrame();\n\tif( commentFrame != null)\n\t{\n\t\t// retrieve the comment field element\n\t\tvar obj = commentFrame.document.getElementById('commentField');\n\t\tif (obj != null)\n\t\t{\n\t\t\treturn obj.value.trim();\n\t\t}\n\t}\n\treturn '';\n}", "function getValueOfContext(context){\n var editorContent = editor.getValue();\n\t\n\tcontext.definition.lastIndex = 0;\n var relevantPart = context.definition.exec(editorContent);\n \n if(relevantPart.length > 1){\n\t return relevantPart[1];\n }\n return \"\";\n}", "function createCommentTagEvaluator(contentLiteral) {\n generate.statement(function () {\n generate.call(generate.writer('comment'), [defer(contentLiteral)]);\n });\n }", "function Comment(value) {\n return function (target, propertyName) {\n models_1.addAttributeOptions(target, propertyName, {\n comment: value\n });\n };\n}", "function getValueOfContext(context) {\n\tvar editorContent = editor.getValue();\n\n\tcontext.definition.lastIndex = 0;\n\tvar relevantPart = context.definition.exec(editorContent);\n\n\tif (relevantPart.length > 1) {\n\t\treturn relevantPart[1];\n\t}\n\treturn \"\";\n}", "function mst_loadValue(t) {\n if (!t) t = thread_id;\n var comment = mst_getValue(t);\n\n // Find the anchor\n var anchors = document.getElementsByTagName('a');\n for (var i=0; i<anchors.length; ++i) {\n if (comment && anchors[i].name == comment.id) {\n // Find the comment div after the anchor\n var a = anchors[i];\n while (a && (!a.className || !a.className.match(/comments/) &&\n a.id != 'prevDiv' && a.id != 'prevDiv2')) {\n a = a.nextSibling;\n }\n\n if (a) {\n markedcomment = a;\n mst_mark(a);\n }\n\n break;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We check the failure patterns one by one, to see if any of those appeared on the errors. If they did, we return the associated error
findAnyFailurePattern(patterns) { const errorsAndOutput = this.errors + this.output; const patternThatAppeared = patterns.find(pattern => { return pattern.pattern instanceof RegExp ? pattern.pattern.test(errorsAndOutput) : errorsAndOutput.indexOf(pattern.pattern) !== -1; }); return patternThatAppeared ? patternThatAppeared.errorCode : null; }
[ "find (api, error) {\n for (let knownError of knownErrors.all) {\n if (typeof knownError.api === \"string\" && !api.name.includes(knownError.api)) {\n continue;\n }\n\n if (typeof knownError.error === \"string\" && !error.message.includes(knownError.error)) {\n continue;\n }\n\n if (knownError.error instanceof RegExp && !knownError.error.test(error.message)) {\n continue;\n }\n\n return knownError;\n }\n }", "get patternError() {\n return (\n this.pattern &&\n this.pattern !== \"\" &&\n this._getFieldValue() &&\n (!this.field.multiple\n ? !this._getFieldValue().match(this.pattern)\n : this._getFieldValue().filter((value) => !value.match(this.pattern)))\n );\n }", "static getErrorMessage(results) {\n let errorMessage = \"\";\n\n results.forEach(result => {\n // Not adding to the error message for valid results.\n if (result.valid) {\n return;\n }\n\n // This adds validation-method-specific messages to the overall message.\n switch (result.validationCode) {\n\n case VALIDATION_CODES.VALIDATE_TYPE:\n {\n let dataName = result.localName || \"Some data\";\n let messageBody = `${dataName} is an invalid data type (${result.received}). `;\n let errorPart = `It should be a(n) ${result.expected}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_TYPES:\n {\n let invalidFields = result.invalidFields;\n let invalidKeys = Object.keys(invalidFields);\n\n invalidKeys.forEach(key => {\n let field = invalidFields[key];\n // Try and get a local name, but make sure one has actually been given.\n let fieldName = result.localNames ? result.localNames[key] || `\"${key}\"` : `\"${key}\"`;\n let messageBody = `The ${fieldName} field is an invalid data type (${field.received}). `;\n let errorPart = `It should be ${field.expected}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n });\n\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_LENGTH:\n {\n let dataName = result.localName || \"Some data\";\n let messageBody = `${dataName} has an invalid number of characters (${result.received}). `;\n let errorPart = `It should be greater than ${result.expected[0]}, and less than ${result.expected[1]}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_LENGTHS:\n {\n let invalidFields = result.invalidFields;\n let invalidKeys = Object.keys(invalidFields);\n\n invalidKeys.forEach(key => {\n let field = invalidFields[key];\n let fieldName = result.localNames ? result.localNames[key] || `\"${key}\"` : `\"${key}\"`;\n let messageBody = `The ${fieldName} field has an invalid number of characters (${field.received}). `;\n let errorPart = `It should be greater than ${field.expected[0]}, and less than ${field.expected[1]}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n });\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_ARRAY_TYPES:\n {\n let invalidFields = result.invalidFields;\n let invalidKeys = Object.keys(invalidFields);\n let dataName = result.localName || \"field\";\n\n invalidKeys.forEach(key => {\n let field = invalidFields[key];\n let fieldName = `\"${key}\"`; // There are no local names per key here.\n let messageBody = `The ${dataName}, ${fieldName}, is an invalid data type (${field.received}). `;\n let errorPart = `It should be a(n) ${field.expected}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n });\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_ARRAY_LENGTHS:\n {\n let invalidFields = result.invalidFields;\n let invalidKeys = Object.keys(invalidFields);\n let dataName = result.localName || \"field\";\n\n invalidKeys.forEach(key => {\n let field = invalidFields[key];\n let fieldName = `\"${key}\"`;\n let messageBody = `The ${dataName}, ${fieldName}, has an invalid number of characters (${field.received}). `;\n let errorPart = `It should be greater than ${field.expected[0]}, and less than ${field.expected[1]}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n });\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_NUMBER_SIZE:\n {\n let dataName = result.localName || \"Some data\";\n let messageBody = `${dataName} has an invalid size (${result.received}). `;\n let errorPart = `It should be greater than ${result.expected[0]}, and less than ${result.expected[1]}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n break;\n }\n\n case VALIDATION_CODES.VALIDATE_KEY_COUNT:\n {\n let dataName = result.localName || \"Some data\";\n let messageBody = `${dataName} has an invalid number of fields (${result.received}). `;\n let errorPart = `It should be equal to ${result.expected}.`;\n\n errorMessage += messageBody + errorPart + \"\\n\";\n break;\n }\n\n default:\n {\n errorMessage += \"Failed to generate partial error message, check console.\\n\";\n console.log(\"Failed partial error message:\");\n console.log(result);\n }\n\n }\n\n });\n\n return errorMessage;\n }", "function failures(cause) {\n return reduceLeft([])((a, c) => c._tag === \"Fail\" ? O.some([...a, c.value]) : O.none)(cause);\n}", "function rgErrorMsgForDisplay(msg) {\n const lines = msg.split('\\n');\n const firstLine = lines[0].trim();\n if (lines.some(l => strings_1.startsWith(l, 'regex parse error'))) {\n return new search_1.SearchError(buildRegexParseError(lines), search_1.SearchErrorCode.regexParseError);\n }\n const match = firstLine.match(/grep config error: unknown encoding: (.*)/);\n if (match) {\n return new search_1.SearchError(`Unknown encoding: ${match[1]}`, search_1.SearchErrorCode.unknownEncoding);\n }\n if (strings_1.startsWith(firstLine, 'error parsing glob')) {\n // Uppercase first letter\n return new search_1.SearchError(firstLine.charAt(0).toUpperCase() + firstLine.substr(1), search_1.SearchErrorCode.globParseError);\n }\n if (strings_1.startsWith(firstLine, 'the literal')) {\n // Uppercase first letter\n return new search_1.SearchError(firstLine.charAt(0).toUpperCase() + firstLine.substr(1), search_1.SearchErrorCode.invalidLiteral);\n }\n if (strings_1.startsWith(firstLine, 'PCRE2: error compiling pattern')) {\n return new search_1.SearchError(firstLine, search_1.SearchErrorCode.regexParseError);\n }\n return undefined;\n }", "function findCardError() {\n var foundError = false;\n var i = 0;\n while (!foundError && i < cards.length) {\n for (var j = 0; j < cards.length; j++) {\n // don't compare to itself\n if (i != j) {\n // only cards with 3 monsters should be compared\n if (cards[i].images.size == 3 && cards[j].images.size == 3) {\n var matches = 0;\n cards[j].images.forEach(function(image) {\n if (cards[i].images.has(image)) {\n matches++;\n }\n });\n if (matches != 1) {\n foundError = true;\n cards[i].valid = false;\n cards[j].valid = false;\n var text = \"Oh no! \";\n if (matches == 0) {\n text = \"Oops! These two cards don't have a match.\";\n } else {\n text = \"Oh no! Cards can only match ONE monster.\";\n }\n colorErrors(i, j, text);\n } else {\n cards[i].valid = true;\n cards[j].valid = true;\n }\n }\n }\n }\n i++;\n }\n if (!foundError) {\n colorCards();\n }\n}", "function verifyErros(){\r\n let foudError = false\r\n\r\n for(let error in field.validity){\r\n // se não for customErro\r\n // então verifica se é verdadeira\r\n // Caso seja possui um erro\r\n if(error != \"customError\" && field.validity[error]){\r\n foundError = error\r\n }\r\n }\r\n return foundError\r\n }", "checkForNextError() {\n if (!isNullOrUndefined(this.viewer)) {\n let errorWords = this.errorWordCollection;\n if (errorWords.length > 0) {\n for (let i = 0; i < errorWords.length; i++) {\n let errorElements = errorWords.get(errorWords.keys[i]);\n for (let j = 0; j < errorElements.length; j++) {\n if (errorElements[j] instanceof ErrorTextElementBox && !errorElements[j].ischangeDetected) {\n this.updateErrorElementTextBox(errorWords.keys[i], errorElements[j]);\n }\n else if (errorElements[j] instanceof TextElementBox) {\n let matchResults = this.getMatchedResultsFromElement(errorElements[j]);\n let results = matchResults.textResults;\n // tslint:disable-next-line:max-line-length\n let markIndex = (errorElements[j].ischangeDetected) ? errorElements[j].start.offset : errorElements[j].line.getOffset(errorElements[j], 0);\n // tslint:disable-next-line:max-line-length\n this.viewer.owner.searchModule.textSearch.updateMatchedTextLocation(matchResults.matches, results, matchResults.elementInfo, 0, errorElements[j], false, null, markIndex);\n for (let i = 0; i < results.length; i++) {\n let element = this.createErrorElementWithInfo(results.innerList[i], errorElements[j]);\n this.updateErrorElementTextBox(element.text, element);\n break;\n }\n }\n break;\n }\n break;\n }\n }\n else {\n this.viewer.clearSelectionHighlight();\n }\n }\n }", "_hasRealErrors(resultFile) {\n const results = JSON.parse(fs.readFileSync(resultFile))\n return results.files.some(file =>\n file.scan_errors.some(error => {\n return !(\n error.includes('ERROR: Processing interrupted: timeout after') ||\n error.includes('ValueError:') ||\n error.includes('package.json')\n )\n })\n )\n }", "function checkErrors() {\n\t\t\tvar i, errorFree = true;\n\n\t\t\tfor (i = 0; i < scope.config.input.length; i++) {\n\t\t\t\t// if we haven't found any errors, such to make sure we are still error free\n\t\t\t\tif (errorFree) {\n\t\t\t\t\terrorFree =\tcheckInputRequirements(scope.config.input[i]);\n\t\t\t\t}\n\t\t\t\t// if we've already found an error, just keep checking for errors so view shows correctly\n\t\t\t\telse {\n\t\t\t\t\tcheckInputRequirements(scope.config.input[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn errorFree;\n\t\t}", "function locateNearestErrorRecoveryRule(state) {\n var stack_probe = s.stack.length - 1;\n var depth = 0;\n\n // try to recover from error\n for(;;) {\n // check for error recovery rule in this state\n if ((TERROR.toString()) in table[state]) {\n return depth;\n }\n if (state === 0 || stack_probe < 2) {\n return false; // No suitable error recovery rule available.\n }\n stack_probe -= 2; // popStack(1): [symbol, action]\n state = s.stack[stack_probe];\n ++depth;\n }\n }", "runsHadError() {\n return this.errors.includes(false);\n }", "function locateNearestErrorRecoveryRule(state) {\n var stack_probe = stack.length - 1;\n var depth = 0;\n\n // try to recover from error\n for(;;) {\n // check for error recovery rule in this state\n if ((TERROR.toString()) in table[state]) {\n return depth;\n }\n if (state === 0 || stack_probe < 2) {\n return false; // No suitable error recovery rule available.\n }\n stack_probe -= 2; // popStack(1): [symbol, action]\n state = stack[stack_probe];\n ++depth;\n }\n }", "errors () {\n let errorList = this.errorList.slice(0)\n\n let errors = {\n all: errorList.map(e => e.message),\n first: errorList.length > 0 ? errorList[0].message : null\n }\n\n return errors\n }", "function locateNearestErrorRecoveryRule(state) {\n var stack_probe = stack.length - 1;\n var depth = 0;\n\n // try to recover from error\n for(;;) {\n // check for error recovery rule in this state\n if ((TERROR.toString()) in table[state]) {\n return depth;\n }\n if (state === 0 || stack_probe < 2) {\n return false; // No suitable error recovery rule available.\n }\n stack_probe -= 2; // popStack(1): [symbol, action]\n state = stack[stack_probe];\n ++depth;\n }\n }", "function findKnownApiError (api, error) {\n for (var i = 0; i < knownApiErrors.length; i++) {\n var knownError = knownApiErrors[i];\n\n if (typeof knownError.api === \"string\" && api.name.indexOf(knownError.api) === -1) {\n continue;\n }\n\n if (typeof knownError.error === \"string\" && error.message.indexOf(knownError.error) === -1) {\n continue;\n }\n\n if (knownError.error instanceof RegExp && !knownError.error.test(error.message)) {\n continue;\n }\n\n return true;\n }\n }", "hasMatch(_errorResponse) {\r\n return true;\r\n }", "function isError() {\n for (var i = 0; i < results.length; i++) {\n if (results[i] === false) return i;\n }\n\n return -1;\n }", "static parseError(stderr) {\n for (const regex in errors_1.GitErrorRegexes) {\n if (stderr.match(regex)) {\n const error = errors_1.GitErrorRegexes[regex];\n return error;\n }\n }\n return null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end change Movie fullscreen mode
function toggleFullScreen() { if (!document.mozFullScreen && !document.webkitFullScreen) { if (video.mozRequestFullScreen) { video.mozRequestFullScreen(); } else { video.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else { document.webkitCancelFullScreen(); } } }
[ "function fullscreen(mode) {\n\tif(mode) {\n\t\tfullscreen_start();\n\t} else {\n\t\tfullscreen_end();\n\t}\n}", "static set macFullscreenMode(value) {}", "onFullScreen() {\n ViewPresActions.fullscreen(true);\n }", "static set defaultIsFullScreen(value) {}", "function makeItFullScreen()\n {\n if (lbVideo.requestFullScreen) {\n lbVideo.requestFullScreen();\n } else if(lbVideo.webkitRequestFullScreen) {\n lbVideo.webkitRequestFullScreen();\n } else if(lbVideo.mozRequestFullScreen) {\n lbVideo.mozRequestFullScreen();\n }\n }", "static set d3d9FullscreenMode(value) {}", "static set d3d11FullscreenMode(value) {}", "function toggle_fullscreen(){\n let fs = fullscreen();\n fullscreen(!fs);\n if(fs == undefined){\n resizeCanvas(displayWidth, displayHeight);\n }else{\n resizeCanvas(original_width, original_height);\n }\n\n background(BACKGROUND_COLOR);\n}", "static set allowFullscreenSwitch(value) {}", "function fullscreen() {\n // NOTE: the Element.requestFullscreen() method issues an asynchronous request to make the element be displayed in full-screen mode.\n video.requestFullscreen();\n}", "function ScreenFull() {\n\nif (key === 'f') {\nenterFullscreen();\n }\n}", "toggleFullScreenEdit() {\n var isFS = document.body.classList.contains(\n this.FULLSCREEN_MODE_CLASS\n );\n\n if (document.webkitIsFullScreen) {\n document.webkitExitFullscreen();\n }\n\n document.body.classList[isFS ? 'remove' : 'add'](\n this.FULLSCREEN_MODE_CLASS\n );\n this.decreaseRes(this.currentDivider);\n }", "function mytoggleFullScreen(){\n\t\tif(full_screen==true){\n\t\t\t$(\"#full_screen_bt\").html(\"fullscreen_exit\");\n\t\t\tfull_screen=false;\n\t\t}\n\t\telse{\n\t\t\t$(\"#full_screen_bt\").html(\"fullscreen\");\n\t\t\tfull_screen=true;\n\t\t}\n\t}", "onFullScreenChanged () {}", "function videoFullScreen(e) {\n if (document.fullscreenEnabled || document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement) {\n $('.popup__bg, .bda-main-nav span, .bda-pagination, .toogle-menu, .creative-commons, .bda-guide').css('z-index', '-1')\n console.log(\"Entra a fullscreen\")\n } else {\n $('.popup__bg').css('z-index', '2')\n $('.bda-main-nav span, .bda-pagination, .toogle-menu, .bda-guide').css('z-index', '1')\n $('.creative-commons').css('z-index', '')\n console.log(\"Sale de fullscreen\")\n }\n }", "function onFullScreenExit() {\n fullScreen = false;\n}", "toggleFullScreenEdit() {\n var isFS = document.body.classList.contains(this.FULLSCREEN_MODE_CLASS);\n\n if (document.webkitIsFullScreen) {\n document.webkitExitFullscreen();\n }\n\n document.body.classList[isFS ? 'remove' : 'add'](this.FULLSCREEN_MODE_CLASS);\n this.decreaseRes(this.currentDivider);\n }", "function fullScreen() {\n /*\n if (divSimula.requestFullscreen) {\n divSimula.requestFullscreen();\n } else if (divSimula.webkitRequestFullscreen) {\n divSimula.webkitRequestFullscreen();\n } else if (divSimula.mozRequestFullScreen) {\n divSimula.mozRequestFullScreen();\n } else if (divSimula.msRequestFullscreen) {\n divSimula.msRequestFullscreen();\n }\n //*/\n }", "function fullscreenButton(video){\r\n video.webkitRequestFullscreen();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduce the size of samples by a factor of N by decreasing the sample rate. The output contains a single (average) sample for every N consecutive samples of input.
function compress(N, samples) { var outSize = Math.floor(samples.length / N); var out = new Float64Array(outSize); var rp = 0, wp = 0; while (wp < outSize) { var total = 0; for (var j = 0; j < N; j++) { total += samples[rp++]; } out[wp++] = total / N; } return out; }
[ "function downsampled(n, factor) {\n var result = [];\n var v = (factor+1) / 2;\n for (var i=0; i<n; i++) {\n result.push(v);\n v += factor;\n }\n return result;\n }", "function mvgmn(in_a,n){\n var out_a = []\n for(j=in_a.length;j>0;j--){\n var slice_start = j-n\n if(slice_start < 0)\n slice_start = 0\n var myslice=in_a.slice(slice_start,j)\n out_a.push(d3.mean(myslice))\n }\n out_a.length == in_a.length //should be true\n return out_a.reverse()\n}", "function decimateByN(array, n = 2) {\n\n let decimatedArray = [];\n\n for (let i=0; i < array.length/n; i++) {\n decimatedArray.push(array[n*i])\n }\n\n return decimatedArray;\n\n}", "function sample_mean_distribution(fullDistribution, sampleSize) {\n var sample_mean = []\n var i = 0\n while (sample_mean.length < maxMeanIterations) {\n sample_mean.push(d3.mean(fullDistribution.slice(i,i+sampleSize)))\n i += maxSampleSize\n }\n return sample_mean\n }", "function moving_average(array, n) {\n var nums = [];\n\n for (i in array) {\n /* If this item in the array is a number */\n if (_.isNumber(array[i])) {\n nums.push(array[i]);\n if (nums.length > n) {\n\tnums.splice(0,1); /* Remove the first element of the array */\n }\n /* Take the average of the n items in this array */\n var sum = _.reduce(nums, function(memo, num){ return memo + num; }, 0);\n array[i] = sum/nums.length;\n }\n }\n\n return array;\n}", "function sample_size() {\n return 5000\n}", "function runningAverage() {\n let arr = [];\n return function(n) {\n arr.push(n);\n let avg = (arr.reduce((a,b) => a + b)/arr.length);\n return (String(avg % 1).length > 3) ? Math.round(avg*100)/100 : avg;\n }\n}", "function resampleInnerLoop(inp, out, outLength, last, inToOutRatio, delta, scale) {\n var prefixLength = Math.min((Math.floor(((((0.5) * inToOutRatio) - delta) / inToOutRatio) - 0.5) + 1), outLength);\n var next = inp[0];\n for (var i = 0|0; i < prefixLength|0; i++) {\n var point = +((i + 0.5) * inToOutRatio) + delta;\n var offset = +(1 + point) % 1;\n out[i] = +(((last * (1 - offset))) + (next * offset)) * scale;\n }\n for (; i < outLength|0; i++) {\n var point = +((i + 0.5) * inToOutRatio) + delta;\n var offset = +point % 1;\n var index = ~~Math.floor(point)|0;\n out[i] = +(((inp[index] * (1 - offset))) + (inp[index + 1] * offset)) * scale;\n }\n}", "function moving_average(data, n) {\n\tlet avg=[data[0]]\t\n\tfor(var i = 2; i <= data.length; i++) {\n\t\tif(i < n) {\n\t\t\tavg.push(simple_average(data.slice(0, i)))\n\t\t} else {\n\t\t\tavg.push(simple_average(data.slice(i-n, i)))\n\t\t}\n\t}\n\treturn avg\n}", "function resample(inp, out, inLength, outLength, context) {\n inLength = inLength|0;\n outLength = outLength|0;\n\n var inToOutRatio = +context.inRate / context.outRate;\n var scale = +context.scale;\n var last = +context.last || 0.0;\n\n // Delta is the offset inherited from the last run so that this run concatenates\n // seamlessly with it. It is initialized to 0.5 to offset from the midpoint of the\n // sample to the lower boundary. Setting it here hoists a common \"-0.5\" operation\n // from the loop.\n var delta = +context.delta != undefined ? context.delta : -0.5;\n\n // Call the inner loop with type coercion, for the optimizer.\n resampleInnerLoop(inp, out, outLength|0, +last, +inToOutRatio, +delta, +scale);\n\n var point = +((outLength + 0.5) * inToOutRatio) + delta;\n var index = ~~Math.floor(point)|0;\n context.last = index < 0 ? last : inp[index];\n context.delta = ((Math.abs(point) % 1) - 1) - (0.5 * inToOutRatio);\n return out;\n}", "simpleMovingAverage(prices, window = 5, n = Infinity) {\n if (!prices || prices.length < window) {\n return []\n }\n\n let index = window - 1\n const length = prices.length + 1\n\n const simpleMovingAverages = []\n\n let numberOfSMAsCalculated = 0\n\n while (++index < length && numberOfSMAsCalculated++ < n) {\n const windowSlice = prices.slice(index - window, index)\n const sum = windowSlice.reduce((prev, curr) => prev + curr, 0)\n simpleMovingAverages.push(sum / window)\n }\n\n return simpleMovingAverages\n }", "average() {\n return this.buffer.reduce((accum, current) => accum + current) / this.size;\n }", "function discretize_from(wave, duration, elapsed_duration, sample_length, data) {\n if (elapsed_duration + sample_length > duration) {\n for (var i = elapsed_duration * FS; i < duration * FS; i++) {\n data[i - elapsed_duration * FS] = wave(i / FS);\n }\n return data;\n } else if (duration - elapsed_duration > 0) {\n for (var i = elapsed_duration * FS;\n\t i < (elapsed_duration + sample_length) * FS;\n\t i++) {\n data[i - elapsed_duration * FS] = wave(i / FS);\n }\n return data;\n }\n}", "averageBps() {\n if (this.samples.length === 0) {\n return 0;\n }\n if (this.doneTime) {\n const elapsedSeconds = (this.doneTime - this.startTime) / 1000;\n return (8 * this.samples[this.samples.length - 1]) / elapsedSeconds;\n }\n const elapsedSeconds = (this.samples.length * this.pollFrequencyMs) / 1000;\n return (8 * (this.samples[this.samples.length - 1] - this.samples[0])) / elapsedSeconds;\n }", "function meanOfArray(arr){\n let numToRemove = Math.floor(arr.length / 100 * 5)\n arr.sort((a, b) => a - b)\n\n for (let i = 0; i < numToRemove; i++){\n arr.shift()\n arr.pop()\n }\n\n const sum = arr.reduce((sum, num) => sum + num)\n return sum / arr.length\n}", "function sample(array, max) {\n if (max <= 0) return [];\n if (max >= array.length) return array;\n\n let result = [];\n for (let n = 0; n < max - 1; n++) {\n let i = Math.round(n / max * array.length);\n result.push(array[i]);\n }\n\n // Always include last result.\n result.push(array[array.length - 1]);\n\n return result;\n}", "function avgNewReading(dist) {\n var r = 0;\n avgBuffer[aIndex] = dist;\n aIndex = (aIndex + 1) % maSize;\n for (var i = 0; i < maSize; i++) {\n r += avgBuffer[i];\n }\n return r / maSize;\n}", "average(){\n return this.buffer.reduce((accum, current) => accum + current) / this.size;\n }", "function averageLength(arr) {\n const avg = Math.round(arr.map(i => i.length).reduce((a, b) => a + b) / arr.length);\n return arr.map(i => i[0].repeat(avg));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print lab open page
function printPageLabOpen(lab) { if ( $.cookie("topo") == undefined ) $.cookie("topo", 'light'); var html = '<div id="lab-sidebar"><ul></ul></div><div id="lab-viewport" data-path="' + lab + '"></div>'; $('#body').html(html); // Print topology $.when(printLabTopology(),getPictures()).done( function (rc,pic) { if ((ROLE == 'admin' || ROLE == 'editor') && LOCK == 0 ) { $('#lab-sidebar ul').append('<li class="action-labobjectadd-li"><a class="action-labobjectadd" href="javascript:void(0)" title="' + MESSAGES[56] + '"><i class="glyphicon glyphicon-plus"></i></a></li>'); } $('#lab-sidebar ul').append('<li class="action-nodesget-li"><a class="action-nodesget" href="javascript:void(0)" title="' + MESSAGES[62] + '"><i class="glyphicon glyphicon-hdd"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-networksget" href="javascript:void(0)" title="' + MESSAGES[61] + '"><i class="glyphicon glyphicon-transfer"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-configsget" href="javascript:void(0)" title="' + MESSAGES[58] + '"><i class="glyphicon glyphicon-align-left"></i></a></li>'); $('#lab-sidebar ul').append('<li class="action-picturesget-li"><a class="action-picturesget" href="javascript:void(0)" title="' + MESSAGES[59] + '"><i class="glyphicon glyphicon-picture"></i></a></li>'); if ( Object.keys(pic) < 1 ) { $('.action-picturesget-li').addClass('hidden'); } $('#lab-sidebar ul').append('<li><a class="action-textobjectsget" href="javascript:void(0)" title="' + MESSAGES[150] + '"><i class="glyphicon glyphicon-text-background"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-moreactions" href="javascript:void(0)" title="' + MESSAGES[125] + '"><i class="glyphicon glyphicon-th"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-labtopologyrefresh" href="javascript:void(0)" title="' + MESSAGES[57] + '"><i class="glyphicon glyphicon-refresh"></i></a></li>'); $('#lab-sidebar ul').append('<li class="plus-minus-slider"><i class="fa fa-minus"></i><div class="col-md-2 glyphicon glyphicon-zoom-in sidemenu-zoom"></div><div id="zoomslide" class="col-md-5"></div><div class="col-md-5"></div><i class="fa fa-plus"></i><br></li>'); $('#zoomslide').slider({value:100,min:10,max:200,step:10,slide:zoomlab}); //$('#lab-sidebar ul').append('<li><a class="action-freeselect" href="javascript:void(0)" title="' + MESSAGES[151] + '"><i class="glyphicon glyphicon-check"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-status" href="javascript:void(0)" title="' + MESSAGES[13] + '"><i class="glyphicon glyphicon-info-sign"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-labbodyget" href="javascript:void(0)" title="' + MESSAGES[64] + '"><i class="glyphicon glyphicon-list-alt"></i></a></li>'); $('#lab-sidebar ul').append('<li><a class="action-lock-lab" href="javascript:void(0)" title="' + MESSAGES[166] + '"><i class="glyphicon glyphicon-ok-circle"></i></a></li>'); if ( $.cookie("topo") == 'dark' ) { $('#lab-sidebar ul').append('<li><a class="action-lightmode" href="javascript:void(0)" title="' + MESSAGES[236] + '"><i class="fas fa-sun"></i></a></li>'); } else { $('#lab-sidebar ul').append('<li><a class="action-nightmode" href="javascript:void(0)" title="' + MESSAGES[235] + '"><i class="fas fa-moon"></i></a></li>'); } $('#lab-sidebar ul').append('<div id="action-labclose"><li><a class="action-labclose" href="javascript:void(0)" title="' + MESSAGES[60] + '"><i class="glyphicon glyphicon-off"></i></a></li></div>'); $('#lab-sidebar ul').append('<li><a class="action-logout" href="javascript:void(0)" title="' + MESSAGES[14] + '"><i class="glyphicon glyphicon-log-out"></i></a></li>'); $('#lab-sidebar ul a').each(function () { var t = $(this).attr("title"); $(this).append(t); }) if ( LOCK == 1 ) { lab_topology.setDraggable($('.node_frame, .network_frame, .customShape'), false); $('.customShape').resizable('disable'); } }) }
[ "function printPageLabOpen(lab) {\n var html =\n '<div id=\"lab-sidebar\"><ul></ul></div><div id=\"lab-viewport\" data-path=\"' +\n lab +\n '\"></div>';\n\n $('#body').html(html);\n\n // Print topology\n printLabTopology();\n\n // Read privileges and set specific actions/elements\n if (ROLE == 'admin' || ROLE == 'editor') {\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-labobjectadd\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[56] +\n '\"><i class=\"glyphicon glyphicon-plus\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-nodelink\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[115] +\n '\"><i class=\"glyphicon glyphicon-link\"></i></a></li>'\n );\n }\n\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-nodesget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[62] +\n '\"><i class=\"glyphicon glyphicon-hdd\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-networksget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[61] +\n '\"><i class=\"glyphicon glyphicon-transfer\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-configsget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[58] +\n '\"><i class=\"glyphicon glyphicon-align-left\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-picturesget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[59] +\n '\"><i class=\"glyphicon glyphicon-picture\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-textobjectsget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[150] +\n '\"><i class=\"glyphicon glyphicon-text-background\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-moreactions\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[125] +\n '\"><i class=\"glyphicon glyphicon-th\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-labtopologyrefresh\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[57] +\n '\"><i class=\"glyphicon glyphicon-refresh\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-freeselect\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[151] +\n '\"><i class=\"glyphicon glyphicon-check\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-status\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[13] +\n '\"><i class=\"glyphicon glyphicon-info-sign\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-labbodyget\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[64] +\n '\"><i class=\"glyphicon glyphicon-list-alt\"></i></a></li>'\n );\n\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-zhidaoshu\" href=\"javascript:void(0)\" title=\"' +\n '实验指导书' +\n '\"><i class=\"glyphicon glyphicon-book\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-tijiaopeizhi\" href=\"javascript:void(0)\" title=\"' +\n '提交实验配置' +\n '\"><i class=\"glyphicon glyphicon-cog\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-tijiaobaogao\" href=\"javascript:void(0)\" title=\"' +\n '提交实验报告' +\n '\"><i class=\"glyphicon glyphicon-list\"></i></a></li>'\n );\n // $('#lab-sidebar ul').append('<li><a class=\"action-peizhidaan\" href=\"javascript:void(0)\" title=\"' + '标准答案' + '\"><i class=\"glyphicon glyphicon-eye-open\"></i></a></li>');\n\n $('#lab-sidebar ul').append(\n '<div id=\"action-labclose\"><li><a class=\"action-labclose\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[60] +\n '\"><i class=\"glyphicon glyphicon-off\"></i></a></li></div>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-lock-lab\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[166] +\n '\"><i class=\"glyphicon glyphicon-ok-circle\"></i></a></li>'\n );\n $('#lab-sidebar ul').append(\n '<li><a class=\"action-logout\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[14] +\n '\"><i class=\"glyphicon glyphicon-log-out\"></i></a></li>'\n );\n $('#lab-sidebar ul a').each(function () {\n var t = $(this).attr('title');\n $(this).append(t);\n });\n}", "function printPage() {\r\n window.print();\r\n }", "function showPrinterPage( res ){\n //start pronsole\n //reset printer\n //show some links here\n header( res );\n\n res.write( '<center>' );\n res.write( '<table width=\"780px\">');\n res.write( '<tr><td>&nbsp;</td><td>' );\n res.write( '<a href=\"moveforward\">^ forward</a>' );\n res.write( '</td><td>&nbsp;</td><td>&nbsp;</td></tr>' );\n\n res.write( '<tr><td>' );\n res.write( '<a href=\"moveleft\"><- left</a>' );\n res.write( '</td><td>&nbsp;</td><td>' );\n res.write( '<a href=\"moveright\">right -></a>' );\n res.write( '</td><td> <a href=\"moveup\">Move up ^</a> <br/><br/> <a href=\"movedown\">Move down v</a>' );\n res.write( '</td><td> <a href=\"/heatoff\">Heat OFF</a> <br/> <a href=\"heaton\">Heat to 210 degrees</a> <br/> '+ \n '<br/><a href=\"extrude\">Extrude 5mm</a> <a href=\"retract\">Retract 5mm</a>'+\n '<br/><br/><a href=\"/printfile\">PRINT G-CODE!</a> </td><td>' );\n res.write( '</td></tr>' );\n \n res.write( '<tr><td>&nbsp;</td><td>' );\n res.write( '<a href=\"moveback\">v backward</a>' );\n res.write( '</td><td>&nbsp;</td><td>&nbsp;</td></tr>' );\n\n res.write('</table>');\n\n res.write('</center>');\n\n res.write( '<br/><a href=\"homexy\">Home X & Y ax </a> <br/>' );\n res.write( '<a href=\"homez\">Home Z ax </a><br/><br/>' );\n\n //todo show snapshot of printer here or status or stuff...\n footer(res);\n}", "function print_current_page() {\n window.print();\n}", "function print_current_page()\n{\nwindow.print();\n}", "function showPrintingToolsTab() {\n }", "function pagePrint() \n\t{\n \twindow.print();\n\t}", "function showPrinterFriendlyPage(strURL) {\n var strFeatures = \"scrollbars=yes,toolbar=yes,location=no\";\n if (isNS4_M) {\n strFeatures += \",resizable=no\";\n } else {\n strFeatures += \",resizable=yes\";\n }\n\tvar objWindow = window.open(strURL, \"PF\" + (new Date()).getTime(), strFeatures).focus();\n \tregisterChildWindows(objWindow, top);\n}", "function printit() {\r\n frames.printPage.focus();\r\n frames.printPage.print();\r\n if (pluginOptions.showMessage) {\r\n unloadMessage();\r\n }\r\n if ($.isFunction(pluginOptions.callback))\r\n {\r\n $.call(this, pluginOptions.callback);\r\n }\r\n }", "function showpage(fp, pg, pages)\n{\n var i, len;\n var inbuf;\n\n\tfp.position = pages[pg];\n\tlen = HEADERMARK.length;\n\tconsole.attributes = attrs.viewer_text;\n for(i = 0; i < 19; i++) {\n if((inbuf = fp.readln(1024)) == null)\n break;\n\t\tinbuf = inbuf.substr(0, 77);\n if(inbuf.substr(0, 2) == HEADERMARK)\n break;\n console.gotoxy(3, i+1);\n console.print(inbuf);\n console.cleartoeol();\n }\n for(; i < 19; i++) {\n console.gotoxy(3, i+1);\n console.cleartoeol();\n }\n console.gotoxy(56, 22);\n\tconsole.attributes = genattrs.help;\n console.print(format(\"Page %d of %d\", pg + 1, pages.length));\n console.cleartoeol();\n console.gotoxy(71, 22);\n\tconsole.attribtes = attrs.reader_prompt;\n console.print(\"< >\");\n}", "function printExamPage() { \n\t//console.log(\"printing\");\n\tvar disp_setting = \"toolbar=yes,location=yes,directories=yes,menubar=yes,\"; \n\tdisp_setting += \"scrollbars=yes,width=800, height=900, left=100, top=25\"; \n\n\tvar content_vlue = $('#exam-container').html(); //document.getElementById(\"print_content\").innerHTML; \n\tcontent_vlue += $('#students-container').html(); \n\t//console.log(content_vlue);\n\tcontent_vlue = content_vlue.replace(/(<button)(.*?<\\/button>)/ig, \"\");\n\n\tvar docprint = window.open(\"\", \"\", disp_setting); \n\tdocprint.document.open(); \n\tdocprint.document.write('<html><head><title>Koekertatuloste</title>'); \n\tdocprint.document.write('</head><body onLoad=\"self.print()\"><center>'); \n\tdocprint.document.write(content_vlue);\n\tdocprint.document.write('</center></body></html>'); \n\tdocprint.document.close(); \n\tdocprint.focus();\n}", "function openPrinterFriendly(url){\r\n\tvar settings = \"width=800,height=600,scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes\";\r\n\tpfLink = window.open(url, 'PrintPage', settings);\r\n\tpfLink.focus();\r\n}//", "function printLabPreview(lab_filename) {\n $.when(getLabInfo(lab_filename))\n .done(function (lab) {\n var html = '<h1>' + lab['name'] + ' v' + lab['version'] + '</h1>';\n if (lab['author'] != null) {\n html += '<h2>by ' + lab['author'] + '</h2>';\n }\n html += '<p><code>' + lab['id'] + '</code></p>';\n if (lab['description'] != null) {\n html += '<p>' + lab['description'] + '</p>';\n }\n html +=\n '<button class=\"action-labopen btn btn-flat\" type=\"button\" data-path=\"' +\n lab_filename +\n '\">' +\n MESSAGES[22] +\n '</button> ';\n if (ROLE != 'user')\n html +=\n '<button class=\"action-labedit-inline btn btn-flat\" type=\"button\" data-path=\"' +\n lab_filename +\n '\">Edit</button>';\n $('#list-title-info span').html(\n lab['filename'].replace(/\\\\/g, '/').replace(/.*\\//, '')\n );\n $('#list-info').html(html);\n })\n .fail(function (message) {\n addModalError(message);\n });\n}", "function _printIt(){\n frame.focus();\n frame.print();\n frame.parent.focus(); // does this work? not sure .. \n //$printFrame.contents().empty();\n //$printFrame.remove(); // would love to do this, but causes reresh of main page .. probably because focus is still on it?\n }", "function printLabPreview(lab_filename) {\n $.when(getLabInfo(lab_filename)).done(function (lab) {\n var html = '<h1>' + lab['name'] + ' v' + lab['version'] + '</h1>';\n if (lab['author'] != null) {\n html += '<h2>by ' + lab['author'] + '</h2>';\n }\n html += '<p><code>' + lab['id'] + '</code></p>';\n if (lab['description'] != null) {\n html += '<p>' + lab['description'] + '</p>';\n }\n html += '<button class=\"action-labopen btn btn-flat\" type=\"button\" data-path=\"' + lab_filename + '\">' + MESSAGES[22] + '</button> ';\n if (ROLE != \"user\")\n html += '<button class=\"action-labedit-inline btn btn-flat\" type=\"button\" data-path=\"' + lab_filename + '\">Edit</button>';\n $('#list-title-info span').html(lab['filename'].replace(/\\\\/g, '/').replace(/.*\\//, ''));\n $('#list-info').html(html);\n }).fail(function (message) {\n addModalError(message);\n });\n}", "function print1Week() {\n window.open(`printschedule/index.html?offset=${weekOffset}&print=1#inapp`);\n}", "printProgress(page) {\n process.stdout.clearLine()\n process.stdout.cursorTo(0) \n process.stdout.write('Scraping PDF pages from Kindle: '+page+' from '+this.noPages)\n }", "function openPrintable(sTitle, sURL)\r\n{\r\n\tvar win = null;\r\n\twin = window.open(sURL, sTitle, \"width=620,height=460,status=no,toolbar=no,scrollbars=yes\");\r\n}", "function showPrinterFriendlyPage(strURL) {\n\tif(typeof strURL != \"undefined\" && strURL) {\n\t\t//Any URL append has to happen only when there is (valid ?) URL, otherwise, some browsers use the referring URL by default and some browsers use null.\n\t\t//In either case of browser operation, security may be compromised.\n\t\tif(strURL.indexOf(\"?\") > -1) {\n\t\t\tstrURL = strURL + \"&targetLocation=popup\";\n\t\t} else {\n\t\t\tstrURL = strURL + \"?targetLocation=popup\";\n\t\t}\n\t}\n\n var strFeatures = \"scrollbars=yes,toolbar=yes,location=no\";\n if (isNS4_M) {\n strFeatures += \",resizable=no\";\n } else {\n strFeatures += \",resizable=yes\";\n }\n var objWindow = window.open(strURL, \"PF\" + (new Date()).getTime(), strFeatures);\n if ( typeof(objWindow) != \"undefined\" && objWindow != null ){\n \tregisterChildWindows(objWindow, getTopWindow());\n \tobjWindow.focus();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ownership modes: IGNORE: leave user as is REMOVE: remove reference to user OVERWRITE: set user to it
function configureOwnership() { for (var objectType in metaData) { //It not iterable, skip if (!Array.isArray(metaData[objectType])) continue; //For each object of objectType for (var obj of metaData[objectType]) { //Set ownersip, if applicable if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("user")) { if (currentExport._ownership.modeOwner == "REMOVE") { delete obj.user; } else if (currentExport._ownership.modeOwner == "OVERWRITE") { obj.user = { "id": currentExport._ownership.ownerId }; } } if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("lastUpdatedBy")) { if (currentExport._ownership.modeLastUpdated == "REMOVE") { delete obj.lastUpdatedBy; } else if (currentExport._ownership.modeLastUpdated == "OVERWRITE") { obj.lastUpdatedBy = { "id": currentExport._ownership.ownerId }; } } if (currentExport.hasOwnProperty("_ownership") && obj.hasOwnProperty("createdBy")) { if (currentExport._ownership.modeCreatedBy == "REMOVE") { delete obj.createdBy; } else if (currentExport._ownership.modeCreatedBy == "OVERWRITE") { obj.createdBy = { "id": currentExport._ownership.ownerId } } } } } }
[ "function setOwnership(doc, previous, options, next) {\n doc._owner = util.adminId\n next()\n}", "function test_set_ownership_back_to_default() {}", "function takeOwnership() {\r\n ownerRef.set(sceneSync.clientId);\r\n }", "updateOwnership()\n {\n this._ownerItem = BaseItem.getAssociatedItem(this._ownerUrl);\n if (this._ownerItem)\n {\n this.addToOwner(this._ownerItem);\n }\n }", "static removeUser() {\n this.removeLocalVal('userName');\n this.setAccessLevel(0);\n this.removeLocalVal('aliases');\n this.removeLocalVal('selectedAlias');\n }", "takeOwnership() {\n\t\tthis.ownerRef.set(this.sceneSync.clientId);\n\t}", "function complete_resetOwnership(){\t\t\t\t\n\t\t\t\t\taddOwnership(res, context, mysql, complete_addOwnership);\t//set the gs in owns_gsid[] to 1\n\t\t\t\t\tfunction complete_addOwnership(){\n\t\t\t\t\t\tres.redirect('/people');\n\t\t\t\t\t}\t\t\n\t\t\t\t}", "function setNoneAccess(user, currentAccessLevel, projectId) {\n if(!listContainsId(user.adminProjectAccess, projectId)){\n user.readProjectAccess = removeIdFromList(user.readProjectAccess, projectId);\n user.useProjectAccess = removeIdFromList(user.useProjectAccess, projectId);\n if(currentAccessLevel !== \"none\"){\n // additional step:\n // remove from the project's list\n removeUserAccess(user, projectId);\n }\n }\n else{\n console.log(\"cannot change admin rights\");\n }\n}", "function adjust_user(u){\n\t//todo: check for whether things need changes, change them, and mark changed as true\n\t//todo: put changes into db...?\n}", "setOwner(project, user) {\n\n // Verify that the user exists\n let verifiedUser = Meteor.users.findOne({_id: user._id});\n if (!verifiedUser) {\n throw new Error('Invalid user');\n }\n\n // Verify that the project exists\n if (!ProjectMethods.exists(project)) {\n throw new Error('Project does not exist');\n }\n\n Projects.update(project._id, {ownerId: user._id});\n }", "updateUidIfAlguienAbandona(){\n\t\tthis.Uids--;\n\t\tif(this.Uids < 0)\n\t\t\tthis.Uids = 0; //evitar -1 si owner quita\n\n\t\tthis.usuarios.forEach((usuario,index) => usuario.setId(index));\n\t}", "function canChangeOwner() {\n return resourceService.canChangeOwner(getSelectedNode());\n }", "unlock(owner) {\n if (this.owner === owner) {\n this.owner = null;\n return true;\n }\n return false;\n }", "destroy(user) {\n// return this.isAllowed('update', article);\n return this.isAdmin()\n }", "_setOwnerConfig(value, context) {\n const parsedValuePath = context.valuePath;\n const auth = context.auth;\n const owner = {\n [PredefinedDbPaths.DOT_OWNER]: {\n [OwnerProperties.OWNERS]: {\n [auth.addr]: buildOwnerPermissions(false, true, true, true),\n [OwnerProperties.ANYONE]: buildOwnerPermissions(false, true, true, true),\n }\n }\n };\n const result = this.setOwnerOrLog(CommonUtil.formatPath(parsedValuePath), owner, context);\n if (!CommonUtil.isFailedTx(result)) {\n return this.returnFuncResult(context, FunctionResultCode.SUCCESS);\n } else {\n return this.returnFuncResult(context, FunctionResultCode.FAILURE);\n }\n }", "async function transferOwnership() {\n const newOwner = process.env.OWNER_ADDRESS;\n if (!newOwner) {\n return;\n }\n const adminOwner = await upgrades.admin.getInstance().then(c => c.owner());\n if (adminOwner.toLowerCase() === newOwner.toLowerCase()) {\n return;\n }\n\n console.log(`Transferring ownership to ${newOwner}...`);\n await upgrades.admin.transferProxyAdminOwnership(newOwner);\n console.log(` Completed`);\n}", "set [_owner.LEGACY_OWNER](value) {}", "function restoreUser(){\n userService.$user = {\n id: null,\n username: null,\n access_token: null,\n role: null\n };\n }", "function addProjectToOwner(userId, projectId){\n \n User.findOne({_id : userId}, function(err, user){\n if(err){\n console.log(err);\n }\n \n user.roles.owner.push(projectId);\n user.save(function(err) {\n if(err){\n console.log(err);\n }\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper that renders branch information. Allows props to be overriden
branch(props) { const { required, scrollIntoView } = this.props return ( <Branch name={props.name} label={props.label} labelSize={props.labelSize} className={props.className} help={props.help} {...props.value || {}} warning={props.warning} onUpdate={props.onUpdate} required={required} onError={props.onError} scrollIntoView={scrollIntoView} > {props.children} </Branch> ) }
[ "function createBranchHTML(branch) {\n\t\tconsole.debug(\"createBranchHTML\");\n\n\t\tbranchContainer = document.createElement(\"div\");\n\t\tvar branchLabel = document.createElement(\"h3\");\n\t\tbranchLabel.style = \"float:left;\";\n\t\tbranchLabel.innerText = \"Branch \" + branch.name;\n\t\tbranchContainer.appendChild(branchLabel);\n\n\t\tvar branchExpander = document.createElement(\"a\");\n\t\tbranchExpander.innerText = \"Hide details for branch\";\n\t\tbranchExpander.setAttribute(\"data-replace-text\", \"Show details for branch \" + branch.name);\n\t\tbranchExpander.className = \"aui-expander-trigger right-aligned\";\n\t\tbranchExpander.setAttribute(\"aria-controls\", branch.hash);\n\t\tbranchContainer.appendChild(branchExpander);\n\n\t\tbranchCollapsableContainer = document.createElement(\"div\");\n\t\tbranchCollapsableContainer.className = \"aui-expander-content\";\n\t\tbranchCollapsableContainer.setAttribute(\"aria-expanded\", true);\n\t\tbranchCollapsableContainer.id = branch.hash;\n\n\t\tbranchRepoLink = document.createElement(\"a\");\n\t\tbranchRepoLink.href = decodeURIComponent(branch.repoUri);\n\t\tbranchRepoLink.target = \"_blank\";\n\t\tbranchRepoLink.innerText = decodeURIComponent(branch.repoUri);\n\t\tbranchRepoLink.className = \"right-aligned\";\n\t\tbranchCollapsableContainer.appendChild(branchRepoLink);\n\n\t\tbranchCollapsableContainer.appendChild(createBranchQualityAssessment(branch));\n\t\tbranchCollapsableContainer.appendChild(createBranchMessageElementsHtml(branch.commitElements));\n\t\tbranchCollapsableContainer.appendChild(createBranchCodeElementsHtml(branch.codeElements));\n\t\tbranchContainer.appendChild(branchCollapsableContainer);\n\n\t\treturn branchContainer;\n\t}", "function showBranch(branchName) {\n $(\"#branch_name\").html(branchName.isWhitespace() ? \"[None]\" : branchName);\n}", "function getBranches(repNum) {\n //clear branches div\n document.getElementById('branches-div').innerHTML = '';\n //get repo name\n let repo = rObj[repNum].name;\n fetch('https://api.github.com/repos/' + username + '/' + repo + '/branches')\n .then(resp => resp.json())\n .then(data => {\n //set global repo obj to most recent response\n let bhtml = '<br>';\n console.log(data.length);\n for (let i = 0; i < data.length; i++) {\n bhtml += 'name: ' + data[i].name + '<br>';\n bhtml += 'sha: ' + data[i].commit.sha + '<br>';\n bhtml += 'url: ' + data[i].commit.url + '<br>';\n bhtml += 'protected: ' + data[i].protected + '<br>';\n bhtml += '<hr>';\n }\n document.getElementById('branches-div').innerHTML += bhtml;\n //console.log(bhtml);\n //let branch\n })\n .catch(error => console.log('ERROR'));\n\n}", "renderViewRepo() {\n const { selectedRepo, viewRepo } = this.state;\n if (viewRepo && selectedRepo) {\n const { default_branch, forks_count, full_name } = selectedRepo;\n let { language } = selectedRepo;\n if (!language) {\n language = \"Not specified\";\n }\n return (\n <div className=\"selectedRepo\">\n <div className=\"name\">{full_name.split('/').pop()}</div>\n <div className=\"language\">Language: {language}</div>\n <div className=\"defaultBranch\">Default branch: {default_branch}</div>\n <div className=\"forks\">Forks: {forks_count}</div>\n </div>\n )\n }\n }", "getBranchNum() {\n return this.branch_num;\n }", "function showBranchDetail(branch) {\n if (branch.distance != '') {\n $('.branches-details-div').append(`\n <div class=\"branch-details-div\">\n <a class=\"branch-title\">${branch.name}</a>\n <a class=\"opening-hours\">${branch.hours}</a>\n <a class=\"distance\">${\n Math.round(branch.distance * 10) / 10\n } km away from you</a>\n <a href=\"${branch.directions}\" class=\"address\"><i class=\"fa fa-directions\"></i> ${branch.address}</a>\n <a href=\"tel:${branch.number}\" class=\"phone\"><i class=\"fa fa-phone-alt\"></i> ${branch.number}</a>\n </div>`);\n } else {\n $('.branches-details-div').append(`\n <div class=\"branch-details-div\">\n <a class=\"branch-title\">${branch.name}</a>\n <a class=\"opening-hours\">${branch.hours}</a>\n <a href=\"${branch.directions}\" class=\"address\"><i class=\"fa fa-directions\"></i> ${branch.address}</a>\n <a href=\"tel:${branch.number}\" class=\"phone\"><i class=\"fa fa-phone-alt\"></i> ${branch.number}</a>\n </div>`);\n }\n}", "getBranchNames() {\n fetch(this.state.camundaUrl + '/rest/variable-instance/?variableName=git_branch_name')\n .then(result => result.json())\n .then(branchNames => this.setState({branchNames}))\n .catch(error => {\n console.log(error);\n });\n }", "getBranchesSelect(clinics) {\n const branches = [\n {\n data: {\n placeholder: 'All Branches',\n value: 'All Branches',\n searchable: 'All Branches',\n },\n component: <div>All Branches</div>,\n },\n ];\n const clinicsLen = clinics.length;\n for (let i1 = 0; i1 < clinicsLen; i1 += 1) {\n if (clinics[i1].Branches) {\n const branchesArr = clinics[i1].Branches;\n const branchesArrLen = branchesArr.length;\n for (let i2 = 0; i2 < branchesArrLen; i2 += 1) {\n const obj = {\n data: {\n placeholder: branchesArr[i2].BranchName,\n value: branchesArr[i2].BranchKey,\n searchable: [branchesArr[i2].BranchName],\n },\n component: <div>{ branchesArr[i2].BranchName }</div>,\n };\n branches.push(obj);\n }\n }\n }\n return branches;\n }", "function SidebarCommitInfo_SidebarCommitInfo(_) {\n const {\n selectedCommitIndex,\n rootID\n } = Object(react[\"useContext\"])(ProfilerContext);\n const {\n profilerStore\n } = Object(react[\"useContext\"])(StoreContext);\n\n if (rootID === null || selectedCommitIndex === null) {\n return /*#__PURE__*/react[\"createElement\"](\"div\", {\n className: SidebarCommitInfo_default.a.NothingSelected\n }, \"Nothing selected\");\n }\n\n const {\n duration,\n effectDuration,\n passiveEffectDuration,\n priorityLevel,\n timestamp,\n updaters\n } = profilerStore.getCommitData(rootID, selectedCommitIndex);\n const hasCommitPhaseDurations = effectDuration !== null || passiveEffectDuration !== null;\n const commitTree = updaters !== null ? getCommitTree({\n commitIndex: selectedCommitIndex,\n profilerStore,\n rootID\n }) : null;\n return /*#__PURE__*/react[\"createElement\"](react[\"Fragment\"], null, /*#__PURE__*/react[\"createElement\"](\"div\", {\n className: SidebarCommitInfo_default.a.Toolbar\n }, \"Commit information\"), /*#__PURE__*/react[\"createElement\"](\"div\", {\n className: SidebarCommitInfo_default.a.Content\n }, /*#__PURE__*/react[\"createElement\"](\"ul\", {\n className: SidebarCommitInfo_default.a.List\n }, priorityLevel !== null && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.ListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Priority\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, priorityLevel)), /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.ListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Committed at\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, formatTime(timestamp), \"s\")), !hasCommitPhaseDurations && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.ListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Render duration\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, formatDuration(duration), \"ms\")), hasCommitPhaseDurations && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.ListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Durations\"), /*#__PURE__*/react[\"createElement\"](\"ul\", {\n className: SidebarCommitInfo_default.a.DurationsList\n }, /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.DurationsListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Render\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, formatDuration(duration), \"ms\")), effectDuration !== null && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.DurationsListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Layout effects\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, formatDuration(effectDuration), \"ms\")), passiveEffectDuration !== null && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.DurationsListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"Passive effects\"), \":\", ' ', /*#__PURE__*/react[\"createElement\"](\"span\", {\n className: SidebarCommitInfo_default.a.Value\n }, formatDuration(passiveEffectDuration), \"ms\")))), updaters !== null && commitTree !== null && /*#__PURE__*/react[\"createElement\"](\"li\", {\n className: SidebarCommitInfo_default.a.ListItem\n }, /*#__PURE__*/react[\"createElement\"](\"label\", {\n className: SidebarCommitInfo_default.a.Label\n }, \"What caused this update\"), \"?\", /*#__PURE__*/react[\"createElement\"](Updaters_Updaters, {\n commitTree: commitTree,\n updaters: updaters\n })))));\n}", "static branch(_branch) {\n if (_branch.nChildren > 0)\n Debug.group(_branch.name);\n else\n Debug.fudge(_branch.name);\n for (let child of _branch.getChildren())\n Debug.branch(child);\n if (_branch.nChildren > 0)\n Debug.groupEnd();\n }", "function displayBranches() {\n //turns this into a json object\n const branches = JSON.parse(this.responseText)\n console.log(branches);\n// creates the html by going through the commits collection and pulling out the data needed and putting it into a li\n const branchesList = `<ul>${branches.map(branch => '<li><strong>' + branch.name + '</li>').join('')}</ul>`\n //gets the DOM element and puts the commitsList html into the div\n document.getElementById(\"details\").innerHTML = branchesList\n}", "get branch() {\n return shell.exec( 'git rev-parse --abbrev-ref HEAD' ).stdout.trim();\n }", "render() {\n const {\n actionError,\n branch,\n dispatch,\n fetchError,\n isActive,\n isFetching,\n project,\n projectList,\n serviceApi,\n userSettings,\n workflows\n } = this.props;\n // The main content of the page depends on the error and fetching state.\n let content = null;\n if (fetchError) {\n // There was an error while fetching the project or the workflow\n // listing.\n content = (\n <div className='page-content wide'>\n <FetchError error={fetchError} />\n </div>\n );\n } else if ((project == null) || (branch == null) || (workflows == null) || (isFetching)) {\n // Show a spinner while the project information is being fetched.\n // There is nothing else to show yet.\n content = <ContentSpinner text='Loading History ...' />;\n } else if (workflows != null) {\n // The branch history has been fetched successfully. Show a table\n // containing the different workflow versions.\n const rows = [];\n for (let i = 0; i < workflows.length; i++) {\n const wf = workflows[i];\n let icon = null;\n let action = null;\n let command = null;\n let color = 'black';\n if (wf.actionIsCreate()) {\n icon = 'fork';\n color = 'grey';\n action = 'Create branch';\n } else {\n if (wf.actionIsDelete()) {\n icon = 'trash';\n color = 'red';\n action = 'Delete cell';\n } else if (wf.actionIsAppend()) {\n icon = 'add square';\n color = 'green';\n action = 'Append cell';\n } else if (wf.actionIsInsert()) {\n icon = 'add circle';\n color = 'olive';\n action = 'Insert cell';\n } else if (wf.actionIsReplace()) {\n icon = 'pencil';\n color = 'blue';\n action = 'Replace cell';\n }\n command = serviceApi\n .engine\n .packages\n .getCommandSpec(wf.packageId, wf.commandId)\n .name;\n }\n const isHead = (i === workflows.length - 1);\n rows.push(\n <tr key={wf.id}>\n <td className='workflow-nr'>{wf.id}</td>\n <td className='workflow-icon'>\n <Icon\n title='Show notebook'\n link name={'eye'}\n onClick={() => (this.handleShowWorkflow(wf, isHead))}\n />\n </td>\n <td className='workflow-icon'><Icon title={action} name={icon} color={color}/></td>\n <td className='workflow-command'>{command}</td>\n <td className='version-timestamp'>{wf.createdAt}</td>\n </tr>\n )\n }\n const pageContent = (\n <div className='branch-history'>\n <h1 className='branch-history'>\n {'Notebooks in Branch '}\n <span className='branch-highlight'>{branch.name}</span>\n </h1>\n <p className='info-text'>This is a list of all notebook versions in the history of\n the branch {branch.name}. Click on the&nbsp; <Icon name='eye' /> to display a notebook.\n </p>\n <table><tbody>{rows}</tbody></table>\n </div>\n );\n // Show branch history table as the main content in a project\n // resource page\n content = (\n <ResourcePage\n actionError={actionError}\n branch={branch}\n content={pageContent}\n contentCss='slim'\n dispatch={dispatch}\n isActive={isActive}\n onDeleteBranch={this.handleDeleteBranch}\n onShowNotebook={this.handleShowWorkflow}\n onSwitchBranch={this.handleSwitchBranch}\n project={project}\n projectList={projectList}\n resource={new BranchResource()}\n serviceApi={serviceApi}\n userSettings={userSettings}\n />\n );\n }\n return content;\n }", "function printBranch(nodes) {\n if (nodes.length >= treecfg.mindepth) {\n // node is at the required depth - this is the data we're interested in,\n // print the branch\n console.log(nodes.join(','));\n }\n}", "function displayBranches(){\n const branches = JSON.parse(this.responseText)\n const branchesList = `<ul>${branches.map(branch => '<li>' + branch.name + '</li>').join('')}</ul>`\n document.getElementById(\"details\").innerHTML = branchesList\n}", "getBranchDetails(branchName = 'master') {\n return new Promise((resolve, reject) => {\n this.repoDetails.branch(branchName, (err, result) => {\n if (err) {\n return reject(err);\n }\n\n this.mainBranch = branchName;\n this.masterSHA = result.commit.sha;\n resolve(result);\n });\n });\n }", "static GetBranchData (id) {\n return Get(`/branches/${id}`)\n }", "setBranchName() {\n const path = window.location.pathname;\n const name = path.match(/(?<=\\/(branch|commits|file)\\/)[\\w-_]+/);\n\n if (name) {\n [this.branchName] = name;\n } else {\n this.branchName = this.defaultBranch;\n }\n }", "function getBranches(el) {\n const repoName = el.dataset.repository\n const uri = rootURL + \"/repos/\" + el.dataset.username + \"/\" + repoName + \"/branches\"\n const xhr = new XMLHttpRequest()\n xhr.addEventListener(\"load\", displayBranches)\n xhr.open(\"GET\", uri)\n xhr.send()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add listener to burger menu
function addListenerToBurger() { burger.addEventListener('click', function (e) { e.preventDefault(); this.classList.toggle('active'); mainMenu.classList.toggle('active'); }); }
[ "function burger() {\n\n let burger = document.querySelector(\".burger\"),\n menu = document.querySelector(\"nav.menu\");\n\n burger.addEventListener(\"click\", ()=>{\n burger.classList.toggle(\"burger--active\")\n menu.classList.toggle(\"menu--active\")\n })\n}", "function burgerMenu(){\n\t$(\".burger-menu\").click(() => {\n\t\t$(\".burger-menu\").toggleClass(\"show\")\n\t\t$(\"nav ul\").toggleClass(\"show\")\n\t})\n}", "function burgerClick() {\n\n setShowBurger(prevState => !prevState);\n\n navRef.current.classList.toggle('show');\n\n }", "function addListenerToMenu() {\n mainMenu.addEventListener('click', function (e) {\n const clickedButton = e.target.closest('.menu-btn');\n const buttonName = clickedButton.textContent;\n const buttonActive = document.querySelector('.btn-active');\n\n if (!clickedButton || clickedButton === buttonActive) {\n return;\n }\n\n if (buttonActive) {\n buttonActive.classList.remove('btn-active');\n }\n\n clickedButton.classList.add('btn-active');\n\n cars.forEach(function (obj) {\n if (obj.name === buttonName) {\n showContent(obj);\n hideBurgerMenu();\n }\n });\n\n });\n }", "function getBurger() {\n const burger = document.querySelector('#burger');\n burger.addEventListener('click', openBurger);\n}", "function addMenuClick() {\n hamburger.addEventListener('click', menuClick);\n for (let i = 0; i < menuItems.length; i++) {\n menuItems[i].addEventListener('click', menuClick);\n }\n}", "function burgerIconClick() {\n $(BURGER_BTN).on('click', e => {\n e.preventDefault();\n toggleMobileMenu();\n });\n}", "function burgerFunction() {\n burger.classList.toggle('change');\n}", "function openBurgerMenu(closeit) {\n\n const burgerScreen = document.getElementById('burgerScreen');\n const burgerOverlay = document.getElementsByClassName('overlay')[0];\n\n\n burgerOverlay.style.display = 'block';\n burgerScreen.classList.toggle('active');\n\n burgerOverlay.addEventListener('click', closeCanvas = function () {\n burgerScreen.classList.remove('active');\n burgerOverlay.style.display = 'none';\n });\n\n\n if (closeit) {\n burgerOverlay.style.display = 'none';\n burgerScreen.classList.remove('active');\n }\n}", "function onMenuClick() {\n console.log('clicked on the menu');\n }", "function eventListenerMenuBar() {\n const menuBarLinks = document.querySelectorAll(\"#events .menubar ul li\");\n menuBarLinks.forEach(link => {\n link.addEventListener(\"click\", handleMenuBar);\n });\n menuBarLinks[0].classList.add(\"active\");\n}", "_addMenuListeners() {\n document.querySelector('.menu-items') && document.querySelector('.menu-items').addEventListener('click', this._onMenuClick.bind(this));\n }", "function toggleBurgerMenu() {\n \n // Gets the burger menu element\n // (the center area's left side contains\n // only the burger menu at this point)\n var menu = document.getElementById('center_left');\n \n // If the burger menu is not visible, is is made visible\n // and the burger menu icon is made active\n if (menu.style.display === 'none') {\n showMenu();\n burgerOn();\n }\n // Otherwise the burger menu is hidden\n else {\n hideMenu();\n }\n}", "_configureMenuBtn() {\n const menuBtn = document.querySelector('.js-menu-btn');\n if(!menuBtn) {\n console.warn('Unable to find js-menu-btn.');\n return;\n }\n\n menuBtn.addEventListener('click', () => {\n this.toggleNavDrawer();\n });\n }", "function onOpen() {\n createMenu();\n}", "function burgerToggler() {\n menuLogo.src = \"img/torty-z-pieluszek-logo-menu-male-2.png\";\n menuBar.classList.toggle(\"active\");\n burgerOn.classList.toggle(\"active\");\n burgerOff.classList.toggle(\"active\");\n}", "function setHamburgerMenu() {\n self.buttons.LeftButtonTwo = makeButton(\n self.header.ButtonName.LeftTwo,\n self.header.ButtonImage.Hamburger,\n function () {\n var menu = new Appworks.Menu();\n menu.showMenu(true);\n });\n\n updateButtons();\n}", "function clickBtnOpenBurgerMenu() {\n $(\"#btnChangeToWhite\").click(() => {\n // cambia de color el header y el navbar\n $(\"header, #navBar\").css({\n \"background-color\": \"white\",\n \"box-shadow\": \"2px 2px 6px rgba(0, 0, 0, 0.25)\",\n });\n\n // se elimina la imagen de burger menu\n $(\"#btnChangeToWhite\").remove();\n\n // se crea la x para cerrar el burger menu\n crearXBurgerMenu();\n });\n}", "function onClickHamburger() {\r\n \t$('#menu-icon-trigger').on('click touchStart', function() {\r\n \t\t$('#st-container').toggleClass('st-menu-open');\r\n \t});\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a response timeout timer is present for a user in a chat
hasResponseTimeoutTimer(chatUserKey) { return this.timeoutTimers[chatUserKey] != null; }
[ "hasPresenceTimeoutTimer(chatUserKey) {\n return this.presenceTimeoutTimers[chatUserKey] != null;\n }", "function isTimeOut()\n{\t\t\n var ajaxUrl = UrlConfig.BaseUrl + '/ajax/chat/getsystemtime';\n\n\ttry {\n\t $j.ajax({\n\t\t type: \"GET\", \n\t\t url: ajaxUrl,\n\t\t data: \"cid=\" + $j(\"#cid\").val(),\n\t\t dataType: \"json\",\n\t\t success: function(responseObject) {\t \n\t if (responseObject) {\t \t\n\t //is time out\n\t if ((responseObject.systime - $j('#hidStartTime').val()) >= (3600*(parseInt(responseObject.extend_count)+1))) {\t\t\t\t\t\t\n\t\t\t\t\t\talertTimeOutConfirm();\n\t }\n\t }\n\t\t },\n\t\t error: function(XMLHttpRequest, textStatus, errorThrown) {\n\t\t \t//alert(textStatus);\n\t\t }\n\t\t});\n\t}\n\tcatch (e) {\n\t\t//alert(e);\n\t}\t \n \n setTimeout(\"isTimeOut()\", CONST_DEFAULT_RELOAD_SECONDS_EXTEND*1000);\n}", "addResponseTimeoutTimer(chatUserKey, msg, question) {\n Logger.debug(\"Control::addResponseTimeoutTimer() key: \" + chatUserKey);\n // Timeout milliseconds and callback\n let useTimeoutMs = question.timeoutMs || this.responseTimeoutMs;\n let useTimeoutText = question.timeoutText;\n if(useTimeoutText == null) {\n useTimeoutText = this.responseTimeoutText;\n }\n let useTimeoutCallback = question.timeoutCallback;\n if(!useTimeoutCallback && useTimeoutText && useTimeoutText.length > 0) {\n Logger.debug(\"Control::addResponseTimeoutTimer() ms: \" + useTimeoutMs + \" text: \" + useTimeoutText);\n useTimeoutCallback = () => {\n question.flow.sendRestartMessage(useTimeoutText);\n };\n } else if(useTimeoutCallback != null) {\n Logger.debug(\"Control::addResponseTimeoutTimer() Using custom callback\");\n }\n\n this.timeoutTimers[chatUserKey] = setTimeout(() => {\n Logger.debug(\"Response timer timeout: key: \" + chatUserKey);\n let flow = this.getActiveQuestionnaire(chatUserKey);\n if(!flow) {\n Logger.error(\"Unable to retrieve flow on response timer timeout: key: \" + chatUserKey);\n return;\n }\n flow.stop(false);\n if(this.questionnaireTimedOutCallback) {\n let userId = ChatTools.getUserId(flow.msg.message.user);\n this.questionnaireTimedOutCallback(userId, flow.answers);\n }\n // Call timeout callback\n if(useTimeoutCallback) {\n useTimeoutCallback();\n }\n }, useTimeoutMs);\n }", "trackTimeout() {\n if (this.hasResponded) return\n\n const soft = this.timeUntilTimeout()\n const hard = this.timeUntilTimeout(true)\n\n // Both values have to be not null otherwise we've timedout.\n this.timedOut = !soft || !hard\n if (!this.timedOut) {\n clearTimeout(this.trackTimeoutId)\n this.trackTimeoutId = setTimeout(\n () => this.trackTimeout(),\n Math.min(soft, hard)\n ).unref()\n }\n }", "function isTimeForMsg(userId) {\n var d = new Date();\n if (status[userId] && d.getTime() < status[userId].nextMessage) {\n return false;\n }\n return true;\n}", "addPresenceTimeoutTimer(chatUserKey) {\n Logger.debug(\"Control::addPresenceTimeoutTimer() key: \" + chatUserKey);\n // Timeout milliseconds and callback\n this.presenceTimeoutTimers[chatUserKey] = setTimeout(() => {\n Logger.debug(\"Presence timer timeout: key: \" + chatUserKey);\n let flow = this.getActiveQuestionnaire(chatUserKey);\n if(!flow) {\n Logger.error(\"Unable to retrieve flow on presence timer timeout: key: \" + chatUserKey);\n return;\n }\n flow.stop(false);\n if(this.questionnaireTimedOutCallback) {\n let userId = ChatTools.getUserId(flow.msg.message.user);\n this.questionnaireTimedOutCallback(userId, flow.answers);\n }\n flow.sendRestartMessage(this.presenceTimeoutText);\n\n }, this.presenceTimeoutMs);\n }", "function checkTimeout(application_token) {\n let timeOutTime = application_token[\"expires_in\"];\n let onSetTime = application_token[\"onSetTime\"];\n let currentTime = new Date().getTime();\n\n let response = {};\n\n if (currentTime - onSetTime >= timeOutTime) {\n response[\"status\"] = \"Miss\";\n } else {\n response[\"status\"] = \"Hit\";\n }\n\n return response;\n}", "function checkTimer()\n\t\t{\n\t\t\t// Session should be valid\n\t\t\tif (!skuidErrors())\n\t\t\t{\n\t\t\t\t// if we have HMTL5 LocalStorage\n\t\t\t\tif (storage)\n\t\t\t\t{\n\t\t\t\t\tupdateLS();\n\t\t\t\t}\n\n\t\t\t\t// check for no outstadning saves or actions\n\t\t\t\tif (!pendingActions)\n\t\t\t\t{\n\t\t\t\t\t$.when(userModel.updateData()).then(function ()\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!startTimeIsValid())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thandleChangedStartTime();\n\t\t\t\t\t\t\twindow.console.log(\"Polled: invalid start time\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// start the timer\n\t\t\t\t\t\t\twindow.console.log(\"Polled: start time valid!\");\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tpollTimer();\n\t\t\t\t}\n\t\t\t\telse // allow action to complete and check back soon.\n\t\t\t\t{\n\t\t\t\t\twindow.setTimeout(checkTimer, MINUTES / 3);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twindow.console.log(\"Polled: invalid Session Id! Refresh or relog\");\n\t\t\t}\n\t\t}", "checkTimeout() {\n const eventTimeout = params_1.RingerParams.params.replay.eventTimeout;\n if (eventTimeout !== null && eventTimeout > 0) {\n const timeoutInfo = this.timeoutInfo;\n const curTime = new Date().getTime();\n // we havent changed events\n const index = this.index;\n if (timeoutInfo.index === index) {\n if (curTime - timeoutInfo.startTime > eventTimeout * 1000) {\n return true;\n }\n }\n else {\n this.timeoutInfo = { startTime: curTime, index: index };\n }\n }\n return false;\n }", "function sessionTimeoutCheck(timedoutCallbackFn)\n{\n sessionCheck(timedoutCallbackFn, true);\n}", "function checkActivity() {\n var timeDiff = _.now() - lastActivity;\n if (timeDiff > 60000) {\n $(\"#reply-is-coming\").fadeOut();\n } else {\n setTimeout(checkActivity, 5000);\n }\n }", "removeResponseTimeoutTimer(chatUserKey) {\n if(this.timeoutTimers[chatUserKey] == null) {\n return;\n }\n Logger.debug(\"Control::removeResponseTimeoutTimer() key: \" + chatUserKey);\n let timer = this.timeoutTimers[chatUserKey];\n delete this.timeoutTimers[chatUserKey];\n clearTimeout(timer);\n }", "function pollForStatus() {\n\n\t// If timeout has not reached.\n\tif(timeRemaining > 0) {\n\t\t// If user has not specified a response(YES/NO).\n\t\tif(!hasResponse) {\n\t\t\tcheckUSSDResponseStatus();\n\t\t\ttimeRemaining = timeRemaining - pollingInterval;\n\t\t\t\n\t\t} else {\n\t\t\thandleTermination();\n\t\t}\n\t\t\n\t} else {\n\t\tisTimeout = true;\n\t\thandleTermination();\n\t}\n}", "timeoutActive() {\n return this.timeout !== undefined && this.timeout._idleTimeout > 0;\n }", "function sessionPeriodicTimeoutCheck(timedoutCallbackFn)\n{\n sessionCheck(timedoutCallbackFn, false);\n}", "function checkUserTimeout(){\n var query = 'select user_id,user_loginTime from rdc01hn4hfiuo1rv.user';\n\n function queryCB(err,data) {\n if (err || (data == undefined)){\n return;\n }\n var toRemove = [];\n for (var i=0;i<data.length;i++){\n var rowTime = data[i].user_loginTime;\n var lastLoginTime = parseInt(rowTime.split(':')[0])*60 + parseInt(rowTime.split(':')[1]);\n var curTime = new Date();\n curTime = curTime.getHours()*60 + curTime.getMinutes();\n timeDiff = curTime - lastLoginTime;\n if (timeDiff>15){\n toRemove.push(data[i].user_id);\n }\n }\n for (var i=0;i<toRemove.length;i++){\n setTimeout(cb,500*i,toRemove[i]);\n function cb(id){\n removeUser(id);\n }\n }\n }\n\n util.queryDB(query,queryCB);\n}", "async checkTimeouts () {\n const timeouts = await this.db.find({ at: { $lt: Date.now() + 300000 } }).toArray()\n\n timeouts\n .filter(x => !this.intervals.has(`${x.user};${x.guild}`))\n .forEach(timeout => {\n this.intervals.set(`${timeout.user};${timeout.guild}`,\n setTimeout(() => {\n this.execTimeout(timeout.guild, timeout.user, timeout.type)\n }, timeout.at - Date.now())\n )\n })\n }", "hasTimeout(name) {\n return !!(this.timeoutMap && this.timeoutMap.has(name));\n }", "async function timeoutUser(bot, msg) {\n let userID = msg.content.split(\" \")[1];\n let time = msg.content.split(\" \")[2]; // how much time in minutes (converted to milliseconds) the timeout will last\n let message = msg.content.substring(config.prefix.length + \"timeout \".length + userID.length + 1 + time.length) // reason for why the user recieved the timeout\n\n let guild = await bot.guilds.cache.filter(guild => guild.id == config.guildID).get(config.guildID);\n guild.members.fetch(userID)\n .then(member => {\n\n if (member.roles.cache.has(config.moderatorRoleID)) return msg.channel.send(\"Timeout command can't be used on another moderator\")\n\n let username = member.user.username;\n let displayName = member.displayName;\n displayName = displayName != username ? displayName : null // set displayName to null if it is identical to the username\n\n msg.channel.send(`A timeout of ${time} minute${ time > 1 ? 's' : ''} was set for user ${username} ${displayName ? ' (' + displayName + ')' : ''}`);\n member.user.send(`You have been set on a timeout for ${time} minute${ time > 1 ? 's' : ''}: ${message}. For the duration of the timeout you will not be able to connect to any voice channels or write in any text channels. If your timeout isn't removed after the set time, please notify a moderator.`);\n member.voice.kick(); // remove user from the voice channel the user is connected to\n member.roles.add(config.timeoutRoleID);\n setTimeout(() => {\n member.roles.remove(config.timeoutRoleID);\n member.user.send(\"You are no longer on a timeout. You will now be able to join voice channels and write in text channels.\");\n }, time * 60 * 1000); // convert time from minutes to milliseconds\n })\n .catch(err => msg.channel.send(\"Could not find any user in the guild with ID \" + userID));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main functionality: Fetch codes, handle errors including backoff
fetchCodes(iteration=iterationCurrent) { if (this.fetchInProgress || !this.signedIn) { return } if (this.lastFetch && this.lastFetch.getTime() + this.backoff > new Date().getTime()) { // slow down spammy requests return } this.lastFetch = new Date() this.fetchInProgress=true let successFunc= iteration == iterationCurrent ? this.updateCodes : this.updatePreFetch if (iteration == iterationCurrent && this.preFetch !== null) { successFunc(this.preFetch) this.fetchInProgress = false return } axios.get(`codes.json?it=${iteration}`) .then(resp => { successFunc(resp.data) this.backoff = 500 // Reset backoff to 500ms }) .catch(err => { this.backoff = this.backoff * 1.5 > 30000 ? 30000 : this.backoff * 1.5 if (err.response && err.response.status) { switch (err.response.status) { case 401: this.createAlert('danger', 'Logged out...', 'Server has no valid token for you: You need to re-login.') this.signedIn = false this.otpItems = [] break case 500: this.createAlert('danger', 'Oops.', `Something went wrong when fetching your codes, will try again in ${Math.round(this.backoff / 1000)}s...`, this.backoff) break; } } else { console.error(err) this.createAlert('danger', 'Oops.', `The request went wrong, will try again in ${Math.round(this.backoff / 1000)}s...`, this.backoff) } if (iteration === iterationCurrent) { this.otpItems = [] this.loading = true } }) .finally(() => { this.fetchInProgress=false }) }
[ "async function fetch_and_verify(url) {\n // There is no 'normal' end condition for this loop.\n // Instead the loop is only exited with a return or throw:\n // - an 'OK' response returns the response.\n // - an error throws an exception.\n // - a 503 response loops a few times, then throws an exception if the\n // problem doesn't clear up.\n for (let retry_sleep = 1; retry_sleep *= 2; true) {\n await check_stop('update (before fetch)');\n\n try {\n var response = await fetch(url, {cache: \"no-cache\"});\n } catch (e) {\n console.warn('fetch failed', e);\n err_status = 'Lost online connectivity. Try again later.';\n throw null;\n }\n\n if (!response) {\n err_status = 'Unexpected fetch response. Try again later?';\n throw null;\n } if (response.status == 404) {\n err_status = '404: Could not find ' + decodeURI(url) + '<br>The online Guide must have updated its files just now. Refresh the page and try again.';\n throw null;\n } if ((response.status == 503) && (retry_sleep <= 8)) {\n // Take N discrete one-second sleeps to make it easier to interrupt.\n // This also re-iterates the retry message in case this is the last\n // thread left running, and it would otherwise look silent.\n for (let i = 0; i < retry_sleep; i++) {\n // Use msg instead of err_status because it's a huge pain to clean up\n // err_status on both success and failure when some other process might\n // have generated a higher priority error message.\n let secs = retry_sleep - i;\n if (secs == 1) {\n secs = '1 second';\n } else {\n secs = secs + ' seconds';\n }\n msg = '503: server busy; retrying in ' + secs;\n\n await check_stop('update (before fetch)');\n await sleep(1000);\n }\n continue;\n } else if (!response.ok) {\n err_status = response.status + ': ' + response.statusText + '<br>The online server is behaving oddly. Try again later?';\n throw null;\n } else {\n // response.ok\n return response;\n }\n }\n}", "function pollSystemCodes() {\n\t\t// Note we need to return here to allow tests\n\t\t// to hook into the promise\n\t\treturn fetchSystemCodes(options.cmdbApiKey)\n\t\t\t.then(codes => {\n\t\t\t\tvalidSystemCodes = codes.concat(options.validationExceptions);\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\t// If the poll errors then we don't throw,\n\t\t\t\t// we just start letting any valid source\n\t\t\t\t// parameter through\n\t\t\t\tvalidSystemCodes = undefined;\n\t\t\t\toptions.log.error(`CMDB error: ${error.message}`);\n\t\t\t});\n\t}", "function fetch(){\n console.log(\"Entering fetch()\"); \n nIR = code[nPC];\n nPC++;\n return 1;\n}", "async function getCounters(){\n return new Promise((resolve,reject) => {\n fetch(baseurl+'/counters',{\n method: 'GET'\n }).then((response) => {\n const status = response.status;\n if (response.ok) {\n response.json()\n .then((obj) => { resolve( obj.map((c) => Counter.from(c)) )}) \n .catch((err) => { reject({ errors: [{ param: \"Application\", msg: \"Cannot parse server response\" }] }) }); // something else\n } else {\n // analyze the cause of error\n response.json()\n .then((obj) => { obj.status = status; reject(obj); }) // error msg in the response body\n .catch((err) => { reject({ errors: [{ param: \"Application\", msg: \"Cannot parse server response\" }] }) }); // something else\n }\n }).catch((err) => { reject({ errors: [{ param: \"Server\", msg: \"Cannot communicate\" }] }) }); // connection errors\n });\n}", "function check_code(url) {\n \tvar response = sync_request(\n 'GET',\n url\n );\n return response.statusCode;\n}", "function fetchFail() {\n}", "function fetchError()\n {\n _TimeoutHandle = setTimeout(fetch, VRS.globalOptions.aircraftListRetryInterval);\n }", "function bootstrap()\n {\n disableCRUD();\n getIp();\n \n log(\"<br>Checking API (\" + _BASEURI + \"ping) :<br>ping... (\" + Date() + \")\");\n \n doAPICall(\"ping\", null, \"GET\", \n function(response) // got ping...\n {\n var m = JSON.parse(response);\n var e = m[\"echo\"];\n log(\"<br>...\" + e[\"echo\"] + \" (\" + new Date(e[\"timestamp\"]) + \")\"); \n show(\"initial\");\n }, \n function (response) { // fail\n log(\"<br>PING FAILED. \" + _API_IS_DOWN);\n throw new Error();\n });\n \n doAPICall(\"resultcodes\",null,\"GET\",\n function(response)\n {\n resultcodes = JSON.parse(response);\n resultcodes = resultcodes[\"items\"];\n console.log(\"Retrieving resultcode list\");\n for (var i=0;i<resultcodes.length;i++)\n {\n console.log(resultcodes[i]);\n } \n \n log(\"<br>Resultcode list cached.\");\n },\n function(response)\n {\n log(\"<br>GET RESULTCODE LIST FAILED. \" + _API_IS_DOWN);\n throw new Error();\n }\n );\n }", "main()\n {\n this.getInnerLinks(this.url).then((result) => {\n \n const loop = async value => {\n let i = 0;\n let minValue = Math.min(this.limitCrawling,this.internalUrl.length);\n\n while (i < minValue) \n {\n let url = this.getNextVisitingLink();\n let result = await this.getInnerLinks(url);\n console.log('visiting internal url:'+url);\n this.setVisitedIncrement();\n i++;\n }\n }\n\n // display what was discovered in the console after the loop finishes\n loop(0).then(() => this.getData());\n });\n }", "async function submitLaunchCodes(code) {\n let requestOptions = {\n method: \"POST\",\n };\n\n const response = await fetch(\n \"https://task-escape-api.herokuapp.com/api/codes\",\n requestOptions\n );\n\n const result = await response.json();\n return result;\n}", "async runRequests() {\r\n this.running = true;\r\n while (this.requests.length !== 0) {\r\n var newReq = this.requests.shift(); // Take the beginning of array\r\n var callBack = newReq[2]; // Take the call back from the request's 3rd element\r\n var url = \"https://flask.team-project.crablab.co/\" + newReq[0]; // Take the URL and add it to base\r\n var body = newReq[1] === null ? // Make the request body checking if passed body is null\r\n { id: this.state.userID, key: \"abc123\", secret: \"def456\", access_token: this.state.accessToken } :\r\n { ...newReq[1], ...{ id: this.state.userID, key: \"abc123\", secret: \"def456\", access_token: this.state.accessToken } };\r\n await fetch(url, {\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n method: \"POST\",\r\n body: JSON.stringify(body) // new body\r\n })\r\n .then(async response => {\r\n if(response.status === 403){\r\n this.requests = [];\r\n await this.setState({\r\n badAccessToken : true\r\n })\r\n throw Error(\"Bad Access Token\");\r\n } else {\r\n return response.json();\r\n }\r\n })\r\n // eslint-disable-next-line no-loop-func\r\n .then(async (json) => {\r\n callBack(json); // Run the call back passed in from the request\r\n await this.setState({\r\n accessToken: json.new_access_token.access_token // Update the access token\r\n })\r\n document.cookie = \"accessToken=\" + json.new_access_token.access_token;\r\n })\r\n .catch((error) => {\r\n console.log(\"An error occured\" + error);\r\n })\r\n\r\n } // Empty stack -> No requests\r\n this.running = false; // It's no longer running, can make the call again from addRequests\r\n }", "function bigFetch(...args){\n //variable error for this if statement if fetch fails\n let error;\n return fetch(...args)\n .then(res => {\n if (!res.ok){\n error= { code: res.status };\n }\n return res.json();\n })\n .then(data => {\n if (error) {\n //error message returned to user if fetch fails\n error.message = data.message;\n return Promise.reject(error);\n }\n return data;\n })\n //catch block with console.log. was having issues with this earlier, seems to be resolved\n .catch(error =>{console.log(error)})\n \n}", "async function handleStatuses() {\n const regex = /Test Suites: \\d+ failed/;\n let startChecking = Date.now();\n let done = false;\n while (!done) {\n let now = Date.now();\n if (now - startChecking > 90 * 60 * 1000) {\n warn(\n \"One hour and a half have passed and the E2E jobs haven't finished yet.\",\n );\n done = true;\n continue;\n }\n\n const githubBaseURL = `https://api.github.com/repos/${danger.github.pr.base.repo.owner.login}/${danger.github.pr.base.repo.name}`;\n const statusesURL = `${githubBaseURL}/commits/${danger.github.pr.head.sha}/statuses?per_page=100`;\n\n const response = await fetch(statusesURL, {\n headers: {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n Authorization: `Bearer ${process.env.DANGER_GITHUB_API_TOKEN}`,\n },\n });\n\n const data = await response.json();\n const e2e_jobs = data.filter(job => {\n return (\n job.context === 'ci/circleci: test_e2e_ios' ||\n job.context === 'ci/circleci: test_e2e_android'\n );\n });\n if (e2e_jobs.length <= 0) {\n console.log('No e2e jobs found yet, retrying in 5 minutes.');\n await new Promise(resolve => setTimeout(resolve, 5 * 60 * 1000));\n continue;\n }\n\n const jobFinished = e2e_jobs.every(job => job.state !== 'pending');\n if (!jobFinished) {\n console.log(\"E2E jobs haven't finished yet, retrying in 5 minutes.\");\n await new Promise(resolve => setTimeout(resolve, 5 * 60 * 1000));\n continue;\n }\n\n e2e_jobs.forEach(async job => {\n const url = job.target_url;\n const components = url.split('/');\n const jobId = components[components.length - 1];\n const jobUrl = `https://circleci.com/api/v2/project/gh/facebook/react-native/${jobId}`;\n const artifactUrl = `${jobUrl}/artifacts`;\n const artifactResponse = await fetch(artifactUrl);\n const artifactData = await artifactResponse.json();\n const testLogs = artifactData.items.filter(\n item => item.path === 'tmp/test_log',\n );\n if (testLogs.length !== 1) {\n warn(\n `Can't find the E2E test log for ${job.context}. <a href=${jobUrl}>Job link</a>`,\n );\n return;\n }\n\n const logUrl = testLogs[0].url;\n const logResponseText = await fetch(logUrl);\n const logText = await logResponseText.text();\n\n if (regex.test(logText)) {\n warn(\n `E2E tests for ${job.context} failed with errors. See the <a href=\"${logUrl}\">logs for details<a/>`,\n );\n }\n });\n done = true;\n }\n}", "async requestRaw(options) {\n \n // Log the request\n let logPrefix = 'Home Connect request #' + ++this.requestCount + ': ';\n this.debug(logPrefix + options.method + ' ' + options.url);\n let startTime = Date.now();\n\n // Issue the request\n let status = 'OK';\n try {\n\n return await requestPromise(options);\n \n } catch (err) {\n\n // Status codes returned by the server have special handling\n status = err.message;\n if (err.name == 'StatusCodeError') {\n\n // Redirection is not an error when expected\n if (!options.followRedirect && err.statusCode == 302) {\n let uri = err.response.headers['location'];\n status = 'Redirect ' + uri;\n return uri;\n }\n\n // Inspect any response returned by the server\n let body = options.json ? err.response.body\n : this.parseJSON(err.response.body);\n if (body && body.error_description) {\n\n // Authorisation (OAuth) error response\n status = body.error_description + ' [' + body.error + ']';\n\n // Special handling for some authorisation errors\n switch (body.error) {\n case 'authorization_pending':\n // User has not yet completed the user interaction steps\n status = 'Authorisation pending';\n return null;\n break;\n \n case 'access_denied':\n if (body.error_description == 'Too many requests') {\n // Token refresh rate limit exceeded\n status = 'Token refresh rate limit exceeded'\n + ' (only 100 refreshes are allowed per day)';\n err.retry = true;\n break;\n }\n // fallthrough\n case 'invalid_grant':\n case 'expired_token':\n // Refresh token not valid; restart whole authorisation\n this.authInvalidate();\n break;\n \n case 'unauthorized_client':\n // There is a problem with the client\n this.authInvalidate();\n status = CLIENT_HELP_PREFIX1 + body.error_description;\n let extra = CLIENT_HELP_EXTRA[body.error_description];\n if (extra) status += CLIENT_HELP_PREFIX2 + extra;\n break;\n }\n \n } else if (body && body.error && body.error.key) {\n\n // Normal Home Connect API error format\n status = (body.error.developerMessage\n || body.error.description\n || body.error.value)\n + ' [' + body.error.key + ']';\n\n // Special handling for some API errors\n switch (body.error.key) {\n case 'invalid_token':\n // Problem with the access token\n this.tokenInvalidate();\n break;\n \n case '429':\n // Rate limit exceeded (wait Retry-After header seconds)\n let delay = err.response.headers['retry-after'];\n this.retryAfter(delay);\n err.retry = true;\n break;\n }\n }\n \n // Use the server's response for the error message\n err.message = 'Home Connect API error: ' + status;\n }\n\n // Re-throw the error unless suppressed above\n throw err;\n \n } finally {\n\n // Log completion of the request\n this.debug(logPrefix + status\n + ' +' + (Date.now() - startTime) + 'ms ');\n \n }\n }", "static get codes () {\n return {\n DONE: '200',\n RESULT: '201',\n USER_ERROR: '300',\n DEV_ERROR: '400'\n };\n }", "async getCredit(event) {\n let fetchData\n\n try {\n event.preventDefault()\n\n _this.setState(prevState => ({\n message: 'Checking BCH address...',\n }))\n\n const options = {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${_this.state.userJwt}`,\n },\n }\n fetchData = await fetch(\n `${SERVER}/apitoken/update-credit/${_this.state.id}`,\n options\n )\n\n const credit = await fetchData.json()\n console.log(`credit: ${credit}`)\n\n _this.setState(prevState => ({\n credit: credit,\n message: 'BCH address checked. Credit updated.',\n }))\n } catch (err) {\n // console.log(`fetchData: `, fetchData)\n // console.log(`fetchData.status: ${fetchData.status}`)\n\n if (fetchData.status === 409) {\n _this.setState(prevState => ({\n message: 'Wait a minute for the indexer to update.',\n }))\n return\n }\n\n console.error(`Error in getCredit(): `, err)\n _this.setState(prevState => ({\n message: err.message,\n }))\n }\n }", "function requestStatusCodeWithGET(requestedURL) {\n try {\n var connection = new java.net.URL(requestedURL).openConnection();\n connection.setDoOutput(false);\n connection.setDoInput(true);\n connection.setInstanceFollowRedirects(false);\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n connection.setRequestProperty(\"charset\", \"utf-8\");\n connection.connect();\n\n var responseCode = connection.getResponseCode();\n return responseCode;\n }\n catch (e) {\n log(\"JSON_LIBRARY: could not retreive contents, socket Exception or Server Timeout\");\n return 500;\n }\n}", "async function fetchWrapper(...args) {\n try {\n // call the IEX Cloud function with the provided args, and return the data if no problems\n let [fetchFunction, ...functionArgs] = args;\n let data = await fetchFunction(...functionArgs);\n return data;\n } catch (e) {\n if (e.response.status === 429) {\n // in the case of Too Many Requests, wait 1s and try again\n await delay(1000);\n return fetchWrapper(...args);\n } else {\n // Propogate all other errors\n throw e;\n }\n }\n}", "function fibServer() {\n console.log(x)\n document.getElementById(\"50Error\").classList.add('loaded');\n document.getElementById(\"xnumber\").classList.remove(\"inputError\");\n let url = \"http://localhost:5050/fibonacci/\" + x;\n document.getElementById(\"Loader\").classList.remove('loaded');\n fetch(url)\n .then(\n function (response) {\n if (response.status !== 200) {\n document.getElementById(\"errText\").classList.remove('loaded');\n throw response\n\n } else {\n document.getElementById(\"errText\").classList.add('loaded');\n return response.json();\n }\n })\n .then(function (data) {\n let y = data.result;\n stopLoader();\n document.getElementById(\"ynumber\").innerText = y;\n fetchResult()\n })\n .catch(error => error.text())\n .then(meaning => {\n console.log(meaning);\n stopLoader();\n let error42 = \"Server Error: \" + meaning\n document.getElementById(\"errText\").innerText = error42;\n\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: isDuplicate Check display table to make sure you don't add a movie multiple times by checking to see if the date, title, and description don't all match
function isDuplicate(row) { var dup = false; var title = $(':nth-child(2)',row).html(); var description = $(':nth-child(4)',row).html(); var date = $(':nth-child(5)',row).html(); var dt, ddes, dd; $("#displayTable").find("tr").each(function() { dt = $(':nth-child(2)',this).html(); dd = $(':nth-child(5)',this).html(); ddes = $(':nth-child(4)',this).html(); if(title == dt && description == ddes && date == dd){ dup = true; } //$(this).children("td:first").html(s); }); return dup; }
[ "function isDuplicate(widgetForm,store){\n \t\t\tfor (var x in store) {\n \t\t\t\tif (store[x].title == widgetForm.title) {\n \t\t\treturn true;\n \t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false;\n \t\t}", "function isDuplicateDocument() {\n for(var i = 0; i < $scope.meeting.documents.length; i++) {\n if($scope.meeting.documents[i].title == $scope.document) {\n return true;\n }\n }\n return false;\n }", "function testMovie() {\n let result;\n\n movieData.forEach(function (movieE, indexE) {\n if (movieE.title === newMovie.title) {\n result = false\n }\n });\n return (result === undefined)\n }", "function validate_movie(count){\n var movie_name= (document.getElementById(`movie_name_${count}`).value).trim();\n console.log(\"List of movies already entered:\",movie_list);\n var name= (document.getElementById(`name_${count}`).value).trim();\n // Validate if user has filled movie name field\n if(movie_name&&name){\n var flag=0;\n for(var i of movie_list){\n if(movie_name.toLowerCase()==i.toLowerCase()){\n flag=1;\n break;\n }\n }\n if(flag){\n alert('You have already entered '+movie_name+'\\nPlease enter a different movie name!');\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Red;\">\"You can't enter the same movie name twice!\"</p>`;\n }\n else{\n console.log(\"Movie entered by user: \"+movie_name+\", where actor/director:\",name);\n url= `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${movie_name}`;\n fetch(url).then(onConnect);\n function onConnect(response){\n response.json().then(function(result){\n var output= result.results;\n if(output.length>0){\n var flag=0;\n for(var res of output){\n if((res[\"original_title\"].toLowerCase()==movie_name.toLowerCase())){\n //console.log((res[\"original_title\"].toLowerCase()==movie_name.toLowerCase()))\n flag=1;\n id=res[\"id\"];\n title=res[\"original_title\"];\n rel_date=res[\"release_date\"];\n credit_url=`https://api.themoviedb.org/3/movie/${id}/credits?api_key=${apiKey}`;\n if(res[\"poster_path\"]==null){\n image=`https://demofree.sirv.com/nope-not-here.jpg`;\n list=`<li> <strong> Movie Title: ${title} </strong> <a href=${image} target=\"_blank\"><img src=${image}></a><br><br> <strong> Release Date: ${rel_date}</strong><br> <br></li>`;\n }\n else{\n image=`https://image.tmdb.org/t/p/w500${res[\"poster_path\"]}`;\n list=`<li> <strong> Movie Title: ${title} </strong> <a href=${image} target=\"_blank\"><img src=${image}></a><br><br> <strong> Release Date: ${rel_date}</strong><br> <br></li>`;\n }\n \n fetch(credit_url).then(onResult);\n break;\n }\n }\n if(flag==0){\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Red;\">\"No results found!\"</p>`;\n }\n }\n else{\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Red;\">\"No results found!\"</p>`;\n }\n });\n }\n\n function onResult(response){\n response.json().then(function(result){\n var entered_name=(name.toLowerCase()).trim();\n var flag_actor = 0;\n var flag_director = 0;\n var flag=0;\n var crew= result.crew;\n var cast= result.cast;\n if(flag==0){\n for(var res of crew){\n if(res[\"job\"] == 'Director'){\n director=res[\"name\"].toLowerCase()\n if(director==entered_name){\n flag_director=1;\n console.log(\"Director recognised!\");\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Green;\">\"Correct!\"</p>`;\n document.getElementById(`uList2_${count}`).innerHTML=list;\n movie=document.getElementById(`movie_name_${count}`).value;\n movie_list.push(movie);\n document.getElementById(`submit_movie_${count}`).disabled = true;\n document.getElementById(`movie_name_${count}`).disabled = true;\n count+=1;\n // Append form to ask for director/actor name\n person_quiz_form(count);\n document.getElementById(`name_${count}`).focus();\n break;\n }\n }\n }\n if(!flag_director){\n flag=1;\n console.log(\"Movie not matched for director, Actual director:\", director);\n console.log(\"\\nLooking for actor...\");\n document.getElementById(`uList2_${count}`).innerHTML=\"\"; \n }\n }\n if(flag==1){\n for(var res of cast){\n actor=res[\"name\"].toLowerCase();\n if(actor==entered_name){\n flag_actor=1;\n console.log(\"Actor Recognised!\");\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Green;\">\"Correct!\"</p>`;\n document.getElementById(`uList2_${count}`).innerHTML=list;\n movie=document.getElementById(`movie_name_${count}`).value;\n movie_list.push(movie);\n document.getElementById(`submit_movie_${count}`).disabled = true;\n document.getElementById(`movie_name_${count}`).disabled = true;\n count+=1;\n // Append quiz form to ask for crew/cast name\n person_quiz_form(count);\n document.getElementById(`name_${count}`).focus();\n break;\n }\n }\n if((!flag_director)&&!(flag_actor)){\n console.log(\"Movie not matched for actor/director\");\n document.getElementById(`movie_response_${count}`).innerHTML=`<p style=\"color:Red;\">\"Your answer is wrong!\"</p>`;\n document.getElementById(`uList2_${count}`).innerHTML=\"\";\n }\n }\n });\n } \n } \n }\n else{\n alert('Please enter both movie name and director/actor name!');\n }\n}", "function isTitleDuplicate(title, $tabSet) {\n var $tabs = $tabSet.children(\".tab\");\n for (var i = 0; i < $tabs.length; i++) {\n if ($tabs.eq(i).text().trim() === title.trim()) {\n return true;\n }\n }\n return false;\n }", "function isDuplicate(newSong){\n return songs.some(function(song) {\n return song.title === newSong.title &&\n song.artist === newSong.artist &&\n song.album === newSong.album;\n });\n\n}//Dpmt a;;pw tje iser tp add spmgs wotj a b;aml srjtist or title", "function approveNewTitle() {\n //if title is empty, deny and alert user\n if (newTitle !== '') {\n titleApproved = true\n } else {\n $('#alertText').text(`*title can not be blank`)\n return\n }\n console.log(displayedIndex)\n //if title is not empty, and title matches the current displayed title, allow it and return\n if (titleApproved && displayedIndex !== null && memoList[displayedIndex].title.toLocaleLowerCase().trim() === newTitle.toLowerCase().trim()) {\n titleApproved = true\n return\n //if title matches a different index location, deny to avoid duplicate title names and alert user to\n } else {\n for (let i = 0; i < memoList.length; i++) {\n if (memoList[i].title.toLocaleLowerCase().trim() === newTitle.toLowerCase().trim()) {\n titleApproved = false\n console.log(`The title: '${memoList[i].title}', already exists at index ${i}`)\n $('#alertText').text(`\"${newTitle}\" already exists`)\n }\n }\n }\n}", "function areSameMovie(firstMovie, secondMovie){\n if(firstMovie.id == secondMovie.id){\n return true;\n }\n else{\n return false;\n }\n }", "function areSameMovie(firstMovie, secondMovie){\n if(firstMovie.id == secondMovie.id){\n return true;\n }\n else{\n return false;\n }\n }", "function checkduplicate(text)\n{\n\tvar i = 0;\n\tvar len = groupStore.length;\n\twhile (i < len)\n\t{\n\t\tvar str = groupStore[i]._title;\n\t\tif(text.toLowerCase()==str.toLowerCase())\n\t\t{\n\t\t\tdocument.getElementById('errorgroup').innerHTML=\"This category name already exists.\";\n\t\t\treturn true;\n\t\t}\n\t\ti++;\n\t}\n\treturn false;\n}", "function titleEntered(movieQuery) {\n if (movieQuery.length > 0) {\n return true;\n }\n return false;\n }", "function checkDuplicates(obj, store){\n console.log(\"checkDuplicates\");\n store.openCursor().onsuccess = function(e){\n console.log(\"cursor successful\");\n var cursor = e.target.result;\n console.log(cursor);\n if(cursor){\n console.log(\"Cursor\");\n if (cursor.value.lectureID == obj.lectureID && cursor.value.slideID == obj.slideID && cursor.value.noteID == obj.noteID){\n console.log(\"SETTING DUPLICATES TO TRUE\");\n displayActionFailure(\"Record already exists\");\n displayNotes(store);\n return;\n }\n cursor.continue();\n }\n else if (cursor == null){\n console.log(\"undefined\");\n addRecord(obj,store);\n return;\n }\n }\n }", "function showListPatientDuplicate( rootElement, validate )\r\n{\r\n\tvar message = $(rootElement).find('message').text();\r\n\tvar patients = $(rootElement).find('patient');\r\n\t\r\n\tvar sPatient = \"\";\r\n $( patients ).each( function( i, patient ) {\r\n\t\t\tsPatient += \"<hr style='margin:5px 0px;'><table>\";\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_system_id + \"</td><td>\" + $(patient).find('systemIdentifier').text() + \"</td></tr>\" ;\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_full_name + \"</td><td>\" + $(patient).find('fullName').text() + \"</td></tr>\" ;\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_gender + \"</td><td>\" + $(patient).find('gender').text() + \"</td></tr>\" ;\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_date_of_birth + \"</td><td>\" + $(patient).find('dateOfBirth').text() + \"</td></tr>\" ;\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_age + \"</td><td>\" + $(patient).find('age').text() + \"</td></tr>\" ;\r\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_phone_number + \"</td><td>\" + $(patient).find('phoneNumber').text() + \"</td></tr>\";\r\n \t\r\n\t\t\tvar identifiers = $(patient).find('identifier');\r\n\r\n \tif( identifiers.length > 0 )\r\n \t{\r\n \t\tsPatient += \"<tr><td colspan='2' class='bold'>\" + i18n_patient_identifiers + \"</td></tr>\";\r\n\r\n $( identifiers ).each( function( i, identifier )\r\n\t\t\t\t{\r\n \t\t\tsPatient +=\"<tr class='identifierRow'>\"\r\n \t\t\t\t+\"<td class='bold'>\" + $(identifier).find('name').text() + \"</td>\"\r\n \t\t\t\t+\"<td>\" + $(identifier).find('value').text() + \"</td>\t\"\r\n \t\t\t\t+\"</tr>\";\r\n \t\t});\r\n \t}\r\n\t\t\t\r\n \tvar attributes = $(patient).find('attribute');\r\n\r\n \tif( attributes.length > 0 )\r\n \t{\r\n \t\tsPatient += \"<tr><td colspan='2' class='bold'>\" + i18n_patient_attributes + \"</td></tr>\";\r\n\r\n $( attributes ).each( function( i, attribute ) {\r\n \t\t\tsPatient +=\"<tr class='attributeRow'>\"\r\n \t\t\t\t+\"<td class='bold'>\" + $(attribute).find('name').text() + \"</td>\"\r\n \t\t\t\t+\"<td>\" + $(attribute).find('value').text() + \"</td>\t\"\r\n \t\t\t\t+\"</tr>\";\r\n \t\t});\r\n \t}\r\n\r\n \tsPatient += \"<tr><td colspan='2'><input type='button' id='\"+ $(patient).find('id').first().text() + \"' value='\" + i18n_edit_this_patient + \"' onclick='showUpdatePatientForm(this.id)'/></td></tr>\";\r\n \tsPatient += \"</table>\";\r\n\t\t});\r\n\t\t\r\n\t\tvar result = i18n_duplicate_warning;\r\n\r\n\t\tif( !validate )\r\n\t\t{\r\n\t\t\tresult += \"<input type='button' value='\" + i18n_create_new_patient + \"' onClick='removeDisabledIdentifier( );addPatient();'/>\";\r\n\t\t\tresult += \"<br><hr style='margin:5px 0px;'>\";\r\n\t\t}\r\n\r\n\t\tresult += \"<br>\" + sPatient;\r\n $('#resultSearchDiv' ).html( result );\r\n $('#resultSearchDiv' ).dialog({\r\n\t\t\ttitle: i18n_duplicated_patient_list,\r\n\t\t\tmaximize: true, \r\n\t\t\tclosable: true,\r\n\t\t\tmodal:true,\r\n\t\t\toverlay:{background:'#000000', opacity:0.1},\r\n\t\t\twidth: 800,\r\n\t\t\theight: 400\r\n\t\t});\r\n}", "function checkForDuplicateFood(data) {\n console.log(\"checking for duplicates...\");\n console.log(\"Input food was: \", addedFood);\n //Retrieve Firebase food data for the specific movie that was passed into the function\n var foodObject = data.val();\n var keys = Object.keys(foodObject);\n\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n var foodItem = foodObject[k].food;\n console.log(\"current food item\", foodItem);\n if (nameClean(addedFood) == foodItem) {\n console.log(\"A:\", addedFood);\n console.log(\"B:\", foodItem);\n uniqueToggle = false;\n return;\n }\n }\n uniqueToggle = true;\n }", "checkDupe() {\n let occurrences = this.props.occurrences;\n let habit = this.state.currentHabit;\n let time = JSON.parse(JSON.stringify(this.state.habitTime));\n let quantity = this.state.quantity;\n let found = false;\n\n occurrences.forEach(item => {\n if (item.timestamp.slice(0, 10) === time.slice(0, 10)) {\n found = true;\n }\n });\n\n if (found) {\n alert('Please make any updates to existing logs by updating your table');\n } else {\n this.props.logHabit(habit, time, quantity);\n }\n }", "function movieAlreadyInWatchHistory(mId){\n var hasFound = false\n $.each(watchHistory, function( index, value ) {\n if(value == mId)\n hasFound = true;\n });\n return hasFound;\n}", "function addMovie(movieTitle) {\n if(movies.has(movieTitle))\n console.log(`Error! - '${movieTitle}' already exists.`);\n else\n {\n movies.add(movieTitle);\n console.log(`${movieTitle} is successfully added to the Set.`);\n }\n}", "function showListPatientDuplicate( rootElement, validate )\n{\n\tvar message = jQuery(rootElement).find('message').text();\n\tvar patients = jQuery(rootElement).find('patient');\n\t\n\tvar sPatient = \"\";\n\tjQuery( patients ).each( function( i, patient )\n {\n\t\t\tsPatient += \"<hr style='margin:5px 0px;'><table>\";\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_system_id + \"</td><td>\" + jQuery(patient).find('systemIdentifier').text() + \"</td></tr>\" ;\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_full_name + \"</td><td>\" + jQuery(patient).find('fullName').text() + \"</td></tr>\" ;\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_gender + \"</td><td>\" + jQuery(patient).find('gender').text() + \"</td></tr>\" ;\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_date_of_birth + \"</td><td>\" + jQuery(patient).find('dateOfBirth').text() + \"</td></tr>\" ;\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_age + \"</td><td>\" + jQuery(patient).find('age').text() + \"</td></tr>\" ;\n\t\t\tsPatient += \"<tr><td class='bold'>\" + i18n_patient_blood_group + \"</td><td>\" + jQuery(patient).find('bloodGroup').text() + \"</td></tr>\";\n \t\n\t\t\tvar identifiers = jQuery(patient).find('identifier');\n \tif( identifiers.length > 0 )\n \t{\n \t\tsPatient += \"<tr><td colspan='2' class='bold'>\" + i18n_patient_identifiers + \"</td></tr>\";\n\n \t\tjQuery( identifiers ).each( function( i, identifier )\n\t\t\t\t{\n \t\t\tsPatient +=\"<tr class='identifierRow'>\"\n \t\t\t\t+\"<td class='bold'>\" + jQuery(identifier).find('name').text() + \"</td>\"\n \t\t\t\t+\"<td>\" + jQuery(identifier).find('value').text() + \"</td>\t\"\t\n \t\t\t\t+\"</tr>\";\n \t\t});\n \t}\n\t\t\t\n \tvar attributes = jQuery(patient).find('attribute');\n \tif( attributes.length > 0 )\n \t{\n \t\tsPatient += \"<tr><td colspan='2' class='bold'>\" + i18n_patient_attributes + \"</td></tr>\";\n\n \t\tjQuery( attributes ).each( function( i, attribute )\n\t\t\t\t{\n \t\t\tsPatient +=\"<tr class='attributeRow'>\"\n \t\t\t\t+\"<td class='bold'>\" + jQuery(attribute).find('name').text() + \"</td>\"\n \t\t\t\t+\"<td>\" + jQuery(attribute).find('value').text() + \"</td>\t\"\t\n \t\t\t\t+\"</tr>\";\n \t\t});\n \t}\n \tsPatient += \"<tr><td colspan='2'><input type='button' id='\"+ jQuery(patient).find('id').first().text() + \"' value='\" + i18n_edit_this_patient + \"' onclick='showUpdatePatientForm(this.id)'/></td></tr>\";\n \tsPatient += \"</table>\";\n\t\t});\n\t\t\n\t\tvar result = i18n_duplicate_warning;\n\t\tif( !validate )\n\t\t{\n\t\t\tresult += \"<input type='button' value='\" + i18n_create_new_patient + \"' onClick='removeDisabledIdentifier( );addPatient();'/>\";\n\t\t\tresult += \"<br><hr style='margin:5px 0px;'>\";\n\t\t}\n\t\t\n\t\tresult += \"<br>\" + sPatient;\n\t\tjQuery('#resultSearchDiv' ).html( result );\n\t\tjQuery('#resultSearchDiv' ).dialog({\n\t\t\ttitle: i18n_duplicated_patient_list,\n\t\t\tmaximize: true, \n\t\t\tclosable: true,\n\t\t\tmodal:true,\n\t\t\toverlay:{background:'#000000', opacity:0.1},\n\t\t\twidth: 800,\n\t\t\theight: 400\n\t\t});\n}", "function isDuplicate() {\n if (vm.uidata == undefined)\n return false;\n for (var i = 0; i < vm.uidata.length; i++) {\n var incomeSource = vm.uidata[i].incomeSource;\n for (var j = 0; j < vm.uidata.length; j++) {\n if (i != j) {\n if (incomeSource == vm.uidata[j].incomeSource) {\n alert(\"Multiple sources of the same income type cannot be selected\");\n return;\n }\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fixup, rename, and retype action targetTableId to targetCollectionId
function fixActionTargets() { tables['actions'].forEach(function(row) { row.targetCollectionId = row._target.slice(0,4) delete row.targetTableId }) }
[ "async function remapForeignKeys (tableName, foreignKeysMap, targetDb, sqlPool) {\r\n\r\n if (!foreignKeysMap) {\r\n console.log(tableName + \" has no foreign keys.\"); \r\n return;\r\n }\r\n\r\n const foreignKeys = Object.keys(foreignKeysMap);\r\n if (foreignKeys.length ==- 0) {\r\n console.log(tableName + \" has no foreign keys.\");\r\n return;\r\n }\r\n\r\n console.log(\"Remapping foreign keys for \" + tableName);\r\n \r\n const thisCollection = targetDb.collection(tableName);\r\n const records = await thisCollection.find().toArray();\r\n console.log(\"Updating \" + records.length + \" records.\");\r\n\r\n for (const record of records) {\r\n const foreignKeyUpdates = {};\r\n let updatesMade = false;\r\n\r\n for (const foreignKey of foreignKeys) {\r\n if (!record[foreignKey]) {\r\n // No value.\r\n continue;\r\n }\r\n const otherTableName = foreignKeysMap[foreignKey].table;\r\n const otherTableRemap = targetDb.collection(otherTableName + '-pkremap');\r\n const remap = await otherTableRemap.findOne({ _id: record[foreignKey] });\r\n foreignKeyUpdates[foreignKey] = remap.new;\r\n updatesMade = true;\r\n }\r\n\r\n if (!updatesMade) {\r\n continue;\r\n }\r\n\r\n thisCollection.update({ _id: record._id }, { $set: foreignKeyUpdates });\r\n }\r\n}", "function fixLinkTargets() {\n tables['links'].forEach(function(row) {\n row.toCollectionId = row._to.slice(0,4)\n row.fromCollectionId = row._from.slice(0,4)\n delete row.toTableId\n delete row.fromTableId\n })\n}", "renameTable(tableName, to) {\n this.pushQuery('rename table ' +\n this.formatter.wrap(tableName) +\n ' to ' +\n this.formatter.wrap(to));\n }", "renameTable(tableName, to) {\n this.pushQuery(\n `exec sp_rename ${this.formatter.parameter(tableName)}, ${this.formatter.parameter(to)}`\n );\n }", "renameTable(tableName, to) {\n this.pushQuery(`rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap(to)}`);\n }", "renamePrimaryKey() {}", "function renameId(src, id, newId, verbose = false) {\n var ctx = new esrefactor.Context(src);\n if(verbose) console.log(\"Getting index for \" + id);\n var index = getIdIndex(src, id, verbose);\n var idObj = ctx.identify(index);\n\n return ctx.rename(idObj, newId);\n}", "_mapActions( actions, target, storeId ) {\n\t\tfor ( let act in actions ) {\n\t\t\tif ( actions.hasOwnProperty(act) ) {\n\t\t\t\tif ( is.object(actions[act]) ) {// hirarchised actions\n\t\t\t\t\t\n\t\t\t\t\tif ( target[act] && !is.object(target[act]) )\n\t\t\t\t\t\tconsole.warn(\"RS : Actions namespace is mapped over an existing function !\", storeId, act);\n\t\t\t\t\t\n\t\t\t\t\ttarget[act] = target[act] || { __targetStores: 0 };\n\t\t\t\t\tthis._mapActions(actions[act], target[act]);\n\t\t\t\t\ttarget[act].__targetStores++;\n\t\t\t\t}\n\t\t\t\telse if ( target.hasOwnProperty(act) )\n\t\t\t\t\ttarget[act].__targetStores++;\n\t\t\t\telse {\n\t\t\t\t\tif ( is.object(target[act]) )\n\t\t\t\t\t\tconsole.warn(\"RS : Action is mapped over existing namespace !\", storeId, act);\n\t\t\t\t\ttarget[act] = this.dispatch.bind(this, act);\n\t\t\t\t\ttarget[act].__targetStores = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function in_RenamePKeyIndex(oldPTableName, newPTableName) {\r\n\r\n\tvar indexDivId = \"IND_\" + oldPTableName;\r\n\tvar indexDiv = document.getElementById(indexDivId);\r\n\t\r\n\tif (indexDiv == null) // don't have index, yet\r\n\t\treturn;\r\n\t\r\n\tvar columnHashTable = indexDiv.columnHashTable;\r\n\tvar oldIndexName = \"PK_\" + oldPTableName;\r\n\tvar newIndexName = \"PK_\" + newPTableName;\r\n\t\r\n\tvar pKeyArray = columnHashTable[oldIndexName]; \r\n\tdelete columnHashTable[oldIndexName];\r\n\tcolumnHashTable[newIndexName] = pKeyArray;\r\n}", "function buildActionFromCollection(collection, action){\n var actionToReturn = action !== null && action !== undefined ? action : {};\n actionToReturn.id = collection.id;\n actionToReturn.name = collection.name;\n actionToReturn.description = collection.description;\n return actionToReturn;\n}", "function fix_sub_sortable_target(sortable_item){\n var addSortablebutton = sortable_item.find('.add-sortable[data-target]');\n var old_target = addSortablebutton.attr('data-target');\n //if a sub-sortable exists..\n if(addSortablebutton.length){\n //define the new target id.\n var new_target = old_target.split('_').slice(0,1) +'_'+Math.floor(Math.random() * 1000000000);\n //set the target and respective id to match.\n addSortablebutton.attr('data-target',new_target);\n sortable_item.find(old_target).attr('id',new_target.substr(1));\n }\n }", "function in_RenameFKeyIndex(oldTableName, newTableName) {\r\n\r\n\tvar indexDivId = \"IND_\" + oldTableName;\r\n\tvar indexDiv = document.getElementById(indexDivId);\r\n\t\r\n\tif (indexDiv == null) // don't have index, yet\r\n\t\treturn;\r\n\t\r\n\tvar columnHashTable = indexDiv.columnHashTable;\r\n\t\r\n\tfor (var property in columnHashTable) {\r\n\t\tvar indexName = property;\r\n\t\t\r\n\t\tvar i = indexName.indexOf('_');\r\n\t\tvar chkStr = indexName.substring(0, i);\r\n\r\n\t\tif (chkStr == \"FK\") {\r\n\t\t\r\n\t\t\tvar j = indexName.indexOf('__');\r\n\t\t\tvar parentTableName = indexName.substring(i+1, j);\r\n\t\t\tvar childTableName = indexName.substring(j+2);\r\n\r\n\t\t\tif (childTableName == oldTableName) {\r\n\t\t\t\r\n\t\t\t\tvar fKeyArray = columnHashTable[indexName]; //save it to temp\r\n\t\t\t\tdelete columnHashTable[indexName];\t\t\t // delete the old one\r\n\t\t\t\tindexName = \"FK_\" + parentTableName + \"__\" + newTableName;\r\n\t\t\t\tcolumnHashTable[indexName] = fKeyArray;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\t\r\n\t}\t\r\n\t\r\n}", "visitAlterTableAction(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "undoAll(collection) {\n const ids = Object.keys(collection.changeState);\n const { remove, upsert } = ids.reduce((acc, id) => {\n const changeState = acc.chgState[id];\n switch (changeState.changeType) {\n case ChangeType.Added:\n acc.remove.push(id);\n break;\n case ChangeType.Deleted:\n const removed = changeState.originalValue;\n if (removed) {\n acc.upsert.push(removed);\n }\n break;\n case ChangeType.Updated:\n acc.upsert.push(changeState.originalValue);\n break;\n }\n return acc;\n }, \n // entitiesToUndo\n {\n remove: [],\n upsert: [],\n chgState: collection.changeState,\n });\n collection = this.adapter.removeMany(remove, collection);\n collection = this.adapter.upsertMany(upsert, collection);\n return { ...collection, changeState: {} };\n }", "function in_RenameChildFKeyIndex(oldPTableName, newPTableName, cTableName) {\r\n\t\r\n\tvar indexDivId = \"IND_\" + cTableName;\r\n\tvar indexDiv = document.getElementById(indexDivId);\r\n\t\r\n\tif (indexDiv == null) // don't have index, yet\r\n\t\treturn;\r\n\t\r\n\tvar columnHashTable = indexDiv.columnHashTable;\r\n\tvar oldIndexName = \"FK_\" + oldPTableName + \"__\" + cTableName;\r\n\tvar newIndexName = \"FK_\" + newPTableName + \"__\" + cTableName;\r\n\t\r\n\tvar pKeyArray = columnHashTable[oldIndexName]; \r\n\tdelete columnHashTable[oldIndexName];\r\n\tcolumnHashTable[newIndexName] = pKeyArray;\r\n\t\r\n\treturn true;\r\n}", "visitAlterByRenameTable(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function tb_RenameTable(tableName, newTableName) {\r\n\r\n\tvar tableDiv = document.getElementById(tableName);\r\n\t\r\n\t//////////////\r\n\t// table\r\n\t//////////////\r\n\r\n\ttableDiv.id = newTableName;\r\n\ttableDiv.name = newTableName;\r\n\r\n\t// relationship\r\n\ttb_NotifyParents(tableDiv, tableName, newTableName);\r\n\ttb_NotifyChildren(tableDiv, tableName, newTableName);\r\n\r\n\r\n\t//////////////\r\n\t// indexes\r\n\t//////////////\r\n\r\n\t// pkey index\r\n\tin_RenamePKeyIndex(tableName, newTableName);\r\n\r\n\t// fkey index for this table\r\n\tin_RenameFKeyIndex(tableName, newTableName);\r\n\r\n\t// fkey indexes for the children tables\r\n\tvar childArray = tableDiv.childArray;\r\n\tfor (var i=0;i<childArray.length;i++)\r\n\t\tin_RenameChildFKeyIndex(tableName, newTableName, childArray[i]);\r\n\r\n\t// then, indexDiv ID\r\n\tin_RenameIndexDivId(tableName, newTableName);\r\n\t\r\n\treturn true;\r\n\t\r\n}", "function MigrateTargetFixup( migrateSelect )\n{\n\tif ( migrateSelect == null )\n\t{\n\t\treturn;\n\t}\n\n\tvar victimID = migrateSelect.options[ migrateSelect.selectedIndex ].value;\n\n\tif ( victimID > 0 )\n\t{\n\t\t$('publish_anchor').href = g_szBaseURL + \"/apps/publishing/\" + victimID;\n\t}\n}", "renameColumn(from, to) {\n // Remove quotes around tableName\n const tableName = this.tableName().slice(1, -1)\n return this.pushQuery(Trigger.renameColumnTrigger(tableName, from, to));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The time elapsed, in seconds, after the request leaves the load balancer until a response from the target is received.
metricTargetResponseTime(props) { try { jsiiDeprecationWarnings.print("aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer#metricTargetResponseTime", "Use ``ApplicationLoadBalancer.metrics.targetResponseTime`` instead"); jsiiDeprecationWarnings.aws_cdk_lib_aws_cloudwatch_MetricOptions(props); } catch (error) { if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") { Error.captureStackTrace(error, this.metricTargetResponseTime); } throw error; } return this.metrics.targetResponseTime(props); }
[ "elapsed() {\r\n var _a;\r\n if (this._startTime) {\r\n const endTime = (_a = this._stopTime) !== null && _a !== void 0 ? _a : Date.now();\r\n return endTime - this._startTime;\r\n }\r\n else {\r\n return 0;\r\n }\r\n }", "_getLapElapsed() {\n if(this.lastLap) {\n return Date.now() - this.lastLap;\n }\n\n return 0;\n }", "function timeRequest() {\n const before = getTime();\n\n const sucessful = sendRequest();\n\n const difference = getTimeDifference(before);\n\n return difference;\n}", "function timeoutLength(){\n\n var ms = Math.floor( (self.endpoint.val - self.time()) * 1000 );\n\n if (self.currentRate == 0.5) return (ms * 2);\n if (self.currentRate == 1 ) return (ms);\n if (self.currentRate == 1.5) return Math.floor(ms * .66);\n \n return ms;\n }", "getResponseRetrievalTime() {\n return this.#responseRetrievalTime;\n }", "get timeRemaining() {\n \n // compute time left since start of judging\n return Math.max(this.time_limit - (new Date() - this.time_start), 1);\n \n }", "elapsed (endTime) {\n return (maybeTime(this, endTime) - this.start) / 1000\n }", "static get LOAD_TIMEOUT_MS() {\n return 15000;\n }", "timeRemaining(reqTimeStamp) {\n let endTime= reqTimeStamp + this.validationWindow;\n let now = parseInt(new Date().getTime()/1000);\n return (endTime - now)\n }", "get elapsedTime() {\n if(this.status === Action.RUNNING){\n now() - this.startedTime\n } else {\n return 0\n }\n }", "function getLag () {\n //.. when we should have arrived at a page \n correctTime = getTime(getCurrentPage());\n var elapsed = getElapsed();\n return correctTime - elapsed;\n }", "get uptime() {\n if (this._state === exports.ClientState.ACTIVE\n && this._currentConnectionStartTime) {\n return Date.now() - this._currentConnectionStartTime;\n }\n else {\n return 0;\n }\n }", "lifeTime(client, peerConnectionLog) {\n const lifeTime\n = peerConnectionLog[peerConnectionLog.length - 1].timestamp - peerConnectionLog[0].timestamp;\n\n return lifeTime > 0 ? lifeTime : undefined;\n }", "get timeRemaining() {\n return (this.next > Date.now()) ? this.next - Date.now() : 0;\n }", "elapsed(endTime) {\n return (maybeTime(this, endTime) - this.start) / 1000;\n }", "_tick() {\n const now = Date.now();\n const elapsed = now - this._lastTime;\n this._lastTime = now;\n return elapsed;\n }", "get promiseDuration () {\n if (!this.promise || !this.promise.settled) return undefined;\n return nanoDiff(this.promise.endTime, this.startTime);\n }", "requestTimeout() { return 3 * 60000; }", "getElapsedTime() {\n return this.timer.elapsedTime();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts coordinates of one sprite to another.
function spritePointToSprite(point, sprite, toSprite) { return svgPointToSprite(spritePointToSvg(point, sprite), toSprite); }
[ "function spritePointToSprite(point, sprite, toSprite) {\n return svgPointToSprite(spritePointToSvg(point, sprite), toSprite);\n }", "function spritePointToSprite(point, sprite, toSprite) {\r\n return svgPointToSprite(spritePointToSvg(point, sprite), toSprite);\r\n}", "function sprite (topleft_x, topleft_y, bottomright_x, bottomright_y, x_off, y_off) {\n\n this.topleft_x = topleft_x;\n\n this.topleft_y = topleft_y;\n\n this.bottomright_x = bottomright_x;\n\n this.bottomright_y = bottomright_y;\n\n this.x_off = x_off;\n\n this.y_off = y_off;\n\n this.getX = function () {\n\n return topleft_x;\n\n }\n\n this.getY = function () {\n\n return topleft_y;\n\n }\n\n this.getW = function () {\n\n return (this.bottomright_x + 1) - this.topleft_x;\n\n }\n\n this.getH = function () {\n\n return (this.bottomright_y + 1) - this.topleft_y;\n\n }\n\n}", "translate(other) {\n assertParameters(arguments, Coordinate);\n \n return new Coordinate(this._x + other.x, this._y + other.y);\n }", "resetSpritePosition() {\n player.sprite.position.x = 201\n player.sprite.position.y = 415\n friend.sprite.position.x = 190\n friend.sprite.position.y = 392\n }", "function svgRectToSprite(rect, sprite) {\r\n var p1 = svgPointToSprite(rect, sprite);\r\n var p2 = svgPointToSprite({ x: rect.x + rect.width, y: rect.y + rect.height }, sprite);\r\n return { x: p1.x, y: p1.y, width: p2.x - p1.x, height: p2.y - p1.y };\r\n}", "function svgRectToSprite(rect, sprite) {\n var p1 = svgPointToSprite(rect, sprite);\n var p2 = svgPointToSprite({\n x: rect.x + rect.width,\n y: rect.y + rect.height\n }, sprite);\n return {\n x: p1.x,\n y: p1.y,\n width: p2.x - p1.x,\n height: p2.y - p1.y\n };\n }", "constructor(sprite, x, y) {\n this.sprite = sprite;\n this.x = x;\n this.y = y;\n }", "function svgRectToSprite(rect, sprite) {\n var p1 = svgPointToSprite(rect, sprite);\n var p2 = svgPointToSprite({\n x: rect.x + rect.width,\n y: rect.y + rect.height\n }, sprite);\n return {\n x: p1.x,\n y: p1.y,\n width: p2.x - p1.x,\n height: p2.y - p1.y\n };\n}", "function svgRectToSprite(rect, sprite) {\n var p1 = svgPointToSprite(rect, sprite);\n var p2 = svgPointToSprite({ x: rect.x + rect.width, y: rect.y + rect.height }, sprite);\n return { x: p1.x, y: p1.y, width: p2.x - p1.x, height: p2.y - p1.y };\n}", "static translate(dst, src, x, y) {\n const a00 = src[0],\n a01 = src[1],\n a02 = src[2],\n a10 = src[3],\n a11 = src[4],\n a12 = src[5],\n a20 = src[6],\n a21 = src[7],\n a22 = src[8];\n\n dst[0] = a00;\n dst[1] = a01;\n dst[2] = a02;\n\n dst[3] = a10;\n dst[4] = a11;\n dst[5] = a12;\n\n dst[6] = x * a00 + y * a10 + a20;\n dst[7] = x * a01 + y * a11 + a21;\n dst[8] = x * a02 + y * a12 + a22;\n return dst;\n }", "function setPos(Sprite, x, y) {\n Sprite.position.set(x,y)\n}", "function convertPosToCoords(x,y) {\n x /= map_w\n y /= map_h\n x = (Math.round(x * 10000) / 100).toPrecision(4)\n y = (Math.round(y * 10000) / 100).toPrecision(4)\n return [x,y]\n}", "function moveSprite( sprite, new_x, new_y ) {\n\tcreatejs.Tween.get( sprite.position ).to({ x: new_x, y: new_y }, 200, createjs.Ease.backOut );\n}", "_scaledCoordinates(xPos, yPos) {\n // Mandatory in case of resize :'(\n this.setCurrentGameWindow(document.querySelector('iframe'));\n\n const scaledX = xPos / (this.baseGameWindow.width / this.gameWindow.width);\n const scaledY = yPos / (this.baseGameWindow.height / this.gameWindow.height);\n\n const { x, y } = this._positionToRelative(scaledX, scaledY);\n\n return { x: Math.round(x), y: Math.round(y) };\n }", "function translatePoints(coordinates, x, y) {\n for (i = 0; i<coordinates.x_values.length; i++) {\n coordinates.x_values[i] = coordinates.x_values[i] + x;\n coordinates.y_values[i] = 1 - (coordinates.y_values[i] + y);\n }\n}", "adjustSprite(sprite){\n sprite.width = sprite.width * this.scaleFactor;\n sprite.height = sprite.height * this.scaleFactor;\n }", "function newSpriteCords(x,y,w,h){\n spriteCords.x = x;\n spriteCords.y = y;\n spriteCords.w = w;\n spriteCords.h = h;\n }", "update () {\n rect(this.position.x, this.position.y, this.position.width, this.position.height);\n rect(this.position2.x, this.position2.y, this.position2.width, this.position2.height);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
open the dropdown without visiting parent link
function openDropdown(e){ // if has 'closed' class... if(hasClass(this, 'closed')){ // prevent link from being visited e.preventDefault(); // remove 'closed' class to enable link this.className = this.className.replace('closed', ''); // add 'open' close this.className = this.className + ' open'; } }
[ "function domain_toggle() {\n $('.dropdown-submenu a.dropdown-title').on(\"click\", function(d){\n $(this).parent().siblings().children().filter('ul').hide();\n $(this).next('ul').toggle();\n d.stopPropagation();\n d.preventDefault();\n });\n }", "function show() {\n if (!$(dropdown).hasClass('open') && !dropdown_disabled) {\n $('>[data-toggle=\"dropdown\"]', dropdown).trigger('click.bs.dropdown');\n }\n }", "dropdownClicked(event){\r\n if(event.data.parent.showingAssignments){\r\n event.data.parent.showingAssignments = false\r\n $('#'+event.data.parent.classesDiv).css(\"visibility\", \"hidden\")\r\n }\r\n else{\r\n event.data.parent.showingAssignments = true\r\n $('#'+event.data.parent.classesDiv).css(\"visibility\", \"visible\")\r\n }\r\n }", "function linkDropdown() { $('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); }); $(document.body).on('click', '[data-toggle=\"dropdown\"]', function () { if (!$(this).parent().hasClass('open') && this.href && this.href != '#') { window.location.href = this.href; } }); }", "open() {\n // var _this = this;\n /**\n * Fires to close other open dropdowns\n * @event Dropdown#closeme\n */\n this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id'));\n this.$anchor.addClass('hover')\n .attr({'aria-expanded': true});\n // this.$element/*.show()*/;\n this._setPosition();\n this.$element.addClass('is-open')\n .attr({'aria-hidden': false});\n\n if(this.options.autoFocus){\n var $focusable = Foundation.Keyboard.findFocusable(this.$element);\n if($focusable.length){\n $focusable.eq(0).focus();\n }\n }\n\n if(this.options.closeOnClick){ this._addBodyHandler(); }\n\n /**\n * Fires once the dropdown is visible.\n * @event Dropdown#show\n */\n this.$element.trigger('show.zf.dropdown', [this.$element]);\n }", "dropdownClicked() {\n this.handleChildDisplay(!this.state.displayChild)\n }", "function parentLink(){\n\t\t$('#affiliates--mob').click(function(e){\n\t\t\tif(isMobile()){\n\t\t\t\t$('.open-open__list').addClass('hidden');\n\t\t\t\t$('#affiliates--mob-menu').removeClass('hidden');\n\t\t\t}\n\t\t})\n\t\t$('.sub-menu--mob .affiliate__pretitle').click(function(e){\n\t\t\t$('.open-open__list').removeClass('hidden');\n\t\t\t$('.sub-menu--mob').addClass('hidden');\n\t\t})\n\n\t\t$('#advertises--mob').click(function(e){\n\t\t\tif(isMobile()){\n\t\t\t\t$('.open-open__list').addClass('hidden');\n\t\t\t\t$('#advertises--mob-menu').removeClass('hidden');\n\t\t\t}\n\t\t})\n\t\t$('.sub-menu--mob .affiliate__pretitle').click(function(e){\n\t\t\t$('.open-open__list').removeClass('hidden');\n\t\t\t$('.sub-menu--mob').addClass('hidden');\n\t\t})\n\t}", "function showDropdown() {\n\t$('.dropdown-toggle').click(function(){\n\t\tvar dropdown = $(this).parent().find('.m-dropdown-menu');\n\t\tif( dropdown.css('display') == 'none' )\n\t\t\tdropdown.show();\n\t\telse\n\t\t\tdropdown.hide();\n\n\t\t// clicks out the dropdown\n\t $('body').click(function(event){\n\t \tif(!$(event.target).is('.m-dropdown-menu a')) {\n\t \t\t$(this).find('.m-dropdown-menu').hide();\n\t \t}\n\t });\n\t\tevent.stopPropagation();\n\t});\n}", "open() {\n this._shouldBeOpen = true;\n if (this.disabled || !this.collapsed || this.target.children.length === 0) {\n return;\n }\n // if no drop-down width is set, the drop-down will be as wide as the autocomplete input;\n this.target.width = this.target.width || (this.parentElement.clientWidth + 'px');\n this.target.open(this.settings);\n this.highlightFirstItem();\n }", "open () {\n\t\t\tthis.el.classList.add('dropdown_open');\n\t\t this.trigger(\"open\");\n\t\t\tdocument.addEventListener('click', this._documentClick);\n\t\t}", "open() {\n\n // var _this = this;\n\n /**\n\n * Fires to close other open dropdowns, typically when dropdown is opening\n\n * @event Dropdown#closeme\n\n */\n\n this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id'));\n\n this.$anchor.addClass('hover')\n\n .attr({'aria-expanded': true});\n\n // this.$element/*.show()*/;\n\n this._setPosition();\n\n this.$element.addClass('is-open')\n\n .attr({'aria-hidden': false});\n\n\n\n if(this.options.autoFocus){\n\n var $focusable = Foundation.Keyboard.findFocusable(this.$element);\n\n if($focusable.length){\n\n $focusable.eq(0).focus();\n\n }\n\n }\n\n\n\n if(this.options.closeOnClick){ this._addBodyHandler(); }\n\n\n\n if (this.options.trapFocus) {\n\n Foundation.Keyboard.trapFocus(this.$element);\n\n }\n\n\n\n /**\n\n * Fires once the dropdown is visible.\n\n * @event Dropdown#show\n\n */\n\n this.$element.trigger('show.zf.dropdown', [this.$element]);\n\n }", "_open() {\n this.$.dropdown.open();\n this.$.cursor.setCursorAtIndex(0);\n Polymer.dom.flush();\n this.$.cursor.target.focus();\n }", "function activateDropdown(elem) {\n var menu = elem.parents('.dropdown-menu');\n if ( menu.length ) {\n var toggle = menu.prev('button, a');\n toggle.text ( elem.text() );\n }\n }", "openDropdown() {\n if (this.state.isDropdownOpen) {\n return;\n }\n this.setState({\n isDropdownOpen: true\n }, () => {\n this.props.onDropdownStateChange(true);\n this.resetClickAwayHandler();\n $(this.value).focus().select();\n });\n }", "open() {\n // var _this = this;\n /**\n * Fires to close other open dropdowns, typically when dropdown is opening\n * @event Dropdown#closeme\n */\n this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id'));\n this.$anchor.addClass('hover')\n .attr({'aria-expanded': true});\n // this.$element/*.show()*/;\n\n this.$element.addClass('is-opening');\n this._setPosition();\n this.$element.removeClass('is-opening').addClass('is-open')\n .attr({'aria-hidden': false});\n\n if(this.options.autoFocus){\n var $focusable = __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__[\"a\" /* Keyboard */].findFocusable(this.$element);\n if($focusable.length){\n $focusable.eq(0).focus();\n }\n }\n\n if(this.options.closeOnClick){ this._addBodyHandler(); }\n\n if (this.options.trapFocus) {\n __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__[\"a\" /* Keyboard */].trapFocus(this.$element);\n }\n\n /**\n * Fires once the dropdown is visible.\n * @event Dropdown#show\n */\n this.$element.trigger('show.zf.dropdown', [this.$element]);\n }", "function menu_dropdown_open() {\r\n var width = $(window).width();\r\n if (width > 991) {\r\n if ($(\".ow-navigation .nav li.ddl-active\").length) {\r\n $(\".ow-navigation .nav > li\").removeClass(\"ddl-active\");\r\n $(\".ow-navigation .nav li .dropdown-menu\").removeAttr(\"style\");\r\n }\r\n } else {\r\n $(\".ow-navigation .nav li .dropdown-menu\").removeAttr(\"style\");\r\n }\r\n }", "function openDropdown(clickedElement) {\n var currentDropdownMenu = $(clickedElement).closest('.button-group').find('.dropdown-box');\n //console.log(clickedElement);\n $(clickedElement).closest('.button-group').find('.dropdown-box').toggleClass('dropdown-box--active');\n $('.dropdown-box.active').not(currentDropdownMenu).removeClass('dropdown-box--active');\n }", "clickOwnerDropdownButton(){\n this.ownerDropdownButton.waitForExist();\n this.ownerDropdownButton.click();\n }", "function select($parent, target) {\n $parent.find(options.links)\n .removeClass(options.active)\n .filter(\"[href='#\"+target+\"']\")\n .addClass(options.active);\n\n $parent.find(options.content).hide();\n $parent.find('#'+target).show();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serializes the abstract list styles
serializeAbstractListStyles(writer, listStyles) { for (let i = 0; i < listStyles.length; i++) { let abstractList = listStyles[i]; writer.writeStartElement(undefined, 'abstractNum', this.wNamespace); writer.writeAttributeString(undefined, 'abstractNumId', this.wNamespace, abstractList.abstractListId.toString()); writer.writeStartElement(undefined, 'nsid', this.wNamespace); writer.writeAttributeString(undefined, 'val', this.wNamespace, this.generateHex()); writer.writeEndElement(); for (let ilvl = 0, cnt = abstractList.levels.length; ilvl < cnt; ilvl++) { this.serializeListLevel(writer, abstractList.levels[ilvl], ilvl); } writer.writeEndElement(); //end of abstractNum } }
[ "serializeListInstances(writer, listStyles) {\n for (let i = 0; i < listStyles.length; i++) {\n let list = listStyles[i];\n writer.writeStartElement(undefined, 'num', this.wNamespace);\n writer.writeAttributeString(undefined, 'numId', this.wNamespace, (list.listId + 1).toString());\n writer.writeStartElement(undefined, 'abstractNumId', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, list.abstractListId.toString());\n writer.writeEndElement();\n writer.writeEndElement();\n }\n }", "serializeStyles() {\n let writer = new XmlWriter();\n writer.writeStartElement('w', 'styles', this.wNamespace);\n writer.writeAttributeString('xmlns', 'mc', undefined, this.veNamespace);\n writer.writeAttributeString('xmlns', 'r', undefined, this.rNamespace);\n writer.writeAttributeString('xmlns', 'w', undefined, this.wNamespace);\n writer.writeAttributeString('xmlns', 'w14', undefined, this.w14Namespace);\n writer.writeAttributeString('xmlns', 'w15', undefined, this.w15Namespace);\n writer.writeAttributeString('mc', 'Ignorable', undefined, 'w14 w15');\n //writes the document defaults, latent styles and default styles.\n this.serializeDefaultStyles(writer);\n //writes the document styles\n this.serializeDocumentStyles(writer);\n writer.writeEndElement(); //end of styles tag\n let zipArchiveItem = new ZipArchiveItem(writer.buffer, this.stylePath);\n this.mArchive.addItem(zipArchiveItem); //this.stylePath, styleStream, false, FileAttributes.Archive);\n }", "toJSON() {\n const json = {}\n for (const prop in this.style) {\n const value = this.style[prop]\n if (typeof value !== 'object') json[prop] = value\n else if (Array.isArray(value)) json[prop] = toCssValue(value)\n }\n return json\n }", "serializeListLevel(writer, listLevel, levelIndex) {\n writer.writeStartElement(undefined, 'lvl', this.wNamespace);\n writer.writeAttributeString(undefined, 'ilvl', this.wNamespace, levelIndex.toString());\n writer.writeStartElement(undefined, 'start', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, listLevel.startAt.toString());\n writer.writeEndElement();\n writer.writeStartElement(undefined, 'numFmt', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, this.getLevelPattern(listLevel.listLevelPattern));\n writer.writeEndElement();\n // if (listLevel.restartLevel > 0) {\n // writer.writeStartElement(undefined, 'lvlRestart', this.wNamespace);\n // writer.writeAttributeString(undefined, 'val', this.wNamespace, '0');\n // writer.writeEndElement();\n // }\n // if (!isNullOrUndefined(listLevel.paragraphFormat)) {\n // string name = listLevel.ParaStyleName.Substring(0, 1).ToUpper() + listLevel.ParaStyleName.Remove(0, 1);\n // writer.WriteStartElement('pStyle', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, name);\n // writer.WriteEndElement();\n // }\n // if (listLevel.IsLegalStyleNumbering) {\n // writer.WriteStartElement('isLgl', this.wNamespace);\n // writer.WriteEndElement();\n // }\n this.serializeLevelFollow(writer, listLevel);\n this.serializeLevelText(writer, listLevel, levelIndex + 1);\n // SerializeLegacyProperties(listLevel);\n // if (listLevel.PicBulletId > 0) {\n // writer.WriteStartElement('lvlPicBulletId', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, listLevel.PicBulletId.ToString());\n // writer.WriteEndElement();\n // }\n // //lvlJc\n // if (listLevel.NumberAlignment !== ListNumberAlignment.Left) {\n // writer.WriteStartElement('lvlJc', this.wNamespace);\n // string alignment = string.Empty;\n // if (listLevel.NumberAlignment === ListNumberAlignment.Right) {\n // alignment = 'right';\n // }\n // else {\n // alignment = 'center';\n // }\n // writer.WriteAttributeString('val', this.wNamespace, alignment);\n // writer.WriteEndElement();\n // }\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, listLevel.paragraphFormat, undefined);\n writer.writeEndElement(); //end of pPr\n this.serializeCharacterFormat(writer, listLevel.characterFormat);\n writer.writeEndElement();\n }", "function writeStyles() {\n try {\n // Save the array\n const json = JSON.stringify(sortedStyles);\n fs.writeFileSync(JSONFILE, json, 'utf-8');\n } catch (err) {\n console.error('Failed to write style file', JSONFILE);\n }\n}", "getListContainerStyle() {\n const style = createStyleFromJson(this.listContainerStyle);\n if (this.height !== undefined) {\n style.height = this.height;\n }\n if (this.maxHeight !== undefined) {\n style.maxHeight = this.maxHeight;\n }\n if (this.minHeight !== undefined) {\n style.minHeight = this.minHeight;\n }\n return style;\n }", "serializeCharacterFormat(writer, characterFormat) {\n writer.writeStartElement(undefined, 'rPr', this.wNamespace);\n if (!isNullOrUndefined(characterFormat.styleName)) {\n writer.writeStartElement(undefined, 'rStyle', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, characterFormat.styleName);\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.fontFamily)) {\n writer.writeStartElement(undefined, 'rFonts', this.wNamespace);\n writer.writeAttributeString(undefined, 'ascii', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'hAnsi', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'eastAsia', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'cs', this.wNamespace, characterFormat.fontFamilyBidi);\n writer.writeEndElement(); //end \n }\n if (!isNullOrUndefined(characterFormat.bold)) {\n this.serializeBoolProperty(writer, 'b', characterFormat.bold);\n }\n if (characterFormat.boldBidi) {\n this.serializeBoolProperty(writer, 'bCs', characterFormat.boldBidi);\n }\n if (!isNullOrUndefined(characterFormat.italic)) {\n this.serializeBoolProperty(writer, 'i', characterFormat.italic);\n }\n if (!isNullOrUndefined(characterFormat.italicBidi)) {\n this.serializeBoolProperty(writer, 'iCs', characterFormat.italicBidi);\n }\n if (characterFormat.bidi) {\n writer.writeStartElement(undefined, 'rtl', this.wNamespace);\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.strikethrough)) {\n switch (characterFormat.strikethrough) {\n case 'SingleStrike':\n this.serializeBoolProperty(writer, 'strike', true);\n break;\n case 'DoubleStrike':\n this.serializeBoolProperty(writer, 'dstrike', true);\n break;\n default:\n this.serializeBoolProperty(writer, 'strike', false);\n this.serializeBoolProperty(writer, 'dstrike', false);\n break;\n }\n }\n if (!isNullOrUndefined(characterFormat.fontColor)) {\n writer.writeStartElement(undefined, 'color', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getColor(characterFormat.fontColor));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.fontSize)) {\n writer.writeStartElement(undefined, 'sz', this.wNamespace);\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString('w', 'val', this.wNamespace, this.roundToTwoDecimal(characterFormat.fontSize * 2).toString());\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.fontSizeBidi)) {\n writer.writeStartElement(undefined, 'szCs', this.wNamespace);\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString('w', 'val', this.wNamespace, this.roundToTwoDecimal(characterFormat.fontSizeBidi * 2).toString());\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.highlightColor) && characterFormat.highlightColor !== 'NoColor') {\n writer.writeStartElement(undefined, 'highlight', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getHighlightColor(characterFormat.highlightColor));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.underline) && characterFormat.underline !== 'None') {\n writer.writeStartElement(undefined, 'u', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getUnderlineStyle(characterFormat.underline));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.baselineAlignment)) {\n writer.writeStartElement(undefined, 'vertAlign', this.wNamespace);\n switch (characterFormat.baselineAlignment) {\n case 'Subscript':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'subscript');\n break;\n case 'Superscript':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'superscript');\n break;\n default:\n writer.writeAttributeString('w', 'val', this.wNamespace, 'baseline');\n break;\n }\n writer.writeEndElement();\n }\n writer.writeEndElement(); //end of rPrChange\n }", "toJSON() {\n return { EntangleList: this.list, sheet: this.sheet.getSheetName(), refRange: this.refRange.getA1Notation() }\n }", "serializeDefaultStyles(writer) {\n writer.writeStartElement(undefined, 'docDefaults', this.wNamespace);\n //if (HasDefaultCharFormat())\n //{\n writer.writeStartElement(undefined, 'rPrDefault', this.wNamespace);\n // if (!isNullOrUndefined(this.mDocument.characterFormat)) {\n this.serializeCharacterFormat(writer, this.defCharacterFormat);\n writer.writeEndElement(); // end of rPrDefault\n // }\n // else {\n // writer.writeStartElement(undefined, 'rPr', this.wNamespace);\n // writer.writeStartElement(undefined, 'rFonts', this.wNamespace);\n // if (!string.IsNullOrEmpty(m_document.StandardAsciiFont))\n // writer.WriteAttributeString('ascii', this.wNamespace, m_document.StandardAsciiFont);\n // if (!string.IsNullOrEmpty(m_document.StandardFarEastFont))\n // writer.WriteAttributeString('eastAsia', this.wNamespace, m_document.StandardFarEastFont);\n // if (!string.IsNullOrEmpty(m_document.StandardNonFarEastFont))\n // writer.WriteAttributeString('hAnsi', this.wNamespace, m_document.StandardNonFarEastFont);\n // if (!string.IsNullOrEmpty(m_document.StandardBidiFont))\n // writer.WriteAttributeString('cs', this.wNamespace, m_document.StandardBidiFont);\n // writer.WriteEndElement();\n // float fontSize = GetDefFontSize(m_document, WCharacterFormat.FontSizeKey);\n // if (fontSize !== 0f)\n // {\n // writer.WriteStartElement('sz', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, (fontSize * 2).ToString(CultureInfo.InvariantCulture));\n // writer.WriteEndElement();\n // }\n // fontSize = GetDefFontSize(m_document, WCharacterFormat.FontSizeBidiKey);\n // if (fontSize !== 0f)\n // {\n // writer.WriteStartElement('szCs', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, (fontSize * 2).ToString(CultureInfo.InvariantCulture));\n // writer.WriteEndElement();\n // }\n // writer.WriteEndElement();\n // }\n // writer.WriteEndElement();\n // //}\n writer.writeStartElement(undefined, 'pPrDefault', this.wNamespace);\n if (!isNullOrUndefined(this.defParagraphFormat)) {\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, this.defParagraphFormat, undefined);\n writer.writeEndElement(); //end of pPr\n }\n writer.writeEndElement(); //end of pPrDefault\n // writer.WriteEndElement();\n // SerializeLatentStyles();\n // //Default styles\n // if (m_document.Styles.length === 0 || isNullOrUndefined(m_document.Styles.FindByName('Normal')))\n // {\n // SerializeDefaultParagraphStyle();\n // }\n // if (!IsDocumentContainsDefaultTableStyle())\n // {\n // SerializeTableNormalStyle();\n // }\n // if (isNullOrUndefined(m_document.Styles.FindByName('No List')) && isNullOrUndefined(m_document.Styles.FindByName('NoList')))\n // SerializeNoListStyle();\n // tslint:disable-next-line:max-line-length\n // if (isNullOrUndefined(m_document.Styles.FindByName('Table Grid')) && isNullOrUndefined(m_document.Styles.FindByName('TableGrid')))\n // {\n // SerializeTableGridStyle();\n // }\n // } \n writer.writeEndElement();\n }", "function serializeStyles(cues){\n\t\tvar styles = {};\n\t\tcues.forEach(function(cue){ styles[cue.style.Name] = cue.style; });\n\n\t\treturn \"[V4+ Styles]\\nFormat: Name,Fontname,Fontsize,\"\n\t\t\t+\"PrimaryColour,SecondaryColour,OutlineColour,BackColour,\"\n\t\t\t+\"Bold,Italic,Underline,Strikeout,ScaleX,ScaleY,Spacing,Angle,\"\n\t\t\t+\"BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding\\n\"\n\t\t\t+Object.keys(styles).map(function(k){\n\t\t\t\tvar style = styles[k];\n\t\t\t\treturn \"Style: \"+k+','\n\t\t\t\t\t+style.Fontname+','\n\t\t\t\t\t+style.Fontsize.toString(10)+','\n\t\t\t\t\t+style.PrimaryColour.toString(10)+','\n\t\t\t\t\t+style.SecondaryColour.toString(10)+','\n\t\t\t\t\t+style.OutlineColour.toString(10)+','\n\t\t\t\t\t+style.BackColour.toString(10)+','\n\t\t\t\t\t+(style.Bold?'-1,':'0,')\n\t\t\t\t\t+(style.Italic?'-1,':'0,')\n\t\t\t\t\t+(style.Underline?'-1,':'0,')\n\t\t\t\t\t+(style.Strikeout?'-1,':'0,')\n\t\t\t\t\t+style.ScaleX.toString(10)+','\n\t\t\t\t\t+style.ScaleY.toString(10)+','\n\t\t\t\t\t+style.Spacing.toString(10)+','\n\t\t\t\t\t+style.Angle.toString(10)+','\n\t\t\t\t\t+style.BorderStyle.toString(10)+','\n\t\t\t\t\t+style.Outline.toString(10)+','\n\t\t\t\t\t+style.Shadow.toString(10)+','\n\t\t\t\t\t+style.Alignment.toString(10)+','\n\t\t\t\t\t+to4digit(style.MarginL)+','\n\t\t\t\t\t+to4digit(style.MarginR)+','\n\t\t\t\t\t+to4digit(style.MarginV)+',0\\n';\n\t\t\t}).join('');\n\t}", "function getStyleList(o) {\r\n\t\t\tvar cssList = new Array(\"accelerator\",\"azimuth\",\"background\",\"background-attachment\",\"background-color\",\"background-image\",\"background-position\",\"background-position-x\",\"background-position-y\",\"background-repeat\",\"behavior\",\"border\",\"border-bottom\",\"border-bottom-color\",\"border-bottom-style\",\"border-bottom-width\",\"border-collapse\",\"border-color\",\"border-left\",\"border-left-color\",\"border-left-style\",\"border-left-width\",\"border-right\",\"border-right-color\",\"border-right-style\",\"border-right-width\",\"border-spacing\",\"border-style\",\"border-top\",\"border-top-color\",\"border-top-style\",\"border-top-width\",\"border-width\",\"bottom\",\"caption-side\",\"clear\",\"clip\",\"color\",\"content\",\"counter-increment\",\"counter-reset\",\"cue\",\"cue-after\",\"cue-before\",\"cursor\",\"direction\",\"display\",\"elevation\",\"empty-cells\",\"filter\",\"float\",\"font\",\"font-family\",\"font-size\",\"font-size-adjust\",\"font-stretch\",\"font-style\",\"font-variant\",\"font-weight\",\"height\",\"ime-mode\",\"include-source\",\"layer-background-color\",\"layer-background-image\",\"layout-flow\",\"layout-grid\",\"layout-grid-char\",\"layout-grid-char-spacing\",\"layout-grid-line\",\"layout-grid-mode\",\"layout-grid-type\",\"left\",\"letter-spacing\",\"line-break\",\"line-height\",\"list-style\",\"list-style-image\",\"list-style-position\",\"list-style-type\",\"margin\",\"margin-bottom\",\"margin-left\",\"margin-right\",\"margin-top\",\"marker-offset\",\"marks\",\"max-height\",\"max-width\",\"min-height\",\"min-width\",\"-moz-binding-moz-border-radius\",\"-moz-border-radius-topleft\",\"-moz-border-radius-topright\",\"-moz-border-radius-bottomright\",\"-moz-border-radius-bottomleft\",\"-moz-border-top-colors\",\"-moz-border-right-colors\",\"-moz-border-bottom-colors\",\"-moz-border-left-colors\",\"-moz-opacity\",\"-moz-outline\",\"-moz-outline-color\",\"-moz-outline-style\",\"-moz-outline-width\",\"-moz-user-focus\",\"-moz-user-input\",\"-moz-user-modify\",\"-moz-user-select\",\"orphans\",\"outline\",\"outline-color\",\"outline-style\",\"outline-width\",\"overflow\",\"overflow-X\",\"overflow-Y\",\"padding\",\"padding-bottom\",\"padding-left\",\"padding-right\",\"padding-top\",\"page\",\"page-break-after\",\"page-break-before\",\"page-break-inside\",\"pause\",\"pause-after\",\"pause-before\",\"pitch\",\"pitch-range\",\"play-during\",\"position\",\"quotes\",\"-replace\",\"richness\",\"right\",\"ruby-align\",\"ruby-overhang\",\"ruby-position\",\"-set-link-source\",\"size\",\"speak\",\"speak-header\",\"speak-numeral\",\"speak-punctuation\",\"speech-rate\",\"stress\",\"scrollbar-arrow-color\",\"scrollbar-base-color\",\"scrollbar-dark-shadow-color\",\"scrollbar-face-color\",\"scrollbar-highlight-color\",\"scrollbar-shadow-color\",\"scrollbar-3d-light-color\",\"scrollbar-track-color\",\"table-layout\",\"text-align\",\"text-align-last\",\"text-decoration\",\"text-indent\",\"text-justify\",\"text-overflow\",\"text-shadow\",\"text-transform\",\"text-autospace\",\"text-kashida-space\",\"text-underline-position\",\"top\",\"unicode-bidi\",\"-use-link-source\",\"vertical-align\",\"visibility\",\"voice-family\",\"volume\",\"white-space\",\"widows\",\"width\",\"word-break\",\"word-spacing\",\"word-wrap\",\"writing-mode\",\"z-index\",\"zoom\");\r\n\t\t\tvar retCssList = \"\", cssVal = \"\";\r\n\r\n\t\t\t// Iterate through each item in array\r\n\t\t\tfor (var i = 0; i < cssList.length; i++) {\r\n\t\t\t\tcssVal = $(o[\"o\"]).css(cssList[i]);\r\n\t\t\t\tretCssList = retCssList + '<br />' + cssList[i] + ': <span class=\"' + dEdit + ' mk-edit-css-prop_' + cssList[i] + '\">' + cssVal + '</span>';\r\n\t\t\t}\r\n\r\n\t\t\t// Return list\r\n\t\t\treturn retCssList;\r\n\t\t}", "static get styles(){return[]}", "serializeNumberings() {\n if (this.document.lists.length === 0) {\n return;\n }\n let writer = new XmlWriter();\n writer.writeStartElement('w', 'numbering', this.wNamespace);\n this.writeCommonAttributeStrings(writer);\n // this.serializePictureBullets(writer, this.mDocument.lists);\n this.serializeAbstractListStyles(writer, this.document.abstractLists);\n this.serializeListInstances(writer, this.document.lists);\n // SerializeListOverrides(writer, this.mDocument.ridesm_document.ListOverrides);\n writer.writeEndElement();\n let zipArchiveItem = new ZipArchiveItem(writer.buffer, this.numberingPath);\n this.mArchive.addItem(zipArchiveItem);\n }", "function layer_serialize(layer) {\n // If the layer has a styleMap, and it's one of the defaults, do this.\n if((typeof layer.styleMap.name !== 'undefined') &&\n (typeof default_styles[layer.styleMap.name] !== 'undefined')) {\n layer.options.styleMap = \"default_styles['\"+layer.styleMap.name+\"']\";\n }\n return \"new \"+layer.CLASS_NAME+\"( '\"+\n layer.name+\"', '\"+\n layer.url+\"', {\"+hash_to_string(layer.options)+\"})\";\n}", "function listToStyles(parentId, list) {\n var styles = [];\n var newStyles = {};\n\n for (var i = 0; i < list.length; i++) {\n var item = list[i];\n var id = item[0];\n var css = item[1];\n var media = item[2];\n var sourceMap = item[3];\n var part = {\n id: parentId + ':' + i,\n css: css,\n media: media,\n sourceMap: sourceMap\n };\n\n if (!newStyles[id]) {\n styles.push(newStyles[id] = {\n id: id,\n parts: [part]\n });\n } else {\n newStyles[id].parts.push(part);\n }\n }\n\n return styles;\n }", "function listToStyles (parentId, list) {\n var styles = []\n var newStyles = {}\n for (var i = 0; i < list.length; i++) {\n var item = list[i]\n var id = item[0]\n var css = item[1]\n var media = item[2]\n var sourceMap = item[3]\n var part = {\n id: parentId + ':' + i,\n css: css,\n media: media,\n sourceMap: sourceMap\n }\n if (!newStyles[id]) {\n styles.push(newStyles[id] = { id: id, parts: [part] })\n } else {\n newStyles[id].parts.push(part)\n }\n }\n return styles\n }", "function listToStyles (parentId, list) {\r\n var styles = []\r\n var newStyles = {}\r\n for (var i = 0; i < list.length; i++) {\r\n var item = list[i]\r\n var id = item[0]\r\n var css = item[1]\r\n var media = item[2]\r\n var sourceMap = item[3]\r\n var part = {\r\n id: parentId + ':' + i,\r\n css: css,\r\n media: media,\r\n sourceMap: sourceMap\r\n }\r\n if (!newStyles[id]) {\r\n styles.push(newStyles[id] = { id: id, parts: [part] })\r\n } else {\r\n newStyles[id].parts.push(part)\r\n }\r\n }\r\n return styles\r\n}", "getListStyle() {\n return {\n position: \"relative\",\n whiteSpace: \"nowrap\",\n overflowX: \"scroll\",\n padding: 0,\n margin: 0,\n };\n }", "function postProcessList( list ) {\r\n\t\tvar children = list.children,\r\n\t\t\tchild, attrs,\r\n\t\t\tcount = list.children.length,\r\n\t\t\tmatch, mergeStyle,\r\n\t\t\tstyleTypeRegexp = /list-style-type:(.*?)(?:;|$)/,\r\n\t\t\tstylesFilter = CKEDITOR.plugins.pastefromword.filters.stylesFilter;\r\n\r\n\t\tattrs = list.attributes;\r\n\t\tif ( styleTypeRegexp.exec( attrs.style ) )\r\n\t\t\treturn;\r\n\r\n\t\tfor ( var i = 0; i < count; i++ ) {\r\n\t\t\tchild = children[ i ];\r\n\r\n\t\t\tif ( child.attributes.value && Number( child.attributes.value ) == i + 1 )\r\n\t\t\t\tdelete child.attributes.value;\r\n\r\n\t\t\tmatch = styleTypeRegexp.exec( child.attributes.style );\r\n\r\n\t\t\tif ( match ) {\r\n\t\t\t\tif ( match[ 1 ] == mergeStyle || !mergeStyle )\r\n\t\t\t\t\tmergeStyle = match[ 1 ];\r\n\t\t\t\telse {\r\n\t\t\t\t\tmergeStyle = null;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif ( mergeStyle ) {\r\n\t\t\tfor ( i = 0; i < count; i++ ) {\r\n\t\t\t\tattrs = children[ i ].attributes;\r\n\t\t\t\tattrs.style && ( attrs.style = stylesFilter( [ [ 'list-style-type' ] ] )( attrs.style ) || '' );\r\n\t\t\t}\r\n\r\n\t\t\tlist.addStyle( 'list-style-type', mergeStyle );\r\n\t\t}\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the repo remote
async setRemote({ url }) { if (!url) return; await spawnGit(["remote", "add", "origin", url]); }
[ "set repo(repo) {\n this._repository = repo\n }", "function setRepos(repos)\n{ \n repo = repos ;\n}", "async addRemote() {\n console.log(`git remote add ${this.t262GithubOrg} ${this.t262GithubRemote}`);\n await execCmd(`git remote add ${this.t262GithubOrg} ${this.t262GithubRemote}`, {\n cwd: this.targetRootDir\n });\n console.info(`Added remote of remote... ${this.t262GithubRemote} as ${this.t262GithubOrg}`);\n }", "async function addRemote ({\n core = 'default',\n dir,\n gitdir = join(dir, '.git'),\n fs: _fs = cores.get(core).get('fs'),\n remote,\n url,\n force = false\n}) {\n try {\n const fs = new FileSystem(_fs);\n if (remote === undefined) {\n throw new GitError(E.MissingRequiredParameterError, {\n function: 'addRemote',\n parameter: 'remote'\n })\n }\n if (url === undefined) {\n throw new GitError(E.MissingRequiredParameterError, {\n function: 'addRemote',\n parameter: 'url'\n })\n }\n if (remote !== cleanGitRef.clean(remote)) {\n throw new GitError(E.InvalidRefNameError, {\n verb: 'add',\n noun: 'remote',\n ref: remote,\n suggestion: cleanGitRef.clean(remote)\n })\n }\n const config = await GitConfigManager.get({ fs, gitdir });\n if (!force) {\n // Check that setting it wouldn't overwrite.\n const remoteNames = await config.getSubsections('remote');\n if (remoteNames.includes(remote)) {\n // Throw an error if it would overwrite an existing remote,\n // but not if it's simply setting the same value again.\n if (url !== (await config.get(`remote.${remote}.url`))) {\n throw new GitError(E.AddingRemoteWouldOverwrite, { remote })\n }\n }\n }\n await config.set(`remote.${remote}.url`, url);\n await config.set(\n `remote.${remote}.fetch`,\n `+refs/heads/*:refs/remotes/${remote}/*`\n );\n await GitConfigManager.save({ fs, gitdir, config });\n } catch (err) {\n err.caller = 'git.addRemote';\n throw err\n }\n}", "function setRemoteManager(rm) {\n\t\tremoteManager = rm;\n\t}", "async fetch() {\r\n const remote = await spawnGit([\"config\", \"--get\", \"remote.origin.url\"]);\r\n if (!remote.length) return this.sendMessage({ type: \"remoteNotConfigured\" });\r\n\r\n await spawnGit([\"fetch\", remote[0]]);\r\n }", "async pull() {\r\n const remote = await spawnGit([\"config\", \"--get\", \"remote.origin.url\"]);\r\n if (!remote.length) return this.sendMessage({ type: \"remoteNotConfigured\" });\r\n\r\n await spawnGit([\"pull\"]);\r\n }", "function GitRemote(parent) {\n this.parent = parent;\n Cmdln.call(this, {\n name: 'git remote',\n desc: 'manage set of tracked repositories',\n options: [\n {names: ['verbose', 'v'], type: 'bool', help: 'Verbose output.'},\n ],\n helpBody: (\n 'More help content blah blah.'\n )\n });\n}", "function setRemotePathsForProjectRepo(paths) {\n getFeatureConfig().set('fb-atomprojects.remotePaths', paths);\n}", "function onRepositorySet(repo) {\n if (repo instanceof Array) {\n socket.repositories = repo;\n }\n self.emit('connect', socket);\n }", "async function gitDefaultRemoteURL(repoDir: string) {\n const remotes = await gitRemotes(repoDir)\n if (remotes.length == 0) {\n return Promise.reject(\"no configured git remotes\")\n }\n if (remotes.length > 1) {\n console.log(\"using first git remote:\", remotes[0])\n }\n return gitRemoteURL(repoDir, remotes[0])\n}", "async function getRemote(options) {\n\tif (options.remote) {\n\t\treturn options.remote;\n\t}\n\n\tconst remotes = await git('remote', '-v');\n\tconst lines = remotes.split('\\n');\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst match = lines[i].match(\n\t\t\t/\\bgithub\\.com[/:]liferay\\/(\\S+?)(?:\\.git)?\\s/i\n\t\t);\n\t\tif (match) {\n\t\t\treturn `https://github.com/liferay/${match[1]}`;\n\t\t}\n\t}\n\n\twarn(\n\t\t'Unable to determine remote repository URL!',\n\t\t'Please specify one with --remote-url=REPOSITORY_URL'\n\t);\n\treturn null;\n}", "async function getRemote(options) {\n\tif (options.remote) {\n\t\treturn options.remote;\n\t}\n\n\tconst remotes = await git('remote', '-v');\n\tconst lines = remotes.split('\\n');\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst match = lines[i].match(\n\t\t\t/\\bgithub\\.com[/:]liferay\\/(\\S+?)(?:\\.git)?\\s/i\n\t\t);\n\t\tif (match) {\n\t\t\treturn `https://github.com/liferay/${match[1]}`;\n\t\t}\n\t}\n\n\twarn(\n\t\t'Unable to determine remote repository URL!',\n\t\t'Please specify one with --remote-url=REPOSITORY_URL'\n\t);\n\n\treturn null;\n}", "getRemoteUrl(remote) {\n return new Promise((resolve, reject) => {\n exec(`git remote get-url ${remote}`, (err, url) => {\n if (url) {\n resolve(url.replace('\\n', ''));\n } else {\n reject (err || 'Remote not found.');\n }\n });\n });\n }", "function repo () {\n opts.git = true\n opts.meta.repo = 'init'\n opts.files.gitignore = true\n }", "function handleChangeRepo(e) {\n setRepo(e.value);\n }", "function initWithRemoteGitRepository(urlString, ref) {\n \n // get repository name from url\n const urlObject = url.parse(urlString);\n var repo = path.basename(urlObject.pathname, \".git\");\n \n // git clone <url>\n var result;\n try {\n // if the repository is not present, clone it first\n if( !fs.existsSync(repo) ) {\n console.log(\"Cloning %s from %s\", repo, urlString);\n result = git.clone(repo, urlString);\n }\n if( result.error || result.fault || !fs.existsSync(repo) ) {\n console.error(\"Error: clone failed: %s\", urlString);\n return;\n }\n // if a tag or branch was specified, then do a checkout, else expect manifest repository to have initial manifest files in master branch\n if( ref ) {\n result = git.checkout(repo, ref);\n if( result.error || result.fault ) {\n console.error(\"Error: cannot checkout %s\", ref);\n return error;\n }\n }\n // there should be some files <repo>/*.yaml to copy into .manifest/ref\n var yamlFiles = listYamlFiles(repo);\n for(var i=0; i<yamlFiles.length; i++) {\n var targetPath = path.join(\".manifest\",\"ref\",path.basename(yamlFiles[i]));\n fs.copyFileSync(yamlFiles[i], targetPath);\n }\n // if there is a \"main.yaml\", then automatically do a checkout to that manifest\n if( fs.existsSync(path.join(\".manifest\",\"ref\",\"main.yaml\"))) {\n cmdcheckout.handler({ref:\"main\"});\n }\n }\n catch(e) {\n if( e.name === 'Fault' ) {\n result = {fault:e.info};\n }\n else {\n result = {fault:{type:e.name,message:e.message}};\n }\n }\n if( result.error || result.fault ) {\n console.error(\"manifest init failed: %o\", result);\n }\n}", "async function gitRemoteURL(repoDir: string, remoteName: string) {\n return execa(\"git\", [\"remote\", \"get-url\", remoteName], { cwd: repoDir }).then(result => {\n return result.stdout\n })\n}", "getRemote (pack) {\n if (pack == null) { pack = {} }\n return (pack.repository != null ? pack.repository.url : undefined) || pack.repository || 'origin'\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using what we've learned about explicit binding, let's create a 'constructor' function that creates new Order objects for us, with our calculation methods.
function OrderConstructor(amount) { this.amount = amount; this.calculateTax = Order.calculateTax; this.calculateTotal = Order.calculateTotal; return this; }
[ "function NewOrderConstructor(amount) {\n this.amount = amount;\n}", "function Order() {\n _classCallCheck(this, Order);\n\n Order.initialize(this);\n }", "function Order(customerName,customerPhoneNumber){\n this.name=customerName;\n this.number=customerPhoneNumber;\n}", "function Order(){\n this.id=null;\n this.price=0;\n this.quantity=0;\n this.description=null;\n this.customerId=null;\n}", "function Order (symbol, price, dir, id) {\n this.symbol=symbol;\n this.price=price;\n this.dir=dir;\n this.id=id;\n}", "function Order() {\n this.price = 0.0;\n this.address = \"\";\n this.pizzas = [];\n this.isForDelivery = false;\n}", "function Order(name, number, pizza) {\n this.name = name;\n this.number = number;\n this.pizza = [];\n}", "static createInstance(orderId) {\n return new Order({orderId});\n }", "function createOrder(walletAddress, creatorId, quantity, price) {\n let tmp = Object.create(order);\n tmp.walletAddress = walletAddress;\n tmp.id = creatorId;\n tmp.quantity = quantity;\n tmp.price = price;\n tmp.orderId = ++orderId;\n return tmp;\n}", "function Order(Customer, pizzas, delivery) {\n this.Customer = Customer;\n this.pizzas = pizzas; // array of Pizza objects\n this.delivery = delivery;\n}", "function Order(customerName, customerAddress, customerPhone, customerCashCredit) {\n this.customerName = customerName;\n this.customerAddress = customerAddress;\n this.customerPhone = customerPhone;\n this.customerCashCredit = customerCashCredit;\n this.pizzas = [];\n}", "function Order (name, pizza) {\n this.name = name;\n this.pizza = [];\n}", "function newOrder() {\n if (currentOrderNumber != 0) {\n orders.push(currentOrder);\n }\n\n currentOrderNumber++;\n currentOrder = new Order(currentOrderNumber);\n console.log(\"[INFO] New Order created\");\n}", "function Order(plates){\n this.plates = plates;\n}", "static createOrder(order) {\n const polygonArray = new Float64Array(order * 3); // This is initialized to zeros!!\n return new BezierCurve3d(polygonArray);\n }", "constructor(a, b, op) {\n //access calculation's internal properties\n this.a = a;\n this.b = b;\n this.op = op;\n }", "function Order(client, data) {\n if (!(this instanceof Order)) {\n return new Order(client, data);\n }\n BaseModel.call(this, client, data);\n}", "compileOrder() {\n let order = {\n created: '',\n payment_method: this.store.paymentMethod,\n discount: [],\n delivery_type: this.store.deliveryType,\n restaurant_id: this.store.storeId,\n coupons: [],\n amount: this.store.cart.products.map(p => p.total).reduce((c, e, i) => { ; return c += e; }, 0),\n address_id: this.store.addressId,\n products: this.store.cart.products\n };\n if (this.store.paymentToken)\n order.payment_token = this.store.paymentToken;\n return order;\n }", "function CustOrder(item_id, product_name, price, qty, isReturn) {\n\tthis.item_id = item_id;\n\tthis.product_name = product_name;\n\tthis.price = price;\n\tthis.isReturn = isReturn;\n\tthis.qty = qty;\n\t// Check to see if order is a return. If so, make qty negative.\n\tif (this.isReturn === true) this.qty *= -1;\n\t// Build output table to display to user.\n\tthis.buildTable = function() {\n\t\t// Currency sign (+ or -) is already handled in \"if\" statement below for design reasons.\n\t\tlet orderTotal = Math.abs(this.price * this.qty);\n\t\t// Create table object with headers and fixed widths.\n\t\tvar table = new consoleTable({\n\t\t\thead: ['Item ID', 'Product', 'Price', 'Qty', 'Order Total'],\n\t\t\tcolWidths: [10, 30, 15, 15, 20]\n\t\t});\n\t\t// Logic for currency sign manipulation based on whether order is a return.\n\t\tvar currencySign = '';\n\t\tif (this.isReturn) {\n\t\t\tcurrencySign = '-$';\n\t\t} else {\n\t\t\tcurrencySign = '$';\n\t\t}\n\t\t// Pushes order data to table object for display to user.\n\t\ttable.push([this.item_id, this.product_name, '$ ' + this.price.toLocaleString('en', {currency: 'USD', minimumFractionDigits: 2}), this.qty.toLocaleString(), currencySign + orderTotal.toLocaleString('en', {currency: 'USD', minimumFractionDigits: 2})]);\n\t\treturn table;\n\t};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calendar move event handler
_moveHandler(event) { const that = this; if (!JQX.Utilities.Core.isMobile || !that._dragStartDetails || (that.displayModeView === 'list' && that.displayMode !== 'month')) { return; } event.originalEvent.preventDefault(); event.preventDefault(); event.stopPropagation(); const details = { x: Math.round(event.pageX), y: Math.round(event.pageY) }; let step; if (that.scrollButtonsNavigationMode === 'portrait') { step = details.y > that._dragStartDetails.y ? -1 * that.months : 1 * that.months; } else { step = details.x < that._dragStartDetails.x ? 1 * that.months : -1 * that.months; } const navigationDate = that._getNextDate(step); if (!navigationDate) { return; } that._dragStartDetails.step = step; that._dragStartDetails.navigationDate = new Date(navigationDate); if (!that.hasAnimation) { return; } let animationTarget; if (that.displayMode !== 'month') { that.$nextMonthsContainer.addClass('jqx-calendar-date-view-container'); animationTarget = that.$.dateViewContainer; if (!(that.$.nextMonthsContainer.children[0].value instanceof Date) || that.$.nextMonthsContainer.children[1].value.getFullYear() !== navigationDate.getFullYear()) { that._setDisplayModeContent(navigationDate, that.$.nextMonthsContainer); } } else { if (that.$nextMonthsContainer.hasClass('jqx-calendar-date-view-container')) { that.$nextMonthsContainer.removeClass('jqx-calendar-date-view-container'); } animationTarget = that.$.monthsContainer; if (!that.$.nextMonthsContainer.children[0]._date || that.$.nextMonthsContainer.children[0]._date.getTime() !== navigationDate.getTime()) { let nextMonths = that.$.nextMonthsContainer.children; for (let i = 0; i < nextMonths.length; i++) { navigationDate.setMonth(that._dragStartDetails.navigationDate.getMonth() + i); that._setMonth(navigationDate, nextMonths[i], true); } } } if (step < 0) { animationTarget.style.order = 3; that.$.nextMonthsContainer.style.order = 1; that.$.body[that._animationSettings.scrollSize] = that.$.body[that._animationSettings.scrollMax]; } else { animationTarget.style.order = 1; that.$.nextMonthsContainer.style.order = 3; that.$.body[that._animationSettings.scrollSize] = 0; } const direction = that.scrollButtonsNavigationMode === 'portrait' ? 'y' : 'x'; if (Math.abs(that._dragStartDetails[direction] - details[direction]) > 10) { that.$.body[that._animationSettings.scrollSize] += -(details[direction] - that._dragStartDetails[direction]) * 2; } }
[ "_moveHandler(event) {\n const that = this;\n\n if (!Smart.Utilities.Core.isMobile || !that._dragStartDetails || (that.displayModeView === 'list' && that.displayMode !== 'month')) {\n return;\n }\n\n event.originalEvent.preventDefault();\n event.preventDefault();\n event.stopPropagation();\n\n const details = { x: Math.round(event.pageX), y: Math.round(event.pageY) };\n let step;\n\n if (that.scrollButtonsNavigationMode === 'portrait') {\n step = details.y > that._dragStartDetails.y ? -1 * that.months : 1 * that.months;\n }\n else {\n step = details.x < that._dragStartDetails.x ? 1 * that.months : -1 * that.months;\n }\n\n let navigationDate;\n\n if (that._previousIteration && step === that._previousIteration.step) {\n navigationDate = that._previousIteration.date;\n }\n else {\n if (that.weeks !== 6 && that.weeks !== 0 && that.displayMode === 'month') {\n let nextDateToUpdateTo;\n\n if (!that._focusedCell) {\n that._focusCell();\n }\n\n let lastVisibleDate;\n const visibleWeeks = [].slice.call(that._focusedCell.closest('.smart-calendar-weeks').children).\n filter(week => !week.classList.contains('smart-hidden'));\n\n if (!visibleWeeks.length) {\n navigationDate = that._getNextDate(step * (that.rightToLeft ? -1 : 1));\n }\n else {\n let calendarDates;\n\n if ((!that.rightToLeft && step < 0) || (that.rightToLeft && step > 0)) {\n calendarDates = visibleWeeks[0].querySelectorAll('.smart-calendar-cell');\n lastVisibleDate = that.rightToLeft ? calendarDates[calendarDates.length - 1] : calendarDates[0];\n }\n else {\n calendarDates = visibleWeeks[visibleWeeks.length - 1].querySelectorAll('.smart-calendar-cell');\n lastVisibleDate = that.rightToLeft ? calendarDates[0] : calendarDates[calendarDates.length - 1];\n }\n\n nextDateToUpdateTo = new Date(lastVisibleDate.value);\n nextDateToUpdateTo.setDate(nextDateToUpdateTo.getDate() + step * (that.rightToLeft ? -1 : 1));\n\n navigationDate = nextDateToUpdateTo;\n }\n }\n else {\n navigationDate = that._getNextDate(step * (that.rightToLeft ? -1 : 1));\n }\n }\n\n if (!navigationDate) {\n return;\n }\n\n if (!that._dragStartDetails.navigationDate) {\n if (that.$.fireEvent('navigationChanging', { value: new Date(navigationDate), type: that.displayMode }).defaultPrevented) {\n that._cancelAnimation();\n that._dragStartDetails = undefined;\n return;\n }\n }\n\n that._dragStartDetails.step = step;\n that._dragStartDetails.navigationDate = new Date(navigationDate);\n\n if (!that.hasAnimation) {\n return;\n }\n\n that._previousIteration = { step: step, date: navigationDate };\n\n that._mobileScrolling = true;\n\n let animationTarget;\n\n if (that.displayMode !== 'month') {\n that.$nextMonthsContainer.addClass('smart-calendar-date-view-container');\n animationTarget = that.$.dateViewContainer;\n if (!(that.$.nextMonthsContainer.children[0].value instanceof Date) ||\n that.$.nextMonthsContainer.children[1].value.getFullYear() !== navigationDate.getFullYear()) {\n that._setDisplayModeContent(navigationDate, that.$.nextMonthsContainer);\n }\n }\n else {\n if (that.$nextMonthsContainer.hasClass('smart-calendar-date-view-container')) {\n that.$nextMonthsContainer.removeClass('smart-calendar-date-view-container');\n }\n\n animationTarget = that.$.monthsContainer;\n\n if (!that.$.nextMonthsContainer.children[0]._date || that.$.nextMonthsContainer.children[0]._date.getTime() !== navigationDate.getTime()) {\n let nextMonths = that.$.nextMonthsContainer.children;\n\n for (let i = 0; i < nextMonths.length; i++) {\n navigationDate.setMonth(that._dragStartDetails.navigationDate.getMonth() + i * (that.rightToLeft ? -1 : 1));\n that._setMonth(new Date(navigationDate), nextMonths[i], true);\n }\n }\n }\n\n if (that.weeks !== 6 && that.weeks !== 0 && that.displayMode === 'month') {\n that._updateWeeksVisibility(step * (that.rightToLeft ? -1 : 1), that._getCellByDate(navigationDate, that.$.nextMonthsContainer));\n }\n\n delete that._mobileScrolling;\n\n if (step < 0) {\n animationTarget.style.order = 3;\n that.$.nextMonthsContainer.style.order = 1;\n that.$.body[that._animationSettings.scrollSize] = that.$.body[that._animationSettings.scrollMax];\n }\n else {\n animationTarget.style.order = 1;\n that.$.nextMonthsContainer.style.order = 3;\n that.$.body[that._animationSettings.scrollSize] = 0;\n }\n\n const direction = that.scrollButtonsNavigationMode === 'portrait' ? 'y' : 'x';\n\n if (Math.abs(that._dragStartDetails[direction] - details[direction]) > 5) {\n that.$.body[that._animationSettings.scrollSize] += -(details[direction] - that._dragStartDetails[direction]) * 2;\n }\n }", "function shiftCals(e)\n {\n e.preventDefault();\n \n var wrapper = $('.calendar_inner');\n var margin = wrapper.css('marginLeft');\n margin = parseInt(margin.substr(0, margin.length-2), 10);\n var maxwidth = wrapper.parent().css('width')\n maxwidth = maxwidth.substr(0, maxwidth.length - 2);\n var width = parseInt(maxwidth/4, 10); // @todo this may be < 4 on some devices\n var move = (e.data.dir == 'right') ? margin - width : margin + width;\n \n // can't move up too far on either side\n if(move <= 0 && move >= (width*8*-1))\n wrapper.animate({marginLeft: move+'px'}, 200, 'easeInOutQuad');\n }", "function _onDragMove(xCalendar, day){\n var isoDate = day.getAttribute(\"data-date\");\n var dateObj = parseSingleDate(isoDate);\n if(day !== xCalendar.xtag.dragStartEl){\n xCalendar.xtag.dragAllowTap = false;\n }\n\n if(!xCalendar.noToggle){\n // trigger a selection if we enter a nonchosen day while in\n // addition mode\n if(xCalendar.xtag.dragType === DRAG_ADD &&\n !(hasClass(day, CHOSEN_CLASS)))\n {\n xtag.fireEvent(xCalendar, \"datetoggleon\",\n {detail: {date: dateObj, iso: isoDate}});\n }\n // trigger a remove if we enter a chosen day while in\n // removal mode\n else if(xCalendar.xtag.dragType === DRAG_REMOVE &&\n hasClass(day, CHOSEN_CLASS))\n {\n xtag.fireEvent(xCalendar, \"datetoggleoff\",\n {detail: {date: dateObj, iso: isoDate}});\n }\n }\n if(xCalendar.xtag.dragType){\n day.setAttribute(\"active\", true);\n }\n }", "function _onDragMove(xCalendar, day) {\n var isoDate = day.getAttribute(\"data-date\");\n var dateObj = parseSingleDate(isoDate);\n if (day !== xCalendar.ns.dragStartEl) {\n xCalendar.ns.dragAllowTap = false;\n }\n\n if (!xCalendar.noToggle) {\n // trigger a selection if we enter a nonchosen day while in\n // addition mode\n if (xCalendar.ns.dragType === DRAG_ADD &&\n !(day.classList.contains(chosenClass))) {\n xCalendar.dispatchEvent(new CustomEvent(\"datetoggleon\", {\n detail: {\n date: dateObj,\n iso: isoDate\n },\n bubbles: true\n }));\n }\n // trigger a remove if we enter a chosen day while in\n // removal mode\n else if (xCalendar.ns.dragType === DRAG_REMOVE &&\n day.classList.contains(chosenClass)) {\n xCalendar.dispatchEvent(new CustomEvent(\"datetoggleoff\", {\n detail: {\n date: dateObj,\n iso: isoDate\n }\n }));\n }\n }\n if (xCalendar.ns.dragType) {\n day.setAttribute(\"active\", true);\n }\n }", "function _moveStart() {\n\t\t\t\t// TODO does anything need to be included in this event?\n\t\t\t\t// TODO make cancelable\n\t\t\t\t$fire(this._timetable, \"moveStart\");\n\t\t\t}", "function moveHandler(e) {\r\n\t\te = getEvent(e);\r\n\r\n // Move the element to the current mouse position, adjusted as\r\n \t\t// necessary by the offset of the initial mouse click.\r\n\t\telementToDrag.style.left = (e.clientX - deltaX) + \"px\";\r\n \t\telementToDrag.style.top = (e.clientY - deltaY) + \"px\";\r\n\r\n\t\t// And don't let anyone else see this event.\r\n\t\t_stopPropagation(event);\r\n }", "onApplyMove(move) {}", "function touch_moved (event) {\n moved_after_touch = true;\n}", "function draggableDayEvent(event, eventElement, seg) {\n var isStart = seg.isStart;\n var origWidth;\n var revert;\n var allDay = true;\n var dayDelta;\n var hoverListener = getHoverListener();\n var colWidth = getColWidth();\n var snapHeight = getSnapHeight();\n var snapMinutes = getSnapMinutes();\n var minMinute = getMinMinute();\n eventElement.draggable({\n opacity: opt('dragOpacity', 'month'),\n // use whatever the month view was using\n revertDuration: opt('dragRevertDuration'),\n start: function start(ev, ui) {\n trigger('eventDragStart', eventElement, event, ev, ui);\n hideEvents(event, eventElement);\n origWidth = eventElement.width();\n hoverListener.start(function (cell, origCell) {\n clearOverlays();\n\n if (cell) {\n revert = false;\n var origDate = cellToDate(0, origCell.col);\n var date = cellToDate(0, cell.col);\n dayDelta = dayDiff(date, origDate);\n\n if (!cell.row) {\n // on full-days\n renderDayOverlay(addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta));\n resetElement();\n } else {\n // mouse is over bottom slots\n if (isStart) {\n if (allDay) {\n // convert event to temporary slot-event\n eventElement.width(colWidth - 10); // don't use entire width\n\n setOuterHeight(eventElement, snapHeight * Math.round((event.end ? (event.end - event.start) / MINUTE_MS : opt('defaultEventMinutes')) / snapMinutes));\n eventElement.draggable('option', 'grid', [colWidth, 1]);\n allDay = false;\n }\n } else {\n revert = true;\n }\n }\n\n revert = revert || allDay && !dayDelta;\n } else {\n resetElement();\n revert = true;\n }\n\n eventElement.draggable('option', 'revert', revert);\n }, ev, 'drag');\n },\n stop: function stop(ev, ui) {\n hoverListener.stop();\n clearOverlays();\n trigger('eventDragStop', eventElement, event, ev, ui);\n\n if (revert) {\n // hasn't moved or is out of bounds (draggable has already reverted)\n resetElement();\n eventElement.css('filter', ''); // clear IE opacity side-effects\n\n showEvents(event, eventElement);\n } else {\n // changed!\n var minuteDelta = 0;\n\n if (!allDay) {\n minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight) * snapMinutes + minMinute - (event.start.getHours() * 60 + event.start.getMinutes());\n }\n\n eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);\n }\n }\n });\n\n function resetElement() {\n if (!allDay) {\n eventElement.width(origWidth).height('').draggable('option', 'grid', null);\n allDay = true;\n }\n }\n } // when event starts out IN TIMESLOTS", "function draggableDayEvent(event, eventElement, seg) {\r\n\t\tvar isStart = seg.isStart;\r\n\t\tvar origWidth;\r\n\t\tvar revert;\r\n\t\tvar allDay = true;\r\n\t\tvar dayDelta;\r\n\t\tvar hoverListener = getHoverListener();\r\n\t\tvar colWidth = getColWidth();\r\n\t\tvar snapHeight = getSnapHeight();\r\n\t\tvar snapMinutes = getSnapMinutes();\r\n\t\tvar minMinute = getMinMinute();\r\n\t\teventElement.draggable({\r\n\t\t\topacity: opt('dragOpacity', 'month'), // use whatever the month view was using\r\n\t\t\trevertDuration: opt('dragRevertDuration'),\r\n\t\t\tstart: function(ev, ui) {\r\n\t\t\t\ttrigger('eventDragStart', eventElement, event, ev, ui);\r\n\t\t\t\thideEvents(event, eventElement);\r\n\t\t\t\torigWidth = eventElement.width();\r\n\t\t\t\thoverListener.start(function(cell, origCell) {\r\n\t\t\t\t\tclearOverlays();\r\n\t\t\t\t\tif (cell) {\r\n\t\t\t\t\t\trevert = false;\r\n\t\t\t\t\t\tvar origDate = cellToDate(0, origCell.col);\r\n\t\t\t\t\t\tvar date = cellToDate(0, cell.col);\r\n\t\t\t\t\t\tdayDelta = dayDiff(date, origDate);\r\n\t\t\t\t\t\tif (!cell.row) {\r\n\t\t\t\t\t\t\t// on full-days\r\n\t\t\t\t\t\t\trenderDayOverlay(\r\n\t\t\t\t\t\t\t\taddDays(cloneDate(event.start), dayDelta),\r\n\t\t\t\t\t\t\t\taddDays(exclEndDay(event), dayDelta)\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tresetElement();\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t// mouse is over bottom slots\r\n\t\t\t\t\t\t\tif (isStart) {\r\n\t\t\t\t\t\t\t\tif (allDay) {\r\n\t\t\t\t\t\t\t\t\t// convert event to temporary slot-event\r\n\t\t\t\t\t\t\t\t\teventElement.width(colWidth - 10); // don't use entire width\r\n\t\t\t\t\t\t\t\t\tsetOuterHeight(\r\n\t\t\t\t\t\t\t\t\t\teventElement,\r\n\t\t\t\t\t\t\t\t\t\tsnapHeight * Math.round(\r\n\t\t\t\t\t\t\t\t\t\t\t(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /\r\n\t\t\t\t\t\t\t\t\t\t\t\tsnapMinutes\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\teventElement.draggable('option', 'grid', [colWidth, 1]);\r\n\t\t\t\t\t\t\t\t\tallDay = false;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t\trevert = true;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\trevert = revert || (allDay && !dayDelta);\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tresetElement();\r\n\t\t\t\t\t\trevert = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\teventElement.draggable('option', 'revert', revert);\r\n\t\t\t\t}, ev, 'drag');\r\n\t\t\t},\r\n\t\t\tstop: function(ev, ui) {\r\n\t\t\t\thoverListener.stop();\r\n\t\t\t\tclearOverlays();\r\n\t\t\t\ttrigger('eventDragStop', eventElement, event, ev, ui);\r\n\t\t\t\tif (revert) {\r\n\t\t\t\t\t// hasn't moved or is out of bounds (draggable has already reverted)\r\n\t\t\t\t\tresetElement();\r\n\t\t\t\t\teventElement.css('filter', ''); // clear IE opacity side-effects\r\n\t\t\t\t\tshowEvents(event, eventElement);\r\n\t\t\t\t}else{\r\n\t\t\t\t\t// changed!\r\n\t\t\t\t\tvar minuteDelta = 0;\r\n\t\t\t\t\tif (!allDay) {\r\n\t\t\t\t\t\tminuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)\r\n\t\t\t\t\t\t\t* snapMinutes\r\n\t\t\t\t\t\t\t+ minMinute\r\n\t\t\t\t\t\t\t- (event.start.getHours() * 60 + event.start.getMinutes());\r\n\t\t\t\t\t}\r\n\t\t\t\t\teventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t\tfunction resetElement() {\r\n\t\t\tif (!allDay) {\r\n\t\t\t\teventElement\r\n\t\t\t\t\t.width(origWidth)\r\n\t\t\t\t\t.height('')\r\n\t\t\t\t\t.draggable('option', 'grid', null);\r\n\t\t\t\tallDay = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function draggableDayEvent(event, eventElement, seg) {\n var isStart = seg.isStart;\n var origWidth;\n var revert;\n var allDay = true;\n var dayDelta;\n var hoverListener = getHoverListener();\n var colWidth = getColWidth();\n var snapHeight = getSnapHeight();\n var snapMinutes = getSnapMinutes();\n var minMinute = getMinMinute();\n eventElement.draggable({\n opacity: opt('dragOpacity', 'month'), // use whatever the month view was using\n revertDuration: opt('dragRevertDuration'),\n start: function(ev, ui) {\n trigger('eventDragStart', eventElement, event, ev, ui);\n hideEvents(event, eventElement);\n origWidth = eventElement.width();\n hoverListener.start(function(cell, origCell) {\n clearOverlays();\n if (cell) {\n revert = false;\n var origDate = cellToDate(0, origCell.col);\n var date = cellToDate(0, cell.col);\n dayDelta = dayDiff(date, origDate);\n if (!cell.row) {\n // on full-days\n renderDayOverlay(\n addDays(cloneDate(event.start), dayDelta),\n addDays(exclEndDay(event), dayDelta)\n );\n resetElement();\n }else{\n // mouse is over bottom slots\n if (isStart) {\n if (allDay) {\n // convert event to temporary slot-event\n eventElement.width(colWidth - 10); // don't use entire width\n setOuterHeight(\n eventElement,\n snapHeight * Math.round(\n (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /\n snapMinutes\n )\n );\n eventElement.draggable('option', 'grid', [colWidth, 1]);\n allDay = false;\n }\n }else{\n revert = true;\n }\n }\n revert = revert || (allDay && !dayDelta);\n }else{\n resetElement();\n revert = true;\n }\n eventElement.draggable('option', 'revert', revert);\n }, ev, 'drag');\n },\n stop: function(ev, ui) {\n hoverListener.stop();\n clearOverlays();\n trigger('eventDragStop', eventElement, event, ev, ui);\n if (revert) {\n // hasn't moved or is out of bounds (draggable has already reverted)\n resetElement();\n eventElement.css('filter', ''); // clear IE opacity side-effects\n showEvents(event, eventElement);\n }else{\n // changed!\n var minuteDelta = 0;\n if (!allDay) {\n minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)\n * snapMinutes\n + minMinute\n - (event.start.getHours() * 60 + event.start.getMinutes());\n }\n eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);\n }\n }\n });\n function resetElement() {\n if (!allDay) {\n eventElement\n .width(origWidth)\n .height('')\n .draggable('option', 'grid', null);\n allDay = true;\n }\n }\n }", "function draggableDayEvent(event, eventElement, seg) {\n\t\tvar isStart = seg.isStart;\n\t\tvar origWidth;\n\t\tvar revert;\n\t\tvar allDay = true;\n\t\tvar dayDelta;\n\t\tvar hoverListener = getHoverListener();\n\t\tvar colWidth = getColWidth();\n\t\tvar snapHeight = getSnapHeight();\n\t\tvar snapMinutes = getSnapMinutes();\n\t\tvar minMinute = getMinMinute();\n\t\teventElement.draggable({\n\t\t\topacity: opt('dragOpacity', 'month'), // use whatever the month view was using\n\t\t\trevertDuration: opt('dragRevertDuration'),\n\t\t\tstart: function(ev, ui) {\n\t\t\t\ttrigger('eventDragStart', eventElement, event, ev, ui);\n\t\t\t\thideEvents(event, eventElement);\n\t\t\t\torigWidth = eventElement.width();\n\t\t\t\thoverListener.start(function(cell, origCell) {\n\t\t\t\t\tclearOverlays();\n\t\t\t\t\tif (cell) {\n\t\t\t\t\t\trevert = false;\n\t\t\t\t\t\tvar origDate = cellToDate(0, origCell.col);\n\t\t\t\t\t\tvar date = cellToDate(0, cell.col);\n\t\t\t\t\t\tdayDelta = dayDiff(date, origDate);\n\t\t\t\t\t\tif (!cell.row) {\n\t\t\t\t\t\t\t// on full-days\n\t\t\t\t\t\t\trenderDayOverlay(\n\t\t\t\t\t\t\t\taddDays(cloneDate(event.start), dayDelta),\n\t\t\t\t\t\t\t\taddDays(exclEndDay(event), dayDelta)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tresetElement();\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t// mouse is over bottom slots\n\t\t\t\t\t\t\tif (isStart) {\n\t\t\t\t\t\t\t\tif (allDay) {\n\t\t\t\t\t\t\t\t\t// convert event to temporary slot-event\n\t\t\t\t\t\t\t\t\teventElement.width(colWidth - 10); // don't use entire width\n\t\t\t\t\t\t\t\t\tsetOuterHeight(\n\t\t\t\t\t\t\t\t\t\teventElement,\n\t\t\t\t\t\t\t\t\t\tsnapHeight * Math.round(\n\t\t\t\t\t\t\t\t\t\t\t(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /\n\t\t\t\t\t\t\t\t\t\t\t\tsnapMinutes\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\teventElement.draggable('option', 'grid', [colWidth, 1]);\n\t\t\t\t\t\t\t\t\tallDay = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\trevert = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\trevert = revert || (allDay && !dayDelta);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tresetElement();\n\t\t\t\t\t\trevert = true;\n\t\t\t\t\t}\n\t\t\t\t\teventElement.draggable('option', 'revert', revert);\n\t\t\t\t}, ev, 'drag');\n\t\t\t},\n\t\t\tstop: function(ev, ui) {\n\t\t\t\thoverListener.stop();\n\t\t\t\tclearOverlays();\n\t\t\t\ttrigger('eventDragStop', eventElement, event, ev, ui);\n\t\t\t\tif (revert) {\n\t\t\t\t\t// hasn't moved or is out of bounds (draggable has already reverted)\n\t\t\t\t\tresetElement();\n\t\t\t\t\teventElement.css('filter', ''); // clear IE opacity side-effects\n\t\t\t\t\tshowEvents(event, eventElement);\n\t\t\t\t}else{\n\t\t\t\t\t// changed!\n\t\t\t\t\tvar minuteDelta = 0;\n\t\t\t\t\tif (!allDay) {\n\t\t\t\t\t\tminuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)\n\t\t\t\t\t\t\t* snapMinutes\n\t\t\t\t\t\t\t+ minMinute\n\t\t\t\t\t\t\t- (event.start.getHours() * 60 + event.start.getMinutes());\n\t\t\t\t\t}\n\t\t\t\t\teventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tfunction resetElement() {\n\t\t\tif (!allDay) {\n\t\t\t\teventElement\n\t\t\t\t\t.width(origWidth)\n\t\t\t\t\t.height('')\n\t\t\t\t\t.draggable('option', 'grid', null);\n\t\t\t\tallDay = true;\n\t\t\t}\n\t\t}\n\t}", "onAfterMove() {}", "function moveEventIfNecessary(tempholiday, cell){\r\n\t\tif (tempholiday.isMovable==1)\r\n\t\t{\t\r\n\t\t\tif (tempholiday.isTzom == 1)\r\n\t\t\t{\r\n\t\t\t\tif (cell % 7 == 6) //tzom is on Saturday\r\n\t\t\t\t{\r\n\t\t\t\t\tcell +=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" + ENUM_GeneralText_EarliedOrPostponed[1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// ENUM_Holidays[21] = hanuka6, 22 - hanuka7, 23 - hanuka 8\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[21] || tempholiday.desc==ENUM_Holidays[22] || tempholiday.desc==ENUM_Holidays[23])\r\n\t\t\t{\r\n\t\t\t\tif (hebDateExists(currHebYear, 3, 30)) // Kislev 30th exists - Hanuka 6th is on Kislev 30th instead of Tevet 1st and so on\r\n\t\t\t\t{\r\n\t\t\t\t\tcell-=1\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// Tzom taanit ester.\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[26])\r\n\t\t\t{\r\n\t\t\t\tif (cell % 7 == 6)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell -=2\r\n\t\t\t\t\ttempholiday.desc += \" - \" + ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// 38 - yom hazikaron.\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[38])\r\n\t\t\t{\r\n\t\t\t\tif (cell % 7 == 5) // Friday\r\n\t\t\t\t{\r\n\t\t\t\t\tcell -=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t}\r\n\t\t\t\telse if (cell % 7 == 0) //Sunday\r\n\t\t\t\t{\r\n\t\t\t\t\tcell +=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// 14 - Rabin.\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[14])\r\n\t\t\t{\r\n\t\t\t\tif (cell % 7 == 5) // Friday\r\n\t\t\t\t{\r\n\t\t\t\t\tcell -=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t}\r\n\t\t\t\telse if (cell % 7 == 6) //Saturday\r\n\t\t\t\t{\r\n\t\t\t\t\tcell -=2\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// Yom Hazikaron - 38\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[38])\r\n\t\t\t{\r\n\t\t\t\tif (currYear == 1950)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell -=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t\ttempholiday.eventType=NONE\t// ONLY this time it's not coordinated with erevYomHaatzmaut\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (cell % 7 == 5) // Friday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell -=2\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (cell % 7 == 4) // Thursday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell -=1\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (cell % 7 == 0) //Sunday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell +=1\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// 39 - yom haatzmauut.\r\n\t\t\telse if (tempholiday.desc==ENUM_Holidays[39])\r\n\t\t\t{\r\n\t\t\t\tif (currYear == 1950)\r\n\t\t\t\t{\r\n\t\t\t\t\ttoolTipCellText[cell]=ENUM_GeneralText_EarliedOrPostponed[2] + \" \" +ENUM_Holidays[39]+ \" - \" + ENUM_GeneralText_EarliedOrPostponed[1]; //\"ערב יום העצמאות - נדחה\"\r\n\t\t\t\t\tcell +=1\r\n\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[1];\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (cell % 7 == 6) // Saturday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell -=2\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (cell % 7 == 5) // Friday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell -=1\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[0];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (cell % 7 == 1) //Monday\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell +=1\r\n\t\t\t\t\t\ttempholiday.desc += \" - \" +ENUM_GeneralText_EarliedOrPostponed[1] ;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn cell\r\n\t}", "function touchMove(e) {\n\te.preventDefault();\n\n\tfor (var i = 0; i < e.changedTouches.length; i++) {\n\t\tvar t = e.changedTouches[i];\n\t\tvar previousPos = lastKnownPos[t.identifier];\n\t\tvar currentPos = mapCoords(t);\n\n\t\t// Only call the callback if the remapped coordinates have changed. This prevents events from \n\t\t// being fired when their positions are rounded off after being remapped.\n\t\tif (previousPos.x != currentPos.x || previousPos.y != currentPos.y) {\n\t\t\tlastKnownPos[t.identifier] = t;\n\n\t\t\tif (fnTouchMove) {\n\t\t\t\tfnTouchMove(t.identifier, previousPos, currentPos);\n\t\t\t}\n\t\t}\n\t}\n}", "constructor(start, end, type, size, moveStart, moveEnd, input) {\n /**\n * If the calendar should be filled in so the first day of the calendar is\n * Sunday and the last day is Saturday.\n */\n this.fill = false;\n /**\n * The minimum number of days in the calendar no matter what the type or size\n * is. This can be used to display a month with a constant number of weeks -\n * because not all months contain the same number of weeks.\n */\n this.minimumSize = 0;\n /**\n * When `true` a [[CalendarEvent]] instance exists on each [[CalendarDay]]\n * the event covers even if the event didn't start on that day.\n */\n this.repeatCovers = true;\n /**\n * When `true` an event instance will be created for each time specified on\n * the schedule. If the schedule specifies an all day event then only one\n * event is added to a day. This is typically done when displaying days or\n * weeks and events can be displayed on a timeline.\n */\n this.listTimes = false;\n /**\n * When `true` events will be added to days \"outside\" the calendar. Days\n * outside the calendar are days filled in when [[Calendar.fill]] is `true`.\n * More specifically days that are in [[Calendar.filled]] and not in\n * [[Calendar.span]].\n */\n this.eventsOutside = false;\n /**\n * When `true` [[CalendarEvent.row]] will be set so when visually displaying\n * the event with others multi-day events will align and not overlap.\n */\n this.updateRows = false;\n /**\n * When `true` [[CalendarEvent.col]] will be set so when visually displaying\n * the event based on start and end time any events that overlap with each\n * other will be \"indented\" to see the event below it.\n */\n this.updateColumns = false;\n /**\n * The function (if any) which sorts the events on a calendar day.\n */\n this.eventSorter = null;\n /**\n * A function to use when parsing meta input into the desired type.\n *\n * @param input The input to parse.\n * @returns The meta parsed from the given input, if any.\n */\n this.parseMeta = (x => x);\n /**\n * A function to use when parsing meta input into the desired type.\n *\n * @param input The input to parse.\n * @returns The meta parsed from the given input, if any.\n */\n this.parseData = (x => x);\n /**\n * A selection of days on the calendar. If no days are selected this is `null`.\n * This is merely used to keep the selection flags in [[CalendarDay]] updated\n * via [[Calendar.refreshSelection]].\n */\n this.selection = null;\n /**\n * The array of days in this calendar and their events.\n */\n this.days = [];\n /**\n * The array of scheduled events added to the calendar.\n */\n this.events = [];\n /**\n * The array of visible events on the calendar. This is built based on the\n * span of the schedule in the given event and also the [[Event.visible]] flag.\n */\n this.visible = [];\n this.span = new DaySpan(start, end);\n this.filled = new DaySpan(start, end);\n this.type = type;\n this.size = size;\n this.moveStart = moveStart;\n this.moveEnd = moveEnd;\n if (fn.isDefined(input)) {\n this.set(input);\n }\n else {\n this.refresh();\n }\n }", "moving(event, ui) {\n this.props.moveNote(this.props.id, ui.x, ui.y);\n }", "function dadMove() {\n if (!gIsDraging) return;\n\n const pos = getEvPos(event);\n changeLinePos(gLineDrag, pos);\n renderCanvas();\n}", "function ScheduleClassDragMove(evt) {\n\treturn 'dragdrop';\n\tvar DEBUG_ScheduleClassDragMove = false;\n\tevt = (evt) ? evt : window.event;\n\tif ( DEBUG_ScheduleClassDragMove ) { console.warn('ScheduleClassDragMove[] evt.target.id='+evt.target.id); }\n\tttHide();\n\t// Find current mouse position.\n\tvar mX = mouseX(evt);\n\tvar mY = mouseY(evt);\n\tif ( DEBUG_ScheduleClassDragMove ) { console.log('mX='+mX+' mY='+mY+' dragElementTL offsetLeft='+dragElementTL.offsetLeft+' offsetTop='+dragElementTL.offsetTop); }\n\t// Calculate position to move class meeting to in order to follow the mouse.\n\tvar posX = mX - dragElementTL.offsetLeft;\n\tvar posY = mY - dragElementTL.offsetTop;\n\tif ( DEBUG_ScheduleClassDragMove ) { console.log('posX='+posX+' posY='+posY); }\n\t// Move the class meeting to follow the mouse.\n\tdragElement.style.left = posX + 'px';\n\tdragElement.style.top = posY + 'px';\n\t// Remember offsetLeft and offsetTop.\n\tvar offsetLeft = dragElementTL.offsetLeft;\n\tvar offsetTop = dragElementTL.offsetTop;\n\tdragElementTL = elementBounds(dragElement.id,1093);\n\t// Put back offsetLeft and offsetTop;\n\tdragElementTL.offsetLeft = offsetLeft;\n\tdragElementTL.offsetTop = offsetTop;\n\tif ( DEBUG_ScheduleClassDragMove ) { console.log('dragElementTL left='+dragElementTL.left+' top='+dragElementTL.top+' right='+dragElementTL.right+' bottom='+dragElementTL.bottom+' offsetLeft='+dragElementTL.offsetLeft+' offsetTop='+dragElementTL.offsetTop); }\n\t// Check if scroll up needed.\n\twhile ( dragElementTL.top > schedulecontainerTL.top && scrollTL.top > 0 && posY < ( scrollTL.top + 1 ) ) {\n\t\tif ( DEBUG_ScheduleClassDragMove ) { console.info('Scroll up'); }\n\t\twindow.scrollBy(0, -1);\n\t\tscrollTL = ScrollLeftTop();\n\t\tconsole.log('scrollTL left='+scrollTL.left+' top='+scrollTL.top);\n\t}\n\t// Check if scroll down needed.\n\t/** /\n\tconsole.log('dragElementTL.top='+dragElementTL.top+' schedulecontainerTL.bottom='+schedulecontainerTL.bottom+' ScheduleIncrementHeight='+ScheduleIncrementHeight);\n\tconsole.log('scrollTL.top='+scrollTL.top+' dragElementTL.bottom='+dragElementTL.bottom);\n\tconsole.log('scrollTL.top='+scrollTL.top+' viewportTL.height='+viewportTL.height);\n\t/**/\n\twhile ( dragElementTL.top < ( schedulecontainerTL.bottom - ScheduleIncrementHeight ) && scrollTL.top < viewportTL.height && dragElementTL.bottom > ( scrollTL.top + viewportTL.height - 1 ) ) {\n\t\tif ( DEBUG_ScheduleClassDragMove ) { console.info('Scroll down'); }\n\t\twindow.scrollBy(0, 1);\n\t\tscrollTL = ScrollLeftTop();\t\n\t\tconsole.log('scrollTL left='+scrollTL.left+' top='+scrollTL.top);\n\t}\n} // END ScheduleClassDragMove." ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Let's try some sorting. Here is an array with the specific rules. The array has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (20, 5, 10, 15) will be sorted like so: (5, 10, 15, 20). Your function should return the sorted list . Precondition: The numbers in the array are unique by their absolute values. Input: An array of numbers . Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.
function absoluteSorting(numbers){ function compare(a, b) { if (a < 0) a*=(-1); if (b < 0) b*=(-1); return a - b; } return numbers.sort(compare); }
[ "function absoluteSorting(arr) {\n\treturn arr.sort((a, b) => {\n\t\treturn Math.abs(a) - Math.abs(b);\n\t});\n}", "function sort(array) {\n\n}", "function greatestToLeast(arr) {\n return arr.sort((num1,num2) => {\n //console.log(num1, num2 )\n return (num2 - num1)\n })\n}", "function greatestToLeast(array) {\n return array.sort((a,b) => b - a);\n}", "function sortedSquares(arr) {}", "function arraySorting(numb) {\n // Sort the array by min to max\n const sorted = numb.sort((a, b) => a - b);\n console.log(sorted);\n }", "function arrangeElements( array ) {\r\n\tarray = array.sort();\r\n\treturn array;\r\n}", "function sortNumbers(arr) {\n //to sort numbers (a-b)\n return arr.sort((function(a, b){return a-b}));\n\n}", "function sortRange(arr) {\n\tif(arr[0] > arr[1]) {\n\t\treturn [arr[1], arr[0]];\n\t} else if(arr[0] < arr[1]) {\n\t\treturn [arr[0], arr[1]];\n\t} else {\n\t\treturn arr;\n\t}\n}", "function almostSorted(arr) {\n let asc = [...arr].sort((a, b)=>a-b);\n // let des = asc.reverse();\n // compareArr(arr, )\n}", "function orderArray(){\n\tconst array1 = [3,1];\n\n\t// write the function that will make this work\n\tfunction orderArray(a) {\n\t\tif (a[0] > a[1]) {\n\t\t\treturn [a[1], a[0]];\n\t\t}\n\t\treturn a;\n\t}\n\n\tconsole.log(\"Should Be: 1, 3:\", \n\t\torderArray(array1));\n\n\tconsole.log(\"Should Be: 1, 5:\", \n\t\torderArray([1, 5]));\n\n\tconsole.log(\"Should Be: 10, 20:\", \n\t\torderArray([20, 10]));\n\n}", "function greatestToLeast(arr) {\r\n return arr.sort(function(a, b){\r\n return b-a\r\n })\r\n\r\n}", "function sortedSquaredArray(array) {\n\tconst output = []\n\t// add negative integers to a new array\n\tconst negs = array.filter(int => int < 0)\n\t// iterate through original array, and push computed squares onto output array\n\t// if element is > current neg element, push neg element's square onto output array\n\tlet negsPointer = negs.length - 1\n\t// start pointer at first postitive integer\n\tlet arrPointer = negs.length\n\twhile(arrPointer < array.length || negsPointer >= 0) {\n\t\t// if we've reached the end of positive ints, push the remaining negs\n\t\tif (arrPointer === array.length || array[arrPointer] >= negs[negsPointer] * -1) {\n\t\t\toutput.push(negs[negsPointer] * negs[negsPointer])\n\t\t\tnegsPointer--\n\t\t}\n\t\telse {\n\t\t\toutput.push(array[arrPointer] * array[arrPointer])\n\t\t\tarrPointer++\n\t\t}\n\t}\n\n\treturn output\n\t// alternative O(n log n) solution\n // return array.map(int => int*int).sort((a, b) => a - b)\n}", "function sortNumbers(arr){\n return arr.sort(function(a, b){ return a - b; });\n }", "function sortedSquares(array){\n// square each element in the array\nvar sortedArr = [];\nfor( let i = 0; i < array.length; i ++){\n sortedArr.push(Math.pow(array[i], 2))\n}\n//return each element sorted\nreturn sortedArr.sort(function(a, b){return a-b});\n}", "function sort(arr) {\n return arr.sort()\n}", "function solution(nums){\n return nums == null ? [] : nums.sort((a,b) => a - b);\n}", "function solve(arr){\n let h = arr.reduce((h,n)=>(h[n]=h[n]+1||1,h),{});\n return arr.sort((a,b)=>h[b]-h[a]||a-b);\n}", "static sortAsc(array) {\n return array.sort(function (a,b) {return a-b;})\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/////////////// Use the stripe api to combine products and prices based on unique product id.
async function s() { const list = [] for (let i = 0; i < packageIDs.length; i++) { try { let price_with_product = await stripe.prices.list({ product: packageIDs[i], expand: ['data.product'], }) list.push({ product: price_with_product.data[0].product, price: price_with_product.data[0].unit_amount }); } catch (err) { console.error(err); } } return list; }
[ "getProductPrice(id) {\r\n\t\tlet select = [\"pw_price.id_price\", \"id_currency\", \"id_tax\", \"purchase_net\", \"purchase_gross\", \"purchase_type\", \"wholesale_net\", \"wholesale_gross\", \"wholesale_type\", \"sale_net\", \"sale_gross\", \"sale_type\"];\r\n\t\tlet prepare = db(\"pw_price\");\r\n\t\tlet where = {\r\n\t\t\tid_products: id\r\n\t\t}\r\n\r\n\t\tprepare = prepare.leftJoin('pw_products_price', 'pw_price.id_price', 'pw_products_price.id_price')\r\n\t\tprepare = prepare.where(where);\r\n\r\n\t\treturn prepare.select(select);\r\n\t}", "async function buildProducts() {\n let response = await fetch('https://api.airtable.com/v0/appcEdYdqWTVWe80T/products?sort%5B0%5D%5Bfield%5D=name', {\n method: 'GET',\n headers: {\n 'Authorization': 'Bearer keyV4oqFP1aJ9oo7R',\n 'Content-Type': 'application/json'\n }\n })\n let json = await response.json()\n let records = json.records\n\n for (let i = 0; i < records.length; i++) {\n let fields = records[i].fields\n let productId = records[i].id\n let name = fields.name\n let description = fields.description\n let imageURL = fields.imageURL\n let price = fields.price\n let productsContainer = document.querySelector('.products')\n productsContainer.insertAdjacentHTML('beforeend', `\n <div class=\"p-4 w-full md:w-1/2 lg:w-1/3\">\n <div class=\"border h-full p-4 flex flex-col\">\n <h2 class=\"text-lg font-bold mb-4\">${name}</h2>\n <div class=\"mb-4\"><img src=\"${imageURL}\"></div>\n <div class=\"mb-4 text-gray-900\">${description}</div>\n <div class=\"mt-auto flex\">\n <div class=\"text-purple-500 text-2xl\">$${price}</div>\n <a href=\"#\" data-product-id=\"${productId}\" class=\"add-to-cart-button ml-auto px-4 py-2 text-white bg-purple-500 rounded\">Add to cart</a>\n </div>\n </div>\n </div>\n `)\n }\n attachAddToCartEventListeners()\n}", "getProductItems(data) {\n const items = [];\n for (let i = 0; i < data.products.length; i += 1) {\n const p = data.products[i];\n items.push({ id: p.aonr, price: p.priceData.total, quantity: p.quantity });\n }\n return items;\n }", "function getProductById (id) {\n\n}", "function getProducts(data){\n return new Promise((resolve, reject) => {\n //console.log(WooCommerce);\n return WooCommerce.getAsync('products').then((result, error) => {\n //return JSON.parse(result.toJSON().body);\n if(!error){\n //have to insert all the items into the database.\n var x = JSON.parse(result.toJSON().body);\n console.log(x.products);\n var products = x.products;\n\n var wc_ref, cat_name, wc_id, sku, price, sale_price, on_sale;\n var items = [];\n\n var i = 0;\n for(i =0; i < products.length; i++){\n //need to search for vendor id in database based on name.\n\n // insert cat name, cat id, woo com id, woo com refrence, sku, and vendor id\n console.log('');\n console.log('=====================================================')\n console.log('woocom reference', href); //changed to use wc v3 api\n console.log('cat name', products[i].categories[0]);\n console.log('woo com id', products[i].id);\n console.log('sku', products[i].sku);\n console.log('price', products[i].price);\n console.log('sale price', products[i].sale_price);\n console.log('on sale', products[i].on_sale);\n console.log('=====================================================')\n console.log('');\n\n\n var href = 'http://www.take-outbuddy.com/wc-api/v3/products/' + products[i].id;\n wc_ref = href;\n cat_name = products[i].categories[0];\n wc_id = products[i].id;\n sku = products[i].sku;\n price = products[i].price;\n sale_price = (products[i].sale_price == null) ? null : products[i].sale_price;\n on_sale = products[i].on_sale;\n\n\n if(sale_price == null){\n console.log('SET SALE PRICE TO NULL');\n }\n var x = {\"wc_ref\" : wc_ref, \"cat_name\": cat_name, \"wc_id\": wc_id, \"sku\": sku, \"price\": price, \"sale_price\": sale_price, \"on_sale\": on_sale }\n items[i] = x;\n }\n\n return items;\n resolve(); //this may not need to be here (need to test)\n\n }else{\n reject(error);\n //callback(error, null);\n }\n })\n .then(items =>{\n\n // 7/8/2018 - Note: Need to finish this route by adding some preliminary checks to determine if vendor exists in database before adding the items.\n\n var qry_string = \"INSERT INTO item(woo_com_href, cat_name , woo_com_id, sku, price, sale_price, on_sale) VALUES\"//forming the string => INSERT INTO \"tmp\"(\"col_a\",\"col_b\") VALUES + ('a1','b1'),('a2','b2')\n for(var i = 0; i < items.length; i++){\n qry_string = qry_string + `( '` + items[i].wc_ref + `','` + items[i].cat_name + `','` + items[i].wc_id + `','` + items[i].sku +\n `','` + items[i].price + `',` + items[i].sale_price + `,'` + items[i].on_sale + `' ),`;\n }\n qry_string = qry_string.replace(/.$/,\";\"); //string last comma and putting semicolon.\n console.log('HERE IS QUERY STRING:', qry_string);\n \n var promise = qp(qry_string, []).then(insert_result =>{\n console.log(insert_result);\n resolve(insert_result);\n })\n return tx([promise]);\n \n });\n\n })\n}", "getProduct(id) {\n return this.getProducts()\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_1__[\"map\"])((products) => products.find(p => p.productId === id)));\n }", "function addToShoppingCart(id){\n\n let chosenProduct = products.find((product)=> product.id == id);\n let shoppingElement = shoppingCart.selectedProducts;\n let priceOfProduct = chosenProduct.price;\n\n shoppingElement = shoppingElement.push(chosenProduct);\n \n shoppingCart.totalPrice = shoppingCart.totalPrice + priceOfProduct;\n \n}", "_getProductPriceData(id, sku) {\n return new Promise((resolve, reject) => {\n superagent\n .get(`${URL}/v1/products/${id}/market?children=${sku}`)\n .set('jwt-authorization', this.jwt)\n .set('x-api-key', API_KEY)\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res.body);\n }\n })\n });\n }", "static async getProduct(id) {\r\n let res = await this.request(`products/${id}`);\r\n return res.product;\r\n }", "function getids(id){\r\n \tvar blength=productids.length;\r\n productids[blength]=id;\r\n totalprice();\r\n }", "function updateProductsInCart (product) {\n for( let i = 0; i < productsInCart.length; i++) {\n if( productsInCart[i].id == product.id ){\n productsInCart[i].price = productsInCart[i].basePrice * productsInCart[i].count;\n return;\n\n }\n }\n productsInCart.push(product);\n}", "function fetchProduct(id) {\n \n}", "static async retrieve_product_coupons_by_product_id(product_id) {\n const coupons = await fetch_product_coupons_by_product_id(product_id);\n return coupons;\n }", "async function setup() {\n for (const product of products) {\n const createdProduct = await stripe.products.create({\n name: product.name,\n description: product.description,\n images: [product.imageUrl],\n metadata: {\n testProduct: product.testProduct\n }\n });\n\n const price = await stripe.prices.create({\n unit_amount: product.price,\n currency: 'usd',\n product: createdProduct.id,\n });\n }\n\n console.log('Successfully added all products to Stripe console');\n}", "addProductAmount(id) {\n let product = shoppingCart.findById(id);\n product.amount++;\n document.getElementById('foodAmountCart-' + product.id).innerHTML = product.amount + 'x';\n document.getElementById('overall-shopping-cart-price-' + product.id).innerHTML = printPrice(product) + '€';\n }", "function addAppendPriceInCart(listProductUpdatedPrice) { \n otElementFormCart = $(window.OTSettings.elementFormCart);\n var total_new = 0;\n let i = 0;\n for (let item of listProductUpdatedPrice) { \n if(typeof item.price_new2 != \"undefined\"){\n item.price_new = item.price_new2;\n } \n if (item.price_new) {\n total_new += Number(item.price_new);\n } else {\n total_new += Number(item.line_price);\n } \n if (item.isDiscount == 1) {\n \n item.pricePerProduct = Shopify.formatMoney(item.price_new / item.quantity,Shopify.money_format);\n item.price = Shopify.formatMoney(item.price,Shopify.money_format);\n item.priceCurrency = Shopify.formatMoney(item.line_price, Shopify.money_with_currency_format);\n item.priceCurrencyReplace = item.priceCurrency.toString().replace(\".\", \",\");\n item.line_price = Shopify.formatMoney(item.line_price,Shopify.money_format);\n item.price_new = Shopify.formatMoney(item.price_new,Shopify.money_format);\n item.total_price = Shopify.formatMoney(item.total_price,Shopify.money_format); \n // APPEND PRICE IN CART \n \n // FIND ELEMENT\n\n /// add code\n // debugger;\n \n var elementTotalPricePerProductInCart = $(`.ot-quantity-cart-total[data-id='${item.variant_id}'],.ot-quantity-cart-total[data-key='${item.key}'],.saso-cart-item-line-price[data-key='${item.key}']`);\n var elementPricePerProductInCart = $(`.ot_quantity_line[data-id='${item.variant_id}'],.ot_quantity_line[data-key='${item.key}']`);\n var elementHanleProductInCart;\n if($(`.ot_quantity_handle[data-id='${item.key}']`).length > 0){\n elementHanleProductInCart = $(`.ot_quantity_handle[data-id='${item.key}']`);\n }else{\n elementHanleProductInCart = otElementFormCart.find(`[href^='/products/${item.handle}?variant=${item.variant_id}']`).last();\n } \n i = i+1;\n if(elementTotalPricePerProductInCart.length == 0){\n // auto append\n elementTotalPricePerProductInCart = getElementTotalPricePerProductInCart(elementHanleProductInCart.parent(),item)\n } \n // Append price \n \n if(item.line_price != item.price_new){\n elementTotalPricePerProductInCart.find(`.money:first`).css('text-decoration', 'line-through');\n elementTotalPricePerProductInCart.find(`:contains(${item.line_price})`).css('text-decoration', 'line-through');\n elementTotalPricePerProductInCart.children().last().after(`<span class=\"ot_price_new money\" style=\"display: block;color: red;\">${item.price_new}</span>`);\n elementPricePerProductInCart.css('text-decoration', 'line-through');\n } \n \n elementPricePerProductInCart.after(`<span class=\"ot_price_per_product_new money\" style=\"display: block;color: red;\">${item.pricePerProduct}</span>`);\n elementHanleProductInCart.after(` <span class=\"ot_notification_product\" style=\"display: block;color: red;\"> ${item.notification} </span> `); \n } \n }\n\t\n //------FORMAT PRICE CHO TUNG PRODUCT------- \n\n formatMoneyByClass(\"ot_formatPriceInNoticeCart\");\n \n //----- APPEND TOTAL PRICE IN CART-------\n \n if (totalPriceInCart != total_new && total_new != 0) { \n totalPriceInCartCurrent = Shopify.formatMoney(totalPriceInCart, Shopify.money_with_currency_format);\n let totalPriceInCartReplace = totalPriceInCartCurrent.toString().replace(\".\", \",\");\n let subTotalPriceOldInCart = Shopify.formatMoney(totalPriceInCart,Shopify.money_format); \n if (elementCartTotal.length == 0) { \n if($(`:contains(${subTotalPriceOldInCart})`).last().length > 0){ // find by price | $29\n elementCartTotal = $(`:contains(${subTotalPriceOldInCart})`).last();\n }else if($(`:contains(${totalPriceInCartCurrent})`).last().length > 0){ // find by price | $29 USD\n elementCartTotal = $(`:contains(${totalPriceInCartCurrent})`).last();\n }else{ // find by price | $29.00 USD\n elementCartTotal = $(`:contains(${totalPriceInCartReplace})`).last(); \n } \n } \n // append subtotal \n elementCartTotal.css(\"text-decoration\", \"line-through\"); \n if(Shopify.shop == \"wunder-kissen-de.myshopify.com\"){\n elementCartTotal.after(` <span class=\"ot_cart__subtotal_new money\" style=\"color:red;display:block;\">Gesamtpreis ${Shopify.formatMoney(total_new,Shopify.money_format)}</span>`);\n }else if(Shopify.shop == \"cp-us.myshopify.com\" || Shopify.shop == \"cp-global.myshopify.com\"){\n $(\".cart-subtotal,.cart-title-total\").find(\".money\").css(\"text-decoration\", \"line-through\"); \n $(\".cart-subtotal,.cart-title-total\").after(` <span class=\"ot_cart__subtotal_new money\" style=\"color:red;display:block;\"> ${Shopify.formatMoney(total_new,Shopify.money_format)}</span>`);\n }else{\n elementCartTotal.after(` <span class=\"ot_cart__subtotal_new money\" style=\"color:red;display:block;\"> ${Shopify.formatMoney(total_new,Shopify.money_format)}</span>`); \n } \n \n window.totalPriceInCart = total_new;\n if(Shopify.shop == \"plastic-solutions-ireland.myshopify.com\"){\n listEventClickCheckout();\n }\n } \n}", "function getProduct(id) {\n return rawdata.filter(product => product.prodId == id);\n}", "function findStripePriceById(id){\n const subscriptions = _.object(_.map(STRIPE_OPTIONS.plans.data, p => [p.id, parseInt(p.metadata.base_cost)] ));\n const hardware = _.object(_.map(STRIPE_OPTIONS.skus.data, s => [s.id, parseInt(s.price)] ));\n\n return parseInt(subscriptions[id]) || parseInt(hardware[id]);\n }", "getProductThumbs (products = []) {\n\n return products.map((product) => {\n const selectedVariant = product.selectedVariant\n const shopifyUrl = 'https://fancyteestore.myshopify.com/products/' + product.id + '?variant=' + selectedVariant.id\n const productQuantity = this.state.productsQuantity[selectedVariant.id] || 1\n const totalPrice = product.selectedVariant.price * productQuantity\n\n return (\n <div key={selectedVariant.id.toString()} data-key={selectedVariant.id.toString()} className=\"product-thumb\">\n <div className=\"thumbnail\">\n <img className=\"img-responsive\" \n src={product.selectedVariantImage && product.selectedVariantImage.src} \n alt={product.title}\n height=\"360px\" />\n <div className=\"caption\">\n <h3>{product.title}</h3>\n <p><StockLabel available={selectedVariant.available}/></p>\n <p dangerouslySetInnerHTML={{__html: product.description || ''}} />\n <p>Price: ${product.selectedVariant.price} * {productQuantity} = ${totalPrice}</p>\n </div>\n <div className=\"Quantity-select\">\n <p>Select Quantity for Product</p>\n <input type=\"number\" \n className=\"form-control\" \n value={productQuantity}\n onChange={this.onQuantityChange.bind(this, selectedVariant)} />\n </div>\n <OptionsDisplay options={product.options} />\n <div className=\"thumb-buttons\">\n <a href=\"#\" onClick={this.buyNow.bind(this, product)} \n className='btn btn-default'>\n Buy Now!\n </a>\n <a href=\"#\" className=\"btn btn-primary\" onClick={this.addToCart.bind(this, selectedVariant)}>\n Add To Cart <span className=\"glyphicon glyphicon-shopping-cart\" aria-hidden=\"true\"></span>\n </a>\n <a href={shopifyUrl} className=\"btn btn-success\">Visit on Shopify Store</a>\n </div>\n </div>\n </div>\n )\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: upsert_delta_modified() PURPOSE: The same element can be modified many times within a transaction on same element repeat modifications, only the last one matters if it's not a repeat, push it to delta.modifications
function upsert_delta_modified(me, entry) { // look for matching modifieds, if found, replace for (var i = 0; i < me.delta.modified.length; i++) { var op_path = me.delta.modified[i].op_path; if (subarray_elements_match(op_path, me.op_path, "K")) { me.delta.modified[i] = entry; return; } } me.delta.modified.push(entry); }
[ "function updateItem(delta) {\n return Item.findOne({\"_id\":delta._id}).then(function(item) {\n let newDescription;\n let newCost;\n let newQuantity;\n if (delta.description) {\n newDescription = delta.description;\n } else {\n newDescription = item.description;\n }\n if (delta.cost) {\n newCost = delta.cost;\n } else {\n newCost = item.cost;\n }\n if (delta.quantity) {\n newQuantity = delta.quantity;\n } else {\n newQuantity = item.quantity;\n }\n return Item.updateOne(item,\n {$set: {\"description\": newDescription,\n \"cost\": newCost,\n \"quantity\": newQuantity}\n })\n })\n}", "updateEntities(delta) {\n this.registeredEntities.forEach((entity) => entity.update(delta));\n }", "function elementModificationReplaceable (eleModRep) {\n const each = eleModRep.each\n const final = eleModRep.is_final\n const eleMod = eleModRep.element_modification\n const eleRep = eleModRep.element_replaceable\n return Object.assign(\n {'each': each || undefined},\n {'final': final || undefined},\n {'element_modification': eleMod ? this.elementModification(eleMod) : undefined},\n {'element_replaceable': eleRep ? this.elementReplaceable(eleRep) : undefined}\n )\n}", "function __full_incr_op(parent, me, val) {\n // Edit found entry in place\n me.got.V.P += val; // Increment P\n if (ZH.IsUndefined(me.got.V.D)) me.got.V.D = val; // SET DELTA\n else me.got.V.D += val; // INCR DELTA\n\n // decrements modify in place -> to-be-delta.modified[]\n var entry = exports.CreateDeltaEntry(me.op_path, me.got);\n upsert_delta_modified(me, entry)\n}", "update(item, modified) {\n const i = this.queue.indexOf(item);\n const queueItem = this.queue[i];\n if (queueItem === Object.assign({}, queueItem, modified)) {\n return false;\n }\n this.queue[i] = Object.assign({}, item, modified);\n return true;\n }", "update(entity, modified) {\n Object.keys(modified).forEach((key) => {\n entity[key] = modified[key];\n });\n return entity.savePromise();\n }", "trackUpdateMany(updates, collection, mergeStrategy) {\n if (mergeStrategy === MergeStrategy.IgnoreChanges ||\n updates == null ||\n updates.length === 0) {\n return collection; // nothing to track\n }\n let didMutate = false;\n const entityMap = collection.entities;\n const changeState = updates.reduce((chgState, update) => {\n const { id, changes: entity } = update;\n if (id == null || id === '') {\n throw new Error(`${collection.entityName} entity update requires a key to be tracked`);\n }\n const originalValue = entityMap[id];\n // Only track if it is in the collection. Silently ignore if it is not.\n // @ngrx/entity adapter would also silently ignore.\n // Todo: should missing update entity really be reported as an error?\n if (originalValue) {\n const trackedChange = chgState[id];\n if (!trackedChange) {\n if (!didMutate) {\n didMutate = true;\n chgState = { ...chgState };\n }\n chgState[id] = { changeType: ChangeType.Updated, originalValue };\n }\n }\n return chgState;\n }, collection.changeState);\n return didMutate ? { ...collection, changeState } : collection;\n }", "modified(field) {\n var schema = this.schema();\n var updated = {};\n var fields = field ? [field] : Object.keys(extend({}, this._persisted, this._data));\n\n var len = fields.length;\n for (var i = 0; i < len; i++) {\n var key = fields[i];\n if (this._data[key] === undefined) {\n if (this._persisted[key] !== undefined) {\n updated[key] = this._persisted[key];\n }\n continue;\n }\n if (this._persisted[key] === undefined) {\n if (!schema.hasRelation(key)) {\n updated[key] = null;\n }\n continue;\n }\n var modified = false;\n var value = this._data[key] !== undefined ? this._data[key] : this._persisted[key];\n\n if (value && typeof value.modified === 'function') {\n modified = this._persisted[key] !== value || value.modified();\n } else {\n modified = this._persisted[key] !== value;\n }\n if (modified) {\n updated[key] = this._persisted[key];\n }\n }\n if (field) {\n return !!Object.keys(updated).length;\n }\n var result = Object.keys(updated);\n return field ? result : result.length !== 0;\n }", "updateModified() {\n let dataset = this.data.dataset\n dataset.modified = moment().format()\n this.update({ dataset })\n }", "function createChangeRecord( old_ds, new_ds ) {\n var change_type;\n if ( old_ds.length==(new_ds.length-2) ) {\n change_type = \"insertion\";\n } else if ( old_ds.length==(new_ds.length+2) ) {\n change_type = \"deletion\";\n } else if ( old_ds.length==new_ds.length ) {\n change_type = \"substitution\";\n } else {\n alert( \"createChangeRecord: unrecognized change type\" );\n return false;\n }\n var final_array = [];\n var combined_array = [];\n var change_record = [];\n var nds = new_ds.slice(0,new_ds.length);\n var el, idx;\n if ( change_type==\"insertion\" ) {\n for ( var i=0; i<old_ds.length; i++ ) {\n el = old_ds[i]; // identify current element\n idx = indexInArray(el,nds); // find its location in nds\n nds.splice( idx, 1 ); // remove it from nds\n final_array.push(el); // add it to the reordered list\n combined_array.push(el); // add it to the record of changes\n change_record.push(\"none\"); // record it as no change\n }\n final_array = final_array.concat( nds ); // add remaining elements of nds to reordered list\n combined_array = combined_array.concat( nds ); // add these to the record of changes\n change_record = change_record.concat( [ \"ins\", \"ins\" ] ); // should be the case that exactly two were added\n } else if ( change_type==\"deletion\" ) {\n for ( var i=0; i<old_ds.length; i++ ) {\n el = old_ds[i]; // identify current element\n idx = indexInArray(el,nds); // find its location in nds\n if ( idx==-1 ) { // this is an element that was removed\n combined_array.push(el); // add it to the record of changes, but not the reordered list\n change_record.push(\"del\"); // record it as removed\n } else { // the element was not removed\n nds.splice( idx, 1 ); // remove it from nds\n final_array.push(el); // add it to the reordered list\n combined_array.push(el); // add it to the record of changes\n change_record.push(\"none\"); // record it as no change\n }\n }\n } else if ( change_type==\"substitution\" ) {\n var sub_idx;\n for ( var i=0; i<old_ds.length; i++ ) {\n el = old_ds[i]; // identify current element\n idx = indexInArray(el,nds); // find its location in nds\n if ( idx!=(-1) ) { // if it's also in the new dataset \n nds.splice( idx, 1 ); // remove it from nds\n final_array.push(el); // add it to the reordered list\n combined_array.push(el); // add it to the record of changes\n change_record.push(\"none\"); // record it as no change\n } else { // if it's NOT in the new dataset, then this element was substituted\n sub_idx = i; // record its position\n final_array.push( 0 ); // put a placeholder here in the reordered list\n combined_array.push(el); // put the original el in the record of changes\n change_record.push(\"del\"); // record it as removed\n combined_array.push( 0 ); // put a placeholder here in the record of changes\n change_record.push(\"ins\"); // record it as added\n }\n }\n el = nds[0]; // the remaining element (should be only 1) is the added one\n final_array[ sub_idx ] = el; // put it into the appropriate position in the reordered list\n combined_array[ sub_idx+1 ] = el; // put it into the appropriate position in the record of changes\n }\n return { \"final_array\": final_array, \"combined_array\": combined_array, \"change_record\": change_record, \"change_type\": change_type };\n}", "saveItems() {\n for (let item of this.getItems()) {\n if (typeof item.isModified === 'function' && item.isModified()) {\n this.saveItem(item);\n }\n }\n }", "perform() {\n let container = DOM.byId(this.containerId)\n this.elementsToModify.forEach(elementToModify => {\n if (elementToModify.previousElementId) {\n maybe(document.getElementById(elementToModify.previousElementId), previousElem => {\n maybe(document.getElementById(elementToModify.elementId), elem => {\n let isInRightPlace = elem.previousElementSibling && elem.previousElementSibling.id == previousElem.id\n if (!isInRightPlace) {\n previousElem.insertAdjacentElement(\"afterend\", elem)\n }\n })\n })\n } else {\n // This is the first element in the container\n maybe(document.getElementById(elementToModify.elementId), elem => {\n let isInRightPlace = elem.previousElementSibling == null\n if (!isInRightPlace) {\n container.insertAdjacentElement(\"afterbegin\", elem)\n }\n })\n }\n })\n\n if(this.updateType == \"prepend\"){\n this.elementIdsToAdd.reverse().forEach(elemId => {\n maybe(document.getElementById(elemId), elem => container.insertAdjacentElement(\"afterbegin\", elem))\n })\n }\n }", "function remove_redundant_modified_entry(me) {\n // Delete Previous Overwrite: remove from delta.modified[]\n for (var i = 0; i < me.delta.modified.length; i++) {\n var op_path = me.delta.modified[i].op_path;\n if (subarray_elements_match(op_path, me.op_path, \"K\")) {\n me.delta.modified.splice(i, 1); // remove entry from modified[]\n return; // there will only be one\n }\n }\n}", "function areTagsModified() {\n var untagKeys = getUntagKeys(self.initialTagCollection, self.editedTagCollection);\n\n if (untagKeys.length !== 0 || self.editedTagCollection.length !== 1) {\n return true;\n }\n\n return self.editedTagCollection[0].key || self.editedTagCollection[0].value;\n }", "_onUpdated(updatedEntry) {\n this.list.some((entry, index) => {\n if (entry._id === updatedEntry._id) {\n this.list[index] = updatedEntry;\n\n return true;\n }\n });\n\n if (this.entry._id === updatedEntry._id) {\n this.entry = updatedEntry;\n }\n }", "canAddModifiers($modifiers, parent){\n var found = false;\n var i=-1;\n let parentModIds = []\n function getAllIds(mod, modIds = []){\n i++\n //add mod to array\n modIds.push(mod.id);\n\n if (mod.modifiers && mod.modifiers.length){\n for (let i=0;i<mod.modifiers.length;i++){\n getAllIds(mod.modifiers[i], [...modIds])\n }\n }\n if (mod.items && mod.items.length){\n for (let i=0;i<mod.items.length;i++){\n for (let j=0;j<mod.items[i].modifiers.length;j++){\n getAllIds(mod.items[i].modifiers[j], [...modIds])\n }\n }\n }\n\n //try to find repetittions\n let thisModModIds = mod.modifiers.map((m)=>m.id);\n thisModModIds.push(mod.id);\n for (let k=0;k<thisModModIds.length;k++){\n let occurrences = modIds.reduce(function(n, val) {\n return n + (val === thisModModIds[k]);\n }, 0);\n //if theres more than one occurence of something in the \"arrayed\" tree we have a cyclic reference\n if (occurrences > 1){\n found = thisModModIds[k];\n }\n }\n\n }\n\n let parentClone = angular.copy(parent);\n parentClone.modifiers.splice(-1,0,...$modifiers);\n getAllIds(parentClone);\n console.log(\"found:\", found);\n return found ? true : false;\n\n }", "AddModifiedElement(originalIndex, modifiedIndex) {\n // The 'true' start index is the smallest of the ones we've seen\n this.m_originalStart = Math.min(this.m_originalStart, originalIndex);\n this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);\n this.m_modifiedCount++;\n }", "applyDeltaState(delta) {\n this._allowGameObjectSets = true;\n if (delta.gameObjects !== undefined) {\n this._initGameObjects(delta.gameObjects);\n }\n\n this._mergeDelta(this.game, delta);\n this._allowGameObjectSets = false;\n }", "function processModifications(clone, params, options, inRule) {\n for (const param of params) {\n const appendIndex = getTagIndex(param, options.tagAppend);\n const insertIndex = getTagIndex(param, options.tagInsert);\n const replaceIndex = getTagIndex(param, options.tagReplace);\n const currentIndex = Math.max(appendIndex, insertIndex, replaceIndex);\n const modifier = param.slice(currentIndex, param.length);\n let current = clone;\n let nodeIndex = current.type !== 'rule' ? -1 : 0;\n let modified = false;\n while (current.parent && !modified) {\n const selectors = current.parent.selectors;\n if (selectors) {\n nodeIndex++;\n if (nodeIndex >= currentIndex && clone.parent.type !== 'root') {\n // Append\n if (appendIndex > 0) {\n current.parent.selectors = selectors.map(\n selector => selector + modifier);\n // Insert\n } else if (insertIndex > 0) {\n current.parent.selectors = selectors.map(\n selector => `${selector} ${modifier}`);\n // Replace\n } else if (replaceIndex > 0) {\n current.parent.selectors = [modifier];\n } else {\n throw inRule.error('No valid tag found', { word: param });\n }\n modified = true;\n }\n }\n current = current.parent;\n }\n if (!modified) {\n throw inRule.error('No parent to modify found', { word: param });\n }\n }\n return clone;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function$prototype$contramap :: (b > c) ~> (a > b) > (a > c)
function Function$prototype$contramap(f) { var contravariant = this; return function(x) { return contravariant (f (x)); }; }
[ "function compare$contramap(f) {\n return Compare((x,y) => this.compare(f(x), f(y)))\n}", "function Function$prototype$contramap(f) {\n var contravariant = this;\n return function(x) { return contravariant(f(x)); };\n }", "function mappedAsc(map) {\n\n return function (a, b) {\n return asc(map(a), map(b));\n };\n\n }", "function contramap(f, contravariant) {\n return Contravariant.methods.contramap(contravariant)(f);\n }", "function K(a, b, c) {\n return a < b ? b : a > c ? c : a\n}", "function comparator(pred){\n\treturn function(x, y){\n\t\tif(pred(x ,y)) return -1;\n\t\telse if(pred(y ,x)) return 1;\n\t\telse return 0; \n\t}\n}", "function keycomp(key) {\n return function(a, b) {\n var ka = key(a)\n var kb = key(b)\n if (ka < kb) return -1\n if (ka > kb) return 1\n return 0 \n }\n}", "function greaterThanLessThan (a,b,c) {\n return a<b<c\n}", "function keycomp(key) {\n\t return function(a, b) {\n\t\tvar ka = key(a);\n\t\tvar kb = key(b);\n\t\tif (ka < kb) return -1;\n\t\tif (ka > kb) return 1;\n\t\treturn 0;\n\t }\n\t}", "function comparableCompareFn(a, b) {\n //saxonPrint(\"ComparableCompareFn \" + showValue(a) + \"~\" + showValue(b));\n return a.compareTo(b);\n }", "function createCnMap() {\n return kiwi.createMap(kiwi.Constraint.Compare);\n }", "function comp(a, b){\n if (a.age < b.age){ return -1;};\n if (a.age > b.age){ return 1;};\n return 0;\n}", "function createCnMap() {\n return kiwi.createMap(kiwi.Constraint.Compare);\n }", "function gtir(a, b, c, registers) {\n registers[c] = (a > registers[b]) ? 1: 0;\n return registers;\n}", "function CreateLokiComparator() {\n return (val, val2) => {\n if (Object(_operator_packages__WEBPACK_IMPORTED_MODULE_0__[/* aeqHelper */ \"b\"])(val, val2))\n return 0;\n if (Object(_operator_packages__WEBPACK_IMPORTED_MODULE_0__[/* ltHelper */ \"c\"])(val, val2, false))\n return -1;\n return 1;\n };\n}", "function compositeCompareFn(compareFns) {\n return function (a, b) {\n for (var c = 0; c < compareFns.length; c++) {\n //saxonPrint(\"Comparing \" + showValue(a.keys[c]) + \" with \" + showValue(b.keys[c]));\n var z = compareFns[c](a.keys[c], b.keys[c]);\n if (z !== 0) {\n return z;\n }\n }\n return 0;\n };\n }", "gt(other) { return this.cmp(other) > 0; }", "cmp(a, b) {\n let key = a + ':' + b;\n let val = this.cache[key];\n if (val !== undefined) return val;\n\n // let result = (a === b) ? '=' : inputCmp(inputArr[a], inputArr[b], ctx);\n \n // XXX DEBUG1 (replace with the above line)\n let result;\n if (a === b) {\n result = '=';\n } else {\n this.numCmpCalls++;\n result = this.inputCmp(this.inputArr[a], this.inputArr[b]);\n }\n \n this.cache[key] = result;\n\n let otherKey = b + ':' + a;\n let otherResult = result;\n if (result === '<') otherResult = '>';\n if (result === '>') otherResult = '<';\n this.cache[otherKey] = otherResult;\n\n return result;\n }", "function mapAB4(someMap){\n if (someMap.has(\"a\") && someMap.has(\"b\")) {\n let a = someMap.get(\"a\");\n let b = someMap.get(\"b\");\n if(a.length > b.length) {\n someMap.set(\"c\", a);\n }\n else if (b.length > a.length) { \n someMap.set(\"c\", b);\n }\n else { \n someMap.set(\"a\", \"\");\n someMap.set(\"b\", \"\");\n }\n }\n return someMap;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getCommandInput Returns editor's command input.
getCommandInput() { return this.commandInput; }
[ "function getCommandInput()\n {\n var lastLine = $(_consoleSelector).val().split('\\n')[$(_consoleSelector).val().split('\\n').length-1];\n var lastLineSplit = lastLine.split(_promptSymbol);\n var command = \"\";\n var i; \n\n for(i =1; i < lastLineSplit.length; i ++)\n {\n command = command + \" \" + (i >= 2? _promptSymbol : \"\") + lastLineSplit[i]; \n }\n \n return command;\n }", "getCommand() {\n return this.executableCommand\n }", "getCommand() {\n return this.executable_command\n }", "getInput() {\n\t\treturn this.textBox.getText();\n\t}", "getCommand() {\n return this.args[2];\n }", "getInput() {\n return this.input;\n }", "command() {\n return this._command;\n }", "get editor() {\n return this._input.editor;\n }", "getCurrentCommand() {\n return this._current_command;\n }", "getCommand() {\n if (this.positional.length > 0 && typeof this.positional[0] !== \"string\") {\n color.logErr(\"expected a command as first argument'\")\n process.exit(1)\n } else {\n if (this.positional.length === 0) return \"\"\n // take the first argument as this.command\n return this.positional.shift()\n }\n }", "get commandName() {}", "getCommand() {\n return this.args.join(' ');\n }", "getCommandForInputLine(line, getBaseCommand = true) {\n // We assume that the first line with a dollar sign in it is an input\n // line. Therefore we can get the username\n let wholeCommand = line.substring(line.indexOf(\"$\") + 1).trim();\n return getBaseCommand ? wholeCommand.split(\" \")[0] : wholeCommand;\n }", "getDefaultCommand() {\n return this._default_command;\n }", "function getCurrentCmd() {\n\t\treturn $('#commandList').val();\n\t}", "get stdin() {\n return this.process && this.process.stdin\n }", "_getEditInput() {\n return this.contentEditInput || this.defaultEditInput;\n }", "getCommandName() {\n return this.commandName;\n }", "verifyCommandInputValidity() {\n if (this.mode == Editor.MODE_COMMAND) {\n if (this.commandInput.getContent()[0] != \":\")\n this.changeMode(Editor.MODE_GENERAL);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal Helper Functions converts the given number to string and pads it to match at least the given length. The pad value is added in front of the string. This padNumber(4, 5, 0) would convert 4 to '00004'
function padNumber(num, length, pad){ num = String(num); while (num.length < length){ num = String(pad) + num; } return num; }
[ "function pad(number, length){\r\n var str = \"\" + number\r\n while (str.length < length) {\r\n str = '0'+str\r\n }\r\n return str\r\n}", "function pad(number) \n{ \n\tif(number < 10 && String(number).substr(0,1) == '0')\n\t{\n\t\treturn number;\n\t}\n \n\treturn (number < 10 ? '0' : '') + number\n \n}", "function pad (num_str, size)\n{\n while (num_str.length < size) num_str = \"0\" + num_str;\n return num_str;\n}", "function pad(n, padSize) {\n var str = n.toString();\n var padZeros = (new Array(padSize)).join('0');\n return (padZeros + str).substr(-padSize);\n }", "pad(num, size, prefix = '0') {\n let s = num.toString();\n while (s.length < size) {\n s = prefix + s;\n }\n return s;\n }", "function pad(n, padSize) {\n var str = n.toString();\n var padZeros = (new Array(padSize)).join('0');\n return (padZeros + str).substr(-padSize);\n }", "function padWithZeros(number,length) {\n\t var str = \"\" + number;\n\t while( str.length < length ) str = '0' + str;\n\t return str;\n}", "function pad(num_str, size) {\n while (num_str.length < size) num_str = \"0\" + num_str;\n return num_str;\n}", "function pad(width, number)\n{\n return new Array(1 + width - number.length).join('0') + number;\n}", "function pad (str) {while (str.length < 4) str = \"0\" + str; return str;}", "function padNumber(number, length) {\n\t\t\treturn \" \".repeat(length - number.toString().length) + number;\n\t\t}", "function string_pad(num, width, padChar) {\n padChar = padChar || '0';\n num = num + '';\n return num.length >= width ? num : new Array(width - num.length + 1).join(padChar) + num;\n}", "function padNumber(str, length) {\n\tstr = str.toString();\n\twhile (str.length < length) {\n\t\tstr = '0' + str;\n\t}\n//logDisplay(str);\n\treturn str;\n}", "function zeroPad(number, len) {\n var s = number + \"\";\n while(s.length < len) {\n s = \"0\" + s;\n }\n return s;\n}", "function zeroPad(num) {\n if (num < 10) {\n return \"0\" + num.toString();\n } else {\n return num.toString();\n }\n}", "function padded(value) {\n return value < 10 ? '0' + value : value;\n}", "function pad(value) {\n var length = value.length;\n\n if (length >= DEFAULT) {\n return value;\n }\n\n if (length === 3) {\n return value + '0';\n }\n\n if (length === 2) {\n return value + '00';\n }\n\n return value + '000';\n}", "function leftPad(number, targetLength) {\n var output = number + '';\n while (output.length < targetLength) {\n output = '0' + output;\n }\n return output;\n}", "function addPadding(number) {\n var a = (\"00000000\" + number).slice(-8);\n return a;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns num as a hexadecimal string, padded to length characters by adding leading 0's.
function intToHex(num, length) { var ret = num.toString(16); while (ret.length < length) { ret = '0' + ret; } return ret; }
[ "function hexStr(num, length, prefix) {\n let str = \"\";\n if (prefix === undefined || prefix === true) str += \"0x\";\n else if (prefix === false) str = \"\";\n else str = prefix;\n return str + num\n .toString(16)\n .toUpperCase()\n .padStart(length, \"0\");\n}", "function toFixedHex(num, len) {\n return num.toString(16).toUpperCase().padStart(len, '0').substring(0, len)\n}", "function fixedHex(number, length){\n\t\tvar str = number.toString(16).toUpperCase();\n\t\twhile(str.length < length)\n\t\t\tstr = \"0\" + str;\n\t\treturn str;\n\t}", "function completeHex(num){\r\n var n = num + \"\"; \r\n while (n.length < 8) n = \"0\" + n;\r\n return n;\r\n}", "function hexpad(number) {\n return number.toString(16).toUpperCase().padStart(2, '0');\n}", "function toHex(nbr, len) {\n return (\"0\"+(Number(nbr).toString(16))).slice(-len).toUpperCase()\n}", "function hexString(num, pad) {\n if (num < 0) num = 0xFFFFFFFF + num + 1;\n var hex = num.toString(16).toUpperCase();\n if (isNumber(pad)) hex = hex.padStart(pad, \"0\");\n return (\"0x\" + hex);\n}", "function pad(number, length){\r\n var str = \"\" + number\r\n while (str.length < length) {\r\n str = '0'+str\r\n }\r\n return str\r\n}", "function zeroPad(number, len) {\n var s = number + \"\";\n while(s.length < len) {\n s = \"0\" + s;\n }\n return s;\n}", "function hexOfInt(num, n) {\n var returnString = num.toString(16);\n if (returnString.length < n) {\n return \"0\".repeat(n - returnString.length) + returnString;\n } else {\n return returnString;\n }\n}", "pad(num, size, prefix = '0') {\n let s = num.toString();\n while (s.length < size) {\n s = prefix + s;\n }\n return s;\n }", "function pad0(val, length)\n{\n val = val.toString();\n\n while (val.length < length)\n {\n val = '0' + val;\n }\n\n return val;\n}", "function zeroPad(num){\n return (num < 10 ? \"0\" + num.toString() : num.toString());\n }", "function pad (num_str, size)\n{\n while (num_str.length < size) num_str = \"0\" + num_str;\n return num_str;\n}", "function hex($num) {\n var str = \"\";\n for(var j = 7; j >= 0; j--)\n str += _chars.charAt(($num >> (j * 4)) & 0x0F);\n return str;\n }", "function toHex(n){return (n<16?\"0\":\"\")+n.toString(16);}", "function hexpad16(num,size) { \n var size = 4;\n var s = \"0000\" + num;\n return s.substr(s.length-size);\n }", "function padNumber(num, length, pad){\n num = String(num);\n while (num.length < length){\n num = String(pad) + num;\n }\n return num;\n }", "function hexpad16(num,size) {\n var size = 4;\n var s = \"0000\" + num;\n return s.substr(s.length-size);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wrap SocialShare in order to plug into Container necessary tradeoff to deal with class component in the store connector
function SocialShareWrapper (props) { return html` <buv-social-share-raw url='${props.url}' onShare='${props.onShare}' display='${props.display}' ></buv-social-share-raw>`; }
[ "function ShareSDKPlugin () {}", "function Share(hoodie) {\n var api;\n this.hoodie = hoodie;\n this._open = this._open.bind(this);\n\n // set pointer to Hoodie.ShareInstance\n this.instance = Hoodie.ShareInstance;\n\n // return custom api which allows direct call\n api = this._open;\n $.extend(api, this);\n\n this.hoodie.store.decoratePromises({\n shareAt: this._storeShareAt,\n unshareAt: this._storeUnshareAt,\n unshare: this._storeUnshare,\n share: this._storeShare\n });\n return api;\n }", "function SocialWrapper() {\n\n /*\n * Retrieves the current viewer.\n */\n this.getViewer = function(callback) {\n osapi.people.getViewer().execute(callback);\n }\n\n /*\n * Retrieves the current owner.\n */\n this.getOwner = function(callback) {\n osapi.people.getOwner().execute(callback);\n }\n\n // ------------------------ ALBUMS ----------------------\n /*\n * Retrieves albums by ID(s).\n */\n this.getAlbumsById = function(userId, albumId, callback) {\n var params = {userId: userId, albumId: albumId};\n osapi.albums.get(params).execute(callback);\n }\n\n /*\n * Retrieves albums by user.\n */\n this.getAlbumsByUser = function(userId, callback) {\n osapi.albums.get({userId: userId}).execute(callback);\n }\n\n /*\n * Retrieves albums by group.\n */\n this.getAlbumsByGroup = function(userId, groupId, callback) {\n osapi.albums.get({userId: userId, groupId: groupId}).execute(callback);\n }\n\n /*\n * Creates an album for the given user.\n */\n this.createAlbum = function(userId, album, callback) {\n var params = {\n userId: userId,\n album: album\n };\n osapi.albums.create(params).execute(callback);\n }\n\n /*\n * Updates an album by ID.\n */\n this.updateAlbum = function(userId, albumId, album, callback) {\n var params = {\n userId: userId,\n albumId: albumId,\n album: album\n };\n osapi.albums.update(params).execute(callback);\n }\n\n /*\n * Deletes an album by ID.\n */\n this.deleteAlbum = function(userId, albumId, callback) {\n var params = {userId: userId, albumId: albumId};\n osapi.albums['delete'](params).execute(callback);\n }\n\n // ------------------------------- MEDIAITEMS ----------------------------\n /*\n * Creates a MediaItem.\n */\n this.createMediaItem = function(userId, albumId, mediaItem, callback) {\n var params = {\n userId: userId,\n albumId: albumId,\n mediaItem: mediaItem\n };\n osapi.mediaItems.create(params).execute(callback);\n }\n\n /*\n * Updates a MediaItem by ID.\n */\n this.updateMediaItem = function(userId, albumId, mediaItemId, mediaItem,\n callback) {\n var params = {\n userId: userId,\n albumId: albumId,\n mediaItemId: mediaItemId,\n mediaItem: mediaItem\n };\n console.log('PARAMS: ' + JSON.stringify(params));\n osapi.mediaItems.update(params).execute(callback);\n }\n\n /*\n * Retrieves MediaItems by ID(s).\n */\n this.getMediaItemsById = function(userId, albumId, mediaItemId, callback) {\n var params = {\n userId: userId,\n albumId: albumId,\n mediaItemId: mediaItemId\n };\n osapi.mediaItems.get(params).execute(callback);\n }\n\n /*\n * Retrieves MediaItems by album.\n */\n this.getMediaItemsByAlbum = function(userId, albumId, callback) {\n osapi.mediaItems.get({userId: userId, albumId: albumId}).execute(callback);\n }\n\n /*\n * Retrieves MediaItems by user and group.\n */\n this.getMediaItemsByUser = function(userId, groupId, callback) {\n osapi.mediaItems.get({userId: userId, groupId: groupId}).execute(callback);\n }\n\n /*\n * Deletes a MediaItem by ID.\n */\n this.deleteMediaItem = function(userId, albumId, mediaItemId, callback) {\n var params = {\n userId: userId,\n albumId: albumId,\n mediaItemId: mediaItemId\n };\n osapi.mediaItems['delete'](params).execute(callback);\n }\n}", "function ShareWidget(options) {\r\n AnimatedWidget.call(this, options);\r\n\r\n this.element.addClass(\"ShareWidget addthis_toolbox addthis_default_style\");\r\n\r\n var smallIcons = ($(window).height() <= 16);\r\n\r\n if (this.options.services) {\r\n this.options.services.split(\",\").forEach(function (service) {\r\n this.element.append(\"<a class='addthis_button_\" + service + \"'>\" +\r\n // We create the images ourselves so that we can easily scale them. the ones inserted automatically by AddThis are background images on nested elements.\r\n // Use the small icons if the widget is small enough.\r\n \"<img src='//cache.addthiscdn.com/icons/v1/thumbs/\" + (smallIcons ? \"\" : \"32x32/\") + service + (smallIcons ? \".gif\" : \".png\") + \"'/>\" +\r\n \"</a>\");\r\n }, this);\r\n\r\n var scope = this;\r\n this.on(\"activate\", function (publicationID, currentPages, widgetPages) {\r\n if (!scope.sharingInitialized) {\r\n // Wait with initializing the sharing until the first activate event so we can get the publication ID.\r\n AddThis.toolbox(\".ShareWidget\", {}, {\r\n url: scope.getShareUrl(publicationID, widgetPages && widgetPages.firstPage),\r\n title: scope.options.title\r\n });\r\n scope.sharingInitialized = true;\r\n }\r\n });\r\n }\r\n\r\n this.initialized.resolve();\r\n }", "function updateSocialPlugin(){\n if(typeof bcPlayer.croSocial === 'function'){\n var mediainfo = bcPlayer.mediainfo;\n if(mediainfo) {\n var socialOptions = {};\n socialOptions.title = mediainfo.title;\n socialOptions.description = mediainfo.description;\n socialOptions.url = createSharingUrl(mediainfo);\n socialOptions.services = {\n facebook: true,\n google: true,\n twitter: true,\n tumblr: false,\n pinterest: true,\n linkedin: false\n };\n bcPlayer.croSocial(socialOptions);\n }\n\n\n }\n }", "function loadSocialModule() \n\t{\n\t\tOO = window[_args[0]];\n\t\tOO.plugin(\"DellUIModule\", function(OO, _, $, W) {\n\t\t\tvar Plugin = {};\n\t\t\tPlugin.DellUIModule = function(mb, id) {\n\t\t\t\tthis.mb = mb;\n\t\t\t\tthis.id = id;\n\t\t\t\tthis.init();\n\t\t\t};\n\t\t\tPlugin.DellUIModule.prototype = \n\t\t\t{\n\t\t\t\tinit: function() {\n\t\t\t\t\tthis.mb.subscribe(OO.EVENTS.PLAYER_CREATED, 'socialUI', _.bind(this.onPlayerCreate, this));\n\t\t\t\t\tthis.mb.subscribe(OO.EVENTS.CONTENT_TREE_FETCHED, 'socialUI', _.bind(this.onContentTreeFetched, this));\n\t\t\t\t},\n\t\t\t\tonPlayerCreate: function(event, elementId, params) {\n\t\t\t\t\tthis.playerRoot = $(\"#\" + elementId);\n\n\t\t\t\t\t/* --------------- Social Media Share */\n\t\t\t\t\tthis.playerRoot = $(\"#\" + elementId);\n\t\t\t\t\tthis.playerRoot.find('.oo_controls_wrap').append('<div class=\"oo_share_container\"></div>');\n\t\t\t\t\tthis.playerRoot.find('.oo_share_container').append('<div class=\"oo_button oo_toolbar_item oo_fb_share oo_sms\"></div>');\n\t\t\t\t\t$('.oo_fb_share').click(function() {\n\t\t\t\t\t\tvar uf = location.href;\n\t\t\t\t\t\tvar tf = document.title;\n\t\t\t\t\t\twindow.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(uf) + '&t=' + encodeURIComponent(tf),'sharer','toolbar=0,status=0,width=600,height=400');return false;\n\t\t\t\t\t});\n\t\t\t\t\tthis.playerRoot.find('.oo_share_container').append('<div class=\"oo_button oo_toolbar_item oo_tw_share oo_sms\"></div>');\n\t\t\t\t\t$('.oo_tw_share').click(function() {\n\t\t\t\t\t\tvar ut = location.href;\n\t\t\t\t\t\tvar tt = document.title;\n\t\t\t\t\t\tvar maxLength = 140 - (ut.length + 1);\n\t\t\t\t\t\tif (tt.length > maxLength)\n\t\t\t\t\t\t\ttt = tt.substr(0, (maxLength - 3)) + '...';\n\t\t\t\t\t\twindow.open('http://twitter.com/home?status=' + encodeURIComponent(tt + ' ' + ut),'sharer','toolbar=0,status=0,width=600,height=400');return false;\n\t\t\t\t\t});\n\t\t\t\t\tvar hideTimer;\n\t\t\t\t\tfunction hideShareContainer() {$('.oo_share_container').slideUp(1000);}\n\t\t\t\t\tfunction showShareContainer() {\n\t\t\t\t\t\tclearTimeout(hideTimer);\n\t\t\t\t\t\t$('.oo_share_container').slideDown(500);\n\t\t\t\t\t}\n\t\t\t\t\t$('.oo_tap_panel').hover(\n\t\t\t\t\t\tfunction(){showShareContainer();},\n\t\t\t\t\t\tfunction(){hideTimer = setTimeout( hideShareContainer,1500);}\n\t\t\t\t\t);\n\t\t\t\t\t$('.oo_share_container').hover(\n\t\t\t\t\t\tfunction(){showShareContainer();},\n\t\t\t\t\t\tfunction(){hideTimer = setTimeout( hideShareContainer,1500);}\n\t\t\t\t\t);\n\t\t\t\t\t/* --------------- Social Media Share */\n\t\t\t\t},\n\t\t\t\tonContentTreeFetched: function(event, content) {},\n\t\t\t\t__end_marker: true\n\t\t\t};\n\t\t\treturn Plugin.DellUIModule;\n\t\t});\n\t}", "share() {\n\t\t\tvar stx = this.context.stx;\n\t\t\tvar self = this;\n\t\t\tself.setState(\"share-generate\");\n\t\t\tvar shareDialog = document.querySelector(\n\t\t\t\t\"cq-share-dialog .share-link-div\"\n\t\t\t);\n\t\t\tif (shareDialog) shareDialog.innerHTML = \"\";\n\t\t\t// \"hide\" is a selector list, of DOM elements to be hidden while an image of the chart is created. \"cq-comparison-add-label\" and \".chartSize\" are hidden by default.\n\t\t\tCIQ.UI.bypassBindings = true;\n\t\t\tCIQ.Share.createImage(\n\t\t\t\tstx,\n\t\t\t\t{\n\t\t\t\t\thide: [\n\t\t\t\t\t\t\".stx_chart_controls\",\n\t\t\t\t\t\t\".stx-btn-panel\",\n\t\t\t\t\t\t\".stx_jump_today\",\n\t\t\t\t\t\t\".stx-baseline-handle\",\n\t\t\t\t\t\t\".ciq-edit\",\n\t\t\t\t\t\t\".ciq-close\",\n\t\t\t\t\t\t\"cq-marker-label\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\tfunction (data) {\n\t\t\t\t\tCIQ.UI.bypassBindings = false;\n\t\t\t\t\tvar id = CIQ.uniqueID();\n\t\t\t\t\tvar host = \"https://share.chartiq.com\";\n\t\t\t\t\tvar startOffset = stx.getStartDateOffset();\n\t\t\t\t\tvar metaData = {\n\t\t\t\t\t\tlayout: stx.exportLayout(),\n\t\t\t\t\t\tdrawings: stx.exportDrawings(),\n\t\t\t\t\t\txOffset: startOffset,\n\t\t\t\t\t\tstartDate: stx.chart.dataSegment[startOffset].Date,\n\t\t\t\t\t\tendDate:\n\t\t\t\t\t\t\tstx.chart.dataSegment[stx.chart.dataSegment.length - 1].Date,\n\t\t\t\t\t\tid: id,\n\t\t\t\t\t\tsymbol: stx.chart.symbol\n\t\t\t\t\t};\n\t\t\t\t\tvar url = host + \"/upload/\" + id;\n\t\t\t\t\tvar payload = { id: id, image: data, config: metaData };\n\t\t\t\t\tself.setState(\"share-upload\");\n\t\t\t\t\tCIQ.Share.uploadImage(data, url, payload, function (err, response) {\n\t\t\t\t\t\tself.setState(\"share-copy\");\n\t\t\t\t\t\tif (err !== null) {\n\t\t\t\t\t\t\tCIQ.alert(\"error: \" + err);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (shareDialog) shareDialog.innerHTML = host + response;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\t\t}", "function Metatagsforshare(props) {\n return (\n <div className=\"wrapper\">\n <MetaTags>\n <meta property=\"fb:app_id\" content=\"413223529303378\"/>\n <meta property=\"og:url\" content={window.location.href}/>\n <meta property=\"og:type\" content=\"article\"/>\n <meta property=\"og:title\" content={props.title}/>\n <meta property=\"og:description\" content={props.description}/>\n <meta property=\"og:image\" content={props.image}/>\n </MetaTags>\n </div>\n );\n }", "constructor() \n {\n var $this = this;\n\n if(!jQuery(\".webshare-list-item\").length) {\n return;\n }\n \n $(document).ready(function() {\n if (navigator.share) {\n $this.addWebShareButtonClickHandler();\n $this.removeSocialSharebuttons();\n } else {\n $this.removeWebSharebutton();\n }\n });\n }", "function initSharingButtons() {\n $('.prettySocial').prettySocial();\n }", "render(){\n return(\n <WeShareView/>\n )\n }", "function SharingPlugin($window, $q, $log, PluginUtils){\n var pluginName = 'SocialSharing';\n var pluginTest = function(){ return $window.plugins && $window.plugins.socialsharing; };\n var service = {\n share: share,\n shareViaFacebook: shareViaFacebook,\n shareViaTwitter: shareViaTwitter,\n shareViaEmail: shareViaEmail\n };\n\n // _fileOrFileArray can be null, a string or an array of strings\n function share(message, _subject, _fileOrFileArray, _link){\n return PluginUtils.onReady(pluginName, pluginTest).then(function(){\n var defer = $q.defer();\n $window.plugins.socialsharing.share(message, _subject || null, _fileOrFileArray || null, _link || null, function(){\n defer.resolve();\n }, function(error){\n $log.error('pluginError:'+pluginName, error);\n defer.reject(error);\n });\n return defer.promise;\n });\n }\n\n function shareViaFacebook(message, _fileOrFileArray, _link){\n return PluginUtils.onReady(pluginName, pluginTest).then(function(){\n var defer = $q.defer();\n $window.plugins.socialsharing.shareViaFacebookWithPasteMessageHint(message, _fileOrFileArray || null, _link || null, 'Tu peux coller le message par défaut si tu veux...', function(){\n defer.resolve();\n }, function(error){\n $log.error('pluginError:'+pluginName, error);\n defer.reject(error);\n });\n return defer.promise;\n });\n }\n\n function shareViaTwitter(message, _file, _link){\n return PluginUtils.onReady(pluginName, pluginTest).then(function(){\n var defer = $q.defer();\n $window.plugins.socialsharing.shareViaTwitter(message, _file || null, _link || null, function(){\n defer.resolve();\n }, function(error){\n $log.error('pluginError:'+pluginName, error);\n defer.reject(error);\n });\n return defer.promise;\n });\n }\n\n function shareViaEmail(message, _subject, _fileOrFileArray){\n return PluginUtils.onReady(pluginName, pluginTest).then(function(){\n var defer = $q.defer();\n $window.plugins.socialsharing.shareViaEmail(message, _subject || null, null /*to*/, null /*cc*/, null /*bcc*/, _fileOrFileArray || null, function(){\n defer.resolve();\n }, function(error){\n $log.error('pluginError:'+pluginName, error);\n defer.reject(error);\n });\n return defer.promise;\n });\n }\n\n return service;\n }", "function PageShare() {\n _classCallCheck$k(this, PageShare);\n }", "function shareContent(container, type){\n\n // Store raw values to later check if undefined/empty\n var postImg = $(container).find('.slick-slides').find('.post-thumb').find('img').attr('src'),\n vidImg = $(container).data('src');\n\n // Create object to neatly store titles, images, links.\n var shareInfo = {\n\n link: $(container).find('.entry-title').find('a').attr('href'),\n name: $(container).find('.entry-title').find('a').html(),\n image : (function checkImage() {\n\n if (postImg === undefined) {\n return 'https://img.youtube.com/vi/' + vidImg + '/hqdefault.jpg';\n } else if (!vidImg) {\n return postImg;\n } else {\n // @TODO: Specify default meta image\n return postImg;\n }\n\n })()\n };\n\n\n switch (type) {\n case 'facebook':\n // Insert object values into FB.ui feed dialogue\n FB.ui(\n {\n method: 'feed',\n name: shareInfo.name,\n caption: shareInfo.name,\n picture: shareInfo.image,\n link: shareInfo.link\n },\n\n function (response) {\n // @TODO: Catch errors, and/or say thanks on success!\n });\n break;\n default:\n }\n\n}", "bindSocials(){\n\t\tlet self = this;\n\t\tlet socials = document.getElementsByClassName('share-icon');\n\n\t\tfor (let i = 0; i < socials.length; i++ ){\n\t\t\tsocials[i].addEventListener('click', self.share, false);\n\t\t}\n\t}", "share (network) {\n this.openSharer(network, this.createSharingUrl(network));\n\n this.$root.$emit('social_shares_open', network, this.url);\n this.$emit('open', network, this.url);\n }", "function setupSocialShares(){\n\n\t\t$( '.facebook-share' ).on( 'click', function(){\n\n\t\t\twindow.open( \"https://facebook.com/sharer.php?u=\" + encodeURIComponent( window.location ), \"\", \"width=500,height=275,top=100,left=100\" );\n\n\t\t} );\n\n\t\t$( '.twitter-share' ).on( 'click', function(){\n\n\t\t\twindow.open(\"https://twitter.com/intent/tweet?text=\" + truncateTitle( $( '.content-title' ).text() ) + \"&url=\" + encodeURIComponent( window.location ), \"\", \"width=500,height=275,top=100,left=100\" );\n\n\t\t} );\n\n\t}", "function getShareDivWrapper$() {\n\t\t\treturn $('<div/>').addClass('form-group shareDiv').append(\n\t\t\t\t$('<textarea/>').addClass('form-control ASWidgetshareBoxInput')\n\t\t\t\t\t.attr('placeholder', localizeString(\"ASWidget-share-sharebox-placeholder\", \"What do you want to share?\"))\n\t\t\t);\n\t\t}", "function initSocialSharingWidget() {\n var widget = $('#tesla-social-widget');\n var type = null;\n var url = null;\n var message = null;\n var page = document.URL;\n var width = 550\n var height = 450;\n if (widget.length !== 0) {\n widget.find('a').each(function() {\n type = $(this).attr('class');\n switch (type) {\n case 'facebook':\n url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(page);\n break;\n case 'twitter':\n message = $(this).find('span').text();\n url = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(message) + '&url=' + encodeURIComponent(page) + '&via=' + encodeURIComponent('TeslaMotors') + '&related=' + encodeURIComponent('TeslaMotors,elonmusk');\n break;\n case 'google':\n url = 'https://plus.google.com/share?url=' + encodeURIComponent(page);\n break;\n }\n if (url !== null) {\n $(this).attr('href', url);\n }\n });\n widget.on('click', 'a', function(e) {\n e.preventDefault();\n window.open($(this).attr('href'), '_blank', 'width=' + width + ', height=' + height);\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update an adaptive card
async function update_card( p, cardId, card ) { console.log("Updating card..."); try { var resp = await p.put(`/team-messaging/v1/adaptive-cards/${cardId}`, card) }catch (e) { console.log(e.message) } }
[ "async function update_card( cardId, card ) {\n console.log(\"Updating card...\");\n try {\n var resp = await platform.put(`/team-messaging/v1/adaptive-cards/${cardId}`, card)\n }catch (e) {\n\t console.log(e.message)\n\t }\n}", "function updateCard() {\n\n // 6-1 Create the payload object.\n const payload = {\n fields: {\n Name: this.name,\n Notes: this.note\n }\n }\n\n // 6-2 Edit the card:\n this.editCard(this.idToEdit, payload)\n}", "updateDealtCards() {\n this.updateBlackjackState();\n }", "updateCard() {\n this.addAddress();\n this.addWeatherData();\n }", "function updateCard() {\n $window.requestAnimationFrame(transformCard);\n }", "updateCard(event) {\n // Grab editor window textarea element\n var editorText = document.getElementById(\"editorText\");\n // Grab editor window video element\n var editorVideo = document.getElementById(\"editorVideo\");\n // grab selected card's index\n var currCardIndex = editorText.cardindex;\n\n // grab array from app.js which holds each clipcard's info\n var cardContainer = this.props.cardContainer;\n // get selected clipcard's info\n var currCardInfo = cardContainer[currCardIndex]\n console.log(\"current card state: \", currCardInfo)\n // get the current card's text and video values\n var currCardText = document.getElementById(currCardInfo['id']).children[0].children[1]\n var currCardMedia = document.getElementById(currCardInfo['id']).children[2];\n // update the card's text value to be the editor window's text's value\n currCardText.value = editorText.value\n // update the card's video source to be the editor window's video source\n currCardMedia.src = editorVideo.src\n\n var clipCard = this.state.clipCard;\n clipCard.mediaPath = currCardMedia.src;\n clipCard.text = currCardText.value\n this.setState({\n 'clipCard': clipCard,\n });\n\n console.log(\"card container: \", cardContainer)\n }", "function updateCard(options, tokens, callback) {\n\tmirrorCall(\n\t\tmirror.timeline.list({ \"sourceItemId\": options.sourceItemId,\n\t\t\t\"isPinned\": options.isPinned || true }),\n\t\ttokens,\n\t\tfunction(err,data) {\n\t\t\tlogOnErr(err);\n\n\t\t\tif (data && data.items.length > 0) {\n\t\t\t\toptions.id = data.items[0].id;\n\t\t\t\tpatchCard(options, tokens, callback);\n\t\t\t} else {\n\t\t\t\tinsertCard(options, tokens, callback);\n\t\t\t}\n\t\t}\n\t);\n}", "function updatingCard(rejName, rejectId,rejectNote,card) {\n card.rejectReasonName = rejName;\n card.rejectReason = rejectId;\n card.rejectNote = rejectNote; \n }", "function cardUpdateListener(data) {\n AppData.setCardContent(data[\"card\"], data[\"newContent\"]);\n \tAppData.saveData();\n }", "function updateFlashcard(flashcard) {\n $.ajax({\n method: \"PUT\",\n url: \"/api/flashcards\",\n data: flashcard\n })\n .then(function() {\n window.location.href = \"/view_cards?subject_id=\";\n });\n }", "function updateCapacitiesForCard(card) {\n\n\tfor (var model_number= 0; model_number<card.models.length; model_number++ ) {\n\t\tmodel = card.models[model_number];\n\t\tfor (var i=0; i<model.capacities.length; i++ ) {\n\t\t\tmodel_capa = model.capacities[i];\n\t\t\t// search in capacities\n\t\t\tif (model_capa._id) { // case model_capa is bad data\n\t\t\t\tvar $capa = capacities_map[model_capa._id.$oid];\n\t\t\t\tmodel_capa._title = $capa._title;\n\t\t\t\tmodel_capa._type = $capa._type;\n\t\t\t\tmodel_capa.__text = $capa.__text;\n\t\t\t}\n\t\t}\n\t}\n\t\n}", "function updateEditorContent(cardObject){\n document.getElementById(\"editor_title\").innerHTML = `编辑卡片${cardObject.cardId}` \n \n updateTextfield(\"eCardId\", cardObject.cardId )\n document.getElementById(\"cardType\").value = cardObject.cardType\n document.getElementById(\"timeLimit\").value = cardObject.timeLimit\n updateTextfield(\"eInstructionText\", cardObject.instructionText )\n updateTextfield(\"eCardText\", cardObject.cardText )\n updateTextfield(\"eCardImage\", cardObject.cardImage )\n updateTextfield(\"eComment\", cardObject.comment ) \n cardObject.actions.forEach(element => {\n document.getElementById(`actionTitle${element.order}`).innerHTML = actionSelector(cardObject.cardType, element.order)\n updateTextfield(`eActionCardText${element.order}`, element.text ) \n updateTextfield(`eNextCardId${element.order}`, element.nextCardId ) \n updateTextfield(`eInterest${element.order}`, element.playerData) \n });\n}", "onUpdateCardInPlay(cardObj) {\n // If a card in play hasn't been set, we need to add the first one to the\n // scene.\n if (!this.currentCardInPlay) {\n const card = new Card(this, this.camera.centerX, this.camera.centerY, cardObj.suit, cardObj.value, cardObj.name);\n this.deck.addCardToPlayPile(card);\n }\n\n // If the card has no value, this means it's a wildcard, show a\n // notification to the player.\n if (!cardObj.value) {\n this.showWildcardMessage(cardObj.suit);\n }\n\n // Play an explosion sound when the queen of spades is played (pickup 5).\n if (cardObj.name === 'q of spades') {\n this.sound.play('explosion');\n }\n\n this.currentCardInPlay = cardObj;\n }", "static adaptiveCard(card) {\n return { contentType: CardStyler.contentTypes.adaptiveCard, content: card };\n }", "updateCardForServer() {\n const data = {\n boardID: this.board.boardID,\n cardID: this.card.cardID,\n cardName: this.card.cardName,\n cardOrder: this.card.order,\n };\n network.cardSet(data).then((response) => {\n return response.json();\n }).then((responseBody) => {\n if (responseBody.status > 200) {\n if (!network.ifTokenValid(responseBody)) {\n this.createCardForServer();\n return;\n }\n this.eventBus.emit('cardModel:setCardFailed', responseBody.codes);\n } else {\n this.eventBus.emit('cardModel:setCardSuccess', responseBody);\n }\n return responseBody;\n });\n }", "updateCardData(cardObject) {\n let card = this.getById(cardObject.id);\n let index = this.items.indexOf(card);\n let tmpCard = this.CardFactory.create(this.dashboard, _.clone(cardObject));\n\n let promise = this.$q.when(true);\n\n // don't load card data if some other card is viewed in explore mode or card builder\n if(card.isBeingLookedAt()) promise = tmpCard.metrics.getLoadPromise();\n\n return promise.then(() => {\n // Positioning is staying original for the card because request for\n // additional data can be cached, so positions will not be loaded each time\n\n let currentDashboardCard = this.items[index];\n for (let key in currentDashboardCard) {\n if (tmpCard.hasOwnProperty(key) && key !== 'positioning') {\n currentDashboardCard[key] = tmpCard[key];\n }\n }\n \n if(!this.batch.enabled) {\n // Preload current user cache with cards\n this.CardCacheHelperService.setCard(this.dashboard, currentDashboardCard);\n } else {\n this.batch.items.push(currentDashboardCard);\n }\n\n return currentDashboardCard;\n });\n }", "function updateInterface() {\n let riskLevel = 0;\n let value = 0;\n // get riskLevel\n for (let i = 0; i < cards.length; i++) {\n // if orange\n if (cards[i].colorId === 1) {\n riskLevel += 15;\n // if red\n } else if (cards[i].colorId === 2) {\n riskLevel += 30;\n }\n value += cards[i].value; // get total value\n }\n // convert riskLevel into colors\n if (riskLevel >= 0 && riskLevel < 33) {\n videoInterface.setRisk(0);\n } else if (riskLevel >= 33 && riskLevel < 66) {\n videoInterface.setRisk(1);\n } else if (riskLevel >= 66) {\n videoInterface.setRisk(2);\n }\n videoInterface.setValue(value); // update value\n // calculate and update rank\n let rank = map(stats.views, 0, MOST_VIEWS, 1, ACTIVE_USERS, true);\n videoInterface.setRank(ACTIVE_USERS - rank);\n}", "updateAllStats(card=null) {\n if (card) {\n card.document.find(`.pcm_hitStats`).css('cursor', 'default');\n card.document.find(`${this.accepted.class}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n card.document.find(`${this.fetched.class}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n } else {\n $(`${this.accepted.id}_${this.myId}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n $(`${this.fetched.id}_${this.myId}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n $(`${this.accepted.id2}_${this.myId}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n $(`${this.fetched.id2}_${this.myId}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n }\n }", "updateCardSettings(update) {\n this.parseParameters(this.props);\n if (this.state.type === \"bar\" || this.state.type === \"line\") {\n this.state.propertiesSelected = []\n }\n if (this.state.type !== \"NONE\") {\n this.forceRefreshByQueryChange()\n }\n this.props.onChange({\"label\": \"CardStateChanged\", \"id\": this.props.id, \"state\": this.state});\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a text element that can be styled (actually a hidden ), and adds it to the specified node. Also, adds parameters to the element and its style as specified. Returns the new element.
function addStyledText(node, text, style_params, params) { node.appendChild(document.createElement("span")); if (params != undefined) { var index = 1; while (index < params.length) { node.lastChild[params[index-1]] = params[index]; index += 2; } } if (style_params != undefined) { var index = 1; while (index < style_params.length) { node.lastChild.style[style_params[index-1]] = style_params[index]; index += 2; } } node.lastChild.appendChild(document.createTextNode(text)); return node.lastChild; }
[ "function appendTextChild(text, node, element, idname) {\n\n // Check input.\n if ( text === undefined || text === null || node === undefined\n || node === null || element === undefined || element === null) {\n return null;\n }\n\n // Create styled text node.\n var txt = document.createTextNode(text);\n var el = _createel(element, idname);\n el.appendChild(txt);\n node.appendChild(el);\n\n return el;\n}", "function addNode(parent, element, nameId, text, styleClass)\n{ \n var newNode = document.createElement(element);\n parent.appendChild(newNode);\n newNode.setAttribute(\"id\", nameId);\n newNode.setAttribute(\"name\", nameId);\n\tnewNode.setAttribute(\"class\", styleClass);\n if (text != \"\")\n {\n var textNode = document.createTextNode(text);\n newNode.appendChild(textNode);\n }\n return newNode;\n}", "function element(x){\n var newItem = document.createElement(\"x\");\n var textnode = document.createTextNode(\"AWESOME\");{\n textnode.style.position = \"fixed\";\n textnode.style.zIndex = \"2147483647\";\n textnode.style.Left = \"20px\";\n textnode.style.Top = \"100px\";\n textnode.style.fontSize = \"200px\";\n\n }\nnewItem.appendChild(textnode);\ndocument.getElementById(\"x\").appendChild(newItem)\n}", "function createStyledNode(textContent, className) {\n let newNode = doc.createElement(\"span\");\n newNode.classList.add(className);\n newNode.textContent = textContent;\n return newNode;\n }", "function createText(text) {\n return document.createTextNode(text);\n }", "function createText(text) {\n\t return document.createTextNode(text);\n\t }", "function createElem (elem, className, parent, text) {\n let newElement = document.createElement(elem);\n newElement.classList.add(className);\n parent.appendChild(newElement);\n newElement.innerText = text\n return newElement;\n}", "createElementWithText(element, text, id, className, elementValue) {\n const newElement = document.createElement(element)\n if (text) {\n newElement.textContent = text \n } \n \n if (id) { \n newElement.id = id \n \n }\n\n if (className) {\n newElement.classList.add(className)\n }\n if (elementValue) {\n newElement.setAttribute(\"value\", elementValue)\n }\n return newElement\n }", "txt({x1, x, y1, y, text = \"Default text\", style, fontStyle, layer = this.topLayer} = {}) {\n //*****************************\n // Create a new text and set its id.\n let newText = new Text(...arguments);\n newText.id = this.generateElementId();\n\n let lookAndFeel = new LookAndFeel();\n let drawer = lookAndFeel.getDrawerFor(newText);\n drawer.svgArea = this;\n let drawnText = drawer.draw(newText);\n this.svg.appendChild(drawnText);\n\n newText.addTag({key: SVGAreaConstants.DRAWN, value: drawnText});\n newText.text = text; // Recalculate the text width calling a listener.\n\n this.registerEvents(newText, drawnText);\n\n return this.addElement({element: newText, layer: layer});\n }", "function createTextElement(elementType, elementValue, parent, className) {\n element = document.createElement(elementType);\n value = document.createTextNode(elementValue);\n if (className != undefined) {\n element.className = className;\n }\n\n element.appendChild(value);\n parent.appendChild(element);\n}", "function addTextNode(/* HTML node*/parentNode, /* String */text, /* String*/className) {\n\tif (isEmpty(text)) return null;\n\tnewNode = document.createElement('span');\n\tif (className) {\n\t\tnewNode.className = className;\n\t}\n\tif (text) {\n\t\tnewNode.appendChild(document.createTextNode(text));\n\t}\n\tif (parentNode) {\n\t\tparentNode.appendChild(newNode);\n\t}\n\treturn newNode;\n}", "function createText(parent, innerText){\n\tvar textInput = document.createElement(\"input\");\n\ttextInput.setAttribute(\"type\", \"text\");\n\ttextInput.setAttribute(\"id\", \"newText\");\n\ttextInput.setAttribute(\"size\", 50);\n\ttextInput.value = innerText;\n\tparent.appendChild(textInput);\n}", "function CreateElementWithText(tagname, content){\n var tag = document.createElement(tagname);\n return tag.appendChild(document.createTextNode(content));\n}", "function makeEmnt(parent, elTyp, className, inText) {\n const tempELm = document.createElement(elTyp);\n tempELm.classList.add(className);\n if (inText) tempELm.innerText = inText;\n parent.appendChild(tempELm);\n\n return tempELm;\n}", "function drawTextStyle(svgParent, innerText, startPoint, cssClass, id) {\r\n\t//create element\r\n\tvar t = document.createElementNS('http://www.w3.org/2000/svg', 'text');\r\n\t//starting position\r\n\tt.setAttribute('x', startPoint.x); \r\n\tt.setAttribute('y', startPoint.y);\r\n\t//inner text\r\n\tt.innerHTML = innerText;\r\n\t//style\r\n\tt.style.fill = style.fillColor;\r\n\tt.style.stroke = style.borderColor;\r\n\tt.style.strokeWidth = style.borderWidth;\r\n\t//id\r\n\tif (typeof id !== 'undefined') t.setAttribute('id', id);\r\n\t//add to parent\r\n\tsvgParent.appendChild(t);\r\n}", "function newTextNode(selection$$1, text, ems) {\n\n\t var nodeName = selection$$1.property('nodeName'),\n\t parent = select(selection$$1.node().parentNode),\n\t lineHeight = ems || 1.6, // ems\n\t dy = parseFloat(selection$$1.attr('dy')),\n\t x = parseFloat(selection$$1.attr('x')),\n\t textAnchor = selection$$1.style('text-anchor');\n\n\t var cloned = parent.append(nodeName)\n\t .attr('dy', ((lineHeight + dy) + \"em\"))\n\t .attr('x', x)\n\t .style('text-anchor', textAnchor)\n\t .text(text);\n\n\t return cloned;\n\n\t}", "function elementFactory(tag, text, css) {\n var element = document.createElement(tag);\n var innerHTML = document.createTextNode(text);\n\n element.appendChild(innerHTML);\n if(css !== '') {\n if(typeof css === 'string') {\n element.classList.add(css);\n } else {\n css.forEach(function(style) {\n element.classList.add(style);\n })\n }\n }\n \n return element;\n}", "function addElement() {\n var newDiv = document.createElement(\"div\");\n var textNode = document.createTextNode(\"AWESOME\");\n newDiv.style.marginLeft = \"20px\";\n newDiv.style.marginTop = \"100px\";\n newDiv.style.fontSize = \"200px\";\n newDiv.style.position = \"fixed\";\n newDiv.style.zIndex = \"2147483647\";\n newDiv.appendChild(textNode);\n console.log(newDiv);\n document.body.appendChild(newDiv);\n}", "function ELEMENT_TEXT$static_(){IconWithTextBEMEntities.ELEMENT_TEXT=( IconWithTextBEMEntities.BLOCK.createElement(\"text\"));}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if given commit hash is referenced.
hasCommit(commitHash) { return this.namesPerCommit.has(commitHash); }
[ "static isCommitHash(target) {\n return !!target && /^[a-f0-9]{5,40}$/.test(target);\n }", "async function commitExists(commit) {\n try {\n await execGitCommand(`git cat-file -e \"${commit}^{commit}\"`);\n return true;\n } catch (error) {\n return false;\n }\n}", "existingCommit(commit) {\n let exists = this.list[commit.blockHash].find(\n p => p.publicKey === commit.publicKey\n );\n return exists;\n }", "function isBranchRef(ref) {\n const matcher = new RegExp(\"^refs/heads/\");\n const match = matcher.test(ref);\n return match;\n}", "isValidCommit(commit) {\n return ChainUtil.verifySignature(\n commit.publicKey,\n commit.signature,\n commit.blockHash\n );\n }", "function isProjectRelatedHash(hash) {\n if (!hash) {\n return false;\n }\n switch (hash.cmd) {\n case \"follow\":\n case \"newproject\":\n case \"newjavascript\":\n // case \"gettingstarted\": // This should be true, #gettingstarted hash handling is not yet implemented\n case \"tutorial\":\n case \"recipe\":\n case \"projects\":\n case \"sandbox\":\n case \"pub\":\n case \"edit\":\n case \"sandboxproject\":\n case \"project\":\n return true;\n default:\n return false;\n }\n}", "isRef(ref) {\n return ref !== undefined\n && (ref.match('^refs/heads/[A-Za-z-]+$')\n || ref.match('^refs/remotes/[A-Za-z-]+/[A-Za-z-]+$')\n || ['HEAD', 'FETCH_HEAD', 'MERGE_HEAD'].indexOf(ref) !== -1);\n }", "function contains_hash() {\n var hash = document.location.hash;\n return hash && (section[0].id == hash.substr(1) ||\n section.find(escapeHash(hash)).length > 0);\n }", "function subtreeHasRef(tree, root, ref) {\n if (!tree.transforms.has(root) || !tree.transforms.has(ref))\n return false;\n return _subtreeHasRef(tree, root, ref);\n }", "async function verify ({\n core = 'default',\n dir,\n gitdir = join(dir, '.git'),\n fs: _fs = cores.get(core).get('fs'),\n ref,\n publicKeys,\n openpgp\n}) {\n try {\n const fs = new FileSystem(_fs);\n const oid = await GitRefManager.resolve({ fs, gitdir, ref });\n const { type, object } = await readObject({ fs, gitdir, oid });\n if (type !== 'commit' && type !== 'tag') {\n throw new GitError(E.ObjectTypeAssertionInRefFail, {\n expected: 'commit/tag',\n ref,\n type\n })\n }\n if (openpgp) {\n // Old API\n let commit = SignedGitCommit.from(object);\n let keys = await commit.listSigningKeys(openpgp);\n let validity = await commit.verify(openpgp, publicKeys);\n if (!validity) return false\n return keys\n } else {\n // Newer plugin API\n let pgp = cores.get(core).get('pgp');\n if (type === 'commit') {\n let commit = GitCommit.from(object);\n let { valid, invalid } = await GitCommit.verify(commit, pgp, publicKeys);\n if (invalid.length > 0) return false\n return valid\n } else if (type === 'tag') {\n let tag = GitAnnotatedTag.from(object);\n let { valid, invalid } = await GitAnnotatedTag.verify(\n tag,\n pgp,\n publicKeys\n );\n if (invalid.length > 0) return false\n return valid\n }\n }\n } catch (err) {\n err.caller = 'git.verify';\n throw err\n }\n}", "isReference() {\n return undefined != this.referenceId;\n }", "function hasAReference(body) {\n return body.pull_request.title.toLowerCase().startsWith('github issue');\n}", "function contains_hash(){\n var hash = document.location.hash;\n return hash && (section[0].id == hash.substr(1) ||\n section.find(hash.replace(/\\./g,\"\\\\.\")).length>0);\n }", "static isReference(x) {\n return typeof x === 'object' && x !== null && REFERENCE_SYMBOL in x;\n }", "function checkObjectRef (ref) {\n // return true if this.options.objRef = a reference or reference path\n // return false otherwise\n if (!ref) {\n return false;\n }\n var refRegex = /^\\S+\\/\\S+(\\/\\d+)?$/;\n var refList = ref.split(';');\n var validRef = true;\n refList.forEach(function(r) {\n if (!refRegex.exec(r)) {\n validRef = false;\n }\n });\n return validRef;\n }", "function HasTheseRefs(obj,refs){\n console.log(\"Se va a comprobar si en el objeto aparecen las referencias \", refs);\n let referencesFound = new Array();\n FindReferences(obj,referencesFound);\n\n for (let i = 0; i < refs.length; i++) {\n if (referencesFound.includes(refs[i])){\n console.log(\"El objeto incluye la referencia \" + refs[i]);\n return true;\n }\n }\n\n console.log(\"Ninguna de esas referencias aparece en el objeto\");\n return false;\n}", "exists(ref) {\n return Refs.isRef(ref) && fs.existsSync(Files.gitletPath(ref));\n }", "async repositoryHasCommits() { \n try {\n await execa.stdout('git', ['log']);\n }\n catch (e) {\n throw new Error('No commits found.');\n }\n return true;\n }", "hash(refOrHash) {\n if (Objects.exists(refOrHash)) {\n return refOrHash;\n }\n const terminalRef = Refs.terminalRef(refOrHash);\n if (terminalRef === 'FETCH_HEAD') {\n return Refs.fetchHeadBranchToMerge(Refs.headBranchName());\n } if (Refs.exists(terminalRef)) {\n return Files.read(Files.gitletPath(terminalRef));\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge action as found on wit.ai story, returns a js promise with new context
merge({sessionId, context, entities, text}) { console.log(`Session ${sessionId} received`); console.log(`The current context is ${JSON.stringify(context)}`); console.log(`Wit extracted ${JSON.stringify(entities)}`); // Reset the weather story // Retrive the location entity and store it in the context field var loc = firstEntityValue(entities, 'location') if (loc) { context.loc = loc } // Reset the cutepics story delete context.borrowrequest // //Inflight Requests // var time = firstEntityValue(entities, 'intent') // if (time) { // context.time = time // } // Retrieve Requests var borrowrequest = firstEntityValue(entities, 'borrowrequest') if (borrowrequest) { context.rawrequest = borrowrequest } // Retrieve the category var category = firstEntityValue(entities, 'category') if (category) { context.cat = category } // Retrieve the sentiment var sentiment = firstEntityValue(entities, 'sentiment') if (sentiment) { context.feedback = text context.feedbackSentiment = sentiment } return Promise.resolve(context); }
[ "_deployAction(action) {\n return new Promise(\n (resolve, reject) => {\n let action_name = Object.keys(action)[0];\n let action_info = action[action_name];\n if (action_info === null || typeof(action_info) === \"undefined\") {\n reject(\"Action \" + action_name + \"is undefined. Action object:\" + util.inspect(action));\n return;\n }\n console.log(\"Adding/updating action: \" + action_name + \". Details:\" + util.inspect(action_info));\n let action_src_path = this.root_folder + \"/\" + action_info.location;\n if (action_info.location === null || typeof(action_info.location) === \"undefined\") {\n reject(\"Action \" + action_name + \" is missing the location property. Action details:\" + util.inspect(action_info));\n return;\n }\n console.log(\"Reading action src from \" + action_src_path);\n\n let action_src = fs.readFileSync(action_src_path, 'utf-8');\n\n let action_qualified_name = this.manifest.package.openwhisk_name + \"/\" + action_name;\n\n console.info(\"Deploying action: \" + action_qualified_name + \" from :\" + action_src_path);\n\n var action_parameters = [];\n if (action_info.inputs !== null && typeof(action_info) !== \"undefined\") {\n for(var key in this.default_parameters) {\n if (this.default_parameters.hasOwnProperty(key) && action_info.inputs.hasOwnProperty(key) ) {\n action_parameters.push({\n key: key,\n value: this.default_parameters[key]\n })\n }\n }\n }\n\n\n // NOTE: openwhisk client only supports nodejs6 \"kind\" of actions ATM\n let action_opts = {\n actionName: action_qualified_name,\n action: action_src,\n namespace: this.openwhisk_client_props.namespace,\n parameters: action_parameters\n };\n // overwrite action_body method in order to send default parameters\n // once https://github.com/openwhisk/openwhisk-client-js/pull/26 is merged we can delete the action_body\n this.openwhisk_client.actions.action_body = function(options) {\n if (options.action instanceof Buffer) {\n options.action = options.action.toString('base64')\n } else if (typeof options.action === 'object') {\n return options.action\n }\n\n var returned_opts = { exec: { kind: 'nodejs:default', code: options.action } };\n if ( options.parameters !== null && typeof(options.parameters) !== \"undefined\") {\n returned_opts.parameters = options.parameters;\n }\n\n return returned_opts\n };\n //\n\n this.openwhisk_client.actions.update(action_opts)\n .then((update_result) => {\n resolve(update_result);\n })\n .catch((update_error) => {\n console.warn(\"There was an error updating the action:\" + action_opts.actionName + \". Recreating it.\");\n console.log(\"update_error:\" + util.inspect(update_error));\n // try to delete and re-create the action\n this.openwhisk_client.actions.delete(action_opts)\n .then((delete_result) => {\n this.openwhisk_client.actions.create(action_opts)\n .then((recreate_result) => {\n console.log(\"Recreated action:\" + action_opts.actionName + \". Result:\" + util.inspect(recreate_result));\n resolve(recreate_result);\n })\n .catch((recreate_error) => {\n console.warn(\"Could not delete/create the action:\" + action_opts.actionName);\n reject({\n \"message\": \"Could not recreate action:\" + action_opts.actionName,\n \"details\": util.inspect(recreate_error)\n });\n });\n\n })\n .catch((get_error) => {\n console.error(\"Could not retrieve action \" + action_opts.actionName);\n reject({\n \"message\": \"Error recreating the action:\" + action_opts.actionName,\n \"details\": util.inspect(get_error)\n })\n })\n })\n }\n );\n }", "_performGetActionWithWorkingCopy(action) {\n\t\tconst fields = [];\n\t\t// HACK adding query params as fields due to bug in performSirenAction (_getSirenFields function)\n\t\tconst url = new URL(action.href, window.location.origin);\n\t\tfor (const [key, value] of url.searchParams) {\n\t\t\tfields.push({ name: key, value: value });\n\t\t}\n\n\t\treturn performSirenAction(this._token, action, fields, false, true);\n\t}", "then(state, action) {\n let newHistory = createImmutableHistory(action.payload);\n return state.merge({\n history: newHistory,\n });\n }", "use(action) {\n \"use strict\";\n this.plugins[action.intent] = action\n\n // this.associate(action.intent, action.sentences, action)\n for(var sentence in action.extractedPair){\n Log.debug('Learning the association of ' + action.extractedPair[sentence].subIntent + ' and ' + sentence);\n this.associate(action.extractedPair[sentence].subIntent, sentence, action)\n }\n }", "getStoryContext(story) {\n return Object.assign({}, story, {\n args: this.args.get(story.id),\n globals: this.globals.get(),\n hooks: this.hooks[story.id]\n });\n }", "static share(\n content: Content,\n options: Options = {},\n ): Promise<{action: string, activityType: ?string}", "evaluateAction() {\n return Promise.resolve();\n }", "get action() {\n const self = this;\n return {\n run: function (aka, actionUri, parameters) {\n // If the first parameter is a plain object, we switch to the \"new\" parameter format:\n //\n // { aka, actionUri, parameters, lock }\n //\n if (_.isPlainObject(aka)) {\n const { aka2, actionUri, parameters, lock, lockExpireSecs } = aka;\n const meta = {\n controlId: self.meta.controlId,\n actionId: self.meta.actionId,\n actionUri: actionUri,\n sourceType: self.opts.type,\n sourceRunnableTypeUri: self.meta.runnableTypeUri,\n lock: lock,\n lockExpireSecs: lockExpireSecs,\n };\n if (self.meta.pid) {\n meta.parentProcessId = self.meta.pid;\n }\n\n self._command({\n type: \"action_run\",\n meta: meta,\n payload: {\n meta: {\n aka: aka2,\n actionUri: actionUri,\n },\n data: parameters,\n },\n });\n return;\n }\n\n // aka parameter is optional\n if (!parameters) {\n parameters = actionUri;\n actionUri = aka;\n aka = null;\n }\n\n if (!aka) {\n aka = self.meta.resourceId;\n }\n\n // TODO: the actionUri should be in the payload not meta. See how the control.run is done\n const meta = {\n controlId: self.meta.controlId,\n actionId: self.meta.actionId,\n actionUri: actionUri,\n sourceType: self.opts.type,\n sourceRunnableTypeUri: self.meta.runnableTypeUri,\n };\n if (self.meta.pid) {\n meta.parentProcessId = self.meta.pid;\n }\n\n self._command({\n type: \"action_run\",\n meta: meta,\n payload: {\n meta: {\n aka: aka,\n actionUri: actionUri,\n },\n data: parameters,\n },\n });\n },\n\n handleEvent: function (aka, actionUri, eventType, event, turbotData) {\n const command = {\n type: \"action_run\",\n meta: {\n controlId: self.meta.controlId,\n actionId: self.meta.actionId,\n sourceType: self.opts.type,\n sourceRunnableTypeUri: self.meta.runnableTypeUri,\n actionRunType: \"handleEvent\",\n aka,\n eventType: \"event.turbot.com:External\",\n eventRaw: eventType,\n actionUri,\n },\n payload: {\n meta: {\n aka: aka,\n actionUri: actionUri,\n },\n data: event,\n },\n };\n\n command.meta = self.setCommandMeta(command.meta, turbotData);\n\n const msg = `Handle event for aka ${aka}.`;\n self.log.info(msg, { event: event, turbotData: turbotData });\n self._command(command);\n return self;\n },\n };\n }", "function addAction(action) {\n return db('actions_table')\n .insert(action)\n .then(ids => ({id: ids[0]}));\n}", "static async DuplicateAction() {\n let actions = Configuration.get(`actions`);\n \n vscode.window.showQuickPick(\n actions.map((action, index) => ({\n label: `${action.name} (${action.type}: ${action.extensions.join(`, `)})`,\n value: index\n })).sort((a, b) => a.label.localeCompare(b.label)),\n {\n placeHolder: `Select an action to duplicate`\n }\n ).then(async (action) => {\n if (action) {\n //@ts-ignore\n const index = action.value;\n\n const newAction = {...actions[index]};\n actions.push(newAction);\n await Configuration.setGlobal(`actions`, actions);\n this.WorkAction(actions.length - 1);\n } else {\n this.MainMenu();\n }\n \n });\n }", "function payloadMerge(fn) {\n return (state, action) => {\n return Object.assign({}, state, fn(action));\n };\n}", "function decoratePromise(p, action) {\n var result = p;\n result.undo = function undo() {\n return decoratePromise(p.then(function () { return undoFn.call(action); }), action);\n };\n result.redo = function redo(options) {\n return decoratePromise(p.then(function () { return redoFn.call(action, options); }), action);\n };\n return result;\n }", "registerActions() {\n\n this.S.addAction(this._customAction.bind(this), {\n handler: 'customAction',\n description: 'A custom action from a custom plugin',\n context: 'custom',\n contextAction: 'run',\n options: [{\n option: 'option',\n shortcut: 'o',\n description: 'test option 1'\n }]\n });\n\n return Promise.resolve();\n }", "function prepare_action(event){\n var tag = event.currentTarget.toString().split(\"#\")[1];\n var links = getPlanetLinks();\n var urls = [];\n var prep = [];\n //Run the appropriate preparation\n switch(tag){\n case REFRESH:\n prep = prepare_refresh(links,urls);\n break;\n case EXPEDITION:\n prep = prepare_expedition(links,urls);\n break;\n case REGROUP:\n prep = prepare_regroup(links,urls);\n break;\n case DISPATCH:\n prep = prepare_dispatch(links,urls);\n break;\n case ACTIVITY:\n set_activity();\n return;\n case CONFIG_ACTIVITY:\n config_activity();\n break;\n case CONFIG_REFRESH:\n config_refresh();\n break;\n case CONFIG_EXPEDITION:\n config_expedition();\n break;\n case CONFIG_DISPATCH:\n config_dispatch();\n break;\n }\n\n /* If preparation is OK\n * prep[0] contains URLS where to go\n * prep[1] can contain DATA for the action\n */\n if(prep.length > 0 && prep[0].length > 0){\n var url = prep[0].shift()\n setItem(MYACTION,tag);\n setItem(tag,prep[0]);\n if(prep[1] !== undefined)\n setItem(DATA,prep[1]);\n location.assign(url)\n }\n\n}", "function putResolve(action) {\n var type = action.type;\n assertAction(type, 'sagaEffects.put.resolve');\n return effects_namespaceObject.put.resolve(\n Object(objectSpread['a' /* default */])({}, action, {\n type: prefixType(type, model),\n }),\n );\n }", "queryAllSuccess(collection, action) {\n const data = this.extractData(action);\n const mergeStrategy = this.extractMergeStrategy(action);\n return {\n ...this.entityChangeTracker.mergeQueryResults(data, collection, mergeStrategy),\n loaded: true,\n loading: false,\n };\n }", "static initialResult(actionContext) {\n return {\n nextContext: actionContext,\n resultOps: [],\n scheduledActions: []\n };\n }", "function createMergeContext() {\n\treturn contextMenus.create({\n\t\ttitle: \"Merge popup\",\n\t\tonclick(info, tab) {\n\t\t\tmergePopup(tab.id, tab.windowId);\n\t\t}\n\t});\n}", "function appendActionEvent(action, event) {\r\n if (action.done) {\r\n return action;\r\n }\r\n // no nested action yet\r\n if (isCurrentAction(action)) {\r\n if (!event.callDone) {\r\n // the action calls to a nested action\r\n var nestedAction = {\r\n name: event.action,\r\n done: false,\r\n collapsed: false,\r\n actionData: event.data,\r\n actions: [],\r\n previousState: action.previousState,\r\n stateCollapses: {}\r\n };\r\n return __assign({}, action, { actions: action.actions.concat(nestedAction) });\r\n }\r\n else if (action.name === event.action) {\r\n // the previous call is now complete: set to done and compute the result\r\n return __assign({}, action, { done: true, actionResult: event.result, nextState: mergeResult(action, event) });\r\n }\r\n else {\r\n // error case\r\n console.log(\"Previous action is done and event.callDone\", action, event);\r\n // TODO what to return?!\r\n return action;\r\n }\r\n }\r\n else {\r\n // there are already some nested actions: call recursivelly\r\n var nested = action.actions;\r\n var nestedAction = nested[nested.length - 1];\r\n var newNestedAction = appendActionEvent(nestedAction, event);\r\n if (nestedAction === newNestedAction) {\r\n return action;\r\n }\r\n return __assign({}, action, { actions: nested.slice(0, nested.length - 1).concat(newNestedAction) });\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the resolved handler to the actions set
addResolvedHandler(lifecycle, action, handler) { const handlers = this.getActionHandlers(lifecycle, action); if (handlers) { handlers.add(handler); } else { this.hooks[lifecycle].set(action, new Set([handler])); } }
[ "addHandler(handler) {\n this.handlers.push(handler);\n }", "addActions() {\n this.addAction('index', this.actionIndex);\n this.addAction('submit', this.actionSubmit);\n }", "add(lifecycle, action, handler) {\n const handlers = this.hooks[lifecycle].get(action);\n if (handlers) {\n handlers.push(handler);\n }\n else {\n this.hooks[lifecycle].set(action, [handler]);\n }\n return this;\n }", "function bind(action, handler) {\n if (!inputHandlers[action]) {\n inputHandlers[action] = [];\n }\n inputHandlers[action].push(handler);\n }", "registerActions() {\n\n this.S.addAction(this._customAction.bind(this), {\n handler: 'customAction',\n description: 'A custom action from a custom plugin',\n context: 'custom',\n contextAction: 'run',\n options: [{\n option: 'option',\n shortcut: 'o',\n description: 'test option 1'\n }]\n });\n\n return Promise.resolve();\n }", "addDefaultHandler(commandHandler) {\n this.defaultHandlers = this.defaultHandlers.concat(commandHandler);\n }", "function actionHandler(action, request, response) {\n\tfor (var i = 0; i < actions.length; i++) {\n\t\tif (actions[i].name == action && actions[i].method == request.method) {\n\t\t\tactions[i].handler(request, response);\n\t\t}\n\t}\n}", "handleAction() {\n if (!this._action || !this._action.handler) {\n return;\n }\n this._action.handler();\n }", "_initActions(actions) {\n actions.forEach(action => {\n if (!this[action]) {\n this[action] = function(action, ...args) {\n return this._callAction(action, ...args)\n }.bind(this, action);\n }\n });\n\n this._actions = actions;\n }", "_collectActions(){\n let self = this;\n \n App.core.use('/' + this.name, (req, res, next) => { self.beforeAction(req, res, next); });\n App.core.use('/' + this.name + '/*', (req, res, next) => { self.beforeAction(req, res, next); });\n\n Object.getOwnPropertyNames(Object.getPrototypeOf(self)).filter((prop) => {\n if(typeof self[prop] === 'function' && prop.slice(0, 6) === 'action'){\n self.actions.push(prop.slice(6).toLowerCase());\n }\n });\n }", "addActions() {\n this.addAction('index', this.actionIndex);\n this.addAction('profile', this.actionProfile);\n this.addAction('logout', this.actionLogout);\n this.addAction('settings', this.actionSettings);\n this.addAction('edit', this.actionEdit);\n this.addAction('uploadavatar', this.actionUploadAvatar);\n }", "static addHandler(handler) {\n assert(handler.call, 'Handler must be a function');\n assert(handler.length === 2 || handler.length === 3, 'Handler function takes 2 (request handler) or 3 (response handler) arguments');\n this._default.push(handler);\n }", "function setup_actions(gatherers, handlers) {\n let actions = document.getElementsByClassName(\"action\");\n const COLOR_TIME = 500;\n for (const action of actions) {\n let button = action.children[0];\n let httpMethod = action.getAttribute(\"action\");\n if (httpMethod === null) {\n httpMethod = \"POST\";\n }\n let name = action.getAttribute(\"name\");\n button.addEventListener(\"click\", query(\n name,\n httpMethod,\n function () {\n button.classList.add(\"working\");\n let data;\n if (gatherers.hasOwnProperty(name)) {\n data = gatherers[name]();\n } else {\n data = {};\n }\n return data;\n },\n function (response) {\n button.classList.remove(\"working\");\n button.classList.add(\"finished\");\n // call handler\n if (handlers.hasOwnProperty(name)) {\n handlers[name](response);\n }\n setTimeout(() => button.classList.remove(\"finished\"), COLOR_TIME);\n },\n function () {\n button.classList.remove(\"working\");\n alert(\"Cannot make request (possibly an override value is missing).\");\n }\n ));\n }\n\n }", "on(type, handler) {\n let map = this._handlers || (this._handlers = Object.create(null))\n map[type] = (type in map) ? map[type].concat(handler) : [handler]\n }", "registerWithDispatcher() {\n this.dispatchToken = Dispatcher.register(action => {\n if (this.handlers.hasOwnProperty(action.type)) {\n this.handlers[action.type](action.data);\n }\n });\n }", "loadActions() {\n if (!this.actions) {\n this.actions = new Actions(this);\n }\n }", "addaction() {\n this.actions.push(this.act);\n }", "_mapActions( actions, target, storeId ) {\n\t\tfor ( let act in actions ) {\n\t\t\tif ( actions.hasOwnProperty(act) ) {\n\t\t\t\tif ( is.object(actions[act]) ) {// hirarchised actions\n\t\t\t\t\t\n\t\t\t\t\tif ( target[act] && !is.object(target[act]) )\n\t\t\t\t\t\tconsole.warn(\"RS : Actions namespace is mapped over an existing function !\", storeId, act);\n\t\t\t\t\t\n\t\t\t\t\ttarget[act] = target[act] || { __targetStores: 0 };\n\t\t\t\t\tthis._mapActions(actions[act], target[act]);\n\t\t\t\t\ttarget[act].__targetStores++;\n\t\t\t\t}\n\t\t\t\telse if ( target.hasOwnProperty(act) )\n\t\t\t\t\ttarget[act].__targetStores++;\n\t\t\t\telse {\n\t\t\t\t\tif ( is.object(target[act]) )\n\t\t\t\t\t\tconsole.warn(\"RS : Action is mapped over existing namespace !\", storeId, act);\n\t\t\t\t\ttarget[act] = this.dispatch.bind(this, act);\n\t\t\t\t\ttarget[act].__targetStores = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "addInvokeRequestHandler (path, commandName, handler) {\n\t\tconst cmdid = SystemInterface.getCommandId (commandName);\n\t\tif (cmdid < 0) {\n\t\t\tthrow Error (`Failed to add invoke request handler, unknown commandName ${commandName}`);\n\t\t}\n\t\tthis.invokeRequestHandlerMap[`${cmdid}:${path}`] = handler;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the actual value is within a minimum on the bound of the expected value. All arguments must be in the same units.
function assertLowerBound(expected, actual, bound) { assert.gte(actual, expected - bound); }
[ "isMin(value, limit) {\n return parseFloat(value) >= limit;\n }", "beLessThanOrEqualTo() {\n this._processArguments(arguments);\n return this._assert(\n this._actual <= this._expected,\n '${actual} is less than or equal to ${expected}.',\n '${actual} is not less than or equal to ${expected}.');\n }", "function SNAP_checkRule_minimum(_elements, _parameters, _required)\r\n{\r\n\tvar element = _elements[0];\r\n\tvar minimum_value = Number(_parameters[0]);\r\n\tvar element_value = Number(SNAP_getElementValue(element));\r\n\t\r\n\t// if nothing & required => failed\r\n\tif (element_value == '' && _required == true)\r\n\t\treturn false;\r\n\t// if nothing & not required => passed\r\n\tif (element_value == '' && _required == false)\r\n\t\treturn true;\r\n\t\r\n\tif (isNaN(element_value))\r\n\t\treturn false;\r\n\tif (isNaN(minimum_value))\r\n\t\treturn false;\r\n\t\r\n\tif (element_value > minimum_value)\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n}", "beLessThan() {\n this._processArguments(arguments);\n return this._assert(\n this._actual < this._expected, '${actual} is less than ${expected}.',\n '${actual} is not less than ${expected}.');\n }", "function checkBoundaries(value) {\n\t\tif (value < options.lowerBound*10)\n\t\t\treturn options.lowerBound*10;\n\t\telse if (value > options.upperBound*10)\n\t\t\treturn options.upperBound*10;\n\t\telse\n\t\t\treturn value;\n\t}", "function checkBoundaries(value) {\n if (value < options.lowerBound*10)\n return options.lowerBound*10;\n else if (value > options.upperBound*10)\n return options.upperBound*10;\n else\n return value;\n }", "function check_min(proposed_type, proposed_value, min, property) {\r\n let error;\r\n if (\r\n proposed_type === lit.TYPE_INT ||\r\n proposed_type === lit.TYPE_FLOAT\r\n ) {\r\n if (proposed_value < min) {\r\n error = new Error(\r\n \"Proposed value \" + proposed_value +\r\n \" is lesser than minimum constraint value \" +\r\n min\r\n );\r\n }\r\n } else if (\r\n proposed_type === lit.TYPE_STRING ||\r\n proposed_type === lit.TYPE_LIST\r\n ) {\r\n if (proposed_value.length < min) {\r\n error = new Error(\r\n \"Proposed value \" + proposed_value +\r\n \" is lesser than minimum constraint value \" +\r\n min + \" of property '\" + property + \"'\"\r\n );\r\n }\r\n }\r\n return error;\r\n}", "static withinTolerance(currentValue, fromValue, toValue) {\n const isGrowing = toValue > fromValue;\n const tolerance =\n Math.abs(\n isGrowing ? toValue - fromValue : fromValue - toValue,\n ) / 60;\n return (\n Math.abs(\n isGrowing ? toValue - currentValue : currentValue - toValue,\n ) < tolerance\n );\n }", "constrainValue(value) {\n return Math.min(Math.max(value, this._min), this._max);\n }", "function constrain(value, min, max) {\n if (typeof value !== \"number\") throw new TypeError();\n if (typeof min !== \"number\") throw new TypeError();\n if (typeof max !== \"number\") throw new TypeError();\n if (min > max) throw new Error();\n\n if (value < min) return min;\n if (value > max) return max;\n return value;\n}", "_assertRange(value) {\n if (Object(_util_TypeCheck__WEBPACK_IMPORTED_MODULE_4__[\"isDefined\"])(this.maxValue) && Object(_util_TypeCheck__WEBPACK_IMPORTED_MODULE_4__[\"isDefined\"])(this.minValue)) {\n Object(_util_Debug__WEBPACK_IMPORTED_MODULE_7__[\"assertRange\"])(value, this._fromType(this.minValue), this._fromType(this.maxValue));\n }\n\n return value;\n }", "testIsLessThan() {\n this.isLessThan(0, 1);\n this.hasException(() => this.isLessThan(1, 0));\n }", "GetNearestValidPoint(value) {\n const scale = value / minStep$1;\n return Math.ceil(scale) * minStep$1;\n }", "_assertRange(value) {\n if (Object(_util_TypeCheck__WEBPACK_IMPORTED_MODULE_4__[\"isDefined\"])(this.maxValue) && Object(_util_TypeCheck__WEBPACK_IMPORTED_MODULE_4__[\"isDefined\"])(this.minValue)) {\n Object(_util_Debug__WEBPACK_IMPORTED_MODULE_7__[\"assertRange\"])(value, this._fromType(this.minValue), this._fromType(this.maxValue));\n }\n return value;\n }", "function boundsCheck(value) {\n\t\tif (base == 10)\tvalue = parseFloat(value);\t\t\t\t\t\t// value is a string, if in base 10, parseFloat() it\n\t\telse value = parseInt(value, 16);\t\t\t\t\t\t\t\t// value is a string, if in base 16, parseInt() it with 16 as parameter (converts to base 10)\n\t\t\n\t\tif (minValue === null && maxValue === null) return true;\t\t// if both min and max is null, there is no limit, simple return true\n\t\telse if (minValue !== null && maxValue !== null) {\t\t\t\t// if both of the values aren't null, check both bounds\n\t\t\tif (value <= maxValue && value >= minValue) return true;\n\t\t}\n\t\telse if (minValue === null && maxValue !== null) {\t\t\t\t// if only the min is null, then there is no lower bound; check the upper bound\n\t\t\tif (value <= maxValue) return true;\n\t\t}\n\t\telse if (minValue !== null && maxValue === null) {\t\t\t\t// if only the max is null, then there is no upper bound; check the lower bound\n\t\t\tif (value >= minValue) return true;\n\t\t}\n\t\t\n\t\treturn false;\t// if we made it here, the number isn't valid; return false\n\t}", "function check_relative_difference(val1, val2, tolerance)\n{\n return ((Math.min(val1, val2) / Math.max(val1, val2)) >= tolerance);\n}", "function checkMinValues(input) {\n if (input.canvasWidth < minDimensions.width || input.canvasHeight < minDimensions.height ) {\n return true;\n } else {\n return false;\n }\n}", "function checkValues() {\n minXVal = parseInt(minX.value);\n maxXVal = parseInt(maxX.value);\n minYVal = parseInt(minY.value);\n maxYVal = parseInt(maxY.value);\n\n if (minXVal < -50 || minXVal > 50 || isNaN(minXVal) || maxXVal < -50 ||\n maxXVal > 50 || isNaN(maxXVal) || minYVal < -50 || minYVal > 50 ||\n isNaN(minYVal) || maxYVal < -50 || maxYVal > 50 || isNaN(maxYVal)) {\n infoMsg.textContent = \"One or more values is not within range of -50 to\"\n + \" 50\";\n return false;\n }\n else {\n infoMsg.textContent = \"\";\n return true;\n }\n}", "function checkValues() {\n minXVal = parseInt(minX.value);\n maxXVal = parseInt(maxX.value);\n minYVal = parseInt(minY.value);\n maxYVal = parseInt(maxY.value);\n\n if (minXVal < -50 || minXVal > 50 || isNaN(minXVal) || maxXVal < -50 ||\n maxXVal > 50 || isNaN(maxXVal) || minYVal < -50 || minYVal > 50 ||\n isNaN(minYVal) || maxYVal < -50 || maxYVal > 50 || isNaN(maxYVal)) {\n infoMsg.textContent = \"One or more values is not within range of -50 to\"\n + \" 50 \";\n return false;\n }\n else {\n infoMsg.textContent = \"\";\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the stark path based on the layer, application, eth address and a given index. layer is a string representing the operating layer (usually 'starkex'). application is a string representing the relevant application (For a list of valid applications, refer to ethereumAddress is a string representing the ethereum public key from which we derive the stark key. index represents an index of the possible associated wallets derived from the seed.
function getAccountPath(layer, application, ethereumAddress, index) { const layerHash = hash .sha256() .update(layer) .digest('hex'); const applicationHash = hash .sha256() .update(application) .digest('hex'); const layerInt = getIntFromBits(layerHash, -31); const applicationInt = getIntFromBits(applicationHash, -31); // Draws the 31 LSBs of the eth address. const ethAddressInt1 = getIntFromBits(ethereumAddress, -31); // Draws the following 31 LSBs of the eth address. const ethAddressInt2 = getIntFromBits(ethereumAddress, -62, -31); return `m/2645'/${layerInt}'/${applicationInt}'/${ethAddressInt1}'/${ethAddressInt2}'/${index}`; }
[ "function queryLayers(index = 0) {\n const layer = searchLayers[index];\n if (layer.type === 'feature') {\n const params = layer.createQuery();\n params.returnGeometry = true;\n params.where = idField\n ? `${idField} = '${feature.attributes[idField]}'`\n : `organizationid = '${orgId}' And assessmentunitidentifier = '${auId}'`;\n params.outFields = ['*'];\n layer\n .queryFeatures(params)\n .then((res) => {\n // if the feature was found, execute the call back and return\n if (res.features.length > 0) {\n callback(res.features[0]);\n return; // exit recursive function\n }\n // if there are more layers query the next layer in the array\n if (index < searchLayers.length) {\n queryLayers(index + 1); // recursive call\n }\n })\n .catch((err) => console.error(err));\n } else if (layer.type === 'graphics') {\n const { organizationid } = feature.attributes;\n\n for (const graphic of layer.graphics.items) {\n const graphicOrgId =\n graphic && graphic.attributes && graphic.attributes.organizationid;\n const graphicAuId =\n graphic &&\n graphic.attributes &&\n graphic.attributes.assessmentunitidentifier;\n if (graphicOrgId === organizationid && graphicAuId === auId) {\n callback(graphic);\n return;\n }\n }\n\n // continue recursive call if there are more layers\n if (index + 1 <= searchLayers.length) queryLayers(index + 1);\n }\n }", "generateKeyPair(wallet, index) {\n if (!wallet.network || wallet.network.connect) {\n throw new Error('Invalid wallet type');\n }\n const addrNode = this.Bip.fromExtendedKey(wallet.ext.xpriv).deriveChild(index);\n const keypair = {\n publicKey: addrNode.getWallet().getPublicKeyString(),\n address: addrNode.getWallet().getChecksumAddressString(),\n derivationPath: `m/44'/60'/0'/0/${index}`,\n privateKey: addrNode.getWallet().getPrivateKeyString(),\n type: 'Ethereum',\n network: this.api || wallet.network,\n };\n return keypair;\n }", "changeAddrFromMnemonic(walletInfo, index) {\n try {\n // root seed buffer\n const rootSeed = this.BITBOX.Mnemonic.toSeed(walletInfo.mnemonic)\n\n // master HDNode\n if (walletInfo.network === \"testnet\")\n var masterHDNode = this.BITBOX.HDNode.fromSeed(rootSeed, \"testnet\")\n else var masterHDNode = this.BITBOX.HDNode.fromSeed(rootSeed)\n\n // HDNode of BIP44 account\n const account = this.BITBOX.HDNode.derivePath(\n masterHDNode,\n \"m/44'/145'/0'\"\n )\n\n // derive the first external change address HDNode which is going to spend utxo\n const change = this.BITBOX.HDNode.derivePath(account, `0/${index}`)\n\n return change\n } catch (err) {\n console.log(`Error in util.js/changeAddrFromMnemonic()`)\n throw err\n }\n }", "function main() {\n const index = process.argv[2];\n const seed = process.argv[3];\n const wallet = addByMnemonic(seed, index)\n const account = JSON.stringify(wallet, null, 4)\n console.log(account)\n}", "function calculateOffset(pk, index, chaincode) {\n const salt = i2osp(index, 4);\n const buffer = Buffer.concat([pk, salt]);\n return createHmac('sha512', bigIntToBufferBE(chaincode, 32)).update(buffer).digest();\n}", "function get_index_pair(net,index){\n\t\tlet idx = index.slice();\n\t\tidx[0] = -idx[0];\n\t\t// find node with index\n\t\tlet pair;\n\t\tnet.forEach((n)=>{\n\t\t\tif(n.index[0]==idx[0] && n.index[1]==idx[1])\n\t\t\t\tpair = n;\n\t\t});\n\t\treturn pair;\n\t}", "async function getSiblingPathByLeafIndex(contractName, leafIndex) {\n console.log(`\\nCalling getSiblingPathByLeafIndex(${contractName}, ${leafIndex})`);\n return new Promise((resolve, reject) => {\n const options = {\n url: `${url}/siblingPath/${leafIndex}`,\n method: 'POST',\n json: true,\n body: { contractName },\n };\n request(options, (err, res, body) => {\n if (err) reject(err);\n else resolve(body.data);\n });\n });\n}", "function makeSecretNetworkPath(a) {\n return [\n crypto_1.Slip10RawIndex.hardened(44),\n crypto_1.Slip10RawIndex.hardened(529),\n crypto_1.Slip10RawIndex.hardened(0),\n crypto_1.Slip10RawIndex.normal(0),\n crypto_1.Slip10RawIndex.normal(a),\n ];\n}", "function handleLayer(index, dynamap, tab_index, url_index, legend){ \r\n\t\r\n\t// Get the MapService for this layer\r\n\tvar service = dynamap.getMapService();\r\n\tvar layer = service.layers[index];\r\n\r\n\r\n\t// Dynamically create a checkbox. This checkbox will toggle the visibility of this layer.\r\n\tvar checkbox = document.createElement('input');\r\n\tvar legendItem = null;\r\n\tvar opt = null;\r\n\tvar closest = null;\r\n\tcheckbox.type = 'checkbox';\r\n\tcheckbox.id = 'cb ' + layer.name;\r\n\tcheckbox.onclick = function(){\r\n\r\n\t\t// Turned on\r\n\t\tif (checkbox.checked === true) {\r\n\r\n\t\t\t// Visibility\r\n\t\t\tlayer.visible = true;\r\n\r\n\t\t\t// Add to active layers\r\n\t\t\tactiveLayers[layer.name] = layer;\r\n\r\n\t\t\t// Query Option\r\n\t\t\topt = document.createElement('option');\r\n\t\t\topt.innerHTML = layer.name;\r\n\t\t\topt.value = layer.name;\r\n\r\n\t\t\t// Add option\t\t\t\r\n\t\t\tdocument.getElementById(\"dropDownLayer\").appendChild(opt);\r\n\t\t\tdocument.getElementById(\"dropDownLayer\").selectedIndex = document.getElementById(\"dropDownLayer\").options.length - 1;\r\n\t\t\tchangeLayer();\r\n\r\n\t\t\t// Legend\r\n\t\t\tlegendItem = getLegend(tab_index, url_index, index, legend, service);\r\n\t\t\t\r\n\t\t\t// Analytics on layer views\r\n\t\t\t_gaq.push(['_trackEvent', layer.name + ' views', 'Checkbox_checked']);\r\n\r\n\t\t}\r\n\r\n\t\t// Turned off\r\n\t\telse {\r\n\r\n\t\t\t// Visibility\r\n\t\t\tlayer.visible = false;\r\n\r\n\t\t\t// Query options\r\n\t\t\tdropdown = document.getElementById(\"dropDownLayer\");\r\n\t\t\tdropdown.remove(opt.index);\r\n\t\t\tdelete activeLayers[layer.name];\r\n\t\t\tchangeLayer();\r\n\t\t\tif (dropdown.options.length > 2) {\r\n\t\t\t\tdropdown.selectedIndex = dropdown.options.length - 1;\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Legend\r\n\t\t\tif(legendItem)\r\n\t\t\t\tdocument.getElementById(\"tabs-2\").removeChild(legendItem);\r\n\r\n\t\t\t// Hide Lingering Features\r\n\t\t\tdispatcher.dispatch(function(feature) {\r\n\t\t\t\tfeature.hide(layer.name);\r\n\t\t\t});\r\n\t\t\tdispatcher.clear(layer.name);\r\n\t\t}\r\n\r\n\t\t// Refresh layer so changes are rendered\r\n\t\tdynamap.refresh();\r\n\r\n\t}; // end of onclick function\r\n\r\n\r\n\t// Label for the checkbox. It's just the name of the associated layer. \r\n\tvar label = document.createElement('label');\r\n\tlabel.className = 'checkbox_label';\r\n\tlabel.appendChild(checkbox);\r\n\tlabel.appendChild(document.createTextNode(layer.name));\r\n\t\r\n\t// Info Box\r\n\tvar metaInfo = document.createElement('div');\r\n\tmetaInfo.className = 'meta_info';\r\n\tmetaInfo.style.display = 'none';\r\n\tmetaInfo.innerHTML = metadata[layer.name];\r\n\tmetaInfo.appendChild(document.createElement('br'));\r\n\r\n\t// Info button\r\n\tvar btn = document.createElement('button');\r\n\tbtn.innerHTML = \"?\";\r\n\tbtn.onclick = function(){\r\n\t\tif (btn.innerHTML == '?') {\r\n\t\t\tmetaInfo.style.display = 'block';\r\n\t\t\tbtn.innerHTML = '-';\r\n\t\t\t//metaInfo.appendChild(document.createElement\r\n\t\t}\r\n\t\telse {\r\n\t\t\tmetaInfo.style.display = 'none';\r\n\t\t\tbtn.innerHTML = '?';\r\n\t\t}\r\n\t}\r\n\tbtn.className = 'info_button';\r\n\t\r\n\t// Find which tab this layer belongs in.\r\n\tvar ID = tabID(tab_index);\r\n\r\n\t// Place the checkbox and the label within the appropriate tab\r\n\tdocument.getElementById(ID).appendChild(btn);\r\n\tdocument.getElementById(ID).appendChild(label);\r\n\tdocument.getElementById(ID).appendChild(document.createElement('br'));\r\n\tdocument.getElementById(ID).appendChild(metaInfo);\r\n\r\n}", "static async createWalletObj(mnemonic, index){\n let hdPath = makeCosmoshubPath(index)\n return await Secp256k1HdWallet.fromMnemonic(mnemonic,hdPath);\n }", "function getPathSegment(path, index) {\n\n return path.split(\"?\")[0].split(\"/\")[index];\n }", "function sleuth_fat(idx,cnt,sectors,ssz,fat_addrs){var q=ENDOFCHAIN;if(idx===ENDOFCHAIN){if(cnt!==0)throw new Error(\"DIFAT chain shorter than expected\");}else if(idx!==-1/*FREESECT*/){var sector=sectors[idx],m=(ssz>>>2)-1;if(!sector)return;for(var i=0;i<m;++i){if((q=__readInt32LE(sector,i*4))===ENDOFCHAIN)break;fat_addrs.push(q);}sleuth_fat(__readInt32LE(sector,ssz-4),cnt-1,sectors,ssz,fat_addrs);}}", "pushHardened(index) {\r\n this._path.push(`${index}'`);\r\n }", "function getSongSymbol(index) {\n let i = 0;\n for (const line of songLines) {\n for (const symbol of line.symbols) {\n if (songBreaks.includes(symbol)) {\n continue;\n }\n if (i == index) {\n return symbol;\n }\n i++;\n }\n }\n}", "function deriveAddress(rootAddressXPRV, index, derivePath) {\n\tif ((derivePath != null) && (derivePath != undefined)) {\n\t\tvar path = derivePath;\n\t} else {\n\t\tpath = \"m/0'/\"+String(index); //http://bip32.org/ - external account master\n\t}\n\tvar root = bitcoin.HDNode.fromBase58(rootAddressXPRV);\n\tvar child = root.derivePath(path);\n\t/*\n\t//Using bip32-utils:\n\tvar i = child.deriveHardened(0);\n\tvar external = i.derive(0);\n\tvar internal = i.derive(1);\n\tvar account = new bip32.Account([\n\t\tnew bip32.Chain(external.neutered()),\n\t\tnew bip32.Chain(internal.neutered())\n\t])\n\ttrace (\"root=\"+root.getAddress());\n\ttrace (\"account.getChainAddress(0)=\"+account.getChainAddress(0));\n\tchild.xprv = rootAddressXPRV;\n\tchild.xpub = account.derive(account.getChainAddress(0)).toBase58();\n\t*/\n\t/*\n\t//Using BlockCypher's API:\n\t//Adds the account created above to BlockCypher as a HD wallet\n\trequest({\n\t\turl: \"https://api.blockcypher.com/v1/btc/main/wallets/hd?token=fb7cf8296b9143a889913b1ce43688aa\",\n\t\tmethod: \"POST\",\n\t\tbody: {\"name\": \"dev1\", \"extended_public_key\": \"xpub6CKPU4Z2znVZz7vVoadaBird7Pt3mAVVFPtUmkkXqDwrMAbVWRkSD16uLuArpjp3VypKg8reWXm3ygsh7PDGJgKwEdntfX8cmWZz7Fn564x\"},\n\t\tjson: true\n\t}, function (error, response, body){\n\t\tconsole.log(error);\n\t\tconsole.log(JSON.stringify(body));\n\t});\n\t//get new derived address:\n\trequest({\n\t\t\turl: \"https://api.blockcypher.com/v1/btc/main/wallets/hd/dev1/addresses/derive?token=fb7cf8296b9143a889913b1ce43688aa\",\n\t\t\tmethod: \"POST\",\n\t\t\tjson: true\n\t\t}, function (error, response, body){\n\t\t\tconsole.log(error);\n\t\t\tconsole.log(JSON.stringify(body));\n\t\t});\n\n\t\t//{\"chains\":[{\"chain_addresses\":[{\"address\":\"19vgSNKNAKFmHzxv4d4K8bm6bhrVc7dhnj\",\"public\":\"03892a1b527a3786e62dddea187f7c5b2f5eb8a35038beaf838bb02536f5d6dd72\",\"path\":\"m/0\"}]}]}\n\t*/\n\treturn (child);\n}", "function deriveAddress(rootAddressXPRV, index, derivePath) {\n\tif ((derivePath != null) && (derivePath != undefined)) {\n\t\tvar path = derivePath;\n\t} else {\n\t\tpath = \"m/0'/\"+String(index); //http://bip32.org/ - external account master\n\t}\n\tvar root = bitcoin.HDNode.fromBase58(rootAddressXPRV);\n\tvar child = root.derivePath(path);\n\t/*\n\t//Using bip32-utils:\n\tvar i = child.deriveHardened(0);\n\tvar external = i.derive(0);\n\tvar internal = i.derive(1);\n\tvar account = new bip32.Account([\n\t\tnew bip32.Chain(external.neutered()),\n\t\tnew bip32.Chain(internal.neutered())\n\t])\n\ttrace (\"root=\"+root.getAddress());\t\n\ttrace (\"account.getChainAddress(0)=\"+account.getChainAddress(0));\n\tchild.xprv = rootAddressXPRV;\n\tchild.xpub = account.derive(account.getChainAddress(0)).toBase58();\n\t*/\n\t/*\n\t//Using BlockCypher's API:\n\t//Adds the account created above to BlockCypher as a HD wallet\n\trequest({\n\t\turl: \"https://api.blockcypher.com/v1/btc/main/wallets/hd?token=fb7cf8296b9143a889913b1ce43688aa\",\n\t\tmethod: \"POST\",\n\t\tbody: {\"name\": \"dev1\", \"extended_public_key\": \"xpub6CKPU4Z2znVZz7vVoadaBird7Pt3mAVVFPtUmkkXqDwrMAbVWRkSD16uLuArpjp3VypKg8reWXm3ygsh7PDGJgKwEdntfX8cmWZz7Fn564x\"},\n\t\tjson: true \n\t}, function (error, response, body){\n\t\tconsole.log(error);\n\t\tconsole.log(JSON.stringify(body));\n\t});\n\t//get new derived address:\n\trequest({\n\t\t\turl: \"https://api.blockcypher.com/v1/btc/main/wallets/hd/dev1/addresses/derive?token=fb7cf8296b9143a889913b1ce43688aa\",\n\t\t\tmethod: \"POST\",\n\t\t\tjson: true \n\t\t}, function (error, response, body){\n\t\t\tconsole.log(error);\n\t\t\tconsole.log(JSON.stringify(body));\n\t\t});\n\t\t\n\t\t//{\"chains\":[{\"chain_addresses\":[{\"address\":\"19vgSNKNAKFmHzxv4d4K8bm6bhrVc7dhnj\",\"public\":\"03892a1b527a3786e62dddea187f7c5b2f5eb8a35038beaf838bb02536f5d6dd72\",\"path\":\"m/0\"}]}]}\n\t*/\n\treturn (child);\n}", "function drawPathFromIndexOrder(indexOrderToDraw, pathStrokeWeight=CIRCLE_STROKE_WEIGHT*2, pathStrokeColor=color(50, 168, 162)) {\r\n beginShape();\r\n for(var i = 0; i < indexOrderToDraw.length; i++) {\r\n if(indexOrderToDraw[i] != null) {\r\n vertex(points[indexOrderToDraw[i]].x, points[indexOrderToDraw[i]].y);\r\n }\r\n }\r\n noFill();\r\n stroke(pathStrokeColor);\r\n strokeWeight(pathStrokeWeight);\r\n endShape();\r\n}", "function startWith(hash, second) {\n console.log(`${VERSION} =>\\n ${hash} inserted`);\n if (hash && hash != \"pending\") {\n console.log(`Attempting to start from IPFS save state ${hash}`);\n ipfspromise(hash)\n .then((blockInfo) => {\n var blockinfo = JSON.parse(blockInfo);\n ipfspromise(blockinfo[1].root ? blockinfo[1].root : hash).then(\n (file) => {\n var data = JSON.parse(file);\n startingBlock = data[0];\n block.root = blockinfo[1].root ? blockinfo[1].root : hash;\n block.prev_root = data[1].prev_root\n ? data[1].prev_root\n : data[1].stats.root || \"\";\n console.log(\"root\", block.root);\n if (!startingBlock) {\n startWith(sh);\n } else {\n store.del([], function (e) {\n if (!e && (second || data[0] > API.RAM.head - 325)) {\n if (hash) {\n var cleanState = data[1];\n store.put([], cleanState, function (err) {\n if (err) {\n console.log(\"errr\", err);\n } else {\n if (blockinfo[1].chain) {\n rundelta(\n blockinfo[1].chain,\n blockinfo[1].ops,\n blockinfo[0],\n blockinfo[1].prev_root\n )\n .then((empty) => {\n const blockState = Buffer.from(\n stringify([startingBlock, block])\n );\n block.ops = [];\n issc(startingBlock, blockState, startApp, 0, 1);\n console.log(\n `Account: ${\n config.username\n }\\nKey: ${config.active.substr(0, 3)}...`\n );\n //getPathNum(['balances', 'ra']).then(r=>console.log(r))\n })\n .catch((e) => console.log(\"Failure of rundelta\", e));\n } else {\n console.log(\"No Chain\");\n TXID.saveNumber = startingBlock;\n startApp();\n }\n }\n });\n } else {\n store.put([], data[1], function (err) {\n if (err) {\n console.log(err);\n } else {\n store.get(\n [\"balances\", \"ra\"],\n function (error, returns) {\n if (!error) {\n console.log(\"there\" + returns);\n }\n }\n );\n startApp();\n }\n });\n }\n } else if (!second) {\n var promises = [];\n for (var runner in data[1].runners) {\n promises.push(\n new Promise((resolve, reject) => {\n console.log(\"runner\", runner);\n hiveClient.api.setOptions({ url: config.startURL });\n hiveClient.api.getAccountHistory(\n runner,\n -1,\n 100,\n ...walletOperationsBitmask,\n function (err, result) {\n var recents = { block: 0 };\n if (err) {\n console.log(\"error in retrieval\");\n resolve({ hash: null, block: null });\n } else {\n let ebus = result.filter(\n (tx) =>\n tx[1].op[1].id === `${config.prefix}report`\n );\n for (i = ebus.length - 1; i >= 0; i--) {\n if (JSON.parse(ebus[i][1].op[1].json).hash) {\n if (\n recents.block <\n JSON.parse(ebus[i][1].op[1].json).block\n ) {\n recents = {\n hash: JSON.parse(ebus[i][1].op[1].json)\n .hash,\n block: parseInt(\n JSON.parse(ebus[i][1].op[1].json).block\n ),\n };\n } else {\n recents[0] = {\n hash: JSON.parse(ebus[i][1].op[1].json)\n .hash,\n block: parseInt(\n JSON.parse(ebus[i][1].op[1].json).block\n ),\n };\n }\n }\n }\n if (recents.block) {\n resolve(recents);\n } else {\n console.log(\"error in processing\", runner);\n resolve({ hash: null, block: null });\n }\n }\n }\n );\n })\n );\n }\n Promise.all(promises).then((values) => {\n hiveClient.api.setOptions({ url: config.clientURL });\n var newest = 0,\n votes = {},\n blocks = {};\n for (var acc in values) {\n if (\n values[acc].block >= newest &&\n !votes[values[acc].hash]\n ) {\n newest = values[acc].block;\n votes[values[acc].hash] = 1;\n blocks[values[acc].hash] = values[acc].block;\n } else if (\n values[acc].block >= newest &&\n votes[values[acc].hash]\n ) {\n votes[values[acc].hash]++;\n }\n }\n var tally = 0,\n winner = null;\n for (hash in votes) {\n if (\n votes[hash] >= tally &&\n blocks[values[acc].hash] == newest\n ) {\n tally = votes[hash];\n var winner = hash;\n }\n }\n if (winner) startWith(winner, true);\n else startWith(hash, true);\n return;\n });\n }\n });\n }\n }\n );\n })\n .catch((e) => {\n console.log(\"error in ipfs\", e);\n process.exit(4);\n });\n } else {\n startingBlock = config.starting_block;\n store.del([], function (e) {\n if (e) {\n console.log({ e });\n }\n store.put([], statestart, function (err) {\n if (err) {\n console.log({ err });\n } else {\n store.get([\"stats\", \"hashLastIBlock\"], function (error, returns) {\n if (!error) {\n console.log(\n `State Check: ${returns}\\nAccount: ${\n config.username\n }\\nKey: ${config.active.substr(0, 3)}...`\n );\n }\n });\n TXID.saveNumber = config.starting_block;\n startApp();\n }\n });\n });\n }\n}", "function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {\n var q = ENDOFCHAIN;\n\n if (idx === ENDOFCHAIN) {\n if (cnt !== 0) throw new Error(\"DIFAT chain shorter than expected\");\n } else if (idx !== -1\n /*FREESECT*/\n ) {\n var sector = sectors[idx],\n m = (ssz >>> 2) - 1;\n if (!sector) return;\n\n for (var i = 0; i < m; ++i) {\n if ((q = __readInt32LE(sector, i * 4)) === ENDOFCHAIN) break;\n fat_addrs.push(q);\n }\n\n sleuth_fat(__readInt32LE(sector, ssz - 4), cnt - 1, sectors, ssz, fat_addrs);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Canvas 2D filter backend.
function Canvas2dFilterBackend() {}
[ "function applyFilterInCanvas() {\n tool.filter = currFilter;\n tool.drawImage(img_container, 0, 0, canvas.width, canvas.height);\n tool.filter = \"none\";\n}", "function filterCanvas(filter)\n{\n\tif (canvas.width > 0 && canvas.height > 0)\n\t{\n\t\tvar imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\t\tfilter(imageData);\n\t\tctx.putImageData(imageData, 0, 0);\n\t\t\trow = window.place[0]\n\t\t\tcolumn = window.place[1]\n\t\t\t// r = window.places[i][2][0]\n\t\t\t// g = window.places[i][2][1]\n\t\t\t// b = window.places[i][2][2]\n\t\t\t// ctx.fillStyle = \"rgb(\"+r+\",\"+g+\",\"+b+\")\";\n\t\t\t// ctx.fillRect(row,column,2,2);\n\n\t\t\t// ctx.beginPath();\n\t\t\t// ctx.arc(row, column, 50, 0, 2 * Math.PI, false);\n\t\t\t// ctx.fillStyle = 'green';\n\t\t\t// ctx.fill();\n\t\t\t// ctx.stroke();\n\n\n\t\t\t\n\n\t\t\t// bezier curve\n\t\t\t// ctx.lineTo(row, column);\n\n\t\t\t// ctx.lineWidth = 1;\n\t\t\t// ctx.strokeStyle = 'teal';\n\t\t\t// ctx.stroke();\n\n\t}\n}", "applyFilter(canvas, value, filter) {\n\n const { name, unit } = filter;\n\n const ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.filter = `${name}(${value}${unit})`;\n ctx.drawImage(this.canvas, 0, 0);\n }", "function filterCanvas(filter) {\n if (canvas.width > 0 && canvas.height > 0) {\n var imageData = context.getImageData(0, 0, canvas.width, canvas.height);\n filter(imageData);\n context.putImageData(imageData, 0, 0);\n }\n}", "function processFilters() {\n\tif (isCanvasSupported())\n\t{\n\t\t// create working buffer outside the main loop so it's only done once\n\t\tvar buffer = document.createElement(\"canvas\");\n\t\t// get the canvas context\n\t\tvar c = buffer.getContext('2d');\n\t\n\t\t// only run if this browser supports canvas, obviously\n\t\tif (supports_canvas()) {\n\t\t\t// you can add or remove lines here, depending on which filters you're using.\n\t\t\taddFilter(\"filter-blur\", buffer, c);\n\t\t\taddFilter(\"filter-edges\", buffer, c);\n\t\t\taddFilter(\"filter-emboss\", buffer, c);\n\t\t\taddFilter(\"filter-greyscale\", buffer, c);\n\t\t\taddFilter(\"filter-matrix\", buffer, c);\n\t\t\taddFilter(\"filter-mosaic\", buffer, c);\n\t\t\taddFilter(\"filter-noise\", buffer, c);\n\t\t\taddFilter(\"filter-posterize\", buffer, c);\n\t\t\taddFilter(\"filter-sepia\", buffer, c);\n\t\t\taddFilter(\"filter-sharpen\", buffer, c);\n\t\t\taddFilter(\"filter-tint\", buffer, c);\n\t\t}\n\t}\n}", "_prepareCanvas2D () {\n\n }", "function ApplyFilter(filter, ctx, canvas){\n\t// console.log('in ApplyFilter')\n\tctx.drawImage(image,0,0, canvas.width, canvas.height);\t\t\t\t\t\t\t\t\t//drow the original image\n\tvar img = ctx.getImageData(0,0,canvas.width, canvas.height);\t\t\t\t\t\t\t// get the image data into a new variable\n\n\tif(filter==='red'){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// if filter is red then, set img.data to original img.data only the red pixel which is img.data[i], each element from 4(0, 4, 8, )\n\t\tfor(var i = 0; i<img.data.length; i+=4){\n\t\t\timg.data[i] = img.data[i];\n\t\t\timg.data[i+1]=0;\n\t\t\timg.data[i+2]=0;\n\t\t\timg.data[i+3]=img.data[i+3];\n\t\t}\n\t} else if (filter==='blue'){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tfor(var i = 0; i<img.data.length; i+=4){\n\t\t\timg.data[i] = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// if filter is blue then, set img.data to original img.data only the blue pixel which is img.data[i], each element from 4(2, 6, 10, )\n\t\t\timg.data[i+1]=0;\n\t\t\timg.data[i+2]=img.data[i+2];\n\t\t\timg.data[i+3]=img.data[i+3];\n\t\t}\n\t} else if (filter==='green'){\n\t\tfor(var i = 0; i<img.data.length; i+=4){\t\t\t\t\t\t\t\t\t\t\t// if filter is green then, set img.data to original img.data only the green pixel which is img.data[i], each element from 4(1, 5, 9, ... )\n\t\t\timg.data[i] = 0;\n\t\t\timg.data[i+1]=img.data[i+1];\n\t\t\timg.data[i+2]=0;\n\t\t\timg.data[i+3]=img.data[i+3];\n\t\t}\n\t} else if (filter==='gray'){\n\t\tfor(var i = 0; i<img.data.length; i+=4){\n\t\t\timg.data[i] = 0.2126*img.data[i] + 0.7152*img.data[i+1]+ 0.0722*img.data[i+2];\t//convert the image data into gray scale and then store the results in the red pixel and assign the grayscale value to the other pixels\n\t\t\t// img.data[i] = 0.333*img.data[i] + 0.333*img.data[i+1]+ 0.333*img.data[i+2];\n\t\t\timg.data[i+1]=img.data[i];\n\t\t\timg.data[i+2]=img.data[i];\n\t\t\timg.data[i+3]=img.data[i+3];\n\t\t}\n\t} else if (filter==='sepia'){\n\t\tfor(var i = 0; i<img.data.length; i+=4){\n\t\t\timg.data[i] = 0.3*img.data[i] + 0.59*img.data[i+1]+ 0.11*img.data[i+2];\t\t\t//Convert the image to another scale using the provided equation, then store the values to the red, green, and blue pixels of the image \n\t\t\timg.data[i+1]=img.data[i]+20;\t\t\t\t\t\t\t\t\t\t\t\t\t//add 20 to each green pixel\n\t\t\timg.data[i+2]=img.data[i]+20;\t\t\t\t\t\t\t\t\t\t\t\t\t//add 20 to each blue pixel\n\t\t\timg.data[i] = img.data[i]+40;\t\t\t\t\t\t\t\t\t\t\t\t\t//add 20 to each red pixel\n\t\t\timg.data[i+3]=img.data[i+3];\n\t\t}\n\t}else if (filter==='invert'){\n\t\tfor(var i = 0; i<img.data.length; i+=4){\t\t\t\t\t\t\t\t\t\t\t//Get the inverse of an image\n\t\t\timg.data[i] = 255-img.data[i];\t\t\t\t\t\t\t\t\t\t\t\t\t//Subtract 255(Max pixel value) from each red, green, and blue pixels\n\t\t\timg.data[i+1]=255-img.data[i+1];\n\t\t\timg.data[i+2]=255-img.data[i+2];\n\t\t\timg.data[i+3]=img.data[i+3];\t\t\t\t\t\t\t\t\t\t\t\t\t//Keep image alpha value as it is.\n\t\t}\n\t}\n\t\n\n\tvar imgData = ctx.createImageData(canvas.width,canvas.width);\t\t\t\t\t\t\t// Create imaData var with the original size of the filter image\t\t\t\n\timgData.data.set(img.data);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Set the imgData data to the processed data from the filters function\t\n\tctx.putImageData(imgData, 0, 0);\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Draw or show the filter image data\n}", "function draw_set_filter(filter, value, calc_type)\n{\n var fil = filter.toString() + '(' + value.toString() + calc_type.toString() + ')';\n //if(context.filter == 'none')\n //{\n surfaceTarget.filter = fil;\n //}\n}", "function addFilterImg(e){\n\n if (mousePos) {\n posX = mousePos.x - (img.width / 2);\n posY = mousePos.y - (img.height / 2);\n\n //Draw the image of the video on the canvas\n ctx.clearRect(0, 0, width, height);\n ctx.filter = filter;\n ctx.drawImage(img, posX, posY, imgSzX, imgSzY);\n\n //show canvas and share button\n canvas.style.display = \"\";\n boolImgFilter = true;\n }\n}", "handleFilterBtns(newFilter){\n let self = this;\n\n //if empty or different filter\n if(self.videoFilter == null || self.videoFilter.filter != newFilter){\n self.videoCanvas.hidden = false;\n self.videoFilter = new videoFilter(self.videoPlayer, self.videoCanvas, newFilter, false);\n self.videoFilter.toggleFilter();\n renderVideoFilter();\n }\n //if filter is already active, disable the filter\n else if(self.videoFilter == newFilter){\n self.videoCanvas.hidden = false;\n self.videoFilter.toggleFilter();\n console.log(self.videoCanvas);\n }\n //in all other cases invert filter-activity\n else{\n self.videoCanvas.hidden = !self.videoCanvas.hidden;\n self.videoFilter.toggleFilter();\n }\n\n //recursive function to repetedly update the filter on the video\n function renderVideoFilter(){\n self.videoFilter.render();\n self.animationID = requestAnimationFrame(renderVideoFilter);\n }\n }", "function filterImg(){\n\tvar canvas = document.getElementById(\"canvas\");\n\tvar context = canvas.getContext(\"2d\");\n\n//canvas.width = mySrcImg.width;\n//canvas.height = mySrcImg.height;\n\ncontext.fillStyle = \"rgb(0,200,0)\";\ncontext.fillRect (0, 0, 300, 300);\n\n//Copy image content to canvas\ncontext.drawImage(mySrcImg, 0, 0);\n\n//Get image data\nvar myImageData;\nvar newImageData;\n\ntry{\n\tmyImageData = context.getImageData(0, 0, canvas.width, canvas.height);\n\tnewImageData = context.createImageData(canvas.width, canvas.height);\n} catch (e) {\n\t//netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n\tmyImageData = context.getImageData(0, 0, canvas.width, canvas.height);\n\tnewImageData = context.createImageData(canvas.width, canvas.height);\n}\n\nalert(\"Starting group pixel processing\");\n\n//Loop over each pixel on canvas\nfor (var x = 0; x < canvas.width; x++){\n\tfor (var y = 0; y < canvas.height; y++){\n\t\t//Index of the pixel in the array\n\t\tvar idx = (x + y * canvas.width) * 4;\n\n\t\t//Indexes for convolution kernel (in screen coordinates\n\t\tfor (var filterx = 0; filterx < convolutionWidth; filterx++){\n\t\t\tfor (var filtery = 0; filtery < convolutionHeight; filtery++){\n\t\t\t\tvar tmpX = ((x - Math.floor(convolutionWidth / 2)) +filterx + canvas.width) % canvas.width;\n\t\t\t\tvar tmpy = ((y - Math.floor(convolutionHeight / 2)) +filtery + canvas.height) % canvas.height;\n\t\t\t\tvar convolutionKernel_Index = (tmpX + tmpy * canvas.width) * 4;\n\n\t\t\t\tvar outputIndex = (filterx + filtery * convolutionWidth) * 4;\n\t\t\t\tconvolutionKernel_Output[outputIndex ] = (convolutionMask[filterx][filtery] * factor) *\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmyImageData.data[convolutionKernel_Index ];\n\n\t\t\t\tconvolutionKernel_Output[outputIndex+1] = (convolutionMask[filterx][filtery] * factor) *\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmyImageData.data[convolutionKernel_Index+1];\n\n\t\t\t\tconvolutionKernel_Output[outputIndex+2] = (convolutionMask[filterx][filtery] * factor) *\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmyImageData.data[convolutionKernel_Index+2];\n\n\t\t\t\tconvolutionKernel_Output[outputIndex+3] = 255;\n\t\t\t}\n\t\t}\n\n//Loop through the output values. Add together\nvar newPixel = new Array(4);\nfor (i=0; i < 4; i++){\n\tnewPixel[i] = 0;\n}\nfor (i=0; i < convolutionKernel_OutputArraySize; i+=4){\n\tnewPixel[0] = newPixel[0] + convolutionKernel_Output[i ] + bias;\n\tnewPixel[1] = newPixel[1] + convolutionKernel_Output[i+1] + bias;\n\tnewPixel[2] = newPixel[2] + convolutionKernel_Output[i+2] + bias;\n\tnewPixel[3] = newPixel[3] + convolutionKernel_Output[i+3] + bias;\n}\n\n//Set the new pixel colour\nnewImageData.data[idx ] = Math.min( Math.max(newPixel[0], 0), 255); //red\nnewImageData.data[idx+1] = Math.min( Math.max(newPixel[1], 0), 255); //green\nnewImageData.data[idx+2] = Math.min( Math.max(newPixel[2], 0), 255); //blue\nnewImageData.data[idx+3] = Math.min( Math.max(newPixel[3], 0), 255); //alpha\n\t}\n}\n\n//Draw the imageDate object at the given (x,y) coordinates\ncontext.putImageData(newImageData, 0,0);\n\nalert(\"Finished group pixel processing\");\n}", "function Filter() {\n var self = this;\n\n // Creates pair of canvases to display before and after images.\n this.display = new ImageProcessingDisplay.ImageProcessingDisplay();\n\n this.defaultOptions = {};\n this.defaultOptions.blurSize = 10;\n this.defaultOptions.cannyThreshold = 75;\n this.defaultOptions.erosionSize = 1;\n\n this.display.on('ready', function (data) {\n self.emit('ready', data);\n });\n}", "function applyFilter(filter) {\n const imageData = getImageData()\n imageData.data = filter(imageData.data)\n canvasContext.putImageData(imageData, 0, 0)\n}", "static _clearExistingCanvasFilter() {\r\n const { style } = this._canvas, filter = \"\";\r\n [style.opacity, style.filter, style.webkitFilter] = [1, filter, filter];\r\n }", "function applyDefaultFilterInUIandCanvas() {\n // Set UI\n img_container.style.filter = \"none\";\n currFilter = \"\";\n // Set Canvas\n tool.drawImage(img_container, 0, 0, canvas.width, canvas.height);\n}", "function FastContext2D(){\r\n\tthis._drawCommands = \"\";\r\n\tthis._globalAlpha = 1.0;\r\n}", "function drawFilters() {\n var fill = getRGBAColorString([255, 255, 255], 0.7);\n for (var i = 0; i < filterShapes.length; i++) {\n filter = filterShapes[i];\n drawCircle(ctxt, filter, fill);\n }\n }", "function sobelFilter(canvas)\n{\n var imageData = canvas.getImageData(0, 0, content.width, content.height);\n var ww = new Worker('/sobel-worker.js');\n ww.postMessage(imageData);\n ww.onmessage = function (event) {\n var sobelData = event.data;\n var sobelImageData = Sobel.toImageData(sobelData, content.width, content.height);\n canvas.putImageData(sobelImageData, 0, 0);\n };\n}", "apply() {\n const g = this.targetCanvas.getContext('2d');\n g.drawImage(this.bufferCanvas, 0, 0);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disable submit inputs in the given form
function disableSubmitButtons(form) { form.find('input[type="submit"]').attr('disabled', true); form.find('button[type="submit"]').attr('disabled', true); }
[ "disable () {\n var els = this.formEls,\n i,\n submitButton = this.getSubmitButtonInstance();\n this.setPropertyAll('disabled', true);\n // add disabled css classes\n for (i = 0; i < els.length; i++) {\n els[i].classList.add('disabled');\n }\n if (submitButton) {\n submitButton.disable();\n }\n\n }", "function disableForm() {\n form.disable();\n form.setDisabled(true);\n confirm_button.setDisabled(true);\n decline_button.setDisabled(true);\n }", "function disableSubmitButtons(form) {\n form.find('input[type=\"submit\"]').attr('disabled', true);\n form.find('button[type=\"submit\"]').attr('disabled', true);\n }", "function enableSubmit(){$(\"#btn_submit_form\").removeAttr('disable');}", "function hackDisableSubmit(){\n $jQ('input[type=\"submit\"]').each(function() {\n $jQ(this).attr(WC+'onclick',$jQ(this).attr('onclick'));\n $jQ(this).attr('onclick','return false;');\n });\n}", "function disableUploadFormSubmitBtn(form) {\n\t\tform.querySelector(\".submit-btn\").disabled = true;\n\t}", "function submitDisabled() {\n let inputs = [...formInput.querySelectorAll('.required')];\n let isIncomplete = inputs.some(input => !input.value);\n btnSubmit.disabled = isIncomplete;\n btnReset.disabled = isIncomplete;\n btnSubmit.style.cursor = isIncomplete ? 'not-allowed' : 'pointer';\n btnReset.style.cursor = isIncomplete ? 'not-allowed' : 'pointer';\n btnSubmit.classList.remove(\"progress-bar-striped\");\n btnSubmit.classList.remove(\"progress-bar-animated\");\n\n }", "function disableForm(form_id) {\r\n $(\"#\" + form_id + \" :input\").prop(\"disabled\", true);\r\n }", "function disableForm() {\n getFormControls().prop('disabled', true).addClass('disabled');\n cancelButton.hide().prop('disabled', true);\n submitButton.prop('disabled', true);\n editButton.prop('disabled', false).show();\n disableFormPassword();\n passwordToggleButton.prop(\"disabled\", true);\n //location.reload(); //the loser's choice\n }", "function no_change_enable_submit_button (form){\n handlers = $.get_logs(form.attr('id')).handlers;\n\n if(typeof handlers != 'undefined' && handlers.length){\n $(handlers).removeClass('disabled').blur();\n }\n }", "function enableSubmitButtons(form) {\n form.find('input[type=\"submit\"]').removeAttr('disabled');\n form.find('button[type=\"submit\"]').removeAttr('disabled');\n }", "function disableHhostForm(form){\r\n\tvar elements=form.elements;\r\n\tvar element,eType;\r\n\tfor (var i=0,iL=elements.length; i<iL; ++i){\r\n\t\telement=elements[i];\r\n\t\teType=element.type;\r\n\t\tif ((eType != \"button\") && (eType != \"hidden\")){\r\n\t\t\tif (isHInput(eType,element.name)){\r\n\t\t\t\telement.disabled = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "enable () {\n var els = this.formEls,\n i,\n submitButton = this.getSubmitButtonInstance();\n this.setPropertyAll('disabled', false);\n // remove disabled css classes\n for (i = 0; i < els.length; i++) {\n els[i].classList.remove('disabled');\n }\n if (submitButton) {\n submitButton.disable();\n }\n }", "function enableFieldsForSubmit(theform) {\r\n var elems = theform.elements;\r\n\r\n for (var i = 0; i < elems.length; i++) {\r\n if (elems[i].disabled) {\r\n if (!(elems[i].style.visibility == \"hidden\")) {\r\n hidElems.push(elems[i]);\r\n }\r\n elems[i].style.visibility = \"hidden\";\r\n elems[i].disabled = false;\r\n }\r\n }\r\n}", "function enableSubmitButtons(form) {\n form.find('input[type=\"submit\"]').removeAttr('disabled');\n form.find('button[type=\"submit\"]').removeAttr('disabled');\n }", "function disableFormFields() {\n\tvar modifyButton = $(modifyButtonName);\n\tvar saveButton = $(saveButtonName);\n\tvar backButton = $(backButtonName);\n\n\tif (modifyButton) {\n\t\tif (modifyButton.oldOnclick) {\n\t\t\t//Transform the cancel back to modify button\n\t\t\tmodifyButton.onclick = modifyButton.oldOnclick;\n\t\t\tmodifyButton.value = modifyLabel;\n\t\t\tmodifyButton.oldOnclick = null;\n\t\t}\n\t}\n\tif (saveButton) {\n\t\tdisableField(saveButton);\n\t}\n\t\n\t//The additional arguments are field names we don't want to touch.\n\tvar keep = $A(arguments);\n\tif (modifyButton) {\n\t\tkeep.push(elementId(modifyButton));\n\t}\n\tif (backButton) {\n\t\tkeep.push(elementId(backButton));\n\t}\n\n\t//Process each field\n\tprocessFields(this, keep, disableField);\n}", "function disableSubmit(){\n $(\"input[type='submit']\").attr('disabled','disabled');\n $(\"input[type='submit']\").addClass('disabled');\n}", "function disableSubmit() {\n document.getElementById(\"submit\").disabled = true;\n}", "function preventImplicitSubmission(form_name){\n // disable enter for all input elements that are not of type submit, button, or reset\n // and for all select elements, that are found to occur at any level within the form.\n // Note that enter is not disabled for textarea elements\n let implicit_sub_input_types = [\"input[type!='submit'][type!='button'][type!='reset']\",\n \"select\"];\n let partial_selector = 'form[name =\"' + form_name + '\"]';\n $.each(implicit_sub_input_types, function(index, value) {\n let input_elements = $(partial_selector).find(value);\n\n // for each input element of the given type in form, disable submit on pressing Enter\n // by making the keydown event return false on presses of that key\n input_elements.each(function() {\n $(this).keydown(function (e) {\n if (e.keyCode === 13) {\n e.preventDefault();\n return false;\n }\n });\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check config for embedded flag
function isEmbedded(config) { return config && (config.embedded === 'always' || config.embedded === 'load'); }
[ "configIsValid(config) {\n return true;\n }", "function hasControlConfig (control) {\n return control.hasAttribute('vfp:config') || control.getElementsByTagName('vfp:config')[0] != undefined; \n}", "function checkConfig(){\n for(let i in configuration)\n if(configuration[i]==null)\n return false;\n return true;\n}", "isConfigurationValid() {\n if (this.config.axosoftUrl == atom.config.defaultSettings['atom-axosoft'].axosoftUrl) {\n return false;\n }\n if (this.config.accessToken == atom.config.defaultSettings['atom-axosoft'].accessToken) {\n return false;\n }\n\n return true;\n }", "verifyConfiguration(config) {\n if (config.traverse_nat_enabled && config.onion_enabled) {\n this.log.error('Refusing to start with both TraverseNatEnabled and ' +\n 'OnionEnabled - this is a privacy risk');\n process.exit(1);\n }\n }", "hasConfiguration() {\n const {integration, provider} = this.props;\n\n return (\n integration.configOrganization.length > 0 ||\n provider.features.filter((f) => CONFIGURABLE_FEATURES.includes(f)).length > 0\n );\n }", "get isConfig() {\n return this.name.startsWith('$');\n }", "function isCloudRun() {\n return !!process.env.K_CONFIGURATION;\n}", "displayInEmbedMode(data) {\r\n const embedValue = data.embed === 'true' ? true : false;\r\n if (embedValue && data.containerID && data.containerID.length > 0) {\r\n return true;\r\n }\r\n return false;\r\n }", "function checkCloudsRenderConfigExtension () {\n return getEngineSettings().then(function (engineSettings) {\n /** @type {string[]} */\n let renderConfigExtensions = engineSettings.render_config_extensions;\n if (!_.isArray(renderConfigExtensions))\n return false;\n \n return renderConfigExtensions.indexOf(CLOUDS_RENDER_CONFIG_NAME) >= 0;\n });\n }", "function validateConfigSpecified() {\n if (!configName) {\n logger.error('You must specify a --config flag');\n process.exit(0);\n } else if (!config.configExists(configName)) {\n logger.error(`The config [${configName}] does not exist in your config file.`);\n process.exit(0);\n }\n}", "function checkConfiguration() {\n // count keys should not be set as array/narg\n Object.keys(flags.counts).find(key => {\n if (checkAllAliases(key, flags.arrays)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));\n return true;\n }\n else if (checkAllAliases(key, flags.nargs)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));\n return true;\n }\n return false;\n });\n }", "_checkProjectConfig() {\n return this._projectConfig.checkConfig();\n }", "function isConfigSecret(k) {\n const envConfigSecretKeys = process.env[configSecretKeysEnvKey];\n if (envConfigSecretKeys) {\n const envConfigSecretArray = JSON.parse(envConfigSecretKeys);\n if (Array.isArray(envConfigSecretArray)) {\n return envConfigSecretArray.includes(k);\n }\n }\n return false;\n}", "function checkConfiguration(config)\n {\n var reqProps = [\"ExteriorColourID\", \"UpholsteryID\",\"GradeID\",\"CarID\",\"BodyTypeID\",\"EngineID\",\"TransmissionID\",\"WheelDriveID\",\"FuelTypeID\",\"WheelID\"],\n \ti = 0,\n \tiL = reqProps.length;\n for(; i < iL; i++)\n {\n \tif(!_configuration.isValid(config[reqProps[i]]) || _configuration.isEmpty(config[reqProps[i]]))\n \t{\n \t\treturn false;\n \t}\n }\n return true;\n }", "function checkConfiguration () {\n // count keys should not be set as array/narg\n Object.keys(flags.counts).find(key => {\n if (checkAllAliases(key, flags.arrays)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key))\n return true\n } else if (checkAllAliases(key, flags.nargs)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key))\n return true\n }\n })\n }", "function checkConfiguration () {\n // count keys should not be set as array/narg\n Object.keys(flags.counts).find(key => {\n if (checkAllAliases(key, flags.arrays)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));\n return true\n } else if (checkAllAliases(key, flags.nargs)) {\n error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));\n return true\n }\n });\n }", "function checkConfig(docType,addCusProps,remCusProps)\n{\n // working with some global vars here\n debug.log(\"INFO\",\"Checking to see if provided configuration is valid.\\n\");\n \n //check custom property info\n var sql = \"SELECT PROP_NAME FROM IN_PROP;\";\n var returnVal; \n var cur = getHostDBLookupInfo_cur(sql,returnVal);\n var allProps = [];\n\n if(!cur || cur == null)\n {\n debug.log(\"Error\",\"Can't get list of CPs.\\n\");\n return false;\n }\n \n while (cur.next())\n {\n allProps.push(cur[0]);\n }\n\n //check the cps to add\n var cpAdd = checkCPs(allProps,addCusProps,CP_ADD_OK);\n //end check the cps to add\n \n //check the cps to remove\n var cpRem = checkCPs(allProps,remCusProps,CP_REMOVE_OK);\n //end check the cps to remove\n\n //check the document types\n var dtToWork = checkDocTypes(docType, DOCTYPE_OK);\n //end check the document types\n\n //return true if it all is OK to proceed\n if (!cpAdd || !cpRem || !dtToWork)\n { \n return false;\n }\n else\n {\n return true;\n }\n}//end checkCPConfig()", "function config_file_exist_test(){\n\tvar request = {\n\t\t\"fileTypes\" : [\"CONFIGURATION\"]\n\t}\n\tpublish(request, topicBase + \"evt/request/resource/files/listing\" )\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format the given error before it is serialized and sent to the client
function formatError(error) { const extensions = error.extensions || {}; const originalError = error.originalError || {}; const code = extensions.code || originalError.code; const headers = originalError.headers || {}; const traceId = extensions.traceId || originalError.traceId || headers['x-trace-id']; const requestId = extensions.requestId || originalError.requestId || headers['x-request-id']; // Include the HTTP status code, trace ID and request ID if they exist. These can come from // the underlying HTTP library such as axios. Including this information in the error for the // benefit of the client that made the request. // // The `extensions` field conforms with the GraphQL format error specification, section 7.1.2 // @see https://graphql.github.io/graphql-spec/June2018/#sec-Errors // N.B. Need to create a new error in order to avoid any potential read-only issue trying to // modify the given error const newError = new Error(); // According to section 7.1.2 of the GraphQL specification, fields `message`, and `path` are // required. The `locations` field may be included. newError.message = determineErrorMessage(error); newError.path = error.path; if (error.locations) { newError.locations = error.locations; } const newExts = {}; newError.extensions = newExts; if (code) { newExts.code = code; } if (traceId) { newExts.traceId = traceId; } if (requestId) { newExts.requestId = requestId; } return newError; }
[ "function formatError() {\r\n\t\terror(format.apply(this, arguments));\r\n\t}", "function formatError (e) {\n let err = new HttpValidationError();\n if (e.data && e.data.hasOwnProperty('GetFormattedErrors')) {\n err.msgLong = e.data.GetFormattedErrors().map((err) => { return err.message; }).toString();\n } else {\n err.msgLong = e.data.errors.toString();\n }\n return err;\n}", "function serializeError(err) {\n if (err instanceof Error) {\n const resError = ld.pick(err, ['name', 'code', 'message', 'statusCode', 'payload'])\n resError.stack = err.stack.split('\\n').slice(0, 6).join('\\n')\n return resError\n }\n return err\n}", "function formatError(error) {\n const responseStatus = `${error.response.status} (${error.response.statusText})`;\n\n console.log(\n `Request failed with HTTP status code ${responseStatus}`,\n JSON.stringify({\n url: error.config.url,\n response: error.response.data\n }, null, 2)\n );\n\n throw error;\n}", "formatSequelizeErrors(error) {\n let validationErrors = [];\n if (error.errors) {\n validationErrors = this.extractSequelizeErrors(error.errors);\n } else if (error.message) {\n validationErrors.push(error.message);\n } else {\n validationErrors.push(error.toString());\n }\n return validationErrors;\n }", "function convertError(error) {\r\n var name = error.name, message = error.message;\r\n var status;\r\n if (error.status) {\r\n status = error.status;\r\n }\r\n // create the data object to send to client\r\n var data = {\r\n name: name,\r\n message: message,\r\n status: status,\r\n };\r\n return data;\r\n}", "function formatErrors(errors) {\n\t\tif(!errors || !errors.length) {\n\t\t\treturn;\n\t\t}\n\n\t\t//$log.log(\"Amount of errors \" + errors.length);\n\t\t//deal with 500 Invalid channel specified\n\t}", "function serializeError(error) {\r\n if (error !== undefined && error !== null) {\r\n var simpleObject = {};\r\n if (error.name) {\r\n simpleObject[\"name\"] = error.name;\r\n }\r\n if (error.message) {\r\n simpleObject[\"message\"] = error.message;\r\n }\r\n if (error.stack) {\r\n simpleObject[\"stack\"] = error.stack;\r\n }\r\n // Copy extra properties not mentioned here.\r\n Object.getOwnPropertyNames(error).forEach(function (key) {\r\n if (simpleObject[key] == undefined) {\r\n simpleObject[key] = error[key];\r\n }\r\n });\r\n return simpleObject;\r\n }\r\n else {\r\n return error;\r\n }\r\n}", "function formatError (error) {\n var hasDiff = typeof (error.actual) !== 'undefined' || typeof (error.expected) !== 'undefined'\n var stack = hasDiff ? error.message : (error.stack ? error.stack : (error.message ? error.message : error))\n var err = [stack]\n if (hasDiff) {\n err.push('expected: ' + error.expected)\n err.push('actual: ' + error.actual)\n }\n return err\n}", "function errSerializer(err) {\n return bunyan.stdSerializers.err(err);\n}", "function _addToJSON(error) {\n Object.defineProperty(error, 'toJSON', {\n value: function() {\n return serializeError(this);\n },\n configurable: true,\n writable: true\n });\n}", "function errorFormatter (err, ctx) {\n const response = mercurius.defaultErrorFormatter(err, ctx)\n response.statusCode = 200\n return response\n}", "function formatErrorData(data) {\n return '<h3><span class=\"glyphicon glyphicon-exclamation-sign\" aria-hidden=\"true\"></span>'\n +'<span class=\"sr-only\">Error:</span>Error:</h3><br><b>Status:</b> '+data.status+' '+data.statusText+'<br>'+data.responseText;\n}", "function buildErrorResponse(err, pretty) {\n var msg = '';\n switch (err) {\n case '400-01':\n msg = 'Syntax Error. The syntax is not correct or missing some parameters';\n break;\n case '420-02':\n msg = 'Method Failure. The database is disconnected';\n break;\n case '406-01':\n msg = 'Not Acceptable. The organization is not in exhausted mode';\n break;\n case '406-02':\n msg = 'Not Acceptable. The organization is not existed';\n break;\n case '406-13':\n msg = 'Not Acceptable. The organization is not in normal mode or exhausted mode';\n break;\n }\n\n return stringifyJsonObj({\n errors: {\n code: err,\n message: msg\n }\n }, pretty);\n}", "function extendToJSON(error) {\n error.toJSON = errorToJSON;\n // Also add an inspect() method, for compatibility with Node.js' `util.inspect()` method\n error.inspect = errorToString;\n }", "function error_out(message, error) {\n\tlet error_fmt = error.toString().replace(/Error: /, '').replace(/Error: /, '').trim();\n\tlog.msg('Error ' + message + ': ' + error_fmt);\n}", "function massageError(error) {\n if (!error.message) {\n return error;\n }\n const message = error.message.replace(/^JSON.parse: /, '').replace(/of the JSON data/, '');\n const parts = /line (\\d+) column (\\d+)/.exec(message);\n if (!parts || parts.length !== 3) {\n return error;\n }\n return {\n message: htmlEncode(message),\n line: Number(parts[1]),\n column: Number(parts[2])\n };\n }", "function format_error(err) {\n var errstr = err.errno;\n\n if (errstr == 'ECONNREFUSED') {\n return 'Could not connect to endpoint ' + err.address;\n } else if (errstr == 'ENOENT') {\n return 'Could not locate ' + err.hostname;\n } else {\n return err.toString();\n }\n\n}", "static forError(error) {\n return new Response({\n contentType: JSON_MIMETYPE,\n description: 'An error occurred',\n name: 'default',\n ref: error ? error.toRef() : undefined,\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_readObject` reads a quad's object
_readObject(token) { switch (token.type) { case 'literal': // Regular literal, can still get a datatype or language if (token.prefix.length === 0) { this._literalValue = token.value; return this._readDataTypeOrLang; } // Pre-datatyped string literal (prefix stores the datatype) else this._object = this._literal(token.value, this._namedNode(token.prefix)); break; case '[': // Start a new quad with a new blank node as subject this._saveContext('blank', this._graph, this._subject, this._predicate, this._subject = this._blank()); return this._readBlankNodeHead; case '(': // Start a new list this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL); this._subject = null; return this._readListItem; case '{': // Start a new formula if (!this._n3Mode) return this._error('Unexpected graph', token); this._saveContext('formula', this._graph, this._subject, this._predicate, this._graph = this._blank()); return this._readSubject; default: // Read the object entity if ((this._object = this._readEntity(token)) === undefined) return; // In N3 mode, the object might be a path if (this._n3Mode) return this._getPathReader(this._getContextEndReader()); } return this._getContextEndReader(); }
[ "function readSOR(){\n var SORObj = readFile();\n //reset all the variables and arrays then load them in like this\n if(SORObj!=null){\n var numV=0;\n meshObject.isMostRecent = false;\n objectList.push(new MeshObject(5000));\n objectList[objectList.length-1].alphaKey = 255-(objectList.length); \n //sets that object as the currently selected object\n meshObject = objectList[objectList.length - 1];//sets the current object\n meshObject.isMostRecent = true; \n newSelected(objectList.length-1);\n for(var i=0;i<5000;i++){\n meshObject.vertices[i]=SORObj.vertices[i];\n numV++;\n }\n var num=0;\n for(var i=0;i<SORObj.indexes[4999];i++){\n meshObject.indices[i]=SORObj.indexes[i];\n num++;\n }\n //gets the index and verts values from the file\n meshObject.numOfIndex=SORObj.indexes[4999];\n meshObject.numOfVertsC=SORObj.vertices[4998];\n meshObject.numOfVerts=3;\n allBuffers();\n }\n}", "_readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else\n this._object = this._literal(token.value, this._namedNode(token.prefix));\n break;\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate,\n this._subject = this._blankNode());\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._blankNode());\n return this._readSubject;\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the object might be a path\n if (this._n3Mode)\n return this._getPathReader(this._getContextEndReader());\n }\n return this._getContextEndReader();\n }", "_readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n }\n // Pre-datatyped string literal (prefix stores the datatype)\n else\n this._object = this._literal(token.value, this._namedNode(token.prefix));\n break;\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate,\n this._subject = this._blank());\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n this._subject = null;\n return this._readListItem;\n case '{':\n // Start a new formula\n if (!this._n3Mode)\n return this._error('Unexpected graph', token);\n this._saveContext('formula', this._graph, this._subject, this._predicate,\n this._graph = this._blank());\n return this._readSubject;\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined)\n return;\n // In N3 mode, the object might be a path\n if (this._n3Mode)\n return this._getPathReader(this._getContextEndReader());\n }\n return this._getContextEndReader();\n }", "function readOBJ(path, position, scale) {\n\tconsole.log(\"Reading OBJ file: \" + path);\n\tvar obj = new Mesh(position, scale);\n\tvar req = new XMLHttpRequest();\n\treq.open('GET', path, false);\n\t\n\treq.send(null);\n loadMesh (obj, req.response);\n obj.generateTriangles();\n\tobj.computeNormals();\n\tconsole.log(\"OBJ file successfully loaded (nbV: \" + obj.V.length + \", nbF: \" + obj.F.length + \")\");\n\t\n\treturn obj;\n}", "function loadObj(name, file)\n{\n let obj_info = ObjectPool[name].ObjectInfo;\n if (obj_info == null) return null;\n\n if (file == null)\n {\n obj_info.positions = [];\n obj_info.indices = [];\n obj_info.textureCoordinates = [];\n obj_info.textureIndices = [];\n obj_info.vertexNormals = [];\n obj_info.normalIndices = [];\n return null;\n }\n\n let strs = (file.name).split(\".\");\n if (strs[1] !== \"obj\") return null;\n\n let reader = new FileReader();\n\n reader.onload = function () {\n let res = objStrAna(this.result);\n let lines = res.split('=');\n let objInfo = {\n verPosition : [],\n texPosition : [],\n norPosition : [],\n indicesForVer : [],\n indicesForTex : [],\n indicesForNor : []\n };\n for (let id in lines){\n let line = lines[id];\n let items = line.split(' ');\n switch (items[0]){\n case 'v' :\n objInfo.verPosition.push(parseFloat(items[1]));\n objInfo.verPosition.push(parseFloat(items[2]));\n objInfo.verPosition.push(parseFloat(items[3]));\n break;\n\n case 'vt' :\n objInfo.texPosition.push(parseFloat(items[1]));\n objInfo.texPosition.push(parseFloat(items[2]));\n //objInfo.texPosition.push(parseFloat(items[3]));\n break;\n\n case 'vn' :\n objInfo.norPosition.push(parseFloat(items[1]));\n objInfo.norPosition.push(parseFloat(items[2]));\n objInfo.norPosition.push(parseFloat(items[3]));\n break;\n\n case 'f' :\n for (let i=1; i<=3; i++) {\n let iitems = items[i].split('\\/');\n objInfo.indicesForVer.push(parseInt(iitems[0]) - 1);\n if (iitems[1].length > 0)\n objInfo.indicesForTex.push(parseInt(iitems[1]) - 1);\n if (iitems[2].length > 0)\n objInfo.indicesForNor.push(parseInt(iitems[2]) - 1);\n }\n\n break;\n\n default :\n let list = [];\n for (let i=1; i<items.length; i++){\n list.push(items[i]);\n }\n if (items[0] === '') break;\n objInfo[items[0]] = list;\n break;\n\n }\n\n }\n\n let maxVer = [-1000000.0, -1000000.0, -1000000.0];\n let minVer = [1000000.0, 1000000.0, 1000000.0];\n for (let id in objInfo.verPosition){\n let item = objInfo.verPosition[id];\n if (maxVer[id%3] < item) maxVer[id%3] = item;\n if (minVer[id%3] > item) minVer[id%3] = item;\n }\n let delta = 0;\n for (let i=0; i<3; i++){\n if (maxVer[i] - minVer[i] > delta){\n delta = maxVer[i] - minVer[i];\n }\n }\n\n for (let id in objInfo.verPosition){\n let item = objInfo.verPosition[id];\n objInfo.verPosition[id] = item / delta;\n }\n\n obj_info.positions = objInfo.verPosition;\n obj_info.indices = objInfo.indicesForVer;\n obj_info.textureCoordinates = objInfo.texPosition;\n obj_info.textureIndices = objInfo.indicesForTex;\n obj_info.vertexNormals = objInfo.norPosition;\n obj_info.normalIndices = objInfo.indicesForNor;\n\n refreshItemInObjectPool(name);\n };\n\n reader.readAsText(file);\n\n return file;\n}", "readObject() {\n //return this.readAmfObject();\n return null;\n }", "read() {\n // Read next tag.\n let [op, arg] = this.readTag();\n let object;\n switch (op) {\n case 0:\n // REF.\n object = this.refs[arg];\n if (object == undefined) throw \"Invalid reference\";\n break;\n\n case 1:\n // FRAME.\n object = this.readFrame(arg, -1);\n break;\n\n case 2:\n // STRING.\n object = this.readString(arg);\n this.refs.push(object);\n break;\n\n case 3:\n // SYMBOL.\n object = this.readSymbol(arg);\n this.refs.push(object);\n break;\n\n case 4:\n // LINK.\n object = this.readLink(arg);\n this.refs.push(object);\n break;\n\n case 5:\n // INTEGER.\n object = arg;\n break;\n\n case 6:\n // FLOAT.\n object = bitsToFloat(arg << 2);\n break;\n\n case 7:\n // SPECIAL.\n switch (arg) {\n case 1: object = null; break;\n case 2: object = this.store.id; break;\n case 3: object = this.store.isa; break;\n case 4: object = this.store.is; break;\n\n case 5:\n // ARRAY.\n object = this.readArray();\n break;\n\n case 6:\n // INDEX.\n object = bitsToFloat((this.readVarint32() << 2) | 0xffc00003)\n break;\n\n case 7:\n // RESOLVE.\n let slots = this.readVarint32();\n let replace = this.readVarint32();\n object = this.readFrame(slots, replace);\n break;\n\n case 8:\n // QSTRING.\n object = this.readQString(arg);\n break;\n }\n break;\n }\n\n return object;\n }", "function readOBJ(path) {\n\tconsole.log(\"Reading OBJ file: \" + path);\n\tvar obj = new Mesh();\n\tvar req = new XMLHttpRequest();\n\treq.open('GET', path, false);\n\t\n\treq.send(null);\n\tobj.load(req.response);\n\tobj.computeNormals();\n\tconsole.log(\"OBJ file successfully loaded (nbV: \" + obj.nbV() + \", nbF: \" + obj.nbF() + \")\");\n\t\n\treturn obj;\n}", "function ObjectInputStream() {\r\n\r\n\t}", "static deserialize(obj) {\n assert && assert(obj.type === 'Quadratic');\n return new Quadratic(new Vector2(obj.startX, obj.startY), new Vector2(obj.controlX, obj.controlY), new Vector2(obj.endX, obj.endY));\n }", "readDbObject() {\n const obj = {};\n let numBytes = this.readUB4();\n if (numBytes > 0)\n obj.toid = Buffer.from(this.readBytesWithLength());\n numBytes = this.readUB4();\n if (numBytes > 0)\n obj.oid = Buffer.from(this.readBytesWithLength());\n numBytes = this.readUB4();\n if (numBytes > 0)\n obj.snapshot = Buffer.from(this.readBytesWithLength());\n this.skipUB2(); // version\n numBytes = this.readUB4();\n this.skipUB2(); // flags\n if (numBytes > 0)\n obj.packedData = Buffer.from(this.readBytesWithLength());\n return obj;\n }", "function loadWavefrontObj(path) {\n\tvar obj = {\n\t\tv: [], vt: [], vn: [], f: []\n\t};\n\n\tvar lo_x = 1e+10, hi_x = -1e+10;\n\tvar lo_y = 1e+10, hi_y = -1e+10;\n\tvar lo_z = 1e+10, hi_z = -1e+10;\n\n\tvar lines = fs.readFileSync(path).toString().split(\"\\n\");\n\tfor (var i = 0; i < lines.length; i++) {\n\t\tvar line = lines[i];\n\t\tif (line.startsWith(\"vt\")) {\n\t\t\t// Vertex texture coordinate.\n\t\t\tvar args = line.split(\" \");\n\t\t\tobj.vt.push([parseFloat(args[1]), parseFloat(args[2]), parseFloat(args[3])]);\n\t\t} else if (line.startsWith(\"vn\")) {\n\t\t\t// Vertex normal.\n\t\t\tvar args = line.split(\" \");\n\t\t\tobj.vn.push([parseFloat(args[1]), parseFloat(args[2]), parseFloat(args[3])]);\n\t\t} else if (line.startsWith(\"v\")) {\n\t\t\t// Vertex.\n\t\t\tvar args = line.split(\" \");\n\t\t\tvar vx = parseFloat(args[1]);\n\t\t\tvar vy = parseFloat(args[2]);\n\t\t\tvar vz = parseFloat(args[3]);\n\t\t\tobj.v.push([vx, vy, vz]);\n\t\t\tif (vx < lo_x) {lo_x = vx;}\n\t\t\tif (vy < lo_y) {lo_y = vy;}\n\t\t\tif (vz < lo_z) {lo_z = vz;}\n\t\t\tif (vx > hi_x) {hi_x = vx;}\n\t\t\tif (vy > hi_y) {hi_y = vy;}\n\t\t\tif (vz > hi_z) {hi_z = vz;}\n\t\t} else if (line.startsWith(\"f\")) {\n\t\t\t// Face.\n\t\t\tvar args = line.split(\" \");\n\t\t\targs.shift();\n\t\t\tvar vertices = [];\n\t\t\tfor (var j = 0; j < args.length; j++) {\n\t\t\t\tvar vtx = args[j].split(\"/\");\n\t\t\t\tvertices.push([parseInt(vtx[0]), parseInt(vtx[1]), parseInt(vtx[2])]);\n\t\t\t}\n\t\t\tobj.f.push(vertices);\n\t\t}\n\t}\n\n\tvar len_x = hi_x - lo_x / 2.0;\n\tvar len_y = hi_y - lo_y;\n\tvar len_z = hi_z - lo_z / 2.0;\n\tfor (var i = 0; i < obj.v.length; i++) {\n\t\tobj.v[i][1] -= lo_y;\n\t\tobj.v[i][0] /= len_x;\n\t\tobj.v[i][1] /= len_y;\n\t\tobj.v[i][2] /= len_z;\n\t}\n\n\treturn obj;\n}", "get serializedObject() {}", "function import3dObjSync(config) {\n var scale = config.scale || 1;\n var xRot = config.xRot || null;\n var yRot = config.yRot || null;\n var zRot = config.zRot || null;\n\n var vertex = [],\n faces = [],\n uvs = [];\n var re = /\\s+/;\n\n var minx, miny, minz, maxx, maxy, maxz;\n minx = miny = minz = maxx = maxy = maxz = 0;\n\n var data = getOBJFileSync(config);\n if (data == false) {\n return;\n }\n var lines = data.split(\"\\n\");\n\n for (let i = 0, imax=lines.length; i < imax; i++) {\n let line = lines[i].split(re);\n switch (line[0]) {\n case \"v\":\n var x = parseFloat(line[1]) * scale,\n y = parseFloat(line[2]) * scale,\n z = parseFloat(line[3]) * scale;\n vertex.push({\n x: x,\n y: y,\n z: z\n });\n if (x < minx) {\n minx = x\n } else {\n if (x > maxx) {\n maxx = x\n }\n }\n if (y < miny) {\n miny = y\n } else {\n if (y > maxy) {\n maxy = y\n }\n }\n if (z < minz) {\n minz = z\n } else {\n if (z > maxz) {\n maxz = z\n }\n }\n break;\n case \"vt\":\n var u = parseFloat(line[1]),\n v = parseFloat(line[2]);\n uvs.push([u, v]);\n break;\n case \"f\":\n line.splice(0, 1);\n var vertices = [],\n uvcoords = [];\n for (var j = 0, vindex, vps; j < line.length; j++) {\n vindex = line[config.reorder ? line.length - j - 1 : j];\n if (vindex.length !== 0) {\n vps = vindex.split(\"/\");\n vertices.push(parseInt(vps[0]) - 1);\n if (vps.length > 1 && vindex.indexOf(\"//\") === -1) {\n var uv = parseInt(vps[1]) - 1;\n if (uvs.length > uv) {\n uvcoords.push(uvs[uv][0], uvs[uv][1])\n }\n }\n }\n }\n faces.push(vertices);\n if (uvcoords.length !== 0) {\n poly.uvs = uvcoords\n }\n break\n }\n }\n if (config.center) {\n var cdispx = (minx + maxx) / 2,\n cdispy = (miny + maxy) / 2,\n cdispz = (minz + maxz) / 2;\n for (var i = 0; i < vertex.length; i++) {\n vertex[i].x -= cdispx;\n vertex[i].y -= cdispy;\n vertex[i].z -= cdispz\n }\n }\n if (config.scaleTo) {\n var sizex = maxx - minx,\n sizey = maxy - miny,\n sizez = maxz - minz;\n var scalefactor = 0;\n if (sizey > sizex) {\n if (sizez > sizey) {\n scalefactor = 1 / (sizez / config.scaleTo)\n } else {\n scalefactor = 1 / (sizey / config.scaleTo)\n }\n } else {\n if (sizez > sizex) {\n scalefactor = 1 / (sizez / config.scaleTo)\n } else {\n scalefactor = 1 / (sizex / config.scaleTo)\n }\n }\n for (let i = 0, imax=vertex.length; i < imax; i++) {\n vertex[i].x *= scalefactor;\n vertex[i].y *= scalefactor;\n vertex[i].z *= scalefactor\n }\n }\n rotateZ3D(zRot, vertex, true);\n rotateY3D(yRot, vertex, true);\n rotateX3D(xRot, vertex, true);\n\n return {\n points: vertex,\n polygons: faces\n }\n }", "function onReadComplete(gl, objDoc) {\n // Acquire the vertex coordinates and colors from OBJ file\n var drawingInfo = objDoc.getDrawingInfo();\n\n // Write date into the buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, model.vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.vertices, gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, model.normalBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.normals, gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, model.colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.colors, gl.STATIC_DRAW);\n\n // Write the indices to the buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, drawingInfo.indices, gl.STATIC_DRAW);\n\n return drawingInfo;\n}", "function readBulletObject(body, object) {\n body.getMotionState().getWorldTransform(transform);\n var origin = transform.getOrigin();\n object[0] = origin.x();\n object[1] = origin.y();\n object[2] = origin.z();\n var rotation = transform.getRotation();\n object[3] = rotation.x();\n object[4] = rotation.y();\n object[5] = rotation.z();\n object[6] = rotation.w();\n }", "function load_obj(gl, obj_src) {\n if (typeof obj_src !== \"string\") {\n throw \"obj source must be a string\";\n } // // Create a WebGL buffer.\n\n\n var mesh = new obj_loader.Mesh(obj_src); // Match the interface we're using for Mesh objects that come from\n // StackGL.\n\n var cell = group_array(mesh.indices, 3);\n var position = group_array(mesh.vertices, 3); // let normal = normals.vertexNormals(cell, position);\n\n var normal = group_array(mesh.vertexNormals, 3);\n var out = {\n positions: make_buffer(gl, position, 'float32', gl.ARRAY_BUFFER),\n cells: make_buffer(gl, cell, 'uint16', gl.ELEMENT_ARRAY_BUFFER),\n normals: make_buffer(gl, normal, 'float32', gl.ARRAY_BUFFER),\n cell_count: cell.length * cell[0].length,\n // This name I invented -- it's not in the StackGL models.\n texcoords: gl_buffer(gl, gl.ARRAY_BUFFER, new Float32Array(mesh.textures))\n }; // .obj files can have normals, but if they don't, this parser library\n // (confusingly) fills the array with NaN.\n // if (!isNaN(mesh.vertexNormals[0])) {\n // out.normals = group_array(mesh.vertexNormals, 3) as Vec3Array;\n // }\n\n return out;\n}", "static deserialize(obj) {\n assert && assert(obj.type === 'Cubic');\n return new Cubic(new Vector2(obj.startX, obj.startY), new Vector2(obj.control1X, obj.control1Y), new Vector2(obj.control2X, obj.control2Y), new Vector2(obj.endX, obj.endY));\n }", "loadObjFile(file) {\n return fetch(file)\n .then(response => response.text())\n .then(contents => {\n const objLoader = new THREE.OBJLoader();\n const object3D = objLoader.parse(contents);\n this.scene.add(object3D);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a boolean, whether the text includes any content written by the person tweeting.
get written() { const autoPattern1 = new RegExp("with @Runkeeper."); return !autoPattern1.test(this.text); }
[ "function textConsented(){\n if(ecnt==null||ecnt.length==0)\n return false;\n if(ecnt.indexOf(\"text\")>-1||ecnt.indexOf(\"both\")>-1)\n return true;\n else\n return false;\n}", "static userMentioned(text) {\n\n if(text.includes(\"<@\")) return true;\n return false;\n \n }", "get written() {\n if (this.source == \"miscellaneous\" || this.text.search(\" - \") >= 0) {\n return true;\n }\n return false;\n }", "function isText(ele) {\n\t\t\t\tele = ele.toLowerCase();\n\n\t\t\t\tif(ele === \"p\" || ele === \"a\" || ele === \"li\" || ele === \"h1\" || ele === \"h2\" || ele === \"h3\" || ele === \"h4\" || ele === \"h5\" || ele === \"h6\") {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t} \n\t\t\t}", "get isMentioned() {\n const mention = new RegExp(`((@)*${this.client.chat.me.username})`);\n return mention.test(this.contentRaw) ? true : false;\n }", "hasTextElements() {\n return this.m_textElementGroups.count() > 0 || this.m_userTextElements.length > 0;\n }", "get containsText(){\n return this.textContent.trim().length > 0;\n }", "function hasContent(content){\n\t\tif(content != \"none\"){\n\t\t\t//Look for printable characters\n\t\t\tfor(var i=0; i<content.length; i++){\n\t\t\t\tif(content.charCodeAt(i) > 32 && content.charCodeAt(i) < 127){\n\t\t\t\t\tif(content.charCodeAt(i) != 34) //Exclude double quote\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "function CLC_HasText(target){\r\n //Do not try to read metadata in the head\r\n if (target.localName && (target.localName.toLowerCase() == \"head\") ) {\r\n return false;\r\n }\r\n //Script elements are for the computer, not the human - they never have text\r\n if (target.localName && (target.localName.toLowerCase() == \"script\") ) {\r\n return false;\r\n }\r\n //Ignore visibility=hidden/display=none nodes\r\n if (target.nodeType == 1){\r\n var style = CLC_Window().getComputedStyle(target, '');\r\n if ((style.display == 'none') || (style.visibility == 'hidden')){\r\n return false;\r\n }\r\n }\r\n if (target.parentNode && target.parentNode.nodeType == 1){\r\n var style = CLC_Window().getComputedStyle(target.parentNode, '');\r\n if ((style.display == 'none') || (style.visibility == 'hidden')){\r\n return false;\r\n }\r\n }\r\n //Input roles are always considered to have text content\r\n if (CLC_RoleIsInput(target)) {\r\n return true;\r\n } \r\n //Inputs are always considered to have text content unless they are hidden\r\n if (target.localName && (target.localName.toLowerCase() == \"input\") ) {\r\n if (target.type.toLowerCase() == \"hidden\"){\r\n return false;\r\n }\r\n return true;\r\n } \r\n //Select boxes are always considered to have text content unless they are hidden\r\n if (target.localName && (target.localName.toLowerCase() == \"select\") ) {\r\n if (target.type.toLowerCase() == \"hidden\"){\r\n return false;\r\n }\r\n return true;\r\n } \r\n //Text areas are always considered to have text\r\n if (target.localName && (target.localName.toLowerCase() == \"textarea\") ) {\r\n return true;\r\n }\r\n if (target.parentNode && target.parentNode.localName && (target.parentNode.localName.toLowerCase() == \"textarea\") ) {\r\n return true;\r\n }\r\n //Iframes should have text, but textContent can't be used to check them.\r\n //Even if there is no text, users should be alerted to their presence.\r\n if (target.localName && (target.localName.toLowerCase() == \"iframe\") ) {\r\n return true;\r\n }\r\n //Handling images\r\n if (target.localName && (target.localName.toLowerCase() == \"img\") && target.hasAttribute(\"alt\")){\r\n return CLC_IsSpeakableString(target.alt);\r\n }\r\n if (CLC_GetRoleStringOf(target) == \"img\"){\r\n return CLC_IsSpeakableString(CLC_GetTextContentFromRole(target));\r\n }\r\n //Make an exception for images which do not have the alt attribute\r\n if (target.localName && (target.localName.toLowerCase() == \"img\") && !target.hasAttribute(\"alt\")){\r\n return true;\r\n }\r\n if (!target.textContent){\r\n return false;\r\n }\r\n return CLC_IsSpeakableString(target.textContent);\r\n }", "function isReTweet(text){\n return text.substring(0,4) === \"RT @\" || text.substring(0,1) === \"♺\";\n \n}", "function isGoodTweet(user, text, mentions) {\n\tvar beruf = userBeruf(user);\n\tif (beruf != 9 && beruf != 0) return true;\n\n\t// cut away potential cuts\n\tfor (var a = 0; a < mentions.length; a++) {\n\t\tberuf = userBeruf(mentions[a].user);\n\t\tif (beruf != 9 && beruf != 0) return true;\n\t}\n\t//util.log('excluded '+user+'::' + text);\n\treturn false;\n}", "function DocTest(text)\n{\n return (document.body.innerHTML.indexOf(text) > -1);\n}", "function _isRetweet(tweetText) {\n //All retweets begin with 'RT @'\n return tweetText.indexOf(\"RT @\") > -1;\n}", "function hasContent(source) {\n if (source.text !== undefined && source.text.trim().length > 0) {\n return true;\n }\n if (source.summary !== undefined && source.summary.trim().length > 0) {\n return true;\n }\n if (source.attachments !== undefined && source.attachments.length > 0) {\n return true;\n }\n if (source.channelData !== undefined) {\n return true;\n }\n return false;\n }", "function isRelevant(tweet) {\n const words = tweet.text.toLowerCase().split(' ');\n if (words.length < 5) return false;\n for (let i = 0; i < words.length; i++) {\n let word = trimHashtagsAndPunctuation(words[i]);\n if (keywords.has(word)) {\n console.log(words[i]);\n return true;\n }\n }\n return false;\n}", "static async emoticonUsed(text, emoticon) {\n\n if(!emoticon) return false;\n\n if(text.includes(emoticon)) return true;\n return false;\n\n }", "function isSpeakerNotes() {\n\n\t\treturn !!window.location.search.match( /receiver/gi );\n\n\t}", "function checkSpam(text) {\n let isSpam = false;\n\n // text is spam if includes spam or hack\n const includeSpam = text.includes('spam');\n const includeHack = text.includes('hack');\n if (includeSpam || includeHack) {\n isSpam = true;\n }\n\n return isSpam;\n}", "function hasText(str) {\n var substr = removeExtraWhitespace(str);\n return !!substr.length;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the male population percounty given the population data
function accumulateFemalePopulationPerCounty(population_arr,counties_arr) { const female_population_pre_county = []; for (let i = 0; i < counties_arr.length; i++) { let female = 0; for (let j = i; j < population_arr.length; j++) { if (counties_arr[i] === population_arr[j].county) { female += population_arr[j].female; } } female_population_pre_county.push(female); } return female_population_pre_county; }
[ "function accumulateMalePopulationPerCounty(population_arr,counties_arr)\n{\n const male_population_pre_county = [];\n for (let i = 0; i < counties_arr.length; i++)\n {\n let male = 0;\n for (let j = i; j < population_arr.length; j++)\n {\n if (counties_arr[i] === population_arr[j].county)\n {\n male += population_arr[j].male; \n }\n }\n male_population_pre_county.push(male);\n }\n return male_population_pre_county;\n}", "function accumulatePopulationPerCounty(male_per_county,female_per_county)\n{\n let population_pre_county = [];\n for (let i = 0; i < male_per_county.length; i++)\n {\n population_pre_county.push(male_per_county[i] + female_per_county[i])\n }\n return population_pre_county;\n}", "function accumulateFemalePopulation(population_arr)\n{\n const female = population_arr.reduce((acc, curr) => acc + curr.female, 0);\n return female;\n}", "function calculateGenderProportion(){\n\t\n\tfor(var disease in diseaseObj){\n\t\t\n\t\tdiseaseObj[disease].maleCount = Math.round(((diseaseObj[disease].maleCount/diseaseObj[disease].value)*100).toFixed(2));\n\t\tdiseaseObj[disease].femaleCount = Math.round(((diseaseObj[disease].femaleCount/diseaseObj[disease].value)*100).toFixed(2));\n\t\tdiseaseObj[disease].northEast = ((diseaseObj[disease].northEast/allNorthEast)*100).toFixed(2);\n\t\tdiseaseObj[disease].midWest = ((diseaseObj[disease].midWest/allMidWest)*100).toFixed(2);\n\t\tdiseaseObj[disease].south = ((diseaseObj[disease].south/allSouth)*100).toFixed(2);\n\t\tdiseaseObj[disease].west = ((diseaseObj[disease].west/allWest)*100).toFixed(2);\n\t}\n}", "function getFemalePopulationPerDistrct(district_data)\n{\n let female_population_pre_district = [];\n for (let i = 0; i < district_data.length; i++)\n {\n female_population_pre_district.push(district_data[i].female);\n }\n return female_population_pre_district;\n}", "function calculatePopulation() {\n const population = data.reduce((acc, user) => (acc += user.population), 0);\n\n const populationEl = document.createElement('div');\n\n populationEl.innerHTML = `<h3>Total Population: <strong>${population}</strong></h3>`;\n main.appendChild(populationEl);\n}", "function getMalePopulationPerDistrct(district_data)\n{\n let male_population_pre_district = [];\n for (let i = 0; i < district_data.length; i++)\n {\n male_population_pre_district.push(district_data[i].male)\n }\n return male_population_pre_district;\n}", "function calculatePopulation() {\n // neutral population factors < 1 as neutral lands are usually pretty wild\n const urbanFactor = 0.9;\n\n // calculate population for each burg (based on trade/people attractors)\n manors.map(function(m) {\n const cell = cells[m.cell];\n let score = cell.score;\n if (score <= 0) {score = rn(Math.random(), 2)}\n if (cell.crossroad) {score += cell.crossroad;} // crossroads\n if (cell.confluence) {score += Math.pow(cell.confluence, 0.3);} // confluences\n if (m.i !== m.region && cell.port) {score *= 1.5;} // ports (not capital)\n if (m.i === m.region && !cell.port) {score *= 2;} // land-capitals\n if (m.i === m.region && cell.port) {score *= 3;} // port-capitals\n if (m.region === \"neutral\") score *= urbanFactor;\n const rnd = 0.6 + Math.random() * 0.8; // random factor\n m.population = rn(score * rnd, 1);\n });\n\n calculateRuralPopulation();\n\n // calculate population for each state\n states.map(function(s, i) {\n // define region burgs count\n const burgs = $.grep(manors, function (e) {\n return e.region === i;\n });\n s.burgs = burgs.length;\n // define region total and burgs population\n let burgsPop = 0; // get summ of all burgs population\n burgs.map(function(b) {burgsPop += b.population;});\n s.urbanPopulation = rn(burgsPop, 2);\n const regionCells = $.grep(cells, function (e) {\n return e.region === i;\n });\n let cellsPop = 0;\n regionCells.map(function(c) {cellsPop += c.pop});\n s.cells = regionCells.length;\n s.ruralPopulation = rn(cellsPop, 1);\n });\n\n // collect data for neutrals\n const neutralCells = $.grep(cells, function(e) {return e.region === \"neutral\";});\n if (neutralCells.length) {\n let burgs = 0, urbanPopulation = 0, ruralPopulation = 0, area = 0;\n manors.forEach(function(m) {\n if (m.region !== \"neutral\") return;\n urbanPopulation += m.population;\n burgs++;\n });\n neutralCells.forEach(function(c) {\n ruralPopulation += c.pop;\n area += cells[c.index].area;\n });\n states.push({i: states.length, color: \"neutral\", name: \"Neutrals\", capital: \"neutral\",\n cells: neutralCells.length, burgs, urbanPopulation: rn(urbanPopulation, 2),\n ruralPopulation: rn(ruralPopulation, 2), area: rn(area)});\n }\n }", "function percentageOfWorld1 (population) {\n return (population / 7900) * 100;\n}", "function initializePopulation() {\n totalPopulation = 0;\n targetPopulation = 0;\n\n for (var i = 0; i < features.length; i++) {\n var feature = features[i];\n totalPopulation += feature.properties[populationField]\n \n }\n targetPopulation = totalPopulation / nDistricts;\n}", "function percentageOfWorld1(population) {\n return population / 7900 * 100;\n}", "function getPopulation(province, data){\n for (var i = 0; i < data.length; i++){\n if (data[i].province == province){\n return data[i].population.total;\n }\n }\n}", "function totalPopulation(){\n return data.reduce((acc, country)=>{\n return acc + country.population;\n }, 0)\n}", "function percentageOfWorld1(population) {\n return (population / 7900) * 100;\n}", "function getUsaAvgMedIncome() {\n // Resets usaIncome to empty in order to get rid of previous date's data.\n usaIncome = [];\n var allFeatures = geoJson.features; // Array of all county features\n var length = allFeatures.length\n var income = 0;\n for(var index = 0; index < length ; index++)\n {\n // The properties of the current county (at index)\n var thisProperty = allFeatures[index].properties; \n var countyIncome = thisProperty.Med_Income;\n income += countyIncome;\n usaIncome[index] = countyIncome;\n }\n income = (income/index);\n return income;\n}", "function populationDensity(population, area) {\n return population / area;\n}", "function describePopulation(countrys,population) {\n percentageofWorld1.call(this,countrys,population)\n this.percentage = population/7900*100;\n return `${countrys} has ${population} million people which is about ${this.percentage} of the world`\n}", "function calculateCountyUnempStats(data) {\n unemp = {};\n\n countyMaxUnempRate = getCountyMaxUnempRate(data)\n countyMaxUnempNum = getCountyMaxUnempNum(data)\n\n unemp[\"County With Highest Unemployment Rate\"] = `${countyMaxUnempRate[0]}, ${countyMaxUnempRate[1]}%`;\n unemp[\"County With Highest Number of Unemployed Persons\"] = `${countyMaxUnempNum[0]}, ${countyMaxUnempNum[1]}`;\n\n return unemp;\n}", "function avarageUsPopulationBetweenYear1990To2000() {\n\t// let peopleCount = 0;\n\t// let yearsCount = 0;\n\t// for(const countryYearPopulation of data){\n\t// \tif(countryYearPopulation.countryiso3code === \"USA\"){\n\t\t\t\n\t// \t\tlet numCountryYearpopulation = Number(countryYearPopulation.date);\n\t// \t\tif(numCountryYearpopulation <= 2000 && numCountryYearpopulation >= 1990){\n\t// \t\t\tpeopleCount += countryYearPopulation.value;\n\t// \t\t\tyearsCount++;\n\t// \t\t}\n\t// \t}\n\t// }\n\t// return Math.round(peopleCount / yearsCount);\n\t\n\tconst usaCountryInfo1990_2000 = data.filter(countryInfo => {\n\t\tconst countryYear = parseInt(countryInfo.date);\n\n\t\treturn countryInfo.countryiso3code === \"USA\" \n\t\t&& countryYear >= 1990 \n\t\t&& countryYear <= 2000\n\t})\n\n\tconst usaCountryInfo1990_2000_sum = usaCountryInfo1990_2000.reduce((yearsHumans, thatYearHumans) => {\n\t\treturn yearsHumans + thatYearHumans.value;\n\t},0)\n\treturn Math.round(usaCountryInfo1990_2000_sum / usaCountryInfo1990_2000.length);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle upload logo functionnality
function handleUploadLogo($, meta_image_frame) { $('#lc_swp_upload_logo_button').click(function(e) { e.preventDefault(); openAndHandleMedia($, meta_image_frame, '#lc_swp_logo_upload_value', '#lc_logo_image_preview img', "Choose Custom Logo Image", "Use this image as logo"); }); $('#lc_swp_remove_logo_button').click(function(){ $('#lc_logo_image_preview img').attr('src', ''); $('#lc_swp_logo_upload_value').val(''); }) }
[ "function _uploadLogo() {\n $scope.deleteLogoFlag = true;\n $scope.submitDisable = true;\n serverRequestService.upload($scope.logoImageVar, ADD_EDIT_PROJECT_CTRL_API_OBJECT.uploadDocs, 'doc').then(function(res) {\n if (res) {\n $scope.project.logoImageId = res._id;\n }\n $scope.logoImage = res;\n $scope.submitDisable = false;\n });\n }", "uploadLogo(file) {\n if (file.get('size') / (1024 * 1024) > 1) {\n options.uploader.removeFile(file.get('file'))\n return get(this, 'toast').error('File size too large. Try uploading a logo less than 1 MB.');\n }\n\n set(this, 'uploadedLogo', file);\n }", "onLogoUploadSuccess (file, response) {\n this.report.logo = response.data.path\n }", "function atualizarUpload(ok, img) {\n if (ok) {\n $(\"#imglogo\").attr(\"src\", img);\n $(\".lbl-addlogo span\").html(\"Alterar logo\");\n $(\"#imglogo\").removeClass(\"invisivel\");\n $(\".rm-img\").removeClass(\"invisivel\");\n\n } else {\n $(\"#imglogo\").attr(\"src\", \"\");\n $(\".lbl-addlogo span\").html(\"Adicionar logo\");\n $(\"#imglogo\").addClass(\"invisivel\");\n $(\".rm-img\").addClass(\"invisivel\");\n $(\"#logo\").val(\"\");\n }\n}", "async function handleLogoChange(e) {\n const file = e.target.files[0];\n // If new logo file added fetch s3 url and upload\n if (!!file) {\n // Get signed url from s3, valid for 60s\n const res = await fetch(`/api/business/gets3url?ext=.${file.type.split(\"/\")[1]}`);\n const { url, fields } = await res.json();\n const formData = new FormData();\n console.log(fields)\n Object.entries({ ...fields, file }).forEach(([key, value]) => {\n formData.append(key, value);\n });\n\n // Upload put request to s3\n const upload = await fetch(url, {\n method: \"POST\",\n body: formData,\n });\n\n if (upload.ok) {\n console.log(\"Uploaded successfully!\");\n } else {\n console.error(\"Upload failed.\");\n }\n \n\n // Format AWS url\n const imageUrl = `https://vie-invoice-app.s3.eu-west-2.amazonaws.com/${fields.key}`;\n\n // Update logo url state to prevent need to refresh page\n setlogo(imageUrl);\n console.log(imageUrl)\n // Values for database update query\n const values = {\n logo: imageUrl,\n };\n\n // // Append all values for database query\n const dbFormData = new FormData();\n for (const key in values) {\n dbFormData.append(key, values[key]);\n }\n // Axios PUT request to Mongodb on business details route\n axios({\n method: \"PUT\",\n url: `/api/business/${id}/logo`,\n data: dbFormData,\n }).then((res) => console.log(\"logo api response\", res)).catch((err) => {\n console.log(err);\n });\n }\n}", "upload_logo_to_inst(req, res, next){\n const file = req.file;\n\n const ServerInstance = model.get(\"ServerInstance\");\n\n ServerInstance.findOne({\n where: {\n inst_id: req._inst_id\n }\n }).then(\n (data) => {\n const logo_file = utils.resolve(data.inst_dir, \"server-icon.png\");\n fs.moveSync(file.path, logo_file, {overwrite: true});\n res.success(true);\n },\n (err) => {\n res.error(500);\n }\n );\n }", "function storeLogo()\n{\n\t// function from the jquery form plugin\n\t $('#myFormImage').ajaxForm({\n\t\tbeforeSend:function(){\n\t\t\t $(\".progress\").show();\n\t\t},\n\t\tuploadProgress:function(event,position,total,percentComplete){\n\t\t\t$(\".progress-bar\").width(percentComplete+'%'); //dynamicaly change the progress bar width\n\t\t\t$(\".sr-only\").html(percentComplete+'%'); // show the percentage number\n\t\t},\n\t\tsuccess:function(){\n\t\t\t$(\".progress\").hide(); //hide progress bar on success of upload\n\t\t},\n\t\tcomplete:function(response){\n\t\t\tif(response.responseText=='0')\n\t\t\t{\n\t\t\t\t$(\".image\").html(\"Error\"); //display error if response is 0\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$(\"#1_GismoBucket\").css('background-color','#a3d3d1');\n\t\t\t\t$(\"#2_GismoBucket\").css('background-color','#a3d3d1');\n\t\t\t\t$(\"#2_GismoBucket\").html('New Store Logo Has Been Updated');\n\t\t\t\t//Other Actions\n\t\t\t\t$('.success_alert').fadeIn(300);\n\t\t\t\t$(\".success_alert\").delay(1500).fadeOut(300);\n\t\t\t\tcloseFormDelete();\n\t\t\t}\n\t\t}\n\t });\n\t //set the progress bar to be hidden on loading\n\t $(\".progress\").hide();\n}", "function _deleteLogo() {\n if ($scope.logoImage.docName) {\n $scope.deleteLogoFlag = false;\n serverRequestService.deleteDocument($scope.logoImage.docName, $scope.logoImage._id).then(function() {\n $scope.logoImage = null;\n $scope.project.logoImageId = null;\n $scope.deleteLogoFlag = true;\n });\n }\n }", "function galleryLogo() {\n\t\t$('body').on('click', '#remove_gallery_logo', function(e) {\n\t\t\te.preventDefault();\n\t\t\t$('.gallery-logo-preview').hide();\n\t\t\t$('#gallery_logo').val('');\n\t\t\t$('#remove_gallery_logo').hide();\n\t\t});\n\t\t\n\t\t// Runs when the image button is clicked.\n\t $('#upload_logo_trigger').click(function(e){\n\t // Prevents the default action from occuring.\n\t e.preventDefault();\n\t \n\t\t var button = $(this);\n\t\t var fieldLabel = 'Add logo';\n\t\n\t // Sets up the media library frame\n\t meta_image_frame = wp.media.frames.meta_image_frame = wp.media({\n\t title: fieldLabel,\n\t button: { text: 'Update logo' },\n\t library: { type: 'image' }\n\t });\n\t\n\t // Runs when an image is selected.\n\t meta_image_frame.on('select', function(){\n\t\n\t // Grabs the attachment selection and creates a JSON representation of the model.\n\t var media_attachment = meta_image_frame.state().get('selection').first().toJSON();\n\t \n\t // Update the hidden field with the media id\n\t $('#gallery_logo').val(media_attachment.id);\n\t \n\t // Update our preview image\n\t $('.gallery-logo-preview').attr('src', media_attachment.sizes.thumbnail.uhisrl);\n\t $('.gallery-logo-preview').fadeIn('fast');\n\t $('#remove_gallery_logo').fadeIn('fast');\n\t \n\t });\n\t\n\t // Opens the media library frame.\n\t meta_image_frame.open();\n\t });\n\t}", "function previewLogoFromFile(file) {\n\t\tvar checkValide = validate(file);\n\t\tif (checkValide == false) {\n\t\t\t//clear the text in the input file field\n\t\t\t$(\"input#file\").replaceWith($(\"input#file\").val(\"\").clone(true));\n\t\t\t$(\"#saveinfo\").hide();\n\t\t\t$(\"#cancelinfo\").hide();\n\t\t\t$(\"#mustpng\").show();\n\t\t\treturn;\n\t\t} else {\n\t\t\tfileUpload = file;\n\t\t\tvar reader = new FileReader();\n\t\t\treader.onload = function(e) {\n\t\t\t\tpreviewLogoFromUrl(e.target.result);\n\t\t\t};\n\t\t\treader.readAsDataURL(file);\n\t\t}\n\t}", "validateLogo(e) {\n let self = this;\n let userlogo = e.target.files;\n let logoValidationState = '';\n this.logoValidationMessage = '';\n if(userlogo != '' && userlogo != undefined) {\n this.logoValidationState = 'success';\n // Only process image files.\n if(userlogo[0] != undefined) {\n if (!userlogo[0].type.match('image.*')) {\n this.logoValidationState = 'error';\n this.logoValidationMessage = \"Select image for logo\";\n return;\n }\n } else {\n self.setState({userlogoBase64: null});\n this.logoValidationState = 'error';\n this.logoValidationMessage = \"User Logo is Required\";\n }\n var reader = new FileReader();\n // Closure to capture the file information.\n reader.onload = (function(theFile) {\n return function(e) {\n // Render thumbnail.\n self.setState({userlogoBase64: e.target.result});\n };\n })(userlogo[0]);\n // Read in the image file as a data URL.\n reader.readAsDataURL(userlogo[0]);\n } else {\n this.logoValidationState = 'error';\n this.logoValidationMessage = \"User Logo is Required\";\n }\n }", "function modifyLogo() {\n storage\n .get({\n [CHOSEN_LOGO_PRIMARY_KEY]:\n DEFAULT_SETTINGS[CHOSEN_LOGO_PRIMARY_KEY],\n })\n .then((response) => {\n let newLogoUrl = {\n satoriPremium: BANNER_URL,\n tcs: TCS_LOGO_URL,\n alternative: ALT_TCS_LOGO_URL,\n }[response[CHOSEN_LOGO_PRIMARY_KEY]];\n $('img[src=\"/files/satori_banner.png\"]').attr(\n 'src',\n newLogoUrl,\n );\n });\n }", "function upload_logo() {\n\t$(\"#pilih\").click();\n}", "function processUpload(metaObject){\n // Grab the icon file, and when you've got it, continue the upload\n request(metaObject.icon).pipe(fs.createWriteStream(__dirname + '/public/icon.jpg')\n .on('finish', function(){\n startUpload(metaObject)\n }));\n}", "function uploadImage(){\n\t\t\tif(window.ActiveTab!='local'){return false;}\n\t\t\twindow.currentLocation = b.opts.imageManagerFolders;\n\t\t\t$('.fr-form input[type=file]').click();\n\t\t\t$('#edit').on('froalaEditor.image.inserted', function (e, editor, $img, response) {\n\t\t\t\t$('.fr-modal, .fr-overlay').hide();\n\t\t\t});\n\t\t}", "function modifyLogo() {\n storage.get({\n [CHOSEN_LOGO_PRIMARY_KEY]: DEFAULT_SETTINGS[CHOSEN_LOGO_PRIMARY_KEY]\n }).then(response => {\n const newLogoUrl = {\n satoriPremium: BANNER_URL,\n shitoriPremium: SHITORI_BANNER_URL,\n suspiciousSatoriPremium: SUSPICIOUS_SATORI_BANNER_URL,\n suspiciousShitoriPremium: SUSPICIOUS_SHITORI_BANNER_URL,\n tcs: TCS_LOGO_URL,\n tcsWhite: TCS_LOGO_WHITE_URL,\n alternative: ALT_TCS_LOGO_URL,\n alternativeWhite: ALT_TCS_WHITE_LOGO_URL,\n }[response[CHOSEN_LOGO_PRIMARY_KEY]];\n $('img[src=\"/files/satori_banner.png\"]').attr('src', newLogoUrl);\n });\n }", "function resownerdeletelogo(){\n\t\t\tvar useFile = (jssiteuserfriendly == 'N' || fb_domain_name == 'fb' || fb_domain_name == 'facebook') ? '/ajaxFile.php' : '/use-file';\n\t\t\tif(confirm('Are you sure want to delete?')){\n\t\t\t\t$.post(jssitebaseUrl+useFile, {'action':'resownerdeleteLogo'},function(response){\n\t\t\t\t//alert(response);\t\n\t\t\t\t\tif($.trim(response) == \"success\"){\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t$(\"#res_owner_logo1\").hide();\n\t\t\t\t\t\t$(\"#res_owner_add_disp_logo\").show();\n\t\t\t\t\t\t$(\"#succPhotoMsg\").addClass('errormsg').html(err_lang_arr['resmycc_logo_deleted_success']);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}else{\n\t\t\t\t\t\talert(err_lang_arr['resmycc_logo_error']);return false;\n\t\t\t\t\t}\n\t\t\t\t});return false;\n\t\t\t}\n\t}", "function save_image() {\n Control.OFC.post_image('includes/ofc_upload_image.php?filename=custom-'+Control.OFC.equivalent,Control.OFC.popup); \n}", "function logoCheck(logoraw) {\n\t\tif (logoraw !== null) {\n\t\t\treturn logoraw;\n\t\t} else {\n\t\t\treturn \"http://dishofsoul.com/extfiles/FJdBSoF.png\";\n\t\t}\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds "_ptr" on to the end of type identifiers that might need it; note that this operates on identifiers, not definitions
function regularizeTypeIdentifier(identifier) { return identifier.replace(/(_(storage|memory|calldata))((_slice)?_ptr)?$/, "$1_ptr" //this used to use lookbehind for clarity, but Firefox... //(see: https://github.com/trufflesuite/truffle/issues/3068 ) ); }
[ "function restorePtr(identifier) {\n return identifier.replace(/(?<=_(storage|memory|calldata))$/, \"_ptr\");\n }", "pointer(ptr) {\n\t\tif (!ptr) {\n\t\t\tthis.dword(0x00000000);\n\t\t\treturn;\n\t\t}\n\t\tlet { address = ptr.mem } = ptr;\n\t\tthis.dword(address);\n\t\tif (address > 0) {\n\t\t\tthis.dword(ptr.type);\n\t\t}\n\t}", "function getPointerDataType(ptr) {\n return ptr.replace(/\\s*(\\*|&amp;)$/, '');\n}", "function prepVararg(ptr, type) {\n if (type === 'double' || type === 'i64') {\n // move so the load is aligned\n if (ptr & 7) {\n assert((ptr & 7) === 4);\n ptr += 4;\n }\n } else {\n assert((ptr & 3) === 0);\n }\n return ptr;\n }", "function prepVararg(ptr, type) {\r\n if (type === 'double' || type === 'i64') {\r\n // move so the load is aligned\r\n if (ptr & 7) {\r\n assert((ptr & 7) === 4);\r\n ptr += 4;\r\n }\r\n } else {\r\n assert((ptr & 3) === 0);\r\n }\r\n return ptr;\r\n }", "addToSymbol(identifier, type, properties) {\n if (this.findSymbolInCurrentTable(identifier)) {\n throw new Error(\"Redifinition of symbol: \" + identifier);\n }\n if (this.findSymbol(identifier)) {\n console.log(\"Warning: Shawdow a variable previously declared: \" + identifier);\n }\n\n this.symbolTable[identifier] = { type: type, properties: properties };\n }", "get inout_ptr() {\n delete this.inout_ptr;\n let ptr_t = new PtrType(\n \"[inout] \" + this.name + \"*\",\n this.implementation.ptr,\n this);\n Object.defineProperty(this, \"inout_ptr\",\n {\n get: function() {\n return ptr_t;\n }\n });\n return ptr_t;\n }", "function newTypeVar() {\n return typeVariable(\"$\" + id++);\n}", "addType(type){\r\n\t\tif (typeof this.typeTable[type.name] == \"undefined\"){\r\n\t\t\t//type.table=this;\r\n\t\t\tthis.typeTable[type.name]=type;\r\n\t\t}else{\r\n\t\t\talert('XSD problem : type '+type.name+' is already defined.');\r\n\t\t}\r\n\t}", "function newTypeVar() {\n return typeVariable(\"@\" + typeId++);\n}", "function mangleTypeName (type) {\n\treturn type.replace(/[\\(\\)\\[\\]\\s,<>\\.]/g, '_').replace(/\\^/g,'B').replace(/\\*/g,'P');\n}", "function QualifiedTypeIdentifier(node, print) {\n print.plain(node.qualification);\n this.push(\".\");\n print.plain(node.id);\n}", "function _registerAlias(types, type) {\n t[type.toUpperCase() + \"_TYPES\"] = types;\n registerType(type);\n}", "TSTypeAliasDeclaration(node) {\n // type T = {}\n const typeToken = tokenStore.getFirstToken(node)\n const idToken = tokenStore.getFirstToken(node.id)\n setOffset(idToken, 1, typeToken)\n let eqToken\n if (node.typeParameters) {\n setOffset(tokenStore.getFirstToken(node.typeParameters), 1, idToken)\n eqToken = tokenStore.getTokenAfter(node.typeParameters)\n } else {\n eqToken = tokenStore.getTokenAfter(node.id)\n }\n const initToken = tokenStore.getTokenAfter(eqToken)\n setOffset([eqToken, initToken], 1, idToken)\n }", "function QualifiedTypeIdentifier(node, print) {\n\t print.plain(node.qualification);\n\t this.push(\".\");\n\t print.plain(node.id);\n\t}", "function _nextPointer(pointer, dict) {\n\t\treturn incrementPointerByOffset(pointer, 1, dict);\n\t}", "newTypeName(){\r\n\t\tvar typeName=\"__type__\"+this.typeIdNumber;\r\n\t\tthis.typeIdNumber++;\r\n\t\treturn typeName;\r\n\t}", "function TypeAlias(node, print) {\n this.push(\"type \");\n print.plain(node.id);\n print.plain(node.typeParameters);\n this.space();\n this.push(\"=\");\n this.space();\n print.plain(node.right);\n this.semicolon();\n}", "function restoreTypeSystem() {\r\n for (var regFuncName in originalRegistrationFunctions) {\r\n if (!originalRegistrationFunctions.hasOwnProperty(regFuncName)) { continue; }\r\n\r\n var original = originalRegistrationFunctions[regFuncName];\r\n var typeOrPrototype = original.isPrototype ? Type.prototype : Type;\r\n if (original.func) {\r\n typeOrPrototype[regFuncName] = original.func;\r\n } else {\r\n delete typeOrPrototype[regFuncName];\r\n }\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
INPUT: [1,2,3,4,5,6] OUTPUT: 3 COMMENTS: 2+4+6=12, 1+3+5=9, 129=3 INPUT: [3,5,7,9] OUTPUT: 24 INPUT: [2,4,6,8,10] OUTPUT: 30 HINT: Parse each string to number Create two variables for even and odd sum Iterate through all elements in the array with forof loop and check if the number is odd or even Print the difference
function main(inputArray){ let evenSum = 0; let oddSum = 0; for(let num of inputArray){ if(num % 2 == 0){ evenSum += num; }else{ oddSum += num; } } let difference = eveSum - oddSum; console.log(difference); }
[ "function sum(str){\n sum_even=0;\n sum_odd=0;\n let len=str.length;\n console.log(len);\n for(let i=0;i<len;i++){\n if(str[i]%2==0)\n sum_even+=parseInt(str[i]);\n else\n sum_odd+=parseInt(str[i]);\n }\n console.log(sum_even); console.log(sum_odd);\n if(sum_even<sum_odd)\n return \"Odd is greater than Even\";\n else if(sum_even>sum_odd)\n return \"Even is greater than Odd\";\n else\n return \"Even and Odd are the same\";\n}", "function solve(arr){\n let evens = 0;\n let odds = 0;\n\n for(let i = 0; i < arr.length; i++) {\n // or could have used 'arr[i] !== isNaN' instead of typeof\n if(arr[i] % 2 === 0 && typeof arr[i] === 'number') {\n evens += 1\n } else if(arr[i] % 2 !== 0 && typeof arr[i] === 'number'){\n odds += 1\n }\n }\n return evens - odds\n}", "function evenOrOdd(str) {\r\n const newArray = str.split('');\r\n var oddNums = 0;\r\n var evenNums = 0;\r\n \r\n for(let i = 0;i < newArray.length;i++){\r\n if(parseInt(newArray[i]) % 2 == 0){\r\n evenNums += parseInt(newArray[i]);\r\n }\r\n else{\r\n oddNums += parseInt(newArray[i]);\r\n }\r\n };\r\n \r\n if(oddNums > evenNums){\r\n return \"Odd is greater than Even\"\r\n }\r\n if(evenNums > oddNums){\r\n return \"Even is greater than Odd\"\r\n }\r\n if(evenNums === oddNums){\r\n return \"Even and Odd are the same\"\r\n }\r\n }", "function solve(a){\n var even = 0\n var odd = 0\n for ( let i = 0 ; i<a.length ; i++){\n if ( typeof(a[i]) === \"number\"){\n if (a[i] %2 ===0){\n even ++\n }else{\n odd ++\n }\n }\n }\n return (even-odd);\n }", "function oddSums(numbers) { // [3, 6, 8, 9, 1]\n // this is where you code\n let sum = 0;\n\n for (let i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2 != 0) {\n sum += numbers[i] // 3 + 9 + 1 = 13\n }\n }\n \n return sum; // 13\n}", "function evenOrOdd(str) {\n var array = str.split(\"\");\n var odd = 0, even = 0;\n for (var item of array) {\n if (parseInt(item) % 2 == 0) {\n even += parseInt(item);\n }\n else {\n odd += parseInt(item);\n }\n }\n return even > odd ? \"Even is greater than Odd\" :\n even < odd ? 'Odd is greater than Even' : 'Even and Odd are the same';\n}", "function oddishOrEvenish(num){\n let str = num.toString().split('');\n console.log(str);\n let output = 0;\n for (let i = 0; i<str.length; i++){\n output += Number.parseInt(str[i])\n }\n console.log(output);\n return output%2==0;\n}", "function substractEvenOdd (arrNum) {\n let odd = []; // gajil\n let even = []; // genap\n let result = [];\n\n for (let i=0; i<arrNum.length; i++) {\n if (arrNum[i]%2 === 0) {\n even.push(arrNum[i]);\n } else {\n odd.push(arrNum[i]);\n }\n }\n\n if (even.length === 0) {\n result.push(0);\n } else if (even.lengh === 1) {\n result.push(even);\n } else {\n let res = even[0];\n for (let j=1; j<even.length; j++) {\n res = res - even[j];\n }\n result.push(res)\n }\n\n if (odd.length === 0) {\n result.push(0);\n } else if (odd.lengh === 1) {\n result.push(odd);\n } else {\n let res = odd[0];\n for (let j=1; j<odd.length; j++) {\n res = res - odd[j];\n }\n result.push(res)\n }\n\n return result;\n\n}", "function sumEvenNumbers(input) {\n return input.filter(value => value % 2 === 0).reduce((counter, value) => counter + value );\n}", "function sumEvenNumbers(input) {\r\n let totalSum = 0;\r\n for(let i = 0; i < input.length; i++){\r\n if(input[i] % 2 === 0){\r\n totalSum += input[i];\r\n }\r\n }\r\n return totalSum;\r\n}", "function evenOddSums(arr) {\n let evenSum = 0;\n let oddSum = 0;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n evenSum += arr[i];\n } else {\n oddSum += arr[i];\n }\n }\n return [evenSum, oddSum];\n}", "function sumOdds(numbers) {\n let odds = [];\n for (let i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2 === 1) odds.push(numbers[i]);\n }\n return odds.reduce((a, b) => a + b, 0);\n}", "function oddishOrEvenish(num) {\n var strNum = num.toString();\n var numSplit = strNum.split(\"\");\n var total = 0;\n for (let i = 0; i < numSplit.length; i++) {\n total += parseInt(numSplit[i]);\n }\n if (total % 2 === 0) {\n return \"Evenish\";\n } else {\n return \"Oddish\";\n }\n}", "function oddSum(array) {\n var result = 0;\n for(var i=0; i<array.length; i++) {\n if(array[i]%2!==0) {\n result += array[i];\n }\n }\n return result;\n}", "function evenOddSums(arr){\n\tlet evenSum = 0;\n\tlet oddSum = 0;\n\n\t//using % to tell if the number is odd or even, using ternary to determine which one to add onto\n\tarr.forEach(num => (num % 2 === 0 ? (evenSum += num) : (oddSum += num)));\n\n\treturn [evenSum, oddSum];\n}", "function oddball_sum(num){\n // setting variable for final count\n let final_count = 0;\n\n //loop thriugh entire list\n for(let i = 0; i <= num.length;i++){\n if(num[i]%2 ===1){\n final_count += num[i];\n }\n }\n return final_count;\n}", "function evenOrOdd(str) {\n const evenOddTotals = str.split('').map(num => +num).reduce((prev, curr) => {\n\n if (curr % 2 === 0) {\n prev[0] += curr\n } else {\n prev[1] += curr\n }\n return prev;\n }, [0, 0]);\n\n return evenOddTotals[0] > evenOddTotals[1] ? \"Even is greater than Odd\" : evenOddTotals[0] < evenOddTotals[1] ? \"Odd is greater than Even\" : \"Even and Odd are the same\";\n}", "function evenOddSums() {}", "function oddball_sum(numbers){\n arrayLen = numbers.length;\n var sum = 0;\n if(arrayLen % 2 == 0){ // even number of elements\n for(var i=0; i<arrayLen-1; i+=2){\n sum += numbers[i];\n }\n }\n else{ // odd number of elements\n for(var i=0; i<arrayLen; i+=2){\n sum += numbers[i];\n }\n }\n return sum;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check two dates has the same year and month
static isSameYearMonth(dateA, dateB) { return ( dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() ); }
[ "_hasSameMonthAndYear(d1, d2) {\n return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&\n this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));\n }", "function isEqualMonth(a, b) {\n if (a == null || b == null) {\n return false\n }\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth()\n }", "function isSameMonth(date1, date2) {\n return (!!date1)\n && (!!date2)\n && date1.getFullYear() === date2.getFullYear()\n && date1.getMonth() === date2.getMonth();\n }", "function equalDates(date1, date2) {\n const dayInMonth1 = date1.getDate();\n const dayInMonth2 = date2.getDate();\n const month1 = date1.getMonth();\n const month2 = date2.getMonth();\n const year1 = date1.getYear();\n const year2 = date2.getYear();\n return dayInMonth1 === dayInMonth2 && month1 === month2 && year1 === year2;\n}", "function inSameMonth(dateA, dateB) {\n return dateA.getMonth() === dateB.getMonth();\n }", "function datesEqual(date1, date2) {\n if (date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate()) {\n return true;\n }\n return false;\n}", "isSameYear(date1, data2) {\n\t\treturn Moment(date1).isSame(data2, 'year');\n\t}", "function thisMonth(date1,date2){\n \tif ((date1[0] == date2[0])&&(date1[1] == date2[1])){\n \t\treturn true;\n \t}\n \treturn false;\n }", "function equalDates(pDate1, pDate2)\r\n{\r\n var b= false;\r\n\r\n b=((pDate1.getFullYear() == pDate2.getFullYear())\r\n && (pDate1.getMonth() == pDate2.getMonth())\r\n && (pDate1.getDate() == pDate2.getDate()));\r\n return b;\r\n}", "function dates_equal(d1, d2) {\r\n if (!d1 || !d2)\r\n return false;\r\n else\r\n return d1.getDate() == d2.getDate() &&\r\n d1.getMonth() == d2.getMonth() &&\r\n d1.getFullYear() == d2.getFullYear();\r\n}", "function compareDate(month, day, year, date2) {\n // month,date,year is selected, date2 is each object\n let o_year = new Date().getFullYear()+1\n\n if (year === o_year)\n year = date2.getFullYear()\n if (month === 13)\n month = date2.getMonth()+1\n if (day === 32)\n day = date2.getDate()\n \n if (year === date2.getFullYear() \n && month === date2.getMonth()+1\n && day === date2.getDate())\n return true;\n return false;\n}", "function sameDate(d0, d1) {\n\treturn d0.getFullYear() == d1.getFullYear() \n\t\t&& d0.getMonth() == d1.getMonth()\n\t\t&& d0.getDate() == d1.getDate();\n}", "function sameDate(d0, d1) {\n\treturn d0.getFullYear() == d1.getFullYear() && d0.getMonth() == d1.getMonth() && d0.getDate() == d1.getDate();\n}", "function _isSameYear(d1, d2) {\n return d1.getFullYear() === d2.getFullYear();\n }", "function isWithinYear(date1, date2) {\n\t\tvar year1 = parseInt(date1[0]);\n\t\tvar year2 = parseInt(date2[0]);\n\t\tvar month1 = parseInt(date1[1]);\n\t\tvar month2 = parseInt(date2[1]);\n\t\tvar day1 = parseInt(date1[2]);\n\t\tvar day2 = parseInt(date2[2]);\n\t\tif (year1 === year2) {\n\t\t\treturn true;\n\t\t} else if (year2 === year1 + 1 && (month2 < month1) || (month2 === month1 && day2 < day1)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "isSameYearSafe(date1, date2) {\n return date1 && date2 && this.isSameYear(date1, date2);\n }", "function checkDateDiff(time1, time2) {\n return (\n //check year\n (time1.getFullYear() !== time2.getFullYear()) ||\n //check month\n (time1.getMonth() !== time2.getMonth()) ||\n //check day\n (time1.getDate() !== time2.getDate())\n );\n}", "function _isNextMonth(d1, d2) {\n if (_isSameYear(d1, d2)) {\n return d2.getMonth() - d1.getMonth() === 1;\n } else if (_isNextYear(d1, d2)) {\n return d1.getMonth() === 11 && d2.getMonth() === 0;\n }\n return false;\n }", "function compareDates(d1, m1, y1, d2, m2, y2) {\n\n\tvar date1\t= new Number(d1);\n\tvar month1\t= new Number(m1);\n\tvar year1\t= new Number(y1);\n\tvar date2\t= new Number(d2);\n\tvar month2\t= new Number(m2);\n\tvar year2\t= new Number(y2);\n\n\tvar\treturnVal = 0;\n\tif (year1 < year2) {\n\t\treturnVal = -1;\n\t} else if (year1 > year2) {\n\t\treturnVal = 1;\n\t} else {\n\t\t//alert('same year');\n\t\tif (month1 < month2) {\n\t\t\treturnVal = -1;\n\t\t} else if (month1 > month2) {\n\t\t\treturnVal = 1;\n\t\t} else {\n\t\t\t//alert('same month');\n\t\t\tif (date1 < date2) {\n\t\t\t\treturnVal = -1;\n\t\t\t} else if (date1 > date2) {\n\t\t\t\treturnVal = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnVal;\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
slantScale :: Float > Vector > Vector
function slantScale(r, [a, b]) {return [r*a, r*b];}
[ "function scaleVector(v, s) {\n v[0] *= s;\n v[1] *= s;\n return v;\n }", "static scale(v, s){\n\t\t\treturn new Vector(v.x*s, v.y*s, v.z*s);\n\n\t}", "function scale( s, v1 ) { return [ s * v1[0], s * v1[1], s * v1[2] ]; }", "function vScale(a, c) {\n return vec(a.x * c, a.y * c);\n}", "function scale(v) {\n return v/82;\n }", "static ScaleVector(vector, scale_factor)\n {\n for (var i = 0; i < vector.length; i++)\n {\n vector[i] *= scale_factor;\n }\n }", "static GetScaledVector(vector, scale_factor)\n {\n let scaled = [];\n this.CopyContent(scaled, vector);\n this.ScaleVector(scaled, scale_factor);\n return scaled;\n }", "function ToRotatedScale( s:Vector2 ) : Vector3\n{\n return Vector3( s.x, s.y, 1.0 );\n}", "function ScaleVector(u,s){\r\n\t\t\tvar r = new Vector3D(s*u.ux,s*u.uy,s*u.uz);\r\n\t\t\treturn r;\r\n\t\t}", "scale(outMatrix, inMatrix, scalingVector) {\r\n // @todo\r\n }", "scaled(s) {\n var x = this.m[0];\n var y = this.m[1];\n var result = new vec2( x*s, y*s );\n return result;\n return this;\n }", "function v3_invscale_new(a, f) {\n return [ a[0] / f,\n a[1] / f,\n a[2] / f ];\n}", "GetScale() {\n return new Number2(this.values[0], this.values[4]);\n }", "static scale(c, v) {\r\n\t\t\r\n\t\ttry {\r\n\t\t\tif (!(v instanceof vector) || (typeof(c) !== \"number\"))\r\n\t\t\t\tthrow \"vector.scale: malformed parameters\";\r\n\t\t\telse\r\n\t\t\t\treturn(new vector(c*v.x, c*v.y, c*v.z));\r\n\t\t} // end try\r\n\t\t\r\n\t\tcatch(e) {\r\n\t\t\tconsole.log(e);\r\n\t\t\treturn(new vector(NaN, NaN, NaN));\r\n\t\t} // end catch\r\n\t\t\r\n\t}", "function scale(x,y){\n if(x instanceof V2){\n return scaleVector(S(y),x);\n }\n if(y instanceof V2){\n return scaleVector(S(x),y);\n }\n\n return scaleNumber(x,y);\n }", "function Scale () {}", "function scaleVec(vector, number){\n\t\tlet result = Vec2();\n\n\t\tresult.x = vector.x * number;\n\t\tresult.y = vector.y * number;\n\n\t\treturn result;\n\t}", "function vecScale(x, c) {\n for (var i = 0; i < x.length; i++) {\n x[i] *= c;\n };\n return x;\n}", "function scale_v2(v, l)\n{\n var len = length_v2(v);\n if (len == 0) return v;\n l /= len;\n return [v[0] * l, v[1] * l];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manage the "display all bot commands" command
function manageDisplayAllBotCommand( client, channel, tags ) { let output = ""; sayWhoseCommands(client, channel, tags); // Bot Commands Message output = "Bot Commands: " + displayAllVideo + " | " + displayAllSound + " | " + displayAllBotCommand + " | "; for ( var i = 0; i < botCommandsJson.length; i++ ) { if ( checkCommandRights(tags, botCommandsJson[i].commandRight) ) { if ( ( output.length + botCommandsJson[i].commandString.length + " | ".length ) >= 500 ) { output = output.slice(0,-3); client.say(channel,output); output = "Bot Commands: "; } output += botCommandsJson[i].commandString + " | "; } } output = output.slice(0,-3); client.say(channel,output); return true; }
[ "function processShowAllCommands(bot, channelID) {\n const storedMessages = db.get('messages');\n const availableCommands = [];\n for (let message of storedMessages) {\n availableCommands.push(' !' + message.command + ' ');\n }\n\n bot.sendMessage({\n to: channelID,\n message: 'Available custom commands are: `'+ availableCommands + '`'\n });\n}", "function listCommands() {\n console.log(`${mainDivider}\\n${\"WELCOME TO LIRI-BOT! HERE'S WHAT I CAN DO!\"}\\n${mainDivider}`)\n console.log(`${\"Use the following commands to run Liri-Bot:\"}\\n${minorDivider}\\n${\"'my-tweets' : To list the last 20 tweets\"}\\n${minorDivider}\\n${\"'spotify-this-song' + 'song name': To lists the Artist, Song Name, Preview Link, and Album\"}\\n${minorDivider}\\n${\"'movie-this' + 'movie title': To lists the Movie Title, Release Year, IMDB Rating, Rotten Tomatoes Rating, Country, Language, Plot, Cast\"}\\n${mainDivider}`);\n}", "function listCommands() {\n console.log(\n 'List of commands available:\\n' +\n '[-help] - Lists all the available commands.\\n' +\n '[Github URL] - Lists the commits for the provided GitHub URL.\\n' +\n '[Github URL] [nocache] - Lists the commits for the provided GitHub URL, ignoring cached values.\\n' +\n '[exit] - Ends Application\\n'\n )\n}", "function showCommands(){\n if (!commands_showing){\n if (general_commands.length > 0){\n var general = \"General commands: \";\n for (var i = 0; i < general_commands.length; ++i){\n general = general + general_commands[i];\n if (i < general_commands.length - 1)\n general = general + \", \"; // If not last command in list, add comma and space\n }\n $(\"#yt-masthead-content\").append(\"<p>\" + general + \"</p>\");\n }\n\n if (page_commands.length > 0){\n var page = \"Page specific commands: \";\n for (var i = 0; i < page_commands.length; ++i){\n page = page + page_commands[i];\n if (i < page_commands.length - 1)\n page = page + \", \"; // If not last command in list, add comma and space\n }\n $(\"#yt-masthead-content\").append(\"<p>\" + page + \"</p>\");\n }\n\n commands_showing = true;\n }\n}", "function printAvailableCommands(){\n myLog(\"\");\n myLog(\"AVAILABLE COMMANDS ARE:\");\n for(command in commands){\n myLog(command + \" [\" + commands[command].optionDesc + \"]\");\n }\n}", "function commandList() {\n \tvar cmdList = [];\n \tCommandHandle.getAll().then((data) => {\n \tfor (let index = 0; index < data.length; index++) {\n \t\tcmdList.push(data[index].commandName);\n \t}\n \tvar cmdmsg = cmdList.toString();\n \tChatMessages.filterMessage(cmdmsg);\n \t});\n}", "listCommand() {\n document.getElementById('message_history').innerHTML += '<pre>' +\n this.HTMLEncode(`\nUsage: !/<Command> <arg1> <arg2> ...\n !/teleport <Map> <x> <y> Teleport to the map Map at coordinate (x, y)\n !/help List command usages\n `) + '</pre>';\n }", "function display(){\n console.log(chalk.yellow.underline.bold(\"Please use one of the following commands:\"))\n console.log(chalk.blue('\\tconcert-this')+\" to find the bands in the town\")\n console.log(chalk.blue('\\tspotify-this-song') + \" to get the song details\")\n console.log(chalk.blue('\\tmovie-this')+ \" to movie details\")\n console.log(chalk.blue('\\tdo-what-it-says') + \" to allow LIRI talk to to random.txt\")\n console.log(chalk.blue('\\tq') + \" to quit the terminal\\n\")\n}", "function outputHelpCommands() {\n output(\"Intercom basic commands\");\n output(\"-----------------------\");\n output(\"<b>help</b> - display help message\");\n output(\"<b>clear</b> - clears the content of the screen\");\n output(\"<b>open [URL]</b> - opens the given URL in the console\");\n}", "function cmdHelp(message, args)\n{\n var output = 'Command/Alias list:';\n for (cmd of Object.keys(commands))\n output += \"\\n\" + cmd;\n message.channel.send(output);\n}", "getAllCommands() {\n return this.commands.concat(this.defaultCommands);\n }", "displayCmd() {\r\n var cmdText = \"Commands \\n\";\r\n for (let i = 0; i < this.cmdOrder.length; ++i) {\r\n cmdText += this.cmdOrder[i] + \": \";\r\n cmdText += keyboardMap[this.cmdKeyCode[this.cmdIdx[this.cmdOrder[i]]]];\r\n cmdText += \"\\n\";\r\n }\r\n this.document.getElementById('commands').innerText = cmdText;\r\n }", "function sayCommands() {\n Bot.say(\"Use ! to choose an Command\");\n Bot.say(\"!1 - \"+voteStor[0][1]);\n Bot.say(\"!2 - \"+voteStor[1][1]);\n Bot.say(\"!3 - \"+voteStor[2][1]);\n}", "function showCommandHelpFucntion(){\n console.log('\"show\" command is used to show the list of clients, servers or both ');\n console.log('that are created by the user during the wrt-c session');\n console.log('The syntax of the command is the follows:');\n console.log('');\n console.log('show [client/server/all]');\n console.log('');\n}", "function commandDisplayer() {\n $(\"#available-options\").empty();\n $(\"#available-options\").append(\"<li>Possible Commands:</li>\")\n if(userCommands.length > 0) {\n for(var idx = 0; idx < userCommands.length; idx++) {\n $(\"#available-options\").append(\"<li>\" + userCommands[idx] + \"</li>\")\n }\n }\n}", "function commandHelp() {\n\tconsole.log(\"--- Available commands: ---\".green);\n\tconsole.log(\"--- (just start typing) ---\");\n\tconsole.log(\" \\\"help\\\":\".green, \" List all available commands (show this message again).\");\n\tconsole.log(\" \t\\\"add\\\":\".green, \" Add a new user that can be used to access the OPC UA Server.\");\n\tconsole.log(\" \tNote that users are not saved after shutdown!\");\n\tconsole.log(\" \\\"users\\\":\".green, \" Display all usernames that can currently be used.\");\n\tconsole.log(\" \\\"randomize\\\":\".green, \" Randomize the values of CoffeeLevel, WaterLevel and Cleanliness.\\n \tSince the Coffee Machine can't provide the actual data,\\n this command can be used instead to demonstrate the\\n visualization of the machine data in the HMI Application\");\n\trl.prompt();\n}", "function queryCommands() {\n server.getCommands().then(function(res) {\n commands.length = 0;\n res.data.commands.forEach(function(command) {\n commands.push(command);\n });\n parseCommands();\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }", "function commandDescriptions() {\n return commands.reduce(function(previous, current) {\n return previous + '\\n' + current.description;\n }, '');\n }", "function printCommands() {\n\tconsole.log(\"1: List contacts\");\n\tconsole.log(\"2: Add a contact\");\n\tconsole.log(\"0: Quit\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
String > Promise[Any] Makes a PreprocessedView request for the indicated view and returns a promise for the returned data
function requestViewAsync(view, instanceId) { var params = { viewFileName: view, paramNames: "ImagePrefix", paramValues: getImagePrefix(instanceId) }, cache = !!instanceId; if (instanceId) { params.instanceId = instanceId; } return makeServiceGetRequestAsync("Forms/PreprocessedView", params, cache); }
[ "async index ({ request, response, view }) {\n const rawContent = await RawContent.query().fetch()\n return rawContent\n }", "async patientView (ctx) {\n console.log('CONTROLLER HIT: PatientView::patientView');\n return new Promise ((resolve, reject) => {\n const query = 'SELECT * FROM patient_view WHERE patient_id = ?';\n const pid = ctx.params.patientview;\n chpConnection.query({\n sql: query,\n values: [pid]\n }, (err, res) => {\n if(err){\n reject(`Error querying CHP.patient_view: ${err}`)\n }\n\n ctx.body = res;\n ctx.status = 200;\n\n resolve();\n });\n }).catch(err => {\n ctx.status = 500;\n ctx.body = err;\n });\n }", "getByIndex(index) {\n return Promise.resolve(this.views[index]);\n }", "function insertView(viewPromise) {\n const contentElement = document.getElementById('content');\n //whatever is returned is in here. go get the promise, then when it finishes, do the function\n viewPromise.then(view => {\n contentElement.innerHTML = view;\n })\n}", "function render(view, context) {\n return new Promise(function(resolve, reject) {\n nunjucks.render(view, context, function(err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n });\n}", "async show ({ params, request, response, view }) {\n const rawContent = await RawContent.find(params.id)\n return rawContent\n }", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n /* loading: require(\"@views/_loading\").default, */\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n /* error: require(\"@views/_timeout\").default, */\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000\n });\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children\n // to the view component.\n return h(AsyncHandler, data, children);\n }\n });\n}", "async patientsView (ctx) {\n console.log('CONTROLLER HIT: PatientView::patientsView');\n return new Promise ((resolve, reject) => {\n const query = 'SELECT * FROM patient_view';\n\n chpConnection.query(query, (err, res) => {\n if (err){\n reject(`Error querying CHP.patient_view: ${err}`);\n }\n\n ctx.body = res;\n ctx.status = 200;\n\n resolve();\n\n });\n }).catch(err => {\n ctx.status = 500;\n ctx.body = err;\n });\n }", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n loading: require('@views/_loading').default,\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n error: require('@views/_timeout').default,\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000,\n })\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children\n // to the view component.\n return h(AsyncHandler, data, children)\n },\n })\n}", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n loading: require('@views/_loading').default,\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n // error: require('@views/_timeout').default,\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000,\n })\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children\n // to the view component.\n return h(AsyncHandler, data, children)\n },\n })\n}", "static actionPromise(view, method, args) {\n view[method](...args);\n return view.renderer.updatePromise();\n }", "function ɵɵloadViewQuery() {\n var index = getCurrentQueryIndex();\n setCurrentQueryIndex(index + 1);\n return loadInternal(getLView(), index - HEADER_OFFSET);\n}", "function ɵɵloadViewQuery() {\n return loadQueryInternal(getLView(), getCurrentQueryIndex());\n}", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n loading: require(\"@/views/loading-page\").default,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n error: require(\"@/views/timeout-page\").default,\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000,\n })\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children\n // to the view component.\n return h(AsyncHandler, data, children)\n },\n })\n}", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n loading: require('@components/_loading').default,\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n // error: require('@views/_timeout').default,\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000,\n })\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children\n // to the view component.\n return h(AsyncHandler, data, children)\n },\n })\n}", "function lazyLoadView(AsyncView) {\n const AsyncHandler = () => ({\n component: AsyncView,\n // A component to use while the component is loading.\n loading: require('@components/_loading').default,\n // Delay before showing the loading component.\n // Default: 200 (milliseconds).\n delay: 400,\n // A fallback component in case the timeout is exceeded\n // when loading the component.\n // error: require('@views/_timeout').default,\n // Time before giving up trying to load the component.\n // Default: Infinity (milliseconds).\n timeout: 10000,\n })\n\n return Promise.resolve({\n functional: true,\n render(h, { data, children }) {\n // Transparently pass any props or children``\n // to the view component.``\n return h(AsyncHandler, data, children)\n },\n })\n}", "async index ({ request, response, view }) {\n const data = await Permision.all()\n\n return data\n }", "function loadView(view) {\n return () =>\n import(/* webpackChunkName:\"[request]\"*/ \"@/views/\" + view + \"/index.vue\");\n}", "read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) ;\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a node to the scene and keep its pose updated using the anchorOffset
addAnchoredNode(anchorOffset, node){ this.anchoredNodes.push({ anchorOffset: anchorOffset, node: node }) this.scene.add(node) }
[ "addAnchoredNode(anchor, node){\n\t\tif (!anchor || !anchor.uid) {\n\t\t\tconsole.error(\"not a valid anchor\", anchor)\n\t\t\treturn;\n\t\t}\n\t\tthis._anchoredNodes.set(anchor.uid, {\n\t\t\tanchor: anchor,\n\t\t\tnode: node\n\t\t})\n\t\tnode.anchor = anchor\n\t\tnode.matrixAutoUpdate = false\n\t\tnode.matrix.fromArray(anchor.modelMatrix)\n\t\tnode.updateMatrixWorld(true)\t\n\t\tthis._scene.add(node)\n\n\t\tanchor.addEventListener(\"update\", this._handleAnchorUpdate.bind(this))\n\t\tanchor.addEventListener(\"remove\", this._handleAnchorDelete.bind(this))\n\t\n\t\treturn node\n\t}", "updateNodeFromAnchorOffset(frame, node, anchorOffset){\n\t\tconst anchor = frame.getAnchor(anchorOffset.anchorUID)\n\t\tif(anchor === null){\n\t\t\tthrottledConsoleLog('Unknown anchor uid', anchorOffset.anchorUID)\n\t\t\tthis.anchoredNodeRemoved(node);\n\t\t\tthis.removeAnchoredNode(node);\n\t\t\treturn\n\t\t}\n\t\tnode.matrixAutoUpdate = false\n\t\tnode.matrix.fromArray(anchorOffset.getOffsetTransform(anchor.coordinateSystem))\n\t\tnode.updateMatrixWorld(true)\n\t}", "addNode(node) {\n this.nodes.push(node);\n }", "addNode(node) {\n this.nodes[node.id] = node;\n this.dagre.setNode(node.id, {\n label: node.label,\n width: node.width,\n height: node.height\n });\n }", "addAnchoredModel(sceneGraphNode, x, y, z){\n\t\t// Save this info for use during the next render frame\n\t\tthis.anchorsToAdd.push({\n\t\t\tnode: sceneGraphNode,\n\t\t\tx: x, y: y, z: z\n\t\t})\n\t}", "addNode(node) {\n this.items.push(node);\n node.setLayer(this);\n }", "addToScene(scene){\n\t\tscene.add(this.lLink1);\n\t}", "function addNode(){\r\n\t\t\r\n\t}", "addNode(node) {\n let parent = node.parent;\n let collider = node.collider;\n let transform = node.transform;\n let rigidBodyComponent = node.rigidBody;\n let dynamics = parent && parent.dynamics;\n \n if (this.sceneComponent==dynamics && collider) {\n // Common: transform\n let btTrx = new Ammo.btTransform();\n btTrx.setIdentity();\n if (transform) {\n btTrx.setFromOpenGLMatrix(transform.matrix.toArray());\n }\n\n // Shape\n let shape = collider.shape.beginSimulation();\n\n // Body\n let mass = rigidBodyComponent && rigidBodyComponent.body.mass || 0;\n let btBody = null;\n let localInertia = new Ammo.btVector3(0,0,0);\n let motionState = new Ammo.btDefaultMotionState(btTrx);\n if (mass!=0) {\n shape.calculateLocalInertia(mass, localInertia);\n }\n btBody = new Ammo.btRigidBody(new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia));\n \n if (rigidBodyComponent) {\n rigidBodyComponent.body.beginSimulation({\n dynamics: this._engine.dynamicsWorld,\n body: btBody,\n node: node\n });\n }\n\n this._engine.dynamicsWorld.addRigidBody(btBody);\n this._engine.bodies.push({\n btBody: btBody,\n node: node\n }); \n }\n }", "addVertex(node) {\n this.nodes.add(node);\n }", "addToScene(scene) {\n\t\tscene.add(this.circle);\n\t}", "add(node) {\n if (!(this.update(node.x, node.y, node.moveCost, node.parent))) {\n this._open.push(node);\n }\n }", "placeNode(){\n let left = Math.floor(Math.random()*80) + 10;\n let top = Math.floor(Math.random()*80) + 10;\n this.node = $(this.createNode(top, left)).appendTo(main);\n this.menu = $(this.createMenu(top, left)).appendTo(main);\n \n //adjust width and height to be middle of point\n let x = this.node.position().left;\n let y = this.node.position().top;\n let x_adj = x - this.node.width()/2;\n let y_adj = y - this.node.height()/2;\n this.node.css('left', x_adj+'px');\n this.node.css('top', y_adj+'px');\n \n let menu_x_adj = x - this.menu.width()/2;\n let menu_y_adj = y - this.menu.height()/2;\n let menu_y_shift = this.node.height()/2 + this.menu.height()/2;\n this.menu.css('left', menu_x_adj);\n this.menu.css('top', menu_y_adj + menu_y_shift);\n }", "function addNodeAndLink(e, obj) {\n var adorn = obj.part;\n e.handled = true;\n var diagram = adorn.diagram;\n diagram.startTransaction(\"Add State\");\n\n // get the node data for which the user clicked the button\n var fromNode = adorn.adornedPart;\n var fromData = fromNode.data;\n var id = getlastnodeid();\n // create a new \"State\" data object, positioned off to the right of the adorned Node\n var toData = { \"id\": id, \"text\": (lang == \"fr\") ? \"Nouveau noeud\" : \"New node\", \"figure\": \"RoundedRectangle\",\n \"background\": \"#fff\", \"color\":\"rgb(76, 76, 76)\", \"border\": \"#60ac60\", \"borderWidth\": 2, \"img\": \"images/null.png\",\n \"userid\": userid, \"timecreated\": time(), \"userupdate\": \"0\", \"timemodified\": \"0\",\n \"link\": \"#\", \"linkIcon\": \"images/null.png\", \"file\": \"null\", \"fileIcon\" : \"images/null.png\", \"fileName\" : \"null\" }\n var p = fromNode.location.copy();\n p.x += 200;\n toData.loc = go.Point.stringify(p); // the \"loc\" property is a string, not a Point object\n // add the new node data to the model\n var model = diagram.model;\n model.addNodeData(toData);\n \n // create a link data from the old node data to the new node data\n var linkdata = {\n from: model.getKeyForNodeData(fromData), // or just: fromData.id\n to: model.getKeyForNodeData(toData)\n //text: \"transition\"\n };\n // and add the link data to the model\n model.addLinkData(linkdata);\n \n // select the new Node\n var newnode = diagram.findNodeForData(toData);\n diagram.select(newnode);\n \n diagram.commitTransaction(\"Add State\");\n\n // if the new node is off-screen, scroll the diagram to show the new node\n diagram.scrollToRect(newnode.actualBounds);\n }", "addToScene(scene) {\n scene.add(this);\n scene.add(this.spotLight);\n scene.add(this.cameraHelper);\n scene.add(this.spotLight.target);\n }", "function addNodeAndLink(e, obj) {\r\n\t var adornment = obj.part;\r\n\t var diagram = e.diagram;\r\n\t diagram.startTransaction(\"Add State\");\r\n\r\n\t // get the node data for which the user clicked the button\r\n\t var fromNode = adornment.adornedPart;\r\n\t var fromData = fromNode.data;\r\n\t // create a new \"State\" data object, positioned off to the right of the adorned Node\r\n\t var toData = { text: \"new\" };\r\n\t var p = fromNode.location.copy();\r\n\t p.x += 200;\r\n\t toData.loc = go.Point.stringify(p); // the \"loc\" property is a string, not a Point object\r\n\t // add the new node data to the model\r\n\t var model = diagram.model;\r\n\t model.addNodeData(toData);\r\n\r\n\t // create a link data from the old node data to the new node data\r\n\t var linkdata = {\r\n\t from: model.getKeyForNodeData(fromData), // or just: fromData.id\r\n\t to: model.getKeyForNodeData(toData),\r\n\t text: \"transition\"\r\n\t };\r\n\t // and add the link data to the model\r\n\t model.addLinkData(linkdata);\r\n\r\n\t // select the new Node\r\n\t var newnode = diagram.findNodeForData(toData);\r\n\t diagram.select(newnode);\r\n\r\n\t diagram.commitTransaction(\"Add State\");\r\n\r\n\t // if the new node is off-screen, scroll the diagram to show the new node\r\n\t diagram.scrollToRect(newnode.actualBounds);\r\n\t }", "addActorToScene(id, o3d, pid) {\n // o3d is scene - not really needed but creates canonical root actor\n if (o3d === scene) {\n actors[id] = o3d; // add scene as root with id i3d-templatename\n o3d.name = id;\n console.log(`added scene with id = ${id} o3d.name = ${o3d.name}`);\n return true;\n }\n // if id is already present, begin replacement by removing the \n // corresponding o3d from its parent in the tree, and from the actors list\n for (let name of Object.keys(scene.children)) {\n //console.log(`scene contains ${name} with val = ${scene[name]}`);\n if (name === id) {\n console.log(`actor ${id} === ${name} is duplicate! did not add!`);\n c3d.removeActorFromScene(id);\n }\n }\n ;\n // add new actor to parent in tree and to actors list\n o3d.name = id;\n if (pid && actors[pid]) {\n actors[pid].add(o3d); // add to parent\n }\n else {\n scene.add(o3d); // add as root to scene\n }\n actors[id] = o3d; // add node itself\n o3d.updateMatrix(); //needed?\n console.log(`added actor ${id} = ${o3d} with pid = ${pid} to scene`);\n //console.log(`actors[${id}] = ${actors[id]}`);\n return true;\n }", "function placeNode () {\n // If there is space for a node to be placed at the cursor's position,\n // create a new node there\n if (nodeCanBePlaced()) { \n // These depth coordinates record node's relative position on canvas\n var xDepth = cursorX/canvas.width;\n var yDepth = cursorY/canvas.height;\n var newNode = new Node(cursorX,cursorY,nodeNumber,xDepth,yDepth);\n nodes.push(newNode); \n nodeNumber++;\n currentItem = newNode;\n currentItem.highlight();\n highlightMode = true;\n nodeJustBeenPlaced = true; \n return true;\n }\n return false;\n }", "function addNodeAndLink(e, obj) {\n var adorn = obj.part;\n e.handled = true;\n var diagram = adorn.diagram;\n diagram.startTransaction(\"Add State\");\n // get the node data for which the user clicked the button\n var fromNode = adorn.adornedPart;\n var fromData = fromNode.data;\n // create a new \"State\" data object, positioned off to the right of the adorned Node\n var toData = { text: \"new\" };\n var p = fromNode.location.copy();\n p.x += 200;\n toData.loc = go.Point.stringify(p); // the \"loc\" property is a string, not a Point object\n // add the new node data to the model\n var model = diagram.model;\n model.addNodeData(toData);\n // create a link data from the old node data to the new node data\n var linkdata = {\n from: model.getKeyForNodeData(fromData),\n to: model.getKeyForNodeData(toData),\n text: \"transition\"\n };\n // and add the link data to the model\n model.addLinkData(linkdata);\n // select the new Node\n var newnode = diagram.findNodeForData(toData);\n diagram.select(newnode);\n diagram.commitTransaction(\"Add State\");\n // if the new node is off-screen, scroll the diagram to show the new node\n diagram.scrollToRect(newnode.actualBounds);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrolls an unrendered event into view. Internal function used from scrollResourceEventIntoView.
scrollUnrenderedEventIntoView(resourceRec, eventRec, options = defaultScrollOptions$3) { if (options.edgeOffset == null) { options.edgeOffset = 20; } const me = this, scroller = me.timeAxisSubGrid.scrollable, box = me.getResourceEventBox(eventRec, resourceRec), // TODO: have all "box" type objects use Rectangle scrollerViewport = scroller.viewport, targetRect = new Rectangle(box.start, box.top, box.end - box.start, box.bottom - box.top).translate( scrollerViewport.x - scroller.x, scrollerViewport.y - scroller.y ), result = scroller.scrollIntoView(targetRect, Object.assign({}, options, { highlight: false })); if (options.highlight || options.focus) { const detatcher = me.on({ eventrepaint({ scheduler, eventRecord, resourceRecord, element }) { if (eventRecord === eventRec) { detatcher(); result.then(() => { options.highlight && DomHelper.highlight(element); options.focus && element.focus(); }); } } }); } return result; }
[ "scrollUnrenderedEventIntoView(resourceRec, eventRec, options = defaultScrollOptions$3) {\n // We must only resolve when the event's element has been painted\n // *and* the scroll has fully completed.\n return new Promise(resolve => {\n const me = this,\n // Knock out highlight and focus options. They must be applied after the scroll\n // has fully completed and we have an element. Use a default edgeOffset of 20.\n modifiedOptions = Object.assign({\n edgeOffset: 20\n }, options, unrenderedScrollOptions),\n scroller = me.timeAxisSubGrid.scrollable,\n box = me.getResourceEventBox(eventRec, resourceRec),\n scrollerViewport = scroller.viewport;\n\n if (!scrollerViewport) {\n resolve();\n return;\n }\n\n const targetRect = box.translate(scrollerViewport.x - scroller.x, scrollerViewport.y - scroller.y),\n delta = scroller.getDeltaTo(targetRect, modifiedOptions)[me.isHorizontal ? 'xDelta' : 'yDelta'],\n onEventRender = async ({\n eventRecord,\n element,\n targetElement\n }) => {\n if (eventRecord === eventRec) {\n // Vertical's renderEvent is different to eventPaint\n const el = element || targetElement;\n detatcher(); // Don't resolve until the scroll has fully completed.\n\n await initialScrollPromise; // If we were scrolling rightwards, then because the rectangle was only *estimated*\n // we must now ensure that the scroll position is fully correct for the *element*.\n // TODO: Needed? The position should be correct with the new rendering\n\n if (delta > 0) {\n await scroller.scrollIntoView(el, {\n edgeOffset: options.edgeOffset\n });\n }\n\n options.highlight && DomHelper.highlight(el);\n options.focus && el.focus();\n resolve();\n }\n },\n // On either paint or repaint of the event, resolve the scroll promise and detach the listeners.\n detatcher = me.on({\n renderEvent: onEventRender\n }),\n initialScrollPromise = scroller.scrollIntoView(targetRect, modifiedOptions);\n });\n }", "function scrollToEvent() {\n // wait for calendar render\n $timeout(function () {\n // add scroll id\n $(\".fc-time-grid-event\").attr(\"id\", \"scrollTo\");\n\n if ($(\"#scrollTo\") && $(\"#scrollTo\").offset() !== undefined) {\n // scroll to event start\n $(\".fc-scroller\").animate({\n scrollTop: $(\"#scrollTo\").offset().top - 150\n }, 200);\n }\n }, 500);\n }", "onBodyScroll(event) {\n this._offsetX.next(event.offsetX);\n this.scroll.emit(event);\n this.cd.detectChanges();\n }", "scrollToHighlightedEvent() {\n const scrollConfig = { behavior: 'smooth', block: 'center' };\n const highlightedEvent = document.querySelector('.highlighted');\n\n if (highlightedEvent) {\n highlightedEvent.scrollIntoView(scrollConfig);\n this.hasScrolled = true;\n }\n }", "scrollDown() {\n if (this.ptr == 0) {\n throw \"this is disposed\";\n }\n instance().exports.Layout_scroll_down(this.ptr);\n }", "function conditionalScrollIntoView(e) {\n if (!entireElementVisible(e)) {\n e.scrollIntoView();\n }\n}", "scrollHitIntoView() {\n this.requestUpdate().then(() => {\n const selected = this.renderRoot.querySelector(\n '.web-search-popout__link--active',\n );\n selected.scrollIntoView({block: 'nearest'});\n this.dispatchEvent(new CustomEvent('resultselect', {detail: {selected}}));\n });\n }", "scrollToView(element)\n {\n element.scrollIntoView();\n }", "scrollIntoView() {\n if (DomUtils.getSelectionType(this.selection) !== \"None\") {\n const elementWithFocus = DomUtils.getElementWithFocus(\n this.selection,\n this.getDirection() === backward,\n );\n if (elementWithFocus) return Scroller.scrollIntoView(elementWithFocus);\n }\n }", "function onScrollHandler(e) {\n setTimeout(function () {\n updateViewport(true);\n }, 10);\n}", "scrollEntryIntoFullView(entry) {\n\t\tconst entryHeight = this.getEntryHeight(entry);\n\t\tif (entry.offsetTop<this.element.scrollTop)\n\t\t\tthis.element.scrollTop = entry.offsetTop;\n\t\telse if ( (entry.offsetTop+entryHeight)>(this.element.scrollTop+this.element.clientHeight) )\n\t\t\tthis.element.scrollTop = (entry.offsetTop+entryHeight) - this.element.clientHeight;\n\t}", "scrollEvent() {\n this.scroll.target = window.pageYOffset;\n }", "function InitScrollEvent(){\n clearIntervalEventView();\n this._interval = setInterval(() => {\n DashboardScreen.deltaX = DashboardScreen.deltaX + DashboardScreen.SCROLL_OFFSET_VARIANT;\n this._scroll.scrollTo({ x: DashboardScreen.deltaX, animated: true });\n }, DashboardScreen.DELAY_INDICATORS_INTERVAL);\n}", "callToScrollTopEvent() {\n const {\n scrollTop,\n } = this.options;\n\n if (!scrollTop) {\n return;\n }\n\n scrollTop();\n }", "_onScroll(ev) {\n // Record current scroll top position\n this._lastScrollTop = this._viewportElement.scrollTop;\n // Don't attempt to scroll if the element is not visible, otherwise scrollTop will be corrupt\n // which causes the terminal to scroll the buffer to the top\n if (!this._viewportElement.offsetParent) {\n return;\n }\n // Ignore the event if it was flagged to ignore (when the source of the event is from Viewport)\n if (this._ignoreNextScrollEvent) {\n this._ignoreNextScrollEvent = false;\n return;\n }\n const newRow = Math.round(this._lastScrollTop / this._currentRowHeight);\n const diff = newRow - this._bufferService.buffer.ydisp;\n this._scrollLines(diff, true);\n }", "function\tdataIntoView(event) {\n\tif (EditorMode == \"xml\") {\n\t\txmlDataIntoView(event);\n\t} else {\n\t\thumdrumDataIntoView(event);\n\t}\n}", "function onScroll(evt) {\n console.log(\"watchForScroll\");\n doScrollToFragment = false;\n }", "get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }", "onInternalScrollChange (scrollPosition) {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the request is valid based on the security hash and the destination path received
function isValidCredential(req){ return uploadCredential.isValid(req.query.security_hash, destPath); }
[ "checkRequestUrl(details) {\n if (details.url === null || details.url.length === 0) {\n return false;\n }\n\n var currentCheckUrl = this.masterURL;\n if (this.redirectURL !== null) {\n currentCheckUrl = this.redirectURL;\n }\n if (currentCheckUrl === null || currentCheckUrl.length === 0) {\n return false;\n }\n if (!(currentCheckUrl === details.url || details.url.indexOf(currentCheckUrl) > -1)) {\n return false;\n }\n return true;\n }", "function ValidateDestination() {}", "validateRequest(req) {\n let path = req.url;\n // Remove initial '/' char\n path = path.slice(1);\n if (path.endsWith(\"/\")) path = path.slice(0, path.length - 1);\n req.path = path.split(\"/\");\n\n if (\n req.path.length > 2 ||\n (req.path.length === 2 && req.path[1] !== \"meta\")\n ) {\n let x = new Error(\"Invalid URL\");\n x.code = 404;\n throw x;\n }\n\n return this.metaData\n .getDataFromId(req.path[0])\n .then(({ path: reqPath }) => {\n // If promise is not rejected then path exists.\n // If it matches ignore patterns then it should not be served.\n let hiddenFile = this.ignore.some(re => re.test(reqPath));\n // Check if path is descendent of any shared directory.\n // This is just an extra check to ensure file is not served in\n // case meta data has extra paths.\n let isShared = isChild(reqPath, this.share);\n\n if (hiddenFile || !isShared) {\n // If hidden or not shared then throw error\n throw Error(\"Resource can't be shared\");\n }\n\n // Check to see if file exists at path and we have access.\n // In most cases this should pass but it's still a valid check\n return fsaccess(reqPath, Fs.constants.F_OK | Fs.constants.R_OK);\n })\n .catch(err => {\n logger.debug(`HTTPService.validateRequest: ${err}`);\n logger.debug(`HTTPService.validateRequest: ${err.stack}`);\n\n // If id doesn't exist in db or it can't be shared then control\n // reaches here\n let x = new Error(\"Resource not found\");\n x.code = 404;\n // Reject returned promise so that rootHandler can handle response\n // properly\n throw x;\n });\n }", "validateDestinationTarget() {\n return _.has(this.scheme[this.getDestination()], this.getTarget());\n }", "function validateDigest(digest, requestBody) {\n // Verify equality of digests.\n return digest === createDigest(requestBody);\n}", "function validateInfoHash(req, res){\n\n\tif (req.query.info_hash == null)\n\t\treturn false;\n\n\tvar hash_buf = unescape(req.query.info_hash);\n\tvar info_hash = new Buffer(40, 'ascii');\n\tfor (var i = 0; i < 20; i+=1){\n\t\tvar s = hash_buf[i].charCodeAt().toString(16);\n\t\tif (s.length == 1){\n\t\t\tinfo_hash.write('0', i*2);\t\t\n\t\t\tinfo_hash.write( s, i*2 + 1);\n\t\t}else{\n\t\t\tinfo_hash.write(hash_buf[i].charCodeAt().toString(16), i*2);\n\t\t}\n\t}\n\treq.query.info_hash = info_hash.toString();\n\n\treturn true;\n}", "function validateRequest (req, secret) {\n const signature = req.headers['x-spark-signature']\n const hash = crypto.createHmac('sha1', secret).update(JSON.stringify(req.body)).digest('hex')\n if (signature != hash) {\n console.error('WARNING: Webhook received message with invalid signature. Potential malicious behavior!')\n return false\n } else {\n return true\n }\n}", "verifyRequest() {\n if (this.protocol !== 'heimdal') return false;\n if (!this.authority) return false;\n\n if (this.signature) {\n const message = this.getSigningMessage();\n\n return this.verifyMessage(message, this.id, this.signature);\n }\n\n return true;\n }", "function validateURL(query) {\n if (query.id == 'NEW') {\n if ('url' in query && 'requesttype' in query && 'pass' in query) {\n return true;\n }\n } else if (query.id == 'EXISTING') {\n if ('url' in query && 'devid' in query && 'requesttype' in query && 'pass' in query) {\n return true;\n }\n } else if (query.id == 'REMOVE') {\n if ('devid' in query && 'pass' in query) {\n return true;\n }\n }\n return false;\n}", "function checkUrl(){\n // get hash the URL\n var hash = window.location.hash;\n // check if something is in the hash\n if (hash){\n var splitted = hash.split(\"/\");\n if (splitted.length == 3){\n var zoom = parseInt(splitted[0].substr(1)),\n lat = parseFloat(splitted[1]),\n lng = parseFloat(splitted[2]);\n // check if parameters are within the swiss createBounds and the allowed zoom levels\n if (zoom >= config.min_zoom && zoom <= config.max_zoom &&\n lat >= config.swiss_bounds[0] && lat <= config.swiss_bounds[2] &&\n lng >= config.swiss_bounds[1] && lng <= config.swiss_bounds[3]\n ){\n return true\n }\n }\n error.showError('Ungültiger Weblink!');\n return false\n }\n else{\n return false\n }\n }", "function validateDigest (key, response) {\n let accept = getWSAccept(response);\n let digest = createHash('sha1').update(`${key}${GUID}`).digest('base64');\n if (!digest === accept) throw new Error('Server Sec-WebSocket-Accept digest does not match key.');\n}", "needsRevalidation (request) {\n const _req = requestObject(request)\n // force method to GET because we only cache GETs\n // but can serve a HEAD from a cached GET\n _req.method = 'GET'\n return !this.policy.satisfiesWithoutRevalidation(_req)\n }", "function checkUrlHash() {\n var hash = window.location.hash;\n\n // Allow deep linking to recover password form\n if (hash === '#recover') {\n toggleRecoverPasswordForm();\n }\n }", "function checkUrlHash() {\r\n var hash = window.location.hash;\r\n\r\n // Allow deep linking to recover password form\r\n if (hash === \"#recover\") {\r\n toggleRecoverPasswordForm();\r\n }\r\n }", "function isValidSourceOrigin(req, sourceOrigin) {\n console.log('---- verifying source origin: ', sourceOrigin);\n if (req.hostname == 'localhost' && req.app.get('env') == 'development') {\n console.log('no origin check in dev mode');\n return true;\n }\n return matchesAnyOrigin(VALID_SOURCE_ORIGINS, sourceOrigin);\n}", "validateRequestByWallet(){\r\n this.server.route({\r\n method: 'POST',\r\n path: '/message-signature/validate',\r\n handler: async (request, h) => {\r\n //Validates payload\r\n if(!request.payload){\r\n throw Boom.badRequest(\"You should provide a valid JSON request\");\r\n }\r\n\r\n let address = request.payload.address;\r\n let signature = request.payload.signature;\r\n\r\n //validates address and signature\r\n if(!address || address.length==0 || !signature || signature.length==0){\r\n throw Boom.badRequest(\"You should provide a valid address and signature properties in the JSON request\");\r\n }\r\n\r\n //returns result of the signature validation\r\n return this.mempoolService.validateRequestByWallet(address,signature);\r\n }\r\n });\r\n }", "function validateReq(){\n\n let valid = true;\n\n if(threadId == undefined){ \n errorMessage.error.push({request_body: 'Request body missing property [thread_id].'});\n valid = false;\n }\n if(password == undefined){ \n errorMessage.error.push({request_body: 'Request body missing property [delete_password].'});\n valid = false;\n }\n\n return valid;\n\n } // end of function validateReq()", "function checkUrlHash() {\n var hash = window.location.hash;\n \n // Allow deep linking to recover password form\n if (hash === '#recover') {\n toggleRecoverPasswordForm();\n }\n }", "function validateRoute(req,res,next){\n const body = req.body;\n !body || body === {}\n ? res.status(400).json({ message: \"post not included\" })\n : req.params.item !== global.configuration.routes[0].sourcePath.replace('/', '')\n ? res.status(404).json({message: \"sourcePath match not found\"})\n : next();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a down arrow
function showArrowDown(e) { e.target.childNodes[1].classList.add('fa-long-arrow-alt-down') e.target.childNodes[1].classList.remove('fa-long-arrow-alt-up') }
[ "get arrow_downward () {\n return new IconData(0xe5db,{fontFamily:'MaterialIcons'})\n }", "function downArrow() {\r\n\t\t\t$down_arrow.css({\r\n\t\t\t\t'margin-top': 22,\r\n\t\t\t\topacity: 1\r\n\t\t\t}).delay(100).animate({\r\n\t\t\t\topacity: 0,\r\n\t\t\t\t'margin-top': 40\r\n\t\t\t}, 600, 'swing', downArrow);\r\n\t\t}", "get keyboard_arrow_down () {\n return new IconData(0xe313,{fontFamily:'MaterialIcons'})\n }", "function showDownArrow () {\r\n\t\t$('.sliceButton').animate({opacity: '0'},500);\r\n\t}", "get arrow_upward () {\n return new IconData(0xe5d8,{fontFamily:'MaterialIcons'})\n }", "get arrow_forward () {\n return new IconData(0xe5c8, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "function drawDownArrow (x, y)\n {\n args.object.context.moveTo(Math.round(x), y - 5);\n args.object.context.lineTo(Math.round(x), y - 5 - length);\n \n args.object.context.stroke();\n args.object.context.beginPath();\n \n // This draws the arrow\n args.object.context.moveTo(Math.round(x), y - 5);\n args.object.context.lineTo(Math.round(x) - 3, y - 10);\n args.object.context.lineTo(Math.round(x) + 3, y - 10);\n args.object.context.closePath();\n }", "function TextExtArrow() {}", "function hideDownArrow() {\n ProductDetailsScreen.FlexImageUpArrow.isVisible = true;\n ProductDetailsScreen.FlexImageDownArrow.isVisible = false;\n}", "get arrow_drop_down () {\n return new IconData(0xe5c5,{fontFamily:'MaterialIcons'})\n }", "function showScrollArrow() {\n $(\"#downwardsArrow\").css('display','block');\n}", "get keyboard_arrow_up () {\n return new IconData(0xe316,{fontFamily:'MaterialIcons'})\n }", "get arrow_drop_up () {\n return new IconData(0xe5c7,{fontFamily:'MaterialIcons'})\n }", "get arrow_back () {\n return new IconData(0xe5c4, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "function hideArrow() {\n if(arrow){\n setArrow(false)\n }\n }", "function go_down() {\n\t\tcharacter.css('top', parseInt(character.css('top')) + 5);\n\t}", "function createArrow(Direction){\n console.log()\n \n if (Direction == \"right\"){return \"→\"}\n \n else if (Direction == \"left\") {return \"←\"}\n \n else if (Direction == \"up\") {return \"↑\"}\n \n else if (Direction == \"down\") {return \"↓\"}\n \n }", "get arrow_forward_ios () {\n return new IconData(0xe5e1, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "get isDownArrowKeyDown() {\n return this._isDownArrowKeyDown;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that every course is already in the system. It looks for the "code". It throws an error in case the entity is not found.
async function checkForCoursePresence(entities) { await updateAndSort("COURSE", Course.getComparator("code")); entities.forEach((entity) => getCourseIdFromCode(entity.Code)); }
[ "isCourseExist()\n\t{\n\t\tfor (var i = 0; i < courseDB.length; i++) \n\t\t{\n\t\t\tif (courseDB[i].cid === this.cid) \n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "checkNewCourse(courseCode) {\n return __awaiter(this, void 0, void 0, function* () {\n const query = \"SELECT courseCode FROM courses WHERE courseCode = ?\";\n const connection = yield this.pool.getConnection();\n const [result] = yield connection.query(query, [courseCode]);\n connection.release();\n return result.length > 0;\n });\n }", "function sanitizeCourseCode(ins){\n const chkr = datab.find(p => p.catalog_nbr == ins);\n\n //if exists in database\n if (chkr) {\n return true;\n }\n else{\n return false;\n }\n}", "async checkForExistingCodeError () {\n\t\tconst { objectId, objectType } = this.request.body;\n\t\tthis.codeError = await this.data.codeErrors.getOneByQuery(\n\t\t\t{ objectId, objectType },\n\t\t\t{ hint: CodeErrorIndexes.byObjectId }\n\t\t);\n\t\tif (this.codeError && this.headerAccountId !== this.codeError.get('accountId')) {\n\t\t\tthrow this.errorHandler.error('createAuth', { reason: 'accountId given in the header does not match the object' });\n\t\t}\n\t\tif (this.codeError && this.codeError.get('accountId') !== this.request.body.accountId) {\n\t\t\tthrow this.errorHandler.error('createAuth', { reason: 'accountId for the comment does not match the accountId of the parent object' });\n\t\t}\n\t\tif (!this.codeError && this.request.body.accountId !== this.headerAccountId) {\n\t\t\tthrow this.errorHandler.error('createAuth', { reason: 'accountId given in the header does not match that given in the body' });\n\t\t}\n\t}", "function checkCourseExist(id) {\n var likeCourses = getLikeCourses();\n var takenCourses = getTakenCourses();\n var courses = likeCourses.concat(takenCourses);\n for ( i = 0; i < courses.length; i++) {\n if (id == courses[i]) {\n return true;\n }\n }\n return false;\n}", "findCourse(courseCode) {\n for (let i = 0; i < this.courses.length; i++) {\n if (this.courses[i].data.courseCode.contains(courseCode)) {\n return this.courses[i];\n }\n }\n }", "function courseExistsInStudent(course, student){\n if(student.courses){\n console.log(\"courses exist\");\n courses = student.courses;\n for(var i = 0; i < courses.length; i++){\n console.log(courses[i]._id);\n //Compare the string versions of the ids\n if(\"\" + courses[i]._id === \"\" + course._id){\n console.log(\"Found the course\");\n return true;\n }\n }\n return false;\n }\n return false;\n}", "detectCourse(input, courses) {\n for (var course in courses) {\n if (courses[course].code == input) {\n return course;\n }\n }\n return false;\n }", "addCourse()\n\t{\n\t\tif (!this.isCourseExist()) \n\t\t{\n\t\t\tcourseDB.push(this);\n\t\t}\n\t\telse\n\t\t{\n\t\t\talert(\"Course id already exists.\");\n\t\t}\n\t}", "function verifyEnrolledCourses(student_number, level, programme) { // new level and new programme\n const db = new sqlite3.Database(dbfile);\n db.run(\"DELETE FROM enrolled WHERE course_code NOT IN (SELECT code FROM course WHERE programme = ? AND level = ?)\", [sanitizer.sanitize(programme), sanitizer.sanitize(level)]);\n db.close();\n}", "function courseExists(course) {\n var sheet = SpreadsheetApp.getActiveSheet();\n var numCourses = sheet.getLastRow() - 1;\n if (numCourses == 0) { \n return false;\n }\n //if here, we know there is at least course in database\n var courses = sheet.getSheetValues(2,2,numCourses,4);\n for (var i = 0; i < courses.length; i++) {\n if (courses[i][0] == course.name && courses[i][1] == course.city &&\n courses[i][2] == course.state && courses[i][3] == course.country) {\n //Exact match!\n return true;\n }\n }\n return false; \n}", "function isCourseExist(course) {\n myCourses = JSON.parse(localStorage.getItem(\"myCourses\")) || [];\n for (let item of myCourses) {\n if (item.title == course.title) { return true; }\n }\n return false;\n }", "async function doesCourseExist(CourseNumber, CourseTitle) {\r\n const snapshot = await db.collection('Courses').where('CourseNumber', '==', CourseNumber).where('CourseTitle', '==', CourseTitle).get();\r\n return (snapshot.docs.map(doc => ({\r\n __id: doc.id,\r\n ...doc.data()\r\n })).length > 0);\r\n}", "function courseExists(newCourseTitle, userName, users) {\n var exists = false;\n var BreakException = {};\n\n try {\n users.forEach(function(user) {\n\n // only check courses for specific user\n if (userName == user.getUserName()) {\n\n var courses = user.getCourses();\n courses.forEach(function(course) {\n if (newCourseTitle == course.getCourseTitle()) {\n exists = true;\n throw BreakException; // break out of loop\n } // else skip this existing course\n });\n } // else skip this user\n });\n } catch(ex) {\n // check to ensure we caught the BreakException\n if (ex !== BreakException) {\n // not a BreakExcption\n alert('An error has occured.');\n } // else ignore\n }\n\n return exists;\n}", "function verifyOwnCourse() {\n UserCoursesService.listUserCourses($scope.user.id).then(function (data) {\n userCoursesTable = data;\n $scope.ownCourse = false;\n for (var i = 0; i < userCoursesTable.length; i++) {\n userCourseIds[i] = userCoursesTable[i].id_curso;\n if ($stateParams.courseId == userCourseIds[i]) {\n // If the user is registered in the selected course, $scope.ownCourse\n // is set to true. We use this in the view for validate if the button\n // for registration to the course appers or the button for the view of\n // course contents\n $scope.ownCourse = true;\n }\n }\n });\n }", "function search_signs(course_id,student_code) {\n\t\tif(course_id == '' || student_code == ''){\n\t\t\talert('กรุณากรอกข้อมูล รหัสวิชา และ รหัสนักศึกษา !');\n\t\t}else{\n\t\t\tcheckIfCourseExists(course_id,student_code);\n\t\t}\n\n\t}", "function isAlreadyAdded(course,courses){\n console.log('isAlreadyAdded() called');\n let flag = 0;\n courses.forEach(function(courseLS){\n if(courseLS.name === course.name && courseLS.id === course.id){\n console.log('Already added');\n flag = 1;\n return false;\n }\n });\n return flag;\n}", "async checkRelatedPrograms() {\n await Utils.asyncForEach(this.careers, async(career, index) => {\n console.log(\"[\" + (index + 1) + \"/\" + this.careers.length + \"] \" + \"Checking \" + career.code + \" | \" + career.title + \"...\\r\");\n career = (await db.queryCollection(\"careers\", {\"code\": career.code}))[0];\n let c = Object.assign(new Career(), career);\n await c.setRelatedPrograms(await this._buildRelatedProgramData(c.code));\n await c.saveToDatabase();\n })\n }", "async function getCourseByCode(courseCode) {\n if ((!courseCode) || (typeof courseCode !== \"string\")) throw \"Course Code is invalid\";\n\n const courseCollection = await courses();\n const foundCourse = await courseCollection.findOne({courseCode: courseCode});\n\n if (foundCourse === null) return undefined;\n\n return foundCourse;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the specified node in the graph is a subgraph node. A subgraph node is one that contains other nodes.
function isSubgraph(g,v){return!!g.children(v).length}
[ "function isSubgraph(g, v) {\n return g.hasOwnProperty(\"children\") && g.children(v).length;\n}", "function isSubgraph(g, v) {\n return !!g.children(v).length;\n}", "function inSubTree(n,p) {\n if(n == p) {\n return true\n } else if(typeof n.parent === 'undefined') {\n return false;\n } else {\n return inSubTree(n.parent, p);\n }\n}", "function isSub(index1, index2) {\r\n\tvar result = false;\r\n\tvar i = index1;\r\n\t\r\n\twhile (i != -1 && nodes[i].parentID != 'root' && result == false) {\r\n\t\tif(nodes[i].parentID==nodes[index2].id) result = true;\r\n\t\ti = getItemIndex(nodes[i].parentID);\t\t\r\n\t}\r\n\r\n\treturn result;\r\n}", "function findSubgraph(node, graph, subnodes = new Set()) {\n const directSubnodes = graph[node];\n if (directSubnodes) {\n for (const directSubnode of directSubnodes) {\n if (!subnodes.has(directSubnode)) {\n subnodes.add(directSubnode);\n findSubgraph(directSubnode, graph, subnodes);\n }\n }\n }\n\n return subnodes;\n}", "function contains(node){\n\t\tif(!graph[node]) return false;\n\t\telse return true;\n\t}", "function isSubdomainOf(domain, subdomain) {\n\tvar ds = getOrCreateState(domain);\n\tvar subds = getOrCreateState(subdomain);\n\tif(ds.is_second_level_domain && !subds.is_second_level_domain && subds.parent_domain === domain) {\n\t\treturn true;\n\t}\n\treturn false;\n}", "function isNodeAChildOf(otherNode) {\n\t\t\t\t\t\tvar children = otherNode[nodesProperty];\n\t\t\t\t\t\tif (angular.isArray(children)) {\n\t\t\t\t\t\t\tfor (var i = 0; i < children.length; i++) {\n\t\t\t\t\t\t\t\tvar child = children[i];\n\t\t\t\t\t\t\t\tif(node == child){\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tvar result = isNodeAChildOf(child);\n\t\t\t\t\t\t\t\tif(result){\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}", "function has_upper_subs(graph, subs, type) {\n\n if (subs.type == type)\n return true;\n\n var inputs = get_inputs(graph, subs);\n for (var i = 0; i < inputs.length; i++)\n if (has_upper_subs(graph, inputs[i], type))\n return true;\n\n return false;\n}", "function isSubfolderOf(subfolder, folder) {\n const subfolderArray = subfolder.split(path.sep);\n const folderArray = folder.split(path.sep);\n // Check to see that every sub directory in subfolder exists in folder.\n return subfolderArray.length <= folderArray.length && subfolderArray.every((subpath, index) => folderArray[index] === subpath);\n}", "function isSub(name) {\n\ttry {\n\t\tif (name === null) {\n\t\t\treturn false;\n\t\t}\n\t\telse if (name.indexOf(\"~Sub\") === 0) {\n\t\t\treturn true;\n\t\t}\n\t\telse return false;\n\t}\n\tcatch (err) {\n\t\tsys.sendAll(\"Errore nel determinare se \"+name+\" è un sostituto, \"+err, tourserrchan);\n\t\treturn false;\n\t}\n}", "function isSub(name) {\r\n try {\r\n if (name === null) {\r\n return false;\r\n }\r\n else if (name.indexOf(\"~Sub\") === 0) {\r\n return true;\r\n }\r\n else return false;\r\n }\r\n catch (err) {\r\n sendChanAll(\"Error in determining whether \"+name+\" is a sub, \"+err, tourserrchan);\r\n return false;\r\n }\r\n}", "function isSupersetOf(superset, subset) {\n return isSubsetOf(subset, superset);\n}", "isSubdomain(domain, sub) {\n let index = domain.indexOf(sub);\n if (index === -1) {\n return false;\n } else if (index === 0) {\n return true;\n } else {\n return domain[index - 1] === '.'; //subdomain\n }\n }", "function hasSubfolders(folder) {\n if (isFolder(folder)) {\n for (var i = 0; i < folder.children.length; i++) {\n if (isFolder(folder.children[i])) {\n return true;\n }\n }\n }\n return false;\n }", "function isParent(node){\n return (node.children && node.children.length);\n }", "function hasChildren(subset) {\n for (var i in subset) {\n if (typeof(subset[i]) === 'object') { return true; }\n }\n}", "function isSubclass(sub,sup) {\n if (sub === sup) return true;\n if (sub.isLeafType || !sub[\"extends\"] || sub[\"extends\"].length == 0) return false;\n let r = sub[\"extends\"].filter(function(x){ return x===sup || isSubclass(x, sup); });\n return r.length > 0;\n}", "function IsSearchBySubSection() {\n if (typeof(pg_bSearchBySubSection) !== \"undefined\" &&\n (pg_bSearchBySubSection === 1)) {\n return true;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomize function which will do the put all the pieces together: randomize the seating list and shuffle it a given number of times, creating a individual seating lists for each course/switch.
function randomize(employeesList, numPlacesPerTable, numTables, numSwitches) { // 1st step - set some initial variables. var numGuests = employeesList.length; var employeesArrays = arrayCreator(employeesList, numSwitches); var employees = courseIterator(employeesArrays, numGuests); // 2nd step - randomize the guest list and give output. var mixed = shuffle(employees[0]); var courseOne = `For the course no 1: \n`; var tableNo = 1; var init = 0; for (var s = 0; s <= mixed.length-1; s = s+numPlacesPerTable) { var currentTable = mixed.slice(init+s,s+numPlacesPerTable); courseOne = courseOne.concat(`Table ${tableNo}: ${currentTable.toString()}. \n`); tableNo = tableNo + 1; } console.log(courseOne); employees[0] = mixed; // 3rd step - do the switches. placeSwitcher(employees, numGuests, numSwitches, numPlacesPerTable, numTables); }
[ "function generateTrialLists() {\n\t/* Generic counter. Necessary for while loops below. */\n\tvar counter = 0;\n /* Generate interleaved list */\n if (experiment.condition === \"interleaved\") {\n /* Appends a pair of Bruno and Ron paintings, but the order of which is first\n in the pairing is randomized. */\n while (counter < (experiment.blocks*(experiment.stimuli/2))) {\n if (Math.round(Math.random()) === 0) {\n trainingList.push( choosePainting(brunoList), choosePainting(ronList));\n } else {\n trainingList.push( choosePainting(ronList), choosePainting(brunoList));\n }\n resetSamplingState(brunoList);\n resetSamplingState(ronList);\n counter++;\n }\n /* Generate blocked list */\n } else {\n /* First, randomly choose Bruno or Ron list, and append all eight paintings\n in random order. */\n if (Math.round(Math.random()) === 0) {\n trainingList = trainingList.concat( shuffle(brunoList));\n } else {\n trainingList = trainingList.concat( shuffle(ronList));\n }\n /* Then, choose the list not chosen from the previous block, and append all\n eight paintings in random order. Do this 9 times, for a total of\n 10 painting blocks. (A block is the set of all paintings.) */\n while (counter < (experiment.blocks*2-1)) {\n if (trainingList[trainingList.length-1][0] == \"Bruno\") {\n trainingList = trainingList.concat( shuffle(ronList));\n } else {\n trainingList = trainingList.concat( shuffle(brunoList));\n }\n counter++;\n }\n }\n /* Generates a test list of 32 paintings, where each painting is shown twice. */\n testList = shuffle( testList.concat(brunoList, ronList));\n\tvar temp = [];\n\ttemp = shuffle( temp.concat(brunoList, ronList));\n\ttestList = testList.concat(temp);\n}", "function generateCards(){\n shuffle(cardList.concat(cardList)).forEach(createCard);\n}", "function randomize_stimuli() {\n console.log(\"starting randomization\");\n // randomize the order within the categories (order LM - LN - SM - SN - remains!)\n let stimuli = [];\n for (let s of [LM, LN, SM, SN]) {\n shuffle(s);\n for (let i of s) {\n // create a deep copy to avoid problems (JS accesses objects by\n // reference!!!)\n stimuli.push(JSON.parse(JSON.stringify(i)));\n // check if you actually didn't mutate the original object:\n stimuli[stimuli.length-1][\"deep_clone\"] = 1;\n // console.log(stimuli[stimuli.length-1][\"deep_clone\"]);\n // console.log(i[\"deep_clone\"]);\n }\n }\n\n // split the list into old and new list: (balanced LM, LN, SM, SN)\n let learning_phase_stimuli = stimuli;\n console.log(learning_phase_stimuli.lenght);\n \n // generate all possible conditions to assign to the images later:\n let conditions = [];\n let combinations = [[\"remember\", \"N + M\", \"switch\"], [\"remember\", \"M + N\", \"switch\"],\n [\"forget\", \"N + M\", \"switch\"], [\"forget\", \"M + N\", \"switch\"],\n [\"remember\", \"N + M\", \"repetition\"], [\"remember\", \"M + N\", \"repetition\"],\n [\"forget\", \"N + M\", \"repetition\"], [\"forget\", \"M + N\", \"repetition\"]];\n\n while (conditions.length < learning_phase_stimuli.length) {\n // shuffle(combinations);\n for (let c of combinations) {\n conditions.push(c);\n }\n }\n // assign conditions to stimuli\n for (let i in learning_phase_stimuli) {\n learning_phase_stimuli[i][\"forget_condition\"] = conditions[i][0];\n learning_phase_stimuli[i][\"resp_map\"] = conditions[i][1];\n learning_phase_stimuli[i][\"probe_condition\"] = conditions[i][2];\n // add the correct response to the timeline data\n learning_phase_stimuli[i] = add_correct_response(learning_phase_stimuli[i]);\n }\n //shuffle(recognition_stimuli);\n return [learning_phase_stimuli];\n}", "function generatePairs() {\n allCards = allCards.concat(allCards);\n allCards = shuffle(allCards);\n}", "function generateCards() {\n for (var i = 0; i < 2; i++) {\n cardLists = shuffle(cardLists);\n cardLists.forEach(createCard);\n }\n}", "function shuffle(){\n\tvar choices = [];\n\tfor (c= 0; c<400 ; c++){\n\t\tfor (t=14; t>=0 ; t--){\n\t\t\tif (movableCheck(tiles[t])){\n\t\t\t\tchoices.push(t);\n\t\t\t}\n\t\t}\n\t\tposMove = choices[Math.floor(Math.random() * choices.length)];\n\t\tmove(tiles[posMove]);\n\t}\n}", "generateRandomCardSet() {\n // clone card list\n let cards = this.cards.slice()\n // shuffle cards\n cards = this.shuffle(cards)\n // pick n number of cards then duplicate\n const tmp = cards.slice(0, 20)\n return this.shuffle(tmp.concat(tmp.slice()))\n }", "function shuffleCards(deck, count) {\n var a,b,c;\n for(var i = 0;i<200;i++) {\n a=Math.floor(Math.random() * count);\n b=Math.floor(Math.random() * count);\n c=deck[a];\n deck[a]=deck[b];\n deck[b]=c;\n }\n}", "function shufflePlayCards() {\r\n shuffle(numArray4);\r\n shuffle(numArray6);\r\n shuffle(iconArray4);\r\n shuffle(iconArray6);\r\n}", "shuffle() {\n // reset dealt cards\n this.cards = this.cards.concat( this.dealt );\n this.dealt = [];\n // asynchronously simultaneously generate 51 random numbers\n const promises = [];\n for ( let i = 0; i < 51; i += 1 ) {\n promises.push( rand( i, 51 ));\n }\n return Promise.all( promises )\n .then(( randoms ) => {\n randoms.forEach(( rando, index ) => {\n const temp = this.cards[index];\n this.cards[index] = this.cards[rando];\n this.cards[rando] = temp;\n });\n });\n }", "function shuffleCards() {\n removeCards();\n const shuffleArray = cards.sort(() => Math.random() - 0.5);\n displayCards(shuffleArray);\n styleCards();\n}", "function shuffle(){\n var currentWinner = document.querySelector('.winner');\n var nextWinner = _.sample(el.sqr);\n\n currentWinner.classList.remove(WINNER);\n nextWinner.classList.add(WINNER);\n}", "function shuffle ( d )\n{\n var i = 0;\n var j = 0;\n \n for (var k=1; k<= 150; k++)\n {\n i = Math.floor((Math.random() * 50) + 1);\n j = Math.floor((Math.random() * 50) + 1);\n swapCard(d,i,j);\n deckTop = 0;\n }\n }", "function initializeTestingStimuli(){\n\n\tfor (var i=0; i<3; i++){\n\t\tvar toRemove = eval(\"category\"+(i+1));\n\t\ttestingStimuli = testingStimuli.concat(toRemove);\n\t}\n\tif (debug) console.log(\"Testing stimuli: \"+testingStimuli);\n\ttestingStimuli = shuffle(testingStimuli);\n\tif (debug) console.log(\"Shuffled testing stimuli: \"+testingStimuli);\n}", "function shufflePlayerList() {\r\n shuffle(players);\r\n\r\n playerInTurn = 0;\r\n}", "function quoteSequence(){\n //console.log('shuffling');\n currentInd = quotesArr.length;\n var temp, pickMe;\n //while there are elements to shuffle\n while(currentInd !== 0){\n //console.log(currentInd);\n pickMe = Math.floor(Math.random()*currentInd);\n currentInd--;\n \n //swap\n temp = quotesArr[currentInd];\n quotesArr[currentInd] = quotesArr[pickMe];\n quotesArr[pickMe] = temp;\n }\n \n}", "shuffle(){\n\t\tif(!this.cards)return;\n\n\t\tlet left = this.cards.slice(0, 26)\n\t\tlet right = this.cards.slice(26,52)\n\n\t\tlet shuffledDeck = []\n\t\tlet now = Date.now().toString()\n\t\tlet seedNum = now.slice(-4)\n\t\tlet nextCard;\n\n\t\tfor(let i=0; i<52; i++){\n\t\t\tif(left.length == 0){\n\t\t\t\tnextCard = right.pop()\n\t\t\t\tshuffledDeck.unshift(nextCard)\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(right.length == 0){\n\t\t\t\tnextCard = left.pop()\n\t\t\t\tshuffledDeck.unshift(nextCard)\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tseedNum = genRand(seedNum)\n\n\t\t\t\tif(seedNum > 5500){\n\t\t\t\t\tnextCard = right.pop()\n\t\t\t\t\tshuffledDeck.unshift(nextCard)\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tnextCard = left.pop()\n\t\t\t\t\tshuffledDeck.unshift(nextCard)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.cards = shuffledDeck\n\t}", "function doRandom() {\n for(i = 0; i < 6; i++) {\n let number = Math.floor(Math.random() * liste.length);\n randomList.push(liste[number]);\n randomList.push(liste[number]);\n liste.splice(number, 1);\n };\n arrayShuffle(randomList);\n return randomList;\n}", "function shuffle() {\n var currentIndex = recipes.length, temporaryValue, randomIndex ;\n\n // While there remain elements to shuffle...\n while (0 !== currentIndex) {\n\n // Pick a remaining element...\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n\n // And swap it with the current element.\n temporaryValue = recipes[currentIndex];\n recipes[currentIndex] = recipes[randomIndex];\n recipes[randomIndex] = temporaryValue;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the currently selected folder
GetSelectedFolder() { console.debug(`ContaplusModel::GetSelectedFolder`) return this.config.get("folder") }
[ "function GetSelectedDirectory()\n{\n return getSelectedDirectoryURI();\n}", "function getCurrentFolderObject(){\n\tif(document.getElementById(\"selectedFolder\").children[0].innerHTML === \"Home of \"+folderData.Name){\n\t\treturn folderData;\n\t}\n\treturn searchCurrentFolderObjectRec(folderData.Folders);\n}", "function get_current_folder_id()\n{\n\treturn current_folder_id;\n}", "folder() {\r\n return getParentFolder(this.path);\r\n }", "static selectFolder(){\n SelectFileFolder.selectFolderDialog(folderPaths => {\n if(folderPaths && folderPaths.length){\n // get the input path \n let path = SelectFileFolder.cleanPath(folderPaths[0]);\n\n // add the folder \n FolderDispatcher.addFolder(path);\n }\n });\n }", "function getSelectedDirectory()\n{\n // Select Addresses Dialog\n if (abList)\n return MailServices.ab.getDirectory(abList.value);\n\n // Main Address Book\n if (gDirTree.currentIndex < 0)\n return null;\n return gDirectoryTreeView.getDirectoryAtIndex(gDirTree.currentIndex);\n}", "_getSelectedPathPart(): ?string {\n\t\tconst i = this._normalizedSelectionIndex();\n\t\tconst result = this.state.fileResults[i];\n\t\tif (result.isDirectory) return result.name;\n\t\treturn null;\n\t}", "function returnFolderPath() {\r\n\r\n\t\tvar inputTag = document.getElementById(s_download_select_folder_id);\r\n\r\n\t\tif (inputTag != null) {\r\n\t\t\tvar pathVal = inputTag.getAttribute(s_download_path);\r\n\r\n\t\t\tif (pathVal)\r\n\t\t\t\tfuncSlectFolder(pathVal);\r\n\t\t\tinputTag.remove();\r\n\t\t}\r\n\t}", "function selectFolderDialog() {\n\treturn new Promise((resolve, reject) => {\n\t\tdialog\n\t\t\t.showOpenDialog(getCurrentWindow(), {\n\t\t\t\tproperties: ['openDirectory'],\n\t\t\t})\n\t\t\t.then(result => {\n\t\t\t\tif (result.canceled) return\n\t\t\t\tconst folderPath = normalizeDir(result.filePaths[0])\n\t\t\t\tresolve(folderPath)\n\t\t\t})\n\t\t\t.catch(err => {\n\t\t\t\treject(err)\n\t\t\t})\n\t})\n}", "function getFolderPath(){\n\tif (folderPath == null){\n\t\treturn null;\n\t}else{\n\t\treturn folderPath;\n\t}\n}", "onSelectFolder_() {\n this.browserProxy_.requestScanToLocation().then(\n /* @type {!SelectedPath} */ (selectedPath) => {\n // When the select dialog closes, set dropdown back to\n // |selectedFolder| option.\n this.$.scanToSelect.selectedIndex = 0;\n\n const baseName = selectedPath.baseName;\n const filePath = selectedPath.filePath;\n // When the select dialog is canceled, |baseName| and |filePath| will\n // be empty.\n if (!baseName || !filePath) {\n return;\n }\n\n this.selectedFolder = baseName;\n this.selectedFilePath = filePath;\n });\n }", "_getSelectedFile(): ?string {\n\t\tconst i = this._normalizedSelectionIndex();\n\t\tconst result = this.state.fileResults[i];\n\t\tif (!result.isDirectory) return result.name;\n\t\treturn null;\n\t}", "get folder() {\r\n return new Folder(this, \"folder\");\r\n }", "function showLastFolder(){\n $('.selectFolder').val(localStorage.getItem('chosenFolderId')).trigger(\"change\");\n }", "function getSelectedFolder ( event ) {\n var id = event.target.attributes.id.value ;\n fireMoveAction( selectedMailFolders[ id ], messageList ) ;\n}", "function getExportsFolder() {\n // Set up 'File open' modal\n var openPanel = NSOpenPanel.openPanel();\n openPanel.setCanChooseDirectories(true);\n openPanel.setCanChooseFiles(false);\n openPanel.setCanCreateDirectories(false);\n\n openPanel.setTitle(\"Choose your exports folder\");\n openPanel.setPrompt(\"Choose\");\n\n // Handle folder chosen\n if (openPanel.runModal() == NSOKButton) {\n return openPanel.URL();\n }\n}", "function ChooseFolder()\n{\n const nsIFilePicker = Components.interfaces.nsIFilePicker;\n\n var fp = Components.classes[\"@mozilla.org/filepicker;1\"]\n .createInstance(nsIFilePicker);\n var prefutilitiesBundle = document.getElementById(\"bundle_prefutilities\");\n var title = prefutilitiesBundle.getString(\"downloadfolder\");\n fp.init(window, title, nsIFilePicker.modeGetFolder);\n fp.appendFilters(nsIFilePicker.filterAll);\n\n var folderListPref = document.getElementById(\"browser.download.folderList\");\n fp.displayDirectory = IndexToFolder(folderListPref.value); // file\n\n if (fp.show() == nsIFilePicker.returnOK) {\n var currentDirPref = document.getElementById(\"browser.download.dir\");\n currentDirPref.value = fp.file;\n folderListPref.value = FolderToIndex(fp.file);\n // Note, the real prefs will not be updated yet, so dnld manager's\n // userDownloadsDirectory may not return the right folder after\n // this code executes. displayDownloadDirPref will be called on\n // the assignment above to update the UI.\n }\n}", "function GetFolderName(Title_) {\r\n var FolderName = \"\";\r\n try {\r\n with (GetExcelApplication()) {\r\n with (FileDialog(4)) { //msoFileDialogFolderPicker\r\n if (Title_ != \"\") { Title = Title_; }\r\n if (Show() == -1) { FolderName = SelectedItems(1); }\r\n }\r\n }\r\n } catch (e) {\r\n FolderName = \"\";\r\n }\r\n return FolderName;\r\n}", "function getFolder( path ) {\n var segments = path.split( \"/\" );\n segments.pop();\n return segments.join( \"/\" );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This funcion adds the currentBeer to the local storage First we instantiate a new object from the "currentBeer"state, and then we do the same with the beer list, this is only a temporary variable, its not used outside the function. We then check the temporary beer list if its empty, remember this is a full copy of the "myBeerList"state, so in theory we're checking if the "myBeerList"state is null. If it is null, this means that we have to create an empty array object, push the "currentBeer"object into it and set it as the "myBeerList"state. If we dont do set it as an empty array objece, it will be a null, and the .push()function we perform afterwards will send out an error. If the tempBeerList is not null push the "currentBeer"object into the tempBeerList and set it as the "myBeerList"state
addToLocalStorage() { const currentBeer = this.state.currentBeer; let tempBeerList = this.state.myBeerList; if(tempBeerList == null) { tempBeerList = []; tempBeerList.push(currentBeer); this.setState( { myBeerList: tempBeerList }); } else { tempBeerList.push(currentBeer); this.setState( { myBeerList: tempBeerList }); } localStorage.setItem("myBeerList", JSON.stringify(tempBeerList)); }
[ "loadDatafromLocalStorage(){\n const savedBeerList = localStorage.getItem(\"myBeerList\");\n\n if(savedBeerList !== '') {\n this.setState({\n myBeerList: JSON.parse(savedBeerList)\n });\n }\n\n\n }", "function updateStorageBeer() {\n var beerString = JSON.stringify(Addbeer.beerDrink);\n localStorage.setItem('beerData', beerString);\n}", "function addNewBeer(){\n let name = document.querySelector(\"#name\").value;\n let image =document.querySelector(\"#urlImage\").value;\n\nlet newBeer ={\nname: name,\nimage: image\n}\nbeers.push(newBeer);\ndocument.querySelector(\"#list-container\").innerHTML=\"\";\nappendBeers(beers);\n}", "clearLocalStorage(){\n localStorage.setItem(\"myBeerList\", '');\n this.setState(\n {\n myBeerList: []\n });\n }", "function setFavorites() {\n var favoriteBeaches = { [beachName]: beachID };\n var localFavorite = JSON.parse(localStorage.getItem(\"favorites\"));\n \n localFavorite = {...localFavorite , ...favoriteBeaches};\n console.log(localFavorite)\n localStorage.setItem(\"favorites\", JSON.stringify(localFavorite));\n var liEl = document.createElement(\"li\");\n $(liEl).text(beachName);\n $(liEl).attr(\"id\", beachID);\n liEl.addEventListener(\"click\", clickedBeach);\n $('#favoriteBox').find(\".menu-list\").append(liEl);\n \n \n \n \n }", "function addLocalStorageWishListData(){\n\tvar violetstreetWishlist = [];\n\tfor(var i = 0; i < wishlists.length; i++){\t\t\n\t\tvioletstreetWishlist.push(wishlists[i].dataStr);\n\t\t// wishListData.push();\n\t\tconsole.log(violetstreetWishlist);\n\t}\n\tlocalStorage.setItem(\"violetstreetWishlist\", JSON.stringify(violetstreetWishlist));\n}", "static addBookToList(book) {\n // get the all the books from local-storage\n let storedBooks = JSON.parse(localStorage.getItem('Books'))\n // check if the stored-books is not null\n storedBooks = storedBooks ? storedBooks : []\n // then push a new book to the list\n storedBooks.push(book)\n // finally rewrite the Books in local-storage with a new added book\n localStorage.setItem('Books', JSON.stringify(storedBooks))\n // and clear the form input fields\n document.getElementById('book-form').reset()\n }", "function addOrder(food){ \n\n\t\t//if localStorage(\"list\") is empty, push food object into \"list\" array and localStorage.\n\t\tif(localStorage.getItem(\"list\") === null){\n\t\t\tlist.push(food); \n\t\t\tlocalStorage.setItem(\"list\",JSON.stringify(list));\n\t\t\tload();\n\t\t\t\n\t\t}else{ //else get current list and pass to check function\n\t\t\tlist = JSON.parse(localStorage.getItem(\"list\")); //get current list\n\t\t\tcheck(food);\n\t\t\tload();\n\t\t}\n\t}", "addToStorage(list = this._list) {\n localStorage.setItem(this._storageKey, JSON.stringify(list));\n }", "function storeTeamBudgetData(){\n var teamBudgetObject = addBudget();\n //if the budget data exists, read and add onto it\n if(localStorage.getItem(\"teamBudgetData\") != null){\n console.log(\"Is not null.\");\n var tempBudgetArray = JSON.parse(localStorage.getItem(\"teamBudgetData\"));\n tempBudgetArray.push(JSON.stringify(teamBudgetObject));\n localStorage.setItem(\"teamBudgetData\",JSON.stringify(tempBudgetArray));\n //otherwise, create the Team Budget object array\n }else{\n console.log(\"Is null.\");\n var tempBudgetArray = [];\n tempBudgetArray.push(JSON.stringify(teamBudgetObject));\n localStorage.setItem(\"teamBudgetData\",JSON.stringify(tempBudgetArray));\n }\n}", "addToLocalStorage() {\n\t\tlocalStorage.setItem('gods@app', JSON.stringify(this.state.gods));\n\t\tlocalStorage.setItem('pantheon@app', JSON.stringify(this.state.pantheon));\n\t\tlocalStorage.setItem('godclass@app', JSON.stringify(this.state.godclass));\n\t}", "function addBeerTab() {\r\n\t\t// Check if the beer is already in the tab\r\n\t\tvar id = ListTab.length;\r\n\t\tvar idInTab = -1;\r\n\r\n\t\tfor(ii = 0; ii<id; ii++){\r\n\t\t\tif (ListTab[ii][3] == beer_id){\r\n\t\t\t\tidInTab = ii;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(idInTab == -1) {\r\n\t\t\t//var length=ListTab[id].length;\r\n\t\t\tvar url = 'http://pub.jamaica-inn.net/fpdb/api.php?username=ervtod&password=ervtod&action=beer_data_get&beer_id=\"' + beer_id + '\"';\r\n\t\t\tvar beer_info = JSON.parse(Get(url));\r\n\t\t\tvar array = [];\r\n\t\t\tarray[0] = beer_info.payload[0].namn;\r\n\t\t\tarray[1] = price;\r\n\t\t\tarray[2] = 1;\r\n\t\t\tarray[3] = beer_id;\r\n\r\n\t\t\tListTab[id] = array;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tListTab[ii][2]++;\r\n\t\t}\r\n\r\n\t\tupdateCost();\r\n\t\t//tab_box();\r\n\t\ttab_table();\r\n\t\tarray = [];\r\n\t}", "function createBeerArray() {\n globalData.barData.storage.forEach((beerType) => {\n const beerObject = {beerName: beerType.name, beerSales: 0};\n globalData.ranking.push(beerType.name = beerObject);\n })\n}", "populateStorage() {\n if (!localStorage.length) {\n library.push(new Book('Twist Of The Wrist', 'Keith Code', 135, 'Read'));\n library.push(new Book('A Perfect Day', 'Lady Teresa', 140, 'Unread'));\n localStorage.setItem('books', JSON.stringify(library));\n }\n }", "function addToLocalStorage() {\n\t\tif (typeof (Storage) !== \"undefined\") {\n\t\t\tlocalStorage.setItem(\"todoList\", JSON.stringify(todoList));\n\t\t} else {\n\t\t\talert(\"error or browser doesn't support local storage!\");\n\t\t}\n\t}", "function saveIntoStorage(sticker) {\n let stickers = getstickersFromStorage();\n\n // add the sticker into the array\n stickers.push(sticker);\n\n // since storage only saves strings, we need to convert JSON into String\n localStorage.setItem('stickers', JSON.stringify(stickers) );\n}", "function addBus(e){\r\n e.preventDefault();\r\n let formData={} \r\n let name = document.getElementById(\"name\").value;\r\n let source = document.getElementById(\"src\").value;\r\n let destination = document.getElementById(\"dest\").value;\r\n let bus_no = document.getElementById(\"num\").value;\r\n let capacity = document.getElementById(\"cap\").value;\r\n\r\n formData.name = name;\r\n formData.source = source;\r\n formData.destination = destination;\r\n formData.bus_no = bus_no;\r\n formData.capacity = capacity;\r\n\r\n let NewBus = JSON.parse(localStorage.getItem(\"Bus\"));\r\n NewBus.push(formData)\r\n console.log(NewBus);\r\n localStorage.setItem(\"Bus\",JSON.stringify(NewBus))\r\n \r\n display()\r\n\r\n document.getElementById(\"name\").value = '';\r\n document.getElementById(\"src\").value = '';\r\n document.getElementById(\"dest\").value = '';\r\n document.getElementById(\"num\").value = '';\r\n document.getElementById(\"cap\").value = '';\r\n}", "function createPet() {\n\n\t// create array and add selected pet\n\n\t\tvar pet = [];\n\n\t\tpet = JSON.stringify({\n\t\t//ID : $(\"#petID\").val(),\n\t\t\"pet_name\" : document.getElementById(\"textinput1\").value,\t\t\n\t\t\"pet_breed\" : document.getElementById(\"textinput2\").value,\n\t\t\"vet_name\" : document.getElementById(\"textinput3\").value,\n\t\t\"vet_contact\" : document.getElementById(\"textinput4\").value,\n\t\t\"vet_oohcontact\" : document.getElementById(\"textinput5\").value,\n\t\t\"ins_name\" : document.getElementById(\"textinput6\").value,\n\t\t\"ins_contact\" : document.getElementById(\"textinput7\").value,\n\t\t\"ins_policyNo\" : document.getElementById(\"textinput8\").value,\n\t\t\"pet_age\" : document.getElementById(\"textinput9\").value,\n\t\t\"pet_weight\" : document.getElementById(\"textinput10\").value,\n\t\t\"tmt_flea\" : document.getElementById(\"textinput11\").value,\n\t\t\"tmt_worm\" : document.getElementById(\"textinput12\").value,\n\t\t\"tmt_jab\" : document.getElementById(\"textinput13\").value,\n\t});\n\n\ttbPets.push(pet);\n\tlocalStorage.setItem(\"tbPets\", JSON.stringify(tbPets));\n\tconsole.log(\"the data was saved\");\n\n\n\n\t// else add new pet to existing array (push?)\n\n\t// add the pet to the array\n\n}", "function Addtostorage(nList){\n Lists.push(nList);\n\n // Stringifying value from storage with JSON\n localStorage.setItem(\"Lists\", JSON.stringify(Lists) );\n\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a web by id (using POST)
openWebById(webId) { return this.clone(Site_1, `openWebById('${webId}')`).postCore().then(d => ({ data: d, web: Web.fromUrl(d["odata.id"] || d.__metadata.uri), })); }
[ "function OpenPostExternal(postId){\n shell.openExternal('https://www.wnmlive.com/post/'+postId) ;\n }", "function openEditPage(id) {\r\n window.open(\"https://myanimelist.net/ownlist/anime/\" + id + \"/edit\", '_blank');\r\n }", "function openChatSwapplace(id) {\n\n window.location.assign('https://' + window.location.host + '/?post_type=swapplaces&p=' + id);\n\n}", "function openChatProduct(id) {\n\n window.location.assign('https://' + window.location.host + '/?post_type=produits&p=' + id);\n\n}", "function callEntry(id) {\n window.location.href = \"/api/entry/\" + id;\n}", "function openEntry(id, url) {\n windows.openEntry(id, url, null);\n }", "function openPlayer(id, title) {\n const link = new URL(kinopoiskWatchLink);\n if (id) link.searchParams.set('id', id);\n if (title) link.searchParams.set('title', title);\n\n window.open(link.toString(), '_blank').focus();\n}", "function openEntry(id, url)\r\n {\r\n windows.openEntry(id, url, null);\r\n }", "function openDraft(id) {\n window.location = './editor/?id=' + id;\n}", "function callRecipeURL (recipeID){\n $.ajax({\n url: \"https://api.spoonacular.com/recipes/\" + recipeID +\"/information?includeNutrition=false&apiKey=\"+ APIKey,\n method: \"GET\"\n }).then(function(data) { \n window.open(data.sourceUrl, '_blank') \n }); \n}", "function aditContact(id){\n window.open(\"adit-contact.html?id=\" + id, \"_self\");\n}", "function reqDetailPelanggan(id) {\n window.location.href = baseURL+'pelanggan/'+id;\n }", "function reply_click(clicked_id){\n window.open('movie-details.html?'+clicked_id);\n}", "function openPetPageForPet(petID) {\n window.location.href = './pet-page.html?id=' + petID;\n}", "function detailedimagepage(){\nwindow.open(\n `index2.html#${id1}`,\n '_blank' \n);\n}", "workitemWithId (baseUrl,username,spacename,id){\n browser.get(baseUrl + username + \"/\" + spacename +\"/plan/detail/\" +id);\n }", "function openPost(){\n window.open(\"postASurvey.html\",\"_self\");\n}", "openTour(id) {\n window.location = window.location.origin + `/tours/${id}`;\n }", "function clickEntity(id){\n var host = $window.location.host;\n $window.location.href = \"http://\" + host + \"/entity/\" + id;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function is use to Delete file attachment
function deleteFileAttachment(req, res) { var toDelete; if (req.body.isTemp) { toDelete = {temp_deleted: true}; } else { toDelete = {deleted: true}; } attachmentFile.findOneAndUpdate({_id: req.body.attachmentId}, toDelete).exec(function(err, data) { if (err) { res.json({code: Constant.ERROR_CODE, message: err}); } else { res.json({code: Constant.SUCCESS_CODE, message: Constant.FILE_DELETE, data: data}); } }); }
[ "function deleteAttachment() {\r\n\tsimpleDialog(langOD27, langOD28,null,null,null,langCancel,\r\n\t\t\"$('#div_attach_upload_link').show();$('#div_attach_download_link').hide();$('#edoc_id').val('');enableAttachImgOption(0);\",langDelete);\r\n}", "async deleteAttachment() {\n\t\tif (!this.canDeleteAttachment()) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst action = this._entity.getActionByName('delete');\n\t\tawait performSirenAction(this._token, action);\n\t}", "function deleteAttachmentFn(data) {\n var deferred = $q.defer();\n var url = mailboxConstantsV2.deleteBlob;\n $http.post(url, data)\n .then(function (response) {\n deferred.resolve(response);\n }, function (error) {\n deferred.reject(error);\n });\n return deferred.promise;\n }", "function deleteAttachment(id) {\n console.log(\"prepare for deleting: \" + id);\n \n }", "function deleteAttachment(attachment) {\n openPopup('delete', {}, function (modalResult) {\n if (modalResult == \"Ok\") {\n RequestService.DeleteConditionAttachment(request.RequestID, attachment, function (data) {\n cancelConditionDetailView();\n ReviewService.GetActionItem(request, function (data) {\n conditionData.splice(0, conditionData.length);\n Array.prototype.push.apply(conditionData, data);\n })\n ShowAlert(\n {\n message: 'Attachment Deleted',\n type: \"success\"\n }\n )\n })\n }\n });\n }", "function deleteInvoiceAttachment(url, itemID) {\n var attachment = web.getFileByServerRelativeUrl(url);\n attachment.deleteObject();\n showInvoiceDetails(itemID);\n}", "function deletePOAttachment(url, itemID) {\n var attachment = web.getFileByServerRelativeUrl(url);\n attachment.deleteObject();\n showPODetails(itemID);\n}", "function deleteAttachment(name, req, res) {\n var name = req.params.id\n , attachment = req.params.attachment\n , rev = req.query.rev\n , opts = makeOpts(req);\n\n req.db.removeAttachment(name, attachment, rev, function (err, response) {\n if (err) return sendError(res, err);\n sendJSON(res, 200, response);\n });\n }", "function deleteAttachment(req, res, next) {\n var userId = req.session.user_id;\n var projectId = req.params.project;\n var taskId = req.params.task;\n var attachName = req.params.attachName;\n\n var resource = 'taskAttachment';\n Task.findById(taskId, \"attachments\", function (err, task) {\n if (err) return next(err);\n\n // find attach id by name\n var attachIndex = -1;\n var attachId;\n for (var i = 0; i < task.attachments.length; i++) {\n if (task.attachments[i].filename === attachName) {\n attachIndex = i;\n attachId = task.attachments[i]._id;\n break;\n }\n }\n\n if (attachIndex === -1) return res.send(404).json({error: 'Attachment not found.'});\n\n // if attach.owner === current user than change resource name on 'myTaskAttachment'\n if (task.attachments[attachIndex].owner.equals(userId)) {\n resource = 'myTaskAttachment';\n }\n\n checkRights(projectId, userId, 'delete', resource, function (err) {\n if (err) return res.status(403).json({error: err.message || err});\n\n // remove attachment from fs and db\n task.attachments.id(attachId).remove();\n\n task.save(function(err) {\n if (err) return next(err);\n\n var filePath = path.resolve(basePath, userId, projectId, taskId, 'attachments', attachName);\n fs.unlink(filePath, function (err) {\n // these errors unhandled because db already updated\n if (err) console.error(err);\n res.sendStatus(200);\n });\n });\n });\n });\n}", "function removeattachment(filename)\n{\n //Remove all the temporary uploaded files-----------\n if( $(\"div#temp_uploads_info span\").length > 0 )\n {\n $.ajax({\n url : \"/\"+PROJECT_NAME+\"ChatAttachment/discard-attachments\",\n data: {\n 'files':filename\n },\n type: \"POST\",\n success: function(jsonData) {\n if(jsonData)\n {\n $('span[ts_file_name='+jsonData+']').remove();\n }\n }\n });\n\n };\n\n}", "function removeattachment(filename)\n{\n\t//Remove all the temporary uploaded files-----------\n\tif( $(\"div#temp_uploads_info span\").length > 0 )\n\t{\n\t\t\n\t $.ajax({\n\t url : \"/\"+PROJECT_NAME+\"enquiry/discard-attachments\",\n\t data: {\n\t\t \t'files':filename\n\t\t \t},\n\t type: \"POST\",\n\t success: function(jsonData) {\n\t if(jsonData)\n\t {\n\t \t$('span[ts_file_name='+jsonData+']').remove();\n\t }\n\t }\n\t\t});\n \t\n\t};\n\t\n}", "async deleteAttachmentFiles () {\n\t\tconst files = this.attachments.map(attachment => attachment.path);\n\t\tawait Promise.all(files.map(async file => {\n\t\t\ttry {\n\t\t\t\tawait callbackWrap(FS.unlink, file);\n\t\t\t}\n\t\t\tcatch (error) {\n\t\t\t\tthis.warn(`Unable to delete temp file ${file}: ${error}`);\n\t\t\t}\n\t\t}));\n\t\ttry {\n\t\t\tawait callbackWrap(FS.rmdir, this.attachmentPath);\n\t\t}\n\t\tcatch (error) {\n\t\t\tthis.warn(`Unable to delete temporary directory ${this.attachmentPath}: ${error}`);\n\t\t}\n\t}", "function deleteAttachment(index, id, filename) {\n\tvar r = confirm(\"Are you sure you want to delete the attachment?\");\n\tif (r == true) {\n\t\t//$('div#divDeleteImg').show();\n\t\tibmweb.overlay.show('divDeleteImg');\n\t\t$.ajax({\n\t\t\turl: \"/deleteAttachment\",\n\t\t\ttype: 'GET',\n\t\t\tdata: { id: id, filename: filename },\n\t\t\tcontentType: 'application/json',\n\t\t\tsuccess: function (response) {\n\t\t\t\t//$('div#divDeleteImg').hide();\n\t\t\t\tibmweb.overlay.hide('divDeleteImg');\n\t\t\t\t$('#downloadAttachment' + index).remove();\n\t\t\t\t$('#deleteAttachment' + index).remove();\n var index = docs_id.indexOf(id);\n\t\t\t\tif(index > -1){\n\t\t\t\t\tdocs_id.splice(index,1);\n\t\t\t\t\tnames.splice(index,1);\n\t\t\t\t\tresult.splice(index,1);\n\t\t\t\t\t$(\"#attachIDs\").val(JSON.stringify(result));\n\t\t\t\t\tpopulateDownload(docs_id, names);\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function() {\n\t\t\t\t//$('div#divDeleteImg').hide();\n\t\t\t\tibmweb.overlay.hide('divDeleteImg');\n\t\t\t\talert(\"There was an error when deleting the Attachment\");\n\t\t\t}\n\t\t});\n\t}\n}", "function deleteAttachment(subjectGuid, name, callback) {\n var params, sql;\n\n function complete() {\n mc.replstore.delete_attachment_date(subjectGuid, name);\n if (callback) {\n callback();\n }\n }\n\n function error(tx, e) {\n tx = undefined;\n if (callback) {\n callback(e);\n }\n }\n\n function success(tx, result) {\n tx = undefined;\n result = undefined;\n if (mc.fs.availableForAtts) {\n log.debug('deleteAttachment[fs data] ' + subjectGuid + ' ' + name);\n mc.fs.deleteAttachment(subjectGuid, name, complete, function(e) {\n log.debug('unable to delete data from file system - code ' + e.code);\n complete();\n });\n }\n else {\n complete();\n }\n }\n\n log.debug('deleteAttachment[db/fs] ' + subjectGuid + ' ' + name);\n subjectGuid = mc.db.getSubjectGuid(subjectGuid);\n sql = \"DELETE FROM attachment WHERE subjectGuid=? AND name=?;\";\n params = [subjectGuid, name];\n doTx('transaction', function(tx) {\n tx.executeSql(sql, params, success, error);\n });\n }", "function del(fileObj) {\n fileObj.remove(function() {\n console.log(\"File removed\");\n },\n function(error) {\n console.log(\"Couldn't remove file\", error);\n });\n }", "function removeAttachment(id) {\n $(\"#attachment_link_\" + id).parent().remove();\n}", "function DeleteFile (filename) {\n var temp = {command: \"delete\", filename: filename};\n this.connection.send(JSON.stringify(temp));\n\n //event.preventDefault();\n}", "function deleteFile(fileName) {\n webSocket.send(\"DELETE \" + fileName);\n}", "function deleteFileFromFolder() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get total value by column Id in data island
function getTotalValue(columnId) { var result = 0; var rowid = surchargePointsGrid1.recordset("ID").value; first(surchargePointsGrid1); while (!surchargePointsGrid1.recordset.eof) { var sValue = surchargePointsGrid1.recordset(columnId).value; if (!isEmpty(sValue) && isSignedInteger(sValue)) { result = result + parseInt(sValue); } next(surchargePointsGrid1); } first(surchargePointsGrid1); selectRow("surchargePointsGrid", rowid); return result; }
[ "getValorTotal(){\n var total = 0.0;\n this.itens.forEach(function(item) {\n total += item.getValorTotal();\n });\n\t\treturn total;\n }", "function getPrecioTotal(){\n var precioTotal = 0;\n $(\"#tabla-detalle tbody tr\").each(function(index){\n var precio = $(this).find(\".precio-detalle\").html();\n precioTotal += parseFloat(precio);\n });\n return precioTotal;\n }", "function get_col_total(aTable,strColName)\r\n{\r\n\tvar intTotal = 0;\r\n\tfor(var y=1;y<aTable.rows.length;y++)\r\n\t{\r\n\t\tvar aRow=aTable.rows[y];\r\n\t\t//-- \r\n\t\tintTotal = intTotal + new Number(get_col_value(aRow,strColName));\r\n\t}\r\n\treturn intTotal;\r\n}", "sum(col){\n\tvar sum = 0;\n\tfor(var i = 0; i<this.state.data.rows.length; i++){\n\t\tsum += Number(this.state.data.rows[i].data[col===\"from\"?15:16]);\n\t}\n\treturn sum;\n}", "Sum() {\n let sum = 0;\n for(let i = 0; i < this.__length__; ++i) {\n sum += this.__cells__[this.__indexByID__(i)];\n }\n return sum;\n }", "function total_price(id, arr){\r\n var total = 0;\r\n for (var i=0; i<arr.length; i++){\r\n if (id == arr[i].salesID){\r\n total += arr[i].salesCount* arr[i].itemPrice;\r\n }\r\n }\r\n return total;\r\n}", "function calcTotal(table,column){//To sum up, which column is need to total the table object, the first column starts from 0.\n var trs = table.find(\"tr\");\n var start=1,//ignoring the first line of the head\n end=trs.length-1;//Ignore the last line\n var total=0;\n for(var i=start;i<end;i++){\n var td=trs.eq(i).find('td').eq(column);\n var hoursInput = td.children().first();\n var t=parseFloat(hoursInput.attr('value'));\n if(t)total+=t;\n }\n trs.eq(end).find('td').eq(column).html(\"<span class='col-md-8'>\" + total + \"</span>\");\n }", "function getSum(){\n\treturn pieData.reduce(function(total,item){return total+(+item.val);},0);\n}", "function getTotalData(){\r\n\t \t\t var totalUnitData = 0;\r\n\t \t\t for (var i=0; i<unitValues.length;i++){\r\n\t \t\t\t totalUnitData += unitValues[i]; \r\n\t \t\t }\r\n\t \t\t return totalUnitData;\r\n\t \t }", "async sum (column) {\n const result = await this.startAggregate('sum', [column])\n return result ? result : 0\n }", "calcTotal() {\n let total = 0;\n\n this.pedido.hamburguesas.forEach(hamburguesa => {\n let estePrecio = 0;\n estePrecio += hamburguesa.precio;\n hamburguesa.extras.forEach(ex => {\n estePrecio += ex.estado? ex.precio : 0;\n });\n total += estePrecio * hamburguesa.cantidad;\n });\n\n this.pedido.papas.forEach(papa => {\n total += papa.precio;\n });\n\n this.pedido.gaseosas.forEach(gaseosa => {\n total += gaseosa.precio;\n });\n\n this.pedido.cervezas.forEach(cerveza => {\n total += cerveza.precio;\n });\n return total;\n }", "totalDepositos() {\n let total = 0;\n for (let i = 0; i < this.depositos.length; i++) {\n total += this.depositos[i][1]\n }\n return total;\n }", "function getColumnTotal(column3)\n\t\t{\n\t\t var total;\n\t\t var value = 0;\n\t \t for(var row = 0; row < numRecords; row++) {\n\t\t\tvalue = value + parseInt(records[row][column3]);\n\t \t }\n\t\t return value;\n\t\t}", "function getSum(data, columnName) {\n return d3.sum(data, function(d) {\n return d[columnName];\n })\n}", "getTotal() {\n return basket\n .get(this)\n .reduce((currentSum, item) => item.price + currentSum, 0);\n }", "sum(field) {\n return this.get().reduce((sum, item) => {\n if (typeof item[field] === 'number') {\n sum += item[field];\n }\n return sum;\n }, 0);\n }", "function calculate_sum(){\r\n\tvar total=0;\r\n\t//get all row\r\n\tvar rows=$('#ordersgrid').datagrid('getRows');\r\n\t//traversing\r\n\t$.each(rows,function(i,row){\r\n\t\t//total+=parseFloat(row.money);//addition need convert to number 1. use parseFloat parseInteger parseDouble 2. object*1\r\n\t\ttotal+=(row.money)*1\r\n\t});\r\n\ttotal=total.toFixed(2);\r\n\t//set all row total amount into row footer\r\n\t$('#ordersgrid').datagrid('reloadFooter', [ \r\n\t {\r\n\t\tnum : 'total',\r\n\t\tmoney : total\r\n\t }\r\n\t]);\r\n}", "getTotalValue(){\n\t\tlet sum = 0;\n\t\tfor(let i = 0; i < this.q.length; i++) sum += this.q[i];\n\t\treturn sum;\n\t}", "function fnReadTotal(id) {\n jQuery.ajax({\n type: 'POST',\n url: bittionUrlProjectAndController + 'fnReadTotal',\n dataType: 'json',\n data: {\n id: id\n },\n success: function (response) {\n if (response['total'] === null) {\n jQuery('#spanTotal').text('0.00');\n jQuery('#spanDiscount').text('0.00');\n jQuery('#spanTotalFinal').text('0.00');\n jQuery('#SalSalePaid').val('0.00');\n } else {\n jQuery('#spanTotal').text(response['total']);\n jQuery('#spanDiscount').text(response['discount']);\n jQuery('#spanTotalFinal').text(response['totalAndDiscount']);\n jQuery('#SalSalePaid').val(response['paid']);\n jQuery('#spanDebt').text(response['debt']);\n }\n\n },\n error: function (response, status, error) {\n bittionAjaxErrorHandler(response, status, error);\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main core dispatcher Receives request and response objects Runs installed middlewares globally or depending of the request information (URI, method, etc) After this runs BundleControllerAction depending of the request information Collects returned response from controlleraction and depending of it's contents understands what to do: 1) if it is regular Response class returned then it should be html/... 2) if it is XMLResponse, JSONResponse, NotFoundResponse etc then perform needed content type 3) if helper function of the controller class was used: this.render(), this.echo(), then ... 4) Controller class will have for sure following methods: getRequest() (getHeaders(), getCookie(s), get..) getResponse() (setHeader(s), setCookie(), set..) 5) Controller can throw exception, then depending of exception we'll set response code and render template
dispatcher(req, res) { this.runPreDispatchHooks(req, res); // TODO: run middlewares arranged by priorities // TODO: instantiate request and response singletones // TODO: check what URL and other request information // TODO: find Bundle-Controller-Action situated for request // TODO: if not found Bundle-Controller-Action then show 404 page res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); // TODO: post-dispatch hook }
[ "async dispatch(input) {\n let output;\n try {\n // Execute global request interceptors\n if (this.requestInterceptors) {\n for (const requestInterceptor of this.requestInterceptors) {\n await requestInterceptor.process(input);\n }\n }\n // Dispatch request to handler chain\n output = await this.dispatchRequest(input);\n // Execute global response interceptors\n if (this.responseInterceptors) {\n for (const responseInterceptor of this.responseInterceptors) {\n await responseInterceptor.process(input, output);\n }\n }\n }\n catch (err) {\n output = await this.dispatchError(input, err);\n }\n return output;\n }", "function _handleHTTPRequest(req, res, next) {\n\n //prevent dispatching request if real file exists\n if (fs.existsSync(path.join(app.getAssetsDir(), req.path))) {\n next();\n }\n\n //this flag tells whetever 404 error should be thrown\n var responseSend = false;\n var moduleLoader = app.getModuleLoader();\n app.getMediator().dispatch(self.ON_REQUEST, req, res);\n\n for (var moduleName in moduleLoader.all()) {\n var module = moduleLoader.get(moduleName);\n\n try {\n if (module.onEvent('onRequest', req, res)) {\n responseSend = true;\n break;\n }\n } catch (e) {\n app.getMediator().dispatch(self.ON_ERROR, e, req, res);\n return;\n }\n }\n\n if (!responseSend) {\n app.getMediator().dispatch(self.ON_HANDLER_NOT_FOUND, req, res);\n return;\n }\n }", "function controller(response,pathname,postData) {\n var patharray=pathname.split('/');\n patharray=patharray.slice(1,patharray.length);\n console.log(\"router/controller : request controller for /\" + patharray.join('/'));\n //console.log(\"patharray : \"+patharray.join(' | ')+\"\\npatharray.length : \"+patharray.length);\n var requireModule=\"\";//This will save the controller to be load\n if(patharray[0]==\"\"){//if empty we load the index\n\trequireModule=require.resolve('./controller/index');\n }\n else{\n\ttry{//try to see if the controller of patharray[0] exist \n\t console.log(\"controller exists \"+require.resolve('./controller/'+patharray[0]));\n\t requireModule=require.resolve('./controller/'+patharray[0]);\n\t}\n\tcatch(e){//if not we send back the error controller\n\t requireModule = require.resolve('./controller/error');\n\t patharray=[];\n\t}\n }\n var controller=require(requireModule);//require the controller found just before\n if(patharray.length<2){\n\t//if there is no function asked in patharray we call the 'create' function, which send the view without args\n\tconsole.log(\"router/controller : create without args \"+patharray[0]);\n\tcontroller.create(response,[]);\n }\n else if(typeof controller[patharray[1]]==='function'){\n\t//if there is a function asked and it exist we call it with the rest of path array as args\n\tconsole.log(\"router/controller : call \"+patharray[1]+\" of \"+patharray[0]);\n\tcontroller[patharray[1]](response,patharray.slice(2,patharray.length),postData);\n }\n else{//if it's not a function we call the function create with the rest of the patharray\n\tconsole.log(\"router/controller : create with args \"+patharray.join('/'));\n\tcontroller.create(response,patharray.slice(2,patharray.length));\n }\n}", "async dispatch(args, httpCallback, dispatchMap, regex) {\n\t\tconst method = args.request.method.toLowerCase();\n\t\t// First find mappings the the HTTP method (GET, POST, etc.)\n\t\tif (dispatchMap.has(method)) {\n\t\t\tconst matches = args.request.url.match(regex);\n\t\t\t\n\t\t\t// Next see if we have an endpoint that handles the operation for the extracted object\n\t\t\tif (matches && matches.length > 1 && dispatchMap.get(method).has(matches[1])) {\n\t\t\t\tconst endpoint = dispatchMap.get(method).get(matches[1]);\n\t\t\t\tconst destArgs = (method == 'get') ? args.query : args.params;\n\t\t\t\t\n\t\t\t\tthis.logger.debug(8, \"Dispatching HTTP call for \" + args.request.url, destArgs);\n\t\t\t\tlet results = null;\n\t\t\t\tlet err = null;\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\t// If the endpoint has a validator pass the input arguments into that\n\t\t\t\t\tlet isValid = true;\n\t\t\t\t\tif (endpoint.validate) {\n\t\t\t\t\t\tconst validation = endpoint.validate(destArgs, args); // Method name is passed first by earlier binding\n\t\t\t\t\t\tif (validation!==true) {\n\t\t\t\t\t\t\tisValid = false;\n\t\t\t\t\t\t\terr = validation;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (isValid) {\n\t\t\t\t\t\t// Validation passed, attempt to call the handler\n\t\t\t\t\t\tresults = await endpoint.handler(destArgs, args);\n\t\t\t\t\t\tthis.logger.debug(8, \"Results of HTTP call for \" + args.request.url, results);\n\t\t\t\t\t}\n\n\t\t\t\t\tresults = PixlRestify.getResponseObject(err, results);\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tresults = PixlRestify.getResponseObject(e, null);\n\t\t\t\t\tthis.logger.error(e.code, \"Error calling \" + args.request.url, {err: results, stack: (e.stack)?JSON.stringify(e.stack):\"\"});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\thttpCallback(results);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst message = \"No handler found for URI: \" + args.request.url;\n\t\t\t\tthis.logger.debug(5, `PixlRestify.dispatch error ${message}`);\n\t\t\t\thttpCallback({code: 'no_handler', message: message} );\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconst message = \"unsupported method: \" + method + \" url: \" + args.request.url;\n\t\t\tthis.logger.debug(5, `PixlRestify.dispatch error ${message}`);\n\t\t\thttpCallback({code: 'unsupported_method', message: message} );\n\t\t}\n\t}", "function doResponse(req, res, next) {\n\n // If we are in install mode, and are not in the installation process, then redirect\n if (!calipso.config.get('installed') && !req.url.match(/^\\/admin\\/install/)) {\n calipso.silly(\"Redirecting to admin/install ...\");\n calipso.app.doingInstall = true;\n res.redirect(\"/admin/install\");\n return;\n }\n\n // If nothing could be matched ...\n if (!res.routeMatched) {\n calipso.log(\"No Calipso module routes matched the current URL \" + req.url);\n res.statusCode = 404;\n }\n\n // Render statuscodes dealt with by themeing engine\n // TODO - this is not very clean\n calipso.silly(\"Responding with statusCode: \" + res.statusCode);\n if (res.statusCode === 404 || res.statusCode === 500 || res.statusCode === 200 || res.statusCode === 403) {\n\n calipso.theme.render(req, res, function (err, content) {\n\n if (err) {\n\n // Something went wrong at the layout, cannot use layout to render.\n res.statusCode = 500;\n res.send(500, \"<html><h2>A fatal error occurred!</h2>\" + \"<p>\" + (err.xMessage ? err.xMessage : err.message) + \"</p>\" + \"<pre>\" + err.stack + \"</pre></html>\");\n req.routeComplete(res);\n\n } else {\n\n res.setHeader('Content-Type', 'text/html');\n // Who am I?\n res.setHeader('X-Powered-By', 'Calipso');\n\n // render\n res.send(content);\n\n // Callback\n req.routeComplete(res);\n\n }\n\n });\n\n } else {\n\n // Otherwise, provided we haven't already issued a redirect, then pass back to Express\n req.routeComplete(res);\n\n }\n\n}", "function dispatchRequest(request, response)\n{\n try {\n //Dispatch\n dispatcher.dispatch(request, response);\n }\n catch (e) {\n console.log(e);\n }\n}", "function dispatchRequest(request, response)\n{\n try {\n //Dispatch\n dispatcher.dispatch(request, response);\n\n }\n catch (e) {\n logger.log(e)\n }\n}", "function controllers (event, res){\r\n\t\r\n\tvar endPoint = event._parsedUrl.path.split('/')[1];\r\n\tconsole.log(' -- calling_controller: ' + './controllers/' + endPoint + '.js' + ' -- event.method: ' + event.method);\t\r\n\t\r\n\ttry{\r\n\t\tvar controller = require('./controllers/' + endPoint + '.js');\r\n\t\tvar models = require('./models/' + endPoint + '.js');\r\n\t}\r\n\tcatch(err){\r\n\t\tres.status(404).send({message: 'Not Found, please check url'});\r\n\t}\t\r\n\tcontroller[event.method](event, endPoint, models, res);\r\n}", "function main(req, res, parts, respond) {}", "function applicationRouteHandler(request, reply) {\n /**\n * Here is the most straight-forward use-case, a simple one-page\n * app without any client-side routing. A simple app such as this\n * will have a single set of data (one aggregated API call) and one\n * parent component to render.\n *\n * If you require multiple client-side routes, each route with its\n * own data needs, see this recipe:\n * https://github.homeawaycorp.com/Catalyst/recipes/tree/master/multiRouteWithData\n **/\n\n // Read the data (a call that aggregates multiple other calls)\n pageApi.read(request).then((results) => {\n // Create redux store\n const store = createStore();\n\n // Dispatch to populate the store\n store.dispatch(actions.fetchPage1DataSuccess(results));\n\n const startRender = Date.now();\n\n // Render react UI based on route and data\n const body = ReactDOMServer.renderToString(\n <Provider store={store}>\n <Page1Container/>\n </Provider>\n );\n\n // Log server-side render times to logs and DataDog\n const renderTime = Date.now() - startRender;\n request.log(['perf'], `name=\\'reactRenderToString\\' url='\\${request.url.pathname}\\' elapsed=${renderTime}`);\n request.server.app.metrics.histogram('serverSideRenderTime').update(renderTime);\n\n // Serialize the state to protect against XSS attacks when inserted into the page\n const initialState = serialize(store.getState(), {isJSON: true});\n\n // Get site info (name, locale, brandId, humanReadableName, hosts)\n const site = request.plugins.SiteResolution.site;\n const lang = site.locale.substring(0, 2);\n\n // build and return the page\n return reply.view('index.hbs', {\n body,\n lang,\n initialState,\n analyticsDataLayer: getAnalyticsDataLayer({site, pagename: 'xxxxx'}),\n siteName: site.name\n });\n }).catch((err) => {\n request.log(['error'], `Read failure resulted in error page: '${err.message || ''}'. Stack: ${err.stack || ''}`);\n // TODO: Response HTML should be localized, or we should be directing the user somewhere that is.\n let responseHtml = `\n <h1>Sorry we'll be right back</h1>\n <p>Something unexpected happened and we're fixing it.</p>\n `;\n if (environment.getName() !== 'production') {\n responseHtml = `\n <h1>Error: ${err.message}</h1>\n <code>${err.stack.replace(/\\n/g, '<br/>').replace(/\\s{4}/g, '&nbsp;&nbsp;&nbsp;&nbsp;')}</code>\n `;\n }\n return reply(responseHtml).code(500);\n });\n}", "initControllers()\n\t\t{\n\t\t\trequire(\"./StarRegistryServiceController.js\")(this.server)\n\t\t}", "function initRender() {\n var allFetchPromises = [// DATA: COMMONS DATA FOR THE APP\n // in some simple app, we might need to call all data for one time only\n // thus, DATA_FOR_APP will be very suitable\n store.dispatch(actions.getData('DATA_FOR_APP'))];\n routeConfig(store.getState().auth.isLoggedIn).some(function (route) {\n var match = matchPath(req.path, route);\n\n if (match && !!route.loadData) {\n // DATA: DATA FOR EACH ROUTE\n // in complex app, each route is a small app in our whole app\n // thus, it might need special data for only it\n // calling Data for Route in server side here in combination with\n // calling Data for Route in client side in App (see Components/App.js)\n allFetchPromises.push(store.dispatch(route.loadData()));\n }\n\n return match;\n }); // WHEN COMMONS DATA AND SPECIFIC DATA ARE SOLVED\n // Mean that we have the store ready to render React app\n // Do all the server DOM content rendering and sending out here\n\n _utils.default.whenAllPromisesFinish(allFetchPromises, function (eachResponse) {\n return eachResponse ? eachResponse.data : null;\n }).then(function (allResults) {\n // console.log(allResults);\n var content = ReactDOMServer.renderToString(React.createElement(ServerRouter, {\n store: store,\n registry: registry,\n location: req.url,\n context: context,\n randomSeed: randomSeed\n }));\n var state = store.getState(); // Inject store data to HTML content so\n // Client side can generate a store in initial phase with those data\n // Thus, the store from client will be matched with store from server\n\n result = result.replace('/*-STATIC-CONTENT-*/', content);\n result = result.replace('/*-MUI-CSS-*/', registry.toString());\n result = result.replace('\"/*-USER-*/\"', JSON.stringify(state.auth));\n result = result.replace('\"/*-DATA-*/\"', JSON.stringify(state.data)); // Send out response\n\n res.status(200).set('content-type', 'text/html').send(result); // End Request Response\n\n return res.end();\n });\n }", "render(controller, view) {}", "function dispatch(req) {\n\t\t// sanity check\n\t\tif (!req) { throw \"no req param provided to request\"; }\n\n\t\t// sane defaults\n\t\treq.headers = req.headers || {};\n\t\treq.query = req.query || {};\n\n\t\t// dispatch behavior override\n\t\t// (used by workers to send requests to the parent document for routing)\n\t\tif (customRequestDispatcher) {\n\t\t\treturn customRequestDispatcher(req);\n\t\t}\n\n\t\t// parse the url\n\t\t// (urld = url description)\n\t\tif (req.url) {\n\t\t\treq.urld = Link.parseUri(req.url);\n\t\t} else {\n\t\t\treq.urld = Link.parseUri(Link.joinUrl(req.host, req.path));\n\t\t}\n\t\tif (!req.urld) {\n\t\t\tthrow \"no URL or host/path provided in request\";\n\t\t}\n\n\t\t// prepend host on relative path\n\t\tif (!req.urld.protocol) {\n\t\t\treq.url = window.location.protocol + \"//\" + window.location.host + req.url;\n\t\t\treq.urld = Link.parseUri(req.url);\n\t\t}\n\n\t\t// execute according to protocol (asyncronously)\n\t\tvar resPromise = promise();\n\t\tif (req.urld.protocol == 'httpl') {\n\t\t\tsetTimeout(function() { __dispatchLocal(req, resPromise); }, 0);\n\t\t} else if (req.urld.protocol == 'http' || req.urld.protocol == 'https') {\n\t\t\tsetTimeout(function() { __dispatchRemote(req, resPromise); }, 0);\n\t\t} else {\n\t\t\tresPromise.fulfill(new ResponseError({ status:0, reason:'unsupported protocol \"'+req.urld.protocol+'\"' }));\n\t\t}\n\t\treturn resPromise;\n\t}", "function WebApp() {\r\n\r\n // Collection of route mappings that map URL patterns to views\r\n this.routeMappings = [];\r\n\r\n // I am the collection of controllers. All controllers are intended to be\r\n // singleton instances.\r\n this.controller = null;\r\n\r\n\t\t// an application can register some helper methods here to be used in\r\n\t\t// templates, <%=webapp.helpers.format_date(this.date) %>, for example\r\n\t\tthis.helpers = {};\r\n\r\n /// validation rules to be used with forms\r\n this.validation_rules = {\r\n };\r\n\r\n // appended to all rest URLs. if specified, should not\r\n // end with a slash\r\n this.rest_service_prefix = '';\r\n this.templates_prefix = '/t/';\r\n this.forms_prefix = '/forms/';\r\n\r\n\r\n this.pageNotFoundView = undefined;\r\n\r\n\t\tthis.isRunning = false;\r\n\r\n this.visitedUrlsLog = [];\r\n\r\n this.testmode = false; // do not show error dialogs when running in testmode\r\n\r\n this.after_view_fully_loaded = null;\r\n\r\n this.xhr_id = 0;\r\n this.currently_active_xhrs = {};\r\n\r\n this.flash_messages = [];\r\n\r\n this.request_cache = {};\r\n this.request_cache_by_type = {};\r\n this.served_cached_requests = 0;\r\n this.served_total_requests = 0;\r\n\r\n /*\r\n Stores \"precognition\" data - the info about the server state\r\n the client knows without actually loading the data from the server.\r\n See 'Minority Report' for details\r\n */\r\n this.precog_cache = {};\r\n\r\n this.compiled_templates = {};\r\n\r\n this.showMessage = function (msg, title) {\r\n /*\r\n Displays a message - a nicer replacement for\r\n alert function\r\n */\r\n if (title) {\r\n msg = '<h1>' + title + '</h1>' + msg;\r\n }\r\n bootbox.alert(msg);\r\n };\r\n\r\n /* The code above is executed before the DOM is loaded so we need to\r\n postpone registering the error handlers until later\r\n */\r\n $(function () {\r\n\r\n $.ajaxSetup({\r\n beforeSend: function (jqXHR, settings) {\r\n jqXHR._url = settings.url;\r\n jqXHR._start = new Date();\r\n },\r\n success: function (data, textStatus, jqXHR) {\r\n webapp._addRequestStats(data, textStatus, jqXHR);\r\n }\r\n });\r\n /// Ajax spinner\r\n //$(\"body\").append($('<div id=\"ajax-spinner\" class=\"flash-message flash-message-normal\">Loading...</div>'));\r\n\r\n $(\"body\").append($('<div id=\"ajax-error\"> </div>'));\r\n\r\n /// Experiment with using Bootstrap's modal dialog\r\n /*$(\"body\").append($('<div id=\"ajax-error\" class=\"modal hide fade\"><div class=\"modal-header\">' +\r\n '<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>' +\r\n '<h3>Server Error</h3></div>' +\r\n '<div class=\"modal-body\"></div>' +\r\n '<div class=\"modal-footer\">' +\r\n '<button class=\"btn\" data-dismiss=\"modal\" aria-hidden=\"true\">Close</button>' +\r\n '</div></div>'\r\n ));*/\r\n\r\n $(document).ajaxSend(function (e, jqx) {\r\n /* add an unique ID to an XHR so we can tell them apart later */\r\n webapp._rememberXHR(jqx);\r\n });\r\n\r\n $(document).ajaxComplete(function (e, jqx) {\r\n /* Called both on success and error */\r\n webapp._forgetXHR(jqx);\r\n });\r\n\r\n $(document).ajaxSuccess(function (e, jqx) {\r\n // TODOXXX: this parses .responseText to JSON\r\n // second time - it's inefficient but I wasn't\r\n // able to find how to get json data from ajaxSuccess\r\n var data;\r\n try {\r\n /*\r\n Arrgh, Firebug sometimes breaks here regardless of the try/except block\r\n Let's really crudely check if the response looks like JSON and bail out\r\n if it doesn't\r\n */\r\n if (jqx.responseText && jqx.responseText[0] === '{') {\r\n data = $.parseJSON(jqx.responseText);\r\n }\r\n } catch (exc) {\r\n // pass\r\n }\r\n\r\n webapp.processFlashMessages(data, jqx);\r\n });\r\n\r\n\r\n /*$(document).ajaxError(function (e, jqx) {\r\n webapp._forgetXHR(jqx);\r\n });*/\r\n\r\n $('#ajax-spinner').ajaxStart(function () {\r\n $(this).fadeIn();\r\n });\r\n $('#ajax-spinner').ajaxStop(function () {\r\n $(this).fadeOut();\r\n });\r\n $('#ajax-spinner').ajaxError(function () {\r\n $(this).fadeOut();\r\n });\r\n $('#ajax-spinner').ajaxComplete(function () {\r\n $(this).fadeOut();\r\n });\r\n /// Error message box\r\n $(document).ajaxError(function (event, jqxhr, ajaxOptions, thrownError) {\r\n\r\n var self = this,\r\n response,\r\n show_alert = function (msg) {\r\n webapp.flash_messages.push({\r\n css_class: 'flash-message-error',\r\n msg: msg\r\n });\r\n\r\n // process the messages right away\r\n if (webapp.getController().currentView.renderFlashMessages) {\r\n webapp.getController().currentView.renderFlashMessages();\r\n }\r\n };\r\n\r\n /* aborted calls trigger ajaxError too - we don't want to\r\n display any messages obviously. Also, responseText is null for\r\n such responses and status = 0.\r\n */\r\n if (jqxhr.statusText == 'abort') {\r\n return;\r\n }\r\n\r\n /*\r\n calling code can set `ignore_errors` attribute to signal\r\n that errors are expected and are handled by the calling code\r\n */\r\n if (jqxhr.ignore_errors) {\r\n return;\r\n }\r\n\r\n response = jqxhr.responseText.replace(new RegExp(\"/_debug/media/\", \"g\"), \"/webapp.client/weberror/\");\r\n\r\n\r\n if (ajaxOptions.webapp_error_response_processed) {\r\n return;\r\n }\r\n\r\n if (!webapp.testmode) {\r\n\r\n /* this one should work in debug mode too */\r\n if (jqxhr.status === 422) {\r\n window.location.reload(true);\r\n return;\r\n }\r\n\r\n /* When debug mode is on the messages are very long,\r\n so we use it to crudely distinquish between when we want to\r\n show a generic message or a traceback */\r\n if (response.length > 400) {\r\n show_alert(response);\r\n } else {\r\n switch (jqxhr.status) {\r\n case 410:\r\n /*\r\n When a resource is soft-deleted the server sends 410 Gone\r\n with a small JSON dict with a `message` attribute\r\n */\r\n show_alert(JSON.parse(response).message);\r\n webapp.relocateTo(webapp.previousPageUrl());\r\n break;\r\n case 422:\r\n /* otherwise it shows a default message momentarily */\r\n break;\r\n case 500:\r\n show_alert(\"There's been a server error. Our engineers have been notified.\");\r\n break;\r\n case 502:\r\n show_alert(\"The site is down. Please try again later.\");\r\n break;\r\n default:\r\n show_alert(\"Can't connect to the site. Please check your internet connection.\");\r\n break;\r\n\r\n }\r\n }\r\n\r\n } else {\r\n //alert(response);\r\n webapp.getController().showMainView(webapp.serverErrorView, webapp.getController().currentView.event);\r\n $(\"div.activeContentView\").html(response);\r\n }\r\n // This was here to deal with deleted tasks,\r\n // but it produces undesirable effects in other places\r\n // webapp.relocateTo(webapp.previousPageUrl());\r\n });\r\n\r\n });\r\n\r\n /// TODO: Not sure it belongs here\r\n $.fn.serializeObject = function () {\r\n /// This creates a custom function which\r\n /// serializes a form into an object which\r\n /// can easily be converted to JSON representation\r\n /// TODO: not sure how robust this is with multiple values\r\n /// See http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery\r\n var o = {},\r\n a = this.serializeArray();\r\n\r\n $.each(a, function () {\r\n // remove formish templates - template's name contains *\r\n if (this.name.indexOf('*') === -1) {\r\n if (o.hasOwnProperty(this.name)) {\r\n /* If the property already exists then we check\r\n if it's an array already, if not we're converting it\r\n to an array and then we append the value\r\n */\r\n if (!o[this.name].push) { /* 'push' is how we tell Array from something else */\r\n o[this.name] = [o[this.name]];\r\n }\r\n o[this.name].push(this.value || '');\r\n } else {\r\n o[this.name] = this.value || '';\r\n }\r\n }\r\n });\r\n\r\n /// unchecked checkboxes are not serialized by serializeArray\r\n /// which conforms to HTML standards but is quite annoying\r\n /// we send 'false' if a checkbox is unchecked\r\n /// but only if there's no already a value (a scalar or an array)\r\n /// for that name.\r\n\r\n $.each(this.find('input:checkbox').not(':checked'), function () {\r\n if (!o.hasOwnProperty(this.name)) {\r\n o[this.name] = false;\r\n }\r\n });\r\n\r\n /// make empty multiselects to return [] - otherwise they're ignored\r\n /// also, for multiselects we convert single values to arrays with one element\r\n $.each(this.find('select'), function () {\r\n var s = $(this);\r\n if (s.attr(\"multiple\")) {\r\n if (s.val() === null) {\r\n o[this.name] = [];\r\n } else if (typeof s.val() === \"string\") {\r\n o[this.name] = [o[this.name]];\r\n }\r\n }\r\n });\r\n\r\n return o;\r\n };\r\n\r\n\t}", "function controllerizer(req, res, next) {\n // returning null from a controller implies a 404\n if (res.promise === null) {\n res.status(404).json('Not Found')\n }\n\n // Either nothing was returned, or it wasn't then-able, so pass it up the chain\n if (res.promise === undefined || !res.promise.then) {\n return next();\n }\n\n res.promise\n .then(body => {\n // Something else has started to return to the client\n if (res.headersSent) return next();\n // Otherwise, send the return value\n res.json(body);\n })\n .catch(err => {\n next(err);\n })\n }", "rest(...args) {\n if (!_.isString(args[0])) {\n throw new Error('first argument of router.rest must be string');\n } \n const url = args[0];\n const controllers = args[args.length - 1];\n if (!_.isObject(controllers)) {\n throw new Error('need rest controllers');\n }\n const middlewares = args.slice(1, args.length - 1);\n if (controllers.list) {\n this.get(url, ...middlewares.map(m => _.isObject(m) ? m.list : m).filter(m => !!m).concat(controllers.list));\n }\n if (controllers.create) {\n this.post(url, ...middlewares.map(m => _.isObject(m) ? m.create : m).filter(m => !!m).concat(controllers.create));\t\t\t\n }\n if (controllers.update) {\n this.put(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.update : m).filter(m => !!m).concat(controllers.update));\n }\n if (controllers.remove) {\n this.del(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.remove : m).filter(m => !!m).concat(controllers.remove));\t\t\t\n }\n if (controllers.view) {\n this.get(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.view : m).filter(m => !!m).concat(controllers.view));\t\t\t\t\t\t\n }\n return this;\n }", "async function setupPostControllerActions() {\n logger.trace('APP:: Setting up post-controller actions');\n\n /**\n * Post-controller failed request handler\n */\n httpApp.use((err, req, res, next) => {\n logger.trace('APP:: Handling controller error.');\n logger.error(`APP:: ERROR: ${JSON.stringify(err)}`);\n let errors = [];\n /* Handle Swagger Errors */\n if (err.failedValidation === true) {\n errors.push({\n error: err.message,\n });\n if (err.results) {\n for (let e of err.results.errors) {\n errors.push({\n error: e.message,\n });\n };\n }\n /* Set 400 for Swagger validation error. */\n res.status(400);\n } else if (err.forbidden) {\n errors.push(err);\n /* Set 403 for Forbidden. */\n res.status(403);\n } else if (err.notFound) {\n errors.push(err);\n /* Set 404 for Not Found. */\n res.status(404);\n } else if (err.allowedMethods) {\n errors.push(err);\n /* Set 405 for Method Not Allowed error. */\n res.status(405);\n } else {\n errors.push({\n error: 'Internal Server error occurred. ',\n });\n /* Set 500 for otherwise unhandled error. */\n res.status(500);\n }\n /* Send response to user. */\n res.json({\n errors: errors,\n });\n logger.trace('APP:: Controller error handled.');\n next();\n });\n\n logger.trace('APP:: Established post-controller actions');\n}", "function handleRequests(request, response){\n\n // Parse the request containing file name\n // assuming url.parse sanitized pathname\n var url_parts = url.parse(request.url, true);\n\n var pathname = url_parts.pathname;\n request.query = url_parts.query;\n\n //swtich statement to handle simple routes\n switch(pathname){\n case '/':\n routes.index(request, response);\n break;\n case '/logout':\n routes.logout(request, response);\n break;\n case '/login':\n if(request.method == 'POST') {\n processPost(request, response,routes.post_login);\n }else{\n routes.login(request, response);\n }\n break;\n //------------------------------------------------------------------------\n case '/retrieve':\n if(request.method == 'POST') {\n processPost(request, response,routes.post_retrieve);\n }else{\n routes.retrieve(request, response);\n }\n\n break;\n\n case '/create':\n if(request.method == 'POST') {\n processPost(request, response,routes.post_create);\n }else{\n routes.create(request, response);\n }\n break;\n\n\n case '/delete':\n if(request.method == 'POST') {\n processPost(request, response,routes.post_delete);\n }else{\n routes.modify(request, response);\n }\n break;\n\n case '/modify':\n if(request.method == 'POST') {\n processPost(request, response,routes.post_modify);\n }else{\n routes.modify(request, response);\n }\n break;\n\n //------------------------------------------------------------------------\n case '/list':\n routes.list(request, response);\n break;\n\n\n //------------------------------------------------------------------------\n\n default:\n routes.fourohfour(request, response);\n }\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new frame aligned to right of other
rightOf(other) { return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height); }
[ "rightOf(other) {\n return new Frame(other.origin.x + other.size.width, this.origin.y, this.size.width, this.size.height);\n }", "leftOf(other) {\n return new Frame(other.origin.x - this.size.width, this.origin.y, this.size.width, this.size.height);\n }", "leftOf(other) {\n return new Frame(other.origin.x - this.size.width, this.origin.y, this.size.width, this.size.height);\n }", "bottomOf(other) {\n return new Frame(this.origin.x, other.origin.y + other.size.height, this.size.width, this.size.height);\n }", "bottomOf(other) {\n return new Frame(this.origin.x, other.origin.y + other.size.height, this.size.width, this.size.height);\n }", "right() { \n function alignRight(alignmentStack) {\n alignmentStack.addSpacer()\n let returnStack = alignmentStack.addStack()\n return returnStack\n }\n this.currentAlignment = alignRight \n }", "set right(right) {\n this._frame.origin.x = Math.round(right - this.width);\n }", "topOf(other) {\n return new Frame(this.origin.x, other.origin.y - this.size.height, this.size.width, this.size.height);\n }", "topOf(other) {\n return new Frame(this.origin.x, other.origin.y - this.size.height, this.size.width, this.size.height);\n }", "putRight(b, xOffset = 0, yOffset = 0) {\n let a = this;\n b.x = (a.x + a.width) + xOffset;\n b.y = (a.y + a.halfHeight - b.halfHeight) + yOffset;\n }", "function addAlignment(x, y) {\n var j;\n frameBuffer[x + width * y] = 1;\n for (j = -2; j < 2; j++) {\n frameBuffer[(x + j) + width * (y - 2)] = 1;\n frameBuffer[(x - 2) + width * (y + j + 1)] = 1;\n frameBuffer[(x + 2) + width * (y + j)] = 1;\n frameBuffer[(x + j + 1) + width * (y + 2)] = 1;\n }\n for (j = 0; j < 2; j++) {\n setMask(x - 1, y + j);\n setMask(x + 1, y - j);\n setMask(x - j, y - 1);\n setMask(x + j, y + 1);\n }\n }", "putRight(b, xOffset = 0, yOffset = 0) {\n let a = this\n b.x = (a.x + a.width) + xOffset\n b.y = (a.y + a.halfHeight - b.halfHeight) + yOffset\n }", "putRight(b, xOffset = 0, yOffset = 0) {\n let a = this;\n b.x = (a.x + a.width) + xOffset;\n b.y = (a.y + a.halfHeight - b.halfHeight) + yOffset;\n }", "centerHorizontalOf(other) {\n return new Frame(other.origin.x + (other.size.width - this.size.width) / 2, this.origin.y, this.size.width, this.size.height);\n }", "centerHorizontalOf(other) {\n return new Frame(other.origin.x + (other.size.width - this.size.width) / 2, this.origin.y, this.size.width, this.size.height);\n }", "centerVerticalOf(other) {\n return new Frame(this.origin.x, other.origin.y + (other.size.height - this.size.height) / 2, this.size.width, this.size.height);\n }", "function createRightSideContainer() {\n let rightSideWrapper = createElement('p', 'cam-text', 'cam-id', camWrap);\n setText(rightSideWrapper, 'Camera Setup <br/><br/> Align the Cameras with the rectangles.');\n return rightSideWrapper;\n }", "function alignRight(alignmentStack) {\n alignmentStack.addSpacer()\n let returnStack = alignmentStack.addStack()\n return returnStack\n }", "centerVerticalOf(other) {\n return new Frame(this.origin.x, other.origin.y + (other.size.height - this.size.height) / 2, this.size.width, this.size.height);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1 is push, 2 is pull and 3 is print min and max
function minMax(arr){ const stack = new MinMaxStack() let command, int for(let i = 0, len = arr.length; i < len; i++){ [command, int] = arr[i] switch(command){ case '1': console.log('adding ', int) stack.push(int) break; case '2': console.log('removing ', stack.peak()) stack.pull() break; case '3': console.log('max is: ', stack.currentMax()) console.log('min is: ', stack.currentMin()) break; default: console.log('Wrong command') } } }
[ "function getPopRange(input) {\n var mx = document.getElementById('hiPop').innerHTML;\n document.getElementById('popden_range').max = mx;\n var mn = document.getElementById('lowPop').innerHTML;\n document.getElementById('popden_range').min = mn;\n var unit = (mx - mn) / 100;\n document.getElementById('popden_range').step = unit;\n filterPopData(input);\n}", "range() {\n if (this.isEmpty()) {\n return \"-\";\n }\n let rover = this.head;\n let max = rover.data, min = rover.data;\n while (rover.next !== null) {\n rover = rover.next;\n if (rover.data > max) {\n max = rover.data;\n }\n if (rover.data < min) {\n min = rover.data;\n }\n }\n return min + \"-\" + max;\n }", "function findMinAndMax(arr){\n var result=\"\";\n var minNumber=arr[0];\n var maxNumber=arr[0];\n var i;\n var length=arr.length;\n \n for(i=0; i<length; i++){\n if(minNumber>arr[i]){\n minNumber=parseInt(arr[i]);\n }\n if(maxNumber<=arr[i]){\n maxNumber=parseInt(arr[i]);\n }\n }\n \n result=\"Min-> \"+minNumber+\"</br>\"+\"Max-> \"+maxNumber;\n document.getElementById('content').innerHTML =result;\n }", "function highAndLow(numbers) {\n numbers = numbers.split(\" \").map(Number);\n console.log('numbers:: ', numbers);\n console.log('max and min:: ', `${Math.max(...numbers)} ${Math.min(...numbers)}`);\n return `${Math.max(...numbers)} ${Math.min(...numbers)}`;\n\n\n}", "function findMinAndMax(value) {\r\n 'use strict';\r\n function isBigger(firstNumber, secondNumber) {\r\n return firstNumber - secondNumber;\r\n }\r\n\r\n value.sort(isBigger);\r\n console.log('Min -> ' + value[0]);\r\n console.log('Max -> ' + value[value.length - 1]);\r\n}", "findMinMax()\n {\n for(let i = 0; i <= this.numbers.length; i++)\n {\n if(this.maxVar<=this.numbers[i])\n {\n this.maxVar=this.numbers[i];\n }\n else if(this.minVar>=this.numbers[i])\n {\n this.minVar=this.numbers[i];\n \n }\n }\n console.log('The Min Value: '+this.minVar);\n console.log('The Max Value: '+this.maxVar);\n }", "function printLowReturnHigh(arr) {\r\n var min = arr[0];\r\n var max = arr[0];\r\n for (var i = 1; i < arr.length; i++) {\r\n if (arr[i] > max) max = arr[i];\r\n if (arr[i] < min) min = arr[i];\r\n }\r\n console.log(min);\r\n return max;\r\n}", "function pull(num=undefined, to_num=undefined, percent=undefined) {\n var pullee;\n if (typeof num === \"object\") {\n // if num is an object, we assume its a pullee object and thus should contain all the other arguments we need already\n pullee = {};\n // lets create a new object from that pullee, so we do not change any of the original pullee's values\n pullee = Object.create(num);\n num = pullee.current;\n // if to_num was also passed in, lets assume its the direction (puller) \n if (to_num!==undefined){\n if ((typeof to_num===\"string\") && (to_num===\"max\" || to_num===\"min\" || to_num===\"reverse\")){\n if (to_num===\"reverse\"){\n // we want to pull in the reverse direction specified in the pullee\n let reversable=false;\n pullee.puller===\"max\"?reversable=\"min\":null;\n pullee.puller===\"min\"?reversable=\"max\":null;\n if (reversable!==false){\n pullee.puller=reversable;\n }\n } else {\n // if the value is max, or min, we will use that as the puller\n pullee.puller=to_num;\n }\n // so we grab the number stored in that direction, and place it into to_num\n to_num = pullee[pullee.puller];\n } else if (typeof to_num===\"number\") {\n // if its not max, min, and is a number type, we will use it as is\n } else if (typeof to_num===\"string\") {\n // if its not max, min, nor a number type, perhaps its a unique property that is on the pullee object\n if (pullee[to_num]!==undefined){\n // Indeed there appears to be a property under the to_num name! \n pullee.puller=to_num;\n to_num = pullee[pullee.puller];\n } else {\n // we cant find a property by the name of the string, and all other methods have failed\n // the 2nd parameter must have been passed in by mistake, so we must use the puller specified by the object\n to_num = pullee[pullee.puller]; \n }\n } else {\n // to_num was defined but we cant identify what it is, defaulting to the pullee's defined puller\n to_num = pullee[pullee.puller];\n }\n } else {\n // to_num was not passed in, meaning we want to use the objects puller to get the number we are pulling toward\n // But first we need to check the polarity of the pullee to see if we need to do the inverse\n // We should only use the objects polarity when we are also using the objects puller (not a unique to_num argument)\n if (pullee.reversed===true && (pullee.puller===\"max\" || pullee.puller===\"min\")){\n // polarity is reversed, however we can only reverse from min to max and vice versa\n let reversable=false;\n pullee.puller===\"max\"?reversable=\"min\":null;\n pullee.puller===\"min\"?reversable=\"max\":null;\n if (reversable!==false){\n pullee.puller=reversable;\n }\n }\n to_num = pullee[pullee.puller];\n }\n // if a percent was passed in as well, then we will use it instead of the one supplied by the pullee object\n if (percent!==undefined){\n // for clarity sake, lets set the objects power\n pullee.power = percent; \n } else {\n percent = pullee.power;\n }\n } else {\n // the first argument was not an object, so we will simply pull num using the passed arguments\n }\n // pull num towards to_num by percent of their difference\n let pull_strength;\n if (num===undefined || to_num===undefined || percent===undefined){\n console.log('PULL() Error, an argument was missing.');\n pull_strength = 0;\n } else if (typeof num!==\"number\" || typeof to_num!==\"number\" || typeof percent!==\"number\"){\n console.log('PULL() Error, all arguments must be numbers');\n pull_strength = 0;\n } else {\n // dont ever allow something to be pulled further than its puller\n percent>1?percent=1:null;\n pull_strength = ((to_num - num) * percent);\n }\n return (num + pull_strength);\n}", "function print_max_and_min(Min, Max) {\r\n\r\n console.log(\"Max weight was %s k of %s\", Max.Details.Weight, Max.Name);\r\n console.log(\"Min weight was %s k of %s\", Min.Details.Weight, Min.Name);\r\n}", "function hs(arr) \n { var highest= Math.max(...arr);\n var smallest= Math.min(...arr);\n console.log(\"higest is:\"+highest);\n console.log(\"lowest is:\"+smallest);\n }", "function increaseMinMax() {\n min -= 10;\n max += 10;\n }", "function playStatistics(){\n var min = 6;\n var max = 1;\n for(var i = 0; i < 8; i++) {\n var result = rollOne();\n if(result < min){\n min = result;\n }\n if(result > max){\n max = result;\n }\n }\n console.log(`Min: ${min}`);\n console.log(`Max: ${max}`);\n}", "function MAX(state) {\n var stack = state.stack;\n var e2 = stack.pop();\n var e1 = stack.pop();\n\n if (exports.DEBUG) {\n console.log(state.step, 'MAX[]', e2, e1);\n }\n\n stack.push(Math.max(e1, e2));\n }", "function applyMinMax(value, min, max) {\n if (min != null && value < min) {\n return min;\n }\n if (max != null && value > max) {\n return max;\n }\n return value;\n }", "calculateMinMax() {\n var i = 0;\n Object.keys(this.data).forEach(key => {\n this.data[key].forEach(reading => {\n var value = parseInt(reading.sensor_value);\n if(i == 0) {\n this.minValue = value;\n this.maxValue = value;\n i ++;\n } else {\n if(value < this.minValue) {\n this.minValue = value;\n }\n if(value > this.maxValue) {\n this.maxValue = value;\n }\n }\n });\n });\n }", "function Max_Finder() {\r\n let numbers = EntryCheckForManyNumbers();\r\n let max = numbers [0]; \r\n let min = numbers [numbers.length-1] ;\r\n for (let i = 0; i < numbers.length; i++){\r\n if (max < numbers[i]) {\r\n max = numbers[i];\r\n }\r\n if ( min > numbers[i]) {\r\n min = numbers[i];\r\n }\r\n } \r\n //console.log(numbers);\r\n // console.log(min, max);\r\n return max;\r\n \r\n }", "function MAX(state) {\n var stack = state.stack;\n var e2 = stack.pop();\n var e1 = stack.pop();\n\n if (DEBUG) console.log(state.step, 'MAX[]', e2, e1);\n\n stack.push(Math.max(e1, e2));\n}", "function MAX(state) {\n\t var stack = state.stack;\n\t var e2 = stack.pop();\n\t var e1 = stack.pop();\n\n\t if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); }\n\n\t stack.push(Math.max(e1, e2));\n\t}", "function MAX(state) {\n var stack = state.stack;\n var e2 = stack.pop();\n var e1 = stack.pop();\n\n if (exports.DEBUG) console.log(state.step, 'MAX[]', e2, e1);\n\n stack.push(Math.max(e1, e2));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode a JV3 floppy disk file.
function decodeJv3FloppyDisk(binary) { let error; const annotations = []; const sectorInfos = []; // Read the directory. let sectorOffset = HEADER_SIZE; for (let i = 0; i < RECORD_COUNT; i++) { const offset = i * 3; if (offset + 2 >= binary.length) { error = "Directory truncated at entry " + i; break; } const track = binary[offset]; const sector = binary[offset + 1]; const flags = binary[offset + 2]; const sectorInfo = new SectorInfo(track, sector, flags, sectorOffset); sectorOffset += sectorInfo.size; if (!sectorInfo.isFree()) { if (sectorOffset > binary.length) { error = `Sector truncated at entry ${i} (${sectorOffset} > ${binary.length})`; break; } annotations.push(new ProgramAnnotation_1.ProgramAnnotation("Track " + sectorInfo.track + ", sector " + sectorInfo.sector + ", " + sectorInfo.flagsToString(), offset, offset + 3)); sectorInfos.push(sectorInfo); } } // Annotate the sectors themselves. for (const sectorInfo of sectorInfos) { annotations.push(new ProgramAnnotation_1.ProgramAnnotation("Track " + sectorInfo.track + ", sector " + sectorInfo.sector, sectorInfo.offset, sectorInfo.offset + sectorInfo.size)); } const writableOffset = RECORD_COUNT * 3; const writable = binary[writableOffset]; if (writable !== 0 && writable !== 0xFF) { error = "Invalid \"writable\" byte: 0x" + z80_base_1.toHexByte(writable); } const writeProtected = writable === 0; annotations.push(new ProgramAnnotation_1.ProgramAnnotation(writeProtected ? "Write protected" : "Writable", writableOffset, writableOffset + 1)); return new Jv3FloppyDisk(binary, error, annotations, sectorInfos, writeProtected); }
[ "function decodeJv3FloppyDisk(binary) {\n let error;\n const annotations = [];\n const sectorInfos = [];\n // Read the directory.\n let sectorOffset = HEADER_SIZE;\n for (let i = 0; i < RECORD_COUNT; i++) {\n const offset = i * 3;\n if (offset + 2 >= binary.length) {\n error = \"Directory truncated at entry \" + i;\n break;\n }\n const track = binary[offset];\n const sector = binary[offset + 1];\n const flags = binary[offset + 2];\n const sectorInfo = new Jv3FloppyDisk_SectorInfo(track, sector, flags, sectorOffset);\n sectorOffset += sectorInfo.size;\n if (!sectorInfo.isFree()) {\n if (sectorOffset > binary.length) {\n error = `Sector truncated at entry ${i} (${sectorOffset} > ${binary.length})`;\n break;\n }\n annotations.push(new ProgramAnnotation(\"Track \" + sectorInfo.track + \", sector \" +\n sectorInfo.sector + \", \" + sectorInfo.flagsToString(), offset, offset + 3));\n sectorInfos.push(sectorInfo);\n }\n }\n // Annotate the sectors themselves.\n for (const sectorInfo of sectorInfos) {\n annotations.push(new ProgramAnnotation(\"Track \" + sectorInfo.track + \", sector \" + sectorInfo.sector, sectorInfo.offset, sectorInfo.offset + sectorInfo.size));\n }\n const writableOffset = RECORD_COUNT * 3;\n const writable = binary[writableOffset];\n if (writable !== 0 && writable !== 0xFF) {\n error = \"Invalid \\\"writable\\\" byte: 0x\" + Object(z80_base_dist[\"toHexByte\"])(writable);\n }\n const writeProtected = writable === 0;\n annotations.push(new ProgramAnnotation(writeProtected ? \"Write protected\" : \"Writable\", writableOffset, writableOffset + 1));\n return new Jv3FloppyDisk_Jv3FloppyDisk(binary, error, annotations, sectorInfos, writeProtected);\n}", "function decodeJv1FloppyDisk(binary) {\n let error;\n const annotations = [];\n const length = binary.length;\n // Magic number check.\n if (length < 2 || binary[0] !== 0x00 || binary[1] !== 0xFE) {\n return undefined;\n }\n // Basic sanity check.\n if (length % BYTES_PER_TRACK !== 0) {\n error = \"Length is not a multiple of track size (\" + BYTES_PER_TRACK + \" bytes)\";\n }\n // Create annotations.\n for (let byteOffset = 0; byteOffset < length; byteOffset += BYTES_PER_SECTOR) {\n const track = Math.floor(byteOffset / BYTES_PER_TRACK);\n const sector = (byteOffset - track * BYTES_PER_TRACK) / BYTES_PER_SECTOR;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Track \" + track + \", sector \" + sector, byteOffset, Math.min(byteOffset + BYTES_PER_SECTOR, length)));\n }\n return new Jv1FloppyDisk(binary, error, annotations);\n}", "function decodeDmkFloppyDisk(binary) {\n const error = undefined;\n const annotations = [];\n if (binary.length < FILE_HEADER_SIZE) {\n return undefined;\n }\n // Decode the header. Comments marked [DMK] are from David Keil's original documentation.\n // [DMK] If this byte is set to FFH the disk is `write protected', 00H allows writing.\n const writeProtected = binary[0] === 0xFF;\n if (binary[0] !== 0x00 && binary[0] !== 0xFF) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(writeProtected ? \"Write protected\" : \"Writable\", 0, 1));\n // [DMK] Number of tracks on virtual disk. Since tracks start at 0 this value will be one greater\n // than the highest track written to the disk. So a disk with 40 tracks will have a value\n // of 40 (28H) in this field after formatting while the highest track written would be 39.\n // This field is updated after a track is formatted if the track formatted is greater than\n // or equal to the current number of tracks. Re-formatting a disk with fewer tracks will\n // NOT reduce the number of tracks on the virtual disk. Once a virtual disk has allocated\n // space for a track it will NEVER release it. Formatting a virtual disk with 80 tracks\n // then re-formatting it with 40 tracks would waste space just like formatting only 40\n // tracks on an 80 track drive. The emulator and TRS-80 operating system don't care.\n // To re-format a virtual disk with fewer tracks use the /I option at start-up to\n // delete and re-create the virtual disk first, then re-format to save space.\n //\n // [DMK] Note: This field should NEVER be modified. Changing this number will cause TRS-80\n // operating system disk errors. (Like reading an 80 track disk in a 40 track drive)\n const trackCount = binary[1];\n if (trackCount > 160) {\n // Not sure what a reasonable maximum is. I've only see 80.\n return undefined;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(trackCount + \" tracks\", 1, 2));\n // [DMK] This is the track length for the virtual disk. By default the value is 1900H, 80H bytes\n // more than the actual track length, this gives a track length of 6272 bytes. A real double\n // density track length is approx. 6250 bytes. This is the default value when a virtual disk is created.\n // Values for other disk and format types are 0CC0H for single density 5.25\" floppies,\n // 14E0H for single density 8\" floppies and 2940H for double density 8\" floppies. The max value is 2940H.\n // For normal formatting of disks the values of 1900H and 2940H for 5.25\" and 8\" are used.\n // The emulator will write two bytes and read every second byte when in single density to maintain\n // proper sector spacing, allowing mixed density disks. Setting the track length must be done before\n // a virtual disk is formatted or the disk will have to be re-formatted and since the space for the\n // disk has already been allocated no space will be saved.\n //\n // [DMK] WARNING: Bytes are entered in reverse order (ex. 2940H would be entered, byte 2=40, byte 3=29).\n //\n // [DMK] Note: No modification of the track length is necessary, doing so only saves space and is not\n // necessary to normal operation. The values for all normal 5.25\" and 8\" disks are set when the\n // virtual disk is created. DON'T modify the track length unless you understand these instructions completely.\n // Nothing in the PC world can be messed up by improper modification but any other virtual disk mounted\n // in the emulator with an improperly modified disk could have their data scrambled.\n const trackLength = binary[2] + (binary[3] << 8);\n if (trackLength > 0x2940) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(trackLength + \" bytes per track\", 2, 4));\n // [DMK] Virtual disk option flags.\n //\n // [DMK] Bit 4 of this byte, if set, means this is a single sided ONLY disk. This bit is set if the\n // user selects single sided during disk creation and should not require modification. This flag is\n // used only to save PC hard disk space and is never required.\n //\n // [DMK] Bit 6 of this byte, if set, means this disk is to be single density size and the emulator\n // will access one byte instead of two when doing I/O in single density. Double density can still\n // be written to a single density disk but with half the track length only 10 256 byte sectors can be\n // written in either density. Mixed density is also possible but sector timing may be off so protected\n // disks may not work, a maximum of 10 256 byte sectors of mixed density can be written to a\n // single density disk. A program like \"Spook House\" which has a mixed density track 0 with 1 SD sector\n // and 1 DD sector and the rest of the disk consisting of 10 SD sectors/track will work with this flag set\n // and save half the PC hard disk space. The protected disk \"Super Utility + 3.0\" however has 6 SD and 6 DD\n // sectors/track for a total of 12 256 byte sectors/track. This disk cannot be single density.\n // This bit is set if the user selects single density during disk creation and should\n // not require modification. This flag is used only to save PC hard disk space and is never required.\n //\n // [DMK] Bit 7 of this byte, if set, means density is to be ignored when accessing this disk. The disk MUST\n // be formatted in double density but the emulator will then read and write the sectors in either density.\n // The emulator will access one byte instead of two when doing I/O in single density.\n // This flag was an early way to support mixed density disks it is no longer needed for this purpose.\n // It is now used for compatibility with old virtual disks created without the double byte now used when in\n // single density. This bit can be set manually in a hex editor to access old virtual disks written\n // in single density.\n const flags = binary[4];\n const flagParts = [];\n const singleSided = (flags & 0x10) !== 0;\n if (singleSided) {\n flagParts.push(\"SS\");\n }\n if ((flags & 0x40) !== 0) {\n flagParts.push(\"SD\");\n }\n if ((flags & 0x80) !== 0) {\n flagParts.push(\"ignore density\");\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Flags: [\" + flagParts.join(\",\") + \"]\", 4, 5));\n // Sanity check.\n const sideCount = singleSided ? 1 : 2;\n const expectedLength = FILE_HEADER_SIZE + sideCount * trackCount * trackLength;\n if (binary.length !== expectedLength) {\n console.error(`DMK file wrong size (${binary.length} != ${expectedLength})`);\n return undefined;\n }\n // Check that these are zero.\n for (let i = 5; i < 12; i++) {\n if (binary[i] !== 0x00) {\n console.error(\"DMK: Reserved byte \" + i + \" is not zero: 0x\" + z80_base_2.toHexByte(binary[i]));\n return undefined;\n }\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Reserved\", 5, 12));\n // [DMK] Must be zero if virtual disk is in emulator's native format.\n //\n // [DMK] Must be 12345678h if virtual disk is a REAL disk specification file used to access\n // REAL TRS-80 floppies in compatible PC drives.\n if (binary[12] + binary[13] + binary[14] + binary[15] !== 0x00) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Virtual disk\", 12, 16));\n const floppyDisk = new DmkFloppyDisk(binary, error, annotations, true, writeProtected, trackCount, trackLength, flags);\n // Read the tracks.\n let binaryOffset = FILE_HEADER_SIZE;\n for (let trackNumber = 0; trackNumber < trackCount; trackNumber++) {\n for (let side = 0; side < sideCount; side++) {\n const trackOffset = binaryOffset;\n const track = new DmkTrack(floppyDisk, trackNumber, FloppyDisk_1.numberToSide(side), trackOffset);\n // Read the track header. The term \"IDAM\" in the comment below refers to the \"ID access mark\",\n // where \"ID\" is referring to the sector ID, the few byte just before the sector data.\n // [DMK] Each side of each track has a 128 (80H) byte header which contains an offset pointer\n // to each IDAM in the track. This allows a maximum of 64 sector IDAMs/track. This is more than\n // twice what an 8 inch disk would require and 3.5 times that of a normal TRS-80 5 inch DD disk.\n // This should more than enough for any protected disk also.\n //\n // [DMK] These IDAM pointers MUST adhere to the following rules:\n //\n // * Each pointer is a 2 byte offset to the FEh byte of the IDAM. In double byte single density\n // the pointer is to the first FEh.\n // * The offset includes the 128 byte header. For example, an IDAM 10h bytes into the track would\n // have a pointer of 90h, 10h+80h=90h.\n // * The IDAM offsets MUST be in ascending order with no unused or bad pointers.\n // * If all the entries are not used the header is terminated with a 0000h entry. Unused entries\n // must also be zero filled..\n // * Any IDAMs overwritten during a sector write command should have their entry removed from the\n // header and all other pointer entries shifted to fill in.\n // * The IDAM pointers are created during the track write command (format). A completed track write\n // MUST remove all previous IDAM pointers. A partial track write (aborted with the forced interrupt\n // command) MUST have it's previous pointers that were not overwritten added to the new IDAM pointers.\n // * The pointer bytes are stored in reverse order (LSB/MSB).\n //\n // [DMK] Each IDAM pointer has two flags. Bit 15 is set if the sector is double density. Bit 14 is\n // currently undefined. These bits must be masked to get the actual sector offset. For example,\n // an offset to an IDAM at byte 90h would be 0090h if single density and 8090h if double density.\n for (let i = 0; i < TRACK_HEADER_SIZE; i += 2) {\n const sectorOffset = binary[binaryOffset + i] + (binary[binaryOffset + i + 1] << 8);\n if (sectorOffset !== 0) {\n track.sectors.push(new DmkSector(track, (sectorOffset & 0x8000) !== 0, sectorOffset & 0x3FFF));\n }\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(`Track ${trackNumber} header`, binaryOffset, binaryOffset + TRACK_HEADER_SIZE));\n for (const sector of track.sectors) {\n let i = trackOffset + sector.offset;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Sector ID access mark\", i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Cylinder \" + sector.getCylinder(), i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Side \" + sector.getSide(), i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Sector \" + sector.getSectorNumber(), i, i + 1));\n i++;\n const sectorLength = sector.getLength();\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Length \" + sectorLength, i, i + 1));\n i++;\n const actualIdamCrc = sector.computeIdemCrc();\n const expectedIdamCrc = sector.getIdamCrc();\n let idamCrcLabel = \"IDAM CRC\";\n if (actualIdamCrc === expectedIdamCrc) {\n idamCrcLabel += \" (valid)\";\n }\n else {\n idamCrcLabel += ` (got 0x${z80_base_1.toHexWord(actualIdamCrc)}, expected 0x${z80_base_1.toHexWord(expectedIdamCrc)})`;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(idamCrcLabel, i, i + 2));\n i += 2;\n i = trackOffset + sector.offset + sector.dataIndex;\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(\"Sector data\", i, i + sectorLength));\n i += sectorLength;\n const actualDataCrc = sector.computeDataCrc();\n const expectedDataCrc = sector.getDataCrc();\n let dataCrcLabel = \"Data CRC\";\n if (actualDataCrc === expectedDataCrc) {\n dataCrcLabel += \" (valid)\";\n }\n else {\n dataCrcLabel += ` (got 0x${z80_base_1.toHexWord(actualDataCrc)}, expected 0x${z80_base_1.toHexWord(expectedDataCrc)})`;\n }\n annotations.push(new ProgramAnnotation_1.ProgramAnnotation(dataCrcLabel, i, i + 2));\n i += 2;\n }\n floppyDisk.tracks.push(track);\n binaryOffset += trackLength;\n }\n }\n return floppyDisk;\n}", "function decodeJv1FloppyDisk(binary) {\n let error;\n const annotations = [];\n const length = binary.length;\n // Magic number check.\n if (length < 2 || binary[0] !== 0x00 || binary[1] !== 0xFE) {\n return undefined;\n }\n // Basic sanity check.\n if (length % BYTES_PER_TRACK !== 0) {\n error = \"Length is not a multiple of track size (\" + BYTES_PER_TRACK + \" bytes)\";\n }\n // Create annotations.\n for (let byteOffset = 0; byteOffset < length; byteOffset += BYTES_PER_SECTOR) {\n const track = Math.floor(byteOffset / BYTES_PER_TRACK);\n const sector = (byteOffset - track * BYTES_PER_TRACK) / BYTES_PER_SECTOR;\n annotations.push(new ProgramAnnotation(\"Track \" + track + \", sector \" + sector, byteOffset, Math.min(byteOffset + BYTES_PER_SECTOR, length)));\n }\n return new Jv1FloppyDisk_Jv1FloppyDisk(binary, error, annotations);\n}", "function decodeDmkFloppyDisk(binary) {\n const error = undefined;\n const annotations = [];\n if (binary.length < FILE_HEADER_SIZE) {\n return undefined;\n }\n // Decode the header. Comments marked [DMK] are from David Keil's original documentation.\n // [DMK] If this byte is set to FFH the disk is `write protected', 00H allows writing.\n const writeProtected = binary[0] === 0xFF;\n if (binary[0] !== 0x00 && binary[0] !== 0xFF) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation(writeProtected ? \"Write protected\" : \"Writable\", 0, 1));\n // [DMK] Number of tracks on virtual disk. Since tracks start at 0 this value will be one greater\n // than the highest track written to the disk. So a disk with 40 tracks will have a value\n // of 40 (28H) in this field after formatting while the highest track written would be 39.\n // This field is updated after a track is formatted if the track formatted is greater than\n // or equal to the current number of tracks. Re-formatting a disk with fewer tracks will\n // NOT reduce the number of tracks on the virtual disk. Once a virtual disk has allocated\n // space for a track it will NEVER release it. Formatting a virtual disk with 80 tracks\n // then re-formatting it with 40 tracks would waste space just like formatting only 40\n // tracks on an 80 track drive. The emulator and TRS-80 operating system don't care.\n // To re-format a virtual disk with fewer tracks use the /I option at start-up to\n // delete and re-create the virtual disk first, then re-format to save space.\n //\n // [DMK] Note: This field should NEVER be modified. Changing this number will cause TRS-80\n // operating system disk errors. (Like reading an 80 track disk in a 40 track drive)\n const trackCount = binary[1];\n if (trackCount > 160) {\n // Not sure what a reasonable maximum is. I've only see 80.\n return undefined;\n }\n annotations.push(new ProgramAnnotation(trackCount + \" tracks\", 1, 2));\n // [DMK] This is the track length for the virtual disk. By default the value is 1900H, 80H bytes\n // more than the actual track length, this gives a track length of 6272 bytes. A real double\n // density track length is approx. 6250 bytes. This is the default value when a virtual disk is created.\n // Values for other disk and format types are 0CC0H for single density 5.25\" floppies,\n // 14E0H for single density 8\" floppies and 2940H for double density 8\" floppies. The max value is 2940H.\n // For normal formatting of disks the values of 1900H and 2940H for 5.25\" and 8\" are used.\n // The emulator will write two bytes and read every second byte when in single density to maintain\n // proper sector spacing, allowing mixed density disks. Setting the track length must be done before\n // a virtual disk is formatted or the disk will have to be re-formatted and since the space for the\n // disk has already been allocated no space will be saved.\n //\n // [DMK] WARNING: Bytes are entered in reverse order (ex. 2940H would be entered, byte 2=40, byte 3=29).\n //\n // [DMK] Note: No modification of the track length is necessary, doing so only saves space and is not\n // necessary to normal operation. The values for all normal 5.25\" and 8\" disks are set when the\n // virtual disk is created. DON'T modify the track length unless you understand these instructions completely.\n // Nothing in the PC world can be messed up by improper modification but any other virtual disk mounted\n // in the emulator with an improperly modified disk could have their data scrambled.\n const trackLength = binary[2] + (binary[3] << 8);\n if (trackLength > 0x2940) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation(trackLength + \" bytes per track\", 2, 4));\n // [DMK] Virtual disk option flags.\n //\n // [DMK] Bit 4 of this byte, if set, means this is a single sided ONLY disk. This bit is set if the\n // user selects single sided during disk creation and should not require modification. This flag is\n // used only to save PC hard disk space and is never required.\n //\n // [DMK] Bit 6 of this byte, if set, means this disk is to be single density size and the emulator\n // will access one byte instead of two when doing I/O in single density. Double density can still\n // be written to a single density disk but with half the track length only 10 256 byte sectors can be\n // written in either density. Mixed density is also possible but sector timing may be off so protected\n // disks may not work, a maximum of 10 256 byte sectors of mixed density can be written to a\n // single density disk. A program like \"Spook House\" which has a mixed density track 0 with 1 SD sector\n // and 1 DD sector and the rest of the disk consisting of 10 SD sectors/track will work with this flag set\n // and save half the PC hard disk space. The protected disk \"Super Utility + 3.0\" however has 6 SD and 6 DD\n // sectors/track for a total of 12 256 byte sectors/track. This disk cannot be single density.\n // This bit is set if the user selects single density during disk creation and should\n // not require modification. This flag is used only to save PC hard disk space and is never required.\n //\n // [DMK] Bit 7 of this byte, if set, means density is to be ignored when accessing this disk. The disk MUST\n // be formatted in double density but the emulator will then read and write the sectors in either density.\n // The emulator will access one byte instead of two when doing I/O in single density.\n // This flag was an early way to support mixed density disks it is no longer needed for this purpose.\n // It is now used for compatibility with old virtual disks created without the double byte now used when in\n // single density. This bit can be set manually in a hex editor to access old virtual disks written\n // in single density.\n const flags = binary[4];\n const flagParts = [];\n const singleSided = (flags & 0x10) !== 0;\n if (singleSided) {\n flagParts.push(\"SS\");\n }\n if ((flags & 0x40) !== 0) {\n flagParts.push(\"SD\");\n }\n if ((flags & 0x80) !== 0) {\n flagParts.push(\"ignore density\");\n }\n annotations.push(new ProgramAnnotation(\"Flags: [\" + flagParts.join(\",\") + \"]\", 4, 5));\n // Sanity check.\n const sideCount = singleSided ? 1 : 2;\n const expectedLength = FILE_HEADER_SIZE + sideCount * trackCount * trackLength;\n if (binary.length !== expectedLength) {\n console.error(`DMK file wrong size (${binary.length} != ${expectedLength})`);\n return undefined;\n }\n // Check that these are zero.\n for (let i = 5; i < 12; i++) {\n if (binary[i] !== 0x00) {\n console.error(\"DMK: Reserved byte \" + i + \" is not zero: 0x\" + Object(z80_base_dist[\"toHexByte\"])(binary[i]));\n return undefined;\n }\n }\n annotations.push(new ProgramAnnotation(\"Reserved\", 5, 12));\n // [DMK] Must be zero if virtual disk is in emulator's native format.\n //\n // [DMK] Must be 12345678h if virtual disk is a REAL disk specification file used to access\n // REAL TRS-80 floppies in compatible PC drives.\n if (binary[12] + binary[13] + binary[14] + binary[15] !== 0x00) {\n return undefined;\n }\n annotations.push(new ProgramAnnotation(\"Virtual disk\", 12, 16));\n const floppyDisk = new DmkFloppyDisk_DmkFloppyDisk(binary, error, annotations, true, writeProtected, trackCount, trackLength, flags);\n // Read the tracks.\n let binaryOffset = FILE_HEADER_SIZE;\n for (let trackNumber = 0; trackNumber < trackCount; trackNumber++) {\n for (let side = 0; side < sideCount; side++) {\n const trackOffset = binaryOffset;\n const track = new DmkTrack(floppyDisk, trackNumber, numberToSide(side), trackOffset);\n // Read the track header. The term \"IDAM\" in the comment below refers to the \"ID access mark\",\n // where \"ID\" is referring to the sector ID, the few byte just before the sector data.\n // [DMK] Each side of each track has a 128 (80H) byte header which contains an offset pointer\n // to each IDAM in the track. This allows a maximum of 64 sector IDAMs/track. This is more than\n // twice what an 8 inch disk would require and 3.5 times that of a normal TRS-80 5 inch DD disk.\n // This should more than enough for any protected disk also.\n //\n // [DMK] These IDAM pointers MUST adhere to the following rules:\n //\n // * Each pointer is a 2 byte offset to the FEh byte of the IDAM. In double byte single density\n // the pointer is to the first FEh.\n // * The offset includes the 128 byte header. For example, an IDAM 10h bytes into the track would\n // have a pointer of 90h, 10h+80h=90h.\n // * The IDAM offsets MUST be in ascending order with no unused or bad pointers.\n // * If all the entries are not used the header is terminated with a 0000h entry. Unused entries\n // must also be zero filled..\n // * Any IDAMs overwritten during a sector write command should have their entry removed from the\n // header and all other pointer entries shifted to fill in.\n // * The IDAM pointers are created during the track write command (format). A completed track write\n // MUST remove all previous IDAM pointers. A partial track write (aborted with the forced interrupt\n // command) MUST have it's previous pointers that were not overwritten added to the new IDAM pointers.\n // * The pointer bytes are stored in reverse order (LSB/MSB).\n //\n // [DMK] Each IDAM pointer has two flags. Bit 15 is set if the sector is double density. Bit 14 is\n // currently undefined. These bits must be masked to get the actual sector offset. For example,\n // an offset to an IDAM at byte 90h would be 0090h if single density and 8090h if double density.\n for (let i = 0; i < TRACK_HEADER_SIZE; i += 2) {\n const sectorOffset = binary[binaryOffset + i] + (binary[binaryOffset + i + 1] << 8);\n if (sectorOffset !== 0) {\n track.sectors.push(new DmkFloppyDisk_DmkSector(track, (sectorOffset & 0x8000) !== 0, sectorOffset & 0x3FFF));\n }\n }\n annotations.push(new ProgramAnnotation(`Track ${trackNumber} header`, binaryOffset, binaryOffset + TRACK_HEADER_SIZE));\n for (const sector of track.sectors) {\n let i = trackOffset + sector.offset;\n annotations.push(new ProgramAnnotation(\"Sector ID access mark\", i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation(\"Cylinder \" + sector.getCylinder(), i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation(\"Side \" + sector.getSide(), i, i + 1));\n i++;\n annotations.push(new ProgramAnnotation(\"Sector \" + sector.getSectorNumber(), i, i + 1));\n i++;\n const sectorLength = sector.getLength();\n annotations.push(new ProgramAnnotation(\"Length \" + sectorLength, i, i + 1));\n i++;\n const actualIdamCrc = sector.computeIdemCrc();\n const expectedIdamCrc = sector.getIdamCrc();\n let idamCrcLabel = \"IDAM CRC\";\n if (actualIdamCrc === expectedIdamCrc) {\n idamCrcLabel += \" (valid)\";\n }\n else {\n idamCrcLabel += ` (got 0x${Object(z80_base_dist[\"toHexWord\"])(actualIdamCrc)}, expected 0x${Object(z80_base_dist[\"toHexWord\"])(expectedIdamCrc)})`;\n }\n annotations.push(new ProgramAnnotation(idamCrcLabel, i, i + 2));\n i += 2;\n i = trackOffset + sector.offset + sector.dataIndex;\n annotations.push(new ProgramAnnotation(\"Sector data\", i, i + sectorLength));\n i += sectorLength;\n const actualDataCrc = sector.computeDataCrc();\n const expectedDataCrc = sector.getDataCrc();\n let dataCrcLabel = \"Data CRC\";\n if (actualDataCrc === expectedDataCrc) {\n dataCrcLabel += \" (valid)\";\n }\n else {\n dataCrcLabel += ` (got 0x${Object(z80_base_dist[\"toHexWord\"])(actualDataCrc)}, expected 0x${Object(z80_base_dist[\"toHexWord\"])(expectedDataCrc)})`;\n }\n annotations.push(new ProgramAnnotation(dataCrcLabel, i, i + 2));\n i += 2;\n }\n floppyDisk.tracks.push(track);\n binaryOffset += trackLength;\n }\n }\n return floppyDisk;\n}", "static Load(fn, unit=\"pt\") {\n\ttry {\n\t var fs = require('fs');\n\t let buffer = fs.readFileSync(fn);\n\t if (buffer.readUInt8(0) != PRE) return null;\n\t if (buffer.readUInt8(buffer.length-4) != 223) return null; // 223?\n\n\t let aDVI = new DVI(unit);\n\t aDVI.LoadFromFile(new BufferFP(buffer));\n\t return aDVI;\n\t}\n\tcatch (e) {\n\t console.error('Failed to read ' + fn);\n\t console.log(e);\n\t console.log(e.stack);\n\t return null;\n\t}\n }", "function decodeFile(input) {\n let ondata = (evt, cb) => {\n if (evt.data[0] == 0) {\n cb({raw: evt.data.subarray(1), links: [], data: evt.data.subarray(1)})\n } else if (evt.data[0] == 1) {\n try {\n let node = dagPB.util.deserialize(evt.data.subarray(1))\n\n let file = Unixfs.unmarshal(node.Data)\n if (file.type != \"raw\" && file.type != \"file\") {\n throw new Error(\"got unexpected file type, wanted raw or file\")\n }\n if (file.data == null) {\n file.data = Buffer.alloc(0)\n }\n\n cb({raw: evt.data.subarray(1), links: node.Links, data: file.data})\n } catch (err) {\n cb(null, err)\n }\n } else {\n cb(null, new Error(\"failed to decode a chunk of file data\"))\n }\n }\n\n return asynchronous(input, ondata)\n}", "function decodeDsk(binary) {\n // TODO see trs_disk.c:trs_disk_emutype()\n // TODO see DiskDrive.cpp:Dectect_JV1, etc.\n let trs80File;\n trs80File = DmkFloppyDisk_1.decodeDmkFloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = Jv1FloppyDisk_1.decodeJv1FloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = Jv3FloppyDisk_1.decodeJv3FloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n return undefined;\n}", "function decodeDsk(binary) {\n // TODO see trs_disk.c:trs_disk_emutype()\n // TODO see DiskDrive.cpp:Dectect_JV1, etc.\n let trs80File;\n trs80File = decodeDmkFloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = decodeJv1FloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = decodeJv3FloppyDisk(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n return undefined;\n}", "function decodeTrs80File(binary, filename) {\n var _a, _b, _c, _d;\n let trs80File;\n const extension = filename === undefined ? \"\" : getExtension(filename);\n if (extension === \".JV1\") {\n return (_a = Jv1FloppyDisk_1.decodeJv1FloppyDisk(binary)) !== null && _a !== void 0 ? _a : new RawBinaryFile_1.RawBinaryFile(binary);\n }\n if (extension === \".DSK\") {\n return (_b = decodeDsk(binary)) !== null && _b !== void 0 ? _b : new RawBinaryFile_1.RawBinaryFile(binary);\n }\n if (extension === \".DMK\") {\n return (_c = DmkFloppyDisk_1.decodeDmkFloppyDisk(binary)) !== null && _c !== void 0 ? _c : new RawBinaryFile_1.RawBinaryFile(binary);\n }\n // \"Model III BiNary\" format, invented by George Phillips for trs80gp.\n // Rarely used as a stand-alone file, usually just embedded in .CAS files.\n if (extension === \".3BN\") {\n return (_d = SystemProgram_1.decodeSystemProgram(binary)) !== null && _d !== void 0 ? _d : new RawBinaryFile_1.RawBinaryFile(binary);\n }\n trs80File = Cassette_1.decodeCassette(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = CmdProgram_1.decodeCmdProgram(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = Basic_1.decodeBasicProgram(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n return new RawBinaryFile_1.RawBinaryFile(binary);\n}", "function decodeTrs80File(binary, filename) {\n var _a, _b, _c, _d;\n let trs80File;\n const extension = filename === undefined ? \"\" : getExtension(filename);\n if (extension === \".JV1\") {\n return (_a = decodeJv1FloppyDisk(binary)) !== null && _a !== void 0 ? _a : new RawBinaryFile_RawBinaryFile(binary);\n }\n if (extension === \".DSK\") {\n return (_b = decodeDsk(binary)) !== null && _b !== void 0 ? _b : new RawBinaryFile_RawBinaryFile(binary);\n }\n if (extension === \".DMK\") {\n return (_c = decodeDmkFloppyDisk(binary)) !== null && _c !== void 0 ? _c : new RawBinaryFile_RawBinaryFile(binary);\n }\n // \"Model III BiNary\" format, invented by George Phillips for trs80gp.\n // Rarely used as a stand-alone file, usually just embedded in .CAS files.\n if (extension === \".3BN\") {\n return (_d = decodeSystemProgram(binary)) !== null && _d !== void 0 ? _d : new RawBinaryFile_RawBinaryFile(binary);\n }\n trs80File = decodeCassette(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = decodeCmdProgram(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n trs80File = decodeBasicProgram(binary);\n if (trs80File !== undefined) {\n return trs80File;\n }\n return new RawBinaryFile_RawBinaryFile(binary);\n}", "function readFile() {\n const filename = getFilename();\n console.log(`read fn=${filename}`);\n\n let data = floppies[filename];\n if (data === undefined) data = ''; // empty\n const length = data.length;\n let dataPtr = cpu.memory.readWord(FLOPPY_DATA_PTR);\n for (var i = 0; i < data.length; ++i) {\n const u = data.charAt(i);\n const tt = fromUnicode(u);\n cpu.memory.write(dataPtr, tt);\n ++dataPtr;\n }\n cpu.memory.writeWord(FLOPPY_LENGTH_ADDRESS, length);\n }", "DecodeBlob(string, EncodingType) {\n\n }", "decompress() {\n\t\tif (!this.raw) {\n\t\t\tthis.readRaw();\n\t\t}\n\t\tlet buff = this.raw;\n\t\tif (this.compressed) {\n\n\t\t\t// Important! In Simcity 4 DBPF files, compressed subfiles are \n\t\t\t// always prefixed with the total size! We can discard this.\n\t\t\tbuff = decompress(buff.slice(4));\n\n\t\t}\n\t\treturn buff;\n\t}", "function readFile(evt) {\n //Retrieve the first (and only!) File from the FileList object\n var files = evt.target.files;\n for (var i = 0, f; f = files[i]; i++) {\n if (f) {\n var r = new FileReader();\n r.onload = function(e) {\n var contents = e.target.result;\n document.getElementById(\"part2\").style.display=\"none\"\n\n decoder(contents)\n document.getElementById(\"part3\").style.display=\"inline\";\n\n }\n r.readAsText(f);\n } else {\n alert(\"Failed to load file\");\n }\n }\n }", "function readIFD (buffer, filepath, isBigEndian) {\n\t\n\t var ifdOffset = readUInt(buffer, 32, 4, isBigEndian);\n\t\n\t // read only till the end of the file\n\t var bufferSize = 1024;\n\t var fileSize = fs.statSync(filepath).size;\n\t if (ifdOffset + bufferSize > fileSize) {\n\t bufferSize = fileSize - ifdOffset - 10;\n\t }\n\t\n\t // populate the buffer\n\t var endBuffer = new Buffer(bufferSize);\n\t var descriptor = fs.openSync(filepath, 'r');\n\t fs.readSync(descriptor, endBuffer, 0, bufferSize, ifdOffset);\n\t\n\t // var ifdLength = readUInt(endBuffer, 16, 0, isBigEndian);\n\t var ifdBuffer = endBuffer.slice(2); //, 2 + 12 * ifdLength);\n\t return ifdBuffer;\n\t}", "function decodeFileRequest(data){\n\tif(obfuscation==1){\n\t\tvar json = data;\n\t\tjson.content = decodeURIComponent(escape(window.atob(json.content)));\n\t\tjson.fileKey = decodeURIComponent(escape(window.atob(json.fileKey)));\n\t\treturn json;\n\t}\n\telse{\n\t\treturn data;\n\t}\n}", "function readIFD (buffer, filepath, isBigEndian) {\n\n var ifdOffset = readUInt(buffer, 32, 4, isBigEndian);\n\n // read only till the end of the file\n var bufferSize = 1024;\n var fileSize = fs.statSync(filepath).size;\n if (ifdOffset + bufferSize > fileSize) {\n bufferSize = fileSize - ifdOffset - 10;\n }\n\n // populate the buffer\n var endBuffer = new Buffer(bufferSize);\n var descriptor = fs.openSync(filepath, 'r');\n fs.readSync(descriptor, endBuffer, 0, bufferSize, ifdOffset);\n\n // var ifdLength = readUInt(endBuffer, 16, 0, isBigEndian);\n var ifdBuffer = endBuffer.slice(2); //, 2 + 12 * ifdLength);\n return ifdBuffer;\n}", "decode(){\n try{\n var headerInfo = this._decodeHeader();\n this._decodeData( headerInfo.offset, headerInfo.header );\n }catch(e){\n console.warn( e );\n }\n\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to enable or disable a menu. For example, there could be multiple left menus, but only one of them should be able to be opened at the same time. If there are multiple menus on the same side, then enabling one menu will also automatically disable all the others that are on the same side.
enable(shouldEnable, menuId) { return _ionic_core__WEBPACK_IMPORTED_MODULE_5__["menuController"].enable(shouldEnable, menuId); }
[ "function enableMenu(menu) {\n if (menu === \"Sides\") {\n disableAll();\n setToggleSides({ display: \"inline-block\" });\n console.log({ toggleSides })\n } else \n if (menu === \"Appetizers\") {\n disableAll();\n setToggleAppetizers({ display: \"inline-block\" });\n console.log({ toggleAppetizers })\n\n }\n else if (menu === \"Main\") {\n disableAll();\n setToggleMain({ display: \"inline-block\" });\n console.log({ toggleMain })\n } else if (menu === \"Drinks\") {\n disableAll();\n setToggleDrinks({ display: \"inline-block\" });\n console.log({ toggleDrinks })\n }\n }", "enable(enable, menu) {\r\n return menuController.enable(enable, menu);\r\n }", "enableMenuButtons() {\n var elements = this.__menuElements;\n for (var i = 0; i < elements.length; i++) {\n elements[i].setEnabled(true);\n }\n }", "enable() {\n\t\tMenu.enableItem(this.handle);\n\t}", "function enableMenu() {\n\n\t$(\"#menuIconImg\").show();\n\t$(\"#menuLink\").show();\n\tchangeMenuVisibility();\n}", "function enableMenu()\r\n{\r\n\tif (typeof top.menu == \"undefined\" || typeof top.menu.divContain == \"undefined\")\r\n\t\treturn -1;\r\n\ttop.menu.divContain.style.visibility = \"hidden\";\r\n\treturn 0;\r\n}", "function mi_enable() {\n\tif(this.status == MI_STATUS_DISABLED) {\n\t\tif(this.HTMLElement != null) {\n\t\t\tif(typeof this.menu.component.cssMenuItem == 'string') {\n\t\t\t\tthis.HTMLElement.className = this.menu.component.cssMenuItem;\n\t\t\t}\n\t\t}\n\n\t\tthis.status = MI_STATUS_NORMAL;\n\t}\n}", "function enableChangingMenuItem() {\n enableMenuItemBtnChanging();\n enableSaveNameBtn();\n enableDeleteBtn();\n}", "isEnabled(menu) {\r\n return menuController.isEnabled(menu);\r\n }", "function toggleMenu(){\n setMenuActive(prevValue => !prevValue);\n }", "function enableMenu() {\r\n\r\n if (currAccount != \"\") {\r\n\r\n $(\"#buy-tokens\").show();\r\n\r\n $(\"#sign-out\").show();\r\n\r\n if (getCookie(\"admin\") == \"1\") {\r\n $(\"#menu-admin\").show();\r\n\r\n }\r\n\r\n if (getCookie(\"delegated\") == \"1\") {\r\n $(\"#cancel-delegation-menu\").show();\r\n $(\"#delegate-votes-menu\").hide();\r\n }\r\n }\r\n else { $(\"#sidebar-menu\").hide(); }\r\n}", "toggleMenuMode()\n {\n this.menuModes[0].current.classList.toggle(\"inactive\");\n this.menuModes[1].current.classList.toggle(\"inactive\");\n this.props.showHoldHold.current.toggleRemovable();\n }", "disableMenuButtons() {\n var elements = this.__menuElements;\n for (var i = 0; i < elements.length; i++) {\n elements[i].setEnabled(false);\n }\n }", "function loanContactsListMenu_Enable(enable) {\n if (enable) {\n //ie 7 will show list icon when it should not. Hiding the wrapper element will not hide\n //the list menu icon. Also Hide the child element to fix ie7 issue.\n $(\"#LoanContactsDetailsWrapper_helm .threeLineMenu\").toggleClass(\"displayNone\", false);\n $(\"#LoanContactsDetailsWrapper_helm .threeLineMenuWrapper\").toggleClass(\"displayNone\", false);\n }\n else { //disable\n $(\"#LoanContactsDetailsWrapper_helm .threeLineMenu\").toggleClass(\"displayNone\", true);\n $(\"#LoanContactsDetailsWrapper_helm .threeLineMenuWrapper\").toggleClass(\"displayNone\", true);\n }\n }", "function FormFieldsMenu_enable(enable)\r\n{\r\n if ((enable != null) && !enable)\r\n {\r\n this.listControl.disable();\r\n }\r\n else\r\n {\r\n this.listControl.enable();\r\n }\r\n}", "function manageMenu() {\n if (menuOpen) {\n menuOpen = false;\n closeMenu();\n } else {\n menuOpen = true;\n openMenu();\n }\n}", "function enableAddingMenuItem() {\n enablePlusBtns();\n enableSaveBtn();\n}", "function createNonAuthMenu()\n{ \n var ui = SpreadsheetApp.getUi();\n var menu = ui.createMenu(gbl_menu_name);\n \n menu.addItem(langstr_en(\"FLB_STR_MENU_ENABLE\"), \"enableInSheet\");\n menu.addToUi();\n}", "function disableMenu()\r\n{\r\n\tif (typeof top.menu == \"undefined\" && typeof top.menu.divContain == \"undefined\")\r\n\t\treturn -1;\r\n\ttop.menu.divContain.style.visibility = \"visible\";\r\n\treturn 0;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
one argument pass dt in loadPopupHoliday function
function loadPopupHoliday(dt){ var full_date,data_header,date,data=''; date=getHoursTime(dt); month_name=getMonthName(date['month']); data_header='Your schedule is '+month_name+' '+date['date']+', '+date['year']; full_date=date['year']+'-'+date['month']+'-'+date['date']; data += "<label class='checkbox-inline'>"; data += "<input type='radio' value='1' class='schedule' id='schedule' name='schedule'>&nbsp;&nbsp;Holiday"; data += "</label>"; data += "<label class='checkbox-inline'>"; data += "<input type='radio' value='2' class='schedule' id='schedule' name='schedule'>&nbsp;&nbsp;Delete(All ocuurs will be delete)"; data += "</label>"; $('#checkboxGroup').html(data); $('.date-hidden').val(full_date); $('#date-header').html(data_header); $('#calenderModal').modal( 'show' ); }
[ "function get_CalednarPopUpDate(tbName){\n obj=new CalendarPopup_FindCalendar(tbName);\n var date = obj.GetDate();\n return date; \n}", "static cal_holiday2(jdn) {\r\n\tjdn=Math.round(jdn);\r\n\tvar myt,my,mm,md,mp,mmt,gy,gm,gd;\r\n\tvar yo=ceMmDateTime.j2m(jdn);\r\n\tmyt=yo.myt; my=yo.my; mm = yo.mm; md=yo.md;\r\n\tmp=ceMmDateTime.cal_mp(md,mm,myt);\r\n\tmmt=Math.floor(mm/13); var hs=[];\r\n\tvar go=ceDateTime.j2w(jdn);\r\n\tgy=go.y; gm=go.m; gd=go.d;\r\n\t//---------------------------------\r\n\t// holidays on gregorian calendar\t\r\n\tvar doe=ceMmDateTime.DoE(gy);\r\n\tif((gy<=2017) && (gm==1) && (gd==1)) {hs.push(\"New Year's Day\");}\r\n\telse if((gy>=1915) && (gm==2) && (gd==13)) {hs.push(\"G. Aung San BD\");}\r\n\telse if((gy>=1969) && (gm==2) && (gd==14)) {hs.push(\"Valentines Day\");}\r\n\telse if((gy>=1970) && (gm==4) && (gd==22)) {hs.push(\"Earth Day\");}\r\n\telse if((gy>=1392) && (gm==4) && (gd==1)) {hs.push(\"April Fools' Day\");}\r\n\telse if((gy>=1948) && (gm==5) && (gd==8)) {hs.push(\"Red Cross Day\");}\r\n\telse if((gy>=1994) && (gm==10) && (gd==5)) {hs.push(\"World Teachers' Day\");}\r\n\telse if((gy>=1947) && (gm==10) && (gd==24)) {hs.push(\"United Nations Day\");}\r\n\telse if((gy>=1753) && (gm==10) && (gd==31)) {hs.push(\"Halloween\");}\r\n\tif((gy>=1876) && (jdn==doe)) {hs.push(\"Easter\");}\r\n\telse if((gy>=1876) && (jdn==(doe-2))) {hs.push(\"Good Friday\");}\r\n\t//---------------------------------\r\n\t// holidays on myanmar calendar\r\n\tif((my>=1309) && (mm==11) && (md==16))\r\n\t\t{hs.push(\"Mon National Day\");}//the ancient founding of Hanthawady\r\n\telse if((mm==9) && (md==1)) {\r\n\t\ths.push(\"Shan New Year's Day\");\r\n\t\tif(my>=1306) {hs.push(\"Authors' Day\");}\r\n\t}//Nadaw waxing moon 1\r\n\telse if((mm==3) && (mp==1)) {hs.push(\"Mahathamaya Day\");}//Nayon full moon\r\n\telse if((mm==6)&&(mp==1)){hs.push(\"Garudhamma Day\");}//Tawthalin full moon\r\n\telse if((my>=1356) && (mm==10) && (mp==1))\r\n\t\t{hs.push(\"Mothers' Day\");}//Pyatho full moon\r\n\telse if((my>=1370) && (mm==12) && (mp==1))\r\n\t\t{hs.push(\"Fathers' Day\");}//Tabaung full moon\r\n\telse if((mm==5) && (mp==1)) {hs.push(\"Metta Day\");}//Waguang full moon\r\n\telse if((mm==5) && (md==10)) {hs.push(\"Taungpyone Pwe\");}//Taung Pyone Pwe\r\n\telse if((mm==5) && (md==23)) {hs.push(\"Yadanagu Pwe\");}//Yadanagu Pwe\r\n\t//----------------------------------------------------------------------------\r\n\t// //other holidays\r\n\t// var ghEid2=[2456936,2457290,2457644,2457998,2458353,2458707];\r\n\t// var ghCNY=[2456689,2456690,2457073,2457074,2457427,2457428,2457782,\r\n\t// \t2457783,2458166,2458167,2458520,2458521];\r\n\t// if(ceMmDateTime.bSearch1(jdn,ghEid2)>=0) {hs.push(\"Eid\");}\r\n\t// if(ceMmDateTime.bSearch1(jdn,ghCNY)>=0) {hs.push(\"Chinese New Year's Day\");}\r\n\t//----------------------------------------------------------------------------\r\n\treturn hs;\r\n}", "function calDateCompanyInfo(obj){\n\t\n\t//상세화면 진입시 해당일자의 정산 데이터를 가져오기 위한 처리\n\tSEARCHDATE = $(obj).closest('tr').children(\":eq(1)\").text();\n\t\n\t//modal title를 유동적으로 처리하기 위해 받아온 data로 modal타이틀을 setting \n\tlet title = \"정산 - 회원사별 ( 정산예정일 : \" + SEARCHDATE + \")\";\n\t\n\t$(\"#calculateDateCompanyModal\").iziModal('setTitle', title);\n\t$(\"#calculateDateCompanyModal\").iziModal('open');\n\t\n\tloadCalculateDateCompany(calculateDateCompanyModalDrawTable, SEARCHDATE, null, null, null);\n\tinitDateCompanySelectBox();\n}", "static checkAndPaintDays(url,date) {\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function () {\n if (this.readyState === 4 && this.status === 200) {\n let a = JSON.parse(this.response);\n Infrastructures.checkWeekDates(\"#calendar_content div\", date, a, \"no-work\", \"holidaySelector\");\n }\n };\n xhttp.open(\"GET\",url, true);\n xhttp.send();\n }", "function isHoliday(d) {\n try {\n if (obj[go.cal.year][go.cal.month][d] !== undefined) {\n return true;\n } else {\n return false;\n }\n } catch (E) {}\n}", "function calDateReserveInfo(obj){\n\t\n\t//상세화면 진입시 해당일자의 정산 데이터를 가져오기 위한 처리\n\tSEARCHDATE = $(obj).closest('tr').children(\":eq(1)\").text();\n\t\n\t//modal title를 유동적으로 처리하기 위해 받아온 data로 modal타이틀을 setting \n\tlet title = \"정산 - 예약별 ( 정산예정일 : \" + SEARCHDATE + \")\";\n\t\n\t$(\"#calculateDateReserveModal\").iziModal('setTitle', title);\n\t$(\"#calculateDateReserveModal\").iziModal('open');\n\t\n\tloadCalculateDateReserve(calculateDateReserveModalDrawTable, SEARCHDATE, null, null, null);\n\tinitDateReserveSelectBox();\n}", "function loadPopupResize(dt,start_time){\n var time,convert_time,end_time,full_date;\n end_time=getHoursTime(dt);\n\n month_name=getMonthName(end_time['month']);\n\n data_header=month_name+' '+end_time['date']+', '+end_time['year'];\n\n time=dt.substr(dt.indexOf(\"T\") + 1);\n start_time=start_time.substr(start_time.indexOf(\"T\") + 1);\n\n convert_time=convertTimeIntoAmPm(time);\n data_header='Your schedule on '+data_header+' at '+convert_time;\n full_date=time;\n\n $('#checkboxGroup').html('<h4>All schedule day will be change after submit </h4>');\n $('#date-header').html(data_header);\n $('#to_time').val(full_date);\n $('#from_time').val(start_time);\n $('.modal-footer').html('<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button><button type=\"submit\" class=\"btn btn-success\">Submit</button>');\n $('#calenderModal').modal( 'show' );\n}", "function MarkDay(dt) {\r\n var isHolliday = holidays[dt];\r\n if (isHolliday) {\r\n return { classes: 'holliday' };\r\n }\r\n if(dt<minDate || dt>maxDayDate){\r\n \treturn {classes: 'old'};\r\n }\r\n}", "function checkLoadHoliday() {\n if (newHolidayStart_date == \"\" || newHolidayEnd_date == \"\") {\n alert(\"Blank space detected\");\n return false;\n } else if (newHolidayStart_date > newHolidayEnd_date) {\n alert(\"Wrong time\")\n return false;\n }\n\n return true;\n}", "function _dt_date(clickedval) {\n $('#datareturn').addClass('hidden');\n $('.hidewrapper').addClass('hidden');\n if (clickedval == null) {\n var startdate = $('#startfiscal').val();\n } else {\n var startdate = clickedval;\n }\n oTable = $('#table_date').DataTable({\n dom: \"<'row'<'col-sm-4 pull-left'l><'col-sm-4 text-center'B><'col-sm-4 pull-right'f>>\" + \"<'row'<'col-sm-12'tr>>\" + \"<'row'<'col-sm-4 pull-left'i><'col-sm-8 pull-right'p>>\",\n destroy: true,\n \"scrollX\": true,\n \"aoColumnDefs\": [\n {\n \"aTargets\": [6], // Column to target\n \"mRender\": function (data, type, full) {\n // 'full' is the row's data object, and 'data' is this column's data\n // e.g. 'full[0]' is the comic id, and 'data' is the comic title\n return '<a href=\"https://www.ups.com/track?loc=en_US&tracknum=' + data + '&requester=WT/trackdetails\" target=\"_blank\">' + data + '</a>';\n }\n }\n ],\n 'sAjaxSource': \"globaldata/custcomp_dtdate_data.php?startdate=\" + startdate,\n buttons: [\n 'copyHtml5',\n 'excelHtml5'\n ]\n });\n $('#modal_date').modal('hide');\n $('#section_date').removeClass('hidden');\n deleteAllCookies();\n}", "function isHoliday(dt, arr){\n console.log(arr);\n var bln = false;\n for ( var i = 0; i < arr.length; i++) {\n if (compare(dt, arr[i])) { //If days are not holidays\n bln = true;\n break;\n }\n }\n return bln;\n }", "function checkyearofcensus() {\r\n \r\n loadDate();\r\n\r\n}", "static cal_holiday(jdn) {\r\n\tjdn=Math.round(jdn);\r\n\tvar myt,my,mm,md,mp,mmt,gy,gm,gd;\r\n\tvar yo=ceMmDateTime.j2m(jdn);\r\n\tmyt=yo.myt; my=yo.my; mm = yo.mm; md=yo.md;\r\n\tmp=ceMmDateTime.cal_mp(md,mm,myt);\r\n\tmmt=Math.floor(mm/13); var hs=[];\r\n\tvar go=ceDateTime.j2w(jdn);\r\n\tgy=go.y; gm=go.m; gd=go.d;\r\n\t//---------------------------------\r\n\t// Thingyan\r\n\tvar SY=1577917828.0/4320000.0; //solar year (365.2587565)\r\n\tvar MO=1954168.050623; //beginning of 0 ME\r\n\tvar BGNTG=1100, SE3=1312;//start of Thingyan and third era\r\n\tvar akn,atn,ja,jk;\r\n\tja=SY*(my+mmt)+MO; // atat time\r\n\tif (my >= SE3) jk=ja-2.169918982; // akya time\r\n\telse jk=ja-2.1675;\r\n\takn=Math.round(jk); atn=Math.round(ja);\r\n\tif(jdn==(atn+1)) {hs.push(\"Myanmar New Year's Day\");}\r\n\tif ((my+mmt)>=BGNTG) {\r\n\t\tif(jdn==atn) {hs.push(\"Thingyan Atat\");}\r\n\t\telse if((jdn>akn)&&(jdn<atn)) {hs.push(\"Thingyan Akyat\");}\r\n\t\telse if(jdn==akn) {hs.push(\"Thingyan Akya\");}\r\n\t\telse if(jdn==(akn-1)) {hs.push(\"Thingyan Akyo\");}\r\n\t\telse if(((my+mmt)>=1369)&&((my+mmt)<1379)&&((jdn==(akn-2))||\r\n\t\t\t((jdn>=(atn+2))&&(jdn<=(akn+7))))) {hs.push(\"Holiday\");}\r\n\t}\r\n\t//---------------------------------\r\n\t// holidays on gregorian calendar\t\r\n\tif((gy>=2018) && (gm==1) && (gd==1)) {hs.push(\"New Year's Day\");}\r\n\telse if((gy>=1948) && (gm==1) && (gd==4)) {hs.push(\"Independence Day\");}\r\n\telse if((gy>=1947) && (gm==2) && (gd==12)) {hs.push(\"Union Day\");}\r\n\telse if((gy>=1958) && (gm==3) && (gd==2)) {hs.push(\"Peasants' Day\");}\r\n\telse if((gy>=1945) && (gm==3) && (gd==27)) {hs.push(\"Resistance Day\");}\r\n\telse if((gy>=1923) && (gm==5) && (gd==1)) {hs.push(\"Labour Day\");}\r\n\telse if((gy>=1947) && (gm==7) && (gd==19)) {hs.push(\"Martyrs' Day\");}\r\n\telse if((gy>=1752) && (gm==12) && (gd==25)) {hs.push(\"Christmas Day\");}\r\n\telse if((gy==2017) && (gm==12) && (gd==30)) {hs.push(\"Holiday\");}\r\n\telse if((gy>=2017) && (gm==12) && (gd==31)) {hs.push(\"Holiday\");}\r\n\t//---------------------------------\r\n\t// holidays on myanmar calendar\r\n\tif((mm==2) && (mp==1)) {hs.push(\"Buddha Day\");}//Vesak day\r\n\telse if((mm==4)&& (mp==1)) {hs.push(\"Start of Buddhist Lent\");}//Warso day\r\n\telse if((mm==7) && (mp==1)) {hs.push(\"End of Buddhist Lent\");}\r\n\telse if((my>=1379) && (mm==7) && (md==14||md==16)) {hs.push(\"Holiday\");}\r\n\telse if((mm==8) && (mp==1)) {hs.push(\"Tazaungdaing\");}\r\n\telse if((my>=1379) && (mm==8) && (md==14)) {hs.push(\"Holiday\");}\r\n\telse if((my>=1282) && (mm==8) && (md==25)) {hs.push(\"National Day\");}\r\n\telse if((mm==10) && (md==1)) {hs.push(\"Karen New Year's Day\");}\r\n\telse if((mm==12) && (mp==1)) {hs.push(\"Tabaung Pwe\");}\r\n\t//---------------------------------\r\n\t// //other holidays\t\r\n\t// var ghEid=[2456513,2456867,2457221,2457576,2457930,2458285,2458640];\t\r\n\t// if(ceMmDateTime.bSearch1(jdn,ghEid)>=0) {hs.push(\"Eid\");}\r\n\r\n\t// // var ghDiwali=[2456599,2456953,2457337,2457691,2458045,2458430,2458784];\r\n\t// // if(ceMmDateTime.bSearch1(jdn,ghDiwali)>=0) {hs.push(\"Diwali\");}\r\n\t// if((mm==7) && (mp==3)) {hs.push(\"~Diwali\");}\r\n\t//---------------------------------\r\n\treturn hs;\r\n}", "function loadPopupBox(from_time, to_time){\n var start_time,end_time,monthNames,data_header,from_time,to_time,month_name,date_hidden;\n\n start_time=getHoursTime(from_time);\n end_time=getHoursTime(to_time);\n \n month_name=getMonthName(start_time['month']);\n\n data_header=month_name+' '+start_time['date']+', '+start_time['year'];\n\n\n from_time=start_time['hours']+':'+start_time['minute']+':'+start_time['second'];\n end_time=end_time['hours']+':'+end_time['minute']+':'+end_time['second'];\n\n data_header = \"Your schedule is \"+data_header+' at '+convertTimeIntoAmPm(from_time)+' to '+convertTimeIntoAmPm(end_time);\n\n $('#date-header').html(data_header);\n\n date_hidden=start_time['year']+'-'+start_time['month']+'-'+start_time['date'];\n $('.date-hidden').val(date_hidden);\n $('#from_time').val(from_time);\n $('#to_time').val(end_time);\n\n \n $('#calenderModal').modal( 'show' );\n}", "function getHolidays(month, year, country) {\r\n\r\n if (month != \"\" && year != \"\" && country != \"\") {\r\n if (month < Number(new Date().getMonth()) + 1) {\r\n document.querySelector(\"#outputMsg\").innerHTML = \"\";\r\n let getCorsRequest = makeCorsRequest(month, year, country);\r\n \r\n getCorsRequest.then(\r\n response => {\r\n let holidays = JSON.parse(response).holidays;\r\n if (holidays != undefined) {\r\n let holidaysDate = holidays.map(function(holiday) {\r\n return holiday.date;\r\n });\r\n // holidaysDate.forEach(date => {\r\n // console.log(date.slice(8, 10));\r\n // });\r\n calendarHolidayDates = holidaysDate;\r\n return holidaysDate;\r\n }\r\n return false;\r\n },\r\n err => {\r\n throw Error(response.statusText);\r\n }\r\n );\r\n } else {\r\n document.querySelector(\"#outputMsg\").innerHTML = \"\";\r\n document.querySelector(\"#outputMsg\").innerHTML =\r\n \"<code>Holidays will not be highlighted for your selected date, you can still get your calendar. Sorry!&nbsp; Holiday Api is limited to historical data for free accounts. A premium account access is required to current and upcoming holiday data. <br> Franco MaC :)</code>\";\r\n }\r\n }\r\n }", "function checkHolidayCalendar(date){\n\ttry{\n\t//check if this is a weekend and return true if yes\n\tvar dayOfWeek = date.getDay();\n \tif (dayOfWeek == 0 || dayOfWeek == 6) return true;\n \t//now check the calendar\n\tvar holiday = false;\n\tvar calArr = new Array();\n\tvar agency = aa.getServiceProviderCode();\n\t//get the holiday calendars\n\tvar initialContext = aa.proxyInvoker.newInstance(\"javax.naming.InitialContext\", null).getOutput();\n\tvar ds = initialContext.lookup(\"java:/AA\");\n\tvar conn = ds.getConnection();\n\tvar selectString = \"select * from CALENDAR WHERE SERV_PROV_CODE = ? AND CALENDAR_TYPE='AGENCY HOLIDAY' AND REC_STATUS='A'\";\n\tvar sStmt = conn.prepareStatement(selectString);\n\tsStmt.setString(1, agency);\n\tvar rSet = sStmt.executeQuery();\n\twhile (rSet.next()) {\n\t\tcalArr.push(rSet.getString(\"CALENDAR_ID\"));\n\t}\n\tsStmt.close();\n\tconn.close(); \n\tfor (var c in calArr){\n\t\tvar cal = aa.calendar.getCalendar(calArr[c]).getOutput();\n\t\tvar events = aa.calendar.getEventSeriesByCalendarID(calArr[c], date.getYear()+1900, date.getMonth()+1).getOutput();\n\t\tfor (var e in events){\n\t\t\tvar event = events[e];\n\t\t\tvar startDate = new Date(event.getStartDate().getTime());\n\t\t\tvar startTime = event.getStartTime();\n\t\t\tvar endDate = event.getEndDate();\n\t\t\tvar allDay = event.isAllDayEvent();\n\t\t\tvar duration = event.getEventDuration();\n\t\t\tif (dateDiff(startDate,date) >= 0 && dateDiff(startDate,date) < 1){\n\t\t\t\tholiday = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn holiday;\n\t}\n\tcatch(r){aa.print(r);}\n}", "function w_displayDatePicker(linkedId1) {\n \n\tw_linkedInputText_1 = linkedId1;\n\tw_linkedInputText_2 = null;\n\n HideWeekCol = true;\t\n w_displayCal();\n}", "function validateHolyday()\r\n {\r\n \r\n /* Variable that saves the holiday to add */\r\n /* Variable que guarda el dia feriado a agregar */\r\n var holyday=$(\"#holyday\").val();\r\n \r\n /* If the holiday is empty, an alert is generated */\r\n /* Si el dia feriado esta vacio se genera un alerta */\r\n if(holyday==\"\")\r\n {\r\n \r\n alert(\"Select a date to add it to the holiday list.\");\r\n return false;\r\n \r\n }\r\n \r\n /* If the holiday is full, the date is returned */\r\n /* Si el dia feriado esta lleno se devuelve la fecha */\r\n else\r\n {\r\n \r\n return holyday;\r\n \r\n }\r\n \r\n }", "function test_service_dialog_date_datetime_picker_dynamic_dialog() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
line reader works perfectly fine this takes all the urls and recursively gets the requests on them
function runRequest(lines) { if (continueRequesting && lines.length > 0) { var line = lines.pop() console.log('urls to get: ' + lines.length) var request = http.get(line, function(res) { var body = ''; res.on('error', function(err) { console.log('we got an error!') console.log(e.message);}); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { uniqueURLArray.push(line); //load the cheerio object var $ = cheerio.load(body); //first thing to do is determine the number of pages to link to (there will be a max of 3 pages of info to scrape through and it'd be better to find those pages using cheerio than doing it manually // the urls are all p2, p3, p4 etc and if we put the first url in there then the rest will follow var url = $('a.Next').prev().attr('href'); //the sibling of the next button (which is the last page of results) //console.log(url, line); if (url != null) { pgNum = url.replace('.html', '').slice(-2).replace(/[^\d]/g,''); //get the page number for (var ii = 2; ii <= pgNum; ii++) { uniqueURLArray.push(url.replace(/(-p(\d+)[.]html)/g, '-p' + ii + '.html')); } } //if the request timed out if (timeout) { timeout = false; console.log(completed_requests, line); } //once 5 requests are completed start parsing the data if (completed_requests++ == 5) { continueRequesting = true; //now get the messages console.log('num urls: ' + uniqueURLArray.length); var messages = []; getMessages(uniqueURLArray, messages, uniqueURLArray.length); //now the messages are all here //time to filter } setTimeout(runRequest(lines), tools.randInt(0,100)); //works with 500-1000 }); }); //request stuff request.setTimeout(90000, function () { request.abort(); console.log('request timed out'); timeout = true; }); request.on('error', function(e) { console.log(e); completed_requests++; }); } }
[ "async function loadMore(pages, url, line) {\n \n for ( let i = 1; i < pages +1; i++ ) {\n await fetch( url + '&page=' + i, {\n \"method\" : \"GET\",\n \"headers\": headers\n } )\n .then( res => res.json() )\n .then( function( data ) {\n data.items.forEach(async element => {\n let file_name = element.name\n \n let url_response = await fetch(element.url,\n {\n \"method\" : \"GET\",\n \"headers\": headers\n })\n \n let url_result = await url_response.json()\n let yaml_file_download_url = url_result.download_url;\n if(yaml_file_download_url.includes(\".travis.yml\")){\n try{\n yaml_paths.write(`${yaml_file_download_url}\\n`) \n repos_with_travis.write((`${line} \\n`))\n }\n catch(e){\n console.log(e)\n \n }\n \n }\n else if(yaml_file_download_url.includes(\".github/workflows\")){\n try{\n yaml_paths.write(`${yaml_file_download_url}\\n`) \n repos_with_github.write((`${line} \\n`))\n }\n catch(e){\n console.log(e)\n \n }\n \n }\n else if(yaml_file_download_url.includes(\"appveyor\")){\n try{\n yaml_paths.write(`${yaml_file_download_url}\\n`) \n repos_with_appveyor.write((`${line} \\n`))\n }\n catch(e){\n console.log(e)\n \n }\n \n }\n else if(yaml_file_download_url.includes(\"wercker\")){\n try{\n yaml_paths.write(`${yaml_file_download_url}\\n`) \n repos_with_wercker.write((`${line} \\n`))\n }\n catch(e){\n console.log(e)\n \n }\n \n }\n else if(yaml_file_download_url.includes(\".circleci/config.yml\")){\n try{\n yaml_paths.write(`${yaml_file_download_url}\\n`) \n repos_with_circle.write((`${line} \\n`))\n }\n catch(e){\n console.log(e)\n \n }\n \n }\n \n \n \n }) \n })\n .catch(function(err) {\n console.log(err);\n });\n \n }\n}", "function crawlRecipe (urlArray, iterator) {\n console.log('url : ' + urlArray[iterator])\n console.log('arrayLength -1: ' + (urlArray.length - 1))\n console.log('iterator : ' + iterator)\n // Crawl another if more in array. If not stop\n if (iterator === urlArray.length - 1) {\n console.log('Finished!')\n wstream.end()\n return\n }\n if (iterator < urlArray.length - 1) {\n requestContent (urlArray[iterator], urlArray, iterator)\n }\n}", "function scrapAMatch(url){\n // async function\n request(url, cb);\n}", "function process_urls(urls) {\n // Loop the urls array and make async requests\n urls.forEach(function(url) {\n request({url: url, timeout: timeout}, function(err, res, body) {\n var ret = [];\n ret.push(url);\n\n // check for errors with the request\n if (err) {\n ret.push('');\n ret.push(err.message.red);\n data.push(ret);\n return;\n }\n\n // response code\n if (res.statusCode === 200)\n ret.push(('' + res.statusCode).green);\n else\n ret.push(('' + res.statusCode).red);\n\n // body\n body = body || '';\n body = body.split('\\n')[0];\n ret.push(body);\n\n data.push(ret);\n });\n });\n}", "divideAndCrawl() {\n const chunks = _array.chunk(this.hyperlinks, this.maxRequests);\n if (this.refIndexChunk >= chunks.length) return Promise.resolve();\n return Promise.map(chunks[this.refIndexChunk++], item => this.crawlEach(item.link))\n .then(() => this.divideAndCrawl());\n }", "async findPathByURL() {\n RequestManager.emitter.on(this.queue, async (urlData) => {\n try {\n let domManager = new DOMManager(urlData);\n let links = RequestManager.getLinksContainDomain(Utils.removeDuplicate(domManager.getAllLinks()), this.domain);\n let newPaths = await this.findAndInsertNewPathsAndUpdateOld(links);\n newPaths.forEach(element => this.crawl(element));\n } catch (err) {\n Utils.registerLogs(Utils.ERROR, err);\n }\n });\n }", "function ex3_2b() {\r\n var index = [\"https://lemida.biu.ac.il/\",\r\n \"https://ims.gov.il/\",\r\n \"https://www.mizrahi-tefahot.co.il/\",\r\n \"https://www.maariv.co.il/\",\r\n \"https://www.wikipedia.org/\"]; \r\n // Set up a namespace for our XMLHttpRequest\r\n var XMLHttpRequest = require(\"xmlhttprequest\").XMLHttpRequest;\r\n (function loop(i) {\r\n if (i>= index.length) {\r\n return;\r\n }\r\n var url = index[i];\r\n // By moving the creation of the request variable into the loop function, we can make sure that the asynchronous aspect\r\n // will work properly and we won`t have a situation where one url request will run over the data of another request,\r\n // leading to undesired and wrong results. \r\n var request = new XMLHttpRequest();\r\n request.open(\"GET\", url, true);\r\n request.onreadystatechange = function() {\r\n if(request.readyState === 4 && request.status === 200) {\r\n var data = request.responseText;\r\n console.log('-->' + i + ' id: ' + data.substring(1,1500));\r\n console.log(\"---------------------------\\n\")\r\n // By calling the loop from within onreadystatechange we make sure the requests are sent in syncronized order.\r\n // Only after we send the request and the url request response is done is the onreadystatechange function preformed.\r\n // In turn we call the loop for the next url in order.\r\n loop(i + 1); \r\n }\r\n }\r\n request.send(); \r\n })(0);\r\n }", "function executeURLS() {\n\n for(var i = 0, len = documentsURL.length; i < len; i++) {\n (function () {\n var aux = i, endChecker = false;\n\n request(documentsURL[i], function (error, response, body) {\n if (!error) {\n if(aux === len - 1) {\n endChecker = true;\n }\n parseDocument(body, documentsURL[aux], endChecker);\n } else {\n console.log(error);\n }\n });\n })();\n }\n }", "function scrapURL(body) {\n\n var $ = cheerio.load(body);\n\n $(\"a[href*='shirt']\",\"#content\").each(function() {\n var link = $(this);\n var href = link.attr(\"href\");\n var productLinks = url.resolve(productpageURL,\"/\" + href);\n //console.log(productLinks);\n visitProductpage(productLinks);\n });\n}", "main()\n {\n this.getInnerLinks(this.url).then((result) => {\n \n const loop = async value => {\n let i = 0;\n let minValue = Math.min(this.limitCrawling,this.internalUrl.length);\n\n while (i < minValue) \n {\n let url = this.getNextVisitingLink();\n let result = await this.getInnerLinks(url);\n console.log('visiting internal url:'+url);\n this.setVisitedIncrement();\n i++;\n }\n }\n\n // display what was discovered in the console after the loop finishes\n loop(0).then(() => this.getData());\n });\n }", "function readUrls(i) {\r\n\tif (i < 5) {\r\n\t\treadUrl(process.argv[i], i, callback);\r\n\t}\r\n}", "function indexUrl(mainUrl, client)\n{\n linksToIndex = getAllLinksToIndex(mainUrl)\n \n XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest\n for(i=0; i<linksToIndex.length; i++) {\n xmlHttp = new XMLHttpRequest()\n xmlHttp.open(\"GET\", linksToIndex[i], false); // false for synchronous request\n xmlHttp.send()\n str = xmlHttp.responseText\n str = removeUnneededTags(str)\n pageParts = str.split(/<.*?>\\s*/).filter(function (el) { return el.length > 0 })\n \n pageSentences = extractSentences(pageParts)\n \n console.log(linksToIndex[i] + ' ' + i)\n \n pageSentences.forEach(function(sentence){indexSentence(client, linksToIndex[i], sentence)})\n }\n\n console.log('indexed done')\n}", "async function getLines(url) {\n let resp = await rp(url);\n \n function __storeData(key, string) {\n if (!chainObjTemp[key]) {\n chainObjTemp[key] = string.split(' ');\n } else {\n chainObjTemp[key] = chainObjTemp[key].concat(string.split(' '));\n }\n }\n\n let tarLen = $('font', resp).length;\n\n for (let i = 0; i < tarLen; i += 1) {\n // get the data from the first child, where the line is kept\n let kids = $('font', resp)[i].children;\n \n let kidsLen = kids.length;\n \n if (kids[0].type === 'text' && kidsLen > 1) {\n let textSplit = kids[0].data.split(' - ');\n // get character name key\n let key = textSplit[0];\n if (characters.includes(key)) {\n __storeData(key, textSplit[1]);\n }\n // iterate through children array find all text nodes\n for (let k = 1; k < kidsLen; k += 1) {\n if (kids[k].type === 'text') {\n if (characters.includes(key)) {\n __storeData(key, kids[k].data);\n }\n }\n }\n } else if (kids[0].type === 'text' && kidsLen === 1) {\n let textSplit = kids[0].data.split(' - ');\n // get character name key\n let key = textSplit[0];\n if (characters.includes(key)) {\n __storeData(key, textSplit[1]);\n }\n }\n }\n console.log(`finished writing ${url.slice(url.lastIndexOf('/'))}`);\n return 'done';\n}", "function findHttpRequests(tmpLine) {\n let result;\n const substring1 = 'httpsrequest.basepath';\n const substring2 = 'httprequest.basepath';\n\n // look for substrings\n if (((tmpLine.indexOf(substring1) !== -1) || (tmpLine.indexOf(substring2) !== -1)) && (tmpLine.indexOf('#') === -1)) {\n result = parseLineForArtifact(tmpLine);\n } else {\n result = null;\n }\n\n return result;\n}", "function startParser() {\n\n for(var i = 0; i < numeroDePaginas; i++) {\n\n (function () {\n var aux = i;\n\n pagina = offset + (i + 1);\n URL = baseURL + consultaURL + pagina;\n\n request(URL, function (error, response, body) {\n\n if (!error) {\n var $ = cheerio.load(body),\n fields = $('table').last().find('.campo:nth-child(3)').find('a'),\n docURL;\n\n // console.log(body);\n\n for(var i = 0, len = fields.length; i < len; i++) {\n docURL = $(fields[i]).prop('href');\n documentsURL.push(baseURL + docURL);\n }\n\n // captcha\n if(documentsURL.length === 0) {\n console.log('Captcha apareceu! :(');\n }\n else {\n // execute URLs when get all of them\n if(aux === numeroDePaginas - 1) {\n console.log(documentsURL.length + ' urls serão executadas!');\n console.log('======================================================');\n setTimeout(function() {\n executeURLS();\n }, 1000);\n }\n }\n } else {\n console.log(error);\n }\n });\n })();\n }\n }", "async function main () {\n let path = `${__dirname}/UrlData.json`;\n let urlData;\n try {\n urlData = await getFileAsJSON(path);\n } catch (e) {\n throw e;\n }\n\n try {// Get the number of files now and then create new file name according the number\n let count = await fs.readFileAsync(\"../filelist.txt\", 'utf-8');\n fileCount += count.split('\\n').length - 1;\n console.log(fileCount);\n } catch (e) {\n // This means the filelist.txt not exist, it will be created later\n }\n \n for (let i=0; i<urlData.url.length; i++) { //Crawl the url listed in UrlData.json\n if(fileCount > 50) {\n console.log(\"Too much web pages!\");\n return;\n }\n await crawlerAllPages(urlData.url[i]);\n }\n}", "function main(url){\n\n var instream = fs.createReadStream('date_ranges_100stars.txt');\n var outstream = new stream;\n var rl = readline.createInterface(instream, outstream);\n console.log(\"start\")\n rl.on('line', function(line) {\n\n ranges.push(line)\n })\n rl.on('close', async function() {\n\n for(let i = 0; i<ranges.length; i++){\n console.log(ranges[i])\n await getRepos(ranges[i], url)\n }\n });\n}", "function urls_restaurant_scrape(url,callback){\n var urls_restaurant=[];\n request(url, function(err,resp,html){ \n var $=cheerio.load(html);\n $('.poi-card-link').each(function(){\n var tmp= \"https://restaurant.michelin.fr\";\n tmp+=$(this).attr('href');\n urls_restaurant.push(url_temp); \n });\n callback(urls_restaurant); //when it's finish, we catch the restaurant information urls put before in the urls_restaurant array\n });\n}", "static fetchAndCheerio(url) {\n return (0, _bluebird.coroutine)(function* () {\n debug('retriving url: %s', url);\n let response = yield needle('get', url);\n debug('retrieved response:', response.body);\n return cheerio.load(response.body);\n })();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Figure out component to be shown at root based on user credentials
getHomeComponent() { const { owner } = this.props; const credentials = getCredentials(owner); const onboarding = isOnboarding(credentials); const signedIn = isSignedIn(credentials); const isGeneral = isGeneralOwner(credentials); const isSubscriber = isSubscriberOwner(credentials); let homeComponent; if (onboarding) { homeComponent = () => <Redirect to={{ pathname: '/onboarding' }} />; } else if (!signedIn) { homeComponent = Login; } else if (isSubscriber) { // Dashboard for both subscriber and subscriber ownrers (subscribers with shares) homeComponent = SubscriberDashboard; } else if (isGeneral) { homeComponent = GeneralDashboard; } return homeComponent; }
[ "render() {\n let loggedin;\n if (window.localStorage.getItem(\"AuthToken\") !== null) {\n loggedin = true;\n } else {\n loggedin = false;\n }\n return <div id=\"parentDiv\">{loggedin ? <PrivateApp /> : <Login />}</div>;\n }", "function getUserAndShowView() {\n switchVisibleElement('loading');\n getCurrentUser(function(user) {\n currentUser = user;\n if (user) {\n console.log('Logged in, showing room selection');\n switchVisibleElement('room-selection');\n } else {\n console.log('No user logged, showing login form');\n switchVisibleElement('form');\n }\n });\n}", "function _getRootView(){\n ermsRepoService.connect();\n }", "renderPanel(){\n this.server.get('/panel', this.isAuthenticated, (req, res) => {\n try {\n res.render('panel', {\n username: req.user.username,\n apiKey: config.apiKey,\n email: config.email\n });\n } \n catch (err){\n this.App.throwAlert(err);\n res.status(500).send(err);\n }\n });\n \n this.App.debug(\"The server is registering route: \\\"/panel\\\" aiming to: panel\");\n }", "renderAdminPanel() {\n const {isAuth, role} = this.context;\n console.log( role +\", \"+ config.ADMIN_ROLE_NAME )\n if(isAuth && role === config.ADMIN_ROLE_NAME) {\n return(\n <React.Fragment>\n <div className=\"card mt-md-3\">\n <div className=\"card-header\">Admin tools</div>\n <div className=\"card-body\">\n <ul>\n <li><Link to=\"/news/compose\">Compose or edit drafts</Link></li>\n </ul>\n </div>\n </div>\n <div className=\"alert alert-success mt-3\">[Admin notice] News shown below are public. Users will see News section as it's shown below.</div>\n <hr/>\n </React.Fragment>\n );\n }\n }", "renderTemplate() {\n this.render({\n outlet: 'login'\n });\n\n const { isInternal } = get(this, 'controller').get('model');\n\n if (isInternal) {\n run.scheduleOnce('afterRender', this, 'showTwoFABanner');\n }\n }", "renderTemplate() {\n this.render({\n outlet: 'login'\n });\n }", "static async getLogin(ctx) {\n const context = ctx.flash.formdata || {};\n\n // user=email querystring?\n if (ctx.request.query.user) context.username = ctx.request.query.user;\n\n if (context.username) {\n // if username set & user has access to more than one org'n, show list of them\n const [ usr ] = await User.getBy('email', context.username);\n if (usr && usr.databases.length>1) context.databases = usr.databases;\n }\n\n await ctx.render('login', context);\n }", "render() {\r\n if(this.props.loggedIn) {\r\n return(ViewsiteJSX.call(this));\r\n } else {\r\n return(<Redirect to=\"/\" />);\r\n }\r\n }", "renderContent() {\n if (this.state.startApp === 1 && this.state.loggedIn > -1)\n return this.checkLoginState();\n else return this.renderLogoPage(); // I will keep showing the startup image until I change the startApp value\n }", "showLogin({ view, session }) {\n return view.render('auth.login')\n }", "getAuthComponents($$) {\n const components = [];\n const userAuth = $$('div')\n .addClass(styles.userAuth);\n\n // Not authenticated.\n if (this.state.authenticated === false) {\n const LoginButton = $$('button')\n .addClass(styles.login)\n .on('click', async () => this.handleSetAuthState(\n authService.login(), true,\n ))\n .setInnerHTML('Login');\n\n // Authentication error\n if (this.state.authenticationError !== null) {\n components.push($$('p')\n .text(this.state.authenticationError));\n components.push($$('p')\n .text('Please contact site admin for support.'));\n }\n\n return userAuth.append([LoginButton, ...components]);\n }\n\n if (this.state.authenticated === true) {\n // Add user info if available.\n if (this.state.user) {\n components.push($$('p').append($$('em')\n .text(`Logged in as ${this.state.user.email}`)));\n }\n\n const LogoutButton = $$('button')\n .addClass(styles.logout)\n .on('click', async () => { authService.logout(); })\n .setInnerHTML('Logout');\n\n return userAuth.append([...components, LogoutButton]);\n }\n\n return userAuth.append($$('p').text('Loading user...'));\n }", "render() {\n const {\n currentForm,\n authorized,\n forms,\n jotformWidgets,\n selectedWidgets,\n user\n } = this.state;\n\n return (\n <Switch>\n <Route\n exact\n path=\"/\"\n component={() => (\n <LoginPage authorized={authorized} getUserData={this.getUserData} />\n )}\n />\n <Route\n path=\"/forms\"\n component={() => (\n <Forms\n user={user}\n authorized={authorized}\n setCurrentForm={this.setCurrentForm}\n forms={forms}\n jotformWidgets={jotformWidgets}\n selectedWidgets={selectedWidgets}\n setAuthFalse={this.setAuthFalse}\n />\n )}\n />\n <Route\n path=\"/submissions\"\n component={() => (\n <Submissions\n user={user}\n form={currentForm}\n authorized={authorized}\n setAuthFalse={this.setAuthFalse}\n />\n )}\n />\n </Switch>\n );\n }", "_renderNewRootComponent(/* instance, ... */) { }", "render() {\r\n if(this.props.loggedIn) {\r\n return(<Redirect to={\"/viewsites/\" + this.props.viewsite.viewsiteName} />);\r\n } else {\r\n return (UserUserFormJSX.call(this));\r\n }\r\n }", "renderLogin() {\n const {\n confirm, description, handleAuthInteraction, header, isInteractive, label,\n authServiceId, windowId,\n } = this.props;\n if (!isInteractive) return null;\n\n return (\n <WindowAuthenticationBar\n header={header}\n description={description}\n label={label}\n confirmButton={confirm}\n onConfirm={() => handleAuthInteraction(windowId, authServiceId)}\n {...this.defaultAuthBarProps()}\n />\n );\n }", "render() {\n\t\treturn(\n\t\t\t(userApi.isLoggedIn()?(\n\t\t\t\t<main>\n\t\t\t\t\t<Route path='/' render={() => (<TeamSelection willLogout={this.props.willLogout} />)} />\n\t\t\t\t</main>\n\t\t\t) : (\n\t\t\t\t<LoginForm onLogin={this.onLogin} onRegister={this.onRegister} />\n\t\t\t))\n\t\t)\n\t}", "render(){\n let componentContent;\n if(!this.props.isCallBack){\n if(Authentication.authenticationService.isLoggedIn()){\n componentContent = super.render();\n }\n else{\n Authentication.authenticationService.setOriginalUrl(this.props.path);\n //Authentication.authenticationService.startAuthentication();\n componentContent = <Redirect to={'/'} />;\n }\n }\n else{\n componentContent = (this.state.hasFinishedAuthentication) ? (\n <Redirect to={Authentication.authenticationService.getOriginalUrl()} />\n ) : super.render();\n }\n return componentContent;\n }", "function App() {\n const [authed, setAuthed] = useState(undefined);\n const [onboard, setOnboard] = useState(undefined);\n\n /**\n * Wraps given component with auth condition, rerouting to the\n * login page if the user is not yet auth'd in. Returns the given\n * component if user is logged in, reroutes otherwise.\n * \n * @param {Component} component - component to render\n * @return {Component} - component to render after considering auth\n */\n function withAuth(component) {\n if (authed === false) {\n // prevent routing loop and return Login if not authed\n if (component === Login) return Login;\n return () => <Redirect to=\"/login\" />;\n }\n\n //reroute to welcome if not onboarded\n if (onboard === false) {\n // prevent routing loop and return welcome if not onboarded\n if (component === Welcome) return Welcome;\n return () => <Redirect to=\"/welcome\"/>;\n }\n \n // reroute /welcome to /dashboard if onboarded\n if (onboard === true && component === Welcome) {\n return () => <Redirect to=\"/dashboard\" />;\n }\n\n // reroute /login to /dashboard if already logged in\n if (authed === true && component === Login) {\n return () => <Redirect to=\"/dashboard\" />;\n }\n // return original component if already auth'd and onboarded\n return component;\n }\n\n // wrap app tree with user session context, so user auth data\n // can be used throughout the DOM tree\n return (\n <UserSession setAuthed={setAuthed} setOnboard={setOnboard}>\n {authed === undefined ? (\n <Loading/>\n ) : (\n <Router>\n <Switch>\n <Route exact path=\"/login\" component={withAuth(Login)} />\n <Route exact path=\"/dashboard\" component={withAuth(Dashboard)} />\n <Route exact path=\"/welcome\" component={withAuth(Welcome)} />\n <Route exact path=\"/tasks\" component={withAuth(Tasks)} />\n <Route component={About} />\n </Switch>\n </Router>\n )}\n </UserSession>\n )\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to return true if the given LR(0) item triple is in the given array
function LRItemInArray(array, lr_item) { for(var a in array) { var obj = array[a]; // Check that the head and dot position match if(obj.head === lr_item.head && obj.dotPosition === lr_item.dotPosition) { // Now compare the body items var allMatched = true; for(var b in obj.body) { if(obj.body[b] !== lr_item.body[b]) { allMatched = false; } } if(allMatched) { return true; } } } return false; }
[ "function isItemInArray(array, item) {\n for (var i = 0; i < array.length; i++) {\n if (array[i][0] === item[0] && array[i][1] === item[1]) return true\n }\n return false;\n }", "function includesArray (arr, item) {\n for (let i = 0; i < arr.length; i++) {\n if (equalArrays(arr[i], item)) {\n return true;\n }\n }\n return false;\n}", "function isInArray(item, array) {\n itemin = false\n for(i = 0; i < array.length; i++) {\n if(array[i] == item) {\n itemin = true\n }\n }\n return itemin\n}", "function in_array(item,arr) {\r\n for(p=0;p<arr.length;p++) if (item == arr[p]) return true;\r\n return false;\r\n}", "function contain(array,item){\n\tfor(var t of array){\n\t\tif(t == item){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function inArray(arr, item) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === item) {\n return true;\n }\n }\n return false;\n }", "function inArray(arr, item) {\n for (var i = 0, len = arr.length; i < len; i++) {\n if (arr[i] === item) {\n return true;\n }\n }\n return false;\n }", "function existed(array, item) {\n\tvar len = array.length;\n\tfor (var i = 0; i < len; i++) {\n\t\tif (item === array[i][0]) return true;\n\t}\n\treturn false;\n}", "function inArray( arr, item ) {\n for ( var i = 0, len = arr.length; i < len; i++ ) {\n if ( arr[ i ] === item ) {\n return true;\n }\n }\n return false;\n }", "function inArray(arr, item) {\n var i, len;\n for (i = 0, len = arr.length; i < len; i++) {\n if (arr[i] === item) {\n return true;\n }\n }\n return false;\n }", "function contains(arr, item){\r\n\tfor(var i = 0; i < arr.length; i++){\r\n\t\tif(arr[i] == item)\r\n\t\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}", "function arrayIncludes(array, item){\n for(var i = 0; i < array.length; i++){\n if(array[i] == item)\n return true;\n }\n return false;\n}", "function check1(element, array){\n\n\t\treturn array.includes(element)\n\t\n}", "function arrayContains( curArr, item )\n{\n var nElements = curArr.length;\n for( var i = 0; i < nElements; i++ )\n if ( curArr[i] == item )\n return true;\n\n return false;\n}", "function contains(array, item) {\r\n var arrayLen = array.length;\r\n for (var i = 0; i < arrayLen; ++i) {\r\n if (array[i] == item) {\r\n return true;\r\n }\r\n }\r\n \r\n return false;\r\n }", "function arrContains(arr, t) {\n if (arr == undefined) {\n return false;\n } else {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === t) {\n return true;\n }\n }\n return false;\n }\n}", "function availableContains(ele, array){\n\tfor(var i = 0; i < array.length; i++)\n\t{\n\t\tif(array[i][0] == ele)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function containsTuple(array, tuple)\r\n{\r\n\tfor(let i = 0; i < array.length; i++)\r\n\t{\r\n\t\tif(array[i][0] == tuple[0] && array[i][1] == tuple[1])\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}", "function isItemInArray(arr, item) {\r\n return arr.includes(item);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder the bus based on all present dependencies.
reorderForDependencies() { if (this.dependencyLinks.size > 0) { const actorsAfter = []; // Temporarily remove all actors that have dependencies for (const actorAfter of this.dependencyLinks.keys()) { const dependentPos = this.actors.indexOf(actorAfter); if (dependentPos >= 0) { this.actors.splice(dependentPos, 1); actorsAfter.push(actorAfter); } } // Iteratively append actors based on the first dependency link // that has all of its dependencies available in the array while (actorsAfter.length > 0) { // Find the first actor that has all of its dependencies available. let activeActorAfterId = -1; for (let i = 0; i < actorsAfter.length; i++) { let validLink = true; for (const dependency of this.dependencyLinks.get(actorsAfter[i])) { if (this.actors.indexOf(dependency) < 0 && actorsAfter.indexOf(dependency) >= 0) { validLink = false; break; } } if (validLink) { activeActorAfterId = i; break; } } // If none of the pending links are possible, there must be a cyclic dependency if (activeActorAfterId < 0) { throw new Error('Cyclic dependency links detected in bus ' + this.name); } // The dependent may not be available (yet), so we don't add it to the array (yet). const activeActorAfter = actorsAfter.splice(activeActorAfterId, 1)[0]; this.actors.push(activeActorAfter); } } }
[ "reorderForDependencies() {\n if (this.dependencyLinks.size > 0) {\n const actorsAfter = [];\n // Temporarily remove all actors that have dependencies\n for (const actorAfter of this.dependencyLinks.keys()) {\n const dependentPos = this.actors.indexOf(actorAfter);\n if (dependentPos >= 0) {\n this.actors.splice(dependentPos, 1);\n actorsAfter.push(actorAfter);\n }\n }\n // Iteratively append actors based on the first dependency link\n // that has all of its dependencies available in the array\n while (actorsAfter.length > 0) {\n // Find the first actor that has all of its dependencies available.\n let activeActorAfterId = -1;\n for (let i = 0; i < actorsAfter.length; i++) {\n let validLink = true;\n for (const dependency of this.dependencyLinks.get(actorsAfter[i])) {\n if (!this.actors.includes(dependency) && actorsAfter.includes(dependency)) {\n validLink = false;\n break;\n }\n }\n if (validLink) {\n activeActorAfterId = i;\n break;\n }\n }\n // If none of the pending links are possible, there must be a cyclic dependency\n if (activeActorAfterId < 0) {\n throw new Error(`Cyclic dependency links detected in bus ${this.name}`);\n }\n // The dependent may not be available (yet), so we don't add it to the array (yet).\n const activeActorAfter = actorsAfter.splice(activeActorAfterId, 1)[0];\n this.actors.push(activeActorAfter);\n }\n }\n }", "reorderDeps(aPolicies,comps) {\n let aSorted=[]; // ordered array\n let sorted={}; // check if in order array\n let unsorted=[];\n const n = aPolicies.length;\n let limit = n*2; // limit in case of cyclic dep\n while(aPolicies.length && limit--)\n {\n unsorted=[];\n for(let i=0;i<aPolicies.length;i++)\n {\n const id = aPolicies[i];\n const conf = comps[id].conf;\n const comp = comps[id].comp;\n const inject = (conf.injections||'');\n if(!inject) \n {\n // no injection \n sorted[id]=true;\n aSorted.push(id);\n aPolicies.splice(i,1);\n }\n else\n {\n let aInject=this._listChildrenInj(inject);\n \n let injSorted=true;\n aInject.forEach(ij=>{\n if(!sorted[ij] && !comp.__init)\n {\n /*\n let comp2 = this.getComponent(ij);\n if(comp2 && !comp2.__init)\n */\n injSorted=false; // deps not yet in sorted => fails this time\n unsorted.push(ij);\n }\n });\n \n if(injSorted)\n {\n // all injections already in ordered array => ok\n sorted[id]=true;\n aSorted.push(id);\n aPolicies.splice(i,1); \n }\n }\n }\n }\n\n for (let i=0;i<aPolicies.length;i++)\n {\n const id = aPolicies[i];\n let comp = this.getComponent(id);\n if(comp)\n {\n aPolicies.splice(i,1);\n }\n }\n\n if(limit<=0 && aPolicies.length)\n {\n const fails = aPolicies.join(',');\n const missing = unsorted.join(',');\n throw new Error(\"Cyclic or missing injection not allowed, check injections for : \"+fails+\" missing = \"+missing);\n }\n\n return aSorted;\n }", "resolveDependencies () {\n\t\tlet sorted;\n\t\ttry {\n\t\t\t// we use the toposort module to figure this out...\n\t\t\tsorted = TopoSort.array(\n\t\t\t\tthis.moduleNames,\n\t\t\t\tthis.moduleDependencies\n\t\t\t);\n\t\t}\n\t\tcatch(error) {\n\t\t\tif (error) {\n\t\t\t\tthrow `Error resolving module dependencies: ${error}`;\n\t\t\t}\n\t\t}\n\t\t// the result of the TopoSort is an array of module names, where those\n\t\t// dependent on others come first ... we need to reverse this so those\n\t\t// dependent on others are registered later\n\t\tthis.modules = sorted.map(moduleName => this.modulesByName[moduleName]);\n\t\tthis.modules.reverse();\n\t}", "function resolveReorder() {\n if (itemsArrangedCount > 0) {\n itemsArrangedCount--;\n }\n\n $timeout(function() {\n if (itemsArrangedCount === 0) {\n $rootScope.$emit('reorder:complete', itemsArrangedCount);\n }\n });\n }", "orderItems() {\n // Items with a preference to go last go last...\n const moving = [];\n while (true) {\n const moveIndex = _.findIndex(self.items, function (item) {\n return item.options.last;\n });\n if (moveIndex === -1) {\n break;\n }\n moving.push(self.items[moveIndex]);\n self.items.splice(moveIndex, 1);\n }\n self.items = self.items.concat(moving);\n // ... But then explicit order kicks in\n _.each(self.options.order || [], function (name) {\n const item = _.find(self.items, { name: name });\n if (item) {\n self.items = [ item ].concat(_.filter(self.items, function (item) {\n return item.name !== name;\n }));\n }\n });\n }", "function reorder() {\n\tconst reorderArray = (newOrder, originalArray) => {\n\t\tconst movedItem = originalArray.filter((item, index) => index === newOrder.oldIndex); \n\t\tconst remainingItems = originalArray.filter((item, index) => index !== newOrder.oldIndex);\n\n\t\tconst reoderedItems = [\n\t\t\t...remainingItems.slice(0, newOrder.newIndex),\n\t\t\t...movedItem,\n\t\t\t...remainingItems.slice(newOrder.newIndex)\n\t\t];\n\t\treturn reoderedItems;\n\t}\n\toriginalArray = reorderArray(newOrder, originalArray)\n\tlistOriginalArray()\n}", "_orderContracts() {\n this.contracts.sort((a, b) => a._getDependenciesCount() - b._getDependenciesCount());\n }", "_order() {\n // reorder the items in all groups\n // TODO: optimization: only reorder groups affected by the changed items\n util.forEach(this.groups, group => {\n group.order();\n });\n }", "cleanupDeps () {\n let i = this.deps.length;\n while (i--) {\n const dep = this.deps[i];\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this);\n }\n }\n let tmp = this.depIds;\n this.depIds = this.newDepIds;\n this.newDepIds = tmp;\n this.newDepIds.clear();\n tmp = this.deps;\n this.deps = this.newDeps;\n this.newDeps = tmp;\n this.newDeps.length = 0;\n }", "function Reorder() {\n\t// Create mapping from old positions to new positions\n\tvar newPositions = [];\n\tvar newNodes = [];\n\tfor (node in nodes) {\n\t\tnewPositions.push($(nodes[node].elem).index() - 1);\n\t}\n\n\tfor (node in nodes) {\n\t\tnewNodes[newPositions[node]] = nodes[node];\n\t}\n\n\t// Replace all connections and dependents with new positions\n\tfor (node in newNodes) {\n\t\tfor (connection in newNodes[node].connections) {\n\t\t\tnewNodes[node].connections[connection] = newPositions[newNodes[node].connections[connection]];\n\t\t}\n\n\t\tfor (dependents in newNodes[node].dependents) {\n\t\t\tnewNodes[node].dependents[dependents] = newPositions[newNodes[node].dependents[dependents]];\n\t\t}\n\t}\n\n\t// Redraw\n\tnodes = newNodes\n\trender();\n}", "cleanupDeps() {\n let i = this.deps.length;\n while (i--) {\n const dep = this.deps[i];\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this);\n }\n }\n let tmp = this.depIds;\n this.depIds = this.newDepIds;\n this.newDepIds = tmp;\n this.newDepIds.clear();\n tmp = this.deps;\n this.deps = this.newDeps;\n this.newDeps = tmp;\n this.newDeps.length = 0;\n }", "cleanupDeps() {\n let i = this.deps.length;\n\n while (i--) {\n const dep = this.deps[i];\n\n if (!this.newDepIds.has(dep.id)) {\n dep.removeSub(this);\n }\n }\n\n let tmp = this.depIds;\n this.depIds = this.newDepIds;\n this.newDepIds = tmp;\n this.newDepIds.clear();\n tmp = this.deps;\n this.deps = this.newDeps;\n this.newDeps = tmp;\n this.newDeps.length = 0;\n }", "cleanupDeps() {\n\t\tlet i = this.deps.length;\n\t\twhile (i--) {\n\t\t\tconst dep = this.deps[i];\n\t\t\tif (!this.newDepIds.has(dep.id)) {\n\t\t\t\tdep.removeSub(this);\n\t\t\t}\n\t\t}\n\t\tlet tmp = this.depIds;\n\t\tthis.depIds = this.newDepIds;\n\t\tthis.newDepIds = tmp;\n\t\tthis.newDepIds.clear();\n\t\ttmp = this.deps;\n\t\tthis.deps = this.newDeps;\n\t\tthis.newDeps = tmp;\n\t\tthis.newDeps.length = 0;\n\t}", "order() {\n debug('order:before', this.names);\n const runLast = this._plugins\n .filter(p => p.requirements.has('runLast'))\n .map(p => p.name);\n for (const name of runLast) {\n const index = this._plugins.findIndex(p => p.name === name);\n this._plugins.push(this._plugins.splice(index, 1)[0]);\n }\n debug('order:after', this.names);\n }", "bindDependencies() {\n // flatten the tree\n let dependenciesList = Object.assign({},\n this.dependencies.Services, this.dependencies.Controllers, this.dependencies.UiControllers);\n // bind\n traverseObjectAndChange(this.dependencies, component => {\n component.dependencies = traverseObjectAndChange(component.dependencies, entry => dependenciesList[entry]);\n });\n }", "function changeOrder(newRoutineOrder){\n setRoutine(newRoutineOrder);\n }", "order() {\r\n debug$1('order:before', this.names);\r\n const runLast = this._plugins\r\n .filter(p => p.requirements.has('runLast'))\r\n .map(p => p.name);\r\n for (const name of runLast) {\r\n const index = this._plugins.findIndex(p => p.name === name);\r\n this._plugins.push(this._plugins.splice(index, 1)[0]);\r\n }\r\n debug$1('order:after', this.names);\r\n }", "resolveDependencies() {\n const queue = [...this.context.drivers];\n this.debug('Resolving dependencies');\n while (queue.length > 0) {\n const driver = queue.shift();\n const deps = new Set(driver.getDependencies());\n this.debug('Resolving %s', driver.name);\n deps.forEach((name) => {\n this.debug(' Including dependency %s', chalk_1.default.green(name));\n queue.push(this.tool.getPlugin('driver', name));\n });\n this.context.addDriverDependency(driver);\n }\n this.tool.onResolveDependencies.emit([this.context, Array.from(this.context.drivers)]);\n }", "_resetReorderState() {\n this.__reorderInfo = { type: 'start', moves: [] };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the knot at given index in the knot vector
setKnot(index, knot) { if (index >= this.knots.shape[0] || index < 0) { throw new Error('Invalid knot index'); } if (knot < 0 || knot > 1) { throw new Error('Invalid knot value'); } if (index < this.degree + 1) { if (knot !== 0) { throw new Error('Clamped knot has to be zero'); } } if (index >= (this.knots.shape[0] - this.degree - 1)) { if (knot !== 1) { throw new Error('Clamped knot has to be one'); } } this.knots.set(index, knot); }
[ "setKnots(knots) {\r\n if (!this.knots.isShapeEqual(knots)) {\r\n throw new Error('Invalid knot vector length');\r\n }\r\n this.knots = knots;\r\n }", "__insert (_xKnot, _yKnot, _indx) {\n for (let i = this.__knots - 1; i >= _indx; i--) {\n this.__t[i + 1] = this.__t[i]\n this.__y[i + 1] = this.__y[i]\n }\n this.__t[_indx] = _xKnot\n this.__y[_indx] = _yKnot\n this.__knots++\n }", "set(i, k) {\n let value = this.sum(i, i);\n this.add(i, k - value);\n }", "function createKnot( color, index ) {\n return new Knot( (color === 'blue' ? 62 : 680) + index * 80, color );\n }", "insertKnot(un, r) {\r\n let p = this.degree;\r\n let dim = this.dimension;\r\n let k = this.findSpan(un);\r\n let isRational = this.isRational();\r\n // If un already exists in the knot vector then s is it's multiplicity\r\n let s = 0;\r\n for (let i = 0; i < this.knots.shape[0]; i++) {\r\n if (this.knots.get(i) === un) {\r\n s++;\r\n }\r\n }\r\n if (r + s >= p) {\r\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\r\n }\r\n let m = this.knots.shape[0] - 1;\r\n let n = m - p - 1;\r\n let P = this.cpoints;\r\n let Up = this.knots;\r\n let Q = new common_1.NDArray({ shape: [P.shape[0] + r, dim] });\r\n let Uq = new common_1.NDArray({ shape: [Up.shape[0] + r] });\r\n let Rtmp, Wtmp;\r\n Rtmp = new common_1.NDArray({ shape: [p + 1, dim] });\r\n let Wp, Wq;\r\n if (this.weights) {\r\n Wp = this.weights;\r\n Wq = new common_1.NDArray({ shape: [Wp.shape[0] + r] });\r\n Wtmp = new common_1.NDArray({ shape: [p + 1] });\r\n }\r\n // Load new knot vector\r\n for (let i = 0; i < k + 1; i++) {\r\n Uq.set(i, Up.get(i));\r\n }\r\n for (let i = 1; i < r + 1; i++) {\r\n Uq.set(k + i, un);\r\n }\r\n for (let i = k + 1; i < m + 1; i++) {\r\n Uq.set(i + r, Up.get(i));\r\n }\r\n // Save unaltered control points\r\n for (let i = 0; i < k - p + 1; i++) {\r\n for (let j = 0; j < dim; j++) {\r\n Q.set(i, j, P.get(i, j));\r\n }\r\n if (Wp && Wq) {\r\n Wq.set(i, Wp.get(i));\r\n }\r\n }\r\n for (let i = k - s; i < n + 1; i++) {\r\n for (let j = 0; j < dim; j++) {\r\n Q.set(i + r, j, P.get(i, j));\r\n }\r\n if (Wp && Wq) {\r\n Wq.set(i + r, Wp.get(i));\r\n }\r\n }\r\n for (let i = 0; i < p - s + 1; i++) {\r\n for (let j = 0; j < dim; j++) {\r\n Rtmp.set(i, j, P.get(k - p + i, j));\r\n }\r\n }\r\n let L = 0;\r\n for (let j = 1; j < r + 1; j++) {\r\n L = k - p + j;\r\n for (let i = 0; i < p - j - s + 1; i++) {\r\n let alpha = (un - Up.get(L + i)) / (Up.get(i + k + 1) - Up.get(L + i));\r\n for (let z = 0; z < dim; z++) {\r\n Rtmp.set(i, z, alpha * Rtmp.get(i + 1, z) + (1 - alpha) * Rtmp.get(i, z));\r\n }\r\n if (Wtmp) {\r\n Wtmp.set(i, alpha * Wtmp.get(i + 1) + (1 - alpha) * Wtmp.get(i));\r\n }\r\n }\r\n for (let z = 0; z < dim; z++) {\r\n Q.set(L, z, Rtmp.get(0, z));\r\n Q.set(k + r - j - s, z, Rtmp.get(p - j - s, z));\r\n }\r\n if (Wq && Wtmp) {\r\n Wq.set(L, Wtmp.get(0));\r\n Wq.set(k + r - j - s, Wtmp.get(p - j - s));\r\n }\r\n }\r\n for (let i = L + 1; i < k - s + 1; i++) {\r\n for (let z = 0; z < dim; z++) {\r\n Q.set(i, z, Rtmp.get(i - L, z));\r\n }\r\n if (Wq && Wtmp) {\r\n Wq.set(i, Wtmp.get(i - L));\r\n }\r\n }\r\n this.knots = Uq;\r\n this.cpoints = Q;\r\n if (isRational) {\r\n this.weights = Wq;\r\n }\r\n }", "insertKnotV(vn, r) {\r\n let q = this.v_degree;\r\n // Knot will be inserted between [k,k+1)\r\n let k = helper_1.findSpan(this.v_degree, this.v_knots.data, vn);\r\n // If v already exists in knot vector, s is its multiplicity\r\n let s = common_1.count(this.v_knots, vn, 0);\r\n if (r + s > q) {\r\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\r\n }\r\n let mU = this.u_knots.length - 1;\r\n let nU = mU - this.u_degree - 1;\r\n let mV = this.v_knots.length - 1;\r\n let nV = mV - this.v_degree - 1;\r\n let P = this.cpoints;\r\n let Q = common_1.empty([nU + 1, nV + r + 1, this.dimension]);\r\n let UP = this.u_knots;\r\n let UQ = common_1.empty([UP.length]);\r\n let VP = this.v_knots;\r\n let VQ = common_1.empty([VP.length + r]);\r\n // Copy u knot vector\r\n UQ.copyfrom(UP);\r\n // Load v knot vector\r\n for (let i = 0; i < k + 1; i++) {\r\n VQ.set(i, VP.get(i));\r\n }\r\n for (let i = 1; i < r + 1; i++) {\r\n VQ.set(k + i, vn);\r\n }\r\n for (let i = k + 1; i < mV + 1; i++) {\r\n VQ.set(i + r, VP.get(i));\r\n }\r\n let alpha = common_1.empty([q + 1, r + 1]);\r\n let R = common_1.empty([q + 1, this.dimension]);\r\n let L = 0;\r\n // Pre-calculate alphas\r\n for (let j = 1; j < r + 1; j++) {\r\n L = k - q + j;\r\n for (let i = 0; i < q - j - s + 1; i++) {\r\n alpha.set(i, j, (vn - VP.get(L + i)) / (VP.get(i + k + 1) - VP.get(L + i)));\r\n }\r\n }\r\n for (let col = 0; col < nU + 1; col++) {\r\n // Save unaltered control points\r\n for (let i = 0; i < k - q + 1; i++) {\r\n Q.set(col, i, P.get(col, i));\r\n }\r\n for (let i = k - s; i < nV + 1; i++) {\r\n Q.set(col, i + r, P.get(col, i));\r\n }\r\n // Load auxiliary control points\r\n for (let i = 0; i < q - s + 1; i++) {\r\n R.set(i, P.get(col, k - q + i));\r\n }\r\n for (let j = 1; j < r + 1; j++) {\r\n L = k - q + j;\r\n for (let i = 0; i < q - j - s + 1; i++) {\r\n R.set(i, common_1.add(common_1.mul(alpha.get(i, j), R.get(i + 1)), common_1.mul((1.0 - alpha.get(i, j)), R.get(i))));\r\n }\r\n Q.set(col, L, R.get(0));\r\n Q.set(col, k + r - j - s, R.get(q - j - s));\r\n }\r\n // Load remaining control points\r\n for (let i = L + 1; i < k - s; i++) {\r\n Q.set(col, i, R.get(i - L));\r\n }\r\n }\r\n this.cpoints = Q;\r\n this.v_knots = VQ;\r\n }", "function sc_vectorSetBang(v, pos, val) {\n\n\n v[pos] = val;\n}", "change(i,k,offset) {\n this._change(1, 0, this.N, i, k, offset);\n }", "setAt(idx, val) {\r\n this.nodes[idx].val = val;\r\n }", "setAt(idx, val) {\n }", "function sc_vectorSetBang(v, pos, val) {\n v[pos] = val;\n}", "setAt(idx, val) {\n let node = this._get(idx);\n node.val = val;\n }", "setAt(idx, val) {\n\n }", "setAt(idx, val) {\n\n const currNode = this.positionToIdx(idx);\n currNode.val = val;\n\n }", "withKnot(newKnot, multiplicity = 1) {\n ts3dutils.assert(ts3dutils.between(newKnot, this.tMin, this.tMax));\n const k = this.tInterval(newKnot);\n const { knots, points, degree } = this;\n const insertPoints = ts3dutils.arrayFromFunction(this.degree, j => {\n const i = k - degree + 1 + j;\n const aiNumerator = newKnot - knots[i];\n // 0/0 defined as 0:\n const ai = aiNumerator == 0 ? 0 : aiNumerator / (knots[i + degree] - knots[i]);\n ts3dutils.assert(ts3dutils.between(ai, 0, 1));\n return ts3dutils.Vector.lerp(points[i - 1], points[i], ai);\n });\n const newPoints = points.slice();\n newPoints.splice(k - degree + 1, degree - 1, ...insertPoints);\n const newKnots = knots.slice();\n newKnots.splice(k + 1, 0, newKnot);\n return new NURBS$$1(newPoints, degree, newKnots, this.tMin, this.tMax);\n }", "function SetK(k) {\r\n\tsequences[0].k = parseInt(k);\r\n}", "setAt(idx, val) {\n this._set(idx, val);\n }", "setAt(idx, val) {\n // this._verifyIdx() ??? would this work???\n \n if(idx <= 0 && idx >= this.length -1) {\n throw new Error(\"invalid index\")\n }\n\n let selected = this._get(idx)\n selected.val = val\n }", "function setWaypoint(index, set) {\n\t\twaypointsSet[index] = set;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a decimal hours, provides the number of minutes that would match the decimal (using 781 rounding)
function decimalMinutes(t) { t = Number((t % 1).toFixed(1)); //remove integer portion for easy math if (t < 0.1) { //0-2 return 0; } else if (t < 0.2) { //3-8 return 5; } else if (t < 0.3) { //9-14 return 10; } else if (t < 0.4) { //15-20 return 15; } else if (t < 0.5) { //21-26 return 25; } else if (t < 0.6) { //27-33 return 30; } else if (t < 0.7) { //34-39 return 35; } else if (t < 0.8) { //40-45 return 45; } else if (t < 0.9) { //46-51 return 50; } else if (t < 1) { //52-59 return 55; } }
[ "function calculateHours(hours){\n var minutesFromHours = hours.split(\"h\")\n return minutesFromHours[0]*60\n }", "function hours_round(h) {\r\n var f = Math.floor(h);\r\n \r\n h = h - f;\r\n h = h * 4.0;\r\n h = Math.round(h) * 0.25;\r\n\r\n return f + h;\r\n}", "roundHours (hours, interval) {\n return (Math.floor(hours / interval) * interval)\n }", "timeInHours(minutes){\r\n minutes*=Min\r\n console.log(Hr)\r\n return minutes/Hr\r\n }", "function minutes_in_hours(m) {\n return m / 60;\n}", "function hoursToSize(hours) {\n if (hours >= 2000000) {\n return 110;\n } else if (hours >= 1000000) {\n return 65;\n } else {\n return 25;\n }\n}", "function getMinutes() {\n if (totalSeconds > 3599) {\n totalSeconds -= 3600;\n totalHours++;\n }\n return (totalSeconds / 60);\n}", "function roundMinutes(t) {\n let sign = (t >= 0 ? 1 : -1)\n let h = Math.floor(Math.abs(t) / 60) * sign;\n let m = Math.abs(t) % 60;\n if (m <= 2) {\n return h;\n } else if (m <= 8) {\n return h + (0.1 * sign);\n } else if (m <= 14) {\n return h + (0.2 * sign);\n } else if (m <= 20) {\n return h + (0.3 * sign);\n } else if (m <= 26) {\n return h + (0.4 * sign);\n } else if (m <= 33) {\n return h + (0.5 * sign);\n } else if (m <= 39) {\n return h + (0.6 * sign);\n } else if (m <= 45) {\n return h + (0.7 * sign);\n } else if (m <= 51) {\n return h + (0.8 * sign);\n } else if (m <= 57) {\n return h + (0.9 * sign);\n } else {\n return h + sign;\n }\n}", "function hrtimeMillisec(a){assertHrtime(a);return Math.floor(a[0]*1e3+a[1]/1e6);}", "function hm2val(hours,minutes){\n\treturn (hours*60+minutes);\n}", "function GetTotalMinutes(hours, minutes){\n\treturn (hours * 60) + minutes;\n}", "function calculateTime(seconds) {\n let hours = Math.floor(seconds / 3600);\n let mins = Math.round((seconds - (hours * 3600)) / 60);\n return (hours + \"h \" + mins + \"m\");\n}", "function decimalHourConverter(time) {\n const hour = Math.floor(time);\n let minute = (time-hour)*60;\n if(minute === 0) {\n minute = \"00\";\n }\n return hour+\":\"+minute;\n}", "minute() {\n var abs = this._abs();\n var mod = abs.mod(constants.secondsPerHour.toUnsigned()).toSigned();\n return mod.div(constants.secondsPerMinute).toNumber();\n }", "timeConvert(numOfMins){\n // Return the hours only and round down\n let hours = math.floor(numOfMins/60);\n // Return the remaining value left over from hours\n let mins = math.floor(numOfMins % 60);\n // Return the remaining value left from mins\n let sec = math.floor(numOfMins % 60)\n // Return sum of hours, mins, and sec\n return hours + \":\" + mins + \":\" + sec;\n }", "function convert(n)\r\n{\r\n return Number(n) * 60;\r\n}", "function getHour(n) {\r\n var xyz = ( n / 100 )\r\n var decimalTimeString = xyz ;\r\n var decimalTime = parseFloat(decimalTimeString);\r\n decimalTime = decimalTime * 60 * 60;\r\n var hours = Math.floor((decimalTime / (60 * 60)));\r\n decimalTime = decimalTime - (hours * 60 * 60);\r\n var minutes = Math.floor((decimalTime / 60));\r\n decimalTime = decimalTime - (minutes * 60);\r\n \r\n if(hours < 10){\r\n hours = \"0\" + hours;\r\n }\r\n if(minutes < 10){\r\n minutes = \"0\" + minutes;\r\n }\r\n\r\n return \"\" + hours + \":\" + minutes; \r\n}", "function minutesToDecimal(minutes){\n //Divide by 60 in order to make time decimal and remove any periods.\n let decimal = String(minutes / 60).replace(`.`, ``);\n //If the number is bigger than 0.1, remove the zero, i.e: 07 -> 7\n if (decimal >= 0.1)\n decimal = decimal.replace(0, ``);\n\n return decimal;\n }", "function roundToQuarterHour(minutes) {\n\t\tif (minutes <= 7) {\n\t\t\treturn .00;\n\t\t}\n\t\telse if (minutes <= 22) {\n\t\t\treturn .25;\n\t\t}\n\t\telse if (minutes <= 37) {\n\t\t\treturn .5;\n\t\t}\n\t\telse if (minutes <= 52) {\n\t\t\treturn .75;\n\t\t}\n\t\telse {\n\t\t\treturn 1;\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate breakpoints in CodeMirror options, don't overwrite other settings
function activate_cm_breakpoints (cell) { let cm = cell.code_mirror; let gutters = cm.getOption('gutters').slice(); if ( $.inArray("CodeMirror-breakpoints", gutters) < 0) { gutters.push('CodeMirror-breakpoints'); cm.setOption('gutters', gutters); cm.on('gutterClick', (self, ln, gutter, event) => { let info = self.lineInfo(ln); if (info.gutterMarkers) { // remove has-breakpoint class to the line wrapper self.removeLineClass(ln, 'text', 'has-breakpoint'); // toggle gutter marker self.setGutterMarker(ln, "CodeMirror-breakpoints", null); // skip folds if (info.gutterMarkers.hasOwnProperty('CodeMirror-foldgutter')) { console.warn( "Setting breakpoint on foldable line is not allowed." ); } } else { // breakpoint marker let marker = document.createElement("div"); marker.innerHTML = "●"; marker.setAttribute('class', 'breakpoint'); // add has-breakpoint class to the line wrapper self.addLineClass(ln, 'text', 'has-breakpoint'); // toggle gutter marker self.setGutterMarker(ln, "CodeMirror-breakpoints", marker); } // update after delay, pass cell here setTimeout(() => updateMetadata(cell), params.update_delay); }); } }
[ "enableDisableAllBreakpoints() {\n this.breakpointManager.flip();\n }", "function setBreakpoints() {\n\t\tif (_settings.breakpoints && _matchMediaSupport) {\n\t\t\tvar breakpoints = _settings.breakpoints;\n\n\t\t\t_mqSmall = _mqSmall.replace('%d', breakpoints.sm);\n\t\t\t_mqMedium = _mqMedium.replace('%d', breakpoints.md);\n\t\t\t_mqLarge = _mqLarge.replace('%d', breakpoints.lg);\n\t\t}\n\t}", "__breakpoints(breakpoints, data){\n\t\t//console.log('setting breakpoints', breakpoints);\n\t\tthis.editor.session.clearBreakpoints();\n\t\tfor (let breakpoint of breakpoints){\n\t\t\tif (breakpoint.file === data.fileName){\n\t\t\t\tthis.editor.session.setBreakpoint(breakpoint.line);\n\t\t\t}\n\t\t}\n\t}", "async _codemirrorSetOptions() {\n const {\n mode: rawMode,\n autoCloseBrackets,\n dynamicHeight,\n getAutocompleteConstants,\n getRenderContext,\n hideGutters,\n hideLineNumbers,\n hideScrollbars,\n hintOptions,\n indentSize,\n indentWithTabs,\n infoOptions,\n jumpOptions,\n keyMap,\n lineWrapping,\n lintOptions,\n noDragDrop,\n noLint,\n noMatchBrackets,\n noStyleActiveLine,\n placeholder,\n readOnly,\n tabIndex,\n } = this.props;\n\n let mode;\n if (this.props.render) {\n mode = { name: 'nunjucks', baseMode: CodeEditor._normalizeMode(rawMode) };\n } else {\n // foo bar baz\n mode = CodeEditor._normalizeMode(rawMode);\n }\n\n // NOTE: YAML is not valid when indented with Tabs\n const isYaml = typeof rawMode === 'string' ? rawMode.includes('yaml') : false;\n const actuallyIndentWithTabs = indentWithTabs && !isYaml;\n\n const options = {\n readOnly: !!readOnly,\n placeholder: placeholder || '',\n mode: mode,\n tabIndex: typeof tabIndex === 'number' ? tabIndex : null,\n dragDrop: !noDragDrop,\n scrollbarStyle: hideScrollbars ? 'null' : 'native',\n styleActiveLine: !noStyleActiveLine,\n lineNumbers: !hideGutters && !hideLineNumbers,\n foldGutter: !hideGutters && !hideLineNumbers,\n lineWrapping: lineWrapping,\n indentWithTabs: actuallyIndentWithTabs,\n matchBrackets: !noMatchBrackets,\n lint: !noLint && !readOnly,\n gutters: [],\n };\n\n // Only set keyMap if we're not read-only. This is so things like\n // ctrl-a work on read-only mode.\n if (!readOnly && keyMap) {\n options.keyMap = keyMap;\n }\n\n if (indentSize) {\n options.tabSize = indentSize;\n options.indentUnit = indentSize;\n }\n\n if (!hideGutters && options.lint) {\n options.gutters.push('CodeMirror-lint-markers');\n }\n\n if (!hideGutters && options.lineNumbers) {\n options.gutters.push('CodeMirror-linenumbers');\n }\n\n if (!hideGutters && options.foldGutter) {\n options.gutters.push('CodeMirror-foldgutter');\n }\n\n if (hintOptions) {\n options.hintOptions = hintOptions;\n }\n\n if (infoOptions) {\n options.info = infoOptions;\n }\n\n if (jumpOptions) {\n options.jump = jumpOptions;\n }\n\n if (lintOptions) {\n options.lint = lintOptions;\n }\n\n if (typeof autoCloseBrackets === 'boolean') {\n options.autoCloseBrackets = autoCloseBrackets;\n }\n\n // Setup the hint options\n if (getRenderContext || getAutocompleteConstants) {\n let getVariables = null;\n let getTags = null;\n if (getRenderContext) {\n getVariables = async () => {\n const context = await getRenderContext();\n const variables = context ? context.keys : [];\n return variables || [];\n };\n\n // Only allow tags if we have variables too\n getTags = async () => {\n const expandedTags = [];\n for (const tagDef of await getTagDefinitions()) {\n const firstArg = tagDef.args[0];\n if (!firstArg || firstArg.type !== 'enum') {\n expandedTags.push(tagDef);\n continue;\n }\n\n for (const option of tagDef.args[0].options) {\n const optionName = misc.fnOrString(option.displayName, tagDef.args) || option.name;\n const newDef = clone(tagDef);\n newDef.displayName = `${tagDef.displayName} ⇒ ${optionName}`;\n newDef.args[0].defaultValue = option.value;\n expandedTags.push(newDef);\n }\n }\n\n return expandedTags;\n };\n }\n options.environmentAutocomplete = {\n getVariables,\n getTags,\n getConstants: getAutocompleteConstants,\n };\n }\n\n if (dynamicHeight) {\n options.viewportMargin = Infinity;\n }\n\n // Strip of charset if there is one\n const cm = this.codeMirror;\n Object.keys(options).map(key => {\n let shouldSetOption = false;\n\n if (key === 'jump' || key === 'info' || key === 'lint' || key === 'hintOptions') {\n // Use stringify here because these could be infinitely recursive due to GraphQL\n // schemas\n shouldSetOption = JSON.stringify(options[key]) !== JSON.stringify(cm.options[key]);\n } else if (!deepEqual(options[key], cm.options[key])) {\n // Don't set the option if it hasn't changed\n shouldSetOption = true;\n }\n\n if (shouldSetOption) {\n cm.setOption(key, options[key]);\n }\n });\n }", "setSettingsOfCurrentBreakpoint () {\n let breakpoint = 0;\n let index = 0;\n\n this.data.breakpoint.forEach((bp, i) => {\n if (bp <= this.data.width.window) {\n breakpoint = bp;\n index = i;\n }\n });\n\n if (!breakpoint && !index) {\n this.settings = this.data.oldSettings;\n } else {\n let tmp = this.settings.responsive.slice(0, index) || [];\n tmp = tmp.reduce((acc, item) => ({ ...acc, ...item.settings }), {});\n this.settings = { ...this.data.oldSettings, ...tmp, ...this.settings.responsive[index].settings };\n }\n }", "function setupCodeMirror(){\r\n \r\n \r\n var codeArea = document.getElementById('code');\r\n \r\n myCodeMirror = CodeMirror.fromTextArea(codeArea, {\r\n lineNumbers: true,\r\n mode: \"javascript\",\r\n gutters: [\"CodeMirror-lint-markers\"],\r\n lint: {\"curly\": true, \"undef\": true, \"funcscope\": true, \"predef\": p5globals},\r\n matchBrackets: true,\r\n theme: \"midnight\",\r\n highlightSelectionMatches: {showToken: /[A-Za-z_]/},\r\n styleActiveLine: true,\r\n inputStyle: \"contenteditable\",\r\n extraKeys: {Tab: function(cm){document.getElementById(\"runcode\").focus();console.log(\"tab\");}},\r\n // dragDrop: false\r\n tabindex: 0,\r\n autofocus: true\r\n });\r\n /*\r\n myCodeMirror.setOption(\"extraKeys\", {\r\n \r\n Tab: function (cm){\r\n console.log(\"tab\");\r\n return false;\r\n }\r\n });\r\n */ \r\n // myCodeMirror.setOption(\"lint\",{\"curly\": true, \"undef\": true, \"unused\": true, \"funcscope\": true, \"predef\": p5globals} );\r\n \r\n myCodeMirror.addOverlay(p5modeOverlay);\r\n \r\n}", "function setupBreakpoints() {\n\t\tsetupBreakpoint('desktop');\n\t\tsetupBreakpoint('tablet');\n\t\tsetupBreakpoint('mobile');\n\t}", "function showDebuggedCode() {\r\n vscode.window.showQuickPick([\"True\", \"False\"]).then(val => {\r\n if (val == \"True\") {\r\n enableLineSelection = false;\r\n vscode.workspace.getConfiguration(\"AutodeskPostUtility\").update(\"showDebuggedCode\", true, true);\r\n } else if (val == \"False\") {\r\n vscode.workspace.getConfiguration(\"AutodeskPostUtility\").update(\"showDebuggedCode\", false, true);\r\n enableLineSelection = vscode.workspace.getConfiguration(\"AutodeskPostUtility\").get(\"enableAutoLineSelection\");\r\n }\r\n });\r\n}", "enableDebug(enabled) {\n atom\n .config\n .set('core.debugLSP', enabled);\n }", "function updateBreakpoints(cm, n) {\n var info = cm.lineInfo(n);\n if (info.gutterMarkers && 'breakpoints' in info.gutterMarkers) {\n app.ports.breakpoints.send({ action: 'remove', line: info.line });\n } else {\n app.ports.breakpoints.send({ action: 'add', line: info.line });\n }\n cm.setGutterMarker(n, \"breakpoints\", info.gutterMarkers ? null : makeMarker());\n}", "function disableBreakpoint(e) {\n var region = e.editor.renderer.$gutterLayer.getRegion(e);\n if (region == \"markers\") {\n e.stop(); // prevent breakpoint toggling\n }\n}", "setDebugMode(mode=true) {\n Debug.mode.debugMode = mode;\n }", "function handleChanges() {\n for (const breakpoint of breakpoints) {\n if (breakpoint.mql.matches) {\n activeBreakpoint = breakpoint;\n }\n }\n}", "function addBreakpoint(row) {\n editor.session.setBreakpoint(row);\n }", "get breakpoints() {\n return this.globals.breakpoints;\n }", "_addBreakpoints() {\n for (var i in Foundation.MediaQuery.queries) {\n var query = Foundation.MediaQuery.queries[i];\n Interchange.SPECIAL_QUERIES[query.name] = query.value;\n }\n }", "function resizeBreakpointGutter(editor) {\n const gutters = editor.display.gutters;\n const breakpoints = gutters.querySelector(\".breakpoints\");\n if (breakpoints) {\n breakpoints.style.width = `${getLineNumberWidth(editor)}px`;\n }\n}", "function switchDebug () {\n Map.debug = !Map.debug;\n}", "function minimizeCodeEditor() {\n parent.find('[data-command=maximize-editor]').show();\n parent.find('[data-command=minimize-editor]').hide();\n\n parent.find('[data-section=config]').show();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Permet d'afficher des popups
function popup() { $('[data-popup]').on('click', (event) => { // Popup cible const { currentTarget: target } = event; const popup = $(target).next('.popup'); // Ouvre la popup popup.toggleClass('active'); // Insertion du data pour charger le contenu uniquement si l'on ouvre la popup $('object', popup).each((index, object) => { $(object).attr('data', $(object).data('data')); }); }); $('.popup button.close, .popup').on('click', (event) => { const { currentTarget: target } = event; if ($(target).hasClass('popup') || $(target).hasClass('close')) { const popup = $(target).closest('.popup'); $(popup).removeClass('active'); // Suppression du data pour stopper le contenu de l'object (vidéo en lecture par exemple) $('object', popup).each((index, object) => { $(object).removeAttr('data'); $(object).clone().appendTo($(object).closest('.fluid-container')); $(object).remove(); }); } }) }
[ "function initPopups() {\n //ANTES ESTABAN LOS DIVs DE LOS POPUPs\n //YA NO EXISTEN PORQUE CAUSABAN PROBLEMAS\n}", "function popups_verboten() {\n\t\topen_modul && open_modul.close();\n\t\talert(\"Das Programm kann nicht im richtigen Kontext angezeigt werden. Schalten Sie bitte ggf. den Popup-Blocker aus.\");\n\t}", "function _clearPopup() {\n me.infoWindow.setContent(\"<div class='popup'><h1></h1>\" + \"<p class='popupWiki'></p>\" + \"<p class='popupForecast'></p></div>\");\n }", "function handlePopups(){\n // Refresh the publishing options\n fetchPubOptions();\n try {\n\n //Added handling to actually show popups\n var popupElts = $x('.//div[contains(@id, \"pop_b\") and not(contains(@style, \"none\"))]', popupfodderElt);\n if (popupElts && popupElts.length > 0) {\n for (var i = 0, iLength=popupElts.length; i < iLength; ++i) {\n var currentClass = popupElts[i].getAttribute('class');\n if(currentClass.indexOf('pop_bg')==-1 && !popupElts[i].getAttribute('opened')){\n popupElts[i].setAttribute('style', 'display: block;');\n popupElts[i].setAttribute('opened', 'yes');\n } else if (popupElts[i].getAttribute('opened')!='yes') { popupElts[i].setAttribute('style', 'display: none;'); }\n }\n }\n //Added handling to actually show fight / battle popups\n var popupElts = $x('.//div[@class=\"fight_true_popup\"]//div[contains(@id, \"pop_b\")]', innerPageElt);\n if (popupElts && popupElts.length > 0) {\n for (var i = 0, iLength=popupElts.length; i < iLength; ++i) {\n var currentClass = popupElts[i].getAttribute('class');\n if(currentClass.indexOf('pop_bg')==-1 && !popupElts[i].getAttribute('opened')){\n popupElts[i].setAttribute('style', 'display: block;');\n popupElts[i].setAttribute('opened', 'yes');\n } else if (popupElts[i].getAttribute('opened')!='yes') { popupElts[i].setAttribute('style', 'display: none;'); }\n }\n }\n\n// Sent Requests Popup\n var requestPopContainer = xpathFirst('.//div[@id=\"requests_toaster\" and contains(@style,\"block\")]');\n if(requestPopContainer){\n var requestPopText = xpathFirst('.//div[@id=\"requests_toaster_txt\"]', requestPopContainer);\n if(requestPopText) addToLog('process Icon', requestPopText.innerHTML.untag());\n var closeElt = xpathFirst('.//div[contains(@onclick,\"fadeOut\")]', requestPopContainer);\n clickElement(closeElt);\n return;\n }\n\n//Buy Prompt Popup\n var popupContainers = $x('.//div[@class=\"buy_prompt\"]', appLayoutElt);\n if(running && popupContainers && popupContainers.length > 0){\n // Process each popup that is open\n for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){\n if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){\n var currentPopup = popupContainers[i];\n return(closePopup(currentPopup, \"Buy Prompt Popup\"));\n }\n }\n }\n\n // Look for Operations popups that are showing\n var popupContainers = $x('.//div[contains(@id,\"socialMissionFail\") and @class=\"socialMissionTryAgain\" and contains(@style,\"block\")]', appLayoutElt);\n if(running && popupContainers && popupContainers.length > 0){\n // Process each popup that is open\n for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){\n if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){\n var currentPopup = popupContainers[i];\n var processElt;\n if(isGMChecked('AutoRetryOperations')){\n processElt = xpathFirst('.//a[contains(@onclick,\"tryAgain\") and contains(.,\"Start\")]',currentPopup);\n DEBUG('Clicking to retry expired operation');\n } else {\n processElt = xpathFirst('.//a[contains(@onclick,\"tryAgain\") and contains(.,\"Close\")]',currentPopup);\n DEBUG('Clicking to close expired operation');\n }\n if(processElt) clickElement(processElt);\n return true;\n }\n }\n }\n\n // Look for Achievements popups that are showing\n var popupContainers = $x('.//div[contains(@id,\"zy_popup_box\") and not(@class=\"zy_popup_box_bg\") and contains(@style,\"block\")]', appLayoutElt);\n if(running && popupContainers && popupContainers.length > 0){\n // Process each popup that is open\n for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){\n if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){\n var currentPopup = popupContainers[i];\n var processElt;\n processElt = xpathFirst('.//div[@class=\"achievement_message_text\"]',currentPopup);\n if(processElt){\n var processTxt = processElt.innerHTML.untag();\n if(processTxt.match(/you earned(.+)share/i)) addToLog('yeah Icon','You earned '+RegExp.$1+'.');\n if(isGMChecked('autoGlobalPublishing')){\n processElt = xpathFirst('.//a[contains(@class,\"sexy_achievement_new\") and contains(.,\"Share the wealth\")]',currentPopup);\n if(processElt){\n clickElement(processElt);\n DEBUG('Clicked to share Achievement Bonus');\n }\n }\n }\n return(closePopup(currentPopup, \"Achievement Popup\"));\n }\n }\n }\n\n // Look for all other popups that are showing\n var popupElts = $x('.//div[(contains(@id,\"pop_box\") and contains(@style, \"block\")) or contains(@id,\"mystery\")]', appLayoutElt);\n if(popupElts && popupElts.length > 0){\n // Process each popup that is open\n for (var i = 0, iLength=popupElts.length; i < iLength; ++i){\n\n if(popupElts[i] && popupElts[i].scrollWidth && popupElts[i].innerHTML.length > 0){\n var currentPopup = popupElts[i];\n var popupInner = currentPopup.innerHTML;\n var popupInnerNoTags = popupInner.untag().toLowerCase();\n\n if( popupInner.indexOf('fight_wrapper') != -1 // Don't Close Fight Popup\n || popupInner.indexOf('bank_popup') != -1 // The Bank\n || popupInner.indexOf('vault_popup') != -1 // Las Vegas Vault\n ){ continue; }\n\n //|| popupInner.indexOf('id=\"map_boss_fight\"') != -1 // Vegas Boss fights\n //|| popupInner.indexOf('id=\"pop_box_map_boss_fight_popup\"') != -1 // Boss fights\n\n // ALWAYS CLOSE these popups:\n if(( popupInner.indexOf('id=\"marketplace\"') != -1 // The Marketplace\n || popupInner.indexOf('id=\"original_buyframe_popup\"') != -1 // The Marketplace\n || popupInner.indexOf('marketplace_title.png') != -1 // The Marketplace\n || popupInner.indexOf('giftcard_iframe') != -1 // The Marketplace\n || popupInner.indexOf('newbuyer_congrats') != -1 // The Marketplace\n || popupInner.indexOf('xw_controller=hospital') != -1 // The Hospital\n || popupInner.indexOf('Build Complete') != -1 // Chop Shop/Weapon Depot success popup\n || popupInner.indexOf('id=\"ChopShopCarousel\"') != -1 // Chop Shop/Weapon Depot craft popup\n || popupInner.indexOf('class=\"account_settings_title\"') != -1 // Account Settings\n || popupInner.indexOf('class=\"exp_discount_main\"') != -1 // Item Sales\n || popupInner.indexOf('TournamentController.nextPage()') != -1 // Tournament Ready to fight popup\n || popupInner.indexOf('this wave has ended') != -1 // kill zombie fight ended\n || popupInnerNoTags.indexOf('wishlist is full') != -1\n || popupInnerNoTags.indexOf('cooldown') != -1\n || popupInnerNoTags.indexOf('buy now order') != -1\n || popupInnerNoTags.indexOf('drag to reorder them') != -1\n || popupInnerNoTags.indexOf('vengeance pack') != -1\n ) && popupInnerNoTags.indexOf('select a consumable to use') == -1) {\n if(running) return(closePopup(currentPopup, \"Annoying Zollipops stuff\"));\n continue;\n }\n\n if(isGMChecked('TestChanges')) DEBUG('Popup Found: '+ popupElts[i].id + ' - '+ popupInnerNoTags); // shows popup_fodder_zmc constantly\n\n /* THESE POPUPS get processed only when PS MWAP is running: */\n /* START */\n\n if(running){\n\n /* THESE POPUPS get always processed: */\n\n // Close Free Gift Selector if timer goes off\n if(popupInnerNoTags.indexOf('close_suggestor_iframe') !=-1){\n if(!timeLeftGM('requestTimer')) return(closePopup(currentPopup, \"Free Gift Suggestor\"));\n return;\n }\n\n // LV/ITALY Boss Confirm Popup\n var elt = xpathFirst('.//a[contains(@class,\"attack_boss\") and contains(@onclick,\"Expert\")]',currentPopup);\n if(elt) {\n endBoss = false;\n if(popupTimer){\n window.clearInterval(popupTimer);\n popupTimer = window.setInterval(handlePopups, 1500);\n }\n autoReload(false, 'Boss Fight');\n colorDEBUG('bossFight - clicked to confirmBoss Fight', caq);\n clickElement(elt);\n return;\n }\n\n // LV/ITALY Boss Fight\n var bossFightContainer = xpathFirst('.//div[@id=\"map_boss_fight\"]', currentPopup);\n if(bossFightContainer){\n if(popupTimer){\n window.clearInterval(popupTimer);\n popupTimer = window.setInterval(handlePopups, 1500);\n }\n autoReload(false, 'Boss Fight');\n // Look for Boss fight Consumables and Click from Right to Left\n var bossConsumables = $x('.//a[contains(@id,\"use_con\") and not(contains(@class,\"greyButton\"))]', bossFightContainer);\n if(bossConsumables && bossConsumables.length>0){\n elt = bossConsumables[bossConsumables.length-1];\n colorDEBUG('bossFight - clicked to use consumable', caq);\n clickElement(elt);\n return;\n }\n // Get the Boss Attack Button\n elt = xpathFirst('.//a[contains(@class,\"sexy_attack_new\") and contains(@onclick,\"BossController\")]', bossFightContainer);\n if(elt) {\n colorDEBUG('bossFight - clicked to attack Boss', caq);\n clickElement(elt);\n }\n return;\n }\n\n // Out of Stamina Popup for Boss Fight\n var elt = xpathFirst('.//div[@id=\"pop_box_map_boss_fight_stamina_popup\"]//a[contains(.,\"Close\")]',currentPopup);\n if(elt){\n colorDEBUG('bossFight - clicked to close Boss Fight Popup - out of stamina', caq);\n clickElement(elt);\n endBoss=true;\n return;\n }\n\n // Close Popup for Boss Fight\n elt = xpathFirst('.//div[@id=\"pop_box_map_boss_fight_popup\"]//a[class=\"pop_close\"]',currentPopup);\n if(elt && endBoss) {\n colorDEBUG('bossFight - clicked to close Boss Fight Popup', caq);\n clickElement(elt);\n return;\n }\n\n // Runaway from Boss Fight\n elt = xpathFirst('.//div[@id=\"pop_box_map_boss_fight_run_away_popup\"]//a[contains(.,\"Run Away\")]',currentPopup);\n if(elt && endBoss) {\n colorDEBUG('bossFight - clicked to Run Away from Boss Fight', caq);\n clickElement(elt);\n if(popupTimer){\n window.clearInterval(popupTimer);\n popupTimer = window.setInterval(handlePopups, 350);\n }\n endBoss = false;\n Autoplay.fx = goHome;\n Autoplay.start();\n return;\n }\n\n //Share LV/ITALY Boss Fight Reward\n var elt = xpathFirst('.//div[@id=\"map_boss_fight_victory\"]//a[contains(.,\"Share\")]',currentPopup);\n if(elt){\n colorDEBUG('bossFight - clicked to share Boss Fight Rewards', caq);\n clickElement(elt);\n if(popupTimer){\n window.clearInterval(popupTimer);\n popupTimer = window.setInterval(handlePopups, 350);\n }\n Autoplay.fx = goHome;\n Autoplay.start();\n return;\n }\n\n // Battle Pop\n var battlePopContainer = xpathFirst('.//div[@id=\"role_select_bg\"]',currentPopup);\n if(battlePopContainer){\n DEBUG('Found Battle Popup');\n elt = xpathFirst('.//a[@class=\"rightArrow\" and contains(.,\"FIGHT\")]', battlePopContainer);\n if(elt){\n clickElement(elt);\n }\n return(closePopup(currentPopup, \"Battle Popup\"));\n }\n\n // Slot Machine!?!\n if(popupInner.indexOf('mw_app=slotmachine') != -1){\n var flashvars = xpathFirst('//object[@id=\"slots\"]/param[@name=\"flashvars\"]');\n if(flashvars && flashvars.value){\n slotSpins = flashvars.value.match(/&freeSpins=(\\d+)&/)[1];\n slotBonus = flashvars.value.match(/&bonusMeter=(\\d+)&/)[1];\n addToLog('info Icon', 'Slot Spins Remaining: ' + slotSpins+' Bonus Level: '+ slotBonus);\n }\n return(closePopup(currentPopup, \"Slot Machine Popup\"));\n }\n\n // Limited Property Upgrade..\n if(popupInner.indexOf('class=\"depotTitle\"') != -1){\n // Look for the ask for upgrade link to click..\n var askButtons = $x('.//a[contains(@onclick,\"postfeedforproperty_part\")]',currentPopup);\n if(askButtons && askButtons.length){\n var askButton = askButtons[askButtons.length-1];\n DEBUG('Clicking Ask Limited Property Element');\n clickElement(askButton); // Click the last element..\n }\n return(closePopup(currentPopup, \"Limited Property\"));\n }\n\n // Accept Gifts from MESSAGE CENTER / Total Requests popup\n if(popupInnerNoTags.indexOf('total requests') != -1){\n var acceptgiftButtons = $x('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"accept_gift\") and not(contains(@onclick,\"item_id=3009\")) ]',currentPopup);\n if(acceptgiftButtons && isGMChecked('autoAcceptMsgGifts')){\n for(i=0;i<acceptgiftButtons.length>0;++i){\n acceptgiftButton = acceptgiftButtons[i];\n clickElement(acceptgiftButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - '+acceptgiftButtons.length+' Gifts Accepted');\n }\n // Accept Boosts from MESSAGE CENTER / Total Requests popup\n acceptgiftButtons = $x('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"accept_boost\")]',currentPopup);\n if(acceptgiftButtons && isGMChecked('autoAcceptMsgBoosts')){\n for(i=0;i<acceptgiftButtons.length>0;++i){\n acceptgiftButton = acceptgiftButtons[i];\n clickElement(acceptgiftButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - '+acceptgiftButtons.length+' Boosts Accepted');\n }\n // Accept War Requests MESSAGE CENTER / Total Requests popup\n if(isGMChecked('AutoBattle')){\n var acceptButtons = $x('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"xw_action=createBattle\") and contains(@onclick,\"opponent_id='+GM_getValue('AutoBattleClanID')+'\")]',currentPopup);\n if(acceptButtons){\n for(i=0;i<acceptButtons.length>0;++i){\n acceptButton = acceptButtons[i];\n clickElement(acceptButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - Accepted '+acceptButtons.length+' battles.');\n }\n }\n // Accept Mafia Invites from MESSAGE CENTER / Total Requests popup\n var acceptButtons = $x('.//a[@class=\"sexy_button_new medium white\" and contains(.,\"Join Mafia\")]',currentPopup);\n if(acceptButtons && isGMChecked('acceptMafiaInvitations')){\n for(i=0;i<acceptButtons.length>0;++i){\n acceptButton = acceptButtons[i];\n clickElement(acceptButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - Added '+acceptButtons.length+' members to your mafia.');\n }\n // Accept Crew Invites from MESSAGE CENTER / Total Requests popup\n var acceptButtons = $x('.//a[@class=\"sexy_button_new medium white\" and contains(.,\"Accept Crew\")]',currentPopup);\n if(acceptButtons && isGMChecked('autoAcceptMsgCrew')){\n for(i=0;i<acceptButtons.length>0;++i){\n acceptButton = acceptButtons[i];\n clickElement(acceptButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - Accepted '+acceptButtons.length+' Crew Invites to your mafia.');\n }\n // Send Eneryg Packs to your Mafia from MESSAGE CENTER / Total Requests popup\n var acceptButtons = $x('.//a[@class=\"sexy_button_new medium white\" and (contains(.,\"Send Energy\") or contains(@onclick,\"xw_action=accept_energy_req\"))]',currentPopup);\n if(acceptButtons && isGMChecked('autosendMsgEnergyPack')){\n for(i=0;i<acceptButtons.length>0;++i){\n acceptButton = acceptButtons[i];\n clickElement(acceptButton);\n }\n DEBUG('Popup Process: MESSAGE CENTER - Sent '+acceptButtons.length+' energy Packs to your mafia.');\n }\n return(closePopup(currentPopup, \"MESSAGE CENTER\"));\n }\n\n // Process Red Mystery Bag popup\n if(popupInnerNoTags.indexOf('opened a red mystery bag') != -1){\n DEBUG('Popup Process: Red Mystery Bag Processed');\n var bagTxt;\n if(popupInnerNoTags.match(/you got:(.+?)(send|share)/i)) bagTxt = RegExp.$1;\n addToLog('lootbag Icon', 'Received <span class=\"loot\">'+ bagTxt+'</span> from a red mystery bag.');\n return(closePopup(currentPopup, \"Red Mystery Bag Drop\"));\n }\n\n // Process Mystery Bag popup\n if(popupInnerNoTags.indexOf('share mystery bonus') != -1){\n DEBUG('Popup Process: Mystery Bag Processed');\n var bagTxt;\n if(popupInnerNoTags.match(/you got:(.+?)(send|share)/i)) bagTxt = RegExp.$1;\n addToLog('lootbag Icon', 'Received <span class=\"loot\">'+ bagTxt+'</span> from a mystery bag.');\n return(closePopup(currentPopup, \"Mystery Bag Drop\"));\n }\n\n // Process Battle Rewards Collect popup\n if(popupInner.indexOf('BattleResultsController')!=-1){\n DEBUG('Found BattleRewards Popup');\n elt = xpathFirst('.//a[contains(@onclick,\"BattleResultsController.collectReward\") and contains(.,\"Collect\")]', currentPopup);\n if(elt){\n DEBUG('Found collect link to click, boom!');\n clickElement(elt);\n } else DEBUG('No collect link found :(');\n return(closePopup(currentPopup, \"Battle Collect Popup\"));\n }\n\n // Process Robbery Loot popup\n if(popupInnerNoTags.indexOf('you cleared the full board') != -1){\n var totalCash=0; var totalXP = 0; var totalNRG = 0; var totalSTAM = 0;\n // get robbing results\n var robResults = $x('.//div[@class=\"rob_res_expanded_details\"]');\n var robResultTxt='';\n if(robResults && robResults.length>0){\n for(i=0,iLength=robResults.length;i<iLength;i++){\n var currentRobResult = robResults[i];\n var currentInnerResult = currentRobResult.innerHTML.untag();\n var cashRobResult = xpathFirst('.//div[@class=\"rob_res_expanded_details_cash\"]',currentRobResult);\n if(cashRobResult){\n if(cashRobResult.innerHTML.untag().match(REGEX_CASH)) totalCash+= parseCash(RegExp.lastMatch);\n }\n\n var xpRobResult = xpathFirst('.//div[@class=\"rob_res_expanded_details_exp\"]',currentRobResult);\n if(xpRobResult){\n if(xpRobResult.innerHTML.untag().match(/(\\d+) Experience/)) totalXP+= parseInt(RegExp.$1);\n }\n if(currentInnerResult.match(/\\+(\\d+) Energy/)) totalNRG+=parseInt(RegExp.$1);\n if(currentInnerResult.untag().match(/\\+(\\d+) Stamina/)) totalSTAM+=parseInt(RegExp.$1);\n }\n\n if(totalCash) robResultTxt+=' <span class=\"good\">'+cities[city][CITY_CASH_SYMBOL]+makeCommaValue(totalCash)+'</span>';\n if(totalXP) robResultTxt+=' and <span class=\"good\">'+totalXP+' experience</span>';\n if(totalNRG) robResultTxt+=' and <span class=\"user\">'+totalNRG+' energy</span>';\n if(totalSTAM) robResultTxt+=' and <span class=\"bad\">'+totalSTAM+' stamina</span>';\n robResultTxt='You Gained '+robResultTxt+'.';\n }\n\n // Look for any loot on popup\n DEBUG('Popup Process: Processing robbing board');\n if(popupInnerNoTags.match(/(\\d+) bonus experience/i)){\n var exp = RegExp.$1.replace(/[^0-9]/g, '');\n var boardrecord =\"\";\n var boardExp = parseInt(boardLastPtsToNextLevel) - parseInt(ptsToNextLevel);\n var boardStam = parseInt(boardLastStamina) - parseInt(stamina);\n var boardRatio = parseFloat(boardExp / boardStam).toFixed(2);\n\n if(popupInner.match(/your record on this board was\\s+(.+?)\\./i)) boardrecord = '<br>Board Record: <span class=\"good\">'+ RegExp.$1+'</span>';\n\n addToLog('yeah Icon', 'Robbing board cleared. '+robResultTxt+' Bonus: <span class=\"good\">'+ exp+' experience</span>.'+ boardrecord+' - Ratio: '+ boardExp+'/'+ boardStam + ' ('+ boardRatio +') ');\n\n boardLastStamina = parseInt(stamina);\n boardLastPtsToNextLevel = parseInt(ptsToNextLevel);\n //DEBUG('doRob Getting start values: '+boardLastStamina+'-'+boardLastPtsToNextLevel);\n\n if(!isGMChecked('fastRob') || !isGMChecked('noStats')){\n updateRobStatistics(null,parseInt(exp));\n updateLogStats();\n }\n if(popupInner.match(/you\\s+(earned|gained|received|collected)\\s+(some|an?)\\s+bonus\\s+(.+?)\\.?<\\/div>/i)){\n addToLog('lootbag Icon', 'Found <span class=\"loot\">'+ RegExp.$3+'</span> on robbing board.');\n }\n }\n return(closePopup(currentPopup, \"Robbing Board Popup\"));\n }\n\n// Level Up popups\n // Process Level Up Skill Points\n var upgradePointsElt = xpathFirst('.//span[@id=\"level_up_skill\"]',currentPopup);\n if(upgradePointsElt){\n if(isGMChecked('autoStat')){\n var upgradePoints=0;\n upgradePoints = parseInt(upgradePointsElt.innerHTML);\n var autoStatValues = autoStatVars();\n if(upgradePoints && autoStatValues[0]!='' && autoStatValues[1]!=0){\n var StatUpgrdUrl = 'remote/html_server.php?xw_controller=stats&xw_action=upgrade&upgrade_key='+autoStatValues[0]+'&upgrade_amt='+autoStatValues[1]+'&no_load=1&source=level_up_popup';\n var ajaxID = createAjaxPage(true);\n var elt = makeElement('a', null, {'onclick':'return do_ajax(\"'+ ajaxID+'\",\"'+StatUpgrdUrl+'\", 1, 0, null, update_level_up_skill); return false;' } );\n if(elt){\n var statName = autoStatValues[0].replace('max_','');\n var statIndex = eval(statName.toUpperCase()+'_STAT');\n var statIcon = statName.toLowerCase()+' Icon';\n var statInc = isNaN(autoStatValues[1]) ? 1 : parseInt(autoStatValues[1]);\n GM_setValue('nextStat' , (statIndex + 1) % 4);\n switch (statIndex){\n case ATTACK_STAT: curAttack += statInc; break;\n case DEFENSE_STAT: curDefense += statInc; break;\n case HEALTH_STAT: maxHealth += statInc; break;\n case ENERGY_STAT: maxEnergy += statInc; break;\n case STAMINA_STAT: maxStamina += statInc; break;\n }\n addToLog(statIcon, '<span style=\"color:#885588;\">'+statName+' increased by '+statInc+' point(s).</span>');\n clickAction = 'autoStatAllocation';\n clickElement(elt);\n return;\n }\n }\n\n var StatUpgrdUrl = 'remote/html_server.php?xw_controller=levelUpBonus&xw_action=addBonusItem&xw_city='+city+'&no_load=1';\n var ajaxID = createAjaxPage(true);\n var elt = makeElement('a', null, {'onclick':'return do_ajax(\"'+ ajaxID+'\",\"'+StatUpgrdUrl+'\", 1, 0, null, update_level_up_bonus_item); return false;' } );\n if(elt && claimLevelUpBonus){\n DEBUG('Claiming Skill Points Allocation Reward');\n clickAction = 'autoStatReward';\n clickElement(elt);\n claimLevelUpBonus = false;\n return;\n }\n } else {\n DEBUG('Skill Poinst Allocation OFF');\n }\n }\n\n // Click to share bonus\n if(popupInnerNoTags.match(/(you are now level|promoted to level) (\\d+)/i)){\n addToLog('info Icon','You were promoted to level <span class=\"good\">'+ RegExp.$2 +'</span>');\n if(document.getElementById('bonusItemName')){\n var bonusItemName = document.getElementById('bonusItemName');\n addToLog('lootbag Icon','Level Up Bonus Item: <span class=\"loot\">'+ bonusItemName.innerHTML +'</span>');\n }\n\n if(isGMChecked('autoGlobalPublishing')){\n var eltPubButton = xpathFirst('.//a[contains(@onclick,\"postLevelUpFeedAndSend\") and contains(.,\"Share\")]',currentPopup);\n if(!eltPubButton) eltPubButton = xpathFirst('.//a[contains(@onclick,\"xw_action=levelup_boost_brag\") and contains(.,\"Share\")]',currentPopup);\n if(!eltPubButton) eltPubButton = xpathFirst('.//div[@id=\"bonusShareButton\"]//a[contains(.,\"Share\")]',currentPopup);\n if(eltPubButton){\n DEBUG('Level Up popup Share button detected');\n clickElement(eltPubButton);\n }\n }\n claimLevelUpBonus = true;\n return(closePopup(currentPopup, \"Level Up Bonus\"));\n }\n\n // Post to friends\n var postFriendsElts = $x('.//a[contains(@onclick,\"postFeedAndSendSocialList\") and contains(.,\"Post\")]',currentPopup);\n if(postFriendsElts && postFriendsElts.length>0){\n return(closePopup(currentPopup, \"Level Up Bonus Sharing\"));\n }\n\n// Operations / Missions popups\n // Get rid of not in Operations popup\n if(popupInnerNoTags.indexOf('not involved in this mission') != -1){\n return(closePopup(currentPopup, \"Not in Operation\"));\n }\n\n // Start a New Operation\n if(popupInnerNoTags.indexOf('start operation') != -1){\n var missionButton = xpathFirst('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"postCelebrateFeed\")]',currentPopup);\n if(!missionButton) missionButton = xpathFirst('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"startMission\")]',currentPopup);\n if(missionButton && isGMChecked('AutoMafiaMission')){\n clickElement(missionButton);\n DEBUG('Popup Process: OPERATIONS - Started a new Operation');\n }\n return(closePopup(currentPopup, \"Start New Operation\"));\n }\n\n // Invite Friends on Operation Start\n if(popupInnerNoTags.indexOf('invite friends') != -1){\n var missionButton = xpathFirst('.//a[@class=\"sexy_button_new medium white\" and contains(@onclick,\"postCelebrateFeed\")]',currentPopup);\n if(missionButton){\n if(isGMChecked('AutoMafiaMission')){\n clickElement(missionButton);\n DEBUG('Popup Process: OPERATIONS - Started My own Operation');\n }\n }\n return(closePopup(currentPopup, \"Inviting Friends on Operation Start\"));\n }\n\n // Claim Operation Rewards Failed\n if(popupInnerNoTags.indexOf('failed to give reward') != -1){\n DEBUG('Popup Process: OPERATIONS - Claim Rewards Failed');\n return(closePopup(currentPopup, \"Claim Operations Rewards Failed\"));\n }\n\n // Log Operation Rewards\n if(popupInnerNoTags.indexOf('completed the operation') != -1){\n DEBUG('Popup Process: OPERATIONS - Claim Rewards : '+currentPopup.id);\n\n var rewards = $x('.//td[@class=\"collectPopLootItem\"]', currentPopup);\n var rewardsTxt =\"\";\n var rewardsNoTags =\"\";\n for(i=0;i<rewards.length;++i){\n rewardsNoTags = rewards[i].innerHTML.untag();\n if(rewardsNoTags.match(/(.+?)(\\d{2})(\\d{2})$/)) rewardsNoTags = '<span class=\"loot\">'+RegExp.$1+ '</span> (A: '+RegExp.$2+' / D: '+ RegExp.$3+')';\n else if(rewardsNoTags.match(/(.+?)(\\d{2})(\\d{1})$/)) rewardsNoTags = '<span class=\"loot\">'+RegExp.$1+ '</span> (A: '+RegExp.$2+' / D: '+ RegExp.$3+')';\n else if(rewardsNoTags.match(/(.+?)(\\d{1})(\\d{2})$/)) rewardsNoTags = '<span class=\"loot\">'+RegExp.$1+ '</span>(A: '+RegExp.$2+' / D: '+ RegExp.$3+')';\n else if(rewardsNoTags.match(/(.+?)(\\d{1})(\\d{1})$/)) rewardsNoTags = '<span class=\"loot\">'+RegExp.$1+ '</span>(A: '+RegExp.$2+' / D: '+ RegExp.$3+')';\n if(rewardsTxt) rewardsTxt += ', '+ rewardsNoTags;\n else rewardsTxt = rewardsNoTags;\n }\n addToLog('lootbag Icon', 'Operation Rewards : '+rewardsTxt);\n if(!isGMChecked('autoShareRewards')) return(closePopup(currentPopup, \"Operations Rewards claimed\"));\n }\n\n // Share Operation Rewards\n var shareButton = xpathFirst('.//a[@class=\"sexy_button_new medium white sexy_call_new\" and contains(@onclick,\"postCelebrateFeed\")]',currentPopup);\n if(shareButton){\n if(isGMChecked('autoShareRewards')){\n clickElement(shareButton);\n DEBUG('Popup Process: OPERATIONS - Share Rewards');\n }\n return(closePopup(currentPopup, \"Share Operations Rewards\"));\n }\n\n// War Popups\n // Get rid of War Fight Won - Succesfull War Attack popup\n if(popupInnerNoTags.indexOf('won the fight') != -1){ return(closePopup(currentPopup, \"Succesfull War Attack\")); }\n // Get rid of War Fight Lost - Succesfull War Attack popup\n if(popupInnerNoTags.indexOf('lost the fight') != -1){ return(closePopup(currentPopup, \"Succesfull War Attack\")); }\n\n // Get rid of War already helped popup\n if(popupInnerNoTags.indexOf('have already helped') != -1){ return(closePopup(currentPopup, \"Already Helped\")); }\n\n // Get rid of War is already over popup\n if(popupInnerNoTags.indexOf('war is already over') != -1){ return(closePopup(currentPopup, \"War already over\")); }\n\n // Get rid of War Not in Mafia popup\n if(popupInnerNoTags.indexOf('a mafia request') != -1){ return(closePopup(currentPopup, \"War Not in Mafia\")); }\n\n // War Declaration\n var warDeclareButton = xpathFirst('.//a[@class=\"sexy_button_new short white sexy_call_new\" and contains(@onclick,\"attemptFeed\")]',currentPopup);\n if(warDeclareButton){\n if(isGMChecked('autoGlobalPublishing')){\n clickElement(warDeclareButton);\n DEBUG('Popup Process: WAR - Declare War Publishing');\n }\n return(closePopup(currentPopup, \"War Declaration Popup\"));\n }\n\n // War Rally for Help\n if(popupInnerNoTags.indexOf('help to take out all 7') != -1){\n eltHelp = xpathFirst('.//a[contains(.,\"Ask Friends for Help\")]', currentPopup);\n if(eltHelp && isGMChecked('autoGlobalPublishing')){\n clickElement(eltHelp);\n DEBUG('Popup Process: WAR - Ask Friends for Help Publishing');\n }\n return(closePopup(currentPopup, \"War Help Popup\"));\n }\n\n // War Reward : Share Victory Coins\n if(popupInnerNoTags.indexOf('share victory coins') != -1){\n var warRewardButtons = $x('.//a[@class=\"sexy_button_new short white\" and contains(@onclick,\"postWarWin\")]',currentPopup);\n if(warRewardButtons && isGMChecked('autoGlobalPublishing')){\n for(i=0;i<warRewardButtons.length>0;++i){\n warRewardButton = warRewardButtons[i];\n clickElement(warRewardButton);\n DEBUG('Popup Process: WAR - Reward Friends (Share Coins) for Help Publishing');\n }\n }\n return(closePopup(currentPopup, \"War Reward (Share Coins) Popup\"));\n }\n\n// Miscelaneous\n // Themed Events\n eltHelp = xpathFirst('.//a[contains(@class,\"sexy_button_new\") and contains(.,\"Share\")]', currentPopup);\n if(eltHelp && isGMChecked('autoGlobalPublishing')){\n clickElement(eltHelp);\n DEBUG('Popup Process: Shared Themed Event Items - '+popupInnerNoTags);\n DEBUG('Popup Process: Button: '+eltHelp.innerHTML);\n return(closePopup(currentPopup, \"Shared Themed Event Items\"));\n }\n\n // Loot Events\n if(popupInnerNoTags.match(/you found (.*) loot event./i) || popupInnerNoTags.match(/you found all (.*) in action./)){\n if(popupInnerNoTags.match(/you found (.*) loot event./i)) logtxt = 'You found '+ RegExp.$1+' loot event.';\n else if(popupInnerNoTags.match(/you found all (.*) in action./)) logtxt = 'You found '+ RegExp.$1+' in action.';\n if(logtxt) addToLog('yeah Icon',logtxt);\n return(closePopup(currentPopup, \"Loot Event\"));\n }\n\n// Brazil City Crew\n//Send city crew requests\n if(( isGMChecked('autoAskCityCrew') || isGMChecked('autoAskChicagoCrew') )&& popupInnerNoTags.indexOf('send city crew requests') != -1){\n var crewMembers = $x('.//div[@class=\"mfs_selectable\"]//li[@class=\"mfs_add\" and not(contains(@style,\"none\"))]',currentPopup);\n var requestButton = xpathFirst('.//a[@class=\"sexy_button_new medium orange\" and contains(@onclick,\"MW.Request.submitMFS\") and contains(.,\"SEND REQUESTS\")]', currentPopup);\n if(crewMembers && crewMembers.length>0 && requestButton){\n var randomButton = xpathFirst('.//a[@id=\"selectMaxButton\" and not (contains(@class,\"disabled\"))]');\n if(randomButton) clickElement(randomButton);\n else {\n var iLength = (crewMembers.length>50) ? 50 : crewMembers.length;\n for(i=0;i<iLength;i++) clickElement(crewMembers[i]);\n }\n clickElement(requestButton);\n } else DEBUG('autoAskCityCrew - handlePopups - NO Crew Members Available or SEND REQUESTS not found');\n if(popupInnerNoTags.indexOf('send city crew requests') != -1 && popupInnerNoTags.indexOf('you have successfully sent requests') != -1)\n addToLog('yeah Icon', 'You have successfully sent out requests to your mafia to join your City Crew'); \n return(closePopup(currentPopup, \"autoAskCityCrew Requests\"));\n }\n\n// Fight // Rob Level Mastery\n if(popupInnerNoTags.indexOf('level mastered') != -1){\n var tellFriendsButton = $xpathFirst('.//a[@class=\"sexy_button_new short green sexy_announce\" and contains(@onclick,\"post_mastery_feed\")]',currentPopup);\n if(tellFriendsButton && isGMChecked('autoGlobalPublishing')){\n clickElement(tellFriendsButton);\n DEBUG('Popup Process: Robbing/Fighting Level Mastery - Tell Your Friends');\n }\n return(closePopup(currentPopup, \"Robbing/Fighting Level Mastered\"));\n }\n\n /* IF THE POPUP COULD NOT BE PROCESSED AS ABOVE WE WILL CLOSE IT */\n /* THESE POPUPS get always closed: */\n // Get rid of Paypal\n if(popupInnerNoTags.indexOf('paypal') != -1) return(closePopup(currentPopup, \"Paypal\"));\n\n // Get rid of buyframe popup (You are almost out of reward points)\n if(popupInner.indexOf('xw_action=buyframe_popup') != -1) return(closePopup(currentPopup, \"Buy Reward Points\"));\n if(popupInnerNoTags.indexOf('div.buyframe_pop_box') != -1) return(closePopup(currentPopup, \"Buy Reward Points\"));\n\n // Get rid of Crime Spree Congratulations popup\n if(popupInnerNoTags.indexOf('safehouse_congrats') != -1) return(closePopup(currentPopup, \"Crime Spree Congratulations\"));\n\n // Get rid of Treasure Chest popup\n if(popupInnerNoTags.indexOf('treasure chest') != -1) return(closePopup(currentPopup, \"Treasure Chest\"));\n\n // Get rid of Keep Winning popup\n if(popupInnerNoTags.indexOf('keep winning') != -1) return(closePopup(currentPopup, \"Robbery Keep Winning\"));\n\n // Get rid of Tired of Losing popup\n if(popupInnerNoTags.indexOf('tired of losing') != -1) return(closePopup(currentPopup, \"Robbery Tired of Losing\"));\n\n // Get rid of Slots Collection popup\n if(popupInnerNoTags.indexOf('the slots collection') != -1) return(closePopup(currentPopup, \"Slots Collection\"));\n\n // Get rid of Grow your Mafia popup\n if(popupInnerNoTags.indexOf('friend to be in your mafia and help') != -1) return(closePopup(currentPopup, \"Grow your Mafia\"));\n\n // Get rid of Slot Machine Teaser popup\n if(popupInnerNoTags.indexOf('new loot!') != -1) return(closePopup(currentPopup, \"Slot Machine Flushed\"));\n\n // Get rid of Your Requests popup\n if(popupInnerNoTags.indexOf('your mafia wars requests have moved to the left column on facebook') != -1) return(closePopup(currentPopup, \"Your Requests\"));\n\n // Get rid of not enough health / stamina / energy popup\n if(popupInnerNoTags.indexOf('not have enough') != -1) return(closePopup(currentPopup, \"not enough health, stamina or energy\"));\n\n // Get rid of out of health / stamina / energy popup\n if(popupInnerNoTags.indexOf('out of') != -1 && popupInnerNoTags.indexOf('the bank') == -1) return(closePopup(currentPopup, \"out of health, stamina or energy\"));\n\n // Get rid of You helped in . . . popup\n if(popupInnerNoTags.indexOf('you helped in') != -1) return(closePopup(currentPopup, \"You helped in\"));\n\n // Get rid of Welcome to Tournaments popup\n if(popupInnerNoTags.indexOf('become world champion') != -1) return(closePopup(currentPopup, \"Welcome to Tournaments\"));\n\n // Get rid of Tournament Expired popup\n if(popupInnerNoTags.indexOf('your previous tournament has expired') != -1) return(closePopup(currentPopup, \"Tournament Expired\"));\n\n // Get rid of Increase your mafia popup\n var mafiaSuggestor = xpathFirst('.//div[@id=\"let_there_be_space\"]',currentPopup);\n var mafiaRequestIfc = xpathFirst('.//div[@id=\"request_ifc\"]',currentPopup);\n if(mafiaSuggestor && mafiaRequestIfc) return(closePopup(currentPopup, \"increase your mafia\")); \n\n // Try to Process Unknown Popups\n if(isGMChecked('autoProcessPopups')){\n eltButton = xpathFirst('.//a[contains(@class,\"sexy_button_new\") and not (contains(.,\"Refill\")) and not (contains(.,\"Buy\")) and not (contains(.,\"RP\"))]', currentPopup);\n if(eltButton){\n DEBUG('Tried to process the following popup ('+eltButton.innerHTML+'):<br>'+popupInnerNoTags);\n clickElement(eltButton);\n } else DEBUG('Could not process the following popup :<br>'+popupInnerNoTags);\n return(closePopup(currentPopup, \"autoClosing (autoProcess) Unknown\"));\n }\n\n // End of Popups Section\n\n }\n /* END */\n }\n }\n }\n } catch (ex){\n DEBUG('Error @handlePopups: '+ ex);\n }\n return false;\n}", "afterShow(popup) {}", "init_popup(parent) {\n // Div, initially hidden, pops up to show full record json\n parent.popup_el = document.getElementById('popup');\n parent.popup_close_el = document.getElementById('popup_close');\n parent.popup_fixed = false;\n }", "function initLabsPopups() {\n \n $(document).ready(function() {\n\n $('#datamodel-img-popup').popup({\n transition: 'all 0.3s'\n });\n\n });\n}", "function popupAdvanced(noticeHTML,params={\n isTutorial : false,\n buttons : [new popupButton()],\n allowClose : false,\n noticeTitleHTML : \"ALERT:\",\n focusIdx : 0\n }){\n var buttons = params.buttons;\n var allowClose = params.allowClose;\n var noticeTitleHTML = params.noticeTitleHTML\n var isTutorial = params.isTutorial\n if(buttons === undefined){\n if(isTutorial){\n buttons = [new popupButton(\n html=\"OK\",\n buttonFunc = function(){\n if( ELEMS.popupChecks[0].checked ){\n document.getElementById(\"ENABLE_TUTORIAL_CHECKBOX\").checked = false;\n console.log(\"TUTORIAL OFF!\")\n STATS.TUTORIAL_ACTIVE = false;\n }\n }, \n buttonDisabled = false, \n closeOnClick= true\n )];\n\n \n } else {\n buttons = [new popupButton()]\n }\n }\n if(isTutorial){\n ELEMS.popupChecks[0].L.style.display = \"block\";\n ELEMS.popupChecks[1].L.style.display = \"none\";\n ELEMS.popupChecks[2].L.style.display = \"none\";\n ELEMS.popupChecks[0].checked = false;\n ELEMS.popupChecks[0].LS.innerHTML = \"Turn off tutorial popups.\"\n }\n \n if(allowClose === undefined){\n allowClose = false\n }\n if(noticeTitleHTML === undefined){\n noticeTitleHTML = \"ALERT:\"\n }\n ELEMS.popupTextBox.innerHTML = noticeHTML;\n ELEMS.popupTitle.innerHTML = noticeTitleHTML;\n\n ELEMS.popupCloseButton.disabled = ! allowClose\n\n for(var i=0; i < ELEMS.popupButtons.length; i++){\n var belem = ELEMS.popupButtons[i];\n \n if(i < buttons.length){\n var buttonInfo = buttons[i];\n belem.style.display = \"block\";\n belem.innerHTML = buttonInfo.html;\n belem.onclick = buttonInfo.getOnClick();\n belem.disabled = buttonInfo.buttonDisabled;\n } else {\n belem.style.display = \"none\";\n }\n }\n openPopupWindow()\n var focusIdx = params.focusIdx;\n if( focusIdx == null){\n focusIdx = 0;\n }\n if(focusIdx >= 0 && buttons.length > 0){\n ELEMS.popupButtons[focusIdx].focus();\n }\n \n \n}", "function t_popup(purl)\n{\n\tif(t_createwindow())\n\t{$('#m_popup').fadeIn();\n\t//m_opacity('m_popup',40,100,800);\n\tdocument.getElementById('m_popup_blok').innerHTML='<iframe id=\"m_di_pop\" src='+purl+' width=100% height=100% style=border:0><\\/iframe>';\n\t}\n}", "function inicializarPopup(){\n\t$popUp = new dhtmlXPopup();\n\t$popUp.attachEvent(\"onHide\", function(){$estatuspopUp=true;});\n\t$estatuspopUp = true;\n}", "function popupPromozioni(id_riga, articolo_selezionato, tipo){\n \n //chiudo il popup di disponibilita\n if(tipo === 'popup'){\n $(\"#popupDisponibilita\").popup(\"close\", \"pop\");\n }\n \n //campi per il calcolo delle scontistiche\n box_promozioni = tipo_sconto = \"\";\n qta_min = 0;//imposto di default la qta minima articoli a 0\n sconto_max = articolo_selezionato.sconto_max * 1;\t\t\t\n qta1 = articolo_selezionato.qta1 * 1;\n sconto_qta1 = articolo_selezionato.sconto_qta1 * 1;\n qta2 = articolo_selezionato.qta2 * 1;\n sconto_qta2 = articolo_selezionato.sconto_qta2 * 1;\n qta3 = articolo_selezionato.qta3 * 1;\n sconto_qta3 = articolo_selezionato.sconto_qta3 * 1; \n\n //se per l'articolo Ŕ disponibile una promo mostro il popup di selezione\n if(qta1>0){\n \n var string_qtal = \"Nessuno sconto presente\";\n if(sconto_max !== 0)\n string_qtal = \"Sconto Max \" + sconto_max + \" %\";\n \n box_promozioni += \"<li><a href=\\\"javascript:void(0);\\\" onClick=\\\"impostaPromoQta(\"+id_riga+\", '', \"+sconto_max+\", 'promo_qta_libera');\\\" >Quantit&agrave; Libera - \" + string_qtal + \"</a></li>\";\n box_promozioni += \"<li><a href=\\\"javascript:void(0);\\\" onClick=\\\"impostaPromoQta(\"+id_riga+\", \"+qta1+\", \"+sconto_qta1+\", 'promo_qta_1');\\\" >Promo \" + qta1 + \" PZ - Sconto Max \" + sconto_qta1 + \" %</a></li>\";\n \n if(qta2>0){\n box_promozioni += \"<li><a href=\\\"javascript:void(0);\\\" onClick=\\\"impostaPromoQta(\"+id_riga+\", \"+qta2+\", \"+sconto_qta2+\", 'promo_qta_2');\\\" >Promo \" + qta2 + \" PZ - Sconto Max \" + sconto_qta2 + \" %</a></li>\";\n }\n \n if(qta3>0){\n box_promozioni += \"<li><a href=\\\"javascript:void(0);\\\" onClick=\\\"impostaPromoQta(\"+id_riga+\", \"+qta3+\", \"+sconto_qta3+\", 'promo_qta_3');\\\" >Promo \" + qta3 + \" PZ - Sconto Max \" + sconto_qta3 + \" %</a></li>\";\n }\n \n tipo_sconto = \"PQ\";//promo qta\n \n }else if(sconto_max !== 0){//sconto massimo impostato\n \n box_promozioni += \"<li><a href=\\\"javascript:void(0);\\\" onClick=\\\"$( '#popupPromozioni' ).popup('close', 'pop');\\\" >Lo sconto massimo applicabile per l'articolo &egrave; \" + sconto_max + \" %</a></li>\"; \n qta_min=0;\n tipo_sconto=\"PF\";//promo fissa\n \n }else{//nessuna promo o sconto arriva per l'articolo\n \n qta_min = 0;\n sconto_max = 0;\n tipo_sconto = \"PF\";//promo fissa\n \n }\n \n //imposto i campi nascosti\n $('#min-qta_' + id_riga).val(qta_min);\n $('#max-sconto_' + id_riga).val(sconto_max);\n $('#tipo-sconto_' + id_riga).val(tipo_sconto);\n \n //verifico se mostrare il box promozioni o meno\n if(box_promozioni !== \"\"){\n \n //salvo il contenuto dell'articolo in un campo input nascosto\n var articolo_json = JSON.stringify(articolo_selezionato);\n $('#articolo_json_promozioni').val(articolo_json);\n \n //compongo la lista e mostro il popup\n var list = \"<ul id=\\\"search_item\\\" data-role=\\\"listview\\\" >\";\n list += box_promozioni;\n list += \"</ul>\";\n \n $(\"#popupPromozioniContent\").html(list);\n setTimeout( function(){ $( '#popupPromozioni' ).popup(\"open\", \"pop\"); }, 100 );\n \n }else{\n\n popupTaglieColori(id_riga, articolo_selezionato);\n \n }\n\n}", "function setupAcpPopups() {\n\t$wpu('#wpumapscreen a.wpuacppopup, #wpumaptab-perms a.wpuacppopup').colorbox({\n\t\twidth: '88%', \n\t\theight: '92%', \n\t\ttitle: (acpPopupTitle == undefined) ? '' : acpPopupTitle,\n\t\tiframe: true,\n\t\tonClosed: function() {\n\t\t\twindow.scrollTo(0,0);\n\t\t\t$wpu('#wpu-desc').html('<strong>' + wpuReloading + '</strong><br />Please wait...');\n\t\t\t$wpu(\"#wpu-reload\").dialog({\n\t\t\t\tmodal: true,\n\t\t\t\ttitle: wpuReloading,\n\t\t\t\twidth: 360,\n\t\t\t\theight: 160,\n\t\t\t\tdraggable: false,\n\t\t\t\tdisabled: true,\n\t\t\t\tcloseOnEscape: false,\n\t\t\t\tresizable: false\n\t\t\t});\n\t\t\t$wpu('.ui-dialog-titlebar').hide();\n\t\t\twindow.location.reload(1);\n\t\t}\n\t});\n}", "getAllPopups() {\n return document.getElementsByClassName(A11yClassNames.POPUP);\n }", "addPopupWin() {\n const popupEl = this.el.getElementsByClassName('wrapper-block__game-blendocu')[0];\n if (popupEl) {\n this._popup.renderTo(popupEl);\n this._popup.render({numStars: this.finalStars, time: ` ${~~(this.timeNowSec/1000)} `, toNextLevel: this.params.toNextLevel});\n }\n }", "function createImagePopups() {\n // for filepath popups\n $('.open-popup-link').fancybox({\n touch : 'false'\n });\n // for search tip popups\n $('.ajax-popup-link').fancybox({\n type : 'ajax'\n });\n }", "function setupMajorsPopups() {\n $('.majorLabel').popup({\n position: 'bottom center',\n inline: true,\n transition: 'vertical flip'\n });\n }", "function ITSMCore_addPopupListeners()\n{\n\t$('.itsmcore-small-popup-link').unbind('click');\n\t\n\t$('.itsmcore-small-popup-link').click(function(e){\n\t\te.preventDefault();\n\t\tITSMCore_openSmallWindow($(this).attr('href'));\n\t});\n\t\n\t$('.itsmcore-small-popup-link-td').find('a').unbind('click');\n\t$('.itsmcore-small-popup-link-td').find('a').click(function(e){\n\t\te.preventDefault();\n\t\tITSMCore_openSmallWindow($(this).attr('href'));\n\t});\n\t$(\".results-button\").click(function(){ITSMCore_addPopupListeners()});\n}", "constructor() {\n const links = document.querySelectorAll('[data-ribspopup]');\n\n Array.from(links).forEach((element) => {\n element.addEventListener('click', (event) => this.openPopup(event));\n });\n }", "function popUp () {\n pub.setAttribute('class','popup');\n let nbPub = sessionStorage.getItem('pub');\n let plusPub = localStorage.getItem('pub');\n if (nbPub == 1 || plusPub == 1){ //sessionStorage ou localStorage pour stocker l'apparition de la pub.\n pub.setAttribute('class','hidden'); //pour empecher la popup de revenir dans la page apres l'avoir fermée une fois\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `BodyProperty`
function CfnWebACL_BodyPropertyValidator(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('oversizeHandling', cdk.validateString)(properties.oversizeHandling)); return errors.wrap('supplied properties not correct for "BodyProperty"'); }
[ "function CfnWebACL_ResponseInspectionBodyContainsPropertyValidator(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('failureStrings', cdk.requiredValidator)(properties.failureStrings));\n errors.collect(cdk.propertyValidator('failureStrings', cdk.listValidator(cdk.validateString))(properties.failureStrings));\n errors.collect(cdk.propertyValidator('successStrings', cdk.requiredValidator)(properties.successStrings));\n errors.collect(cdk.propertyValidator('successStrings', cdk.listValidator(cdk.validateString))(properties.successStrings));\n return errors.wrap('supplied properties not correct for \"ResponseInspectionBodyContainsProperty\"');\n}", "function isValidRequest(req, properties) {\n\n\tconst hasAllProperties = (hasAllPropertiesSoFar, currentProperty) => hasAllPropertiesSoFar && req.body.hasOwnProperty(currentProperty);\n\treturn properties.reduce(hasAllProperties, true);\n}", "function CfnWebACL_JsonBodyPropertyValidator(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('invalidFallbackBehavior', cdk.validateString)(properties.invalidFallbackBehavior));\n errors.collect(cdk.propertyValidator('matchPattern', cdk.requiredValidator)(properties.matchPattern));\n errors.collect(cdk.propertyValidator('matchPattern', CfnWebACL_JsonMatchPatternPropertyValidator)(properties.matchPattern));\n errors.collect(cdk.propertyValidator('matchScope', cdk.requiredValidator)(properties.matchScope));\n errors.collect(cdk.propertyValidator('matchScope', cdk.validateString)(properties.matchScope));\n errors.collect(cdk.propertyValidator('oversizeHandling', cdk.validateString)(properties.oversizeHandling));\n return errors.wrap('supplied properties not correct for \"JsonBodyProperty\"');\n}", "hasProperty(aProperty){\n for(let i = 0; i < this._properties.length; i++){\n let prop = this._properties[i];\n if(aProperty.matches(prop)){\n return true;\n }\n }\n return false;\n }", "function CfnRule_MatchPropertyValidator(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('httpMatch', cdk.requiredValidator)(properties.httpMatch));\n errors.collect(cdk.propertyValidator('httpMatch', CfnRule_HttpMatchPropertyValidator)(properties.httpMatch));\n return errors.wrap('supplied properties not correct for \"MatchProperty\"');\n}", "function propertiesEquals(objA, objB, properties) {\n var i, property;\n\n for (i = 0; i < properties.length; i++) {\n property = properties[i];\n\n if (!equals(objA[property], objB[property])) {\n return false;\n }\n }\n\n return true;\n}", "function CfnRule_HeaderMatchPropertyValidator(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('caseSensitive', cdk.validateBoolean)(properties.caseSensitive));\n errors.collect(cdk.propertyValidator('match', cdk.requiredValidator)(properties.match));\n errors.collect(cdk.propertyValidator('match', CfnRule_HeaderMatchTypePropertyValidator)(properties.match));\n errors.collect(cdk.propertyValidator('name', cdk.requiredValidator)(properties.name));\n errors.collect(cdk.propertyValidator('name', cdk.validateString)(properties.name));\n return errors.wrap('supplied properties not correct for \"HeaderMatchProperty\"');\n}", "function CfnRule_HeaderMatchTypePropertyValidator(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('contains', cdk.validateString)(properties.contains));\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n return errors.wrap('supplied properties not correct for \"HeaderMatchTypeProperty\"');\n}", "function containsAllowedProps(properties) {\n if (properties === null || (typeof properties === 'undefined' ? 'undefined' : _typeof(properties)) !== 'object') {\n return false;\n }\n return Object.entries(properties).some(function (property) {\n var key = property[0];\n var value = property[1];\n if (typeof value === 'string') {\n return key === 'style' || key === 'src' || key === 'href';\n } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && key === 'attributes') {\n return 'class' in properties.attributes;\n }\n });\n}", "function hasProperties(actual, expected) {\n for (var k in expected) {\n var v = expected[k];\n if (!(k in actual))\n return false;\n if (Object(v) === v) {\n if (!hasProperties(actual[k], v))\n return false;\n } else {\n if (actual[k] !== v)\n return false;\n }\n }\n return true;\n}", "function CfnRuleGroup_FieldToMatchPropertyValidator(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('allQueryArguments', cdk.validateObject)(properties.allQueryArguments));\n errors.collect(cdk.propertyValidator('body', CfnRuleGroup_BodyPropertyValidator)(properties.body));\n errors.collect(cdk.propertyValidator('cookies', CfnRuleGroup_CookiesPropertyValidator)(properties.cookies));\n errors.collect(cdk.propertyValidator('headers', CfnRuleGroup_HeadersPropertyValidator)(properties.headers));\n errors.collect(cdk.propertyValidator('jsonBody', CfnRuleGroup_JsonBodyPropertyValidator)(properties.jsonBody));\n errors.collect(cdk.propertyValidator('method', cdk.validateObject)(properties.method));\n errors.collect(cdk.propertyValidator('queryString', cdk.validateObject)(properties.queryString));\n errors.collect(cdk.propertyValidator('singleHeader', cdk.validateObject)(properties.singleHeader));\n errors.collect(cdk.propertyValidator('singleQueryArgument', cdk.validateObject)(properties.singleQueryArgument));\n errors.collect(cdk.propertyValidator('uriPath', cdk.validateObject)(properties.uriPath));\n return errors.wrap('supplied properties not correct for \"FieldToMatchProperty\"');\n}", "function validateProperties(props) {\n let validProps = getProperties();\n for (let i in props) {\n if (!validProps.includes(props[i])) {\n return false;\n }\n }\n return true;\n}", "function CfnLoggingConfiguration_FieldToMatchPropertyValidator(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('jsonBody', cdk.validateObject)(properties.jsonBody));\n errors.collect(cdk.propertyValidator('method', cdk.validateObject)(properties.method));\n errors.collect(cdk.propertyValidator('queryString', cdk.validateObject)(properties.queryString));\n errors.collect(cdk.propertyValidator('singleHeader', cdk.validateObject)(properties.singleHeader));\n errors.collect(cdk.propertyValidator('uriPath', cdk.validateObject)(properties.uriPath));\n return errors.wrap('supplied properties not correct for \"FieldToMatchProperty\"');\n}", "function CfnRule_HttpMatchPropertyValidator(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('headerMatches', cdk.listValidator(CfnRule_HeaderMatchPropertyValidator))(properties.headerMatches));\n errors.collect(cdk.propertyValidator('method', cdk.validateString)(properties.method));\n errors.collect(cdk.propertyValidator('pathMatch', CfnRule_PathMatchPropertyValidator)(properties.pathMatch));\n return errors.wrap('supplied properties not correct for \"HttpMatchProperty\"');\n}", "function checkSameProps(properties, qParams, model) {\n var result = INCLUDE;\n\n _.each(properties, function(property) {\n if (_.has(qParams, property) && qParams[property] !== model.get(property)) {\n result = EXCLUDE;\n }\n });\n\n return result;\n }", "function CfnWebACL_HeaderMatchPatternPropertyValidator(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('all', cdk.validateObject)(properties.all));\n errors.collect(cdk.propertyValidator('excludedHeaders', cdk.listValidator(cdk.validateString))(properties.excludedHeaders));\n errors.collect(cdk.propertyValidator('includedHeaders', cdk.listValidator(cdk.validateString))(properties.includedHeaders));\n return errors.wrap('supplied properties not correct for \"HeaderMatchPatternProperty\"');\n}", "function CfnWebACL_JsonMatchPatternPropertyValidator(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('all', cdk.validateObject)(properties.all));\n errors.collect(cdk.propertyValidator('includedPaths', cdk.listValidator(cdk.validateString))(properties.includedPaths));\n return errors.wrap('supplied properties not correct for \"JsonMatchPatternProperty\"');\n}", "function hasSamePropertiesValue(properties1, properties2) {\n for (var property in properties1) {\n if (properties1.hasOwnProperty(property)) {\n if (properties1[property] !== properties2[property]) return false;\n }\n }\n\n return true;\n }", "function CfnRule_PathMatchPropertyValidator(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('caseSensitive', cdk.validateBoolean)(properties.caseSensitive));\n errors.collect(cdk.propertyValidator('match', cdk.requiredValidator)(properties.match));\n errors.collect(cdk.propertyValidator('match', CfnRule_PathMatchTypePropertyValidator)(properties.match));\n return errors.wrap('supplied properties not correct for \"PathMatchProperty\"');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of favicons at the given domain with the specified file types
function getFavicons(domain, fileTypes) { var fav = new Image(); var icons = []; for(var i = 0; i < fileTypes.length; i++) { var path = domain + "favicon." + fileTypes[i]; fav.onload = icons.push(path); fav.src = path; } return icons; }
[ "function getFavicon(domain, fileTypes) {\n return getFavicons(domain, fileTypes)[0]; // first favicon\n}", "function filesByMimetype(pattern)\n {\n return m_properties.files.value().filter(function (meta)\n {\n return meta.mimeType.startsWith(pattern);\n })\n .map(function (meta)\n {\n return meta.uri;\n });\n }", "function images(files) {\n const images = [];\n files.forEach(function(f) {\n if (isImage(f.mediatype.mime)) {\n images.push(f);\n }\n });\n return images;\n }", "function getImages(entries) {\n var regex = /.*\\.jpg|.*\\.png/;\n return entries.filter(entry => regex.test(entry.name));\n}", "function add_favicons_to(links) {\n for (var i=0; i<links.length; i++) {\n if (links[i].firstChild.tagName != 'IMG') {\n var host = links[i].href.replace(/^https?:\\/\\//,'').replace(/\\/.*$/,'');\n var img = document.createElement('IMG');\n img.src = 'http://www.google.com/s2/favicons?domain=' + host;\n img.width = '16';\n img.height = '16';\n img.className = 'favicon';\n links[i].insertBefore(img, links[i].firstChild);\n }\n }\n }", "function getImageFiles() {\n var the_files = [];\n $.each(project.files, function(i, file) {\n if (file.type === \"image\") {\n the_files.push(file);\n };\n });\n return the_files;\n}", "function getIcons(cb) {\n\n\t//search all icons\n\tvar icons = fs.readdirSync('./public/images/icons');\n\t\n\t//cut file extension (.png)\n\tfor (var i=0; i < icons.length; i++) {\n\t\ticons[i] = icons[i].slice(0, -4);\n\t}\n\n\tcb(icons);\n}", "function getIcon(mimeType){\n\t//console.log(mimeType)\n\tswitch (mimeType){\n\t//For folder\n\tcase \"application/vnd.google-apps.folder\":\n\t\treturn \"/icon/cheser/24x24/places/folder-documents.png\";\n\t\n\t//For files\n\tcase \"text/plain\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/text-x-generic.png\";\n\tcase \"text/html\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/text-html.png\";\n\tcase \"application/rtf\":\n\tcase \"application/pdf\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/application-pdf.png\";\n\tcase \"application/vnd.google-apps.document\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-document.png\";\n\tcase \"application/vnd.oasis.opendocument.text\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-document.png\";\n\tcase \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-document.png\";\n\tcase \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-spreadsheet.png\";\n\tcase \"application/x-vnd.oasis.opendocument.spreadsheet\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-spreadsheet.png\";\n\tcase \"application/vnd.google-apps.spreadsheet\":\t\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-spreadsheet.png\";\n\tcase \"application/vnd.oasis.opendocument.presentation\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-presentation.png\";\n\tcase \"application/vnd.openxmlformats-officedocument.presentationml.presentation\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-presentation.png\";\n\tcase \"application/vnd.google-apps.presentation\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-presentation.png\";\n\tcase \"image/png\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"image/jpeg\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"image/gif\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"image/svg+xml\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"image/tiff\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"image/bmp\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/image-x-generic.png\";\n\tcase \"application/vnd.google-apps.drawing\":\n\t\treturn \"/icon/cheser/24x24/mimetypes/x-office-drawing.png\";\n\n\tdefault:\n\t\t//other applications\n\t\treturn \"/icon/cheser/24x24/mimetypes/applications-other.png\";\n\t}\t\t\t\t\n}", "static getExtensionMimeType() {\n return [\n {\n \"extension\": \"svg\",\n \"mimeType\": \"image/svg+xml\"\n },\n {\n \"extension\": \"gif\",\n \"mimeType\": \"image/gif\"\n },\n {\n \"extension\": \"jpeg\",\n \"mimeType\": \"image/jpeg\"\n },\n {\n \"extension\": \"png\",\n \"mimeType\": \"image/png\"\n },\n ]\n }", "function googleFavIconUrl(domain) {\n return \"https://www.google.com/s2/favicons?domain=\".concat(domain);\n} // return our best guess for the domain name of a story", "function getIconsList(){\n IconsListsResurce.get({},\n function(response){\n iconsList = response.fruits;\n getImages(response.fruits);\n \n },\n function(response){\n //Manage Errors here\n }\n )\n }", "function getImages(imageDir, callback) {\n var fileType = '.gif',\n files = [], i;\n fs.readdir(imageDir, function (err, list) {\n for (i = 0; i < list.length; i++) {\n if (path.extname(list[i]) === fileType) {\n files.push(list[i]); //store the file name into the array files\n }\n }\n callback(err, files);\n });\n}", "static async getAllFavours() {\n\t\tconst result = await axios.get('/favours/view/all', config);\n\t\tconst favours = result.data.map((favour) => new Favour(favour));\n\t\treturn favours;\n\t}", "async function getFavicon(domain) {\n\n let googleRes = await fetch(`https://care37-cors-anywhere.herokuapp.com/https://www.google.com/s2/favicons?sz=128&domain=${domain}`);\n let img = await googleRes.blob();\n let url = await readFileAsDataURL(img);\n googleFaviconFetchDefaultUrl = await googleFaviconFetchDefaultUrl;\n\n // if the favicon doesn't exist fetch from another domain\n if (url === googleFaviconFetchDefaultUrl) {\n let duckduckgoRes = await fetch(`https://care37-cors-anywhere.herokuapp.com/https://icons.duckduckgo.com/ip3/${domain}.ico`);\n img = await duckduckgoRes.blob();\n url = await readFileAsDataURL(img);\n }\n\n return url;\n}", "function favicons() {\n return gulp.src('src/favicons/**/*')\n .pipe(gulp.dest(PATHS.dist + '/favicons'));\n}", "static async getAll() {\n\t\tconst result = await axios.get('/favour-types/get-all', config);\n\t\tconst favourTypes = result.data.favourTypes;\n\t\treturn favourTypes.map((favourType) => new FavourType({ ...favourType }));\n\t}", "_generateFavIconMarkup(favicons) {\n // Case: TAB list item -- NO favIconUrl: \"\"\n if (favicons.length === 1 && !favicons[0]) {\n //todo:: maybe need to still render empty img?\n // console.log('NO favicon for this tab!');\n return '';\n }\n // Case: COLLECTION list item -- display first 3 favicons(?)\n if (favicons.length > 1) {\n console.log('GETTING FIRST 3 favicons');\n let counter = 0;\n const fav = favicons\n .filter(favicon => {\n if (favicon) counter++;\n return favicon && counter <= 3;\n })\n .map(favicon => {\n // if(favicon)\n return `<img class=\"favicons\" src=\"${favicon}\" alt=\"\">`;\n })\n .join('');\n if (!fav) return '';\n return fav;\n }\n // Case: TAB list item -- YES favIconUrl EXISTS\n // console.log(`TAB FAVICON: <img class=\"favicons\" src=\"${favicons[0]}\" alt=\"\">`);\n return `<img class=\"favicons\" src=\"${favicons[0]}\" alt=\"\">`;\n }", "function importAll(r) {\n var images = [];\n r.keys().map((item) => \n {\n var src = item.replace('./',''); // DRY stuff\n images.push(\n {\n src: src, // E.g. Glasses/glasses1.png\n img: r(item), // The image\n type: src.substr(0,src.indexOf('/')), // e.g. Glasses\n fileName: src.substr(src.indexOf('/')+1,src.length) // E.g. glasses1.png\n }); \n });\n return images;\n}", "function getRandomIcons() {\n let icons = [];\n\n switch (Math.floor(Math.random() * 10 % 5)) {\n case 0:\n icons = [\n \"google\",\n \"meetup\",\n \"evernote\",\n \"pocket\",\n \"dropbox\",\n \"twitter\",\n \"youtube\",\n \"yahoo\"\n ];\n break;\n\n case 1:\n icons = [\n \"acrobat\",\n \"amazon\",\n \"android\",\n \"bitbucket\",\n \"bitcoin\",\n \"appstore\",\n \"wikipedia\",\n \"dribbble\"\n ];\n break;\n case 2:\n icons = [\n \"googleplus\",\n \"pinterest\",\n \"windows\",\n \"yelp\",\n \"spotify\",\n \"skype\",\n \"macstore\",\n \"instagram\"\n ];\n break;\n case 3:\n icons = [\n \"cal\",\n \"call\",\n \"cart\",\n \"guest\",\n \"print\",\n \"pinboard\",\n \"podcast\",\n \"email\"\n ];\n break;\n case 4:\n icons = [\n \"quora\",\n \"reddit\",\n \"googleplay\",\n \"tumblr\",\n \"steam\",\n \"flickr\",\n \"stumbleupon\",\n \"weibo\"\n ];\n break;\n }\n\n return icons;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends sender action via the Send API
function callSenderActionAPI(sender_psid, action) { // Construct the message body let request_body = { "recipient": { "id": sender_psid }, "sender_action": action } // Send the HTTP request to the Messenger Platform request({ "uri": "https://graph.facebook.com/v2.6/me/messages", "qs": { "access_token": process.env.PAGE_ACCESS_TOKEN }, "method": "POST", "json": request_body }, (err, res, body) => { if (!err) { console.log('message sent!') } else { console.error("Unable to send message:" + err); } }); }
[ "sendAction(action) {\n const data = JSON.stringify({\n type: WS_ACTION,\n action\n });\n this.logger.log({\n sender: \"SERVER\",\n playerId: this.playerId,\n data\n });\n this.socket.send(data);\n }", "send() {\n // Disable send button;\n this.okPressed = true;\n\n // Decrypt/generate private key and check it. Returned private key is contained into this.common\n if (!CryptoHelpers.passwordToPrivatekeyClear(this.common, this._Wallet.currentAccount, this._Wallet.algo, true)) {\n this._Alert.invalidPassword();\n // Enable send button\n this.okPressed = false;\n return;\n } else if (!CryptoHelpers.checkAddress(this.common.privateKey, this._Wallet.network, this._Wallet.currentAccount.address)) {\n this._Alert.invalidPassword();\n // Enable send button\n this.okPressed = false;\n return;\n }\n\n // Construct transaction byte array, sign and broadcast it to the network\n var namespacemosaic = this.selectedMosaic.split(\":\");\n this.options = {};\n this.options.message = this.formData.message;\n this._sendMosaic(this.formData.recipient, namespacemosaic[0], namespacemosaic[1], this.formData.amount, this.common, this.options).then((data)=>{\n this._state.go('app.balance');\n },\n (err) => {\n\n });\n }", "async send(amount, destinationAddress, sender) {\n return this.sendWithDetails({\n amount,\n destination: destinationAddress,\n sender,\n });\n }", "send() {\n this._libhoney.sendEvent(this);\n }", "function sendSignal(action, message) {\n var jsonStr = JSON.stringify({\n 'peer': username,\n 'action': action,\n 'message': message,\n });\n webSocket.send(jsonStr);\n}", "function sendAction() {\n if (debouncer) {\n clearTimeout(debouncer);\n }\n debouncer = setTimeout(function() {\n var message = {\n type: 'action',\n data: myself\n }\n if (ws.readyState === ws.OPEN) {\n ws.send(JSON.stringify(message));\n }\n debouncer = undefined;\n }, 5);\n}", "async send(amount, destinationPayID, sender) {\n return this.sendWithDetails({\n amount,\n destination: destinationPayID,\n sender,\n });\n }", "async sendAction(request: TSendActionRequest): Promise<TSendActionResponse> {\n return await this.send(this.sendAction.name, request);\n }", "handleSend() {\n // Send the message\n this.SendMessage();\n }", "function sendSignal(action, message){\n webSocket.send(\n JSON.stringify(\n {\n 'peer': username,\n 'action': action,\n 'message': message,\n }\n )\n )\n}", "function sendMessage(action) {\n let obj = {\n clientName: \"Test Client\",\n action: action,\n id: myId\n };\n socket.send(JSON.stringify(obj));\n}", "handleSend(){\n this.dispatchEvent(new CustomEvent('send'));\n }", "static async sendEtherAction (senderAddress, senderPrivateKey, receiverAddress, sendAmount) {\n let privateKey = Buffer.from(senderPrivateKey, 'hex')\n // Get the neccessary information to create raw transaction\n let nonce = await EtherscanServices.getNounce(senderAddress)\n let gasPrice = await EtherscanServices.getGasPrice()\n // gasPrice *= countPercent\n let gasLimit = await this.getGasLimit(receiverAddress)\n let value = new BigNumber(this.convertBalanceToWei(sendAmount))\n value = '0x' + value.toString(16)\n\n let data = ''\n // Create raw transaction\n gasPrice = parseFloat(gasPrice.toFixed(0))\n let rawTransaction = {\n nonce: nonce,\n gasPrice: '0x' + gasPrice.toString(16),\n gasLimit: '0x' + gasLimit.toString(16),\n to: receiverAddress,\n value: value,\n data: data\n }\n // Create transaction and sign with private key\n var transaction = new EthereumTx(rawTransaction)\n transaction.sign(privateKey)\n\n // Serialize and convert transaction to hex\n let serializedTransaction = transaction.serialize()\n let hexSerializedTransaction = '0x' + serializedTransaction.toString('hex')\n return EtherscanServices.sendRawTransaction(hexSerializedTransaction)\n }", "function send(){\n if (client) {\n client.send(channel, \"Triggering a push notification\");\n };\n}", "send (/*messages*/) {\n\n }", "clickSendButton() {\n this.waitUtil.waitForElementToBeClickable(\n this.btnSend,\n 25000,\n \"Send Button\"\n );\n this.btnSend.click();\n }", "function send(){\n\tvar from = $(USERNAME).val();\n\tvar to = $(TO_USER_SELECT).val();\n\tvar message = $(MESSAGE).val();\n\tsendMessage(from, to, message);\n}", "function SendActivity() {\n\tComponent.call(this);\n}", "function send(){\n if (client) {\n client.send(channel, \"This will trigger a push notification\");\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch stuff from Tumblr
async function doFetch() { options.verbose && console.error("Fetching from Tumblr"); var baseUrl = options.src + "/api/read?num=" + options.number; var blog = { posts: [] }; /** * Let's fetch */ var start = 0; var total = 1; // Will be set to real value after first request while (start < total) { requestUrl = baseUrl + "&start=" + start; var rawResponse; try { options.verbose && console.error("Requesting: %j", requestUrl); rawResponse = await request(requestUrl); } catch (err) { console.error("Got request error: %j", err); process.exit(1); } var jsonResponse; try { jsonResponse = await xml2js(rawResponse); } catch (err) { console.error("XML Parse error: %j", err); process.exit(2); } /** * Update total if needed */ if (total === 1) { total = parseInt(jsonResponse.tumblr.posts[0].$.total); options.verbose && console.error("Total set to ", total); } /** * Update blog title if needed */ if (!blog.title) { blog.title = jsonResponse.tumblr.tumblelog[0].$.title; } /** * Update blog name if needed */ if (!blog.name) { blog.name = jsonResponse.tumblr.tumblelog[0].$.name; } // Go through posts options.verbose && console.error("Going through " + jsonResponse.tumblr.posts[0].post.length + " posts"); for (var postNumber = 0, len = jsonResponse.tumblr.posts[0].post.length; postNumber < len; ++postNumber) { var origPost = jsonResponse.tumblr.posts[0].post[postNumber]; var post = {}; post.tumblrId = origPost.$.id; post.postType = origPost.$.type; post.tumblrUrl = origPost.$.url; post.tumblrSlug = origPost.$.slug; post.tags = origPost.tag blog.posts.push(post); //console.error("Original post: ", JSON.stringify(origPost, null, 2)); } start += options.number; } options.verbose && console.error("Done Fetching from Tumblr"); return blog; }
[ "function loadPosts() {\n let queryurl =\n \"https://api.tumblr.com/v2/tagged?api_key=\" + apikey + \"&tag=\";\n queryurl += encodeURI(tagbox.value);\n let postsxhr = new XMLHttpRequest();\n postsxhr.onload = loadedPosts;\n postsxhr.onerror = erroredPosts;\n postsxhr.open(\"GET\", queryurl);\n postsxhr.send();\n}", "function getFromTumblr(post, memo, topLevelCallback) {\n\t\tfetch.get(post, function(retPost) {\n\t\t\tmemo.tumblrGet++;\n\t\t\t//if it's older than 1 month, it does not need to be updated\n\t\t\tvar postTime = new Date(retPost.timestamp * 1000);\n\t\t\tvar now = new Date();\n\t\t\tvar lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());\n\t\t\t//also if the post has no photo AND no text, don't put it in\n\t\t\tvar nothing = (post.photo === '') && (post.text === '');\n\t\t\t//now put hte post in our DB\n\t\t\tif(postTime > lastMonth && !nothing) {\n\t\t\t\t//make sure the artist gets added to the db\n\t\t\t\tasync.parallel([\n\t\t\t\tfunction(putDBCallback) {\n\t\t\t\t\tdb.put(retPost, memo, function() {\n\t\t\t\t\t\tputDBCallback(null);\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\tfunction(updateReblogsCallback) {\n\t\t\t\t\t//console.log('post added: %d %s', retPost.id, retPost.blog_name);\n\t\t\t\t\tupdateReblogs(retPost, memo, updateReblogsCallback);\n\t\t\t\t}], function(err) {\n\t\t\t\t\tif(!err) {\n\t\t\t\t\t\ttopLevelCallback(null);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttopLevelCallback(null);\n\t\t\t}\n\t\t});\n\t}", "function get(post, callback) {\n\t\tvar id = post.id;\n\t\tvar blog_name = post.blog_name;\n\t\tvar artist = post.artist;\n\t\tvar options = {\n\t\t\thost : 'api.tumblr.com',\n\t\t\tport : 80,\n\t\t\tpath : '/v2/blog/' + blog_name + \".tumblr.com/posts?api_key=\" + keys.tumblrAPIKey + \"&id=\" + id + \"&notes_info=true&reblog_info=true&filter=text\",\n\t\t\tmethod : 'GET',\n\t\t};\t\n\t\tmakeRequest(options, function(response) {\n\t\t\t//parse the response\n\t\t\tvar post = parsePost(response.posts[0], artist);\n\t\t\t//call the callback if it exists\n\t\t\tcallback(post);\n\t\t});\n\t}", "function scrape_tumblr() {\r\n\t// Tumblr's goals are basically like Inkbunny's:\r\n\t//\t\t- On a generic post or /image/ page with a single image: redirect to that image in the highest resolution available\r\n\t//\t\t- On a multi-image post: do nothing, since photosets already are or link to their highest-resolution versions\r\n\tif( address_bar_contains('/image/') ) { \t\t// on centered-image pages\r\n\t\textract_image_url_after( 'id=\"content-image\"', 'http://' );\t\t// get conveniently-labeled id=\"image\" image\r\n\t}\t\t// The above will handle /post/ to /image/ URL conversions in a sort of double-redirect, letting Tumblr do the hard work of finding the highest-res version of an image\r\n\telse if( address_bar_contains( '/post/' ) ) {\t\t// on generic Tumblr posts\r\n\t\timage_url = window.location.href.replace( '/post/', '/image/' ); \r\n\t\tvar comment_check_index = image_url.lastIndexOf( '/' );\t\t// if the /post/ contained text, it gets appended after the post/image number and screws up the URL...\r\n\t\tif( image_url.substring( comment_check_index - 6, comment_check_index ) !== '/image' ) {\t\t// ... so if the last '/' isn't the latter in '/image/' then we dump everything after that '/'...\r\n\t\t\timage_url = image_url.substring( 0, comment_check_index );\t\t// ... by taking the substring up to the index of that final '/'.\r\n\t\t}\r\n\t\t\t// If the theme is kind enough to use proper Open Graph tags, let's use those instead for a single redirect:\r\n\t\tvar post_image_url = image_url;\t\t// store the double-redirect URL just in case\r\n\t\textract_image_url_after( 'property=\"og:image\"', 'http' );\r\n\t\tif( image_url.indexOf( '_1280.' ) == -1 ) { image_url = post_image_url; }\t\t// if the Open Graph isn't _1280 (and thus might be misdefined at low-res), just double-redirect instead \r\n\t}\t\t// this might also trigger on images with no _size in the URL, but I think those are all tumblr-feed:entry items anyway. hardly matters. /image/ would still work. \r\n\r\n\t\t// Now that image_url is defined, we can blank it out if we don't want to redirect. Much easier than piling on if( || && || )-style logic. \r\n\tif( address_bar_contains( '_iframe/' ) ) { image_url = ''; }\t\t// Do not redirect from photoset iframe pages, since they trigger their own instance of this script\r\n\tif( html_dump.indexOf( 'class=\"html_photoset\"' ) !== -1 ) { image_url = ''; }\t\t// Do not redirect from photosets (because photoset images always are or link to highest-res versions)\r\n\tif( html_dump.indexOf( 'content=\"tumblr-feed:entry\"' ) !== -1 ) { image_url = ''; }\t// Do not redirect if Open Graph indicates a text-only post (as opposed to tumblr-feed:photo). \r\n\tif( html_dump.indexOf( 'content=\"tumblr-feed:photoset\"\"' ) !== -1 ) { image_url = ''; }\t// Do not redirect if Open Graph indicates a text-only post (as opposed to tumblr-feed:photo). \r\n}", "function loadPosts () {\n\n var key = \"api_key=iSCTzggSVfQGj4CkKfEmBSShk0T7J0qtj6dBMwb4b1ixavvS1h\";\n var api = \"https://api.tumblr.com/v2/blog/sergeymisharin.tumblr.com/\";\n\n $.getJSON(api + \"posts/text?callback=?&filter=text&limit=3&offset=0&\" + key,function(data) {\n $.each(data.response.posts, function(i, item) {\n var content = item.body;\n var divWithContent = '<div class=\"col-sm-6\">' + content + '</div>';\n $(\".space_weather\").append(divWithContent);\n });\n\n });\n }", "function getPosts1() {\n fetch(baseLink + \"/mystorypage?_embed\")\n .then(res => res.json())\n .then(showPosts1)\n}", "function loadMorePosts() {\n //clear animations completely on any already-loaded post\n document.querySelectorAll(\".post\").forEach(function(post) {\n post.style[\"animation-duration\"] = \"0s\";\n post.style[\"animation-delay\"] = \"0s\";\n //console.log(\"de-animated a post\");\n });\n let queryurl =\n \"https://api.tumblr.com/v2/tagged?api_key=\"+ apikey + \"&tag=\";\n queryurl += encodeURI(tagbox.value);\n queryurl += \"&before=\" + pagetimestamp;\n //console.log(queryurl);\n let postsxhr = new XMLHttpRequest();\n postsxhr.onload = loadedPosts;\n postsxhr.onerror = erroredPosts;\n postsxhr.open(\"GET\", queryurl);\n postsxhr.send();\n}", "function injectTumblr(data) {\n\tvar count = 0;\n\t$.each(data.response, function(i, post) {\n\t\tif (post.type == \"photo\") {\n\t\t\t$.each(post.photos, function(j, size) {\t\n\t\t\t\t// Code to get the icon-sized pictures and places them in the gallery\n\t\t\t\t$.each(size.alt_sizes, function(k, icon) {\n\t\t\t\t\tif (icon.width == 75) {\t\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t$iconpic = $('<a>', {'href' : icon.url});\n\t\t\t\t\t\t$('<img>', {'src' : icon.url}).appendTo($iconpic);\n\t\t\t\t\t\t$iconpic.appendTo('#gallery');\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t// Adds all the original-sized images to a list of images so we can load and navigate these images\n\t\t\t\t\t\tIMAGES[IMAGES.length] = size.original_size.url;\n\t\t\t\t\t\tvar length = IMAGES.length - 1;\n\t\t\t\t\t\t// Calls the function to allow the original-sized image to pop up\n\t\t\t\t\t\t$iconpic.click(function(event) {\n\t\t\t\t\t\t\tenlarge(event, length);\n\t\t\t\t\t\t\tsetNavigation(length);\n\t\t\t\t\t\t});\t\n\t\t\t\t\t} \t\n\t\t\t\t});\t\t\n\t\t\t});\t\n\t\t}\n\t\tTIMESTAMP = post.timestamp;\n\t});\n\tif (count == 0) {\n\t\t$('#centerMessages').show();\n\t} else {\n\t\t$('#centerMessages').hide();\n\t}\n\n}", "function retrieveAPI(url) {\n $.getScript(url, function() {\n let i = 0;\n while (bool && i < 30) {\n try {\n let post = tumblr_api_read.posts[i];\n\t\tpostLength = tumblr_api_read.posts.length;\n let audioEmbed = post[\"audio-embed\"];\n let track = post[\"id3-title\"];\n let artist = post[\"id3-artist\"];\n \tlet postURL = decodeURIComponent(post[\"url\"]);\n let audiofile = audioEmbed.substring(audioEmbed.indexOf(\"src\") + 5, audioEmbed.indexOf('\" frameborder'));\n let fileType = getFileType(audiofile);\n if (fileType === 0) {\n processTumblrAudio(audiofile);\n appendTracks(track, artist, \"tumblr\");\n postURLs[count] = postURL;\n }\n \telse if (fileType === 1) {\n \t count++;\n \t audioFiles[count] = decodeURIComponent(audiofile);\n \t appendTracks(track, artist, \"tumblr\");\n\t\t postURLs[count] = postURL;\n \t}\n else if(fileType === 2) {\n processSCAudio(audiofile);\n appendTracks(track, artist, \"soundcloud\");\n postURLs[count] = postURL;\n }\n else if (fileType === 3) {\n\t\t count++;\n\t \t processBCAudio(audiofile, count);\n\t\t appendTracks(track, artist, \"bandcamp\");\n\t\t audioFiles[count] = \"./audio/emptysong.mp3\";\n\t\t postURLs[count] = postURL;\n }\n\t\telse if (fileType === 4) {\n\t\t count++;\n\t\t processSPAudio(audiofile, count);\n\t\t appendTracks(track, artist, \"spotify\");\n\t\t audioFiles[count] = \"./audio/emptysong.mp3\";\n\t\t postURLs[count] = postURL;\n\t\t}\n else {\n postsEnd++;\n }\n }\n catch(e) {\n console.log(e);\n i++;\n }\n\t\ti++;\n }\n console.log(count + \" files processed.\");\n }).done(function() {\n\tnumOfSongs = audioFiles.length;\n\t\n\tif (postsEnd <= postsTotal && (postLength + postsEnd) > 50) {\n\t $(\"#tracks\").append(\"<div id='loadmore' class='lin' onClick='boombox.loadMore()'>Load more</div>\");\n\t}\n\t \n\tconsole.log(\"Setting cache and filter...\");\n\t$(\"#tracks\").prepend(trackCache);\n\ttrackCache = $(\"#tracks .tune\").detach();\n\tfilter();\n\n });\n}", "async function getExploreArtist1() {\n let response = await fetch(\"http://wordpress.oscho.dk//wp-json/wp/v2/posts?_embed&categories=28\");\n let data = await response.json();\n console.log(data)\n\n appendExploreArtist1(data);\n //showLoader(false);\n }", "function getPosts() {\n\tvar snippet = {\n\t\tquery : {},\n\t\tfields: \"title,category,thumbnail\"\n\t}\n\t// for unpublished\n\t// snippet.query = {published: false, nextKey: '-K_W8zLX65ktmaKwf1Yx'}\n\n\trimer.post.find(snippet, function(error, value) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t}\n\t\telse {\n\t\t\tconsole.log(value)\n\t\t}\n\t})\n}", "function displayCurrentTumblr() {\n currentVia = null;\n currentTumblr.viewed = true;\n $(\"#explorerTitle\").html(createTagTumblrLink(currentTumblr.id) + \" <a href='\" + currentTumblr.url + \"' target='_blank'>\" + currentTumblr.name + \"</a>\").slideDown();\n bindTagTumblrLink(currentTumblr.id);\n loadingStatus = 0;\n for (var i = 0; i < Math.min(25, currentTumblr.posts.length); i++) {\n loadingStatus++;\n addCurrentTumblrPost(currentTumblr.posts[i]);\n }\n}", "function extractTumblrMedia (body) {\n var media = [];\n while (/src=\"(http:\\/\\/www\\.tumblr\\.com[^\"]+)\"/.test(body)) {\n media.push(RegExp.$1);\n }\n return media;\n }", "function getTagPhotos (tagName){\r\n\r\n\tfetch('https://api.tumblr.com/v2/tagged?tag='+tagName+'&api_key=hdBrTPhpjUgfZIOUSixU1P3ofgmMZlwsGNaDmxelgskJwt4FRX')\r\n\t// convert the raw response into a JSON\r\n\t\t.then(function(response){\r\n\t\t\treturn response.json();\r\n\t\t})\r\n\r\n\t\t.then(function(result){\r\n\r\n\t\t\tconst items = result.response;\r\n\r\n\r\n\t\t\tfor (i=0; i<items.length; i++){\r\n\t\t\t\tconst item = items[i];\r\n\r\n\t\t\t\tif (item.photos != undefined){\r\n\r\n\t\t\t\t\tconst altSizes = item.photos[0].alt_sizes;\r\n\r\n\t\t\t\t\tconst imageSrc = altSizes[altSizes.length - 4].url;\r\n\t\t\t\t\t\r\n\t\t\t\t\tconst li = document.createElement('li');\r\n\t\t\t\t\t\r\n\t\t\t\t\tconst image = document.createElement('img');\r\n\r\n\t\t\t\t\t// same as setting attribute (eg. src) to image\r\n\t\t\t\t\t// image.setAttribute('src', imageSrc);\r\n\t\t\t\t\timage.src = imageSrc;\r\n\r\n\t\t\t\t\tli.appendChild(image);\r\n\r\n\t\t\t\t\tphotoList.appendChild(li);\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\t.catch (function(err){\r\n\t\t\tconsole.log(err);\r\n\t\t\twindow.alert('The Tumblr API is not working. Try again later');\r\n\t\t})\r\n\r\n}", "function wpREST(){\n var blogTitle1 = document.getElementById('blogTitle1'),\n blogTitle2 = document.getElementById('blogTitle2'),\n blogLink1 = document.getElementById('blogLink1'),\n blogLink2 = document.getElementById('blogLink2'),\n blogImage1 = document.getElementById('blogImage1'),\n blogImage2 = document.getElementById('blogImage2'),\n wpURL = 'https://blog.yorklighting.com/wp-json/wp/v2/posts';\n //Fetches Title and URL\n fetch(wpURL)\n .then((response) => response.json())\n\n .then(function(data){\n\n blogTitle1.innerHTML = data[0].title.rendered\n blogTitle2.innerHTML = data[1].title.rendered\n blogLink1.href = data[0].link\n blogLink2.href = data[1].link\n blogImage1.src = data[0].fimg_url\n blogImage2.src = data[1].fimg_url\n });\n\n}", "function getTumblrBlogs(div, index){\r\n\t\t(async function () {\r\n\t\t\t// Get user temporary token\r\n\t\t\tvar idToken = await USER.getIdToken();\r\n\t\t\t// URL server\r\n\t\t\tconst url = URL_SERVER + '/getTumblrApi_userInfo?index=' + index + '&idToken=' + idToken;\r\n\t\t\t// Request blogs list to server\r\n\t\t\t$.getJSON(url, function(result){\r\n\t\t\t\tvar blogs = result.blogs;\r\n\t\t\t\t// Display list\r\n\t\t\t\tblogs.forEach((l, i) => {\r\n\t\t\t\t\tlet input = document.createElement(\"input\");\r\n\t\t\t\t\tlet label = document.createElement(\"label\");\r\n\t\t\t\t\tlet d = document.createElement(\"div\");\r\n\r\n\t\t\t\t\tinput.setAttribute(\"id\", l.uuid);\r\n\t\t\t\t\tinput.setAttribute(\"type\", \"checkbox\");\r\n\t\t\t\t\tlabel.innerHTML = l.name + \" (tumblr)\";\r\n\t\t\t\t\tlabel.setAttribute(\"for\", i);\r\n\t\t\t\t\td.append(input);\r\n\t\t\t\t\td.append(label);\r\n\t\t\t\t\tdiv.append(d);\r\n\t\t\t\t});\r\n\t\t \t});\r\n\t\t})();\r\n\t}", "function tumblrPage(args, res){\n\tfs.readFile(thefile, function(err, data){\n\t\ttry{\n\t\t\tres.send(hogan.compile( tumblrToMustache( data + '' ) ).render(args.merge({\n\t\t\t\t\"title\" : tumblrCache.response.blog.title,\n\t\t\t\t\"Description\" : tumblrCache.response.blog.description,\n\t\t\t\t\"ask_enabled\" : appconfig['ask'] || tumblrCache.response.blog.ask,\n\t\t\t\t\"submission_enabled\" : appconfig['submission_enabled'],\n\t\t\t\t\"has_pages\" : (appconfig.pages.length != 0),\n\t\t\t\t\"pages\" : appconfig.pages\n\t\t\t})) + Tinjection);\n\t\t} catch(e){ console.log(e); }\n\t});\n}", "async fetchFrontpageText() {\n let response = await fetch(\"https://www.xn--caminofrsherred-dub.dk/wordpress/wp-json/wp/v2/posts?_embed&categories=16\")\n this.frontpageText = await response.json();\n console.log('fetcher', this.frontpageText)\n this.appendFrontpageInfo()\n }", "function getImg() {\n $http({\n method: 'GET',\n url: 'http://api.tumblr.com/v2/blog/passport-life.tumblr.com/posts/photo?api_key=SOiMe7M47zoEcQYKtnuzjO6Kcq2M1dAZESAQ9ipStoqvpMMYpT&notes_info=true'\n }).then(whenSuccess, whenError);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Shows website in outer tab.
function showWebsite(p_name, p_url) { if (v_connTabControl) $('#modal_about').modal('hide'); v_connTabControl.tag.createWebsiteOuterTab(p_name,p_url); }
[ "function showWebsite(p_name, p_url) {\n\n\tif (v_connTabControl)\n\t\thideAbout();\n\t\tv_connTabControl.tag.createWebsiteOuterTab(p_name,p_url);\n\n}", "function show_tab_browse() {\n // console.log(\"show_tab_browse\");\n fill_browse_experiments(experiment_metadata);\n }", "function openHnTab(tab) {\n var data = allData[tab.id];\n if (data && data.hnUrl) {\n window.open(data.hnUrl);\n } else {\n window.open('https://news.ycombinator.com/submit');\n }\n}", "function showMyAuctionTab()\r\n{\r\n\r\n\tvar open=getTabIndexByTitle('My Auction');\r\n\tif (open<0)// if the tab is not open yet\r\n\t{\t\r\n\t\tvar aTab= createMyAuctionTab('tabPanel','My Auction', true);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tshowTab('tabPanel',open[1]);\r\n\t}\r\n}", "function openSomTab() {\r\n\tvar _url = data.url(\"som/som.html\");\r\n\ttabs.open({ url: _url });\r\n}", "function show(details, url, startEvt, err) {\n if (details.type != \"main_frame\") {\n return\n }\n tabs[details.tabId] = tabInfo(url, startEvt, err)\n\n if (err != null) {\n browser.pageAction.setIcon({\n path: {32: \"assets/small_error.png\"},\n tabId: details.tabId,\n })\n }\n browser.pageAction.show(details.tabId)\n}", "function website() {\n\twindow.open(\"https://restorationtrust.org.uk\");\n}", "function openElpha(){\n window.open(\"https://elpha.com/\", \"_blank\");\n }", "function openTab() {\n var dashboard = getSelectedDashboard();\n var url = (dashboard == false) ? '/options.html' : HOME_URL + '/dashboard/' + dashboard.name;\n browser.tabs.query({currentWindow: true}, function(tabs) {\n var founded = false;\n for (i = 0; i < tabs.length; i++) {\n var tab = tabs[i];\n if (!founded && tab.url.match(HOME_URL + '/([a-z]{2}$|signin|signup|dashboard/' + (dashboard.name || '')+ ')')) {\n founded = true;\n var data = {active: true };\n if (!tab.url.match('^' + url)) {\n data.url = url;\n }\n browser.tabs.update(tab.id, data);\n }\n }\n if (!founded) browser.tabs.create({active: true, url: url});\n });\n}", "function openMyPage() {\n console.log(\"injecting\");\n browser.tabs.create({\n \"url\": \"/sony-tv.html\"\n });\n}", "function showTab() {\n var url = window.location.href;\n if(url.indexOf('/get_started/why_mxnet') != -1) return;\n for(var i = 0; i < TITLE.length; ++i) {\n if(url.indexOf(TITLE[i]) != -1) {\n var tab = $($('#main-nav').children().eq(i));\n if(!tab.is('a')) tab = tab.find('a').first();\n tab.css('border-bottom', '3px solid');\n }\n }\n}", "function showMainPage() {\n\tshowPage(pages.main);\n}", "function openWebsite() {\n window.open('https://www.santaluciapizza.com/', '1563527672085',\n 'width=700,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0');\n}", "function showReasonerConfiguration() {\t \n gBrowser.selectedTab = gBrowser.addTab(\"chrome://reasonerExtension/content/HORUSHtml/index.html\");\n }", "function openGoodWebsite() {\n var goodWebsite = window.open(\"https://aluminumfencesdirect.net\", \"_blank\");\n}", "showWebpage(url) {\n electron.shell.openExternal(url)\n }", "function visitMoodle() {\n chrome.tabs.create({\n \"url\": \"http://online.mrt.ac.lk/my/\",\n \"selected\": true\n });\n}", "function openUrlInCurrentTab(url){\r\n BRW_openUrlInCurrentTab(redirectModification(url));\r\n }", "function openAboutPage() {\r\n\tif(hobsonsPage === true){\r\n\t\tchrome.tabs.create({\"url\": \"/about.html\" });\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grab the URL for a machine by id.
function get_machine_url(db, ts, machineID) { "use strict"; return [lnt_url_base, "db_" + db, "v4", ts, "machine", machineID].join('/'); }
[ "function getUrlFromId(id, callback){\n\t//Get the url model.\n\tvar urls = require(\"./url.model\");\n\turls.find({id: id}, function(err,url){\n\t\tif(err)\n\t\t\tconsole.log(err);\n\t\telse{\n\t\t\treturn callback(url[0].url);\n\t\t}\n\t});\n}", "function getMachineInfo(machineID) {\n return fetch(`http://localhost:3001/machineinfo/${machineID}`)\n}", "idFromUrl() {\n let idFromUrl = null;\n let matches = browser.getUrl().match(uuidRegexp());\n if (matches) {\n idFromUrl = matches[0];\n }\n return idFromUrl;\n }", "function getMachine(username){\n return fetch(`http://localhost:3001/machineid/${username}`)\n}", "function url(id){\n\t\tif(id)\n\t\t\treturn thingbroker + \"things?thingId=\" + id;\n\t\treturn thingbroker + \"things\";\n\t}", "static getSpecificRestaurantUrl(id) {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants/${id}`;\r\n }", "get id() { return this.siteURL; }", "function getMachine(id) {\n if (id.charAt(0) == 'R') {\n for (var i = 0; i < robots.length; i++) {\n if (robots[i].id == id) {\n return robots[i];\n }\n }\n\n console.log('Robot with id ' + id + ' not found!!');\n\n } else {\n for (var i = 0; i < cars.length; i++) {\n if (cars[i].id == id) {\n return cars[i];\n }\n }\n\n console.log('Car with id ' + id + ' not found!!');\n }\n}", "workitemWithId (baseUrl,username,spacename,id){\n browser.get(baseUrl + username + \"/\" + spacename +\"/plan/detail/\" +id);\n }", "static getSpecificRestaurantUrl(id) {\n const port = DBHelper.SERVER_PORT;\n return `http://localhost:${port}/restaurants/${id}`;\n }", "function getUrl(id) {\n \n return newUrl = id === \"0\" ? GLOBAL_CASES_URL : (COUNTRIES_URL + \"/\" + id)\n\n }", "async getLaunch(id) {\r\n return this.get(`launches/${id}`);\r\n }", "function getSpecificRecipeURL(recipeId){\n var url = \"http://food2fork.com/api/get?key=0e799db0a42173dfbfd14aad4560b1bc\";\n url += \"&rId=\" + recipeId;\n return url;\n}", "function getImdbUrl(imdbID) {\n let url = \"https://www.imdb.com/title/\";\n url += imdbID;\n return new URL(url);\n}", "function getURL(path, GUID, callback){\r\n dropboxClient.authenticate(function (error, client){\r\n if (error) { throw error; };\r\n client.makeUrl(path, null, function (error, publicURL){\r\n return callback(publicURL.url);\r\n });\r\n });\r\n }", "function getLink(id) {\r\n\tvar regex = new RegExp(\" ~ \" + id + \", ([^~]+), ([^~]+) ~ \");\r\n\tif (m = regex.exec(customEngines)) {\r\n\t\tvar e = new engine(m[1],'',m[2]);\r\n\t\treturn e.completeLink();\r\n\t}\r\n\tif (engines[id]) { return engines[id].completeLink(); }\r\n\treturn '';\r\n}", "createImdbUrl(id) {\n return `http://www.imdb.com/title/${id}`;\n }", "function load(req, res, next, id) {\n Machine.get(id)\n .then((machine) => {\n req.machine = machine; // eslint-disable-line no-param-reassign\n return next();\n })\n .catch(e => next(e));\n}", "function build_url(env_id, vm_id) {\n var endpoint = `/configurations/${env_id}/vms/${vm_id}`;\n return process.env.SKYTAP_HOSTNAME.concat(endpoint);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new event specified by restaurant, party size, and time
"events.createNewEvent"( business, sizeLimit, appTimeObj, displayDate, displayTime ) { check(displayDate, String); check(displayTime, String); if (Meteor.isServer) { if (!Meteor.userId()) { throw new Meteor.Error("not-authorized"); } Events.insert({ createAt: Date.now(), owner: this.userId, status: "ongoing", isFull: false, member: [ { id: this.userId, vote: -1 } ], appTime: appTimeObj, displayDate: displayDate, displayTime: displayTime, restaurantId: business.id, restaurantUrl: business.url, restaurantName: business.name, peopleLimit: sizeLimit }); } }
[ "function createEvent() {\n var calendarId = 'primary';\n var start = getRelativeDate(1, 12);\n var end = getRelativeDate(1, 13);\n var event = {\n summary: 'Lunch Meeting',\n location: 'The Deli',\n description: 'To discuss our plans for the presentation next week.',\n start: {\n dateTime: start.toISOString()\n },\n end: {\n dateTime: end.toISOString()\n },\n attendees: [\n {email: 'alice@example.com'},\n {email: 'bob@example.com'}\n ],\n // Red background. Use Calendar.Colors.get() for the full list.\n colorId: 11\n };\n event = Calendar.Events.insert(event, calendarId);\n Logger.log('Event ID: ' + event.id);\n}", "function createEvent() {\n var calendarId = 'primary';\n var start = getRelativeDate(1, 12);\n var end = getRelativeDate(1, 13);\n var event = {\n summary: 'Lunch Meeting',\n location: 'The Deli',\n description: 'To discuss our plans for the presentation next week.',\n start: {\n dateTime: start.toISOString()\n },\n end: {\n dateTime: end.toISOString()\n },\n attendees: [\n {email: 'alice@example.com'},\n {email: 'bob@example.com'}\n ],\n // Red background. Use Calendar.Colors.get() for the full list.\n colorId: 11\n };\n event = Calendar.Events.insert(event, calendarId);\n Logger.log('Event ID: ' + event.getId());\n}", "function place(grinderobj, newevent, time) {\n let found = grinderobj.events.findIndex( (event) =>\n event.time == time);\n if( found < 0) {\n grinderobj.events.push({\n \"time\": time,\n \"ons\": [],\n \"offs\": [],\n \"pitchbends\": []\n });\n found = grinderobj.events.length - 1;\n };\n switch( newevent.type) {\n case \"on\": { grinderobj.events[found].ons.push(newevent); break; }\n case \"off\": { grinderobj.events[found].offs.push(newevent); break; }\n case \"pitchbend\": { grinderobj.events[found].pitchbends.push(newevent); }\n }\n}", "function createEvent(args) {\n //verify user input\n if(!args.name || !args.capacity || !args.startDate || !args.endDate)\n return \"Missing requiered input parameters\"\n else if(typeof(args.name) == \"string\" || typeof(args.capacity) == \"number\" || typeof(args.startDate) == \"number\" || typeof(args.endDate) == \"number\")\n return \"Input parameters are not of the correct datatypes\";\n \n //auto generate ID\n let id = events[events.length-1].id + 1;\n let event = {\n id: id,\n name: args.name,\n description: (args.description == null) ? \"\" : args.description,\n location: (args.location == null) ? \"\" : args.location,\n capacity: args.capacity,\n remaining: args.capacity,\n startDate: new Date(parseInt(args.startDate)),\n endDate: new Date(parseInt(args.endDate)),\n bookings: []\n }\n events.push(event);\n return event;\n}", "function createOrder() {\n let newOrder = {\n storeName: storName,\n orderId: faker.random.uuid(),\n customerName: faker.name.findName(),\n address: faker.address.streetAddress()\n }\n console.log('*******************New Order*************************');\n setTimeout(createOrder, 5000);\n myEvent.emit('pickup', newOrder)\n}", "function insertBaseEvents(eventDate) {\n\t\tvar monthStartPartyDate = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), 1, 17, 0 ,0 ,0);\n\t\tvar monthStartPartyDateEnd = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), 1, 21, 0 ,0 ,0);\n\t\tvar monthStartPartyDesc = \"It's the start of a new month, come \" +\n\t\t\t\"celebrate with us at Spice Girls!\";\n\n\t\tvar midMonthPartyDate = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), eventDate.getDaysInMonth()/2, 13, 0, 0, 0);\n\t\tvar midMonthPartyDateEnd = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), eventDate.getDaysInMonth()/2, 17, 0, 0, 0);\n\t\tvar midMonthPartyDesc = \"We're halfway through the month! Join us for\" + \n\t\t\t\" our mid month party at Spice Girls!\";\n\n\t\tvar monthEndPartyDate = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), eventDate.getDaysInMonth(), 15, 0, 0, 0);\n\t\tvar monthEndPartyDateEnd = new Date(eventDate.getFullYear(), \n\t\t\teventDate.getMonth(), eventDate.getDaysInMonth(), 19, 0, 0, 0);\n\t\tvar monthEndPartyDesc = \"The end of the month has come but that \" + \n\t\t\t\"doesn't stop the party here at Spice Girls!\";\n\n\t\tvar monthStartParty = new RestaurantEvent(\"Start of the Month Party\", \n\t\t\tmonthStartPartyDate, monthStartPartyDateEnd, monthStartPartyDesc);\n\t\tvar midMonthParty = new RestaurantEvent(\"Mid Month Party\", \n\t\t\tmidMonthPartyDate, midMonthPartyDateEnd, midMonthPartyDesc);\n\t\tvar monthEndParty = new RestaurantEvent(\"Month End Party\", \n\t\t\tmonthEndPartyDate, monthEndPartyDateEnd, monthEndPartyDesc);\n\n\t\tinputEvent(monthStartParty);\n\t\tinputEvent(midMonthParty);\n\t\tinputEvent(monthEndParty);\n\t}", "function addNewEvent_Room(title, name, eventstart, eventend, location, classroom, professor, color, isOnline, eventsArray) {\r\n var timedEvents = [];\r\n //var numOnline = 0;\r\n eventsArray.forEach(function(event, i){\r\n if (!event.online){\r\n timedEvents.push(event);\r\n }\r\n });\r\n var minCourseTime = getMinTime(timedEvents, 0);\r\n var minHour = moment(minCourseTime, 'hh:mm:ss').hour();\r\n if (!isOnline){\r\n eventsArray.push({\r\n title: title,\r\n name: name,\r\n start: formatTime_fullCalendar(eventstart),\r\n end: formatTime_fullCalendar(eventend),\r\n color: color,\r\n location: location,\r\n classroom: classroom,\r\n professor: professor,\r\n online: isOnline\r\n });\r\n }\r\n}", "function createEventBlock(eventName, eventDate, creatorName, slotsRemaining, eventTime, eventLocation)\n{\n\t//console.log(eventDate);\n\tvar titleContainer = $('<div></div>');\n\ttitleContainer.addClass(\"titleContainer\");\n\n\tvar newEvent = $('<div></div>');\n\n\tvar newEventName = $('<div><text></text></div>');\n\tvar eventNameText = eventName;\n\n\t//var newEventIcon = $('<div><img src=\"./icon.png\"></img></div>');\n\tvar newEventIcon = $('<div><img src=\"MyEventBoardLogos/MEB_logo-04.png\"></img></div>');\n\n\tvar newEventCreator = $('<div><text></text></div>');\n\tvar creatorText = creatorName;\n\n\tvar timeOfEvent = $('<text></text>');\n\tvar locationOfEvent = $('<text></text>');\n\n\tvar newEventAvailSlot = $('<div><text></text></div>');\n\tvar slotsText = \"Slots: \";\n\tslotsText = slotsText + slotsRemaining + \" remaining\";\n\n\tnewEventName.text(eventNameText);\n\tnewEventName.addClass(\"eventBlockName\");\n\tnewEventName.addClass(\"Container\");\n\n\tnewEventIcon.addClass(\"eventIcon\");\n\n\n\tnewEventCreator.text(creatorText);\n\tnewEventCreator.addClass(\"eventBlockCreator\");\n\tnewEventCreator.addClass(\"Container\");\n\n\tlocationOfEvent.text(eventLocation);\n\tlocationOfEvent.addClass(\"eventBlockSpace\");\n\tlocationOfEvent.addClass(\"Container\");\n\t\n\ttimeOfEvent.text(eventTime);\n\ttimeOfEvent.addClass(\"eventBlockSpace\");\n\ttimeOfEvent.addClass(\"Container\");\n\n\tvar eventInfo = $('<div></div>');\n\teventInfo.append(locationOfEvent);\n\teventInfo.append('<br>');\n\teventInfo.append(timeOfEvent);\n\teventInfo.addClass(\"container infoHolder\");\n\t\n\t//newEventAvailSlot.text(slotsText);\n\t//newEventAvailSlot.addClass(\"eventBlockSpace\");\n\n\ttitleContainer.append(newEventName);\n\ttitleContainer.append(newEventIcon);\n\t//newEvent.append(newEventName);\n\t//newEvent.append(newEventIcon);\n\tnewEvent.append(titleContainer);\n\tnewEvent.append(newEventCreator);\n\tnewEvent.append(eventInfo);\n\t//newEvent.append(newEventAvailSlot);\n\n\n\tnewEvent.addClass(\"eventBlock\");\n\t\n\t\n\tvar date = new Date();\n\tvar todayTimeStamp = getCurrentTime();\n\t\n\tif (checkTimeIfLessThanToday(eventTime, todayTimeStamp) == true && getDate(date) === eventDate) {\n\t\tnewEvent.addClass(\"finishedEvent\"); // Make reservations that are past transparent.\n\t}\n\t\n\treturn newEvent;\n}", "function createEvent(req, res){\n var newActivity = new db.Activity({\n name: req.body.activityname\n });\n\n var newEvent = new db.Event({\n name: req.body.name,\n date: req.body.date,\n votingAllowed: req.body.votingAllowed,\n activity: newActivity\n });\n\n newEvent.save(function handleDBSave(err, data){\n if (err){\n console.log('handleDBSave err: ', err);\n return res.status(400).send({error: err});\n }\n res.redirect('/events/' + data._id);\n });\n}", "function constructEvent(type){\r\n var length=tw.local.events.data.listLength;\r\n tw.local.events.data[length] = new tw.object.Data();\r\n \r\n tw.local.events.data[length].customerEmailEventType=getCustomerEmailEventType();\r\n \r\n if(type && type.search('(CUSEML)$')!=-1){\r\n //Place customerEmailEventType if its ends with EML\r\n \t tw.local.events.data[length].customerEmailEventType = type;\r\n }else if(type && type.search('(EML)$') != -1 ){\r\n //Place partnerEmailEventType if its ends with EML\r\n tw.local.events.data[length].partnerEmailEventType=type;\r\n }else{\r\n tw.local.events.data[length].eventType=type; \r\n }\r\n \r\n tw.local.events.data[length].orderId=tw.local.order.header.orderId;\r\n \r\n if(tw.local.lineItemRequired)\r\n tw.local.events.data[length].orderLineId=tw.local.order.header.lineItemId; \r\n PLogInfo(\"constructEvent()-post\"+tw.local.events); \r\n}", "_putToFoodTray(item, quantity, time) {\n\n let foodItem = new Item(item.id, item.name, true, 0);\n for(let x = 0 ; x < quantity ; x++) {\n let newItem = Object.assign(new Item(), foodItem);\n //set it to done\n newItem.done();\n //and set the time\n newItem.time = time;\n //also set the time\n this._foodTray.add(newItem);\n }\n }", "function event_add_event()\n{\n\tvar descr = L_mymodel.get(\"event_description\");\n\tvar type = L_mymodel.get(\"event_type\");\n\tvar mydate = L_mymodel.get(\"date\");\n\tmydate = dd_mname_yyyy_to_mysql(mydate); \n\tvar mytime = L_mymodel.get(\"time\");\t\n\tvar the_datetime = mydate.substr(0,10) + \" \" + mytime;\n\t\n\tadd_event ( the_datetime, G_selected_team, type, descr)\n\tprocess_events_queue (events_cb);\n}", "async createHouse(player, location, interiorId) {\n const name = player.name + '\\'s house';\n const data = await server.database.query(\n CREATE_HOUSE_QUERY, location.id, player.account.userId, interiorId, name);\n\n return {\n id: data.insertId,\n name: name,\n\n ownerId: player.account.userId,\n ownerGangId: player.gangId,\n ownerName: player.name,\n\n purchaseTime: Math.floor(Date.now() / 1000),\n\n interiorId: interiorId,\n\n access: HouseSettings.ACCESS_DEFAULT,\n spawnPoint: false,\n welcomeMessage: '',\n streamUrl: '',\n markerColor: 'yellow',\n\n features: new Map(),\n vehicles: []\n };\n }", "function makeCampaign(restaurant, deliveryTime){\n \n // console.log(restaurant.waitTime);\n // console.log(restaurant);\n var endTime = new Date(deliveryTime.getTime() - restaurant.waitTime * 60*1000);\n // console.log(endTime);\n var campaign = { restaurant: restaurant._id, \n currentStatus: \"active\",\n endTime: endTime,\n deliveryTime: deliveryTime,\n \tbalance: 0} ;\n\n return campaign;\n}", "function ParseEventCreate(owner, title, location, time, startTimeInMilliseconds, endTimeInMilliseconds, visibility, description, errorObject, destID, displayFunction) {\n var UserEvent = Parse.Object.extend(\"UserEvent\");\n var userEvent = new UserEvent();\n\n userEvent.set(\"owner\",owner);\n userEvent.set(\"title\",title);\n userEvent.set(\"location\",location);\n userEvent.set(\"time\",time);\n userEvent.set(\"startTimeInMilliseconds\", startTimeInMilliseconds);\n userEvent.set(\"endTimeInMilliseconds\", endTimeInMilliseconds);\n userEvent.set(\"visibility\",visibility);\n userEvent.set(\"description\",description);\n userEvent.set(\"commentNumber\",0);\n userEvent.set(\"reportNum\", 0);\n\n userEvent.save(null, {\n success: function(userEvent) {\n displayFunction(userEvent);\n $.mobile.changePage(destID);\n },\n error: function(userEvent, error){\n errorObject.html(\"Error: \" + error.code + \" \" + error.message);\n }\n });\n}", "createNewPastSearch(username, location, time, eateryType){\n let date = new Date();\n let newPastSearch = {\n Username : username,\n Location : location,\n Time : time,\n EateryType : eateryType,\n DayOfSearch : date.getDate(),\n MonthOfSearch : date.getMonth() + 1,\n YearOfSearch : date.getFullYear()\n };\n\n this.PastSearchesModel.create(newPastSearch, function (err) {\n if (err) return console.log(err);\n });\n\n\n console.log('[PAST_SEARCHES] new past search created');\n console.log(newPastSearch);\n\n return null;\n }", "function makeNewEvent() {\n var form = collectFormData();\n console.log(form);\n var event = formateEvent(form.bName, form.bDate, form.bTime, form.guestCount, form.bPhone);\n console.log(event);\n addEventListener(event);\n}", "addNewEvent(){\n const nameValue = document.querySelector(\"#event-name\").value\n const dateValue = document.querySelector(\"#event-date\").value.split(\"T\")[0]\n const timeValue = document.querySelector(\"#event-date\").value.split(\"T\")[1]\n const locationValue = document.querySelector(\"#event-location\").value\n const descriptionValue = document.querySelector(\"#event-description\").value\n\n const newEventObject ={\n name: nameValue,\n date: dateValue,\n time: timeValue,\n location:locationValue,\n description:descriptionValue,\n userId: sessionStorage.getItem(\"userId\")\n }\n return newEventObject;\n }", "function createEvent(request, response, next) {\n var newEvent = Event({title: request.body.title, description: request.body.description});\n\n util.mergeObjects(newEvent, request.body);\n\n newEvent.save(function (err) {\n if (err) throw err;\n response.send({event: newEvent});\n next();\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ex. 3 A function that takes 3 numbers as parameters. The 3 parameters are called min, max, and target. Return whether target number is between the min and the max (inclusive).
function targetInBetween(min, max, target){ if (target>min && target<max){ return true; } else { return false; } }
[ "function arr(min,target,max){\n if(target >= min && target <= max){\n return true; \n } else {\n return false;\n }\n}", "function rangeCheck(input, min, max) {\r\n return ((input > min) && (input < max));\r\n}", "function between(min, max, num) {\n return (num >= min && num <= max);\n}", "InRange(value, min,max){\n return ((value-min)*(value-max) <= 0)\n }", "function inRange(num, min, max, inclusive = false) {\n\tif (inclusive) {\n\t} else {\n\t\treturn num > min && num < max;\n\t}\n}", "function controlloRangeNumeri(min, max, number) {\n var result = false;\n if (number >= min && number <= max) {\n result = true;\n }\n return result;\n}", "function checkNumbers(min, max, number) {\r\n var result = false;\r\n if (number >= min && number <= max) {\r\n result = true;\r\n }\r\n return result;\r\n}", "function numberBetween(n, min, max) {\n if (Number(n) !== n) {\n return false;\n } else {\n if (typeof min === \"undefined\" && typeof max === \"undefined\") {\n return true;\n } else if (typeof min !== \"undefined\" && typeof max === \"undefined\") {\n return nr > min;\n } else if (typeof min === \"undefined\" && typeof max !== \"undefined\") {\n return nr < max;\n } else {\n return nr > min && nr < max;\n }\n }\n}", "function isInRange(num, range) {\n return ((num >= range.min) && (num <= range.max )) ;\n}", "function inRange(x, minVal, maxVal) {\n return minVal <= x && x <= maxVal;\n}", "function isWithinLimits(value, min, max) {\n return value >= min && value < max;\n}", "function isInRange(num, range) {\n return range.min <= num && range.max >= num;\n}", "function isBetween(value, [min, max]) {\n return value >= min && value <= max;\n}", "function isWithin(value, min, max) {\n return ((value <= min) && (value >= max));\n}", "function isBetween(value, min, max) {\n return ( (value >= min) && (value <= max) );\n}", "static inRange(value, min, max) {\n return value >= Math.min(min, max) && value <= Math.max(min, max);\n }", "function isInRange(num, range) {\n\treturn num >= range.min && num <= range.max ? true : false;\n}", "function isAmountInRange(amount, min, max) {\n return amount >= min && amount <=max;\n}", "function isInRange(a, b, c) {\n return a <= b && b <= c;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================================== This code makes the about section to flow from one color to another ==========================================
function flowAboutSectionColor() { let coords = getObjectCoords(aboutSection); // GC - Green Channel // BC - Blue Channel let GCStart = 90; let BCStart = 61; let GCEnd = 30; let BCEnd = 172; let GCCurrent = normalize(0, -500, GCStart, GCEnd, coords.top); let BCCurrent = normalize(0, -500, BCStart, BCEnd, coords.top); aboutSection.css( "background-color", `rgb(255, ${GCCurrent}, ${BCCurrent})` ); }
[ "function updateColors( sectionNumber ) {\n clearAside();\n advanceAside( sectionNumber );\n clearBar();\n advancePBar( sectionNumber );\n}", "function changeHeadingColor() {\n\tdocument.getElementById(\"heading\").style.backgroundColor = colors[colorIndex];\n\tcolorIndex = (colorIndex + 1) % colors.length; // Alternates the next heading background color. \n}", "function changeColors(settinglines){\n var colorInfo = settinglines[1];\n var hash = \"#\";\n if (!(colorInfo == \"\")){\n //extract the first number as text color rgb value\n colorInfo = colorInfo.substr(1);\n var idx = colorInfo.indexOf(\"#\");\n textColor = hash.concat(colorInfo.substr(0,idx));\n colorInfo = colorInfo.substr(idx);\n //extract the second number as the highlight background color\n if (colorInfo.substr(0,1) === \"#\") {\n colorInfo = colorInfo.substr(1);\n idx = colorInfo.indexOf(\"#\");\n highlightBGColor = hash.concat(colorInfo.substr(0,idx));\n colorInfo = colorInfo.substr(idx);\n if (colorInfo.substr(0,1) === \"#\") {\n colorInfo = colorInfo.substr(1);\n idx = colorInfo.indexOf(\"#\");\n highlightTxtColor = hash.concat(colorInfo.substr(0,idx));\n colorInfo = colorInfo.substr(idx);\n if (colorInfo.substr(0,1) === \"#\") {\n colorInfo = hash.concat(colorInfo.substr(1));\n bgColor = colorInfo;\n }\n }\n }\n //test whether we have the four information for colors\n if (textColor == null || highlightBGColor == null || highlightTxtColor == null || bgColor == null) {\n alert(\"color customized info lacked, we assign the default colors\");\n textColor = \"#000000\";\n highlightBGColor = \"#ffffe0\";\n highlightTxtColor = \"#000000\";\n bgColor = \"#ffffff\";\n }\n //after we get the four valid values of the colors, assign them\n //$(\"#content\").css(\"color\", textColor);\n //$(\"#content\").css(\"background-color\", bgColor);\n $(\"body\").css(\"color\", textColor);\n $(\"body\").css(\"background-color\", bgColor);\n }\n $(\".firstTopic\").css(\"background-color\", highlightBGColor);\n $(\".firstTopic\").css(\"color\", highlightTxtColor);\n $(\".firstTopic\").addClass(\"currentHighlight\");\n}", "function changeColor() {\n var randomColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +\n (Math.floor(Math.random() * 256)) + ',' +\n (Math.floor(Math.random() * 256)) + ')';\n header.animate({ color: randomColor }, 2500);\n changeColor();\n }", "function highlightButton(){\n\t//gets the height of a section / 2, all sections are equal height\n\tvar sectionMidPoint = document.getElementById(\"frontCover\").getBoundingClientRect().height / 2;\n\tswitch(true){\n\t\tcase(windowPosition === 0):\n\t\t\tvar top = document.getElementById(\"top\");\n\t\t\ttop.style.backgroundColor = \"#FF3B3F\";\n\t\t\ttop.style.color = \"#F8F8F8\";\n\t\t\treturn(\"#top\");\n\n\t\tcase (windowPosition > 0 && windowPosition < aboutStartPos - sectionMidPoint):\n\t\t\tvar top = document.getElementById(\"top\");\n\t\t\ttop.style.backgroundColor = \"#FF3B3F\";\n\t\t\ttop.style.color = \"#282828\";\n\t\t\treturn(\"#top\");\n\n\t\tcase (windowPosition >= aboutStartPos - sectionMidPoint && windowPosition < portfolioStartPos - sectionMidPoint):\n\t\t\tvar about = document.getElementById(\"about\");\n\t\t\tabout.style.backgroundColor = \"#FF3B3F\";\n\t\t\tabout.style.color = \"#282828\";\n\t\t\treturn(\"#about\");\n\n\t\tcase (windowPosition >= portfolioStartPos - sectionMidPoint && windowPosition < contactStartPos - sectionMidPoint):\n\t\t\tvar portfolio = document.getElementById(\"portfolio\");\n\t\t\tportfolio.style.backgroundColor = \"#FF3B3F\";\n\t\t\tportfolio.style.color = \"#282828\";\n\t\t\treturn(\"#portfolio\");\n\n\t\tcase (windowPosition >= contactStartPos - sectionMidPoint):\n\t\t\tvar contact = document.getElementById(\"contact\");\n\t\t\tcontact.style.backgroundColor = \"#FF3b3F\";\n\t\t\tcontact.style.color = \"#282828\";\n\t\t\treturn(\"#contact\");\n\n\t}\n\n}", "function ColorSelection() {\n\n selectedColor = color(`rgba(${c.map((dat) => dat)})`);\n hueVarr = Math.round(hue(selectedColor));\n\n //h % 180\n fill(color(`rgba(${c.map((dat) => dat)})`));\n push();\n fill(100,0,100);\n textSize(12);\n text(\"Primary Secondary\", width/4 * 3, height/20, 120, 25);\n fill(255, 255, 255, 51);\n pop();\n rect(width/4 * 3, height/10, 50, 50);\n\n fill(hueVarr > 180 ? hueVarr / 2 : hueVarr * 2, 100, 100)\n rect(width/4 * 3 + 50, height/10, 50, 50);\n\n bColorsPicked = true;\n //PaintButton.show();\n}", "function colorChange(color) {\n\tvar lightness = hslaGetLightness(color);\n\n\t// get a more contrasted version of the color\n\tcolor = hslaAdjustLightness(color, lighterColor);\n\n\t// always change the subhead text to match new color\n\tsubhead.style.color = color;\n\n\t// for really light colors, add a shadow to the title\n\t// so that its a little more readable\n\tif (lightness > 70) {\n\t\theader.style.color = color;\n\t\theader.className = 'with-shadow';\n\t} else {\n\t\theader.style.color = '';\n\t\theader.className = '';\n\t}\n\n\tfor (var i = 0; i < colorChangeElements.length; i++) {\n\t\tcolorChangeElements[i].style.color = color;\n\t}\n}", "function colorChange() {\n document.body.style.backgroundColor = colorArray[ranColor];\n document.body.style.transition = 'all 1.2s';\n }", "function colorChange() {\n if (newTurn == 1) {\n $('.turn').css(\"background\", \"linear-gradient(to right, #BEEE62 50%, transparent 50%)\");\n } else {\n $('.turn').css(\"background\", \"linear-gradient(to right, transparent 50%, #BEEE62 50%)\");\n }\n }", "function correctColorDisplay(){\r\n\theader.style.backgroundColor = colorPicked;\t\r\n\tfor(var x=0; x<squares.length; x++){\r\n\t\tsquares[x].style.backgroundColor = colorPicked;\r\n\t\tsquares[x].style.opacity = \"1\";\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t}\r\n}", "function changeSectionBG(color){\n document.getElementById(\"section\").style.background = color;\n }", "function changeColors(rgb) {\n for (var i = 0; i < mode; i++) {\n squares[i].style.backgroundColor = rgb;\n }\n h1.style.backgroundColor = rgb;\n}", "updateColorTheme() { \n this.mode = 'matchup'\n MU_COLOR_IDX = (MU_COLOR_IDX + 1) % 3\n this.plot();\n }", "transitionToTutorial() {\n if (this.tick <= 50) {\n this.logo.alpha -= 0.02;\n this.pressAnyKey.alpha -= 0.02;\n this.titleText.alpha -= 0.02;\n }\n else if (this.tick <= 100) {\n this.tutorial.alpha += 0.02;\n }\n else {\n this.state = 2;\n this.tick = 0;\n this.fireToContinue.setAlpha(1);\n }\n }", "function progressAndChangeColor() {\n var wichColorAxisToChange = 'rgb'[Math.floor(Math.random() * 3)];\n currentColor[wichColorAxisToChange] += currentColor.variationAmount;\n currentColor[wichColorAxisToChange] %= 256;\n\n var newColorText = `rgb(${currentColor.r},${currentColor.g},${currentColor.b})`;\n document.body.style.backgroundColor = newColorText;\n document.querySelector('.category').style.color = newColorText;\n console.dir(currentColor);\n}", "function colorSwitcher(el) {\n switch(colorCounter)\n {\n case 0 :\n var inverted = invertColor(randomBoolean() ? settings.preferredPrimaryColor : randomColor());\n el.css({\n 'color' : randomBoolean() ? settings.preferredPrimaryColor : randomColor(),\n 'background-color' : inverted\n }); \n break;\n case 1 :\n var inverted = invertColor(randomBoolean() ? settings.preferredSecondaryColor : randomColor());\n el.css({\n 'color' : randomBoolean() ? settings.preferredSecondaryColor : randomColor(),\n 'background-color' : inverted\n }); \n break;\n case 2 : \n var inverted = invertColor(randomBoolean() ? settings.preferredTertiaryColor : randomColor());\n el.css({\n 'color' : randomBoolean() ? settings.preferredTertiaryColor : randomColor(),\n 'background-color' : inverted\n }); \n break;\n }\n colorCounter == 2 ? colorCounter = 0 : colorCounter++;\n }", "function changeColor() {\n for (var i = 0; i < cubeElements.length; i++) {\n var currentColor = window.getComputedStyle(this).backgroundColor;\n cubeElements[i].style.backgroundColor = currentColor;\n h1.style.textShadow = \"3px 3px \" + currentColor;\n };\n}", "function resetColor(){\n\n\t\t\treset.text('New Colors');\n\t\t\tmessage.text('');\n\t\t\th1.css('background-color', 'steelblue');\n\t\t\tcolors= generateRandomColors(difficult);\n\t\t\tpickedColor= pickColor();\n\t\t\tspan1.text(pickedColor);\n\t\t\tchangeColors(colors);\n\n\t\t\tfor (var i = 0; i < difficult; i++){\n\t\t\t\tsquares[i].style.backgroundColor= colors[i];\n\t\t\t\tsquares[i].addEventListener(\"click\", checkColor);\n\t\t\t}\n\t\t}", "function navSetup () {\r\n if (gameMode === \"rgb\") {\r\n rgbMode.style.backgroundColor = headerColor;\r\n rgbMode.style.color = \"white\";\r\n } else {\r\n hexMode.style.backgroundColor = headerColor;\r\n hexMode.style.color = \"white\";\r\n }\r\n\r\n if (difficulty === 2) {\r\n easy.style.backgroundColor = headerColor;\r\n easy.style.color = \"white\";\r\n medium.style.backgroundColor = \"white\";\r\n medium.style.color = \"black\";\r\n hard.style.backgroundColor = \"white\";\r\n hard.style.color = \"black\";\r\n } else if (difficulty === 4) {\r\n medium.style.backgroundColor = headerColor;\r\n medium.style.color = \"white\";\r\n easy.style.backgroundColor = \"white\";\r\n easy.style.color = \"black\";\r\n hard.style.backgroundColor = \"white\";\r\n hard.style.color = \"black\";\r\n } else if (difficulty === 6) {\r\n hard.style.backgroundColor = headerColor;\r\n hard.style.color = \"white\";\r\n medium.style.backgroundColor = \"white\";\r\n medium.style.color = \"black\";\r\n easy.style.backgroundColor = \"white\";\r\n easy.style.color = \"black\";\r\n }\r\n\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this should implement the task view
function taskView() { // set up necessary data const taskList = $("#tasklist"); const archiveList = $("#archivelist"); const tasks = $("body").data("tasks"); const active = tasks["active"]; const activeKeys = Object.keys(active); // first, update the tasklist with data from the DOM const activeList = getIDList("tasklist"); if (activeList.length > 0) // there are already entries in the table { for (let i = 0; i < activeKeys.length; i++) { if (!activeList.find(element => element === activeKeys[i])) { // write the task to the table addTask(activeKeys[i], active[activeKeys[i]]); } } } else { for (let j = 0; j < activeKeys.length; j++) { // write the task to the table addTask(activeKeys[j], active[activeKeys[j]]); } } // hide the archive archiveList.hide(); // show the tasklist taskList.show(); // switch our links around switchViewLinks("archive"); }
[ "function displayTask() {\n if (tasks.length != 0) { \n panel.refreshTask(tasks[0]);\n } else {\n panel.allTasksDone();\n }\n }", "viewTasks(){\n for(let i = 0; i < this.tasks.length; i++){\n console.log(`Task : ${this.tasks[i]}`);\n }\n }", "function taskView() {\n var tasksToDo = $.map(manager.toDos, function(task, index) {\n return(\"<li><input type='checkbox' class='toDoTask' id=toDo\" + index + \">\" + task + \"</li>\");\n });\n $(\".tasks\").html(tasksToDo);\n }", "renderTask(task) {\n return (\n <TaskListItem key={task.id} task={task} deleteTask={this.deleteTask.bind(this)} updateTask={this.updateTask.bind(this)} />\n )\n }", "displayTasks() {\n switch (this.display) {\n case \"all\":\n this.showAll();\n break;\n case \"active\":\n this.showActive();\n break;\n case \"completed\":\n this.showCompleted();\n break;\n default:\n this.showAll();\n }\n\n this.updateTaskNum();\n }", "function openTaskView() {\n withUniqueClass(\n requireCursor(),\n ['content', 'task_list_item__body'],\n all,\n click,\n );\n }", "render() {\n const taskItem = document.createElement('div');\n\n taskItem.classList.add('wrapper-task');\n taskItem.innerHTML = task(this.model.getTaskInfo());\n\n this.root.append(taskItem);\n\n this.attachListeners(taskItem);\n }", "function createTask(v,t){\r\n \r\n }", "function getTaskDetails() {\n $scope.tasks = [];\n angular.forEach($scope.taskList, function(task) {\n $scope.tasks.push(task.content);\n });\n }", "static createView(task) {\n let div = document.importNode(TaskView.taskTemplate, true);\n let view = new TaskView(div);\n __classPrivateFieldGet(view, _TaskView_instances, \"m\", _TaskView_renderDiv).call(view, task);\n __classPrivateFieldGet(view, _TaskView_instances, \"m\", _TaskView_bindController).call(view, task);\n TaskView.taskList.appendChild(__classPrivateFieldGet(view, _TaskView_div, \"f\"));\n return view;\n }", "function displayTasks() {\n // Loop through all tasks in the local array\n for (let task of tasks) {\n // Call helper function to add to UI\n addTaskToDisplay(task);\n }\n}", "function displayTasks() {\n document.querySelector(\"#tasks\").innerHTML = \"\";\n sortTasks();\n for (let task of tasks) {\n new Task(task.content, task.date, task.time, task.pin, task.id).displayTask();\n };\n executeRotation();\n recolorPastTasks();\n}", "static displayData(){\n const tasks = Store.getData();\n\n //Inte ui\n const ui = new UI;\n\n tasks.forEach(function(task){\n ui.addTask(task);\n })\n }", "function renderTasks () {\n // Set which tasks to render\n var tasksBeingViewed = [];\n if (mode === 'future') tasksBeingViewed = futureTasks;\n if (mode === 'today') tasksBeingViewed = todaysTasks;\n if (mode === 'prev') tasksBeingViewed = previousTasks;\n\n // If there's no tasks to show, show that message\n if (!tasksBeingViewed || tasksBeingViewed.length == 0) {\n var noTaskHtml = '<h2>No Tasks</h2>';\n $('#task-item-div').html(noTaskHtml);\n return;\n }\n\n // Create HTML to add to the page\n var htmlToShow = '';\n for (let i in tasksBeingViewed) {\n let task = tasksBeingViewed[i];\n // Process filiters \n // Complete filter \n if (hasCompleteFilter && task.complete !== completeFilter) {\n continue;\n }\n // Priority filter \n if (hasPriorityFilter && task.priority !== priorityFilter) {\n continue;\n }\n // Category filter \n if (hasCategoryFilter && task.category !== categoryFilter) {\n continue;\n }\n\n htmlToShow += '<div class=\"task-item\" id=\"task-item-' + task._id + '\">';\n htmlToShow += '<h4 class=\"task-description task-item-content\">' + task.description + '</h4>';\n htmlToShow += '<h6 class=\"task-item-content\"><i> Due: ' + task.deadline + '</i></h6>';\n htmlToShow += '<h5 class=\"task-item-content\"><i>Priority: </i>' + task.priority + '</h5>';\n htmlToShow += '<h5 class=\"task-item-content\"><i>Category: </i>' + task.category + '</h5>';\n // Show collaborators if there are other people too (i.e. not just current user)\n if (task.users.length > 1) {\n var collaborators = ''; \n for (let j in task.users) {\n // Skip the logged in user\n if (task.users[j] === userLoggedIn) continue;\n collaborators += task.users[j] + ' ';\n }\n htmlToShow += '<h5 class=\"task-item-content\"><i>Collaborators: </i>' + collaborators + '</h5>';\n } \n htmlToShow += '<div class=\"task-item-controls\" id=\"task-item-controls-' + task._id + '\">';\n htmlToShow += '<div class=\"row header-row task-status-row\">';\n htmlToShow += '<div class=\"col-md-6\" style=\"text-align:left\">';\n var completeText = task.complete ? 'Complete' : 'Incomplete';\n htmlToShow += '<h5 class=\"task-status\">' + completeText + '</h5></div>';\n htmlToShow += '<div class=\"col-md-6\" style=\"text-align:right\">';\n htmlToShow += '<button type=\"button\" class=\"btn btn-danger btn-xs task-item-control-btn\" id=\"delete-task-btn-' + task._id + '\">Delete</button> ';\n var completeButtonHtml = '<button type=\"button\" class=\"btn btn-success btn-xs task-item-control-btn\" id=\"complete-task-btn-' + task._id + '\">Mark Complete</button>'; \n if (task.complete) {\n completeButtonHtml = '<button type=\"button\" class=\"btn btn-warning btn-xs task-item-control-btn\" id=\"complete-task-btn-' + task._id + '\">Mark Incomplete</button>'; \n }\n htmlToShow += completeButtonHtml;\n htmlToShow += '</div></div></div></div>';\n }\n $('#task-item-div').html(htmlToShow);\n\n // Add click listenders for buttons \n for (let i in tasksBeingViewed) {\n let task = tasksBeingViewed[i];\n if (task.complete) {\n // Change the background color of complete tasks \n $('#task-item-' + task._id).css('background-color', 'rgba(0,0,0,.5)');\n $('#task-item-controls-' + task._id).css('background-color', 'rgba(0,0,0,.5)');\n }\n // NOTE - this needs to be done this way to avoid closure issues\n (function (task, i) {\n // Delete button\n $('#delete-task-btn-' + task._id).on('click', function () {\n $.post('api/deleteTask', {tid: task._id}, function (data) {\n if (data.status === 'ok') {\n // Remove the deleted task from the list and re-render\n if (mode === 'future') {\n futureTasks.splice(i, 1);\n renderTasks();\n }\n if (mode === 'today') {\n todaysTasks.splice(i, 1);\n renderTasks();\n }\n if (mode === 'prev') {\n previousTasks.splice(i, 1);\n renderTasks();\n }\n }\n });\n });\n\n // Toggle task complete button\n $('#complete-task-btn-' + task._id).on('click', function () {\n // Toggle completion\n $.post('api/toggleTaskCompletion', {tid: task._id}, function (data) {\n if (data.status === 'ok') {\n // Edit the toggled task list and rerender\n if (mode === 'future') {\n futureTasks[i].complete = !futureTasks[i].complete;\n renderTasks();\n }\n if (mode === 'today') {\n todaysTasks[i].complete = !todaysTasks[i].complete;\n renderTasks();\n }\n if (mode === 'prev') {\n previousTasks[i].complete = !previousTasks[i].complete;\n renderTasks();\n }\n }\n });\n });\n }(task, i)); \n } \n }", "function displayTasks() {\n\t$.each(allItems, function(i, v) {\n\t\t//Appends new task and separates with lines\n\t\tif(this != allItems[allItems.length - 1]) {\n\t\t\t$todoList.append(\"<li><b>\" + this.task + \"</b><span class='date'>\" + this.due.toDateString() + \"</span> <ul class='notes'> \" + this.desc + '</ul></li><hr class=\"inner\">');\n\t\t}\n\t\telse {\n\t\t\t$todoList.append(\"<li><b>\" + this.task + \"</b><span class='date'>\" + this.due.toDateString() + \"</span> <ul class='notes'> \" + this.desc + '</ul></li>');\n\t\t}\n\t});\n\n\tdueSoon();\n\tdueThisWeek();\n\tdueClear();\n}", "show() {\n this.__utils.log(\n 'tasks',\n 'Currently Running Tasks:',\n () => {\n for ( let taskCategory in this.task.roster ) {\n this.__utils.log(\n false,\n taskCategory,\n () => {\n for ( let taskID in this.task.roster[taskCategory] ) {\n this.__utils.log(\n false,\n taskID,\n this.task.roster[taskCategory][taskID].name\n )\n }\n }\n )\n }\n }\n )\n }", "function renderTasks() {\n saveTasks();\n taskArea.innerHTML = \"\";\n tasks.forEach(function (task) {\n taskArea.appendChild(task.render());\n });\n}", "renderTasks() {\n // Get the current tab from the state\n let {currentTab} = this.state;\n // Prepare return variable\n let displayedTasks = [];\n let OriginTasks = this.tasks;\n\n // If the tabs is not a progressed tab\n if (unprogressedTab.has(currentTab)) {\n for (let i = 0; i < OriginTasks.length; i += 1) {\n let task = OriginTasks[i];\n if (task.status === currentTab) {\n displayedTasks.push(\n (<TouchableHighlight\n style={[KanbanStyles.taskItems]}\n onPress={() => this.clickTaskHandler(task.id)}\n >\n <KanbanUnprogressTask\n detail={{\n title: task.title,\n deadline: task.deadline\n }}\n />\n </TouchableHighlight>)\n );\n }\n }\n }\n // If the tab is a progressed tab\n else if (progressedTab.has(currentTab)) {\n for (let i = 0; i < OriginTasks.length; i += 1) {\n let task = OriginTasks[i];\n if (task.status === currentTab) {\n displayedTasks.push(\n (<TouchableHighlight\n style={[KanbanStyles.taskItems]}\n\n onPress={() => this.clickTaskHandler(task.id)}\n >\n <KanbanProgressTask\n detail={{\n title: task.title,\n deadline: task.deadline,\n progress: task.progress,\n duration: task.duration\n }}\n />\n </TouchableHighlight>)\n );\n }\n }\n }\n\n return displayedTasks;\n }", "function listTasks(){\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by AgtypeParserfloatLiteral.
enterFloatLiteral(ctx) { }
[ "enterFloatLiteral(ctx) {\n\t}", "exitFloatLiteral(ctx) {\n\t}", "exitFloatLiteral(ctx) {\n }", "function updateFloatLabel(node, value) { }", "SetFloat() {}", "function floatHandler(id) {\n operatorSelectorCleaner(id);\n createAndAddNewOptions(\"number\", id);\n inputBuilder(\"float\", id);\n}", "function as_float(v) {\r\n return setType(v, 'float');\r\n}", "function isFloat(token) {\n return !isNaN(Number(token)) && token.indexOf('.') != -1;\n}", "set floatValue(value) {}", "set floatParameter(value) {}", "enterFloatValue(ctx) {\n }", "constructor() {\n super(expressionType_1.ExpressionType.Float, Float.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnary);\n }", "function parseF(s) {\n // if (typeof(parseInt(s)) === \"number\"){\n // return parseFloat(s)\n \n // }else{\n // return null\n // }\n \n if ( isNaN(parseFloat(s) )) {\n return null\n } else{\n return parseFloat(s)\n }\n \n \n }", "function LogicNodeFloat() {\n\t\t\tLogicNode.call(this);\n\t\t\tthis.logicInterface = LogicNodeFloat.logicInterface;\n\t\t\tthis.type = 'LogicNodeFloat';\n\t\t}", "SetFloats() {}", "function LogicNodeFloat() {\n\t\tLogicNode.call(this);\n\t\tthis.logicInterface = LogicNodeFloat.logicInterface;\n\t\tthis.type = 'LogicNodeFloat';\n\t}", "readFloat(){return this.__readFloatingPointNumber(4)}", "function asFloat(t) {\n return parseFloat(t.innerHTML)\n}", "function number(token)\n{\n return token.type == \"float\" || token.type == \"integer\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render the view. This will set up any subforms that might be available within the form. Returns: RB.FormView: This object, for chaining.
render() { this._$subforms = this.$('.rb-c-form-fieldset.-is-subform'); if (this._$subforms.length > 0) { this._setupSubforms(); } this.setupFormWidgets(); return this; }
[ "renderForms() {\n for (const form of this._configForms.values()) {\n form.render();\n }\n\n /*\n * Ensure that if the browser sets the value of the <select> upon\n * refresh that we update the model accordingly.\n */\n this.$('#id_avatar_service_id').change();\n this._showHideForms(true);\n\n return this;\n }", "render() {\n let template = this._renderTemplate('Tinymce/InternalLink/internalLinkForm');\n this.$el.html(template);\n let $formRegion = $('.modal-body', this.$el);\n this._displayLoader($formRegion);\n\n let url = Routing.generate('open_orchestra_backoffice_internal_link_form');\n FormBuilder.createFormFromUrl(url, (form) => {\n let internalLinkFormView = new InternalLinkFormView({\n form: form,\n editor: this._editor,\n modal: this\n });\n $formRegion.html(internalLinkFormView.render().$el);\n }, this._data);\n\n return this;\n }", "render() {\n this._userConfigView.render();\n this._brokerConfigView.render();\n\n const template = RB.Product ? this._templateRB4 : this._templateRB3;\n this.$el.html(template);\n\n this._$form = this.$('form');\n\n this.$('.rb-c-form-fieldset__fields')\n .append(this._userConfigView.$el)\n .append(this._brokerConfigView.$el);\n\n this._$saveButton = this.$('input[type=\"submit\"]')\n .val(gettext('Save'));\n\n return this;\n }", "renderForm() {\r\n\r\n if (this.schema.data.dirty) {\r\n this.addDirtyCheck();\r\n }\r\n\r\n this.events.trigger(ExoFormFactory.events.renderStart)\r\n this._cleanup();\r\n\r\n return new Promise((resolve, reject) => {\r\n\r\n this.container.appendChild(this.form);\r\n if (this.schema.form.id) {\r\n this.container.setAttribute(\"id\", this.schema.form.id);\r\n }\r\n\r\n try {\r\n\r\n this._renderPages().then(() => {\r\n\r\n this._finalizeForm().then(() => {\r\n\r\n resolve(this);\r\n });\r\n\r\n })\r\n\r\n .catch(ex => {\r\n reject(\"_renderPages() failed: \" + ex.toString());\r\n });\r\n\r\n }\r\n catch (ex) {\r\n reject(\"Exception in _renderPages(): \" + ex.toString())\r\n }\r\n });\r\n }", "function FormView() {\n\t\n\t//oFormFields is JSON Object like: \t\n\t//\t{\n\t//\t\t\"subform_0\": {\n\t//\t\t\t\"cred_id\": \"tm\",\n\t//\t\t\t\"form_ID\": \"91\",\n\t//\n\t//\t\t},\n\t//\t\t\"subform_1\": {\n\t//\t\t\t\"page_num_02\": \"\",\n\t//\t\t\t\"doc_number_01\": \"\",\n\t//\t\t\t\"file_number_01\": \"\",\n\t//\n\t//\t\t},\n\t//\t\t\"subform_2\": {\n\t//\t\t\t\"save\": \"\",\n\t//\t\t\t\"review\": \"\",\n\t//\t\t\t\"complete\": \"\",\n\t//\t\t\t\"page_num_03\": \"\",\n\t//\t\t}\n\t//\t}\t\n\t\t\n\t\n\t\n\tthis.oFormFields = {}; \n\t\n\tthis.oRequiredField = {};\n\t\n\tthis.oLabel = {};\n\t\n\tthis.oReadOnlyField = {};\n\t\n\tthis.oImageField = {};\n\t\n\tthis.oMapOption = null;\n\t\n\tthis.oInitMapCentre = null;\n\t\n\tthis.getFormFields = function() {\n\t\treturn this.oFormFields;\n\t};\n\t\n\tthis.setFormFields = function(oFields) {\n\t\tthis.oFormFields = oFields;\n\t};\n\t\n\tthis.getRequiredField = function() {\n//\t\tconsole.log(\"this.oRequiredField: \" + Array.isArray(this.oRequiredField));\n\t\treturn this.oRequiredField;\n\t};\n\t\n\tthis.setRequiredField = function(oFields) {\n//\t\tconsole.log(\"oFields: \" + Array.isArray(oFields));\n\t\tthis.oRequiredField = oFields;\n\t};\t\n\t\n\tthis.getLabelFields = function() {\n\t\treturn this.oLabel;\n\t};\n\t\n\tthis.setLabelFields = function(obj) {\n//\t\tconsole.log(\"oFields: \" + Array.isArray(oFields));\n\t\tthis.oLabel = obj;\n\t};\t\n\t\n\tthis.getReadOnlyFields = function() {\n\t\treturn this.oReadOnlyField;\n\t};\n\t\n\tthis.setReadOnlyFields = function(oFields) {\n\t\tthis.oReadOnlyField = oFields;\n\t\tenableReadOnlyFields(oFields);\n\t};\n\t\n\tthis.setImageField = function(obj) {\n\t\tthis.oImageField = obj;\n\t}\n\t\n\tthis.getImageField = function() {\n\t\treturn this.oImageField;\n\t}\t\n\t\n\tthis.setMapOption = function(obj) {\n\t\tthis.oMapOption = obj;\n\t}\n\t\n\tthis.getMapOption = function() {\n\t\treturn this.oMapOption;\n\t} \n\t\n\tthis.setInitMapCentre = function(obj) {\n\t\tthis.oInitMapCentre = obj;\n\t}\n\t\n\tthis.getInitMapCentre = function() {\n\t\treturn this.oInitMapCentre;\n\t} \t\n\t\n\tthis.putFieldValue = function(sField, iSubform, value) {\n\t\tvar subformName = \"subform_\" + iSubform;\n\t\t//Modification to avoide error \"Cannot set property 'complete_flag' of undefined\"\n\t\tif (this.oFormFields[subformName] && this.oFormFields[subformName][sField]) {\n\t\t\tthis.oFormFields[subformName][sField] = value;\n\t\t}\n\t}\n\n\tthis.getFieldValue = function(sField, iSubform) {\n\t\tvar subformName = \"subform_\" + iSubform;\n\t\treturn\tthis.oFormFields[subformName][sField];\t\n\t}\n\n\t//Update some field value in subform[0] by oList which is JSON object. For instance,\n\t//\tvar oList = {\n\t//\t\t\t\"app_password2\" : \t\"31035aaca4\",\n\t//\t\t\t\"super_password2\":\t\"31035aaca4\"\n\t//\t}\n\t\n\tthis.updateFormFields = function(oList) { \n\t\tfor(var key in oList) {\n\t\t\tthis.putFieldValue(key, 0, oList[key]);\n\t\t}\n\t}\n\t\t\n}", "render() {\n Fields.BaseFieldView.prototype.render.call(this);\n\n this.$el.change(() => {\n this._saveValue(this.$el.is(':checked'), {\n error: err => this.trigger('fieldError', err),\n success: () => this.trigger('fieldSaved'),\n });\n });\n\n return this;\n }", "render(){\n\t\tif(this.has_elements){\n\t\t\tthis.$title.html(this.form_data.title);\n\t\t\tthis.$pb_form.hide();\n\t\t\tthis.create_reset_button();\n\t\t\tthis.create_submit_button();\n\t\t\tthis.$content_container.append(this.$wrapper);\n\t\t}\n\t}", "render() {\n Fields.BaseFieldView.prototype.render.call(this);\n\n this.$el.change(() => {\n this._saveValue(this.$el.val(), {\n error: err => this.trigger('fieldError', err),\n success: () => this.trigger('fieldSaved'),\n });\n });\n\n return this;\n }", "render() {\n RB.CollapsableBoxView.prototype.render.call(this);\n\n this._reviewView = new RB.ReviewView({\n el: this.el,\n model: this.model,\n reviewRequestEditor: this.options.reviewRequestEditor,\n $bannerFloatContainer: this._$box,\n $bannerParent: this.$('.banners'),\n bannerNoFloatContainerClass: 'collapsed',\n showSendEmail: this.options.showSendEmail,\n });\n\n this._$boxStatus = this.$('.box-status');\n this._$fixItLabel = this._$boxStatus.find('.fix-it-label');\n\n this.listenTo(this._reviewView, 'hasDraftChanged',\n hasDraft => this.$el.toggleClass('has-draft', hasDraft));\n this.listenTo(this._reviewView, 'openIssuesChanged',\n this._updateLabels);\n\n this._reviewView.render();\n this._updateLabels();\n\n return this;\n }", "build() {\n if (this.options.flat) {\n this.builder.renderInputs(this.createFormJson());\n } else {\n this.builder.renderGroups(this.createFormJson());\n }\n\n this.builder.append(\n this.builder.createSubmitBtn(this.options.locale.submit, this.onSubmit.bind(this)),\n );\n }", "render() {\r\n return(ViewsiteFormJSX.call(this));\r\n }", "render() {\n ParentView.prototype.render.call(this);\n\n this._reviewView = new RB.ReviewRequestPage.ReviewView({\n el: this.el,\n model: this.model.get('review'),\n entryModel: this.model,\n $bannerFloatContainer: this._$box,\n $bannerParent: this.$('.banners'),\n bannerNoFloatContainerClass: 'collapsed',\n reviewRequestEditorView: this.reviewRequestEditorView,\n });\n\n this._$boxStatus = this.$('.box-status');\n this._$fixItLabel = this._$boxStatus.find('.fix-it-label');\n this._$shipItLabel = this._$boxStatus.find('.ship-it-label');\n\n this.listenTo(this._reviewView, 'hasDraftChanged',\n hasDraft => this.$el.toggleClass('has-draft', hasDraft));\n this.listenTo(this._reviewView, 'openIssuesChanged',\n this._updateLabels);\n\n this._reviewView.render();\n this._updateLabels();\n\n return this;\n }", "render() {\r\n return(FormJSX.call(this));\r\n }", "renderForm(form) {\n form.renderAdd(this.section);\n }", "render() {\n Fields.BaseFieldView.prototype.render.call(this);\n\n /*\n * We needn't render the view because it has already been rendered by\n * the server.\n */\n this._commitListView = new RB.DiffCommitListView({\n el: this.$('.commit-list'),\n model: new RB.DiffCommitList({\n commits: this.model.get('commits'),\n isInterdiff: false,\n }),\n });\n\n return this;\n }", "render() {\n this.listView = new this.listViewType({\n ItemView: this.listItemViewType,\n el: this.$('.djblets-c-config-forms-list'),\n model: this.list,\n });\n this.listView.render().$el\n .removeAttr('aria-busy');\n\n this._$listContainer = this.listView.$el.parent();\n\n this.listenTo(this.list.collection, 'add remove',\n this._showOrHideConfigsList);\n this._showOrHideConfigsList();\n\n return this;\n }", "render() {\n this.$el.html(this.model.get('fieldHTML'));\n\n return this;\n }", "render () {\n return this.state.formOpen ? this.renderForm() : this.renderAddButton();\n }", "render() {\n let elem = document.createElement(this.type);\n elem.name = this.name\n elem.id = this.id\n elem.className = this.cssClass\n\n if (this.placeholder != undefined) {\n elem.placeholder = this.placeholder\n }\n\n if (this.config.attrs != undefined) {\n this.config.attrs.forEach(obj => {\n elem[obj.name] = obj.value\n })\n }\n\n const _self = this;\n\n // add listener to update the obj when element values changes\n elem.addEventListener('change', function () {\n if (form.fields[this.name] != undefined) {\n form.fields[this.name].value = this.value;\n } else if (form.subForm.fields[this.name] != undefined) {\n form.subForm.fields[this.name].value = this.value;\n }\n });\n this.populate(elem)\n this.addRefreshListener(elem)\n this.extraRenderConfig(elem)\n return elem;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ANIMATION Allows growth and shrinkage for any object in the game Call `startGrowth(...)` or `startShrink(...)` accordingly, on any object, to start growing or shrinking the object. Main game loop invoke `animateGrow` and `animateShrink` which handle incremental grow and shrink updates.
function startGrowth(object, duration, dy, scale) { // TODO: annotate all of these functions object.animateGrow_isGrowing = true; object.animateGrow_end_time = duration; object.animateGrow_end_dy = dy; object.animateGrow_end_scale = scale; object.animateGrow_start_y = object.position.y - dy; object.animateGrow_time = 0; }
[ "async growAndShrink() {\n await this._temporaryAnimation(this._icon, 'grow-and-shrink', 200);\n }", "function animate() {\n ctx.clearRect(0, 0, canvasWidth, canvasHeight);\n\n for (var i = 0; i < objects.length; i++) {\n objects[i].move();\n objects[i].draw();\n }\n\n if (debug) {\n drawDebugInfo();\n }\n }", "function playObjectAnimations() {\r\n powerUps.playAnimation(\"cherryAnims\", true);\r\n jewels.playAnimation(\"jewelAnims\", true);\r\n}", "function createObjectAnimations() {\r\n\r\n}", "animateObjects() {\n // Ask each AnimatedObject to update its loop and cell number if required.\n for (let aniObj of this.state.animatedObjects) {\n aniObj.updateLoopAndCel();\n }\n\n this.state.Vars[Defines.EGOEDGE] = 0;\n this.state.Vars[Defines.OBJHIT] = 0;\n this.state.Vars[Defines.OBJEDGE] = 0;\n\n // Restore the backgrounds of the previous drawn cels for each AnimatedObject.\n this.state.restoreBackgrounds(this.state.updateObjectList);\n\n // Ask each AnimatedObject to move if it needs to.\n for (let aniObj of this.state.animatedObjects) {\n aniObj.updatePosition();\n }\n\n // Draw the AnimatedObjects to screen in priority order.\n this.state.drawObjects(this.state.makeUpdateObjectList());\n this.state.showObjects(this.pixels, this.state.updateObjectList);\n\n // Clear the 'must be on water or land' bits for ego.\n this.state.ego.stayOnLand = false;\n this.state.ego.stayOnWater = false;\n }", "function createObjectAnimations() {\n\n}", "function animate(){\n drawBackground();\n drawspider();\n drawFly();\n drawScore();\n}", "function animate() {\n // If the GUI control for crush is selected\n if(DeformControls.Crush)\n // And object is above 0.25 of its original size\n // Then reduce scale by 0.01 and twistObj\n DeformControls.ScaleY > 0.25 ? (DeformControls.ScaleY-=0.01, twistObj( geometry )) : null;\n requestAnimationFrame( animate );\n renderer.render( scene, camera );\n}", "function animateObjects()\n{\n\t//Brains\n\tfor (var loop=0; loop < brainCount; loop++) //for each brain on the screen\n\t{\n\t\n\t\tbrains[loop].ySpeed = Math.round( -2.3 * Math.sin(brains[loop].age * Math.PI / 50)); //calculate new Y speed value\n\t\tbrains[loop].age++; //increase age by 1\n\t\t\n\t\tbrains[loop].x += brains[loop].xSpeed; //+= X speed\n\t\tbrains[loop].y += brains[loop].ySpeed; //+= Y speed\n\n\t\tbrains[loop].reposition();\t//call the reposition function to perform the movement\n\t}\n\t\n\t//Special brains\n\tfor (var loop=0; loop < specialCount; loop++)\n\t{\n\t\n\t\tspecials[loop].ySpeed = Math.round( -2.3 * Math.sin(specials[loop].age * Math.PI / 50));\n\t\tspecials[loop].age++;\n\t\t\n\t\tspecials[loop].x += specials[loop].xSpeed;\n\t\tspecials[loop].y += specials[loop].ySpeed;\n\n\t\tspecials[loop].reposition();\t\n\t}\n\t\n\t//Candy\n\tfor (var loop=0; loop < candyCount; loop++)\n\t{\n\t\n\t\tcandies[loop].ySpeed = Math.round( -1.7 * Math.sin(candies[loop].age * Math.PI / 120));\n\t\tcandies[loop].age++;\n\t\t\n\t\tcandies[loop].x += candies[loop].xSpeed;\n\t\tcandies[loop].y += candies[loop].ySpeed;\n\n\t\tcandies[loop].reposition();\t\n\t}\n}", "initAnimationState(growMe, shrinkMe) {\n // TODO\n var growMeOnSameFrond, shrinkMeOnSameFrond;\n var tranx = this.animationState.tranx;\n if (growMe.isRoot()) { // C==R,F!=R (we know F!=R because if F==R then C==F which aborts above)\n // The root is growing, so in lieu of growing the root Petal, grow the whole graph.\n tranx.push(new FlowerResize(this, {scale: this.state.scaleX, finalScale:1}));\n tranx.push(new FlowerMove(this, Object.assign({}, deadCenter)));\n // so shrinkMe can NOT be the root therefore\n //tranx.push(new PetalShrink(this, {}, shrinkMe));\n this.addAnimTransFor(shrinkMe, PetalShrink);\n } else { // C!=R\n var factor = .8;\n if (shrinkMe.isRoot()) { // C!=R,F==R -- shrink the root and grow the clicked petal\n // TODO in truth the further out the petal, the smaller the flower\n tranx.push(new FlowerResize(this, {scale: this.state.scaleX, finalScale:.5}));\n tranx.push(new FlowerMove(this, growMe.getCenter(factor)));\n this.addAnimTransFor(growMe, PetalGrow);\n //tranx.push(new PetalGrow(this, {governChildren: true}, growMe));\n } else { // C!=R,F!=R -- shrink the Focused and grow the Clicked\n tranx.push(new FlowerMove(this, growMe.getCenter(-1 * factor)));\n if (shrinkMe.getTheGoods().frond.idx == growMe.getTheGoods().frond.idx) {\n this.log('same frond');\n growMeOnSameFrond = growMe;\n shrinkMeOnSameFrond = shrinkMe;\n }\n this.addAnimTransFor(shrinkMe, PetalShrink, growMeOnSameFrond);\n this.addAnimTransFor(growMe, PetalGrow, shrinkMeOnSameFrond);\n }\n }\n }", "function animate() {\n\trequestAnimationFrame( animate );\n\trender();\n\tupdate();\n}", "function animate() { }", "function createObjectAnimations() {\r\n this.anims.create({\r\n key: 'jewelAnims',\r\n frames: this.anims.generateFrameNumbers('jewel', { start: 0, end: 4 }),\r\n frameRate: 10,\r\n repeat: -1,\r\n });\r\n\r\n this.anims.create({\r\n key: 'cherryAnims',\r\n frames: this.anims.generateFrameNumbers('cherry', { start: 0, end: 6 }),\r\n frameRate: 6,\r\n repeat: -1,\r\n });\r\n}", "function animate() {\n console.log(\"animate\");\n //delete\n endabgabe.crc.clearRect(0, 0, endabgabe.crc.canvas.width, endabgabe.crc.canvas.height);\n //putImgData\n endabgabe.crc.putImageData(imgData, 0, 0);\n for (let i = 0; i < movingObjects.length; i++) {\n movingObjects[i].update();\n if (movingObjects[i].checkHit() == true) {\n //inputsAdaptObjectValues(movingObjects[i]);\n //movingObjects[i].adaptManipulation(xSpeedRange.valueAsNumber, ySpeedRange.valueAsNumber, scaleRange.valueAsNumber, checkRotationValue(), colorInput.value, wabbleBox.checked, glowBox.checked);\n }\n }\n window.setTimeout(animate, 5);\n }", "function animate() {\n game.update();\n game.draw();\n window.requestAnimFrame(animate);\n}", "function animate() {\n\n\t\trequestAnimationFrame( animate );\n\n\t\tswitch(gameState.scene) {\n\n\t\t\tcase \"youwon\":\n\t\t\t\t//endText.rotateY(0.005);\n\t\t\t\trenderer.render( endScene, endCamera );\n\t\t\t\tbreak;\n\n\t\t\tcase \"start\":\n\t\t\t\trenderer.render( startScene, startCamera );\n\t\t\t\tbreak;\n\n\t\t\tcase \"gameover\":\n\t\t\t\t//endText2.rotateY(0.005);\n\t\t\t\trenderer.render( endScene2, endCamera2 );\n\t\t\t\tbreak;\n\n\t\t\tcase \"main\":\n\t\t\t\tupdateAvatar();\n\t\t\t\tupdateNPC();\n edgeCam.lookAt(avatar.position);\n\t \tscene.simulate();\n\t\t\t\tif (gameState.camera!= 'none'){\n\t\t\t\t\trenderer.render( scene, gameState.camera );\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"start\":\n\t\t\t\trenderer.render(startScreen, startCam);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t console.log(\"don't know the scene \"+gameState.scene);\n\t\t}\n\n\t\t//bullet array\n\t\tfor(var i = 0; i < bullets.length; i+= 1){\n\t\t\tif(bullets[i] == undefined) continue;\n\t\t\tif(bullets[i].alive == false){\n\t\t\t\tbullets.splice(i,1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbullets[i].position.add(bullets[i].velocity);\n\t\t}\n\n\t\t//draw heads up display ..\n\t var info = document.getElementById(\"info\");\n\t\tinfo.innerHTML='<div style=\"font-size:24pt\">Score: '\n + gameState.score\n + \" health=\"+gameState.health\n + '</div>';\n\n\t}", "function animate(){\n // Increase the angle of rotation after each frame is rendered\n rotationAngle+=.04;\n\n if(squashScale>.25){\n // If the block I is too large, make squash rate negative\n // so that it shrinks\n squashRate=-.01;\n }\n else if(squashScale<0){\n // If the block I is too small, make squash rate positive\n // so that it grows\n squashRate=.01;\n }\n // Change the scale of the block I\n squashScale+=squashRate;\n\n if(y_offset>1){\n // If the block I is too far up, make y offset decrease\n y_rate=-.05;\n }\n else if(y_offset<-1){\n // If the block I is too far down, make y offset increase\n y_rate=.05;\n }\n y_offset+=y_rate;\n\n // Call setupBuffers to update the vertices locations of the block I (for up/down animation)\n setupBuffers();\n}", "function animate() {\n // Schedule next frame\n window.requestAnimationFrame(animate);\n render();\n}", "function animate() {\n requestAnimationFrame(animate);\n\n if (explosionMaterial) {\n explosionMaterial.uniforms['time'].value = .01 * (Date.now() - start);\n }\n\n if (needsReset && !clock.running) {\n clock.start();\n }\n if (clock.getElapsedTime() >= 3) {\n clock.stop();\n clock = new THREE.Clock(false);\n needsReset = false;\n start = Date.now();\n clearScene();\n createScene();\n }\n\n render();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private function used by Plotly.moveTraces to check input args
function checkMoveTracesArgs(gd, currentIndices, newIndices) { // check that gd has attribute 'data' and 'data' is array if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array.'); } // validate currentIndices array if(typeof currentIndices === 'undefined') { throw new Error('currentIndices is a required argument.'); } else if(!Array.isArray(currentIndices)) { currentIndices = [currentIndices]; } assertIndexArray(gd, currentIndices, 'currentIndices'); // validate newIndices array if it exists if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) { newIndices = [newIndices]; } if(typeof newIndices !== 'undefined') { assertIndexArray(gd, newIndices, 'newIndices'); } // check currentIndices and newIndices are the same length if newIdices exists if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) { throw new Error('current and new indices must be of equal length.'); } }
[ "function checkMoveTracesArgs(gd, currentIndices, newIndices) {\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // validate currentIndices array\n\t if(typeof currentIndices === 'undefined') {\n\t throw new Error('currentIndices is a required argument.');\n\t } else if(!Array.isArray(currentIndices)) {\n\t currentIndices = [currentIndices];\n\t }\n\t assertIndexArray(gd, currentIndices, 'currentIndices');\n\n\t // validate newIndices array if it exists\n\t if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if(typeof newIndices !== 'undefined') {\n\t assertIndexArray(gd, newIndices, 'newIndices');\n\t }\n\n\t // check currentIndices and newIndices are the same length if newIdices exists\n\t if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {\n\t throw new Error('current and new indices must be of equal length.');\n\t }\n\n\t}", "function checkMoveTracesArgs(gd, currentIndices, newIndices) {\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if (!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // validate currentIndices array\n\t if (typeof currentIndices === 'undefined') {\n\t throw new Error('currentIndices is a required argument.');\n\t } else if (!Array.isArray(currentIndices)) {\n\t currentIndices = [currentIndices];\n\t }\n\t assertIndexArray(gd, currentIndices, 'currentIndices');\n\n\t // validate newIndices array if it exists\n\t if (typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if (typeof newIndices !== 'undefined') {\n\t assertIndexArray(gd, newIndices, 'newIndices');\n\t }\n\n\t // check currentIndices and newIndices are the same length if newIdices exists\n\t if (typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {\n\t throw new Error('current and new indices must be of equal length.');\n\t }\n\n\t}", "function checkMoveTracesArgs(gd, currentIndices, newIndices) {\n\n // check that gd has attribute 'data' and 'data' is array\n if(!Array.isArray(gd.data)) {\n throw new Error('gd.data must be an array.');\n }\n\n // validate currentIndices array\n if(typeof currentIndices === 'undefined') {\n throw new Error('currentIndices is a required argument.');\n } else if(!Array.isArray(currentIndices)) {\n currentIndices = [currentIndices];\n }\n assertIndexArray(gd, currentIndices, 'currentIndices');\n\n // validate newIndices array if it exists\n if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n newIndices = [newIndices];\n }\n if(typeof newIndices !== 'undefined') {\n assertIndexArray(gd, newIndices, 'newIndices');\n }\n\n // check currentIndices and newIndices are the same length if newIdices exists\n if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {\n throw new Error('current and new indices must be of equal length.');\n }\n\n}", "function checkMoveTracesArgs(gd, currentIndices, newIndices) {\n // check that gd has attribute 'data' and 'data' is array\n if(!Array.isArray(gd.data)) {\n throw new Error('gd.data must be an array.');\n }\n\n // validate currentIndices array\n if(typeof currentIndices === 'undefined') {\n throw new Error('currentIndices is a required argument.');\n } else if(!Array.isArray(currentIndices)) {\n currentIndices = [currentIndices];\n }\n assertIndexArray(gd, currentIndices, 'currentIndices');\n\n // validate newIndices array if it exists\n if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n newIndices = [newIndices];\n }\n if(typeof newIndices !== 'undefined') {\n assertIndexArray(gd, newIndices, 'newIndices');\n }\n\n // check currentIndices and newIndices are the same length if newIdices exists\n if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {\n throw new Error('current and new indices must be of equal length.');\n }\n}", "function checkAddTracesArgs(gd, traces, newIndices) {\n\t var i, value;\n\t\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\t\n\t // make sure traces exists\n\t if(typeof traces === 'undefined') {\n\t throw new Error('traces must be defined.');\n\t }\n\t\n\t // make sure traces is an array\n\t if(!Array.isArray(traces)) {\n\t traces = [traces];\n\t }\n\t\n\t // make sure each value in traces is an object\n\t for(i = 0; i < traces.length; i++) {\n\t value = traces[i];\n\t if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n\t throw new Error('all values in traces array must be non-array objects');\n\t }\n\t }\n\t\n\t // make sure we have an index for each trace\n\t if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n\t throw new Error(\n\t 'if indices is specified, traces.length must equal indices.length'\n\t );\n\t }\n\t}", "function checkAddTracesArgs(gd, traces, newIndices) {\n\t var i,\n\t value;\n\t\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\t\n\t // make sure traces exists\n\t if(typeof traces === 'undefined') {\n\t throw new Error('traces must be defined.');\n\t }\n\t\n\t // make sure traces is an array\n\t if(!Array.isArray(traces)) {\n\t traces = [traces];\n\t }\n\t\n\t // make sure each value in traces is an object\n\t for(i = 0; i < traces.length; i++) {\n\t value = traces[i];\n\t if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n\t throw new Error('all values in traces array must be non-array objects');\n\t }\n\t }\n\t\n\t // make sure we have an index for each trace\n\t if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n\t throw new Error(\n\t 'if indices is specified, traces.length must equal indices.length'\n\t );\n\t }\n\t}", "function checkAddTracesArgs(gd, traces, newIndices) {\n\t var i, value;\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // make sure traces exists\n\t if(typeof traces === 'undefined') {\n\t throw new Error('traces must be defined.');\n\t }\n\n\t // make sure traces is an array\n\t if(!Array.isArray(traces)) {\n\t traces = [traces];\n\t }\n\n\t // make sure each value in traces is an object\n\t for(i = 0; i < traces.length; i++) {\n\t value = traces[i];\n\t if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n\t throw new Error('all values in traces array must be non-array objects');\n\t }\n\t }\n\n\t // make sure we have an index for each trace\n\t if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n\t throw new Error(\n\t 'if indices is specified, traces.length must equal indices.length'\n\t );\n\t }\n\t}", "function checkAddTracesArgs(gd, traces, newIndices) {\n\t var i,\n\t value;\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if(!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // make sure traces exists\n\t if(typeof traces === 'undefined') {\n\t throw new Error('traces must be defined.');\n\t }\n\n\t // make sure traces is an array\n\t if(!Array.isArray(traces)) {\n\t traces = [traces];\n\t }\n\n\t // make sure each value in traces is an object\n\t for(i = 0; i < traces.length; i++) {\n\t value = traces[i];\n\t if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n\t throw new Error('all values in traces array must be non-array objects');\n\t }\n\t }\n\n\t // make sure we have an index for each trace\n\t if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n\t throw new Error(\n\t 'if indices is specified, traces.length must equal indices.length'\n\t );\n\t }\n\t}", "function checkAddTracesArgs(gd, traces, newIndices) {\n\t var i,\n\t value;\n\n\t // check that gd has attribute 'data' and 'data' is array\n\t if (!Array.isArray(gd.data)) {\n\t throw new Error('gd.data must be an array.');\n\t }\n\n\t // make sure traces exists\n\t if (typeof traces === 'undefined') {\n\t throw new Error('traces must be defined.');\n\t }\n\n\t // make sure traces is an array\n\t if (!Array.isArray(traces)) {\n\t traces = [traces];\n\t }\n\n\t // make sure each value in traces is an object\n\t for (i = 0; i < traces.length; i++) {\n\t value = traces[i];\n\t if (typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n\t throw new Error('all values in traces array must be non-array objects');\n\t }\n\t }\n\n\t // make sure we have an index for each trace\n\t if (typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n\t newIndices = [newIndices];\n\t }\n\t if (typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n\t throw new Error(\n\t 'if indices is specified, traces.length must equal indices.length'\n\t );\n\t }\n\t}", "function checkAddTracesArgs(gd, traces, newIndices) {\n var i, value;\n\n // check that gd has attribute 'data' and 'data' is array\n if (!Array.isArray(gd.data)) {\n throw new Error('gd.data must be an array.');\n }\n\n // make sure traces exists\n if (typeof traces === 'undefined') {\n throw new Error('traces must be defined.');\n }\n\n // make sure traces is an array\n if (!Array.isArray(traces)) {\n traces = [traces];\n }\n\n // make sure each value in traces is an object\n for (i = 0; i < traces.length; i++) {\n value = traces[i];\n if (typeof value !== 'object' || Array.isArray(value) || value === null) {\n throw new Error('all values in traces array must be non-array objects');\n }\n }\n\n // make sure we have an index for each trace\n if (typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n newIndices = [newIndices];\n }\n if (typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n throw new Error('if indices is specified, traces.length must equal indices.length');\n }\n }", "function checkAddTracesArgs(gd, traces, newIndices) {\n var i, value;\n\n // check that gd has attribute 'data' and 'data' is array\n if(!Array.isArray(gd.data)) {\n throw new Error('gd.data must be an array.');\n }\n\n // make sure traces exists\n if(typeof traces === 'undefined') {\n throw new Error('traces must be defined.');\n }\n\n // make sure traces is an array\n if(!Array.isArray(traces)) {\n traces = [traces];\n }\n\n // make sure each value in traces is an object\n for(i = 0; i < traces.length; i++) {\n value = traces[i];\n if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {\n throw new Error('all values in traces array must be non-array objects');\n }\n }\n\n // make sure we have an index for each trace\n if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {\n newIndices = [newIndices];\n }\n if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {\n throw new Error(\n 'if indices is specified, traces.length must equal indices.length'\n );\n }\n}", "function processChangesOnXAxis(eventdata) {\n\tconsole.log( 'Received plotly_relayout event data:' + JSON.stringify(eventdata));\n\tvar previousStart = viewerVars.start;\n\tvar previousEnd = viewerVars.end;\n\tif (('xaxis.range[0]' in eventdata && 'xaxis.range[1]' in eventdata)\n\t\t\t|| ('xaxis2.range[0]' in eventdata && 'xaxis2.range[1]' in eventdata)\n\t\t\t) {\n\t\tif('xaxis.range[0]' in eventdata && 'xaxis.range[1]' in eventdata) {\n\t\t\tviewerVars.start = moment(eventdata['xaxis.range[0]']).toDate();\n\t\t\tviewerVars.end = moment(eventdata['xaxis.range[1]']).toDate();\n\t\t} else if('xaxis2.range[0]' in eventdata && 'xaxis2.range[1]' in eventdata) {\n\t\t\tviewerVars.start = moment(eventdata['xaxis2.range[0]']).toDate();\n\t\t\tviewerVars.end = moment(eventdata['xaxis2.range[1]']).toDate();\n\t\t}\n\t\tvar previousDuration = previousEnd.getTime() - previousStart.getTime();\n\t\tvar duration = viewerVars.end.getTime() - viewerVars.start.getTime();\n\n\t\tif(viewerVars.currentBinningOperator.startsWith('errorbar')) {\n\t\t\tviewerVars.queryStart = viewerVars.start;\n\t\t\tviewerVars.queryEnd = viewerVars.end;\n\t\t\tfetchDataFromServerAndPlot(\"ReplaceTraces\");\n\t\t\treturn;\n\t\t}\n\t\tif (Math.abs(duration - previousDuration) < 10*1000) {\n\t\t\tconsole.log(\"Resolution stays the same; use extendTraces/prependTrace\");\n\t\t\tif(viewerVars.start < previousStart) {\n\t\t\t\t// We panned left\n\t\t\t\tviewerVars.queryStart = viewerVars.start;\n\t\t\t\tviewerVars.queryEnd = previousStart;\n\t\t\t\tfetchDataFromServerAndPlot(\"LeftPan\");\n\t\t\t} else {\n\t\t\t\t// We panned right\n\t\t\t\tviewerVars.queryStart = previousEnd;\n\t\t\t\tviewerVars.queryEnd = viewerVars.end;\n\t\t\t\tfetchDataFromServerAndPlot(\"RightPan\");\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.log(\"Change in resolution; deleting and replacing traces\");\n\t\t\tdetermineBinSize();\n\t\t\tviewerVars.queryStart = viewerVars.start;\n\t\t\tviewerVars.queryEnd = viewerVars.end;\n\t\t\tfetchDataFromServerAndPlot(\"ReplaceTraces\");\n\t\t\tif(duration == 7*60*1000) {\n\t\t\t\tconsole.log(\"Kicking off live mode..\");\n\t\t\t\tvar layoutChanges = {'xaxis' : { 'autorange' : true}};\n\t\t\t\tlayoutChanges.xaxis.rangeselector = viewerVars.selectorOptions;\n\t\t\t\tlayoutChanges.xaxis.domain = myDiv.layout.xaxis.domain;\n\t\t\t\tPlotly.relayout(myDiv, layoutChanges);\n\t\t\t\tviewerVars.liveModeTimer = setInterval(liveModeTick, 1*1000);\n\t\t\t} else {\n\t\t\t\tif(viewerVars.liveModeTimer != null) {\n\t\t\t\t\tclearInterval(viewerVars.liveModeTimer);\n\t\t\t\t\tviewerVars.liveModeTimer = null;\n\t\t\t\t\tvar layoutChanges = {'xaxis' : { 'autorange' : false}};\n\t\t\t\t\tlayoutChanges.xaxis.rangeselector = viewerVars.selectorOptions;\n\t\t\t\t\tlayoutChanges.xaxis.range = [viewerVars.start.getTime(), viewerVars.end.getTime()];\n\t\t\t\t\tlayoutChanges.xaxis.domain = myDiv.layout.xaxis.domain;\n\t\t\t\t\tPlotly.relayout(myDiv, layoutChanges);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if ('xaxis.range[0]' in eventdata) {\n\t\tconsole.log(\"We compressed the time scale on the left side\");\n\t\tviewerVars.start = moment(eventdata['xaxis.range[0]']).toDate();\n\t\tviewerVars.queryStart = viewerVars.start;\n\t\tviewerVars.queryEnd = previousStart;\n\t\tfetchDataFromServerAndPlot(\"LeftPan\");\n\t}\n}", "_checkArgs(args) {\n const unknown = complement(this.argids, args);\n if (unknown.length>0) {\n throw new Error(`unknown members of args - [${unknown}]`);\n }\n }", "piece_taken(args) {\n console.log(`${this.get_side(args.side)} taken at ${args.x}:${args.y}`);\n }", "onSameSide (...args) {\n let _x1 = null\n let _y1 = null\n let _x2 = null\n let _y2 = null\n switch (args.length) {\n case 2:\n if ((args[0] instanceof geom.Point) && (args[1] instanceof geom.Point)) {\n let p1 = args[0]\n let p2 = args[1]\n _x1 = p1.x()\n _y1 = p1.y()\n _x2 = p2.x()\n _y2 = p2.y()\n }\n break\n case 4:\n if ((typeof args[0]) === 'number' && (typeof args[1]) === 'number' && (typeof args[2]) === 'number' && (typeof args[3]) === 'number') {\n _x1 = args[0]\n _y1 = args[1]\n _x2 = args[2]\n _y2 = args[3]\n }\n break\n default: break\n }\n if (_x1 === null || _y1 === null || _x2 === null || _y2 === null) throw new Error('Exception: Invalid geom.Line.onSameSide arguments.')\n\n let ok = false\n if (geom.Util.epsilonEquals(this._x1, this._x2)) {\n if (this._x1 <= _x1 && this._x1 <= _x2) {\n ok = true\n }\n else\n if (_x1 <= this._x1 && _x2 <= this._x1) {\n ok = true\n }\n }\n else {\n let m = this.slope()\n // console.log('m = ' + m)\n let c = this.y(0, true) // this.yIntercept()\n let yy1 = m * _x1 + c\n let yy2 = m * _x2 + c\n if (_y1 <= yy1 && _y2 <= yy2) {\n ok = true\n }\n else\n if (yy1 <= _y1 && yy2 <= _y2) {\n ok = true\n }\n }\n return ok\n }", "function isNotSpreadArgument(arg) {\n return !t.isSpreadElement(arg);\n }", "function sanityCheck() {\n expectLT(graphView().startTime_, graphView().endTime_);\n expectLE(0, scrollbar().getPosition());\n expectLE(scrollbar().getPosition(), scrollbar().getRange());\n }", "function removeTraces() { // eslint-disable-line no-unused-vars\n chartState1 = [0, 0];\n chartState2 = [0, 0];\n chartTDID1 = ['', ''];\n chartTDID2 = ['', ''];\n traceArray1 = [0];\n traceArray2 = [0];\n numTraces1 = 0;\n numTraces2 = 0;\n chartTitles1 = ['', ''];\n chartTitles2 = ['', ''];\n}", "function checkArgsObject() {\n argsObject = argsArray[0];\n argsObject.inventoryCycles = Math.min(\n Math.max(1, parseInt(argsObject.inventoryCycles, 10)),\n\t\t\tvalueLimits.maxInventoryCycles\n\t\t);\n if (isNaN(argsObject.inventoryCycles)) {\n argsObject.inventoryCycles = defaultValues.inventoryCycles;\n }\n // not an allowed \"input args parameter\", but has to be set for the java call\n if(bInventoryUseBestAlgorithm === true){\n argsObject.inventoryCyclesForJava = 1;\n }else{\n argsObject.inventoryCyclesForJava = argsObject.inventoryCycles;\n }\n argsObject.retriesReadWrite = Math.min(\n Math.max(1, parseInt(argsObject.retriesReadWrite, 10)),\n valueLimits.maxRetriesReadWrite\n\t\t);\n if (isNaN(argsObject.retriesReadWrite)) {\n argsObject.retriesReadWrite = defaultValues.retriesReadWrite;\n }\n argsObject.inventoryCountThreshold = Math.min(\n Math.max(1, parseInt(argsObject.inventoryCountThreshold, 10)),\n valueLimits.inventoryCountThreshold\n );\n\t\tif (isNaN(argsObject.inventoryCountThreshold)) {\n argsObject.inventoryCountThreshold = defaultValues.inventoryCountThreshold;\n }\n [\"epcToRead\", \"epcToWrite\", \"dataToWrite\"].forEach(function (ELEM) {\n if (!isSet(argsObject[ELEM])) {\n argsObject[ELEM] = \"\";\n }\n });\n\n seenCountForFind = Math.min(\n Math.max(1, parseInt(argsObject.seenCountForFind, 10)),\n valueLimits.maxSeenCountForFind\n\t\t);\n if (isNaN(seenCountForFind)) {\n seenCountForFind = defaultValues.seenCountForFind;\n }\n seenCountAdvantageForFind = Math.min(\n Math.max(1, parseInt(argsObject.seenCountAdvantageForFind, 10)),\n valueLimits.maxSeenCountAdvantageForFind\n\t\t);\n if (isNaN(seenCountAdvantageForFind)) {\n seenCountAdvantageForFind = defaultValues.seenCountAdvantageForFind;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add `ch` to the current line breaking context, and returns whether a break opportunity exists before `ch`.
breakBefore(ch) { var value = lineBreakValue(ch.charCodeAt(0)); var breakBefore = breakBetweenLineBreakValues(this._lastLineBreakValue, value); this._lastLineBreakValue = value; return breakBefore; }
[ "advance (line, line_height) {\n let can_push = this.push(line);\n if (can_push){\n return this.createLine(line_height);\n }\n else {\n return false;\n }\n }", "hasPrecedingCharactersOnLine() {\n const bufferPosition = this.getBufferPosition();\n const line = this.editor.lineTextForBufferRow(bufferPosition.row);\n const firstCharacterColumn = line.search(/\\S/);\n\n if (firstCharacterColumn === -1) {\n return false;\n } else {\n return bufferPosition.column > firstCharacterColumn;\n }\n }", "addLineBreak () {\n const spaces = Array.from(document.querySelectorAll('#phrase li.space'));\n spaces.forEach(space => space.classList.remove('break'));\n while (spaces.some(space => (space.offsetLeft + 15) >= innerWidth)) {\n const reference = spaces.find(space => (space.offsetLeft + 15) >= innerWidth);\n if (reference) {\n const refIndex = spaces.indexOf(reference);\n const breakSpot = spaces[refIndex - 1];\n if (breakSpot) {\n breakSpot.classList.contains('break') ? spaces[refIndex].classList.add('break') : breakSpot.classList.add('break');\n } else break;\n }\n };\n if (document.querySelector('#phrase li:last-child').offsetLeft + 65 >= innerWidth &&\n spaces[spaces.length - 1]) {\n spaces[spaces.length - 1].classList.add('break');\n }\n }", "function is_linebreak(c) {\n return ((c > 0x0009 && c < 0x000E) // LINE FEED .. CARRIAGE RETURN\n || c === 0x0085 // NEXT LINE\n || c === 0x2028 // LINE SEPARATOR\n || c === 0x2029 // PARAGRAPH SEPARATOR\n );\n}", "static canBreakBetween(ch1, ch2) {\n return breakBetweenLineBreakValues(lineBreakValue(ch1.charCodeAt(0)), lineBreakValue(ch2.charCodeAt(0))) != null;\n }", "function isCollapsedLineBreak(br) {\n\t\tif (!isNamedHtmlElement(br, 'br')) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Add a zwsp after it and see if that changes the height of the nearest\n\t\t// non-inline parent. Note: this is not actually reliable, because the\n\t\t// parent might have a fixed height or something.\n\t\tvar ref = br.parentNode;\n\t\twhile ($_.getComputedStyle(ref).display == \"inline\") {\n\t\t\tref = ref.parentNode;\n\t\t}\n\n\t\tvar origStyle = {\n\t\t\theight: ref.style.height,\n\t\t\tmaxHeight: ref.style.maxHeight,\n\t\t\tminHeight: ref.style.minHeight\n\t\t};\n\n\t\tref.style.height = 'auto';\n\t\tref.style.maxHeight = 'none';\n\t\tif (!(Aloha.browser.msie && Aloha.browser.version < 8)) {\n\t\t\tref.style.minHeight = '0';\n\t\t}\n\t\tvar space = document.createTextNode('\\u200b');\n\t\tvar origHeight = ref.offsetHeight;\n\t\tif (origHeight == 0) {\n\t\t\tthrow 'isCollapsedLineBreak: original height is zero, bug?';\n\t\t}\n\t\tbr.parentNode.insertBefore(space, br.nextSibling);\n\t\tvar finalHeight = ref.offsetHeight;\n\t\tspace.parentNode.removeChild(space);\n\n\t\tref.style.height = origStyle.height;\n\t\tref.style.maxHeight = origStyle.maxHeight;\n\t\tif (!(Aloha.browser.msie && Aloha.browser.version < 8)) {\n\t\t\tref.style.minHeight = origStyle.minHeight;\n\t\t}\n\n\t\t// Allow some leeway in case the zwsp didn't create a whole new line, but\n\t\t// only made an existing line slightly higher. Firefox 6.0a2 shows this\n\t\t// behavior when the first line is bold.\n\t\treturn origHeight < finalHeight - 5;\n\t}", "function isCollapsedLineBreak(br) {\n if (!isHtmlElement(br, \"br\")) {\n return false;\n }\n\n // Add a zwsp after it and see if that changes the height of the nearest\n // non-inline parent. Note: this is not actually reliable, because the\n // parent might have a fixed height or something.\n var ref = br.parentNode;\n while (getComputedStyleProperty(ref, \"display\") == \"inline\") {\n ref = ref.parentNode;\n }\n var refStyle = ref.hasAttribute(\"style\") ? ref.getAttribute(\"style\") : null;\n ref.style.height = \"auto\";\n ref.style.maxHeight = \"none\";\n ref.style.minHeight = \"0\";\n var space = document.createTextNode(\"\\u200b\");\n var origHeight = ref.offsetHeight;\n if (origHeight == 0) {\n throw \"isCollapsedLineBreak: original height is zero, bug?\";\n }\n br.parentNode.insertBefore(space, br.nextSibling);\n var finalHeight = ref.offsetHeight;\n space.parentNode.removeChild(space);\n if (refStyle === null) {\n // Without the setAttribute() line, removeAttribute() doesn't work in\n // Chrome 14 dev. I have no idea why.\n ref.setAttribute(\"style\", \"\");\n ref.removeAttribute(\"style\");\n } else {\n ref.setAttribute(\"style\", refStyle);\n }\n\n // Allow some leeway in case the zwsp didn't create a whole new line, but\n // only made an existing line slightly higher. Firefox 6.0a2 shows this\n // behavior when the first line is bold.\n return origHeight < finalHeight - 5;\n }", "shouldFriendlyBreak( prevChar, lastInlineOffset, nextBreak, INNER_WIDTH ) {\n // We can't check if last glyph is break-line-friendly it does not exist\n if ( !prevChar || !prevChar.glyph ) return false\n // Next break-line-friendly glyph is inside boundary\n if ( lastInlineOffset + nextBreak < INNER_WIDTH ) return false\n // Characters to prioritize breaking line (eg: white space)\n const BREAK_ON = this.getBreakOn();\n // Previous glyph was break-line-friendly\n return BREAK_ON.indexOf( prevChar.glyph ) > -1\n }", "function insertLine (interactive = true) {\n if (!story.canContinue) {\n return Promise.resolve(false);\n }\n const line = story.Continue();\n const {elementType, classes} = decodeTags(story.currentTags);\n const elem = createLineElement(line, elementType, classes);\n if (interactive) {\n return new Promise(resolve => {\n const cb = oneTimeCB(resolve);\n elem.addEventListener('animationend', cb);\n setTimeout(cb, 2000);\n stageDiv.appendChild(elem);\n });\n } else {\n stageDiv.appendChild(elem);\n return Promise.resolve(true);\n }\n}", "checkToStartOfLine(test) {\n var n, tp;\n n = this.immutable();\n tp = n.textPosition();\n while (!n.isEmpty() && (test(n))) {\n if (differentLines(tp, n.textPosition())) {\n return true;\n }\n n = n.backwardChar();\n }\n return n.isEmpty();\n }", "shouldFriendlyBreak( prevChar, lastInlineOffset, nextBreak, INNER_WIDTH ) {\n\n // We can't check if last glyph is break-line-friendly it does not exist\n if ( !prevChar || !prevChar.glyph ) return false\n\n // Next break-line-friendly glyph is inside boundary\n if ( lastInlineOffset + nextBreak < INNER_WIDTH ) return false\n\n // Characters to prioritize breaking line (eg: white space)\n const BREAK_ON = this.getBreakOn();\n\n // Previous glyph was break-line-friendly\n return BREAK_ON.indexOf( prevChar.glyph ) > -1\n\n }", "function checkLineBreak() {\n\tlet criteriaBar = document.getElementById(\"criteriaBar\");\n\tlet appliedCriteria = document.getElementsByClassName(\"criterion\");\n\n\tfor (let i = 0; i < appliedCriteria.length; i++) {\n\t\tif (appliedCriteria[i].offsetHeight > 2 * font) {\n\t\t\tcriteriaBar.insertBefore(document.createElement(\"br\"), appliedCriteria[i]);\n\t\t}\n\t}\n}", "function extendCommentToNextLine(line, pos) {\n if (line.trim().startsWith(';') && line.slice(pos).trim().length && line.slice(0, pos).trim().length) {\n return true;\n }\n return false;\n}", "function is_wrapped_in_character(line, character) {\n return line[0] === character && line[line.length - 1] === character;\n}", "isAtBeginningOfLine() {\n return this.getBufferPosition().column === 0;\n }", "isCurrentLine(lineNum) {\n if (this.isEditing) {\n return false;\n }\n return this.currentLine === lineNum;\n }", "function isLineTerminator(ch) {\n return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);\n }", "cursorPrecedingLine(params) {\n this.cursorUp(params);\n this._bufferService.buffer.x = 0;\n return true;\n }", "function isCollapsedLineBreak(br) {\n if (!isHtmlElement(br, \"br\")) {\n return false;\n }\n\n // Add a zwsp after it and see if that changes the height of the nearest\n // non-inline parent. Note: this is not actually reliable, because the\n // parent might have a fixed height or something.\n var ref = br.parentNode;\n while (getComputedStyle(ref).display == \"inline\") {\n ref = ref.parentNode;\n }\n var refStyle = ref.hasAttribute(\"style\") ? ref.getAttribute(\"style\") : null;\n ref.style.height = \"auto\";\n ref.style.maxHeight = \"none\";\n ref.style.minHeight = \"0\";\n var space = document.createTextNode(\"\\u200b\");\n var origHeight = ref.offsetHeight;\n if (origHeight == 0) {\n throw \"isCollapsedLineBreak: original height is zero, bug?\";\n }\n br.parentNode.insertBefore(space, br.nextSibling);\n var finalHeight = ref.offsetHeight;\n space.parentNode.removeChild(space);\n if (refStyle === null) {\n // Without the setAttribute() line, removeAttribute() doesn't work in\n // Chrome 14 dev. I have no idea why.\n ref.setAttribute(\"style\", \"\");\n ref.removeAttribute(\"style\");\n } else {\n ref.setAttribute(\"style\", refStyle);\n }\n\n // Allow some leeway in case the zwsp didn't create a whole new line, but\n // only made an existing line slightly higher. Firefox 6.0a2 shows this\n // behavior when the first line is bold.\n return origHeight < finalHeight - 5;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate spinner html element. Spinner html element must follow template from
generateSpinnerElement() { let emptyDivKey = Object.keys(this.numberOfEmptyDivForSpinner).find(element => element === this.options.spinnerIcon); let emptyDivElement = this.generateEmptyDivElement(this.numberOfEmptyDivForSpinner[emptyDivKey]); this.spinner = `<div style="color: ${this.options.spinnerColor}" class="la-${ this.options.spinnerIcon } la-${this.options.spinnerSize}">${ emptyDivElement }</div>` }
[ "renderSpinner() {\n const markup = `\n <div class=\"spinner\">\n <div></div>\n <div></div>\n <div></div>\n </div>`;\n\n this._clear();\n this._display(markup);\n }", "function getSpinner(){\n\treturn '<div style=\"text-align: center\"><i class=\"fa fa-spinner fa-spin\" style=\"font-size:40px\"></i></div>';\n}", "renderSpinner() {\n const markupSpinner = `\n <div class=\"loading d-flex justify-content-center align-items-center\">\n <div class=\"d-flex align-items-center flex-column\">\n <div class=\"spinner-border mr-3\" role=\"status\" aria-hidden=\"true\"></div>\n <strong class=\"mt-4\"> Please wait while the countries are loading...</strong>\n </div>\n </div>`;\n\n this._clear();\n this._parentElement.insertAdjacentHTML(\"afterbegin\", markupSpinner);\n }", "function spinner() {\n return createElement(\"div\", { class: \"spinner\" });\n}", "renderSpinner() {\n const markup = `\n <div class=\"spinner\">\n <svg>\n <use href=\"${icons}#icon-loader\"></use>\n </svg>\n </div>\n `;\n this._parentElement.innerHTML = '';\n this._parentElement.insertAdjacentHTML('afterBegin', markup);\n }", "function spinnerHtml(id) {\r\n var myHtml = \"\";\r\n myHtml = '<div id=\"' + \"loader\" + id + '\" class=\"loader center-block\">';\r\n myHtml += '</div>';\r\n myHtml += '<br/>';\r\n return myHtml;\r\n}", "createSpinner() {\n\t\t$(\"body\").append($(\"<div/>\").addClass(\"aimeos-spinner\"));\n\t}", "function loadingSpinner(){\n\tvar html = '';\n\thtml += '<div class=\"spinner-circle\">';\n\thtml += \t'<div class=\"spinner-circle1 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle2 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle3 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle4 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle5 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle6 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle7 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle8 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle9 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle10 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle11 spinner-child\"></div>';\n\thtml += \t'<div class=\"spinner-circle12 spinner-child\"></div>';\n\thtml += '</div>';\n\t\n\treturn html;\n}", "function setSpinner(btn) {\n btn.html('<i class=\"fa fa-spinner fa-spin\"></i>');\n}", "renderLoading() {\n return (this.renderTemplate('loading', null) ||\n html `\n <div class=\"message-parent\">\n <mgt-spinner></mgt-spinner>\n <div label=\"loading-text\" aria-label=\"loading\" class=\"loading-text\">\n ${this.strings.loadingMessage}\n </div>\n </div>\n `);\n }", "function createSpinner() {\n const spinner = document.createElement('div');\n spinner.setAttribute('class', 'spinner');\n\n addDiv(spinner, 'rect1');\n addDiv(spinner, 'rect2');\n addDiv(spinner, 'rect3');\n addDiv(spinner, 'rect4');\n addDiv(spinner, 'rect5');\n\n return spinner;\n }", "function Spinner() { return this.initialize.apply(this, _slice.call(arguments)); }", "getSpinner() {\n return this.selector('#' + this.id);\n }", "function makeSpinner(element){\n\t\tvar chars = '|/-\\\\',\n\t\t\ti = 0,\n\t\t\tinterval;\n\t\t\t\n\t\telement.style.cursor = 'help';\n\t\telement.style.textAlign = 'center';\n\t\telement.title = 'Loading layer...';\n\t\tapplySpinnerCheckboxStyle(element);\n\t\t\t\n\t\tinterval = setInterval(function(){\n\t\t\ti = i === chars.length - 1 ? 0 : i + 1;\n\t\t\telement.innerHTML = chars[i];\n\t\t}, 200);\n\t\t\n\t\telement.stopSpinner = function(){\n\t\t\tclearInterval(interval);\n\t\t};\n\t}", "function makeSpin(elem) {\n\n return spinner;\n}", "function Spinner() {\n var _this = _super.call(this) || this;\n _this.addClass('jp-Spinner');\n _this.node.tabIndex = -1;\n var content = document.createElement('div');\n content.className = 'jp-SpinnerContent';\n _this.node.appendChild(content);\n return _this;\n }", "showSpinner() {\n showSpinner(this.element);\n }", "function createSpinner(view) {\n spinnerContainer = view.$el;\n\n spinner = new SpinnerWidget({\n \"container\": spinnerContainer\n });\n }", "function createSpinner(){\n var alignContent = document.createElement('div');\n alignContent.style.zIndex = \"2200\";\n alignContent.style.position = \"absolute\";\n alignContent.style.left = \"50%\";\n alignContent.style.top = \"300px\";\n alignContent.classList.add('d-flex');\n alignContent.classList.add('justify-content-center');\n var spinner = document.createElement('div');\n spinner.classList.add('spinner-border');\n spinner.setAttribute(\"role\", \"status\");\n var spanSpin = document.createElement('span');\n spinner.appendChild(spanSpin);\n alignContent.appendChild(spinner);\n return alignContent;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
merge function that takes in an array with a low mid and high to merge on uses a copied array to help merge
function merge(array, copy, low, mid, hi) { for(var x = low; x <= hi; x++) { copy[x] = array[x] } var i = low, j = mid+1; for(var k = low; k <= hi; k++) { if(i > mid) { array[k] = copy[j++] } // if we have no more in the lower array else if(j > hi) { array[k] = copy[i++] } // if we have no more in the higher array else if(copy[j] > copy[i]) { array[k] = copy[i++] } else { array[k] = copy[j++] } } }
[ "static _merge(arr, aux, lo, mid, hi) {\n // Copy to aux[]\n for (let k = lo; k <= hi; k++) {\n aux[k] = arr[k]; \n }\n\n // Merge back to arr[]\n let i = lo;\n let j = mid + 1;\n for (let k = lo; k <= hi; k++) {\n if (i > mid) {\n arr[k] = aux[j++];\n } else if (j > hi) {\n arr[k] = aux[i++];\n } else if (less(aux[j], aux[i])) {\n arr[k] = aux[j++];\n } else {\n arr[k] = aux[i++];\n }\n }\n }", "function merge(a, aux, lo, mid, hi) {\n // copy to aux\n for (var k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n var i = lo;\n var j = mid + 1;\n for (var k = lo; k <= hi; k++) {\n var cmp = compare(aux[j], aux[i]);\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (cmp < 0) a[k] = aux[j++];\n else a[k] = aux[i++];\n }\n}", "function mergeSort(a, aux, lo, hi) {\n if (hi <= lo) return;\n var mid = Math.floor(lo + (hi - lo) / 2);\n mergeSort(a, aux, lo, mid);\n mergeSort(a, aux, mid + 1, hi);\n merge(a, aux, lo, mid, hi);\n}", "function mergeSort(mainArray, startIndex, endIndex, copiedArray, animations) {\n // Return if the same element\n if (startIndex === endIndex)\n return;\n\n // Find midpoint\n const midIndex = Math.floor((startIndex + endIndex) / 2);\n\n // Merge bottom half \n mergeSort(copiedArray, startIndex, midIndex, mainArray, animations);\n // Merge top half\n mergeSort(copiedArray, midIndex + 1, endIndex, mainArray, animations);\n merge(mainArray, startIndex, midIndex, endIndex, copiedArray, animations);\n}", "mergeSortWithSentinel(arr = []) {\n function mergeCall(arr, start, end) {\n if (start >= end) {\n return\n }\n let mid = (start + end) / 2 | 0\n mergeCall(arr, start, mid)\n mergeCall(arr, mid + 1, end)\n merge(arr, start, mid, end)\n }\n function merge(arr, left, mid ,right) {\n let i = 0, j = 0\n // 把数组拷贝到两份临时数组, 比对回填到原数组. 两份数组最后放一个无穷大数做哨兵\n let tempLeft = arr.slice(left, mid + 1)\n tempLeft[tempLeft.length] = Number.POSITIVE_INFINITY\n let tempRight = arr.slice(mid + 1, right + 1)\n tempRight[tempRight.length] = Number.POSITIVE_INFINITY\n\n for (let k = left; k <= right; k++) {\n if (tempLeft[i] <= tempRight[j]) {\n arr[k] = tempLeft[i++]\n } else {\n arr[k] = tempRight[j++]\n }\n }\n }\n mergeCall(arr, 0, arr.length - 1)\n }", "function mergerSort(arr){\n if(arr.length <= 1) return arr;\n var mid = Math.floor(arr.length/2)\n var left = mergerSort(arr.slice(0,mid))//calls the function and add the call stcak and return array each time incremental ad poped and added into array\n var right = mergerSort(arr.slice(mid))\n \n return mergeArrays(left,right);\n \n //function to compare and merge arrays\n function mergeArrays(arr1,arr2){\n var result = [];\n var i = 0;\n var j = 0;\n while(i < arr1.length && j < arr2.length){\n if(arr1[i] < arr2[j]){\n result.push(arr1[i])\n i++\n }else{\n result.push(arr2[j])\n j++\n }\n }\n while(i < arr1.length){\n result.push(arr1[i])\n i++\n }\n while(j < arr2.length){\n result.push(arr2[j])\n j++\n }\n return result;\n }\n\n}", "function mergeSort(arr){\n var len = arr.length;\n if(len <2)\n return arr;\n var mid = Math.floor(len/2),\n left = arr.slice(0,mid),\n right =arr.slice(mid);\n //send left and right to the mergeSort to broke it down into pieces\n //then merge those\n return merge(mergeSort(left),mergeSort(right));\n}", "function merge_sort(array){\n if (array.length<=1){\n return array;\n }\n \n let mid = Math.floor(array.length/2);\n let left = merge_sort(array.slice(0,mid)); //O(log(n))\n let right = merge_sort(array.slice(mid,array.length)); //O(log(n))\n return merge(left,right); //O(n)\n}", "async function merge(array, left, middle, right) {\n // length of the left subarray\n let leftLength = middle - left;\n\n // copy data from the left subarray into a temp array\n let leftArr = [];\n for (let i = 0; i < leftLength; i++) {\n leftArr[i] = array[left + i];\n }\n\n // initial indexes for the temp arrays\n let leftIndex = 0;\n let rightIndex = middle;\n\n // the starting index for the resulting sorted subarray\n let arrayIndex = left;\n\n // merge the temp arrays\n while (leftIndex < leftLength && rightIndex < right) {\n if (leftArr[leftIndex] <= array[rightIndex]) {\n // add element from the left subarray\n array[arrayIndex] = leftArr[leftIndex];\n leftIndex++;\n await sleep();\n } else {\n // add element from the right subarray\n array[arrayIndex] = array[rightIndex];\n rightIndex++;\n await sleep();\n }\n arrayIndex++;\n }\n\n // copy remaining elements of the temp arrays\n while (leftIndex < leftLength) {\n array[arrayIndex] = leftArr[leftIndex];\n leftIndex++;\n arrayIndex++;\n await sleep();\n }\n }", "function mergeSort(array){\n let midpoint = array.length / 2\n let firstHalf = array.slice(0, midpoint)\n let secondHalf = array.slice(midpoint, array.length)\n let sorted;\n\n\n if(firstHalf < 2){\n return array \n } else {\n sorted = merge(mergeSort(firstHalf), mergeSort(secondHalf))\n }\n return sorted\n}", "function merge(blocks, left, mid, right) {\n \n //create two temporary arrays\n let leftarr = []\n let rightarr = []\n\n //copy data to temp arrays\n for (let i = left; i <= right; i++) {\n leftarr[i - left] = blocks[i]\n }\n for (let i = mid + 1; i <= right; i++) {\n rightarr[i - mid - 1] = blocks[i]\n }\n\n let indexofleft = 0\n let indexofright = 0\n\n let indexofmerged = left\n\n //merge the temp arrays back into the blocks array\n while (indexofleft < leftarr.length && indexofright < rightarr.length) {\n if (leftarr[indexofleft].height < rightarr[indexofright].height) {\n blocks[indexofmerged] = leftarr[indexofleft]\n indexofleft++\n } else {\n blocks[indexofmerged] = rightarr[indexofright]\n indexofright++\n }\n indexofmerged++\n }\n //copy the rest of the left array into the blocks array if there is any left\n while (indexofleft < leftarr.length) {\n blocks[indexofmerged] = leftarr[indexofleft]\n indexofleft++\n indexofmerged++\n }\n //copy the rest of the right array into the blocks array if there is any left\n while (indexofright < rightarr.length) {\n blocks[indexofmerged] = rightarr[indexofright]\n indexofright++\n indexofmerged++\n }\n}", "function mergeArrays(array, startIdx, midIdx, endIdx, copyArray, animations) {\n let k = startIdx;\n let i = startIdx;\n let j = midIdx + 1;\n while (i <= midIdx && j <= endIdx) {\n animations.push([i, j, startIdx, endIdx]);\n animations.push([i, j, startIdx, endIdx]);\n // third array is pushed to animations array to know which value to put in the kth position of the main array\n if (copyArray[i] <= copyArray[j]) {\n animations.push([k, copyArray[i], startIdx, endIdx]);\n array[k++] = copyArray[i++];\n } else {\n animations.push([k, copyArray[j], startIdx, endIdx]);\n array[k++] = copyArray[j++];\n }\n }\n\n while (i <= midIdx) {\n animations.push([i, i, startIdx, endIdx]);\n animations.push([i, i, startIdx, endIdx]);\n animations.push([k, copyArray[i], startIdx, endIdx]);\n array[k++] = copyArray[i++];\n }\n while (j <= endIdx) {\n animations.push([j, j, startIdx, endIdx]);\n animations.push([j, j, startIdx, endIdx]);\n animations.push([k, copyArray[j], startIdx, endIdx]);\n array[k++] = copyArray[j++];\n }\n}", "function mergeSort(arr) {\n let arrLen = arr.length;\n if (arrLen <= 1) return arr;\n let mid = Math.floor(arrLen / 2);\n let arr1 = mergeSort(arr.slice(0, mid));\n let arr2 = mergeSort(arr.slice(mid));\n return mergeSortedArrays(arr1, arr2);\n}", "function mergeSortArr(arr){\n if (arr.length<=1){\n return arr\n }\n let mid = Math.floor(arr.length/2)\n var leftArr = arr.slice(0,mid);\n var rightArr = arr.slice(mid);\n\n return combineArrs(mergeSortArr(leftArr),mergeSortArr(rightArr))\n}", "function mergeSort (arr, descending=false) {\n if (arr.length == 1) return arr;\n //if there's only two value around we can't return 0 to the divider, that produce a 0 which aren't really hekoting \n let divider = arr.length >> 1 | 0;\n if (divider == 0) divider++;\n //dividing the array to two parts\n let left = mergeSort(arr.splice(0, divider), descending);\n arr = mergeSort(arr, descending);\n //using recursion to continously dividing the array\n return merge (left, arr, descending);\n}", "function mergeVirtualSeq(seq, left, middle, right, tmpArray) {\n let a = left;\n let b = middle+1;\n\n let k = 0;\n // console.log('a: ', a, ': ', 'b: ', b);\n\n while (a <= middle && b <= right) {\n if (seq[a] < seq[b]) {\n tmpArray[k] = seq[a];\n a++;\n } else {\n tmpArray[k] = seq[b];\n b++;\n }\n k++;\n }\n\n while (a <= middle) {\n tmpArray[k] = seq[a];\n a++;\n k++;\n }\n while (b <= right) {\n tmpArray[k] = seq[b];\n b++;\n k++;\n }\n\n for (let i = 0; i <= right-left; i++) {\n seq[i+left] = tmpArray[i];\n }\n // console.log('tmpArray: ', tmpArray);\n // console.log('seq: ', seq);\n}", "function merge(arr,l,m,r) {\n\n\n\tvar i,j,k\n\tvar n1 = m - l+1; //get length of left portion of array\n\tvar n2 = r - m; //get length of right portion of array\n\n\t//create temp arrays\n\tvar L = [];\n\tvar R = [];\n\n\t//copy data into temp arrays\n\tfor (i = 0; i < n1; i++) {\n\t\tL[i] = arr[l + i];\n\t}\n\n\tfor (j = 0; j < n2; j++) {\n\t\tR[j] = arr[m + 1 + j];\n\t}\n\n\t//merge the temp arrays back into arr[l..r]\n\ti = 0; //initial index of first subarray\n\tj = 0; //initial index of second subarray\n\tk = l; //initial index of merged subarray\n\n\twhile (i < n1 && j < n2) {\n\n\t\tif(L[i] <= R[j]) {\n\t\t\tarr[k] = L[i];\n\t\t\ti++;\n\t\t}else {\n\n\t\t\tarr[k] = R[j];\n\t\t\tj++;\n\t\t}\n\t\tk++;\n\n\t}\n\n\t//copy the remaining elements of L[], if there are any\n\twhile (i < n1) {\n\t\tarr[k] = L[i];\n\t\ti++;\n\t\tk++;\n\n\t}\n\n\t//copy the remaining elements of R[] if there are any\n\twhile (j < n2) {\n\t\tarr[k] = R[j];\n\t\tj++;\n\t\tk++;\n\t}\n}", "function mergeSorted (array1, array2) {\n\n}", "mergeSort(arr, l, r) { \n if (l < r){\n let m = Math.floor(l + (r - l) / 2)\n \n // # Sort first and second halves \n this.mergeSort(arr, l, m); \n this.mergeSort(arr, m + 1, r);\n l = 0 \n tStack.add([...arr])\n this.merge(arr, l, m, r); \n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
implement getElementsByAttribute() naive approach: grab all of the elements in the DOM, then looping through all of them and checking attributes faster approach: checking attributes as we grab every element (DFS) refer to dommanipulation.html
function getElementsByAttribute(attr) { var found = []; function checkNode(node) { // check if node has children (remember [] returns true) if(node && node.getAttribute) { if(node.getAttribute(attr)) { found.push(node); } if(node.childNodes && node.childNodes.length) { for(let i = 0; i < node.childNodes.length; i++) { let ele = node.childNodes[i]; checkNode(ele); } } } } checkNode(document.body); return found; }
[ "getElementsByAttribute(name, value) {\n return this.getElementsBy(elem => {\n if (elem.hasAttribute(name)) {\n if (value === undefined) {\n return true;\n } else {\n return elem.getAttribute(name) === value;\n }\n }\n return false;\n });\n }", "function funcElementsByAttributes(arrAttr, node, func){\n\tif(node == null)\n\t\tnode = window.document;\n\t\n\tif(node.attributes){\n\t\tvar b = true;\n\t\tfor(var j in arrAttr){\n\t\t\tif((j == \"value\")){ \n\t\t\t\tif(node.value != arrAttr[j].toString())\t\n\t\t\t\t\tb = false;\n\t\t\t}\n\t\t\telse{ \n\t\t\t\ttry{\n\t\t\t\tif(node.getAttribute(j) != arrAttr[j])\n\t\t\t\t\tb = false;\n\t\t\t\t}catch(e){alert(e.message)}\n\t\t\t}\n\t\t}\n\t\tif(b)\n\t\t\tfunc(node);\n\t}\n\t\n\tfor(var i in node.childNodes){\n\t\tif(node.childNodes[i].nodeType == 1){\n\t\t\tfuncElementsByAttributes(arrAttr, node.childNodes[i], func);\n\t\t}\n\t}\n}", "function xGetElementsByAttribute(sTag, sAtt, sRE, fn)\r\n{\r\n var a, list, found = new Array(), re = new RegExp(sRE, 'i');\r\n list = xGetElementsByTagName(sTag);\r\n for (var i = 0; i < list.length; ++i) {\r\n a = list[i].getAttribute(sAtt);\r\n if (!a) {a = list[i][sAtt];}\r\n if (typeof(a)=='string' && a.search(re) != -1) {\r\n found[found.length] = list[i];\r\n if (fn) fn(list[i]);\r\n }\r\n }\r\n return found;\r\n}", "function parseAttributes( domObj ){\n var atts = domObj.attributes;\n for (var i=0, l=atts.length; i<l; i++){\n if ( atts[i].value.match(badNames) || atts[i].value.match(badUrls) ){\n console.log(\"removing:\", atts[i].value)\n return true;\n }\n }\n return false;\n}", "function xGetElementsByAttribute(sTag, sAtt, sRE, fn)\n{\n var a, list, found = new Array(), re = new RegExp(sRE, 'i');\n list = xGetElementsByTagName(sTag);\n for (var i = 0; i < list.length; ++i) {\n a = list[i].getAttribute(sAtt);\n if (!a) {a = list[i][sAtt];}\n if (typeof(a)=='string' && a.search(re) != -1) {\n found[found.length] = list[i];\n if (fn) fn(list[i]);\n }\n }\n return found;\n}", "function walkTheDOMWithAttributes(node,func,depth,returnedFromParent) {\r\n var root = node || window.document;\r\n returnedFromParent = func(root,depth++,returnedFromParent);\r\n if (root.attributes) {\r\n for(var i=0; i < root.attributes.length; i++) {\r\n walkTheDOMWithAttributes(root.attributes[i],func,depth-1,returnedFromParent);\r\n }\r\n }\r\n if(root.nodeType != ADS.node.ATTRIBUTE_NODE) {\r\n node = root.firstChild;\r\n while(node) {\r\n walkTheDOMWithAttributes(node,func,depth,returnedFromParent);\r\n node = node.nextSibling;\r\n }\r\n }\r\n }", "function getNodesByAttribute(attr, attrVal) {\r\n var nodes = [];\r\n var allNodes = document.getElementsByTagName(\"*\");\r\n for (i=0; i < allNodes.length; i++) {\r\n if (allNodes[i].hasAttribute(\"name\") == true && allNodes[i].getAttribute(\"name\") = attrVal) {\r\n elems.push(allNodes[i]);\r\n }\r\n }\r\n return nodes;\r\n}", "function getCustomAttribute() {\r\n let elements = document.getElementsByTagName(\"*\"); //(\"[data-customAttr]\");\r\n for (let element of elements)\r\n if (element.hasAttribute(\"data-customAttr\")) {\r\n console.log(element.getAttribute(\"data-customAttr\"));\r\n console.log(element);\r\n console.log(\"--\");\r\n }\r\n}", "function getAllElementsWithAttribute(nodes, attributeName, attributeValue) {\r\n var matchingElements = [];\r\n for (var i = 0, n = nodes.length; i < n; i++) {\r\n if (nodes[i].attributes && nodes[i].getAttribute(attributeName) == attributeValue) {\r\n // Element exists with attribute. Add to array.\r\n matchingElements.push(nodes[i]);\r\n }\r\n }\r\n return matchingElements;\r\n}", "function BuildHTMLAttributeTable() {\n var nodeMap = gElement.attributes;\n var i;\n if (nodeMap.length > 0) {\n var added = false;\n for (i = 0; i < nodeMap.length; i++) {\n let name = nodeMap[i].name.trim().toLowerCase();\n if (\n CheckAttributeNameSimilarity(nodeMap[i].nodeName, HTMLAttrs) ||\n name.startsWith(\"on\") ||\n name == \"style\"\n ) {\n continue; // repeated or non-HTML attribute, ignore this one and go to next\n }\n if (\n !name.startsWith(\"_moz\") &&\n AddTreeItem(name, nodeMap[i].value, \"HTMLAList\", HTMLAttrs)\n ) {\n added = true;\n }\n }\n\n if (added) {\n SelectHTMLTree(0);\n }\n }\n}", "function CLC_GetDescendentNodesWithAttribute(targObj, targAttributeName, targAttributeValue){\r\n var matchingNodes = new Array();\r\n var descendents = targObj.getElementsByTagName('*');\r\n for (var i=0; i<descendents.length; i++){\r\n if (descendents[i].getAttribute && (descendents[i].getAttribute(targAttributeName) == targAttributeValue)){\r\n matchingNodes.push(descendents[i]);\r\n } \r\n }\r\n return matchingNodes;\r\n }", "function getAllMetaElementsWithAttribute(attribute) {\n\tvar matchingElements = [];\n\tvar metaElements = document.getElementsByTagName(\"meta\");\n\t\n\tfor (var i = 0; i < metaElements.length; i++) { //Loop through every element in the array and check for the \"name\" attribute and that it matches our parameter. If found, add the element to matchingElements.\n\t\tif (metaElements[i].getAttribute(\"name\") && metaElements[i].getAttribute(\"name\").toLowerCase() == attribute)\n\t\t\tmatchingElements.push(metaElements[i]);\n\t}\n\t\n\treturn matchingElements;\n}", "async loadAttributes () {\n //for (const [attr, val] of Object.entries(allAttributeSetters(this.elem)))\n Object.entries(allAttributeSetters(this.elem)).forEach(async ([attr, val]) =>\n attributes(this.elem)[attr] = await this.evaluate(val) || '')\n }", "function getElementsByAttribute(name, value) {\n\tvar result = [],\n\t i =0,\n\t temp,\n\t att= null, \n\t children = this.getElementsByTagName(\"*\"),\n\t\tvalue = value || \"*\";\n\t\n\tif (name ) {\n\t\t//if ()\n\t\tfor (i=0; i < children.length; i++) {\n\t\t\ttemp = children[i];\n\t\t//\tif (temp.nodeType == 1) {\n\t\t\tif (temp.hasAttribute(name)) {\n\t\t\t\tif (value !== \"*\") {\n\t\t\t\t\tatt = temp.getAttribute(name);\n\t\t\t\t\tif (att && att.toLowerCase() === value.toLowerCase()) {\n\t\t\t\t\t\tresult.push(temp);\t\t\t\t\t\n\t\t\t\t\t}\t\n\t\t\t\t} else {\n\t\t\t\t\tresult.push(temp);\n\t\t\t\t}\n\t\t\t}\t\t\t\t\n\t\t//\t}\n\t\t}\n\t\treturn result;\n\t}\n\t// name attribute not provided \n\treturn null;\t\n}", "elementAndChildren(el, attr) {\n const all_elements = Array.from(el.getElementsByTagName('*'))\n all_elements.push(el)\n const toAttrMatch = (acc, child) => {\n if (child.attributes.hasOwnProperty(attr)) {\n acc.push(child)\n return acc\n } else {\n return acc\n }\n }\n\n return all_elements.reduce(toAttrMatch, [])\n }", "validAttribute(tag, attribute) {\n if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {\n for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {\n if (attribute === Strophe.XHTML.attributes[tag][i]) {\n return true;\n }\n }\n }\n\n return false;\n }", "function has_attributes(node, all_attrs)\n\t{\n\t\tvar had_attrs = [];\n\t\tif ( node.nodeType == Util.Node.ELEMENT_NODE )\n\t\t{\n\t\t\tfor ( var i = 0; i < all_attrs.length; i++ )\n\t\t\t{\n\t\t\t\t// Sometimes in IE node.getAttribute throws an \"Invalid argument\"\n\t\t\t\t// error here. I have _no_ idea why, but we want to catch it\n\t\t\t\t// here so that the rest of the tests run. XXX figure out why?\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( node.getAttribute(all_attrs[i]) != null )\n\t\t\t\t\t\thad_attrs.push(all_attrs[i]);\n\t\t\t\t}\n\t\t\t\tcatch(e) { /*mb('error in has_attributes: [node, e.message]: ', [node, e.message]);*/ }\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ( had_attrs.length > 0 )\n\t\t\t? had_attrs\n\t\t\t: false;\n\t}", "function Xml_HasAttribute(objNode,strAttribute)\r\n{\r\n return !Aux_IsNullOrEmpty(objNode.getAttribute(strAttribute));\r\n}", "function getElementByAttributeValue(attribute, value)\n{\n var allElements = document.getElementsByTagName('*');\n for (var i = 0; i < allElements.length; i++)\n {\n if (allElements[i].getAttribute(attribute) == value)\n {\n return allElements[i];\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }