query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Sends initial Socks v4 handshake request.
sendSocks4InitialHandshake() { const userId = this._options.proxy.userId || ''; const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(0x04); buff.writeUInt8(constants_1.SocksCommand[this._options.command]); buff.writeUInt16BE(this._options.destination.port); // Socks 4 (IPv4) if (net.isIPv4(this._options.destination.host)) { buff.writeBuffer(ip.toBuffer(this._options.destination.host)); buff.writeStringNT(userId); // Socks 4a (hostname) } else { buff.writeUInt8(0x00); buff.writeUInt8(0x00); buff.writeUInt8(0x00); buff.writeUInt8(0x01); buff.writeStringNT(userId); buff.writeStringNT(this._options.destination.host); } this._nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; this._socket.write(buff.toBuffer()); }
[ "sendSocks4InitialHandshake() {\n const userId = this.options.proxy.userId || '';\n const buff = new smart_buffer_1.SmartBuffer();\n buff.writeUInt8(0x04);\n buff.writeUInt8(constants_1.SocksCommand[this.options.command]);\n buff.writeUInt16BE(this.options.destination.port);\n // Socks 4 (IPv4)\n if (net.isIPv4(this.options.destination.host)) {\n buff.writeBuffer(ip.toBuffer(this.options.destination.host));\n buff.writeStringNT(userId);\n // Socks 4a (hostname)\n }\n else {\n buff.writeUInt8(0x00);\n buff.writeUInt8(0x00);\n buff.writeUInt8(0x00);\n buff.writeUInt8(0x01);\n buff.writeStringNT(userId);\n buff.writeStringNT(this.options.destination.host);\n }\n this.nextRequiredPacketBufferSize =\n constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;\n this.socket.write(buff.toBuffer());\n }", "sendSocks5InitialHandshake() {\n const buff = new smart_buffer_1.SmartBuffer();\n const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];\n if (this.options.proxy.userId || this.options.proxy.password) {\n supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);\n }\n if (this.options.proxy.custom_auth_method !== void 0) {\n supportedAuthMethods.push(this.options.proxy.custom_auth_method);\n }\n buff.writeUInt8(5);\n buff.writeUInt8(supportedAuthMethods.length);\n for (const authMethod of supportedAuthMethods) {\n buff.writeUInt8(authMethod);\n }\n this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;\n this.socket.write(buff.toBuffer());\n this.setState(constants_1.SocksClientState.SentInitialHandshake);\n }", "sendSocks5InitialHandshake() {\n const buff = new smart_buffer_1.SmartBuffer();\n buff.writeUInt8(0x05);\n buff.writeUInt8(2);\n buff.writeUInt8(constants_1.Socks5Auth.NoAuth);\n buff.writeUInt8(constants_1.Socks5Auth.UserPass);\n this._nextRequiredPacketBufferSize =\n constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;\n this._socket.write(buff.toBuffer());\n this.state = constants_1.SocksClientState.SentInitialHandshake;\n }", "_sendHandshakeRequest() {\n let packet = {\n \"cType\": contentType.HANDSHAKE,\n \"hType\": handshakeType.CLIENT_HELLO,\n \"epoch\": 0,\n \"headerSeq\": 0,\n \"sessionId\": 0,\n \"cookie\": 0,\n \"handshakeSeq\": 0\n };\n\n this._encrypted = false;\n let msg = this._createPacket(packet);\n this._sendMsg(msg, this._readResponse);\n\n this._helloClientPacket = packet;\n }", "sendSocks5InitialHandshake() {\n const buff = new smart_buffer_1.SmartBuffer();\n buff.writeUInt8(0x05);\n // We should only tell the proxy we support user/pass auth if auth info is actually provided.\n // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority.\n if (this._options.proxy.userId || this._options.proxy.password) {\n buff.writeUInt8(2);\n buff.writeUInt8(constants_1.Socks5Auth.NoAuth);\n buff.writeUInt8(constants_1.Socks5Auth.UserPass);\n }\n else {\n buff.writeUInt8(1);\n buff.writeUInt8(constants_1.Socks5Auth.NoAuth);\n }\n this._nextRequiredPacketBufferSize =\n constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;\n this._socket.write(buff.toBuffer());\n this.state = constants_1.SocksClientState.SentInitialHandshake;\n }", "function doHandshake() {\n /*\n These are the lines that are sent as a handshake from the client.\n Chromium sends two blank lines that might be a part of the\n specification.\n\n 0: GET /echo HTTP/1.1\n 1: Upgrade: WebSocket\n 2: Connection: Upgrade\n 3: Host: localhost:8000\n 4: Origin: file://\n 5:\n 6:\n */\n\n var lines = data.split('\\r\\n');\n\n // Line 0\n var request = lines[0].split(' ');\n \n // Return flash policy file for web-socket-js\n // http://github.com/gimite/web-socket-js\n if(request[0].match(/policy-file-request/)){\n sys.puts('requesting flash policy file');\n \n policy_xml = \n '<?xml version=\"1.0\"?>' +\n '<!DOCTYPE cross-domain-policy SYSTEM ' +\n 'ww.macromedia.com/xml/dtds/cross-domain-policy.dtd\">' +\n '<cross-domain-policy>' +\n \"<allow-access-from domain='*' to-ports='*'/>\" +\n '</cross-domain-policy>'\n connection.send(policy_xml);\n connection.close();\n }\n \n if (((request[0] === 'GET') && (request[2] === 'HTTP/1.1'))\n !== true) {\n notAccepted('Request not valid.');\n return;\n }else \n sys.puts(request.join(','))\n var resource = request[1];\n\n if (resource[0] !== '/') {\n notAccepted('Request resource not valid.');\n return;\n }\n\n // Line 1-6\n\n // Inspired by pywebsocket. If the value is set to anything other\n // than '' here, then it has to be set to the same value by the\n // client.\n\n var headers = {\n 'Upgrade': 'WebSocket',\n 'Connection': 'Upgrade',\n 'Host': '',\n 'Origin': ''\n }\n\n for (i = 1; i < lines.length; i++) {\n\n // We should 'continue' if it's acceptable with blank lines\n // between headers.\n\n if (lines[i] === '')\n break;\n\n // Split the header line into a key and a value. Check against\n // the headers hash. Warn the user if the header isn't\n // supported.\n\n var line = lines[i].split(': ');\n\n var headerValue = headers[line[0]];\n\n if (headerValue === undefined) {\n notSupported('Header \\'' + line[0] + '\\' not supported.');\n continue;\n }\n else if ((headerValue !== '') && (line[1] !== headerValue)) {\n notAccepted('Header \\'' + line[0] + '\\' is not \\'' +\n headerValue + '\\'.');\n return;\n }\n else\n headers[line[0]] = line[1];\n }\n\n // Import requested resource\n\n try {\n _resource = require('./resources' + resource);\n } catch (e) {\n sys.puts(headers['Host'] + ' tries to connect to resource \\'' +\n resource + '\\', but the resource does not exist.');\n connection.close();\n return;\n }\n\n // Send handshake back\n\n connection.send('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n 'WebSocket-Origin: ' + headers['Origin'] + '\\r\\n' +\n 'WebSocket-Location: ws://' + headers['Host'] + resource +\n '\\r\\n' +\n '\\r\\n');\n\n _doneHandshake = true;\n\n return;\n }", "function sendAuthRequest() {\n const box = seal(self.publicKey, self.peerAuthKey)\n\n // Send without shared key encryption until peer can derive it\n self.socket.write(box)\n\n self.once('data', receiveChallenge)\n }", "handleSocks4FinalHandshakeResponse() {\n const data = this._receiveBuffer.get(8);\n if (data[1] !== constants_1.Socks4Response.Granted) {\n this._closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);\n }\n else {\n // Bind response\n if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.bind) {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const remoteHost = {\n port: buff.readUInt16BE(),\n host: ip.fromLong(buff.readUInt32BE())\n };\n // If host is 0.0.0.0, set to proxy host.\n if (remoteHost.host === '0.0.0.0') {\n remoteHost.host = this._options.proxy.ipaddress;\n }\n this.state = constants_1.SocksClientState.BoundWaitingForConnection;\n this.emit('bound', { socket: this._socket, remoteHost });\n // Connect response\n }\n else {\n this.state = constants_1.SocksClientState.Established;\n this.removeInternalSocketHandlers();\n this.emit('established', { socket: this._socket });\n }\n }\n }", "handleSocks4FinalHandshakeResponse() {\n const data = this.receiveBuffer.get(8);\n if (data[1] !== constants_1.Socks4Response.Granted) {\n this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);\n }\n else {\n // Bind response\n if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const remoteHost = {\n port: buff.readUInt16BE(),\n host: ip.fromLong(buff.readUInt32BE()),\n };\n // If host is 0.0.0.0, set to proxy host.\n if (remoteHost.host === '0.0.0.0') {\n remoteHost.host = this.options.proxy.ipaddress;\n }\n this.setState(constants_1.SocksClientState.BoundWaitingForConnection);\n this.emit('bound', { remoteHost, socket: this.socket });\n // Connect response\n }\n else {\n this.setState(constants_1.SocksClientState.Established);\n this.removeInternalSocketHandlers();\n this.emit('established', { socket: this.socket });\n }\n }\n }", "function assembleHandshake (url, key) {\n//function assembleHandshake (host, origin, key) {\n let urlParts = Url.parse(url);\n return `GET / HTTP/1.1\nHost: ${urlParts.hostname}\nUpgrade: websocket\nConnection: Upgrade\nOrigin: ${url}\nSec-WebSocket-Key: ${key}\nSec-WebSocket-Version: 13\n\n`;\n}", "function handshake() {\n let { cert, config } = api.getCertAndConfig();\n\n let endPoint = `${config.basePath}/handshake?employerRegistrationNumber=${\n cert.epn\n }&softwareUsed=${config.softwareName}&softwareVersion=${\n config.softwareVersion\n }`;\n\n return new Message(api.options('GET', config.host, endPoint), cert);\n}", "handleInitialSocks5HandshakeResponse() {\n const data = this.receiveBuffer.get(2);\n if (data[0] !== 0x05) {\n this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);\n }\n else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {\n this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);\n }\n else {\n // If selected Socks v5 auth method is no auth, send final handshake request.\n if (data[1] === constants_1.Socks5Auth.NoAuth) {\n this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;\n this.sendSocks5CommandRequest();\n // If selected Socks v5 auth method is user/password, send auth handshake.\n }\n else if (data[1] === constants_1.Socks5Auth.UserPass) {\n this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;\n this.sendSocks5UserPassAuthentication();\n // If selected Socks v5 auth method is the custom_auth_method, send custom handshake.\n }\n else if (data[1] === this.options.proxy.custom_auth_method) {\n this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;\n this.sendSocks5CustomAuthentication();\n }\n else {\n this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);\n }\n }\n }", "Handshake()\n {\n this._buffer.WriteByte(Network.CONNECT);\n this._buffer.WriteShort(this._id);\n\n this._socket.send(this._buffer.GetTrimmedBuffer());\n this._buffer.Reset();\n\n this._socket.on(\"message\", (data) => {\n let b = new ByteBuffer(toArrayBuffer(data));\n this.Receive(b);\n });\n }", "handshake() {\n return __awaiter(this, void 0, void 0, function* () {\n const status = yield this.requestWithTimeout(exports.MSG_CODES.STATUS, exports.MSG_CODES.STATUS, [\n this.protocolVersion,\n this.ethChain.common.networkId(),\n yield this.ethChain.getBlocksTD(),\n (yield this.ethChain.getBestBlock()).hash(),\n this.ethChain.genesis().hash\n ]);\n this.setStatus(status);\n });\n }", "sendClientHello () {\n this.sendHandshakeMessage(HandshakeType.CLIENT_HELLO, concat([\n VER12,\n this.clientRandom,\n from([0]), // session_id\n from([0x00, 0x02, 0x00, 0x2f]), // cipher_suites\n from([0x01, 0x00]) // compression_methods\n ]))\n }", "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 }", "handleInitialSocks5HandshakeResponse() {\n const data = this._receiveBuffer.get(2);\n if (data[0] !== 0x05) {\n this._closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);\n }\n else if (data[1] === 0xff) {\n this._closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);\n }\n else {\n // If selected Socks v5 auth method is no auth, send final handshake request.\n if (data[1] === constants_1.Socks5Auth.NoAuth) {\n this.sendSocks5CommandRequest();\n // If selected Socks v5 auth method is user/password, send auth handshake.\n }\n else if (data[1] === constants_1.Socks5Auth.UserPass) {\n this.sendSocks5UserPassAuthentication();\n }\n else {\n this._closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);\n }\n }\n }", "handleSocks4IncomingConnectionResponse() {\n const data = this._receiveBuffer.get(8);\n if (data[1] !== constants_1.Socks4Response.Granted) {\n this._closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);\n }\n else {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const remoteHost = {\n port: buff.readUInt16BE(),\n host: ip.fromLong(buff.readUInt32BE())\n };\n this.state = constants_1.SocksClientState.Established;\n this.removeInternalSocketHandlers();\n this.emit('established', { socket: this._socket, remoteHost });\n }\n }", "handleSocks4IncomingConnectionResponse() {\n const data = this.receiveBuffer.get(8);\n if (data[1] !== constants_1.Socks4Response.Granted) {\n this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);\n } else {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const remoteHost = {\n port: buff.readUInt16BE(),\n host: ip.fromLong(buff.readUInt32BE())\n };\n this.setState(constants_1.SocksClientState.Established);\n this.removeInternalSocketHandlers();\n this.emit(\"established\", { remoteHost, socket: this.socket });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setJulian Set Julian date and update all calendars
function setJulian(j) { document.julianday.day.value = new Number(j); calcJulian(); }
[ "function setJulian(j) { juliandayvalue = new Number(j);calcJulian();}", "function calcJulianCalendar()\n {\n setJulian(julian_to_jd((new Number(document.juliancalendar.year.value)),\n\t\t\t document.juliancalendar.month.selectedIndex + 1,\n\t\t\t (new Number(document.juliancalendar.day.value))));\n }", "function setJulian(j)\n{\n document.julianday.day.value = new Number(j);\n calcJulian();\n}", "function calcJulian()\n {\n var j, date, time;\n\n j = new Number(document.julianday.day.value);\n date = jd_to_gregorian(j);\n time = jhms(j);\n document.gregorian.year.value = date[0];\n document.gregorian.month.selectedIndex = date[1] - 1;\n document.gregorian.day.value = date[2];\n document.gregorian.hour.value = pad(time[0], 2, \" \");\n document.gregorian.min.value = pad(time[1], 2, \"0\");\n document.gregorian.sec.value = pad(time[2], 2, \"0\");\n updateFromGregorian();\n }", "function calcJulianCalendar()\n{\n setJulian(julian_to_jd((new Number(document.juliancalendar.year.value)),\n document.juliancalendar.month.selectedIndex + 1,\n (new Number(document.juliancalendar.day.value))));\n}", "function calcJulian()\n{\n var j, date, time;\n\n j = new Number(document.julianday.day.value);\n date = jd_to_gregorian(j);\n time = jhms(j);\n document.gregorian.year.value = date[0];\n document.gregorian.month.selectedIndex = date[1] - 1;\n document.gregorian.day.value = date[2];\n document.gregorian.hour.value = pad(time[0], 2, \" \");\n document.gregorian.min.value = pad(time[1], 2, \"0\");\n document.gregorian.sec.value = pad(time[2], 2, \"0\");\n updateFromGregorian();\n}", "function calcModifiedJulian()\n {\n setJulian((new Number(document.modifiedjulianday.day.value)) + JMJD);\n }", "function calcModifiedJulian()\n{\n setJulian((new Number(document.modifiedjulianday.day.value)) + JMJD);\n}", "function calcIndianCivilCalendar()\n{\n setJulian(indian_civil_to_jd(\n (new Number(document.indiancivilcalendar.year.value)),\n document.indiancivilcalendar.month.selectedIndex + 1,\n (new Number(document.indiancivilcalendar.day.value))));\n}", "function updateFromGregorian()\n {\n var j, year, mon, mday, hour, min, sec,\n\t weekday, julcal, hebcal, islcal, hmindex, utime, isoweek,\n\t may_countcal, mayhaabcal, maytzolkincal, bahcal, frrcal,\n\t indcal, isoday, xgregcal;\n\n year = new Number(document.gregorian.year.value);\n mon = document.gregorian.month.selectedIndex;\n mday = new Number(document.gregorian.day.value);\n hour = min = sec = 0;\n hour = new Number(document.gregorian.hour.value);\n min = new Number(document.gregorian.min.value);\n sec = new Number(document.gregorian.sec.value);\n\n // Update Julian day\n\n j = gregorian_to_jd(year, mon + 1, mday) +\n\t (Math.floor(sec + 60 * (min + 60 * hour) + 0.5) / 86400.0);\n\n document.julianday.day.value = j;\n document.modifiedjulianday.day.value = j - JMJD;\n\n // Update day of week in Gregorian box\n\n weekday = jwday(j);\n document.gregorian.wday.value = Weekdays[weekday];\n\n // Update leap year status in Gregorian box\n\n document.gregorian.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0];\n\n // Update Julian Calendar\n\n julcal = jd_to_julian(j);\n document.juliancalendar.year.value = julcal[0];\n document.juliancalendar.month.selectedIndex = julcal[1] - 1;\n document.juliancalendar.day.value = julcal[2];\n document.juliancalendar.leap.value = NormLeap[leap_julian(julcal[0]) ? 1 : 0];\n weekday = jwday(j);\n document.juliancalendar.wday.value = Weekdays[weekday];\n\n // Update Hebrew Calendar\n\n hebcal = jd_to_hebrew(j);\n if (hebrew_leap(hebcal[0])) {\n\t document.hebrew.month.options.length = 13;\n\t document.hebrew.month.options[11] = new Option(\"Adar I\");\n\t document.hebrew.month.options[12] = new Option(\"Veadar\");\n } else {\n\t document.hebrew.month.options.length = 12;\n\t document.hebrew.month.options[11] = new Option(\"Adar\");\n }\n document.hebrew.year.value = hebcal[0];\n document.hebrew.month.selectedIndex = hebcal[1] - 1;\n document.hebrew.day.value = hebcal[2];\n hmindex = hebcal[1];\n if (hmindex == 12 && !hebrew_leap(hebcal[0])) {\n\t hmindex = 14;\n }\n document.hebrew.hebmonth.src = \"figures/hebrew_month_\" +\n\t hmindex + \".gif\";\n switch (hebrew_year_days(hebcal[0])) {\n\t case 353:\n\t document.hebrew.leap.value = \"Common deficient (353 days)\";\n\t break;\n\n\t case 354:\n\t document.hebrew.leap.value = \"Common regular (354 days)\";\n\t break;\n\n\t case 355:\n\t document.hebrew.leap.value = \"Common complete (355 days)\";\n\t break;\n\n\t case 383:\n\t document.hebrew.leap.value = \"Embolismic deficient (383 days)\";\n\t break;\n\n\t case 384:\n\t document.hebrew.leap.value = \"Embolismic regular (384 days)\";\n\t break;\n\n\t case 385:\n\t document.hebrew.leap.value = \"Embolismic complete (385 days)\";\n\t break;\n\n\t default:\n\t document.hebrew.leap.value = \"Invalid year length: \" +\n\t\t hebrew_year_days(hebcal[0]) + \" days.\";\n\t break;\n }\n\n // Update Islamic Calendar\n\n islcal = jd_to_islamic(j);\n document.islamic.year.value = islcal[0];\n document.islamic.month.selectedIndex = islcal[1] - 1;\n document.islamic.day.value = islcal[2];\n document.islamic.wday.value = \"yawm \" + ISLAMIC_WEEKDAYS[weekday];\n document.islamic.leap.value = NormLeap[leap_islamic(islcal[0]) ? 1 : 0];\n\n // Update Persian Calendar\n\n perscal = jd_to_persian(j);\n document.persian.year.value = perscal[0];\n document.persian.month.selectedIndex = perscal[1] - 1;\n document.persian.day.value = perscal[2];\n document.persian.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persian.leap.value = NormLeap[leap_persian(perscal[0]) ? 1 : 0];\n\n // Update Persian Astronomical Calendar\n\n perscal = jd_to_persiana(j);\n document.persiana.year.value = perscal[0];\n document.persiana.month.selectedIndex = perscal[1] - 1;\n document.persiana.day.value = perscal[2];\n document.persiana.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persiana.leap.value = NormLeap[leap_persiana(perscal[0]) ? 1 : 0];\n\n // Update Mayan Calendars\n\n may_countcal = jd_to_mayan_count(j);\n document.mayancount.baktun.value = may_countcal[0];\n document.mayancount.katun.value = may_countcal[1];\n document.mayancount.tun.value = may_countcal[2];\n document.mayancount.uinal.value = may_countcal[3];\n document.mayancount.kin.value = may_countcal[4];\n mayhaabcal = jd_to_mayan_haab(j);\n document.mayancount.haab.value = \"\" + mayhaabcal[1] + \" \" + MAYAN_HAAB_MONTHS[mayhaabcal[0] - 1];\n maytzolkincal = jd_to_mayan_tzolkin(j);\n document.mayancount.tzolkin.value = \"\" + maytzolkincal[1] + \" \" + MAYAN_TZOLKIN_MONTHS[maytzolkincal[0] - 1];\n\n // Update Bahai Calendar\n\n bahcal = jd_to_bahai(j);\n document.bahai.kull_i_shay.value = bahcal[0];\n document.bahai.vahid.value = bahcal[1];\n document.bahai.year.selectedIndex = bahcal[2] - 1;\n document.bahai.month.selectedIndex = bahcal[3] - 1;\n document.bahai.day.selectedIndex = bahcal[4] - 1;\n document.bahai.weekday.value = BAHAI_WEEKDAYS[weekday];\n document.bahai.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0]; // Bahai uses same leap rule as Gregorian\n\n // Update Indian Civil Calendar\n\n indcal = jd_to_indian_civil(j);\n document.indiancivilcalendar.year.value = indcal[0];\n document.indiancivilcalendar.month.selectedIndex = indcal[1] - 1;\n document.indiancivilcalendar.day.value = indcal[2];\n document.indiancivilcalendar.weekday.value = INDIAN_CIVIL_WEEKDAYS[weekday];\n document.indiancivilcalendar.leap.value = NormLeap[leap_gregorian(indcal[0] + 78) ? 1 : 0];\n\n // Update French Republican Calendar\n\n frrcal = jd_to_french_revolutionary(j);\n document.french.an.value = frrcal[0];\n document.french.mois.selectedIndex = frrcal[1] - 1;\n document.french.decade.selectedIndex = frrcal[2] - 1;\n document.french.jour.selectedIndex = ((frrcal[1] <= 12) ? frrcal[3] : (frrcal[3] + 11)) - 1;\n\n // Update Gregorian serial number\n\n if (document.gregserial != null) {\n\t document.gregserial.day.value = j - J0000;\n }\n\n // Update Excel 1900 and 1904 day serial numbers\n\n document.excelserial1900.day.value = (j - J1900) + 1 +\n\t /* Microsoft marching morons thought 1900 was a leap year.\n\t\t Adjust dates after 1900-02-28 to compensate for their\n\t\t idiocy. */\n\t ((j > 2415078.5) ? 1 : 0)\n\t ;\n document.excelserial1904.day.value = j - J1904;\n\n // Update Unix time()\n\n utime = (j - J1970) * (60 * 60 * 24 * 1000);\n document.unixtime.time.value = Math.round(utime / 1000);\n\n // Update ISO Week\n\n isoweek = jd_to_iso(j);\n document.isoweek.year.value = isoweek[0];\n document.isoweek.week.value = isoweek[1];\n document.isoweek.day.value = isoweek[2];\n\n // Update ISO Day\n\n isoday = jd_to_iso_day(j);\n document.isoday.year.value = isoday[0];\n document.isoday.day.value = isoday[1];\n }", "function updateFromGregorian()\n{\n var j, year, mon, mday, hour, min, sec,\n weekday, julcal, hebcal, islcal, hmindex, utime, isoweek,\n may_countcal, mayhaabcal, maytzolkincal, bahcal, frrcal,\n indcal, isoday, xgregcal;\n\n year = new Number(document.gregorian.year.value);\n mon = document.gregorian.month.selectedIndex;\n mday = new Number(document.gregorian.day.value);\n hour = min = sec = 0;\n hour = new Number(document.gregorian.hour.value);\n min = new Number(document.gregorian.min.value);\n sec = new Number(document.gregorian.sec.value);\n\n // Update Julian day\n\n j = gregorian_to_jd(year, mon + 1, mday) +\n (Math.floor(sec + 60 * (min + 60 * hour) + 0.5) / 86400.0);\n\n document.julianday.day.value = j;\n document.modifiedjulianday.day.value = j - JMJD;\n\n // Update day of week in Gregorian box\n\n weekday = jwday(j);\n document.gregorian.wday.value = Weekdays[weekday];\n\n // Update leap year status in Gregorian box\n\n document.gregorian.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0];\n\n // Update Julian Calendar\n\n julcal = jd_to_julian(j);\n document.juliancalendar.year.value = julcal[0];\n document.juliancalendar.month.selectedIndex = julcal[1] - 1;\n document.juliancalendar.day.value = julcal[2];\n document.juliancalendar.leap.value = NormLeap[leap_julian(julcal[0]) ? 1 : 0];\n weekday = jwday(j);\n document.juliancalendar.wday.value = Weekdays[weekday];\n\n // Update Hebrew Calendar\n\n hebcal = jd_to_hebrew(j);\n if (hebrew_leap(hebcal[0])) {\n document.hebrew.month.options.length = 13;\n document.hebrew.month.options[11] = new Option(\"Adar I\");\n document.hebrew.month.options[12] = new Option(\"Veadar\");\n } else {\n document.hebrew.month.options.length = 12;\n document.hebrew.month.options[11] = new Option(\"Adar\");\n }\n document.hebrew.year.value = hebcal[0];\n document.hebrew.month.selectedIndex = hebcal[1] - 1;\n document.hebrew.day.value = hebcal[2];\n hmindex = hebcal[1];\n if (hmindex == 12 && !hebrew_leap(hebcal[0])) {\n hmindex = 14;\n }\n document.hebrew.hebmonth.src = \"/img/hebrew/hebrew_month_\" +\n hmindex + \".gif\";\n switch (hebrew_year_days(hebcal[0])) {\n case 353:\n document.hebrew.leap.value = \"Common deficient (353 days)\";\n break;\n\n case 354:\n document.hebrew.leap.value = \"Common regular (354 days)\";\n break;\n\n case 355:\n document.hebrew.leap.value = \"Common complete (355 days)\";\n break;\n\n case 383:\n document.hebrew.leap.value = \"Embolismic deficient (383 days)\";\n break;\n\n case 384:\n document.hebrew.leap.value = \"Embolismic regular (384 days)\";\n break;\n\n case 385:\n document.hebrew.leap.value = \"Embolismic complete (385 days)\";\n break;\n\n default:\n document.hebrew.leap.value = \"Invalid year length: \" +\n hebrew_year_days(hebcal[0]) + \" days.\";\n break;\n }\n\n // Update Islamic Calendar\n\n islcal = jd_to_islamic(j);\n document.islamic.year.value = islcal[0];\n document.islamic.month.selectedIndex = islcal[1] - 1;\n document.islamic.day.value = islcal[2];\n document.islamic.wday.value = \"yawm \" + ISLAMIC_WEEKDAYS[weekday];\n document.islamic.leap.value = NormLeap[leap_islamic(islcal[0]) ? 1 : 0];\n\n // Update Persian Calendar\n\n perscal = jd_to_persian(j);\n document.persian.year.value = perscal[0];\n document.persian.month.selectedIndex = perscal[1] - 1;\n document.persian.day.value = perscal[2];\n document.persian.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persian.leap.value = NormLeap[leap_persian(perscal[0]) ? 1 : 0];\n\n // Update Mayan Calendars\n\n may_countcal = jd_to_mayan_count(j);\n document.mayancount.baktun.value = may_countcal[0];\n document.mayancount.katun.value = may_countcal[1];\n document.mayancount.tun.value = may_countcal[2];\n document.mayancount.uinal.value = may_countcal[3];\n document.mayancount.kin.value = may_countcal[4];\n mayhaabcal = jd_to_mayan_haab(j);\n document.mayancount.haab.value = \"\" + mayhaabcal[1] + \" \" + MAYAN_HAAB_MONTHS[mayhaabcal[0] - 1];\n maytzolkincal = jd_to_mayan_tzolkin(j);\n document.mayancount.tzolkin.value = \"\" + maytzolkincal[1] + \" \" + MAYAN_TZOLKIN_MONTHS[maytzolkincal[0] - 1];\n\n // Update Bahai Calendar\n\n bahcal = jd_to_bahai(j);\n document.bahai.kull_i_shay.value = bahcal[0];\n document.bahai.vahid.value = bahcal[1];\n document.bahai.year.selectedIndex = bahcal[2] - 1;\n document.bahai.month.selectedIndex = bahcal[3] - 1;\n document.bahai.day.selectedIndex = bahcal[4] - 1;\n document.bahai.weekday.value = BAHAI_WEEKDAYS[weekday];\n document.bahai.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0]; // Bahai uses same leap rule as Gregorian\n\n // Update Indian Civil Calendar\n\n indcal = jd_to_indian_civil(j);\n document.indiancivilcalendar.year.value = indcal[0];\n document.indiancivilcalendar.month.selectedIndex = indcal[1] - 1;\n document.indiancivilcalendar.day.value = indcal[2];\n document.indiancivilcalendar.weekday.value = INDIAN_CIVIL_WEEKDAYS[weekday];\n document.indiancivilcalendar.leap.value = NormLeap[leap_gregorian(indcal[0] + 78) ? 1 : 0];\n\n // Update French Republican Calendar\n\n frrcal = jd_to_french_revolutionary(j);\n document.french.an.value = frrcal[0];\n document.french.mois.selectedIndex = frrcal[1] - 1;\n document.french.decade.selectedIndex = frrcal[2] - 1;\n document.french.jour.selectedIndex = ((frrcal[1] <= 12) ? frrcal[3] : (frrcal[3] + 11)) - 1;\n\n // Update Gregorian serial number\n\n if (document.gregserial != null) {\n document.gregserial.day.value = j - J0000;\n }\n\n // Update Excel 1900 and 1904 day serial numbers\n\n document.excelserial1900.day.value = (j - J1900) + 1 +\n /* Microsoft marching morons thought 1900 was a leap year.\n Adjust dates after 1900-02-28 to compensate for their\n idiocy. */\n ((j > 2415078.5) ? 1 : 0)\n ;\n document.excelserial1904.day.value = j - J1904;\n\n // Update Unix time()\n\n utime = (j - J1970) * (60 * 60 * 24 * 1000);\n document.unixtime.time.value = Math.round(utime / 1000);\n\n // Update ISO Week\n\n isoweek = jd_to_iso(j);\n document.isoweek.year.value = isoweek[0];\n document.isoweek.week.value = isoweek[1];\n document.isoweek.day.value = isoweek[2];\n\n // Update ISO Day\n\n isoday = jd_to_iso_day(j);\n document.isoday.year.value = isoday[0];\n document.isoday.day.value = isoday[1];\n}", "function calcGregSerial()\n{\n setJulian((new Number(document.gregserial.day.value)) + J0000);\n}", "calculateJulianDate () {\n return this.CDT.JulianDate( this.year, this.month, this.day,\n this.hour, this.minute, this.second, this.millisecond )\n }", "function calcPersian()\n{\n setJulian(persian_to_jd((new Number(document.persian.year.value)),\n document.persian.month.selectedIndex + 1,\n (new Number(document.persian.day.value))));\n}", "function calcIslamic()\n{\n setJulian(islamic_to_jd((new Number(document.islamic.year.value)),\n document.islamic.month.selectedIndex + 1,\n (new Number(document.islamic.day.value))));\n}", "function calcIndianCivilCalendar()\n {\n setJulian(indian_civil_to_jd(\n\t\t\t (new Number(document.indiancivilcalendar.year.value)),\n\t\t\t document.indiancivilcalendar.month.selectedIndex + 1,\n\t\t\t (new Number(document.indiancivilcalendar.day.value))));\n }", "function julian_date()\n{\n var dt_as_str, mm, dd, yy;\n var a, b;\n\n dt_as_str = document.planets.date_txt.value;\n\n mm = eval(dt_as_str.substring(0,2));\n dd = eval(dt_as_str.substring(3,5));\n yy = eval(dt_as_str.substring(6,10));\n\n with (Math) {\n var yyy=yy;\n var mmm=mm;\n if (mm < 3)\n {\n yyy = yy - 1;\n mmm = mm + 12;\n }\n a = floor(yyy/100);\n b = 2 - a + floor(a/4);\n\n return floor(365.25*yyy) + floor(30.6001*(mmm+1)) + dd + 1720994.5 + b;\n }\n}", "function calcJulianDay(){\n\tvar j = (document.daycounter.julianday.value); // extract Julian Day, numeric value (not necessarily integer) expected.\n\tj = j.replace(/\\s/gi, \"\"); j = j.replace(/,/gi, \".\"); j = Number (j);\n\tif (isNaN (j)) alert (\"Non numeric value\" + ' \"' + document.daycounter.julianday.value + '\"')\n\telse {\n\t\tlet jd = new modules.ExtCountDate (jdcounterselector,\"iso8601\",0);\n\t\tjd.setFromCount(j);\n\t\tif (isNaN(jd.valueOf())) alert (\"Date out of range\")\n\t\telse {\n\t\t\ttargetDate = new modules.ExtDate (calendars[customCalIndex],jd.valueOf());\n\t\t\tsetDisplay();\n\t\t}\n\t}\n}", "function calcPersian()\n {\n setJulian(persian_to_jd((new Number(document.persian.year.value)),\n\t\t\t document.persian.month.selectedIndex + 1,\n\t\t\t (new Number(document.persian.day.value))));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the already selected skills from grafts for step seven
function getGraftSkills(type){ var skillString = type + "Skills"; //check step 3 subtype graft skills var skillList = []; var subtype = $('#creatureSubTypeDrop').val().trim(); if (subtype != '' && subtype != 'None') { if (creatureSubType[subtype].hasOwnProperty(skillString)){ skillList = skillList.concat(creatureSubType[subtype][skillString]); } if (creatureSubType[subtype].hasOwnProperty("SubRaces")){ subRaceDrop = $('#stepThreeOptionDrop').val().trim(); if (creatureSubType[subtype].SubRaces[subRaceDrop].hasOwnProperty(skillString)){ skillList = skillList.concat(creatureSubType[subtype].SubRaces[subRaceDrop][skillString]); } } } //check step 4 class graft var classDrop = $('#classDrop').val().trim(); if (classDrop != '' && classDrop != 'None') { //operative and mystic skills depend on class choices if (classDrop == "Mystic" || classDrop == "Operative") { if (classData[classDrop].hasOwnProperty(skillString)){ var connectionDrop = $('#stepFourOptionDrop').val().trim(); skillList = skillList.concat(classData[classDrop][skillString][connectionDrop]); } } else { if (classData[classDrop].hasOwnProperty(skillString)){ skillList = skillList.concat(classData[classDrop][skillString]); } } } //check step 5 graft var graft = $('#graftDrop').val().trim(); if (graft != '' && graft != 'None') { for (var subgraft in graftTemplates){ if (graftTemplates[subgraft].hasOwnProperty(graft)){ if (graftTemplates[subgraft][graft].hasOwnProperty(skillString)){ skillList = skillList.concat(graftTemplates[subgraft][graft][skillString]); } } } } //capitalise to match data array entries for (var i = 0; i < skillList.length; i++) { skillList[i] = skillList[i].capitalise(); } //remove duplicates var unique = skillList.filter(function(elem, index, self) { return index === self.indexOf(elem); }) unique = unique.sort(); return unique; }
[ "function getAdditionalAbilities(){\n //check step 3 subtype graft skills\n var skillList = {};\n var subtype = $('#creatureSubTypeDrop').val().trim();\n if (subtype != '' && subtype != 'None') {\n if (creatureSubType[subtype].hasOwnProperty(\"AdditionalAbilities\")){\n skillList = creatureSubType[subtype][\"AdditionalAbilities\"];\n } else if (creatureSubType[subtype].hasOwnProperty(\"SubRaces\")){\n subRaceDrop = $('#stepThreeOptionDrop').val().trim();\n if (creatureSubType[subtype].SubRaces[subRaceDrop].hasOwnProperty(\"AdditionalAbilities\")){\n skillList = creatureSubType[subtype].SubRaces[subRaceDrop][\"AdditionalAbilities\"];\n }\n }\n }\n return skillList;\n}", "function getGraftSpelllikeAbilities(){\n\n //check step 3 subtype graft skills\n var spelllike = {}\n\n var subtype = $('#creatureSubTypeDrop').val().trim();\n if (subtype != '' && subtype != 'None') {\n if (creatureSubType[subtype].hasOwnProperty(\"Spell-likeAbilities\")){\n spelllike = creatureSubType[subtype][\"Spell-likeAbilities\"];\n }\n if (creatureSubType[subtype].hasOwnProperty(\"SubRaces\")){\n subRaceDrop = $('#stepThreeOptionDrop').val().trim();\n if (creatureSubType[subtype].SubRaces[subRaceDrop].hasOwnProperty(\"Spell-likeAbilities\")){\n spelllike = creatureSubType[subtype].SubRaces[subRaceDrop][\"Spell-likeAbilities\"];\n }\n }\n }\n\n //check step 5 graft\n var graft = $('#graftDrop').val().trim();\n if (graft != '' && graft != 'None') {\n for (var subgraft in graftTemplates){\n if (graftTemplates[subgraft].hasOwnProperty(graft)){\n if (graftTemplates[subgraft][graft].hasOwnProperty(\"Spell-likeAbilities\")){\n spelllike = graftTemplates[subgraft][graft][\"Spell-likeAbilities\"];\n }\n }\n }\n }\n //if any spell like attributes found\n return spelllike;\n\n}", "function getSelectedSkills() {\n var res = new Array();\n for (var i = 0; i < 3; i++) {\n var skill_id = $(\"select#skill\" + i + \" option:selected\").val();\n var skill = Skill.get(skill_id);\n if (skill != null)\n res.push(skill);\n }\n return res;\n}", "function getTopSkills() {\n\tresetData(\"skills\");\n\n\tvar active = skillsd3.data.active;\n\tvar passive = skillsd3.data.passive;\n\t\n\n \tallGRiftHeroes.forEach(function (currentHero) {\n\n \t\tif (currentHero.skills != undefined) {\n \t\t\t//add active skills for graph\n\t \t\tvar currentHeroActiveSkills = currentHero.skills.active;\n\t \t\tcurrentHeroActiveSkills.forEach(function (currentActive) {\n\t \t\t\tif (currentActive.skill != undefined) {\n\t\t \t\t\tvar currentSkillName = currentActive.skill.name;\n\t\t \t\t\tvar currentRuneName;\n\t\t \t\t\t//set rune name\n\t\t \t\t\tif (currentActive.rune == undefined) {\n\t\t \t\t\t\tcurrentRuneName = \"No Rune\";\n\t\t \t\t\t}\n\t\t \t\t\telse {\n\t\t\t \t\t\tcurrentRuneName = currentActive.rune.name;\n\t\t \t\t\t}\n\n\t\t \t\t\t//check if skill has been added\n\t\t \t\t\tvar locationOfCurrentActive = active.names.indexOf(currentSkillName);\n\t\t \t\t\tif (locationOfCurrentActive == -1) {\n\t\t \t\t\t\tactive.names.push(currentSkillName);\n\t\t \t\t\t\tactive.count.push(1);\n\n\t\t \t\t\t\tactive.runeNames.push([currentRuneName]);\n\t\t \t\t\t\tactive.runeCount.push([1]);\n\t\t \t\t\t\tactive.total += 1;\n\t\t \t\t\t}\n\t\t \t\t\telse {\n\t\t \t\t\t\tactive.count[locationOfCurrentActive] += 1;\n\t\t \t\t\t\tactive.total += 1;\n\t\t \t\t\t\t//check if rune was already added.\n\t\t \t\t\t\tvar runesForCurrentSkill = active.runeNames[locationOfCurrentActive]\n\t\t \t\t\t\tvar runeCountForCurrentSkill = active.runeCount[locationOfCurrentActive];\n\n\t\t \t\t\t\tvar locationOfCurrentRune = runesForCurrentSkill.indexOf(currentRuneName);\n\t\t \t\t\t\tif (locationOfCurrentRune == -1) {\n\t\t \t\t\t\t\trunesForCurrentSkill.push(currentRuneName);\n\t\t \t\t\t\t\truneCountForCurrentSkill.push(1);\n\t\t \t\t\t\t}\n\t\t \t\t\t\telse {\n\t\t \t\t\t\t\truneCountForCurrentSkill[locationOfCurrentRune] += 1;\n\t\t \t\t\t\t}\n\t\t \t\t\t}\n\t \t\t\t}\n\t \t\t});//finished adding active skills and runes\n\n\t\t\t//add passive\n\t\t\tvar currentHeroPassives = currentHero.skills.passive;\n\t\t\tcurrentHeroPassives.forEach(function (currentPassive) {\n\t\t\t\tif (currentPassive.skill != undefined) {\n\t\t\t\t\tvar currentPassiveName = currentPassive.skill.name;\n\t\t\t\t\tvar locationOfCurrentPassive = passive.names.indexOf(currentPassiveName);\n\t\t\t\t\tif (locationOfCurrentPassive == -1) {\n\t\t \t\t\t\tpassive.names.push(currentPassiveName);\n\t\t \t\t\t\tpassive.count.push(1);\n\t\t \t\t\t\tpassive.total += 1;\n\t\t \t\t\t}\n\t\t \t\t\telse {\n\t\t \t\t\t\tpassive.count[locationOfCurrentPassive] += 1;\n\t\t \t\t\t\tpassive.total += 1;\n\t\t \t\t\t}\n\t\t\t\t}\n\t\t\t});\n \t\t}\n \t});\n}", "function getSkills() {\n return [\"sourceTerminalEducate1\", \"sourceTerminalEducate2\"].map(p => (0, _property.get)(p)).filter(s => s !== \"\").map(s => Skill.get(s.slice(0, -4)));\n}", "skills () {\n return Object.keys(this._skillStates).filter((key) => {\n const state = this._skillStates[key]\n return state && state.assigned\n })\n }", "generateStartingSkills() {\n CareerPathStartingSkills[this.career.careerPath].forEach(startingSkill => {\n if (Array.isArray(startingSkill)) {\n console.debug(`Choosing from ${startingSkill}`);\n const choice = dn(startingSkill.length) - 1;\n this.skillSet.push(startingSkill[choice]);\n } else {\n this.skillSet.push(startingSkill);\n }\n });\n }", "function getAll() {\n return skills;\n}", "function parseSkills(root, buildText) {\n var skills = querySelectorAll(root, \".skill\");\n var skillLetter = \"PQWER\"; // 0 is the passive.\n var parsed = {skills: []};\n parsed.title = \"{{order}} (\" + buildText.innerText.trim() + \")\";\n\n for (var i = 1; i <= 4; i++) {\n var skill = querySelectorAll(skills[i], \".skill-selections > div\");\n expect(skill, skill.length == 18);\n for (var j = 0; j < 18; j++) {\n if (skill[j].className.search(\"selected\") != -1) {\n if (parsed.skills[j] != null)\n throw new Error(\"Skills: Multiple choices for level \" + (j+1));\n parsed.skills[j] = skillLetter[i];\n }\n }\n }\n return parsed;\n}", "function getHobbies(){\n let allelements = document.querySelectorAll('[name=\"skills\"]')\n let arrayofallelements = [...allelements]\n let result = arrayofallelements.forEach(x => {\n if (x.selected){\n console.log(x.innerText)\n }\n })\n return result\n}", "function getAll() {\n return skills;\n }", "function parseQuests() {\n addElementsToQuestList();\n return availableQuests;\n }", "function getAllSkills () {\n return skills;\n }", "function getHobbies() {\n\tlet array = document.getElementsByName('skills');\n\t\n\t//Expect only one skills section\n\tlet skillSelect = array[0];\n\tif(skillSelect && skillSelect.tagName === 'SELECT') {\n\t\tlet child = skillSelect.firstElementChild;\n\t\t\n\t\twhile(child && child.tagName === 'OPTION') {\n\t\t\tconsole.log('value = ' + child.getAttribute('value') + \", contents = \" + child.innerHTML);\n\t\t\tchild = child.nextElementSibling;\n\t\t}\n\t}\n\t\n}", "function getGraftAbilities(type){\n\n //current type choices - Other, Special\n\n var abilityString = type + \"Abilities\";\n\n //check step 3 subtype graft skills\n var Abilities = [];\n var subtype = $('#creatureSubTypeDrop').val().trim();\n if (subtype != '' && subtype != 'None') {\n if (creatureSubType[subtype].hasOwnProperty(abilityString)){\n Abilities = Abilities.concat(creatureSubType[subtype][abilityString]);\n }\n if (creatureSubType[subtype].hasOwnProperty(\"SubRaces\")){\n subRaceDrop = $('#stepThreeOptionDrop').val().trim();\n if (creatureSubType[subtype].SubRaces[subRaceDrop].hasOwnProperty(abilityString)){\n Abilities = Abilities.concat(creatureSubType[subtype].SubRaces[subRaceDrop][abilityString]);\n }\n }\n }\n //check step 4 class graft\n var classDrop = $('#classDrop').val().trim();\n if (classDrop != '' && classDrop != 'None') {\n if (classData[classDrop].hasOwnProperty(abilityString)){\n Abilities = Abilities.concat(classData[classDrop][abilityString]);\n }\n }\n //check step 5 graft\n var graft = $('#graftDrop').val().trim();\n if (graft != '' && graft != 'None') {\n for (var subgraft in graftTemplates){\n if (graftTemplates[subgraft].hasOwnProperty(graft)){\n if (graftTemplates[subgraft][graft].hasOwnProperty(abilityString)){\n Abilities = Abilities.concat(graftTemplates[subgraft][graft][abilityString]);\n }\n }\n }\n }\n\n //capitalise to match data array entries\n for (var i = 0; i < Abilities.length; i++) {\n Abilities[i] = Abilities[i].capitalise();\n }\n\n //remove duplicates\n var unique = Abilities.filter(function(elem, index, self) {\n return index === self.indexOf(elem);\n })\n\n unique = unique.sort();\n\n return unique;\n\n}", "get skills() {\n return this._skills;\n }", "function updateSkills() {\n\tvar choices = \"\";\n\tvar k = 1;\n\tvar oskillList = [];\n\tvar oskillOptions = [];\n\tfor (let o = 0; o < oskills.length; o++) {\n\t\tif (character[oskills[o]] > 0) {\n\t\t\tvar natClass = oskills_info[oskills[o]].native_class;\n\t\t\tif (character.class_name.toLowerCase() != natClass) {\n\t\t\t\tvar natIndex = oskills_info[oskills[o]].i;\n\t\t\t\tvar addSkill = 0;\n\t\t\t\tif (natClass != \"none\") { if (skills_all[natClass][natIndex].bindable > 0) { addSkill = 1 } } else { addSkill = 1 }\n\t\t\t\tif (addSkill == 1) {\n\t\t\t\t\toskillList[k] = oskills_info[oskills[o]].name\n\t\t\t\t\toskillOptions[k] = \"<option class='gray-all'>\" + oskills_info[oskills[o]].name + \"</option>\"\n\t\t\t\t\tchoices += oskillOptions[k]\n\t\t\t\t\tk++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tskillList = oskillList;\n\tskillOptions = oskillOptions;\n\tfor (let s = 0; s < skills.length; s++) {\n\t\tif (skills[s].bindable > 0 && (skills[s].level > 0 || skills[s].force_levels > 0)) {\n\t\t\tskillList[k] = skills[s].name\n\t\t\tskillOptions[k] = \"<option class='gray-all'>\" + skills[s].name + \"</option>\"\n\t\t\tchoices += skillOptions[k]\n\t\t\tk++\n\t\t}\n\t}\n\t\n\t// TODO: make less inefficient, include oskills\n\tfor (let s = 0; s < skills.length; s++) {\n\t\tif (skills[s].level == 0 && skills[s].force_levels == 0) {\n\t\t\tif (selectedSkill[0] == skills[s].name) { selectedSkill[0] = \" ­ ­ ­ ­ Skill 1\" }\n\t\t\tif (selectedSkill[1] == skills[s].name) { selectedSkill[1] = \" ­ ­ ­ ­ Skill 2\" }\n\t\t}\n\t}\n\n\tdocument.getElementById(\"dropdown_skill1\").innerHTML = \"<option class='gray-all' style='color:gray' disabled>\" + \" ­ ­ ­ ­ Skill 1\" + \"</option>\" + choices\n\tdocument.getElementById(\"dropdown_skill2\").innerHTML = \"<option class='gray-all' style='color:gray' disabled>\" + \" ­ ­ ­ ­ Skill 2\" + \"</option>\" + choices\n\tvar selectedIndex = [0,0];\n\tfor (let l = 0; l < skillList.length; l++) {\n\t\tif (skillList[l] == selectedSkill[0]) { selectedIndex[0] = l }\n\t\tif (skillList[l] == selectedSkill[1]) { selectedIndex[1] = l }\n\t}\n\tdocument.getElementById(\"dropdown_skill1\").selectedIndex = selectedIndex[0]\n\tdocument.getElementById(\"dropdown_skill2\").selectedIndex = selectedIndex[1]\n\tif (selectedSkill[0] == \" ­ ­ ­ ­ Skill 1\") { document.getElementById(\"skill1_info\").innerHTML = \":\"; document.getElementById(\"ar_skill1\").innerHTML = \"\"; }\n\tif (selectedSkill[1] == \" ­ ­ ­ ­ Skill 2\") { document.getElementById(\"skill2_info\").innerHTML = \":\"; document.getElementById(\"ar_skill2\").innerHTML = \"\"; }\n}", "function parseSkills(root) {\n var skills = querySelectorAll(root, \".ability-row\");\n var skillLetter = \"PQWER\"; // 0 is the passive.\n var parsed = [];\n for (var i = 1; i <= 4; i++) {\n var skill = querySelectorAll(skills[i], \".ability-check\");\n expect(skill, skill.length == 18);\n for (var j = 0; j < 18; j++) {\n if (skill[j].className.search(\"selected\") != -1) {\n if (parsed[j] != null)\n throw new Error(\"Skills: Multiple choices for level \" + (j+1));\n parsed[j] = skillLetter[i];\n }\n }\n }\n return parsed;\n}", "function getSkills() {\n skillService.getAll( function(response) {\n vic.skills = response;\n }, function(){});\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a full kernel model from the server by kernel id string.
function getKernelModel(id, settings) { settings = settings || __1.ServerConnection.makeSettings(); var url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id)); var request = { url: url, method: 'GET', cache: false }; return __1.ServerConnection.makeRequest(request, settings).then(function (response) { if (response.xhr.status !== 200) { throw __1.ServerConnection.makeError(response); } var data = response.data; try { validate.validateModel(data); } catch (err) { throw __1.ServerConnection.makeError(response, err.message); } return data; }, Private.onKernelError); }
[ "async getKernelModel() {\n const { serverParams, kernelId } = localStorage\n const { url, token } = JSON.parse(serverParams)\n\n const serverSettings = ServerConnection.makeSettings({\n baseUrl: url,\n wsUrl: util.baseToWsUrl(url),\n token: token,\n })\n\n const kernelModel = await Kernel.findById(kernelId, serverSettings)\n return { serverSettings, kernelModel }\n }", "function getKernelModel(id, options) {\n\t options = options || {};\n\t var baseUrl = options.baseUrl || utils.getBaseUrl();\n\t var url = utils.urlPathJoin(baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id));\n\t var ajaxSettings = utils.ajaxSettingsWithToken(options.ajaxSettings, options.token);\n\t ajaxSettings.method = 'GET';\n\t ajaxSettings.dataType = 'json';\n\t ajaxSettings.cache = false;\n\t return utils.ajaxRequest(url, ajaxSettings).then(function (success) {\n\t if (success.xhr.status !== 200) {\n\t throw utils.makeAjaxError(success);\n\t }\n\t var data = success.data;\n\t try {\n\t validate.validateModel(data);\n\t }\n\t catch (err) {\n\t throw utils.makeAjaxError(success, err.message);\n\t }\n\t return data;\n\t }, Private.onKernelError);\n\t }", "function getKernelModel(id, options) {\n options = options || {};\n var baseUrl = options.baseUrl || utils.getBaseUrl();\n var url = utils.urlPathJoin(baseUrl, KERNEL_SERVICE_URL, encodeURIComponent(id));\n var ajaxSettings = options.ajaxSettings || {};\n ajaxSettings.method = 'GET';\n ajaxSettings.dataType = 'json';\n ajaxSettings.cache = false;\n return utils.ajaxRequest(url, ajaxSettings).then(function (success) {\n if (success.xhr.status !== 200) {\n return utils.makeAjaxError(success);\n }\n var data = success.data;\n try {\n validate.validateKernelModel(data);\n }\n catch (err) {\n return utils.makeAjaxError(success, err.message);\n }\n return data;\n }, Private.onKernelError);\n }", "function findKernelById(id, options) {\n var kernels = Private.runningKernels;\n for (var clientId in kernels) {\n var kernel = kernels[clientId];\n if (kernel.id === id) {\n var result = { id: kernel.id, name: kernel.name };\n return Promise.resolve(result);\n }\n }\n return Private.getKernelModel(id, options).catch(function () {\n return Private.typedThrow(\"No running kernel with id: \" + id);\n });\n}", "function findById(id, settings) {\n var kernel = algorithm_1.find(Private.runningKernels, function (value) {\n return (value.id === id);\n });\n if (kernel) {\n return Promise.resolve(kernel.model);\n }\n return getKernelModel(id, settings).catch(function () {\n throw new Error(\"No running kernel with id: \" + id);\n });\n }", "function findById(id, settings) {\n let kernel = algorithm_1.find(Private.runningKernels, value => {\n return value.id === id;\n });\n if (kernel) {\n return Promise.resolve(kernel.model);\n }\n return getKernelModel(id, settings).catch(() => {\n throw new Error(`No running kernel with id: ${id}`);\n });\n }", "findById(id) {\n return kernel_1.Kernel.findById(id, this.serverSettings);\n }", "function connectToKernel(id, options) {\n for (var clientId in Private.runningKernels) {\n var kernel = Private.runningKernels[clientId];\n if (kernel.id === id) {\n return Promise.resolve(kernel.clone());\n }\n }\n return Private.getKernelModel(id, options).then(function (model) {\n return new Kernel(options, id);\n }).catch(function () {\n return Private.typedThrow(\"No running kernel with id: \" + id);\n });\n}", "async getKernel() {\n const { serverSettings, kernelModel } = await this.getKernelModel()\n return await Kernel.connectTo(kernelModel, serverSettings)\n }", "get kernelId() {\n return this.getStringAttribute('kernel_id');\n }", "function serviceGetModel(req, resp) {\n\t\tlogger.info(\"<Service> GetModel.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tgetModel(getData.id, function (err, obj) {\n\t\t\tif (err) error(2, resp);\n\t\t\telse resp.end(JSON.stringify(obj)); \n\t\t});\n\t}", "static get deviceModel() {}", "function loadModel(id) {\n return (0, _ajax2.default)('/models/' + id).then(function (response) {\n return JSON.parse(response);\n });\n}", "function loadModel(id) {\n return persistenceService.readObject(SPACE, id);\n }", "_getInternalModelForId(modelName, id, clientId) {\n var internalModel;\n\n if (clientId) {\n internalModel = this._newlyCreatedModelsFor(modelName).get(clientId);\n }\n\n if (!internalModel) {\n internalModel = this._internalModelsFor(modelName).get(id);\n }\n\n return internalModel;\n }", "function loadModel(id) {\n return ajax(`/models/${id}`).then(response => JSON.parse(response));\n}", "function getModel(id) {\n // console.log('Getting model: ' + model.id)\n return modelCache[id] ? modelCache[id] : null;\n }", "getKernelPreference(path, widgetName, kernel) {\n widgetName = widgetName.toLowerCase();\n let widgetFactory = this._widgetFactories[widgetName];\n if (!widgetFactory) {\n return void 0;\n }\n let modelFactory = this.getModelFactory(widgetFactory.modelName || 'text');\n if (!modelFactory) {\n return void 0;\n }\n let language = modelFactory.preferredLanguage(coreutils_1.PathExt.basename(path));\n let name = kernel && kernel.name;\n let id = kernel && kernel.id;\n return {\n id,\n name,\n language,\n shouldStart: widgetFactory.preferKernel,\n canStart: widgetFactory.canStartKernel\n };\n }", "async function getDevicePrivateModel(config, privateId) {\n try {\n const options = {\n method: \"GET\",\n uri: `${config.server}:${config.port}/api/devicePrivateData/${privateId}`,\n json: true, // Automatically stringifies the body to JSON\n };\n\n const data = await rp(options);\n\n return data.collection;\n } catch (err) {\n config.logr.error(`Error in util.js/getDevicePrivateModel(): ${err}`);\n config.logr.error(`Error stringified: ${JSON.stringify(err, null, 2)}`);\n throw err;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`getKeyValueChunks` Split a string into chunks matching `: ` /:: declare function getKeyValueChunks (raw: string): Array
function getKeyValueChunks(raw) { var chunks = []; var offset = 0; var sep = ';'; var hasUnclosedUrl = /url\([^\)]+$/; var chunk = ''; var nextSplit; while (offset < raw.length) { nextSplit = raw.indexOf(sep, offset); if (nextSplit === -1) { nextSplit = raw.length; } chunk += raw.substring(offset, nextSplit); // data URIs can contain semicolons, so make sure we get the whole thing if (hasUnclosedUrl.test(chunk)) { chunk += ';'; offset = nextSplit + 1; continue; } chunks.push(chunk); chunk = ''; offset = nextSplit + 1; } return chunks; }
[ "function getKeyValueChunks(raw) {\n\t\t\t\tvar chunks = [];\n\t\t\t\tvar offset = 0;\n\t\t\t\tvar sep = ';';\n\t\t\t\tvar hasUnclosedUrl = /url\\([^\\)]+$/;\n\t\t\t\tvar chunk = '';\n\t\t\t\tvar nextSplit;\n\t\t\t\twhile (offset < raw.length) {\n\t\t\t\t\tnextSplit = raw.indexOf(sep, offset);\n\t\t\t\t\tif (nextSplit === -1) {\n\t\t\t\t\t\tnextSplit = raw.length;\n\t\t\t\t\t}\n\n\t\t\t\t\tchunk += raw.substring(offset, nextSplit);\n\n\t\t\t\t\t// data URIs can contain semicolons, so make sure we get the whole thing\n\t\t\t\t\tif (hasUnclosedUrl.test(chunk)) {\n\t\t\t\t\t\tchunk += ';';\n\t\t\t\t\t\toffset = nextSplit + 1;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tchunks.push(chunk);\n\t\t\t\t\tchunk = '';\n\t\t\t\t\toffset = nextSplit + 1;\n\t\t\t\t}\n\n\t\t\t\treturn chunks;\n\t\t\t}", "function getKeyValueChunks (raw) {\n var chunks = [];\n var offset = 0;\n var sep = ';';\n var hasUnclosedUrl = /url\\([^\\)]+$/;\n var chunk = '';\n var nextSplit;\n while (offset < raw.length) {\n nextSplit = raw.indexOf(sep, offset);\n if (nextSplit === -1) { nextSplit = raw.length; }\n\n chunk += raw.substring(offset, nextSplit);\n\n // data URIs can contain semicolons, so make sure we get the whole thing\n if (hasUnclosedUrl.test(chunk)) {\n chunk += ';';\n offset = nextSplit + 1;\n continue;\n }\n\n chunks.push(chunk);\n chunk = '';\n offset = nextSplit + 1;\n }\n\n return chunks;\n}", "function getKeyValueChunks(raw) {\n\t var chunks = [];\n\t var offset = 0;\n\t var sep = ';';\n\t var hasUnclosedUrl = /url\\([^\\)]+$/;\n\t var chunk = '';\n\t var nextSplit;\n\t while (offset < raw.length) {\n\t nextSplit = raw.indexOf(sep, offset);\n\t if (nextSplit === -1) {\n\t nextSplit = raw.length;\n\t }\n\t\n\t chunk += raw.substring(offset, nextSplit);\n\t\n\t // data URIs can contain semicolons, so make sure we get the whole thing\n\t if (hasUnclosedUrl.test(chunk)) {\n\t chunk += ';';\n\t offset = nextSplit + 1;\n\t continue;\n\t }\n\t\n\t chunks.push(chunk);\n\t chunk = '';\n\t offset = nextSplit + 1;\n\t }\n\t\n\t return chunks;\n\t}", "keyPieces(key) {\n const pieces = key.split(/,/);\n return { path: pieces[0], stage: parseInt(pieces[1]) };\n }", "splitInto3Segments(key) {\n const bytes = hexToBytes(key);\n\n // we're going to split in 3 parts\n let start = 0, end = 0;\n let bufpart = [];\n let partLen = Math.round(bytes.length / 3);\n for (let i = 0; i < 3; i++) {\n if (i === 2) {\n // last element store the remainder\n end = bytes.length;\n } else {\n end = start + partLen;\n }\n bufpart[i] = bytes.slice(start, end);\n start = start + bufpart[i].length;\n }\n\n let keyLength = Math.max(partLen, bufpart[2].length); // this will typically be 11 for Ethereum private keys\n return {keySegments: bufpart, keyLength};\n }", "function splitKeyValuePair(str){var index=str.indexOf('=');var key;var val;if(index===-1){key=str;}else{key=str.substr(0,index);val=str.substr(index+1);}return[key,val];}", "function splitKeyValuePair(str) {\n var index = str.indexOf('=');\n var key;\n var val;\n\n if (index === -1) {\n key = str;\n } else {\n key = str.substr(0, index);\n val = str.substr(index + 1);\n }\n\n return [key, val];\n}", "splitArmoredBlocks(keyBlockStr) {\n let myRe = /-----BEGIN PGP (PUBLIC|PRIVATE) KEY BLOCK-----/g;\n let myArray;\n let retArr = [];\n let startIndex = -1;\n while ((myArray = myRe.exec(keyBlockStr)) !== null) {\n if (startIndex >= 0) {\n let s = keyBlockStr.substring(startIndex, myArray.index);\n retArr.push(s);\n }\n startIndex = myArray.index;\n }\n\n retArr.push(keyBlockStr.substring(startIndex));\n\n return retArr;\n }", "function hashFold(key, chunkSize) {\n // Define the size of each divided portion\n let strKey = String(key); // Convert integer into string for slicing\n console.log(\"Key: \" + strKey);\n let hashVal = 0;\n console.log(\"Chunks:\");\n for (var i = 0; i < chunkSize; i += strKey.length) {\n if (i + chunkSize < strKey.length) {\n console.log(strKey.slice(i, i + chunkSize)); // Slice the appropriate chunk from the string\n hashVal += Number(strKey.slice(i, i + chunkSize)); // convert into integer\n } else {\n console.log(strKey.slice(i, strKey.length));\n hashVal += Number(strKey.slice(i, strKey.length));\n }\n }\n return hashVal;\n}", "function splitKeyValuePair(str) {\n\t var index = str.indexOf('=');\n\t var key;\n\t var val;\n\n\t if (index === -1) {\n\t key = str;\n\t } else {\n\t key = str.substr(0, index);\n\t val = str.substr(index + 1);\n\t }\n\n\t return [key, val];\n\t}", "function splitKeyValuePair(str) {\n\t var index = str.indexOf('=');\n\t var key;\n\t var val;\n\t\n\t if (index === -1) {\n\t key = str;\n\t } else {\n\t key = str.substr(0, index);\n\t val = str.substr(index + 1);\n\t }\n\t\n\t return [key, val];\n\t}", "parseTextChunks() {\n\t\tlet textChunks = this.metaChunks.filter(info => info.type === TEXT)\n\t\tfor (let seg of textChunks) {\n\t\t\tlet [key, val] = this.file.getString(seg.start, seg.size).split('\\0')\n\t\t\tthis.injectKeyValToIhdr(key, val)\n\t\t}\n\t}", "function splitElements(raw) {\n\tif (typeof raw != 'string')\n\t\traw = String(raw)\n\tlet x = -1\n\tlet elt = ''\n\tlet elements = []\n\tlet end\n\tlet c\n\n\twhile (c = raw[++x]) switch (c) {\n\t\tcase '.':\n\t\t\tif (!elt)\n\t\t\t\tthrow error('Unexpected \".\"')\n\t\t\telements.push(elt)\n\t\t\telt = ''\n\t\tcontinue\n\n\t\tcase '\"':\n\t\tcase \"'\":\n\t\t\tend = fragment(raw, x)\n\t\t\tif (end == x+2)\n\t\t\t\tthrow error('Empty string key')\n\t\t\telt += raw.slice(x+1, end-1)\n\t\t\tx = end-1\n\t\tcontinue\n\n\t\tdefault:\n\t\t\telt += c\n\t}\n\n\t// we add the last one\n\tif (elt)\n\t\telements.push(elt)\n\n\treturn elements\n}", "multilineValue() {\n var [key, c1, c2, ...values] = trimStart(this.peek());\n var k = key.value.trim();\n // check for valid keys\n if (!k.length || k.match(/[\\s\\?\\/=\"']/)) {\n return true;\n }\n this.advance();\n var next;\n var ender = k.toLowerCase();\n while (next = this.peek()) {\n if (this.matchValues(\":\", \":\", new RegExp(ender, \"i\"))) {\n break;\n }\n values.push(...next);\n this.advance();\n }\n var value = combine(values);\n this.addInstruction(\"value\", k, value);\n this.advance();\n }", "answerDataToKeyValues (data) {\n let strings = [];\n let kvPairs = {};\n let kvPointer = 0;\n let kvLen = data[kvPointer];\n while (kvLen) {\n let pair = data.slice(kvPointer + 1, kvPointer + 1 + kvLen);\n strings.push(pair.toString());\n let kvMatch = /^([^=]+)=([^=]*)$/.exec(pair.toString());\n if (kvMatch) {\n kvPairs[kvMatch[1]] = kvMatch[2];\n }\n kvPointer = kvPointer + 1 + kvLen;\n kvLen = data[kvPointer];\n }\n return { strings: strings, keyValuePairs: kvPairs };\n }", "function unpack_key(key) {\n key = key.split(opts.separator);\n\n // if it is length 1, and the end char is the terminator, it was just a string key\n if (key.length === 1 && key[0][key[0].length - 1] === opts.terminator) {\n key = key[0].substring(0, key[0].length - 1);\n }\n return key;\n }", "get segments(){\n return getKeySegmentsFromString(this.key);\n }", "function getFlagKeysFromString(value) {\n if (!value) return [];\n\n let result = value.split(key_value_delimiter);\n result = trimArray(result);\n\n return result;\n}", "function parse_value_chunks(value, needs_return, adapter, dynamic) {\n adapter.__value = chunk_string(value, dynamic);\n adapter.__dynamic = dynamic;\n adapter.__needs_return = needs_return;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
select a pokemon with a relevant type.
static getRelevantPokemon(typeArray) { // array of pokemon's relevant types // Randomly select a TYPE from the array let randType = typeArray[Math.floor(Math.random() * typeArray.length)] // Collect an array of pokemon with that TYPE let arrayTypePokemon= Pokemon.filterPokemonByType(randType) // Randomly select a POKEMON from the weakArray let pokemonWithType = arrayTypePokemon[Math.floor(Math.random() * arrayTypePokemon.length)] return pokemonWithType }
[ "function getPokemonByType(type){\n if(typeof(type) !== \"string\"){\n return {good:false , error:\"ERROR: Type must be a string\"};\n }\n type = type.toUpperCase();\n return pokemonList.filter(monster => monster.types.includes(type));\n }", "async function getPokemonByType(type) {\n var url = `https://pokeapi.co/api/v2/type/${type}`;\n var response = await fetch(url);\n var resultsJSON = await response.json();\n var pokemonByType = resultsJSON.pokemon;\n return pokemonByType;\n }", "function findPokemonByType(event) {\n if (event.target.tagName !== 'SPAN') {\n return;\n }\n typeHeading.textContent = `Type: ${event.target.textContent}`;\n axios\n .get(`https://pokeapi.co/api/v2/type/${event.target.textContent}`)\n .then((result) => displayNames(result.data.pokemon));\n}", "function selectCurrentPokemon(selected) {\n\tvar species = document.getElementById('pokemon_type').value;\n\tvar name = selected.options[species-1].text;\n\t//console.log(species);\n\t//console.log(name);\n\tvar lower = name.toLowerCase();\n\tvar img = document.getElementById('currentpokemonimg');\n\timg.src = \"https://img.pokemondb.net/artwork/\" + lower + \".jpg\";\n}", "function selectPokemon(e){\n\t\te.preventDefault();\n\n\t\t// Don't select more than allowed\n\t\tif(($(\".modal .rank.selected\").length >= maxCount)&&(!$(e.target).closest(\".rank\").hasClass(\"selected\"))){\n\t\t\treturn;\n\t\t}\n\n\t\t$(e.target).closest(\".rank\").toggleClass(\"selected\");\n\n\t\tvar index = $(e.target).closest(\".rank\").index();\n\t\tvar pokemon = filteredBox[index];\n\n\t\tif(selectMode == \"single\"){\n\t\t\tselector.setSelectedPokemon(pokemon);\n\t\t\tcloseModalWindow();\n\t\t} else{\n\t\t\t$(\".modal .poke-count\").html($(\".modal .rank.selected\").length);\n\t\t}\n\t}", "getPokemonByTypee(pokeType) {\n return this.http\n .get(_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.pokeUrlBase + 'type/' + pokeType, {\n headers: new _angular_common_http__WEBPACK_IMPORTED_MODULE_1__.HttpHeaders().set('Accept', 'applicaion/json'),\n })\n .pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.mergeMap)((res) => (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.zip)((0,rxjs__WEBPACK_IMPORTED_MODULE_4__.of)(res), this.http.get(this.selectRandomPokemon(res)))), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(([tipo, pokemon]) => ({\n type: tipo.name,\n name: pokemon.name,\n sprite: pokemon.sprites.front_default,\n image: pokemon.sprites.other['official-artwork'].front_default,\n })));\n }", "filterByType (pokemon, type) {\n const filterType = [];\n for(let i= 0; i < pokemon.length; i++){\n for(let t=0; t < pokemon[i].type.length; t++){\n if (pokemon[i].type[t] === type){\n filterType.push(pokemon[i]);\n }\n }\n }\n\n return filterType;\n}", "function selectCup(e){\n\t\t\t\tvar cup = $(\".cup-select option:selected\").val();\n\t\t\t\tbattle.setCup(cup);\n\t\t\t\t\n\t\t\t\t// Filter PokeSelect options by type\n\t\t\t\t\n\t\t\t\tconsole.log(gm);\n\t\t\t\t\n\t\t\t\tvar cupTypes = gm.data.cups[cup];\n\t\t\t\t\n\t\t\t\tfor(var i = 0; i < pokeSelectors.length; i++){\n\t\t\t\t\tpokeSelectors[i].filterByTypes(cupTypes);\n\t\t\t\t}\n\t\t\t}", "function typeSelect(){\n\tif( cbit != 1 ){\n\t\trandomItinerary(parkArray);\n\t\tnavigation(page2, page4);\n\t}else{\n\t\tnavigation(page2,page3);\n\t};\n}", "function pokeGetType(pokeLocation){\n\tloop:\n\tfor (var i = 0; i < pokeLocation.length; i++) {\n\t\tfor (var j = 0; j < typeLocation.length ; j++) {\n\t\t\tif(typeLocation[j][0] == pokeLocation[i]){\n\t\t\t\tvar typeChosen = typeLocation[j][Math.floor((Math.random() * (typeLocation[j].length-1))+1)]\n\t\t\t\tbreak loop;\n\t\t\t}\n\t\t}\n\t}\n\tapi(typeChosen);\n}", "function isPokemonType(pokemon, type) {\n for (var i = 0; i < POKEMON_DATA[pokemon.name].type.length; i++) {\n if (POKEMON_DATA[pokemon.name].type[i] === type) {\n return true;\n }\n };\n return false;\n}", "function playerSelect() {\n $(\".pokemon .poke-container\").click(function () {\n // get the name of the clicked pokemon and compare it to the name in pokemonList array\n let name = $(this).children(\"h2\").text();\n for (let i in pokemonList) {\n if (pokemonList[i].name === name) {\n // find and save the chosen pokemon as the player's choice\n player.choice = pokemonList[i];\n //hide the pokemon list\n pokemon.style.display = \"none\";\n //after selecting pokemon, generate the pokemon in the battle arena, along with the user attacks\n createPoke($(\".arena .player\"), player.choice);\n createPoke($(\".arena .computer\"), computer.choice);\n attackList();\n }\n }\n });\n}", "getSelectedDish(type) {\n\t\tvar theDish = menu.find(dish => dish.type = type);\n\t\treturn theDish;\n\t}", "async getPokemons(type, value) {\n let response = {};\n await request.get('http://localhost:3000/pokemon', { form: { type, value } }, function(\n err,\n http,\n body\n ) {\n response.body = body.length == 2 ? 'Error: The pokemon was not found' : JSON.parse(body);\n response.status = http.statusCode;\n });\n return response;\n }", "function searchPokemonFromType(event) {\n if (event.target.tagName !== 'LI') {\n return;\n }\n search.value = event.target.textContent;\n searching();\n}", "function addAlternativePokemon(e){\n\t\t\t\tvar id = $(e.target).attr(\"pokemon\");\n\t\t\t\t$(\".poke-select-container .poke.multi .add-poke-btn\").trigger(\"click\", false);\n\t\t\t\t$(\".modal .poke-select option[value=\\\"\"+id+\"\\\"]\").prop(\"selected\", \"selected\");\n\t\t\t\t$(\".modal .poke-select\").trigger(\"change\");\n\t\t\t\t$(\"html, body\").animate({ scrollTop: $(\".poke.multi\").offset().top }, 500);\n\t\t\t}", "function selectState(type) {\n if (type === \"promoters\") {\n return state.promoters;\n } else if (type === \"passives\") {\n return state.passives;\n } else if (type === \"detractors\") {\n return state.detractors;\n }\n }", "function loadPinpointType(typeId) {\n // Send a request to the api using the 'GetAllTypes' command\n api(\"GetAllTypes\", function(data) {\n // Append an 'option' element for each type\n $.each(data, function (key, value) {\n $('#pinpointType').append($(\"<option></option>\").attr(\"value\", value[\"id\"]).text(value[\"name\"]));\n });\n\n // Pre-select the specified element\n $('#pinpointType option').eq(typeId - 1).attr('selected', '');\n });\n}", "function displayPokemonOfType(type = \"\"){\r\n //reset the display div \r\n const display = document.getElementById(\"pokemon-display\");\r\n display.innerHTML = getTableHeaders();\r\n //add all pokemon of a certain type to the display container\r\n allPokemon.filter(pokemon=>{\r\n [type1,type2] = pokemon.types;\r\n return (type1.type.name.toLowerCase() === type.toLowerCase() ||\r\n (type2 != null && type2.type.name.toLowerCase() === type.toLowerCase()))\r\n }).forEach(pokemon=>{\r\n addPokemonToDisplayListForm(pokemon);\r\n });\r\n display.innerHTML += \"</table>\"\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Temporarily removes code blocks from contents before transforming, transforms, then restores the the blocks.
transformWithoutCodeBlocks_(contents, transformer) { const codeBlockVars = new Map(); // Replace code blocks with variable references contents = contents.replace(patterns.newMarkdownCodePattern(), (match) => { const varRef = `{{ code_${ uuid() } }}`; codeBlockVars.set(varRef, match); return varRef; }); // Run transformation function against code-less Markdown contents = transformer(contents); // Restore code blocks for (let [k, v] of codeBlockVars.entries()) { contents = contents.replace(k, v); } return contents; }
[ "function cleanupBlocks(ast) {\n \n esrecurse.visit(ast, {\n BlockStatement: function (node) {\n var cleaned = [];\n for (var i = 0; i < node.body.length; i++) {\n var stmt = node.body[i];\n this.visit(stmt);\n if (stmt.type === 'BlockStatement' && stmt.needed === false) {\n cleaned = cleaned.concat(stmt.body);\n } else {\n cleaned.push(stmt);\n }\n }\n node.body = cleaned;\n }\n });\n }", "removeBlockTransformation(state, block, transformData, shouldMerge = true) {\n const { selection } = state;\n const { listBlockType, textMarker, indentationCount } = transformData;\n\n // Do nothing if target block is not of the transform block type.\n if (block.type !== transformData.blockType) return;\n\n // Remove block and block marker\n const transform = state\n .transform()\n .moveToRangeOf(block)\n .removeMark(textMarker)\n .setBlock('paragraph');\n\n // Remove list blocks\n if (listBlockType) {\n transform.unwrapBlock(listBlockType);\n\n // Remove indentations if any\n if (indentationCount > 0) {\n const deleteRange = selection\n .collapseToStartOf(block)\n .extendForward(indentationCount);\n transform\n .moveTo(deleteRange)\n .delete();\n }\n }\n\n // Revert selection changes\n transform.moveTo(selection);\n\n // Apply changes\n return transform.apply({ merge: shouldMerge });\n }", "function cleanCode(ast) {\n // Coalese BlockStatements\n\n // TODO: For ES6, this needs more care, as blocks containing 'let' have a scope of their own\n parser.treeWalker(ast,function(node, descend, path){\n descend();\n // If this node is a block with vanilla BlockStatements (no controlling entity), merge them\n var block,child ;\n if ((block = examine(node).isBlockStatement) && !containsBlockScopedDeclarations(block)) {\n // Remove any empty statements from within the block\n for (var i=0; i<block.length; i++) {\n if (child = examine(block[i]).isBlockStatement) {\n [].splice.apply(block,[i,1].concat(child)) ;\n }\n }\n }\n }) ;\n\n // Truncate BlockStatements with a Jump (break;continue;return;throw) inside\n parser.treeWalker(ast,function(node, descend, path){\n descend();\n if (examine(node).isJump) {\n var ref = path[0] ;\n if ('index' in ref) {\n var i = ref.index+1 ;\n var ctn = ref.parent[ref.field] ;\n while (i<ctn.length) {\n // Remove any statements EXCEPT for function/var definitions\n if ((ctn[i].type==='VariableDeclaration')\n || ((examine(ctn[i]).isFunction)\n && ctn[i].id))\n i += 1 ;\n else\n ctn.splice(i,1) ;\n }\n }\n }\n }) ;\n\n /* Inline continuations that are only referenced once */\n\n // Find any continuations that have a single reference\n parser.treeWalker(ast,function(node, descend, path){\n descend();\n if (node.$thisCall && continuations[node.name]) {\n if (continuations[node.name].ref) {\n delete continuations[node.name] ; // Multiple ref\n } else {\n continuations[node.name].ref = node.$thisCall ;\n }\n }\n }) ;\n\n var calls = Object.keys(continuations).map(function(c){ return continuations[c].ref }) ;\n if (calls.length) {\n // Replace all the calls to the continuation with the body from the continuation followed by 'return;'\n parser.treeWalker(ast,function(node, descend, path){\n descend();\n if (calls.indexOf(node)>=0) {\n if (path[1].self.type==='ReturnStatement') {\n var sym = node.$thisCallName ;\n var repl = cloneNode(continuations[sym].def.body.body) ;\n continuations[sym].$inlined = true ;\n if (!examine(path[1].self).isJump)\n repl.push({type:'ReturnStatement'}) ;\n path[1].replace(repl) ;\n }\n }\n }) ;\n\n var defs = Object.keys(continuations).map(function(c){ return continuations[c].$inlined && continuations[c].def }) ;\n // Remove all the (now inline) declarations of the continuations\n parser.treeWalker(ast,function(node, descend, path){\n descend();\n if (defs.indexOf(node)>=0) {\n path[0].remove() ;\n }\n }) ;\n }\n /*\n // Find declarations of functions of the form:\n // function [sym]() { return _call_.call(this) }\n // or\n // function [sym]() { return _call_() }\n // and replace with:\n // _call_\n // If the [sym] exists and is referenced elsewhere, replace those too. This\n // needs to be done recursively from the bottom of the tree upwards.\n // NB: If _call_ is in the parameter list for the function, this is NOT a correct optimization\n\n // For either of the call forms above, return the actually invoked symbol name\n function simpleCallName(node) {\n if ((node.TYPE==\"Call\")\n && node.args.length==0\n && node.expression instanceof U2.AST_SymbolRef) {\n return node.expression.name ;\n }\n\n if ((node.TYPE==\"Call\")\n && node.$thisCallName) {\n return node.$thisCallName ;\n }\n\n return null ;\n }\n\n var replaced = {} ;\n asyncWalk = new U2.TreeWalker(function(node, descend){\n descend();\n\n if (node instanceof U2.AST_Lambda) {\n if ((node.body[0] instanceof U2.AST_Return) && node.body[0].value) {\n var to = simpleCallName(node.body[0].value) ;\n if (to && node.argnames.every(function(sym){ return sym.name != to })) {\n if (replaced[to])\n to = replaced[to] ;\n var from = node.name && node.name.name ;\n if (from) {\n var stack = asyncWalk.stack;\n for (var i = stack.length-1; --i >= 0;) {\n var scope = stack[i];\n if (scope instanceof U2.AST_Scope) {\n replaced[from] = to ;\n replaceSymbols(scope,from,to) ;\n }\n }\n coerce(node,new U2.AST_DeletedNode()) ;\n } else {\n // This is an anonymous function, so can be replaced in-situ\n coerce(node,new U2.AST_SymbolRef({name:to})) ;\n }\n }\n }\n }\n return true ;\n }) ;\n ast.walk(asyncWalk) ;\n\n // The symbol folding above might generate lines like:\n // $return.$asyncbind(this,$error)\n // these can be simplified to:\n // $return\n asyncWalk = new U2.TreeWalker(function(node, descend){\n descend();\n\n if (node instanceof U2.AST_Call\n && node.expression instanceof U2.AST_Dot\n && node.expression.property == '$asyncbind'\n && node.expression.expression instanceof U2.AST_SymbolRef\n && node.expression.expression.name == \"$return\"\n ) {\n coerce(node,node.expression.expression) ;\n }\n return true ;\n }) ;\n ast.walk(asyncWalk) ;\n */\n return ast ;\n }", "function cleanCode(ast) {\n // Coalese BlockStatements\n parser.treeWalker(ast, function (node, descend, path) {\n descend();\n if (node.type==='ArrowFunctionExpression'\n && node.body.type === 'BlockStatement'\n && node.body.body.length===1\n && node.body.body[0].type==='ReturnStatement') {\n node.body = node.body.body[0].argument\n } else {\n var block, child;\n // If this node is a block with vanilla BlockStatements (no controlling entity), merge them\n if (block = examine(node).isBlockStatement) {\n // Remove any empty statements from within the block\n // For ES6, this needs more care, as blocks containing 'let/const/class' have a scope of their own\n for (var i = 0;i < block.length; i++) {\n if ((child = examine(block[i]).isBlockStatement) && !containsBlockScopedDeclarations(child)) {\n if (!containsBlockScopedDeclarations(block[i]))\n [].splice.apply(block, [i,1].concat(child));\n }\n }\n }\n }\n });\n // Truncate BlockStatements with a Jump (break;continue;return;throw) inside\n parser.treeWalker(ast, function (node, descend, path) {\n descend();\n if (examine(node).isJump) {\n var ref = path[0];\n if ('index' in ref) {\n var i = ref.index + 1;\n var ctn = ref.parent[ref.field];\n while (i < ctn.length) {\n // Remove any statements EXCEPT for function/var definitions\n if (ctn[i].type === 'VariableDeclaration' || examine(ctn[i]).isFunction && ctn[i].id)\n i += 1;\n else\n ctn.splice(i, 1);\n }\n }\n }\n });\n /* Inline continuations that are only referenced once */\n // Find any continuations that have a single reference\n parser.treeWalker(ast, function (node, descend, path) {\n descend();\n if (node.$thisCall && continuations[node.name]) {\n if (continuations[node.name].ref) {\n delete continuations[node.name]; // Multiple ref\n } else {\n continuations[node.name].ref = node.$thisCall;\n }\n }\n });\n var calls = Object.keys(continuations).map(function (c) {\n return continuations[c].ref;\n });\n if (calls.length) {\n // Replace all the calls to the continuation with the body from the continuation followed by 'return;'\n parser.treeWalker(ast, function (node, descend, path) {\n descend();\n if (calls.indexOf(node) >= 0) {\n if (path[1].self.type === 'ReturnStatement') {\n var sym = node.$thisCallName;\n var repl = cloneNode(continuations[sym].def.body.body);\n continuations[sym].$inlined = true;\n if (!examine(path[1].self).isJump)\n repl.push({\n type: 'ReturnStatement'\n });\n path[1].replace(repl);\n }\n }\n });\n var defs = Object.keys(continuations).map(function (c) {\n return continuations[c].$inlined && continuations[c].def;\n });\n // Remove all the (now inline) declarations of the continuations\n parser.treeWalker(ast, function (node, descend, path) {\n descend();\n if (defs.indexOf(node) >= 0) {\n path[0].remove();\n }\n });\n }\n\n // Hoist generated FunctionDeclarations within ES5 Strict functions (actually put them at the\n // end of the scope-block, don't hoist them, it's just an expensive operation)\n var looksLikeES6 = (ast.type==='Program' && ast.sourceType==='module') || contains(ast,function(n){\n return examine(n).isES6 ;\n },true) ;\n\n if (!looksLikeES6) {\n var useStrict = isStrict(ast) ;\n (function(ast){\n parser.treeWalker(ast, function (node, descend, path) {\n if (node.type==='Program' || node.type==='FunctionDeclaration' || node.type==='FunctionExpression') {\n var wasStrict = useStrict ;\n useStrict = useStrict || isStrict(node) ;\n if (useStrict) {\n descend();\n\n var functionScope = node.type === 'Program' ? node : node.body ;\n var functions = scopedNodes(functionScope,function(n,path){\n if (n.type==='FunctionDeclaration') {\n return path[0].parent !== functionScope ;\n }\n }) ;\n\n functions = functions.map(function (path) {\n return path[0].remove() ;\n });\n [].push.apply(functionScope.body,functions) ;\n } else {\n descend();\n }\n useStrict = wasStrict ;\n } else {\n descend();\n }\n }) ;\n })(ast);\n }\n\n /*\n function replaceSymbols(ast,from,to) {\n parser.treeWalker(ast,function(node,descend,path){\n descend() ;\n if (node.type=='Identifier' && node.name==from) {\n node.name = to ;\n }\n }) ;\n return ast ;\n }\n\n // Find declarations of functions of the form:\n // function [sym]() { return _call_.call(this) }\n // or\n // function [sym]() { return _call_() }\n // and replace with:\n // _call_\n // If the [sym] exists and is referenced elsewhere, replace those too. This\n // needs to be done recursively from the bottom of the tree upwards.\n // NB: If _call_ is in the parameter list for the function, this is NOT a correct optimization\n\n\n // The symbol folding above might generate lines like:\n // $return.$asyncbind(this,$error)\n // these can be simplified to:\n // $return\n */\n\n // Remove all the 'hiiden' node info generated during transformation\n parser.treeWalker(ast,function(node,descend,path){\n descend() ;\n Object.keys(node).filter(function(k){ return k[0]==='$'}).forEach(function(k){\n delete node[k] ;\n }) ;\n }) ;\n return ast;\n }", "async function postCompilation(code, transforms) {\n // Following successful Closure Compiler compilation, each transform needs an opportunity\n // to clean up work is performed in preCompilation via postCompilation.\n for (const transform of transforms) {\n const result = await transform.postCompilation(code, 'none');\n if (result && result.code) {\n code = result.code;\n }\n }\n return code;\n}", "applyTransforms(moduleName, contents) {\n let opts = this.syntax.defaultOptions({ contents, moduleName });\n if (opts.plugins && opts.plugins.ast) {\n // the user-provided plugins come first in the list, and those are the\n // only ones we want to run. The built-in plugins don't need to run here\n // in stage1, it's better that they run in stage3 when the appropriate\n // ember version is in charge.\n //\n // rather than slicing them off, we could choose instead to not call\n // syntax.defaultOptions, but then we lose some of the compatibility\n // normalization that it does on the user-provided plugins.\n opts.plugins.ast = this.getReversedASTPlugins(this.params.plugins.ast).map(plugin => {\n // Although the precompile API does, this direct glimmer syntax api\n // does not support these legacy plugins, so we must wrap them.\n return wrap_legacy_hbs_plugin_if_needed_1.default(plugin);\n });\n }\n opts.filename = moduleName;\n opts.moduleName = this.params.resolver\n ? this.params.resolver.absPathToRuntimeName(moduleName) || moduleName\n : moduleName;\n let ast = this.syntax.preprocess(contents, opts);\n return this.syntax.print(ast);\n }", "function replaceCodeBlocks(contents) {\n\tfunction processCode() {\n\t\treturn ast => {\n\t\t\tvisit(ast, 'code', node => {\n\t\t\t\tconst start = node.position.start.line;\n\t\t\t\tconst end = node.position.end.line;\n\t\t\t\tfor (let line = start; line < end - 1; line++) {\n\t\t\t\t\tlines[line] = '';\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\n\tconst lines = splitLines(contents);\n\tremark()\n\t\t.use(processCode)\n\t\t.process(contents);\n\treturn lines.join('\\n');\n}", "function replace() {\n var i, name, value;\n checkContext();\n\n if (savedBlocks) {\n for (i = 0; i < blockFunctionNames.length; i++) {\n name = blockFunctionNames[i];\n value = context[name];\n if (typeof value === 'function' && savedBlocks[name] !== value) {\n savedBlocks[name] = value;\n context[name] = wrapFn(value);\n }\n }\n } else {\n savedBlocks = {};\n for (i = 0; i < blockFunctionNames.length; i++) {\n name = blockFunctionNames[i];\n value = context[name];\n if (typeof value === 'function') {\n savedBlocks[name] = value;\n context[name] = wrapFn(value);\n }\n }\n }\n}", "transform(parseTree) {\n if (parseTree) {\n this.visit(parseTree);\n }\n const templateCount = this.templates.toArray().length;\n let currentIndex = 0;\n for (const template of this.templates) {\n currentIndex++;\n if (currentIndex < templateCount) {\n template.body = this.removeTrailingNewline(template.body);\n }\n }\n return this.templates;\n }", "applyTransforms(moduleName, contents) {\n let opts = this.syntax.defaultOptions({ contents, moduleName });\n if (opts.plugins && opts.plugins.ast) {\n // the user-provided plugins come first in the list, and those are the\n // only ones we want to run. The built-in plugins don't need to run here\n // in stage1, it's better that they run in stage3 when the appropriate\n // ember version is in charge.\n //\n // rather than slicing them off, we could choose instead to not call\n // syntax.defaultOptions, but then we lose some of the compatibility\n // normalization that it does on the user-provided plugins.\n opts.plugins.ast = opts.plugins.ast.slice(0, this.userPluginsCount);\n }\n let ast = this.syntax.preprocess(contents, opts);\n return this.syntax.print(ast);\n }", "function clearBlockFormat(editor, tagsToUnwrap, tagsToStopUnwrap, attributesToPreserve) {\n if (tagsToUnwrap === void 0) { tagsToUnwrap = exports.TAGS_TO_UNWRAP; }\n if (tagsToStopUnwrap === void 0) { tagsToStopUnwrap = exports.TAGS_TO_STOP_UNWRAP; }\n if (attributesToPreserve === void 0) { attributesToPreserve = exports.ATTRIBUTES_TO_PRESERVE; }\n editor.focus();\n editor.addUndoSnapshot(function (start, end) {\n var groups = [{}];\n var stopUnwrapSelector = tagsToStopUnwrap.join(',');\n // 1. Collapse the selected blocks and get first and last element\n collapseSelectedBlocks_1.default(editor, function (element) {\n var group = groups[groups.length - 1];\n var td = editor.getElementAtCursor(stopUnwrapSelector, element);\n if (td != group.td && group.first) {\n groups.push((group = {}));\n }\n group.td = td;\n group.first = group.first || element;\n group.last = element;\n });\n groups\n .filter(function (group) { return group.first; })\n .forEach(function (group) {\n // 2. Collapse with first and last element to make them under same parent\n var nodes = editor.collapseNodes(group.first, group.last, true /*canSplitParent*/);\n // 3. Continue collapse until we can't collapse any more (hit root node, or a table)\n if (canCollapse(tagsToStopUnwrap, nodes[0])) {\n while (editor.contains(nodes[0].parentNode) &&\n canCollapse(tagsToStopUnwrap, nodes[0].parentNode)) {\n nodes = [roosterjs_editor_dom_1.splitBalancedNodeRange(nodes)];\n }\n }\n // 4. Clear formats of the nodes\n nodes.forEach(function (node) {\n return clearNodeFormat(node, tagsToUnwrap, tagsToStopUnwrap, attributesToPreserve);\n });\n // 5. Clear CSS of container TD if exist\n if (group.td) {\n var styles = group.td.getAttribute('style') || '';\n var styleArray = styles.split(';');\n styleArray = styleArray.filter(function (style) {\n return style\n .trim()\n .toLowerCase()\n .indexOf('border') == 0;\n });\n styles = styleArray.join(';');\n if (styles) {\n group.td.setAttribute('style', styles);\n }\n else {\n group.td.removeAttribute('style');\n }\n }\n });\n editor.select(start, end);\n }, \"Format\" /* Format */);\n}", "function removeAllBlocks() {\n\tblocks.innerHTML = '';\n\tsetScriptNumber('');\n}", "revert() {\n // Delete the arrays of split text elements\n if (this.isSplit) {\n this.lines = null\n this.words = null\n this.chars = null\n }\n\n // Remove split text from target elements and restore original content\n this.elements.forEach((element) => {\n if (Data(element).isSplit && Data(element).html) {\n element.innerHTML = Data(element).html\n element.style.height = Data(element).cssHeight || ''\n element.style.width = Data(element).cssWidth || ''\n this.isSplit = false\n }\n })\n }", "function cleanBlock(editor) {\n _cleanBlock(editor.codemirror);\n}", "function processSnippet(code /*: string[]*/) /*: string*/ {\n const lines = code.split('\\n');\n let outputLines = [...lines];\n\n // Perform transformations individually, in order\n outputLines = removeFirstLineAfterComments(outputLines);\n outputLines = removeSectionsFromSnippet(outputLines);\n outputLines = adjustIndentation(outputLines);\n\n const content = [...outputLines].join(\"\\n\");\n return content;\n}", "removeExtraBlockMarkersFromBlock(state, block, transformData, shouldMerge = true) {\n const { document, selection } = state;\n const marks = Object.keys(this.schema.marks);\n\n // Determine the selection to remove the markers.\n // If the block is transformed we select everything past the matched text,\n // else we select the whole block.\n let markerSelection = selection.moveToRangeOf(block);\n if (transformData) {\n const markerLength = block.text.indexOf(' ') + 1;\n markerSelection = markerSelection\n .moveToOffsets(markerLength, block.length);\n }\n\n // Remove all possible markers from the selection\n const transform = state.transform().moveTo(markerSelection);\n let marksRemoved = false;\n marks.forEach((oneMark) => {\n const hasMark = document\n .getMarksAtRange(markerSelection)\n .some(mark => mark.type === oneMark);\n if (hasMark) {\n transform.removeMark(oneMark);\n marksRemoved = true;\n }\n });\n\n // Apply the transformation\n if (marksRemoved) {\n return transform\n .moveTo(selection)\n .apply({ merge: shouldMerge });\n }\n }", "function queueConversionOfCodeBlocks(paragraphs) {\n /// <param name=\"paragraphs\" type=\"Word.ParagraphCollection\" />\n\n var previousParagraphIsCode = false;\n var codeBlockParagraphs = [];\n\n paragraphs.items.forEach(function (paragraph) {\n\n // Only process a paragraph outside of a table.\n if (paragraph.tableNestingLevel === 0) {\n\n // Assumption: Code block paragraphs will use Consolas font.\n if (paragraph.font.name === 'Consolas') {\n if (!previousParagraphIsCode) {\n\n // This paragraph is Code, but the previous one was not,\n // so we are at the start of a code block. Add the ``` above the\n // paragraph to start the Markdown code block.\n var tripleTickParagraph = paragraph.insertParagraph('```', 'Before');\n previousParagraphIsCode = true;\n codeBlockParagraphs.push(tripleTickParagraph);\n }\n // Store in order to change its font and background later.\n codeBlockParagraphs.push(paragraph);\n }\n\n if ((paragraph.font.name != 'Consolas') && (previousParagraphIsCode)) {\n\n // This parapraph is not Code, but the previous one was,\n // so add the Markdown ``` to end the code block.\n\n // But Word gives a paragraph that is inserted \"Before\" the same style.\n // So change to Normal style temporarily to avoid, for example, giving\n // the ``` a Header 2 style which would result in Markdown: \"## ```\".\n var oldStyle = paragraph.styleBuiltIn;\n paragraph.styleBuiltIn = 'Normal';\n paragraph.insertParagraph('```', 'Before');\n paragraph.styleBuiltIn = oldStyle;\n previousParagraphIsCode = false;\n }\n }\n })\n\n // Change font and background color of code block paragraphs to make\n // look more like plain Markdown text.\n codeBlockParagraphs.forEach(function (codeParagraph) {\n codeParagraph.font.name = 'Calibri (Body)';\n codeParagraph.font.highlightColor = null;\n })\n }", "function rearrangeTilesAndContent() {\n\n var codeSnippets = FrameTrail.module('HypervideoModel').codeSnippets;\n\n for (var i = 0; i < codeSnippets.length; i++) {\n\n codeSnippets[i].initCodeSnippetFunction();\n\n }\n\n\n }", "function cleanBlock(editor) {\n\tvar cm = editor.codemirror;\n\t_cleanBlock(cm);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Color applied to heading after import to avoid duplication. Updates the main document, importing content from the source files. Uses the above parameters to locate content to be imported. Called from menu option.
function performImport() { // Gets the folder in Drive associated with this application. const folder = getFolderByName_(PROJECT_FOLDER_NAME); // Gets the Google Docs files found in the folder. const files = getFiles(folder); // Warns the user if the folder is empty. const ui = DocumentApp.getUi(); if (files.length === 0) { const msg = `No files found in the folder '${PROJECT_FOLDER_NAME}'. Run '${MENU.SETUP}' | '${MENU.SAMPLES}' from the menu if you'd like to create samples files.` ui.alert(APP_TITLE, msg, ui.ButtonSet.OK); return; } /** Processes main document */ // Gets the active document and body section. const docTarget = DocumentApp.getActiveDocument(); const docTargetBody = docTarget.getBody(); // Appends import summary section to the end of the target document. // Adds a horizontal line and a header with today's date and a title string. docTargetBody.appendHorizontalRule(); const dateString = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'MMMM dd, yyyy'); const headingText = `Imported: ${dateString}`; docTargetBody.appendParagraph(headingText).setHeading(APP_STYLE); // Appends a blank paragraph for spacing. docTargetBody.appendParagraph(" "); /** Process source documents */ // Iterates through each source document in the folder. // Copies and pastes new updates to the main document. let noContentList = []; let numUpdates = 0; for (let id of files) { // Opens source document; get info and body. const docOpen = DocumentApp.openById(id); const docName = docOpen.getName(); const docHtml = docOpen.getUrl(); const docBody = docOpen.getBody(); // Gets summary content from document and returns as object {content:content} const content = getContent(docBody); // Logs if document doesn't contain content to be imported. if (!content) { noContentList.push(docName); continue; } else { numUpdates++ // Inserts content into the main document. // Appends a title/url reference link back to source document. docTargetBody.appendParagraph('').appendText(`${docName}`).setLinkUrl(docHtml); // Appends a single-cell table and pastes the content. docTargetBody.appendTable(content); } docOpen.saveAndClose() } /** Provides an import summary */ docTarget.saveAndClose(); let msg = `Number of documents updated: ${numUpdates}` if (noContentList.length != 0) { msg += `\n\nThe following documents had no updates:` for (let file of noContentList) { msg += `\n ${file}`; } } ui.alert(APP_TITLE, msg, ui.ButtonSet.OK); }
[ "updateCodeMirrorHeadings() {\n Object.keys(this.headings).forEach((id) => {\n const h1Edit = document.getElementById(`${id}-edit`);\n applyRefStyles(h1Edit, this.codeMirrorSizerRef);\n });\n }", "function menuCallbackUpdate() {\n \n // Get style property\n var hStyle = getOneProperty('hStyle');\n \n if(!hStyle || hStyle == '0'){ // No hStyle to update\n var ui = DocumentApp.getUi();\n ui.alert('Could not update heading numbers','No heading numbering style is active. Please apply a style first.' , ui.ButtonSet.OK);\n } else { // Update\n numberHeadings(parseInt(hStyle));\n }\n}", "function syncContent() {\n print('Importing content from: ' + defaultsURL)\n\n // If the user didn't enter a valid URL, tell them, then exit\n var sheetId = validateURL()\n if (!sheetId) {\n var alert = NSAlert.alloc().init()\n alert.setIcon(iconImage)\n \talert.setMessageText(\"Invalid Google Sheet URL\")\n \talert.setInformativeText(\"The URL you entered wasn't valid\")\n \talert.addButtonWithTitle(\"Ok\")\n return alert.runModal()\n }\n\n // Fetch all the values for the given URL\n fetchSheetValues(sheetId)\n\n if (sheetValues.length < 1)\n return\n\n // Update the values for each page\n doc.pages().forEach(function(page) {\n\n var sheetTitle = valueFromName(page.name())\n var pageValues = valuesForSheet(sheetTitle)\n\n // If no sheet title provided - just use the first sheet\n if (sheetTitle == '' || pageValues == null) {\n var firstSheet = sheetValues[0]\n pageValues = firstSheet.values\n }\n\n page.children().forEach(function(child) {\n if (child.isMemberOfClass(MSSymbolInstance)) {\n\n // Store new overrides that need to be made\n var overrides = {}\n\n child.symbolMaster().children().forEach(function(symbolLayer) {\n // Ignore layers that are not text layers\n // Only include layers that have a '#' in the name\n if (!symbolLayer.isMemberOfClass(MSTextLayer) || symbolLayer.name().indexOf('#') < 0)\n return\n\n var nameFormat = formatName(symbolLayer.name())\n var childName = nameFormat.lookupName\n var values = pageValues[childName]\n\n // Get the index from the name of the Symbol instance. e.g. '.3'\n var instanceIndex = indexFromName(child.name())\n // Set the overrides to match the index of the instance name\n if (instanceIndex && instanceIndex != nameFormat.index) {\n nameFormat.index = instanceIndex\n }\n\n // Set the value of the text layer accordingly\n // Based on if it was given an index, otherwise return the first one\n if (values && values.length > 0) {\n var value = (values.length >= nameFormat.index) ? values[nameFormat.index - 1] : 'N/A'\n overrides[symbolLayer.objectID()] = value == '' ? 'N/A' : value\n } else {\n overrides[symbolLayer.objectID()] = 'N/A'\n }\n })\n\n // Apply the new overrides\n child.addOverrides_ancestorIDs(overrides, nil)\n }\n\n // Only check text layers\n // Only include layers that have a '#' in the name\n if (!child.isMemberOfClass(MSTextLayer) || child.name().indexOf('#') < 0)\n return\n\n\n var nameFormat = formatName(child.name())\n var childName = nameFormat.lookupName\n var values = pageValues[childName]\n\n // Set the value of the text layer accordingly\n // Based on if it was given an index, otherwise return the first one\n if (values && values.length > 0) {\n var value = (values.length >= nameFormat.index) ? values[nameFormat.index - 1] : 'N/A'\n child.setStringValue(value == '' ? 'N/A' : value)\n } else {\n child.setStringValue('N/A')\n }\n })\n })\n\n saveDefaults(doc.hash())\n\n doc.showMessage(\"Content successfully imported! ⚡️\")\n\n doc.reloadInspector()\n}", "function changeHeadingWord (color) {\ndocument.getElementById('heading').innerHTML=color; }", "function updateHeader() {\n removeChemElements();\n elementsCurrentlyUsed.forEach(molId => addChemElement(molId));\n}", "function updateHeading(){\n\t\tif (ide == \"st3\"){ // use Sublime Text 3 heading\n\t\t\t$(\".your_snippet\").text(\"Your Sublime Text Snippet:\")\n\t\t\t$(\".hidden_heading\").text(\"Your Sublime Text Snippet:\")\n\t\t}\n\t\telse { // use Visual Studio Code heading\n\t\t\t$(\".your_snippet\").text(\"Your VS Code Snippet:\")\n\t\t\t$(\".hidden_heading\").text(\"Your VS Code Snippet:\")\n\t\t}\n\t}", "function setFromImport(importData) {\n document.getElementById(\"sys_name\").value = importData[\"name\"];\n\n dir_path = importData[\"directory\"];\n document.getElementById(\"dir_name\").value = importData[\"directory\"];\n\n document.getElementById(\"merge_subdirs\").value = importData[\"includeSubDir\"];\n\n cover_path = importData[\"coverSheet\"];\n document.getElementById(\"cover_name\").value = importData[\"coverSheet\"];\n\n document.getElementById(\"enable_tagging\").checked =\n importData[\"versionTagging\"];\n\n document.getElementById(\"engineer_name\").value =\n importData[\"versionData\"][\"authorName\"];\n document.getElementById(\"version_tag\").value =\n importData[\"versionData\"][\"versionTag\"];\n\n toggleVersioning();\n\n document.getElementById(\"include_visio\").checked = importData.fileTypes.visio;\n document.getElementById(\"include_excel\").checked =\n importData[\"fileTypes\"][\"excel\"];\n document.getElementById(\"include_word\").checked =\n importData[\"fileTypes\"][\"word\"];\n document.getElementById(\"include_powerpoint\").checked =\n importData[\"fileTypes\"][\"ipowerpoint\"];\n document.getElementById(\"include_publisher\").checked =\n importData[\"fileTypes\"][\"publisher\"];\n document.getElementById(\"include_outlook\").checked =\n importData[\"fileTypes\"][\"outlook\"];\n document.getElementById(\"include_project\").checked =\n importData[\"fileTypes\"][\"project\"];\n document.getElementById(\"include_openoffice\").checked =\n importData[\"fileTypes\"][\"openoffice\"];\n\n document.getElementById(\"save_job\").checked = importData[\"saveJob\"];\n}", "function updateHeaders()\n{\n updateHeader('todoSection', 'toDoLabel', 'To Do');\n updateHeader('inProgressSection', 'inProgressLabel', 'Doing');\n updateHeader('completedSection', 'completedLabel', 'Done');\n //updateTopnav();\n}", "function setHeadTitleStyle() {\n doc.setFontSize(20);\n doc.setFontType(\"bold\");\n doc.setTextColor(255, 0, 0);\n}", "function populate() {\n $('h3, h2, h1')\n .each(function () {\n const title = $(this);\n var body = '';\n\n if (title.is('h3')) {\n body = title.nextUntil('h4');\n }\n if (title.is('h2')) {\n if (title.next()\n .is('h3')) {\n return;\n } else {\n body = title.nextUntil('h2');\n }\n }\n if (title.is('h1')) {\n body = title.nextUntil('h2');\n }\n\n // removes irrelevant information such as code examples from our documents.\n body = body.not('pre');\n\n const document =\n {\n id: title.prop('id'),\n title: title.text(),\n body: body.text()\n };\n index.addDoc(document);\n });\n}", "async function main_setHeadersIDs() {\n\t// Validate if headers respect the hierarchy and add error in \"Problem\" panel view\n\tconst validationResult = await main_validateHeaders(true);\n\t\n\t// If error found, stop the current process\n\tif (validationResult != true) {\n//\t\tvscode.window.showErrorMessage(\"It's impossible to set/reset IDs. Check the 'Problems' tab for more detail.\")\n\t\treturn;\n\t}\n\n\t// Get the active text editor\n\tconst myEditor = genFunc.getActiveEditor();\n\tif (myEditor == false) {\n\t\treturn;\n\t}\n\n\t// Get the DOM from the selected part of code\n\tlet myDOM = getDOM();\n\n\t// Get all headers in the DOM\n\tconst myDOMHeaders = myDOM.window.document.querySelectorAll(\"h2,h3,h4,h5,h6\");\n\n\t// check if header(s) have IDs.\n\tconst keepPreviousIDs = await areTherePreviousHeadersIDs(myDOMHeaders);\n\t// Escape key has been used in the question to user then stop process\n\tif (keepPreviousIDs == null) {\n\t\treturn;\n\t}\n\tif (await setNewIDs(myDOMHeaders, keepPreviousIDs)) {\n\t\tconst theRange = genFunc.getRangeSelected(true);\n\t\t// Set the new headers ID\n\t\tgenFunc.updateEditor(myDOM.window.document.getElementsByTagName('body')[0].innerHTML, theRange);\n\t}\n}", "function importWordHTML()\n{\n T.finish(); //ensure Tabs are through getting input\n\n // Lets save the settings first. That way if something crashes or\n // goes wrong during the processing, the user doesn't need to reset\n // all of the options again.\n if(doSaveSettings())\n saveSettings();\n\n // Set up logging particulars\n if ( doShowLog() )\n {\n MM_enableLogging();\n MM_clearLog();\n }\n else\n {\n MM_disableLogging();\n }\n\n version = getVersion();\n\n MM.setBusyCursor();\n\n switch(version)\n {\n case \"2000\":\n ProcessWord2000();\n break;\n\n case \"97\":\n ProcessWord97();\n break;\n }\n\n // Do some processing that needs to be done no matter the version.\n GeneralProcessing();\n\n // Cleanup\n PostProcess();\n\n MM.clearBusyCursor();\n\n // Show the log, if they said to.\n finish();\n}", "function updateHeader() {\n\tif (isPkgs) {\n\t\t$('#header-main-text').text('Packages');\n\t\t$('#header-nonmain-text').text('Options');\n\t\t$('title').text('Helsinki Packages');\n\t\t$('#home-manager-field').hide();\n\t} else {\n\t\t$('#header-main-text').text('Options');\n\t\t$('#header-nonmain-text').text('Packages');\n\t\t$('title').text('Helsinki Options');\n\t\t$('#home-manager-field').show();\n\t}\n\tupdateReleases();\n}", "loadMainHeader () {\n // Get site name and description from store\n const siteName = model.getPostBySlug( 'site-name', 'settings' ),\n siteDescription = model.getPostBySlug(\n 'site-description',\n 'settings'\n );\n view.updateSiteName( siteName.content );\n view.updateSiteDescription( siteDescription.content );\n }", "function addHeaderContent() {\n var topSection = createEl('section', {id: 'top', class: 'section'}),\n headerData = doc_data.thisClass.headerInfo,\n header = createEl('h1'),\n extendsNode = createEl('p'),\n extendsLink,\n definedIn = createEl('p'),\n definedInLink = createEl('a', {href: docsPath + classFilePath + '#L' + headerData.meta.lineno}),\n description = createEl('div', {style: 'border:none', id: 'classDescription'}),\n descriptionEl,\n constructorHeader = createEl('h3'),\n constructorPre = createEl('pre'),\n constructorCode = createEl('code'),\n constructorParamsHeader = createEl('h4'),\n constructorParams = [],\n text;\n // add main content wrapper\n doc_body.appendChild(mainContent);\n main = doc.getElementById('main');\n // add elements\n topSection.appendChild(header);\n topSection.appendChild(description);\n // source file\n topSection.appendChild(definedIn);\n addText(definedIn, 'DEFINED IN: ');\n definedIn.appendChild(definedInLink);\n addText(definedInLink, headerData.meta.filename + ' line number: ' + headerData.meta.lineno);\n mainContent.appendChild(topSection);\n // page header\n addText(header, headerData.name);\n // parent info if this class extends another\n if (isDefined(doc_data.parentClasses)) {\n topSection.appendChild(extendsNode);\n addText(extendsNode, 'EXTENDS: ');\n extendsLink = createEl('a', {href: parentClassFilePath + doc_data.parentClasses[0].headerInfo.meta.filename});\n extendsNode.appendChild(extendsLink);\n addText(extendsLink, doc_data.parentClasses[0].headerInfo.meta.filename);\n }\n // constructor info - don't add for video.js\n if (doc_data.thisClass.headerInfo.name !== 'videojs') {\n topSection.appendChild(constructorHeader);\n topSection.appendChild(constructorPre);\n constructorPre.appendChild(constructorCode);\n // create the constructor info\n addText(constructorHeader, 'Constructor');\n\n // get constructor params if any\n if (isDefined(headerData.params)) {\n var paramTableHeaders = ['name', 'Type', 'Required', 'Description'],\n paramTable = createEl('table'),\n paramThead = createEl('thead'),\n paramTbody = createEl('tbody'),\n paramTheadRow = createEl('tr'),\n paramTbodyRow = createEl('tr'),\n paramTH,\n paramTD,\n k,\n kMax;\n\n addText(constructorParamsHeader, 'Parameters');\n paramTable.appendChild(paramThead);\n paramTable.appendChild(paramTbody);\n paramThead.appendChild(paramTheadRow);\n // set the table headers\n kMax = paramTableHeaders.length;\n for (k = 0; k < kMax; k++) {\n paramTH = createEl('th');\n paramTheadRow.appendChild(paramTH);\n addText(paramTH, paramTableHeaders[k]);\n }\n // now the table info\n kMax = headerData.params.length;\n for (k = 0; k < kMax; k++) {\n paramTbodyRow = createEl('tr');\n paramTbody.appendChild(paramTbodyRow);\n paramTD = createEl('td');\n addText(paramTD, headerData.params[k].name);\n paramTbodyRow.appendChild(paramTD);\n paramTD = createEl('td');\n addText(paramTD, headerData.params[k].type.names.join('|'));\n paramTbodyRow.appendChild(paramTD);\n paramTD = createEl('td');\n if (headerData.params[k].optional) {\n text = doc.createTextNode('no');\n constructorParams.push('[' + headerData.params[k].name + ']');\n } else {\n text = doc.createTextNode('yes');\n constructorParams.push(headerData.params[k].name);\n }\n paramTD.appendChild(text);\n if (isDefined(headerData.params[k].description)) {\n paramTbodyRow.appendChild(paramTD);\n paramTD = createEl('td');\n addText(paramTD, headerData.params[k].description.slice(3, headerData.params[k].description.indexOf('</p>')));\n paramTbodyRow.appendChild(paramTD);\n }\n paramTbody.appendChild(paramTbodyRow);\n }\n topSection.appendChild(constructorParamsHeader);\n topSection.appendChild(paramTable);\n }\n }\n // add constructor params to signature if any\n if (constructorParams.length > 0) {\n text = doc.createTextNode(headerData.name + '( ' + constructorParams.join(',') + ' )');\n } else {\n text = doc.createTextNode(headerData.name + '()');\n }\n constructorCode.appendChild(text);\n descriptionEl = doc.getElementById('classDescription');\n descriptionEl.innerHTML = headerData.description;\n}", "function addHeader() {\r\n const contentsSrc = 'MasterPage/header_contents.txt';\r\n if (document.getElementById) {\r\n let header = document.getElementById('header');\r\n if (header) {\r\n let pathPrefix = relativePath();\r\n let navState = navSelected();\r\n let headerContents = readContents(pathPrefix + contentsSrc);\r\n if (headerContents) {\r\n\theaderContents = headerContents.replace('{{indexPrefix}}'\r\n\t\t , pathPrefix);\r\n headerContents = headerContents.replace('{{aboutPrefix}}'\r\n\t\t , pathPrefix);\r\n headerContents = headerContents.replace('{{archivesPrefix}}'\r\n\t\t , pathPrefix);\r\n\theaderContents = headerContents.replace('{{indexNav}}'\r\n\t\t , navState.index);\r\n headerContents = headerContents.replace('{{aboutNav}}'\r\n\t\t , navState.about);\r\n headerContents = headerContents.replace('{{archivesNav}}'\r\n\t\t , navState.archives);\t\t\t\t\t\r\n placeInOuterHtml(header, headerContents);\r\n }\r\n }\r\n } \r\n}", "function updateAutoDocColors(){\n\tfor(docId in docIdToIndexMap){\n\t\tdocIdWTopic = mainWindow.getDocIdWithTopic(docId);\n\t\tif(mainWindow.checkExists(docId)){\n\t\t\tdocument.getElementById(docIdWTopic).style.backgroundColor = '';\n\t\t\tif(docId in classificationDocLabelMap == false && docId in docLabelMap == false){//if not in classification and not in docLabelMap\n\t\t\t\tdocument.getElementById(docIdWTopic).style.color = '#B0B0B0';\n\t\t\t\tdocument.getElementById(docIdWTopic).style.fontWeight= \"normal\";\n\t\t\t\tdocument.getElementById(docIdWTopic).style.fontSize= \"small\";\n\t\t\t}\n\t\t\telse if(docId in classificationDocLabelMap){\n\t\t\t\tlabel_val = classificationDocLabelMap[docId];\n\t\t\t\tif(label_val != ''){\n\t\t\t\t\tdocument.getElementById(docIdWTopic).style.color = labelToColor[label_val];\n\t\t\t\t\tdocument.getElementById(docIdWTopic).style.backgroundColor = '#E6E6E6';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tmainWindow.updateYellowHighlight();\n}", "function _updateContent(itemsClass) {\n var listItems = lv_help.querySelectorAll(itemsClass); \n if (lv_help.winControl.loadingState == \"complete\") {\n // update item color\n _deselectItems(listItems, itemsClass);\n //update description\n _showCurrentDescription();\n }\n else\n if (_currentItemInvoked && lv_help.winControl.elementFromIndex(_currentItemInvoked.index).querySelector(itemsClass))\n lv_help.winControl.elementFromIndex(_currentItemInvoked.index).querySelector(itemsClass).style.backgroundColor = \"#ebc24b\";\n }", "function loadWordStyle() {\n\n // modify description seen in the top section of the page\n document.getElementById(\"word-header1\").style.display = \"block\";\n document.getElementById(\"word-header2\").style.display = \"block\";\n document.getElementById(\"wiki-header1\").style.display = \"none\";\n document.getElementById(\"wiki-header2\").style.display = \"none\";\n document.getElementById(\"git-header1\").style.display = \"none\";\n document.getElementById(\"git-header2\").style.display = \"none\";\n document.getElementById(\"doc-header\").textContent = \"Change the style to see what you can do!\"\n\n let mod = document.getElementById(\"mod\");\n mod.removeChild(mod.childNodes[2]);\n\n let div = document.createElement(\"div\");\n // insert word HTML template\n div.insertAdjacentHTML(\"afterbegin\", word);\n // insert tabs HTML template\n div.insertAdjacentHTML(\"afterbegin\", tabs);\n\n mod.appendChild(div);\n \n if (docChosen == \"CAD2017\") {\n // load CAD buttons\n loadButtons();\n // load Word style for CAD v.2017\n loadCAD(CADedits2017);\n } else if (docChosen == \"CAD2012\") {\n // load CAD buttons\n loadButtons();\n // load Word style for CAD v.2012\n loadCAD(CADedits2012);\n };\n\n activeStyle = \"Word\";\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if `value` is objectlike. A value is objectlike if it's not `null` and has a `typeof` result of "object".
function isObjectLike(value) { return _typeof$1(value) == 'object' && value !== null; }
[ "function isObjectLike(value) {\n return _typeof$2(value) == 'object' && value !== null;\n }", "function isObjectLike(value) {\n return _typeof$3(value) == 'object' && value !== null;\n }", "function isObjectLike(value) {\n return _typeof(value) == 'object' && value !== null;\n }", "function isObjectLike(value) {\n return _typeof$1(value) == 'object' && value !== null;\n}", "function isObjectLike(value) {\n return _typeof(value) == 'object' && value !== null;\n}", "__is_object(value) {\n return value && typeof value === 'object' && value.constructor === Object;\n }", "function isObject(value) {\n return Object.prototype.toString.call(value) === '[object Object]';\n }", "function isObj(value) {\n var type = typeof value;\n return value !== null && (type === 'object' || type === 'function');\n}", "function isNonNullObject(value) {\n return !!value && typeof value === 'object'\n }", "function isType(value) {\n return typeof value === \"object\" && value && value.isType === true;\n}", "function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}", "function isNonNullObject(value) {\n return isObject(value) && value !== null;\n}", "function _is_json_value(value) {\n\tif (value === undefined) return false;\n\tif (value === null) return true;\n\treturn ([Object, Array, String, Number, Boolean].indexOf(value.constructor) !== -1);\n}", "function isObject(val) {\n return typeOf(val) === 'object';\n}", "function isObjectLike(variable) {\n return typeof variable === \"object\" && !isNull(variable);\n}", "function isObject(val) {\n\t return typeOf(val) === 'object';\n\t}", "function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);\n }", "function isOfSupportedType(value) {\n if (value === null) {\n return true;\n }\n switch (exports.classof(value)) {\n case 'string':\n case 'number':\n case 'boolean':\n case 'date':\n return true;\n default:\n return false;\n }\n }", "isPlainObject(obj) {\n return _toString.call(obj) === '[object Object]'\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set content on a travel page during transition
function setTravelContent(page, switchPage) { setContent(page, switchPage); // Load the HTML with ajax setTimeout(function() { // Want this to run after the page transition var $bg1 = $('#bg1'); numDivs = $('.bg').length - 1; // Get # of bgDivs to set body height $('body').height(String((scrollMultiplier * numDivs + 1) * 100 - 1) + 'vh'); $('#divStack').css({'display': 'block'}); // Now that we can scroll, make the divStack visible // $bg1.css({'opacity': '0'}); // I don't think this is necessary... lets delete it $bg1.css('background', 'url(./' + page + '/bg1.jpg) no-repeat center center').css('background-size', 'cover'); $('#expandTextBar').mouseover(function() { $(this).stop().animate({color: '#E0CDAC', backgroundColor: '#555'}, 150)}); $('#expandTextBar').mouseout(function() { $(this).stop().animate({color: '#FFB74D', backgroundColor: '#393939'}, 300)}); }, bgDelay); }
[ "function setContent() {\n\n toggleLoader('hide');\n _contentContainer.innerHTML = _contentHolder.innerHTML;\n _contentContainer.classList.remove('is--transitioning');\n window.reInit();\n _contentHolder.remove();\n _isTransitioning = false;\n _contentContainer.removeEventListener('transitionend', setContent);\n\n\n }", "function travelTo(page, backPressed, switchPage) {\r\n if (locked || currentPage == page) return;\r\n locked = true;\r\n currentPage = page; // Update global page variable to whatever the new page is\r\n pageType = 'travel'; // Fadey-transitioney scroll pages\r\n var scrollToTopDelay = 0;\r\n if (scrollPosition > 0) scrollToTopDelay = textDelay;\r\n $('html, body').animate({scrollTop: 0}, textDelay);\r\n setTimeout(function() { // Scroll to the top of the page before page transition\r\n $('#divStack').css({'display': 'none'});\r\n toggleTravelBar(); // Set travelBar visibility depending on page being loaded\r\n setBG(page + '/bg0.jpg'); // Set the new background\r\n $('.button').unbind(); // No mouseover effects on the buttons while transitioning pages\r\n $('.button.active').animate({ // Fade out old active button\r\n color: '#CFD8DC', backgroundColor: 'rgba(80, 85, 90, 0.2)'}, bgDelay).removeClass('active');\r\n $('#' + page).animate({ // Fade in new active button\r\n color: '#FFB74D', backgroundColor: 'rgba(35, 35, 35, 0.9)'}, bgDelay).addClass('active');\r\n setTravelContent(page, switchPage);\r\n if (backPressed != true) window.history.pushState({urlPath: '/' + page}, '', '/' + page + '.html');\r\n setTimeout(function() { \r\n setTravelBar(page); \r\n setTimeout(function() { locked = false; }, bgDelay); // Release lock after page transition\r\n }, bgDelay);\r\n }, scrollToTopDelay);\r\n}", "function pageTransition() {\r\n\r\n var tl = gsap.timeline();\r\n tl.set('.loading-screen', { transformOrigin: \"bottom left\"});\r\n tl.to('.loading-screen', { duration: .5, scaleY: 1});\r\n tl.to('.loading-screen', { duration: .5, scaleY: 0, skewX: 0, transformOrigin: \"top left\", ease: \"power1.out\", delay: 1 });\r\n }", "function pageTransition() {\n let tl = gsap.timeline();\n\n tl.to('.transition-item', {\n duration: 0.3,\n scaleY: 1,\n transformOrigin: 'bottom left',\n stagger: 0.15,\n ease: 'power2.easeInOut',\n });\n tl.to('.transition-item', {\n duration: 0.3,\n scaleY: 0,\n transformOrigin: 'bottom left',\n stagger: 0.1,\n ease: 'power2.easeInOut',\n });\n}", "function pageTransition() {\n var tl = gsap.timeline();\n tl.to(\".loading-screen\", { \n duration: 1.2,\n width: \"100%\",\n left: \"0%\",\n ease: \"Expo.easeInOut\",\n });\n\n tl.to(\".loading-screen\", {\n duration: 1, \n width: \"100%\",\n left: \"100%\",\n ease: \"Expo.easeInOut\",\n delay: 0.1, \n });\n tl.set(\".loading-screen\", { left: \"-100%\" });\n }", "function pageTransition(target) {\n let targetpage = target;\n setTimeout(\n function() {\n let outpage = document.getElementById(currentpage);\n let inpage = document.getElementById(targetpage);\n\n currentpage = targetpage;\n\n outpage.classList.add(\"leftout\");\n outpage.classList.add(\"ontop\");\n\n inpage.classList.add(\"pagecurrent\");\n inpage.classList.add(\"leftin\");\n\n setTimeout(\n function() {\n outpage.classList.remove(\"pagecurrent\");\n outpage.classList.remove(\"leftout\");\n outpage.classList.remove(\"ontop\");\n\n inpage.classList.remove(\"leftin\");\n\n window.location = \"#\"\n }, 800);\n }, 200);\n}", "function setContentOfPage() {\n //The object we will pass to markup that will be used to generate the HTML.\n var context = { \"listitems\": _data.items };\n \n //The SDK automatically parses any templates you associate with this view on the bc.templates object.\n var markupTemplate = bc.templates[\"first-page-tmpl\"];\n \n //The generated HTML for this template.\n var html = Mark.up( markupTemplate, context );\n \n //Set the HTML of the element.\n $( \"#first-page-content\" ).html( html );\n }", "function changeContent(page) {\n}", "function changeContent() {\n $(\"#main-content\").addClass(\"d-none\");\n $(\"#header-title\").addClass(\"d-none\");\n $(\"#main-header-line\").addClass(\"d-none\");\n $(\".header-paragraph\").addClass(\"d-none\");\n\n $(\"#city-content\").removeClass(\"d-none\");\n $(\"#city-header-title\").removeClass(\"d-none\");\n $(\".city-gallery\").removeClass(\"d-none\");\n $(\"#city-header-line\").removeClass(\"d-none\");\n\n // bring the user to the top of the page\n window.scrollTo({ top: 0, behavior: 'smooth' });\n }", "function switchContent(content)\r\n\t{\r\n\t\tsettings.infoContainer\r\n\t\t\t// stop current transition\r\n\t\t\t.stop()\r\n\t\t\t// fade out the container\r\n\t\t\t.fadeTo(200, 0, function() {\r\n\t\t\t\t// when complete\r\n\t\t\t\tsettings.infoContainer\r\n\t\t\t\t\t// update the content\r\n\t\t\t\t\t.html(content)\r\n\t\t\t\t\t// fade in the container\r\n\t\t\t\t\t.fadeTo(200, 1);\r\n\t\t\t});\r\n\t}", "function pageTransition(){\n // Problem: css animationen nicht stapelbar (Plugin: http://labs.bigroomstudios.com/libraries/animo-js )\n // animation: none --> elemets jump back to start\n\n var atomOffset;\n var $wrapper = jQuery('.wrapper');\n var wrapperWidth = ($wrapper.width()/2) + $wrapper.offset().left; // calculate center of wrapper pane\n var wrapperHeight= $wrapper.height()/2;\n\n $overlay.animate({ opacity: 0}, 500);\n jQuery('img.logo, span.button').animate({\n height: ($(this).height()*0),\n width: ($(this).width()*0),\n \"font-size\": 0,\n opacity: 0\n }, 500, function(){\n $atom.each(function(){\n atomOffset = jQuery(this).offset();\n\n // calculate vector\n VecX = wrapperWidth - atomOffset.left;\n VecY = wrapperHeight - atomOffset.top;\n\n normalizeVector();\n\n jQuery(this).animate({\n position: \"relative\",\n top: 1000*-VecY,\n left: 1000*-VecX\n }, 1000, function(){\n window.location = '#/menu';\n });\n });\n\n });\n\n}", "function setContent(page, switchPage) {\r\n var $content = $('#content');\r\n var $tempDiv = $('<div>'); // Create temporary div stored in memory\r\n $tempDiv.load(page + 'Content'); // Load new content into $tempDiv first b/c ajax load is laggy/slow\r\n if (switchPage == true) $content.stop().animate({opacity: 0}, textDelay); // Fade out current content for page switch\r\n setTimeout(function() { $content.html($tempDiv.html()).stop().animate({opacity: 1}, textDelay + 50) }, textDelay - 50);\r\n}", "transition ( view ) {\n var slideTime = this._pageLoad ? 0 : this.transitionTime;\n var fadeTime = this.transitionTime + 200;\n var currentScreen = window._view_current;\n var $current = $(`.view-container[data-view-n=\"${currentScreen}\"]`);\n var $to = $(`.view-container[data-view=\"${view}\"]`);\n var to = $to.attr('data-view-n');\n\n // where the 'current' view should end up\n var curAnim = to > currentScreen ? { top: '-'+($current.height()+100)+\"px\" } : { top: '110%' };\n // where the 'to' view should begin\n var toAnim = to > currentScreen ? { top: \"110%\" } : { top: '-110%' };\n\n if ( this._pageLoad ) {\n this._pageLoad = false;\n slideTime = 0;\n }\n else if ( to == currentScreen ) {\n return false;\n }\n\n $('body').css({\"overflow-y\": 'hidden'});\n setTimeout(function() {\n $('body').css({\"overflow-y\": 'auto'});\n }, fadeTime);\n\n if ( $current ) {\n $current.animate(curAnim, { duration: slideTime, queue: false });\n $current.fadeOut( { duration: fadeTime, queue: false } );\n }\n\n if ( $to ) {\n $to.css(toAnim);\n $to.animate({ top: \"0%\" }, { duration: slideTime, queue: false } );\n $to.fadeIn( { duration: fadeTime, queue: false } );\n }\n\n window._view_current = to;\n }", "async setContent(){\n if(this._instanceDestroyed) return;\n await tryWithPageAwareness(async () => {\n await this._page.setContent(...arguments, { waitUntil: 'load'});\n await this._reflectContents();\n });\n }", "function setBodyTransitions(){\n\n\t\tvar main_nav_links = $('.body-main-header').find('.nav-links li a');\n\n\t\t//listener for nav click\n\t\t$(main_nav_links).on('click', function(e){\n\n\t\t\tvar filter_href = e.target.getAttribute('href').split('#'); //filterhref of link by splitting at every #\n\t\t\tvar id_string = filter_href[filter_href.length-1]; //gets page's raw id and creates page-id\n\t\t\tvar page_id = \"#page-\" + id_string;\n\n\t\t\tvar destination = $(body).find('.body-slider').find(page_id);\n\n\t\t\t//if destination exists\n\t\t\tif(destination.length > 0){\n\t\t\t\t//on click, distance of page is found and applied to body slider to move to page\n\t\t\t\tdocument.getElementsByClassName('body-slider')[0].style.left = \"-\" + $(destination).css('left');\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tvar current = $('.page-active').attr('id');\n\t\t\t\t\t$(destination).addClass('page-active');\n\t\t\t\t\t$(document.getElementById(current)).delay(1000).removeClass('page-active');\n\t\t\t\t},300);\n\t\t\t}\n\t\t});\n\n\n\t}", "function setContent(contentUrl) {\n\n $(document).ready(function () {\n\n $('#Main2-container').load(contentUrl);\n\n });\n\n window.scrollTo(0, 0); //move the view back to the top of the window\n}", "function goToContent() {\n $('html, body').animate({\n scrollTop: ($('#content').offset().top - 50)\n }, 250);\n }", "function transitionToSecondPage( evt ) {\n //We are using index of the array to determine which element was clicks, but with your data if you have unique ID that would be ideal.\n var index = $( this ).index();\n \n //The object we will pass to markup that will be used to generate the HTML.\n var context = { \"text\": _data.items[index].description };\n \n //The SDK automatically parses any templates you associate with this view on the bc.templates object.\n var markupTemplate = bc.templates[\"second-page-tmpl\"];\n \n //The generated HTML for this template.\n var html = Mark.up( markupTemplate, context );\n \n //Set the HTML of the element.\n $( \"#second-page-content\" ).html( html );\n \n //Transition to the new page.\n bc.ui.forwardPage( $( \"#pagetwo\" ) );\n }", "function transition(toPage, type){\n\tvar toPage = $(toPage),\n \tfromPage = $(\".pages .current\"); // store the page that is currently showing\n\n toPage\n .addClass(\"current \" + type + \" in\")\n .one(\"msAnimationEnd animationend oAnimationEnd\", function(){ // listens for when the animation has finished\n fromPage.removeClass(\"current \" + type + \" out\" );\n toPage.removeClass(type + \" in\");\n });\n fromPage.addClass(type + \" out \");\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process data array into form easy for flytable code to process: calculate index and yaxis extents to determine when search has found right record copy forward unchanged metadata attributes for use by comic renderer returns the calculated total height of the comics
function cookData(array, rowPadding) { var prev = {i: 0, h: 0, y: 0}; var first = array[0]; // discover custom attributes var attributes = []; for(key in first) { if(!(key in prev)) { attributes.push(key); } } for(var i = 0; i < array.length; i++) { var item = array[i]; // copy attributes forward for(var a = 0; a < attributes.length; a++) { var attr = attributes[a]; if(!(attr in item)) { item[attr] = prev[attr]; } } // copy height forward + ensure requested padding if(item.h) { item.h += rowPadding; } else { item.h = prev.h; } // calculate segment height & spanned indices var span = item.i - prev.i; item.y = prev.y + span * prev.h; prev.last = item.i; prev.lastY = item.y; prev = item; } // last item needs to be given explicitly var lastEntry = array[array.length - 1]; array.last = lastEntry.i; lastEntry.last = lastEntry.i + 1; var lastSpan = lastEntry.last - lastEntry.i; var totalHeight = lastEntry.y + lastEntry.h * lastSpan; lastEntry.lastY = totalHeight; return totalHeight; }
[ "function calculateDim(data, dimensions) {\n\t\n\tvar row = 0;\n\tvar x = dimensions[0];\n\tvar y = dimensions[1];\n\tvar fontSize = doc.internal.getFontSize();\n\tvar noOfLines = 0;\n\tvar indexHelper = 0;\n\tvar lengths = [];\n\n\theights = [];\n\tvalue = 0;\n\tSplitIndex = [];\n\n\tfor (var i = 0; i < data.length; i++) {\n\t\tvar obj = data[i];\n\t\tvar length = 0;\n\t\tfor (var key in obj) {\n\t\t\tif (obj[key] !== null) {\n\t\t\t\tif (length < obj[key].length) {\n\t\t\t\t\tlengths[row] = obj[key].length;\n\t\t\t\t\tlength = lengths[row];\n\t\t\t\t}\n\t\t\t}\n\t\t}++row;\n\t}\n\n\tfor (var i = 0; i < lengths.length; i++) {\n\t\tif ((lengths[i] * (fontSize)) > (width - dimensions[5])) {\n\t\t\tnoOfLines = Math.ceil((lengths[i] * (fontSize)) / width);\n\t\t\theights[i] = (noOfLines) * (fontSize / 2) + dimensions[6] + 10;\n\t\t} else {\n\t\t\theights[i] = (fontSize + (fontSize / 2)) + dimensions[6] + 10;\n\t\t}\n\t}\n\n\tfor (var i = 0; i < heights.length; i++) {\n\t\tvalue += heights[i];\n\t\tindexHelper += heights[i];\n\t\tif (indexHelper > (doc.internal.pageSize.height - pageStart)) {\n\t\t\tSplitIndex.push(i);\n\t\t\tindexHelper = 0;\n\t\t\tpageStart = dimensions[4] + 30;\n\t\t}\n\t}\n\n\treturn value;\n}", "function processData(){\r\n \r\n var unit,\r\n powerFactor,\r\n pow10x;\r\n \r\n // reset values\r\n _min = 0;\r\n _max = 0;\r\n _barData =[];\r\n _xLegends = [];\r\n _yLegends = [];\r\n \r\n for(var i = 0; i < _data.length; i++){\r\n _min = Math.min(_min, _data[i]);\r\n _max = Math.max(_max, _data[i]);\r\n _barData.push(_data[i]);\r\n _xLegends.push(i);\r\n }\r\n unit = (_max - _min) / (_step);\r\n if (unit > 0) {\r\n powerFactor = Math.ceil((Math.log(unit) / Math.log(10)) - 1);\r\n } else {\r\n powerFactor = 0;\r\n }\r\n pow10x = Math.pow(10, powerFactor);\r\n \r\n if(pow10x < -1){\r\n _max = Math.ceil(_max);\r\n unit = (_max - _min) / (_step);\r\n _range = unit;\r\n } else {\r\n _range = Math.ceil(unit / pow10x) * pow10x;\r\n }\r\n \r\n if (_range == 0) _range == 0.01667;\r\n \r\n _max = _range * _step;\r\n \r\n for(var j = _step; j >= 0; j--){\r\n _yLegends.push(_range*j);\r\n }\r\n if(_max > 20)\r\n _decimcalFixed = 0;\r\n else if(_max > 2)\r\n _decimcalFixed = 1;\r\n else if(_max > 0.1)\r\n _decimcalFixed = 2;\r\n else if(_max > 0.01)\r\n _decimcalFixed = 3; \r\n else if(_max > 0.001)\r\n _decimcalFixed = 4; \r\n else\r\n _decimcalFixed = 5; \r\n \r\n }", "function dataProcess(d){\r\n var len = d.length;\r\n for (var i = 0; i < len; i++) {\r\n interAxisData.push(new dataUnit(d[i][\"ID\"], d[i][\"Maker\"] + \" \" + d[i][\"Model Name\"] + \" \" + d[i][\"Trim\"], d[i][\"Country\"] ));\r\n if (countryMap.has(d[i][\"Country\"])) {\r\n countryMap.get(d[i][\"Country\"]).push(d[i][\"ID\"]);\r\n } else {\r\n countryMap.set(d[i][\"Country\"], []);\r\n }\r\n\r\n interAxisData[i].data.push(parseInt(d[i][\"Year\"]));\r\n //split body attribute into six binary attributes;\r\n var body = d[i][\"Body\"].toLowerCase();\r\n if (body.includes(\"suv\") || body.includes(\"sport utility\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([1, 0, 0, 0, 0, 0]);\r\n } else if (body.includes(\"sedan\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 1, 0, 0, 0, 0]);\r\n } else if (body.includes(\"truck\") || body.includes(\"pickup\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 1, 0, 0, 0]);\r\n } else if (body.includes(\"sport\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 0, 1, 0, 0]);\r\n } else if (body.includes(\"wagon\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 0, 0, 1, 0]);\r\n } else if (body.includes(\"mini\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 0, 0, 0, 1]);\r\n } else {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 0, 0, 0, 0]);\r\n }\r\n\r\n interAxisData[i].data.push(parseInt(d[i][\"Engine CC\"]));\r\n interAxisData[i].data.push(parseInt(d[i][\"Cylinder\"]));\r\n interAxisData[i].data.push(parseInt(d[i][\"Engine Power\"]));\r\n interAxisData[i].data.push(parseInt(d[i][\"Engine Torque\"]));\r\n //split fuel type attribute;\r\n var fuelType = d[i][\"Fuel Type\"].toLowerCase();\r\n if (fuelType.includes(\"hybrid\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 0, 1]);\r\n } else if (fuelType.includes(\"electric\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 1, 0]);\r\n } else if (fuelType.includes(\"diesel\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 1, 0, 0]);\r\n } else {\r\n interAxisData[i].data = interAxisData[i].data.concat([1, 0, 0, 0]);\r\n }\r\n //split drive attribute;\r\n var drive = d[i][\"Drive\"].toLowerCase();\r\n if (drive.includes(\"rear\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 0, 1]);\r\n } else if (drive.includes(\"four\") || drive.includes(\"4\") || drive.includes(\"awd\") || drive.includes(\"all\")) {\r\n interAxisData[i].data = interAxisData[i].data.concat([1, 0, 0]);\r\n } else {\r\n interAxisData[i].data = interAxisData[i].data.concat([0, 1, 0]);\r\n }\r\n //automatic is one, manual is zero\r\n if (d[i][\"Transmission Type\"].toLowerCase().includes(\"auto\")) {\r\n interAxisData[i].data.push(1);\r\n } else {\r\n interAxisData[i].data.push(0);\r\n }\r\n\r\n interAxisData[i].data.push(parseInt(d[i][\"Seats\"]));\r\n interAxisData[i].data.push(parseInt(d[i][\"Doors\"]));\r\n interAxisData[i].data.push(parseInt(d[i][\"Weight\"]));\r\n //convert lkm into mpg\r\n interAxisData[i].data.push(parseInt(100 * 3.785 / (1.609 * parseFloat(d[i][\"LKM HWY\"])) ));\r\n interAxisData[i].data.push(parseInt(100 * 3.785 / (1.609 * parseFloat(d[i][\"LKM City\"])) ));\r\n interAxisData[i].data.push(parseInt(d[i][\"Fuel Capacity\"]));\r\n //calculate x y coordinate when creating each point\r\n pointpos = calcCoordinate(i);\r\n interAxisData[i].x = pointpos[0];\r\n interAxisData[i].y = pointpos[1];\r\n }\r\n for (var i = 0; i < iaAttrList.length; i++) {\r\n curmin = interAxisData[0].data[i];\r\n curmax = interAxisData[0].data[i];\r\n for (j = 1; j < interAxisData.length; j++) {\r\n if (interAxisData[j].data[i] < curmin) {\r\n curmin = interAxisData[j].data[i];\r\n }\r\n if (interAxisData[j].data[i] > curmax) {\r\n curmax = interAxisData[j].data[i];\r\n }\r\n }\r\n iaAttrRange.push([curmin, curmax]);\r\n }\r\n console.log(iaAttrRange);\r\n // find range of x and y value for interAxis plot auto adjustment.\r\n var maxX = interAxisData[0].x;\r\n var minX = interAxisData[0].x;\r\n var maxY = interAxisData[0].y;\r\n var minY = interAxisData[0].y;\r\n for (var i = 0; i < len; i++) {\r\n if (interAxisData[i].x > maxX) {\r\n maxX = interAxisData[i].x;\r\n } else if (interAxisData[i].x < minX) {\r\n minX = interAxisData[i].x;\r\n }\r\n if (interAxisData[i].y > maxY) {\r\n maxY = interAxisData[i].y;\r\n } else if (interAxisData[i].y < minY) {\r\n minY = interAxisData[i].y;\r\n }\r\n }\r\n xRange[0] = minX;\r\n xRange[1] = maxX;\r\n yRange[0] = minY;\r\n yRange[1] = maxY;\r\n\r\n console.log(countryMap);\r\n //console.log(xRange);\r\n //console.log(yRange);\r\n}", "function processData(data) {\r\n // Turn 1D arrays to 2D\r\n const is2D = Array.isArray(data[0])\r\n const data2D = is2D\r\n ? data.map((elem) => [...elem])\r\n : data.map((elem) => [elem])\r\n\r\n // Calculations\r\n const sums = collapseArray(data2D, ...toSum)\r\n const max = sums.reduce(...toMax)\r\n const maxLength = data2D.reduce(...toMaxLength)\r\n\r\n // Pad and add difference to max at end\r\n data2D.forEach((arr, i) => {\r\n padArray(arr, 0, maxLength)\r\n arr.push(max - sums[i])\r\n })\r\n\r\n return {\r\n is2D: is2D,\r\n barCount: data2D.length,\r\n subBarCount: maxLength,\r\n max: max,\r\n values: data2D,\r\n }\r\n}", "function getHeightData() {\n\n var xSteps = Math.floor(_imageWidth / _guiOptions.pixelStep);\n var ySteps = Math.floor(_imageHeight / _guiOptions.pixelStep);\n\n var heightData = new Float32Array( xSteps * ySteps );\n\n var idxHeight = 0;\n\n // Note that we need to step from bottom to top since image data is\n // top->bottom but model data is bottom->top\n for (var y = ySteps - 1; y >= 0; --y) {\n var yStep = y * _guiOptions.pixelStep;\n\n for (var x = 0; x < xSteps; ++x) {\n var xStep = x * _guiOptions.pixelStep;\n\n var color = getColor(xStep, yStep);\n var brightness = getBrightness(color); // val 0 - 1\n\n heightData[idxHeight++] = brightness * _guiOptions.maxHeight;\n }\n }\n\n return { data: heightData, width: xSteps, height: ySteps };\n}", "function stackeddata(data,height,margin){\n var dataobj=[];\n data.forEach(function(datainput,index){\n var yvalue=height-(datainput.input+datainput.output)-margin.bottom\n dataobj[index]={x:datainput.x,y:yvalue,height:datainput.output} \n })\n console.log(dataobj);\n return dataobj\n }", "function getHeights(data) {\n var total = flagImage.height - 27;\n var heights = [];\n\n for (var i = 0; i < data.length; i++) {\n heights.push(data[i] * total);\n }\n return heights;\n}", "function updateHeightValues() {\n //TODO: this is going to be updated to use ChunkArray data to be faster.\n var height = 0, i = 0, contentHeight;\n while (i < inst.rowsLength) {\n rowOffsets[i] = height;\n height += inst.templateModel.getTemplateHeight(inst.data[i]);\n i += 1;\n }\n options.rowHeight = inst.rowsLength ? inst.templateModel.getTemplateHeight(\"default\") : 0;\n contentHeight = getContentHeight();\n inst.getContent()[0].style.height = contentHeight + \"px\";\n inst.log(\"heights: viewport %s content %s\", inst.getViewportHeight(), contentHeight);\n }", "function yaxisticsFaults(tabinput, varName1, x, y, plotwidth, plotheight, ticsize, yoffset, unitscale, strkWght, strkClr, txtsze) {\n\n stroke(strkClr);\n strokeWeight(strkWght);\n textSize(txtsze)\n\n // find the column number (counting from 0)\n // let col1 = tabinput.columns.indexOf(varName1);\n textAlign(RIGHT)\n\n // ---------------------------\n let miny1 = 0;\n let maxy1 = -300000;\n\n\n for (var i = 0; i < (faultlinedata.length); i++) {\n // if (tabinput.getNum(i, col1) <= miny1) {\n // miny1 = tabinput.getNum(i, col1);\n // // print(\"The min is: \" + miny1)\n // }\n if (faultlinedata[i].distance >= maxy1) {\n maxy1 = faultlinedata[i].distance;\n // print(\"The max is: \" + maxy1)\n }\n }\n\n\n // let yzero = y - map(0, miny1, maxy1, 0, plotheight)\n\n let j = miny1 + yoffset;\n let k = j;\n // Add tics for axis here....\n while (j <= maxy1) {\n ytic = map(j, miny1, maxy1, plotheight,0)\n line(x - 2, y + ytic, x + 2, y + ytic);\n text(round(k * 10) / 10 * unitscale, x - 4, y + ytic + 2 )\n j += ticsize;\n k += ticsize;\n }\n\n}", "function getWidths(data) {\n var total = flagView.width - flagImage.x;\n var heights = [];\n\n for (var i = 0; i < data.length; i++) {\n heights.push(data[i] * total);\n }\n\n return heights;\n}", "function calculateHeights() {\n\t\tpanelsizes = [];\n\n\t\tvar sumheight = 0;\n\t\tvar i = 0;\n\t\tgPanels.forEach( function (v, k, m) {\n\t\t\tvar height = EPISEC_HEIGHT_PERCENT[gPanels.size - 1][i]*h;\n\t\t\tv.move(0, sumheight, w, height, xRescale, xBand, xBandv, xBandnp);\n\t\t\tsumheight += height;\n\t\t\ti++;\n\t\t});\n\t}", "function applyExtractedData(){\n for(var i=0;i<extractedCols.length;i++){\n for(var j=0;j<extractedCols[i].values.length;j++){\n for(var k=0;k<data[j].length;k++){\n data[j][k][extractedCols[i].key] = extractedCols[i].values[j][0].value;\n }\n }\n }\n extractYLabels();\n }", "adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata) {\n let boundingBox = this.getBoundingBox();\n let top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();\n let bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();\n let firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));\n let lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));\n // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();\n let codewords = this.getCodewords();\n let barcodeRow = -1;\n let maxRowHeight = 1;\n let currentRowHeight = 0;\n for (let codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n let codeword = codewords[codewordsRow];\n codeword.setRowNumberAsRowIndicatorColumn();\n let rowDifference = codeword.getRowNumber() - barcodeRow;\n // TODO improve handling with case where first row indicator doesn't start with 0\n if (rowDifference === 0) {\n currentRowHeight++;\n }\n else if (rowDifference === 1) {\n maxRowHeight = Math.max(maxRowHeight, currentRowHeight);\n currentRowHeight = 1;\n barcodeRow = codeword.getRowNumber();\n }\n else if (codeword.getRowNumber() >= barcodeMetadata.getRowCount()) {\n codewords[codewordsRow] = null;\n }\n else {\n barcodeRow = codeword.getRowNumber();\n currentRowHeight = 1;\n }\n }\n // return (int) (averageRowHeight + 0.5);\n }", "function renderData(container, processed_data) {\n \n // Different Container Div States and how to function in each state.\n //\n // 1. Neither height nor width is specified for the containing dv.\n //\n // In this state the widget should be defined by the sum of all its\n // children. Hence, intelligent defaults will be used and it will\n // be rendered.\n //\n // 2. Both height and width are specified.\n //\n // In this state the widget size is defined explicitly, hence the\n // widget will be the size explicity defined and the contents will be\n // horizontally and vertically scaled to fit N sub groups where N is\n // the number of subgroups provided..\n //\n // 3. Only width is specified\n \n // Diffrent Container Div States\n //\n // 1. The client application didn't specify a width or height, so they\n // are expecting the width and height of that div to be defined by the\n // combination of its children and its parent.\n //\n // 2. The client application does specify a width and height, so they\n // are expecting the div to only take up the provided width and height\n // in area.\n // 1. Make everything fit into the specified height and width of the div.\n //\n // 2. \n \n \n // var i;\n var html = \"\";\n // var max_bar_width = 125;\n \n // function calcBarLength(perc, max_bar_width) {\n // var r;\n // r = Math.floor((perc/100) * max_bar_width);\n // if (r == 0) {\n // r = 1;\n // }\n // return r;\n // }\n\n //container.addClass(\"ui-widget\");\n //container.addClass(\"ui-comphist-widget\");\n\n // Obtain the height of the container div and set the font-size to that\n // height in pixels so that I can then make all of the fonts and child\n // elements sized relative to that size.\n var container_width_in_px = container.height();\n //container.css('font-size', container_width_in_px + 'px');\n\n html += '<div class=\"ui-comphist-widget\" style=\"font-size: ' + container_width_in_px + 'px;\">';\n // Create the comparitive histogram header \n html += ' <div class=\"ui-comphist-header\">';\n html += ' <span class=\"ui-comphist-pop-size\">' + processed_data.population_count + '</span>';\n html += ' <span class=\"ui-comphist-pop-label\">' + processed_data.population_label + '</span>';\n html += ' </div>';\n \n html += ' <div class=\"ui-comphist-spacer\">';\n html += ' </div>';\n\n html += ' <div class=\"ui-comphist-pseudotable\">';\n // // Create primary group one bars column.\n html += ' <div class=\"ui-comphist-bars-col\">';\n html += ' <div class=\"ui-comphist-label-row ui-comphist-left-row\">';\n html += ' <div class=\"ui-comphist-group-label ui-comphist-left-label\">' + processed_data.group_1_label + '</div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row\">';\n if (processed_data.group_1_perc == 0) {\n html += ' <div class=\"ui-comphist-sum-bar ui-comphist-left\" style=\"width: 1%;\">';\n } else {\n html += ' <div class=\"ui-comphist-sum-bar ui-comphist-left\" style=\"width: ' + processed_data.group_1_perc + '%;\">';\n }\n html += ' </div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row\">';\n if (processed_data.subgroups[i].group_1_perc == 0) {\n html += ' <div class=\"ui-comphist-bar ui-comphist-left\" style=\"width: 1%;\">';\n } else {\n html += ' <div class=\"ui-comphist-bar ui-comphist-left\" style=\"width: ' + processed_data.subgroups[i].group_1_perc + '%;\">';\n }\n html += ' </div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n }\n html += ' </div>'; // close group one bars column\n // \n // // Create primary group two bars column.\n html += ' <div class=\"ui-comphist-bars-col\">';\n html += ' <div class=\"ui-comphist-label-row\">';\n html += ' <div class=\"ui-comphist-group-label ui-comphist-right-label\">' + processed_data.group_2_label + '</div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row\">';\n if (processed_data.group_2_perc == 0) { \n html += ' <div class=\"ui-comphist-sum-bar ui-comphist-right\" style=\"width: 1%;\">';\n } else {\n html += ' <div class=\"ui-comphist-sum-bar ui-comphist-right\" style=\"width: ' + processed_data.group_2_perc + '%;\">';\n }\n html += ' </div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row\">';\n if (processed_data.subgroups[i].group_2_perc == 0) {\n html += ' <div class=\"ui-comphist-bar ui-comphist-right\" style=\"width: 1%;\">';\n } else {\n html += ' <div class=\"ui-comphist-bar ui-comphist-right\" style=\"width: ' + processed_data.subgroups[i].group_2_perc + '%;\">';\n }\n html += ' </div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n } \n html += ' </div>'; // close group two bars column\n\n // Create the subgroup labels bar\n html += ' <div class=\"ui-comphist-subgroup-label-col\">';\n html += ' <div class=\"ui-comphist-label-row\">';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row\">';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row\">';\n html += ' <span class=\"ui-comphist-subgroup-label ui-comphist-right\">' + processed_data.subgroups[i].label + '</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n }\n html += ' </div>'\n\n // Create the group one stats column\n html += ' <div class=\"ui-comphist-subgroup-col\">';\n html += ' <div class=\"ui-comphist-label-row ui-comphist-left-row\">';\n html += ' <div class=\"ui-comphist-group-label ui-comphist-left-label\">' + processed_data.group_1_label + '</div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row ui-comphist-row-left\">';\n html += ' <span class=\"ui-comphist-sum-val ui-comphist-left\">' + processed_data.group_1_perc + '%</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row ui-comphist-row-left\">';\n html += ' <span class=\"ui-comphist-subgroup-val ui-comphist-left\">' + processed_data.subgroups[i].group_1_perc + '%</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n }\n html += ' </div>';\n // \n // // Create the group two stats column\n html += ' <div class=\"ui-comphist-subgroup-col\">';\n html += ' <div class=\"ui-comphist-label-row\">';\n html += ' <div class=\"ui-comphist-group-label ui-comphist-right-label\">' + processed_data.group_2_label + '</div>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row\">';\n html += ' <span class=\"ui-comphist-sum-val ui-comphist-right\">' + processed_data.group_2_perc + '%</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row\">';\n html += ' <span class=\"ui-comphist-subgroup-val ui-comphist-right\">' + processed_data.subgroups[i].group_2_perc + '%</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n }\n html += ' </div>';\n // \n // // Create the subgroup totals column\n html += ' <div class=\"ui-comphist-totals-col\">';\n html += ' <div class=\"ui-comphist-label-row\">';\n html += ' </div>';\n html += ' <div class=\"ui-comphist-sum-row\">';\n html += ' </div>';\n for (i = 0; i < processed_data.subgroups.length; i++) {\n html += ' <div class=\"ui-comphist-subgroup-row\">';\n html += ' <span class=\"ui-comphist-subgroup-tot-val ui-comphist-right\">' + processed_data.subgroups[i].tot_perc + '%</span>';\n html += ' <div style=\"clear: both;\"></div>';\n html += ' </div>';\n }\n html += ' </div>';\n \n html += \" </div>\"; // close the ui-comphist-pseudotable\n html += \"</div>\"; // close the ui-comphist-widget\n \n container.html(html);\n \n container.mouseover(function (event) {\n var curo = $(event.target);\n if (curo.hasClass(\"ui-comphist-bar\") || curo.hasClass(\"ui-comphist-sum-bar\")) {\n container.trigger(\"barover\", [curo.css(\"width\"), curo.position()]);\n }\n });\n container.mouseout(function (event) {\n var curo = $(event.target);\n if (curo.hasClass(\"ui-comphist-bar\") || curo.hasClass(\"ui-comphist-sum-bar\")) {\n container.trigger(\"barout\", [curo.css(\"width\"), curo.position()]);\n }\n });\n }", "function renderCallback(renderConfig) {\r\n\r\n\t\tvar chart = renderConfig.moonbeamInstance;\r\n\t\tvar data = renderConfig.data;\r\n\t\tvar w = renderConfig.width;\r\n\t\tvar h = renderConfig.height;\r\n\r\n\t\tvar container = d3.select(renderConfig.container)\r\n\t\t\t.attr('class', 'com_ibi_chart');\r\n\r\n\t\t// If there's nothing in series_break, dataBuckets.depth will be 1 and data will be a flat array of datum objects.\r\n\t\t// Normalize whether we have a series_break or not by forcing internal data to always have two aray dimensions.\r\n\t\tif (renderConfig.dataBuckets.depth === 1) {\r\n\t\t\tdata = [data];\r\n\t\t}\r\n\r\n\t\t// If we have only one measure, measure title is a string not array; normalize that too\r\n\t\tif (renderConfig.dataBuckets.buckets.value && !Array.isArray(renderConfig.dataBuckets.buckets.value.title)) {\r\n\t\t\trenderConfig.dataBuckets.buckets.value.title = [renderConfig.dataBuckets.buckets.value.title];\r\n\t\t}\r\n\r\n\t\t// Build list of all unique axis labels found across the entire data set\r\n\t\tvar axisLabels = pv.blend(data).map(function(el) {return el.labels;}).filter(function() {\r\n\t\t\tvar seen = {};\r\n\t\t\treturn function(el) {\r\n\t\t\t\treturn el != null && !(el in seen) && (seen[el] = 1);\r\n\t\t\t};\r\n\t\t}());\r\n\r\n\t\t// If the label bucket is empty, use 'Label X' placeholders\r\n\t\tif (!axisLabels.length) {\r\n\t\t\tvar labelCount = d3.max(data, function(el){return el.length;});\r\n\t\t\taxisLabels = d3.range(0, labelCount).map(function(el) {return 'Label ' + el;});\r\n\t\t}\r\n\r\n\t\tvar splitYCount = tdgchart.util.get('dataBuckets.buckets.value.count', renderConfig, 1);\r\n\t\tvar splitYData = [];\r\n\r\n\t\t// Data arrives in an array of arrays of {value: [a, b, c]} entires.\r\n\t\t// Each entry in 'value' gets drawn on a unique split-y axis.\r\n\t\t// Split that long list into one list of values for each split-y axis.\r\n\t\tdata.forEach(function(array) {\r\n\t\t\tarray.forEach(function(el, i) {\r\n\t\t\t\tel.value = Array.isArray(el.value) ? el.value : [el.value];\r\n\t\t\t\tif (!el.labels) {\r\n\t\t\t\t\tel.labels = 'Label ' + i;\r\n\t\t\t\t}\r\n\t\t\t\tel.value.forEach(function(v, idx) {\r\n\t\t\t\t\tsplitYData[idx] = splitYData[idx] || [];\r\n\t\t\t\t\tvar labelIndex = axisLabels.indexOf(el.labels);\r\n\t\t\t\t\tif (labelIndex >= 0) {\r\n\t\t\t\t\t\tsplitYData[idx][labelIndex] = splitYData[idx][labelIndex] || [];\r\n\t\t\t\t\t\tsplitYData[idx][labelIndex].push({\r\n\t\t\t\t\t\t\tvalue: v, yaxis: idx, labels: el.labels\r\n\t\t\t\t\t\t});\r\n\t\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// Calculate a y value for the start and end positions of each riser in each stack\r\n\t\tsplitYData.forEach(function(el) {\r\n\t\t\tel.forEach(function(stack) {\r\n\t\t\t\tvar acc = 0;\r\n\t\t\t\tstack.forEach(function(d) {\r\n\t\t\t\t\td.y0 = acc;\r\n\t\t\t\t\td.y1 = acc + d.value;\r\n\t\t\t\t\tacc += d.value;\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tvar xLabelHeight = 25;\r\n\t\tvar yHeight = (h - xLabelHeight) / splitYCount;\r\n\t\tvar x = d3.scale.ordinal().domain(axisLabels).rangeRoundBands([xLabelHeight, w - 25], 0.2);\r\n\t\tvar yScaleList = splitYData.map(function(el) {\r\n\t\t\tvar ymax = d3.max(el.map(function(a) {return d3.sum(a, function(d) {return d.value;});}));\r\n\t\t\treturn d3.scale.linear().domain([0, ymax]).range([yHeight, 20]);\r\n\t\t});\r\n\r\n\t\tvar splitYGroups = container.selectAll('g')\r\n\t\t\t.data(splitYData)\r\n\t\t\t.enter().append('g')\r\n\t\t\t.attr('transform', function(d, i) {\r\n\t\t\t\treturn 'translate(' + xLabelHeight + ', ' + (h - xLabelHeight - (yHeight * (i + 1))) + ')';\r\n\t\t\t});\r\n\r\n\t\t// Add axis divider line\r\n\t\tsplitYGroups.append('path')\r\n\t\t\t.attr('d', function(d, i) {\r\n\t\t\t\treturn 'M0,' + yScaleList[i](0) + 'l' + (w - 25) + ',0';\r\n\t\t\t})\r\n\t\t\t.attr('stroke', 'grey')\r\n\t\t\t.attr('stroke-width', 1)\r\n\t\t\t.attr('shape-rendering', 'crispEdges');\r\n\r\n\t\t// Add rotated split y axis label\r\n\t\tsplitYGroups.append('text')\r\n\t\t\t.attr('transform', function() {\r\n\t\t\t\treturn 'translate(-10,' + (yHeight / 2) + ') rotate(-90)';\r\n\t\t\t})\r\n\t\t\t.attr('fill', 'black')\r\n\t\t\t.attr('font-size', '12px')\r\n\t\t\t.attr('font-family', 'helvetica')\r\n\t\t\t.attr('text-anchor', 'middle')\r\n\t\t\t.text(function(d, i) {return tdgchart.util.get('dataBuckets.buckets.value.title[' + i + ']', renderConfig, '');});\r\n\r\n\t\t// Add risers, grouped by stack\r\n\t\tvar riserGroups = splitYGroups.selectAll('g')\r\n\t\t\t.data(function(d) {\r\n\t\t\t\treturn d; // d: flat array of riser data\r\n\t\t\t})\r\n\t\t\t.enter().append('g');\r\n\r\n\t\t// Draw the actual risers themselves\r\n\t\triserGroups.selectAll('rect')\r\n\t\t\t.data(function(d) {\r\n\t\t\t\treturn d; // d: single {y0, y1, label} datum (finally!)\r\n\t\t\t})\r\n\t\t\t.enter().append('rect')\r\n\t\t\t.attr('shape-rendering', 'crispEdges')\r\n\t\t\t.attr('x', function(d) {\r\n\t\t\t\treturn x(d.labels);\r\n\t\t\t})\r\n\t\t\t.attr('y', function(d) {\r\n\t\t\t\treturn yScaleList[d.yaxis](d.y1);\r\n\t\t\t})\r\n\t\t\t.attr('width', x.rangeBand())\r\n\t\t\t.attr('height', function(d) {\r\n\t\t\t\treturn Math.abs(yScaleList[d.yaxis](d.y1) - yScaleList[d.yaxis](d.y0));\r\n\t\t\t})\r\n\t\t\t.attr('class', function(d, s, g) {\r\n\r\n\t\t\t\t// To support data selection, events and tooltips, each riser must include a class name with the appropriate seriesID and groupID\r\n\t\t\t\t// Use chart.buildClassName to create an appropriate class name.\r\n\t\t\t\t// 1st argument must be 'riser', 2nd is seriesID, 3rd is groupID, 4th is an optional extra string which can be used to identify the risers in your extension.\r\n\t\t\t\treturn chart.buildClassName('riser', s, g, 'bar');\r\n\t\t\t})\r\n\t\t\t.attr('fill', function(d, s) {\r\n\r\n\t\t\t\t// getSeriesAndGroupProperty(seriesID, groupID, property) is a handy function\r\n\t\t\t\t// to easily look up any series dependent property. 'property' can be in\r\n\t\t\t\t// dot notation (eg: 'marker.border.width')\r\n\t\t\t\treturn chart.getSeriesAndGroupProperty(s, null, 'color');\r\n\t\t\t})\r\n\t\t\t.each(function(d, s, g) {\r\n\r\n\t\t\t\t// addDefaultToolTipContent will add the same tooltip to this riser as the built in chart types would.\r\n\t\t\t\t// Assumes that 'this' node includes a fully qualified series & group class string.\r\n\t\t\t\t// addDefaultToolTipContent can also accept optional arguments:\r\n\t\t\t\t// addDefaultToolTipContent(target, s, g, d, data), useful if this node does not have a class\r\n\t\t\t\t// or if you want to override the default series / group / datum lookup logic.\r\n\t\t\t\trenderConfig.modules.tooltip.addDefaultToolTipContent(this, s, g, d);\r\n\t\t\t});\r\n\r\n\t\t// Add bottom ordinal x axis labels\r\n\t\tcontainer.append('g')\r\n\t\t\t.selectAll('text')\r\n\t\t\t.data(axisLabels)\r\n\t\t\t.enter().append('text')\r\n\t\t\t.attr('transform', function(d) {\r\n\t\t\t\treturn 'translate(' + (x(d) + xLabelHeight + (x.rangeBand() / 2)) + ',' + (h - 5) + ')';\r\n\t\t\t})\r\n\t\t\t.attr('fill', 'black')\r\n\t\t\t.attr('font-size', '12px')\r\n\t\t\t.attr('font-family', 'helvetica')\r\n\t\t\t.attr('text-anchor', 'middle')\r\n\t\t\t.text(function(d, i) {return axisLabels[i];});\r\n\r\n\t\trenderConfig.renderComplete();\r\n\t}", "function updateOffsets() {\n //For each line, update the offsets.\n for (var j = 0; j < lineArray.length; j++) {\n l = lineArray[j];\n //Calculate the angle of the line:\n var angle = lineAngleFromOrigin(l.startx, l.starty, l.endx, l.endy);\n\n //transform angle to start at x axis and go positive C.C:\n angle = angle - 90;\n if (angle <= 0) {\n angle = angle + 360;\n }\n angle = 360 - angle;\n\n var actLength = l.lineLength * Scale;\n\n //call a function that defines offsets based on line data:\n var offsetArray = findOffsets(\n actLength,\n l.startx,\n l.starty,\n l.endx,\n l.endy,\n angle\n );\n var xoffset1 = offsetArray[2];\n var yoffset1 = offsetArray[3];\n var xoffset2 = offsetArray[4];\n var yoffset2 = offsetArray[5];\n var perpOffset = offsetArray[8];\n\n for (var i = 0; i < linearDimArray.length; i++) {\n d = linearDimArray[i];\n if (d.elementID == l.lineID) {\n d.xoffset1 = xoffset1;\n d.yoffset1 = yoffset1;\n d.xoffset2 = xoffset2;\n d.yoffset2 = yoffset2;\n d.perpOffset = perpOffset;\n }\n }\n }\n\n //For each fillet, update the offset:\n for (var i = 0; i < arcArray.length; i++) {\n a = arcArray[i];\n updateFilletDim(a.arcID);\n }\n}", "function processDimsWithMeasure()\r\n {\r\n var startIndex = 0,\r\n endIndex = data_.values.length;\r\n var dimInRow = dimInRow_,\r\n dimInCol = dimInCol_;\r\n var bMNDInner = false,\r\n bMNDInRow = true;\r\n var i;\r\n if(data_.values[0].type === \"MND\")\r\n {\r\n ++startIndex;\r\n if(dimInRow > 0){ \r\n --dimInRow;\r\n } else {\r\n --dimInCol;\r\n bMNDInRow = false;\r\n }\r\n }\r\n\r\n if(data_.values[endIndex - 1].type === \"MND\")\r\n {\r\n bMNDInner = true;\r\n --endIndex;\r\n if(dimInCol > 0)\r\n {\r\n --dimInCol;\r\n bMNDInRow = false;\r\n }else{\r\n bMNDInRow = true;\r\n --dimInRow;\r\n }\r\n }\r\n\r\n //process no MND cases first\r\n if(startIndex < endIndex)\r\n {\r\n //some dimension in row and some in column \r\n var rowIndexs = [];\r\n if(dimInCol > 0 || dimInRow > 0)\r\n {\r\n //process row dimension first\r\n rowIndexs[0] = 0;\r\n rowCount_ = 0;\r\n if(dimInRow > 0)\r\n {\r\n buildRowDimension(dimInRow, startIndex, rowIndexs);\r\n }else{\r\n rowCount_ = 1;\r\n for(i = 1; i < data_.values[startIndex].rows.length; ++i){\r\n rowIndexs[i] = 0;\r\n }\r\n }\r\n \r\n //build column dimensions and indexes\r\n var colIndexs = [];\r\n if(dimInCol > 0)\r\n {\r\n colIndexs = processColHeader(startIndex + dimInRow, dimInCol);\r\n }else{\r\n colCount_ = 1;\r\n for(i = 0; i < data_.values[startIndex].rows.length; ++i){\r\n colIndexs[i] = 0;\r\n }\r\n }\r\n \r\n //generate data context for each sub chart\r\n ctx_ = new Array(rowCount_);\r\n for(i = 0; i < rowCount_; ++i)\r\n {\r\n ctx_[i] = [];\r\n for(var j = 0; j < colCount_; ++j){\r\n ctx_[i][j] = null;\r\n }\r\n }\r\n\r\n for(i = 0 ; i < data_.values[startIndex].rows.length; ++i)\r\n {\r\n ctx_[rowIndexs[i]][colIndexs[i]] = data_.values[startIndex + dimInRow + dimInCol - 1].rows[i].ctx;\r\n }\r\n }\r\n \r\n //process measure names at last\r\n if(dimInRow < dimInRow_ || dimInCol < dimInCol_)\r\n {\r\n addMND(bMNDInner, bMNDInRow, dimInRow, dimInCol);\r\n }\r\n }\r\n }", "function updateOldData() {\r\n /**REWRITTEN WITH BINHEAPS*/\r\n var selectDisplays = getMultiSelectionArray();\r\n var selectDisplaysLength = selectDisplays.length;\r\n if (selectDisplays.length === 0) {\r\n return;\r\n }\r\n olddata = new Array(selectDisplaysLength);\r\n \r\n //update bounds\r\n getMSBounds();\r\n var leftDist = dataHolder._leftExternal.peek(), //boundArray[0],\r\n rightDist = dataHolder._rightExternal.peek(); //boundArray[1];\r\n if (leftDist) { //null checking\r\n leftDist = leftDist.bound;\r\n }\r\n if (rightDist) { //null checking\r\n rightDist = rightDist.bound;\r\n }\r\n for (var i = 0; i < selectDisplaysLength; i++) {\r\n olddata[i] = new Array(5);\r\n var leftbound = selectDisplays[i].getStart() - leftDist;\r\n var rightbound = selectDisplays[i].getEnd() + rightDist;\r\n olddata[i][0] = selectDisplays[i].getStart();\r\n olddata[i][1] = selectDisplays[i].getMainStart();\r\n olddata[i][2] = selectDisplays[i].getOutStart();\r\n olddata[i][3] = leftbound;\r\n olddata[i][4] = rightbound;\r\n }\r\n }", "adjustCompleteIndicatorColumnRowNumbers(barcodeMetadata) {\n let codewords = this.getCodewords();\n this.setRowNumbers();\n this.removeIncorrectCodewords(codewords, barcodeMetadata);\n let boundingBox = this.getBoundingBox();\n let top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();\n let bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();\n let firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));\n let lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));\n // We need to be careful using the average row height. Barcode could be skewed so that we have smaller and\n // taller rows\n // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();\n let barcodeRow = -1;\n let maxRowHeight = 1;\n let currentRowHeight = 0;\n for (let codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n let codeword = codewords[codewordsRow];\n // float expectedRowNumber = (codewordsRow - firstRow) / averageRowHeight;\n // if (Math.abs(codeword.getRowNumber() - expectedRowNumber) > 2) {\n // SimpleLog.log(LEVEL.WARNING,\n // \"Removing codeword, rowNumberSkew too high, codeword[\" + codewordsRow + \"]: Expected Row: \" +\n // expectedRowNumber + \", RealRow: \" + codeword.getRowNumber() + \", value: \" + codeword.getValue());\n // codewords[codewordsRow] = null;\n // }\n let rowDifference = codeword.getRowNumber() - barcodeRow;\n // TODO improve handling with case where first row indicator doesn't start with 0\n if (rowDifference === 0) {\n currentRowHeight++;\n }\n else if (rowDifference === 1) {\n maxRowHeight = Math.max(maxRowHeight, currentRowHeight);\n currentRowHeight = 1;\n barcodeRow = codeword.getRowNumber();\n }\n else if (rowDifference < 0 ||\n codeword.getRowNumber() >= barcodeMetadata.getRowCount() ||\n rowDifference > codewordsRow) {\n codewords[codewordsRow] = null;\n }\n else {\n let checkedRows;\n if (maxRowHeight > 2) {\n checkedRows = (maxRowHeight - 2) * rowDifference;\n }\n else {\n checkedRows = rowDifference;\n }\n let closePreviousCodewordFound = checkedRows >= codewordsRow;\n for (let i /*int*/ = 1; i <= checkedRows && !closePreviousCodewordFound; i++) {\n // there must be (height * rowDifference) number of codewords missing. For now we assume height = 1.\n // This should hopefully get rid of most problems already.\n closePreviousCodewordFound = codewords[codewordsRow - i] != null;\n }\n if (closePreviousCodewordFound) {\n codewords[codewordsRow] = null;\n }\n else {\n barcodeRow = codeword.getRowNumber();\n currentRowHeight = 1;\n }\n }\n }\n // return (int) (averageRowHeight + 0.5);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verplaats en animeer robots
function updateRobots() { for (var i = 0; i < robotData.length; i++) { // Check for hit let hit_Check = overlappenNanonautRobot( nanonautX + nanonaut_Hitbox.x_Offset, nanonautY + nanonaut_Hitbox.y_Offset, nanonaut_Hitbox.breedte, nanonaut_Hitbox.hoogte, robotData[i].x + robot_Hitbox.x_Offset, robotData[i].y + robot_Hitbox.y_Offset, robot_Hitbox.breedte, robot_Hitbox.hoogte ); if (hit_Check) { console.log("Hit!!" + hit_Check); schermschudden = true; damageCalc("robot"); } // Robots run left robotData[i].x -= ROBOT_X_SNELHEID; if ((spelFrameTeller % ROBOT_ANIMATIESNELHEID) === 0) { robotData[i].frameNR++; if (robotData[i].frameNR >= ROBOT_NR_ANIMATIEFRAMES) { robotData[i].frameNR = 0; } } // Verwijder robots die uit beeld zijn, uit de robotData array. let robotIndex = 0; while (robotIndex < robotData.length) { if (robotData[robotIndex].x < cameraX - ROBOT_BREEDTE) { robotData.splice(robotIndex, 1); console.log("Robot gone " + robotIndex); } else { robotIndex++; // console.log("Robot in screen " + robotIndex); } } } // Generate new robot within the robotData array. if (robotData.length < MAX_ACTIEVE_ROBOTS) { let laatsteRobotX = CANVAS_BREEDTE; if (robotData.length > 0) { laatsteRobotX = robotData[robotData.length -1].x; } let nieuweRobotX = laatsteRobotX + MIN_AFSTAND_TUSSEN_ROBOTS + Math.random() * (MAX_AFSTAND_TUSSEN_ROBOTS - MIN_AFSTAND_TUSSEN_ROBOTS); robotData.push({ x: nieuweRobotX, y: GROND_Y - ROBOT_HOOGTE, frameNR: 0 }); } }
[ "checkVirus() {\n var {x, y} = this.pos;\n agents.filter(a => a instanceof Virus).forEach(v => {\n if(getDistance(x,v.pos.x,y,v.pos.y) < options.infectionDistance && !this.isInfected) {\n if(Math.random() < options.infectionProbability) {\n this.infect();\n return false;\n }\n }\n \n });\n }", "checkVirus() {\n var {x, y} = this.pos;\n agents.filter(a => a instanceof Virus).forEach(v => {\n var dist = getDistance(x,v.pos.x,y,v.pos.y);\n if(dist < options.followDistance) {\n this.angle = getFollowAngle(x,v.pos.x,y,v.pos.y);\n if(dist < options.defenseDistance) {\n if(Math.random() < options.defenseProbability) {\n if(agents.filter(a => a instanceof Defender).length < Math.floor(options.defenderRatio * 5 * options.bloodCellStartCount)) {\n spawnWhiteBloodCell();\n } \n removeAgent(v.id);\n }\n }\n }\n });\n }", "function verifyVelha(){\n let testeVelha = game.filter((item) =>{\n return item.value != 'X' && item.value != 'O';\n });\n\n if(testeVelha[0] == null){ \n let videoTextureVelha = new BABYLON.VideoTexture(\"video\", \"assets/img/velha.mp4\", scene, true);\n groundMaterial.emissiveColor= new BABYLON.Vector3(0,0,0);\n \n let ground = scene.getMeshByName('ground');\n ground.material.emissiveTexture = videoTextureVelha;\n possoJogar = false;\n scene.activeCamera =camera2;\n resetGame();\n }\n }", "function magnetDetected() {\n rotation++\n}", "function Robot(){\n this.evil = false;\n}", "function DetectaPalmOS(){\n\n if (uagent.search(dispositivoPalm) > -1)\n\n return true;\n\n else\n\n return false;\n\n}", "function reinitialiserRobots() {\n\tvar L = document.querySelectorAll('#plateau .robot, #boutons .bouton');\n\tfor (var i = 0; i < L.length; i++) {\n\t\t[\n\t\t\t'deplace',\n\t\t\t'dernier-deplace',\n\t\t\t'selection'\n\t\t].forEach(function(class_) {\n\t\t\tutil.removeClass(L[i], class_);\n\t\t});\n\t\tif (util.hasClass(L[i], 'robot')) {\n\t\t\tutil.moveTo(L[i], getCase(L[i].getAttribute('data-ligne-origine'), L[i].getAttribute('data-colonne-origine')));\n\t\t}\n\t}\n}", "function avancer_polygone() {\n\n\tfor (var p = 0; p<18; p++) {\n\n\t\tpolygone[p][1] = polygone[p][1] + vitesse_ver_route;\t\t/* on fait avancer le point verticalement */\n\n\t\tif (polygone[p][1] > 100) {\t\t\t\t/* test : si le point est sorti en bas de l'écran, on le redessine en haut */\n\t\t\tvitesse_lat_route = vitesse_lat_route + Math.floor(3*Math.random())/10 - 0.1;\n\t\t\tif (vitesse_lat_route > 1 || vitesse_lat_route < -1) {\n\t\t\t\tvitesse_lat_route = 0;\t\t\t/* rétroaction négative pour éviter une trop grande difficulté */\n\t\t\t}\n\t\t\tif (xroute+vitesse_lat_route <0 \n\t\t\t\t|| xroute+vitesse_lat_route+largeur > 100) {\n\t\t\t\t\tvitesse_lat_route = -vitesse_lat_route;\t\t/* pour faire tourner la route dans l'autre sens si on atteind le bord */\n\t\t\t}\n\t\t\txroute = xroute + vitesse_lat_route;\n\t\t\tpolygone[p][0] = xroute;\n\t\t\tpolygone[p][1] = polygone[p][1] % 100;\n\t\t\tpremierpoint = p;\n\t\t}\n\t}\n\n}", "function updateRTCVideo()\n{\n var currentRobot = document.getElementById('robot_videoname').value;\n var robotVideo = currentRobot.replace(/[/]/g,\"\");\n\n\n // Use AppRTC instead of gruveo for video\n var videoURL = \"https://appear.in/\" + robotVideo;\n document.getElementById(\"video_frame\").src = videoURL;\n\n}", "async function verififierJoueursActif() {\n//TODO Suppression des joueurs inactifs\n}", "function configureViruses() {\n viruses.children.iterate(virus => {\n virus.setVelocity(Phaser.Math.Between(0.5, 4), Phaser.Math.Between(0.9, 2));\n virus.setCollideWorldBounds(true);\n virus.setBounce(Phaser.Math.Between(0.1, 1));\n });\n}", "function verVegano(){\n var v = p.filtrarVegano();\n p.dibujarSurtido(v);\n}", "function updateRobot(vars) {\n var add_robot_flag = true;\n if(vars.length < 8) { // probably no velocity, so we pad\n vars[7] = vars[6];\n vars[6] = 0;\n }\n if(current_robot_list.length) {\n for(var i = 0; i < current_robot_list.length; i++) {\n if(current_robot_list[i].values[0].innerHTML == vars[0]) {\n add_robot_flag = false;\n for(var j = 0; j < number_of_fields; j++) {\n if(current_robot_list[i].fields[j].innerHTML === 'Status') {\n current_robot_list[i].status = 'Connected';\n current_robot_list[i].values[j].innerHTML = current_robot_list[i ].status;\n current_robot_list[i].values[j].classList.remove('status-disconnected');\n current_robot_list[i].values[j].classList.add('status-connected');\n } else if(current_robot_list[i].fields[j].innerHTML === 'Position X') {\n current_robot_list[i].x = vars[j];\n current_robot_list[i].values[j].innerHTML = vars[j];\n } else if(current_robot_list[i].fields[j].innerHTML === 'Position Y') {\n current_robot_list[i].y = vars[j];\n current_robot_list[i].values[j].innerHTML = vars[j];\n } else if(current_robot_list[i].fields[j].innerHTML === 'Heading') {\n current_robot_list[i].heading = parseFloat(vars[j]);\n current_robot_list[i].values[j].innerHTML = Math.round(((parseFloat(vars[j])) * 180 / Math.PI) * 100)/100;\n } else if(current_robot_list[i].fields[j].innerHTML === 'Color') {\n \n } else {\n current_robot_list[i].values[j].innerHTML = vars[j];\n }\n }\n timer(current_robot_list[i]);\n }\n }\n drawRobots();\n if(add_robot_flag) {\n addRobot(createRobot(vars));\n }\n } else {\n addRobot(createRobot(vars));\n }\n}", "async function updateVideo() {\n if (using_normal_mediapipe) {\n await pose.send({ image: videoElement });\n } else {\n const poses = await detector.estimatePoses(videoElement, estimationConfig, timestamp);\n tfjsSetLandmarks(poses)\n }\n window.requestAnimationFrame(updateVideo);\n}", "function receptBroodje (vulling) {\n console.log (\"pak 2 sneetjes brood en stop daar\" + vulling + \" \" + \"tussen.\");\n}", "infect() {\n this.isInfected = true;\n this.color = \"yellow\";\n var {x, y} = this.pos;\n var id = this.id;\n setTimeout(() => {\n for(let i = 0; i < 2; i++) {\n agents = [...agents,new Virus({x,y,id:\"virus\"+agents.filter(a => a instanceof Virus).length})]\n }\n $(\"#virusCount\").text(agents.filter(a => a instanceof Virus).length);\n removeAgent(id);\n },5000);\n }", "function createVirusB(controller, pos, direction, speed, orient, health){\n\tvar virus = createEnemy(controller, pos, direction, speed, orient, 10, health);\n\t\n\tvirus.subType = \"VirusB\";\n\t\n\tvirus.STATE_MOVING = 0;\n\tvirus.STATE_DEAD = 1;\n\t\n\tvirus.state = virus.STATE_MOVING;\n\t\n\tvirus.pointToGo = undefined;\n\tvirus.xToGo = undefined;\n\tvirus.yToGo = undefined;\n\t\n\t var animations = [ new Animation(\"anim\", 0, 8, 512 / 8, 64, 3) ];\n\t animations[0].setFrame(parseInt(Math.random() * 8, 10));\n\t animations[0].setDuration(parseInt(Math.random() * 3 + 3, 10));\n\t virus.sprite = new Sprite(animations, ResourceManagerObject.getResource('virus'));\n\t\n\tvirus.update = function() {\n\t\tif (this.state == this.STATE_MOVING) {\n\t\t\tthis.sprite.animate();\n\t\t\tif(this.xToGo == undefined){\n\t\t\t\tvar angle = Math.random() * Math.PI * 2;\n\t\t\t\tthis.xToGo = this.controller.player.pos.x + Math.cos(angle) * this.boundRadius * 5; \n\t\t\t\tthis.yToGo = this.controller.player.pos.y + Math.sin(angle) * this.boundRadius * 5;\n\t\t\t\t\n\t\t\t\tthis.pointToGo = createVec(this.xToGo, this.yToGo);\n\t\t\t\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tvar tempX = this.pos.x - this.xToGo;\n\t\t\t\tvar tempY = this.pos.y - this.yToGo;\n\t\t\t\t\n\t\t\t\tvar intensity = Math.sqrt(tempX * tempX + tempY * tempY);\n\t\t\t\tif(intensity < 10){\n\t\t\t\t\tthis.xToGo = undefined;\n\t\t\t\t\tthis.yToGo = undefined;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tvar x = this.xToGo - this.pos.x;\n\t\t\tvar y = this.yToGo - this.pos.y;\n\t\t\tvar mag = 1 / Math.sqrt(x * x + y * y);\n\t\t\tthis.direction.x = x*mag;\n\t\t\tthis.direction.y = y*mag;\n\t\t\t\n\t\t\tthis.pos = this.pos.add(this.direction.mult(this.speed));\t\t\t\n\t\t}else if(this.state == this.STATE_DEAD){\n\t\t\teff = createParticleEffect(this.controller, this.pos, 15);\n\t\t\tthis.controller.addEffect(eff);\n\t\t\tthis.controller.removeEnemy(this);\n\n\t\t\t// create item\n\t\t\tif (Math.random() < 0.25) {\n\t\t\t\tvar virusItem = createVirusItem(this.controller, createVec(this.pos.x, this.pos.y), \n\t\t\t\t\t\tcreateVec(0, 1), 2.0, createVec(0, 1), 5.0);\t\t\t\t\n\t\t\t\tthis.controller.addItem(virusItem);\t\n\t\t\t}\n\t\t}\n\n\t};\n\t\n\tvirus.draw = function(ctx){\n\t\tctx.save();\n\t\tctx.translate(this.pos.x, this.pos.y);\n\t\tthis.sprite.draw(ctx);\n\t\tctx.restore();\n\t};\n\n\tvirus.eventCollision = function(collisionEvent) {\n\t\tif (collisionEvent.obj1.type == \"Bullet\") {\n\t\t\tAudioManagerObject.play('explosion');\n\t\t\tthis.state = this.STATE_DEAD;\n\t\t} else if (collisionEvent.obj1.type == \"Player\"){ \n\t\t\tthis.state = this.STATE_DEAD;\n\t\t}\n\t\t\n\t};\n\t\n\treturn virus;\n\t\n}", "function alien_is_sad() {\n wiggle_ears(110, 30, 226, 0.5, function () {\n setTimeout(function () {\n wiggle_ears(100, 40, 216, 0.5);\n }, 1000);\n });\n}", "function maakEenBroodjeKaas() {\r\n console.log(\"pak een boterham\");\r\n console.log(\"smeer er boter op\");\r\n console.log(\"leg er een plakje kaas op\");\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
displayWelcome() Displays Welcome message with image of flower and nifty custom animations. Also shows the 'Charts' dropdown for user to select visualizations.
function displayWelcome() { $("#welcome").css('opacity', 0).show().animate({ opacity: 1 }, 750, function() { $("#welcome").animate({ top: "15%" }, 1000, function() { $("#welcomemessage").fadeIn(function () { setTimeout(function() { $("#welcomebutton").fadeIn(function() { initializeRockAndRollButton(); }); }, 500); }); }); }); }
[ "function showWelcome() {\n const demo = action(\"load-demo\", \"demo database\");\n let message = `<p>${messages.invite}<br>or load the ${demo}.</p>`;\n message += `<p>Click the logo anytime to start from scratch.</p>`;\n if (!gister.hasCredentials()) {\n const settings = action(\"visit\", \"settings\", \"settings\");\n message += `<p>Visit ${settings} to enable sharing.</p>`;\n }\n const about = action(\"visit\", \"About SQLime\", \"about\");\n message += `<p>${about}</p>`;\n ui.status.info(message);\n}", "function showWelcome() {\n console.log('SHOW WELCOME');\n\n g.selectAll('.wind-img')\n .transition(hide)\n .style('opacity', 0);\n\n let bubbles = g.selectAll('.bubble');\n bubbles.selectAll('circle')\n .transition(hide)\n .attr('r', 0)\n .style('opacity', 0);\n bubbles.selectAll('text')\n .transition(hide)\n .style('opacity', 0);\n\n g.selectAll('.welcome')\n .transition(show)\n .style('opacity', 1.0);\n }", "drawWelcomeScreen() {\n clear();\n log(chalk.yellowBright(\" ============================================================ \"));\n log(\n chalk.yellowBright(\n figlet.textSync(\" > S P I N <\", {\n horizontalLayout: 'full'\n })\n )\n );\n log(chalk.yellowBright(\" ============================================================ \"));\n }", "function showWelcome() {\n\tvar message = '1) Shake phone to attack!\\n2) Touch screen to yell!',\n\t\tbuttonText = 'Start',\n\t\ttoastId,\n\n\t\t// button clicked callback\n\t\tonButtonSelected = function() {\n\t\t\tgong.play();\n\t\t},\n\n\t\t// toast dismissed callback\n\t\tonToastDismissed = function() {};\n\n\t// toast options\n\toptions = {\n\t\tbuttonText: buttonText,\n\t\tbuttonCallback: onButtonSelected,\n\t\tdismissCallback: onToastDismissed,\n\t\ttimeout: 20000\n\t};\n\n\t// display the toast message\n\ttoastId = blackberry.ui.toast.show(message, options);\n}", "function welcomeScreen() {\n\t\t$(\"header\").fadeIn(1000);\n\t\t$(\"#beginButton\").fadeIn(1000);\n\t\t$(\"#submitButton\").hide();\n\t\t$(\"#continueButton\").hide();\n\t\t$(\"#retryButton\").hide();\n\t}", "function welcomeDisplay() {\n console.log(\"*******************************************************************\".rainbow);\n console.log(\" Welcome to Bamazon Manager View \".bgRed);\n console.log(\"*******************************************************************\\n\".rainbow);\n}", "function revealWelcome() {\n // Keep progress bar hidden\n $userProgress.hide();\n // Hide welcome message initially\n $welcomeText.hide();\n $affirmation.hide();\n $playButton.hide();\n\n // Fade out inspirational image\n setTimeout(function() {$introImage.fadeOut(function() {\n // Then fade in sidebar displaying zodiac image\n // and play accompanying sound effect\n $appearSFX.play();\n $sidebar.fadeIn(function() {\n // Then fade in welcome message\n $welcomeText.fadeIn('slow', function() {\n // After a pause, reveal final profile question\n setTimeout(function() {\n console.log('last one!');\n $userProfile.filter('h3').filter(':nth-child(5)').fadeIn();\n $userAura.fadeIn();\n }, 500);\n });\n });\n });\n},100);\n\n // Set inspirational image to gif for later\n\n}", "function displayWelcome(){\n $tickerText.stop(true,true);\n $tickerText.html('Hi, Welcome to Simon The Synth. Please press play to start the game.');\n animateLongTicker();\n}", "function displayWelcomeMessage() {\n \n welcomeCardEl.show();\n questionCardEl.hide();\n timeUpCardEl.hide();\n highScoreCardEl.hide();\n invalidInitialsEl.hide();\n}", "function welcomeScreen() {\n\n const welcomeMessage = `\n \n ***************************************************\n | |\n | Dev Team Builder |\n | |\n ***************************************************\n \n * This command-line application will generate an *\n * html page with the information of each of your *\n * team members, for easy reference. *\n\n `\n\n console.clear();\n console.log(\"\\n\");\n console.log(welcomeMessage);\n console.log(\"\\n\");\n}", "function renderWelcomeScreen(){\r\n getTemplateAjax('./templates/welcome.handlebars', function(template) {\r\n welcomeData =\r\n {welcomeTitle: \"Hey. Where do you want to park?\", welcomeMessage: \"Single-origin coffee portland squid tofu 3 wolf moon fixie thundercats single-origin coffee tofu jean shorts.\"}\r\n $('#welcomeScreen').html(template(welcomeData));\r\n })\r\n }", "function printWelcome(){\n console.log(\n chalk.hex('#108771')(\n figlet.textSync('Welcome to', { horizontalLayout: 'default', font: 'cyberlarge' })\n )\n );\n\n console.log(\n // Hex colour taken from Multitudes website\n chalk.hex('#6DD8AA')(\n figlet.textSync('Multitudes CLI', { horizontalLayout: 'fitted' })\n )\n );\n}", "function welcome() {\r\n\t\tctx.clearRect(0, 0, cw, ch);\r\n\t\tctx.fillStyle = \"white\";\r\n\t\tctx.font = ch*2/15 + \"px Lucida Console\";\r\n\t\tctx.fillText(\"Retro Snaker\", cw/6, ch/2, cw*2/3);\r\n\t\tctx.font = ch*1/25 + \"px Lucida Console\";\r\n\t\tctx.fillText(\"Press \\\"↑ ↓ ← →\\\" to Start\", cw*3/10, 11*ch/15, cw*2/5);\r\n\t}", "function showWelcome()\n {\n// switched off on client request\n//\tvar srcFile = \"../ModelPopup/WelcomeModal.aspx\";\t//COMDIFF: prepend \"../\"\n//\tvar cFrame = new Element('iframe').setProperties({id:\"yt-HelpContent\", height:'580px', width:'600px', frameborder:\"0\", scrolling:\"no\", src:srcFile}).injectInside(document.body);\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n//\tcustomModalBox.htmlBox('yt-HelpContent', '', 'Help'); \n//\t$('mb_contents').addClass('yt-Panel-Primary');\n//\tnew Element('h2').setHTML('Welcome to Your Tribute').setProperty('id','mb_Title').injectTop($('mb_contents'));\n//\twelcomeClose();\n}", "function renderWelcome() {\n var welcome = $('#welcome');\n welcome.find('.first_name').html(friendCache.me.first_name);\n welcome.find('.profile').attr('src', friendCache.me.picture.data.url);\n welcome.find('.stats .coins').html(Parse.User.current().get('coins'));\n welcome.find('.stats .bombs').html(Parse.User.current().get('bombs'));\n}", "displayWelcomeMsg() {\n // Game start message\n console.log('%c Space Battle', 'color: white; font-size: 40px; border;');\n alert(`You have now begun playing Space Battle! The instructions are simple. Keep playing until you've destroyed all the enemy alien ships! You must save Earth from Thanos' invading alien army!`);\n // Generates 6 alien ships\n this.alienships.generateShip(6);\n alert(`There are ${this.alienships.spaceships.length - (this.iterable)} alien ships remaining!`);\n }", "function drawWelcomeMessage(barText) {\n document.querySelector('#welcome-message').innerHTML = `\n Hello ${user.displayName}! You are at ${barText}.\n `\n }", "function displayWelcomeMessage() {\n const username = getLocalStorageUsername();\n welcomeH1.innerHTML = `<h1 class=\"welcome-h1\">Hey, ${username}! Here's your todo list for today.</h1>\n <h3>The goal is to prevent the rainbow bar to get empty by completing you daily tasks.</h3>\n <h3>No one can stop you!</h3>`;\n}", "function renderWelcome () {\n \n var welcomeHTML = `\n <div class=\"curriculum_image\">\n </div>\n <h1 class=\"dashboard_welcome\">Welcome ${state.teacher_first_name} ${state.teacher_last_name},</h1>\n\n <h2 class=\"features F_one\">You currently have <strong>${state.student_records.length}</strong> students!</h2>\n\n <h2 class=\"features F_two\">To add a student, click the <strong>Add / Edit Student</strong> button.</h2>\n\n <h2 class=\"features F_three\">To add a student project, click the <strong>Add Student Project</strong> button. A project can only be added for an existing student.</h2>\n\n <h2 class=\"features F_four\">To view your student list, search and sort students, and view detailed student info and curriculum data, click the <strong>Student List and Schedule</strong> button.</h2>\n \n `;\n \n $('div.background').html(welcomeHTML);\n\n\n if (state.student_records.length === 0) {\n $('.features F_One').text('You have not added any students yet.');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add tab scope/DOM node to the cache and configure to autoremove when the scope is destroyed.
function addToCache(cache, item) { var scope = item.tab; cache[ scope.$id ] = item; cache.length = cache.length + 1; // When the tab is removed, remove its associated material-view Node... scope.$on("$destroy", function () { angular.element(item.element).remove(); delete cache[ scope.$id]; cache.length = cache.length - 1; }); }
[ "function SetTabStorageVariable() {\n chrome.storage.local.set({'TabsCache': {}});\n }", "rewriteCache() {\n this.cache = {\n levels: [],\n levelCount: 0,\n rows: [],\n nodeInfo: new WeakMap()\n };\n\n rangeEach(0, this.data.length - 1, (i) => {\n this.cacheNode(this.data[i], 0, null);\n });\n }", "function fillScopes(cacheEntry) {\n if (typeof(scopeId) != 'object')\n cacheEntry.scopes[scopeId] = true;\n else\n angular.forEach(scopeId, function(value, key) {\n cacheEntry.scopes[key] = true;\n });\n }", "function clearCache(node) {\n node['__incrementalDOMData'] = null;\n for (var child = node.firstChild; child; child = child.nextSibling) {\n clearCache(child);\n }\n}", "get scopeCache() {\n return this.context.scope().attributes().getOrElseUpdate(\"scopeCache\", scalaF0({}));\n}", "function cacheDom() {\n }", "crawlScope() {\n (traverse.clearCache || traverse.cache.clear)();\n this.program.scope.crawl();\n }", "function updateTab(node) {\n if (tabMap.get(node.id)) {\n chromeTabs.updateTab(tabMap.get(node.id), { \n title: node.name, \n id: node.id, \n favicon: node.element.childNodes[0].getElementsByClassName('file-icon')[0].src\n });\n }\n}", "clearCache() {\n this.treeArray = [];\n }", "invalidateChildrenCache() {\n this._invalidChildrenCache = true;\n }", "function recache($node, pa) {\n const path = pa.concat($node.data(\"key\"));\n\n if (Tree.debug) {\n Serror.assert(pa);\n\t\t\t\tconst p = path.join(PATHSEP);\n Serror.assert(!Tree.path2$node[p], `Cannot remap '${p}'`);\n\t\t\t\tSerror.assert(!$node.data(\"path\"),\n\t\t\t\t\t\t\t\t `Node at ${p}already mapped`);\n }\n\n // node->path mapping\n $node.data(\"path\", path);\n\n // path->node mapping\n Tree.path2$node[path.join(PATHSEP)] = $node;\n\n // Repeat for subnodes\n $node\n .find(\"ul\")\n .first()\n .children(\".tree\")\n .each(function () {\n recache($(this), path);\n });\n }", "function removeNewXmlEntry() {\n var notebookFileName = getNotebookFileName(currentTabEntryId);\n var xmlDoc = $.parseXML($('#txtCache-' + notebookFileName).text());\n $notebook = $(xmlDoc).find('notebook')[0];\n var nextEntryId = $notebook.getAttribute(\"nextEntryId\");\n var entryId = parseInt(nextEntryId,10)-1;\n $notebook.setAttribute(\"nextEntryId\", entryId); \n $($(xmlDoc).find('entry[id=\"' + entryId + '\"]')[0]).remove(); \n currentTabEntryId = previousTabEntryId;\n // save the xml string in cache textarea\n $('#txtCache-' + notebookFileName).text((new XMLSerializer()).serializeToString(xmlDoc));\n\tsaveNotebook(notebookFileName);\n }", "startCaching() {\n this[symbol('cacheMap')] = new WeakMap();\n }", "function copyToCache() {\n var to = cachedTree._root.children;\n var nodeToCopy = dbTree.findNode(selectedDBNode, dbTree._root);\n var clonedNode = nodeShallowCopy(nodeToCopy);\n if (cachedTree.findNode(selectedDBNode) || nodeToCopy.isElementDeleted)\n alert('This node already exists in cache or removed');\n else if (clonedNode.expectedParent) {\n var tmp = cachedTree.findNode(clonedNode.expectedParent);\n if (tmp) {\n tmp.children.push(clonedNode);\n clonedNode.parent = tmp;\n clonedNode.expectedParent = null;\n } else {\n to.push(clonedNode);\n clonedNode.parent = cachedTree._root;\n }\n }\n render(cachedTree, 'CachedTreeView');\n}", "function cacheDom() {}", "clear_caches() {\n for (let k in this.animation_set) {\n this.animation_set[k].node_cache = {};\n }\n }", "function CacheEl() {\n // $DivOrganization = $('#DivOrganization');\n\n }", "function CacheEl() {\n \n }", "function cacheDom() {\n DOM.$catClicker = $('#cat-clicker');\n DOM.$catImage = $(document.createElement('img'));\n DOM.$counter = $(document.createElement('p'));\n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tell message to actor by system.eventStream
tell(event, message) { this.eventStream.emit(event, message); }
[ "addEvent(e) {\n this.stream.addEvent(e);\n }", "dispatchMessageEvent(){\n const detail = this.getMessage();\n const event = new CustomEvent('message', {detail});\n this.dispatchEvent(event);\n }", "emitMessage (event) {\n this.emit('on-message', event)\n }", "_onStreamEvent(message) {\n let eventTarget;\n if (this._publication && message.id === this._publication.id) {\n eventTarget = this._publication;\n } else if (\n this._subscribedStream && message.id === this._subscribedStream.id) {\n eventTarget = this._subscription;\n }\n if (!eventTarget) {\n return;\n }\n let trackKind;\n if (message.data.field === 'audio.status') {\n trackKind = TrackKind.AUDIO;\n } else if (message.data.field === 'video.status') {\n trackKind = TrackKind.VIDEO;\n } else {\n Logger.warning('Invalid data field for stream update info.');\n }\n if (message.data.value === 'active') {\n eventTarget.dispatchEvent(new MuteEvent('unmute', {kind: trackKind}));\n } else if (message.data.value === 'inactive') {\n eventTarget.dispatchEvent(new MuteEvent('mute', {kind: trackKind}));\n } else {\n Logger.warning('Invalid data value for stream update info.');\n }\n }", "_onStreamEvent(message) {\n let eventTarget;\n\n if (this._publication && message.id === this._publication.id) {\n eventTarget = this._publication;\n } else if (this._subscribedStream && message.id === this._subscribedStream.id) {\n eventTarget = this._subscription;\n }\n\n if (!eventTarget) {\n return;\n }\n\n let trackKind;\n\n if (message.data.field === 'audio.status') {\n trackKind = TrackKind.AUDIO;\n } else if (message.data.field === 'video.status') {\n trackKind = TrackKind.VIDEO;\n } else {\n Logger.warning('Invalid data field for stream update info.');\n }\n\n if (message.data.value === 'active') {\n eventTarget.dispatchEvent(new MuteEvent('unmute', {\n kind: trackKind\n }));\n } else if (message.data.value === 'inactive') {\n eventTarget.dispatchEvent(new MuteEvent('mute', {\n kind: trackKind\n }));\n } else {\n Logger.warning('Invalid data value for stream update info.');\n }\n }", "function sendMIDIEvent(event){\n midiAccess.outputs.forEach(function(port){\n port.send(event);\n });\n }", "sendEvent(event) {\n this.connections.forEach((port) => {\n port.sendEvent(event);\n });\n }", "function mouseMessage (message) {\n socket.broadcast.emit('mouse', message);\n }", "function sendEvent(message){\n socket.emit('chat', {\n student: student.name,\n message: message\n });\n}", "message(actorId, msg) {\n this._trackedFeed(actorId).peers.forEach(peer => {\n this._messagePeer(peer, msg)\n })\n }", "onMessage(fromSprite,cmd,data) {\n }", "function fireIncoming(message, isSystemMessage, isMine) {\n Events.trigger('chat:incoming', message, isSystemMessage, isMine);\n}", "_eventListener(msg){\r\n\r\n // do Something when the subscriber receive the message from the Publisher\r\n // example:\r\n console.log(\"Message %s received from Publisher\", msg.content.toString());\r\n \r\n }", "_reactToEvent(event,path,stats,details) {\n this._ioEventCallback(event,path,stats,details);\n }", "send(event, data) {\n\t\tthis.connection.emit(event, data);\n\t}", "_messageProcessor(e) {\n const msg = e.data;\n const data = msg.data;\n\n switch (msg.type) {\n case MsgType.INIT:\n // Once it's initialised, we can send it the data it needs to process\n this.port.postMessage({\n type: MsgType.START,\n data: {\n ...this._initializeProcessor(this._buffer),\n cuts: this._cuts,\n stack: this._stack\n }\n });\n break;\n\n case MsgType.READY:\n this.dispatchEvent(new CustomEvent(\"init\", {\n detail: data\n }));\n return;\n\n case MsgType.STACK:\n this.dispatchEvent(new CustomEvent(\"stack\", {\n detail: data\n }));\n return;\n\n case MsgType.POS:\n this.time = data.time;\n this.dispatchEvent(new CustomEvent(\"pos\", {\n detail: data\n }));\n return;\n\n case MsgType.STOP:\n this.time = 0;\n this.dispatchEvent(new CustomEvent(\"stop\", {\n detail: null\n }));\n return;\n\n case MsgType.LENGTH:\n this.dispatchEvent(new CustomEvent(\"length\", {\n detail: data\n }));\n return;\n\n case MsgType.UPDATE:\n this.dispatchEvent(new CustomEvent(\"gainL\", {\n detail: data.gain[0] * 50\n }));\n this.dispatchEvent(new CustomEvent(\"gainR\", {\n detail: data.gain[1] * 50\n }));\n this.dispatchEvent(new CustomEvent(\"tempo\", {\n detail: 100 * (2 * data.tempo - 1) / 3\n }));\n this.dispatchEvent(new CustomEvent(\"pitch\", {\n detail: 100 * (2 * data.pitch - 1) / 3\n }));\n return;\n\n default:\n console.log(\"Unknown message type in node\", msg.type);\n return;\n }\n }", "emit(event, body) {\n let msg = new Message();\n msg.Namespace = this.nsConn.namespace;\n msg.Room = this.name;\n msg.Event = event;\n msg.Body = body;\n return this.nsConn.conn.write(msg);\n }", "broadcastEvent(msg, data) {\n this.socket.emit('bc', {msg: msg, data: data});\n this.gameEngine.emit(msg, Object.assign({\n playerId: this.playerId\n }, data));\n }", "sendReactorEvent(event) {\n const { label, data, context } = event\n const {\n level, step, reactor, result, info = '', debugLevel\n } = data\n\n const params = {\n op: 'react',\n level,\n label,\n step,\n reactor: reactor ? reactor.name : '',\n info,\n result,\n debugLevel\n }\n this.send(context, 'reactorEvent', params)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO emit events: entity>children:removeChild
removeChild(childId) { const idx = this.children.indexOf(childId); if (idx >= 0) { this.children.splice(idx, 1); } const child = this.getEntity(childId); if (child.hasComponent(Children)) { child.children.setParent(undefined); } }
[ "removeChild(node)\r\n {\r\n for(i = 0; i < children.length; i++){\r\n if(children[i] == node)\r\n {\r\n children.splice(i, 1)\r\n }\r\n }\r\n node.setParent\r\n }", "removeChild(child) {\n this.children = this.children.filter(el => { return el.tid != child.tid; });\n }", "removeChild(child) {\n var index = -1; \n for (var i = 0; i < this.children.length; i++) {\n if (this.children[i].id == child.id) index = i;\n }\n if (index != -1) {\n this.children.splice(index, 1);\n }\n child.parent = false;\n }", "removeChildren() {\n while (this._el.firstChild) this._el.removeChild(this._el.firstChild);\n }", "removeChildren() {\n while (this._el.firstChild)\n this._el.removeChild(this._el.firstChild);\n }", "removeAllChildren() {\n while (this.dom.firstChild) {\n this.dom.removeChild(this.dom.lastChild)\n }\n }", "remove_child(node) {\n delete this.children[node.get_token_string()];\n this.notify_fragment_dirty();\n }", "detachImmediateChildren() {\n this.creationTree.children.forEach( child =>{\n child.creationTree.parent = null;\n });\n }", "removeChilds( ) {\n if ( !this.dom ) {\n return;\n }\n\n let all = this.flattenChildren( );\n\n all.forEach( ( item ) => {\n let dom = item.clearDom( );\n if( dom ) {\n dom.remove( );\n }\n } );\n\n // remove all remaining elements (not DOMNodes)\n let node = this.dom;\n while ( node.lastChild ) {\n node.removeChild( node.lastChild );\n }\n }", "removeChild(child) {\n this.children.delete(this.getPlatformAwareName(child.name));\n }", "removeSelf() {\n this.DOM.wrap.remove();\n\n /*\n this.getChildren.forEach((child) => {\n child.offline();\n });*/\n }", "destroy() {\n // First destroys all children.\n for (let childId in this._children) {\n this._children[childId].destroy();\n }\n \n // Remove from parent, if have one.\n // TODO: Is there a better way w/o directly accessing properties?\n if (this._parent) {\n delete this._parent._children[this.id];\n }\n \n if (this.initialized) {\n this._entityManager.notifyDeletion(this);\n } \n }", "removeChild({\n child\n }) {\n for (const [variable, c] of this._children.entries())\n if (c === child)\n this._children.delete(variable);\n if (this._children.size < 1\n && this.parent !== undefined)\n this.parent.removeChild({ child: this });\n }", "RemoveFromDom() {\n if (this.Handle && this.ParentHandle) {\n this.ParentHandle.removeChild(this.Handle);\n this.OnParentChanged();\n }\n }", "removeChild(/** @type GameObject **/ child) {\n this.children = this.children.filter((c) => c !== child);\n }", "removeAllChildren () {\n\t\tlet kids = this.children;\n\t\twhile (kids.length) { this._removeChildAt(0); }\n\t}", "destroyChildren() {\n while(this.children.length)\n this.children.shift().destroy();\n }", "removeAllChildren() {\n for (let i = 0; i < this.children.length; ++i) {\n this.children[i].destroy();\n }\n this.children.length = 0;\n }", "function removeChildren(node) {\n node.children = [];\n node.childrenToShow = 0;\n drawTree();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to determine amount covered and log out for each patient.
function amountCovered(claim){ var paidOutPerClient = ''; var percent = percentageCovered(claim); //Amount paid out rounded to the nearest dollar amount. var amount = Math.round(claim.visitCost * (percent / 100)); //Add to the total money paid out. Logged at the end. totalPayedOut += amount; paidOutPerClient += ('Paid out $<mark>' + amount + '</mark> for ' + claim.patientName); //Add new ol item for each client's details $('table').append('<tr><td>' + paidOutPerClient + '</td></tr>'); console.log('Paid out $' + amount + ' for ' + claim.patientName); }
[ "function amountCovered(claim) {\n\tvar covered = Math.round(claim.visitCost * coveragePercent(claim));\n\tconsole.log(\"Paid out $\" + covered + \" for \" + claim.patientName);\n\ttotalPayedOut += covered;\n\treturn covered;\n}", "function percentCovered(patient) {\n\tvar covered = 0;\n\tvar visit = patient.visitType;\n\t// console.log(visit);\n\tswitch(visit){\n\t\tcase 'Optical':\n\t\tcovered = 0;\n\t\tbreak;\n\t\tcase 'Specialist':\n\t\tcovered = 0.10;\n\t\tbreak;\n\t\tcase 'Emergency':\n\t\tcovered = 1.00;\n\t\tbreak;\n\t\tcase 'Primary Care':\n\t\tcovered = 0.50;\n\t\tbreak;\n\t}\n\t// console.log(covered);\n\treturn covered;\n\n}", "function determineAmountCovered(object, percent){\n\tvar amountCovered = Math.round(percent * object.visitCost);\n\tvar patientName = object.patientName;\n\ttotalPayedOut += amountCovered;\n\tconsole.log(\"Paid out $\" + amountCovered + \" for \" + patientName + \".\");\n}", "function getAmountCovered(patientObject) {\n\nvar visitCost = Math.round(patientObject.visitCost * getPercent(patientObject));\n\nconsole.log(\"Paid out $\" + visitCost + \" for \" + patientObject.patientName);\n\nreturn visitCost;\n}", "function amountCovered(personObj) {\t\n\tpersonObj.amountPaidOut = Math.round(percentCovered(personObj.visitType) * personObj.visitCost);\n\treturn (\"Paid out $\" + personObj.amountPaidOut + \" for \" + personObj.patientName + \".\");\n\t\n}", "function amountCovered(i){\n\tvar totalCost = initialList[i].visitCost;\n\tvar percent = percentCovered(i);\n\tvar name = initialList[i].patientName;\n\tvar amount = 0;\n\t\tamount += Math.round(totalCost*percent);\n\n\t\tconsole.log(\"The total amount paid for claim\" + (i + 1) + \" is $\" + amount + \".\");\n\n\t\tconsole.log(\"Paid out $\" + amount + \" for \" + name + \".\");\n\t\treturn amount;\n\t}", "function ammountCovered(claim){\r\n\treturn ( claim.visitCost * percentCovered(claim));\r\n}", "function percentCovered(claim) {\n\tvar claimNumber = claim.visitType;\n\tvar whatsCovered = 0;\n\n\tswitch(claimNumber){\n case \"Optical\":\n whatsCovered = 0;\n break;\n case \"Specialist\":\n whatsCovered = .10;\n break;\n case \"Emergency\":\n whatsCovered = 1;\n break;\n case \"Primary Care\":\n whatsCovered = .5;\n break;\n }\n\treturn whatsCovered;\n}", "function percentCovered(claim) {\n\tvar percentageCovered = 0;\n\n\tswitch(claim.visitType) {\n\t\tcase \"Optical\":\n\t\tpercentageCovered = 0;\n\t\tbreak;\n\t\tcase \"Specialist\":\n\t\tpercentageCovered = .10;\n\t\tbreak;\n\t\tcase \"Emergency\":\n\t\tpercentageCovered = 1;\n\t\tbreak;\n\t\tcase \"Primary Care\":\n\t\tpercentageCovered = .5;\n\t\tbreak;\n\t\tdefault:\n\t\tpercentageCovered = 0; \n\t}\n\treturn percentageCovered;\n}", "function percentageCovered(claim) {\n if (claim.visitType === \"Optical\") {\n return 0;\n } else if (claim.visitType === \"Specialist\") {\n return 0.1;\n } else if (claim.visitType === \"Emergency\") {\n return 1;\n } else if (claim.visitType === \"Primary Care\") {\n return 0.5;\n }\n}", "function calcAmountCovered(claim) {\n\tvar claimCost = claim.visitCost;\n\tvar amountCovered = calcPercentCovered(claim) * claimCost / 100;\n\treturn amountCovered;\n}", "function computeAmountCovered(claim) {\n\tclaimAmountPaid = Math.round(percentCovered(claim) * claim.visitCost);\n\n\treturn claimAmountPaid;\n}", "function calculateCoverage() {\n var numTrue = 0;\n for (var i in codeCoverage) {\n if (codeCoverage[i]) {\n numTrue++;\n }\n }\n return numTrue * 100 / codeCoverage.length\n}", "sumIndividualCoverage(coverageRequested) {\n let sum = 0;\n if ((coverageRequested != null) && (coverageRequested.length > 0)) {\n coverageRequested.forEach(cr => {\n const idRequested = cr;\n const tempCoverageRequested = this.coverage.find(element => {\n return (element.id === idRequested);\n });\n if (tempCoverageRequested.valor) sum += tempCoverageRequested.valor;\n });\n }\n this.totalCoverage = sum;\n return sum;\n }", "function calcPercentCovered(claim) {\n\tvar claimType = claim.visitType;\n\tswitch(claimType) {\n\t\tcase 'Optical':\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase 'Specialist':\n\t\t\treturn 10;\n\t\t\tbreak;\n\t\tcase 'Emergency':\n\t\t\treturn 100;\n\t\t\tbreak;\n\t\tcase 'Primary Care':\n\t\t\treturn 50;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}", "function calculateCoverage() {\n var numTrue = 0;\n for (var i in codeCoverage) {\n if (codeCoverage[i]) {\n numTrue++;\n }\n }\n return numTrue * 100 / codeCoverage.length;\n}", "function countDrawer() {\n let total = 0;\n for (let i = 0; i < cid.length; i++) {\n denomQty.push(Math.round(cid[i][1] / moneyVal[i][1]));\n total += cid[i][1];\n }\n Math.round(total * 100) / 100;\n return total;\n }", "function determinePercentCovered(object){\n\tswitch(object.visitType){\n\t\tcase (\"Optical\"):\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase (\"Specialist\"):\n\t\t\treturn 0.10;\n\t\t\tbreak;\n\t\tcase (\"Emergency\"):\n\t\t\treturn 1;\n\t\t\tbreak;\n\t\tcase (\"Primary Care\"):\n\t\t\treturn 0.50;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log(\"Not covered.\");\n\t}\n}", "function percentCovered(claimNumber) {\n\t\tvar typeOfVisit = claimNumber.visitType;\n\t\tvar percent = 0;\n\t\tswitch(typeOfVisit) {\n\t\t\tcase \"Optical\":\n\t\t\tpercent += 0;\n\t\t\tbreak;\n\t\t\tcase \"Specialist\":\n\t\t\tpercent += 0.10;\n\t\t\tbreak;\n\t\t\tcase \"Emergency\":\n\t\t\tpercent += 1;\n\t\t\tbreak;\n\t\t\tcase \"Primary Care\":\n\t\t\tpercent += 0.50;\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\tpercent = 0;\n\t\t}\n\t\treturn percent;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ask for an image anchor. Provide a uid for the anchor that will be created. Supply the image in an ArrayBuffer, typedArray or ImageData width and height are in meters
createImageAnchor(uid, buffer, width, height, physicalWidthInMeters) { return new Promise((resolve, reject) => { if (!this._isInitialized){ reject(new Error('ARKit is not initialized')); return; } let b64 = base64.encode(buffer); window.webkit.messageHandlers.createImageAnchor.postMessage({ uid: uid, buffer: b64, imageWidth: width, imageHeight: height, physicalWidth: physicalWidthInMeters, callback: this._createPromiseCallback('createImageAnchor', resolve) }) }) }
[ "function createImageAnchor(image) {\n var imageAnchor = document.createElement(\"a\");\n imageAnchor.onmouseover = function anonymous() { mousedOnThumbnail(image.id); };\n imageAnchor.appendChild(image);\n return imageAnchor;\n }", "function getContactPhoto(uid,cb) {\n var contactImg = getContactImg(uid,function(contactImg) {\n // Checking whether the image was actually loaded or not\n if(contactImg !== null) {\n canvas.width = contactImg.width;\n canvas.height = contactImg.height;\n\n canvas.getContext('2d').drawImage(contactImg,0,0);\n\n cb(canvas.toDataURL());\n }\n else {\n cb('');\n }\n });\n }", "function display_image(ab){\n\t var arrayBufferView = new Uint8Array( ab );\n\t var blob = new Blob( [ arrayBufferView ], { type: \"image/png\" } );\n\t var urlCreator = window.URL || window.webkitURL;\n\t var blob_url = urlCreator.createObjectURL( blob );\n\t \n\t image.src=blob_url;\n\t}", "function calculateAnchorCoords (anchor) {\n var time = anchor[0];\n var value = anchor[1];\n\n var coords = [0, 0];\n coords[0] = gridLeft() + time * gridWidth();\n\n var top = gridTop();\n coords[1] = top + gridHeight() * (value - verticalTopValue) / (verticalBottomValue - verticalTopValue);\n\n return coords;\n }", "handleUpdateAnchor() {\n const position = this._cachePosition || this.rgbToPosition(this._rgb);\n\n const anchor = this.anchorElement;\n const offset = anchor.offsetWidth / 2;\n const x = position.x - offset + 5;\n const y = position.y - offset - 5;\n const xPercent = (x / this._canvas.width) * 100;\n const yPercent = (y / this._canvas.height) * 100;\n\n anchor.style.left = `${xPercent}%`;\n anchor.style.top = `${yPercent}%`;\n }", "getAnchor(uid){\n\t\t// XRAnchor? getAnchor(DOMString uid);\n\t\treturn this._session.reality._getAnchor(uid)\n\t}", "function link_to_avatar(size) {\n return async function (N, urlStr, params) {\n let user = await N.models.users.User.findOne()\n .where('hid').equals(params.user)\n .select('avatar_id')\n .lean(true);\n\n if (!user || !user.avatar_id) {\n return {\n apiPath: 'core.gridfs',\n params: {\n bucket: PH_OBJECTID + (size && size !== 'orig' ? '_' + size : '')\n }\n };\n }\n\n return {\n apiPath: 'core.gridfs',\n params: {\n bucket: user.avatar_id + (size && size !== 'orig' ? '_' + size : '')\n }\n };\n };\n }", "_anchorToInnerEdge() {\n\n const { height, width } = this.image,\n { left, top, right, bottom } = this.cropGuide\n\n // set initial zoom\n // if inner image has wider ratio than container\n if ((right - left) / (bottom - top) > this.outerWidth / this.outerHeight) {\n\n // set image width to outer width / inner width\n this.width = this.outerWidth / (right - left)\n this.scale = this.width / width\n this.height = height * this.scale\n }\n else {\n // set image height to outer width / inner height\n this.height = this.outerHeight / (bottom - top)\n this.scale = this.height / height\n this.width = width * this.scale\n }\n this.x = (this.outerWidth / 2) - (this.width * this.focus.x)\n this.y = (this.outerHeight / 2) - (this.height * this.focus.y)\n }", "function createImageNode(imageAsset) {\n return store.dispatch((0, _sceneGraph.addNode)({\n name: imageAsset.name || file.name,\n type: 'Image',\n parent: (0, _scene.find)(store, { name: 'Material Library' }),\n plugs: {\n Image: [['Image', { glBitmapFile: imageAsset.id, glOption: 1 }]],\n Properties: [['ImageProperties', {}]]\n }\n })).then(function (imageNodeId) {\n return {\n imageNodeId: imageNodeId,\n assetId: imageAsset.id,\n imageSize: {\n width: imageAsset.height,\n height: imageAsset.width,\n originalWidth: imageAsset.originalWidth,\n originalHeight: imageAsset.originalHeight\n },\n url: imageAsset.original\n };\n });\n }", "function createuploadanchor(meal) {\n\n // Create anchor object\n var uploadAnchor = $(dc('a'))\n .attr('id', 'uploadPictureAnchor')\n .attr('class', 'carousel_caption uploadPictureAnchor grid_3')\n .html('Upload New Picture');\n \n // Click function for the upload anchor\n uploadAnchor.click(function() {\n \n // Popup works from a hidden frame\n uploadmealpopup(meal.userid, meal.timestamp, function(err, pinfo) {\n \n // Throw any errors\n if(err) throw(err);\n\n if(pinfo) {\n \n // Add this to the carousel\n elm.addpicture(pinfo, false, false, function(added, ckfirst, ts) {\n \n if(added) {\n \n // Make key photo if this was the first\n if(ckfirst && setgriddisplay) {\n setgriddisplay(meal, pinfo);\n }\n \n // console.log('pushing ' + pinfo.timestamp + ' ts is ' + ts);\n \n // Push this picture onto the meal.picInfo array\n meal.picInfo.push(pinfo);\n \n // Update picture count\n if(setgridcount) \n setgridcount(meal);\n }\n \n // Set the focus back on the carousel\n elm.focus();\n });\n }\n });\n });\n\n return uploadAnchor;\n }", "findFloorAnchor(uid=null){\n\t\t// Promise<XRAnchorOffset?> findFloorAnchor();\n\t\treturn this._session.reality._findFloorAnchor(this._session.display, uid)\n\t}", "function drawAnchors(canvas, img) {\n\t\tvar con = canvas.getContext(\"2d\");\n\t\t\timg = img.jquery ? img : $(img);\n\t\tcon.fillStyle = \"hsla(0, 0%, 60%, 0.6)\";\n\t\tcon.fillRect(img.data(\"x\"), img.data(\"y\"), dim, dim);\n\t\tcon.fillRect(img.data(\"x\") + img.data('w') - dim, img.data(\"y\"), dim, dim);\n\t\tcon.fillRect(img.data(\"x\") + img.data('w') - dim, img.data(\"y\")\n\t\t\t \t+ img.data('h') - dim, dim, dim);\n\t\tcon.fillRect(img.data(\"x\"), img.data(\"y\") + img.data('h') - dim, dim, dim);\n\t\t\n\t}", "function addImage(src, type, doc, page, x, y, width, height, link, func) {\n let img = new Image();\n img.src = baseURL + src;\n img.addEventListener('load', function(event) {\n let url = getDataUrl(img, type);\n height = height? height: width * img.height / img.width;\n x = x < 0? -x - width: x;\n y = y < 0? -y - height: y;\n doc.setPage(page);\n doc.addImage(url, type, x, y, width, height);\n if (link)\n {\n let options = {url: link};\n doc.link(x, y, width, height, options);\n }\n });\n }", "function createImage(args) {\n\t// first lets remove the image since we are using it at as backgroundImage of a view;\n\tvar image = {\n\t\timage : args.image,\n\t\twidth : args.width,\n\t\theight : args.height,\n\t\tscaletofit : args.scaletofit\n\t}, hasImage = args.image;\n\t//var behaviour = args.scaletofit;\n\n\tdelete args.image;\n\tdelete args.id;\n\n\t// Lets stage the context\n\tvar imageView = Ti.UI.createImageView({\n\t\theight : Ti.UI.FILL,\n\t\twidth : Ti.UI.FILL,\n\t\tzIndex : 3,\n\t\tpreventDefaultImage : true\n\t});\n\n\tvar viewport = Ti.UI.createView(args);\n\n\t// Lets add the spinner\n\tif ( typeof args.noindicator === \"undefined\") {\n\n\t\tviewport.add(Ti.UI.createActivityIndicator({\n\t\t\tstyle : ACTIVITYCOLOR,\n\t\t\tmessage : '',\n\t\t\twidth : Ti.UI.SIZE,\n\t\t\theight : Ti.UI.SIZE,\n\t\t\tzIndex : 2\n\t\t}));\n\t\t// Lets add the indicator is there\n\t\timage.hasIndicator = true;\n\t}\n\n\tviewport._liquaniumImage = image;\n\tviewport.add(imageView);\n\n\tviewport.addEventListener('setimage', processImage);\n\tviewport.addEventListener('postlayout', processImage);\n\n\t// call the image utils if there is one set\n\treturn viewport;\n}", "function etalage_click_callback(image_anchor){\n\t\"use strict\";\n\tjQuery.fancybox({\n\t\thref: image_anchor\n\t});\n}", "get_image(img_tag){\n let fake_canvas = document.createElement('canvas'),\n fake_context = fake_canvas.getContext('2d');\n fake_canvas.width = img_tag.width;\n fake_canvas.height = img_tag.height;\n fake_context.drawImage(img_tag, 0, 0);\n return fake_context.getImageData(0, 0, img_tag.width, img_tag.height);\n }", "function saveAnchorPoint(image, mousePos) {\r\n\t\tif (image && image.slice) {\r\n\t\t\tmAnchorPoint = {\r\n\t\t\t\tx : image.slice.x + mousePos.x,\r\n\t\t\t\ty : image.slice.y + mousePos.y\r\n\t\t\t};\r\n\t\t}\r\n\t}", "function AkkoImage(){\r\n\t\r\n\tthis.image = new Image();\r\n\tthis.source;\r\n\t\r\n\tthis.set_source = function(image){\r\n\t\t\r\n\t\tthis.image = image;\r\n\t\t\r\n\t}\r\n\t\r\n}", "function etalage_click_callback(image_anchor, instance_id){\n\t$.fancybox({\n\t\thref: image_anchor\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the max separation between poly1 and poly2 using edge normals from poly1.
function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulT(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { // Get poly1 normal in frame2. var n = Rot.mul(xf.q, n1s[i]); var v1 = Transform.mul(xf, v1s[i]); // Find deepest point for normal i. var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } // used to keep last FindMaxSeparation call values FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; }
[ "function FindMaxSeparation(poly1, xf1, poly2, xf2) {\n var count1 = poly1.m_count;\n var count2 = poly2.m_count;\n var n1s = poly1.m_normals;\n var v1s = poly1.m_vertices;\n var v2s = poly2.m_vertices;\n var xf = Transform.mulTXf(xf2, xf1);\n\n var bestIndex = 0;\n var maxSeparation = -Infinity;\n for (var i = 0; i < count1; ++i) {\n // Get poly1 normal in frame2.\n var n = Rot.mulVec2(xf.q, n1s[i]);\n var v1 = Transform.mulVec2(xf, v1s[i]);\n\n // Find deepest point for normal i.\n var si = Infinity;\n for (var j = 0; j < count2; ++j) {\n var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);\n if (sij < si) {\n si = sij;\n }\n }\n\n if (si > maxSeparation) {\n maxSeparation = si;\n bestIndex = i;\n }\n }\n\n // used to keep last FindMaxSeparation call values\n FindMaxSeparation._maxSeparation = maxSeparation;\n FindMaxSeparation._bestIndex = bestIndex;\n}", "function FindMaxSeparation(poly1, xf1, poly2, xf2) {\n var count1 = poly1.m_count;\n var count2 = poly2.m_count;\n var n1s = poly1.m_normals;\n var v1s = poly1.m_vertices;\n var v2s = poly2.m_vertices;\n var xf = Transform.mulT(xf2, xf1);\n\n var bestIndex = 0;\n var maxSeparation = -Infinity;\n for (var i = 0; i < count1; ++i) {\n // Get poly1 normal in frame2.\n var n = Rot.mul(xf.q, n1s[i]);\n var v1 = Transform.mul(xf, v1s[i]);\n\n // Find deepest point for normal i.\n var si = Infinity;\n for (var j = 0; j < count2; ++j) {\n var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);\n if (sij < si) {\n si = sij;\n }\n }\n\n if (si > maxSeparation) {\n maxSeparation = si;\n bestIndex = i;\n }\n }\n\n // used to keep last FindMaxSeparation call values\n FindMaxSeparation._maxSeparation = maxSeparation;\n FindMaxSeparation._bestIndex = bestIndex;\n}", "testSeparatingAxisTheorem(other) {\n const poly1 = this;\n const poly2 = other;\n const axes = poly1.axes.concat(poly2.axes);\n let minOverlap = Number.MAX_VALUE;\n let minAxis = null;\n let minIndex = -1;\n for (let i = 0; i < axes.length; i++) {\n const proj1 = poly1.project(axes[i]);\n const proj2 = poly2.project(axes[i]);\n const overlap = proj1.getOverlap(proj2);\n if (overlap <= 0) {\n return null;\n }\n else {\n if (overlap < minOverlap) {\n minOverlap = overlap;\n minAxis = axes[i];\n minIndex = i;\n }\n }\n }\n // Sanity check\n if (minIndex === -1) {\n return null;\n }\n return minAxis.normalize().scale(minOverlap);\n }", "dist2_to_edge(p) {\n let min_d2 = Number.POSITIVE_INFINITY;\n for (let s of Array.from(this.segments)) {\n let v0 = this.vertices[s[0]];\n let v1 = this.vertices[s[1]];\n min_d2 = Math.min(min_d2, seg_pt_dist2(v0.x, v0.y, v1.x, v1.y, p.x, p.y));\n }\n return min_d2;\n }", "function maximumEdge(side1, side2) {\n console.log((side1 + side2) - 1);\n}", "function calcLongestSide(a,b)\n{\n\treturn Math.sqrt((a*a) + (b*b));\n}", "_computeInitialHull() {\n\n\t\tlet v0, v1, v2, v3;\n\n\t\tconst vertices = this._vertices;\n\t\tconst extremes = this._computeExtremes();\n\t\tconst min = extremes.min;\n\t\tconst max = extremes.max;\n\n\t\t// 1. Find the two points 'p0' and 'p1' with the greatest 1d separation\n\t\t// (max.x - min.x)\n\t\t// (max.y - min.y)\n\t\t// (max.z - min.z)\n\n\t\t// check x\n\n\t\tlet distance, maxDistance;\n\n\t\tmaxDistance = max.x.point.x - min.x.point.x;\n\n\t\tv0 = min.x;\n\t\tv1 = max.x;\n\n\t\t// check y\n\n\t\tdistance = max.y.point.y - min.y.point.y;\n\n\t\tif ( distance > maxDistance ) {\n\n\t\t\tv0 = min.y;\n\t\t\tv1 = max.y;\n\n\t\t\tmaxDistance = distance;\n\n\t\t}\n\n\t\t// check z\n\n\t\tdistance = max.z.point.z - min.z.point.z;\n\n\t\tif ( distance > maxDistance ) {\n\n\t\t\tv0 = min.z;\n\t\t\tv1 = max.z;\n\n\t\t}\n\n\t\t// 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1'\n\n\t\tmaxDistance = - Infinity;\n\t\tline.set( v0.point, v1.point );\n\n\t\tfor ( let i = 0, l = vertices.length; i < l; i ++ ) {\n\n\t\t\tconst vertex = vertices[ i ];\n\n\t\t\tif ( vertex !== v0 && vertex !== v1 ) {\n\n\t\t\t\tline.closestPointToPoint( vertex.point, true, closestPoint );\n\n\t\t\t\tdistance = closestPoint.squaredDistanceTo( vertex.point );\n\n\t\t\t\tif ( distance > maxDistance ) {\n\n\t\t\t\t\tmaxDistance = distance;\n\t\t\t\t\tv2 = vertex;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2'\n\n\t\tmaxDistance = - Infinity;\n\t\tplane$1.fromCoplanarPoints( v0.point, v1.point, v2.point );\n\n\t\tfor ( let i = 0, l = vertices.length; i < l; i ++ ) {\n\n\t\t\tconst vertex = vertices[ i ];\n\n\t\t\tif ( vertex !== v0 && vertex !== v1 && vertex !== v2 ) {\n\n\t\t\t\tdistance = Math.abs( plane$1.distanceToPoint( vertex.point ) );\n\n\t\t\t\tif ( distance > maxDistance ) {\n\n\t\t\t\t\tmaxDistance = distance;\n\t\t\t\t\tv3 = vertex;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// handle case where all points lie in one plane\n\n\t\tif ( plane$1.distanceToPoint( v3.point ) === 0 ) {\n\n\t\t\tthrow 'ERROR: YUKA.ConvexHull: All extreme points lie in a single plane. Unable to compute convex hull.';\n\n\t\t}\n\n\t\t// build initial tetrahedron\n\n\t\tconst faces = this.faces;\n\n\t\tif ( plane$1.distanceToPoint( v3.point ) < 0 ) {\n\n\t\t\t// the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron\n\n\t\t\tfaces.push(\n\t\t\t\tnew Face( v0.point, v1.point, v2.point ),\n\t\t\t\tnew Face( v3.point, v1.point, v0.point ),\n\t\t\t\tnew Face( v3.point, v2.point, v1.point ),\n\t\t\t\tnew Face( v3.point, v0.point, v2.point )\n\t\t\t);\n\n\t\t\t// set the twin edge\n\n\t\t\t// join face[ i ] i > 0, with the first face\n\n\t\t\tfaces[ 1 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 1 ) );\n\t\t\tfaces[ 2 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 2 ) );\n\t\t\tfaces[ 3 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 0 ) );\n\n\t\t\t// join face[ i ] with face[ i + 1 ], 1 <= i <= 3\n\n\t\t\tfaces[ 1 ].getEdge( 1 ).linkOpponent( faces[ 2 ].getEdge( 0 ) );\n\t\t\tfaces[ 2 ].getEdge( 1 ).linkOpponent( faces[ 3 ].getEdge( 0 ) );\n\t\t\tfaces[ 3 ].getEdge( 1 ).linkOpponent( faces[ 1 ].getEdge( 0 ) );\n\n\t\t} else {\n\n\t\t\t// the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron\n\n\t\t\tfaces.push(\n\t\t\t\tnew Face( v0.point, v2.point, v1.point ),\n\t\t\t\tnew Face( v3.point, v0.point, v1.point ),\n\t\t\t\tnew Face( v3.point, v1.point, v2.point ),\n\t\t\t\tnew Face( v3.point, v2.point, v0.point )\n\t\t\t);\n\n\t\t\t// set the twin edge\n\n\t\t\t// join face[ i ] i > 0, with the first face\n\n\t\t\tfaces[ 1 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 0 ) );\n\t\t\tfaces[ 2 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 2 ) );\n\t\t\tfaces[ 3 ].getEdge( 2 ).linkOpponent( faces[ 0 ].getEdge( 1 ) );\n\n\t\t\t// join face[ i ] with face[ i + 1 ], 1 <= i <= 3\n\n\t\t\tfaces[ 1 ].getEdge( 0 ).linkOpponent( faces[ 2 ].getEdge( 1 ) );\n\t\t\tfaces[ 2 ].getEdge( 0 ).linkOpponent( faces[ 3 ].getEdge( 1 ) );\n\t\t\tfaces[ 3 ].getEdge( 0 ).linkOpponent( faces[ 1 ].getEdge( 1 ) );\n\n\t\t}\n\n\t\t// initial assignment of vertices to the faces of the tetrahedron\n\n\t\tfor ( let i = 0, l = vertices.length; i < l; i ++ ) {\n\n\t\t\tconst vertex = vertices[ i ];\n\n\t\t\tif ( vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3 ) {\n\n\t\t\t\tmaxDistance = this._tolerance;\n\t\t\t\tlet maxFace = null;\n\n\t\t\t\tfor ( let j = 0; j < 4; j ++ ) {\n\n\t\t\t\t\tdistance = faces[ j ].distanceToPoint( vertex.point );\n\n\t\t\t\t\tif ( distance > maxDistance ) {\n\n\t\t\t\t\t\tmaxDistance = distance;\n\t\t\t\t\t\tmaxFace = faces[ j ];\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( maxFace !== null ) {\n\n\t\t\t\t\tthis._addVertexToFace( vertex, maxFace );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}", "dist2_to_edge(p) {\n let n = this.points.length;\n if (n < 2) { return 0; }\n let min_d2 = Number.POSITIVE_INFINITY;\n for (let i = 0; i < this.points.length; i++) {\n let v0 = this.points[i];\n let v1 = this.points[(i + 1) % this.points.length];\n min_d2 = Math.min(min_d2, seg_pt_dist2(v0.x, v0.y, v1.x, v1.y, p.x, p.y));\n }\n return min_d2;\n }", "function findMostDistantToLine(points, a, b) {\n var maxDistance = -Infinity;\n var mostDistant;\n for (var i = 0; i < points.length; ++i) {\n var d = points[i].distanceToLine(a,b);\n if (d > maxDistance) {\n maxDistance = d;\n mostDistant = points[i];\n }\n }\n return mostDistant;\n}", "perpVectorBetweenLines(other) {\n const otherDir = other.direction();\n const unitDot = this.direction().dot(otherDir);\n if (!withinTol(Math.abs(unitDot), 1, ADJOIN_DOT_PRODUCT_TOL)) {\n return new XY(0, 0);\n }\n // Basically parallel. Now measure the perpendicular distance between\n // this.a->other.a and other.a->other.b.\n const d = other.a.minus(this.a);\n return d.minus(d.project(otherDir));\n }", "function getSlope(p1, p2) {\n if (p1[0] === p2[0] && p1[1] === p2[1]) return null;\n \n return (p1[1] - p2[1]) / (p1[0] - p2[0]);\n}", "filterVerticesBetweenEdges(sides, lEdges, geometry) {\r\n \r\n // sort vertices along Z axis on each line\r\n // and remove doubles\r\n sides[0].sort(function(a, b) { return geometry.vertices[a].z - geometry.vertices[b].z;});\r\n sides[1].sort(function(a, b) { return geometry.vertices[a].z - geometry.vertices[b].z;});\r\n\r\n sides[0] = sides[0].filter(function(item, pos, ary) { return !pos || item != ary[pos - 1];});\r\n sides[1] = sides[1].filter(function(item, pos, ary) { return !pos || item != ary[pos - 1];});\r\n \r\n // get vertices in the similar edges\r\n var eVerts = [].concat.apply([], lEdges);\r\n\r\n // remove top and bottom vertices not involved in an edge\r\n while(eVerts.indexOf(sides[0][0]) == -1) { sides[0].shift(); }\r\n while(eVerts.indexOf(sides[1][0]) == -1) { sides[1].shift(); }\r\n \r\n while(eVerts.indexOf(sides[0][sides[0].length - 1]) == -1) { sides[0].pop(); }\r\n while(eVerts.indexOf(sides[1][sides[1].length - 1]) == -1) { sides[1].pop(); }\r\n\r\n return sides;\r\n }", "function getNormalsOfPoly(poly)\n{\n var normals = new Array();\n for(var i = 0; i < poly.length; i+=2)\n {\n normals[normals.length] = getLineNormal([poly[i], poly[i+1], poly[(i+2)%poly.length], poly[(i+3)%poly.length]]);\n }\n return normals;\n}", "function bdccGeoDistanceToPolyMtrs(poly, point) {\n\tvar d = 999999999;\n\tvar i;\n\tvar p = new bdccGeo(point.lat(), point.lng());\n\tvar path = poly.getPath();\n\tfor (i = 0; i < path.getLength() - 1; i++) {\n\t\tvar p1 = path.getAt(i);\n\t\tvar l1 = new bdccGeo(p1.lat(), p1.lng());\n\t\tvar p2 = path.getAt(i + 1);\n\t\tvar l2 = new bdccGeo(p2.lat(), p2.lng());\n\t\tvar dp = p.distanceToLineSegMtrs(l1, l2);\n\t\tif (dp < d) d = dp;\n\t}\n\treturn d;\n}", "function computeMaxError(pts, first, last, curve, u, splitPoint) {\n var maxDist = 0;\n\n for (var i = first + 1; i < last; i++) {\n var P = bezier(3, curve, u[i-first]);\n var v = P.subtract(pts[i]);\n var dist = v.getLengthSquared();\n if (dist >= maxDist) {\n maxDist = dist;\n splitPoint.i = i;\n }\n }\n\n return maxDist;\n }", "function classify(p1, p2) {\n// Find the unshared vertex in each triangle (u1 & u2).\nconst s1 = new Set(p1.vertices.map(v => v.pos));\nconst s2 = new Set(p2.vertices.map(v => v.pos));\nconst u1 = [...s1].filter(v => !s2.has(v))[0];\nconst u2 = [...s2].filter(v => !s1.has(v))[0];\nconst distBetweenUnsharedVertices = u1.distanceTo(u2);\nconst distBetweenHeadsOfPlaneNormalsFromUnsharedVertices =\nu1.plus(p1.plane.normal).distanceTo(u2.plus(p2.plane.normal));\nif (distBetweenUnsharedVertices < distBetweenHeadsOfPlaneNormalsFromUnsharedVertices) {\n return \"M\";\n}\nreturn \"V\";\n}", "lineDistance(other) {\n return this.perpVectorBetweenLines(other).l2norm();\n }", "function getMaxDiff(a1, a2){\n\tvar maxdif = 0;\n\tfor (var i = 0; i < a1.length; i++) {\n\t\tvar dif = a1[i] - a2[i];\n\t\tif (dif > maxdif) maxdif = dif;\n\t}\n\treturn maxdif;\n}", "function get_maxdiff(vertarr) {\n var xmin = 0;\n var ymin = 0;\n var zmin = 0;\n var xmax = 0;\n var ymax = 0;\n var zmax = 0;\n\n for (var vert = 1; vert < vertarr.length - 1; vert++) {\n //console.log(\"vert[0] is\", vertarr[vert][0]);\n if (vertarr[vert][0] < xmin) xmin = vertarr[vert][0];\n if (vertarr[vert][0] > xmax) xmax = vertarr[vert][0];\n if (vertarr[vert][1] < ymin) ymin = vertarr[vert][1];\n if (vertarr[vert][1] > ymax) ymax = vertarr[vert][1];\n if (vertarr[vert][2] < zmin) zmin = vertarr[vert][2];\n if (vertarr[vert][2] > zmax) zmax = vertarr[vert][2];\n };\n\n var diffx = xmax - xmin;\n var diffy = ymax - ymin;\n var diffz = zmax - zmin;\n\n var maxdiff = Math.max(diffx, diffy, diffz);\n return maxdiff;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reset default inputs (name, qty, comments)
function resetInputs() { $('#qty').val("1"); $("#name").val(""); $("#comments").val(""); }
[ "function resetFields () {\n this.input.value = '';\n this.output.value = '';\n }", "function resetFields() {\n document.getElementById('add-name').value = '';\n document.getElementById('add-rating').value = '';\n document.getElementById('add-comment').value = '';\n}", "_clearForm() {\n // Clears input fields\n itemNameInput.value =\n itemDueDateInput.value =\n itemTimeDueInput.value =\n itemDescriptionInput.value =\n \"\";\n // Makes sure default pri always \"no priority\"\n itemPriorityInput.value = \"no_pri\";\n }", "function resetFields() {\n\t\tlabelInput.value = '';\n\t\turlInput.value = '';\n\t\tisEditing = false;\n\t\teditIndex = -1;\n\t\taddButton.textContent = 'Add';\n\t}", "function resetInputFields() {\n $nameField.val('');\n $emailField.val('');\n $subjectField.val('');\n $messageField.val('');\n}", "function resetInputs() {\n operation = '';\n $('#firstNumberInput').val('');\n $('#secondNumberInput').val('');\n\n // console logs used for testing, debugging, and process tracking\n if (verbose) {\n console.log('*** in resetInputs() ***');\n console.log('\\toperation:', operation);\n }\n}", "static clear_input(){\n title.value='';\n author.value='';\n isbn.value='';\n }", "function resetInput(){\n $(\"#quantity-counter\").text(1);\n $(\"#item-name\").val('');\n}", "function resetInventoryForm(){\n\t\t\t FirstNameField.setValue(''),\n\t\t\t\tLastNameField.setValue(''),\n\t\t\t\tDeptField.setValue(''),\n\t\t\t\tBuildingField.setValue(''),\n\t\t\t\tRoomField.setValue(''),\t \n\t\t\t\tTagField.setValue(''),\n\t\t\t\tPurchaseDateField.setValue(''),\n\t\t\t\tPurchaseByField.setValue(''),\n\t\t\t\tMakeField.setValue(''),\n\t\t\t\tModelField.setValue(''),\n\t\t\t\tSerialField.setValue(''),\n\t\t\t\tLocationField.setValue(''),\n\t\t\t\tOperatingSystemField.setValue(''),\n\t\t\t\tMacAddressField.getValue(''),\n\t\t\t\tWirelessMacAddressField.setValue(''),\n\t\t\t\tPrinterField.setValue(''),\n\t\t\t\tNotesField.setValue('')\n\t\t }", "function resetData(){\n editAmount.value=null\n editNotes.value=null\n}", "function resetInputFields() {\n $( \".title\" ).val('');\n $( \".body\" ).val('');\n}", "function resetFields() {\n\t\t\t$wizardFields.find('.row :input').each(function() {\n\t\t\t\tif($(this).is(\":checkbox\")) { this.checked = true; } else { this.value = ''; }\n\t\t\t});\n\n\t\t\t$wizardFields.find('p.row').hide();\n\t\t\t$multipleValues.find(':input').remove();\n\t\t\t$wizardFields.show();\n\n\t\t\tfieldType = 'text';\n\t\t\tfieldName = '';\n\t\t\t$valueLabel.html( strings.initialValue + \" <small>\" + strings.optional + \"</small>\" );\n\t\t}", "resetInputsFromFormNewsletter(){\n $('#name')[0].value = '';\n $('#selectMonth')[0].value = '';\n $('#selectYear')[0].value = '';\n }", "function resetInputs(){\n $('#firstName').val(``);\n $('#lastName').val(``);\n $('#idNumber').val(``);\n $('#jobTitle').val(``);\n $('#annualSalary').val(``);\n $('#monthlySalary').val(``);\n\n}", "function limpiarInputs(){\n\t\tdocument.getElementById(\"codigoEst\").value = \"\";\n\t\tdocument.getElementById(\"nombreEst\").value = \"\";\n\t\tdocument.getElementById(\"nota1Est\").value = \"\";\n\t\tdocument.getElementById(\"nota2Est\").value = \"\";\n\t}", "clearGroupInputs() {\n\n this.inputGroupName = '';\n this.inputGroupTax = 0;\n }", "clearFields(title,author,isbn){\n title.value= author.value = isbn.value = '';\n }", "static clearFields() {\n document.querySelector('#title').value = '';\n document.querySelector('#author').value = '';\n document.querySelector('#price').value = '';\n document.querySelector('#isbn').value = '';\n }", "clearFields() {\n document.getElementById('title').value = '';\n document.getElementById('author').value = '';\n document.getElementById('isbn').value = '';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init the various properties of the conflictedTaxaObj as needed.
function initConflictedGenus() { if ( conflictedTaxaObj["conflictedGenus"] === undefined ) { conflictedTaxaObj["conflictedGenus"] = {}; } if ( conflictedTaxaObj.conflictedGenus[tP.role] === undefined ) { conflictedTaxaObj.conflictedGenus[tP.role] = {}; } if ( conflictedTaxaObj.conflictedGenus[tP.role][taxonName] === undefined ) { conflictedTaxaObj.conflictedGenus[tP.role][taxonName] = []; } }
[ "function initTopTaxa() {\n taxaNameMap[1] = 'Animalia';\n taxaNameMap[2] = 'Chiroptera';\n taxaNameMap[3] = 'Plantae';\n taxaNameMap[4] = 'Arthropoda';\n batTaxaRefObj = {\n Animalia: {\n kingdom: \"Animalia\",\n parent: null,\n name: \"Animalia\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++\n },\n Chiroptera: {\n kingdom: \"Animalia\",\n parent: 1, // 1 = animalia\n name: \"Chiroptera\",\n level: 4,\n tempId: curTempId++\n },\n };\n objTaxaRefObj = {\n Animalia: { //Repeated here because it will be collapsed in the merge process and animalia waas added as an ancestor antrhopoda very late in the writting of this code and restructuring didn't seen worth the effort and time.\n kingdom: \"Animalia\",\n parent: null,\n name: \"Animalia\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: 1\n },\n Plantae: {\n kingdom: \"Plantae\",\n parent: null,\n name: \"Plantae\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++\n },\n Arthropoda: { // concat names of taxa, and all parent levels present, are used as keys to later link taxa.\n kingdom: \"Animalia\",\n parent: 1,\n name: \"Arthropoda\",\n level: 2,\n tempId: curTempId++\n },\n };\n }", "function buildTaxonObjs(recrdsObj) {\n var batTaxaRefObj, objTaxaRefObj; // Taxon objects for each role, keyed by taxonName\n var taxaNameMap = {}; // Used as a quick link between id and the taxonName\n var conflictedTaxaObj = {}; // Taxa records with conflicted field data [ERROR TYPE]\n var nullKingdoms = {}; // Taxa records with null Kingdoms, i.e. taxon with no parent [ERROR TYPE]\n var nullTaxa = {}; // Interaction records with no taxa in one, or both roles. [ERROR TYPE]\n var mergeRefObj = {}; // Reference object for merging back into interaction records\n var taxonRecrdObjsAry = entityObj.taxaRcrdObjsAry; // Extracted taxaObjs, one per record. \n var recrdsObj = entityObj.curRcrds;\n var curTempId = 1;\n var batFields = JSON.parse(JSON.stringify(entityParams.taxon.subjCols));\n var objFields = JSON.parse(JSON.stringify(entityParams.taxon.objCols));\n batFields.reverse(); //species, genus, family, order\n objFields.reverse(); //all levels, species through kingdom // console.log(\"objFields = %O\", objFields);\n\n initTopTaxa(); \n taxonRecrdObjsAry.forEach(function(recrd) { buildTaxaTree(recrd); });\n\n if (!isEmpty(nullKingdoms)) { rprtNullKingdoms() } // console.log(\"mergeRefObj = %O, batTaxaRefObj = %O, objTaxaRefObj = %O\", mergeRefObj, batTaxaRefObj, objTaxaRefObj)\n if (!isEmpty(conflictedTaxaObj)) { rprtConflictedTaxon() } // console.log(\"conflictedTaxaObj = %O\", conflictedTaxaObj); \n if (!isEmpty(nullTaxa)) { rprtNullTaxa() } // console.log(\"conflictedTaxaObj = %O\", conflictedTaxaObj); \n \n \t[batTaxaRefObj, objTaxaRefObj].forEach(mergeRefsWithRcrds); // console.log(\"taxonRecrdObjsAry = %O\", taxonRecrdObjsAry)\n \n entityObj.taxon.taxonObjs = taxaNameMap;\n entityObj.taxon.mergeRefs = mergeRefObj;\n entityObj.taxon.nameMap = taxaNameMap;\n\n function buildTaxaTree(recrd) {\n var lvlAry = [7, 6, 5, 4, 3, 2, 1]; // Used to reference back to the original hierarchy structure of the levels (i.e. Lvl Kingdom = 1)\n var errors = false; // Used as an escape flag if errors are found that invalidate the record.\n\n buildSubjTaxa(recrd);\n buildObjTaxa(recrd); \n\n function buildSubjTaxa(recrd) { // console.log(\"subject recrd = %O\", recrd)\n extractUnqTaxa(recrd, batTaxaRefObj, batFields, \"subject\");\n }\n function buildObjTaxa(recrd) { // console.log(\"object recrd = %O\", recrd)\n extractUnqTaxa(recrd, objTaxaRefObj, objFields, \"object\");\n }\n function extractUnqTaxa(recrd, taxaObjs, fieldAry, role) { // console.log(\"recrd inside extractUnqTaxa = %O\", recrd)\n var taxaParams = { // Referenced as tP throughout.\n recrd: recrd,\n taxaObjs: taxaObjs,\n fieldAry: fieldAry,\n role: role,\n genusParent: false // If species is present, the first word of the species taxonym is added here for later comparison. \n };\n // Loop through the taxa fields from species up. When a value is found, begin to build the taxon object.\n var taxaFound = fieldAry.some(function(field, idx) {\n if (recrd[field] !== null) {\n taxaParams.field = field;\n taxaParams.idx = idx;\n foundMostSpecificLevel(taxaParams);\n return true; }\n });\n if (!taxaFound) { addNullTaxa(recrd, role); }\n }\n function foundMostSpecificLevel(tP) { \n var taxonName = tP.recrd[tP.field]; // console.log(\"foundMostSpecificLevel for %s. tP = %O\", taxonName, tP); // tP = taxaParams\n if (tP.field === \"objSpecies\" || tP.field === \"subjSpecies\") { getGenusStr(tP.recrd[tP.field], tP) }\n addTaxonData(taxonName, tP.field, tP.idx, tP); \n addMergeObjRef(taxonName, tP);\n \n }\n function addMergeObjRef(taxonName, tP) {\n if (mergeRefObj[tP.recrd.tempId] === undefined) { mergeRefObj[tP.recrd.tempId] = {}; }\n mergeRefObj[tP.recrd.tempId][tP.role] = errors ? false : tP.taxaObjs[taxonName].tempId; \n }\n // The first word of the species taxonym is added to tP for later comparison. \n function getGenusStr(genusSpeciesStr, tP) { \n var nameAry = genusSpeciesStr.split(\" \");\n tP.genusParent = nameAry[0];\n }\n /**\n * If taxonName already exists as a taxaObj, check for new data. Otherwise, build the taxon obj.\n * Add taxon's new taxaObj id to the reference object for later merging with interactions.\n */\n function addTaxonData(taxonName, field, idx, tP) { //console.log(\"addTaxonData called. taxonName = \", taxonName);\n if (taxonName in tP.taxaObjs) { fillInAnyNewData(taxonName, field, idx, tP);\n } else { buildTaxonObj(taxonName, field, idx, tP); }\n } /* End addTaxonData */\n function addNullTaxa(rcrd, role) {\n if ( nullTaxa[role] === undefined ) { nullTaxa[role] = []; }\n nullTaxa[role].push(rcrd.tempId);\n }\n /*-------------- Taxon Data Fill and Conflict Methods ----------------*/\n /**\n * First checks if this is already the highest level for this role in the record. (subject = Order; object = Kingdom)\n * Gets the existing parent for this taxonName and gets the parent present in this record;\n * if they are different @checkIfTreesMerge is called to determine whether this is due to missing or conflicting data.\n */\n function fillInAnyNewData(taxonName, field, idx, tP) { // console.log(\"fillInAnyNewData aclled for \", taxonName); \n if ( tP.fieldAry.indexOf(field) === tP.fieldAry.length - 1 ) { return; } //console.log(\"last field in set\"); \n if (tP.fieldAry[0] === field) { fillNullGenus() } //If species...\n var existingParentId = tP.taxaObjs[taxonName].parent;\n var newParentId = linkparentTaxonId(idx, tP);\n\n if ( newParentId !== existingParentId ) {\n checkIfTreesMerge(taxonName, newParentId, existingParentId, tP); \n }\n // If Genus is null, set genus as the first word of the species string.\n function fillNullGenus() {\n if (tP.recrd[tP.fieldAry[1]] === null) { \n tP.recrd[tP.fieldAry[1]] = tP.genusParent; }\n }\n } /* End fillInAnyNewData */\n /**\n * If the taxon has a different direct parent in this record than in one previously processed, \n * check and see if the parent tree merges at a later point @doTreesMerge and @confirmDirectRelationship. If they do, \n * add this new taxon as the most direct parent. If the records have conflicting taxonNames \n * at the same level they are checked for validity and conflicts @checkForSharedTaxonymOrConflicts.\n */\n function checkIfTreesMerge(taxonName, newParentId, existingParentId, tP) { // console.log(\"checkIfTreesMerge called. taxaNameMap = %O, newParentId = %s\", taxaNameMap, newParentId);\n // Grab the existing taxaObjs' parents' levels.\n var newLvl = tP.taxaObjs[taxaNameMap[newParentId]].level; \n var existingLvl = tP.taxaObjs[taxaNameMap[existingParentId]].level; // console.log(\"newLvl = %s, existingLvl = \", newLvl, existingLvl);\n if (newLvl !== existingLvl) {\n doTreesMerge(newLvl, existingLvl, newParentId, existingParentId, tP);\n } else { checkForSharedTaxonymOrConflicts(taxonName, newLvl, newParentId, existingParentId, tP); }\n } /* End checkIfTreesMerge */\n /**\n * If the taxon has a more specific direct parent in this record than in one previously processed, \n * check and see if the parent tree merges at a later point @doTreesMerge. If they do, \n * add this new taxon as the most direct parent.\n */\n function doTreesMerge(newLvl, existingLvl, newParentId, existingParentId, tP) { //console.log(\"doTreesMerge called. newLvl = %s, existingLvl = %s, newParent = %s, existingParent = %s\", newLvl, existingLvl, taxaNameMap[newParentId], taxaNameMap[existingParentId])\n if (newLvl > existingLvl) { // more specific taxon\n if (treesMergeAtHigherLevel(tP.taxaObjs[taxaNameMap[newParentId]], existingParentId, tP)) {\n tP.recrd.parent = newParentId; \t\t\t\t\t\t// console.log(\"trees merge\");\n }\n } else { confirmDirectRelationship(tP.taxaObjs[taxaNameMap[newParentId]], newParentId); }\n /**\n * If the taxon has a less specific direct parent in this record than in one previously processed, \n * check to ensure the existing parent is a child of the parent taxon in this record.\n */\n function confirmDirectRelationship(existingTaxonObj, newParentId) { \n if (!isChild(existingTaxonObj)) { // No case yet. TODO: add to Complex Errors\n console.log(\"trees don't merge. newParent =%s, existing =%s, rcrd = %O, existingParent = %O\", taxaNameMap[newParentId], taxaNameMap[existingParentId], tP.recrd, tP.taxaObjs[taxaNameMap[existingParentId]].name); \n }\n\n function isChild(existingParnt) { // console.log(\"existingParnt - %s, existingParntLvl - %s, tP.taxaObjs = %O\", existingParnt.name, existingParnt.level, tP.taxaObjs)\n if ( existingParnt.level === newLvl ) { //console.log(\"levels equal. existingId = %s, newParentId = %s\", existingParnt.tempId, newParentId)\n if ( existingParnt.tempId === newParentId ) { return true; \n } else { return false; }\n }\n if ( existingParnt.parent === newParentId ) { return true;\n } else { return isChild(existingParnt.parent); }\n }\n }\n } /* End doTreesMerge */\n /**\n * If @taxonObjWasCreatedWithSharedTaxonym return false, check if @speciesHasCorrectGenusParent and,\n * if so, @addUniqueTaxaWithSharedTaxonym. If the species and genus names conflict @hasParentConflicts \n * is called with the existing taxonObj unaffected. If there is another level with conflicting data \n * between the two records, both records are quarantined in @hasParentConflicts.\n */\n function checkForSharedTaxonymOrConflicts(taxonName, newLvl, newParentId, existingParentId, tP) { //if (taxonName === 'Arthropoda') {console.log(\"checkForSharedTaxonymOrConflicts called. arguments = %O\", arguments);}\n if ( taxonObjWasCreatedWithSharedTaxonym(taxonName, newParentId, tP) ) { return; }\n if ( speciesHasCorrectGenusParent(existingParentId, tP, newLvl) ) { addUniqueTaxaWithSharedTaxonym(taxonName, tP); \n } else if ( speciesHasCorrectGenusParent(existingParentId, tP, newLvl) === false ) { \n hasParentConflicts(taxonName, null, newLvl, tP); \n } else { hasParentConflicts(taxonName, tP.taxaObjs[taxonName], newLvl, tP); }\n }\n /**\n * Checks if current taxon has been previously created under a taxonName with an appended \n * number by checking the parent of any matching taxonName found. If the parent matches, \n * this taxon has already been created with the proper parent and there is nothing more to do.\n */\n function taxonObjWasCreatedWithSharedTaxonym (taxonName, newParentId, tP) { // console.log(\"taxonObjWasCreatedWithSharedTaxonym called for \", taxonName)\n var taxonym1 = taxonName + '-1';\n return hasBeenCreated(taxonym1); \n /** Returns true if a taxon record is found with passed taxonym and the parents match. */\n function hasBeenCreated(taxonym, cnt) {\n if (taxonym in tP.taxaObjs) {\n if ( tP.taxaObjs[taxonym].parent === newParentId ) { return true; \n } else {\n var nextTaxonym = taxonym + '-' + ++cnt;\n return hasBeenCreated(nextTaxonym, cnt); }\n } else { return false; }\n }\n } /* End taxonObjWasCreatedWithSharedTaxonym */\n /**\n * If the conflicted level is Genus, check whether the genus portion of the species name string \n * from this record is the same as it's genus field. \n * If so, this taxonName is a unique taxon that shares a species name with another taxon. \n */\n function speciesHasCorrectGenusParent(existingParentId, tP, lvl) { // console.log(\"speciesHasCorrectGenusParent called.\");\n if (lvl === 6) {\n var parentName = tP.recrd[tP.fieldAry[lvlAry[lvl]]]; \t\t// console.log(\"parentName = %s, genusParent = %s\", parentName, tP.genusParent)\n return tP.genusParent === parentName; \n } else { return null; }\n }\n /**\n * This taxonName is a unique taxon that shares a species name with another taxon.\n * @appendNumToTaxonym and @addTaxonData. \n */\n function addUniqueTaxaWithSharedTaxonym(taxonName, tP) { console.log(\"addUniqueTaxaWithSharedTaxonym called for %s. %O\", taxonName, tP)\n var taxonym = appendNumToTaxonym(taxonName, tP); \t\t\t\t//console.log(\"addUniqueTaxaWithSharedTaxonym new taxonym = \", taxonym)\n addTaxonData(taxonym, tP.field, tP.idx, tP);\n }\n /** Appends a number incrementally until a unique taxonym is found. */\n function appendNumToTaxonym(taxonName, tP) { \n var count = 1;\n var taxonym1 = taxonName + '-1';\n return nextInTaxaObj(taxonName, taxonym1, count, tP);\n \n function nextInTaxaObj(taxonName, taxonym, cnt, tP) {\n if (taxonym in tP.taxaObjs) {\n var nextTaxonym = taxonName + '-' + ++cnt; \n return nextInTaxaObj(taxonName, nextTaxonym, cnt, tP)\n } else { return taxonym; }\n }\n } /* End appendNumToTaxonym */\n /** Adds conflcited records to the conflictedTaxaObj. */\n function hasParentConflicts(taxonName, existingTaxonObj, conflictingLvl, tP) {\n if ( existingTaxonObj === null ) { \n initConflictedGenus();\n addConflictedGenus() ;\n } else { \n initConflictedTaxa();\n addConflictedTaxa(); } \n /** Init the various properties of the conflictedTaxaObj as needed. */\n function initConflictedGenus() {\n if ( conflictedTaxaObj[\"conflictedGenus\"] === undefined ) { conflictedTaxaObj[\"conflictedGenus\"] = {}; }\n if ( conflictedTaxaObj.conflictedGenus[tP.role] === undefined ) { conflictedTaxaObj.conflictedGenus[tP.role] = {}; }\n if ( conflictedTaxaObj.conflictedGenus[tP.role][taxonName] === undefined ) { \n conflictedTaxaObj.conflictedGenus[tP.role][taxonName] = []; }\n }\n function initConflictedTaxa() {\n if ( conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]] === undefined ) { \n conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]] = {}; }\n if ( conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]][tP.role] === undefined ) { \n conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]][tP.role] = {}; }\n if ( conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]][tP.role][taxonName] === undefined ) { \n conflictedTaxaObj[tP.fieldAry[lvlAry[conflictingLvl]]][tP.role][taxonName] = {}; }\n }\n /** Pushes the taxonObj IDs onto the conflictedTaxaObj. */\n function addConflictedGenus() {\n conflictedTaxaObj.conflictedGenus[tP.role][taxonName].push(tP.recrd.tempId); \n }\n /** Pushes both taxonObj IDs onto the conflictedTaxaObj. */\n function addConflictedTaxa() { // console.log(\"conflicting parents pushed = old.%O- new.%O \", taxonRecrdObjsAry[existingTaxonObj.tempId], taxonRecrdObjsAry[tP.recrd.tempId]);\n var level = tP.fieldAry[lvlAry[conflictingLvl]];\n var existingParentName = taxaNameMap[existingTaxonObj.parent]; \n var newParentName = tP.recrd[level];\n initParentTaxaProps(existingParentName, newParentName);\n addTaxaIds();\n\n function addTaxaIds() {\n conflictedTaxaObj[level][tP.role][taxonName][existingParentName].push(existingTaxonObj.rcrdId); \n conflictedTaxaObj[level][tP.role][taxonName][newParentName].push(tP.recrd.tempId); \n }\n\n function initParentTaxaProps() {\n if (conflictedTaxaObj[level][tP.role][taxonName][existingParentName] === undefined) {\n conflictedTaxaObj[level][tP.role][taxonName][existingParentName] = []; }\n if (conflictedTaxaObj[level][tP.role][taxonName][newParentName] === undefined) {\n conflictedTaxaObj[level][tP.role][taxonName][newParentName] = []; }\n }\n }\n } /* End hasParentConflicts */\n /** \n * Recurses through all parents of the 'newParentTaxonRcrd' and returns\n * true if the tree merges back into the existing parent taxon. \n */\n function treesMergeAtHigherLevel(newParentTaxonRcrd, existingParentId, tP) {\n if (newParentTaxonRcrd.parent === null) { return false; }\n if (newParentTaxonRcrd.parent === existingParentId) {\n return true;\n } else {\n return treesMergeAtHigherLevel(tP.taxaObjs[taxaNameMap[newParentTaxonRcrd.parent]], existingParentId, tP)\n }\n }\n /*-------------- Taxon Object Methods --------------------------------*/\n \t/**\n \t * Creates the taxon object, i.e. taxon record, that will be linked back into the \n \t * interaction records. There will one taxon record for each unique taxon at any \n \t * level in the records, linked to their parent and children by id.\n \t */\n function buildTaxonObj(taxonName, field, idx, tP) { //console.log(\"buildTaxonObj called. arguemnts = %O\", arguments);\n var level = lvlAry[idx];\n var kingdom = tP.role === \"subject\" ? \"Animalia\" : tP.recrd.objKingdom;\n // If this taxon is a Species \n if (tP.fieldAry[0] === field) { checkGenus() }\t\t\n if (errors) { return; }\n\n var parentTaxonId = linkparentTaxonId(idx, tP);\n if (parentTaxonId === null) { nullParentError(tP);\n } else {\n tP.taxaObjs[taxonName] = {\n kingdom: kingdom,\n parent: parentTaxonId,\n name: taxonName,\n level: level, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++,\n rcrdId: tP.recrd.tempId\n };\n taxaNameMap[tP.taxaObjs[taxonName].tempId] = taxonName; \n }\n /**\n * If the Genus field is null, set with the genus from the species name. \n * If Genus is set, check if it's a @validGenus.\n */\n function checkGenus() { \t\t\t\t\t\t\t\t\t\t\n if (tP.recrd[tP.fieldAry[1]] === null) { \n \ttP.fieldAry[1] = tP.genusParent; \n } else if (!validGenus()) { conflictedGenusError(); }\n }\n /** Check that the genus field value and the genus from the species name are the same. */\n function validGenus() { \t\t\t\t\t\t\t\t\t\t// console.log(\"isValidGenus = \", tP.recrd[tP.fieldAry[1]] === tP.genusParent);\n return tP.recrd[tP.fieldAry[1]] === tP.genusParent;\n }\n /** Add record with conflicted fields to the conflictedTaxaObj. Trigger end of build with errors=true. */\n function conflictedGenusError() { \n hasParentConflicts(taxonName, null, 6, tP); \n errors = true;\n }\n } /* End buildTaxonObj */\n /**\n * Finds the next field that has a value in it; this is the parent taxon. It is sent into\n * @addTaxonData with it's related data. There the taxon is either created or checked for \n * new data. The parent's taxonObj id is returned, linking children to their parents.\n */\n function linkparentTaxonId(idx, tP) { \t\t\t\t\t\t\t\t//console.log(\"linkparentTaxonId called. arguments = %O\", arguments);\n if (idx === 6) { console.log(\"Error. Parent taxon idx too high. recrd = %O\", tP.recrd); return null; }\n var parentIdx = getParentLevel(tP, idx);\n if (parentIdx === false) { return null; }\n var parentField = tP.fieldAry[parentIdx]; \t\t\t\t\t\t//console.log(\"parentField = \", parentField)\n var parentName = tP.recrd[parentField]; \t\t\t\t\t\t//console.log(\"parentName = \", parentName)\n \n addTaxonData(parentName, parentField, parentIdx, tP);\n\n return tP.taxaObjs[parentName].tempId;\n }\n /** Finds the next field that has a value. */\n function getParentLevel(tP, idx) { \t\t\t\t\t\t\t\t// console.log(\"getParentLevel called. idx = \", idx)\n for (var i = ++idx; i <= 7; i++) { \t\t\t// 7 indicates there is no value in kingdom(6)\n if (i === 7) { console.log(\"i=7; kingdom===null; no parent found at top of tree.\"); return false; }\n if (tP.recrd[tP.fieldAry[i]] !== null) { return i; }\n }\n }\n /** If no parent taxon is found, the record is quarantined and flagged. */\n function nullParentError(tP) { \t\t\t\t\t\t\t\t\t\t// console.log(\"nullParentError tP = %O\", tP)\n errors = true;\n if (nullKingdoms[tP.role] === undefined) { nullKingdoms[tP.role] = [] };\n nullKingdoms[tP.role].push(tP.recrd);\n delete recrdsObj[tP.recrd.tempId];\n }\n } /* End buildTaxaTree */\n /** If taxon records without kingdom values were found, they are added to the validation report. */\n function rprtNullKingdoms() {\n if (entityObj.taxon.valRpt.rcrdsWithNullReqFields === undefined) { entityObj.taxon.valRpt.rcrdsWithNullReqFields = {}; };\n entityObj.taxon.valRpt.rcrdsWithNullReqFields.kingdom = nullKingdoms;\n }\n /** \n * Conflicted taxa quarantined here by ID reference are replaced with their records and \n * added to the validation reort. The source interaction records are thus quarantined. \n */\n function rprtConflictedTaxon() {\n \tvar rcrdIds = [];\n for (var conflct in conflictedTaxaObj) {\n for (var role in conflictedTaxaObj[conflct]) { \t\t\t\t//console.log(\"\")\n for (var taxonName in conflictedTaxaObj[conflct][role]) { ///\tconsole.log(\"conflictedTaxaObj[conflct][role][taxonName] = %O\", conflictedTaxaObj[conflct][role][taxonName])\n if (Array.isArray(conflictedTaxaObj[conflct][role][taxonName])) {\n conflictedTaxaObj[conflct][role][taxonName] = rprtGenusConflicts(conflictedTaxaObj[conflct][role][taxonName])\n } else { rprtLevelConflicts(conflictedTaxaObj[conflct][role][taxonName]); }\n }\n }\n }\n entityObj.taxon.valRpt.shareUnqKeyWithConflictedData = conflictedTaxaObj; // console.log(\" conflicted taxa report obj = %O\", entityObj.taxon.valRpt.shareUnqKeyWithConflictedData);\n removeAffectedIntRcrds();\n\n function rprtGenusConflicts(conflictAry) {// console.log(\"-------------------rprtGenusConflicts called. ary = %O\", conflictAry)\n conflictAry = conflictAry.filter(onlyUnique);\n return replaceIdsWithRcrds(conflictAry, role); \n\n }\n function rprtLevelConflicts(taxaNameConflicts) {\n for (var parentName in taxaNameConflicts){\n taxaNameConflicts[parentName] = taxaNameConflicts[parentName].filter(onlyUnique);\n taxaNameConflicts[parentName] = replaceIdsWithRcrds(taxaNameConflicts[parentName], role);\n }\n }\n function replaceIdsWithRcrds(taxaIdAry, role) {\n var taxaObjs = role === \"subject\" ? batTaxaRefObj : objTaxaRefObj;\n return taxaIdAry.map(function(recrdId){ // console.log(\"taxaObj = %O, rcrd = %O\", taxaObjs[taxaNameMap[recrdId]], taxonRecrdObjsAry[recrdId]);\n rcrdIds.push(recrdId);\n return taxonRecrdObjsAry[recrdId];\n });\n }\n function removeAffectedIntRcrds() {\n \trcrdIds.forEach(function(id){ delete recrdsObj[id]; });\n }\n } /* End rprtConflictedTaxon */\n function rprtNullTaxa() {\n for (var role in nullTaxa) { nullTaxa[role] = nullTaxa[role].map(replaceIdWithRcrdAndDeleteRef); }\n entityObj.taxon.valRpt.rcrdsWithNullReqFields = nullTaxa; //console.log(\" null taxa report obj = %O\", entityObj.taxon.valRpt.rcrdsWithNullReqFields);\n\n function replaceIdWithRcrdAndDeleteRef(rcrdId) {\n delete recrdsObj[rcrdId];\n return taxonRecrdObjsAry[rcrdId];\n }\n } /* End rprtNullTaxa */\n /** Build taxonObjs for the top taxa and add them to the taxaNameMap reference object. */\n function initTopTaxa() {\n taxaNameMap[1] = 'Animalia';\n taxaNameMap[2] = 'Chiroptera';\n taxaNameMap[3] = 'Plantae';\n taxaNameMap[4] = 'Arthropoda';\n batTaxaRefObj = {\n Animalia: {\n kingdom: \"Animalia\",\n parent: null,\n name: \"Animalia\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++\n },\n Chiroptera: {\n kingdom: \"Animalia\",\n parent: 1, // 1 = animalia\n name: \"Chiroptera\",\n level: 4,\n tempId: curTempId++\n },\n };\n objTaxaRefObj = {\n Animalia: { //Repeated here because it will be collapsed in the merge process and animalia waas added as an ancestor antrhopoda very late in the writting of this code and restructuring didn't seen worth the effort and time.\n kingdom: \"Animalia\",\n parent: null,\n name: \"Animalia\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: 1\n },\n Plantae: {\n kingdom: \"Plantae\",\n parent: null,\n name: \"Plantae\",\n level: 1, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++\n },\n Arthropoda: { // concat names of taxa, and all parent levels present, are used as keys to later link taxa.\n kingdom: \"Animalia\",\n parent: 1,\n name: \"Arthropoda\",\n level: 2,\n tempId: curTempId++\n },\n };\n } /* End initTopTaxa */\n function mergeRefsWithRcrds(taxonRcrdAryByRole) {\n mergeParentRcrds();\n mergeTaxaNameMapWithRcrds(); \t\n\n function mergeParentRcrds() {\n for (var taxonName in taxonRcrdAryByRole) {\n var taxonObj = taxonRcrdAryByRole[taxonName];\n var parentObj = taxonRcrdAryByRole[taxaNameMap[taxonObj.parent]];\n taxonObj.parent = parentObj || null;\n }\n }\n function mergeTaxaNameMapWithRcrds() {\n for (var taxonName in taxonRcrdAryByRole) {\n var taxonObj = taxonRcrdAryByRole[taxonName];\n taxaNameMap[taxonObj.tempId] = taxonObj; \n }\n }\n }\n }", "function buildTaxonObj(taxonName, field, idx, tP) { //console.log(\"buildTaxonObj called. arguemnts = %O\", arguments);\n var level = lvlAry[idx];\n var kingdom = tP.role === \"subject\" ? \"Animalia\" : tP.recrd.objKingdom;\n // If this taxon is a Species \n if (tP.fieldAry[0] === field) { checkGenus() }\t\t\n if (errors) { return; }\n\n var parentTaxonId = linkparentTaxonId(idx, tP);\n if (parentTaxonId === null) { nullParentError(tP);\n } else {\n tP.taxaObjs[taxonName] = {\n kingdom: kingdom,\n parent: parentTaxonId,\n name: taxonName,\n level: level, // Kingdom (1), Phylum (2), Class (3), Order (4), Family (5), Genus (6), Species (7)\n tempId: curTempId++,\n rcrdId: tP.recrd.tempId\n };\n taxaNameMap[tP.taxaObjs[taxonName].tempId] = taxonName; \n }\n /**\n * If the Genus field is null, set with the genus from the species name. \n * If Genus is set, check if it's a @validGenus.\n */\n function checkGenus() { \t\t\t\t\t\t\t\t\t\t\n if (tP.recrd[tP.fieldAry[1]] === null) { \n \ttP.fieldAry[1] = tP.genusParent; \n } else if (!validGenus()) { conflictedGenusError(); }\n }\n /** Check that the genus field value and the genus from the species name are the same. */\n function validGenus() { \t\t\t\t\t\t\t\t\t\t// console.log(\"isValidGenus = \", tP.recrd[tP.fieldAry[1]] === tP.genusParent);\n return tP.recrd[tP.fieldAry[1]] === tP.genusParent;\n }\n /** Add record with conflicted fields to the conflictedTaxaObj. Trigger end of build with errors=true. */\n function conflictedGenusError() { \n hasParentConflicts(taxonName, null, 6, tP); \n errors = true;\n }\n }", "function addConflictedTaxa() { // console.log(\"conflicting parents pushed = old.%O- new.%O \", taxonRecrdObjsAry[existingTaxonObj.tempId], taxonRecrdObjsAry[tP.recrd.tempId]);\n var level = tP.fieldAry[lvlAry[conflictingLvl]];\n var existingParentName = taxaNameMap[existingTaxonObj.parent]; \n var newParentName = tP.recrd[level];\n initParentTaxaProps(existingParentName, newParentName);\n addTaxaIds();\n\n function addTaxaIds() {\n conflictedTaxaObj[level][tP.role][taxonName][existingParentName].push(existingTaxonObj.rcrdId); \n conflictedTaxaObj[level][tP.role][taxonName][newParentName].push(tP.recrd.tempId); \n }\n\n function initParentTaxaProps() {\n if (conflictedTaxaObj[level][tP.role][taxonName][existingParentName] === undefined) {\n conflictedTaxaObj[level][tP.role][taxonName][existingParentName] = []; }\n if (conflictedTaxaObj[level][tP.role][taxonName][newParentName] === undefined) {\n conflictedTaxaObj[level][tP.role][taxonName][newParentName] = []; }\n }\n }", "constructor() { \n OrganizationCountAndAddressInfo.initialize(this);DealsCountAndActivityInfo.initialize(this);\n AdditionalBaseOrganizationItemInfo.initialize(this);\n }", "function setInitValues(facet, obj) {\n\tif (hierarchylevelnameFacet == facet) hierarchyInits = obj;\n\telse if (scenarioFacet == facet) scenarioInits = obj;\n\telse if (datatypeFacet == facet) datatypeInits = obj;\n\telse if (organizationFacet == facet) organizationInits = obj;\n\telse if (topicFacet == facet) topicInits = obj;\n}", "function mergeTaxaIntoInteractions() {\n \tvar recrdsObj = entityObj.curRcrds; \n\t var taxonObjs = entityObj.taxon.taxonObjs;\t\t\t\t\t\t\t //\tconsole.log(\"taxonObjs = %O\", taxonObjs); \n\t var mergeRefs = entityObj.taxon.mergeRefs;\t\t\t\t\t\t\t\t// console.log(\"mergeRefs = %O\", mergeRefs); \n\n\t for (var rcrdId in recrdsObj) {\t\t\t\t\t\t\t\t\t\t\t//console.log(\"mergeTaxaIntoInteractions rcrd = %O\", recrdsObj[rcrdId][0]);\n recrdsObj[rcrdId][0].subjTaxon = taxonObjs[mergeRefs[rcrdId].subject];\n recrdsObj[rcrdId][0].objTaxon = taxonObjs[mergeRefs[rcrdId].object];\t\n\t }\n }", "constructor() { \n PersonNameCountAndEmailInfoWithIds.initialize(this);MergePersonDealRelatedInfo.initialize(this);\n AdditionalMergePersonInfo.initialize(this);\n }", "constructor() { \n PersonNameInfoWithOrgAndOwnerId.initialize(this);PersonCountEmailDealAndActivityInfo.initialize(this);\n AdditionalPersonInfo.initialize(this);\n }", "async _initializeVars() {\n const oThis = this;\n\n switch (oThis.chainKind) {\n case coreConstants.originChainKind:\n oThis.chainId = oThis._configStrategyObject.originChainId;\n oThis.associatedAuxChainId = 0;\n oThis.anchorOrgContractOwnerKind = chainAddressConstants.originAnchorOrgContractOwnerKind;\n // Define anchor and co-anchor addresses here.\n oThis.anchorContractAddressKind = chainAddressConstants.originAnchorContractKind;\n oThis.coAnchorContractAddressKind = chainAddressConstants.auxAnchorContractKind;\n\n let gasPriceCacheObj = new gasPriceCacheKlass(),\n garPriceRsp = await gasPriceCacheObj.fetch();\n oThis.gasPrice = garPriceRsp.data;\n\n break;\n case coreConstants.auxChainKind:\n oThis.chainId = oThis.auxChainId;\n oThis.associatedAuxChainId = oThis.auxChainId;\n oThis.anchorOrgContractOwnerKind = chainAddressConstants.auxAnchorOrgContractOwnerKind;\n // Define anchor and co-anchor addresses here.\n oThis.anchorContractAddressKind = chainAddressConstants.auxAnchorContractKind;\n oThis.coAnchorContractAddressKind = chainAddressConstants.originAnchorContractKind;\n\n oThis.gasPrice = contractConstants.zeroGasPrice;\n break;\n default:\n throw `unsupported chainKind: ${oThis.chainKind}`;\n }\n }", "constructor() { \n \n Tax.initialize(this);\n }", "constructor() { \n \n TaxTypeData.initialize(this);\n }", "constructor() { \n \n SummarizedTax.initialize(this);\n }", "function rprtConflictedTaxon() {\n \tvar rcrdIds = [];\n for (var conflct in conflictedTaxaObj) {\n for (var role in conflictedTaxaObj[conflct]) { \t\t\t\t//console.log(\"\")\n for (var taxonName in conflictedTaxaObj[conflct][role]) { ///\tconsole.log(\"conflictedTaxaObj[conflct][role][taxonName] = %O\", conflictedTaxaObj[conflct][role][taxonName])\n if (Array.isArray(conflictedTaxaObj[conflct][role][taxonName])) {\n conflictedTaxaObj[conflct][role][taxonName] = rprtGenusConflicts(conflictedTaxaObj[conflct][role][taxonName])\n } else { rprtLevelConflicts(conflictedTaxaObj[conflct][role][taxonName]); }\n }\n }\n }\n entityObj.taxon.valRpt.shareUnqKeyWithConflictedData = conflictedTaxaObj; // console.log(\" conflicted taxa report obj = %O\", entityObj.taxon.valRpt.shareUnqKeyWithConflictedData);\n removeAffectedIntRcrds();\n\n function rprtGenusConflicts(conflictAry) {// console.log(\"-------------------rprtGenusConflicts called. ary = %O\", conflictAry)\n conflictAry = conflictAry.filter(onlyUnique);\n return replaceIdsWithRcrds(conflictAry, role); \n\n }\n function rprtLevelConflicts(taxaNameConflicts) {\n for (var parentName in taxaNameConflicts){\n taxaNameConflicts[parentName] = taxaNameConflicts[parentName].filter(onlyUnique);\n taxaNameConflicts[parentName] = replaceIdsWithRcrds(taxaNameConflicts[parentName], role);\n }\n }\n function replaceIdsWithRcrds(taxaIdAry, role) {\n var taxaObjs = role === \"subject\" ? batTaxaRefObj : objTaxaRefObj;\n return taxaIdAry.map(function(recrdId){ // console.log(\"taxaObj = %O, rcrd = %O\", taxaObjs[taxaNameMap[recrdId]], taxonRecrdObjsAry[recrdId]);\n rcrdIds.push(recrdId);\n return taxonRecrdObjsAry[recrdId];\n });\n }\n function removeAffectedIntRcrds() {\n \trcrdIds.forEach(function(id){ delete recrdsObj[id]; });\n }\n }", "function initObjects() {\n\tvar fam, build, currentBuild;\n\tfor (fam in listBuilds) {\n\t\tfor (build in listBuilds[fam]) {\n\t\t\tcurrentBuild = listBuilds[fam][build];\n\t\t\tcurrentBuild.myDiv = $(\"#\" + build);\n\t\t\tif (currentBuild.parent !== \"\") {\n\t\t\t\tcurrentBuild.parent = listBuilds[fam][currentBuild.parent];\n\t\t\t}\n\t\t\tif (currentBuild.otherParent !== \"\") {\n\t\t\t\tcurrentBuild.otherParent = listBuilds[getFamily(currentBuild.otherParent)][currentBuild.otherParent];\n\t\t\t}\n\t\t}\n\t}\n}", "constructor() { \n OrganizationAddressInfo.initialize(this);OrganizationsCollectionResponseObjectAllOf.initialize(this);\n OrganizationsCollectionResponseObject.initialize(this);\n }", "constructor() { \n UpdateTeam.initialize(this);BaseTeamAdditionalProperties.initialize(this);\n UpdateTeamWithAdditionalProperties.initialize(this);\n }", "async _initializeVars() {\n const oThis = this;\n\n switch (oThis.chainKind) {\n case coreConstants.originChainKind:\n oThis.chainId = oThis._configStrategyObject.originChainId;\n oThis.associatedAuxChainId = 0;\n oThis.deployerKind = chainAddressConstants.originDeployerKind;\n oThis.mppLibContractKind = chainAddressConstants.originMppLibContractKind;\n\n let gasPriceCacheObj = new gasPriceCacheKlass(),\n gasPriceRsp = await gasPriceCacheObj.fetch();\n oThis.gasPrice = gasPriceRsp.data;\n break;\n case coreConstants.auxChainKind:\n oThis.chainId = oThis._configStrategyObject.auxChainId;\n oThis.auxChainId = oThis._configStrategyObject.auxChainId;\n oThis.associatedAuxChainId = oThis.auxChainId;\n oThis.deployerKind = chainAddressConstants.auxDeployerKind;\n oThis.mppLibContractKind = chainAddressConstants.auxMppLibContractKind;\n oThis.gasPrice = contractConstants.zeroGasPrice;\n break;\n default:\n throw `unsupported chainKind: ${oThis.chainKind}`;\n }\n\n switch (oThis.libKind) {\n case 'merklePatriciaProof':\n oThis.stepKind = chainSetupLogsConstants.deployMerklePatriciaProofLibStepKind;\n oThis.chainAddressKind =\n oThis.chainKind == coreConstants.originChainKind\n ? chainAddressConstants.originMppLibContractKind\n : chainAddressConstants.auxMppLibContractKind;\n oThis.gas = contractConstants.deployMppLibGas;\n break;\n case 'messageBus':\n oThis.stepKind = chainSetupLogsConstants.deployMessageBusLibStepKind;\n oThis.chainAddressKind =\n oThis.chainKind == coreConstants.originChainKind\n ? chainAddressConstants.originMbLibContractKind\n : chainAddressConstants.auxMbLibContractKind;\n oThis.gas = contractConstants.deployMbLibGas;\n break;\n case 'gateway':\n oThis.stepKind = chainSetupLogsConstants.deployGatewayLibStepKind;\n oThis.chainAddressKind =\n oThis.chainKind == coreConstants.originChainKind\n ? chainAddressConstants.originGatewayLibContractKind\n : chainAddressConstants.auxGatewayLibContractKind;\n oThis.gas = contractConstants.deployGatewayLibGas;\n break;\n default:\n throw `unsupported libLind ${oThis.libKind}`;\n }\n }", "init(object) {\n // import the sequence and version vector, yet it keeps the identifier of\n // this instance of the core.\n\n // this.broadcast = Object.assign(new VVwE(this.id),object.causality);\n\n // var local = this.broadcast.causality.local;\n this.broadcast._causality = this.broadcast._causality.constructor.fromJSON(object.causality);\n\n\n // this.broadcast.causality.local = local;\n var local = this.broadcast._causality.local;\n // this.broadcast.causality.vector.insert(this.broadcast.causality.local);\n\n this.No_antientropy.broadcast._causality.local.e = local.e;\n\n this.sequence.fromJSON(object.sequence);\n this.sequence._s = local.e;\n this.sequence._c = local.v;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the string contains any fullwidth chars. If given value is not a string, then it returns false.
function isFullWidth(value) { return typeof value === 'string' && validator_lib_isFullWidth__WEBPACK_IMPORTED_MODULE_1___default()(value); }
[ "function isFullWidth(value) {\n return typeof value === \"string\" && validator.isFullWidth(value);\n}", "function isFullWidth(value) {\n return typeof value === \"string\" && validator.isFullWidth(value);\n }", "function isFullWidth(dataValue)\r\n{\r\n\r\n\tif (dataValue == \"\" ) {\r\n\t\treturn(\"\");\r\n\t}\r\n\t\r\n\tvar unicode_value = 0;\r\n\tvar fullwidth = true;\r\n\tvar charCode = 0;\r\n\tfor (var i = 0; i < dataValue.length; i++)\t{\r\n\t\tunicode_value = dataValue.charCodeAt(i);\r\n//\t\talert(\"Code is \" + unicode_value )\r\n\r\n\t\tif (! ((unicode_value >= 65296 && unicode_value <= 65370) || \r\n\t\t\t\t(unicode_value >= 12450 && unicode_value <= 12531) ||\r\n\t\t\t\t(unicode_value >= 12354 && unicode_value <= 12435) ))\t{\r\n//\t\t\talert(\"Improper Character \" + unicode_value + \">>\" + dataValue.charAt(i));\r\n\t\t\tfullwidth = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn fullwidth;\t\r\n}", "function isFullWidth(value) {\n return typeof value === 'string' && isFullWidth_1.default(value);\n}", "function isFullWidth(value) {\n return typeof value === \"string\" && validator__WEBPACK_IMPORTED_MODULE_1___default.a.isFullWidth(value);\n}", "function isAString(string){\n if(typeof string === \"string\" & string.length >= 8){\n return true;\n }\n else {\n return false;\n }\n}", "function isUnemptyString (thing) {\n return isString(thing) && thing !== '';\n }", "function isStringWithLength(variable) {\n return isString(variable) && variable.length > 0;\n}", "function stringIsWord(value) {\n\treturn value.length <=50 && /^[a-z\\-\\s]+$/i.test(value) && !/^[\\-\\s]+$/.test(value);\n}", "function checkStringValid(input) {\n\tif (input.length <= 256 && input != \"\") {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t} \n}", "function exactLength(str,len){\n if((str == null || str.length == 0)) return false;\n if(str.length == len){\n return true;\n }\n else{\n return false;\n }\n}", "function isHalfWidth(dataValue )\r\n{\r\n\tif (dataValue == \"\" ) {\r\n\t\treturn(\"\");\r\n\t}\r\n\t\r\n\tvar unicode_value = 0;\r\n\tvar halfwidth = true;\r\n\tvar charCode = 0;\r\n\tfor (var i = 0; i < dataValue.length; i++)\t{\r\n\t\tunicode_value = dataValue.charCodeAt(i);\r\n//\t\talert(\"Code is \" + unicode_value )\r\n\r\n\t\tif (! (unicode_value < 127 || (unicode_value >= 65393 && unicode_value <= 65437)) ){\r\n//\t\t\talert(\"Improper Character \" + unicode_value + \">>\" + dataValue.charAt(i));\r\n\t\t\thalfwidth = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn halfwidth;\t\r\n}", "function desiredString(x) {\n if (typeof x === \"string\") {\n return x.length >= 8;\n }\n return false;\n}", "function blank(string){\n\n if(typeof string === 'string' && string.length === 0){\n return true;\n\n }else{\n return false;\n }\n}", "function blank(s) {\n\tif (typeof s !== \"string\") toss(\"type\");\n\tif (s.length === 0) return true;\n\treturn false;\n}", "function eightCharatersLong(input) {\n if (typeof input === 'string' && input.length >= 8){\n return true;\n }\n else {\n return false;\n }\n}", "function not_empty(s) {\n return s && s.length && s.length > 0\n }", "function isShortWord(str) {\n return str.length < 5;\n}", "function isString(val) {\n return typeof val === 'string' && val.length > 0\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an "event" onto the fake xhr object that just calls the samenamed method. This is in case a library adds callbacks for these events.
function _addEventListener(eventName, xhr){ xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener(event); } }); }
[ "function AjaxEvent () {}", "function _addEventListener(eventName, xhr) {\n xhr.addEventListener(eventName, function (event) {\n var listener = xhr[\"on\" + eventName];\n\n if (listener && typeof listener == \"function\") {\n listener.call(event.target, event);\n }\n });\n }", "function createHandler(eventType) {\n xhr['on' + eventType] = function(event) {\n copyLifecycleProperties(lifecycleProps, xhr, fakeXHR);\n dispatchEvent(fakeXHR, eventType, event);\n };\n }", "function createHandler(eventType) {\n xhr['on' + eventType] = function (event) {\n copyLifecycleProperties(lifecycleProps, xhr, fakeXHR);\n dispatchEvent(fakeXHR, eventType, event);\n };\n }", "on(event, callback) {\n if (this.customEvents[event])\n this.customEvents[event].push(callback)\n else\n document.addEventListener(event, callback)\n }", "featureClickEventHandler(event) {\r\n this.featureEventResponse(event);\r\n }", "function HttpSentEvent(){}", "function testEvent(){ testEvent.fired = true; }", "function callback(eventName){\r\n\tvar customEvent = document.createEvent('Event');\r\n\tcustomEvent.initEvent(eventName, false, true);\r\n\tdocument.dispatchEvent(customEvent);\r\n}", "function HttpSentEvent() {}", "function MockXMLHttpRequest() {}", "onEvent(callback) {\n this.eventCallback = callback;\n }", "addEvent(event) {\r\n\t\tthis.eventQueue.add(event);\r\n\t}", "function createUploadHandler(eventType) {\n if (xhr.upload && fakeXHR.upload && fakeXHR.upload['on' + eventType]) {\n xhr.upload['on' + eventType] = function (event) {\n dispatchEvent(fakeXHR.upload, eventType, event);\n };\n }\n }", "onIntercept(details) {\n // NOTE: If you want to send a data object with the event, it has to\n // be wrapped in another object as the \"detail\" property.\n var event = new CustomEvent(\"onRequestInterception\", {\n detail: { requestDetails: details }\n });\n\n // Dispatch it to the window object so everybody can register for\n // the event\n window.dispatchEvent(event);\n }", "function HttpSentEvent() { }", "setupXHRInterception() {\n // Store original XMLHttpRequest implementation so we can hook back\n // in after dispatching our events\n var send_imp = XMLHttpRequest.prototype.send,\n open_imp = XMLHttpRequest.prototype.open,\n setRequestHeader_imp = XMLHttpRequest.prototype.setRequestHeader;\n\n // Ensure we have a concrete reference to this instance, as `this`\n // changes context when you are in callbacks, etc\n var self = this;\n\n // Redefine XMLHttpRequest methods, in which we dispatch our\n // interception event, and then call the original implementation.\n XMLHttpRequest.prototype.send = function(data) {\n var requestBody = self.sanitizeBodyData(data);\n\n self.onIntercept({\n requestId: this.requestId,\n url: this.requestUrl,\n type: \"XHR_send\",\n props: {\n requestBody: requestBody\n }\n });\n\n send_imp.apply(this, arguments);\n };\n\n XMLHttpRequest.prototype.open = function(method, url, async, user, password) {\n // If the URL doesn't have any protocol/host info, then lets\n // get it from the window.location object. (origin is the\n // protocol + host/domain)\n var sanitizedUrl = self.sanitizeUrl(url);\n\n // Tag the request so we can follow it through the other\n // XHR methods\n this.requestId = guid();\n this.requestUrl = sanitizedUrl;\n\n // Create timeStamp on open() so we get the timestamp of the\n // request, not the complete\n // TODO: Verify this is correct behaviour?\n var timeStamp = new Date().getTime();\n\n // Add a readystatechange listener when we detect an XHR so we can\n // detect when we have a response\n this.addEventListener('readystatechange', function(event) {\n var success = this.status.isSuccessfulStatusCode();\n var finished = this.readyState === XMLHttpRequest.DONE;\n\n // Ignore if we haven't completed successfully.\n if (!(success && finished)) {\n return;\n }\n\n var responseBody = self.sanitizeBodyData(this.response);\n\n self.onIntercept({\n requestId: this.requestId,\n url: this.requestUrl,\n type: \"XHR_complete\",\n props: {\n url: sanitizedUrl,\n method: method,\n timeStamp: timeStamp,\n statusCode: this.status,\n responseHeaders: getHeaderDictionary(this.getAllResponseHeaders()),\n responseBody: responseBody\n }\n });\n });\n\n // Add an error listener so we can clear out the request\n this.addEventListener('error', function(event) {\n self.onIntercept({\n requestId: this.requestId,\n url: this.requestUrl,\n type: \"XHR_error\",\n props: {}\n });\n });\n\n self.onIntercept({\n requestId: this.requestId,\n url: this.requestUrl,\n type: \"XHR_open\",\n props: {}\n });\n\n open_imp.apply(this, arguments);\n };\n\n XMLHttpRequest.prototype.setRequestHeader = function(header, value) {\n self.onIntercept({\n requestId: this.requestId,\n url: this.requestUrl,\n type: \"XHR_setRequestHeader\",\n props: {\n requestHeader: { name: header, value: value }\n }\n });\n\n setRequestHeader_imp.apply(this, arguments);\n };\n }", "function createUploadHandler(eventType) {\n if (xhr.upload) {\n xhr.upload['on' + eventType] = function(event) {\n dispatchEvent(fakeXHR.upload, eventType, event);\n };\n }\n }", "_registerEvent() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function sets the second Y point
setPoint2Y(y) { return this.point2.setY(y); }
[ "setY(index, y) {\n this.xy[index * 2 + 1] = y;\n }", "setY(index, y) {\n this.xy[index * 2 + 1] = y;\n }", "setPoint1Y(y) {\n\n return this.point1.setY(y);\n }", "function onSetSecondLineY() {\n setSecondLineY();\n}", "setY(index, y) {\n this._linePoints[index * 2 + 1] = y;\n }", "setY(newY) { this.y = newY;}", "set y(value) {\r\n this._y = value;\r\n this.updateY();\r\n }", "set y(value) {this._y = value;}", "set y(val) {\n this.m[1] = val;\n }", "set y (y) {\n this.data.y = y;\n this.updateCss();\n }", "set Y(y) {\n if (isNaN(y)) {\n console.log('Error: Your value is not a number.');\n } else {\n y = parseInt(y);\n if (y < this._minY) y = this._minY + 1;\n if (y > this._maxY) y = this._maxY - 1;\n this._y = y - this._yCorrection;\n this.robot.style.top = this._y;\n }\n }", "set y(newY){\n\t\tthis.paddle.setAttribute(\"y\", newY);\n\t}", "function animateY2() {\n\t// Calculate the new value of Y2 \n\tfunction getNewY2() {\n\t\tvar newY2 = y2 + y2v; // Calculate the new value of Y2 based on the current velocity\n\t\tif ((newY2 < 0) || (newY2 >= c.height)) { // If the new value exceeds the canvas:\n\t\t\ty2v = -y2v; // Invert the velocity\n\t\t\tnewY2 = y2 + y2v; // Discard the previous result and recalculate the position\n\t\t}\n\t\thue = Math.round(y2 * (heightTo255));\n\t\treturn newY2; // Return the new Y2 coordinate\n\t}\n\t// Main code of animate()\n\ty2 = getNewY2();\n\tredraw();\n\tupdateWatch();\n}", "function FSS_SetCoordY(y, i)\n{\n\tthis.coordY[i] = y;\n}", "setY(y) {\n this.y = y;\n return this;\n }", "modifyY(y) {\n return 800 - (y / this.scale);\n }", "function setYval(val) {\r\n // Update yVal\r\n yVal = val;\r\n // Update the axis\r\n yScale.domain([d3.min(data, function(d) { return parseFloat(d[yVal]); })-1,\r\n d3.max(data, function(d) { return parseFloat(d[yVal]); })+1])\r\n yAxis.scale(yScale);\r\n yAxisG.call(yAxis);\r\n yLabel.text(yVal);\r\n // Update the points\r\n\r\n}", "function setPosY( dancer, posY ) {\n dancer.pos = new vec2( dancer.pos.x, posY )\n }", "function getNewY2() {\n\t\tvar newY2 = y2 + y2v; // Calculate the new value of Y2 based on the current velocity\n\t\tif ((newY2 < 0) || (newY2 >= c.height)) { // If the new value exceeds the canvas:\n\t\t\ty2v = -y2v; // Invert the velocity\n\t\t\tnewY2 = y2 + y2v; // Discard the previous result and recalculate the position\n\t\t}\n\t\thue = Math.round(y2 * (heightTo255));\n\t\treturn newY2; // Return the new Y2 coordinate\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do something when dragging stops on agenda div
function myAgendaDragStop(eventObj, divElm, agendaItem) { //alert("drag stop"); }
[ "function myAgendaDragStop(eventObj,divElm,agendaItem){\n\t\t//alert(\"drag stop\");\n\t}", "function myAgendaDragStop(eventObj,divElm,agendaItem){\n\talert(\"drag stop\");\n}", "handleDragEnd() {\n this.stopDragging();\n\n this.isDragging = false;\n }", "function dragend(d) {\n\t\n}", "onScrollerDragEnd() {\n\t\tthis.block.setElMod(this.$refs.scroller, 'scroller', 'active', false);\n\t}", "endDrag(x, y) {}", "function flightsDragEndHandler(ev) {\n dragEventCounter--;\n if (dragEventCounter === 0) {\n $(\".drop_box\").hide();\n $(\".internal\").show();\n $(\".external\").show();\n $(\".flights *\").css(\"pointer-events\", \"\");\n }\n}", "function DIF_enddrag(e) {\r\n\tDIF_dragging=false;\r\n//\tDIF_objectDragging.style.cursor=\"auto\";\r\n\tDIF_iframeBeingDragged=\"\";\r\n}", "function dragstop()\r\n{\r\n dragobject = null;\r\n dragging = false;\r\n}", "function endDrag () {\n $element.parents().off( \"mousemove\", handleDrag );\n $element.parents().off( \"mouseup\", endDrag );\n $element[0].dispatchEvent( new CustomEvent(\n ( $element[0].dragType == 4 ) ? 'moved' : 'resized',\n { bubbles : true } ) );\n }", "dragend(){\r\n if ( this.removable ){\r\n this.visibleBin = false;\r\n this.draggedIdx = -1;\r\n }\r\n }", "async onDragEnd() {\r\n this.getParent().updateMovedLocations();\r\n }", "function dropUnstarted(ev) {\n ev.preventDefault(); \n\n let taskId = ev.dataTransfer.getData(\"text/plain\");\n\n move(taskId, 'ongoingTask', 'task');\n move(taskId, 'finishedTask', 'task');\n }", "onElementTouchEnd(event) {\n if (this.dragContext) {\n this.endMove();\n event.preventDefault();\n }\n }", "function dragstop()\n{\n\tdragobject = null;\n\tdragging = false;\n}", "function _onDragEnd() {\n var xCalendars = document.querySelectorAll(\"brick-calendar\");\n for (var i = 0; i < xCalendars.length; i++) {\n var xCalendar = xCalendars[i];\n xCalendar.ns.dragType = null;\n xCalendar.ns.dragStartEl = null;\n xCalendar.ns.dragAllowTap = false;\n xCalendar.removeAttribute(\"active\");\n }\n\n var days = document.querySelectorAll(\"brick-calendar .day[active]\");\n for (var j = 0; j < days.length; j++) {\n days[j].removeAttribute(\"active\");\n }\n }", "onDragStart() {\n isSpinning = false;\n }", "function anadirEventoDulce(){\r\n $('img').draggable({\r\n containment: '.panel-tablero',\r\n\t\tdroppable: 'img',\r\n\t\trevert: true,\r\n\t\trevertDuration: 500,\r\n\t\tgrid: [100, 100],\r\n\t\tzIndex: 10,\r\n\t\tdrag: constrainCandyMovement\r\n });\r\n $('img').droppable({\r\n\t\tdrop: dejaDulce\r\n\t});\r\n activarEventoDulce();\r\n}", "function stopDragHandler (e) {\n DomLibrary.removeClass(DomLibrary.getRootElement(), \"dragging\");\n clearElement(\"drag-proxy\");\n if (!(ourDraggedId === ourInvalidId)) {\n var box = document.getElementById(ourDraggedId);\n DomLibrary.removeClass(box, \"drag-source\");\n ourInstance.visitChildBoxes(box, \"dnd-drop\", resetChildDrop);\n if (!(ourDropId === ourInvalidId)) {\n switch (ourDropWhere) {\n case \"on\":\n doDndBox(ourDraggedId, ourDropId, box);\n break;\n case \"after\":\n doDndBoxAfter(ourDraggedId, ourDropId, box);\n break;\n case \"before\":\n doDndBoxBefore(ourDraggedId, ourDropId, box);\n break;\n default:\n // FIXME: Animate the box returning on failed drop\n break;\n }\n }\n setDropId();\n ourDraggedId = ourInvalidId;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if the trusted FQDN matched the certificate common name
function checkAcmActivationCertName(commonName, trustedFqdn) { commonName = commonName.toLowerCase(); trustedFqdn = trustedFqdn.toLowerCase(); if (commonName.startsWith('*.') && (commonName.length > 2)) { commonName = commonName.substring(2); } return ((commonName == trustedFqdn) || (trustedFqdn.endsWith('.' + commonName))); }
[ "function check_CN(cn, did) {\n\n log.info('verifying CN matches the d3ck ID')\n\n var cmd = 'openssl'\n\n var argz = ['x509', '-noout', '-subject', '-in', d3ck_keystore +'/'+ did + \"/d3ck.crt\"]\n\n cn = d3ck_spawn_sync(cmd, argz)\n\n // subject= /C=AQ/ST=White/L=D3cktown/O=D3ckasaurusRex/CN=8fd983b93ee52e80ddbf457b5ba8f0ec\n\n var disk_cn = cn.substring(cn.indexOf('/CN=')+4)\n\n log.info('cn vs. cn on disk: ' + cn + ' <=> ' + disk_cn)\n\n if (cn == disk_cn)\n return true\n else\n return false\n\n}", "function check_CN(cn, did) {\n\n console.log('verifying CN matches the d3ck ID')\n\n var cmd = 'openssl'\n\n var argz = ['x509', '-noout', '-subject', '-in', d3ck_keystore +'/'+ did + \"/d3ck.crt\"]\n \n var cn = d3ck_spawn_sync(cmd, argz)\n\n // subject= /C=AQ/ST=White/L=D3cktown/O=D3ckasaurusRex/CN=8fd983b93ee52e80ddbf457b5ba8f0ec\n\n var disk_cn = substring(cn.indexOf('/CN=')+4)\n\n console.log('cn vs. cn on disk: ' + cn + ' <=> ' + disk_cn)\n\n if (cn == disk_cn)\n return true\n else\n return false\n\n}", "is3rdPartyToDoc() {\n let docDomain = this.getDocDomain();\n if ( docDomain === '' ) { docDomain = this.docHostname; }\n if ( this.domain !== undefined && this.domain !== '' ) {\n return this.domain !== docDomain;\n }\n const hostname = this.getHostname();\n if ( hostname.endsWith(docDomain) === false ) { return true; }\n const i = hostname.length - docDomain.length;\n if ( i === 0 ) { return false; }\n return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */;\n }", "function isTrustedDomain(domain) {\n\t// Only these are currently trustworthy. The rest of the internet is\n\t// full of no-good wastrels!\n\treturn domain === 'https://www.udacity.com' ||\n\tdomain === 'http://localhost:8080' ||\n\tdomain === 'http://localhost:8087' ||\n\tdomain === 'https://assignments-dot-udacity-extras.appspot.com';\n}", "async has (dir) {\n let subject = await this.getSubject(this.pemFilename);\n let trustStore = new TrustStore(dir);\n\n // Return false if record with this subject is not found\n if (!await trustStore.hasRecords(subject)) {\n return false;\n }\n\n // If record is found, check fingerprints to verify that they didn't change\n let previousFingerprint = await trustStore.getFingerPrintFromRecord(subject);\n let currentFingerprint = await this.getFingerPrint();\n return previousFingerprint.toString() === currentFingerprint.toString();\n }", "validaRfcFromForgeCert({ cer, rfc }) {\n try {\n for (i = 0; i < cer.subject.attributes.length; i++) {\n var val = cer.subject.attributes[i].value.trim();\n if (val == rfc.trim()) {\n return true;\n }\n }\n return false;\n } catch (e) {\n return false;\n }\n }", "isTrusted(context: AnyTrustContext) {\n if (context.url && !context.protocol) {\n context.protocol = utils.protocolFromUrl(context.url);\n }\n const trust = typeof this.trust === \"function\"\n ? this.trust(context)\n : this.trust;\n return Boolean(trust);\n }", "function certExists(cert) {\n return false;\n var actualCert = certdb.constructX509FromBase64(fixupCert(cert));\n try {\n var installedCert = certdb.findCertByNickname(null, actualCert.commonName + \" - \" + actualCert.organization);\n if (installedCert)\n return true;\n } catch(ex) {}\n return false;\n}", "function verifyCert(chain){\n\tconst nsIX509Cert = Ci.nsIX509Cert;\n\tconst nsIX509CertDB = Ci.nsIX509CertDB;\n\tconst nsX509CertDB = \"@mozilla.org/security/x509certdb;1\";\n\tlet certdb = Cc[nsX509CertDB].getService(nsIX509CertDB);\n\tlet cert_obj = certdb.constructX509FromBase64(b64encode(chain[0]));\n\tlet a = {}, b = {};\n\tlet retval = certdb.verifyCertNow(cert_obj, nsIX509Cert.CERT_USAGE_SSLServerWithStepUp, nsIX509CertDB.FLAG_LOCAL_ONLY, a, b);\n\tif (retval === 0){ \t\t//success\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}", "function isCert() {\n\tvar textValue = event.srcElement.value;\n\tvar dExists = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// D (for DAS) has been already introduced?\n\tvar cExists = false;\t\t\t\t\t\t\t\t\t\t\t\t\t// C (for Cardington) has been already introduced?\n\tif ((textValue.length > 0) && ((textValue.substring(0, 1) == \"D\") || (textValue.substring(0, 1) == \"d\")))\n\t\tdExists = 1;\n\tif ((textValue.length > 0) && ((textValue.indexOf(\"C\") != -1) || (textValue.indexOf(\"c\") != -1)))\n\t\tcExists = true;\n\n\tif((event.keyCode == 68) || (event.keyCode == 100))\t\t\t\t\t\t// if D or d\n\t\treturn (textValue.length == 0);\n\telse if((event.keyCode >= 48) && (event.keyCode <= 57))\t\t\t\t\t// if number\n\t\treturn ((textValue.length < 13 + dExists) && !cExists);\n\telse if ((event.keyCode == 67) || (event.keyCode == 99))\t\t\t\t// if C or c\n\t\treturn ((textValue.length >= 1 + dExists) && (textValue.length <= 13 + dExists) && !cExists);\n\treturn false;\n}", "function isPeerDomain(originalURI, redirectURI) {\n if (isSameDomain(originalURI, redirectURI)) {\n // If the domains are the same, then they are peers.\n return true;\n }\n\n var originalScheme = originalURI.scheme.toLowerCase();\n var redirectScheme = redirectURI.scheme.toLowerCase();\n \n // We should allow redirecting to a more secure scheme from a less\n // secure scheme. For example, we should allow redirecting from \n // ws -> wss and wse -> wse+ssl.\n if (redirectScheme.indexOf(originalScheme) == -1) {\n return false;\n }\n\n var originalHost = originalURI.host;\n var redirectHost = redirectURI.host;\n var originalBaseDomain = getBaseDomain(originalHost);\n var redirectBaseDomain = getBaseDomain(redirectHost);\n\n if (redirectHost.indexOf(originalBaseDomain, (redirectHost.length - originalBaseDomain.length)) == -1) {\n // If redirectHost does not end with the base domain computed using\n // the originalURI, then return false.\n return false;\n }\n\n if (originalHost.indexOf(redirectBaseDomain, (originalHost.length - redirectBaseDomain.length)) == -1) {\n // If originalHost does not end with the base domain computed using\n // the redirectURI, then return false.\n return false;\n }\n \n // Otherwise, the two URIs have peer-domains.\n return true;\n }", "function isCloudDomain(domain) {\n return domain.certificateBody !== undefined;\n}", "function passCitizenshipLookup(countryArr) {\n if (sanctionedCountryList.indexOf(countryArr[0]) !== -1 || sanctionedCountryList.indexOf(countryArr[1]) !== -1 || sanctionedCountryList.indexOf(countryArr[2]) !== -1) {\n return false;\n }\n return true;\n}", "async has (dir) {\n let subject = await this.getSubject(this.pemFilename);\n\n let trustStore = new TrustStore(dir);\n let records = await trustStore.getRecords(subject);\n return records.length > 0;\n }", "function cookieMatch(c1, c2) {\n \t return (c1.name == c2.name) && (c1.domain == c2.domain) &&\n \t (c1.hostOnly == c2.hostOnly) && (c1.path == c2.path) &&\n \t (c1.secure == c2.secure) && (c1.httpOnly == c2.httpOnly) &&\n \t (c1.session == c2.session) && (c1.storeId == c2.storeId);\n\t}", "async _isEks(cert) {\n const options = {\n ca: cert,\n headers: {\n Authorization: await this._getK8sCredHeader(),\n },\n hostname: this.K8S_SVC_URL,\n method: 'GET',\n path: this.AUTH_CONFIGMAP_PATH,\n timeout: this.TIMEOUT_MS,\n };\n return !!(await this._fetchString(options));\n }", "function cookieMatch(c1, c2) {\n return (\n c1.name == c2.name &&\n c1.domain == c2.domain &&\n c1.hostOnly == c2.hostOnly &&\n c1.path == c2.path &&\n c1.secure == c2.secure &&\n c1.httpOnly == c2.httpOnly &&\n c1.session == c2.session &&\n c1.storeId == c2.storeId\n );\n}", "static isFQDN (url) {\n let FQDN = new RegExp(/(?:^|[ \\t])((https?:\\/\\/)?(?:localhost|[\\w-]+(?:\\.[\\w-]+)+)(:\\d+)?(\\/\\S*)?)/gm)\n return FQDN.test(url)\n }", "function cookieMatch(c1, c2) {\n return (c1.name == c2.name) && (c1.domain == c2.domain) &&\n (c1.hostOnly == c2.hostOnly) && (c1.path == c2.path) &&\n (c1.secure == c2.secure) && (c1.httpOnly == c2.httpOnly) &&\n (c1.session == c2.session) && (c1.storeId == c2.storeId);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Middleware to check the ownership of campground
function checkCampgroundOwnership(req, res, next) { if (req.isAuthenticated()) { Campground.findById(req.params.id, (err, foundCampground) => { if (err) { res.redirect("back") } else { // if yes, does hes own the campgrounds if (foundCampground.author.id.equals(req.user._id)) { next(); } else { res.redirect("back"); } } }); } else { res.redirect("back"); } }
[ "function checkCampOwnership(req,res,next) {\n\t// is user logged in \n\t\tif(req.isAuthenticated()){\n\t\t\t\t\t// true\n\t\t// does the user own campground?\n\t\t\tCampground.findById(req.params.id,function(err,foundCamp){\n\t\n\t\t\tif(err){\n\t\t\t\tconsole.log(\"couldnt find campground\");\n\t\t\t\treq.flash(\"error\",\"couldnt find campground\");\n\t\t\t\tres.redirect(\"back\");\n\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\t//check if user owns campground\t\t\t\t\n\t\t\t\t//type mismatch so use .equals()\n\t\t\t\tif(foundCamp.author.id.equals(req.user._id))\n\t\t\t\t\t// authorized\n\t\t\t\t\tnext();\n\t\t\t\telse\n\t\t\t\t\t{req.flash(\"error\",\"You dont have permission to do that as you are not the owner of the post!\");\n\t\n\t\t\t\t\tres.redirect(\"back\");\t}\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t\t}else{\n\t\t\treq.flash(\"error\",\"You need to be logged in!\");\n\t\t\tres.redirect(\"/login\");\n\t\t}\n\n}", "function checkCampgroundOwnership(req, res, next){\n if(req.isAuthenticated()){\n Campground.findById(req.params.id, function(err, foundCampground){\n if(err){\n console.log(\"error getting campground by ID!\");\n console.log(err);\n res.redirect(\"back\");\n }else{\n //Check to see if user owns the campground\n if(foundCampground.author.id.equals(req.user._id)){\n //Allow owner to edit campground\n next();\n }else{\n //Don't allow non-owner to edit campground and redirect\n res.redirect(\"back\");\n }\n } \n });\n }else{\n //User is not logged in, so redirect user back to previous page\n res.redirect(\"back\");\n }\n}", "function isCampgroundOwner(req, res, next) {\n if(req.isAuthenticated()) {\n Campground.findById(req.params.id, function(err, campgroundId) {\n if (err) {\n res.redirect(\"back\");\n }\n else {\n if(campgroundId.author.id.equals(req.user._id)) {\n next();\n }\n else {\n res.redirect(\"back\");\n }\n }\n });\n }\n else {\n res.redirect(\"back\");\n }\n}", "function checkCampgroundOwnerShip(req ,res ,next) {\n \n // check user login or not\n if(req.isAuthenticated()){\n Campground.findById(req.params.id , function(err, foundCampground) {\n if (err) {\n console.log(err);\n res.redirect(\"back\"); //redirect to back directory\n \n } else {\n //check autherisation\n if(foundCampground.author.id.equals(req.user._id)){\n next();\n }\n else {\n res.redirect(\"back\");\n }\n }\n });\n \n } else {\n res.redirect(\"/login\");\n }\n}", "function checkOwnership(req, trip) {\n const { visibility: vis } = trip;\n const { method, user } = req;\n\n if (user && user.id === trip.creator.toString()) {\n return trip;\n }\n\n if (vis === 'public' || (vis === 'viewOnly' && method === 'GET')) {\n return trip;\n }\n\n // Return an error as catch-all\n return Promise.reject(createUnauthorizedError());\n}", "function checkCommentOwnership(req,res,next){\n\tif(req.isAuthenticated()){\n\t//does the user own the campground ?\n\t\tComment.findById(req.params.comment_id,function(err,foundComment){\n\t\tif(err){\n\t\t\tres.redirect(\"back\")\n\t\t}else {\n\t\t\tif(foundComment.author.id.equals(req.user._id)){\n\t\t\t\tnext()\n\t\t\t}else {\n\t\t\t\treq.flash(\"error\", \"You don't have permission to do that\");\n\t\t\t\tres.redirect(\"back\")\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t})\n\n\t\t}else{\n\t\t\treq.flash(\"error\", \"You need to be logged in to do that\");\n\t\t\tres.redirect(\"back\") //previous page\n\t\t}\n\t}", "function checkPostOwnership(req, res, next){\n if (req.isAuthenticated()){\n Destination.findById(req.params.id, (error, retDestination)=>{ // if no destination is found (due to wrong id), return empty retDestination)\n if (error || !retDestination){\n req.flash(\"error\", \"Sorry, that post does not exist!\");\n return res.redirect(\"back\")\n } else {\n if (retDestination.author.id.equals(req.user._id)) // does user own campgrounds?\n next()\n else{\n req.flash(\"error\", \"You don't have permission to access this post!\")\n res.redirect(\"/destinations\") // take user back to previous page they were on\n }\n }\n })\n } else {\n req.flash(\"error\", \"Please log in first!\")\n res.redirect(\"/login\"); // take user back to previous page they were on\n }\n}", "function checkOwnership(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n Comment.findById(req.params.comment_id, function (err, foundComment) {\r\n if (err) {\r\n res.redirect(\"back\");\r\n } else {\r\n // console.log(foundCampground.author.id); mongoose object\r\n // console.log(req.user._id) string\r\n if (foundComment.author.id.equals(req.user._id) || req.user.isAdmin) {\r\n next();\r\n } else {\r\n req.flash(\"error\", \"You don't have the permission\");\r\n res.redirect(\"back\");\r\n }\r\n }\r\n });\r\n } else {\r\n req.flash(\"error\", \"You need to be logged in\");\r\n res.redirect(\"back\");\r\n }\r\n}", "function checkPoolOwnership(req, res, next)\n{\n //is user logged in\n if(req.isAuthenticated())\n {\n Pool.findById(req.params.id, function(err, foundPool)\n {\n if(err)\n {\n req.flash(\"error\", \"Pool not found\");\n res.redirect(\"back\");\n }\n else\n {\n //does user own the pool\n if(foundPool.author.id.equals(req.user._id)) // .equals() is a method that comes with mongoose that allows you to compare variables of different types\n {\n next();\n }\n else\n {\n req.flash(\"error\", \"You don't have permission to modify that pool\");\n res.redirect(\"back\");\n }\n }\n });\n }\n else\n {\n req.flash(\"error\", \"Please log in first\");\n res.redirect(\"back\");\n }\n}", "function campsiteOwnershipAuthentication(req, res, next){\n\tif(req.isAuthenticated()){\n\t\tCampsite.findById(req.params.id, function(err, foundCampsite){\n\t\t\tif(err){\n\t\t\t\tres.redirect(\"back\");\n\t\t\t} else {\n\t\t\t\tif(foundCampsite.author.id.equals(req.user._id)) {\n\t\t\t\t\tnext();\n\t\t\t\t} else {\n\t\t\t\t\tres.redirect(\"back\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} else {\n\t\tres.redirect(\"back\");\n\t}\n}", "function middleware(req, res, next){\n switch(action){\n case 'update':\n //\n const owner = req.body.id\n auth.check.own(req,owner) \n next()\n break\n default:\n next()\n }\n }", "function checkCampgroundCreator(req, res, next){\n if(req.session.passport && req.session.passport.user !== undefined){\n Campground.findById(req.params.id, function(err, campground){\n\t\t\t\t\t\t\t\t\tif(err){\n\t\t\t\t\t\t\t\t\t\tres.redirect(\"back\");\n\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\tif(campground.user.id.equals(req.session.passport.user._id)){\n\t\t\t\t\t\t\t\t\t\t\tnext();\n\t\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\t\treturn res.redirect(\"back\")\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})\n }else{\n\t\t\t\t\tres.redirect(\"back\");\n\t\t\t\t}\n\n}", "function checkCommentOwnership(req, res, next){\n if (req.isAuthenticated()){\n Comment.findById(req.params.comment_id, (error, retComment)=>{\n if (error || !retComment){ // if no comment is found (due to wrong id), return empty retComment\n req.flash(\"error\", \"Sorry! That comment does not exist or something went wrong!\")\n console.log(\"Error in checkCommentOwnership(): \", error);\n return res.redirect(\"back\")\n } else {\n if (retComment.author.id.equals(req.user._id)) // does user own campgrounds?\n next()\n else{\n req.flash(\"error\", \"You don't have permission to access this comment!\")\n res.redirect(\"/destinations\") // take user back to previous page they were on\n }\n }\n })\n } else {\n res.redirect(\"/login\"); // take user back to previous page they were on\n }\n}", "function checkCourseOwner(req, res, next) {\r\n const {educatorId} = req.body.course;\r\n console.log(req.user)\r\n const {user} = req;\r\n if (user.userType === \"admin\" || user.id === educatorId) {\r\n return next();\r\n }\r\n\r\n return next(new HTTPError(422, \"Unauthorised\"))\r\n}", "function checkOwnership(req, res, next){\n\t// is User logged in?\n\tif (req.isAuthenticated){\n\t\t\t\t//if yes, then...\n\t\t\t\tToDo.findById(req.params.id, function(err, user) { // finds all Blogs in database\n\t\t\t\t\tif(err){\n\t\t\t\t\t\tres.direct('back');\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// does the user own the blog? If yes....\n\t\t\t\t\t\tif (user.author.id.equals(req.user._id)) {\n\t\t\t\t\t\tnext();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If no....\n\t\t\t\t\t\tres.send('You do not have permission to do that')\n\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t});\n\t\t}\n}", "function authorizeOnlyToCompanyMembers(req, res, next){\n //check if member is the member of the company \n const isMember = req.resources.company.members.find((member) => {\n return member.toString() === req.user._id.toString();\n });\n if(!isMember) {\n return res.status(403).json({message:'Unauthorized member'});\n }\n next();//go to the next middlewares\n\n\n}", "function ensureOwnership(req,res,next){\n var id = req.body.table_id;\n Tables.findById(id,function(err,table){\n if (err) return res.send(500,{error: \"database error\"});\n if (table.members.indexOf(req.user._id) !== -1){\n return next();\n } else {\n return res.send(401, {error:\"You don't have access to this document\"})\n }\n });\n }", "function checkOwnerShip(req , res , next){\r\n if(req.isAuthenticated()){\r\n Item.findById(req.params.id , (err , itemfound)=>{\r\n if(err){\r\n req.flash(\"error\" , \"Item not found\")\r\n res.redirect(\"back\")\r\n }else{\r\n // the user owns it or not\r\n if((itemfound.author.id).equals(req.user._id)){\r\n next();\r\n }else{\r\n req.flash(\"error\" , \"You are not allowed to do that\")\r\n res.redirect(\"back\");\r\n }\r\n }\r\n })\r\n }else{\r\n req.flash(\"error\" , \"You need to login to do that\")\r\n res.redirect(\"back\");\r\n }\r\n}", "function checkAuthorized(done) {\n\n if (this.req.resourceset.owner !== this.req.user.id)\n return done(error('not_owner',\n 'Party requesting permission is not owner of resource set, expected'));\n\n done();\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
judging is a pair of brackets valid or not
function isBracketValid(Look) { try { var Bracket = new Array(); for (var i = 0; i < Look.length; i++) { if (Look[i] == "(" || Look[i] == ")") { Bracket.push(Look[i]); } } if (Bracket.length % 2 != 0) throw "odd Brackets"; var count1 = 0, count2 = 0; for (i = 0; i < Bracket.length; i++) { if (Bracket[i] != "(") { ++count1; } if (Bracket[i] != ")") { ++count2; } } if (count2 != count1) throw "Brackets dispair"; return true; } catch(Error) { alert(Error); ClearAll(); } }
[ "static validateTagParentheses(s) {\n let open = 0;\n let index = 0;\n for (let j = 0; j < s.length; j++) {\n let i = s[j];\n if (i === \"[\") {\n if (s[index-1]) {\n if (s[index-1] !== \"/\") {\n open++;\n }\n } else {\n open++;\n }\n }\n if (i === \"]\") {\n if (s[index-1]) {\n if (s[index-1] !== \"/\") {\n if (open > 0) {\n open--;\n } else {\n return false;\n }\n }\n } else {\n if (open > 0) {\n open--;\n } else {\n return false;\n }\n }\n }\n index++;\n }\n if (open === 0) {\n return true;\n } else {\n return false;\n }\n }", "function parensValid(string){\n \n \n}", "function checkBrackets(value){\n\n checkX();\n // this part of code is to make sure I can put a ( in... it is a very sad if if if function.\n if(operatorUsed === true) {\n\n if (operatorafterBracket === false) {\n if (value === \"(\") {\n valueBetweenBracket = false;\n operatorUsed = true;\n leftBracket += 1;\n x += \"(\";\n updateDisplay();\n return;\n }\n }\n }\n\n if (value === \")\") {\n if (valueBetweenBracket === true) {\n if (leftBracket > rightBracket) {\n leftBracket -= 1;\n operatorafterBracket = true;\n x += \")\";\n updateDisplay();\n return;\n }\n }\n\n }\n\n\n\n\n}", "function checkBracketErrors(oneLine, linenum){\n//check for basic bracket errors\n\tvar state = '';\n\tvar len = oneLine.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tswitch(state){\n\t\tcase '':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '{': case '[': case '<':\n\t\t\t\tstate = oneLine[i]; break;\n\t\t\tcase '}': case ']': \n\t\t\t\treturn 'There is an extra \\'' + oneLine[i] + '\\' on line ' + linenum + '.';\n\t\t\tcase '>':\n\t\t\t\treturn 'There is an extra \\'&lt;\\' on line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '[':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase ']':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': case '}':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tcase '<':\n\t\t\t\treturn 'There is an unexpected \\'&lt;\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tcase '>':\n\t\t\t\treturn 'There is an unexpected \\'&gt;\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '{':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '}':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': case ']':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\'}\\' in line ' + linenum + '.';\n\t\t\tcase '<':\n\t\t\t\treturn 'There is an unexpected \\'&lt;\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tcase '>':\n\t\t\t\treturn 'There is an unexpected \\'&gt;\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '<':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '>':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': \n\t\t\tcase ']':case '}':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\'>\\' in line ' + linenum + '.'\n\t\t\tcase '<':\n\t\t\t\treturn 'There is an unexpected \\'&lt;\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(state !== '') return 'A \\'' + state + '\\' bracket on line ' + linenum + ' is not closed.';\n}", "function checkBracketErrors(oneLine, linenum){\n//check for basic bracket errors\n\tvar state = '';\n\tvar len = oneLine.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tswitch(state){\n\t\tcase '':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '{': case '[': case '<':\n\t\t\t\tstate = oneLine[i]; break;\n\t\t\tcase '}': case ']': case '>':\n\t\t\t\treturn 'There is an extra \\'' + oneLine[i] + '\\' on line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '[':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase ']':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': case '<':\n\t\t\tcase '}':case '>':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\']\\' in line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '{':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '}':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': case '<':\n\t\t\tcase ']':case '>':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\'}\\' in line ' + linenum + '.';\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '<':\n\t\t\tswitch(oneLine[i]){\n\t\t\tcase '>':\n\t\t\t\tstate = ''; break;\n\t\t\tcase '{': case '[': case '<':\n\t\t\tcase ']':case '}':\n\t\t\t\treturn 'There is an unexpected \\'' + oneLine[i] + '\\' before an expected \\'>\\' in line ' + linenum + '.'\n\t\t\tdefault:\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(state !== '') return 'A \\'' + state + '\\' bracket on line ' + linenum + ' is not closed.';\n}", "function validPar(str){\n var count = 0;\n for(var i = 0; i < str.length; i ++){\n if(str[i] == \"(\"){\n count++;\n }\n if(str[i] == \")\"){\n count--;\n }\n if(count < 0){\n return false;\n }\n }\n return true; \n }", "static validateBrackets (stringDefinition = ''){\n let leftBraceCount = (stringDefinition.match ('{') || []).length;\n let rightBraceCount = (stringDefinition.match ('}') || []).length;\n let leftParenCount = (stringDefinition.match ('(') || []).length;\n let rightParenCount = (stringDefinition.match (')') || []).length;\n let leftBoxBracketCount = (stringDefinition.match ('[') || []).length;\n let rightBoxBracketCount = (stringDefinition.match (']') || []).length;\n\n // If there are any braces, parentheses, or box brackets without pair, throw an error\n if (leftBraceCount != rightBraceCount ||\n leftParenCount != rightParenCount ||\n leftBoxBracketCount != rightBoxBracketCount) {\n\n let errorMessage = 'Not all brackets are closed';\n if (leftBraceCount != rightBraceCount) {\n errorMessage += `\\n\\tThere are ${leftBraceCount} '{' and ${rightBraceCount} '}'`;\n }\n if (leftParenCount != rightParenCount) {\n errorMessage += `\\n\\tThere are ${leftParenCount} '(' and ${rightParenCount} ')'`;\n }\n if (leftBoxBracketCount != rightBoxBracketCount) {\n errorMessage += `\\n\\tThere are ${leftBoxBracketCount} '[' and ${leftBoxBracketCount} ']'`;\n }\n throw new Error (errorMessage);\n }\n\n }", "function checkBrackets(str) {\n const openingBraces = [];\n for (let i = 0; i < str.length; i++) {\n // console.log(\"iteration: \", i);\n // console.log(`str[${i}] = ${str[i]}`);\n if (str[i] === \"(\") {\n openingBraces.push(str[i]);\n } else if (str[i] === \")\") {\n const poppedBrace = openingBraces.pop(); // [].pop() will remove the last element from an array and return it\n // console.log(\"poppedBrace: \", poppedBrace);\n if (!poppedBrace) { //\n return false;\n }\n }\n // console.log(\"==============\");\n }\n\n // console.log(\"openingBraces length: \", openingBraces.length);\n if (openingBraces.length !== 0) {\n return false\n } else {\n return true;\n }\n }", "function checkBrackets(expression){\n expression = expression.toString();\n var countOpened = 0;\n var countClosed = 0;\n var flagOpen = true;\n //Actualmente no soporta una expresion (( ) ( )) xD, solo ((( )))\n //Funciona bien para los examples\n for (var i = 0; i < expression.length ;i++)\n {\n if(expression[i] == \"(\")\n {\n countOpened +=1;\n if(flagOpen==false){\n return false;\n }\n }\n if(expression[i]==\")\"){\n flagOpen= false;\n countClosed +=1;\n }\n }\n if (countOpened == countClosed){\n return true;\n }\n return false;\n}", "function bracketsAllowed(str) {\n let open_bracket_idx = str.search(\"\\\\(\");\n let closed_bracket_idx = str.search(\"\\\\)\");\n if (open_bracket_idx == -1 || closed_bracket_idx == -1) {\n return true;\n }\n if (closed_bracket_idx - open_bracket_idx == 4) {\n return true;\n }\n return false;\n}", "matchBrackets() {\n const inputLength = this.inputExpression.length;\n for (let i = 0; i < inputLength; i++) {\n const char = this.inputExpression.charAt(i);\n switch (char) {\n case \"(\":\n case \"[\":\n case \"{\":\n this.stack.push(char);\n break;\n case \"]\":\n case \")\":\n case \"}\":\n if (!this.stack.isEmpty()) {\n const tmpChar = this.stack.pop();\n if (\n (tmpChar !== \"{\" && char == \"}\") ||\n (tmpChar !== \"[\" && char == \"]\") ||\n (tmpChar !== \"(\" && char == \")\")\n ) {\n this.isExpressionValid = false;\n this.errorCode = ErrorConstant.NO_MATCHING_OPENING_BRACKETS(\n char,\n this.inputExpression\n );\n }\n } else {\n this.isExpressionValid = false;\n this.errorCode = ErrorConstant.EXTRA_CLOSING_BRACKETS(\n char,\n this.inputExpression\n );\n }\n break;\n }\n // break the loop on the first mistake.\n if (!this.isExpressionValid) {\n break;\n }\n }\n if (this.isExpressionValid) {\n // There is still possibility that extra brackets being present here.\n if (!this.stack.isEmpty()) {\n this.isExpressionValid = false;\n this.errorCode = ErrorConstant.EXTRA_OPENING_BRACKETS(\n this.inputExpression\n );\n }\n }\n }", "function validBraces(braces) {\n\tlet stack = [];\n\tlet strEx = '({[';\n\tlet strEx2 = ')}]';\n\tbraces = braces.split('');\n\tbraces = braces.map(el => {\n\t\tif (strEx.indexOf(el) >= 0) {\n\t\t\tstack.push(el);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tlet rem = stack.pop();\n\t\t\treturn strEx.indexOf(rem) == strEx2.indexOf(el);\n\t\t}\n\t});\n\tbraces = braces.every(el => el) && stack.length == 0;\n\treturn braces;\n}", "function parensValid(string) {\r\n}", "function paren_valid(str){\n var count=0;\n for(var i=0;i<str.length;i++){\n if(str.charAt(i)==\"(\") // add 1 for left (\n count+=1;\n else if (str.charAt(i)==\")\") // minus 1 for right )\n count-=1;\n if (count<0) // if the count isn't 0 then they are not even\n return false;\n }\n return count === 0\n }", "function ValidBrackets(str, openToClose, closeToOpen) {\n\treturn (ValidParens(str, openToClose, closeToOpen));\n}", "function parensValid(str) {\n for (i=0;i<str.length/2;i++){\n j=str.length-1-i\n if(str[i]==\"(\"&&str[j]!=\")\"){\n return \"False\"\n }\n else if(i==j || i==j-1) {\n return \"True\"\n }\n }\n}", "function validParentheses(parens){\n let stack = 0;\n for (let char of parens.split(\"\")) {\n if (char === \")\" && stack === 0) {return false;}\n else if (char === \")\") {stack--;}\n else {stack++;}\n }\n return stack === 0;\n}", "function areBracketsOk(arr){\r\n let nOpen=0;\r\n let nClose=0;\r\n\r\n for (var i=0;i<arr.length;i++){\r\n if (arr[i]=='(') nOpen+=1;\r\n\r\n if (arr[i]==')') nClose+=1;\r\n\r\n if (nClose>nOpen){\r\n console.log('Opening bracket is missing');\r\n return 0;\r\n }\r\n if(i>0 && arr[i-1]=='(' && arr[i]==')'){\r\n console.log('Empty brackets detected');\r\n return 0;\r\n }\r\n\r\n if(i>0 &&(arr[i-1])==')' && (numbers.indexOf(arr[i]))!=-1){\r\n console.log('impossible to have a number after a closing bracket');\r\n return 0;\r\n }\r\n\r\n if(i>0 &&(arr[i])=='(' && (numbers.indexOf(arr[i-1]))!=-1){\r\n console.log('impossible to have a number before an opening bracket');\r\n return 0;\r\n }\r\n }\r\n return (nOpen==nClose)?1:0;\r\n}", "function correctBrackets(expression) {\n var count = 0;\n for (var i = 0; i < expression.length; i++) {\n if (expression[i] === '(') {\n count++;\n }\n if (expression[i] === ')') {\n count--;\n }\n }\n if (count !== 0 || expression[0] === ')' || expression[expression.length - 1] === '(') {\n console.log('No, there is something wrong!');\n }\n else {\n console.log('The brackets are put correctly!');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the validity of every text input field on the page. Scans all of the text input objects and checks their validity, marking them as appropriate.
function checkAll() { jQuery("input[type='text']").each(function() { check(this, this.name); }); }
[ "function SP_ValidateTextFields() {\n\tvar pageList = new String(mcEditablePages).split(','),\n\t\ttxtVal = '';\n\n\tif (SP_Trim(pageList) !== '') {\n\t\tfor (var i = 0, l = pageList.length; i < l; ++i) {\n\t\t\tvar pageId = +SP_Trim(pageList[i]) + 1;\n\t\t\t\n\t\t\tif (pageId > 2) {\n\t\t\t\tif (pageId < 10) {\n\t\t\t\t\tpageId = 'mcPage_00' + pageId;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpageId = 'mcPage_0' + pageId;\n\t\t\t\t}\n\t\n\t\t\t\t$('#' + pageId).find('textarea').each(function (IndexInput) {\n\t\t\t\t\tif ($(this).css('display') !== 'none' && $(this).val().length > 0) {\n\t\t\t\t\t\t$(this).trigger('onkeyup');\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t$('#' + pageId).find(':text').each(function (IndexInput) {\n\t\t\t\t\tif ($(this).css('display') !== 'none' && $(this).val().length > $(this).attr('maxlength')) {\n\t\t\t\t\t\ttxtVal = $(this).val();\n\t\t\t\t\t\ttxtVal = txtVal.substring(0, $(this).attr('maxlength'));\n\t\t\t\t\t\t$(this).val(txtVal);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}", "function runValidators() {\n $('input[type=text]').not('#imgurl').each(function(){validateField(this);});\n validateImageUrl();\n validateImageFile();\n}", "function validateFields() {\n const validators = {\n \"#txtEpisode\": hasValidEpisodeNumber,\n \"#txtTitle\": hasNonEmptyString,\n \"#txtCrawl\": hasNonEmptyString\n };\n Object.entries(validators).forEach(([sel, fn]) => {\n const fld = document.querySelector(sel);\n if (fn(fld.value)) {\n fld.parentNode.classList.remove(\"error\");\n } else {\n fld.parentNode.classList.add(\"error\");\n }\n });\n}", "function validateAll()\r\n{\r\n\tfor (var i = 0; i < theFormValidations.length; i++) \r\n {\r\n\t\tvar field = document.getElementById(theFormValidations[i].id);\r\n\t\tif (!isEmpty(field.value)) validate(field);\r\n\t} // end for (var i = 0; i < theFormValidations.length; i++) \r\n}", "function checkOnSubmit(){\n\t\n\tvar errClassArray = document.getElementsByClassName(\"error\");\n\tvar inputClassArray = document.getElementsByClassName(\"userInput\");\n\tvar errClassLength = errClassArray.length;\n\tvar inputClassLength = inputClassArray.length;\n\t\n\t//Check userInput class values. Flag first blank\n\tvar inputCheckValue = \"\"; //Get value of all \"userInput\" class values\n\tfor(var i = 0; i < inputClassArray.length; i++){\n\t\tinputCheckValue = inputClassArray[i].value;\n\t\tif(inputCheckValue == \"\"){\n\t\t\talert(\"Your input contains blank fields. Please fill out completely\");\n\t\t\tinputClassArray[i].focus();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//Check all error class innerHTML. If blank, then there is no error.\n\tvar errCheckValue =\"\";//Stores value of innerHTML \"error\" class <p> tags\n\tfor(var i = 0; i < errClassLength; i++){\n\t\terrCheckValue = errClassArray[i].innerHTML;\n\t\t\n\t\t//If not blank get previous sibling from DOM and set focus\n\t\tvar prevSibID = \"\";\n\t\tif(errCheckValue != \"\"){\n\t\t\tprevSibID = errClassArray[i].previousSibling.previousSibling.id;\n\t\t\talert(\"Your input containes Error(s). Please correct the indicated fields\");\n\t\t\tdocument.getElementById(prevSibID).focus();\n\t\t\tbreak;\n\t\t}\n\t}\t\t\t\t\t\n}", "function checkFields () {\n var everythingGood = true\n\n // date\n const year = DOM('editor_year').value\n const month = DOM('editor_month').value\n const day = DOM('editor_day').value\n\n if (year != null && month != null && day != null) {\n // padding with 0's\n var m = month.toString().length < 2 ? \"0\" + month : month\n var d = day.toString().length < 2 ? \"0\" + day : day\n\n var dateval = \"\"\n dateval += \"\" + year\n dateval += \"-\" + m\n dateval += \"-\" + d\n\n var date = new Date(dateval)\n const isDate = date.toString() !== \"Invalid Date\"\n\n if (!isDate) {\n DOM(\"editor_day\").classList.add('error-field')\n DOM(\"editor_month\").classList.add('error-field')\n DOM(\"editor_year\").classList.add('error-field')\n everythingGood = false\n \n }\n\n } else {\n DOM(\"editor_day\").classList.add('error-field')\n DOM(\"editor_month\").classList.add('error-field')\n DOM(\"editor_year\").classList.add('error-field')\n everythingGood = false\n }\n\n // place\n // only check if its not empty\n const locval = DOM(\"editor_place\").value\n if (!locval || locval === \"\") {\n DOM(\"editor_place\").classList.add('error-field')\n everythingGood = false\n }\n\n return everythingGood\n}", "function checkFormValidity() {\n var inputs = document.querySelectorAll('input'),\n i;\n\n for (i = 0; i < inputs.length; i = i + 1) {\n customCheckValidity(inputs[i]);\n }\n }", "function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_admin,\"+LANG_LOCALE['12140'];\n txtFieldIdArr[1] = \"tf1_guest,\"+LANG_LOCALE['12141'];\n \n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, '\\'\" ', NOT_SUPPORTED) == false) \n return false;\n \n var myObj = document.getElementById('tf1_admin');\n if (numericValueRangeCheck(myObj, '', '', 0, 999, true, LANG_LOCALE['11205'], '') == false) \n return false;\n \n myObj = document.getElementById('tf1_guest');\n if (numericValueRangeCheck(myObj, '', '', 0, 999, true, LANG_LOCALE['11270'], '') == false) \n return false;\n \n return true;\n \n}", "function checkFormInputs() {\n enableUpdateButton([minNumField, maxNumField]);\n checkValidMinMaxInput([minNumField, maxNumField]);\n enableClearButton();\n enableSubmitButton(challengerInputFields);\n checkValidGuessInput();\n}", "validateOnEntry() {\n let self = this\n this.fields.forEach(field => {\n const input = document.querySelector(`#${field}`)\n\n input.addEventListener('input', () => {\n self.validateFields(input)\n })\n })\n }", "function checkAllInputs() {\n checkUsername(username, usernameErrMsg);\n checkEmail(email, emailErrMsg);\n checkPassword(password, passwordErrMsg);\n passwordMatch(password, password2, password2ErrMsg);\n}", "validateAll () {\n for (let fieldID of Object.keys(this.fields)) {\n this.fields[fieldID].validate()\n }\n }", "function register_text_fields()\r\n {\r\n var tg = document.getElementsByTagName(\"INPUT\");\r\n\r\n if(tg)\r\n {\r\n for(var i = 0; i < tg.length; i++)\r\n register_input_field(i);\r\n }\r\n\r\n tg = document.getElementsByTagName(\"TEXTAREA\");\r\n\r\n if(tg)\r\n {\r\n for(var i = 0; i < tg.length; i++)\r\n register_textarea_field(i);\r\n }\r\n }", "function validateAll(formObj, requiredfieldids) {\n\tvar reqfieldidArr = requiredfieldids.split(':');\n\tvar notvalidatedArr = requiredfieldids.split(':');\n\tvar errstr = '';\n\t\n\t//Check to make sure ranges are all correct\n\tvar rangeElement = 'js_range';\n\tif (document.getElementById(rangeElement)) {\n\t\terrstr += validateRangeComplex(document.getElementById(rangeElement).value);\n\t}\n\t//Check to make sure dates are all correct\n\tvar dateElement = 'js_date';\n\tif (document.getElementById(dateElement)) {\n\t\terrstr += validateDateComplex(document.getElementById(dateElement).value);\n\t}\n\t\n\tfor (var i=0; i < (formObj.elements.length -1); i++) {\n elem = formObj.elements[i];\n\t\tisRequired = false;\n\n\t\tif (elem.id) {\n\t\t\tif (arrElementExists(notvalidatedArr, elem.id) != -1) {\n\t\t\t\tnotvalidatedArr = arrElementDelete(notvalidatedArr, elem.id);\n\t\t\t\tisRequired = true;\n\t\t\t}\n\t\t}\n \n\t\t//Start Use Complex validation\n\t\t//Due to the nature of how js_allowhtml, js_date and js_range are used, they are\n\t\t//omitted from this list\n\t\tcomplexValidations = new Array('js_number', 'js_alphanum');\n\t\tfor (valType in complexValidations) {\n\t\t\tuseValidation = useComplexValidation(elem, complexValidations[valType]);\n\t\t\t\n\t\t\tif (useValidation) {\n\t\t\t\terrstr += validateElementComplex(elem, complexValidations[valType]);\n\t\t\t}\n\t\t}\n\t\t//End Use Complex Validations\n\t\t\t\t\n\t\t\n\t\tif (isRequired) {\n\t\t\terrstr += validateElement(elem, 1);\n\t\t}\n\t\telse {\n\t\t\terrstr += validateElement(elem, 0);\n\t\t}\n\t}\n\tif(errstr != \"\") {\n\t\talert(errstr);\n\t\treturn false;\n\t}\n\treturn true;\n}", "function _getElements()\n\t\t{\n\t\t\tvar inputs = _getForm().find('input, textarea');\n\t\t\tvar element = new Array();\n\t\t\tvar validation = true;\n\t\t\tfor(var i = 0; inputs.length >= i; i++) \n\t\t\t{\n\t\t\t\tif($(inputs[i]).attr('data-validation'))\n\t\t\t\t{\n\t\t\t\t\telement[$(inputs[i]).attr('name')] = $(inputs[i]).attr('data-validation');\n\t\t\t\t\t_removeErrorMessage($(inputs[i]));\n\t\t\t\t\t\n\t\t\t\t\tvar validations = _rulesElements($(inputs[i]), element[$(inputs[i]).attr('name')]);\n\t\t\t\t\t\n\t\t\t\t\tif(validations==false)\n\t\t\t\t\t{\n\t\t\t\t\t\tvalidation = validations;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tif(validation == true)\n\t\t\t{\n\t\t\t\t_submitForm(_getForm());\n\t\t\t}\n\t\t}", "function verifyFields(){\n let fieldTexts = document.getElementsByClassName('input-field');\n let hasAllvalues = true;\n for(let i = 0; i < fieldTexts.length; i++){\n if(!fieldTexts[i].value){\n hasAllvalues = false;\n }\n }\n return hasAllvalues;\n}", "function mdlCleanUp(){\n var mdlInputs = doc.querySelectorAll('.mdl-js-textfield');\n for (var i = 0, l = mdlInputs.length; i < l; i++) {\n mdlInputs[i].MaterialTextfield.checkDirty();\n } \n }", "function checkAllInputFields() {\n //run for the first time (run on method change [without change in equation input]):\n if (isAllValid()) calcBtn.prop('disabled', false)\n else calcBtn.prop('disabled', true)\n\n // bind it:\n equationCard.find('input[type!=submit]:visible').bind('keyup change', () => {\n if (isAllValid()) calcBtn.prop('disabled', false)\n else calcBtn.prop('disabled', true)\n })\n }", "function validate()\n{\n var faultFound = false;\n var msg = \"The form has been completed incorrectly.\\n\\n\";\n\n // test runsScored[1-8] for NaN and \"\"\n for (i = 1; i <= 8 && !faultFound; ++i)\n {\n var runsScored = document.getElementById(\"runsScored\" + i).value;\n\n if (runsScored === \"\" || isNaN(runsScored))\n {\n faultFound = true;\n msg += \"An integer must be entered in the 'Runs Scored' field for each batsman.\\n\";\n }\n }\n\n // test runsConceded[1-16] and wicketsTaken[1-16] for NaN and \"\"\n for (i = 1; i <= 16 && !faultFound; ++i)\n {\n var wicketsTaken = document.getElementById(\"wicketsTaken\" + i).value;\n var runsConceded = document.getElementById(\"runsConceded\" + i).value;\n\n if ( wicketsTaken === \"\" || isNaN(wicketsTaken)\n || runsConceded === \"\" || isNaN(runsConceded))\n {\n faultFound = true;\n msg += \"An integer must be entered in the 'Wickets Taken'\";\n msg += \" and 'Runs Conceded' field for each bowler.\\n\";\n }\n }\n\n if (faultFound)\n {\n alert(msg);\n return false;\n }\n else\n return true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adjust s.no. column data in the table
function adjustSno(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=1; i<rowCount; i++) { table.rows[i].cells[0].innerHTML = i; } }
[ "function updateDataCol (tr, col, s) {\n Doc.tmplElement(tr, col).textContent = s\n}", "function updateNumCol() {\n if (hasNumCol()) {\n i = 1;\n var rowSpan = 0;\n var rowSpanCount = 0;\n\n each(table.rows, function(tr, y) {\n tr = $(tr);\n\n if (AJS.Rte.Table.areCellsHeadings(tr.children())) {\n tr.children(':first')\n .addClass('numberingColumn')\n .attr('contenteditable', 'true');\n } else if (rowSpanCount > 0) {\n rowSpanCount--;\n } else {\n tr.children(':first')\n .html(i)\n .attr('contenteditable', 'false')\n .addClass('numberingColumn');\n\n rowSpan = tr.children(':first').attr('rowspan');\n if (rowSpan > 1) {\n rowSpanCount = rowSpan - 1;\n }\n\n i++;\n }\n });\n }\n }", "function renumberColumns(){\n\t\t$(table + \"tr:first td\").each(function(i){\n\t\t\t$(this).attr(\"id\", i+1);\t\n\t\t});\n\t}", "function assignColumnNumber(e) {\n //add data params\n for (var i = 0; i < cell.length; i++) {\n cell[i].dataset.column = i % 7;\n cell[i].dataset.cell = i;\n }\n}", "function UpdateSN(tableName) {\n var rows = $('#' + tableName + ' tbody tr');\n var sn = 0;\n rows.each(function () {\n sn++;\n $(\"td:nth-child(1)\", this).html(sn);\n });\n}", "function fixColspan(row)\r\n{\r\n var tdElem = row.getElementsByTagName('td')[0];\r\n var oldColspan = parseInt(tdElem.getAttribute('colspan'));\r\n tdElem.setAttribute('colspan', oldColspan+4);\r\n}", "function reOrderCols() {\n\t\n}", "dosageColumn(cell, row) {\r\n let obj = this.state.uomData.find(x => x.Id == row['DosageUoMId']);\r\n return obj ? row['Dosage'] + ' ' + (obj.Name || '') : '';\r\n }", "function update_row_data(row_data) {\n for (var big = 0; big < row_data.length; big++) {\n if (row_data[big][0] != 'text') {\n for (var small = 0; small < row_data[big][1].length; small++) {\n var add_on = [\n [big, small, row_data[big][1].length]\n ];\n row_data[big][1][small] = row_data[big][1][small].concat(add_on);\n }\n }\n }\n}", "function updateRowNumberColumn() {\n // Update row number column size\n if (component.controller.rowNumbers) {\n // Get string size\n var rowNumberColumnSize = (String(getLastRecord()).length + 1) * component.scope.charSize;\n // Change column width\n var column = grid.api.grid.getColumn(\"rowNum\");\n var prevRowNumberWidth = column.width;\n if (prevRowNumberWidth !== rowNumberColumnSize) {\n column.width = Math.max(column.minWidth, rowNumberColumnSize);\n finishPendingActions();\n }\n }\n }", "function setInterpreterTableColumnCount(newValue) {\r\n\tcurrentK=getSetColumnCount();\r\n\tif (isNaN(currentK) || newValue==currentK) {\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tif (newValue<currentK) {\r\n\t\tremoveInterpreterTableColumns(currentK-newValue);\r\n\t} else {\r\n\r\n\t\taddInterpreterTableColumns(newValue-currentK);\r\n\t}\r\n\t$(\".spanningHeadCol\").attr(\"colspan\",currentK+1);\r\n}", "_fillColumn (col, data, tableOffset, tableHeight, column, x)\n {\n for (let i=0; i<MONTHS_IN_YEAR.length; i++)\n {\n let obj = data[i];\n\n for (let key in obj)\n {\n if (key === column)\n {\n let text = obj[key];\n if (typeof(obj[key]) === 'number')\n text = obj[key].toFixed(1);\n\n col.append('tspan')\n .attr('id', column + '_c' + i)\n .attr('class', 'cell')\n .attr('x', x)\n .attr('y', (tableHeight * (i+1)) + tableOffset)\n .style('text-align', 'right')\n .text(text)\n }\n }\n }\n }", "function table_modify(increment) {\n // set the first measurement that isn't an integer. table.rows will grab the row at the specified index in brackets. selecting the cells[0] means the left most td's are selected in that row. these are html collections and also have many properties. inner html and inner text are among them and therefore can be updated\n table.rows[1].cells[0].innerText = (1 - increment).toFixed(2) + '\\' down';\n // table.rows[1].cells[0].innerText = '0.3\\' feet down';\n // now, loop through the rest of the table body, starting after the first row that was changed, in this case at j = 2.\n for(j = 2; j <= table.rows.length - 1; j++) {\n // subtracting 0.7 from j will give the correct feet down increments. to update the right cells with this value, use table.rows[j].cells[0].innerText\n table.rows[j].cells[0].innerText = j - increment + '\\' down';\n }\n } // ends table_modfy function", "function adjustMessageTable() {\n\t\tif ( ! that.messageTable ) {\n \t\t\tthrow new Error(\"There is no message table to adjust.\");\n \t\t}\n\t\tfor(var i=0;i < that.messageTable.rows.length;i++){\n \t\t\tvar cell = that.messageTable.rows[i].insertCell(0);\n\t\t\tcell.width=\"1%\";\n \t\t}\n\t}", "_onColumnChange(e){this.selected=e.detail.value;this._updateCols(parseInt(e.detail.value))}", "updateNumericalColumn(colDesc) {\n const column = this.lineUpRef.current.adapter.data.find(d => d.desc.type === 'number' && d.desc.column === colDesc);\n if (column !== null) {\n const values = this.props.data.map(d => d[colDesc]).filter(d => !Number.isNaN(d));\n column.setMapping(new ScaleMappingFunction([Math.min(...values), Math.max(...values)], 'linear'));\n }\n }", "function numberingList_safety_stock(){\n\t\t$('#tabel_safety_stock_bahanBaku tbody tr').each(function (index) {\n\t $(this).children(\"td:eq(0)\").html(index + 1);\n\t });\n\t}", "calculateCharsAttr() {\n this.sizes.forEach(column => {\n if (!column.size) {\n if (column.inputSizeFromCharsAttr) {\n if (column.inputColumnsSize < column.inputSizeFromCharsAttr) {\n column.size = column.inputSizeFromCharsAttr;\n } else {\n if (column.columnNoExpand || column.onlyOneRowInColumn) {\n column.size = column.inputSizeFromCharsAttr;\n } else {\n column.size = column.inputColumnsSize;\n }\n }\n } else {\n column.size = column.inputColumnsSize;\n }\n }\n });\n }", "updateLineUp() {\n this.props.columnDefs.filter(def => def.datatype === 'number' && def.domain.length === 0).forEach((def) => {\n this.updateNumericalColumn(def.column);\n });\n this.lineUpRef.current.adapter.data.setData(this.props.data);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
start watching beacon signal
watch () { dbg('watch') this.delegate = new cordova.plugins.locationManager.Delegate() cordova.plugins.locationManager.setDelegate(this.delegate) // Declare regions let beaconRegion = new cordova.plugins.locationManager.BeaconRegion(this.beacons.identifier, this.beacons.uuid, this.beacons.major, this.beacons.minor) cordova.plugins.locationManager.startRangingBeaconsInRegion(beaconRegion) .fail(function (e) { console.error(e) }) .done() }
[ "async start(){\r\n // do full scan first so we have state that can change\r\n await this.rescan()\r\n\r\n this.chokidar = chokidar.watch([this.watchPath], {\r\n persistent: true,\r\n ignoreInitial : true,\r\n awaitWriteFinish: {\r\n stabilityThreshold: 2000,\r\n pollInterval: 100\r\n }\r\n });\r\n \r\n // start watched for file changes\r\n this.chokidar\r\n .on('add', p =>{\r\n this._registerFileChange(p, 'add')\r\n })\r\n .on('change', p =>{\r\n this._registerFileChange(p, 'change')\r\n })\r\n .on('unlink', p =>{\r\n this._registerFileChange(p, 'delete')\r\n })\r\n }", "function activateBeacon() {\n radio.beacon=true;\n}", "function activateBeacon() {\n radio.beacon = true;\n}", "startWatch() {\n if (!this._watching) {\n this._changed = false;\n this._watching = true;\n }\n }", "function startWatching() {\r\n\t\tstatus = INITIALISING;\r\n\t\twatch_id = navigator.geolocation.watchPosition(change, error/*, config*/);\r\n\t}", "function activateBeacon(){\n radio.beacon = 'true';\n}", "start() {\n var watcher = this;\n fs.watchFile(watchDir, function() {\n watcher.watch();\n });\n }", "function scanStart(){\n console.log('Scan Start!');\n noble.startScanning([], true);\n noble.on('discover', discovered);\n}", "_startWatch()\n\t{\n\t\tthis.logger.info(`OpenVPNMonitor FS watcher initiated`);\n\t\tthis.watch = customWatch(process.env.OPENVPN_STATUS_FILE, this._statusFileUpdater.bind(this));\n\t\tthis.watch.addListener('close', () => {\n\t\t\tthis.logger.info(`OpenVPNMonitor FS Watcher closed`);\n\t\t});\n\t}", "scanBeacon(){\n this.scanClosest().then((beacon)=>{\n this.beacon=beacon;\n this.loadData();\n \n });\n }", "startScanning() {\n this.isScanning = true;\n if (noble.state === NOBLE_POWERED_ON) {\n this._log(\"debug\", \"start scanning …\");\n noble.startScanning();\n }\n }", "start() {\n fs.watchFile(this.watchDir, () => {\n this.watch();\n });\n }", "function startNotificationWatcher() {\n notificationCheck(true);\n notificationWatcher = setInterval(notificationCheck, 5000);\n}", "function startWatch() {\r\n if (!watchUserInterval) {\r\n watchUserInterval = setInterval(deviceGPS_watchPosition, 3000);\r\n }\r\n }", "function startHeartbeatMonitor() {\n\n heart.createEvent(3, function() {\n var connections = connectionController.connections;\n var connection;\n var connectionID;\n\n for (connectionID in connections) {\n connection = connections[connectionID];\n\n if (connection !== undefined && connection.incomingPulse.missedBeats > 2) {\n connection.close(1011, 'Flatlining Connection');\n }\n }\n });\n}", "function startAdvertising()\n{\n var uuid = '87209302-C7F2-4D56-B1D1-14EADD0CE41F';\n var major = 0; //RaspberryPi piBeacons Major = 1 // 0 - 65535\n var minor = 0; //RaspberryPi piBeacons Minor = 0 - 65535 and must be configured per deployment/location\n \n var measuredPower = -59; // -128 - 127 (measured RSSI at 1 meter)\n \n console.log( 'start Advertising uuid:' + uuid +' major:' + major +' minor:' + minor );\n \n Bleacon.startAdvertising(uuid, major, minor, measuredPower);\n}//end startAdvertising", "function startWatch() {\n\t\t// Update acceleration every 50 milliseconds\n\t\tvar options = { frequency: 50 };\n\t\twatchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);\n\t}", "function startAdvertising()\n{\n\t\n console.log( 'start Advertising uuid:' + self_uuid +' major:' + self_major +' minor:' + self_minor );\n \n Bleacon.startAdvertising(self_uuid, self_major, self_minor, self_measuredPower);\n\t\n\t//onboard yourself into the system?\n\tpiBeacon_add_location(\"name\", self_uuid, self_major, self_minor, 37.796996, -122.429281);\n\t\n}//end startAdvertising", "function startWatch() {\n\t// Update acceleration every 0.5 seconds\n\tvar options = {\n\t\tfrequency: choosenFrequency\n\t};\n\t\n\twatchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of DocumentContext a store for current x, y positions and available width/height. It facilitates column divisions and vertical sync
function DocumentContext(pageSize, pageMargins) { this.pages = []; this.pageMargins = pageMargins; this.x = pageMargins.left; this.availableWidth = pageSize.width - pageMargins.left - pageMargins.right; this.availableHeight = 0; this.page = -1; this.snapshots = []; this.endingCell = null; this.tracker = new TraversalTracker(); this.backgroundLength = []; this.addPage(pageSize); }
[ "function DocumentContext(pageSize,pageMargins){this.pages=[];this.pageMargins=pageMargins;this.x=pageMargins.left;this.availableWidth=pageSize.width-pageMargins.left-pageMargins.right;this.availableHeight=0;this.page=-1;this.snapshots=[];this.endingCell=null;this.tracker=new TraversalTracker();this.backgroundLength=[];this.addPage(pageSize);}", "function DocumentContext(pageSize, pageMargins) {\r\n\tthis.pages = [];\r\n\r\n\tthis.pageMargins = pageMargins;\r\n\r\n\tthis.x = pageMargins.left;\r\n\tthis.availableWidth = pageSize.width - pageMargins.left - pageMargins.right;\r\n\tthis.availableHeight = 0;\r\n\tthis.page = -1;\r\n\r\n\tthis.snapshots = [];\r\n\r\n\tthis.endingCell = null;\r\n\r\n\tthis.tracker = new TraversalTracker();\r\n\r\n\tthis.backgroundLength = [];\r\n\r\n\tthis.addPage(pageSize);\r\n}", "function DocumentContext(pageSize, pageMargins) {\n\tthis.pages = [];\n\n\tthis.pageMargins = pageMargins;\n\n\tthis.x = pageMargins.left;\n\tthis.availableWidth = pageSize.width - pageMargins.left - pageMargins.right;\n\tthis.availableHeight = 0;\n\tthis.page = -1;\n\n\tthis.snapshots = [];\n\n\tthis.endingCell = null;\n\n\tthis.tracker = new TraversalTracker();\n\n\tthis.addPage(pageSize);\n\n\tthis.hasBackground = false;\n}", "canvasContext() {\n this._canvas = this.template.querySelector('canvas');\n this._canvasCtx = this._canvas.getContext('2d');\n this._cursorActive = false;\n }", "function Window(width, height, context)\n{\n this.id = 0;\n this.width = width;\n this.height = height;\n this.viewList = new Array();\n this.rotation = 0;\n this.x_center = 0;\n this.y_center = 0;\n this.x = 0;\n this.y = 0;\n this.scale_x = 1.0;\n this.scale_y = 1.0;\n this.context = context;\n this.identity_matrix = {\n\t\t\t\t\t\tm11: 1, m12: 0, dx: 0,\n\t\t\t\t\t\tm21: 0, m22: 1, dy: 0\n\t\t\t\t\t\t// 0 0 1\n\t\t\t\t\t };\n}", "getDrawingCtx(width = this._tempCanvas.width, height = this._tempCanvas.height) {\n if (width != this._tempCanvas.width || height != this._tempCanvas.height) {\n this._tempCanvas.width = width;\n this._tempCanvas.height = height;\n }\n return this._tempCtx;\n }", "createCanvasContext() {\n this.canvas = document.createElement('canvas');\n this.canvas.width = this.config.width;\n this.canvas.height = this.config.height;\n document.body.appendChild(this.canvas);\n this.context = this.canvas.getContext('2d');\n }", "async getCurrentState() {\n let document = await this.document;\n let position = await this.getCursorPosition();\n return {\n document: document.textDocument,\n position\n };\n }", "_updateRenderingContext() {\n this._renderingContext.timeToPixel = this.timeContext.timeToPixel;\n this._renderingContext.valueToPixel = this._valueToPixel;\n\n this._renderingContext.height = this.params.height;\n this._renderingContext.width = this.timeContext.timeToPixel(this.timeContext.duration);\n // for foreign object issue in chrome\n this._renderingContext.offsetX = this.timeContext.timeToPixel(this.timeContext.offset);\n this._renderingContext.startX = this.timeContext.parent.timeToPixel(this.timeContext.start);\n\n // @TODO replace with `minX` and `maxX` representing the visible pixels in which\n // the shapes should be rendered, could allow to not update the DOM of shapes\n // who are not in this area.\n // in between: expose some timeline attributes -> improves Waveform perfs\n this._renderingContext.trackOffsetX = this.timeContext.parent.timeToPixel(this.timeContext.parent.offset);\n this._renderingContext.visibleWidth = this.timeContext.parent.visibleWidth;\n }", "get context() {\n const ctx = {\n $implicit: this.value,\n additionalTemplateContext: this.column.additionalTemplateContext,\n };\n /* Turns the `cell` property from the template context object into lazy-evaluated one.\n * Otherwise on each detection cycle the cell template is recreating N cell instances where\n * N = number of visible cells in the grid, leading to massive performance degradation in large grids.\n */\n Object.defineProperty(ctx, 'cell', {\n get: () => this.getCellType(true)\n });\n return ctx;\n }", "function getContext() {\n var canvas = document.createElement('canvas');\n canvas.width = options.tileWidth * options.divX;\n canvas.height = options.tileHeight * options.divY;\n var context = canvas.getContext('2d');\n context.drawImage(options.image, 0, 0, canvas.width, canvas.height);\n return context;\n }", "function ScreenContext() {\n EventEmitter.call(this);\n\n this.canvas_name = \"xianCanvas\";\n this.canvas_div_name = \"xianDiv\";\n\n //designed game view area\n this._designWidth = 0;\n this._designHeight = 0;\n\n this._offSetY = 0;\n //real viewport area\n this._viewWidth = 0;\n this._viewHeight = 0;\n\n //real game view area\n this._stageWidth = 0;\n this._stageHeight = 0;\n\n //real scale factor\n this._scaleX = 1;\n this._scaleY = 1;\n\n this._autoSize = false;\n this._resolutionPolicy = ResolutionPolicy;\n}", "createCanvas(){\n this.myCanvasHolder = document.querySelector(\".myPaint\");\n this.width = this.myCanvasHolder.width = document.querySelector(\".content\").offsetWidth;\n this.height = this.myCanvasHolder.height = window.innerHeight*0.9;\n this.ctx = this.myCanvasHolder.getContext(\"2d\");\n this.ctx.width = this.width;\n this.ctx.height = this.height;\n this.isDrawing = false;\n }", "function createContext(width, height, is3d) {\n\tif (width < 1 || height < 1) {\n\t\tconsole.error(\"Can't create context with size \" + width + \" x \" + height);\n\t\treturn createDummyImage(64, 64);\n\t}\n\tconst canvas = document.createElement(\"canvas\");\n\tcanvas.setAttribute('width', width);\n\tcanvas.setAttribute('height', height);\n\tconst context = canvas.getContext(is3d ? '3d' : '2d');\n\tcontext.width = width;\n\tcontext.height = height;\n\treturn context;\n}", "function Geometry() {\n if (window.screenLeft) { // IE and others\n Geometry.getWindowX = function() { return window.screenLeft; };\n Geometry.getWindowY = function() { return window.screenTop; };\n }\n else if (window.screenX) { // Firefox and others\n Geometry.getWindowX = function() { return window.screenX; };\n Geometry.getWindowY = function() { return window.screenY; };\n }\n \n if (window.innerWidth) { // All browsers but IE\n Geometry.getViewportWidth = function() { return window.innerWidth; };\n Geometry.getViewportHeight = function() { return window.innerHeight; };\n Geometry.getHorizontalScroll = function() { return window.pageXOffset; };\n Geometry.getVerticalScroll = function() { return window.pageYOffset; };\n }\n else if (document.documentElement && document.documentElement.clientWidth) {\n // These functions are for IE 6 when there is a DOCTYPE\n Geometry.getViewportWidth =\n function() { return document.documentElement.clientWidth; };\n Geometry.getViewportHeight =\n function() { return document.documentElement.clientHeight; };\n Geometry.getHorizontalScroll =\n function() { return document.documentElement.scrollLeft; };\n Geometry.getVerticalScroll =\n function() { return document.documentElement.scrollTop; };\n }\n else if (document.body.clientWidth) {\n // These are for IE4, IE5, and IE6 without a DOCTYPE\n Geometry.getViewportWidth =\n function() { return document.body.clientWidth; };\n Geometry.getViewportHeight =\n function() { return document.body.clientHeight; };\n Geometry.getHorizontalScroll =\n function() { return document.body.scrollLeft; };\n Geometry.getVerticalScroll =\n function() { return document.body.scrollTop; };\n }\n \n // These functions return the size of the document. They are not window\n // related, but they are useful to have here anyway.\n if (document.documentElement && document.documentElement.scrollWidth) {\n Geometry.getDocumentWidth =\n function() { return document.documentElement.scrollWidth; };\n Geometry.getDocumentHeight =\n function() { return document.documentElement.scrollHeight; };\n }\n else if (document.body.scrollWidth) {\n Geometry.getDocumentWidth =\n function() { return document.body.scrollWidth; };\n Geometry.getDocumentHeight =\n function() { return document.body.scrollHeight; };\n }\n}", "function RenderingContext() {\r\n\tthis.init = RenderingContext_init;\r\n\r\n\t// Generic getters - used most often\r\n\tthis.launchMode = RenderingContext_launchMode;\r\n\tthis.lessonMode = RenderingContext_lessonMode;\r\n\tthis.pageMode = RenderingContext_pageMode;\r\n\t\r\n\t// Specialized getters - used less often\r\n\tthis.launchCtx = RenderingContext_launchCtx;\r\n\tthis.lessonCtx = RenderingContext_lessonCtx;\r\n\tthis.pageCtx = RenderingContext_pageCtx;\r\n\t\r\n\t// Specialized setters - used when rendering mode is changed during runtime: \r\n\t// e.g. toggle to preview mode in editor)\r\n\tthis.getLessonCtx = RenderingContext_getLessonCtx;\r\n\tthis.setLessonCtx = RenderingContext_setLessonCtx;\r\n\tthis.getLessonEditorCtx = RenderingContext_getLessonEditorCtx;\r\n\tthis.editorEditLayout = RenderingContext_editorEditLayout;\r\n\tthis.editorEditContent = RenderingContext_editorEditContent;\r\n\tthis.editorEditPreview = RenderingContext_editorEditPreview;\r\n\tthis.editorEditTemplate = RenderingContext_editorEditTemplate;\r\n\r\n\tthis.playerToggleDoAndPreview = RenderingContext_playerToggleDoAndPreview;\r\n\tthis.editorPageToggleEditAndGraEdit = RenderingContext_editorPageToggleEditAndGraEdit;\r\n\tthis.playerPageChangeToZodi = RenderingContext_playerPageChangeToZodi;\r\n\tthis.playerGetZodiChangesPages = RenderingContext_playerGetZodiChangesPages;\r\n\t\r\n\t// Specific checks based on launchCtx used in notes-dlg\r\n\tthis.studentNotesState = RenderingContext_studentNotesState; // \"editable\" or \"read-only\"\r\n\tthis.teacherRemarksState = RenderingContext_teacherRemarksState; // \"editable\" or \"read-only\" or \"hidden\"\r\n\tthis.canShowScore = RenderingContext_canShowScore; // true/false\r\n this.canEditScore = RenderingContext_canEditScore; // true/false\r\n\r\n\tthis.data = {};\r\n}", "function CalculationDocument(data)\n{\n\tconsole.time('init_calculation_document');\n\tthis.tContext = data;\n\tvar formulasets = data.formulasets;\n\tvar formulasetsCount = data.formulasets.length;\n\tvar viewmodes = {};\n\tvar NA = data.navalue;\n\tvar indexed = [];// holds a indexed reference for quicked lookup for real-column-contexts/ can be used for the column variable\n\tvar templateindexed = [];// holds a indexed reference for quicked lookup for contexts/ its only for the templates and will only be used during build time\n\tthis.viewmodes = viewmodes;\n\t// make an array storing the formulaset for all columnentrees, used for quicker lookup later\n\tvar formulasetLookup = [];// used to lookup the\n\t// we assume they ordered, looping trough the entrees, using the currentPeriod as being used until index had been reached\n\tvar periods = data.layout.period;\n\tvar currentperiod = periods[0];\n\tvar aggregationformulaset = formulasets[formulasets.length - 1];\n\tcurrentperiod.formulaset = formulasets[currentperiod.formulasetId];\n\tfor (var i = 0; i < data.layout.idx; i++)\n\t{\n\t\tif (i >= currentperiod.idx)\n\t\t{\n\t\t\tcurrentperiod = periods[currentperiod.formulasetId + 1];\n\t\t\t// assign the formulaset, it was stored as reference\n\t\t\tcurrentperiod.formulaset = formulasets[currentperiod.formulasetId];\n\t\t}\n\t\tformulasetLookup[i] = currentperiod;\n\t}\n\tcurrentperiod.last = data.layout.idx;\n\tthis.column = function(variable, vars, hIndex, fIndex)\n\t{\n\t\t// var fi = (fIndex * formulasetsCount) + this.f;\n\t\t// should pass trough formula to the variable deocorator..\n\t\t// he can still swap flipflop T\n\t\t// i can pass trough the scope.. // return variable.evaluated[fIndex].call(this, variable, vars, hIndex, this);\n\t\t// i will pass trouhg the engine as scope..\n\t\treturn variable.evaluated[(formulasetsCount * fIndex) + this.f](variable, vars, hIndex, this);\n\t}\n\tvar dummyColumn = {\n\t\tt : 0,\n\t\tprevTl : undefined,\n\t\tcalc : function(variable, vars, hIndex, formula)\n\t\t{\n\t\t\t// this is a special number.. and should be a variable..\n\t\t\treturn NA;\n\t\t}\n\t};\n\tdummyColumn.f = 0;\n\tdummyColumn.prev = dummyColumn;\n\t// dummyColumn.prevTl = dummyColumn;\n\tvar timelineSize = data.time.timelineSize;\n\tvar timelineMultiplier = data.time.timelineMultiplier;\n\tvar columnMultiplier = data.time.columnMultiplier;\n\t// find out all viewtypes in the document\n\tvar layout = data.layout;\n\twhile (layout != undefined)\n\t{\n\t\tviewmodes[layout.name] = {\n\t\t\tdoc : [],\n\t\t\tperiod : [],\n\t\t\tcolumns : [],\n\t\t\tcols : []\n\t\t};\n\t\tlayout = layout.children[0];\n\t}\n\t// tricky recursion here, just debug it.. too many to explain\n\tfunction nestRecursive(parent, object, offset, func)\n\t{\n\t\tobject.forEach(function(child)\n\t\t{\n\t\t\tchild.parent = parent;\n\t\t\tvar tempincrease = child.size;\n\t\t\tvar no = 0;\n\t\t\tchild.parent.sibling = [];\n\t\t\twhile (tempincrease <= (parent.size - 1))\n\t\t\t{\n\t\t\t\tchild.idx = (offset + tempincrease);\n\t\t\t\tchild.no = no;\n\t\t\t\ttempincrease += child.size;\n\t\t\t\tchild.parent.sibling.push((offset + (child.size * (no + 1))));\n\t\t\t\tnestRecursive(child, child.children, offset + (child.size * (no)), func)\n\t\t\t\tno++;\n\t\t\t}\n\t\t});\n\t\tfunc(parent);\n\t}\n\tfunction extractBaseChildren(child, array)\n\t{\n\t\tchild.sibling.forEach(function(innerchild)\n\t\t{\n\t\t\tvar foundChild = templateindexed[innerchild];\n\t\t\tif (foundChild.sibling == undefined)\n\t\t\t{\n\t\t\t\tarray.push(innerchild);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\textractBaseChildren(foundChild, array);\n\t\t\t}\n\t\t});\n\t}\n\t// extract data from recursion\n\t// make new column objects\n\t// be aware the values from child in here are temporally from transitive nature. U cannot keep references since they will change in future. Presumably to the last one...\n\tnestRecursive(data.layout, data.layout.children, 0, function(child)\n\t{\n\t\t// console.info(child.no);\n\t\t// actual element\n\t\tvar newElement = {\n\t\t\t// type : child.name,\n\t\t\tparenttypes : [],\n\t\t\tt : child.idx\n\t\t};\n\t\t// find out all parents and top\n\t\tvar parent = child.parent;\n\t\twhile (parent != undefined)\n\t\t{\n\t\t\t// register aggregation type\n\t\t\t// register all types to the new columnIndex object\n\t\t\tvar previdx = child.idx - parent.size;\n\t\t\tnewElement.parenttypes.push({\n\t\t\t\tidx : parent.idx,\n\t\t\t\ttype : parent.name,\n\t\t\t\tprevme : previdx > 0 ? previdx : undefined\n\t\t\t});\n\t\t\t// if the next is undefined, we found top.\n\t\t\tnewElement.top = parent.idx;\n\t\t\tparent = parent.parent;\n\t\t}\n\t\t// could be top, of so, we don't need this information\n\t\tif (child.parent != undefined)\n\t\t{\n\t\t\tnewElement.agg = child.parent.idx;\n\t\t\tnewElement.period = formulasetLookup[child.idx];\n\t\t}\n\t\t// could be aggregated, we want to know what siblings it had\n\t\tif (child.sibling != undefined)\n\t\t{\n\t\t\tnewElement.sibling = child.sibling.slice();\n\t\t\tvar children = newElement.sibling;\n\t\t\tvar tarr = [];\n\t\t\t// add the base children aswell for quicker and eaier lookup later\n\t\t\textractBaseChildren(child, tarr);\n\t\t\tnewElement.allchildren = tarr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// this is smallest we get\n\t\t\tvar period = formulasetLookup[child.idx];\n\t\t\tif (period.first == undefined)\n\t\t\t{\n\t\t\t\tperiod.first = child.idx;\n\t\t\t}\n\t\t\tformulasetLookup[child.idx].last = child.idx;\n\t\t}\n\t\t// add elements to the base cols\n\t\tviewmodes[child.name].cols.push(newElement);\n\t\ttemplateindexed[newElement.t] = newElement;\n\t});\n\t// convert template column index into real index\n\tfunction calculateIndex(timelineId, columnId)\n\t{\n\t\tvar columnId = (columnId * columnMultiplier);\n\t\t// add offset,0 for the titleValue, 1 for dummy cache,we starting from 1 so +1\n\t\tcolumnId++;\n\t\t// add timeline\n\t\tcolumnId += (timelineId * timelineMultiplier);\n\t\treturn columnId;\n\t}\n\t// convert meta data in real column object..\n\t// don't make references. The values are re-used over timelines\n\tfor (vmode in this.viewmodes)\n\t{\n\t\t// this loop will be used for all viewmodes when wisely declared.\n\t\tfor (var tId = 0; tId < timelineSize; tId++)\n\t\t{\n\t\t\t// create new array for the timeline\n\t\t\tthis.viewmodes[vmode].columns[tId] = [];\n\t\t}\n\t}\n\t// creat all real objects for all timeslines first, we use the indexes created to lookup the elements while loooking for references\n\tfor (var tId = 0; tId < timelineSize; tId++)\n\t{\n\t\tfor (vmode in this.viewmodes)\n\t\t{\n\t\t\t// times multiplier\n\t\t\t// jsut for quick reference place the array in here;\n\t\t\tvar currentviewmode = viewmodes[vmode];\n\t\t\tvar currentviewmodecolumns = currentviewmode.cols;\n\t\t\tfor (var cId = 0; cId < currentviewmodecolumns.length; cId++)\n\t\t\t{\n\t\t\t\tvar columnEntries = currentviewmode.columns;\n\t\t\t\tvar columnEntriesForTimeline = currentviewmode.columns[tId];\n\t\t\t\tvar metadata = currentviewmode.cols[cId];\n\t\t\t\tvar columnId = calculateIndex(tId, metadata.t);\n\t\t\t\tvar previousColumn = (cId == 0 ? dummyColumn : columnEntriesForTimeline[columnEntriesForTimeline.length - 1]);\n\t\t\t\tvar previousTimelineColumn = (tId == 0 ? undefined : columnEntries[tId - 1][columnEntriesForTimeline.length]);\n\t\t\t\tvar columnElement = {\n\t\t\t\t\tt : columnId,\n\t\t\t\t\tprevTl : previousTimelineColumn,\n\t\t\t\t\tcalc : this.column,\n\t\t\t\t\tprev : previousColumn\n\t\t\t\t};\n\t\t\t\tindexed[columnId] = columnElement;\n\t\t\t\t// add to the stack\n\t\t\t\tcolumnEntriesForTimeline.push(columnElement);\n\t\t\t\t// we know the first column from this, while being the first we can references it from here\n\t\t\t\tcolumnElement.first = columnEntriesForTimeline[0];\n\t\t\t\t// we don't knwow the last.. since it could be in the future, we have to add it later\n\t\t\t}\n\t\t}\n\t\t// now all entree are filled, for its timeline we can reference the last\n\t\t// be aware that the the viewmodes walked top,bkyr,half,qurt,detl. No reference can be made for the real column objects,from top->detl. It would require a new loop\n\t\t// so u can ask from a detl about a parent type children, but not about information about those children, since they are not determined yet, they exist, but the references are not\n\t\t// u can however obtain information about the children from the template. And ofc there should not be a need to ask these kind of information\n\t\tfor (vmode in this.viewmodes)\n\t\t{\n\t\t\t// times multiplier\n\t\t\t// jsut for quick reference place the array in here;\n\t\t\tvar currentviewmode = viewmodes[vmode];\n\t\t\tvar currentviewmodecolumns = currentviewmode.cols;\n\t\t\tvar columnslength = currentviewmodecolumns.length;\n\t\t\tfor (var cId = 0; cId < columnslength; cId++)\n\t\t\t{\n\t\t\t\t// here all references are made\n\t\t\t\t// bky,doc,period,formula,aggregation, top, children.. all\n\t\t\t\tvar columnEntries = currentviewmode.columns;\n\t\t\t\tvar columnEntriesForTimeline = columnEntries[tId];\n\t\t\t\tvar entree = currentviewmode.columns[tId][cId];\n\t\t\t\tentree.last = columnEntriesForTimeline[columnEntriesForTimeline.length - 1];\n\t\t\t\tentree.first = columnEntriesForTimeline[0];\n\t\t\t\tentree.next = (cId == (columnslength - 1)) ? dummyColumn : columnEntriesForTimeline[cId + 1];\n\t\t\t\tvar metadata = currentviewmode.cols[cId];\n\t\t\t\tentree.formula = metadata.period;\n\t\t\t\tif (metadata.agg != undefined)\n\t\t\t\t{\n\t\t\t\t\tvar aggColumnId = calculateIndex(tId, metadata.agg);\n\t\t\t\t\tentree.agg = indexed[aggColumnId];\n\t\t\t\t}\n\t\t\t\tif (metadata.sibling != undefined)\n\t\t\t\t{\n\t\t\t\t\tentree.f = aggregationformulaset.formulasetId;\n\t\t\t\t\tentree.aggcols = [];\n\t\t\t\t\tmetadata.sibling.forEach(function(childid)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar childColId = calculateIndex(tId, childid);\n\t\t\t\t\t\tentree.aggcols.push(indexed[childColId]);\n\t\t\t\t\t});\n\t\t\t\t\tentree.firstchild = indexed[calculateIndex(tId, metadata.allchildren[0])];\n\t\t\t\t\tentree.lastchild = indexed[calculateIndex(tId, metadata.allchildren[metadata.allchildren.length - 1])];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tentree.f = formulasetLookup[metadata.t].formulasetId;\n\t\t\t\t}\n\t\t\t\t// this will allow document values per timeline, if referring to timeline[0] there will only be one possible..\n\t\t\t\tentree.doc = columnEntriesForTimeline[0];// there only is one and one only, always correct behavior\n\t\t\t\t// entree.period = (cId == 0) ? columnEntriesForTimeline[0] : columnEntriesForTimeline[1];// detail should refer to corresponding period\n\t\t\t\t// add all period information\n\t\t\t\tif (metadata.period != undefined)\n\t\t\t\t{\n\t\t\t\t\t// now it will be able to aggregate\n\t\t\t\t\t// can't do firstchild in this type.\n\t\t\t\t\tentree.period = columnEntriesForTimeline[metadata.period.t];\n\t\t\t\t\tentree.firstinperiod = indexed[calculateIndex(tId, metadata.period.first)];\n\t\t\t\t\tentree.lastinperiod = indexed[calculateIndex(tId, metadata.period.last)];\n\t\t\t\t\tfor (var pi = 0; pi < periods.length; pi++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar period = periods[pi];\n\t\t\t\t\t\tvar tFirst = indexed[calculateIndex(tId, period.first)];\n\t\t\t\t\t\tvar formulaname = period.formulaset.name;\n\t\t\t\t\t\tentree['first' + formulaname] = tFirst;\n\t\t\t\t\t\tvar tLast = indexed[calculateIndex(tId, period.last)];\n\t\t\t\t\t\tentree['last' + formulaname] = tLast;\n\t\t\t\t\t\tentree['isfirst' + formulaname] = (tFirst.t == entree.t);\n\t\t\t\t\t\tentree['islast' + formulaname] = (tLast.t == entree.t);\n\t\t\t\t\t\tentree['is' + formulaname] = (period.formulasetId == formulasetLookup[metadata.t].formulasetId);\n\t\t\t\t\t\tentree['isprev' + formulaname] = entree.prev.t == 0 ? false : entree.prev['is' + formulaname];\n\t\t\t\t\t}\n\t\t\t\t\tentree.isfirstinperiod = (entree.firstinperiod.t == entree.t);\n\t\t\t\t\tentree.islastinperiod = (entree.lastinperiod.t == entree.t);\n\t\t\t\t}\n\t\t\t\tentree.aggregated = (metadata.sibling != undefined);\n\t\t\t\tentree.tsy = (metadata.sibling == undefined) ? 1 : metadata.allchildren.length;\n\t\t\t\tentree.texceedtsy = metadata.t > entree.tsy;// should be infirstbkyr\n\t\t\t\t// add all information about aggregation types;bkyr,all are available if not top..\n\t\t\t\t// there is no need yet to give aggregated columns information about bookyear etc.. yet\n\t\t\t\tif (metadata.sibling == undefined)\n\t\t\t\t{\n\t\t\t\t\tfor (var aggi = 0; aggi < metadata.parenttypes.length; aggi++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar agg = metadata.parenttypes[aggi];\n\t\t\t\t\t\tvar aggtype = agg.type;\n\t\t\t\t\t\tvar template = templateindexed[agg.idx];\n\t\t\t\t\t\tvar tempatechilds = template.allchildren;\n\t\t\t\t\t\tvar aggentree = indexed[calculateIndex(tId, template.t)];\n\t\t\t\t\t\tentree[aggtype] = aggentree;\n\t\t\t\t\t\tentree['prev' + aggtype] = aggentree.prev == undefined ? dummyColumn : aggentree.prev;\n\t\t\t\t\t\tentree['previn' + aggtype] = agg.prevme == undefined ? dummyColumn : indexed[calculateIndex(tId, agg.prevme)];\n\t\t\t\t\t\tentree['isinfirst' + aggtype] = agg.prevme == undefined;\n\t\t\t\t\t\tvar prevagg = aggentree.prev;\n\t\t\t\t\t\tentree['lastinprev' + aggtype] = (prevagg.t == 0) ? dummyColumn : prevagg.lastchild;\n\t\t\t\t\t\tentree['firstinprev' + aggtype] = (prevagg.t == 0) ? dummyColumn : prevagg.firstchild;\n\t\t\t\t\t\tentree['lastin' + aggtype] = prevagg;\n\t\t\t\t\t\tvar firstEntree = indexed[calculateIndex(tId, tempatechilds[0])];\n\t\t\t\t\t\tentree['first' + aggtype] = firstEntree;\n\t\t\t\t\t\tentree['isfirst' + aggtype] = (firstEntree.t == entree.t);\n\t\t\t\t\t\tvar lastEntree = indexed[calculateIndex(tId, tempatechilds[tempatechilds.length - 1])];\n\t\t\t\t\t\tentree['last' + aggtype] = lastEntree;\n\t\t\t\t\t\tentree['islast' + aggtype] = (lastEntree.t == entree.t);\n\t\t\t\t\t}\n\t\t\t\t\tentree.mutcalc = entree.infirstbkyr ? 1 : NA;// information not available in aggcolumns,yet...\n\t\t\t\t}\n\t\t\t\t// when period or doc variable refer to Detail Variable, which is kind of strange..\n\t\t\t\tentree.detail = (cId == 0) ? columnEntriesForTimeline[0] : columnEntriesForTimeline[1];// period should refer to first detail from own period\n\t\t\t}\n\t\t}\n\t}\n\tthis.indexed = indexed;\n\ttemplateindexed = undefined;\n\tconsole.timeEnd('init_calculation_document');\n}", "_getCanvasPos(x, y) {\r\n let rect = canvas.getBoundingClientRect();\r\n let sx = canvas.scrollWidth / this.width || 1;\r\n let sy = canvas.scrollHeight / this.height || 1;\r\n let p = {x: 0, y: 0};\r\n \r\n p.x = (x - rect.left) / sx;\r\n p.y = (y - rect.top) / sy;\r\n \r\n return p;\r\n }", "showPageContextIfPresent() {\n const doc = this.docs_[this.cursor.doc];\n this.contextRow_.innerHTML = '';\n this.contextRow_.style.display = 'none';\n if (!doc.srcContext || !doc.tgtContext) {\n return;\n }\n\n /**\n * Keep image width down to fit more content vertically. But if\n * the height is very large then use a larger width.\n */\n const width = Math.max(doc.srcContext.h,\n doc.tgtContext.h) > 2000 ? 450 : 320;\n\n /**\n * Slightly complex layout, to allow scrolling images vertically, and\n * yet let the zoomed view spill outside. The zoomed view also shows\n * the selection outline.\n * td\n * anthea-context-image-wrapper\n * anthea-context-image-port (scrollable)\n * anthea-context-image-cell\n * img\n * anthea-context-image-selection\n * anthea-context-image-zoom\n * full-img\n * full-selection\n */\n const srcImg = googdom.createDom(\n 'img', {src: doc.srcContext.url,\n class: 'anthea-context-image', width: width});\n const srcScale = width / doc.srcContext.w;\n const srcSelection = googdom.createDom('div',\n 'anthea-context-image-selection');\n this.setRectStyle(srcSelection, doc.srcContext.box, srcScale);\n const srcCell = googdom.createDom(\n 'div', 'anthea-context-image-cell', srcImg, srcSelection);\n const srcPort = googdom.createDom('div',\n 'anthea-context-image-port', srcCell);\n const srcZoom = googdom.createDom('div', 'anthea-context-image-zoom');\n srcZoom.style.display = 'none';\n const srcWrapper = googdom.createDom(\n 'div', 'anthea-context-image-wrapper', srcPort, srcZoom);\n this.contextRow_.appendChild(googdom.createDom('td', null, srcWrapper));\n this.setUpImageZooming(srcWrapper, srcCell, srcZoom, doc.srcContext.url,\n doc.srcContext.w, doc.srcContext.h,\n doc.srcContext.box, srcScale);\n\n const tgtImg = googdom.createDom(\n 'img', {src: doc.tgtContext.url,\n class: 'anthea-context-image', width: width});\n const tgtScale = width / doc.tgtContext.w;\n const tgtSelection = googdom.createDom('div',\n 'anthea-context-image-selection');\n this.setRectStyle(tgtSelection, doc.tgtContext.box, tgtScale);\n const tgtCell = googdom.createDom(\n 'div', 'anthea-context-image-cell', tgtImg, tgtSelection);\n const tgtPort = googdom.createDom('div',\n 'anthea-context-image-port', tgtCell);\n const tgtZoom = googdom.createDom('div',\n 'anthea-context-image-zoom');\n tgtZoom.style.display = 'none';\n const tgtWrapper = googdom.createDom(\n 'div', 'anthea-context-image-wrapper', tgtPort, tgtZoom);\n this.contextRow_.appendChild(googdom.createDom('td', null, tgtWrapper));\n this.setUpImageZooming(tgtWrapper, tgtCell, tgtZoom, doc.tgtContext.url,\n doc.tgtContext.w, doc.tgtContext.h,\n doc.tgtContext.box, tgtScale);\n\n this.contextRow_.appendChild(googdom.createDom('td',\n 'anthea-context-eval-cell'));\n this.contextRow_.style.display = '';\n\n const sOpt = {block: \"center\"};\n srcSelection.scrollIntoView(sOpt);\n tgtSelection.scrollIntoView(sOpt);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch account data for UI when User switches accounts in wallet User switches networks in wallet User connects wallet initially
async function refreshAccountData() { // If any current data is displayed when // the user is switching acounts in the wallet // immediate hide this data document.querySelector("#connected").style.display = "none"; document.querySelector("#prepare").style.display = "block"; // Disable button while UI is loading. // fetchAccountData() will take a while as it communicates // with Ethereum node via JSON-RPC and loads chain data // over an API call. document.querySelector("#btn-connect").setAttribute("disabled", "disabled") await fetchAccountData(provider); document.querySelector("#btn-connect").removeAttribute("disabled") }
[ "async function refreshAccountData() {\n\n // If any current data is displayed when\n // the user is switching acounts in the wallet\n // immediate hide this data\n //document.querySelector(\"#connected\").style.display = \"none\";\n //document.querySelector(\"#prepare\").style.display = \"block\";\n //document.querySelector(\"#btn-accountdetails\").style.display = \"none\";\n document.querySelector(\"#btn-connect\").style.display = \"block\";\n //document.querySelector(\"#btn-disconnect\").style.display = \"none\";\n document.querySelector(\"#btn-account\").style.display = \"none\";\n\n // Disable button while UI is loading.\n // fetchAccountData() will take a while as it communicates\n // with Ethereum node via JSON-RPC and loads chain data\n // over an API call.\n document.querySelector(\"#btn-connect\").setAttribute(\"disabled\", \"disabled\");\n await fetchAccountData(provider);\n document.querySelector(\"#btn-connect\").removeAttribute(\"disabled\");\n}", "async function refreshAccountData() {\n\t// If any current data is displayed when\n\t// the user is switching acounts in the wallet\n\t// immediate hide this data\n\t//.document.querySelector(\"#connected\").style.display = \"none\";\n\t//document.querySelector(\"#prepare\").style.display = \"block\";\n\n\t// Disable button while UI is loading.\n\t// fetchAccountData() will take a while as it communicates\n\t// with Ethereum node via JSON-RPC and loads chain data\n\t// over an API call.\n\t// document.querySelector(\"#btn-connect\").setAttribute(\"disabled\", \"disabled\")\n\tawait fetchAccountData(provider);\n\t//document.querySelector(\"#btn-connect\").removeAttribute(\"disabled\")\n}", "async function refreshAccountData() {\n\n // If any current data is displayed when\n // the user is switching acounts in the wallet\n // immediate hide this data\n// document.querySelector(\"#connected\").style.display = \"none\";\n// document.querySelector(\"#prepare\").style.display = \"block\";\n\n // Disable button while UI is loading.\n // fetchAccountData() will take a while as it communicates\n // with Ethereum node via JSON-RPC and loads chain data\n // over an API call.\n// document.querySelector(\"#btn-connect\").setAttribute(\"disabled\", \"disabled\")\n await fetchAccountData(provider);\n// document.querySelector(\"#btn-connect\").removeAttribute(\"disabled\")\n}", "async function accountChange() {\r\n\tawait window.ethereum.enable();\r\n \r\n\tweb3.eth.getAccounts(function (error, accounts) {\r\n\t\tconsole.log(accounts[0], 'current account on init');\r\n\t\taccount = accounts[0];\r\n\t});\r\n \r\n\t// Acccounts now exposed\r\n\twindow.ethereum.on('accountsChanged', function () {\r\n\t\tweb3.eth.getAccounts(function (error, accounts) {\r\n\t\t\tconsole.log(accounts[0], 'current account after account change');\r\n\t\t\taccount = accounts[0];\r\n\t\t});\r\n\t});\r\n}", "async getWalletInfo() {\n if (window.ethereum) {\n window.ethereum.autoRefreshOnNetworkChange = false;\n window.web3 = new Web3(window.ethereum);\n } else {\n console.log(\n \"Please install MetaMask. How To instructions can be found here: https://www.youtube.com/watch?v=wTlI2_zxXpU\"\n );\n return 0;\n }\n\n await window.ethereum\n .enable()\n .then(accounts => {\n console.log(\"Wallet access approval granted\");\n console.log(\"fromAddress = \", accounts[0]);\n this.setState({ fromAddress: accounts[0] });\n\n // this handler will fire when account is changed in MetaMask\n window.ethereum.on(\"accountsChanged\", accounts => {\n // Note: accounts[0] and window.ethereum.selectedAddress are the same\n console.log(\"updated fromAddress = \", accounts[0]);\n this.setState({ fromAddress: accounts[0] });\n });\n })\n // User denied account access...\n .catch(error => {\n console.log(\n \"maybe user didn't give permission to use wallet??. Cannot proceed.\",\n error\n );\n this.setState({ fromAccount: 0 });\n return 0;\n });\n }", "async function getCurrentWalletConnected(){\n if(window.ethereum){\n try{\n const addressArray = await window.ethereum.request({\n method: \"eth_accounts\"\n });\n if(addressArray.length > 0 && window.localStorage.getItem(\"logged-in\") !== null){\n saveUserInfo({walletAddress: addressArray[0]});\n return;\n }\n\n saveUserInfo({walletAddress: \"\"});\n }catch(err){\n saveUserInfo({walletAddress: \"\"});\n console.error(\"something went wrong fetching current wallet\", err.message);\n }\n }\n }", "async function handleConnectWallet() {\n setLoading(true);\n\n await requestConnection()\n await setConnectedAccount()\n\n setLoading(false);\n }", "async function checkAccount() {\n let web3 = new Web3(window.ethereum);\n setWeb3(web3);\n const accounts = await web3.eth.getAccounts();\n setAccount(accounts[0]);\n\n const chainId = await web3.eth.getChainId();\n setChainId(chainId);\n\n window.ethereum.on(\"accountsChanged\", function (accounts) {\n setAccount(accounts[0]);\n });\n\n window.ethereum.on(\"networkChanged\", function (networkId) {\n setChainId(networkId);\n });\n\n setDisconnected(false);\n }", "_onAccountChanged(accounts) {\n console.log(\"wallet account changed.\");\n console.log(accounts);\n if (accounts.length === 0) {\n this._onDisconnected();\n } else {\n this.wallet.account = accounts[0];\n this._clearBalances();\n }\n }", "static async walletStatusUpdate() {\n const isEnable = accountControl.auth.isEnable\n const isReady = accountControl.auth.isReady\n const type = MTypeTab.LOCK_STAUS\n let selectedAccount = null\n\n if (isEnable) {\n const storage = new BrowserStorage()\n const wallet = await storage.get(FIELDS.WALLET)\n\n if (!wallet || !wallet.identities || wallet.identities.length === 0) {\n return null\n }\n\n selectedAccount = wallet.identities[wallet.selectedAddress]\n }\n\n if (isEnable && isReady) {\n socketControl.start()\n } else {\n socketControl.stop()\n }\n\n return new TabsMessage({\n type,\n payload: {\n isEnable,\n isReady,\n account: selectedAccount\n }\n }).send()\n }", "async function connect() {\n // Not using provider method here because it doesn't \n // open metamask when there are no connected accounts :/\n const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });\n const selectedAddress = window.selectedAddress || accounts[0] || null;\n\n console.log('Initial accounts received: ', accounts, selectedAddress);\n setSelectedAddress(selectedAddress);\n }", "function displayWallet() {\n if (localStorage.getItem('reddcoinWallet')) {\n $('#walletSwapInteract').trigger('click');\n }\n else {\n $('#createWalletSetup').trigger('click');\n }\n\n if (localStorage.getItem('reddcoinWallet') || localStorage.getItem('user')) {\n Reddcoin.popup.updateBalance();\n Reddcoin.popup.updateHistory();\n\n // TODO: SEARCH\n Reddcoin.popup.updateSend();\n Reddcoin.popup.updateAccount();\n Reddcoin.popup.updateReceive();\n }\n}", "function refreshAccounts() {\n vm.disconnectedAccounts = [];\n vm.connectedAccounts = [];\n var additionalDataKeys = null;\n if (vm.user.additionalProvidersData) {\n additionalDataKeys = Object.keys(vm.user.additionalProvidersData);\n } else {\n additionalDataKeys = [];\n }\n for (var additionalDataIndex = 0; additionalDataIndex < additionalDataKeys.length; additionalDataIndex++) {\n var accountFound = false; \n for (var accountIndex = 0; accountIndex < vm.accounts.length && !accountFound; accountIndex++) {\n if (additionalDataKeys[additionalDataIndex] === vm.accounts[accountIndex].customerId) {\n console.log('FOUND ACCOUNT - ' + additionalDataKeys[additionalDataIndex]);\n accountFound = true;\n vm.accounts[accountIndex].status = 'CONNECTED';\n vm.accounts[accountIndex].connected = new Date();\n vm.accounts[accountIndex].proverData = additionalDataKeys[additionalDataIndex];\n vm.connectedAccounts.push(vm.accounts[accountIndex]);\n }\n }\n }\n for (var accountIndex = 0; accountIndex < vm.accounts.length; accountIndex++) {\n if (vm.accounts[accountIndex].status === 'DISCONNECTED')\n vm.disconnectedAccounts.push(vm.accounts[accountIndex]);\n }\n }", "function onAccountChanged(acc) {\n\n account.current = acc;\n forceUpdate();\n updateUserSpecificBlockchainData();\n\n }", "async loadBlockchainData(){\n const web3 = window.web3;\n const accounts = await web3.eth.getAccounts()\n this.setState({\n account: accounts[0]\n })\n const networkId = await web3.eth.net.getId()\n const networkData = HealthCare.networks[networkId]\n if(networkData){\n const abi = HealthCare.abi\n const address = networkData.address\n//fetch contract\n const contract = new web3.eth.Contract(abi, address)\n this.setState({\n contract: contract\n })\n console.log(this.state.contract);\n // const HealthCareHash = await contract.methods.get().call()\n // this.setState({\n // HealthCareHash: HealthCareHash\n // })\n }else{\n window.alert(\"Smart contract not deployed to detected network\")\n }\n \n console.log(networkId)\n\n\n //console.log(accounts)\n\n }", "accountDidChange(data) {\n this.get(\"routing\").transitionTo('protected.accounts.account.entries', [data.node.original.id]);\n }", "getUserAccount(){\n\t\tconsole.log(\"get account\");\n\n\t\tAPI.getUserAccount()\n\t\t.then(data => {return data.json()})\n\t\t.then(jsonObj => {\n\t\t\t// console.log(\"jsonObj\",jsonObj)\n\t\t\t// if there is account data\n\t\t\tif(Object.keys(jsonObj).length > 0){\n\t\t\t\t// console.log(\"has keys\")\n\t\t\t\tthis.setState({\n\t\t\t\t\tname: jsonObj.name,\n\t\t\t\t\tstreet: jsonObj.street,\n\t\t\t\t\tcity: jsonObj.city,\n\t\t\t\t\tstate: jsonObj.state,\n\t\t\t\t\tzip: jsonObj.zip,\n\t\t\t\t\tcountry: jsonObj.country,\n\t\t\t\t\tphone: jsonObj.phone,\n\t\t\t\t\tlastFour: jsonObj.lastFour,\n\t\t\t\t\tcardExpire: jsonObj.cardExpire,\n\t\t\t\t\tcreatedAt: moment(jsonObj.createdAt).format(\"M/DD/YYYY\"),\n\t\t\t\t\thasData: true,\n\t\t\t\t\tshowForm: false\n\t\t\t\t});\n\t\t\t}\n\t\t})\n\t \t.catch(err => console.log(\"err\",err));\n\t}", "async fetchState() {\n this._state = await this.connection.provider.query(`account/${this.accountId}`, '');\n }", "fetchUserAccount() {\n if ( !this._apikey || !this._ajax ) return;\n\n this._ajax.get( this.getSignedUrl( '/v3/account' ), {\n type: 'json',\n headers: { 'X-MBX-APIKEY': this._apikey },\n\n success: ( xhr, status, response ) => {\n let balances = this.parseUserBalances( response );\n this.emit( 'user_balances', balances );\n this.emit( 'user_data', true );\n },\n error: ( xhr, status, error ) => {\n this.emit( 'user_fail', error );\n this.stopUserStream();\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the event handler for the completion of the DOM loading. This creates the Grid within the body element.
function initHexGrid() { console.log('onDocumentLoad'); window.removeEventListener('load', initHexGrid); var hexGridContainer = document.getElementById('hex-grid-area'); main.grid = window.hg.controller.createNewHexGrid(hexGridContainer, app.data.postData, false); app.parameters.initDatGui(main.grid); app.data.fetchData(updateTileData); }
[ "function social_curator_grid_post_loaded(data, element){}", "load() {\n $(this.parentPageDom).append(this.render());\n this._bindEvent();\n this._bindResizable();\n }", "function pageLoaded() {\n\n\t\t// injectSVG(); // inject them SVGs\n\n\t\trowHeight();\n\t\ttoggleShit();\n\n\t}", "function loadGrid() {\n \n }", "function drawGrid() {\n\t\t\t// add container styles\n\t\t\t$container.addClass('container gantt');\n\t\t\t\n\t\t\t// empty container\n\t\t\t$container.empty();\n\t\t\t\t\t\t\n\t\t\t// render contents into container\n\t\t\t$container.append(gridTmpl(controller));\t\n\t\t\tinitEls();\n\t\t\t\n\t\t\t// adjust layout components\n\t\t\tadjustLayout();\n\t\t\tinitHScroller();\t\t\t\n\t\t}", "function pageLoaded() {\n\tbuildPage();\n}", "function bodyOnLoad() {\n }", "function attachNewsGridLoader() {\n if (pdf(\"dbFrame\").el('newsFrame').readyState == 'complete') { \n hideLayer();\n pdf(\"dbFrame\").el('newsFrame').detachEvent(\"onreadystatechange\", attachNewsGridLoader);\n }\n}", "createAllElements(){\n\t\tvar body = this.AddNewNestedElement(document.body).getAElement();\n\n\t\tlog(\"Add body\");\n\t\tlog(this.camera.getAElement().hasLoaded);\n\n\t\tif(this.camera.getAElement().hasLoaded)\n\t\t\tthis.a_element_container.appendChild(body);\n\t\telse\n\t\t\tthis.camera.getAElement().addEventListener(\"loaded\", (function(){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t this.a_element_container.appendChild(body);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}).bind(this) );\n\t}", "function onBodyLoaded () {\r\n // onWindowLoaded is the event that is fired when the full page is loaded.\r\n // Do not use this one!\r\n}", "ready() {\n this._root = this._createRoot();\n super.ready();\n this._firstRendered();\n }", "function handleDOMConentLoaded() {\n\tconst scaffold = window[\"my-site\"];\n\n\tfunction cb() {\n\t\t// Do something after components initialize\n\t}\n\n\t// Call component constructors\n\tpop({ scaffold, classMap, actions, cb });\n}", "createGridElement_() {\n let gridDiv = document.getElementById('grid-container');\n while (gridDiv.firstChild) {\n gridDiv.removeChild(gridDiv.firstChild);\n }\n\n for (let i = 0; i < this.numRows_; i++) {\n for (let j = 0; j < this.numCols_; j++) {\n let cellElement = this.cells_[i][j].getElement();\n gridDiv.appendChild(cellElement);\n }\n }\n }", "function pageLoaded() {\n\n\t\t// add 'has_scrollbar' class for OSs that use a visible scrollbar\n\t\tif (hasScrollbar) {\n\t\t\tclassie.add(elHTML, 'has_scrollbar');\n\t\t}\n\n\t\t// the rest of the code does not apply to IE9, so exit\n\t\tif ( classie.has(elHTML, 'ie9') ) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar elHeader = document.getElementsByTagName('header')[0];\n\n\t\telHeader.addEventListener(animationEvent, removeFOUT);\n\n\t\tfunction removeFOUT() {\n\n\t\t\tclassie.add(elHTML, 'ready');\n\t\t\telHeader.removeEventListener(animationEvent, removeFOUT);\n\n\t\t\tlayoutPackery();\n\n\t\t}\n\n\t}", "initGridCanvas() {\n this.gridCanvas = createCanvas('grid');\n this.containerElement.appendChild(this.gridCanvas);\n }", "function loadGridMenu(){\n\t$.ajax({\n url: \"pages/ConfigEditor/gridPopup.html\",\n dataType: 'html',\n success: function(data) {\n\t\t\t$(\"#gridPanel\").append(data);\n//\t\t\t$( \"#configEditorPage\" ).trigger('create');\n\t\t loadBarsMenu();\n\n\t\t}\n\t});\n}", "function populatePage() {\n \"use strict\";\n // Compile Handlebars template\n var source = $(\"#toCompile\").html();\n var template = Handlebars.compile(source);\n var compiled = template(globalDataObj);\n $('#compiledContainer').html(compiled);\n\n Materialize.updateTextFields(); // Ensures labels are properly set to active or inactive\n $('.collapsible').collapsible(); // update collapsible objects after render\n\n // populate history\n if (globalDataObj.hasOwnProperty('medicalHistory')) {\n $('#historyContainer').empty();\n $('#historyContainer').html(atob(globalDataObj.medicalHistory));\n }\n\n // populate diagnostics\n if (globalDataObj.hasOwnProperty('diagnostics')) {\n $('#diagnosticContainer').empty();\n $('#diagnosticContainer').html(atob(globalDataObj.diagnostics));\n }\n\n pageActive = true;\n registerEditListeners();\n loadImage();\n}", "function buildGrid() {\r\n // REMOVE THE EXISTING SET OF ROWS BY REMOVING THE ENTIRE TBODY SECTION\r\n tbody;\r\n let tableEle = tbody[0].parentNode;\r\n tableEle.removeChild(tbody[0]);\r\n // REBUILD THE TBODY FROM SCRATCH\r\n let newTbody = document.createElement('tbody');\r\n // LOOP THROUGH THE ARRAY OF EMPLOYEES\r\n for (let empdetails of empData ){\r\n newTbody.appendChild(createTableRow(empdetails));\r\n }\r\n // REBUILDING THE ROW STRUCTURE\r\n tableEle.appendChild(newTbody);\r\n\r\n // BIND THE TBODY TO THE EMPLOYEE TABLE\r\n\r\n // UPDATE EMPLOYEE COUNT\r\n empCount.value = empData.length;\r\n // STORE THE ARRAY IN STORAGE\r\n localStorage.setItem('empdetails', JSON.stringify(empData))\r\n\r\n}", "function onBodyLoad(){\n //console.log(\"onBodyLoad\");\n loadThemesJSON();\n loadConfigJSON();\n initializeJoint(); \n openDialogSelectNetwork(); \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move to next visible property.
NextVisible() {}
[ "function mainMoveToNextProperty(wnd)\n\t{\n\t\tif (incrementCurrentPropertyIndex())\n\t\t{\n\t\t\tmainShowCurrentProperty(wnd);\n\t\t}\n\t\telse\n\t\t{\n\t\t\twnd.location.replace(\"weights.html\"); // --> Finished answering questions.\n\t\t}\n\t}", "next() {\n if (this.isHide()) return;\n\n const oldSelected = this._getSelectedDomItem();\n if (!oldSelected) return;\n let selected = oldSelected;\n\n while (selected.nextElementSibling) {\n selected = selected.nextElementSibling;\n\n if (selected.matches('.cmd-palette-item--hide')) continue;\n break;\n }\n\n oldSelected.removeAttribute('selected');\n selected.setAttribute('selected', 'selected');\n\n PaletteCommand._scrollTo(selected);\n }", "toggleVisible(previousProp, nextProp) {\n if (!isShallowEqual(previousProp, nextProp)) {\n if (nextProp === true) this.massMarks.show();\n if (nextProp === false) this.massMarks.hide();\n }\n }", "function gotoNextStep()\n {\n var stepNumber = vm.currentStepNumber + 1;\n\n // Test the following steps and make sure we\n // will land to the one that is not hidden\n for ( var s = stepNumber; s <= vm.steps.length; s++ )\n {\n if ( !isStepHidden(s) )\n {\n stepNumber = s;\n break;\n }\n }\n\n vm.setCurrentStep(stepNumber);\n }", "function nextProperty() {\n if (currProperty && currSelectors) {\n currSelectors.properties.push(currProperty);\n prevProperty = currProperty;\n currProperty = null;\n }\n }", "function nextMove() {\n move(canBeMoved(this));\n }", "toggleVisible(previousProp, nextProp) {\n if (!isShallowEqual(previousProp, nextProp)) {\n if (nextProp === true) this.tileLayerTraffic.show();\n if (nextProp === false) this.tileLayerTraffic.hide();\n }\n }", "function gotoNext() {\n showStep(vm.currentStep + 1);\n }", "next() {\n this.selectedIndex = Math.min(this._selectedIndex + 1, this.steps.length - 1);\n }", "toggleVisible(previousProp, nextProp) {\n if (!isShallowEqual(previousProp, nextProp)) {\n if (nextProp === true) this.bezierCurve.show();\n if (nextProp === false) this.bezierCurve.hide();\n }\n }", "moveNext() {\n let next = this.currentRef + 1;\n let index = this.slides[next] ? next : 0;\n\n this.slideWrapper.setAttribute('data-dir', 'next');\n this.moveToIndex(index);\n }", "function next() {\n $ctrl.index++;\n\n // Move on if all players have been shown\n if ($ctrl.index === $ctrl.players.length) {\n $state.go('play');\n }\n // Otherwise show next role\n else {\n showRole();\n }\n }", "scrollNext() {\n this.appendActivator();\n this.scrollCurrentPosition++;\n this.cardsScroll.style.left = `-${this.scrollCurrentPosition * this.stepSize}px`;\n this.showControls();\n }", "next() {\n const index = this.steps.indexOf(this.currentStep);\n\n if (index === this.steps.length - 1) {\n this.complete();\n } else {\n this.show(index + 1, true);\n }\n }", "next() {\n this.slider.move(1);\n }", "next() {\n const { index, showTooltip } = this.state;\n const { steps } = this.props;\n const nextIndex = index + 1;\n\n const shouldDisplay = Boolean(steps[nextIndex]) && showTooltip;\n\n this.logger('joyride:next', ['new index:', nextIndex]);\n this.toggleTooltip(shouldDisplay, nextIndex, 'next');\n }", "next() {\n const newIndex = this.index + 1;\n\n if (this.isOutRange(newIndex)) {\n return;\n }\n\n this.doSwitch(newIndex);\n }", "next() {\n const activeItem = this._getActiveItem()\n let nextItem = null\n\n // check if last item\n if (activeItem.position === this._items.length - 1) {\n nextItem = this._items[0]\n } else {\n nextItem = this._items[activeItem.position + 1]\n }\n\n this.slideTo(nextItem.position)\n\n // callback function\n this._options.onNext(this)\n }", "advance() {\n var steps = this.get('steps');\n var step = this.get('step');\n var i = steps.findIndex((e) => e === step);\n\n if (steps[i+1]) {\n this.set('step', steps[i+1]);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New random color variable for next
newNextColor() { if (this.gameOver) { return; } this.nextBlob1Color = Math.floor(Math.random() * this.puyoVariations) + 1; this.nextBlob2Color = Math.floor(Math.random() * this.puyoVariations) + 1; this.state.updateNextBlobs(); }
[ "function randomColor(){\n\n\t\t//Random number generator 0-3\n\t\tvar randomNumber = Math.floor((Math.random() * 4));\n\t\tvar color = colors[randomNumber];\n\t\tsimonSequence.push(color);\n\t}", "function randomColor() { return Math.floor(Math.random() * 16777215); }", "function randomize() {\n color1.value = createHexValue();\n color2.value = createHexValue();\n setGradient();\n}", "function generateNewColor() {\n var newNumber = Math.floor(Math.random() * ((4-0)+1) + 0);\n if (newNumber === 1) {\n computer.sequence.push(\"green\");\n } else if (newNumber === 2) {\n computer.sequence.push(\"red\");\n } else if (newNumber === 3) {\n computer.sequence.push(\"yellow\");\n } else {\n computer.sequence.push(\"blue\");\n }\n iterator();\n}", "function randomColor() {\n //When values for randomNumber(0, colors.length) only 2 colors are being picked, why?\n//sets value to open string in the $(document).ready(function()\n currentColor = colors[randomNumber(0, colors.length-1)];\n }", "function change_color() {\n r = random(100, 256);\n g = random(100, 256);\n b = random(100, 256);\n}", "function genColorVal(){\r\n return Math.floor(Math.random() * 256);\r\n }", "function newcolor(){\r\n var r = Math.floor(Math.random() * 256);\r\n var g = Math.floor(Math.random() * 256);\r\n var b = Math.floor(Math.random() * 256);\r\n var c = (\"rgb(\" + r + \", \" + g + \", \" + b + \")\");\r\n return c;\r\n\r\n}", "setRandomColor()\n {\n for(let i=0;i<this.n;i++)\n {\n //r g and b are all values between 0-255 inclusive \n let r = (Math.floor(Math.random()*Math.floor(256)))/256;\n let g = (Math.floor(Math.random()*Math.floor(256)))/256;\n let b = (Math.floor(Math.random()*Math.floor(256)))/256; \n this.vertices[i].setColor(r,g,b); \n }\n //console.log(this.color+\"\\n\"); \n }", "setRandomColor(){\n let newColor = RGB.makeRandomColor();\n this._color.setColor(newColor.r, newColor.g, newColor.b);\n }", "function colorChange(){\n\tvar r = Math.floor((Math.random() * 300) + 1);\n\tvar g = Math.floor((Math.random() * 200) + 1);\n\tvar b = Math.floor((Math.random() * 200) + 1);\n\treturn \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function newRandomColor() {\r\n var num = Math.floor(Math.random() * (numColors - 1));\r\n\r\n if (num >= randomColorNumber) {\r\n num++;\r\n }\r\n\r\n randomColorNumber = num;\r\n return colorArray[num];\r\n}", "pushNewColor() {\n const idx = Math.floor(Math.random() * this.colors.length);\n this.correctSequence.push(this.colors[idx])\n }", "function generateRandomColors() {\r\n color1.value = getRandom();\r\n color2.value = getRandom();\r\n setGradient();\r\n}", "function generateColor() {\n return Math.floor(Math.random() * 256);\n}", "function addNewColor() {\n LOG(LOG_DEBUG, \"Add new color, sequence now is:\");\n var coloridx = Math.floor(Math.random() * (LAST_BUTTON + 1 - FIRST_BUTTON) + FIRST_BUTTON);\n coloridx = 1;\n simonsSequence.push(coloridx);\n LOG(LOG_DEBUG, simonsSequence)\n showSimonsSequence(false);\n\n}", "function getRandomColorIncrementValue() {\n return calcRndGenMinMax(1, 8);\n }", "function generateColor(){\n\tvar colorType = (Math.floor(Math.random()*20)+1)%7;\n\tvar colorpool = [\"#ff4500\", \"#ffa500\", \"#40e0d0\", \"#ffff00\", \"#87cefa\", \"#ffb6c1\", \"#00ff00\"];\n\tcolor = colorpool[colorType];\n}", "function addNextColor(){\n var randomNumber = Math.round((Math.random() * 10) / 3);\n var randomChosenColor = buttonColors[randomNumber]; // stores randomly selected color\n gamePattern.push(randomChosenColor); // append randomly selected color to gamePattern\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for deleteEnvironmentForRepository / Delete an environment
deleteEnvironmentForRepository(incomingOptions, cb) { const Bitbucket = require('./dist'); let apiInstance = new Bitbucket.DeploymentsApi(); // String | The account // String | The repository // String | The environment UUID. /*let username = "username_example";*/ /*let repoSlug = "repoSlug_example";*/ /*let environmentUuid = "environmentUuid_example";*/ apiInstance.deleteEnvironmentForRepository( incomingOptions.username, incomingOptions.repoSlug, incomingOptions.environmentUuid, (error, data, response) => { if (error) { cb(error, null, response); } else { cb(null, '', response); } } ); }
[ "deleteEnvironment(env) {\n if(['*', 'default', 'gui'].indexOf(env) === -1)\n {\n const INPUT_SETTINGS = global.settings.input;\n if(this.environment === env) INPUT_SETTINGS.I_ENVIRONMENT = this.environment = 'default';\n this.environments.splice(this.environments.indexOf(env), 1);\n this.registry[env] = null;\n }\n }", "function envRemoveAgree(env_id){\n var env = new Environment(env_id);\n env.trash();\n}", "cleanupEnvironment() {}", "function deleteEnvironment() {\n var r = confirm(\"Delete environment\\nName: \" + currentEnvironment.name);\n\n if (r === true) {\n environmentHandler.deleteEnvironment(currentEnvironment.id);\n environmentHandler.loadProducts(displayEnvironments);\n }\n\n $(\"#popupUpdateDelete\").popup(\"close\");\n}", "function deleteArchitecture(domain, architecture) {\n name = architecture.Architecture + \" - \" + architecture.Version\n\n // delete architecture\n return fetch(\"http://\" + window.location.hostname + \":\" + window.location.port + \"/architecture/\" + domain + \"/\" + name, {method: \"DELETE\"})\n .then((response) => response.text())\n}", "delete() {\n // Query API to delete repo, this will trigger sadness in the dashboard too\n }", "function ucd_pacdeleteenvironment(project_name,authorization,project_name,no_of_environment,callback)\r\n{\r\n console.log(\"Deletion of Environment for Project Area has Started\");\r\n project_name = project_name;\r\n for (var i = 0 ; i < no_of_environment ; i++)\r\n {\r\n \tif ( i === 0)\r\n \t{\r\n \t\tenv_name = \"Dev\";\r\n \t\t\r\n \t}else if(i === 1){\r\n env_name = \"Test\";\r\n \t\t\r\n \t}else{\r\n \t\tenv_name = \"Prod\";\r\n \t\t\r\n \t};\r\n request({\r\n headers:\r\n {\r\n 'Authorization': authorization,\r\n 'Content-Type': 'application/json'\r\n },\r\n method: \"DELETE\",\r\n uri:myConstants.UCD_BASE_URL+'/cli/environment/deleteEnvironment?application='+project_name+'&environment='+env_name,\r\n timeout:myConstants.UCD_TIMEOUT\r\n },function(err,res,body){\r\n if (err===null)\r\n {\r\n if (res.statusCode===200 || res.statusCode===201 || res.statusCode===204 )\r\n {\r\n \r\n console.log(\"Creation of Environment for Project Area and its linkage is Established\");\r\n \r\n \r\n }else{\r\n var error = myError.seterror(myErrorConst.SERVICE_BUSINESS_EXCEPTION,myErrorConst.UCD_ENVIRONMEMT_DELETE_ERR,JSON.stringify(res));\r\n console.log(JSON.stringify(error));\r\n callback(err,null);\r\n \r\n } \r\n }else{\r\n var error = myError.seterror(myErrorConst.SERVICE_RUNTIME_EXCEPTION,myErrorConst.UCD_ENVIRONMEMT_DELETE_ERR,JSON.stringify(err));\r\n console.log(JSON.stringify(error));\r\n callback(err,null);\r\n }; \r\n });\r\n };\r\n }", "function deleteEnvNFZ (req, res) {\r\n\tconsole.log ('DELETE /environment/:scenarioID/nfzs/:nfzID');\r\n\t// delete the NFZ from the DB\r\n\tNFZ.remove ({'_id' : req.params.nfzID}, function (err, nfz) {\r\n\t\tif (err) {\r\n\t\t\tres.status(500).send({ message : 'Error while deleting the NFZ in the DB'});\r\n\t\t} else {\r\n\t\t\tif (!nfz) {\r\n\t\t\t\tres.status(404).send({ message : 'NFZ does not exist in the DB'});\r\n\t\t\t} else {\r\n\t\t\t\t//remove the deleted sensor from the given UAV\r\n\t\t\t\tScenario.findOneAndUpdate (\r\n\t\t\t\t\t{'_id' :req.params.scenarioID},\r\n\t\t\t\t\t{ $pull : {\r\n\t\t\t\t\t\t'environment.nfzs': req.params.nfzID}\r\n\t\t\t\t\t},\r\n\t\t\t\t\t{new : true}).\r\n\t\t\t\t\texec(function (err, scenario) {\r\n\t\t\t\t\t\tif (err) {\r\n\t\t\t\t\t\t\tres.status(500).send({ message : 'Error while deleting the NFZ of the scenario'});\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tif (!scenario) {\r\n\t\t\t\t\t\t\t\tres.status(404).send({ message : 'Scenario does not exist in the DB'});\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tres.status(200).jsonp(scenario.environment.nfzs);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t}\r\n \t}\r\n\t});\r\n}", "delete(application, context) {}", "static deleteProject(projectName) {\n const todoList = Storage.getTodoList()\n todoList.deleteProject(projectName)\n Storage.saveTodoList(todoList)\n }", "function _testSuiteCleanUp() {\n return ImptTestHelper.runCommand(`impt product delete -p ${PRODUCT_NAME} -f -q`, ImptTestHelper.emptyCheck).\n then(() => ImptTestHelper.runCommand(`impt project delete --all -q`, ImptTestHelper.emptyCheck));\n }", "del() {\n let argv = this.argv;\n let key = argv.del || argv.d;\n let config = this.readSteamerConfig({ isGlobal: this.isGlobal });\n\n delete config[key];\n\n this.createSteamerConfig(config, {\n isGlobal: this.isGlobal,\n overwrite: true,\n });\n }", "function cleanup() {\n\n var ds = application.dataStore;\n\n //delete the application's directory. This will auto-delete any contained accounts and groups:\n ds.getResource(application.defaultAccountStoreMapping.href, function(err, mapping) {\n if (err) throw err;\n\n console.log('Retrieved application accountStoreMapping for deletion:');\n console.log(mapping);\n\n ds.deleteResource(mapping.accountStore, function(err) {\n if(err) throw err;\n\n console.log('Deleted application directory.');\n\n application.delete(function(err) {\n if (err) throw err;\n console.log('Deleted application.');\n });\n });\n });\n}", "function delvars () {\n const argv = process.argv;\n\n ['NODE_CONFIG', 'NODE_CONFIG_DIR'].forEach(function (name) {\n const argName = '--' + name + '='\n\n for (let i = 2; i < argv.length; i++) {\n if (argv[i].indexOf(argName) === 0) {\n argv[i] = 'DEL'\n }\n }\n if (process.env[name]) {\n delete process.env[name]\n }\n })\n}", "async function deleteTenantConfiguration() {\n const subscriptionId =\n process.env[\"PORTAL_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const configurationName = \"default\";\n const credential = new DefaultAzureCredential();\n const client = new Portal(credential, subscriptionId);\n const result = await client.tenantConfigurations.delete(configurationName);\n console.log(result);\n}", "function cleanup() {\n const patProjectdir = './public/projects/';\n shell.rm('-Rf', patProjectdir);\n shell.rm('-Rf', '*.db');\n}", "function repoManagerDeleteRepo(repo, appName) {\n var appRepos = repos[appName]; // This should never happen...\n\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(\"Database \" + appName + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}", "function destroyProject(model, callback) {\n var rm = function(basePath, callback) {\n var killswitch = false;\n Step(\n function() {\n fs.stat(basePath, this);\n },\n function(err, stat) {\n if (stat.isDirectory()) {\n this();\n } else if (stat.isFile()) {\n killswitch = true;\n fs.unlink(basePath, this);\n } else {\n killswitch = true;\n this();\n }\n },\n // The next steps apply only when basePath refers to a directory.\n function(err) {\n if (killswitch) return this();\n fs.readdir(basePath, this);\n },\n function(err, files) {\n if (killswitch) return this();\n if (files.length === 0) {\n this();\n } else {\n var group = this.group();\n for (var i = 0; i < files.length; i++) {\n rm(path.join(basePath, files[i]), group());\n }\n }\n },\n function(err) {\n if (killswitch) return callback();\n fs.rmdir(basePath, callback);\n }\n );\n };\n var modelPath = path.join(settings.files, 'project', model.id);\n rm(modelPath, callback);\n}", "function repoManagerDeleteRepo(repo, appName) {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the SWFUploader with the given ID
function getUploader(uploaderId) { for (var i = 0; i < uploaders.length; i++) { if (uploaders[i].movieName == uploaderId) { return uploaders[i]; } } return null; }
[ "function getUploader(uploaderId) {\n for (var i = 0; i < uploaders.length; i++) {\n if (uploaders[i].movieName == uploaderId) {\n return uploaders[i];\n }\n }\n return null ;\n }", "getById(id) {\r\n return new Drive(this, id);\r\n }", "function object_flash( id ){\n\tif(!Flash_checkForMinPlayer()) {return null;}\n\treturn document.getElementById(id);\n}", "static async from_video_id(id) {\n\t\tif(id.includes('/embed/')) id = id.slice(id.indexOf('/embed/') + 7);\n\n\t\tlet page = (await request.get_embed_page(id)).body;\n\n\t\tlet url_start = page.indexOf('\"jsUrl\":');\n\t\tif(url_start === -1) throw new Error(\"Could not find player file\");\n\t\turl_start = page.indexOf('\"', url_start + 8) + 1;\n\n\t\tlet url_end = page.indexOf('\",', url_start + 1);\n\n\t\treturn new CipherLoader(page.slice(url_start, url_end));\n\t}", "function uploader(instanceToStore) {\n return dataStore(\"uploader\", instanceToStore);\n }", "function getFile(id){\n\t\t\tfor(var i = 0; i < $scope.files.length; i++){\n\t\t\t\tif($scope.files[i].id == id){\n\t\t\t\t\treturn $scope.files[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function _getSWF()\n\t{\n\t\tvar tags = ['object', 'embed'];\n\t\tfor (var i = 0; i < tags.length; i++)\n\t\t{\n\t\t\tvar a = document.getElementsByTagName(tags[i]);\n\t\t\tfor (var j = 0; j < a.length; j++)\n\t\t\t{\n\t\t\t\tif (a[j].dispatchStateChangeEvents)\n\t\t\t\t{\n\t\t\t\t\treturn a[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "function getPlaylistById(id){\n let playlistById = player.playlists.filter(playlist =>{\n if(playlist.id === id){\n return playlist;\n }\n })\n return playlistById[0];\n }", "function getFileById(id) {\n return _.findWhere(files, {id: id});\n }", "function getPlayer()\n{\n var player = document.getElementById(getPlayerId());\n \n if (player == null)\n player = document.getElementsByTagName('object')[0];\n \n\t// STL commented out -- SWFObject does slightly different embedding\n\t// and this code is not compatible with it.\n\t// see http://fbflex.wordpress.com/2008/07/05/getting-the-flex-browsermanager-working-with-swfobject/\n //if (player == null || player.object == null)\n // player = document.getElementsByTagName('embed')[0];\n\n return player;\n}", "function find(id) {\n\t\tvar result = videos.filter((video) => video.id == id );\n return result? result[0] : null;\n\t}", "function getSound(id) {\r\n if (id !== undefined) {\r\n var sound = jWebAudio.soundArray[id];\r\n } else {\r\n $.error('Please call createSound first!');\r\n return;\r\n }\r\n return sound;\r\n }", "function getFlashObject( id )\n{\n var flashObj = null; \n \n\t// Check for Internet Explorer \n if(navigator.appName.indexOf(\"Microsoft\") != -1) {\n flashObj = window[id];\n }\n else {\n\n // Index our ID within the document object\n if(document[id].length != undefined) {\n flashObj = document[id][1];\n }\n else {\n flashObj = document[id];\n }\n }\n \n // We want to alert them if the object was not found.\n if( !flashObj ) {\n alert( id + \" not found!\" );\n }\n \n return flashObj;\n}", "getMediaFromStore (id) {\n return new Promise((resolve, reject) => {\n\n const transaction = this.getTransaction();\n\n // Retreive file\n const req = transaction.objectStore(storeName).get(id);\n req.onsuccess = (event) => {\n // Get media from event\n const media_blob = event.target.result;\n\n if (media_blob != null)\n resolve(media_blob); // Return media\n else\n reject(null); // Return media\n }\n });\n }", "getById(id) {\r\n return new DriveItem(this, id);\r\n }", "function get(id){\n return streams[id];\n }", "function getVideo(id)\r\n{\r\n\tfor(var i in videos)\r\n\t\tif(videos[i].id == id)\r\n\t\t\treturn videos[i];\r\n\treturn null;\r\n}", "function getFlashMovie(movieId) {\n return document.getElementById(movieId);\n }", "getFileSDKInstance(pluginId) {\n return new FileSDK_1.default(pluginId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fills in the tabbed display of metadata for one model
function listMetadata(name){ console.log("in listMetadata"); if (name != null) { document.getElementById("metadata_holder").style.display = "block"; document.getElementById("type_holder").style.display = "none"; console.log(" model to display is " + name); getMetadata(master_data, name); // extract the metadata for that model openOverview(); } return false; }
[ "function show_edit_metadata(exp_id) {\n fill_controlled_vocabulary(null);\n fill_run_category_vocabulary(exp_id, null);\n var exp = experiment_metadata[exp_id];\n $.each(metadata_fields, function(index, val) {\n var input_id = val[2];\n var field_value = exp[input_id];\n $(\"#\" + input_id).val(field_value);\n });\n fill_edit_runs(exp_id);\n }", "async function showInfo() {\n \n var data = await tf.io.listModels(),\n table = document.querySelector('#mdata'),\n tx = db.transaction(\"models_store\", \"readonly\"),\n store = tx.objectStore(\"models_store\");\n\n empty(table);\n // Update table data\n (function (callback) {\n for (let key in data) {\n let name = key.split(\"/\").pop(),\n date = data[key].dateSaved.toString().slice(0,15),\n size = (data[key].modelTopologyBytes + data[key].weightDataBytes + data[key].weightSpecsBytes) / (1024*1024),\n row = table.insertRow(),\n classes, input_shape, td;\n store.get(name).onsuccess = function (e) {\n classes = (e.target.result.classes.join(', '));\n input_shape = e.target.result.input_shape.slice(1, 3).join(\"x\");\n td = row.insertCell();\n td.innerHTML = name.slice(0, -3);\n td = row.insertCell();\n td.innerHTML = classes;\n td = row.insertCell();\n td.innerHTML = input_shape;\n td = row.insertCell();\n td.innerHTML = +size.toFixed(2);\n td = row.insertCell();\n td.innerHTML = date;\n }\n }\n callback;\n })($UI.infoModal.open())\n\n\n}", "function refreshMetaData() {\n $('#metadata')[0].innerHTML = '';\n if (!(Object.keys(editor.openStories).includes(current_story))) {\n current_page = null;\n return;\n }\n\n meta = 'Engine Details: ';\n num_pages = Object.keys(editor.getStoryPageList(current_story)).length;\n story_id = editor.openStories[current_story].getCurrent().story_id;\n meta += 'id=' + story_id + ', name=' + current_story + ', root=' + \n editor.getStoryState(current_story)['root_name'] + ', #pages=' + num_pages;\n $('#metadata')[0].innerHTML = meta;\n}", "function make_browse_metadata_form() {\n var div = $(\"#exp-metadata-tab\");\n // console.log(metadata_fields);\n $.each(metadata_fields, function(index, val) {\n var span_id = \"browse-\" + val[2];\n var label = $(\"<label/>\", { \"class\": \"col-2 col-form-label\",\n \"for\": span_id }).text(val[0]);\n var span = $(\"<span/>\", { \"class\": \"col-10 col-form-label metadata-value\",\n \"id\": span_id });\n div.append($(\"<div/>\", { \"class\": \"form-group row\" })\n .append(label, span));\n });\n }", "function populateInformationModal() {\n\t// add text to the label\n\tvar category = allViews[activeView];\n\t// trim the heading \"TissueSpecific\" if necessary\n\tif (category.substr(0,14) == \"TissueSpecific\") {\n\t\tcategory = category.substr(14);\n\t}\n\t$('#informationLabel').text(category+\" Information\"); \n\t\n\t// now put info text in body\n\t$('#informationBody').html(allInfoFiles[activeView]);\n\t\n}", "function setupPersonFullView() {\r\n populatePersonFullData();\r\n}", "function show_model_details() {\n\n // get the short id of the selected item\n var shortid = $('[id^=selectbox_]').parent().find(\"option:selected\").val();\n\n // call django view to get model program metadata\n $.ajax({\n type: \"GET\",\n url: '/hsapi/_internal/get-model-metadata/',\n data: {resource_id:shortid},\n success: function (data) {\n\n // if the data is empty, hide the table\n if (Object.keys(data).length == 0){\n // set the visibility of the table element (hide)\n table = document.getElementById('program_details_div');\n table.style.display = 'none';\n }\n // if the data is not empty, populate the model details table\n else {\n // set the visibility of the table element (visible)\n table_div = document.getElementById('program_details_div');\n table_div.style.display = 'block';\n\n // create and ordered list of keys to access input data\n var keys = [\"description\", \"date_released\", \"software_version\", \"software_language\", \"operating_sys\", \"url\"];\n\n // populate metadata inside description div\n var rows = document.getElementById('program_details_table').rows;\n for (i = 0; i < rows.length; i++) {\n\n // get the current row element\n var row = rows[i];\n\n // get the second cell in the row\n var cell = row.cells[1];\n\n if (keys[i] != \"url\") {\n // set the text for this cell\n cell.innerText = data[keys[i]]\n }\n else {\n // insert an href for the url item\n cell.innerHTML = \"<a href= \" + data['url'] + \" target='_blank'>Resource Landing Page</a>\"\n }\n }\n }\n },\n error: function (data) {\n console.log('There was an error with model instance GET.')\n },\n complete: function(data){\n\n // Sets the ModelProgram shortid to the hidden model_name field. This field is submitted to django and used to set\n // database fields ModelName and ModelForeignKey.\n document.getElementById('id_model_name').value = shortid;\n\n // enable/disable the save button if the value has been changed to something new\n if (shortid != mp_old_id)\n $('#id-executedby').find('.btn-primary').show();\n else\n $('#id-executedby').find('.btn-primary').hide();\n }\n });\n\n}", "setTemplateInfo (state, model) {\n state.title = model['title']\n state.subtitle = model['subtitle']\n state.description = model['description']\n }", "function fill_browse_metadata(exp_id) {\n if (!browse_exp_id)\n return;\n var exp = experiment_metadata[browse_exp_id];\n $.each(metadata_fields, function(index, val) {\n var span_id = val[2];\n var field_value = exp[span_id];\n $(\"#browse-\" + span_id).text(field_value);\n });\n browse_experiment_enable(true, true);\n }", "function segMetainfoJS() {\n frmRowTemplates.segMetainfo.setData([{\n lblSegmeta1: \"Titanium Card\",\n lblSegmeta2: \"$200\",\n lblSegmeta3: \"$400\",\n metainfo: {\n skin: \"segrowfocus\"\n }\n }, {\n lblSegmeta1: \"Gold Card\",\n lblSegmeta2: \"$300\",\n lblSegmeta3: \"$100\",\n metainfo: {\n skin: \"rowFocusSkin\"\n }\n }, {\n lblSegmeta1: \"Silver Card\",\n lblSegmeta2: \"$500\",\n lblSegmeta3: \"$600\",\n metainfo: {\n skin: \"rowSkin\"\n }\n }]);\n}", "function fill_edit_metadata_form() {\n var div = $(\"#edit-metadata-exp\");\n $.each(metadata_fields, function(index, val) {\n var input_type = val[1];\n var input_id = val[2];\n var label = $(\"<label/>\", { \"class\": \"col-2 col-form-label\",\n \"for\": input_id }).text(val[0]);\n var input;\n if (input_type == \"exptype\") {\n container = input = add_exptype_vocab(input_id);\n input.addClass(\"disabled\").attr(\"disabled\", \"disabled\");\n } else if (input_type == \"runcat\") {\n container = input = add_runcat_vocab(input_id);\n } else if (input_type == \"textarea\")\n container = input = $(\"<textarea/>\", { \"id\": input_id });\n else\n container = input = $(\"<input/>\", { \"type\": input_type,\n \"id\": input_id });\n $.each(val[3], function(index, value) {\n input.prop(value[0], value[1]);\n });\n container.attr(\"class\", \"col-10\");\n div.append($(\"<div/>\", { \"class\": \"form-group row\" })\n .append(label, container));\n });\n }", "static setupMetadataPanel() {\n $('#metaDataPanel').hide();\n $('#metaDataPanel .panel-heading').click(() => {\n GUI.hideMetaData();\n DiffDrawer.refreshMinimap();\n });\n }", "onTableModelMetaDataChanged() {\n this._updateContent();\n }", "function show_tab_edit() {\n fill_edit_experiments(experiment_metadata);\n }", "function changeMetaData(data) {\n let $panelBody = document.getElementById(\"metadata-sample\");\n // clear any existing metadata\n $panelBody.innerHTML = \"\";\n // Loop through keys in json response and create new tags for metadata\n for (let key in data) {\n h5Tag = document.createElement(\"h5\");\n metadataText = document.createTextNode(`${key}: ${data[key]}`);\n h5Tag.append(metadataText);\n $panelBody.appendChild(h5Tag);\n }\n}", "function segMetainfoJS()\n{\n\t\n\tfrmRowTemplates.segMetainfo.setData([\n\t\t\t\t\t{lblSegmeta1: \"Titanium Card\",lblSegmeta2: \"$200\",lblSegmeta3: \"$400\",metainfo:{skin:\"segrowfocus\"}}, \n\t\t\t\t\t{lblSegmeta1: \"Gold Card\",lblSegmeta2: \"$300\",lblSegmeta3: \"$100\",metainfo:{skin:\"rowFocusSkin\"}}, \n\t\t\t\t\t{lblSegmeta1: \"Silver Card\",lblSegmeta2: \"$500\",lblSegmeta3: \"$600\",metainfo:{skin:\"rowSkin\"}}\n\t\t\t\t ]);\n\t\t\n}", "function displayMetadata(metaData,ev) {\n\t\t\t$mdDialog.show(\n\t\t\t $mdDialog.alert()\n\t\t\t\t.parent(angular.element(document.querySelector('#popupContainer')))\n\t\t\t\t.clickOutsideToClose(true)\n\t\t\t\t.title('Metadata')\n\t\t\t\t.htmlContent('<table id=\"metadata_table\" class=\"display\" cellspacing=\"0\" width=\"100%\">'+\n\t\t' <thead align=\"left\">'+\n\t\t' <tr class=\"metadataHeader\">'+\n\t\t' <th>Project&nbsp;&nbsp;&nbsp;</th>'+\n\t\t' <th>Layer&nbsp;&nbsp;&nbsp;</th>'+\n//\t\t' <th>Data&nbsp;</th>'+\n//\t\t' <th>Metadata&nbsp;</th>'+\n\t\t' <th>Description&nbsp;&nbsp;&nbsp;</th>'+\n\t\t' <th>Years of Data</th>'+\n\t\t\t' <th>Point of Contact</th>'+\n\t\t' <th>Updated&nbsp;&nbsp;&nbsp;</th>'+\n\n\n\n\t\t' </tr>'+\n\t\t' </thead>'+\n\t\t' <tbody>'+\n\t\t\t\t\tmetaData +\n\t\t\t' </tbody>'+\n\t\t ' </table>\t')\n\t\t\t\t.ariaLabel('Metadata')\n\t\t\t\t.ok('Close')\n\t\t\t\t.targetEvent(ev)\n\t\t\t);\n\n }", "function init_browse_metadata() {\n if (metadata_fields)\n make_browse_metadata_form();\n else\n $.ajax({\n dataType: \"json\",\n method: \"POST\",\n url: BaseURL,\n data: {\n action: \"metadata_fields\",\n },\n success: function(data) {\n metadata_fields = data.results;\n make_browse_metadata_form();\n },\n });\n }", "function demoInfo() {\n d3.select(\"#sample-metadata\").html(\"\");\n d3.select(\"#sample-metadata\").append(\"ul\");\n d3.select(\"ul\").append(\"li\").text(\"id: \" + data.metadata[getId()].id);\n d3.select(\"ul\").append(\"li\").text(\"ethnicity: \" + data.metadata[getId()].ethnicity);\n d3.select(\"ul\").append(\"li\").text(\"gender: \" + data.metadata[getId()].gender);\n d3.select(\"ul\").append(\"li\").text(\"age: \" + data.metadata[getId()].age);\n d3.select(\"ul\").append(\"li\").text(\"location: \" + data.metadata[getId()].location);\n d3.select(\"ul\").append(\"li\").text(\"bbtype: \" + data.metadata[getId()].bbtype);\n d3.select(\"ul\").append(\"li\").text(\"wfreq: \" + data.metadata[getId()].wfreq);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disables / enables the submit button depending on the selected trim. If a valid version is select the submit button is enabled, else not.
function handleSubmitButton() { var trim = document.getElementById("trim").value; var submitButton = document.getElementById("submit"); submitButton.disabled = (trim == ""); }
[ "function changeTrim() {\n if ($trimSelect.val() !== \"\") {\n $submitBtn.removeClass(\"disabled\");\n } else {\n $submitBtn.addClass(\"disabled\");\n }\n }", "function handleSubmitButton(versionName) {\r\n\tvar submitButton = document.getElementById(\"submit\");\r\n\tsubmitButton.disabled = (versionName == \"\");\r\n}", "function update_analyze_button() {\n if ($(\"#analysis\").val() != \"Select...\" &&\n $(\"#analysis_tree\").val() != \"Select...\" &&\n $(\"#analysis_table\").val() != \"Select...\" &&\n $(\"#parameter\").val() &&\n $(\"#parameter\").val() != \"Select...\") {\n $(\"#analyze\").prop(\"disabled\", false);\n } else {\n $(\"#analyze\").prop(\"disabled\", true);\n }\n}", "function enableSubmit(){\n if(radioInfected && fileLoaded){\n document.getElementById(\"sb\").disabled=false\n } else {\n document.getElementById(\"sb\").disabled=true\n }\n}", "function update_upload_button() {\n if (!selected_file || !$(\"#upload-type\").val())\n $(\"#upload-button\").attr(\"disabled\", \"disabled\");\n else\n $(\"#upload-button\").removeAttr(\"disabled\");\n }", "function setSubmitStatus() {\n\t\tvar b = document.getElementById('submitbutton');\n\n\t\tb.className = b.className.replace(new RegExp('(\\\\s|^)disabled(\\\\s|$)'), ' ');\t\t\t\n\t\n\t\tif ( strong && match ) { \n\t\t\tb.removeAttribute('disabled');\n\t\t} else {\n\t\t\tb.setAttribute('disabled', true);\n\t\t\tb.className = b.className + ' ' + 'disabled';\n\t\t}\n\t}", "function toggleSubmitButton() {\n var isValid = true;\n\n if ($('#description').val().replace(/^\\s+/, '') === '' ||\n $('#description').hasClass('invalid') ||\n $('#id_url').hasClass('invalid') ||\n $('#id_email').hasClass('invalid')) {\n isValid = false;\n }\n\n $('#form-submit-btn').prop('disabled', !isValid);\n }", "function enableDisableSubmitButton() {\n var startData = document.getElementById(\"start\").value;\n var destData = document.getElementById(\"destination\").value;\n if (startData != \"\" && destData != \"\") {\n document.getElementById(\"button\").removeAttribute(\"disabled\");\n }\n else {\n document.getElementById(\"button\").setAttribute(\"disabled\", null);\n }\n}", "function enableBtn()\n{\n if (m_iiSubmitCharges)\n $('#submitCharges').attr(\"disabled\", false);\n}", "function validate(){\n const submitButton = document.getElementById('submit')\n let number = document.getElementById('numbers').selectedIndex\n let messageValue =document.getElementById('message').value;\nif(messageValue != \"\" && number>=0 && apiLoggedIn==true) {\nsubmitButton.className = 'button enabledButton'\nsubmitButton.disabled=false;\n}\nelse{\nsubmitButton.className = 'button disabledButton'\nsubmitButton.disabled=true;\n}}", "function bookingButtonEnabler(){\n if(isFormFilled()){\n btnConfirm.disabled = false;\n } else{\n btnConfirm.disabled = true;\n }\n}", "function unlockSubmit() {\n //Cycle through each executable\n for (index = 0; index < executable.length; index++) {\n //Get the current executable\n var currentExecutable = executable[index];\n //If a required element wasn't filled out in this form\n if ( $(\"#\" + currentExecutable).is(\":invalid\") ) {\n //Disable/Lock the submit button\n $(\"#\" + currentExecutable + \" .sendCmdArgs\").prop(\"disabled\", true);\n //If all required elements in a form have been fulfilled\n } else {\n //Enable/Unlock the submit button\n $(\"#\" + currentExecutable + \" .sendCmdArgs\").prop(\"disabled\", false);\n }\n }\n\n}", "function toggleDownload() {\n\t\tif ($(opts.sDateEl).val() == \"\" || $(opts.eDateEl).val() == \"\") {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t}\n\n\t\tif ($(opts.stationEl).val() == null || $(opts.stationEl).val().length < 1) {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\t$(opts.codeEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t}\n\n\t\tif (($(opts.measurementEl).val() == null || $(opts.measurementEl).val().length < 1) && ($(opts.maintenanceEl).val() == null || $(opts.maintenanceEl).val().length < 1)) {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\t$(opts.codeEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t} \n\n\t\t$(opts.submitEl).removeAttr(\"disabled\");\n\t\t$(opts.codeEl).removeAttr(\"disabled\");\n\t}", "function toggleDownload() {\n\t\tif ($(opts.sDateEl).val() == \"\" || $(opts.eDateEl).val() == \"\") {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t}\n\n\t\tif ($(opts.stationEl).val() == null || $(opts.stationEl).val().length < 1) {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\t$(opts.codeEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t}\n\n\t\tif (($(opts.measurementEl).val() == null || $(opts.measurementEl).val().length < 1) && ($(opts.maintenanceEl).val() == null || $(opts.maintenanceEl).val().length < 1)) {\n\t\t\t$(opts.submitEl).attr(\"disabled\", \"disabled\");\n\t\t\t$(opts.codeEl).attr(\"disabled\", \"disabled\");\n\t\t\treturn\n\t\t}\n\n\t\t$(opts.submitEl).removeAttr(\"disabled\");\n\t\t$(opts.codeEl).removeAttr(\"disabled\");\n\t}", "function disableFormOnClick(){\n const notApplicableButton = $('#company-notapplication');\n const companyLegalFieldset = $('#company-legal-fieldset');\n const currentForm = companyLegalFieldset.parent('form');\n const originalNextUrl = currentForm.data('next');\n const subURL = '/welcome_release';\n\n const fromServer = notApplicableButton.prop('checked');\n\n if (fromServer) {\n companyLegalFieldset.prop(\"disabled\", true);\n currentForm.attr('data-next', subURL);\n } else {\n companyLegalFieldset.prop(\"disabled\", false);\n currentForm.attr('data-next', originalNextUrl);\n }\n\n notApplicableButton.change(function(e){\n var isChecked = notApplicableButton.prop('checked');\n\n if (isChecked) {\n companyLegalFieldset.prop(\"disabled\", true);\n currentForm.attr('data-next', subURL);\n } else {\n companyLegalFieldset.prop(\"disabled\", false);\n currentForm.attr('data-next', originalNextUrl);\n }\n })//onchange function end\n}", "function enableRadioButtonToPass() {\n sshKeyAddress\n .attr('disabled', 'disabled')\n .class('remotehost_text text_box text_readonly');\n browseButton.prop('disabled', true);\n }", "function update_visualize_button() {\n var selected_vis = $(\"#vis\").val();\n var selected_tree = $(\"#vis_tree\").val();\n var selected_table = $(\"#vis_table\").val();\n if (selected_vis == \"VTK TreeHeatmap\" && (selected_tree != \"Select...\" ||\n selected_table != \"Select...\")) {\n $(\"#visualize\").prop(\"disabled\", false);\n } else if (selected_vis == \"D3 Tree\" && selected_tree != \"Select...\") {\n $(\"#visualize\").prop(\"disabled\", false);\n } else if (selected_vis == \"OneZoom Tree\" && selected_tree != \"Select...\") {\n $(\"#visualize\").prop(\"disabled\", false);\n } else if (selected_vis == \"Table\" && selected_table != \"Select...\") {\n $(\"#visualize\").prop(\"disabled\", false);\n } else {\n $(\"#visualize\").prop(\"disabled\", true);\n }\n}", "function setActive() {\n if (document.querySelector('#roundedges').value.length > 0)\n document.querySelector('.roundedgesbtn').disabled = false;\n else\n document.querySelector('.roundedgesbtn').disabled = true;\n}", "function enableOtherVersion()\n {\n var txVer = document.searchParmsForm.tVersion.value;\n if (txVer != null && txVer != \"\")\n {\n //alert(\"finite \" + isFinite(txVer) + \"parse \" + parseFloat(txVer) + \"nan \" + isNaN(txVer));\n if (isNaN(txVer))\n {\n if (txVer == \".\")\n document.searchParmsForm.tVersion.value = \"0.\";\n else\n {\n alert(\"Version filter must be a positive number\");\n txVer = txVer.substring(0, txVer.length -1);\n document.searchParmsForm.tVersion.value = txVer;\n }\n }\n }\n document.searchParmsForm.rVersion[2].checked = true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the four a positions we're interested in |||| .. |||| => possible split positions // total is first times second ..aa bbbb a..a bbbb aa.. O(N^2) due to the case where we have no 'a' and we have to find all possible three groups
function solution(S) { const a_indexes = findIndexesOfA(S); if (!a_indexes.length) return [...subsets(S.split(''), 3)].length; // all possible three groups if (a_indexes.length % 3) return 0; // not possible to split in three groups having same amount of 'a' chars // now we're sure that it can be splitted in three // and there are same number of 'a' chars in each group const measureUnit = a_indexes.length / 3; const firstGroupLastA = a_indexes[measureUnit - 1]; const middleGroupFirstA = a_indexes[measureUnit]; const middleGroupLastA = a_indexes[2 * measureUnit - 1]; const lastGroupFirstA = a_indexes[2 * measureUnit]; return (middleGroupFirstA - firstGroupLastA) * (lastGroupFirstA - middleGroupLastA); }
[ "function threeSplit(a) {\n const sum = a.reduce((a, b) => a + b);\n if (sum % 3 !== 0) {\n return 0;\n }\n const third = sum / 3;\n let ways = 0;\n let jStart = 2;\n for (let i = 1; i < a.length - 1; i++) {\n let firstSum = a.slice(0, i).reduce((a, b) => a + b);\n for (let j = jStart; j < a.length; j++) {\n if (firstSum !== third) {\n break;\n }\n let secondSum = a.slice(i, j).reduce((a, b) => a + b);\n if (secondSum !== third) {\n continue;\n }\n let thirdSum = a.slice(j).reduce((a, b) => a + b);\n if (thirdSum !== third) {\n continue;\n }\n if (firstSum === secondSum && secondSum === thirdSum) {\n ways++;\n }\n }\n jStart++;\n }\n return ways;\n}", "function largeGroupPositions(s) {\n // First attempt: accepted, but quite slow:\n // let currIdx = 0;\n // const r = [];\n\n // while (currIdx < s.length) {\n // let start = currIdx;\n // let end;\n\n // for (let i = currIdx; i <= s.length; i++) {\n // if (s[i] !== s[currIdx]) {\n // if (end - start >= 2) {\n // r.push([start, end]);\n // currIdx = end;\n // }\n // break;\n // }\n\n // if (s[i] === s[currIdx]) {\n // end = i;\n // }\n // }\n\n // currIdx++;\n // }\n\n // return r;\n const r = [];\n let start = 0,\n end = 0;\n for (let i = 1; i < s.length; i++) {\n if (s[i] !== s[i - 1]) {\n if (end - start >= 2) {\n r.push([start, end]);\n }\n start = i;\n end = i;\n } else {\n end++;\n }\n }\n if (end - start >= 2) {\n r.push([start, end]);\n }\n return r;\n}", "function countWaysToSplit(s) {\n let counter = 0;\n for (let i = 1; i < s.length - 1; i++) {\n const a = s.slice(0, i);\n for (let j = i + 1; j < s.length; j++) {\n const b = s.slice(i, j);\n const c = s.slice(j, s.length);\n const ab = a + b;\n const bc = b + c;\n const ca = c + a;\n if (ab != bc && bc != ca && ca != ab) {\n counter++;\n }\n }\n }\n return counter;\n}", "function split(a) {\n const c = f * a;\n const a_h = c - (c - a);\n const a_l = a - a_h;\n return [a_h, a_l];\n}", "function calc_splits(items, m) {\n var result = [];\n var split;\n for (var i=1; i <= m; i++) {\n split = nth_split(items, i, m);\n result.push(split);\n }\n return result;\n }", "function group(names,n){\n var extra = names.length % n;\n var minSize = (names.length - extra)/n;\n\n //console.log(minSize + \" : \" + extra);\n //names = shuffle(names);\n var groups = [];\n for(var i=0; i<n; i++){\n groups[groups.length] = [];\n }\n\n var count = 0;\n\n var cap = 0;\n var pointer = -1;\n\n for(i=0;i<names.length;i++){\n if(cap <= 0){\n pointer++;\n var cap = minSize;\n if(extra > 0){\n cap++;\n extra--;\n }\n }\n var end = groups[pointer].length;\n groups[pointer][end] = names[i];\n cap--;\n }\n //console.log(\"Split into \" + n);\n return groups;\n}", "static threeWayPartition(array, a, b)\n {\n //your code here\n array = Sort.mergeSort(array,\"i\");\n let parted = 1;\n for(let i =0;i<array.length;i++){\n console.log(array[i]);\n if((array[i]===a && (array[i-1]>a || array[i+1]<a))|| (array[i]===b && (array[i-1]>b || array[i+1]<b))){\n parted = 0;\n }\n }\n return parted;\n }", "function numberGroups({a, b, c}){\nal = a.length;\n bl = b.length;\n cl = c.length;\n\nif (al < bl){\n return b; \n}else if (bl < cl){\n return c;\n}else return a;\n\n}", "function allSplitGroups(string) {\n let result = [];\n (function allSplitGroups(accum, string) {\n result = concat(result, [concat(accum, string)]);\n (function forAnyRemainingChar(i) {\n if(i === string.length) return;\n allSplitGroups([...accum, takeNChars(i)(string)], dropNChars(i)(string));\n forAnyRemainingChar(i + 1);\n })(1);\n })([], string);\n return result;\n}", "function splitIntoGroups(word) {\n if (word.length <= 6) {\n return [word];\n }\n if (word.length > 6) {\n var leftSplit = splitIntoGroups(word.substring(0, word.length/2));\n var rightSplit = splitIntoGroups(word.substring(word.length/2));\n return [].concat(leftSplit).concat(rightSplit);\n }\n}", "function breakArrIntoTwo(a){\n let sol=99999\n for(let i=0;i<a.length-1;i++){\n //firstSet 1,6,7 1+6+7\n const ans = Math.abs(sum(a,0,i+1), sum(a, i+1,a.length))\n if(ans <sol)\n sol =ans\n }\n return sol\n}", "function getRepeatingSegments(arr) {\n var a = [], b = [], repeatingElements = [], prev;\n\n arr.sort();\n for ( var i = 0; i < arr.length; i++ ) {\n if ( arr[i] !== prev ) {\n a.push(arr[i]);\n b.push(1);\n } else {\n b[b.length-1]++;\n }\n prev = arr[i];\n }\n\n for (var j=0; j<a.length; j++) {\n if (b[j] > 1) {\n \trepeatingElements.push(a[j]);\n }\n }\n return repeatingElements;\n }", "function identicalSequenceRange(a, b) {\n for (let i = 0; i < a.length - 3; i++) {\n // Find the first entry of b that matches the current entry of a.\n const pos = b.indexOf(a[i]);\n if (pos !== -1) {\n const rest = b.length - pos;\n if (rest > 3) {\n let len = 1;\n const maxLen = Math.min(a.length - i, rest);\n // Count the number of consecutive entries.\n while (maxLen > len && a[i + len] === b[pos + len]) {\n len++;\n }\n if (len > 3) {\n return [len, i];\n }\n }\n }\n }\n\n return [0, 0];\n}", "function numberGroups({a,b,c}){\n if(a.length > b.length){\n if(a.length > c.length){\n return a\n } else if( c.length > b.length) {\n return c\n }\n }\n return b\n}", "function generateMultipleCombins(en,pSets,numbSet)\n{\n \nfunction makeTwoSets(en,pSetsNumb,pNumbSet)\n{\n var keepSet = []\n var splitSet =[]\n var baOut = binaryAssignment(en,pSetsNumb,pNumbSet,true);\n if ((baOut[0][0].length==pSetsNumb))\n {\n splitSet=baOut[1].slice();\n keepSet=baOut[0].slice();\n }\n else\n {\n splitSet=baOut[0].slice();\n keepSet=baOut[1].slice(); \n }\n return [splitSet,keepSet]\n}\n \n \nfunction splitAndReturn(pSets,setPos,setToSplit)\n{\n// if ((setPos==(pSets.length-1))&&(setToSplit.length==pSets[setPos]))\n if (setPos==(pSets.length-2))\n {\n return binaryAssignment(setToSplit.length,pSets[setPos],setToSplit,false);\n }\n else\n {\n var twoSets = makeTwoSets(setToSplit.length,pSets[setPos],setToSplit);\n var groupToKeep = twoSets[1].slice();\n var groupToSplit = twoSets[0].slice();\n var stepRet = []\n// if (pSets.length==1)\n for (var cA=0;cA<groupToSplit.length;cA++)\n {\n stepRet.push([groupToKeep[cA],splitAndReturn(pSets,setPos+1,groupToSplit[cA])])\n }\n return stepRet.slice(); \n }\n}\n\nif (pSets.length==1)\n{\n return binaryAssignment(numbSet.length,pSets[0],numbSet,true)[0];\n}\n\n\nif (pSets.length==2)\n{\n return binaryAssignment(numbSet.length,pSets[0],numbSet,false);\n}\n\nreturn splitAndReturn(pSets,0,numbSet);\n\n}", "function kaprekarSplit(n){\n if (n === 1) return 0\n let pow = (n ** 2).toString().split('')\n let value = 0\n let x = 0\n let index = 0\n for (let i = 0; i <= pow.length; i++) {\n let copy = [...pow]\n x = copy.splice(i + 1)\n value = +x.join('') + +copy.join('')\n if (n === value) {\n index = i + 1\n break\n } else {\n index = -1\n }\n }\n return index\n}", "function get_splits(){\n let splits;\n switch(THREAD){\n case THREADS.BACKWARDS:\n splits = ['900','800','700','600','500','400','300','200','100','000'];\n break;\n case THREADS.BASE2:\n splits = ['0010000000','0100000000','0110000000','1000000000','1010000000','1100000000','1110000000','0000000000']\n break;\n case THREADS.BASE3:\n splits = ['010000','020000','100000','110000','120000','200000','210000','220000','000000']\n break;\n case THREADS.BASE4:\n splits = ['02000','10000','12000','20000','22000','30000','32000','00000']\n break;\n default:\n splits = ['100','200','300','400','500','600','700','800','900','000'];\n break;\n }\n return splits;\n}", "function Group_Elimination()\r\n{\r\n\t//alert(\"Total Set : \" + Total_Set);\r\n\tfor(var a=0; a<3; a++)\r\n\t{\r\n\t\tfor(var b=0; b<3; b++)\r\n\t\t{\r\n\t\t\t\tComplexity++;\r\n\t\t\t\tif(Block_Group_Elemination(a,b)) return true;\r\n\r\n\t\t\t\tComplexity++;\r\n\t\t\t\tif(Horizon_Group_Elemination(a,b)) return true;\r\n\r\n\t\t\t\tComplexity++;\r\n\t\t\t\tif(Vertical_Group_Elemination(a,b)) return true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}", "function findSequences(numbers) {\n // console.log(numbers)\n var sequences = [];\n if (numbers.length < 3) {\n return sequences;\n }\n\n for (var i=0; i<=numbers.length-3; i++) {\n for (var j=i+1; j<=numbers.length-2; j++) {\n var increment = numbers[j] - numbers[i];\n for (var k=j+1; k<=numbers.length-1; k++) {\n if (numbers[k] - numbers[j] == increment) {\n sequences.push([numbers[i], numbers[j], numbers[k]]);\n break;\n }\n }\n }\n }\n return sequences\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For this example page, stop the Form from being submitted, and update the cal instead
function handleSubmit(e) { updateCal(); YAHOO.util.Event.preventDefault(e); }
[ "function handleSubmit(e) {\n updateCal();\n YAHOO.util.Event.preventDefault(e);\n }", "function submit() {\n api.create_travel_date(props.form);\n // Clear and close the form afterward\n cancel();\n }", "function watchSubmitUpdateTask() {\n $('#task-form-update').submit(event => {\n event.preventDefault();\n const targetOne = $(event.currentTarget).find('#message-form-task-update')\n\n const taskMsg = targetOne.val()\n\n targetOne.val('')\n\n updateTaskCall(taskMsg, function (e) {\n $('#calendarMonth').html('')\n $('#daysOfMonth').html('')\n $('#task-form-update').hide(500)\n\n //UPDATES PAGE\n createCalender();\n })\n })\n }", "function watchSubmitSchedule() {\n $('#schedule-form').submit(event => {\n event.preventDefault();\n const targetOne = $(event.currentTarget).find('#message-form-schedule')\n\n const scheduleMsg = targetOne.val()\n\n targetOne.val('')\n\n postScheduleRequest(scheduleMsg, function (e) {\n $('#calendarMonth').html('')\n $('#daysOfMonth').html('')\n $('#schedule-form').hide(500)\n createCalender();\n })\n })\n }", "function submitForm2() {\n\n if (stDate.length == 0) {\n\n //window.console &&console.log(\"Using standard .ajax\");\n //alert('In submitForm. This is where formPost should be updated with new dates');\n\n postReminder();\n //postAdvancement();\n /*\n var url= 'https://' + host +'/mobile/dashboard/calendar/editevent.asp?' + iEventID;\n $.ajax({\n url: url,\n type: 'POST',\n data: formPost,\n dataType: 'xxscript',\n error: function (xhr, ajaxOptions, thrownError) {\n location.href = '/mobile/500.asp?Error=' + escape('url: ' + url + ' postData: ' + formPost + ' Status: ' + xhr.status + ' thrownError: ' + thrownError + ' responseText: ' + xhr.responseText.substring(0, 400));\n }\n ,\n complete: atEnd\n });\n */\n } else {\n\n ReminderSave();\n\n }\n}", "function scheduleEvent(){\r\n\tvar month = document.getElementById(\"month\").value;\r\n\tvar year = document.getElementById(\"year\").value;\r\n\tvar day = document.getElementById(\"day\").value;\r\n\tvar viewerOfCalendar = document.getElementById(\"viewerOfCalendar\").innerHTML;\r\n\tvar ownerOfCalendar = document.getElementById(\"ownerOfCalendar\").innerHTML;\r\n\tvar url = \"/DistCalendar/rest/calendar/scheduleEvent/\"+viewerOfCalendar+\"/\"+year+\"/\"+month+\"/\"+day;\t\r\n\tvar form = document.scheduleEventForm;\r\n\tvar accessControl = form.access.value;\r\n\tvar timeBegin = document.scheduleEventForm.begin.value;\r\n\tvar timeEnd = document.scheduleEventForm.end.value;\r\n\tif(viewerOfCalendar != ownerOfCalendar && accessControl == \"Private\"){\r\n\t\talert(\"You can not schedule Private events on someone's else calendar\");\r\n\t}\r\n\tif(formValidator(timeBegin,timeEnd)){\r\n\t\tform.action = url;\r\n\t\tform.submit();\r\n\t}\r\n}", "function onClickAddEvent(e) {\n clearView();\n document.getElementById(\"addEventView\").style.display=\"block\";\n var form = document.getElementById(\"addEventForm\");\n //reset, so no old data will be displayed\n form.reset();\n //set the current date values inside the form\n var start = new Date();\n var end = new Date(start);\n end.setHours(start.getHours()+1);\n form.elements[\"startDate\"].value = start.toJSON().substring(0,10);\n form.elements[\"startTime\"].value = start.toJSON().substring(11,16);\n form.elements[\"endDate\"].value = end.toJSON().substring(0,10);\n form.elements[\"endTime\"].value = end.toJSON().substring(11,16);\n}", "function main() {\r\n \r\n var form = FormApp.openByUrl('https://docs.google.com/forms/d/19iKjKvxzxEcOOAigZGJqKfhFLndm0zSYHu0nZKvaXXw/edit?ts=5acbfea7');\r\n var responses = form.getResponses();\r\n\r\n /*for (var i = 0; i < responses.length; i++) {\r\n var formResponse = responses[i];\r\n parseForm(i, formResponse);\r\n schedule();\r\n }*/\r\n var formResponse = responses[responses.length - 1]\r\n parseForm(responses.length - 1, formResponse);\r\n schedule();\r\n}", "function handleFormSubmit(event) {\n event.preventDefault();\n if (formObject.ticketDate) {\n API.saveTicket({\n ticketDate: formObject.ticketDate,\n ticketNum: formObject.ticketNum,\n ticketCust: formObject.ticketCust,\n ticketMaterial: formObject.ticketMaterial,\n ticketTareWeight: formObject.ticketTareWeight,\n ticketGrossWeight: formObject.ticketGrossWeight,\n ticketNetWeight: formObject.ticketGrossWeight - formObject.ticketTareWeight\n })\n .then(res => loadTickets())\n .catch(err => console.log(err));\n document.getElementById(\"ticketFrm\").reset(); \n setFormObject({}) \n }\n }", "function updateEventInForm(calEvent) {\n var $form = $(\"#schedule_form\"); \n var inputId = \"eventInput\" + calEvent.id\n var $eventInput = $form.find(\"#\" + inputId);\n if ($eventInput.length == 0) {\n //Make new input tag\n $eventInput = $('<input/>', \n {type: \"hidden\",\n name: \"timeslots[]\",\n id: inputId\n }\n );\n $eventInput.insertBefore($form.find('input[type=\"submit\"]'));\n }\n var newEvent = jQuery.extend({}, calEvent);\n newEvent[\"start\"] = asUTC(newEvent[\"start\"]);\n newEvent[\"end\"] = asUTC(newEvent[\"end\"]);\n $eventInput.val(JSON.stringify(newEvent));\n}", "function showGreivanceForm(){\r\n\tdocument.forms[0].action=\"addGrievance.do\";\r\n\tdocument.forms[0].EventName.value=\"showGrievanceForm\";\r\n\tdocument.forms[0].submit();\r\n}", "function submitEvent(){\r\n\r\n\t\tvar elemDescription = document.getElementById(\"EventDescription\")\r\n\t\tvar elemYear = document.getElementById(\"EventYear\")\r\n\t\tvar elemMonth = document.getElementById(\"EventMonth\")\r\n\t\tvar elemDay = document.getElementById(\"EventDay\")\r\n\t\tvar elemAnnually = document.getElementById(\"annually\")\r\n\t\t\t// If there is no event description do nothing.\r\n\t\tif (elemDescription.value==\"\") {\r\n\t\t\tdisplayMessage(ENUM_EventTabMessagesToUser[0]);\r\n\t\t\telemDescription.focus();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t// Modify month/year/day selected.\r\n\t\tvar monthSelected = parseInt(elemMonth.options[elemMonth.selectedIndex].value);\r\n\t\tvar yearSelected = parseInt(elemYear.options[elemYear.selectedIndex].value);\r\n\t\tvar daySelected=parseInt(elemDay.options[elemDay.selectedIndex].value);\r\n\t\t\t// obtain the type of event to be added - Gregorian or Hebrew calendar.\r\n\t\tvar GregOrHeb = (currentGregOrHeb == \"AddGregDate\") ? \"g\" : \"h\";\r\n\t\t\t// Call the function to add event, upon success display success message and reset the description text box.\r\n\t\tvar bool=addEventToList(GregOrHeb,elemDescription.value,daySelected,monthSelected,yearSelected,elemAnnually.checked);\r\n\t\tif (bool==1)\r\n\t\t{\r\n\t\t\tif (editMode == true) {\r\n\t\t\t\tdisplayMessage(ENUM_EventTabMessagesToUser[1]);\r\n\t\t\t\t$('#tabs ul:first li:eq(1) a').text(ENUM_TabsNames[2]);\t\t\t\t\r\n\t\t\t\t//tabs.getTabs()[1].getNameContainer().innerHTML = ENUM_TabsNames[2];\r\n\t\t\t\tdeleteEvent(editingIndex);\r\n\t\t\t\teditMode = false;\r\n\t\t\t\t$( \"#tabs\" ).tabs( \"option\", \"active\", 2);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tdisplayMessage(ENUM_EventTabMessagesToUser[2]);\r\n\t\t\tdocument.getElementById('EventDescription').value=''\r\n\t\t\telemDescription.focus();\r\n\t\t}\r\n\t\telse if (bool == -1)\r\n\t\t\tdisplayMessage(ENUM_EventTabMessagesToUser[3]);\r\n\t\telse if (bool == -2)\r\n\t\t\tdisplayMessage(ENUM_EventTabMessagesToUser[4]);\r\n\t}", "function handleDatesComplete() {\n $(\".dates\").submit(function(event) {\n event.preventDefault();\n disableForm(\"dates\");\n $(this)\n .find(\"#submit-dates\")\n .hide();\n let duration = $(\"#duration\").val();\n\n displayItineraryForm(duration);\n });\n}", "function updateExpiryDate() {\n\n // Ensures that expiry date is appropriately updated each time user changes hour package\n let days = packageInfo[`${hours.value}`].expiry;\n\n // Takes start date from the form + calculates expiry date\n var startDate = new Date(document.getElementById('start_date').value);\n var expiryDate = new Date(startDate.setDate(startDate.getDate() + days));\n\n // Converts it to appropriate format to put in the form\n document.getElementById('expirydate').value = expiryDate.toISOString().substr(0, 10);\n\n // Generate relevant label for the expiry date\n var text;\n if (days == 1) {\n text = `Your package will expire <strong>1 day</strong> after your start date:`;\n }\n else {\n text = `Your package will expire <strong>${days} days</strong> after your start date:`;\n }\n document.querySelector(\"#expiryLabel\").innerHTML = text;\n}", "function onSubmit()\n\t\t\t\t\t\t{\t\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\t\td3.select(\"#fromnow\").remove();\n\t\t\t\t\n\t\t\t\t\t\t\t$(\"#longevityCalculator\").submit(function(event)\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tevent.preventDefault(); // the default action of the event will not be triggered.\n\t\t\t\t\t\t\t\tevent.stopPropagation(); //Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// call function to handle input and interaction with current age text bo input\n\t\t\t\t\t\t\t\tonblurYourAge();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// retrieve and store current age entered by user\n\t\t\t\t\t\t\t\tdvc.myCurrentAge = $(\"#currentAge\").val();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// call function to use age value to retrieve data from stored arrays\n\t\t\t\t\t\t\t\tgetValues();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\treturn;\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t});// end $(\"#longevityCalculator\").submit(function(event)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}", "function formChanged(event) {\n write_pacforms_representation();\n check_the_form_validity();\n}", "function setUp_() {\n if (ScriptProperties.getProperty('calId')) {\n Browser.msgBox('Your form is already set sent. Look in Google Drive!');\n }\n var ss = SpreadsheetApp.getActive();\n var sheet = ss.getSheetByName('Conference Setup');\n var range = sheet.getDataRange();\n var values = range.getValues();\n //setUpCalendar_(values, range);\n setUpForm_(ss, values);\n ScriptApp.newTrigger('onFormSubmit').forSpreadsheet(ss).onFormSubmit()\n .create();\n ss.removeMenu('Conference');\n}", "function updateView(){\n loadTasks();\n alert('Task added successfully', 'Task added');\n document.forms.add.desc.value = '';\n document.forms.add.due_date.value = '';\n location.hash = '#list';\n }", "async _submitClick() {\n\t\tconst selectedDate = await this.getCurrentDateTime();\n\n\t\tthis.value = this.getFormat().format(selectedDate);\n\t\tconst valid = this.isValid(this.value);\n\n\t\tif (this.value !== this.previousValue) {\n\t\t\tthis.fireEvent(\"change\", { value: this.value, valid });\n\t\t\tthis.fireEvent(\"value-changed\", { value: this.value, valid });\n\t\t}\n\n\t\tthis.closePicker();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get /lists/points/block block lists in order of points (upvotesdownvotes)
function getBlockByOrder() { return db('lists') .select('*') .where('is_block_list', true) .where('public', true) .orderBy('list_points', 'desc') }
[ "function getBlockByOrder() {\n return db('lists')\n .select('*')\n .where('is_block_list', true)\n .orderByRaw('(list_upvotes - list_downvotes) desc')\n}", "function getAllByOrder() {\n return db('lists')\n .select('*')\n .where('public', true)\n .orderBy('list_points', 'desc')\n}", "function getAllByOrder() {\n return db('lists')\n .select('*')\n .orderBy('list_points', 'desc')\n}", "function getFollowByOrder() {\n return db('lists')\n .select('*')\n .where('is_block_list', false)\n .where('public', true)\n .orderBy('list_points', 'desc')\n}", "function getFollowByOrder() {\n return db('lists')\n .select('*')\n .where('is_block_list', false)\n .orderByRaw('(list_upvotes - list_downvotes) desc')\n}", "function getPoints() {\n var request = require(\"request\");\n var options = {\n method: 'GET',\n url: Config.endPoint,\n qs: {\n apikey: Config.apiKey\n },\n };\n\n request(options, function (error, response, body) {\n if (error) {\n throw new Error(error.statusText);\n }\n\n var result = JSON.parse(body);\n var points = result.slice(0, Config.resultsLimit);\n\n generatePanelsList(points);\n });\n }", "function listBlocks(args) {\n const state = State(args.url)\n\n state\n .loadBlocks()\n .then(function(personList) {\n\n\n return;\n if(args.format == 'json') {\n console.log(Formatters.asJson(personList))\n }\n else {\n console.log(Formatters.listPersonsTable(personList))\n }\n\n })\n}", "function getBikePoints(name) {\n\tvar bikePoints = searchBikeLocationInStorage(name);\n\tconsole.log(bikePoints);\n\tif (!bikePoints) {\n\t\tbikePoints = getBikePointsFromAPI(name);\n\t\treturn;\n\t}\n\n\tvar result = document.getElementById(\"result\");\n\tresult.innerHTML = \"\";\n\tvar listResults = document.createElement(\"ul\");\n\n\tfor (var i=0; i < bikePoints.length; i++) {\n\t\tlet line = document.createElement('li');\n\t\tlet bikeId = bikePoints[i].id.split('_')[1];\n\t\tline.innerHTML = bikeId + ` ${bikePoints[i].commonName} (${bikePoints[i].lat},${bikePoints[i].lon})`;\n\t\tlistResults.appendChild(line);\n\t}\n\n\tresult.appendChild(listResults);\n}", "async function getUserBlocks(req, res) {\n const offset = parseInt(req.params.offset || 0);\n const total = await BlockModel.countDocuments()\n\n if (offset > total || offset < 0) {\n return res.status(400).json({\n message: 'OUT_OF_BOUNDS'\n });\n }\n\n const records = await BlockModel\n .find({\n user_id: req.user.id\n })\n .sort([\n ['date', -1]\n ])\n .skip(offset)\n .limit(LIMIT)\n\n res.json({\n pageSize: LIMIT,\n total,\n blocks: records.map(record => record.serialize())\n })\n}", "function getBlocksPool() {\n const listOfChannels = [\n // 'webzine-landscape-blob-pngs',\n 'digital-love-projects-ephemera',\n 'love-letters-to-a-speculative-liberatory-learning-environment',\n 'code-as-a-gift',\n 'people-r1w1odycp2i',\n 'people-cdxyphwj0lo',\n 'folder-poetry-fm8h1k8vsfk',\n 'folder-poetry-4ds7cifq2do',\n 'passing-notes',\n 'passing-notes-lepghojthjg',\n 'digital-love-languages',\n 'learning-growing-reaching-extending'\n ];\n for (let i=0; i<listOfChannels.length; i++) {\n var channel = listOfChannels[i];\n var channelUrl = \"channels/\" + channel + \"?per=100\"\n console.log('++ fetching blocks from ' + channel);\n axiosArena.get(channelUrl).then(response => {\n console.log(response);\n if (response.data && response.data.contents.length > 1) {\n for (let i=0; i<response.data.contents.length; i++) {\n availableBlocks.push(response.data.contents[i])\n }\n }\n });\n }\n }", "function getBlocks(){\n return blocks;\n }", "list(status) {\n let out = Object.values(this.points)\n if(status !== undefined) {\n out = out.filter(item => item.status === status)\n }\n out.sort((a, b) => {\n let compare = -(a.status - b.status)\n compare = compare || a.name.localeCompare(b.name)\n return compare\n })\n return out\n }", "function getPinpoints() {\n // Send a request to the api using the 'GetAllPinpoints' command\n api(\"GetAllPinpoints\", function (data) {\n // Fill the pinpoint table with the received data\n fillPinpointTable(data);\n });\n}", "get_ordered_soulmates(node = '/me', soulmate_points, config) {\n\n let _this = this;\n\n if (node !== '' && node.split('')[0] !== '/') {\n node = `/${node}`;\n }\n\n soulmate_points = _.extend({\n //photos\n photo_one: 6,\n photo_two: 4,\n photo_many: 2,\n photos_limit: 50,\n\n //posts\n post_comment: 4,\n post_comment_withtags: 1,\n post_like: 6,\n post_like_withtags: 1,\n post_mention: 6,\n post_tag: 4,\n posts_limit: 40,\n\n //friends\n appfriend: 2,\n }, soulmate_points);\n\n config = _.extend({\n //photos\n use_photos: true,\n photos_limit: 25,\n photos_max_items: 50,\n photos_request_highres: true,\n\n //posts\n use_posts: true,\n posts_limit: 25,\n posts_max_items: 50,\n\n //friends\n use_friends: true,\n friends_limit: 25,\n friends_max_items: 150,\n\n //general\n batch_split: 50,\n }, config);\n\n let candidates = [];\n\n function get_candidates() {\n return candidates;\n }\n\n function gather_candidates(id, chance) {\n if (candidates[id]) {\n // candidate exists, increase his chance to be soulmate\n candidates[id]['chance'] += chance;\n } else {\n candidates[id] = {id: id, chance: chance};\n }\n\n }\n\n function analyze_photos() {\n return new Promise((resolve, reject) => {\n const photos_settings = {\n fields: 'id,tags',\n limit: config.photos_limit,\n };\n const photos_config = {\n max_items: config.photos_max_items,\n };\n\n _this.fb_promises.get_photos(node, photos_settings, photos_config)\n .then(function (response) {\n for (let img in response) {\n console.log('analyze_photos response',response);\n let photo = response[img];\n\n if (photo.tags && photo.tags.data && photo.tags.data.length > 0) {\n for (let photo_tag in photo.tags.data) {\n if (photo.tags.data[photo_tag] && photo.tags.data[photo_tag].id) {\n if (photo.tags.data.length <= 2) {\n gather_candidates(photo.tags.data[photo_tag].id, soulmate_points.photo_one);\n } else if (photo.tags.data.length <= 3) {\n gather_candidates(photo.tags.data[photo_tag].id, soulmate_points.photo_two);\n } else if (photo.tags.data.length <= 10) {\n gather_candidates(photo.tags.data[photo_tag].id, soulmate_points.photo_many);\n }\n }\n }\n }\n }\n resolve();\n })\n .catch(function (error) {\n reject(error);\n });\n\n });\n }\n\n function analyze_friends() {\n return new Promise((resolve, reject) => {\n const friends_settings = {\n fields: 'id',\n limit: config.friends_limit,\n };\n const friends_config = {\n max_items: config.friends_max_items\n };\n\n _this.fb_promises.get_friends(node, friends_settings, friends_config)\n .then(function (response) {\n console.log('analyze_friends response',response);\n for (let f in response) {\n gather_candidates(response[f].id, soulmate_points.appfriend);\n }\n resolve();\n })\n .catch(function (error) {\n reject();\n });\n });\n }\n\n function analyze_posts() {\n return new Promise((resolve, reject) => {\n const posts_settings = {\n fields: 'id,likes,comments,with_tags,to',\n limit: config.posts_limit,\n };\n const posts_config = {\n max_items: config.posts_max_items\n };\n\n _this.fb_promises.get_posts(node, posts_settings, posts_config)\n .then(function (response) {\n console.log('analyze_posts response',response);\n for (let stat in response) {\n try {\n\n if (response[stat]) {\n let interaction = response[stat];\n\n // comments\n if (interaction.comments && interaction.comments.data.length > 0) {\n for (let com in interaction.comments.data) {\n if (interaction.comments.data[com] && interaction.comments.data[com].from && interaction.comments.data[com].from.id) {\n if (interaction.with_tags && interaction.with_tags.data.length > 0) {\n gather_candidates(interaction.comments.data[com].from.id, soulmate_points.post_comment_withtags);\n } else {\n gather_candidates(interaction.comments.data[com].from.id, soulmate_points.post_comment);\n }\n }\n }\n }\n\n // likes\n if (interaction.likes && interaction.likes.data.length > 0) {\n for (let like in interaction.likes.data) {\n if (interaction.likes.data[like] && interaction.likes.data[like].id) {\n if (interaction.with_tags && interaction.with_tags.data.length > 0) {\n gather_candidates(interaction.likes.data[like].id, soulmate_points.post_like_withtags);\n } else {\n gather_candidates(interaction.likes.data[like].id, soulmate_points.post_like);\n }\n }\n }\n }\n\n // with tags\n if (interaction.with_tags && interaction.with_tags.data.length > 0) {\n for (let wtag in interaction.with_tags.data) {\n if (interaction.with_tags.data[wtag] && interaction.with_tags.data[wtag].id) {\n gather_candidates(interaction.with_tags.data[wtag].id, soulmate_points.post_tag);\n }\n }\n }\n\n // to\n if (interaction.to && interaction.to.data.length > 0) {\n for (let to in interaction.to.data) {\n if (interaction.to.data[to] && interaction.to.data[to].id) {\n gather_candidates(interaction.to.data[to].id, soulmate_points.post_mention);\n }\n }\n }\n }\n } catch (err) {\n // instead of rejecting, just continue with next interaction\n }\n }\n resolve();\n })\n .catch(function (error) {\n reject();\n });\n });\n }\n\n function filter_soulmate_users() {\n let soulmate_array = get_candidates();\n\n return new Promise((resolve, reject) => {\n\n let batch_array = [];\n\n for (let key in soulmate_array) {\n const item = soulmate_array[key];\n batch_array.push({method: 'GET', relative_url: item.id + '?metadata=1&fields=id,metadata{type}'});\n }\n\n const config = {\n split: 50 //splits the batch_arrays in seperate requests, with the size of 50\n };\n\n _this.fb_core.batch_p(batch_array, config)\n .then(response => {\n for (let key in response) {\n const item = response[key];\n if (item.metadata.type !== 'user') {\n delete soulmate_array[key];\n }\n }\n\n resolve(soulmate_array);\n });\n }\n );\n }\n\n return new Promise((resolve, reject) => {\n const promises = [];\n\n if (config.use_friends === true) {\n promises.push(analyze_friends());\n }\n\n if (config.use_posts === true) {\n promises.push(analyze_posts());\n }\n\n if (config.use_photos === true) {\n promises.push(analyze_photos());\n }\n\n Promise.all(promises.map(p => p.catch(e => e)))\n .then(response => {\n\n filter_soulmate_users()\n .then(function (soulmates) {\n\n let ordered_soulmates = Object.keys(soulmates).sort(function (a, b) {\n return soulmates[b]['chance'] - soulmates[a]['chance'];\n });\n\n const get_nodes_data_config = {\n request_birthday: false,\n request_highres: config.photos_request_highres,\n batch_split: config.batch_split,\n };\n\n _this.get_nodes_data(ordered_soulmates, get_nodes_data_config)\n .then(response => {\n resolve(response);\n })\n .catch(error => {\n reject(error);\n });\n });\n });\n });\n\n }", "function getBikePointsFromAPI(name) {\n\tfetch(\"https://api.tfl.gov.uk/BikePoint/Search?query=\" + name)\n\t.then(function(r) {\n\t\t//console.log(r);\n\t\treturn r.json();\n\t})\n\t.then(function(r) {\n\t\tconsole.log(r);\n\n\t\tif (r.length==0) {\n\t\t\tdisplayMessage(\"bikeNotfound\", name);\n\t\t}\n\t\telse {\n\t\t\tvar result = document.getElementById(\"result\");\n\t\t\tresult.innerHTML = \"\";\n\t\t\tvar listResults = document.createElement(\"ul\");\n\n\t\t\tfor (var i=0; i < r.length; i++) {\n\t\t\t\tlet line = document.createElement('li');\n\t\t\t\tlet bikeId = r[i].id.split('_')[1];\n\t\t\t\tline.innerHTML = bikeId + ` ${r[i].commonName} (${r[i].lat},${r[i].lon})`;\n\t\t\t\tlistResults.appendChild(line);\n\t\t\t}\n\n\t\t\tresult.appendChild(listResults);\n\t\t}\n\t\treturn r;\n\t})\n\t.then(function(r) {\n\t\tsaveBikeLocationInStorage(name, r);\n\t}),\n\tfunction (err) {\n\t\tdisplayMessage(\"bikeNotfound\", name);\n };\n}", "function fetch_posts(){\n let getAddress = nodeAddress + \"/chain\";\n http.get(getAddress, function(response){\n response.on('data', (d) =>{\n let content = [];\n const chain = JSON.parse(d);\n //console.log(chain);\n chain.chain.forEach(block =>{\n block.transactions.forEach(tx =>{\n \t//console.log(tx);\n tx.index = block.index;\n tx.hash = block.previous_hash;\n content.push(tx);\n })\n })\n posts = content.sort((a, b)=>{ b.timestamp - a.timestamp})\n //console.log(posts);\n })\n })\n\n}", "async function getTopPoints() {\n \treturn new Promise(resolve => {\n \tusersDB.find({}).sort({ points: -1 }).exec(function (err, docs) {\n \t\t// docs is [doc1, doc3, doc2];\n \t\tresolve(docs)\n \t});\n \t})\n}", "getPastLists() {\n\n return new TotoAPI().fetch('/supermarket/pastLists?maxResults=20').then((response) => response.json());\n }", "function getBlocksPool() {\n const listOfChannels = [\n // 'webzine-landscape-blob-pngs',\n 'digital-love-projects-ephemera',\n 'love-letters-to-a-speculative-liberatory-learning-environment',\n 'code-as-a-gift',\n 'digital-love-looks',\n 'people-cdxyphwj0lo',\n 'folder-poetry-fm8h1k8vsfk',\n 'digital-love-languages-quotes',\n 'passing-notes-lepghojthjg',\n 'learning-growing-reaching-extending'\n ];\n for (let i = 0; i < listOfChannels.length; i++) {\n var channel = listOfChannels[i];\n var channelUrl = \"channels/\" + channel + \"?per=100\"\n console.log('++ fetching blocks from ' + channel);\n axiosArena.get(channelUrl).then(response => {\n // console.log(response);\n if (response.data && response.data.contents.length > 1) {\n for (let i = 0; i < response.data.contents.length; i++) {\n // set the channel title to be part of the block so we can access it later\n response.data.contents[i].channelTitle = response.data.title;\n response.data.contents[i].channelSlug = response.data.slug;\n // then add it to the queue\n availableBlocks.push(response.data.contents[i])\n }\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vuelve a editar a la direccion original
async restaruarDireccionEntrega() { addStep('Vuelve a editar a la direccion original'); await super.clickearElemento(await this.botonUpdate); await super.clickearElemento(this.address); await super.vaciarCampoYEnviarTexto(await this.address, datos.direccion); await super.clickearElemento(this.botonSave); }
[ "function editPath() {\r\n\tif (minigames[8].vars.edit_path) {\r\n\t\tstopEdit();\r\n\t} else {\r\n\t\tminigames[8].vars.edit_path = true;\r\n\t}\r\n}", "function editFile() {\n\tvar theDOM = dw.getDocumentDOM();\n\t\n\tif (pathControl.value == \"\") {\n\t\treturn;\n\t}\n\t\n\tif (pathControl.value.match(/^\\//gi)) {\n\t\tfullPath = dw.getSiteRoot().replace(/\\/$/gi, '') + pathControl.value;\n\t} else {\n\t\tfullPath = dreamweaver.relativeToAbsoluteURL(theDOM.URL, \"\", pathControl.value);\n\t}\n\t\n\tdreamweaver.openDocument(fullPath);\n}", "function _pathChange() {\n // don't allow user to edit value.\n // revert changes while still letting user navigate box\n if (oFilePath.value != gSavedEditValue && gRevertKeypress) {\n oFilePath.value = gSavedEditValue;\n }\n\n gRevertKeypress = false;\n}", "function changePath() {\r\n dialog.showOpenDialog({\r\n properties: ['openDirectory']\r\n }).then(function(new_path) {\r\n if(!new_path.canceled) {\r\n // Update settings.json file\r\n let settings_updated = {\r\n path: process.platform == 'win32' ? path.join(String(new_path.filePaths), 'wallpaperio', '\\\\') : path.join(String(new_path.filePaths), 'wallpaperio', '\\/')\r\n };\r\n fs.writeFileSync('settings.json', JSON.stringify(settings_updated));\r\n\r\n // Move entire catalog to dest\r\n var mv = require('mv');\r\n mv(user_absolute_path, settings_updated.path, {mkdirp: true}, function(err) {\r\n if(DEBUG) {\r\n console.log(user_absolute_path);\r\n console.log(settings_updated.path);\r\n }\r\n user_absolute_path = settings_updated.path;\r\n notifier.notify({\r\n title: 'Wallpaperio - Information',\r\n message: 'Catalog path changed successfully.',\r\n sound: true,\r\n });\r\n });\r\n }\r\n })\r\n}", "function handleEdit(name) {\n var newDriveContent = driveContent;\n var currentDirectory = findCurrentDirectory();\n currentDirectory[`${editType}s`].forEach(item => {\n if (item.name === editValue) {\n item.name = name;\n }\n });\n setDriveContent(newDriveContent);\n setContentOnScreen(currentDirectory[\"folders\"].concat(currentDirectory[\"files\"]));\n setEditValue(\"\");\n }", "function editFile(path) {\n fs.readFile(path, 'utf-8', function (err, data) {\n if (err) {\n log.error(\"Read file error:\" + err);\n } else {\n if (data.indexOf(oldName)) {\n var re = new RegExp(oldName, \"g\");\n if (data.indexOf(oldName) !== -1) {\n fs.writeFile(path, data.replace(re, newName), function (err) {\n if (err) {\n log.error('Modify file failure' + err);\n } else {\n log.info('Modify file success' + path);\n }\n });\n }\n }\n }\n });\n}", "function editPath (place, choice) {\n place = place;\n choice = choice;\n userPath[place] = choice;\n}", "function moveTo() \n {\n // move file system entry\n var callback = function(srcEntry) {\n var parent = document.getElementById('parent').value,\n newName = document.getElementById('newName').value,\n parentEntry = new Entry({fullPath: parent});\n srcEntry.moveTo(parentEntry, newName, displayEntry, onFileSystemError);\n };\n\n // look up file system entry and move it to destination path\n window.resolveLocalFileSystemURI(getFileSystemURI(), callback, onFileSystemError);\n }", "async editarDireccionEntrega(direccionEditada) {\n addStep('Editar direccion de entrega');\n await super.clickearElemento(await this.botonUpdate);\n await super.clickearElemento(this.address); \n await super.vaciarCampoYEnviarTexto(await this.address, direccionEditada);\n await super.clickearElemento(this.botonSave);\n }", "function editNode() {\n copyNode();\n deleteNode();\n}", "function changeName(path, ele, isDirectory) {\n var re = new RegExp(oldName, \"g\");\n var oldPath = path + \"/\" + ele;\n var newPath = path + \"/\" + ele.replace(re, newName);\n //修改文件名称\n fs.rename(oldPath, newPath, function (err) {\n if (!err) {\n log.info(oldPath + ' replace ' + newPath);\n if (isDirectory) {\n readDir(newPath);\n } else {\n editFile(newPath);\n }\n } else {\n log.error(err)\n }\n })\n}", "function replace_path()\n{\n\tdocument.getElementById('robo_path').value \t = document.getElementById('out_path').value;\n\tdocument.getElementById('robo_path-bg').value = document.getElementById('out_path-bg').value;\t\n}", "function _pathKeyDown() {\n // Save value prior to change\n gRevertKeypress = true;\n gSavedEditValue = oFilePath.value;\n}", "edit() {\n this.isEditing = true;\n this.editData = this.copy(this.source);\n }", "function chromePathUpdate(newPath){\n exPath2=newPath;\n}", "function changeDirectory(path) {\n let nextNode = nodeFrom(path);\n if (nextNode === undefined || nextNode.type === 'file') {\n badCommand();\n return;\n }\n currentNode = nextNode;\n currentPointer = currentNode.name;\n window.location.hash = currentPointer;\n let $inputParagraph = $terminal.find('div').find('p').last();\n $inputParagraph.attr('data-prompt', getPrompt());\n updateAllowedCommands();\n}", "[_changePath] (newPath) {\n // have to de-list before changing paths\n this[_delistFromMeta]()\n const oldPath = this.path\n this.path = newPath\n const namePattern = /(?:^|\\/|\\\\)node_modules[\\\\/](@[^/\\\\]+[\\\\/][^\\\\/]+|[^\\\\/]+)$/\n const nameChange = newPath.match(namePattern)\n if (nameChange && this.name !== nameChange[1])\n this.name = nameChange[1].replace(/\\\\/g, '/')\n\n // if we move a link target, update link realpaths\n if (!this.isLink) {\n this.realpath = newPath\n for (const link of this.linksIn) {\n link[_delistFromMeta]()\n link.realpath = newPath\n link[_refreshLocation]()\n }\n }\n // if we move /x to /y, then a module at /x/a/b becomes /y/a/b\n for (const child of this.fsChildren)\n child[_changePath](resolve(newPath, relative(oldPath, child.path)))\n for (const [name, child] of this.children.entries())\n child[_changePath](resolve(newPath, 'node_modules', name))\n\n this[_refreshLocation]()\n }", "edit() {\n const { alert } = Nullthrows(this.props.dialogService);\n const { terminal } = Nullthrows(this.props.directoryService);\n const { unescape } = Nullthrows(this.props.uriService);\n\n const editor = this.env.EDITOR;\n\n if (!editor) {\n alert(`You have to define EDITOR environment variable.`);\n return;\n }\n\n const file = this.getCursor();\n const match = /^file:\\/\\/(.+)/.exec(file.uri);\n\n if (!match) {\n alert(`${file.uri} is not local.`);\n return;\n }\n\n terminal([\"-e\", editor, unescape(match[1])]);\n }", "updateFieldPath(){\n this.field.setXY(this.player.X,this.player.Y,pathCharacter);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process GROW data to prepare it for graphing, pass data to drawGrowChart function
function processGrowData(data) { // The order of GROW variables returned is not consistent // So we need to check if the variable names match // Before assigning them to their javascript variables if (data['Data'][0]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') { air_temperature = data['Data'][0]['Data']; } else if (data['Data'][0]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') { soil_moisture = data['Data'][0]['Data']; } else { light = data['Data'][0]['Data']; } if (data['Data'][1]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') { air_temperature = data['Data'][1]['Data']; } else if (data['Data'][1]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') { soil_moisture = data['Data'][1]['Data']; } else { light = data['Data'][1]['Data']; } if (data['Data'][2]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') { air_temperature = data['Data'][2]['Data']; } else if (data['Data'][2]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') { soil_moisture = data['Data'][2]['Data']; } else { light = data['Data'][2]['Data']; } window.grow_air_temperature = air_temperature; window.grow_soil_moisture = soil_moisture; drawGrowChart(air_temperature, soil_moisture, light); }
[ "function processGrowData(data) {\n // The order of GROW variables returned is not consistent,\n // so we need to check if the variable names match\n // before assigning them to their javascript variables.\n if (data['Data'][0]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') {\n air_temperature = data['Data'][0]['Data'];\n } else if (data['Data'][0]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') {\n soil_moisture = data['Data'][0]['Data'];\n } else {\n light = data['Data'][0]['Data'];\n }\n\n if (data['Data'][1]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') {\n air_temperature = data['Data'][1]['Data'];\n } else if (data['Data'][1]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') {\n soil_moisture = data['Data'][1]['Data'];\n } else {\n light = data['Data'][1]['Data'];\n }\n\n if (data['Data'][2]['VariableCode'] == 'Thingful.Connectors.GROWSensors.air_temperature') {\n air_temperature = data['Data'][2]['Data'];\n } else if (data['Data'][2]['VariableCode'] == 'Thingful.Connectors.GROWSensors.calibrated_soil_moisture') {\n soil_moisture = data['Data'][2]['Data'];\n } else {\n light = data['Data'][2]['Data'];\n }\n window.grow_air_temperature = air_temperature;\n window.grow_soil_moisture = soil_moisture;\n drawGrowChart(air_temperature, soil_moisture, light);\n}", "function buildGauge(data){\n \n}", "function processData(){\r\n \r\n var unit,\r\n powerFactor,\r\n pow10x;\r\n \r\n // reset values\r\n _min = 0;\r\n _max = 0;\r\n _barData =[];\r\n _xLegends = [];\r\n _yLegends = [];\r\n \r\n for(var i = 0; i < _data.length; i++){\r\n _min = Math.min(_min, _data[i]);\r\n _max = Math.max(_max, _data[i]);\r\n _barData.push(_data[i]);\r\n _xLegends.push(i);\r\n }\r\n unit = (_max - _min) / (_step);\r\n if (unit > 0) {\r\n powerFactor = Math.ceil((Math.log(unit) / Math.log(10)) - 1);\r\n } else {\r\n powerFactor = 0;\r\n }\r\n pow10x = Math.pow(10, powerFactor);\r\n \r\n if(pow10x < -1){\r\n _max = Math.ceil(_max);\r\n unit = (_max - _min) / (_step);\r\n _range = unit;\r\n } else {\r\n _range = Math.ceil(unit / pow10x) * pow10x;\r\n }\r\n \r\n if (_range == 0) _range == 0.01667;\r\n \r\n _max = _range * _step;\r\n \r\n for(var j = _step; j >= 0; j--){\r\n _yLegends.push(_range*j);\r\n }\r\n if(_max > 20)\r\n _decimcalFixed = 0;\r\n else if(_max > 2)\r\n _decimcalFixed = 1;\r\n else if(_max > 0.1)\r\n _decimcalFixed = 2;\r\n else if(_max > 0.01)\r\n _decimcalFixed = 3; \r\n else if(_max > 0.001)\r\n _decimcalFixed = 4; \r\n else\r\n _decimcalFixed = 5; \r\n \r\n }", "function drawGrowWowTemp(grow_air_temp, wow_air_temp, datetimes) {\n var data = new google.visualization.DataTable();\n data.addColumn('datetime', 'datetime');\n data.addColumn('number', 'grow_air_temp');\n data.addColumn('number', 'wow_air_temp');\n for (i = grow_air_temp.length - 1; i >= 0; i--) {\n var date_str = grow_air_temp[i]['DateTime'];\n var date_edit = date_str.slice(0,4) + '-' \n + date_str.slice(4,6) + '-' \n + date_str.slice(6,8) + 'T'\n + date_str.slice(8,10) + ':'\n + date_str.slice(10,12) + ':'\n + date_str.slice(12,14) \n var my_date = new Date(date_edit);\n data.addRow([my_date, \n grow_air_temp[i]['Value'], \n null\n ]);\n }\n for (i = wow_air_temp.length - 1; i >= 0; i--) {\n var date_str = datetimes[i];\n var my_date = new Date(date_str);\n data.addRow([my_date,\n null,\n wow_air_temp[i]\n ]);\n }\n var options = {\n title: 'GROW/WOW Air Temperature Comparison',\n legend: {position: 'bottom'},\n height: 400,\n };\n var chart = new google.visualization.LineChart(document.getElementById('grow_wow_temp_chart'));\n chart.draw(data, options);\n}", "function prepareDataForNewRelativeChart(selectedMadication, rawData) {\n // var selectedMadication = e.currentTarget.attributes.madication.nodeValue;\n var data = [];\n //Commented dependable drugData value fro value score chart which is repeatitive and lengthy\n // var tempData = jQuery.parseJSON(e.currentTarget.attributes.drugData.nodeValue);\n var tempData = rawData;\n // Sort by Value low to high\n tempData.sort(function(a, b) {\n return parseFloat(a.DrugPopulationSize) - parseFloat(b.DrugPopulationSize);\n });\n\n //set min & max size for bubbles as per their data size. but now this dynamic sizing appraoch is not used.\n var minimumSize = tempData[0].DrugPopulationSize;\n var totalCount = tempData.length;\n var maximumSize = tempData[totalCount - 1].DrugPopulationSize;\n var previousSize = 28;\n\n var efficacyData = [];\n //if the tempData array has some value\n if (tempData.length > 0) {\n for (var i = 0; i < tempData.length; i++) {\n var json = {};\n //check for NaN case for Adherence\n if (tempData[i].Adherence.Adherence == 'NaN') {\n json['Adherence'] = 55;\n } else {\n json['Adherence'] = parseFloat(tempData[i].Adherence.Adherence);\n }\n json['Cost'] = parseInt(tempData[i].Cost.TotalCost / 1000);\n\n //check for relative value chart when cost is < 1000 (in order to show it in K)\n json['Cost1'] = tempData[i].Cost.TotalCost;\n // Added By Jayesh 22th March for Efficacy NA condition.\n //check for NaN case for Efficacy\n if (tempData[i].Efficacy.Efficacy == 'NaN' || tempData[i].Efficacy.Efficacy == 'NA') {\n json['Efficacy'] = 0;\n } else {\n json['Efficacy'] = parseFloat(tempData[i].Efficacy.Efficacy);\n }\n\n //if Efficacy is less or equal to 50 then slightly shift its plotting position on the chart\n if (tempData[i].Efficacy.Efficacy <= 50) {\n json['EfficacyPlot'] = 60;\n efficacyData.push(60);\n }\n //if Efficacy is greater or equal 100 then restrict its plotting to max 100 only\n else if (tempData[i].Efficacy.Efficacy >= 100) {\n json['EfficacyPlot'] = 100;\n efficacyData.push(100);\n } else {\n json['EfficacyPlot'] = parseFloat(tempData[i].Efficacy.Efficacy);\n efficacyData.push(parseFloat(tempData[i].Efficacy.Efficacy));\n }\n json['Madication'] = tempData[i].DrugName;\n json['Utilization'] = tempData[i].Utilization.Utilization;\n json['TotalN'] = tempData[i].TotalN;\n json['DrugN'] = tempData[i].DrugN;\n json['Safety'] = parseFloat(tempData[i].Safety);\n\n if (tempData[i].DrugPopulationSize == minimumSize) {\n json['Size'] = 40;\n } else if (tempData[i].DrugPopulationSize == maximumSize) {\n json['Size'] = 55;\n } else {\n var size = calculateSize(minimumSize, maximumSize, tempData[i].DrugPopulationSize, totalCount, previousSize);\n previousSize = size;\n json['Size'] = size;\n }\n\n\n if (selectedMadication === tempData[i].DrugName) {\n json['SelectedMadication'] = 'true';\n } else {\n json['SelectedMadication'] = 'false';\n }\n json['SelectSvg'] = 'SelectedMadication';\n json['drugNameDisplayCount'] = i;\n data.push(json);\n }\n }\n\n //sort the efficacy data in descending order\n efficacyData.sort(function(a, b) {\n return parseFloat(a) - parseFloat(b);\n });\n\n // sort the chart data in descending order based on the drug cost of each drug\n data.sort(function(a, b) {\n return parseFloat(a.Cost) - parseFloat(b.Cost);\n });\n return data;\n\n}", "function mloadData(GDPDATA){\nconsole.log(GDPDATA);\n\n//4) I will now add my datatable to the visualization using the Google Viz API\nvar gTable = new google.visualization.DataTable();\ngTable.addColumn('string', GDPDATA.columns[0]);\ngTable.addColumn('number', GDPDATA.columns[1]);\ngTable.addRows(GDPDATA.rows);\n\t\n//5) Now I will create the chart, and tell the program to put the chart in my div\t\nvar gChart = new google.visualization.LineChart(document.getElementById(\"gChartDiv\"));\n//Options tag\nvar gchartOptions = {\n title: \"GDP Growth\", \n };\n//6) And finally, we draw the chart\ngChart.draw(gTable, gchartOptions);\n\n}", "function processData(allRows) {\n console.log(allRows);\n \n var data = [];\n var penPos = [];\n var penNeg = [];\n var strPos = [];\n var strNeg = [];\n var neoPos = [];\n var neoNeg = [];\n // all the positive grain stain result MIC levels placed in array\n // all the negative grain stain result MIC levels placed in array\n for (var i = 0; i < allRows.length; i++) {\n var row = allRows[i];\n var x = row['Gram Staining '];\n if (x == 'positive') {\n penPos.push(Math.log(row['Penicilin']));\n strPos.push(Math.log(row['Streptomycin ']));\n neoPos.push(Math.log(row['Neomycin']));\n } else {\n penNeg.push(Math.log(row['Penicilin']));\n strNeg.push(Math.log(row['Streptomycin ']));\n neoNeg.push(Math.log(row['Neomycin']));\n }\n }\n // total amount of pencilin MIC levels (positive and negative)\n var pen = [];\n // total amount of streptomycin MIC levels (positive and negative)\n var str = [];\n // total amount of neomycin MIC levels (positive and negative)\n var neo = [];\n\n for (var i = 0; i < penPos.length; i++) {\n pen.push(penPos[i]);\n }\n for (var i = 0; i < penNeg.length; i++) {\n pen.push(penNeg[i]);\n }\n for (var i = 0; i < strPos.length; i++) {\n str.push(strPos[i]);\n }\n for (var i = 0; i < strNeg.length; i++) {\n str.push(strNeg[i]);\n }\n for (var i = 0; i < neoPos.length; i++) {\n neo.push(neoPos[i]);\n }\n for (var i = 0; i < neoNeg.length; i++) {\n neo.push(neoNeg[i]);\n }\n\n makeBarGraph(penPos, penNeg, strPos, strNeg, neoPos, neoNeg);\n makePlotly(penPos, penNeg, strPos, strNeg, neoPos, neoNeg);\n make3dPlot(pen, str, neo);\n }", "function drawGrowWowRainfall(grow_soil_moisture, wow_rainfall, datetimes) {\n var data = new google.visualization.DataTable();\n data.addColumn('datetime', 'datetime');\n data.addColumn('number', 'grow_soil_moisture');\n data.addColumn('number', 'wow_rainfall');\n for (i = grow_soil_moisture.length - 1; i >= 0; i--) {\n var date_str = grow_soil_moisture[i]['DateTime'];\n var date_edit = date_str.slice(0,4) + '-' \n + date_str.slice(4,6) + '-' \n + date_str.slice(6,8) + 'T'\n + date_str.slice(8,10) + ':'\n + date_str.slice(10,12) + ':'\n + date_str.slice(12,14) \n var my_date = new Date(date_edit);\n data.addRow([my_date, \n grow_soil_moisture[i]['Value'], \n null\n ]);\n }\n for (i = wow_rainfall.length - 1; i >= 0; i--) {\n var date_str = datetimes[i];\n var my_date = new Date(date_str);\n data.addRow([my_date,\n null,\n wow_rainfall[i]\n ]);\n }\n var options = {\n title: 'GROW/WOW Rainfall - Soil Moisture Comparison',\n legend: {position: 'bottom'},\n height: 400,\n };\n var chart = new google.visualization.LineChart(document.getElementById('grow_wow_rainfall_chart'));\n chart.draw(data, options);\n}", "function drawWeightGraph(data) {\n if (data === null || data === undefined)\n return;\n\n var temp = [];\n\n data.forEach(function(entry) {\n var date = new Date(entry.datetime);\n temp.push([date, entry.weight]);\n });\n\n var table = new google.visualization.DataTable();\n table.addColumn('date', 'Date');\n table.addColumn('number', 'Weight');\n table.addRows(temp);\n\n var options = {\n chart : {\n title : 'Weight',\n subtitle : 'In pounds (lbs)'\n },\n legend : { position : 'none' },\n width : '100%',\n margin : '0 auto'\n };\n\n var chart = new google.charts.Line(document.getElementById(\"weightChart\"));\n chart.draw(table, options);\n}", "function processChartData(data, year) {\n\n // Format and calculate data\n data.forEach(function(d) {\n d.totalEnergyPercentage = 100;\n d.greenEnergyPercentage = Number(d[year]);\n\n // Limit green energy to 100% to avoid problems\n if (d.greenEnergyPercentage > 100) {\n d.greenEnergyPercentage = 100;\n }\n\n d.greyEnergyPercentage = d.totalEnergyPercentage - d.greenEnergyPercentage;\n });\n}", "function processWowData(data) {\n distance = data['distance'];\n air_temperature = data['air_temp'];\n datetimes = data['datetime'];\n rainfall = data['rainfall'];\n drawWowChart(distance, air_temperature, datetimes, rainfall);\n drawGrowWowTemp(window.grow_air_temperature, air_temperature, datetimes)\n drawGrowWowRainfall(window.grow_soil_moisture, rainfall, datetimes)\n}", "function drawGauges() {\n\n //get and draw Messages Gauge\n $.ajax({\n url: serverHost + \"/api/count/type/all\",\n dataType:\"jsonp\"\n })\n .done(function( data ) {\n\n var optionsMessages = {\n width: 130, height: 120,\n max: 5000, min: 0,\n redFrom: 4500, redTo: 5000,\n yellowFrom:4000, yellowTo: 4500,\n minorTicks: 3\n };\n\n var dataMessages = new google.visualization.DataTable(data);\n\n var chart2 = new google.visualization.Gauge(document.getElementById('messages'));\n chart2.draw(dataMessages, optionsMessages);\n\n\n });\n\n var dataSensors = google.visualization.arrayToDataTable([\n ['Label', 'Value'],\n ['Sensors', Math.floor(Math.random() * (130 - 125 + 1)) + 125]\n ]);\n\n var dataMessages = new google.visualization.DataTable(data);\n\n var dataOccupancy = google.visualization.arrayToDataTable([\n ['Label', 'Value'],\n ['Occupancy', 84]\n ]);\n\n var optionsSensors = {\n width: 130, height: 120,\n max: 250, min: 0,\n redFrom: 225, redTo: 250,\n yellowFrom:210, yellowTo: 225,\n minorTicks: 5\n };\n\n var optionsOccupancy = {\n width: 130, height: 120,\n redFrom: 90, redTo: 100,\n yellowFrom:75, yellowTo: 90,\n minorTicks: 5\n };\n\n var chart1 = new google.visualization.Gauge(document.getElementById('sensors'));\n chart1.draw(dataSensors, optionsSensors);\n\n var chart3 = new google.visualization.Gauge(document.getElementById('occupancy'));\n chart3.draw(dataOccupancy, optionsOccupancy);\n\n }", "function processChartElevData(data, currentLake) {\n //console.log(\"processChartElevData \" + currentLake.bodyOfWater);\n // Building the data for the Elev charts on the back end for performance\n update.buildElevChartData(data.data, currentLake); // build data for elev chart tab (performance)\n // Building the data for the Flow charts on the back end for performance\n update.buildFlowChartData(data.data, currentLake); // build data for flow chart tab (performance)\n // Building the data for the River charts on the back end for performance\n update.buildRiverChartData(data.data, currentLake); // build data for river chart tab (performance)\n // Building the data for the flow hourly charts on the back end for performance\n update.buildHourlyFlowChartData(data.data, currentLake); // build data for hourly flow chart tab (performance)\n\n}", "function processGrowFaults(data) {\n if (data.length == 0) {\n var days_since_anomaly = null;\n var last_anomaly_datetime = null;\n } else {\n var days_since_anomaly = data[0][0];\n var last_anomaly_datetime = data[0][1];\n }\n\n if (days_since_anomaly == null) {\n var health_status = 'Healthy';\n } else if (days_since_anomaly < 2) {\n var health_status = 'Not Healthy';\n } else {\n var health_status = 'Recovered State';\n }\n document.getElementById('grow_health_status').innerHTML = health_status;\n document.getElementById('grow_anomaly_date').innerHTML = last_anomaly_datetime;\n}", "function reloadData(){\n\t\t\t// The data is already there, find and refresh based on the new min and max hssp score\n\t\t\tvar hssp_curve;\n\t\t\t// Find and store hssp curve\n\t\t\tfor(var i = data.length - 1; i >= 0; i--) {\n\t\t\t\tif(data[i].name === \"hssp curve\") {\n\t\t\t\t hssp_curve = data[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata = jQuery.extend(true, [], original_data);\n\t\t\tdata.push(hssp_curve);\n\t\t\trefreshDownloadableContent(true);\n\t\t\tfor(var i =0; i< data.length; i++){\n\t\t\t\tif(graph.series[i].name != \"hssp curve\" && graph.series[i].name != \"number\"){\n\t\t\t\t\tgraph.series[i].setData(data[i].data);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//plot = $.plot(placeholder, choices, options);\n\t\t}", "function draw_us() {\n // after loading geo jason and price csv file, process data \n // and draw static interquartile line chart\n function fill_content(error, geo_data, price_data) {\n if (error) throw error;\n\n // for zooming\n var feature_cali = geo_data.features\n .filter(function(d) { return d.properties.NAME === 'California'; })[0];\n\n // draw static US states map\n var svg_map = d3.select('#div_chart1')\n .append('svg')\n .attr('width', width)\n .attr('height', height)\n .style(\"opacity\", 0); // need to manually show it later\n var map_return = draw_us_map(geo_data, svg_map, width, height);\n\n // find out property median price extent\n var price_extent = d3.extent(price_data, function(d) {\n return d['Median'];\n });\n\n // find California's peak stats and save globally for later reference\n var data_cali = price_data.filter(function(d) { return d['RegionName'] === 'California'; });\n data_cali.sort(function(a, b) { return b['Median'] - a['Median']; })\n cali_highest_median = data_cali[0]['Median'];\n cali_highest_year = data_cali[0]['Year'];\n\n // get color mapper by price extent\n var nice_extent = get_nice_extent(price_extent, pricing_unit, true);\n var color_range = ['#FFFFFF', '#FFA263'];\n var colors = range_colors(nice_extent, pricing_unit, color_range);\n var ticks = 6;\n\n // show color mapping scale\n draw_scale_legend_vertical(map_return.svg, color_range, nice_extent, ticks,\n 1, 60, 10, 140, d3.format('$,s'));\n\n // show year title\n map_return.svg.append('g')\n .append('text')\n .attr('id', 'year_label')\n .attr('x', 1)\n .attr('y', 15)\n .attr('dy', '0.5em')\n .text('Monthly Medians of the Year')\n .call(wrap_text, 100);\n\n // aggregation function to nest raw data by timing period\n function agg_states(leaves) {\n var states = new Array();\n var medians = new Array();\n var median_major = 0;\n\n leaves.forEach(function(d) {\n if (d['RegionName'] === 'California') { median_major = d['Median']; }\n if (!isNaN(d['Median']) && d['Median'] > 0) { medians.push(d['Median']); }\n var s = {\n 'name': d['RegionName'],\n 'median': d['Median']\n };\n states.push(s);\n });\n\n medians.sort(function(a, b) { return a - b; });\n\n // specific structure used by interquartile charting function\n return {\n 'year': leaves[0]['Year'],\n 'month': leaves[0]['Month'],\n 'period_val': leaves[0]['Year'] + leaves[0]['Month']/100.0,\n 'period_date': new Date(leaves[0]['Year'], leaves[0]['Month'], 1),\n 'segment': leaves[0]['Segment'], //only one segment for now\n 'median_period': d3.median(medians),\n 'median_max': d3.max(medians),\n 'median_min': d3.min(medians),\n 'median_q1': d3.quantile(medians, 0.25),\n 'median_q3': d3.quantile(medians, 0.75),\n 'median_major': median_major,\n 'states': states\n };\n }\n\n // nest data by timing period for time series charting\n var nested = d3.nest()\n .key(function(d) {\n return (d['Year'] + d['Month']/100.0);\n })\n .rollup(agg_states)\n .entries(price_data);\n\n // plot static interquartile line chart by time series\n var svg_chart = d3.select('#div_chart2')\n .append('svg')\n .attr('width', width)\n .attr('height', height/2)\n .style(\"opacity\", 0); // need to manually show it later\n var chart_return = draw_iqr_line_chart(nested, nice_extent, ticks,\n svg_chart, width, height/2, margin);\n var svg_chart = chart_return.svg;\n var line_major = chart_return.line_major;\n\n // for animation, update colors of states by prices\n function update_map_color(period_val) {\n var filtered = nested.filter(function(d) {\n return +d['key'] === period_val;\n });\n var states = filtered[0].values['states'];\n var state_names = states.map(function(d) { return d['name']; });\n\n function update_state_colors(d) {\n var idx = state_names.indexOf(d.properties.NAME);\n if (idx === -1) {\n return colors.color_default;\n } else {\n return colors.color_func(states[idx]['median']);\n }\n }\n\n map_return.g.selectAll('path')\n .transition()\n .duration(interval)\n .style('fill', update_state_colors);\n\n // update year title\n d3.select('#year_label')\n .text('Monthly Medians of ' + filtered[0].values['year'])\n .call(wrap_text, 100);\n }\n\n // for animation, update California line by prices\n function update_chart_california(period_val) {\n var period_date = nested.filter(function(d) {\n return +d['key'] === period_val;\n })[0]['values']['period_date'];\n var filtered = nested.filter(function(d) {\n return d['values']['period_date'] <= period_date;\n });\n \n svg_chart.selectAll(\"path.line\")\n .data([filtered])\n .enter()\n .append(\"path\")\n .attr(\"class\",\"iqr major\")\n .attr(\"d\", line_major)\n .attr('stroke', '#E37419')\n .transition()\n .duration(interval);\n }\n\n // display wrapped text on svg\n function describe_california(feature, scale, translate) {\n // Stats needed to describe California's situation\n var most_current_key = nested.map(function(d) { return d['key']; }).sort().reverse()[0];\n var filtered = nested.filter(function(d) {\n return d['key'] === most_current_key;\n });\n var most_recent_year = filtered[0]['values']['year'];\n var most_recent_month = filtered[0]['values']['month'];\n var states_desc = filtered[0]['values']['states']\n .sort(function(a, b) { return b.median - a.median; });\n var state_names = states_desc.map(function(d) { return d['name']; })\n var cali_rank = state_names.indexOf('California') + 1;\n var min_most_recent = filtered[0]['values']['median_min'];\n var median_most_recent = filtered[0]['values']['median_period'];\n cali_most_recent = filtered[0]['values']['median_major'];\n max_most_recent = filtered[0]['values']['median_max'];\n\n // update year title, add month\n var curr_title = d3.select('#year_label').text();\n d3.select('#year_label')\n .text('Monthly Medians of ' + most_recent_year + \n ' - ' + Month_Names[most_recent_month - 1])\n .call(wrap_text, 100);\n\n // get coordinates and width to add text\n var text_box = get_text_boundaries(map_return.path, feature, scale, translate);\n\n var dollar = d3.format('$,');\n var n = 0;\n\n // append to svg directly to avoid text zoom-in\n map_return.svg.append(\"text\")\n .attr(\"x\", text_box.x)\n .attr(\"y\", text_box.y+45)\n .attr(\"dy\", \".5em\")\n .style('text-anchor', 'start')\n .html('California\\'s median home price was always above 75% (3rd quartile) ' +\n 'but had been fluctuating quite a bit. As of ' + \n Month_Names[most_recent_month-1] + ' ' + most_recent_year +\n ', CA keeps the #' + cali_rank + ' highest median home price ' +\n 'after ' + concat_words(state_names.slice(0, cali_rank-1)) +\n '. CA\\'s current median home price is ' + dollar(cali_most_recent) +\n ' - very high comparing to min ' + dollar(min_most_recent) +\n ', median ' + dollar(median_most_recent) + ' and ' +\n 'max ' + dollar(max_most_recent) + ' of all states\\' medians. ')\n .call(wrap_text, text_box.width)\n .style(\"opacity\", 0)\n .transition()\n .duration(duration/3)\n .style(\"opacity\", 1)\n .each(function() { ++n; }) \n .each('end', function(){ if(!--n) { // after rendering text display buttons\n var bbox = this.getBBox();\n draw_buttons(map_return.svg, bbox.x, bbox.y + bbox.height + 10, 80,\n [{label: 'Replay', func: function() { clear_svgs(duration, null, draw_us); }},\n {label: 'Continue', func: function() { clear_svgs(duration, null, draw_cali); }}]); }\n });\n }\n\n // animation - update map colors and price trend at designated speed\n function update() { \n var period_vals = nested\n .map(function(d) { return d['values']['period_val']; })\n .sort();\n var period_i = 0;\n\n // loop through every period and update map and chart\n var year_month_interval = setInterval(function() {\n update_map_color(period_vals[period_i]);\n update_chart_california(period_vals[period_i]);\n\n period_i++;\n\n if(period_i >= period_vals.length) {\n clearInterval(year_month_interval);\n // zoome to California when finishing time series\n // after zooming in, display text to describe California condition\n setTimeout(function(){\n var factors = get_zoom_in_factors(map_return.path, feature_cali, width, height);\n zoom_in_feature(map_return.g, factors.scale, factors.translate, duration, \n function(){ describe_california(feature_cali, factors.scale, factors.translate); });\n }, wait*3);\n }\n }, interval);\n }\n\n // after map and chart show up, wait for few seconds and then start animation\n show_svgs(duration, null, function() {\n setTimeout(function(){\n update();\n }, wait);\n });\n }\n\n // load geo json and price csv files\n queue()\n .defer(d3.json, '/data/GeoJSON/gz_2010_us_states_500k.json')\n .defer(d3.csv, '/data/Zillow_CSV/median_by_state.csv', function(d) {\n d['Median'] = +d['Median'];\n d['Year'] = +d['Year'];\n d['Month'] = +d['Month'];\n return d;\n })\n .await(fill_content);\n}", "function setupChartData() {\n\tqueueData = new google.visualization.DataTable();\n\tqueueData.addColumn('string', 'Label');\n\tqueueData.addColumn('number', 'Value');\n\tqueueData.addRows(1);\n\tqueueData.setValue(0, 0, defaultQ);\n\tqueueData.setValue(0, 1, 0);\n\t\n\tqueueChart = new google.visualization.Gauge(\n\t\tdocument.getElementById('queueguage'));\n\tjobsPageGuage = new google.visualization.Gauge(\n\t\tdocument.getElementById('jobsPageGuage'));\n\tqueueOptions = {width:120, height:120, redFrom:90, redTo:100,\n\t\tyellowFrom:75, yellowTo:90, minorTicks:5};\n}", "function OCG_on_receive_gpx(jsondata,gpx,plot_graph)\n{\n\tif(jsondata.status == 'success')\n\t{\n \n if(plot_graph)\n OCG_clear_chart_data();\n\t\tOCG_clear_vect_layers();\n\t\t\n \n\t\tOCG_on_get_gpx_reponse(jsondata.data.gpxJSON,gpx,plot_graph);\n\t\t\n var map = OCG_config.map;\n\t\tvar layer = OCG_config.vect_layers.last();\n\t\tmap.zoomToExtent(layer.getDataExtent());\n\t\t\n var tmp = JSON.parse( jsondata.data.gpxJSON );\n\t\tvar str = \"<table class='mylist' >\";\n\t\tstr+= \"<tr><td>Durée</td> <td>\"+tmp.info.timeTotal+\"</td></tr>\";\n\t\tstr+= \"<tr><td>Distance</td> <td>\"+Math.round(tmp.info.distTotal/100)/10+\" km </td></tr>\";\n\t\tstr+= \"<tr><td>D+</td> <td>\"+tmp.info.eleTotalPos+\" m </td></tr>\";\n\t\tstr+= \"<tr><td>D-</td> <td>\"+tmp.info.eleTotalNeg+\" m </td></tr>\";\n\t\tstr+= \"</table>\";\n $('#geomap_gpx_info').show();\n\t\t$('#data_view').hide();\n\t\t$('#data_view').html(str);\n\t\t$('#data_view').fadeIn();\n\t}\n\telse\n\t{\n\t\tOC.dialogs.alert(jsondata.data.message, t('geomap', 'Error'));\n\t}\n}", "function monthdataGraphing() {\n monthdata = new google.visualization.DataTable();\n monthdata.addColumn(\"number\", \"X\");\n monthdata.addColumn(\"number\", \"Kabelrummet\");\n monthdata.addColumn(\"number\", \"Kafeterian\");\n monthdata.addColumn(\"number\", \"Pingisrummet\");\n monthdata.addColumn(\"number\", \"Personalrummet\");\n monthdata.addColumn(\"number\", \"Tekniklabbet\");\n\n console.log(\"-----------------------------------------------------\");\n\n for (const i in long1) {\n let mkeys = Object.keys(long1[i]); //sets variable mkeys to array of strings of the keynames inside long1[i] object in this case the day number that was pushed from the esp8266 to firebase\n //gets the amount of data the graf should use\n dayAmount = 0;\n if (mkeys.length > dayAmount) {\n dayAmount = mkeys.length;\n days = mkeys;\n }\n if (mkeys.length > currDate.getDate()) {\n dayAmount = currDate.getDate();\n }\n }\n //--------\n for (var k = 0; k < dayAmount; k++) {\n //adds data for the graf\n monthdata.addRows([\n [\n parseInt(days[k]),\n long1[\"rum1\"][days[k]][\"temp\"],\n long1[\"rum2\"][days[k]][\"temp\"],\n long1[\"rum3\"][days[k]][\"temp\"],\n long1[\"rum4\"][days[k]][\"temp\"],\n long1[\"rum5\"][days[k]][\"temp\"],\n ],\n ]);\n }\n moptions = {\n curveType: grafCurveType,\n chartArea: {\n left: \"8%\",\n right: \"8%\",\n width: \"100%\",\n },\n hAxis: {\n title: \"Day\",\n gridlines: {\n count: dayAmount,\n color: \"transparent\",\n },\n },\n vAxis: {\n title: \"Temperature\",\n },\n legend: {\n position: \"bottom\",\n },\n backgroundColor: {\n fill: \"transparent\",\n },\n };\n\n drawnow();\n console.log(days);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parsing the DOM for on and action attribute
onEvent() { const elements = document.querySelectorAll("[on]"); for (let i = 0; i < elements.length; i++) { const attr = elements[i].getAttribute("on"); const action = elements[i].getAttribute("action"); elements[i].addEventListener(attr, () => { eval(action); }); } }
[ "function onAttr( tag ,atr,value=true){\tswitch(value){\r\n\tcase false:return delAttr(tag,atr);break;case true:return tag.getAttribue(atr);break;default:return setAttr(tag,atr,value);break;}\t\r\n}", "function evaluateAttribute(scope, elem, attrs) {\r\n\t\t//the list is first split into macro group accordingly with the \r\n\t\t//handler applied each group is divided from the others with the pipe char\r\n\t\tvar macroList = attrs.tvxOnEvent.split('|');\r\n\t\tfor ( var k=0;k<macroList.length;k++) {\r\n\t\t//each macro section is then again parsed\r\n\t\t\tbuildEventGroup(macroList[k], elem, scope);\r\n\t\t}\r\n\r\n\t}", "getFormAction(element) {\n return element.getAttribute(\"action\");\n }", "function _parseUiElementActions(actionList) {\n\t\tvar uiElemActionMap = {};\n\t\tDojoArray.forEach(actionList,function(action){\n\t\t\tuiElemActionMap[action] = true;\n\t\t});\n\t\treturn uiElemActionMap;\n\t}", "function processXmlActions(xmlActions, element) {\r\n\tvar actions = xmlActions.getElementsByTagName(\"action\");\r\n\tvar result = false;\r\n\t\r\n\tfor (var i = 0; i < actions.length; i++) {\r\n\t\tvar action = actions.item(i);\r\n\t\tresult = true;\r\n\t\t\r\n\t\tif (action != null) {\r\n\t\t\tvar toDo = action.getAttribute(\"toDo\");\r\n\t\t\t\r\n\t\t\tif (toDo == \"ajaxTimed\") {\r\n\t\t\t\tvar paramTime\t= action.getElementsByTagName(\"param\").item(0).firstChild.nodeValue;\r\n\t\t\t\tvar paramUrl\t= action.getElementsByTagName(\"param\").item(1).firstChild.nodeValue;\r\n\t\t\t\t\r\n\t\t\t\tajaxTimeout1 = setTimeout(\"doModalAjaxTimed('\" + paramUrl + \"')\",paramTime);\r\n\t\t\t} else if (toDo == \"functionTimedCall\") {\r\n\t\t\t\tvar paramTime\t= action.getElementsByTagName(\"param\").item(0).firstChild.nodeValue;\r\n\t\t\t\tvar paramFnc\t= action.getElementsByTagName(\"param\").item(1).firstChild.nodeValue;\r\n\t\t\t\t\r\n\t\t\t\tif(paramFnc.indexOf('(') != -1){\r\n\t\t\t\t\tsetTimeout(function() {\r\n\t\t\t\t\t\teval(paramFnc);\r\n\t\t\t\t\t},paramTime);\r\n\t\t\t\t} else {\r\n\t\t\t\t\r\n\t\t\t\t\tvar fn = window[paramFnc];\r\n\t\t\t\t\r\n\t\t\t\t\tajaxTimeout1 = setTimeout(fn,paramTime);\r\n\t\t\t\t}\r\n\t\t\t} else if (toDo == \"linkTimed\") {\r\n\t\t\t\tvar paramTime\t= action.getElementsByTagName(\"param\").item(0).firstChild.nodeValue;\r\n\t\t\t\tvar paramUrl\t= action.getElementsByTagName(\"param\").item(1).firstChild.nodeValue;\r\n\r\n\t\t\t\tif (paramUrl.indexOf(\"/\") != 0) paramUrl = \"/\" + paramUrl;\r\n\t\t\t\t\r\n\t\t\t\tajaxTimeout1\t= setTimeout(\"doLink('\" + CONTEXT + paramUrl + \"')\",paramTime);\r\n\t\t\t\t\r\n\t\t\t} else if (toDo == \"ajaxHidde\") {\r\n\t\t\t\tvar paramTime\t= action.getElementsByTagName(\"param\").item(0).firstChild.nodeValue;\r\n\t\t\t\tajaxTimeout2\t= setTimeout(\"SYS_PANELS.closeActive()\",paramTime);\r\n\t\t\t\t\r\n\t\t\t} else if (toDo == \"ajaxHiddeAll\") {\r\n\t\t\t\tvar paramTime\t= action.getElementsByTagName(\"param\").item(0).firstChild.nodeValue;\r\n\t\t\t\tajaxTimeout2\t= setTimeout(\"SYS_PANELS.closeAll()\",paramTime);\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn result;\r\n}", "function parseAttrs() {\n attrArray = [];\n if ($(\"#OOS\").is(\":checked\")) { attrArray.push(\" Inquiry Out Of Scope / Scope Enforcement \"); }\n if ($(\"#multiple\").is(\":checked\")) { attrArray.push(\" Issue Persisting After Multiple Calls \"); }\n if ($(\"#misinform\").is(\":checked\")) { attrArray.push(\" Caused By Customer Being Misinformed/Sold \"); }\n if ($(\"#expectations\").is(\":checked\")) { attrArray.push(\" Improper Expecations Set For Service Or Product \"); }\n if ($('#common').is(\":checked\")) { attrArray.push(\" Training Needed For Common Issue. See Note. \"); }\n if ($(\"#goodTransfer\").is(\":checked\")) { attrArray = []; attrArray.push(\" Good Transfer \"); }\n }", "_initAttributesActions() {\n [\"next\", \"previous\"].forEach((action) => {\n __querySelectorLive(`[s-slider-${action}]:not(s-slider#${this.id} s-slider [s-slider-${action}])`, ($elm) => {\n $elm.addEventListener(\"pointerup\", (e) => {\n e.preventDefault();\n this[action](true);\n });\n }, {\n scopes: false,\n rootNode: this\n });\n });\n __querySelectorLive(`[s-slider-goto]:not(s-slider#${this.id} .s-slider [s-slider-goto])`, ($elm) => {\n $elm.addEventListener(\"pointerup\", (e) => {\n var _a;\n const slideIdx = (_a = parseInt($elm.getAttribute(\"s-slider-goto\"))) !== null && _a !== void 0 ? _a : 0;\n this.goTo(slideIdx, true);\n });\n }, {\n scopes: false,\n rootNode: this\n });\n }", "function getFormActionAttribute(){\r\n var strAction = document.forms[0].getAttribute(\"action\");\r\n return strAction;\r\n}", "_actions() {\n return this.element().getDriver().actions();\n }", "static onClick(tag, action) {\n //alert('onClick\\ntag:' + tag + '\\naction: ' + action);\n document.getElementById(tag).addEventListener(\"click\", action);\n }", "function checkForActions(xml_data, stepId, taskId){\n \n $(xml_data).find(\"step\").each(function() {\n if($(this).find(\"step-id\").text() == stepId){\n $(this).find(\"sub-step\").each(function() { \n if($(this).find(\"value\").text() == taskId){\n // when landing in here, I've got the correct action element\n $(this).find(\"action\").each(function() {\n \n // evaluate the action and call specific functions $(this).attr(\"type\")\n var type = $(this).attr(\"type\"); \n if(type == \"task_overlay\"){\n \n var section = $(this).attr(\"section\");\n var group = $(this).attr(\"group\");\n var helper_type = $(this).attr(\"helper_type\");\n var variable_name = $(this).attr(\"variable_name\");\n var read = $(this).attr(\"read\");\n var value = $(this).text().replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n \n // create action, that it can get removed when task is closed\n var actionName = $(this).attr(\"type\") + \"_\" + $(this).attr(\"variable_name\");\n \n addAction(type, section, variable_name, value, stepId, taskId, actionName, {\"helper_type\":helper_type, \"group\":group, \"read\":read });\n \n }else if(type == \"autopilot\") {\n \n var section = $(this).attr(\"section\");\n var group = $(this).attr(\"group\");\n var helper_type = $(this).attr(\"helper_type\");\n var variable_name = $(this).attr(\"variable_name\");\n var value = $(this).text().replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n \n // create action, that it can get removed when task is closed\n var actionName = $(this).attr(\"type\") + \"_\" + $(this).attr(\"variable_name\");\n addAction(type, section, variable_name, value, stepId, taskId, actionName, {\"helper_type\":helper_type, \"group\":group});\n \n }else if(type ==\"move_edupack\") {\n var section = $(this).attr(\"section\");\n var group = $(this).attr(\"group\");\n var helper_type = $(this).attr(\"helper_type\");\n var variable_name = $(this).attr(\"variable_name\");\n var value = $(this).text().replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n \n var actionName = $(this).attr(\"type\") + \"_\" + $(this).attr(\"variable_name\");\n addAction(type, section, variable_name, value, stepId, taskId, actionName, {});\n } else {\n var section = $(this).attr(\"section\");\n var variable_name = $(this).attr(\"variable_name\");\n var value = $(this).attr(\"value\");\n var actionName = $(this).attr(\"type\") + \"_\" + $(this).attr(\"variable_name\");\n addAction(type, section, variable_name, value, stepId, taskId, actionName, {});\n }\n });\n }\n }); \n }\n });\n \n return true;\n}", "function parseMIDIActions(node, widget) {\n\n if(node.hasAttribute('midinote')) {\n var action_list = node.getAttribute('midinote').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = new MidiAction(midi, 'note', parseInt(params[0].trim())); //, parseInt(params[1].trim()), parseInt(params[2].trim()) );\n action.note = parseInt(params[1].trim());\n action.velocity = 127;\n if(params.length > 2) action.velocity = parseInt(params[2].trim());\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midicc')) {\n var action_list = node.getAttribute('midicc').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = null;\n if(widget.constructor.name == 'Button') {\n action = new MidiAction(midi, 'cc', parseInt(params[0].trim()));\n action.cc = parseInt(params[1].trim());\n if(params.length > 2) {\n action.cc_val_on = parseInt(params[2].trim());\n action.cc_val_off = parseInt(params[3].trim());\n } else {\n // User forgot to add parameters, only fallback is zeros\n action.cc_val_on = 0; action.cc_val_off = 0;\n }\n } else {\n action = new MidiAction(midi, 'cc', parseInt(params[0].trim()));\n action.cc = parseInt(params[1].trim());\n }\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midinrpn')) {\n var action_list = node.getAttribute('midinrpn').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = new MidiAction(midi, 'nrpn', parseInt(params[0].trim()));\n if(widget.constructor.name == 'Button') {\n if(params.length > 2) {\n action.nrpn_val_on = parseInt(params[3].trim());\n action.nrpn_val_off = parseInt(params[4].trim());\n } else {\n // User forgot to add parameters, only fallback is zeros\n action.nrpn_val_on = 0; action.nrpn_val_off = 0;\n }\n }\n action.nrpn_msb = parseInt(params[1].trim());\n action.nrpn_lsb = parseInt(params[2].trim());\n if(widget.max > 127)\n action.high_res = true;\n // console.log(\"parsed nrpn\")\n // console.dir(action)\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midiprog')) {\n var action_list = node.getAttribute('midiprog').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = null;\n var action = new MidiAction(midi, 'prog', parseInt(params[0].trim()));\n action.prog_msb = parseInt(params[1].trim());\n action.prog_lsb = parseInt(params[2].trim());\n action.prog_num = params.length > 3 ? parseInt(params[3].trim()) : null;\n widget.midiactions.push(action);\n }\n }\n}", "function performActions(target,doc,node,actions){\r\n for(var i=0,n=actions.length;i<n;i++){\r\n var action = actions[i];\r\n if(action.nodeType==1){\r\n \t // Get the action type\r\n \t var type;\r\n if(window.ActiveXObject){\r\n type = action.baseName.toLowerCase();\r\n }else{\r\n type = action.localName.toLowerCase();\r\n }\r\n \t switch(type){\r\n \t case \"comment\":\r\n \t var author = getFirstChildTextValue(doc,\"author\");\r\n commentText(target,node,action,author); // in comments.js\r\n break;\r\n case \"regexp-data\":\r\n regexpData(node,action);\r\n break;\r\n case \"set-attr\":\r\n setAttrib(node,action);\r\n break;\r\n case \"img-over\":\r\n insertImg(target,node,action);\r\n break;\r\n case \"inner-html\":\r\n innerHTML(node,action);\r\n break;\r\n case \"insert-node\":\r\n insertNode(target,node,action);\r\n break;\r\n default:\r\n break;\r\n } \r\n } \r\n }\r\n}", "function execute_actions (update) {\n for (var i = 0; i < update.childNodes.length; i++) {\n var up = update.childNodes[i];\n if (up.nodeType == up.ELEMENT_NODE) {\n // Dispatch action based on tag name\n var action = up.tagName;\n if (action in actions) {\n actions[action](up);\n }\n else {\n // No error reporting here right now.\n }\n }\n }\n}", "function pullActionUrls(html) {\n\n // Sanity check.\n if (typeof(html.match) == \"undefined\") return undefined;\n \n // Do we have action attributes?\n const actPat = /action\\s*=\\s*\"([^\"]*)\"/g;\n const r = [];\n for (const match of html.matchAll(actPat)) {\n var currAct = match[1];\n if (!currAct.startsWith(\"http\") && !currAct.startsWith(\"//\")) continue;\n if (currAct.startsWith(\"//\")) currAct = \"https:\" + currAct;\n r.push(currAct);\n }\n\n // Do we have URLs in the action attribute values?\n if (r.length == 0) return undefined;\n return r;\n}", "function getFormUrl(xml){\n return String(xml.@action);\n}", "stripETagsFromValue(action){delete action.eTag;return action;}", "function get_video_option_nodes(){\r\n var iterator = document.evaluate(\"//div[@class='vp_entry detail']\", document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );\r\n var nodes = new Array();\r\n var i =0;\r\n try {\r\n var thisNode = iterator.iterateNext();\r\n \r\n while (thisNode) {\r\n //GM_log( thisNode.getAttribute('onClick'));\r\n nodes[i] = thisNode;\r\n i++;\r\n thisNode = iterator.iterateNext();\r\n } \r\n \r\n } catch (e) {\r\n GM_log( 'Error: Document tree modified during iteraton ' + e );\r\n }\r\n return nodes;\r\n }", "function parseMIDIActions(node, widget) {\n\n if(node.hasAttribute('midinote')) {\n var action_list = node.getAttribute('midinote').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = new MidiAction('note', parseInt(params[0].trim())); //, parseInt(params[1].trim()), parseInt(params[2].trim()) );\n action.note = parseInt(params[1].trim());\n action.velocity = 127;\n if(params.length > 2) action.velocity = parseInt(params[2].trim());\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midicc')) {\n var action_list = node.getAttribute('midicc').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = null;\n if(widget.constructor.name == 'Button') {\n action = new MidiAction('cc', parseInt(params[0].trim()));\n action.cc = parseInt(params[1].trim());\n if(params.length > 2) {\n action.cc_val_on = parseInt(params[2].trim());\n action.cc_val_off = parseInt(params[3].trim());\n } else {\n // User forgot to add parameters, only fallback is zeros\n action.cc_val_on = 0; action.cc_val_off = 0;\n }\n } else {\n action = new MidiAction('cc', parseInt(params[0].trim()));\n action.cc = parseInt(params[1].trim());\n }\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midinrpn')) {\n var action_list = node.getAttribute('midinrpn').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = new MidiAction('nrpn', parseInt(params[0].trim()));\n if(widget.constructor.name == 'Button') {\n if(params.length > 2) {\n action.nrpn_val_on = parseInt(params[3].trim());\n action.nrpn_val_off = parseInt(params[4].trim());\n } else {\n // User forgot to add parameters, only fallback is zeros\n action.nrpn_val_on = 0; action.nrpn_val_off = 0;\n }\n }\n action.nrpn_msb = parseInt(params[1].trim());\n action.nrpn_lsb = parseInt(params[2].trim());\n if(widget.max > 127)\n action.high_res = true;\n console.log(\"parsed nrpn\")\n console.dir(action)\n widget.midiactions.push(action);\n }\n }\n\n if(node.hasAttribute('midiprog')) {\n var action_list = node.getAttribute('midiprog').split('|');\n for (var i = 0; i < action_list.length; i++) {\n var params = action_list[i].split(',');\n var action = null;\n var action = new MidiAction('prog', parseInt(params[0].trim()));\n action.prog_msb = parseInt(params[1].trim());\n action.prog_lsb = parseInt(params[2].trim());\n action.prog_num = params.length > 3 ? parseInt(params[3].trim()) : null;\n widget.midiactions.push(action);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isValidRegionPlacement returns true if a value is a valid value for a region
isValidRegionPlacement(row, column, value) { if (this.getCell(row, column)) { return false; } else { return isValidValue(this.getRegion(row, column), value); } }
[ "function isValidRegion(region) {\n return regions.hasOwnProperty(region);\n}", "function assertValidRegion({region}) {\n return region;\n}", "isValidRegion(regionName) {\n // use isValidState/ZipCode/County to check if given US geography exists\n return ( this.isValidState(regionName) ||\n this.isValidZipCode(regionName) ||\n this.isValidCounty(regionName) );\n }", "function checkRegion(coordinates) {\n\n}", "function fnValidateRegion(oInput){\n\n\t// Gets region\n\tvar sText = oInput.parent().siblings('.selected').text();\n\n\t// Checks that the value is changed\n\tif (sText == \"Vælg region her..\") {\n\t\toInput.parent().parent().addClass('invalid-property');\n\t\treturn false;\n\t} else {\n\t\toInput.parent().parent().removeClass('invalid-property');\n\t\treturn true;\n\t}\n}", "isValidRowPlacement(row, column, value) {\n if (this.getCell(row, column)) {\n return false;\n } else {\n return isValidValue(this.getRow(row), value);\n }\n }", "function validateAddRegionForm()\n{\n var regionValidation = validateName(\"add_region_form\",\"region\",\"region_span_name\");\n if (regionValidation) \n {\n addRegion();\n }\n return false;\n}", "function placeIsInRange() {\n if (place && place.geometry) {\n var serviceAreaPaths = parseServiceAreaPaths(config.serviceArea)\n var serviceArea = new google.maps.Polygon({ paths: serviceAreaPaths })\n return google.maps.geometry.poly.containsLocation(place.geometry.location, serviceArea)\n }\n }", "hasRegion(name) {\n return !!this.getRegion(name);\n }", "get isAnyRegionType() {\n return this.dgnBoundaryType() === 2 || this.dgnBoundaryType() === 5 || this.dgnBoundaryType() === 4;\n }", "function validateRegion(regionName){\r\n\tvar re=/^\\s*$/;\r\n\tif (re.test(regionName)){\r\n\t\talertify.alert(\"Please enter Region.\");\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}", "function isRegion( node ) {\n return node === null ? false : node.Type === 0;\n }", "function isRegionProvider(arg) {\n return arg.getRegion !== undefined;\n}", "validateRegionExists(stage, region) {\n return this.meta.validateRegionExists(stage, region);\n }", "function isInArea(item, value){\n\tvar coordinates;\n\n\tif (value === \"all\") {\n\t\treturn true;\n\t}\n\telse if (value === \"campus\"){\n\t\tcoordinates = {\n\t\t\tsouth: 30277638,\n\t\t\twest: -97752770,\n\t\t\tnorth: 30296389,\n\t\t\teast: -97728051\n\t\t};\n\t}\n\telse if (value === \"downtown\") {\n\t\tcoordinates = {\n\t\t\tnorth: 30277638,\n\t\t\tsouth: 30260236,\n\t\t\teast: -97736533,\n\t\t\twest: -97755952\n\t\t};\n\t}\n\telse if (value === \"south\") {\n\t\tcoordinates = {\n\t\t\tnorth: 30266617,\n\t\t\tsouth: 30240840,\n\t\t\teast: -97745281,\n\t\t\twest: -97783862\n\t\t};\n\t}\n\telse if (value === \"east\") {\n\t\tcoordinates = {\n\t\t\tnorth: 30280478,\n\t\t\tsouth: 30247396,\n\t\t\teast: -97699200,\n\t\t\twest: -97734440\n\t\t};\n\t}\n\t\t\n\tif (item.lat >= coordinates.south && item.lat <= coordinates.north && item.lng <= coordinates.east && item.lng >= coordinates.west) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}", "function isAwsRegion(region) {\r\n return (typeof region === \"string\" &&\r\n /^(us|eu|af|ap|me|sa|ca)\\-(north|south|east|west|central|northeast|southeast)\\-[1-3]$/.test(region));\r\n}", "isValidColumnPlacement(row, column, value) {\n if (this.getCell(row, column)) {\n return false;\n } else {\n return isValidValue(this.getColumn(column), value);\n }\n }", "function isNearFinalPosition(region, final_position) {\n var reg = region;\n var o = final_position;\n var regX = reg.x();\n var regY = reg.y();\n\n if (regX > o.x - 20 && regX < o.x + 20 && regY > o.y - 20 && regY < o.y + 20) {\n return true;\n } else {\n return false;\n }\n}", "validateIndividualPlaces() {\n for (let i = 0; i < (this.myObj.places).length; i++) {\n if (Destinations.undefinedOrEmpty(this.myObj.places[i]) === false) {\n return false;//a field in a place was not defined\n }\n }\n return true;//all places have fields, and able to be rendered\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that the provided named option equals one of the expected values.
function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) { var expectedDescription = []; for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) { var val = expected_1[_i]; if (val === input) { return; } expectedDescription.push(valueDescription(val)); } var actualDescription = valueDescription(input); throw new FirestoreError(Code.INVALID_ARGUMENT, "Invalid value " + actualDescription + " provided to function " + functionName + "() for option " + ("\"" + optionName + "\". Acceptable values: " + expectedDescription.join(', '))); }
[ "function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \" +\n (\"\\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', ')));\n}", "function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n\n if (val === input) {\n return;\n }\n\n expectedDescription.push(valueDescription(val));\n }\n\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \" + (\"\\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', ')));\n}", "function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\r\n var expectedDescription = [];\r\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\r\n var val = expected_1[_i];\r\n if (val === input) {\r\n return;\r\n }\r\n expectedDescription.push(valueDescription(val));\r\n }\r\n var actualDescription = valueDescription(input);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \" +\r\n (\"\\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', ')));\r\n}", "function validateOptions(options){\n\n\t}", "function validateOptions(options){\n\n }", "function isOptionValid(option){\n for( var i = 0; i < validOptions.length; i++){\n if(validOptions[i] === option){\n return true;\n }\n }\n return false;\n }", "function validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n }", "function validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}", "function verifyOptionType(sourcePath, name, value) {\n if (typeof value === 'object') {\n var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Object value not supported for option \"' + name + '\"!';\n console.error(msg);\n throw new Error(msg);\n } else if (!sourcePath && typeof value === 'function') {\n var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Source file\\'s path isn not determined - only explicit values for option \"' + name + '\" supported! Value passed is a function.';\n console.error(msg);\n throw new Error(msg);\n } else if (!sourcePath && ((value.toString().indexOf('[') >= 0) || (value.toString().indexOf(']') >= 0))) {\n var msg = 'POSTCSS-HASH-CLASSNAME WARNING: Source file\\'s path isn not determined - only explicit values for option \"' + name + '\" supported! Value passed detected as using templating.';\n console.warn(msg);\n }\n}", "function checkOptionValue(args, option) {\n if (args.length === 0) {\n print(\"Error: no value specified for \\\"\" + option + \"\\\" option\");\n quit();\n }\n}", "function check_options() {\r\n let error, cfg, regex, current_value;\r\n\r\n for (let opt in config_obj) {\r\n cfg = config_obj[opt];\r\n regex = cfg[REGEX];\r\n current_value = cfg[CURRENT_VALUE];\r\n // We do not validate an option if it does not have any value. In other\r\n // words, if an option is niether provided at the command line, nor in\r\n // any of the config files, nor can have a default value, then regex\r\n // validation is skipped. MAC id is an example.\r\n if (current_value && regex) {\r\n if (!regex.test(current_value)) {\r\n error = new Error(\r\n \"Regular expression: \" +\r\n regex +\r\n \" failing for option: \" +\r\n opt +\r\n \" with value: \" +\r\n current_value\r\n );\r\n break;\r\n }\r\n }\r\n }\r\n return error;\r\n}", "function testRequiredOptions(options, requiredOptions) {\n for (var i = 0; i < requiredOptions.length; i++) {\n var opt = requiredOptions[i];\n if (!options[opt]) {throw missingArgError(opt);}\n }\n}", "function _validateOptions() {\n // --browser option\n //\n // We only want \"chrome\", or \"phantomjs\" as values. We don't expect string\n // values to be case sensitive.\n if (typeof options.browser === 'string') {\n let lcBrowserStr = options.browser.toLowerCase();\n\n switch (lcBrowserStr) {\n case 'chrome':\n options.browser = 'Chrome';\n break;\n case 'phantomjs':\n options.browser = 'PhantomJS';\n break;\n default:\n options.browser = 'PhantomJS';\n break;\n }\n } else {\n options.browser = 'PhantomJS';\n }\n\n // --once option\n //\n // This option can be supplied without a value - in this case it is evaluated\n // as `true` (boolean value). Also we accept values \"true\" and \"false\". We\n // don't expect string values to be case sensitive.\n if (typeof options.once === 'string') {\n let lcOnceStr = options.once.toLowerCase();\n\n switch (lcOnceStr) {\n case 'true':\n options.once = true;\n break;\n case 'false':\n options.once = false;\n break;\n default:\n options.once = false;\n break;\n }\n } else if (typeof options.once !== 'boolean') {\n options.once = false;\n }\n}", "validateParamOptions() {\n Object.keys(CmdLineParamsOptions).forEach(key => {\n if (!this.options[key]) {\n this.options[key] = CmdLineParamsOptions[key][0];\n } else if (!CmdLineParamsOptions[key].find(i => i === this.options[key])) {\n const options = CmdLineParamsOptions[key].join(' or ');\n throw new this.serverless.classes.Error(\n `Invalid ${key} parameter value, must be either ${options}.`\n );\n }\n });\n }", "function EZcheckOptions(pOptions, pChoices)\n{\n\tif (!pOptions || !pChoices) return false;\n\tvar inputOpts = \",\" + pOptions + \",\";\n\tinputOpts = inputOpts.toLowerCase();\n\n\tvar searchOpts = pChoices.toLowerCase();\n\tvar str;\n\tvar pos;\n\n\t//----- For each desired choice ...\n\twhile ( !searchOpts == \"\" )\n\t{\n\t\tstr = searchOpts;\n\t\tpos = str.indexOf(\",\");\n\t\tif (pos == 0)\n\t\t{\n\t\t\tsearchOpts = str.substring(pos+1);\t//strip comma\n\t\t\tcontinue;\n\t\t} else if (pos > 0)\n\t\t{\n\t\t\tsearchOpts = str.substring(pos+1);\n\t\t\tstr = str.substring(0,pos);\n\t\t} else\n\t\t{// no commaa\n\t\t\tsearchOpts = \"\";\n\t\t}\n\t\t// check for this choice\n\t\tif (inputOpts.indexOf(\",\" + str + \",\") >= 0) return true;\n\t\tif (inputOpts.indexOf(\",\" + str + \"=\") >= 0) return true;\n\t}\n\treturn false;\n}", "function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, optionName1 + \" and \" + optionName2 + \" cannot be used together.\");\n }\n}", "function EZcheckOptions( pOptions, pChoices )\n{\n\n\tvar inputOpts = \",\" + pOptions + \",\";\n\tinputOpts = inputOpts.toLowerCase();\n\n\tvar searchOpts = pChoices.toLowerCase();\n\tvar str;\n\tvar pos;\n\n\t//----- For each desired choice ...\n\twhile ( !searchOpts == \"\" )\n\t{\n\t\tstr = searchOpts;\n\t\tpos = str.indexOf(\",\");\n\t\tif (pos == 0)\n\t\t{\n\t\t\tsearchOpts = str.substring(pos+1);\t//strip comma\n\t\t\tcontinue;\n\t\t} else if (pos > 0)\n\t\t{\n\t\t\tsearchOpts = str.substring(pos+1);\n\t\t\tstr = str.substring(0,pos);\n\t\t} else\n\t\t{// no comma\n\t\t\tsearchOpts = \"\";\n\t\t}\n\t\t// check for this choice\n\t\tif (inputOpts.indexOf(\",\" + str + \",\") >= 0) return true;\n\t\tif (inputOpts.indexOf(\",\" + str + \"=\") >= 0) return true;\n\t}\n\treturn false;\n}", "function matchOption(argument, matchers) {\n\tfor (const [name, matcher] of Object.entries(matchers)) {\n\t\tif (name.endsWith('=')) {\n\t\t\tconst match = new RegExp(`^(?:-{0,2})(?:${name})(.+)`, 'i').exec(\n\t\t\t\targument\n\t\t\t);\n\n\t\t\tif (match) {\n\t\t\t\tmatcher(match[1]);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconst match = new RegExp(`^(?:-{0,2})(no-)?(?:${name})$`, 'i').exec(\n\t\t\t\targument\n\t\t\t);\n\n\t\t\tif (match) {\n\t\t\t\tmatcher(!match[1]);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\terror(\n\t\t`Unrecognized argument ${argument}; see --help for available options`\n\t);\n\n\treturn false;\n}", "function validateOptionString(options, key) {\n if (!R.is(String, options[key])) {\n throw ('Must be a string.');\n }\n if (R.isEmpty(options[key].trim())) {\n throw ('Value must not be empty.');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The (absolute) position directly before the wrapping node at the given level, or, when `depth` is `this.depth + 1`, the original position.
before(depth) { depth = this.resolveDepth(depth); if (!depth) throw new RangeError("There is no position before the top-level node"); return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; }
[ "after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }", "childBefore(pos) { return this.enter(-1, pos); }", "get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }", "assignPosition(node, position) { \n // assign the position\n node.position = position;\n\n // if the node is a \"leaf\" (on the end of a tree branch) end the recursion and let the above\n // function know to add 1 to the position \n if(node.children.length == 0){\n return 1;\n }\n \n // start the branch offset at 0\n let offset = 0;\n // recurse down the tree, adding 1 for every leaf node. \n // without multiple inheritance, this is the only reason we will need to increment position\n node.children.forEach(n => {\n // child nodes get assigned the passed-in position plus the offset\n offset += this.assignPosition(n, position+offset);\n });\n\n // return the offset to the above function\n return offset;\n }", "function topLevelNodeBefore(node, top) {\n while (!node.previousSibling && node.parentNode != top)\n node = node.parentNode;\n return topLevelNodeAt(node.previousSibling, top);\n }", "childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }", "function topLevelNodeBefore(node, top) {\n while (!node.previousSibling && node.parentNode != top) {\n node = node.parentNode;\n }\n return topLevelNodeAt(node.previousSibling, top);\n }", "above() {\r\n return new Pos(this.row - 1, this.col, this);\r\n }", "assignPosition(node, position) {\n node.position = position;\n\n if (node.children) {\n node.children.forEach(function(child) {\n position=this.assignPosition(child,position);\n }.bind(this))\n\n if (node.children.length == 0) {\n position++;\n }\n\n }\n return position;\n }", "function before(node) {\n return new Point(magic).moveToBefore(node);\n}", "function position() {\n var before = now()\n\n // Add the position to a node.\n function patch(node) {\n node.position = new Position(before)\n\n return node\n }\n\n return patch\n }", "function posOffset() {\n\t\tif (parent) {\n\t\t\treturn {\n\t\t\t\tx: parent.pos().x,// + pos.x,\n\t\t\t\ty: parent.pos().y// + pos.y\n\t\t\t};\n\t\t}\n\t\treturn {x: 0, y: 0};\n\t}", "get relativeDepth() {\n return 0;\n }", "get layerAbove()\n {\n var currentLayer = this;\n\n if (currentLayer.sublayerIndex + 1 < currentLayer.parent._sublayers.length) {\n currentLayer = currentLayer.parent._sublayers[currentLayer.sublayerIndex + 1];\n } else {\n // this layer has no more siblings in the up direction, so\n // its parent is what's above it, unless it's a top layer,\n // in which case we're at the top of the stack\n if (this.isTopLayer) {\n return null;\n } else {\n return currentLayer.parent;\n }\n }\n\n // keep drilling into the 0th (the lowest) sublayer until we run\n // out of sublayers, which will be the layer above inLayer\n while (currentLayer._sublayers.length > 0) {\n currentLayer = currentLayer._sublayers[0];\n }\n\n return currentLayer;\n }", "assignLevel(node, level) {\n // update the level of the node\n node.level = level;\n\n // the base case\n if (node.children.length === 0)\n {\n return node;\n }\n // the recursive case\n else\n {\n for (var h = 0; h < node.children.length; h++)\n {\n this.assignLevel(node.children[h], level + 1);\n }\n }\n }", "assignLevel(node, level) {\n node.level = level;\n for(let i = 0; i<node.children.length;++i){\n this.assignLevel(node.children[i],level+1);\n }\n }", "assignLevel(node, level) {\n\t\tnode.level = level;\n\n\t\tif(node.children.length === 0) return;\n\n\t\tfor(let i = 0; i < node.children.length; ++i)\n\t\t\tthis.assignLevel(node.children[i], level + 1);\n\t}", "function setPosition(arr, level, leftOffset) {\r\n console.log(\"In setPosition with level \" + level + \" and leftOffset \" + leftOffset + \". Also, leftEdge is \" + leftEdge);\r\n var blockWidth = 46;\r\n var rowHeight = 80;\r\n var left = leftEdge + leftOffset * blockWidth;\r\n var top = rowHeight * (level - 1);\r\n console.log(\"Position for array: \" + left + \", \" + top);\r\n // Set the top and left values so that all arrays are spaced properly\r\n arr.element.css({\"left\": left, \"top\": top});\r\n }", "leftViewUtil(node, level) {\n // Base Case \n if (node == null)\n return;\n\n // If this is the first node of its level \n if (this.max_level < level) {\n console.log(\" \" + node.data);\n this.max_level = level;\n }\n\n // Recur for left and right subtrees \n this.leftViewUtil(node.left, level + 1);\n this.leftViewUtil(node.right, level + 1);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
connct with end points
connectEpochEndPoints() { // console.log(this.allEndPoints); setTimeout( ()=>{ try{ // console.log(this.jsPlumbInstance); this.state.setupRules && this.state.setupRules.map( (ep,idx)=>{ ep.parent.map( (c,io)=>{ // console.log("Parent Map ==>",c) const pcCon = this.jsPlumbInstance.select({source:ep.nodeKey, target:c}); const cpCon = this.jsPlumbInstance.select({source:c, target:ep.nodeKey}); // this.jsPlumbInstance.select({source:et.component.source.id, target:et.component.target.id}) this.jsPlumbInstance.getAllConnections() // console.log("Connection Info",this.jsPlumbInstance.select({source:ep.nodeKey, target:c})); // console.log("Connection Opposite ",this.jsPlumbInstance.select({source:c, target:ep.nodeKey})); if( (pcCon && pcCon.length>0) || (cpCon && cpCon.length>0) ){ } else{ for(var e in this.allEndPoints){ if(e==c){ if("startWindow"==c){ // console.log( "End point ==>",ep.nodeKey.toString(),this.allEndPoints,this.allEndPoints[ep.nodeKey.toString()]); // console.log("ep.nodeKey===>",this.allEndPoints.epoch_1) // console.log("End bu node key ",this.allEndPoints.hasOwnProperty(ep.nodeKey),ep.nodeKey,e,ep.nodeKey==e ) this.jsPlumbInstance.connect({ source: this.allEndPoints[c], target: this.allEndPoints[ep.nodeKey][0] }); } else{ this.jsPlumbInstance.connect({ source: this.allEndPoints[c][1], target: this.allEndPoints[ep.nodeKey][0] }); } } } } }); ep.child.map( (ch,io)=>{ // console.log("child Map ==>",ch) const child_pcCon = this.jsPlumbInstance.select({source:ep.nodeKey, target:ch}); const child_cpCon = this.jsPlumbInstance.select({source:ch, target:ep.nodeKey}); if( (child_pcCon && child_pcCon.length>0) || (child_cpCon && child_cpCon.length>0 )){ } else{ for(var e in this.allEndPoints){ if(e==ch){ // console.log("End bu node key ",this.allEndPoints.hasOwnProperty(ep.nodeKey),ep.nodeKey,e,ep.nodeKey==e ) if("endWindow"==ch){ // console.log( "End point 1212 ==>",ep.nodeKey.toString(),this.allEndPoints); this.jsPlumbInstance.connect({ source: this.allEndPoints[ep.nodeKey][1], target: this.allEndPoints["endWindow"] }); } else{ this.jsPlumbInstance.connect({ source: this.allEndPoints[ep.nodeKey][1], target: this.allEndPoints[ch][0] }); } } } } }); }); this.jsPlumbInstance.repaintEverything(); } catch(e){ console.log(e) } } ,200) }
[ "get endPoints() {\n return [this.startPoint, this.endPoint];\n }", "calculateEndpoints(head = this.head, tail = this.tail) {\n const curve = new Curve(head, this.controlPt, tail);\n const incrementsArray = [0.001, 0.005, 0.01, 0.05];\n let increment = incrementsArray.pop();\n let t = 0;\n // let iterations = 0;\n while (increment && t < 0.5) {\n // iterations++;\n const pt = curve.bezier(t);\n if (this.tail.contains(pt)) {\n t += increment;\n } else {\n t -= increment;\n increment = incrementsArray.pop();\n t += increment || 0;\n }\n }\n // console.log('itertions: ' + iterations);\n this.endPt = curve.bezier(t);\n this.startPt = curve.bezier(1 - t);\n }", "getConnectionPoints()\n {\n let startBounds = this.start.getBounds()\n let endBounds = this.end.getBounds()\n let startCenter = new Point()\n\t startCenter.setPoint(startBounds.getCenterX(), startBounds.getCenterY())\n let endCenter = new Point()\n\t endCenter.setPoint(endBounds.getCenterX(), endBounds.getCenterY())\n let l = new Line()\n\t l.setPoints(this.start.getConnectionPoint(endCenter), this.end.getConnectionPoint(startCenter))\n\t return l\n }", "function getEndpoints() {\n var endpoints = []\n var entries = rows(ENDPOINTS)\n for(var i=0; i<entries.length; i++) {\n endpoints.push(entries[i])\n }\n return endpoints;\n}", "function connectionpoints(source, target, stubsource, stubtarget, anchorsource, anchortarget, strokestyle, dashstyle){\n instance.connect({\n source: source,\n target: target, \n connector:[ \"Flowchart\", { stub:[stubsource, stubtarget], gap:5, cornerRadius:5, alwaysRespectStubs:true } ],\n anchors:[anchorsource, anchortarget],\n paintStyle:{\n lineWidth:3,\n strokeStyle: strokestyle,\n dashstyle:dashstyle,\n joinstyle:\"miter\"\n },\n endpointStyle:{\n radius:1\n },\n endpointsOnTop:true,\n overlays : [\n [\"Arrow\", {\n cssClass:\"l1arrow\",\n id:\"arrow\",\n location:1, width:20,length:20,\n events:{\n \"click\":function(arrow, evt) {\n alert(\"clicked on arrow for connection \" + arrow.component.id);\n }\n }\n }]\n ]\n });\n }", "getConnectionPoints() {\n let startBound = this.startNode.getBounds()\n let endBound = this.endNode.getBounds()\n let startCenterX = (startBound.x + startBound.width) / 2\n let startCenterY = (startBound.y + startBound.height) / 2\n let endCenterX = (endBound.x + endBound.width) / 2\n let endCenterY = (endBound.y + endBound.height) / 2\n return [startNode.getConnectionPoint(endCenterX, endCenterY),\n endNode.getConnectionPoint(startCenterX, startCenterY)] \n }", "function EndConnections(stem_num, vorgaenger, EndBaseConnections, EndBasePairConnections) {\n\tvar bases_between_stems = new Array(stem_num);\t//contains the number of bases between the stems (in each coord. the bases \"before\" the\n\t\t\t\t\t\t\t\t\t\t\t\t\t//stem, only at the last coord. of bases_between_stems the free bases after\n\t\t\t\t\t\t\t\t\t\t\t\t\t//the last stem and before the closing BP are stored\n\t\n\tvar one_connection = new Array(); //help vector for one connection\n\tvar i;\n\n\t// number of free bases between the stem-ending base pairs\n\tfor(i = 0; i < stem_num-1; i++)\n\t\tbases_between_stems[i] = BP_Order[vorgaenger[i+1]][0] - BP_Order[vorgaenger[i]][1] - 1;\n\t\n\tbases_between_stems[stem_num-1] = brackets.length - BP_Order[vorgaenger[stem_num-1]][1] - 1;\n\n\t// finding all connections: (concerning free bases)\n\t//**************************************************\n\tfor(i = 0; i < stm_num-1; i++) {\n\t\t// if there is only one free base between the stems and if there is at least one free base after the next stem\n\t\tif(bases_between_stems[i] >= 1) {\n\t\t\tone_connection.push(BP_Order[vorgaenger[i]][1] + 1);\n\t\t\tif(bases_between_stems > 1) {\n\t\t\t\tEndBaseConnections.push(one_connection);\n\t\t\t\tone_connection.length = 0; // practically the same as .clear();\n\t\t\t\tone_connection.push(BP_Order[vorgaenger[i+1]][0] - 1);\n\t\t\t}\n\t\t} else {\n\t\t\tEndBaseConnections.push(one_connection);\n\t\t\tone_connection.length = 0; \n\t\t}\n\t}\n\n\tif(bases_between_stems[stem_num - 1] >= 1) {\n\t\tone_connection.push(BP_Order[vorgaenger[stem_num-1]][1]+1);\n\t\tEndBaseConnections.push(one_connection);\n\t\tone_connection.length = 0; \n\t} else {\n\t\tEndBaseConnections.push(one_connection);\n\t\tone_connection.length = 0;\n\t}\n\n\t// finding all connections: (concerning stems)\n\t//*************************************************\n\tone_connection.push(vorgaenger[0]);\n\n\tfor(i = 0; i < stem_num-1; i++) {\n\t\tif(bases_between_stems[i] == 1)\n\t\t\tone_connection.push(vorgaenger[i+1]);\n\t\telse {\n\t\t\tEndBasePairConnections.push(one_connection);\n\t\t\tone_connection.length = 0;\n\t\t\tone_connection.push(vorgaenger[i+1]);\n\t\t}\n\t}\n\tEndBasePairConnections.push(one_connection);\n\tone_connection.length = 0;\n}", "function EndConnections(vorgaenger, EndBaseConnections, EndBaseSizes, EndBasePairConnections, EndBasePairSizes) {\n\tvar stem_num = Math.max(BP_Order[numBP][3], 1);\n\tvar num_bp_con = 0; \t//current number of BasePairConnections\n\tvar num_base_con = 0;\t//current number of BaseConnections\n\tvar bp, base;\t//current position in the current connection\n\tvar bases_between_stems = new Array(stem_num);\t//contains the number of bases between the stems (in each coord. the bases \"before\" the\n\t\t\t\t\t\t\t\t\t\t\t\t\t//stem, only at the last coord. of bases_between_stems the free bases after\n\t\t\t\t\t\t\t\t\t\t\t\t\t//the last stem and before the closing BP are stored\n\n\tvar i; \n\n\t// number of free bases between the stem-ending base pairs\n\tfor(i = 0; i < stem_num-1; i++)\n\t\tbases_between_stems[i] = BP_Order[vorgaenger[i+1]][0] - BP_Order[vorgaenger[i]][1] - 1;\n\tbases_between_stems[stem_num-1] = struct_len - BP_Order[vorgaenger[stem_num-1]][1] - 1;\n\n\t// finding all connections: (concerning free bases)\n\t//**************************************************\n\tbp = 0;\n\tbase = 0;\n\n\tfor(i = 0; i < stem_num-1; i++) {\n\n\t\t// if there is only one free base between the stem and if there is atleast one free base after the next stem\n\t\tif(bases_between_stems[i] >= 1) {\n\t\t\tEndBaseConnections[num_base_con][base++] = BP_Order[vorgaenger[i]][1] + 1;\n\t\t\tif(bases_between_stems[i] > 1) {\n\t\t\t\tEndBaseSizes[num_base_con] = base;\n\t\t\t\tnum_base_con++;\n\t\t\t\tbase = 0;\n\t\t\t\tEndBaseConnections[num_base_con][base++] = BP_Order[vorgaenger[i+1]][0] - 1;\n\t\t\t}\n\t\t} else {\n\t\t\tEndBaseSizes[num_base_con] = base;\n\t\t\tnum_base_con++;\n\t\t\tbase = 0;\n\t\t}\n\t}\n\n\tif(bases_between_stems[stem_num - 1] >= 1) {\n\t\tEndBaseConnections[num_base_con][base++] = BP_Order[vorgaenger[stem_num-1]][1] + 1;\n\t\tEndBaseSizes[num_base_con] = base;\n\t\tnum_base_con++;\n\t\tbase = 0;\n\t} else {\n\t\tEndBaseSizes[num_base_con] = base;\n\t\tnum_base_con++;\n\t\tbase = 0;\n\t}\n\n\t// finding all connections: (concerning stems)\n\t//*************************************************\n\tEndBasePairConnections[num_bp_con][bp++] = vorgaenger[0];\n\n\tfor(i = 0; i < stem_num-1; i++) {\n\t\tif(bases_between_stems[i] == 1)\n\t\t\tEndBasePairConnections[num_bp_con][bp++] = vorgaenger[i+1];\n\t\telse {\n\t\t\tEndBasePairSizes[num_bp_con] = bp;\n\t\t\tnum_bp_con++;\n\t\t\tbp = 0;\n\t\t\tEndBasePairConnections[num_bp_con][bp++] = vorgaenger[i+1];\n\t\t}\n\t}\n\n\tEndBasePairSizes[num_bp_con] = bp;\n\tnum_bp_con++;\n\tbp = 0;\n}", "function agregarendpoint(nuevoendpoint) {\n endpoints.push(nuevoendpoint);\n}", "_implicitUrlContinuationEnd(start, max)\n {\n let initial = start;\n let maybe = false;\n while (start <= max)\n {\n // Not an exact science, as a URL can contain a lot of things after the domain, especially\n // when things aren't always escaped. Because of that, there are three categories:\n // 1. Allowed - characters we always allow to be in URLs\n // 2. Disallowed - characters that always terminate a URL\n // 3. Grey - characters that might terminate a URL. If the next character is grey or disallowed,\n // don't include this one in the URL. Otherwise if the next character is allowed, include this as well.\n switch (this.text[start])\n {\n case ' ':\n case ',':\n case '\\n':\n case '\"':\n case \"'\":\n return start - (maybe ? 1 : 0);\n case ':':\n case ';':\n case '.':\n case '!':\n case ')':\n case '(':\n case '[':\n case ']':\n case '\\\\':\n maybe = true;\n break;\n default:\n maybe = false;\n break;\n }\n\n ++start;\n }\n\n if (maybe)\n {\n return start - 1;\n }\n\n return start == this.text.length ? start : initial;\n }", "static endpoints() {\n\t\treturn NativeModules.NearbyConnection.endpoints();\n\t}", "function hostNamesConnectedTo(endhost) {\n return new Promise((fullfil, reject) => {\n pool.query('SELECT DISTINCT starthost FROM hostconnections WHERE endhost = $1 AND conndate BETWEEN now() - interval \\'1 hour\\' and now();', [endhost],\n function (err, result) {\n if (err) {\n reject(err);\n } else {\n fullfil(result);\n }\n });\n\n });\n}", "function secondaryConnect(startIndex, endIndex) {\n let start = parseInt(startIndex);\n let end = parseInt(endIndex);\n codeBoxArr[start][4] = parseInt(end);\n codeBoxArr[end][5].push(start);\n}", "function setupEndpoint() {\n if (host.val().indexOf('/') != -1) {\n var hostArr = host.val().split('/');\n\n path = \"http://\" + hostArr[0] + \":\" + port.val();\n hostArr.shift(); // remove host\n\n if (hostArr.length > 0) { // anything left?\n path += \"/\" + hostArr.join('/');\n }\n } else {\n path = \"http://\" + host.val() + \":\" + port.val();\n }\n endpoint = path;\n }", "function secondaryConnect(startIndex, endIndex) {\n let start = parseInt(startIndex);\n let end = parseInt(endIndex);\n codeBoxArr[start][4] = parseInt(end);\n}", "function getEnds(connector) {\n\treturn map(connector, function(primitive) {\n\t\treturn [primitive.source, primitive.target];\n\t});\n}", "function deriveEndpoint(edge,index,ep,conn){return options.deriveEndpoint?options.deriveEndpoint(edge,index,ep,conn):options.endpoint?options.endpoint:ep.type;}//", "connect(n1, n2){\n this.start = n1\n this.end = n2\n this.start.addEdge(this)\n this.end.addEdge(this)\n this.draw()\n }", "_onEnd () {\n debug('Connection to %s:%s ended', this.host, this.port)\n this.emit('end')\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called at the after a model constructor function is run. exitNamespace() will shift the current namespace off of the stack, 'exiting' to the next namespace in the stack
function exitNamespace() { namespaceStack.shift(); return fw.utils.currentNamespace(); }
[ "exitOracle_namespace(ctx) {\n\t}", "_exitScope() {\n\t\tthis.scope = this.scope.parent;\n\t}", "exitNseModelName(ctx) {\n\t}", "exitNseModel(ctx) {\n\t}", "exitExplicitSubModel(ctx) {\n\t}", "exitComplexModel(ctx) {\n\t}", "exitConstructor_declaration(ctx) {\n\t}", "exitModelInfoDefinition(ctx) {\n\t}", "exitXml_namespaces_clause(ctx) {\n\t}", "function exitScope() {\n if (scopeInfo) {\n scopeInfo = scopeInfo.upper;\n }\n }", "exitMain_model_name(ctx) {\n\t}", "exitModelInfoSection(ctx) {\n\t}", "function enterNamespace(namespace) {\n namespaceStack.unshift( namespace.getName() );\n return namespace;\n}", "exitPackageDeclaration(ctx) {\n\t}", "exitConstraintDeclaration(ctx) {\n\t}", "exitScope() {\n // Free up all the identifiers used in the previous scope\n this.scopes.pop().free(this.context);\n this.scope = this.scopes[this.scopes.length - 1];\n }", "function namespaceHTMLInternal() {\n instructionState.lFrame.currentNamespace = null;\n}", "exitInitDeclarator(ctx) {\n\t}", "exitAnnotation(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a slider for floating point numbers
addFloat(name, min, max, value, callback, hide = true) { this.defaultValues[name] = value; this.elementMap[name] = this.elementCounter; this.types[name] = "float"; let e = document.getElementById("guiArea"); let line = document.createElement("div"); line.setAttribute("class", "guiLine" + (hide ? " hideGuiElement" : "")); line.setAttribute("name", "guiElemGroup" + this.elementGroupCounter); let tagField = document.createElement("div"); tagField.textContent = this.getDisplayName(name); tagField.setAttribute("class", "guiTag"); let valueField = document.createElement("input"); valueField.setAttribute("type", "number"); valueField.value = value; valueField.setAttribute("class", "guiValueFloat"); let slider = document.createElement("input"); slider.setAttribute("id", "guiElem" + this.elementCounter); slider.setAttribute("type", "range"); slider.setAttribute("min", min); slider.setAttribute("max", max); slider.setAttribute("step", (max - min) / 1000000000.0); slider.setAttribute("value", value); slider.setAttribute("class", "guiSlider"); line.appendChild(tagField); line.appendChild(slider); line.appendChild(valueField); e.appendChild(line); valueField.addEventListener( "input", function () { this.values[name] = valueField.value; slider.value = valueField.value; callback(valueField.value); //valueField.blur() // Leave focus, otherwise selection cannot work }.bind(this), false ); slider.addEventListener( "input", function () { this.values[name] = slider.value; valueField.value = slider.value; callback(slider.value); //slider.blur() // Leave focus, otherwise selection cannot work }.bind(this), false ); this.elementCounter += 1; }
[ "function makeSlide(t,e){return'<label for=\"'+t+'\" > '+t+': <span id=\"'+t+'-value\">…</span></label> <input type=\"range\" min=\"0\" max=\"'+e+'\" step=\"0.1\" id=\"'+t+'\">'}", "function showSliderValue() {\n rangeBullet.innerHTML = rangeSlider.value;\n let leftPosition = (window.screen.width - 500) / 2;\n let bulletPosition = rangeSlider.value / rangeSlider.max;\n rangeBullet.style.left = bulletPosition * 480 + leftPosition + \"px\";\n}", "function setSlider(slider, sliderHTMLval, value, commaDigits, str_units){\n var formattedValue=value.toFixed(commaDigits);\n slider.value=value;\n sliderHTMLval.innerHTML=formattedValue+\" \"+str_units; // +\" \" DOS=>str_units\n console.log(\"setSlider: value=\",value\n\t ,\" innerHTML=\",sliderHTMLval.innerHTML);\n}", "function setSliderVal(tgt, val) {\n $('#'+tgt+'_slider').slider('value',(g_scale_factor*val).toFixed());\n}", "function displaySlider(){\n\n document.getElementById(\"mySliderDiv\").innerHTML = '<input id=\"mySlider\" type=\"text\" class=\"span2\" value=\"\" data-slider-min=\"0.1\" data-slider-max=\"14.9\" data-slider-step=\"0.1\" data-slider-value=\"14\" data-slider-orientation=\"vertical\" data-slider-selection=\"after\"data-slider-tooltip=\"hide\">';\n\n $('.slider').slider();\n\n $('#mySlider').slider()\n .on('slide', function(ev){\n\n for (var i = 0 ; i < sphereList.length ; i++){\n //\n sphereList[i].scale.x = 15 - ev.value;\n sphereList[i].scale.y = 15 - ev.value;\n sphereList[i].scale.z = 15 - ev.value;\n //\n currentScale = 15 - ev.value; \n } \n\n });\n\n}", "function addSlider(id){\r\n\tslider = new Slider(id, {\r\n\t\tcallback: function(value) {\r\n\t\t},\r\n\t\tanimation_callback: function(value) {\r\n\t\t\tif(value>0){\r\n\t\t\t getDocViewer('documentViewer').setZoom(5*value);\r\n\t\t\t setZoomText(5*value);\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "function updateSlider() {\n var val = $(\"#slider\").val();\n\n $(\"#salary-cap-box\").html(`$${addCommas(val)}`);\n luxuryTax();\n }", "function showSliderValue(x)\n{\n document.getElementById('slider-value').innerHTML=x;\n}", "function update_sliders() {\r\n sliderValues=[]\r\n \tarr.forEach(function(el) {\r\n \t\tel.slider.val(Math.round(el.val));\r\n \t\tel.disp.text(Math.round(el.val) + '%');\r\n sliderValues.push(Math.round(el.val));\r\n \t});\r\n }", "function update_slider() {\r $slider.slider('values', 0, current_input_from());\r $slider.slider('values', 1, current_input_to());\r }", "function set_sliders(th,ra,at,re){\n document.querySelector('#threshold').value = th\n document.querySelector('#ratio').value = ra\n document.querySelector('#attack').value = at\n document.querySelector('#release').value = re\n}", "function addSlider(){\n\tif (typeof graphDiv.layout.xaxis.rangeslider === 'undefined') { graphDiv.layout.xaxis = {rangeslider: {}}; }\n\telse { graphDiv.layout.xaxis = {}; }\n\t\n\tPlotly.redraw(graphDiv);\n}", "function adjustSlider(){\n if ( $( \"#js-slider-range\" ).slider(\"instance\") !== undefined) {\n $(\"#js-slider-range\").slider(\"values\",0,rangeStart);\n $(\"#js-slider-range\").slider(\"values\",1,rangeEnd);\n }\n $( \"#js-amount\" ).html( formatCurrency(rangeStart) + \" - \" + formatCurrency(rangeEnd));\n $( \"input[name=price]\" ).val( rangeStart + \";\" + rangeEnd );\n }", "function rangeSlider(value) {\n\tbpmValue.innerHTML = value;\n}", "_updateValue () {\n let sliderWidth = this._sliderElement.offsetWidth;\n\n // Calculate the new value\n let { minValue, maxValue } = this._options;\n let percentage = this._xPosition / sliderWidth;\n let value = minValue + (maxValue - minValue) * percentage;\n this.emit(\"update\", value);\n }", "function changeRateDbl() {\n document.getElementById(\"rateSlider\").value = 10000;\n changeRate();\n}", "function addSlider (data,multiplier,circleColor) {\n $( \"#slider\" ).slider({\n range: \"max\",\n min: 1,\n max: 10,\n\t step: 1,\n value: 1,\n slide: function( event, ui ) {\n //$( \"#amount\" ).val( ui.value );\n\t\t//console.log(ui.value);\n\t\tvar multiplier = ui.value;\n\t\tconsole.log('the value of the multiplier is: ' + multiplier);\n\t\t//remove all the data points already plotted\n\t\t$(\".dataPt\").remove();\n\t\t//reset any colors of circles already set previously back to default color\n\t\tcircleColor = '#add2f1';\n\t\t//figure out circle color based on multiplier\n\t\tif (multiplier ==2)\t{\n\t\t\tcircleColor = '#aeb6ff'\n\t\t}\n\t\tif (multiplier == 3)\t{\n\t\t\tcircleColor = '#edb2ff'\n\t\t}\n\t\tif (multiplier == 4)\t{\n\t\t\tcircleColor = '#ffc161'\n\t\t}\n\t\tif (multiplier == 5)\t{\n\t\t\tcircleColor = '#ef4c15'\n\t\t}\n\t\tif (multiplier == 6)\t{\n\t\t\tcircleColor = '#ef1515'\n\t\t}\n\t\tif (multiplier >= 7)\t{\n\t\t\tcircleColor = '#380000'\n\t\t}\n\t\t//now go ahead and replot the data points again \n\t\t//using the multiplier from the slider\n\t\tplotDataPoints(data,multiplier,circleColor);\n }\n });\n}", "function addSlider(name, parent, min, max, start, onchange) {\n var step = (max-min)/(1000);\n var newSlider = document.createElement(\"input\");\n var newNode = document.createElement(\"p\");\n var padding = document.createElement(\"div\");\n newNode.id = name;\n newNode.textContent = name + \":\";\n newSlider.id = name + \"-slider\"; // if this naming convention changes, getSliderValue needs to change.\n newSlider.type = \"range\";\n newSlider.step = step;\n newSlider.min = min;\n newSlider.max = max;\n newSlider.value = start;\n newSlider.onchange = onchange;\n newNode.appendChild(padding);\n padding.appendChild(newSlider);\n document.getElementById(parent).appendChild(newNode);\n // document.getElementById(name).appendChild(newSlider);\n}", "addSliders() {\n this.sliders = this.config.map(function createSlider(obj) {\n var slider = document.createElement('input'),\n valueElement = document.createElement('span');\n slider.type = 'range';\n slider.min = 0;\n slider.value = 0;\n slider.setAttribute('data-axis', obj.gS);\n slider.setAttribute('data-vpart', obj.vPart);\n slider.setAttribute('data-size', obj.size);\n valueElement.textContent = obj.vPart + ': 0';\n extensionElements.mouseSlidersWrapper.appendChild(slider);\n extensionElements.mouseSlidersWrapper.appendChild(valueElement);\n slider.addEventListener('input', this.onSliderChange.bind(this));\n slider.addEventListener('blur', this.onSliderBlur);\n return slider;\n }, this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swaps the sortIndex with the next lesserEntry.
function decrementSortIndex(entry){ var d = $.Deferred(); db.transaction(function (tx) { // fetch sortIndex of the current entry tx.executeSql('SELECT sortIndex FROM entries WHERE id = ? ', [entry.id], function (tx, entryResults) { if (!entryResults.rows.length) { // no sortIndex for current entry d.reject(); return; } entry.sortIndex = entryResults.rows.item(0).sortIndex; // fetch id and sortIndex of the next lesserEntry tx.executeSql('SELECT id, sortIndex FROM entries WHERE sortIndex < ? ORDER BY sortIndex DESC LIMIT 1', [entry.sortIndex], function (tx, results) { if(!results.rows.length){ // no lesserEntry d.reject(); return; } // set sortIndex of the entry to the one of the lesserEntry tx.executeSql('UPDATE entries SET sortIndex = ? WHERE id = ?', [results.rows.item(0).sortIndex, entry.id]); // set sortIndex of the lesserEntry to the one of the entry tx.executeSql('UPDATE entries SET sortIndex = ? WHERE id = ?', [entry.sortIndex, results.rows.item(0).id]); }) }) }, function (error) { console.log("Transaction Error: " + error.message); d.reject(); }, function () { d.resolve(); }); return d; }
[ "function incrementSortIndex(entry){\n\n var d = $.Deferred();\n\n db.transaction(function (tx) {\n\n // fetch sortIndex of the current entry\n tx.executeSql('SELECT sortIndex FROM entries WHERE id = ? ', [entry.id], function (tx, entryResults) {\n if (!entryResults.rows.length) {\n // no sortIndex for current entry\n d.reject();\n return;\n }\n entry.sortIndex = entryResults.rows.item(0).sortIndex;\n\n // fetch id and sortIndex of the next greaterEntry\n tx.executeSql('SELECT id, sortIndex FROM entries WHERE sortIndex > ? ORDER BY sortIndex ASC LIMIT 1', [entry.sortIndex], function (tx, results) {\n if(!results.rows.length){\n // no greaterEntry\n d.reject();\n return;\n }\n // set sortIndex of the entry to the one of the greaterEntry\n tx.executeSql('UPDATE entries SET sortIndex = ? WHERE id = ?', [results.rows.item(0).sortIndex, entry.id]);\n // set sortIndex of the greaterEntry to the one of the entry\n tx.executeSql('UPDATE entries SET sortIndex = ? WHERE id = ?', [entry.sortIndex, results.rows.item(0).id]);\n })\n\n })\n\n },\n function (error) {\n console.log(\"Transaction Error: \" + error.message);\n d.reject();\n },\n function () {\n d.resolve();\n });\n\n return d;\n }", "function _insertionSort() {\r\n n = sortingArray.length;\r\n for (var i = 0; i < n; i++) {\r\n for (var j = i - 1; j >= 0; j--) {\r\n if (sortingArray.getItem(j).getValue() > sortingArray.getItem(j + 1).getValue()) {\r\n // Shift element at j to the right and shift element at i to the left\r\n _swap(j, j + 1);\r\n }\r\n }\r\n }\r\n}", "function sorter(a, b) {\n if (a.index < b.index) {\n return -1;\n }\n if (a.index > b.index) {\n return 1;\n }\n return 0;\n }", "function swapSort(items, lookingFor, unsortedInd) {\n\titems.forEach((item, index) => {\n\t\t/*\n\t\t\tSwaps current value with the value at the unsorted index if current value is the current wanted value.\n\t\t*/\n\t\tif (lookingFor === item) {\n\t\t\tswapElements(items, unsortedInd, index)\n\t\t\t++unsortedInd\t// array is partially sorted, increment index to get to new unsorted index\n\t\t}\n\t})\n\n\treturn unsortedInd\n}", "heapifyUp() {\n //assing the last added item's index position\n let index = this.lastItemIndex();\n //as long as there is a parent and\n //as long as parent value is greater than current value\n //swap the two values in the array\n while (\n this.hasParent(index) &&\n this.parentItem(index) > this.result[index]\n ) {\n this.swap(this.result, this.parentIndex(index), index);\n //and reset the index position\n index = this.parentIndex(index);\n }\n }", "function sortByIndex1(a, b) {\n\tif (a[1] === b[1]) {\n\t\treturn 0;\n\t}\n\telse {\n\t\treturn (a[1] < b[1]) ? 1 : -1; // largest to smallest\n\t}\n}", "function inssortshift2(A) {\n for (var i = 1; i !== A.length; i++) { // Insert i'th record\n var j;\n var temp = A[i];\n for (j = i; (j !== 0) && (temp < A[j - 1]); j--)\n A[j] = A[j-1];\n A[j] = temp;\n }\n}", "_swap_if_less(idx_a, idx_b) {\n\t\tif (this._less_than(this._array[idx_a], this._array[idx_b])) {\n\t\t\tthis._swap(idx_a, idx_b);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "function inssort2(A) {\n var temp;\n for (var i = 1; i < A.length; i++) // Insert i'th record\n for (var j = i; (j > 0) && (A[j] < A[j - 1]); j--) {\n temp = A[j]; A[j] = A[j - 1]; A[j - 1] = temp;\n }\n}", "function ShellSortCardIndex(iCardIndexList, iCompareMethod)\r\r\n{\r\r\n DebugLn(\"ShellSortCardIndex\");\r\r\n var sortIncrement = 3\r\r\n while (sortIncrement > 0)\r\r\n {\r\r\n var iiCard = 0;\r\r\n for (iiCard = sortIncrement; iiCard < iCardIndexList.length; iiCard++)\r\r\n {\r\r\n var jjCard = iiCard;\r\r\n var tempCardNum = iCardIndexList[iiCard];\r\r\n while (jjCard >= sortIncrement && \r\r\n iCompareMethod(iCardIndexList[jjCard - sortIncrement], tempCardNum) > 0)\r\r\n {\r\r\n var delta = jjCard - sortIncrement;\r\r\n iCardIndexList[jjCard] = iCardIndexList[delta];\r\r\n jjCard = delta;\r\r\n }\r\r\n iCardIndexList[jjCard] = tempCardNum;\r\r\n }\r\r\n if (sortIncrement == 1)\r\r\n {\r\r\n sortIncrement = 0;\r\r\n }\r\r\n else\r\r\n {\r\r\n sortIncrement = Math.floor(sortIncrement / 2);\r\r\n if (sortIncrement == 0)\r\r\n sortIncrement = 1;\r\r\n }\r\r\n }\r\r\n}", "function _entrySort(a, b){\n a = new Date(a.date);\n b = new Date(b.date);\n return b - a;\n }", "_fixTopHeap(idx) {\n if (idx === 0) return;\n\n let _parentIdx = (idx - 1) >> 1;\n\n if (this.comparison(\n this._priorityHeap[idx], this._priorityHeap[_parentIdx])) {\n this._swap(idx, _parentIdx);\n this._fixTopHeap(_parentIdx);\n }\n }", "_sortTopDown(): void {\n let current = 0;\n let left = (current + 1) * 2 - 1;\n let right = (current + 1) * 2;\n let leftExists = this.size > left;\n let rightExists = this.size > right;\n\n // Check if the heap property is satisfied for the current index.\n while (\n (leftExists && this._values[left] < this._values[current]) ||\n (rightExists && this._values[right] < this._values[current])\n ) {\n // Swap with the smallest child.\n if (\n (leftExists && !rightExists) ||\n (leftExists && rightExists && this._values[left] < this._values[right])\n ) {\n this._swapIndices(current, left);\n current = left;\n } else {\n this._swapIndices(current, right);\n current = right;\n }\n\n left = (current + 1) * 2 - 1;\n right = (current + 1) * 2;\n leftExists = this.size > left;\n rightExists = this.size > right;\n }\n }", "function sortShops(currentIndex, oldIndex){\r\n var buffer = shopStorage[oldIndex];\r\n if (currentIndex < oldIndex){\r\n for(var i = oldIndex; i > currentIndex; i--){\r\n shopStorage[i] = shopStorage[i-1];\r\n }\r\n shopStorage[currentIndex] = buffer;\r\n }else if (currentIndex > oldIndex){\r\n for(var i = oldIndex; i < currentIndex; i++){\r\n shopStorage[i] = shopStorage[i+1];\r\n }\r\n shopStorage[currentIndex] = buffer;\r\n }\r\n sortShopNumbers();\r\n }", "stepSort() {\n if (this.leftLimit < this.rightLimit) {\n if (this.sortRight) {\n if (this.rightItr < this.rightLimit) {\n if (\n this.compare(\n this.array[this.rightItr],\n this.array[this.rightItr + 1]\n )\n ) {\n let temp = this.array[this.rightItr];\n this.array[this.rightItr] = this.array[this.rightItr + 1];\n this.array[this.rightItr + 1] = temp;\n }\n } else {\n this.rightLimit = this.rightItr - 1;\n this.leftItr = this.rightLimit;\n this.sortRight = false;\n }\n this.rightItr++;\n } else {\n if (this.leftItr > this.leftLimit) {\n if (\n this.compare(this.array[this.leftItr - 1], this.array[this.leftItr])\n ) {\n let temp = this.array[this.leftItr];\n this.array[this.leftItr] = this.array[this.leftItr - 1];\n this.array[this.leftItr - 1] = temp;\n }\n } else {\n this.leftLimit = this.leftItr + 1;\n this.rightItr = this.leftLimit;\n this.sortRight = true;\n }\n this.leftItr = this.leftItr - 1;\n }\n }\n return this.array;\n }", "_swap(idx1, idx2) {\n let _tempElement = this._elementHeap[idx1];\n let _tempPriority = this._priorityHeap[idx1];\n\n this._elementHeap[idx1] = this._elementHeap[idx2];\n this._priorityHeap[idx1] = this._priorityHeap[idx2];\n\n this._elementHeap[idx2] = _tempElement;\n this._priorityHeap[idx2] = _tempPriority;\n\n this._indexLookup[this._elementHeap[idx1]] = idx1;\n this._indexLookup[this._elementHeap[idx2]] = idx2;\n }", "function insertSort() {\n // first, make copy of the generated array so array is not overwritten\n var sortedArray = copyArray(theArray);\n \n // set # of comparisions and swaps to zero\n compNs = 0;\n swapNs = 0;\n \n \n for (var i=1; i<sortedArray.length; i++) {\n // value that is being examined\n vInsert = sortedArray[i];\n // index of examined value\n pInsert = i;\n \n while (pInsert>0 && sortedArray[pInsert-1]>vInsert) {\n // note: this is not considered a swap (theyre puedo insertions...copies)\n sortedArray[pInsert] = sortedArray[pInsert-1];\n pInsert--;\n compNs = compNs+1;\n }\n \n // perform final swap if nesessary & add to swap count\n if (i != pInsert) {\n sortedArray[pInsert] = vInsert;\n swapNs = swapNs+1;\n }\n \n }\n \n document.getElementById(\"new\").innerHTML = formatArray(sortedArray);\n\n document.getElementById(\"comps\").innerHTML = \"Number of Comparisons: \" + compNs;\n document.getElementById(\"swaps\").innerHTML = \"Number of Swaps: \" + swapNs;\n document.getElementById(\"method\").innerHTML = \"using the insertion sort method\";\n \n}", "function insertionSortSwap(arr) {\n for (let i = 0; i < arr.length - 1; i++) {\n for (let j = i + 1; j > 0; j--) {\n if (arr[j] < arr[j - 1]) [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];\n else break;\n }\n }\n\n return arr;\n}", "function sortByNumber(tableIndex) {\n let rows, switching, i, x, y, shouldSwitch;\n switching = true;\n while (switching) {\n switching = false;\n rows = table.getElementsByTagName(\"tr\");\n for (i = 1; i < (rows.length - 1); i++) {\n shouldSwitch = false;\n // Parse the string as an integer so we can use mathematical comparisons, rather than string comparison\n x = parseInt(rows[i].getElementsByTagName(\"td\")[tableIndex].innerHTML);\n y = parseInt(rows[i + 1].getElementsByTagName(\"td\")[tableIndex].innerHTML);\n // If we are ordering by position, leave as this comparison as we want lowest to highest numerical value\n if (x > y) {\n shouldSwitch = true;\n break;\n }\n }\n if (shouldSwitch) {\n rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);\n switching = true;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers one or more userdefined types into xtypejs.
function registerMultipleTypes(customTypes) { if (typeof customTypes !== 'object') { return; } objKeys(customTypes).forEach(function(customTypeName) { registerSingleType(customTypeName, customTypes[customTypeName]); }); }
[ "addTypes(types) {\n for (let name in types) {\n this.addType(name, types[name]);\n }\n }", "function registerTypes(types, category) {\n\tvar prefix = category ? category + '.' : '';\n\t_.forOwn(types, function(value, key) {\n\t\tvar inh = value.inherit, i;\n\t\tif (inh) {\n\t\t\tfor (i = 0; i < inh.length; i++) {\n\t\t\t\t_.defaults(value, inh[i]);\n\t\t\t}\n\t\t\tdelete value.inherit;\n\t\t}\n\t\tvar tname = prefix + key;\n\t\tif (Types.hasOwnProperty(tname)) {\n\t\t\tconsole.error('Duplicate type registered: ' + tname);\n\t\t\treturn;\n\t\t}\n\t\tTypes[tname] = value;\n\t});\n}", "function _registerAlias(types, type) {\n t[type.toUpperCase() + \"_TYPES\"] = types;\n registerType(type);\n}", "function TypeRegistry() {\n this.types = {};\n }", "function register( type, baseType ){\n var fullType;\n if( baseType ){\n var origType = type.type;\n type.type = baseType;\n fullType = enrichTypeInstance( type );\n fullType.type = origType;\n } else {\n fullType = _.defaults( type, defaultType );\n }\n registeredTypes.push( fullType );\n}", "static register(cls) {\n this.NodeTypes.push(cls);\n }", "static register(arr) {\n\t\tif (!Array.isArray(arr)) arr = [[].slice.call(arguments)];\n\t\tfor (let entry of arr) {\n\t\t\tif (!Array.isArray(entry)) entry = [entry];\n\t\t\tlet [id, Klass] = entry;\n\t\t\tif (!Klass) {\n\t\t\t\tKlass = id;\n\t\t\t\tid = Klass.id || Klass.prototype.id;\n\t\t\t}\n\n\t\t\t// Register.\n\t\t\tDBPF.FileTypes[ id ] = Klass;\n\n\t\t}\n\t}", "function initTypes(customTypes) {\n for (var type in customTypes) {\n if (hasOwnProperty.call(customTypes, type)) {\n createType(type, customTypes[type]);\n }\n }\n}", "init() {\n [\n \"anything\",\n \"boolean\",\n \"date\",\n \"email\",\n \"enum\",\n \"geoPoint\",\n \"geoShape\",\n \"integer\",\n \"ipAddress\",\n \"numeric\",\n \"object\",\n \"string\",\n \"url\",\n ].forEach((typeFile) => {\n const TypeConstructor = require(`./types/${typeFile}`);\n this.addType(new TypeConstructor());\n });\n }", "function register(data) {\n\t\ttypes[data.name] = data;\n\t\tich.addTemplate(data.name, data.content);\n\t}", "function register() {\n if (Object.prototype.typeOf !== boundTypeOf) {\n otypeof = Object.prototype.typeOf;\n Object.prototype.typeOf = boundTypeOf;\n }\n }", "registerType(type, Class) {\n if (this.WOClassLookup[type]) {\n console.error(\n `registerType: ${type} is already defined. This will override previous definition.`\n );\n }\n this.WOClassLookup[type] = Class;\n }", "addType(id, data) {\n this.types[id] = new TypeData(data);\n }", "function register() {\n safeRegister();\n exports.clone.register();\n exports.copy.register();\n exports.extend.register();\n exports.typeOf.register();\n }", "function addType(type, ext) {\n moduleType[ext] = type;\n }", "register(name, typeConstructor) {\r\n this.getInstance()._types[name] = typeConstructor;\r\n }", "function register(typeName, opts) {\n // initialise options\n opts = opts || {};\n opts.checks = opts.checks || {};\n opts.type = opts.type || typeName;\n \n interactors.push(opts);\n }", "function register(type, name, value) {\n\tregistry[type][name] = value;\n}", "registerDanmakuType(name, type) {\n\t\tthis.nameToType.set(name, type)\n\t\tthis.danmakuPools.set(type, new Set())\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shouldComponentUpdate is invoked when ReactChild render is invoked React will invoke this function pretty often, so the implementation has to be fast.
shouldComponentUpdate(){ if(this.props.debug)console.log("Child - shouldComponentUpdate"); return false; // this ensures parent render wont render this component }
[ "shouldComponentUpdate (nextProps) {\n if (!nextProps.allowUpdateRender) {\n return false\n }\n\n // Prevent redundant renders\n return !equal(this.props, nextProps)\n }", "shouldComponentUpdate(nextProps) {\n return shallowCompare(this, nextProps);\n }", "shouldComponentUpdate() {\n\t\treturn false;\n\t}", "shouldComponentUpdate() {\n return false;\n }", "shouldComponentUpdate(props, state) {\n return +state.modified > +this.state.modified;\n }", "shouldComponentUpdate(nextProps) {\n return nextProps.complete != this.props.complete;\n }", "shouldComponentUpdate (nextProps, nextState) {\n // Update component only if the modal is oppened or closed, in other words\n // if props.show changed\n return (\n nextProps.show !== this.props.show ||\n nextProps.children !== this.props.children\n )\n // with children we are taking into consideration the spinner and order\n // summary components when deciding whether or not to update the component\n }", "shouldComponentUpdate(nextProps, nextState) {\n return nextProps.rule !== this.props.rule || this.state.needsToGrow || this.state.inGrowth;\n }", "shouldComponentUpdate(nextProps, nextState) {\n // if props exist and it is different from the props, then we render\n if (nextProps.ignoreProp && this.props.ignoreProp !== nextProps.ignoreProp) {\n console.log('shouldComponentUpdate - DO NOT RENDER')\n console.log('-------------------------------------')\n return false;\n }\n console.log('shouldComponentUpdate - DO RENDER')\n return true;\n }", "shouldComponentUpdate(nextProps) {\n const isWidgetContainer = ['object', 'list'].includes(nextProps.field.get('widget'));\n return isWidgetContainer || this.props.value !== nextProps.value;\n }", "shouldComponentUpdate(nextProps,nextState){\r\n return nextProps.show !== this.props.show || nextProps.children !==this.props.children ;\r\n }", "shouldComponentUpdate(nextProps, nextState) {\n return this.props.time != nextProps.time;\n }", "shouldComponentUpdate(nextProps, nextState) {\n // include check for when props of children have changed,\n // to show loading state (and spinner) for order component which is a child of modal comp\n return nextProps.show !== this.props.show || nextProps.children !== this.props.children\n }", "shouldComponentUpdate(nextProps) {\n let shouldRedraw = (nextProps.districts !== this.props.districts)\n if (shouldRedraw) this.drawDistricts(nextProps.districts)\n return false\n }", "shouldUpdate() {\n //should update if not render before\n if (!this._lastRender) {\n return true;\n }\n // make sure this have no side effect to this component\n const html = this.getTemplate().call(this, (this.getData()));\n return (html != this._lastRender.html) || !this._isSameMountPoint(this.getMountPoint(), this._lastRender.mountPoint);\n }", "shouldComponentUpdate(nextProps, nextState) {\n return nextProps.show !== this.props.show;\n }", "shouldComponentUpdate(nextProps) {\n if (!nextProps.position) {\n return false;\n }\n return true;\n }", "shouldComponentUpdate(nextProps) {\n if (this.props === nextProps) return false\n\n return (this.props.className !== nextProps.className) ||\n (this.props.style !== nextProps.style) ||\n (this.props.onClick !== nextProps.onClick) ||\n (this.props.isUnread !== nextProps.isUnread) ||\n (!isEqual(this.props.feed, nextProps.feed))\n }", "shouldComponentUpdate(nextProps) {\n log(`Shelf.shouldComponentUpdate: ${this.props.videos.length !== nextProps.videos.length}`);\n return this.props.videos.length !== nextProps.videos.length;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inicializa productos de cada html
function inicializarProd() { //obtengo el html actual que navego para crear los productos correspondientes let htmlActual = document.documentURI.split("/")[document.documentURI.split("/").length - 1]; if (htmlActual == "smartphone.html") { let productos = document.getElementById("productos"); createProductos(arrayOfSmartphones, productos); createFooter(); createModal(); createModalPersona(); createModalMenor(); createModalEmail(); createModalSolicitudProcesada(); } else if (htmlActual == "tecno.html") { let productos = document.getElementById("productos"); createProductos(arrayOfTecno, productos); createFooter(); createModal(); createModalPersona(); createModalMenor(); createModalEmail(); createModalSolicitudProcesada(); } else if (htmlActual == "xp.html") { let productos = document.getElementById("productos"); createProductos(arrayOfXP, productos); createFooter(); createModal(); createModalPersona(); createModalMenor(); createModalEmail(); createModalSolicitudProcesada(); } }
[ "function createProducts() {\n products = [\n new Product('Burrito', 'Safiger Burrito mit zarter Hähnchenbrust und mediterranem Gemüse', 6.00, 'burrito.jpg', 1),\n new Product('Taco', 'Knuspriger Taco mit verschiedenem Gemüse der Saison', 3.90, 'taco.jpg', 1),\n new Product('Quesadilla', 'Gebackene Quesadilla gefüllt mit mediterrandem Gemüse und würzigem Käse', 7.00, 'quesadilla.jpg', 1),\n new Product('Tortilla', 'Schmackhafte Tortilla aus Kartoffeln mit Knoblauchöl', 4.70, 'tortilla.jpg', 1),\n new Product('Chili', 'Feurig-scharfes Chili mit Hackfleisch, Bohnen und frischem Koriander', 5.50, 'chili.jpg', 1)\n ]\n}", "function crearListadoProductos(dataProductos) {\n //Limpiamos el div catalogo para filtrar por etiquetas correctamente\n $(\"#divProductosCatalogo\").html(\"\");\n //Vaciamos la constante productos\n productos.splice(0, productos.length);\n if (dataProductos && dataProductos.data.length > 0) {\n for (let i = 0; i < dataProductos.data.length; i++) {\n let unProducto = dataProductos.data[i];\n let prodX = new Producto(unProducto._id, unProducto.codigo, unProducto.nombre, unProducto.precio, unProducto.urlImagen, unProducto.estado, unProducto.etiquetas);\n productos.push(prodX);\n let unaImagenUrl = `http://ec2-54-210-28-85.compute-1.amazonaws.com:3000/assets/imgs/${unProducto.urlImagen}.jpg`;\n let unaCard = `<ons-card modifier=\"material\">\n <div class=\"title\" style=\"text-align: center\">${unProducto.nombre}</div>\n <div> \n <ons-list>\n <ons-list-item tappable>\n <ons-list-item><img src=${unaImagenUrl} alt=\"Imagen no disponible\" style=\"width: 60%; display:block; margin:auto\"></ons-list-item>\n <ons-list-item><strong>Precio:&nbsp;</strong> $${unProducto.precio}</ons-list-item> \n <ons-list-item><strong>Código:&nbsp;</strong> ${unProducto.codigo}</ons-list-item>\n <ons-list-item><strong>Etiquetas:&nbsp;</strong> ${unProducto.etiquetas}</ons-list-item>\n <ons-list-item><strong>Estado:&nbsp;</strong> ${unProducto.estado}</ons-list-item>\n </ons-list-item>\n </ons-list>\n <p style=\"text-align:center\">\n <ons-button modifier=\"material\" onclick=\"navegar('detalleProducto', false, '${unProducto._id}')\">Ver producto</ons-button>\n <ons-button class=\"filaLista\" myAttr=\"${unProducto._id}\" modifier=\"material\"><i class=\"fas fa-heart\"></i></ons-button> </div>\n </p>\n </ons-card>`;\n $(\"#divProductosCatalogo\").append(unaCard);\n }\n $(\".filaLista\").click(btnProductoFavoritoHandler);\n }\n}", "insertProduct() {\n this.wrapper.querySelector('.image').src = this.product.imageUrl\n this.wrapper.querySelector('.name').innerText = this.product.name\n this.wrapper.querySelector('.price').innerText = Math.ceil((this.product.price )/100) + '€'\n this.wrapper.querySelector('.description').innerText = this.product.description\n this.product.colors.forEach(element => {\n let option = document.createElement('option')\n option.innerText = element\n document.getElementById('itemPersonnalisationId').appendChild(option)\n })\n this.bindAddToCart()\n }", "function setupProductList() {\n if(document.getElementById(\"productList\")) {\n for (productSku of Object.keys(products)) {\n\t // products[productSku].name\t\n\t $(\"#productList\").append(\n\t $(\"<a>\").attr(\"href\",\"product.html?sku=\" + productSku).append(\t \n $(\"<div>\").addClass(\"productItem\").append(\n\t $(\"<h2>\").addClass(\"productTitle\").text(products[productSku].name)\n\t ).append(\n\t\t $(\"<span>\").addClass(\"productPrice\").text(products[productSku].price)\n\t ).append(\n $(\"<img>\").addClass(\"productImage\").attr(\"src\", \"img/\" + products[productSku].img)\n\t )\n\t )\n\t );\n }\n }\n}", "function initPage() {\n $.get('product-template.html', function(data){\n template = data;\n //now go get the products\n page.getproducts('data.json', function() {\n page.updateproducthtml();\n page.updatedom()\n });\n });\n}", "fillProducts(products) {\n const templateDiv = document.querySelector('#product-template');\n\n for (let product of products) {\n let clone = templateDiv.cloneNode(true);\n\n let productDiv = this.fillProduct(clone, product);\n\n this.content.appendChild(productDiv);\n }\n\n this.addLinkEvents();\n }", "function instanciarProductos() {\n const producto_uno = new Producto(\"Zapatillas\", 9000, \"img/zapatillas.png\", 450, \"Calzado\");\n const producto_dos = new Producto(\"Remeras\", 1500, \"img/remeras.png\", 650, \"Indumentaria\");\n const producto_tres = new Producto(\"Gorras\", 500, \"img/gorras.png\", 800, \"Accesorio\");\n const producto_cuatro = new Producto(\"Lentes\", 2000, \"img/lentes.png\", 500, \"Accesorio\");\n const producto_cinco = new Producto(\"Camperas\", 15000, \"img/camperas.png\", 400, \"Indumentaria\");\n const producto_seis = new Producto(\"Zapatos\", 8000, \"img/zapatos.png\", 350, \"Calzado\");\n const producto_siete = new Producto(\"Medias\", 600, \"img/medias.png\", 900, \"Indumentaria\");\n const producto_ocho = new Producto(\"Cintos\", 900, \"img/cintos.png\", 250, \"Accesorio\");\n \n const baseDeDatos = [producto_uno, producto_dos, producto_tres, producto_cuatro, producto_cinco, producto_seis, producto_siete, producto_ocho];\n \n return baseDeDatos;\n}", "function _plantillaElementProduct(p_producto){\n\n let l_templateProduct = \n `\n <!-- producto -->\n <div class=\"producto col-8 col-sm-6 col-md-4 col-lg-3 d-flex flex-column align-items-center m-auto p-2\">\n <!-- DIV que define el elemento que se mostrara encima del producto cuando se posicione el raton por encima -->\n <!-- producto-hover -->\n <div class=\"producto-hover cursor-pointer d-flex flex-column justify-content-center align-items-center text-white p-2\">\n \n <!-- ANYADIR a CARRITO -->\n <!-- id=\"${p_producto.codigo}\" -->\n <div class=\"d-flex flex-column justify-content-center align-items-center\">\n <i datos=\"${c_DATOS_ANYADIRACARRITO}\" codigo_producto=\"${p_producto.codigo}\" class=\"fas fa-cart-plus font-size-50 text-danger\"></i>\n <p datos=\"${c_DATOS_ANYADIRACARRITO}\" codigo_producto=\"${p_producto.codigo}\" class=\"font-size-18 border-letter-danger text-center\">Añadir a carrito</p>\n </div>\n\n <!-- VER DETALLE PRODUCTO -->\n <div id=\"ver-detalle-prod-hover\" class=\"d-flex flex-column justify-content-center align-items-center\">\n <i datos=\"${c_DATOS_VERDETALLEPRODUCTO}\" codigo_producto=\"${p_producto.codigo}\" class=\"fas fa-info-circle font-size-50 text-warning\"></i>\n <p datos=\"${c_DATOS_VERDETALLEPRODUCTO}\" codigo_producto=\"${p_producto.codigo}\" class=\"font-size-18 border-letter-warning text-center\">Ver detalle</p>\n </div>\n\n </div><!-- .producto-hover -->\n\n <!-- Caja de imagen -->\n <div class=\"caja-imagen d-flex justify-content-center align-items-center h-20rem w-100\">\n <img src=\"${p_producto.imagenURL}\" alt=\"${p_producto.nombre}\" title=\"${p_producto.nombre}\" class=\"img-fit h-100 w-100 roundedRem-20\">\n </div>\n\n <!-- Caja de informacion del producto -->\n <div class=\"caja-descripcion d-flex flex-column align-items-center w-100\">\n <h5 class=\"titulo-producto m-0\">${p_producto.nombre}</h5>\n <p class=\"precio-producto text-wrap text-center w-100 m-0\">${p_producto.precio.toFixed(2)} €</p>\n </div>\n </div><!-- .producto -->\n `;\n return l_templateProduct;\n}", "function setProductFromUrl() {\n\n // URL REGEX\n let path = document.location.pathname;\n var regJardin = new RegExp(URL_PREFIXE_JARDIN + \"(\\\\w+)(-(\\\\d{1,2}))?\");\n var regAvivre = new RegExp(URL_PREFIXE_AVIVRE + \"(\\\\w+)(-(\\\\d{1,2}))?\");\n var regEnfant = new RegExp(URL_PREFIXE_ENFANTS + \"(\\\\w+)(-(\\\\d{1,2}))?\");\n var regAnimaux = new RegExp(URL_PREFIXE_ANIMAUX + \"(\\\\w+)(-(\\\\d{1,2}))?\");\n\n // A - Kobe corner case\n $('.display-vivre').hide();\n if (path.includes('kobe')) {\n product.name = 'kobe';\n }\n // B - jardin\n if (regJardin.test(path)) {\n product.name = path.match(regJardin)[1];\n product.type = \"jardin\";\n\n if (typeof path.match(regJardin)[3] != 'undefined') {\n product.surface = path.match(regJardin)[3];\n product.price = window[\"jardin_\" + product.name + '_' + product.surface];\n } else {\n product.surface = '';\n product.price = {};\n }\n }\n // C A vivre\n if (regAvivre.test(path) && !path.includes('jardin')) {\n product.name = path.match(regAvivre)[1];\n product.type = \"avivre\";\n\n\n }\n // D - Else\n if (regEnfant.test(path) || regAnimaux.test(path) || !path.includes('kobe') && !path.includes('jardin') && !path.includes('york') && !path.includes('grison') && !path.includes('ardenne')) {\n product.name = regEnfant.test(path) ? path.match(regEnfant)[1] : path.match(regAnimaux)[1];\n if (product.name == 'parme') {\n product.prix = { 'fixe': 6390 };\n product.type = 'enfant';\n } else if (product.name == 'paris') {\n product.prix = { 'fixe': 6900 };\n product.type = 'enfant';\n }\n }\n}", "function affichageProduits(resultat){\n //1-Sélection élément du DOM\n const positionElement = document.querySelector(\".Vcams-container\");\n\n //2-Boucle for pour afficher tous les objets dans la page web\n for (i = 0 ; i < resultat.length ; i++){\n\n //3-mettre les données dans les variables\n resultat.forEach((element, i) => {\n nom[i] = element.name;\n price[i] = element.price;\n description[i] = element.description;\n _id[i] = element._id;\n imageUrl[i] = element.imageUrl;\n // lenses[i] = element.lenses;\n });\n //4-afficher tous les objets sur la page web\n // Ci-dessous on fait une récurssivité de la variable à chaque tour de boucle pour afaire appaître les autre éléments\n structureProduits = structureProduits +`\n <a href=\"./PageProduit.html?id=${_id[i]}\" class=\"link\">\n <div class=\"card\">\n <img src=\"${imageUrl[i]}\" class=\"card-img-top lsimg\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">${nom[i]}<span>${price[i]/100}€</span></h5>\n <p class=\"card-text\">${description[i]}</p>\n </div>\n </div>\n </a>`;\n\n //5-injection html\n positionElement.innerHTML = structureProduits;\n }\n}", "function appendProducts(products) {\n let htmlTemplate = \"\";\n\n for (let product of products) {\n htmlTemplate += `\n <article>\n <div class=\"card\">\n <div class=\"card-image waves-effect waves-block waves-light\">\n <img class=\"activator\" src=\"${product.acf.img}\">\n </div>\n <div class=\"card-content\">\n <span class=\"card-title activator grey-text text-darken-4\">${product.title.rendered}<i class=\"material-icons right\">more_vert</i></span>\n <p>${product.acf.indeholder}</p><p>${product.acf.kategori}</p>\n </div>\n <div class=\"card-reveal\">\n <span class=\"card-title grey-text text-darken-4\">${product.title.rendered}<i class=\"material-icons right\">close</i></span>\n <p>${product.acf.tags}</p><a href=\"${product.acf.kob}\">KØB</a>\n <div> <h4>Anvendelse</h4>\n <p>${product.acf.beskrivelse}</p></div>\n <div> <h4>Ingrediensliste</h4>\n <p>${product.acf.ingrediensliste}</p></div>\n <p>${product.acf.andet}</p>\n </div>\n </div>\n </article>\n `;\n }\n\n document.querySelector('#products-container').innerHTML = htmlTemplate;\n}", "static PopulateWithProducts() {\n let bikeInstanceKeys = Object.keys(Bike.Instances);\n\n for (let i = 0; i < bikeInstanceKeys.length; i++) {\n const bike = Bike.Instances[bikeInstanceKeys[i]];\n\n let productClone = document.importNode(Bikes.Template.content, true);\n\n let productData = {\n title: productClone.querySelector('.card-title'),\n thumbnail: productClone.querySelector('img'),\n price: productClone.querySelector('.bike-price'),\n colorsParent: productClone.querySelector('.bike-colors'),\n seeSpecsBtn: productClone.querySelector('button')\n }\n\n productData.title.innerHTML = bike.Name;\n productData.thumbnail.setAttribute('src', bike.ThumbnailUrl);\n productData.price.innerHTML = '$'.concat(bike.Price.toString());\n \n // Create bike colors\n this._CreateBikeColors(bike.Colors, productData.colorsParent);\n\n productData.seeSpecsBtn.addEventListener('click', function(){\n Bikes.RefreshSpecsModal(bike);\n });\n\n document.querySelector('.products-list').appendChild(productClone);\n }\n }", "function createProductPage(type, products){\n\n\t// get the body element\n\tvar body = document.getElementById(\"body\");\n\n\t// create a container for the main guitar jumbotron\n\tvar jumbotron = generateProductPageHeaderJumbotron(type);\n\tbody.appendChild(jumbotron);\n\n\t// create a container for the products\n\tvar container = document.createElement(\"div\");\n\tcontainer.id = \"product-container\";\n\tcontainer.className = \"container border border-dark rounded-lg p-3 mb-3 bg-light\";\n\tbody.appendChild(container);\n\n\t// create a row for the products\n\tvar row = document.createElement(\"div\");\n\trow.className = \"row border border-dark rounded-lg m-3 p-3 bg-light\";\n\tcontainer.appendChild(row);\n\n\t// for each product generate rows of images\n\tif(type == \"guitar\"){\n\t\tfor (i in products){\n\t\t\tvar card = createGuitarCard(products[i]);\n\t\t\trow.appendChild(card);\n\t\t}\n\t}\n\telse if(type == \"amplifier\"){\n\t\tfor (i in products){\n\t\t\tvar card = createAmplifierCard(products[i]);\n\t\t\trow.appendChild(card);\n\t\t}\n\t}\n\telse if(type == \"strings\"){\n\t\tfor (i in products){\n\t\t\tvar card = createStringsCard(products[i]);\n\t\t\trow.appendChild(card);\n\t\t}\n\t}\n\n}", "function crearOtrosProductos() {\n const URLOTROSPRODUCTOS =\n \"https://script.google.com/macros/s/AKfycbxUPp4O8ao51WgG_jrpoK8i1ix52ekaZkUDSJEQjOImXd8lkXk/exec\";\n\n $.get(URLOTROSPRODUCTOS, (respuesta, estado) => {\n if (estado === \"success\") {\n let listado = respuesta;\n\n for (let producto of listado) {\n listaOtrosProductos.push(\n new OtrosProductos(\n producto.id,\n producto.tipoDeProducto,\n producto.marca,\n producto.modelo,\n producto.precio,\n producto.img\n )\n );\n }\n }\n\n // para que una vez termine de obtener los datos de la pagina se ejecute la function e imprima en pantalla\n renderizarListaOtrosProductos(listaOtrosProductos, \"Todos\");\n });\n\n return listaOtrosProductos;\n}", "function createProductElements( ) {\n const newItems = store.map(function (product, index) {\n const thumbnail = `img/products/${product.url}`;\n const price = ` $${product.price}.00/<span class=\"currency\">CAD</span>`;\n const productTemplate = `\n <aside class=\"print\">\n <header class=\"print-header\">\n <h3 class=\"print-title\"> ${product.title}</h3>\n <p class=\"print-price\"> ${price}</p>\n </header> \n <img class=\"print-image\" src=\"${thumbnail}\" alt=\"${product.title}\" /> \n <p class=\"print-details\">${product.description} </p> \n <footer class=\"print-footer\"> \n <button class=\"add-to-cart\" data-key=\"${product.id}\"> add to cart </button>\n </footer>\n </aside> \n `;\n /* \n Take the template string and convert it to an element node.\n */\n const item = document\n .createRange()\n .createContextualFragment(productTemplate)\n .querySelector(\"aside\");\n\n /* \n Add a click event to the add to cart button for each item in the store\n */\n item.querySelector('.add-to-cart').addEventListener('click', onAddItemToCart)\n\n \n return item;\n });\n\n return newItems\n }", "function leerDatosProductos(producto){\n const infoProducto = {\n img: producto.querySelector('.imagen').src,\n titulo: producto.querySelector('#title-product').textContent,\n cantidad: producto.querySelector('#cantidad').value,\n precio: producto.querySelector('#precio').textContent,\n id: producto.querySelector('#agregar-carrito').getAttribute('data-id')\n };\n agregarAlCarrito(infoProducto); \n}", "function valesHTML() {\n //limpiar el html\n limpiarHTML();\n\n valesCanjeados.forEach((vale) => {\n const div = document.createElement(\"p\");\n div.innerHTML = `\n <div class=\"div-img\">\n <div>\n <img src=\"${vale.imagen}\" width=\"200px\"; style=\"padding:5px; border-radius:20px;\" >\n \n </div>\n </div>\n `;\n\n //Agrega el html de vcanjeados en el div\n cVales.appendChild(div);\n });\n\n //agregando vales canjeados al storage\n sincronizarStorage();\n}", "function appendProducts(products) { \n document.querySelector(\"#products-container\").innerHTML = \"\"\n for (let product of products){\n document.querySelector(\"#products-container\").innerHTML += /*html*/\n `\n <article>\n <img src=\"${product.img}\">\n <h3>${product.model}</h3>\n Brand: ${product.brand}\n Price: ${product.price}\n </article>\n `\n }\n\n // to do\n}", "function carregarProdutos() {\n\n\t// variáveis usadas para armazenar a div e o conteúdo\n\tlet t1 = document.getElementById('lista-produtos');\n\tlet linha = '';\n\n\tif (listaProdutos.length > 0) { // se houver elementos na lista\n\t\tfor (let i = 0; i < listaProdutos.length; i++) {\n\t\t\tlet { codigo, nomeProduto, quantidade, unidade, codigoBarra, produtoAtivo } = listaProdutos[i];\n\t\t\t\n\t\t\tlinha += `<div class=\"box-produto\">\n\t\t\t\t\t\t\t\t\t<img class=\"img-produto\" src=\"imagens/product.png\" alt=\"Imagem do produto\" width=\"150px\">\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\t<span class=\"lista-nome\">${nomeProduto}</span>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\tCód.:\n\t\t\t\t\t\t\t\t\t\t<span class=\"lista-cod\">${codigo}</span>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\tQtd.:\n\t\t\t\t\t\t\t\t\t\t<span class=\"lista-qtd\">${quantidade}</span>\n\t\t\t\t\t\t\t\t\t\t<span class=\"lista-un\">${unidade}</span>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\tCód. Barras:\n\t\t\t\t\t\t\t\t\t\t<span class=\"lista-cod-barras\">${codigoBarra}</span>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\tAtivo:\n\t\t\t\t\t\t\t\t\t\t<span lista-ativo>${produtoAtivo}</span>\n\t\t\t\t\t\t\t\t\t</p>\n\n\t\t\t\t\t\t\t\t\t<form>\n\t\t\t\t\t\t\t\t\t\t<button class=\"bt-editar\" type=\"button\" onclick=\"editarProduto(${i});\">Editar</button>\n\t\t\t\t\t\t\t\t\t\t<button class=\"bt-excluir\" type=\"button\" onclick=\"excluirProduto(${i});\">Excluir</button>\n\t\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t\t</div>`;\n\t\t}\n\t} else { // se a lista for vazia\n\t\tlinha += `<p>Não existem produtos cadastrados.</p>`;\n\t}\n\n\t// insere o conteúdo na div\n\tt1.innerHTML = linha;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update music option text value
function updateMusicOption() { var currText = 'Música'; var currValue = (scene.musicOn ? 'ON': 'OFF'); $('#optMusic').attr('value', currText + ' (' + currValue + ')'); }
[ "updateControlText_() {\n const soundOff = this.player_.muted() || this.player_.volume() === 0;\n const text = soundOff ? 'Unmute' : 'Mute';\n if (this.controlText() !== text) {\n this.controlText(text);\n }\n }", "updateControlText_() {\n const soundOff = this.player_.muted() || this.player_.volume() === 0;\n const text = soundOff ? 'Unmute' : 'Mute';\n\n if (this.controlText() !== text) {\n this.controlText(text);\n }\n }", "function updateSpeedOption() {\n var currText = 'Velocidad';\n var currValue = gameSpeed;\n $('#optSpeed').attr('value', currText + ' (' + currValue + ')');\n}", "updateOption() {\n this.selectedOption.setText(this.options[this.selectedId]);\n this.selectedText = this.options[this.selectedId];\n }", "function SetExploreToPlaylist(){\n document.getElementById(\"explore-select\").textContent=\"Playlist\";\n}", "function setMusicVolume() {\r\n musicElement[0].volume = $(this)[0].valueAsNumber / 100; \r\n currentMusicVolElement.text($(this)[0].valueAsNumber);\r\n }", "function changeMusic2() {\r\n \r\n var selected = document.getElementById('dropdown').value;\r\n \r\n if(selected == 'stop' && musicCount > 0)\r\n {\r\n \r\n music.stop();\r\n }\r\n \r\n else if(musicCount > 0)\r\n {\r\n music.stop();\r\n \r\n music = game.sound.add(selected, {\r\n mute: false,\r\n volume: 1,\r\n rate: 1,\r\n detune: 0,\r\n seek: 0,\r\n loop: true,\r\n delay: 0\r\n });\r\n \r\n music.play(config);\r\n \r\n }\r\n \r\n else if(musicCount == 0 && selected != 'stop')\r\n {\r\n music = game.sound.add(selected, {\r\n mute: false,\r\n volume: 1,\r\n rate: 1,\r\n detune: 0,\r\n seek: 0,\r\n loop: true,\r\n delay: 0\r\n });\r\n \r\n music.play(config);\r\n musicCount++;\r\n\r\n }\r\n \r\n document.getElementById('dropdown1').innerHTML='';\r\n\r\n}", "function SetExploreToArtist(){\n document.getElementById(\"explore-select\").textContent=\"Artist\";\n}", "function setMusicVolume() {\r\n musicElement[0].volume = $(this)[0].valueAsNumber / 100;\r\n currentMusicVolElement.text($(this)[0].valueAsNumber);\r\n }", "function updateMusicUI(artist_name,song_title) {\n\n\tvar playlist_name = \"\";\n\tswitch(current_mood) {\n\tcase mood.HAPPY:\n\t\tplaylist_name = \"Happy Playlist\"\n\n\t\tbreak;\n\tcase mood.SAD:\n\t\tplaylist_name = \"Sad Playlist\"\n\t\tbreak;\n\tcase mood.ANGRY:\n\t\tplaylist_name = \"Angry Playlist\"\n\t\tbreak;\n\tdefault: // default is happy\n\t\tplaylist_name = \"Happy Playlist\"\t\t\t\n\t}\n\t\n\t$(\"#div_artistname\").text(artist_name);\n\t$(\"#div_songtitle\").text(song_title);\n\t$(\"#div_playlist\").text(playlist_name);\n\t\n}", "function updateStatsOption() {\n var currText = 'Información';\n var currValue = (showStats ? 'ON': 'OFF');\n $('#optStats').attr('value', currText + ' (' + currValue + ')');\n}", "function updateEffectsOption() {\n var currText = 'Efectos';\n var currValue = (scene.effectsOn() ? 'ON': 'OFF');\n $('#optEffects').attr('value', currText + ' (' + currValue + ')');\n}", "function updateVideoDesc(){\r\n \r\n // Update Video info\r\n title_field.value = current_song.title;\r\n artist_field.value = current_song.artist;\r\n \r\n}", "updateTrueVolumeText(newValue){\n document.getElementById(\"trueVolumeText\").innerHTML = String(newValue);\n }", "function interface_update_controls_music_volume() {\n\tconst elements_controls_media_music = document.forms[\"controls_media_music\"].elements;\n\tplayer.music.volume = Number(elements_controls_media_music[\"controls_media_music_volume\"].value);\n\tplayer.music.volume = Math.max(Math.min(player.music.volume, 1), 0);\n\n\tinterface.media_music_controls_volume_label.innerHTML = percent(player.music.volume);\n\tif(document.body.contains(player.music.element))\n\t\tplayer.music.element.volume = player.music.volume;\n}", "setMusicState(option) {\n let audioEl = document.getElementById('music');\n\n if (this._soundOn) {\n this._musicOn = option || this._musicOn;\n this._musicOn === \"on\" ? audioEl.play() : audioEl.pause();\n Game.gameSettings.musicOn = this._musicOn;\n }\n }", "function setVoice() {\n msg.voice = voices.find(voice => voice.name === this.value); //loops over every single one of the voices in the array and it's gonna find the one where its name is the same as the option that's currently selected\n toggle();\n }", "function setInitialMusicVol() {\r\n musicElement[0].volume = 0.5;\r\n currentMusicVolElement.text(\"50\");\r\n }", "function setInitialMusicVol() {\r\n musicElement[0].volume = 0.5;\r\n currentMusicVolElement.text(\"50\");\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a computer ID
function createComputerID () { return "comp"+(+Date.now()); }
[ "function createID(){\n console.log(\"Creating ID for device...\");\n\n var deviceID = uuidV4();\n console.log(\"ID \" + deviceID + \" created.\");\n\n return deviceID;\n}", "function createNewId() {\n onIdSubmit(uuidV4());\n }", "function _createId() {\n return Date.now().toString(32);\n}", "function makeComputer() {\n\tvar computer1= {\n\t\tID: '0033-AA200',\n\t\tSystem: 'Windows10',\n\t\tprocessor: 'Intel Core I5',\n\t\tSystemType: '64 bits'\n\t}\n\tvar computer2= {\n\t\tID: '0896-AV256',\n\t\tSystem: 'Windows10',\n\t\tprocessor: 'Intel Core I7',\n\t\tSystemType: '64 bits'\n\t}\n\tvar computers = [ computer1, computer2 ];\n\n\treturn computers ;\n}", "function createTripId() {\n const tripId = 'trip-' + tripIdCounter;\n tripIdCounter += 1;\n return tripId;\n}", "function makeComputer(computer) {\n\t// TODO: Your code here\n}", "function createId(){\n return Math.round(Math.random()*1000000);\n }", "function createGUID(){\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +\n s4() + '-' + s4() + s4() + s4();\n}", "generateId()\n {\n var date = new Date();\n var id = [date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),date.getMilliseconds()].join(\"\");\n \n function s4(key)\n {\n return Math.floor((((key) ? key : 1) + Math.random()) * 0x10000).toString(16).substring(1);\n }\n date = null;\n return s4(id) + s4(process.pid);\n }", "function makeId() {\n return \"_\" + (\"\" + Math.random()).slice(2, 10);\n }", "generateId() {\n return cuid();\n }", "function createGameID () {\n return \"game\"+(+Date.now());\n}", "function createNewID(res, req) { \r\n var data;\r\n var confirmToken = req.body.userID;\r\n console.log(\"create:\" + libCrypt.cipher(req.body.userID, req.apikey));\r\n \r\n data = {\r\n uuid: req.uuid,\r\n userid: libCrypt.cipher(req.body.userID, req.apikey),\r\n fname: libCrypt.cipher(req.body.fname, req.apikey),\r\n lname: libCrypt.cipher(req.body.lname, req.apikey),\r\n mnames: libCrypt.cipher(req.body.mnames, req.apikey),\r\n gender: libCrypt.cipher(req.body.gender, req.apikey),\r\n photo: libCrypt.cipher(req.body.photo, req.apikey),\r\n address: libCrypt.cipher(req.body.address, req.apikey),\r\n idcard: libCrypt.cipher(req.body.idcard, req.apikey),\r\n driverlic: libCrypt.cipher(req.body.driverlic, req.apikey),\r\n passport: libCrypt.cipher(req.body.passport, req.apikey)\r\n };\r\n \r\n ID.create(data,\r\n function(id) { \r\n return trans.resp('CreateIDSuccessful', res, { uuid: id.uuid });\r\n },\r\n function(err) {\r\n return trans.resp('ExecutionError', res, err);\r\n }\r\n );\r\n }", "function makeID() {\n function trash() {\n return Math.floor((1 + Math.random()) * 0x10000);\n }\n return `${trash()}${Date.now()}${trash()}`;\n}", "function createID() {\n return Math.floor(Math.random() * 10000000000);\n}", "function createId(){\n return Math.floor(Math.random() * 10000)\n}", "function generateID() { \n var uniqueID;\n var date = new Date();\n var components = [\n date.getYear(),\n date.getMonth(),\n date.getDate(),\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n date.getMilliseconds()\n ];\n uniqueID = parseInt(components.join(\"\"));\n uniqueID = (uniqueID * ((1 + Math.random()) * 0x10000)).toString(16); \n return uniqueID;\n }", "generateCid() {\n // random number + last 7 numbers of current time\n return 'cid_' + Math.random().toString(36).substr(2) + '_' + new Date().getTime().toString().substr(-7);\n }", "function createID() {\r\n return s_lastID++;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The all important drawing function. Responsible for clearing out old tooltips, generating color interpolators (gray to red + values) (blue to gray for values). Actual lines are created by iterating over the features of the geojson slice specified by the brain view and the slider. paths are created for the visible and invisible canvases, and yellow strokes are provided for areas that are specified in the rois field on the canvas class. Fill values are linearly interpolated to the color scheme selected if the value for the specific isn't NaN.
drawCanvas() { //TODO find better version of how to structure so that the margin can be programmatically set this.ctx.clearRect(0, 0, this.can.width, this.can.height) this.invisictx.clearRect(0, 0, this.can.width, this.can.height) // remove previous tooltips while (this.infoHolder.firstChild) { this.infoHolder.removeChild(this.infoHolder.firstChild) } let red = { r: 227, g: 74, b: 51 } let gray = { r: 254, g: 232, b: 200 } let blue = { r: 67, g: 162, b: 202 } // iterate over the boundary data for (let region of this.paneOb.sliceData.features) { // this is the object that has features, and properties for (let coords of region.geometry.coordinates) { this.ctx.lineWidth = 2 this.ctx.beginPath() this.invisictx.beginPath() // create simplified variable with points and region name let linedata = { points: coords, region: region.properties.regionName } // begin actual drawing to the canvas let first = linedata.points[0] let x = this.xinterp.calc(first[0]) let y = this.yinterp.calc(first[1]) this.ctx.moveTo(x, y) this.invisictx.moveTo(x, y) for (let i = 1; i < linedata.points.length; i++) { let pt = linedata.points[i] let x = this.xinterp.calc(pt[0]) let y = this.yinterp.calc(pt[1]) this.ctx.lineTo(x, y) this.invisictx.lineTo(x, y) } this.ctx.closePath() this.invisictx.closePath() // check if its a roilisted if (this.paneOb.rois[linedata.region]) { if (this.paneOb.rois[linedata.region]) { this.ctx.strokeStyle = "black" this.ctx.lineWidth = 5 this.ctx.stroke() } // add tooltips that are visible let regId = linedata.region.replace(/[-_]/g, "") // if we don't find the element must make the tooltip, make search specific to pane if (!this.paneOb.paneDiv.querySelector(`#tooltip${regId}`)) { this.tooltipMaker(linedata.region, this.paneOb.rois[linedata.region]) } } // default stroke gray, update if nec this.ctx.strokeStyle = "gray" this.ctx.stroke() // these aren't defined yet if (this.regNameToValueMap != undefined) { if (this.regNameToValueMap[linedata.region]) { let scanData = this.regNameToValueMap[linedata.region].value let lerpc if (scanData < 0) { // use the blue to gray instead of gray to red let t = this.colInterpolator.calc(scanData) lerpc = LerpCol( t) } else { let t = this.colInterpolator.calc(scanData) lerpc = LerpCol( t) } this.ctx.fillStyle = lerpc this.ctx.fill() // query the region to color map } } this.invisictx.fillStyle = `rgb(${this.regToColMap[linedata.region][0]},${this.regToColMap[linedata.region][1]},${this.regToColMap[linedata.region][2]})` this.invisictx.fill() } } if (this.scanDatamin != undefined && this.scanDatamax != undefined) { // setup a legend in the corner let gradient = this.ctx.createLinearGradient(0, 0, 0, this.can.height / 4) // color stop for rgb if (this.scanDatamin < 0 && this.scanDatamax > 0) { gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`) gradient.addColorStop(.5, `rgb(${gray.r},${gray.g},${gray.b})`) gradient.addColorStop(0, `rgb(${red.r},${red.g},${red.b})`) } else if (this.scanDatamax > 0) { gradient.addColorStop(1.0, `rgb(255,255,178)`) gradient.addColorStop(0.75, `rgb(254,204,92)`) gradient.addColorStop(0.5, `rgb(253,141,60)`) gradient.addColorStop(0.25, `rgb(240,59,32)`) gradient.addColorStop(.0, `rgb(189,0,38)`) } else { // this is the case of blue only console.log(this.scanDatamax, "max", this.scanDatamin, "min") gradient.addColorStop(0, `rgb(${gray.r},${gray.g},${gray.b})`) gradient.addColorStop(1, `rgb(${blue.r},${blue.g},${blue.b})`) } let gradientWidth = 10 this.ctx.fillStyle = gradient let startx = this.can.width - this.margin - gradientWidth let endx = this.can.width - this.margin * 2 this.ctx.fillRect(startx, 0, endx, this.can.height / 4) // add numeric values to the gradient // measure the text so it sits right next to the gradient this.ctx.font = "15px Arial" let minmeasure = this.ctx.measureText(this.scanDatamin).width let maxmeasure = this.ctx.measureText(this.scanDatamax).width this.ctx.fillStyle = "black" // the -5 is a spacer for the text next to the gradient bar this.ctx.fillText(this.scanDatamin, startx - minmeasure - 5, this.can.height / 4) this.ctx.fillText(this.scanDatamax, startx - maxmeasure - 5, 15) } }
[ "draw() {\n // Draw all the previous paths saved to the history array\n if(this.drawHistory) {\n this.drawPreviousEdges();\n }\n\n // Draw bounds\n if(this.showBounds && this.bounds != undefined && this.bounds instanceof Bounds) {\n this.drawBounds();\n }\n\n // Set shape fill \n if(this.fillMode && this.isClosed) {\n this.p5.fill(this.currentFillColor.h, this.currentFillColor.s, this.currentFillColor.b, this.currentFillColor.a);\n } else {\n this.p5.noFill();\n }\n\n // Set stroke color\n this.p5.stroke(this.currentStrokeColor.h, this.currentStrokeColor.s, this.currentStrokeColor.b, this.currentStrokeColor.a);\n\n // Draw current edges\n this.drawCurrentEdges();\n\n // Draw all nodes\n if(this.drawNodes) {\n this.drawCurrentNodes();\n }\n }", "function finalDraw() {\n\t Shapes.drawAll(gd);\n\t Images.draw(gd);\n\t Plotly.Annotations.drawAll(gd);\n\t Legend.draw(gd);\n\t RangeSlider.draw(gd);\n\t RangeSelector.draw(gd);\n\t }", "function draw() {\n updateFeatures();\n drawMap();\n drawArcs();\n drawPlots();\n}", "draw() {\n if (!this.traceMode) {\n this.drawBackground();\n }\n\n for (let path of this.paths) {\n path.draw();\n }\n }", "function redraw() {\n\t// TODO:\n\t// - Handle single point and double point strokes\n\n\t// 3 points needed for a look-ahead bezier\n\tvar len = curFilteredStroke.length;\n\tif(len >= 3) {\n\t\tbezierDrawer.drawControlPoints(\n\t\t\tcurFilteredStroke[len - 3],\n\t\t\tcurFilteredStroke[len - 2],\n\t\t\tcurFilteredStroke[len - 1]\n\t\t);\n\t}\n}", "customDraw() {\n var subcircuitScope = scopeList[this.id];\n\n var ctx = simulationArea.context;\n\n ctx.lineWidth = globalScope.scale * 3;\n ctx.strokeStyle = colors[\"stroke\"]; // (\"rgba(0,0,0,1)\");\n ctx.fillStyle = colors[\"fill\"];\n var xx = this.x;\n var yy = this.y;\n\n ctx.strokeStyle = colors['stroke'];\n ctx.fillStyle = colors['fill'];\n ctx.lineWidth = correctWidth(3);\n ctx.beginPath();\n rect2(ctx, -this.leftDimensionX, -this.upDimensionY, this.leftDimensionX + this.rightDimensionX, this.upDimensionY + this.downDimensionY, this.x, this.y, [this.direction, 'RIGHT'][+this.directionFixed]);\n if(!this.elementHover) {\n if ((this.hover && !simulationArea.shiftDown) || simulationArea.lastSelected === this || simulationArea.multipleObjectSelections.contains(this))\n ctx.fillStyle = colors[\"hover_select\"];\n }\n ctx.fill();\n ctx.stroke();\n\n ctx.beginPath();\n\n ctx.textAlign = \"center\";\n ctx.fillStyle = \"black\";\n if (this.version == \"1.0\") {\n fillText(\n ctx,\n subcircuitScope.name,\n xx,\n yy - subcircuitScope.layout.height / 2 + 13,\n 11\n );\n } else if (this.version == \"2.0\") {\n if (subcircuitScope.layout.titleEnabled) {\n fillText(\n ctx,\n subcircuitScope.name,\n subcircuitScope.layout.title_x + xx,\n yy + subcircuitScope.layout.title_y,\n 11\n );\n }\n } else {\n console.log(\"Unknown Version: \", this.version);\n }\n\n for (var i = 0; i < subcircuitScope.Input.length; i++) {\n if (!subcircuitScope.Input[i].label) continue;\n var info = this.determine_label(\n this.inputNodes[i].x,\n this.inputNodes[i].y\n );\n ctx.textAlign = info[0];\n fillText(\n ctx,\n subcircuitScope.Input[i].label,\n this.inputNodes[i].x + info[1] + xx,\n yy + this.inputNodes[i].y + info[2],\n 12\n );\n }\n\n for (var i = 0; i < subcircuitScope.Output.length; i++) {\n if (!subcircuitScope.Output[i].label) continue;\n var info = this.determine_label(\n this.outputNodes[i].x,\n this.outputNodes[i].y\n );\n ctx.textAlign = info[0];\n fillText(\n ctx,\n subcircuitScope.Output[i].label,\n this.outputNodes[i].x + info[1] + xx,\n yy + this.outputNodes[i].y + info[2],\n 12\n );\n }\n ctx.fill();\n for (let i = 0; i < this.outputNodes.length; i++) {\n this.outputNodes[i].draw();\n }\n for (let i = 0; i < this.inputNodes.length; i++) {\n this.inputNodes[i].draw();\n }\n\n // draw subcircuitElements\n for(let el of circuitElementList){\n if(this.localScope[el].length === 0) continue;\n if(!this.localScope[el][0].canShowInSubcircuit) continue;\n for(let i = 0; i < this.localScope[el].length; i++){\n if (this.localScope[el][i].subcircuitMetadata.showInSubcircuit) {\n this.localScope[el][i].drawLayoutMode(this.x, this.y);\n }\n }\n }\n }", "setupCanvas() {\n // mingle the two filtered datasets \n /** This is a helper attribute that will hold the values that have passed all available filters */\n this.fillData = []\n // if both data filters aren't specified use whole initial range\n if (this.paneOb.filteredFillColData == undefined &&\n this.paneOb.filteredAltColData == undefined) {\n this.fillData = this.paneOb.initialColData\n } else if (this.paneOb.filteredFillColData == undefined && this.paneOb.filteredAltColData != undefined) {\n this.fillData = this.paneOb.filteredAltColData\n } else if (this.paneOb.filteredFillColData != undefined && this.paneOb.filteredAltColData == undefined) {\n this.fillData = this.paneOb.filteredFillColData\n } else {\n // if only the activity is specified\n // if both filters are around\n for (let i = 0; i < this.paneOb.initialColData.length; i++) {\n // if the two different filters have non NAN at that index add it to fill\n\n if (isNaN(this.paneOb.filteredAltColData[i]) || isNaN(this.paneOb.filteredFillColData[i])) {\n this.fillData.push(NaN)\n } else {\n this.fillData.push(this.paneOb.initialColData[i])\n\n }\n\n }\n }\n // will update the map used in the draw to determine the color of a region\n if (this.paneOb.csvData) {\n this.makeRegDataMap()\n }\n // initialize the color setting for the invisican\n let cc = color_collection(this.paneOb.sliceData.features.length)\n /** This is the map that has red,green,blue strings as keys to look up region names. an example pair would be \"15,22,180\":\"PL_Op_L\" */\n this.colToRegMap = {}\n /** This is the inverse of the colToRegMap */\n this.regToColMap = {}\n this.paneOb.sliceData.features.map((f, i) => {\n // this is for the fill on the invisible canvas\n this.regToColMap[f.properties.regionName] = cc.array[i]\n this.colToRegMap[JSON.stringify(cc.array[i])] = f.properties.regionName\n })\n // this will happen at the beginning before column selection\n if (this.fillData != undefined) {\n this.calcValueColMinMax()\n }\n // create the region data to screen space interpolators\n let xinterp = interpolator()\n let yinterp = interpolator()\n // use correct ratio\n if (this.canvasRatio > 1) {\n xinterp.setup(this.regionSizes[0], 0 + this.margin, this.regionSizes[2], this.can.width / this.canvasRatio - this.margin)\n yinterp.setup(this.regionSizes[1], (this.can.height - this.margin), this.regionSizes[3], this.margin)// extra 10is the margin split intwo\n\n } else {\n\n xinterp.setup(this.regionSizes[0], 0 + this.margin, this.regionSizes[2], this.can.width - this.margin)\n yinterp.setup(this.regionSizes[1], this.can.height * this.canvasRatio - this.margin, this.regionSizes[3], this.margin)// extra 10is the margin split intwo\n }\n /** This is the interpolator for converting region coordinate y values to the y axis of the canvas. Don't forget that 0 is the top of the canvas which is why in the setup code the full height minus the margin is mapped to the min value of the region size */\n this.yinterp = yinterp\n /** This is the interpolator for converting the x coordinates of a region's boundary to the x dimension of the canvas. */\n this.xinterp = xinterp\n }", "draw() {\n console.log(\"Drawing visualization...\");\n this.renderer.center(this.renderer.path.bounds(this.data.clusters.geo));\n this.drawClusters();\n // this.drawCompass();\n this.drawHover();\n // this.drawBorders();\n this.drawScale();\n }", "drawDebug() {\n if (!this.debugCanvas) return;\n let ctx = this.debugCanvas.getContext('2d');\n ctx.clearRect(0, 0, this.debugCanvas.width, this.debugCanvas.height);\n \n //bound\n let bound = this.bounds;\n ctx.strokeStyle = '#FF0000';\n if (bound) {\n \n ctx.beginPath();\n ctx.rect(bound.left, \n bound.top, \n bound.right - bound.left, \n bound.bottom - bound.top);\n ctx.stroke();\n }\n //bounds\n ctx.beginPath();\n ctx.rect(this.bounds.left,\n this.bounds.top,\n this.bounds.right - this.bounds.left,\n this.bounds.bottom - this.bounds.top);\n ctx.stroke();\n\n //springNodes\n ctx.strokeStyle = '#00FF00';\n for (let n = 0; n < this.springNodes.length; n++) {\n let node = this.springNodes[n];\n \n ctx.beginPath();\n ctx.arc(node.x, node.y,5,0,2*Math.PI);\n ctx.stroke();\n }\n\n //smoothNodes\n ctx.strokeStyle = '#00FFFF';\n for (let n = 0; n < this.smoothNodes.length; n++) {\n let node = this.smoothNodes[n];\n\n ctx.beginPath();\n ctx.arc(node.x, node.y,10,0,2*Math.PI);\n ctx.stroke();\n }\n }", "draw() {\n // Draw in the currently toggled Links\n this.links.forEach((link) => {\n if (\n (link.top && link.category === this.config.topLinkCategory) ||\n (!link.top && link.category === this.config.bottomLinkCategory)\n ) {\n link.show();\n }\n\n if (\n (link.top && this.config.showTopMainLabel) ||\n (!link.top && this.config.showBottomMainLabel)\n ) {\n link.showMainLabel();\n } else {\n link.hideMainLabel();\n }\n\n if (\n (link.top && this.config.showTopArgLabels) ||\n (!link.top && this.config.showBottomArgLabels)\n ) {\n link.showArgLabels();\n } else {\n link.hideArgLabels();\n }\n });\n\n // Now that Links are visible, make sure that all Rows have enough space\n this.rowManager.resizeAll();\n\n // And change the Row resize cursor if compact mode is on\n this.rowManager.rows.forEach((row) => {\n this.config.compactRows\n ? row.draggable.addClass(\"row-drag-compact\")\n : row.draggable.removeClass(\"row-drag-compact\");\n });\n\n // Change token colours based on the current taxonomy, if loaded\n this.taxonomyManager.colour(this.words);\n }", "function Draw4(){\n\n\t/*First disable click event on clicker button*/\n\tstopClicker();\n\t/*Show and run the progressBar*/\n\trunProgressBar(time=700*2);\t\n\t\n\t/*SOMA - South Park intro text*/\n\tchangeTopText(newText = \"First, let's only look at the GoBike riders that started from SOMA with a specific destination\",\n\t\tloc = 1/2, delayDisappear = 0, delayAppear = 1, finalText = true);\n\t\t\n\t/*Bottom text disappear*/\n\tchangeBottomText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\t\n\t\n /*Make the non Samsung & Nokia arcs less visible*/\n svg.selectAll(\"g.group\").select(\"path\")\n\t\t.transition().duration(1000)\n\t\t.style(\"opacity\", function(d) {\n\t\t\tif(d.index != 25 && d.index != 5) {return opacityValue;}\n\t\t});\t\t\n\t\n\t/*Make the other strokes less visible*/\n\td3.selectAll(\"g.group\").selectAll(\"line\")\n\t\t.transition().duration(700)\n\t\t.style(\"stroke\",function(d,i,j) {if (j == 5 || j == 25) {return \"#000\";} else {return \"#DBDBDB\";}});\n\t/*Same for the %'s*/\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".tickLabels\").style(\"opacity\",function(d,i,j) {if (j == 5 || j == 25) {return 1;} else {return opacityValue;}});\n\t/*And the Names of each Arc*/\t\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".titles\").style(\"opacity\", function(d) { if(d.index == 25 || d.index == 5) {return 1;} else {return opacityValue;}});\n\n\t/*Show only the SOMA-South Park chord*/\n\tchords.transition().duration(2000)\n\t\t.attr(\"opacity\", function(d, i) { \n\t\t\tif(d.source.index == 5 && d.target.index == 25) \n\t\t\t\t{return opacityValueBase;}\n\t\t\telse {return 0;}\n\t\t});\n\t\n}", "drawAnnotations() {\n this.mainLayer.activate();\n this.mainLayer.removeChildren();\n this.currentSample.objects.forEach((feature) => {\n const pts = feature.polygon.map((pt) => {\n return new Paper.Point(pt.x, pt.y)\n });\n\n const path = new Paper.Path(pts);\n this.initPathProperties(path);\n feature.path = path;\n path.feature = feature;\n path.closed = true;\n\n this.setColor(path, this.activeSoc.colorForIndexAsHex(feature.classIndex));\n });\n this.updateGeometry(false);\n this.disableComposition();\n this.enableComposition();\n }", "function Draw11(){\n\n\t/*First disable click event on clicker button*/\n\tstopClicker();\n\t/*Show and run the progressBar*/\n\trunProgressBar(time=700*2);\t\n\t\n\tchangeTopText(newText = \"Here are all the chords for those wires that originate in Canada \"+ \n\t\t\t\t\t\t\t\"and move inside of Canada\",\n\t\tloc = 3/2, delayDisappear = 0, delayAppear = 1, finalText = true, xloc=-80, w=200);\n\t\t\n\t/*Remove the China arc*/\n\td3.selectAll(\".ChinaLoyalArc\")\n\t\t.transition().duration(1000)\n\t\t.attr(\"opacity\", 0)\n\t\t.each(\"end\", function() {d3.selectAll(\".ChinaLoyalArc\").remove();});\n\t\t\t\n\t/*Only show the chords of Canada*/\n\tchords.transition().duration(2000)\n .attr(\"opacity\", function(d, i) { \n\t\tif(d.source.index == 0 || d.target.index == 0) {return opacityValueBase;}\n\t\telse {return 0;}\n\t});\n\n\t/*Highlight arc of Canada*/\n\tsvg.selectAll(\"g.group\").select(\"path\")\n\t\t.transition().duration(2000)\n\t\t.style(\"opacity\", function(d) {\n\t\t\tif(d.index != 0) {return opacityValue;}\n\t\t});\t\n\t\t\n\t/*Show only the ticks and text at Canada*/\n\t/*Make the other strokes less visible*/\n\td3.selectAll(\"g.group\").selectAll(\"line\")\n\t\t.transition().duration(700)\n\t\t.style(\"stroke\",function(d,i,j) {if (j == 0) {return \"#000\";} else {return \"#DBDBDB\";}});\n\t/*Same for the %'s*/\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".tickLabels\").style(\"opacity\",function(d,i,j) {if (j == 0) {return 1;} else {return opacityValue;}});\n\t/*And the Names of each Arc*/\t\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".titles\").style(\"opacity\", function(d) { if(d.index == 0) {return 1;} else {return opacityValue;}});\n\n}", "function drawPaths() {\r\n var cw = viewerElt.width();\r\n var ch = viewerElt.height();\r\n var paths = \"\";\r\n var cpaths = \"\";\r\n var i;\r\n var len = pathObjects.length;\r\n for (i = 0; i < len; i++) { //removes paths from canvas\r\n pathObjects[i].remove();\r\n }\r\n pathObjects.length = 0;\r\n for (i = 0; i < ml.length; i++) { //construct the paths\r\n if (ml[i] === 'M') {\r\n paths += \"PATH::[pathstring]\"; // the paths to be drawn now\r\n cpaths += \"PATH::[pathstring]\"; // the paths we will save for our datastring (in relative coordinates)\r\n }\r\n paths += ml[i] + (cw * xy[i][0]) + ',' + (ch * xy[i][1]); // absolute coords\r\n cpaths += ml[i] + (xy[i][0]) + ',' + (xy[i][1]); // relative coords\r\n if (ml[i + 1] != 'L') {\r\n // if we're here, we've reached the end of a path, so add style information to the path strings\r\n paths += \"[stroke]\" + pa[i].color + \"[strokeo]\" + pa[i].opacity + \"[strokew]\" + (ch * pa[i].width) + \"[]|\";\r\n cpaths += \"[stroke]\" + pa[i].color + \"[strokeo]\" + pa[i].opacity + \"[strokew]\" + pa[i].width + \"[]|\";\r\n }\r\n }\r\n var path = [];\r\n if (paths.length > 0) {\r\n path = paths.split('PATH::');\r\n }\r\n for (i = 1; i < path.length; i++) {\r\n var pstring = get_attr(path[i], \"pathstring\", \"s\");\r\n var strokec = get_attr(path[i], \"stroke\", \"s\");\r\n var strokeo = get_attr(path[i], \"strokeo\", \"f\");\r\n var strokew = get_attr(path[i], \"strokew\", \"f\");\r\n var drawing = paper.path(pstring); // draw the path to the canvas\r\n drawing.data(\"type\", \"path\");\r\n drawing.attr({\r\n \"stroke-width\": strokew,\r\n \"stroke-opacity\": strokeo,\r\n \"stroke\": strokec,\r\n \"stroke-linejoin\": \"round\",\r\n \"stroke-linecap\": \"round\"\r\n });\r\n pathObjects.push(drawing);\r\n }\r\n currpaths = cpaths; // currpaths is used in update_datastring as the string representing all paths on the canvas\r\n //update_datastring();\r\n }", "function Draw4(){\n\n\t/*First disable click event on clicker button*/\n\tstopClicker();\n\t/*Show and run the progressBar*/\n\trunProgressBar(time=700*2);\t\n\t\n\t/*USA and China intro text*/\n\tchangeTopText(newText = \"First, let's only look at the in the USA with wires from China \",\n\t\tloc = 5, delayDisappear = 0, delayAppear = 1, finalText = true);\n\t\t\n\t/*Bottom text disappear*/\n\tchangeBottomText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\t\n\t\n /*Make the non USA & China arcs less visible*/\n svg.selectAll(\"g.group\").select(\"path\")\n\t\t.transition().duration(1000)\n\t\t.style(\"opacity\", function(d) {\n\t\t\tif(d.index != 4 && d.index != 5) {return opacityValue;}\n\t\t});\t\t\n\t\n\t/*Make the other strokes less visible*/\n\td3.selectAll(\"g.group\").selectAll(\"line\")\n\t\t.transition().duration(700)\n\t\t.style(\"stroke\",function(d,i,j) {if (j == 5 || j == 4) {return \"#000\";} else {return \"#DBDBDB\";}});\n\t/*Same for the %'s*/\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".tickLabels\").style(\"opacity\",function(d,i,j) {if (j == 5 || j == 4) {return 1;} else {return opacityValue;}});\n\t/*And the Names of each Arc*/\t\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(700)\n\t\t.selectAll(\".titles\").style(\"opacity\", function(d) { if(d.index == 4 || d.index == 5) {return 1;} else {return opacityValue;}});\n\n\t/*Show only the USA China chord*/\n\tchords.transition().duration(2000)\n\t\t.attr(\"opacity\", function(d, i) { \n\t\t\tif(d.source.index == 5 && d.target.index == 4) \n\t\t\t\t{return opacityValueBase;}\n\t\t\telse {return 0;}\n\t\t});\n\t\n}", "function scribble_canvas(tag) {\n this.tagcanvasDiv = tag; \n this.colorseg = Math.floor(Math.random()*14);\n this.cache_random_number = Math.random();\n\n this.segmentation_in_progress = 0;\n this.currently_drawing = OBJECT_DRAWING;\n this.flag_changed = 0;\n this.maxclicX = -1;\n this.minclicX = -1;\n this.maxclicY = -1;\n this.minclicY = -1;\n this.clickX = new Array();\n this.clickY = new Array();\n this.clickDrag = new Array();\n this.clickColor = new Array();\n this.clickWidth = new Array();\n this.hoverX = -1;\n this.hoverY = -1;\n this.paint = false;\n\n this.editborderlx = -1;\n this.editborderrx = -1;\n this.editborderly = -1;\n this.editborderry = -1;\n this.scribble_image = \"\";\n this.annotationid = -1;\n\n this.object_corners = new Array();\n\n this.scribblecanvas;\n \n\tthis.alpha = SCRIBBLE_OPACITY_DEFAULT;\n\tthis.maskAlpha = MASK_OPACITY_DEFAULT;\n\tthis.blur = GAUSSIAN_BLUR_DEFAULT_SEL;\n\tthis.lineWidth = 1;\n\n // These two functions are called to show and hide the spinner wheel \n // when the segmentation is in progress\n this.showspinner = function (){\n document.getElementById('segmentbtn').disabled = true;\n document.getElementById('donebtn').disabled = true;\n $('#loadspinner').show();\n }\n\n this.hidespinner = function (){\n document.getElementById('donebtn').disabled = false;\n document.getElementById('segmentbtn').disabled = false;\n $('#loadspinner').hide();\n }\n\n // Clean the scribbles from the canvas.\n this.cleanscribbles = function (){\n this.clickX = new Array();\n this.clickY = new Array();\n this.clickDrag = new Array();\n this.clickColor = new Array();\n this.clickWidth = new Array();\n paint = false;\n ClearMask('aux_mask');\n this.redraw();\n };\n\n // This function is called once we set the scribble mode. It prepares the canvas where the scribbles\n // will be drawn and initializes the necessary data structures.\n this.startSegmentationMode = function(){\n this.clickX = new Array();\n this.clickY = new Array();\n this.clickDrag = new Array();\n this.clickColor = new Array();\n this.clickWidth = new Array();\n paint = false;\n resp = \"\";\n this.prepareHTMLtoDraw(); \n };\n\n // Close the canvas where the scribbles will be drawn.\n this.CloseCanvas = function() {\n var p = document.getElementById('canvasDiv');\n p.parentNode.removeChild(p);\n };\n\n\t// Returns the color that should be applied according to the type of drawing used\n\t// (red/blue/rubber), if it's for the webpage or the scribble output, and if it's a cursor or not.\n\tthis.GetColorFromType = function (color, drawForUI, drawForCursor) {\n\t\t\n\t\tvar alpha = this.alpha;\n\t\tif( drawForCursor == true ) {\n\t\t\talpha = 1.0;\n\t\t}\n\t\tif (color == OBJECT_DRAWING) {\n\t\t\tif (drawForUI == true) {\n\t\t\t\treturn \"rgba(255,0,0,\" + alpha + \")\";\n\t\t\t} else {\n\t\t\t\treturn \"rgba(255,0,0,1)\";//100% opacity\t\t\t \n\t\t\t}\n\t\t} else if (color == BG_DRAWING) {\n\t\t\tif (drawForUI == true) {\n\t\t\t\treturn \"rgba(0,0,255,\" + alpha + \")\";//40% opacity\n\t\t\t} else {\n\t\t\t\treturn \"rgba(0,0,255,1)\";//100% opacity\t\t\t \n\t\t\t}\n\t\t} else if (color == RUBBER_DRAWING) {\n\t\t\tif (drawForCursor == true) {\n\t\t\t\treturn \"rgba(255,255,255,\" + alpha + \")\";\t \n\t\t\t} else { \n\t\t\t\treturn \"rgba(0,0,0,1)\";\n\t\t\t}\n\t\t}\n\t\treturn \"#000000\";\n\t}\n\n // Used by redraw() and redraw2()\n this.drawScribbles = function (scale, drawForUI) {\n\t\t// Initialize canvas and context\n var context = this.scribblecanvas.getContext(\"2d\");\n\t\t\n context.imageSmoothingEnabled = false;\n context.webkitImageSmoothingEnabled = false;\n\n\t\t// Clear for the image (we don't need it for the UI, it only slows everything down)\n context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas\n if (drawForUI != true && this.annotationid > -1) {\n scribble_canvas.scribblecanvas.getContext(\"2d\").globalCompositeOperation = \"source-over\";\n scribble_canvas.scribblecanvas.getContext(\"2d\").drawImage(scribble_canvas.scribble_image, 0, 0, main_media.width_orig, main_media.height_orig);\n }\n\n\t\tif( this.clickX.length > 0 )\n\t\t{\n\t\t\t// We want to scrbble over pixels only.\n\t\t\tcontext.lineJoin = \"bevel\";\n\t\t\tcontext.lineCap = \"square\";\t\t\n\t\t\n\t\t\tlastColor = -1;\n\t\t\tlastWidth = -1;\n\t\t\tcontext.beginPath();\n\t\t\t\n\t\t\t// Actually draw scribbles\n for(var i=0; i < this.clickX.length; i++) { \n\n\t\t\t\tvar color = this.clickColor[i];\n\t\t\t\tvar lineWidth = this.clickWidth[i];\n\t\t\t\tif( (lastColor != color) || (lastWidth != lineWidth) ) {\n\t\t\t\t\t//Set a different path for every color (or lineWidth), but not every point!\n\t\t\t\t\t//That way it's much faster, but we still need to change path when something changes (color/width)\n\t\t\t\t\tthis.closePath( context );\n\t\t\t\t\t\n\t\t\t\t\tcontext.lineWidth = lineWidth;\n\t\t\t\t\tcontext.strokeStyle = this.GetColorFromType( color, drawForUI, false );\n\n\t\t\t\t\tif (color == RUBBER_DRAWING) {\n\t\t\t\t\t\tcontext.globalCompositeOperation = \"destination-out\";\t\n\t\t\t\t\t} else {\t\t\t\t\n\t\t\t\t\t\tcontext.globalCompositeOperation = \"source-over\";\n\t\t\t\t\t}\n\t\t\t\t\t\n context.beginPath();\n\t\t\t\t}\n\t\t\t\tif (this.clickDrag[i] && i) {\n\t\t\t\t\tthis.drawLine(context, this.clickX[i - 1], this.clickY[i - 1],\n\t\t\t\t\t\tthis.clickX[i], this.clickY[i], color, lineWidth, drawForUI);\n\n }\n else{\n\t\t\t\t\tthis.drawLine(context, this.clickX[i], this.clickY[i],\n\t\t\t\t\t\tthis.clickX[i], this.clickY[i], color, lineWidth, drawForUI);\n\t\t\t\t}\n\t\t\t\tlastColor = color;\n\t\t\t\tlastWidth = lineWidth;\n\t\t\t}\n\t\t\tthis.closePath( context );\n\t\t}\n\n if (drawForUI == true) {\n\t\t\tthis.drawCursor( context, scale );\n }\n };\n\t\n\tthis.closePath = function( context ) {\n\t\tcontext.moveTo(-1,-1);// This is to \"close\" the path ... otherwise a single click will only show a tiny line, not a \"dot\".\n\t\tcontext.closePath();\n\t\tcontext.stroke();\n } \n\t\n // Draw the cursor, or where the path will be drawn if the user clicks there.\n\tthis.drawCursor = function( context, scale ) {\n\t\t\n\t\tcontext.lineJoin = \"bevel\";\n\t\tcontext.lineCap = \"square\";\t\t\n\t\tcontext.beginPath();\n\t\t\n context.globalCompositeOperation = \"source-over\";\n\t\t\n\t\t\n\t\t// Thank you Jonas for 0.5 : http://stackoverflow.com/questions/9311428/draw-single-pixel-line-in-html5-canvas\n\t\tvar x = this.hoverX - this.lineWidth/2;\n\t\tvar y = this.hoverY - this.lineWidth/2\n\t\tif( ((this.lineWidth) % 2) ) {//}&& !(x == x2 && y == y2) ) {\n\t\t\tx = x + 0.5;\n\t\t\ty = y + 0.5;\t\t\n } \n\t\tcontext.fillStyle = \"rgba(0,0,0,\" + this.alpha + \")\";//50% alpha black\n\t\tif( this.lineWidth < 5 )\n\t\t{\n\t\t\t//*1 for integer, not \"2\" + 20 = 220, for example ...\n\t\t\tcontext.rect( x-10, y, this.lineWidth*1+20, this.lineWidth );\n\t\t\tcontext.fill();\n\t\t\tcontext.closePath();\n\t\t\tcontext.beginPath();\n\t\t\tcontext.rect( x, y-10, this.lineWidth, this.lineWidth*1+20 );\n\t\t\tcontext.fill();\n\t\t\tcontext.closePath();\n\t\t\tcontext.beginPath();\n }\n\t\tcontext.fillStyle = this.GetColorFromType( this.currently_drawing, true, true );\n\t\tcontext.rect( x, y, this.lineWidth, this.lineWidth );\n\t\tcontext.fill();\n\t\t\t\t\t\t\n context.closePath();\n\t}\n\n // Used by drawScribbles() to draw a simple line\n this.drawLine = function (context, x, y, x2, y2, color, lineWidth, drawForUI) {\n\t\tif( !( x == x2 || y == y2) ) {\n\t\t\t// we only want vertical or horizontal lines\n\t\t\tthis.drawLine( context, x, y, x, y2, color, lineWidth, drawForUI );\n\t\t\tthis.drawLine( context, x, y2, x2, y2, color, lineWidth, drawForUI );\n\t\t\treturn;\n }\n\t\t// Thank you Jonas for 0.5 : http://stackoverflow.com/questions/9311428/draw-single-pixel-line-in-html5-canvas\t\n\t\tif( lineWidth % 2 ) {// || (x == x2 && y == y2) ) {\n\t\t\tcontext.moveTo(x+0.5-0.01, y+0.5);\n\t\t\tcontext.lineTo(x2+0.5+0.01, y2+0.5);\t\t\n\t\t} else{\n\t\t\tcontext.moveTo(x-0.01, y);\n\t\t\tcontext.lineTo(x2, y2);\t\t\t\t\t\t\n\t\t}\n };\n\n // Draws the scribbles in the canvas according to the zoom parameter\n // The function loops over clickX, clickY to know the coordinates of the scribbles.\n this.redraw = function () {\n this.drawScribbles(main_media.GetImRatio(), true);\n };\n\n // similar to redraw() but to set the scribbles to the same size than \n // the original image (not according to the zoom) this function is only \n // called when creating the segmentation to create save an image with \n // the scribbles \n this.redraw2 = function() {\n this.drawScribbles(1, false);\n }\n\t\n\tthis.UpdateSize = function(drawForUI) {\n\t\t\n\t\tthis.scribblecanvas.setAttribute('width', main_media.width_orig);\n\t\tthis.scribblecanvas.setAttribute('height', main_media.height_orig);\n\t\t\n\t\t// DON'T change the canvas size! only how it's shown! (css). So instead of changing canvas width/height, change 'style' attribute\n\t\t// Also, setting scribblecanvas.style.width doesn't seem to work, we need oto set the whole string.\n\t\tthis.scribblecanvas.setAttribute('style', 'width:' + main_media.width_curr + 'px;height:' + main_media.height_curr + 'px;');\n\t\t\n\t\t// We need to set this everytime, since setting the style overrides it.\n\t\tthis.scribblecanvas.style.cursor = 'none'\n } \n\tthis.ClearCanvas = function( drawForUI ) {\n }\n // Saves the resized scribbles into the server to create the segmentation\n this.saveImage = function(url, imname, dir, async, segment_ratio, fw, fh, annotation_ended) {\n var canvasData = url;\n \n $.ajax({\n async: async,\n type: \"POST\",\n url: \"annotationTools/php/saveimage.php\",\n data: { \n image: canvasData,\n name: imname,\n uploadDir: dir,\n }\n }).done(function(o) {\n var Nobj = $(LM_xml).children(\"annotation\").children(\"object\").length;\n if (scribble_canvas.annotationid > -1) Nobj = scribble_canvas.annotationid;\n \n // Save the scribble for segmenting (this is done synchronously \n // because we need to wait for the image to be saved in order \n // to segment).\n var imagname = main_media.GetFileInfo().GetImName();\n imagname = imagname.substr(0, imagname.length-4);\n\n var collectionName = main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n console.log(collectionName);\n scribble_canvas.createDir(\"annotationCache/TmpAnnotations/\"+collectionName);\n\t\t\tscribble_canvas.resizeandsaveImage(collectionName + \"/\" + imagname + '_scribble_' + Nobj + '.png', 'scribble.png', collectionName + \"/\", segment_ratio, fw, fh, -1, 0, annotation_ended, \"false\");\n });\n };\n\n // General function to synchronously create a directory from a given url\n this.createDir = function(url){\n $.ajax({\n async: false,\n type: \"POST\",\n url: \"annotationTools/php/createdir.php\",\n data: { \n urlData: url\n }\n }).done(function(o) {\n console.log(url);\n });\n };\n\n\n // ********************************************\n // THESE FUNCTIONS ARE COPIES OF ALREADY IMPLEMENTED FUNCTIONS BUT \n // ADAPTED TO SEGMENTATIONS. I REWROTE THEM HERE TO AVOID MIXING CODE \n // BUT SHOULD BE REFACTORED WITH THE REST\n // ********************************************\n this.DrawToQuery = function () {\n if((object_choices!='...') && (object_choices.length==1)) {\n main_handler.SubmitQuery();\n StopDrawEvent();\n return;\n }\n active_canvas = QUERY_CANVAS;\n\n // Move draw canvas to the back:\n document.getElementById('draw_canvas').style.zIndex = -2;\n document.getElementById('draw_canvas_div').style.zIndex = -2;\n\n // Remove polygon from draw canvas:\n var anno = null;\n if(draw_anno) {\n draw_anno.DeletePolygon();\n anno = draw_anno;\n draw_anno = null;\n }\n\n // Move query canvas to front:\n document.getElementById('query_canvas').style.zIndex = 0;\n document.getElementById('query_canvas_div').style.zIndex = 0;\n\n // Set object list choices for points and lines:\n var doReset = SetObjectChoicesPointLine(anno.GetPtsX().length);\n\n // Get location where popup bubble will appear:\n var im_ratio = main_media.GetImRatio();\n var pt = main_media.SlideWindow((anno.GetPtsX()[0]*im_ratio + anno.GetPtsX()[1]*im_ratio)/2,(anno.GetPtsY()[0]*im_ratio + anno.GetPtsY()[2]*im_ratio)/2);\n\n // Make query popup appear.\n main_media.ScrollbarsOff();\n WriteLogMsg('*What_is_this_object_query');\n \n wait_for_input = 1;\n var innerHTML = this.GetPopupFormDraw();\n\n CreatePopupBubble(pt[0],pt[1],innerHTML,'main_section');\n\n // Focus the cursor inside the box\n document.getElementById('objEnter').focus();\n document.getElementById('objEnter').select();\n\n // If annotation is point or line, then \n if(doReset) object_choices = '...';\n\n // Render annotation:\n query_anno = anno;\n query_anno.SetDivAttach('query_canvas');\n var anno_id = query_anno.GetAnnoID();\n query_anno.DrawPolygon(main_media.GetImRatio());\n \n // Set polygon actions:\n query_anno.SetAttribute('onmousedown','StartEditEvent(' + anno_id + ',evt); return false;');\n query_anno.SetAttribute('onmousemove','main_handler.CanvasMouseMove(evt,'+ anno_id +'); return false;');\n query_anno.SetAttribute('oncontextmenu','return false');\n query_anno.SetCSS('cursor','pointer');\n };\n\nthis.GetPopupFormDraw = function() {\n\t\t\n html_str = GetPopupFormDrawButtons();//\"<br />\";\n html_str += \"<b>Enter object name</b><br />\";\n html_str += this.HTMLobjectBox(\"mask\");\n \n if(use_attributes) {\n html_str += \"<b>Enter attributes</b><br />\";\n html_str += HTMLattributesBox(\"\");\n html_str += HTMLoccludedBox(\"\");\n }\n \n if(use_parts) {\n html_str += HTMLpartsBox(\"\");\n }\n \n html_str += GetPopupFormDrawButtons();//\"<br />\";\n\n return html_str;\n }\n\n\tfunction GetPopupFormDrawButtons() {\n\t \n\t\thtml_str = \"<div style='text-align: center;'>\";\n \n // Done button:\n html_str += '<input type=\"button\" value=\"Done\" title=\"Press this button after you have provided all the information you want about the object.\" onclick=\"main_handler.SubmitQuery();\" tabindex=\"0\" />';\n \n // Undo close button:\n html_str += '<input type=\"button\" value=\"Edit Scribble\" title=\"Press this button if to keep adding scribbles.\" onclick=\"KeepEditingScribbles();\" tabindex=\"0\" />';\n \n // Delete button:\n html_str += '<input type=\"button\" value=\"Delete\" title=\"Press this button if you wish to delete the polygon.\" onclick=\"scribble_canvas.WhatIsThisObjectDeleteButton();\" tabindex=\"0\" />';\n \n\t\thtml_str += \"</div>\";\n return html_str;\n}\n\nthis.WhatIsThisObjectDeleteButton = function (){\n submission_edited = 0;\n main_handler.QueryToRest();\n this.cleanscribbles();\n ClearMask('aux_mask');\n}\n\nthis.HTMLobjectBox = function(obj_name) {\n var html_str=\"\";\n \n html_str += '<input name=\"objEnter\" id=\"objEnter\" type=\"text\" style=\"width:345px;\" tabindex=\"0\" value=\"' + obj_name + '\" title=\"Enter the object\\'s name here. Avoid application specific names, codes, long descriptions. Use a name you think other people would agree in using. \"';\n \n html_str += ' onkeyup=\"var c;if(event.keyCode)c=event.keyCode;if(event.which)c=event.which;if(c==13)';\n \n // if obj_name is empty it means that the box is being created\n if (obj_name=='') {\n // If press enter, then submit; if press ESC, then delete:\n html_str += 'main_handler.SubmitQuery();if(c==27)scribble_canvas.WhatIsThisObjectDeleteButton();\" ';\n }\n else {\n // If press enter, then submit:\n html_str += 'this.SubmitEditLabel();\" ';\n }\n \n // if there is a list of objects, we need to habilitate the list\n if(object_choices=='...') {\n html_str += '/>'; // close <input\n }\n else {\n html_str += 'list=\"datalist1\" />'; // insert list and close <input\n html_str += '<datalist id=\"datalist1\"><select style=\"display:none\">';\n for(var i = 0; i < object_choices.length; i++) {\n html_str += '<option value=\"' + object_choices[i] + '\">' + object_choices[i] + '</option>';\n }\n html_str += '</select></datalist>';\n }\n \n html_str += '<br />';\n \n return html_str;\n}\n\n // Called after the segmentation is done. It prepares an annotation \n // object describing the new segmentation and shows up a bubble to \n // introduce the name of the object. If the user was editing a \n // segmentation we update the xml with the new coordinates of the \n // bounding box.\n this.preparetoSubmit = function(){\n if (this.annotationid == -1){ // The segmentation was new\n var anno = new annotation(AllAnnotations.length);\n var Nobj = $(LM_xml).children(\"annotation\").children(\"object\").length;\n var imagname = main_media.GetFileInfo().GetImName();\n imagname = imagname.substr(0, imagname.length-4);\n anno.SetRandomCache(this.cache_random_number);\n anno.SetType(1);\n anno.SetImageCorners(Math.max(0, this.minclicX-(this.maxclicX - this.minclicX)*0.25), \n Math.max(0, this.minclicY - (this.maxclicY - this.minclicY)*0.25),\n\t\t\t Math.min(main_media.width_orig, this.maxclicX+(this.maxclicX - this.minclicX)*0.25), \n\t\t\t Math.min(main_media.height_orig, this.maxclicY+(this.maxclicY - this.minclicY)*0.25));\n anno.SetCorners(object_corners[0], object_corners[1], object_corners[2], object_corners[3]);\n anno.SetImName(resp);\n anno.SetScribbleName(imagname+'_scribble_'+Nobj+'.png');\n\n // Draw polygon on draw canvas:\n draw_anno = anno;\n draw_anno.SetDivAttach('draw_canvas');\n draw_anno.DrawPolygon(main_media.GetImRatio());\n \n // Set polygon actions:\n draw_anno.SetAttribute('onmousedown','StartEditEvent(' + draw_anno.GetAnnoID() + ',evt); return false;');\n draw_anno.SetAttribute('onmousemove','main_handler.CanvasMouseMove(evt,'+ draw_anno.GetAnnoID() +'); return false;');\n draw_anno.SetAttribute('oncontextmenu','return false');\n draw_anno.SetCSS('cursor','pointer');\n\n this.DrawToQuery();\n }\n else { // We were editting a segmentation\n var anno = AllAnnotations[this.annotationid];\n var idx = scribble_canvas.annotationid;\n\n if (scribble_canvas.clickX.length > 0){\n var lx = Math.max(0, scribble_canvas.minclicX-(scribble_canvas.maxclicX - scribble_canvas.minclicX)*0.25);\n var ly = Math.max(0, scribble_canvas.minclicY - (scribble_canvas.maxclicY - scribble_canvas.minclicY)*0.25);\n\tvar rx = Math.min(main_media.width_orig, scribble_canvas.maxclicX+(scribble_canvas.maxclicX - scribble_canvas.minclicX)*0.25);\n\tvar ry = Math.min(main_media.height_orig, scribble_canvas.maxclicY+(scribble_canvas.maxclicY - scribble_canvas.minclicY)*0.25);\n anno.SetImageCorners(Math.min(lx, scribble_canvas.editborderlx), \n Math.min(ly, scribble_canvas.editborderly),\n Math.max(rx, scribble_canvas.editborderrx), \n Math.max(ry, scribble_canvas.editborderry));\n anno.SetCorners(object_corners[0], object_corners[1], object_corners[2], object_corners[3]);\n anno.SetRandomCache(scribble_canvas.cache_random_number);\n AllAnnotations[scribble_canvas.annotationid] = anno;\n\n scribble_canvas.UpdateMaskXML(idx, anno);\n }\n main_canvas.AttachAnnotation(anno);\n \n scribble_canvas.annotationid = -1;\n scribble_canvas.cleanscribbles();\n active_canvas = REST_CANVAS;\n \n main_handler.AnnotationLinkClick(idx);\n }\n resp = \"\";\n }\n\n // Updates the XML with the object 'idx' according to the edited \n // segmentation. It updates the boundaries of the polygon enclosing \n // the segmentation and the boundaries of the image containing the \n // segmentation. \n this.UpdateMaskXML = function (idx, annot){\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"scribbles\").children(\"xmin\").text(annot.GetCornerLX());\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"scribbles\").children(\"ymin\").text(annot.GetCornerLY());\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"scribbles\").children(\"xmax\").text(annot.GetCornerRX());\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"scribbles\").children(\"ymax\").text(annot.GetCornerRY());\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"box\").children(\"xmin\").text(annot.GetPtsX()[0]);\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"box\").children(\"ymin\").text(annot.GetPtsY()[0]);\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"box\").children(\"xmax\").text(annot.GetPtsX()[1]);\n $(LM_xml).children(\"annotation\").children(\"object\").eq(idx).children(\"segm\").children(\"box\").children(\"ymax\").text(annot.GetPtsY()[2]);\n\n WriteXML(SubmitXmlUrl,LM_xml,function(){return;});\n }\n\n // Creates the segmentation in different steps according to the \n // callback value. The function is done this way to allow asynchronous \n // behavior.\n // 1. the function saves the scribbles that the user has introduced to \n // segment an image.\n // 2. it saves a portion of the original image, according to the region \n // where the scribbles where drawn\n // 3. Creates the Masks directory and through an http requests calls a \n // cgi that will perform the segmentation through GraphCuts. It saves \n // the resulting mask in the new folder\n // 4. The final mask is drawn over the canvas, and the spinner that \n // indicated the segmentation process is turned off.\n\n this.resizeandsaveImage = function (urlSource, namedest, urlDest, scale, fwidth, fheight, dir, callback, annotation_ended, blur) {\n\n var poslx = Math.max(0, this.minclicX-(this.maxclicX - this.minclicX)*0.25);\n var posly = Math.max(0, this.minclicY - (this.maxclicY - this.minclicY)*0.25);\n if (this.annotationid > -1){\n poslx = Math.min(poslx, this.editborderlx);\n posly = Math.min(posly, this.editborderly); \n }\n\n $.ajax({\n async: true,\n cache: false,\n type: \"POST\",\n url: \"annotationTools/php/resizeandsaveimage.php\",\n data: { \n urlSource: urlSource,\n namedest: namedest,\n urlDest: urlDest,\n scale: scale,\n posx: poslx,\n posy: posly,\n fwidth: fwidth,\n fheight: fheight,\n dir: dir,\n bwidth: main_media.width_orig,\n bheight: main_media.height_orig,\n\t\t\t\tblur: blur,\n\n }\n }).done(function(data_response) {\n var imagetoSegmentURL = main_media.GetFileInfo().GetFullName();\n imagetoSegmentURL = imagetoSegmentURL.replace(\"///\",\"/\");\n var Nobj = $(LM_xml).children(\"annotation\").children(\"object\").length;\n if (scribble_canvas.annotationid > -1) Nobj = scribble_canvas.annotationid;\n if (callback == 0){\n\tvar collectionName = main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n\t\t\t\tscribble_canvas.resizeandsaveImage(imagetoSegmentURL, 'image.jpg', collectionName + \"/\", scale, fwidth, fheight, 0, 1, annotation_ended, scribble_canvas.blur);\n }\n else if (callback == 1){\n console.log(data_response);\n\tvar collectionName = main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n scribble_canvas.createDir(\"Masks/\"+collectionName+\"/\");\n\n // Execute the cgi to perform the segmentation\n var url = 'annotationTools/scribble/segment.cgi';\n\n var req_submit;\n if (window.XMLHttpRequest) {\n path = data_response;\n\t tmpPath = path+main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n\n req_submit = new XMLHttpRequest();\n req_submit.open(\"POST\", url, false);\n \n req_submit.send(imagetoSegmentURL+\"&\"+Nobj+\"&\"+scribble_canvas.colorseg+\"&\"+tmpPath);\n var cadena = req_submit.responseText.split('&');\n resp = cadena[0];\n\n // Here we add +1 to object_corners's right, because of how the lines are stored (if there's a one pixel line,\n // the min and max are the same, but max should be one more than min.).\n object_corners = new Array();\n object_corners.push(poslx + (cadena[1]/scale)); \n object_corners.push(posly + (cadena[2]/scale)); \n object_corners.push(poslx + (cadena[3] / scale) + 1);\n object_corners.push(posly + (cadena[4] / scale) + 1);\n \n\t // Save the segmentation result in the Masks folder:\n console.log(collectionName);\n\t\t\t\t\tscribble_canvas.resizeandsaveImage(collectionName + \"/\", resp, collectionName + \"/\", 1. / scale, main_media.width_orig, main_media.height_orig, 1, 2, annotation_ended, \"false\");\n\n\n }\n }\n else if (callback == 2){\n scribble_canvas.drawMask(1);\n scribble_canvas.hidespinner();\n scribble_canvas.segmentation_in_progress = 0;\n scribble_canvas.flag_changed = 0;\n if (annotation_ended){\n scribble_canvas.preparetoSubmit();\n }\n }\n });\n }\n\n // Draw the segmentation mask into the canvas, clearing previous masks from the canvas if there were any\n this.drawMask = function(modified){\n var loc = window.location.href;\n var dir = loc.substring(0, loc.lastIndexOf('/tool.html'));\n ClearMask('aux_mask')\n if (resp){\n this.cache_random_number = Math.random();\n var collectionName = main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n\n DrawSegmentation('myCanvas_bg','Masks/'+collectionName+\"/\"+resp, main_media.width_curr, main_media.height_curr, this.cache_random_number, 'aux_mask');\n } \n };\n\n // This function is called when the user clicks the segment or done \n // button. It creates the segmentation and prepares a query if the \n // user has hit done. If the scribbles have not changed since the \n // last time the user segmented the image it will avoid calculating \n // the new mask.\n this.segmentImage = function(annotation_ended){\n if (drawing_mode == 0){\n SetDrawingMode(1);\n if(draw_anno) return;\n }\n if (this.clickX.length == 0 && this.annotationid == -1){\n alert(\"Can not segment: you need to scribble on the image first\");\n return;\n }\n if (this.flag_changed == 1){\n this.showspinner();\n this.segmentation_in_progress = 1;\n \n\t\t\t// Set \"zoom\" to original size to redraw the scribbles in the image (UpdateSize(false))\n\t\t\t// and set back to current zoom for UI after (UpdateSize(true))\n\t\t\tthis.UpdateSize(false);\n this.redraw2();\n this.segmentAfterScribblesDone(annotation_ended);\n\t\t\tthis.UpdateSize(true);\n \n this.redraw();\n\n }\n else if (annotation_ended){ // if the last segmentation has not ended\n this.preparetoSubmit();\n }\n };\n\n // Crops an image surrounding the scribbles drawn by the user and \n // saves a resized version of the original image and the scribbles to \n // compute the segmentation mask. The resizing is done accordingly to \n // the size of the scribbles to avoid having to segment big images \n // when the user annotates big objects.\n this.segmentAfterScribblesDone = function (annotation_ended){\n var clx = Math.max(0, this.minclicX-(this.maxclicX - this.minclicX)*0.25);\n var crx = Math.min(main_media.width_orig, this.maxclicX+(this.maxclicX - this.minclicX)*0.25);\n var cly = Math.max(0, this.minclicY - (this.maxclicY - this.minclicY)*0.25);\n var cry = Math.min(main_media.height_orig, this.maxclicY+(this.maxclicY - this.minclicY)*0.25);\n if (this.annotationid > -1){\n // ESTA MAL\n clx = Math.min(clx, this.editborderlx);\n crx = Math.max(crx, this.editborderrx);\n cly = Math.min(cly, this.editborderly);\n cry = Math.max(cry, this.editborderry);\n }\n var fw = crx - clx;\n var fh = cry - cly;\n \n var scribblesize = Math.sqrt(fw*fh);\n var segment_ratio = Math.min(500/scribblesize,1);\n\n var scribbledataURL = this.scribblecanvas.toDataURL(\"image/png\"); \n this.redraw();\n \n var Nobj = $(LM_xml).children(\"annotation\").children(\"object\").length;\n if (this.annotationid > -1) Nobj = this.annotationid;\n\n // Save the scribble in the Scribbles folder\n var collectionName = main_media.GetFileInfo().GetDirName().replace(\"///\",\"/\");\n this.createDir(\"Scribbles/\"+collectionName+\"/\");\n\n var imagname = main_media.GetFileInfo().GetImName();\n imagname = imagname.substr(0, imagname.length-4);\n \n this.saveImage(scribbledataURL, imagname+'_scribble_'+Nobj+'.png', collectionName+\"/\", true, segment_ratio, fw, fh, annotation_ended);\n\n }\n\n // Creates the div elements to insert the scribble_canvas in the html\n this.prepareHTMLtoDraw = function(){ \n html_str = '<div id=\"canvasDiv\" ';\n html_str+='style=\"position:absolute;left:0px;top:0px;z-index:1;width:100%;height:100%;background-color:rgba(128,64,0,0);\">';\n html_str+='</div>';\n $('#'+this.tagcanvasDiv).append(html_str);\n $(document).ready(function() {scribble_canvas.prepareDrawingCanvas();});\n };\n \n // Creates the canvas where the scribbles will be drawn. \n this.prepareDrawingCanvas = function(){\n this.canvasDiv = document.getElementById('canvasDiv'); \n this.scribblecanvas = document.createElement('canvas');\n\t\t\n this.scribblecanvas.setAttribute('id', 'scribble_canvas');\n this.canvasDiv.appendChild(this.scribblecanvas);\n if(typeof G_vmlCanvasManager != 'undefined') {\n this.scribblecanvas = G_vmlCanvasManager.initElement(this.scribblecanvas);\n }\n\t\t\n\t\tthis.UpdateSize( true );\n\t\t\n $('#scribble_canvas').mousedown(function(e){\n if (e.button > 1) return;\n\t// If we are hiding all polygons, then clear the main canvas:\n\tif(IsHidingAllPolygons) {\n\t for(var i = 0; i < main_canvas.annotations.length; i++) {\n\t main_canvas.annotations[i].hidden = true;\n\t main_canvas.annotations[i].DeletePolygon();\n\t }\n\t}\n\n var mouseX = GetEventPosX(e.originalEvent);\n var mouseY = GetEventPosY(e.originalEvent); \n this.paint = true;\n scribble_canvas.addClick(mouseX, mouseY);\n scribble_canvas.redraw();\n });\n\n $('#scribble_canvas').mouseout(function(e){\n this.paint = false;\n });\n\n $('#scribble_canvas').mousemove(function(e){\n if(this.paint){\n scribble_canvas.addClick(GetEventPosX(e.originalEvent) , GetEventPosY(e.originalEvent) , true);\n }\n scribble_canvas.setHover(GetEventPosX(e.originalEvent), GetEventPosY(e.originalEvent));\n scribble_canvas.redraw();\n\n });\n \n $('#scribble_canvas').mouseup(function(e){\n this.paint = false;\n });\n };\n\n // Called each periodically while dragging the mouse over the screen. \n // Saves the coordinates of the clicks introduced by the user.\n this.addClick = function(x, y, dragging){\n this.flag_changed = 1;\n var ratio = main_media.GetImRatio(); \n x-=1; \n x = Math.round(x/ratio);\n y = Math.round(y/ratio);\n if (this.clickX.length == 0){\n this.maxclicX = this.minclicX = x;\n this.maxclicY = this.minclicY = y;\n }\n else { \n this.maxclicY = Math.max(this.maxclicY, y); this.maxclicX = Math.max(this.maxclicX, x); \n this.minclicY = Math.min(this.minclicY, y); this.minclicX = Math.min(this.minclicX, x);\n }\n this.clickX.push(x);\n this.clickY.push(y);\n this.clickDrag.push(dragging);\n this.clickColor.push(this.currently_drawing);\n this.clickWidth.push(this.lineWidth);\n };\n\n this.setHover = function (x, y) {\n this.flag_changed = 1;\n var ratio = main_media.GetImRatio();\n x -= 1;\n x = Math.round(x / ratio);\n y = Math.round(y / ratio);\n this.hoverX = x;\n this.hoverY = y;\n };\n\n // changes to foreground/backgorund/rubber\n this.setCurrentDraw = function(val){\n if (drawing_mode == 0){ \n SetDrawingMode(1);\n if(draw_anno) return;\n }\n if (val != OBJECT_DRAWING && val != BG_DRAWING && val != RUBBER_DRAWING) return;\n\t\tthis.scribblecanvas.style.cursor = 'none'\n this.currently_drawing = val;\n };\n }", "function update(rawdata){\n\t\tconsole.log('----WARNING: ITEMS ARE DRAWN IN LAYERS IN THE ODER IN WHICH THEIR SVG ELEMENT WAS CREATED------\\n'); \n\t\t//console.log('mousedLine ' + mousedLine +'\\n');\n\t\tlinesSVG.selectAll(\"path.line\").each(function(d,i){\t\t\t\t\t\t//<----------use .each for d3 selections (can use 'this'), and .forEach for traditional arrays \n\t\t\tlineIDX = i;\n\t\t\tif(mousedLine !== -1){\n\t\t\t\t//----DO NOT CHANGE THE ORDER OF THESE CHECKS...\n\t\t\t\t//....THE COLORING OF THE DATA POINTS IMPLICITLY DEPENDS ON IT!!!!!!-----\n\t\t\t\t\tif( \"US Average\" === this.getAttribute('idKey')) {\n\t\t\t\t\t\t//console.log('modifying line ' + mousedLine + '\\n'); \n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.75);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\t\n\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(parseInt(sampleData.us_average_data.time_category_data[i].key)))\n\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(sampleData.us_average_data.time_category_data[i].values))\t\t\t\t\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"r\", 6)\n\t\t\t\t\t\t\td3.select(this).attr(\"idKey\", parseInt(sampleData.us_average_data.time_category_data[i].key))\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 1)\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.85)\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke\", \"rgb(64, 64, 64)\")\n\t\t\t\t\t\t\t//d3.select(this).attr(\"fill\", \"rgb(255, 0, 0)\")\n\t\t\t\t\t\t\t//d3.select(this).attr(\"fill-opacity\", 0.5)\t\n\t\t\t\t\t\t}); \n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i) {\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(parseInt(sampleData.us_average_data.time_category_data[i].key)) + \",\" + yScale(sampleData.us_average_data.time_category_data[i].values - 35) + \")\");\n\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\tts = t.selectAll(\"tspan\");\n\t\t\t\t\t\t\tts[0][0].textContent = sampleData.us_average_data.category_state;\n\t\t\t\t\t\t\tts[0][1].textContent = Math.round(sampleData.us_average_data.time_category_data[i].values * 100)/100;\t\t\t\t\t\t\t \n\t\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse if(mousedLine === this.getAttribute('idKey')) {\n\t\t\t\t\t\t//apply no oppacity to the line that has been mousedOver.\n\t\t\t\t\t\t//make the line thicker\n\t\t\t\t\t\t\t//console.log('points on lineIDX = ' + lineIDX + '\\n');\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.75);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t\t//-------move the points to the one for the selected line-----\n\t\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i].key)))\t\t\t//lineIDX-1 because svg idexing it 1 indexed and d3 javascript is 0 indexed\n\t\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(sampleData.state_category_data[lineIDX-1].time_category_data[i].values))\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"r\", 6)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"idKey\", parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i].key))\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 1)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.85)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke\", \"rgb(64, 64, 64)\")\n\t\t\t\t\t\t\t\t//d3.select(this).attr(\"fill\", \"rgb(0, 0, 255)\")\n\t\t\t\t\t\t\t\t//d3.select(this).attr(\"fill-opacity\", 0.5)\t\n\t\t\t\t\t\t\t}); \n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i1) {\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i1].key)) + \",\" + yScale(sampleData.state_category_data[lineIDX-1].time_category_data[i1].values) + 35 + \")\");\n\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\tts = t.selectAll(\"tspan\");\n\t\t\t\t\t\t\tts[0][0].textContent = sampleData.state_category_data[lineIDX-1].category_state;\n\t\t\t\t\t\t\tts[0][1].textContent = Math.round(sampleData.state_category_data[lineIDX-1].time_category_data[i1].values * 100)/100;\t\t\t\t\t\t\t \n\t\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// dim the non-moused over lines\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.2);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 2);\n\t\t\t\t\t}\n\t\t\t\t\ttooltipsSVG.attr(\"opacity\", 0.85);\t\n\t\t\t}\n\t\t\telse {\n\t\n\t\t\t\t//-------- Reset all lines to default ----------\n\t\t\t\t\tif( \"US Average\" === this.getAttribute('idKey')) {\n\t\t\t\t\t\t// reset the US Average line\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.5);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// reset all the other lines\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.5);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 2);\n\t\t\t\t\t}\n\t\n\t\t\t\t\t//-------hide all the points-----\n\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\n\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(-100))\n\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(-100))\t\t\t\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0)\n\t\t\t\t\t\t\td3.select(this).attr(\"fill-opacity\", 0)\t\n\t\t\t\t\t\t}); \t\t\t\t\n\t\t\t\t\t//--------- Move and hide all tool tips and points to keep them out of the way ---------\t\t\t\t\n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i) {\t\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(-100) + \",\" + yScale(-100) + \")\");\t\t\t\t\t//moving the tool tips off the edge of the svg object window to hide them.\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\t\t\tt.selectAll(\"tspan\").each( function(d,i) {\n\t\t\t\t\t\t\t\t\t\td3.select(this).text(Math.round(0 * 100)/100);\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*/\n\t\t\t\t\t\t});\n\t\t\t\t\t\ttooltipsSVG.attr(\"opacity\", 0);\t\t\t\t\t\t\n\t\n\t\t\t}\n\t\n\t\t});\n\t\t\n\t\tthis.test1 = linesSVG.selectAll(\"path.line\");\n\t\tthis.test2 = pointsSVG.selectAll(\"circle\");\n\t\tthis.test3 = tooltipsSVG.selectAll('g');\n\t}", "function draw() {\n ctx.clearRect(0, 0, getCanvasSize(0), getCanvasSize(1));\n var countries = $scope.countriesJSON[\"countries\"]\n for (var countryIndex=0; countryIndex < countries.length; countryIndex++){\n var country=countries[countryIndex];\n var areas=country[\"areas\"];\n \n for (var areaIndex=0; areaIndex < areas.length; areaIndex++){\n var area=areas[areaIndex];\n var drawingResult=drawArea(area, getAreaColor(country, area));\n\n if (isSelectedCountry(country)){\n var subAreas=$scope.selectedCountry[\"subareas\"];\n for (var subAreaIndex=0; subAreaIndex<subAreas.length; subAreaIndex++){\n var subArea = subAreas[subAreaIndex];\n var color;\n if (isSelectedArea(subArea)){\n color=selectedColor;\n }\n var subAreaDrawingResult = drawArea(subArea, color);\n writeName(subArea[\"name\"], subAreaDrawingResult);\n }\n }else if (area[\"substract\"] != 1){\n writeName(country[\"name\"], drawingResult);\n }\n }\n }\n \n if ($scope.addingRegion){\n if (newArea.length >= 1){\n if (newArea.length == 1){\n drawCross(newArea[0])\n }else {\n drawShape(newArea);\n }\n }\n }\n }", "function initDraw() {\r\n brushLabel.text(\"Width: \");\r\n brushLabel1.text(\"7px\");\r\n brushLabel.append(brushLabel1);\r\n brushSliderPoint.css(\"left\", \"0px\");\r\n drawLabel.css({ 'color': 'black' });\r\n eraseLabel.css({ 'color': 'gray' });\r\n drawMode = 'draw';\r\n drawModeLabel1.text(\"Draw\");\r\n //eraserLabel.text(\"Eraser: \");\r\n //eraserLabel1.text(\"7px\");\r\n //eraserLabel.append(eraserLabel1);\r\n //eraserSliderPoint.css(\"left\", \"0px\");\r\n opacityLabel.text(\"Opacity: \");\r\n opacityLabel1.text(\"100%\");\r\n opacityLabel.append(opacityLabel1);\r\n opacitySliderPoint.css(\"left\", (0.87 * opacitySlider.width()) + \"px\");\r\n hideAll(drawArray);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies a folder by path to destination path Also works with different site collections.
copyByPath(destUrl, KeepBoth = false) { return __awaiter(this, void 0, void 0, function* () { const urlInfo = yield this.getParentInfos(); const uri = new URL(urlInfo.ParentWeb.Url); yield spPost(Folder(uri.origin, "/_api/SP.MoveCopyUtil.CopyFolderByPath()"), body({ destPath: toResourcePath(isUrlAbsolute(destUrl) ? destUrl : combine(uri.origin, destUrl)), options: { KeepBoth: KeepBoth, ResetAuthorAndCreatedOnCopy: true, ShouldBypassSharedLocks: true, __metadata: { type: "SP.MoveCopyOptions", }, }, srcPath: toResourcePath(combine(uri.origin, urlInfo.Folder.ServerRelativeUrl)), })); }); }
[ "function File_CopyFolder(sourceFolder, destinationFolder)\r\n{\r\n var exitResult;\r\n File_CheckFileExists(sourceFolder);\r\n\r\n exitResult = aqFileSystem.CopyFolder(sourceFolder, destinationFolder, false);\r\n if(!exitResult)\r\n CommonReporting.Log_StepError(\"[CommonFiles: File_CopyFolder] Folder <\" + sourceFolder + \"> was not copied\");\r\n\r\n CommonReporting.Log_Debug(\"[CommonFiles: File_CopyFolder] Copying files in folder: \" + aqFileSystem.IncludeTrailingBackSlash(destinationFolder));\r\n}", "copyTo(destFolder, destName, deep, multistatus) { }", "moveByPath(destUrl, KeepBoth = false) {\n return __awaiter(this, void 0, void 0, function* () {\n const urlInfo = yield this.getParentInfos();\n const uri = new URL(urlInfo.ParentWeb.Url);\n yield spPost(Folder(uri.origin, \"/_api/SP.MoveCopyUtil.MoveFolderByPath()\"), body({\n destPath: toResourcePath(isUrlAbsolute(destUrl) ? destUrl : combine(uri.origin, destUrl)),\n options: {\n KeepBoth,\n ResetAuthorAndCreatedOnCopy: true,\n ShouldBypassSharedLocks: true,\n __metadata: {\n type: \"SP.MoveCopyOptions\",\n },\n },\n srcPath: toResourcePath(combine(uri.origin, urlInfo.Folder.ServerRelativeUrl)),\n }));\n });\n }", "function copyDir(src, dest) {\n fs.copy(src, dest, function (err) {\n if (err) return console.error(err)\n console.log(src + ' folder successfully copied')\n });\n}", "static async copyDir(source, destination) {\n const files = await fs.readdir(source);\n\n await Promise.all(files.map(async (name) => {\n const sourcePath = `${source}/${name}`;\n const destinationPath = `${destination}/${name}`;\n\n const stat = await fs.lstat(sourcePath);\n if (stat.isDirectory()) {\n if (!fs.existsSync(destinationPath)) {\n fs.mkdir(destinationPath);\n }\n await FileManager.copyDir(sourcePath, destinationPath);\n } else if (!fs.existsSync(destinationPath)) {\n await fs.copyFile(sourcePath, destinationPath);\n }\n }));\n }", "function copyDir(sourceFile, destinationPath) {\n if (sourceFile.isExists()) {\n if (sourceFile.isDirectory()) {\n var files = sourceFile.listFiles();\n for (var i = 0; i < files.length; i++) {\n copyDir(files[i], destinationPath + '/' +sourceFile.getName());\n }\n } else {\n copyFile(sourceFile, destinationPath + '/' + sourceFile.getName());\n }\n }\n}", "copyByPath(destUrl, shouldOverWrite, KeepBoth = false) {\n return __awaiter(this, void 0, void 0, function* () {\n const { ServerRelativeUrl: srcUrl, [\"odata.id\"]: absoluteUrl } = yield this.select(\"ServerRelativeUrl\")();\n const webBaseUrl = extractWebUrl(absoluteUrl);\n const hostUrl = webBaseUrl.replace(\"://\", \"___\").split(\"/\")[0].replace(\"___\", \"://\");\n yield spPost(File(webBaseUrl, `/_api/SP.MoveCopyUtil.CopyFileByPath(overwrite=@a1)?@a1=${shouldOverWrite}`), body({\n destPath: toResourcePath(isUrlAbsolute(destUrl) ? destUrl : `${hostUrl}${destUrl}`),\n options: {\n KeepBoth: KeepBoth,\n ResetAuthorAndCreatedOnCopy: true,\n ShouldBypassSharedLocks: true,\n __metadata: {\n type: \"SP.MoveCopyOptions\",\n },\n },\n srcPath: toResourcePath(isUrlAbsolute(srcUrl) ? srcUrl : `${hostUrl}${srcUrl}`),\n }));\n });\n }", "copyDir ({ src, dest }) {\n return this.runtime.copyDir(\n this.templatePath(src),\n this.destinationPath(dest)\n )\n }", "function copyFiletoFolder(dirpath, destFolder){ \n let orgFileName = path.basename(dirpath); // get name of file from dirpath -> file.txt\n let destFilePath = path.join(destFolder, orgFileName); // destFilePath = \"C:\\Users\\\\DELL\\Downloads\\organised_files\\docs\\file.txt\"\n console.log(\"---------------------------------------------------------------------\", dirpath);\n console.log(\"---------------------------------------------------------------------\", destFilePath);\n fs.copyFileSync(dirpath,destFilePath); // fs.copyFileSync(p1, p2), this fn copies content of p1 file to p2\n // so it's neccessary for p2 also be a file at dest. locn. \n}", "function copy(directory) {\n fs.mkdir(dst + directory, echo);\n glob(src + directory + \"*\", function (err, files) {\n if (err) \n console.log(err);\n else {\n for (var f in files) {\n f = files[f].substring(files[f].lastIndexOf('/')+1);\n if (f.indexOf('.') == -1) {\n copy(directory + \"/\" + f + \"/\");\n } else {\n ncp(src + directory + f, dst + directory + f, echo);\n }\n }\n }\n });\n}", "function _gdrive_copy_process(item_list, srcFolder, dstFolder, callback) {\n if(!(item_list && item_list.length)) {\n callback(); // done\n } else {\n var re = new RegExp('/'+srcFolder.id+'/', 'g'); \n var item = item_list.shift();\n \n if(item.mimeType == GDRIVE_FOLDER_MIME_TYPE) {\n gdrive_folder_copy(item, item.title, dstFolder, function(error, res) {\n if(error) {\n callback(error);\n } else {\n _gdrive_copy_process(item_list, srcFolder, dstFolder, callback);\n }\n }); \n } else if(item.title.match('.+\\\\.json$')) {\n _gdrive_load_json(item, function(error, data) { \n if(error) {\n callback(error);\n } else {\n var content = JSON.stringify(data).replace(re, '/'+dstFolder.id+'/');\n \n gdrive_file_create(dstFolder, item.title, content, function(error, response) {\n if(error) {\n callback(error);\n } else {\n _gdrive_copy_process(item_list, srcFolder, dstFolder, callback);\n }\n }); \n }\n });\n } else if(item.title != STORYMAP_LOCK_FILE) { // don't copy lock file \n gdrive_file_copy(item.id, dstFolder, item.title, function(error, res) {\n if(error) {\n callback(error);\n } else {\n _gdrive_copy_process(item_list, srcFolder, dstFolder, callback);\n } \n });\n } else {\n _gdrive_copy_process(item_list, srcFolder, dstFolder, callback);\n } \n }\n}", "copy(path, newpath) {\n\n\t}", "function copyAllFilesUnderASharedFolder(srcFolder, destRootFolder) {\n\n // Shared Folder I want to copy\n var defaultFolderID = \"\";\n\n if (srcFolder == null)\n srcFolder = DriveApp.getFolderById(defaultFolderID);\n\n // Destination Root Folder Owned by me.\n var destRootFolderID = \"\";\n\n if (destRootFolder == null)\n destRootFolder = DriveApp.getFolderById(destRootFolderID);\n\n if (srcFolder == null || destRootFolder == null)\n return;\n\n // Logger.log(\"Source Folder Name: \" + srcFolder.getName());\n // Logger.log(\"Destination Parent Folder Name: \" + destRootFolder.getName());\n // Logger.log(\"Creating folder: \" + srcFolder.getName());\n var newFolder = DriveApp.createFolder(srcFolder.getName());\n\n destRootFolder.addFolder(newFolder);\n\n var files = srcFolder.getFiles();\n while (files.hasNext()) {\n var file = files.next();\n // Logger.log(\"Copying file: \" + file.getName());\n var newFile = file.makeCopy();\n // Logger.log(\"Coppied file name: \" + newFile.getName());\n newFolder.addFile(newFile);\n // Logger.log(\"Resetting coppied filename to : \" + file.getName());\n newFile.setName(file.getName());\n }\n\n // Recursive step\n var childFolders = srcFolder.getFolders();\n while (childFolders.hasNext()) {\n var child = childFolders.next();\n // Logger.log(\"Child folder: \"+ child.getName());\n copyAllFilesUnderASharedFolder(child, newFolder);\n }\n}", "function copyDir(src, dst) {\n if (!fs.existsSync(dst)) {\n mkdirsSync(dst);\n }\n for (var file of fs.readdirSync(src)) {\n var srcName = path.join(src, file);\n var dstName = path.join(dst, file);\n var stat = fs.lstatSync(srcName);\n if (stat.isDirectory()) {\n copyDir(srcName, dstName);\n } else if (stat.isFile()) {\n copyFile(srcName, dstName);\n }\n }\n}", "function copyDirectoryHelper(srcPath, destPath) {\n //read the contents of the source directory\n const allFilesAndDirs = fs.readdirSync(srcPath);\n\n //go through the contents of the dir\n for (let i = 0; i < allFilesAndDirs.length; i++) {\n //get the full path to the file or directory\n const fullPathToSrcFileOrDir = path.join(srcPath, allFilesAndDirs[i]);\n const fullPathToDestFileOrDir = path.join(destPath, allFilesAndDirs[i]);\n\n //get some stats about the file/dir\n const stats = fs.statSync(fullPathToSrcFileOrDir);\n\n //if this is a dir\n if(stats.isDirectory()) {\n //if the directory does not already exist\n if(fs.existsSync(fullPathToDestFileOrDir) === false) {\n //create the new subdirectory\n fs.mkdirSync(fullPathToDestFileOrDir);\n }\n\n //recurse in the subdirectories\n copyDirectoryHelper(fullPathToSrcFileOrDir, fullPathToDestFileOrDir);\n } else if(stats.isFile()) {\n //copy the file (overwite if it exists already)\n fs.copyFileSync(fullPathToSrcFileOrDir, fullPathToDestFileOrDir);\n }\n }\n}", "function copyDirectory(item, cb) {\n\n Utils.createDirectory(item.val, item.parent, function(err, newDir) {\n if(err) return cb(err);\n\n // Store the top-level directory to return\n if (!topLevelCopy) topLevelCopy = newDir;\n\n // Lookup directory files\n File.find({ DirectoryId: item.val.id }).exec(function(err, files) {\n if(err) return cb(err);\n\n files.forEach(function(file) {\n stack.push({ type: 'file', val: file, parent: newDir.id });\n });\n\n // Lookup children directories\n Directory.find({ DirectoryId: item.val.id }).exec(function(err, dirs) {\n\n dirs.forEach(function(dir) {\n stack.push({ type: 'directory', val: dir, parent: newDir.id });\n });\n\n // run processStack again\n return processStack();\n });\n });\n });\n }", "function copy(source, dest){\n if (!fs.existsSync(source)){\n throw new ValueError(\"Source does not exist\")\n }\n\n if(!fs.existsSync(dest)){\n fs.mkdirSync(dest)\n }\n\n if(!isDir(dest)){\n throw new ValueError(\"Dest must be a directory.\")\n }\n\n if(isFile(source)){\n let filename = lastPathElement(source)\n fs.copyFileSync(source, path.join(dest, filename))\n } else {\n let dirname = lastPathElement(source)\n let nestedDir = path.join(dest, dirname)\n fs.mkdirSync(nestedDir)\n for(let item of fs.readdirSync(source)){\n copy(path.join(source, item), nestedDir)\n }\n }\n}", "static folders(generator) {\n generator.fs.copy(\n generator.sourceRoot() + \"/default\",\n generator.destinationRoot()\n );\n }", "function browseForFolder()\n\t{\n\tvar newDirectory = dreamweaver.browseForFolderURL(MSG_PickFolder, findObject(\"destinationFolder\").value, true);\n\tif (newDirectory.length > 0 && newDirectory.charAt(newDirectory.length-1) != '/')\n\t\tnewDirectory += '/';\n\tif (newDirectory != null && newDirectory != \"\") \n\t\tfindObject(\"destinationFolder\").value = newDirectory; \n\t} //browseForFolder" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
stackDraw(n): Removes the indicated card from the stack and returns it.
function stackDraw(n) { var card; if (n >= 0 && n < this.cards.length) { card = this.cards[n]; this.cards.splice(n, 1); } else card = null; return card; }
[ "function discardCard(card) {\n\t\tremoveDrawn(card);\n\t\tdiscard.push(card);\n\t}", "function drawCard(deck){\n return deck.pop()\n}", "function discardcard() {\n unbr.discard.unshift((unbr.hand[unbr.selected[0]]));\n unbr.hand.splice(unbr.selected[0], 1);\n $(\".card\").slice(unbr.normselect, unbr.normselect+1).fadeOut(200);\n $(\".card\").slice(unbr.normselect, unbr.normselect+1).remove();\n drawcard();\n\n}", "removeCard(card) {\n var index = this.hand.indexOf(card);\n return this.hand.splice(index,1)[0];\n }", "function removeCard(data) {\n //Find the index of the card we need to remove\n var index = boardHand.indexOf(data.card);\n //If we find it\n if(index > -1) {\n //Remove it from the board\n boardHand.splice(index, 1);\n $(\"#activeHand img\").last().remove();\n }\n}", "removeCard(card) {\n let cleanID = card[0].id.split('_')[1];\n canvas.currentCards[cleanID].inStack = false;\n __IPC.ipcRenderer.send('card' + cleanID + '_toggle_sketches' + this.id, true);\n\n // grep returning only cards that do not contain the target id\n this.cards = $.grep(this.cards, function(n) {\n return $(n.card).attr('id') !== card.attr('id');\n });\n\n $(card).css({\n top: $(card).offset().top,\n left: $(card).offset().left,\n }).droppable('enable');\n document.body.appendChild($(card)[0]);\n $(card).find('.card-header').find('button').each((index, button) => {\n $(button).attr('disabled', false);\n });\n }", "removeCardFromHandAndDraw(player, idx) {\n const cards = this.hands[player.data.handIdx];\n const card = cards.splice(idx, 1)[0];\n cards.push(...this.dealCards(1))\n return card;\n }", "dispenseCard(){\n let card = undefined;\n card = this.drawPile.pop();\n return card;\n }", "removeCard(leavingEmpty = false){\r\n if (this.card){ //If it contains a card, remove it\r\n let card = this.card;\r\n card.image.remove();\r\n card.slot = null;\r\n this.card = null;\r\n return card;\r\n }\r\n }", "function discardhand() {\n cardcount();\n unbr.discard.unshift(unbr.hand);\n unbr.hand = [];\n $(\"#hand div\").fadeOut(200);\n $(\"#hand\").empty();\n drawhandstart();\n}", "function drawCard() {\n let cardIndex = Math.floor(Math.random() * cards.length);\n let card = cards.splice(cardIndex, 1)[0];\n return dummyDeck[card];\n }", "function removeCard() {\n if (deck.length != 0) {\n card = document.querySelector('img')\n card.remove()\n deck.shift()\n if (deck.length == 0) {\n actions.innerHTML = 'No cards left in the deck. :-('\n }\n }\n}", "function drawCardFromDeck() {\n var cardIndex = getRandom(0, deck.length);\n var card = deck[cardIndex];\n deck.splice(cardIndex,1);\n return card;\n}", "removeCard(){\n let willowCard = this.stock.shift()\n placeWillow(willowCard)\n }", "function removeCardsFromOpenCards() {\n\topenCards.pop();\n\topenCards.pop();\n}", "function removeCard() {\n\t\tlet card = this.parentNode;\n\t\tcardArea.removeChild(card);\n\t}", "function draw() {\n \tlet drawnCard = deck.pop()\n if(drawnCard == undefined) return 'empty' // in case deck has no more cards and need to reset\n graveyard.push(drawnCard)\n \treturn getCard(drawnCard)\n }", "discard(card) {\n let findCard = this.deck.indexOf(card);\n let removedCard = this.deck.splice(findCard, 1);\n let discardedArr = this.discardPile.concat(removedCard);\n this.discardPile = discardedArr;\n }", "function restackCards() {\r\n\tvar pile = document.getElementById(\"stock-wrapper\")\r\n\tif (pile.children.length == 1) {\r\n\t\tvar hand = document.getElementById(\"hand-wrapper\")\r\n\t\tvar cardList = [];\r\n\t\tfor (var card of hand.children) {\r\n\t\t\tcardList.push(card.id);\r\n\t\t}\r\n\t\tfor (var i = cardList.length - 1; i >= 0; i--) {\r\n\t\t\tvar id = cardList[i];\r\n\t\t\tvar card = document.getElementById(id);\r\n\t\t\tcard.removeEventListener(\"dblclick\", checkCard, true);\r\n\t\t\tcard.addEventListener(\"click\", uncover, true);\r\n\t\t\tcard.classList.add(\"covered\");\r\n\t\t\tpile.appendChild(card);\r\n\t\t\tcard.setAttribute('draggable', false);\r\n\t\t}\r\n\t\tupdateScore(-50);\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the tl_sldr_nav position based upon the day() clicked Content (div class="tl_sldr_box")
function moveSliderBoxDay(index) { // index needs to be zero-indexed zeroIndex = index - 1; //highlightIndex = index - 1; //add and remove the day CSS class highlight $('#tl_slider .tl_sldr_box ul li').removeClass('current-day'); //console.log($('.tl_sldr_box ul').find('li[' + highlightIndex + ']')); $('#tl_slider .tl_sldr_box ul li.' + phaseDates[currentPhase][index]).addClass('current-day'); //hide/show event circle if highlighted day contains an event. (per Dave 2012-05-12) $('#tl_slider .tl_sldr_box ul li').find('.tl_event_circle').css('display','block'); if($('#tl_slider .tl_sldr_box ul').find('li.' + phaseDates[currentPhase][index]).has('.tl_event_circle')) { $('#tl_slider .tl_sldr_box ul li.' + phaseDates[currentPhase][index]).find('.tl_event_circle').css('display','none'); } // lastly, move the slider //console.log($.slider()); $('#tl_sldr_nav').slider( 'option', 'value', index ); }
[ "function _changeDayView(view, day) {\n if (day) {\n //dayview\n switch (view) {\n\n case \"edit_item\":\n $(\".page__background\").css(\"background-color\", \"ghostwhite\");\n $(\".settings-list\").css(\"background-color\", \"ghostwhite\");\n $(\".list__item\").css(\"color\", \"black\");\n $(\".profile-name\").css(\"color\", \"black\");\n $(\".profile-email\").css(\"color\", \"black\");\n $(\".list--inset\").css(\"border\", \"1px solid #ddd\");\n break;\n\n case \"manage_items\":\n $(\".page__background\").css(\"background-color\", \"ghostwhite\");\n $(\".list__item\").css(\"background-color\", \"ghostwhite\");\n $(\".item-desc\").css(\"color\", \"#666\");\n $(\".navigation-bar\").removeClass(\"transparent-day\");\n $(\".navigation-bar\").removeClass(\"transparent-night\");\n break;\n\n case \"green\":\n $(\".page__background\").removeClass(\"background-green-night\");\n $(\".page__background\").addClass(\"background-green-day\");\n $(\".navigation-bar\").addClass(\"transparent-day\");\n $(\".navigation-bar\").removeClass(\"transparent-night\");\n break;\n\n case \"history\":\n $(\".page__background\").removeClass(\"background-history-night\");\n $(\".page__background\").addClass(\"background-history-day\");\n $(\".navigation-bar\").addClass(\"transparent-day\");\n $(\".navigation-bar\").removeClass(\"transparent-night\");\n break;\n }\n } else {\n //nightview\n switch (view) {\n\n case \"edit_item\":\n $(\".page__background\").css(\"background-color\", \"dimgrey\");\n $(\".settings-list\").css(\"background-color\", \"dimgrey\");\n $(\".list__item\").css(\"color\", \"white\");\n $(\".profile-name\").css(\"color\", \"white\");\n $(\".profile-email\").css(\"color\", \"white\");\n $(\".list--inset\").css(\"border\", \"1px solid lightgrey\");\n $(\".navigation-bar\").removeClass(\"transparent-day\");\n $(\".navigation-bar\").addClass(\"transparent-night\");\n break;\n\n case \"manage_items\":\n $(\".page__background\").css(\"background-color\", \"dimgrey\");\n $(\".list__item\").css(\"background-color\", \"dimgrey\");\n $(\".item-desc\").css(\"color\", \"ghostwhite\");\n $(\".navigation-bar\").removeClass(\"transparent-day\");\n $(\".navigation-bar\").addClass(\"transparent-night\");\n break;\n\n case \"green\":\n $(\".page__background\").removeClass(\"background-green-day\");\n $(\".page__background\").addClass(\"background-green-night\");\n $(\".navigation-bar\").removeClass(\"transparent-day\");\n $(\".navigation-bar\").addClass(\"transparent-night\");\n break;\n\n case \"history\":\n $(\".page__background\").removeClass(\"background-history-day\");\n $(\".page__background\").addClass(\"background-history-night\");\n $(\".navigation-bar\").removeClass(\"transparent-day\");\n $(\".navigation-bar\").addClass(\"transparent-night\");\n break;\n }\n }\n}", "function dayClick(e) {\n\t\tvar day = e.target.getAttribute('data-day');\n\t\tvar current = document.querySelector('body').getAttribute('data-selected-day');\n\n\t\tif (current !== day) {\n\t\t\tdocument.querySelector('body').setAttribute('data-selected-day', day);\n\t\t\tif (document.querySelector('body').getAttribute('data-active-schedule') === 'main') mainSwiper.slideTo(day);\n\t\t\telse otherSwiper.slideTo(day);\n\t\t}\n\t}", "function weekClicked (event) { // pass an informaton about the element clicked into the function\n\tweekToDisplay = event.target.parentNode.parentNode.getAttribute('id'); // save Id of clicked grandparent element\n\tview = \"month\"; // change view status to month\n\tchangeView(); // change view to week (because it was set to month before)\n}", "function menuOpenClicked() {\n document.getElementById('leftSideBar').style.left = \"0\";\n document.getElementById('emptyPage').style.left = \"0\";\n }", "function moveIntoPlace(){\n\t\t$globalNavCont.append( $megaMenu );\n\t\t//$global-nav.after( $megaMenu );\n\t\tfirstClick = false;\n\t}", "function onClickDay()\n// Helper to refresh the nb of abstract in the togle\n{\n $(\"#whichday .btn\").click(function(){\n $(\".day\").removeClass('active')\n var day = $(this).text();\n $(\"#button-%s\".format(day)).addClass('active')\n displayBlockApp(day)\n });\n}", "function currentMenu(){\n $('.header_gnb_m').before('<div class=\"currentBox\">' + locationTxt + '<div><i class=\"fas fa-times\"></i></div></div>');\n }", "function SwitchCases(){\n\tvar dateRange = $('li[class=\"selected\"]').attr('id');\n\tswitch(dateRange)\n\t{\n\t\tcase 'nav1':\n\t\t\tShowToday();\n\t\t\tbreak;\n\t\tcase 'nav2':\n\t\t\tShowYesterday();\n\t\t\tbreak;\n\t\tcase 'nav3':\n\t\t\tShowThisweek();\n\t\t\tbreak;\n\t\tcase 'nav4':\n\t\t\tShowLastweek();\n\t\t\tbreak;\n\t\tcase 'nav5':\n\t\t\tShowThismonth();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tShowToday();\n\t}\n}", "startDatePanelClick() {\n // change time type to start time mode\n dispatch(modifyInnerState_timeType(1))\n // route to time selector page\n dispatch(modifyInnerState_route(3))\n }", "function subMenuOpenClicked(name) {\n categoryClicked(name)\n setTimeout(() => {\n menuOpenClicked();\n document.getElementById('leftSubSideBar').style.left = \"0\"; \n }, 100)\n }", "function positionCalendar(objetParent){\n //document.getElementById('calendrier').style.left = ds_getleft(objetParent) + \"px\";\n document.getElementById('calendrier').style.left = ds_getleft(objetParent) + \"px\";\n //document.getElementById('calendrier').style.top = ds_gettop(objetParent) + 20 + \"px\" ;\n document.getElementById('calendrier').style.top = ds_gettop(objetParent) + 20 + \"px\" ;\n // et on le rend visible\n document.getElementById('calendrier').style.visibility = \"visible\";\n}", "function openMenu() {\n document.getElementsByClassName('so-section')[0].style.left = '0';\n document.getElementsByClassName('navigator-links')[0].style.left = '-100%';\n setMenuIsOpen(true);\n }", "function dayClicked (event) { // pass an informaton about the element clicked into the function\n\tvar element = event.target; // save information about the element as a variable\n\tdocument.getElementById(\"divCurrentDay\").removeAttribute(\"id\"); // remove clicked element's Id\n\telement.parentNode.setAttribute(\"id\", \"divCurrentDay\"); // add a new Id to the element\n\tday = parseInt(event.target.innerHTML); // save the HTML content as a day variable\n\tfindEventIndex(day); // check if there is an event connected to that day\n\tgetEventDetails(); // display informations about an event (or lack of it)\n}", "function setCurrentLocation() {\n var scrollTop = $(window).scrollTop();\n\n // Fix the sidebar to the top when scrolling.\n if (scrollTop >= $sidebarContainer.offset().top - topTrigger) {\n $sidebar.addClass('content-sidebar-fixed');\n }\n else {\n $sidebar.removeClass('content-sidebar-fixed');\n }\n\n // Look for when the bottom of the .content-container is within bottomSpacing of the bottom of the nav sidebar.\n if (scrollTop + $sidebar[0].offsetTop + $sidebar[0].offsetHeight + bottomSpacing >= $footer[0].offsetTop) {\n $sidebar.addClass('content-sidebar-bottom');\n }\n else {\n $sidebar.removeClass('content-sidebar-bottom');\n }\n\n // Find menu item currently displayed in viewport.\n var s;\n var sb;\n for (s = 0; s < $sections.length; s++) {\n var section = $sections[s];\n sb = $sections.length - 1;\n if (scrollTop < section.offsetTop - topSpacing - 10) {\n sb = (s === 0) ? 0 : s - 1;\n break;\n }\n }\n // Set text in Open button to currently displayed menu item.\n if (s !== 0) {\n var i = (sb > $leftNavItems.length - 1) ? $leftNavItems.length - 1 : sb;\n $leftNavOpen.text($leftNavItems[i].innerText);\n }\n // Set class on menu item for currently displayed section.\n selectMenuItem($sections[sb].id);\n }", "function pageNav() {\n jQuery(document).on(\"click\", \".we-slider .slider-nav span\", function () {\n parentWidth = jQuery(this).parents(\".we-slider\").width();\n slider = jQuery(this).parents(\".we-slider\").find(\".slider\");\n jQuery(this).addClass(\"active\");\n jQuery(this).parents(\".we-slider\").find(\".slider-nav \").find(\"span\").not(jQuery(this)).removeClass(\"active\");\n activeIndex = jQuery(this).index();\n leftValue = parentWidth * activeIndex;\n slider.stop(true, true).animate({\"margin-left\": \"-\" + leftValue + \"px\"}, 600);\n });\n}", "function changeContent() {\n $(\"#main-content\").addClass(\"d-none\");\n $(\"#header-title\").addClass(\"d-none\");\n $(\"#main-header-line\").addClass(\"d-none\");\n $(\".header-paragraph\").addClass(\"d-none\");\n\n $(\"#city-content\").removeClass(\"d-none\");\n $(\"#city-header-title\").removeClass(\"d-none\");\n $(\".city-gallery\").removeClass(\"d-none\");\n $(\"#city-header-line\").removeClass(\"d-none\");\n\n // bring the user to the top of the page\n window.scrollTo({ top: 0, behavior: 'smooth' });\n }", "function switchTabs(day) {\r\n $('div.show.active').removeClass('show active');\r\n $('a.nav-link.active').removeClass('active');\r\n $(`#${day}`).addClass('show active');\r\n $(`a[href='#${day}']`).addClass('active');\r\n}", "function checkAndClickUpperNavButton() {\n if (clickUpperNavButton === 'publishedNews') {\n document.getElementById('nav-link_publishedNews').click()\n }\n if (clickUpperNavButton === 'allNews') {\n document.getElementById('nav-link_allNews').click()\n }\n if (clickUpperNavButton === 'unpublishedNews') {\n document.getElementById('nav-link_unpublishedNews').click()\n }\n if (clickUpperNavButton === 'archivedNews') {\n document.getElementById('nav-link_archivedNews').click()\n }\n}", "function makeNavInView() {\n\t\t\tlet currentItem = $( '.sticky__nav-item.is-active' );\n\t\t\tlet winW = $( window ).width();\n\t\t\tif ( winW > 799 && currentItem.length > 0 ) {\n\t\t\t\tcurrentItem[ 0 ].scrollIntoView(\n\t\t\t\t\t{\n\t\t\t\t\t\tblock: 'center',\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converte todas as pericias. Primeiro calcula o total de pontos e depois varre as gEntradas de pericia, computando o valor de cada uma e o numero de pontos disponiveis.
function _ConvertePericias() { for (var i = 0; i < gEntradas.pericias.length; ++i) { var pericia_personagem = gPersonagem.pericias.lista[gEntradas.pericias[i].chave]; pericia_personagem.pontos = gEntradas.pericias[i].pontos; pericia_personagem.complemento = 'complemento' in gEntradas.pericias[i] ? gEntradas.pericias[i].complemento : ''; } }
[ "function porcentajes(numeroChicos, numeroChicas) {\n let total = numeroChicos + numeroChicas;\n let porcentajeChicos = (numeroChicos * 100) / total; \n let porcentajeChicas = (numeroChicas * 100) / total;\n console.log (`% de chicos = ${porcentajeChicos.toFixed(2)}`);\n console.log (`% de chicas = ${porcentajeChicas.toFixed(2)}`);\n}", "function obtenerPorcentajes() {\n if (EPS != undefined) {\n let totalAfiliados = EPS.afiliados.totalMujeres + EPS.afiliados.totalHombres;\n let porcentajeMujeres = Math.round((EPS.afiliados.totalMujeres * 100) / totalAfiliados);\n let porcentajeHombres = Math.round((EPS.afiliados.totalHombres * 100) / totalAfiliados);\n console.log(`----------------------------------------------------------------------------------------`);\n console.log(`Total Afiliados ${totalAfiliados}`);\n console.log(`Porcentaje mujeres ${porcentajeMujeres}% --> Porcentaje hombres ${porcentajeHombres}%`);\n console.log(`----------------------------------------------------------------------------------------`);\n\n }\n}", "promedio(numeros) {\n let divisor = numeros.length;\n let dividendo = this.sumatoria(numeros);\n let resultado = dividendo / divisor;\n return Math.round(resultado * 10) / 10;\n }", "function calcularPerfilGrupalCiudades() {\n //Recorrer las columnas de cada persona,se asume q todas las personas tienen las mismas colunas\n //por eso se usa la posicion cero como muestra y se inicia el contador p=1, por que en cero esta el nombre\n for (p = 1; p < listaOrdenados[0].persona.length; p++) {\n perfilGrupal2[p - 2] = 0;\n //Recorrer a todas las personas\n for (let index = 0; index < inputKD5.value; index++) {\n perfilGrupal2[p - 2] += parseInt(listaOrdenados[index].persona[p]);\n }\n //debe sumarse el mismo objetoA\n perfilGrupal[p - 2] += parseInt(objetoA[p]);\n //calculamos el promedio\n console.log(\"Suma Perfil: \" + perfilGrupal2[p - 2]);\n perfilGrupal2[p - 2] = perfilGrupal2[p - 2] / (parseInt(inputKD5.value) + 1);\n }\n console.log('perfil grupal 2 ' + perfilGrupal2);\n}", "function descuentoPersonas(precio, personas){\n var descuentoTotal = 0;\n \n if (personas >= 4 && personas <= 6) {\n descuentoTotal = precio * 5;\n }\n if (personas >= 7 && personas <= 8) {\n descuentoTotal = precio * 10;\n \n }\n if (personas > 8) {\n descuentoTotal = precio * 15;\n }\n return descuentoTotal / 100;\n}", "function nota_promedio(){\n\t\tvar sum = 0;\n\t\tvar pro = 0;\n\t\tfor(num = 0; num < alumnos.length; num ++){\n\t\t\tsum += (alumnos[num].nota);\n\t\t}\n\t\tpro = sum / 10;\n\t\tdocument.getElementById(\"promedio\").innerHTML = \"El Promedio es: <b>\" + pro.toFixed(2) + \"</b>\";\n\t}", "function convertiraPesos(precioDolares){\n\n const TRM=3932; // 3932 pesos equivalen a 1 dolar\n let precioPesos=precioDolares*TRM;\n\n return precioPesos;\n\n\n}", "function percent(totaleDati){\n var fatturato = 0; //Variabile vuota pari a 0, dove aggiungero il risulato e riporterò fuori con il return\n for (var i = 0; i < totaleDati.length; i++) {\n var datoSingolo = totaleDati[i];\n var valoreDato = datoSingolo.amount;\n fatturato += parseInt(valoreDato);\n }\n return fatturato;\n}", "getGananciaPromedio() {\n let sum = 0;\n this.ganancias.forEach(num => {\n sum += num;\n });\n return sum / this.ganancias.length\n }", "pago_TotalSinPenalizacion(depto){\n let sumatoriaPagoColaboradores =0;\n let pagoPorColaborador= this.pago_total(this.depto, this.dias);\n let pagoTotal =[];\n\n\n if( depto=='Mantenimiento Edificios' || depto=='Silo Molino' || depto=='Bono TYG'|| depto == 'Placa' || depto=='Molienda' || depto == 'Molino' || depto =='Mcs Frame' || depto =='Kbrs' || depto =='Electrolux' || depto =='Commscope' || depto=='AOS Mith' || depto=='Aligerante' || depto=='CEDI' || depto=='Chofer Local' || depto =='PreExpansion' || depto == 'Mantenimiento' || depto == 'Bloquera' || depto == 'Moldeo' || depto=='Almacén' || depto =='Almacen' || depto=='Almacen Const' || depto=='Almacen CEDI' || depto=='Almacen Playa' || depto =='Choferes' || depto =='Choferes Locales' || depto == 'Choferes CEDI' || depto =='Corte' || depto =='Steelfoam' || depto == 'Insulpanel' || depto == 'RotuladoT1' || depto =='PreexpYMoldeo' || depto =='Recupera' || depto=='Molienda de MR' || depto=='Hielera' || depto=='CorteConst' || depto=='CorteMaquila' || depto == 'Vitro' || depto == 'EMCO' || depto=='Corte NIP' || depto=='Corte L' || depto=='Herramental'|| depto=='Rotulado Hielera 1' || depto=='Rotulado Hielera 2' || depto=='Rotulado Hielera 3' || depto=='Rotulado' || depto=='Construpanel' || depto=='Empaque Perla'){\n for(var i=0; i<pagoPorColaborador.length; i++){\n sumatoriaPagoColaboradores = sumatoriaPagoColaboradores + pagoPorColaborador[i];\n }\n pagoTotal = sumatoriaPagoColaboradores;\n\n }else{ //depto corte\n // let pagoTiempoExtra = this.pago_TiempoExtra(this.tiempo_extra,this.factor_dias_laborados, this.dias);\n\n for(var i=0; i<pagoPorColaborador.length; i++){\n sumatoriaPagoColaboradores = sumatoriaPagoColaboradores + pagoPorColaborador[i];\n }\n \n pagoTotal = sumatoriaPagoColaboradores //+ pagoTiempoExtra ;\n }\n\n \n return pagoTotal;\n }", "function obtenerTotalAfiliados()\r\n {\r\n let porcentajeMujeres = Math.round((EPS.afiliados.totalMujeres*100)/totalAfiliados);\r\n let porcentajeHombres = Math.round((EPS.afiliados.totalHombres*100)/totalAfiliados);\r\n console.log(`Total de afiliados a la EPS -> ${totalAfiliados}`);\r\n console.log(`Porcentaje Mujeres -> ${porcentajeMujeres}%`);\r\n console.log(`Porcentaje Hombres -> ${porcentajeHombres}%`);\r\n }", "function getPelnas() {\n let pajamos = 12500;\n let islaidos = 7500;\n return pajamos - islaidos;\n}", "function calculoValor(porcentagem){\r\n var apareceTela = document.getElementById(\"valor\")\r\n apareceTela.innerHTML = `<p class='small-title'>Valor</p>`\r\n\r\n var total = slider.value * 1000\r\n var valorFinal = 0\r\n var percent = 0\r\n for(var j in porcentagem){\r\n percent = porcentagem[j]/100\r\n valorFinal = total * percent\r\n apareceTela.innerHTML += `<p>${valorFinal.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'})}</p>`\r\n }\r\n\r\n var porcentagemTela = document.getElementById(\"porcentagem\")\r\n var valorPorcentagem = 0\r\n porcentagemTela.innerHTML += `<p class='small-title'>Alocação</p>`\r\n for(var k in porcentagem){\r\n valorPorcentagem = porcentagem[k]\r\n porcentagemTela.innerHTML += `<p>${valorPorcentagem}%</p>`\r\n //console.log(valorPorcentagem)\r\n }\r\n\r\n }", "function puntuacion()\n{\n\tvar punt=0;\n\n\t//Aqui utilizamos el metodo search de la clase array,\n\tif($(\"#mensaje\").text().search(\"Perdiste\")!=-1)\n\t\tpunt = (aciertos*5)/palabras[num].length;\n\telse\n\t{\n\t\tpunt=5;\n\t\tpunt+=(vidas*0.25);\n\t\tif(h==0 && m <1)\n\t\t\tpunt+=3;\n\t\telse if(h==0 && m==1 && s<30)\n\t\t\tpunt+=2;\n\t\telse if(h==0 && m <2)\n\t\t\tpunt+=1;\n\t}\n\t//aqui utilizamos el metodo toFixed de la clase number.\n\treturn \" Puntuacion: \"+punt.toFixed(2);\n}", "function calculaPorcentaje(totalParcial,porcentaje){\n\tvar montoPorcentual= (porcentaje*totalParcial)/100;\n\treturn montoPorcentual;\n}", "calculatePercantage() {\n var difference = this.maxAdi - this.minAdi;\n var precentage = Number((this.props.ADI * 100 / difference) + 50);\n return precentage;\n }", "function getPrimes(){\n if(puissanceFiscale==2){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"37.601\")\n }else if(puissanceFiscale>=3 && puissanceFiscale<=6){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"45.181\")\n }else if(puissanceFiscale>=7 && puissanceFiscale<=10){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"51.078\")\n }else if(puissanceFiscale>=11 && puissanceFiscale<=14){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"65.677\")\n }else if(puissanceFiscale>=15 && puissanceFiscale<=23){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"86.456\")\n }else if(puissanceFiscale>=24){\n writeData(\"prime_pack_mini\",\"prime_pack_classique\",\"prime_pack_liberte\",\"prime_pack_confort\",\"104.143\")\n }\n }", "function calcularPromedio() {\n const notas = [];\n let suma = 0;\n const notaParcial1 = prompt('Ingrese nota del primer parcial');\n const notaParcial2 = prompt('Ingrese nota del segundo parcial');\n const notaProyectoFinal = prompt('Ingrese nota del proyecto final');\n\n notas.push(notaParcial1);\n notas.push(notaParcial2);\n notas.push(notaProyectoFinal);\n\n for (let indice = 0; indice < notas.length; indice++) {\n // const element = notas[indice];\n suma = suma + parseInt(notas[indice]);\n }\n\n const promedio = suma / notas.length;\n\n if (promedio >= 6) {\n console.log('Aprobó la materia');\n } else {\n console.log('Desaprobó la materia 😣');\n }\n\n console.log(notas);\n\n}", "function calcPerc(reservoir_gallons, reservoir_capacity) {\n // store length of gallons array passed into this function\n var length = reservoir_gallons.length;\n // initialize variables\n var i, percents = [];\n // loop through all gallon values from the array passed in\n for(i = 0; i < length; i++) {\n percents.push(((reservoir_gallons[i]/reservoir_capacity)*100).toFixed(2));\n } // ends loop through each gallon increments\n // return the percentages\n return percents;\n} // ends calPerc function" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse pageText for get content of html tag with id = id.
function gval(id, pageText){ var startText = pageText.slice(pageText.indexOf(id)); startText = startText.slice(startText.indexOf(">")+1,startText.indexOf("<")); return startText.replace(/[^0-9]/g, ''); }
[ "function getInnerHTMLById(id, responseText){\n\tvar tagName = document.getElementById(id).nodeName.toLowerCase();\n var startTagName = \"<\" + tagName;\n\tvar finishTagName = \"</\" + tagName;\n\tvar startPos = responseText.indexOf('>', responseText.indexOf('id=\"' + id + '\"'));\n\tvar startPosTemp = startPos;\n\tvar finishPos = startPos;\n\t\n\tdo{\n\t startPosTemp = responseText.indexOf(startTagName, startPosTemp + 1);\n\t finishPos = responseText.indexOf(finishTagName, finishPos + 1);\n\t} while (startPosTemp != -1 && startPosTemp < finishPos);\n\n\treturn responseText.substring(startPos + 1, finishPos);\n }", "parsePageContent() {\n var taskTitleElement;\n\n taskTitleElement = this._getElementByXpath('//*[@id=\"content\"]/h2');\n if (taskTitleElement) {\n let matches = taskTitleElement.innerHTML.match(/#([0-9]+)/);\n if (matches && matches[1]) {\n this.taskTitleElement = taskTitleElement;\n this.issueId = matches[1];\n this.logger.log('Find issue #' + this.issueId);\n } else {\n this.logger.log('regexp doesnt match any issue number in: ' + taskTitleElement.innerHTML);\n }\n } else {\n this.logger.log('task title doesnt exist');\n }\n }", "parse () {\n const place = [];\n const texts = [];\n const ids = {};\n\n const htmlParser = new htmlparser2.Parser({\n onopentag(tagname, attributes) {\n let id = uuid();\n\n ids[id] = {\n id: id,\n tag: tagname.toLowerCase(),\n attributes: attributes,\n text: null,\n descendants: []\n };\n\n // add it to all ancestors\n place.forEach(anscestorId => {\n ids[anscestorId].descendants.push(id);\n });\n\n place.push(id);\n },\n ontext(text) {\n texts.push(text.trim());\n },\n onclosetag() {\n let id = place.pop();\n\n if (id && (typeof ids[id] !== 'undefined')) {\n ids[id].text = texts.pop();\n }\n }\n });\n\n htmlParser.write(this.html);\n\n this.items = Object.values(ids);\n }", "parse(html, id, asHtml) {\r\n\t\t//return html;\r\n\t\t//console.log(\"=====================\");\r\n\t\t//console.log(`in: \"${html}\"`);\r\n\t\tif (!this.fixVizAscii) \r\n\t\t\treturn html;\r\n\t\tif (debug)\r\n\t\t\tconsole.log(`html: \"${html}\", id:\"${id}\"`);\r\n\t\tif (!asHtml) {\r\n\t\t\tif (html == \"\") \r\n\t\t\t\treturn \"\";\r\n\t\t\tvar w;\r\n\t\t\tvar out = \"\";\r\n\t\t\tvar first = true;\r\n\t\t\tthis.content = html.split(erBN);\t\t\t\r\n\t\t\tfor (var line of this.content) {\r\n\t\t\t\tif (this.fixVizAsciiAlways || !isAscii(line)) {\r\n\t\t\t\t\tif (first)\r\n\t\t\t\t\t\t first = false;\r\n\t\t\t\t\telse out +=\"\\\\n\";\r\n\t\t\t\t\tw = this.width(line);\r\n\t\t\t\t\tline = this.code(w);\r\n\t\t\t\t\tout += line;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.nodeFix[id] = this.content; \r\n\t\t\treturn out;\r\n\t\t}\t\t\t\r\n\t\thtml = \"<P>\" + html + \"</P>\"; \r\n\t\r\n\t\tvar parser = new DOMParser();\r\n\t\tvar xmlDoc = parser.parseFromString(html, \"text/xml\");\r\n\t\tif (debug)\r\n\t\t\tconsole.log(\"xmlDoc\", xmlDoc);\r\n\t\tthis.level = 1;\r\n\t\tthis.id = id;\r\n\t\tthis.parseNode(xmlDoc.childNodes[0]);\r\n\t\tout = this.outerHTML(xmlDoc);\r\n\t\tout = out.slice(3,-4); // remove initial tag \"P\"\r\n\t\tif (out == \"<>\") out = '\"\"';\r\n\t\t//console.log(`out: \"${out}\"`);\r\n\t\treturn out;\r\n\t}", "static getContent(id) {\n\t\treturn document.getElementById(id).textContent;\n\t}", "static async grabDataInnerText(page, selector) {\n try {\n let element = null;\n element = await HtmlExtractor.getSingleSelector(selector, page);\n const data = await page.evaluate(ele => ele.textContent, element);\n return data.trim();\n } catch (e) {\n // this.logger('error', 'Error while fetching data from HTML innerText', e)\n console.log('error', 'Error while fetching data from HTML innerText', e);\n return null;\n }\n }", "async function parsePageContent(html, url, category) {\n const { document } = new JSDOM(html, { runScripts: 'dangerously' }).window;\n const title = document.querySelector('h1').textContent;\n let section;\n let order = 0;\n\n document.querySelectorAll('h1, h3, p').forEach((element) => {\n if (element.tagName === 'P') {\n if (element.textContent[0] === '<') {\n return;\n }\n\n category.items[category.items.length - 1].description += element.textContent + '\\n';\n } else {\n section = {\n title,\n description: '',\n order,\n url\n };\n\n if (element.tagName === 'H3') {\n section.subtitle = element.textContent;\n section.hash = element.id;\n }\n\n category.items.push(Object.assign({ objectID: slugify(`${section.title} ${order} ${section.subtitle || ''}`) }, section));\n order += 1;\n }\n });\n}", "function getTextById (id) {\n return $(\"#\" + id).text();\n}", "function parseHtml(html){\n //document.querySelector=> $\n console.log(\"````````````````````````````````````````\");\n let d = cheerio.load(html);\n let itemWrapper = d(\".item-wrapper .description\");\n let text = d(itemWrapper[0]).text();\n // let text = headings.text();\n console.log(text);\n}", "async parse(element) {\n const reshtml = await this.getPage()\n const dom = new JSDOM(reshtml)\n\n /*\n element structure:\n <div id=enc-abstract>\n <p>\n ...Abstract text\n </p>\n </div>\n\n get back just the text within the <p> element in #enc-abstract element on page\n */\n \n if(dom.window.document.body.querySelector(element)) {\n const htmlabs = dom.window.document.querySelector(element).textContent\n \n // trim out unnecessary lines\n const abstract = htmlabs.split('\\n').join('').split(' ').join('')\n if(abstract.length == 0) \n return ''\n else\n return abstract\n }\n else\n return ''\n }", "function ParseTextAsHTML(rawHTML, id, stripJavaScript) {\n var returnString = \"\";\n // see https://www.w3schools.com/xml/xml_parser.asp \n // and see https://www.w3schools.com/xml/dom_intro.asp\n var parser = new DOMParser();\n if (parser) {\n var xmlDoc = parser.parseFromString(rawHTML, \"text/html\");\n if (xmlDoc && xmlDoc.body !== undefined && id !== undefined) {\n switch (id) {\n case 'body':\n returnString = xmlDoc.body.innerHTML;\n break;\n case 'head':\n returnString = xmlDoc.head.innerHTML;\n break;\n default:\n var XMLFragment = xmlDoc.getElementsByTagName(id);\n if (XMLFragment && XMLFragment.length > 0) {\n returnString = XMLFragment[0].innerHTML;\n }\n else {\n // XML has an error in it\n console.log(`HTML document has an improperly closed tag such as a <br>, an <img> etc.`);\n }\n break;\n }\n }\n }\n else {\n console.log(`Cannot parse fragment as XML`);\n console.log(rawXML);\n }\n if (stripJavaScript) {\n const scriptTagClose = '</script>';\n // see https://www.w3schools.com/jsref/jsref_search.asp\n var startPoint = returnString.search(/<script/i);\n while (startPoint > 0) {\n // see https://www.w3schools.com/jsref/jsref_indexof.asp\n var endPoint = returnString.toLowerCase().indexOf(scriptTagClose,startPoint +2) ;\n // see https://www.w3schools.com/jsref/jsref_substring.asp\n if (endPoint > 0){\n returnString = returnString.substring(0,startPoint) + returnString.substring(endPoint +scriptTagClose.length +1);\n }\n else {\n returnString = returnString.substring(0,startPoint)\n }\n // Are there any more script tags in the HTML?\n startPoint = returnString.search(/<script>/i);\n }\n }\n return returnString;\n}", "function parseHtml(html) {\n // document.querySelector=> $\n console.log(\"`````````````````````````````````````````````````````````\");\n let d = cheerio.load(html);\n let itemWrapper = d(\".item-wrapper .description\");\n let text = d(itemWrapper[0]).text();\n // let text = headings.text();\n console.log(text);\n}", "function getTextById(id) {\n return document.getElementById(id).textContent;\n}", "function extractContentHtml(htmlText){\n var n = -1; \n var m = -1;\n var innerText;\n var tagText;\n \n //TODO: se puede refactorizar mas XXD\n htmlText = performReplace(\"<body>\",\"</body>\",htmlText);\n htmlText = performReplace(\"<html>\",\"</html>\",htmlText);\n htmlText = performReplace(\"<div>\",\"</div>\",htmlText);\n htmlText = performReplace(\"<title>\",\"</title>\",htmlText); \n htmlText = performReplace(\"<head>\",\"</head>\",htmlText); \n return htmlText;\n \n //Reemplaza todas las etiquetas div iguales de un texto\n function performReplace(tag1,tag2,text)\n {\n var iFlag = false;\n var replaced = text;\n while (iFlag == false){\n if(thereIsTag(tag1,text))\n {\n text = replaceTag(tag1,tag2,text);\n }else\n {\n iFlag = true;\n }\n }\n return text;\n }\n \n //comprobar q exista la etiqueta\n function thereIsTag(tag,text){\n n = text.indexOf(tag);\n if (n != -1)\n {\n return true;\n }\n return false;\n }\n \n //realiza el reemplazo de una sola etiqueta\n function replaceTag(tag1,tag2,text)\n {\n n = text.indexOf(tag1);\n m = text.indexOf(tag2);\n innerText = text.substring( n+tag1.length,m);\n tagText = text.substring(n , m+tag2.length);\n text = text.replace(tagText,innerText);\n return text;\n }\n}", "function getTextById (id) {\n return document.getElementById(id).textContent;\n}", "getInnerTextById(id) {\n let element = document.getElementById(id)\n if (!element)\n return null;\n return element.innerText;\n }", "function getPageContent(pageId){\n\n // Content for each navigation link.\n var intros = {\n home: \"Welcome to the home page.\",\n about: \"This is the About page.\",\n contact: \"This is the Contact page.\"\n };\n return intros[pageId];\n}", "function paginationGetBody(id)\n\t\t{ return($('#'+id).children('.paginationBody').first()); }", "function ParseTextAsXML(rawXML, id) {\r\n // debugger;\r\n var returnString = \"\";\r\n // see https://www.w3schools.com/xml/xml_parser.asp \r\n var parser = new DOMParser();\r\n if (parser) {\r\n var xmlDoc = parser.parseFromString(rawXML, \"text/xml\");\r\n if (xmlDoc && id !== undefined) {\r\n var XMLFragment = xmlDoc.getElementsByTagName(id);\r\n if (XMLFragment && XMLFragment.length > 0) {\r\n returnString = XMLFragment[0].innerHTML;\r\n }\r\n }\r\n }\r\n else {\r\n console.log(`Cannot parse fragment as XML`);\r\n console.log(rawXML);\r\n }\r\n return returnString;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets and highlights a time part.
_getAndHighlightTimePart(matchIndex, regExpIndex, index) { const that = this; that._programmaticSelection = true; if (that.$.input.selectionStart !== matchIndex || that.$.input.selectionEnd !== regExpIndex) { that.$.input.setSelectionRange(matchIndex, regExpIndex); } else { setTimeout(function () { that.$.input.setSelectionRange(matchIndex, regExpIndex); }, 200); } that._highlightedTimePart = { code: that._formatStringRegExp.groups[index], index: index, from: matchIndex, to: regExpIndex }; }
[ "function getHighlightedWords() {\n // get current Time\n const date = new Date();\n var hour = date.getHours();\n var minute = date.getMinutes();\n \n // get fixed time if set in config/params\n if (widget_config.fixedTime != \"\"){\n console.log(\"actual time: \" + hour + \":\" + minute)\n hour = Number(widget_config.fixedTime.split(\":\")[0])\n minute = Number(widget_config.fixedTime.split(\":\")[1])\n console.log(\"fixed time set: \" + hour + \":\" + minute)\n }\n\n // apply offset\n minute = minute + widget_config.offset_minutes\n if (minute >= 60) {\n minute = minute % 60\n hour = hour + 1\n }\n\n \n if (widget_config.dot_view === true){\n setDotDisplayLayout(hour);\n return onOffMap;\n }\n \n // get minute to display\n minute = minute - (minute % 5)\n\n // highlight IT & IS\n onCells(time_map.i);\n\n\n // check, if special format applies\n if (typeof(time_map.c[hour]) != \"undefined\") {\n if (typeof(time_map.c[hour][minute]) != \"undefined\") {\n \n onCells(time_map.c[hour][minute]);\n return onOffMap;\n }\n }\n\n if (minute >= hour_display_limit) {\n hour = hour + 1;\n }\n\n // trim hours by 12 if needed\n if (Object.keys(time_map.e).length == 12) {\n hour = hour % 12;\n }\n else {\n hour = hour % 24;\n }\n\n // display minute\n onCells(time_map.d[minute]);\n\n // display hour\n onCells(time_map.e[hour])\n\n\n return onOffMap;\n}", "_highlightTimePartBasedOnCursor(caretPosition) {\n const that = this,\n inputValue = that.$.input.value,\n matches = that._formatStringRegExp.regExp.exec(inputValue);\n\n function getCaretPosition() {\n if (caretPosition === undefined) {\n return that.$.input.selectionStart;\n }\n\n return caretPosition;\n }\n\n if (matches === null) {\n that._highlightedTimePart = undefined;\n return;\n }\n\n if (!that._iOS && caretPosition === undefined) {\n caretPosition = that.$.input.selectionStart;\n }\n\n let regExpIndex = matches.index,\n matchIndex;\n\n for (let i = 1; i < matches.length; i++) {\n const match = matches[i];\n\n matchIndex = inputValue.indexOf(match, regExpIndex);\n regExpIndex = matchIndex + match.length;\n\n if (i === 1 && getCaretPosition() < matchIndex) {\n that._getAndHighlightTimePart(matchIndex, regExpIndex, 0);\n break;\n }\n\n if (getCaretPosition() >= matchIndex && getCaretPosition() <= regExpIndex) {\n that._getAndHighlightTimePart(matchIndex, regExpIndex, i - 1);\n break;\n }\n\n const nextMatch = matches[i + 1];\n\n if (nextMatch) {\n const indexOfNextMatch = inputValue.indexOf(nextMatch, regExpIndex);\n\n if (getCaretPosition() > regExpIndex && getCaretPosition() < indexOfNextMatch) {\n if (getCaretPosition() - regExpIndex <= indexOfNextMatch - getCaretPosition()) {\n that._getAndHighlightTimePart(matchIndex, regExpIndex, i - 1);\n }\n else {\n that._formatStringRegExp.groups[i];\n that._programmaticSelection = true;\n that.$.input.setSelectionRange(indexOfNextMatch, indexOfNextMatch + nextMatch.length);\n }\n break;\n }\n }\n else {\n that._programmaticSelection = true;\n that.$.input.setSelectionRange(matchIndex, regExpIndex);\n that._highlightedTimePart = {\n code: that._formatStringRegExp.groups[i - 1],\n index: i - 1,\n from: matchIndex,\n to: regExpIndex\n };\n break;\n }\n }\n }", "buildTimeRailHighlight() {\n if (this.highlightRail) {\n const t = this.mejsTimeRailHelper.calculateSegmentT(\n this.segmentsMap[this.activeSegmentId],\n this.currentStreamInfo\n );\n\n // Create our custom time rail highlighter element\n this.highlightSpanEl = this.mejsTimeRailHelper.createTimeHighlightEl(\n document.getElementById('content')\n );\n this.highlightTimeRail(t, this.activeSegmentId);\n }\n }", "function highlightText(time){\n for(i = 0; i < all; i++){\n if(time >= timestamps[i].start && time <= timestamps[i].end){\n timestamps[i].elm.addClass('highlight');\n } else {\n timestamps[i].elm.removeClass('highlight');\n }\n }\n}", "_navigateToNextTimePart() {\n const that = this;\n\n that._highlightTimePartBasedOnIndex(that._highlightedTimePart.index + 1);\n }", "function highlight(time){\n\tonAnn.forEach(function (e, i, a) {\n\t\t$('#' + e.displayID).removeClass(\"highlighted\");\n\t\tunhighlightTick(e);\n\t});\n\tonAnn = [];\n\tfor (i = 0; i < annotations.length; i++) {\n\t\tif (annotations[i].timestamp == time) {\n\t\t\t$('#' + annotations[i].displayID).addClass(\"highlighted\");\n\t\t\tscrollToAnnotation(annotations[i]);\n\t\t\thighlightTick(annotations[i]);\n\t\t\tonAnn.push(annotations[i]);\n\t\t}\n\t}\n}", "function highlightByHour() {\n var currentHour = moment().hours();\n currentHour = $(\".text-row\").each(function () {\n var blockHour = parseInt($(this).attr(\"id\"));\n\n if (blockHour < currentHour) {\n $(this).addClass(\"past\");\n } else if (blockHour == currentHour) {\n $(this).removeClass(\"past\");\n $(this).addClass(\"present\");\n } else {\n $(this).removeClass(\"past\");\n $(this).removeClass(\"present\");\n $(this).addClass(\"future\");\n }\n });\n}", "function highlightPastTime() {\n let today = moment();\n\n // Get day of the week, Monday = 1; Sunday = 7\n let day = today.isoWeekday();\n let hours = today.hours();\n let currentTimeRange;\n\n // Sunday and after 10 p.m.\n if (day === SUN && hours === 22) {\n day = 0;\n hours = 1;\n }\n // Convert the current time to the time range index we used in the table\n currentTimeRange = hours - 8;\n\n for (let col = MON; col < day; col++) {\n for (let row = 0; row <= 14; row++) {\n // Before 8 a.m.\n if (col === day - 1 && currentTimeRange < 0) {\n break;\n }\n // Generate the element selector\n let selectedSession = '#slot-' + col + '-' + row;\n $(selectedSession).addClass('bg-danger');\n // Reach current hour\n if (col === day - 1 && row === currentTimeRange) {\n break;\n }\n }\n }\n}", "function getHighlightedWords() {\n // The dimensions of this should match the dimensions of\n // TIME_WORDS_MATRIX\n const defaultHighlights = [\n [true, true, false, false],\n [false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, true],\n ];\n\n const date = new Date();\n let hour = date.getHours();\n const minute = date.getMinutes();\n\n if (minute <= 30) {\n // highlight \"past\"\n defaultHighlights[3][0] = true;\n } else {\n // highlight \"to\"\n defaultHighlights[2][2] = true;\n // increment hour\n hour = hour + 1;\n }\n\n if (minute >= 5 && minute < 10) {\n // highlight \"five\"\n defaultHighlights[2][0] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 10 && minute < 15) {\n // highlight \"ten\"\n defaultHighlights[0][3] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 15 && minute < 20) {\n // highlight \"quarter\"\n defaultHighlights[1][0] = true;\n } else if (minute >= 20 && minute < 25) {\n // highlight \"twenty\"\n defaultHighlights[1][1] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 25 && minute < 30) {\n // highlight \"twenty\"\n defaultHighlights[1][1] = true;\n // highlight \"five\"\n defaultHighlights[2][0] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 30 && minute < 35) {\n // highlight \"half\"\n defaultHighlights[0][2] = true;\n } else if (minute >= 35 && minute < 40) {\n // highlight \"twenty\"\n defaultHighlights[1][1] = true;\n // highlight \"five\"\n defaultHighlights[2][0] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 40 && minute < 45) {\n // highlight \"twenty\"\n defaultHighlights[1][1] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 45 && minute < 50) {\n // highlight \"quarter\"\n defaultHighlights[1][0] = true;\n } else if (minute >= 50 && minute < 55) {\n // highlight \"ten\"\n defaultHighlights[0][3] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 55) {\n // highlight \"five\"\n defaultHighlights[2][0] = true;\n // highlight \"minutes\"\n defaultHighlights[2][1] = true;\n }\n \n if (hour > 12) {\n hour = hour - 12;\n }\n\n if (hour === 1) {\n defaultHighlights[4][0] = true;\n } else if (hour === 2) {\n defaultHighlights[3][1] = true;\n } else if (hour === 3) {\n defaultHighlights[3][2] = true;\n } else if (hour === 4) {\n defaultHighlights[4][1] = true;\n } else if (hour === 5) {\n defaultHighlights[4][2] = true;\n } else if (hour === 6) {\n defaultHighlights[5][0] = true;\n } else if (hour === 7) {\n defaultHighlights[5][1] = true;\n } else if (hour === 8) {\n defaultHighlights[5][2] = true;\n } else if (hour === 9) {\n defaultHighlights[6][0] = true;\n } else if (hour === 10) {\n defaultHighlights[6][1] = true;\n } else if (hour === 11) {\n defaultHighlights[6][2] = true;\n } else if (hour === 12) {\n defaultHighlights[7][0] = true;\n } \n\n return defaultHighlights;\n}", "function colorCode() {\n var currentTime = moment().hours();\n\n $(\".time-block\").each(function () {\n var timeBlock = parseInt($(this).attr(\"id\").split(\"-\")[0]);\n\n if (timeBlock === currentTime) {\n $(this).addClass(\"present\");\n }\n else if (timeBlock < currentTime) {\n $(this).addClass(\"past\");\n }\n else {\n $(this).addClass(\"future\");\n }\n });\n }", "function getHighlightedWords() {\n // The dimensions of this should match the dimensions of\n // TIME_WORDS_MATRIX\n const defaultHighlights = [\n [true, true],\n [false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, false, false],\n [false, false],\n ];\n\n const date = new Date();\n let hour = date.getHours();\n const minute = date.getMinutes();\n\n if (minute>=5 && minute<20) {\n // highlight \"nach\"\n defaultHighlights[2][2] = true;\n } else if (minute >=20 && minute<30) {\n // highlight \"vor\"\n defaultHighlights[3][0] = true;\n // increment hour\n hour = hour + 1;\n } else if (minute>=30 && minute<35) {\n // increment hour\n hour = hour + 1;\n } else if (minute>35 && minute<45) {\n // highlight \"nach\"\n defaultHighlights[2][2] = true;\n // increment hour\n hour = hour + 1;\n } else if (minute>=45 && minute<50) {\n // increment hour\n hour = hour + 1;\n } else if (minute>50 && minute<=59) {\n // highlight \"vor\"\n defaultHighlights[3][0] = true;\n // increment hour\n hour = hour + 1;\n }\n\n if (minute >= 5 && minute < 10) {\n // highlight \"fünf\"\n defaultHighlights[2][1] = true;\n } else if (minute >= 10 && minute < 15) {\n // highlight \"zehn\"\n defaultHighlights[2][0] = true;\n } else if (minute >= 15 && minute < 20) {\n // highlight \"viertl\"\n defaultHighlights[1][1] = true;\n } else if (minute >= 20 && minute < 25) {\n // highlight \"zehn\"\n defaultHighlights[2][0] = true;\n // highlight \"halb\"\n defaultHighlights[3][1] = true;\n } else if (minute >= 25 && minute < 30) {\n // highlight \"fünf\"\n defaultHighlights[2][1] = true;\n // highlight \"halb\"\n defaultHighlights[3][1] = true;\n } else if (minute >= 30 && minute < 35) {\n // highlight \"half\"\n defaultHighlights[3][1] = true;\n } else if (minute >= 35 && minute < 40) {\n // highlight \"fünf\"\n defaultHighlights[2][1] = true;\n // highlight \"halb\"\n defaultHighlights[3][1] = true;\n } else if (minute >= 40 && minute < 45) {\n // highlight \"zehn\"\n defaultHighlights[2][0] = true;\n // highlight \"halb\"\n defaultHighlights[3][1] = true;\n } else if (minute >= 45 && minute < 50) {\n // highlight \"dreiviertel\"\n defaultHighlights[1][0] = true;\n defaultHighlights[1][1] = true;\n } else if (minute >= 50 && minute < 55) {\n // highlight \"zehn\"\n defaultHighlights[2][0] = true;\n } else if (minute >= 55) {\n // highlight \"fünf\"\n defaultHighlights[2][1] = true;\n }\n \n if (hour > 12) {\n hour = hour - 12;\n }\n\n if (hour === 1) {\n defaultHighlights[4][0] = true;\n } else if (hour === 2) {\n defaultHighlights[5][0] = true;\n } else if (hour === 3) {\n defaultHighlights[5][2] = true;\n } else if (hour === 4) {\n defaultHighlights[7][1] = true;\n } else if (hour === 5) {\n defaultHighlights[3][2] = true;\n } else if (hour === 6) {\n defaultHighlights[4][1] = true;\n } else if (hour === 7) {\n defaultHighlights[7][0] = true;\n } else if (hour === 8) {\n defaultHighlights[5][1] = true;\n } else if (hour === 9) {\n defaultHighlights[6][2] = true;\n } else if (hour === 10) {\n defaultHighlights[6][1] = true;\n } else if (hour === 11) {\n defaultHighlights[4][2] = true;\n } else if (hour === 12) {\n defaultHighlights[6][0] = true;\n } \n\n return defaultHighlights;\n}", "function inspectOnTime(item, tab=SP, lf=BR, ind=0) {\n let str = tabs(ind, tab) + MSG.set_tim_title + lf;\n str += tabs(ind + 1, tab) + MSG.set_tim_time + lf;\n if (item.params.times.length == 0) {\n str += tabs(ind + 2, tab) + MSG.set_tim_none + lf;\n return str;\n }\n item.params.times.forEach(function(time, i) {\n str += tabs(ind + 2, tab) + time + lf;\n });\n return str;\n}", "_highlightTimePartBasedOnIndex(index) {\n const that = this,\n inputValue = that.$.input.value,\n matches = that._formatStringRegExp.regExp.exec(inputValue);\n\n if (matches === null) {\n that._validateValue(undefined, that._cloneValue(), false);\n that._highlightTimePartBasedOnIndex(index);\n return;\n }\n\n let regExpIndex = matches.index,\n matchIndex;\n const activeElement = that.shadowRoot ? that.shadowRoot.activeElement : document.activeElement;\n\n if (index < 0 || index >= matches.length) {\n return;\n }\n\n if (that.$.input !== activeElement) {\n that.$.input.focus();\n }\n\n for (let i = 1; i < matches.length; i++) {\n const match = matches[i];\n\n matchIndex = inputValue.indexOf(match, regExpIndex);\n regExpIndex = matchIndex + match.length;\n\n if (index === i - 1) {\n that._getAndHighlightTimePart(matchIndex, regExpIndex, index);\n break;\n }\n }\n }", "_highlightTimePartBasedOnIndex(index) {\n const that = this,\n inputValue = that.$.input.value,\n matches = that._formatStringRegExp.regExp.exec(inputValue);\n\n if (matches === null) {\n that._validateValue(undefined, that._cloneValue(), false);\n that._highlightTimePartBasedOnIndex(index);\n return;\n }\n\n let regExpIndex = matches.index,\n matchIndex;\n const activeElement = that.enableShadowDOM ? that.shadowRoot.activeElement : document.activeElement;\n\n if (index < 0 || index >= matches.length) {\n return;\n }\n\n if (that.$.input !== activeElement) {\n that.$.input.focus();\n }\n\n for (let i = 1; i < matches.length; i++) {\n const match = matches[i];\n\n matchIndex = inputValue.indexOf(match, regExpIndex);\n regExpIndex = matchIndex + match.length;\n\n if (index === i - 1) {\n that._getAndHighlightTimePart(matchIndex, regExpIndex, index);\n break;\n }\n }\n }", "function highlightText() {\n\t//Get current video time\n\tvar highlightTime = vid.currentTime;\n\n\t\t//Highlight span corresponding to current time\n\t\tfunction toggleHighlight(n) {\n\t\t\t// Removed highlight from any unclicked text\n\t\t\tfor (var i=0; i < cues.length; i++) {\n\t\t\t\tcues[i].classList.remove(\"highlighted\");\n\t\t\t}\n\t\t\t//Add highlighted class\n\t\t\tcues[n].classList.add('highlighted');\n\t\t}\n\n\t\tif (highlightTime > 0 && highlightTime < 4.13) {\n\t\t\ttoggleHighlight(0);\n\t\t} else if (highlightTime > 4.13 && highlightTime < 7.535) {\n\t\t\ttoggleHighlight(1);\n\t\t} else if (highlightTime > 7.535 && highlightTime < 11.27) {\n\t\t\ttoggleHighlight(2);\n\t\t} else if (highlightTime > 11.27 && highlightTime < 13.96) {\n\t\t\ttoggleHighlight(3);\n\t\t} else if (highlightTime > 13.96 && highlightTime < 17.94) {\n\t\t\ttoggleHighlight(4);\n\t\t} else if (highlightTime > 17.94 && highlightTime < 22.37) {\n\t\t\ttoggleHighlight(5);\n\t\t} else if (highlightTime > 22.37 && highlightTime < 26.88) {\n\t\t\ttoggleHighlight(6);\n\t\t} else if (highlightTime > 26.88 && highlightTime < 32.1) {\n\t\t\ttoggleHighlight(7);\n\t\t} else if (highlightTime > 32.1 && highlightTime < 34.73) {\n\t\t\ttoggleHighlight(8);\n\t\t} else if (highlightTime > 34.73 && highlightTime < 39.43) {\n\t\t\ttoggleHighlight(9);\n\t\t} else if (highlightTime > 39.43 && highlightTime < 42.35) {\n\t\t\ttoggleHighlight(10);\n\t\t} else if (highlightTime > 42.35 && highlightTime < 46.3) {\n\t\t\ttoggleHighlight(11);\n\t\t} else if (highlightTime > 46.3 && highlightTime < 49.27) {\n\t\t\ttoggleHighlight(12);\n\t\t} else if (highlightTime > 49.27 && highlightTime < 53.76) {\n\t\t\ttoggleHighlight(13);\n\t\t} else if (highlightTime > 53.76 && highlightTime < 57.78 ) {\n\t\t\ttoggleHighlight(14);\n\t\t}\n}", "function colorTime() {\n var textBlocks = $(document).find('textarea');\n var rightNow = Number(moment().format('k'));\n\n for (var i = 0; i < textBlocks.length; i++){\n\n switch(true){\n case (textBlocks[i].dataset.time < rightNow):\n $(textBlocks[i]).addClass('past');\n break;\n case (textBlocks[i].dataset.time == rightNow):\n $(textBlocks[i]).addClass('present');\n break;\n case (textBlocks[i].dataset.time > rightNow):\n $(textBlocks[i]).addClass('future');\n }\n }\n if (rightNow == 24 && textBlocks[0].dataset.time == 0) {\n $(textBlocks[0]).addClass('present');\n }\n}", "function highlightSchedule()\n{\n // Set the current schedule position\n const current = new Date();\n\n var h = current.getHours();\n var m = current.getMinutes();\n\n let needs_highlighting = document.getElementsByClassName(\"schedule-time\");\n var highlight_index = -1;\n for(i = 0; i < needs_highlighting.length;i++) {\n needs_highlighting[i].parentElement.className = \"\";\n var time = needs_highlighting[i].innerHTML;\n if(time === \"|\") continue;\n var hour = parseInt(time.substr(0, 2));\n var mins = parseInt(time.substr(3, 2));\n // if the current time hasn't reached this part yet\n if(hour > h || hour == h && mins > m) {\n break;\n }\n highlight_index++;\n }\n if(highlight_index < 0) return;\n needs_highlighting[highlight_index].parentElement.className = \"active\";\n console.log(highlight_index);\n}", "function showsection(t){\n for(i=0;i<all;i++){\n if(t >= timestamps[i].start && t <= timestamps[i].end){\n timestamps[i].elm.addClass('highlight');\n } else {\n timestamps[i].elm.removeClass('highlight');\n }\n }\n }", "_navigateToPreviousTimePart() {\n const that = this;\n\n that._highlightTimePartBasedOnIndex(that._highlightedTimePart.index - 1);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reload data according to selected bird load birdDate according to filename
function loadData(file) { d3.selectAll('.bird-position').remove(); d3.csv(`data/birds/${file}.csv`) .then(bird => { let timeSlider = initSlider(bird); let currentDate = d3.timeFormat('%Y-%m-%d')(timeSlider.value()); drawBird(bird, currentDate); const playButton = document.querySelector('#play'); birdplayer = BirdPlayer(playButton, bird, timeSlider); map.on('moveend', update); }); }
[ "function loadNewBirds() {\n $('.img-holder').css('background', \"\");\n $('.game-bird').css('opacity', '');\n\n birdFactory.getBirds()\n .then(function(birds){\n birds = birds.data;\n $scope.four = getSome(birds, 4);\n $scope.answer = Math.floor(Math.random() *4);\n $scope.song = $sce.trustAsResourceUrl($scope.four[$scope.answer].song);\n });\n }", "loadNextBird() {\n if (this.nextBird == true) {\n this.birds[this.currentBird].removeFromWorld();\n this.birds.splice(this.currentBird, 1);\n this.birds[this.currentBird].body.isSensor = false;\n this.birds[this.currentBird].body.isStatic = false;\n this.birds[this.currentBird].body.collisionFilter.category = slingshotCategory;\n Body.setPosition(this.birds[this.currentBird].body, {\n x: 300,\n y: 440\n });\n this.constraint.bodyB = this.birds[this.currentBird].body;\n this.nextBird = false;\n }\n }", "loadDB() {\n\n if( !fs.existsSync( this.dbPath ) ) return;\n\n // cargar la informacion\n const info = fs.readFileSync( this.dbPath, {encoding: 'utf-8'});\n \n // parseo de datos a JSON\n const data = JSON.parse( info );\n\n this.historial = data.historial;\n }", "function drawBird(bird, currentDate) {\n bird.forEach(d => {\n if(d.timestamp === currentDate){\n if(d3.select('#'+d['individual-local-identifier']).empty()){ //if bird is not shown on map yet\n d3.select('.leaflet-birds-pane svg') //create a new circle\n .datum(d)\n .append('circle')\n .attr('id', d['individual-local-identifier'])\n .attr('class', 'bird-position')\n .attr('cx', getPosition(d).x)\n .attr('cy', getPosition(d).y)\n .attr('r', 5)\n .style('fill', 'white');\n }\n else { //otherwise just move the existing circle\n const transition = d3.transition()\n .duration(100)\n .ease(d3.easeLinear);\n\n d3.select('#'+d['individual-local-identifier'])\n .transition(transition)\n .attr('cx', getPosition(d).x)\n .attr('cy', getPosition(d).y);\n }\n if(d['last-timestamp-flag'] === \"true\"){ //remove bird once last timestamp was reached\n d3.select('#'+d['individual-local-identifier']).remove();\n }\n }\n })\n\n}", "onFilenameChanged() {\n this.loadImage();\n }", "function reload(files) {\n readFiles(files).then(pList=>{\n compare(pList)\n }).then(fieldSelection)\n }", "function reloadFIlesTable(file_list){\n clearFilesTable();\n\n //skip first two files, current directory and parent directory \n for(var i= 2, len= file_list.length; i<len; i++){\n insertFilesTableRow(file_list[i]);\n }\n }", "reload() {\n\t\tconst data = fs.readFileSync('./file.json', 'utf-8');\n\t\tthis.objects = JSON.parse(data);\n\t}", "function loadDatabaseFileSelector() {\n var selector = $('.data-selector')\n selector.empty()\n fs.readdir(__dirname + '/datastores/', \"ascii\", (err, files) => {\n files.forEach(file => {\n if (file !== 'feynmanDatabase.json') {\n file = file.replace('.json', '')\n if (file === db.getData(\"data_file\")[\"data_file\"]) {\n $('.data-selector').append('<option value=\"' + file + '\">' + file + ' (current)</option>')\n } else {\n $('.data-selector').append('<option value=\"' + file + '\">' + file + '</option>')\n }\n }\n });\n })\n }", "function updateBirdFields(nextBird){\n document.getElementById(\"common-name\").innerHTML = nextBird.common_name;\n document.getElementById(\"scientific-name\").innerHTML = nextBird.scientific_name;\n\n // audio\n let sound = nextBird.sound;\n document.getElementById(\"audio-player\").setAttribute('src', sound.sound_url);\n document.getElementById('audio-caption').innerHTML = sound.sound_name;\n document.getElementById(\"sound-recordist\").innerHTML = sound.sound_recordist;\n document.getElementById(\"sound-info-url\").href = 'https://www.xeno-canto.org/'+sound.xeno_id;\n document.getElementById(\"sound-license-code\").innerHTML = sound.sound_license_code;\n document.getElementById(\"sound-license\").href = sound.sound_license_url;\n\n // image (temp use first image, TODO: add slideshow)\n let image = nextBird.images[0];\n document.getElementById(\"bird-image\").setAttribute('src', image.image_url);\n document.getElementById(\"image-info-url\").href = image.image_info_url;\n document.getElementById(\"image-author\").innerHTML = image.image_author;\n document.getElementById(\"image-license\").innerHTML = image.image_license_code;\n document.getElementById(\"image-license\").href = image.image_license_url;\n let objectPosition = image.image_css_x+\"% \"+image.image_css_y+\"%\";\n document.getElementById('bird-image').style.objectPosition = objectPosition;\n}", "function updateBirds() {\n browser.storage.local.get(STORAGE_LAST_UPDATE_ALL, results => {\n let lastUpdateAll = (results[STORAGE_LAST_UPDATE_ALL] || 0);\n let timeDiffAll = Date.now() - lastUpdateAll;\n // check if we haven't updated the full list in a while.\n if (0 == effinBirds.size || UPDATE_ALL_RATE < timeDiffAll) {\n //console.log(\"Doing a full bird update.\");\n getAllBirds();\n } else {\n browser.storage.local.get(STORAGE_LAST_UPDATE_RECENT, results => {\n let lastUpdate = (results[STORAGE_LAST_UPDATE_RECENT] || 0);\n let timeDiff = Date.now() - lastUpdate;\n // check if we haven't done a partial update in a while.\n if (UPDATE_RECENT_RATE < timeDiff) {\n //console.log(\"Doing a recent bird update.\");\n //getRecentBirds();\n } else {\n // check back when an update is due.\n //console.log(\"Birds are up to date.\");\n window.setTimeout(function() { updateBirds(); }, timeDiff);\n }\n });\n }\n });\n}", "function reloadContent() {\n setupCalender(\n state.currentDate.getFullYear(),\n state.currentDate.getMonth() + 1\n );\n if (state.cutentSelektedDay) {\n populateTodoContainer(new Date(state.cutentSelektedDay));\n } else {\n populateTodoContainer(null);\n }\n}", "onReload() {\n this.loadData();\n }", "function loadBird(birdJSON)\n{\n let bestBird = NeuralNetwork.deserialize(birdJSON);\n bird[0] = new Bird(bestBird);\n}", "static load(patches=\"all\"){\n if(Array.isArray(patches)){\n for(let patch_number of patches){\n let path = this.patch_number_to_path(patch_number)\n try{\n load_files(path)\n }\n catch(err){\n warning(\"While calling PatchDDE.load, there was an error loading: \" + path +\n \"<br/>\" + err.message)\n }\n }\n }\n else { //handles patches of \"all\" and a positive integer\n let files = this.patch_paths_lowest_first()\n for(let file of files) {\n let patch_number = this.path_to_patch_number(file)\n if((typeof(patches) == \"number\") && (patch_number > patches)){} //don't load this file\n else {\n load_files(file)\n this.latest_patch_loaded = file\n }\n }\n }\n }", "function load_data(urlInfo, reload) {\n \n var state = (urlInfo&&urlInfo.state)?urlInfo.state:($('#state_selector').val()?$('#state_selector').val():\"0\");\n var county = (urlInfo&&urlInfo.county)?urlInfo.county:($('#county_selector').val()?$('#county_selector').val():undefined);\n \n if($.trim(state)!=='0') {\n // Update Soc Sharing with Full State Name\n if(county!=='' && typeof county !== \"undefined\") {\n setShareLinks({state:county+\", \"+ state, state_code:state,county:county});\n } else {\n setShareLinks({state:$(\"#state_selector option[value='\"+state+\"']\").text(), state_code:state});\n } \n cur_county = county;\n show_loader();\n if(cur_json_data==\"\") { \n getJSONData(\"./states/\" + state + \"/\" + state + \".json\",$.trim(state),$.trim(county));\n } else { \n new_display_data(cur_json_data,state,county);\n hide_loader();\n }\n \n } \n}", "function refreshGal(op) {\n op = op || 'date';\n var name;\n allGal = {};\n //~~~ getLocalGalNames();\n allGal = readWebGalX();\n var ss = [];\n // patch up errors in gallery, and turn to array ss for sort into webGalByNum\n for(name in allGal) {\n var entry = allGal[name];\n if (entry.name === \"\")\n entry.name = name;\n if (entry.name !== name) {\n var debug=0;\n }\n if (isNaN(Date.parse(entry.date)))\n entry.date = new Date('2013-1-1');\n // entry.genes.name = name; // no genes yet\n ss.push(entry);\n }\n var sss;\n if (op === 'name')\n sss = ss.sort( function(a,b) { return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1; });\n else\n sss = ss.sort( function(a,b) { return a.date < b.date ? 1 : -1; });\n\n var s = \"\";\n webGalByNum = sss;\n for (let v = 0; v<sss.length; v++) {\n name = sss[v].name;\n s += '<span class=\"savename\" onclick=\"FCall(\\'loadOao\\',\\'' + name + '\\')\">' + name+ '</span> ';\n }\n document.getElementById(\"loads\").innerHTML = s;\n}", "function setReloadLastFile() {\n if ($('#reload-last-file').prop('checked') === true) {\n trjs.param.reloadLastFile = true;\n } else {\n trjs.param.reloadLastFile = false;\n }\n trjs.param.saveStorage();\n }", "function preload() {\n\n // Loading bird images\n birdImages[0] = loadImage(\"data/no_flap.PNG\");\n birdImages[1] = loadImage(\"data/up_flap.PNG\");\n birdImages[2] = loadImage(\"data/down_flap.PNG\");\n\n // Loading pipe images\n pipeImages[0] = loadImage(\"data/pipe.PNG\");\n pipeImages[1] = loadImage(\"data/pipe_inverted.PNG\");\n\n // Loading number images\n for (var i = 0; i < 10; i++) {\n var number = str(i);\n number += \".PNG\";\n numbers[i] = loadImage(\"data/\" + number);\n }\n\n // Loading other images\n backgroundImage = loadImage(\"data/background.PNG\");\n end = loadImage(\"data/end.PNG\");\n floorImage = loadImage(\"data/floor.PNG\");\n scoreboard = loadImage(\"data/scoreboard.PNG\");\n newScore = loadImage(\"data/new.PNG\");\n getReady = loadImage(\"data/get_ready.PNG\");\n tap = loadImage(\"data/tap.PNG\");\n bronze = loadImage(\"data/bronze.PNG\");\n silver = loadImage(\"data/silver.PNG\");\n gold = loadImage(\"data/gold.PNG\");\n platinum = loadImage(\"data/platinum.PNG\");\n ok = loadImage(\"data/ok.PNG\");\n\n // Loading sound files\n die = loadSound(\"data/die.wav\");\n flap = loadSound(\"data/wing.wav\");\n pointSound = loadSound(\"data/point.wav\");\n hit = loadSound(\"data/hit.wav\");\n swoosh = loadSound(\"data/swooshing.wav\");\n\n // Loading old high score\n // highScoreObject = loadJSON(\"highscore.json\");\n // console.log(highScoreObject.highScore);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uses pageblocker div in index.php, liteweight block page from user interaction during transitions to avoid clickhappiness
function pageBlockOn(){ $('#pageBlockerOuter').css({'display': 'block'}); }
[ "function blockPage() {\n console.log(\"Unwanted video! Blocking.\")\n document.documentElement.innerHTML = '';\n document.documentElement.innerHTML = 'This site is blocked';\n document.documentElement.scrollTop = 0;\n}", "function adBlocker()\r\n{\r\n avtng.settings.adBlocker ^= 1;\r\n updateAVTNGSettings();\r\n reloadPage();\r\n}", "function blockPageMsg(msg) {\n $('#azure-block-page').find('.azure-block-page-msg').html(msg);\n}", "function\nMainDisplayBlocker()\n{\n document.getElementById(\"MainBlocker\").style.visibility = \"visible\";\n}", "function\nHideBlocker\n()\n{\n var blocker;\n\n blocker = document.getElementById(\"MainBlocker\");\n blocker.style.visibility = \"hidden\";\n}", "function uIBlock() {\n $(document)\n .ajaxStart(function () {\n smBlockUI();\n })\n .ajaxStop($.unblockUI);\n }", "function blockSite() {\n var htmlPath = chrome.extension.getURL('src/blocked.html');\n document.location = htmlPath;\n $(body).html(html);\n}", "static blockTheScreen() {\n $('body').addClass(CLASS_BLOCKING_THE_SCREEN);\n $exampleFaceModal.addClass(CLASS_BLOCKING_THE_SCREEN);\n }", "function blockUI(el, centerY) {\n var el = jQuery(el);\n var loc = window.location;\n var pathName = loc.pathname.substring(0,loc.pathname.indexOf('/', 1)+1);\n var mess = '<img src=' + pathName + 'resources/img/ajax-loading.gif align=\"\">';\n if (el.height() <= 400) {\n centerY = true;\n }\n el.block({\n message: mess,\n centerY: centerY != undefined ? centerY : true,\n css: {\n top: '10%',\n border: 'none',\n padding: '2px',\n backgroundColor: 'none'\n },\n overlayCSS: {\n backgroundColor: '#000',\n opacity: 0.05,\n cursor: 'wait'\n }\n });\n }", "function\nShowBlocker\n()\n{\n var blocker;\n\n blocker = document.getElementById(\"MainBlocker\");\n blocker.style.visibility = \"visible\";\n}", "function onWhyPage()\n{\n\t// Do animations to hide the second page, and reveal the third!\n\t$(\"#bb-content-2\").animate({\n\t\theight: \"hide\"\n\t}, 1000);\n\n\t$(\"#bb-content-3\").animate({\n\t\theight: \"show\"\n\t}, 1000);\n}", "function\nMainHideBlocker()\n{\n document.getElementById(\"MainBlocker\").style.visibility = \"hidden\";\n}", "function disablePage(url) {\n page_disabled = true;\n\n //remove closing lightbox features\n $(\".lightbox_cross\").remove();\n\n $('body').on('click', '#alert_btn', function() {\n window.location.href = url;\n });\n}", "function add_block_page()\r\n\t\t {\r\n\t\t\tvar block_page = $('<div class=\"vz_block_page\"></div>');\r\n\t\t\t\t\t\t\t $(block_page).appendTo('body');\r\n\t\t }", "function add_block_page(){\n\t\t\tvar block_page = $('<div class=\"paulund_block_page\"></div>');\n\t\t\t\t\t\t\n\t\t\t$(block_page).appendTo('body');\n\t\t}", "function add_block_page(){\r\n\t\t\tvar block_page = $('<div class=\"paulund_block_page\"></div>');\r\n\t\t\t\t\t\t\r\n\t\t\t$(block_page).appendTo('body');\r\n\t\t}", "function showAboutUsBlock() {\n history.pushState(null, 'Abous Us', '/about-us');\n changePageTitle('About Us - Transportation');\n\n hideSectionThreeBlocks();\n $('#aboutUs-block').show();\n $('#section-three').show();\n}", "function skipWelcomePage(){\n hideWelcomePage();\n incrementClickCounter();\n}", "function revealBlockedContent(curr_page) {\n\t// set display to none of current inserted html\n\t$(curr_page).find(\"#inserted\").remove();\n\t// get the closest parent and set display to inline\n\t$(curr_page).find(\".userContentWrapper._5pcr\").css(\"display\", \"inline\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles updated campus registration
async submitRegistrationChange(event) { event.preventDefault(); const { changeRegistration } = this.props; const { id } = this.state; const newCampusId = parseInt(this.state.campusId); const prevCampusId = this.state.preValues.campusId; // If submitted on the default "...select campus" option, return if (newCampusId === 0) { return; } // Dispatches the 'change registration' event await changeRegistration({ id, newCampusId, prevCampusId }); // Searches the state for our new campus bc we updated "student count" const { allCampuses } = this.props; const newCampus = allCampuses.find( (campus) => campus.id === newCampusId, ); // New Student from Redux Store const { newStudent } = this.props; // If successful (not implemented yet) update the state to these values this.setState({ ...this.state, campus: newCampus, campusId: newStudent.CampusId, preValues: { campus: newCampus, campusId: newStudent.CampusId, }, }); }
[ "update(codigo, nome, cidade) {\n try {\n\n let campus = this.get(codigo);\n if (!campus) return false;\n\n campus.nome = nome || campus.nome;\n campus.cidade = cidade || campus.cidade;\n\n db.push(`/campus/${codigo}`, campus, false);\n\n return true;\n\n } catch (error) {\n throw error;\n }\n }", "function seeRegForm() {\n // clear #seeForm (we may write an error there)\n $(\"#seeForm\").html(\"\");\n player.UserRegistration.registerFields();\n}", "function seeRegForm() {\r\n // clear #seeForm (we may write an error there)\r\n $( '#seeForm' ).html('');\r\n player.UserRegistration.registerFields();\r\n}", "async function createUserCampus() {\n const { data, error } = await supabase.from('user_campus').insert({\n user_id: userId,\n campus: id,\n name: name,\n country: country,\n latitude: latitude,\n longitude: longitude,\n });\n console.log(data);\n if (error) {\n console.log(error);\n }\n\n console.log('Post OK.');\n history.push('/charts');\n }", "async setCampus() {\n try {\n await AsyncStorage.setItem('default_campus', this.state.campus.toString())\n } catch (e) {\n // Do nothing despite failing to save the selected default campus?\n } finally {\n this.setState({ visible: false });\n }\n console.log('POPUP: The app has prompted the user to select a default campus')\n console.log('PRESS: The user set the default campus')\n }", "function handleUpdateRegisterUser() {\n if (idPeople) {\n isCreateUser ? setTitleUpdate(\"CRIAR \") : setTitleUpdate(\"ALTERAR \");\n setUpdateRegister(true);\n setIsReadonly(false);\n } else if (idPeople.length === 0) {\n notify(\n \"warning\",\n \"Para acessar a alteração de dados primeiro informe a pessoa desejada.\"\n );\n } else {\n notify(\n \"warning\",\n \"Não foi possível acessar a alteração de dados, pois nenhuma pessoa foi encontrada com o código informado.\"\n );\n }\n }", "function submitRegistration() {\n\tregistrationForm.setValidation();\n}", "function contactUs() {\n app.getForm('contactus').clear();\n if (customer.authenticated) {\n var contactusform = app.getForm('contactus').object;\n contactusform.firstname.value = customer.profile.firstName;\n contactusform.lastname.value = customer.profile.lastName;\n contactusform.email.value = customer.profile.email;\n }\n app.getView('CustomerService').render('content/contactus');\n}", "function seeRegister() {\n var fields = _formDataToObject($(\"#seeForm\"));\n\n // clear field errors\n $(\".seeError\").remove();\n\n player.UserRegistration.registerUser(fields, 0);\n}", "updateForm(register) {\n this.title.value = register.title;\n this.username.value = register.username;\n this.password.value = register.password;\n this.url.value = register.url;\n this.note.value = register.note;\n }", "function setupInitialClubInfo()\n{\n if($(\"#admin-change-club\").length > 0)\n {\n $(\"#admin-change-club\").val(1).change();\n $(\"#admin-change-club-members\").val(1).change();\n $(\"#admin-change-club-events\").val(1).change();\n }\n\n}", "function onRegisterFields(result) {\n debug(\"register-fields: \" + JSON.stringify(result));\n\n // Build the registration/update form\n // Loop through the registration fields\n for (var i = 0; i < result.data.fields.length; i++) {\n var field = result.data.fields[i];\n // Field label\n $(\"#seeForm\").append(field.description + \": \");\n // Fields come in different types which are handled here\n switch (field.type) {\n case \"single_line\":\n // input box\n $(\"#seeForm\").append(\n '<input type=\"text\" id=\"seeForm_' +\n field.name +\n '\" name=\"' +\n field.name +\n '\" value=\"' +\n field.value +\n '\"><br/>'\n );\n break;\n case \"password\":\n // Password\n $(\"#seeForm\").append(\n '<input type=\"password\" id=\"seeForm_' +\n field.name +\n '\" name=\"' +\n field.name +\n '\"><br/>'\n );\n break;\n case \"multi_line\":\n // textarea\n $(\"#seeForm\").append(\n '<textarea id=\"seeForm_' +\n field.name +\n '\" name=\"' +\n field.name +\n '\">' +\n field.value +\n \"</textarea><br/>\"\n );\n break;\n case \"single_choice\":\n // dropdown\n var options = \"\";\n for (var j = 0; j < field.answers.length; j++) {\n var selected = \"\";\n if (field.answers[j] == field.value) {\n selected = \" selected\";\n }\n options +=\n \"<option\" + selected + \">\" + field.answers[j] + \"</option>\";\n }\n $(\"#seeForm\").append(\n '<select id=\"seeForm_' +\n field.name +\n '\" name=\"' +\n field.name +\n '\">' +\n options +\n \"</select><br/>\"\n );\n break;\n case \"multi_choice\":\n // listbox\n var options = \"\";\n for (var j = 0; j < field.answers.length; j++) {\n var selected = \"\";\n if (field.value.indexOf(field.answers[j]) > 0) {\n selected = \" selected\";\n }\n options +=\n \"<option\" + selected + \">\" + field.answers[j] + \"</option>\";\n }\n $(\"#seeForm\").append(\n '<select id=\"seeForm_' +\n field.name +\n '\" name=\"' +\n field.name +\n '\" multiple size=\"5\">' +\n options +\n \"</select><br/>\"\n );\n break;\n default:\n break;\n }\n }\n\n // Determine the form type (Register/Update) based on the user's\n // logged in state\n var formType = \"Register\";\n if (player.UserRegistration.isLoggedIn()) {\n formType = \"Update\";\n }\n\n // Form button\n $(\"#seeForm\").append(\n '<input type=\"button\" class=\"btn\" id=\"see' +\n formType +\n '\" value=\"' +\n formType +\n '\"/>'\n );\n}", "function onRegisterFields( result )\r\n{\r\n debug( 'register-fields: ' + JSON.stringify( result ) );\r\n\r\n // Build the registration/update form\r\n // Loop through the registration fields\r\n for (var i=0; i<result.data.fields.length; i++) {\r\n var field = result.data.fields[i];\r\n // Field label\r\n $( \"#seeForm\" ).append( field.description + ': ' );\r\n // Fields come in different types which are handled here\r\n switch ( field.type ) {\r\n case 'single_line':\r\n // input box\r\n $( \"#seeForm\" ).append( '<input type=\"text\" id=\"seeForm_' + field.name + '\" name=\"' + field.name + '\" value=\"' + field.value + '\"><br/>');\r\n break;\r\n case 'password':\r\n // Password\r\n $( \"#seeForm\" ).append( '<input type=\"password\" id=\"seeForm_' + field.name + '\" name=\"' + field.name + '\"><br/>');\r\n break;\r\n case 'multi_line':\r\n // textarea\r\n $( \"#seeForm\" ).append( '<textarea id=\"seeForm_' + field.name + '\" name=\"' + field.name + '\">' + field.value + '</textarea><br/>');\r\n break;\r\n case 'single_choice':\r\n // dropdown\r\n var options = '';\r\n for (var j=0; j<field.answers.length; j++) {\r\n var selected = '';\r\n if (field.answers[j] == field.value) {\r\n selected = ' selected';\r\n }\r\n options += '<option' + selected + '>' + field.answers[j] + '</option>';\r\n }\r\n $( \"#seeForm\" ).append( '<select id=\"seeForm_' + field.name + '\" name=\"' + field.name + '\">' + options + '</select><br/>' );\r\n break;\r\n case 'multi_choice':\r\n // listbox\r\n var options = '';\r\n for (var j=0; j<field.answers.length; j++) {\r\n var selected = '';\r\n if (field.value.indexOf(field.answers[j]) > 0) {\r\n selected = ' selected';\r\n }\r\n options += '<option' + selected + '>' + field.answers[j] + '</option>';\r\n }\r\n $( \"#seeForm\" ).append( '<select id=\"seeForm_' + field.name + '\" name=\"' + field.name + '\" multiple size=\"5\">' + options + '</select><br/>' );\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n // Determine the form type (Register/Update) based on the user's\r\n // logged in state\r\n var formType = 'Register';\r\n if (player.UserRegistration.isLoggedIn()) {\r\n formType = 'Update';\r\n }\r\n\r\n // Form button\r\n $( \"#seeForm\" ).append('<input type=\"button\" class=\"btn\" id=\"see' + formType + '\" value=\"' + formType + '\"/>');\r\n}", "update() {\n Spark.put('/settings/contact', this.form).then(() => {\n Bus.$emit('updateUser');\n });\n }", "signupWriteSuccessCallback () {\n console.log(\"Wrote new user data.\")\n\n // refresh necessary page elements\n //app.setSelectedMemeCategory(\"bestof\");\n app.setAdminStatus(normie.isAdmin);\n app.refreshMemeList();\n\n // reset #signupModal\n app.setSignupModal();\n }", "function seeRegister() {\r\n var fields = _formDataToObject( $( \"#seeForm\") );\r\n\r\n // clear field errors\r\n $( '.seeError' ).remove();\r\n\r\n player.UserRegistration.registerUser( fields, 0 );\r\n}", "static async createCampusAccount(req, res){\n try{\n const {campus_name, location, address, long, lat, school_id} = req.body;\n\n await Campus.findAll({\n where: {campus_name: campus_name}\n })\n .then(result=>{\n if(result.length > 0){\n res.status(203).json({message: \"Sorry, Campus name already exist.\"});\n }else{\n let createNewCampus = {\n campus_name: campus_name,\n location: location,\n address: address,\n long: long,\n lat: lat,\n school_id: school_id\n }\n Campus.create(createNewCampus)\n .then(data=>{\n res.status(201).json({message: \"Campus account created successfully\",campusData: data});\n })\n .then(err=>res.json({error: err}));\n }\n })\n .then(err=>{\n res.status(500);\n })\n }catch (e) {\n res.send(500);\n }\n }", "function ready_register() {\n $('.modal-button').click(function() {\n $('.register-form').submit();\n });\n }", "function validarCampos () {\n\tsave();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
words count in input keywordinput
function countWords(keyword){ return (keyword.replace(/(^\s*)|(\s*$)/gi,"").replace(/[ ]{2,}/gi," ").replace(/\n /,"\n").split(' ').length); }
[ "function countWords(){\n\tlet textLength = text.value.length;\n\t// create a substring that checks if each new key typed is a space\t\n\tif(text.value.substring((textLength-1), textLength) == \" \")\n\t\tnumWords++;\n}", "function wordCounter(text) {\n var text = input.value.split(' ');\n var wordCount = 0;\n for (var i = 0; i < text.length; i++) {\n if (text[i] !== ' ' && onlyWords(text[i])) {\n wordCount++;\n }\n }\n count.innerText = wordCount;\n }", "function wordCounter(text) {\n var text = input.value; \n var wordCount = 0; //start at 0 words before we type anything\n \n //increments wordcount every time new word is typed\n //new word is recognized by the space separating words\n for (var i = 0; i<= text.length; i++) {\n if (text.charAt(i) == ' '){\n wordCount++; \n }\n }\n count.innerText = wordCount;\n }", "function nwtCounter() {\n let wordsTyped = myText.value.split(\" \").length; \n nwtTotal.innerHTML = wordsTyped++;\n }", "function wordCount(enteredText) {\n var words = wordsOnly(enteredText).replace(/\\s/g, ',').trim().split(',');\n count = 0;\n for (i = 0; i < words.length; i++) {\n if (words[i] !== \"\") {\n count += 1;\n }\n }\n return count;\n}", "function wordCount() {\r\n s = document1;\r\n //s = s.replace(/(^\\s*)|(\\s*$)/gi, \"\"); //old method\r\n //s = s.replace(/[ ]{2,}/gi, \" \");\r\n //s = s.replace(/\\n /, \"\\n\");\r\n ////writeToPage(s.split(' ').length);\r\n //return s.split(' ').length;\r\n try { //new method\r\n //the try catch is incase there is a big change in the document, this can bring up an error sometimes but the try catch fixes this\r\n var word = s.match(/\\S+/g);\r\n //document.getElementById(\"req0\").value = \"\"+ word && word.length || 0; //Used for testing\r\n return word && word.length || 0;\r\n }\r\n catch (err) {\r\n return 0;\r\n }\r\n }", "function countKeywords($elem, max)\n {\n var keywords = $elem.val().split(','),\n count = keywords.length;\n\n if ($elem.val() == '') count = 0;\n\n if (count > max) {\n keywords.pop();\n $elem.val(keywords.join(','));\n } else {\n $elem.parent().find('.keyword-count').html(max - count);\n }\n }", "function wordCount(element) {\n\tvar string = element.val();\n\treturn $.grep($.trim(string).split(/\\W+/), function(element, index) {\n\t\treturn element != \"\";\n\t}).length;\n}", "function countKeywords() {\n\tfor (let i = 0; i < textAreaArray.length; i++) {\n\t\tconst word = textAreaArray[i];\n\t\tif (word in keywords) {\n\t\t\tif (word in textObj) {\n\t\t\t\ttextObj[word]++;\n\t\t\t} else {\n\t\t\t\ttextObj[word] = 1;\n\t\t\t}\n\t\t}\n\t}\n}", "function countSubstringOccur(input) {\n var keywordOccur = 0,\n keyword = input[0].toLowerCase(),\n text = input[1].toLowerCase();\n\n for (var i = 0; i < text.length - keyword.length; i++) {\n if (keyword === text.substr(i, keyword.length)) {\n keywordOccur++;\n }\n }\n return keywordOccur;\n}", "function wordsTyped() {\n testString = testArea.value;\n words = testString.split(\" \");\n return words.length;\n}", "function string_count_total_word_accurance(content, keywords)\n{\n var sum = 0;\n var total = 0;\n\n keywords = string_to_array(keywords, ' ');\n for(var i=0; i<keywords.length; i++)\n {\n keyword = keywords[i];\n total = string_exist_count(content, \" \"+keyword+\" \");\n sum += total;\n }\n\n return sum;\n}", "function wordOccurrences(word, text) {\n if (noInputtedWord(word, text)) {\n return 0;\n }\n const wordArray = text.split(\" \");\n let wordCount = 0;\n wordArray.forEach(function(element) {\n if (element.toLowerCase()===word.toLowerCase()) {\n wordCount++;\n }\n });\n return wordCount;\n}", "function counting (words){\n return words.split(\" \").length;\n}", "function displayWordCounter(){\nvar getTextValue = document.frm.txttiet.value; // Get input textarea value\nvar getTextLength = getTextValue.length; // Get length of input textarea value\nif(getTextLength > setTotalNumberOfWordCounter){ //compare this length with total count\n getTextValue = getTextValue.substring(0,setTotalNumberOfWordCounter);\n document.frm.txttiet.value =getTextValue;\n return false;\n}\n\n \n}", "function updateCounts() {\n text = document.getElementById('textBox').value;\n var charCount = text.length + 1;\n var wordCount = text.split(' ').length;\n\n document.getElementById('charCount').innerHTML = charCount;\n document.getElementById('wordCount').innerHTML = wordCount;\n}", "function wordCount(text) {\n var textarea = $('#user-text').val();\n var words = textarea.split(\" \").length;\n return words;\n}", "function countWords(sting){\n sting = sting.split(' ');\n return sting.length;\n}", "function countWordsInText(text) {\n console.log('countWordsInText');\n var words = text.toString().toLowerCase().split(/\\W+/);\n\n for (var index in words) {\n var word = words[index];\n if (word) {\n wordCounts[word] = (wordCounts[word] ? wordCounts[word] + 1 : 1);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log requests to console
function logConsole() { return function (req, res, next) { console.log('Received request: ' + req.method + ' ' + req.originalUrl); next(); }; }
[ "function logAllRequests(req, res, next) {\n console.log('\\n' + JSON.stringify({\n path : req.path,\n remoteAddress : req.connection.remoteAddress,\n headers : req.headers,\n body : req.body\n }));\n next();\n}", "logRequests() {\n this.app.use('/', (req, res, next) => {\n this.debug(`Request: ${req.protocol}://${req.get('host')}${req.originalUrl}`);\n next();\n });\n }", "function logIncomingToConsole(req, res, next) {\n console.info(`Got request on ${req.path} (${req.method}).`);\n next();\n}", "function requestLog(req, res) {\n Log(config.basis.log_prefix, {\n request_end_point: req.originalUrl,\n request_parameters: req.params,\n request_method: req.method,\n response_status: 200\n })\n}", "function logRequest(req, res, next) {\n console.debug(`Incoming ${req.method} on ${req.url}`)\n next()\n}", "logAPIRequest(req) {\n this.log.info({ req });\n }", "function logger(req, res, next) {\n console.log(`Request Method: ${req.method}`);\n console.log(`URL: ${req.url}`);\n console.log(`Timestamp: ${new Date()}`);\n next();\n }", "function logging(response){\n console.log(\"response\",response)\n}", "function requestLog(req, res) {\n Log(config.basis.log_prefix, {\n request_end_point: req.originalUrl,\n request_parameters: req.params,\n request_method: req.method,\n response_status: res.statusCode \n })\n}", "logRequest(req) {\n\t\tlet message = req.method + ' ' + req.url;\n\n\t\tif (req.body) {\n\t\t\tmessage += '\\n' + JSON.stringify(req.body, null, ' ') + '\\n\\n';\n\t\t}\n\n\t\tlog.info(message);\n\t\t// log.info({ req: req }, message);\n\t}", "function logger(req, res, next) {\n console.log(req.method);\n console.log(req.url);\n console.log(Date.now());\n next();\n}", "function consoleLog() {\n page.on('console', consoleObj => {\n const text = consoleObj.text();\n console.log('[Page] '+text);\n if (text.startsWith('[showResourceTimingsResult]')) {\n const splitted = text.split(' ');\n const results = JSON.parse(splitted[2]);\n console.log('Results', splitted[1], results);\n testStack.push(results);\n }\n });\n }", "function logRequest(request, response) {\n requestLogger.info({ url: request.url, method: request.method }, 'Received a new request');\n response.on('finish', () => {\n requestLogger.info({\n url: request.url,\n method: request.method,\n status: response.statusCode\n });\n });\n}", "function setup_debug_log() {\n\tapp.use(function (req, res, next) {\n\t\treq._tx_id = tools.ot_misc.buildTxId(req); \t\t\t\t\t\t// make an id that follows this requests journey, gets logged\n\t\treq._orig_headers = JSON.parse(JSON.stringify(req.headers));\t// store original headers, b/c we might rewrite the authorization header\n\t\treq._notifications = [];\t\t\t\t\t\t\t\t\t\t// create an array to store athena notifications generated by the request\n\n\t\tconst skip = ['.js', '.map', '.svg', '.woff2', '.css'];\n\t\tlet print_log = true;\n\t\tfor (const i in skip) {\n\t\t\tif (req.url.indexOf(skip[i]) >= 0) {\n\t\t\t\tprint_log = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (req.path.includes(healthcheck_route)) {\t\t\t\t\t\t// avoid spamming logs with the healtcheck api\n\t\t\tprint_log = false;\n\t\t}\n\n\t\tif (print_log) {\n\t\t\tconst safe_url = req.path ? req.path : 'n/a';\t\t// no longer need to encodeURI(path), automatically done\n\t\t\tlogger.silly('--------------------------------- incoming request ---------------------------------');\n\t\t\tlogger.info('[' + req._tx_id + '] New ' + req.method + ' request for url:', safe_url);\n\t\t}\n\t\tnext();\n\t});\n}", "function log() {\n if (window.console && console.log && document.domain == 'localhost') {\n console.log.apply(console, arguments);\n }\n }", "function httpLog(request, load) {\r\n\t\t// Log request.\r\n\t\tvar d = new Date();\r\n\t\tvar now = d.getTime();\r\n\t\tvar line = now + \"\\t\" + request.connection.remoteAddress + \"\\t\" + load + \"\\r\\n\";\r\n\t\tfs.appendFile('logs/http.tsv', line, function (err) {});\r\n\t}", "function console_log() {\n Platform.Response.Write('<scr' + 'ipt>');\n Platform.Response.Write('console.log.apply(null,' + Platform.Function.Stringify(Array.from(arguments)) + ')');\n Platform.Response.Write('</scr' + 'ipt>'); \n }", "printLogs() {\n var _a, _b;\n console.log((_b = (_a = this.response.meta) === null || _a === void 0 ? void 0 : _a.logMessages) === null || _b === void 0 ? void 0 : _b.join(\"\\n\"));\n }", "function logVisit(req, res, next){\n console.log(\n `${req.method} to ${req.url} from ${req.get('Origin')}`\n )\n next();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets integration to install
function getIntegrationsToSetup(options) { var defaultIntegrations = (options.defaultIntegrations && Object(tslib_es6["e" /* __spread */])(options.defaultIntegrations)) || []; var userIntegrations = options.integrations; var integrations = []; if (Array.isArray(userIntegrations)) { var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); var pickedIntegrationsNames_1 = []; // Leave only unique default integrations, that were not overridden with provided user integrations defaultIntegrations.forEach(function (defaultIntegration) { if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { integrations.push(defaultIntegration); pickedIntegrationsNames_1.push(defaultIntegration.name); } }); // Don't add same user integration twice userIntegrations.forEach(function (userIntegration) { if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { integrations.push(userIntegration); pickedIntegrationsNames_1.push(userIntegration.name); } }); } else if (typeof userIntegrations === 'function') { integrations = userIntegrations(defaultIntegrations); integrations = Array.isArray(integrations) ? integrations : [integrations]; } else { integrations = Object(tslib_es6["e" /* __spread */])(defaultIntegrations); } // Make sure that if present, `Debug` integration will always run last var integrationsNames = integrations.map(function (i) { return i.name; }); var alwaysLastToRun = 'Debug'; if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { integrations.push.apply(integrations, Object(tslib_es6["e" /* __spread */])(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); } return integrations; }
[ "function getIntegrationsToSetup(options){var defaultIntegrations=options.defaultIntegrations&&Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(options.defaultIntegrations)||[];var userIntegrations=options.integrations;var integrations=[];if(Array.isArray(userIntegrations)){var userIntegrationsNames_1=userIntegrations.map(function(i){return i.name;});var pickedIntegrationsNames_1=[];// Leave only unique default integrations, that were not overridden with provided user integrations\ndefaultIntegrations.forEach(function(defaultIntegration){if(userIntegrationsNames_1.indexOf(defaultIntegration.name)===-1&&pickedIntegrationsNames_1.indexOf(defaultIntegration.name)===-1){integrations.push(defaultIntegration);pickedIntegrationsNames_1.push(defaultIntegration.name);}});// Don't add same user integration twice\nuserIntegrations.forEach(function(userIntegration){if(pickedIntegrationsNames_1.indexOf(userIntegration.name)===-1){integrations.push(userIntegration);pickedIntegrationsNames_1.push(userIntegration.name);}});}else if(typeof userIntegrations==='function'){integrations=userIntegrations(defaultIntegrations);integrations=Array.isArray(integrations)?integrations:[integrations];}else{integrations=Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(defaultIntegrations);}// Make sure that if present, `Debug` integration will always run last\nvar integrationsNames=integrations.map(function(i){return i.name;});var alwaysLastToRun='Debug';if(integrationsNames.indexOf(alwaysLastToRun)!==-1){integrations.push.apply(integrations,Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(integrations.splice(integrationsNames.indexOf(alwaysLastToRun),1)));}return integrations;}", "getInstallLocation() {\n return EnigmailApp._installLocation;\n }", "function getIntegrationsToSetup(options) {\n var defaultIntegrations = (options.defaultIntegrations && Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(options.defaultIntegrations)) || [];\n var userIntegrations = options.integrations;\n var integrations = [];\n if (Array.isArray(userIntegrations)) {\n var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; });\n var pickedIntegrationsNames_1 = [];\n // Leave only unique default integrations, that were not overridden with provided user integrations\n defaultIntegrations.forEach(function (defaultIntegration) {\n if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 &&\n pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) {\n integrations.push(defaultIntegration);\n pickedIntegrationsNames_1.push(defaultIntegration.name);\n }\n });\n // Don't add same user integration twice\n userIntegrations.forEach(function (userIntegration) {\n if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) {\n integrations.push(userIntegration);\n pickedIntegrationsNames_1.push(userIntegration.name);\n }\n });\n }\n else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n else {\n integrations = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(defaultIntegrations);\n }\n // Make sure that if present, `Debug` integration will always run last\n var integrationsNames = integrations.map(function (i) { return i.name; });\n var alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push.apply(integrations, Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));\n }\n return integrations;\n}", "async getIntegratorUrl() {\n const homeyId = await this.homey.cloud.getHomeyId();\n return 'https://my.shelly.cloud/integrator.html?itg='+ Homey.env.SHELLY_TAG +'&cb=https://webhooks.athom.com/webhook/'+ Homey.env.WEBHOOK_ID +'/?homey='+ homeyId\n }", "function getIntegrationsToSetup(options) {\n var defaultIntegrations = (options.defaultIntegrations && node_modules_tslib_tslib_es6_spread(options.defaultIntegrations)) || [];\n var userIntegrations = options.integrations;\n var integrations = [];\n if (Array.isArray(userIntegrations)) {\n var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; });\n var pickedIntegrationsNames_1 = [];\n // Leave only unique default integrations, that were not overridden with provided user integrations\n defaultIntegrations.forEach(function (defaultIntegration) {\n if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 &&\n pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) {\n integrations.push(defaultIntegration);\n pickedIntegrationsNames_1.push(defaultIntegration.name);\n }\n });\n // Don't add same user integration twice\n userIntegrations.forEach(function (userIntegration) {\n if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) {\n integrations.push(userIntegration);\n pickedIntegrationsNames_1.push(userIntegration.name);\n }\n });\n }\n else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n else {\n integrations = node_modules_tslib_tslib_es6_spread(defaultIntegrations);\n }\n // Make sure that if present, `Debug` integration will always run last\n var integrationsNames = integrations.map(function (i) { return i.name; });\n var alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push.apply(integrations, node_modules_tslib_tslib_es6_spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));\n }\n return integrations;\n}", "function getIntegrationsToSetup(options) {\n var defaultIntegrations = (options.defaultIntegrations && tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"](options.defaultIntegrations)) || [];\n var userIntegrations = options.integrations;\n var integrations = [];\n if (Array.isArray(userIntegrations)) {\n var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; });\n var pickedIntegrationsNames_1 = [];\n // Leave only unique default integrations, that were not overridden with provided user integrations\n defaultIntegrations.forEach(function (defaultIntegration) {\n if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 &&\n pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) {\n integrations.push(defaultIntegration);\n pickedIntegrationsNames_1.push(defaultIntegration.name);\n }\n });\n // Don't add same user integration twice\n userIntegrations.forEach(function (userIntegration) {\n if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) {\n integrations.push(userIntegration);\n pickedIntegrationsNames_1.push(userIntegration.name);\n }\n });\n }\n else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n else {\n integrations = tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"](defaultIntegrations);\n }\n // Make sure that if present, `Debug` integration will always run last\n var integrationsNames = integrations.map(function (i) { return i.name; });\n var alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push.apply(integrations, tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"](integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));\n }\n return integrations;\n}", "static getInstallations() {\n return chromeFinder[utils_1.getPlatform()]();\n }", "getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }", "getIntegrationById(integrationId) {\n\t return this._integrations[integrationId];\n\t }", "handlePluginInstallation(plugin) {\n Installer.installPlugin(plugin).then((response) => {\n console.log(response);\n }, (err) => {\n console.log(err);\n })\n }", "setupIntegrations() {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = integration.setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }", "getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }", "installService() {\n return platform_1.PlatformInformation.getCurrent(this._extensionConstants.getRuntimeId, this._extensionConstants.extensionName).then(platformInfo => {\n if (platformInfo.isValidRuntime()) {\n return this._serverProvider.getOrDownloadServer(platformInfo.runtimeId);\n }\n else {\n throw new Error('unsupported runtime');\n }\n });\n }", "function GetiQPlusInstallInfo()\n{\n var versionInfo =null\n var command =\"wmic product get Name,Version\"\n var oShell = getActiveXObject(\"WScript.Shell\") // Or oShell = WshShell\n //var oExec = oShell.Exec(\"powershell -command Get-Process\");\n var oExec = oShell.Exec(command)\n oExec.StdIn.Close(); // Close standard input before reading output\n\n // Get PowerShell output\n var strOutput = oExec.StdOut.ReadAll()\n // Trim leading and trailing empty lines\n strOutput = aqString.Trim(strOutput, aqString.stAll)\n\n // Post PowerShell output to the test log line by line\n aqString.ListSeparator = \"\\r\\n\";\n for (var indexProgram = 0; indexProgram < aqString.GetListLength(strOutput); indexProgram++)\n {\n if(aqString.Find(aqString.GetListItem(strOutput,indexProgram),\"Qualitrol\")!=-1)\n {\n versionInfo = aqString.GetListItem(strOutput, indexProgram) \n Log.Message(versionInfo)\n break\n } \n }\n return versionInfo\n}", "install() {\n this.installerDataSvc.setup(\n this.installerDataSvc.getInstallable('virtualbox').getLocation(),\n this.installerDataSvc.getInstallable('jdk').getLocation(),\n this.installerDataSvc.getInstallable('jbds').getLocation(),\n this.installerDataSvc.getInstallable('vagrant').getLocation(),\n this.installerDataSvc.getInstallable('cygwin').getLocation(),\n this.installerDataSvc.getInstallable('cdk').getLocation()\n );\n this.router.go('install');\n }", "function setupIntegration(integration, integrationIndex) {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Integration installed: ${integration.name}`);\n }\n }", "get addonID()\n {\n let {addonID} = require(\"info\");\n return addonID;\n }", "getPluginLicenseInfo() {\n return axios.get(Craft.getActionUrl('app/get-plugin-license-info'))\n }", "setupIntegrations() {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a list of datasets, creates Leaflet layers of either L.Knreise.GeoJSON or L.Knreise.MarkerClusterGroup according to config. Can be supplied an initial bbox for filtering and a filter function
function loadDatasets(datasets, bounds, filter, loadedCallback, skipLoadOutside) { datasets = _.filter(datasets, function (dataset) { return !dataset.noLoad; }); var loaded; if (loadedCallback) { var featurecollections = []; var finished = _.after(datasets.length, function () { loadedCallback(featurecollections); }); loaded = function (featureCollection) { featurecollections.push(featureCollection); finished(); }; } var res = _.map(datasets, function (dataset) { //extend with defaults dataset = _.extend({}, _defaults, dataset); //copy properties from parent if (dataset.datasets) { _copyProperties(dataset); } //set default style if (KR.Style.setDatasetStyle) { if (dataset.datasets) { _.each(dataset.datasets, _setStyle); } else { _setStyle(dataset); } } if (!dataset.visible) { dataset.notLoaded = true; } if (dataset.minZoom && dataset.bbox) { dataset.isStatic = false; } return _addDataset(dataset, filter, bounds, loaded, skipLoadOutside); }); reloads = _.pluck(res, 'reload'); var layers = _.pluck(res, 'layer'); if (useCommonCluster) { commonCluster(layers); } return layers; }
[ "function LoadData (mapCluster) \r\n{\r\n L.mapbox.featureLayer().loadURL('../example/geojson/stations.geojson').on('ready', function(e) \r\n {\r\n var clusterGroup = new L.MarkerClusterGroup();\r\n e.target.eachLayer(function(layer) \r\n {\r\n clusterGroup.addLayer(layer);\r\n });\r\n mapCluster.addLayer(clusterGroup);\r\n });\r\n}", "function initializeDataLayers(dataLayers) {\n\n dataLayers.forEach(function (layer) {\n dataLayers[dataLayers.indexOf(layer)] = new L.GeoJSON();\n });\n\n}", "function loadAllSchools(data) {\n $(\"#search-option\").hide();\n $(\"#filters\").hide();\n $(\"#markers-list\").show();\n featureLayer = L.mapbox.featureLayer(data)\n clusterGroup = createClusterGroup(featureLayer)\n map.addLayer(clusterGroup); \n clusterGroup.eachLayer(function(marker) {\n addMarkerContent(marker);\n }) \n createAllSchoolsMarkerList(featureLayer); \n finishedLoading();\n}", "function loadAllSchools(data) {\n // featureLayer = L.mapbox.featureLayer(data, {pointToLayer:scaledPoint}).addTo(map)\n featureLayer = L.mapbox.featureLayer(data)\n clusterGroup = createClusterGroup(featureLayer)\n map.addLayer(clusterGroup); \n}", "function createLayer(filteredData) {\n\n\tvar markers = L.markerClusterGroup();\n\n\tfor (var i = 0; i < filteredData.length; i++) {\n\t\tvar record = filteredData[i];\n\n\t\tvar animalMarker = L.marker([record.latitude, record.longitude]);\n\t\t\n\t\t// bind a pop-up to show the some information on the sighting record\n\t\tanimalMarker.bindPopup(\"<h4>\" + record.comm_name +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"</h4><hr><p>\" + record.start_date + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'<br>' + '[' + record.latitude + ', ' + record.longitude + ']' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'<br>' + 'Total Sightings: ' + record.totalcount + \"</p>\");\n\n\t\t// Add a new marker to the cluster group and bind a pop-up\n\t\tmarkers.addLayer(animalMarker); \n\t}\n\n\treturn markers;\n}", "function loadJSONData(datasetString) {\n if (window.initialLoad == true) {\n return\n };\n window.initialLoad = true;\n var types = ['STREAMGAGE','SNOTEL','SNOWCOURSE','SCAN', 'RESERVOIR'];\n var data = datasetString;\n //var data = JSON.parse(datasetString);\n types.forEach(function(type) {\n var layer = L.geoJSON(data, {\n filter: function(feature, layer) {\n return feature.properties.DatasetType == type;\n },\n pointToLayer: function (feature, latlng) {\n var fillColor = \"#cf56ff\";\n switch (feature.properties.DatasetType) {\n case 'STREAMGAGE': \n fillColor = '#23ff27';\n break;\n case 'SNOTEL': \n fillColor = '#4cffed';\n break;\n case 'SNOWCOURSE': \n fillColor = '#00beff';\n break;\n case 'SCAN': \n fillColor = '#604fa5';\n break;\n case 'RESERVOIR':\n fillColor = '#005dff';\n break;\n };\n var markr = L.circleMarker (latlng, {\n pane: \"PointsPane\",\n fillColor: fillColor,\n color: \"#000000\",\n weight: 1,\n radius: 7,\n fillOpacity: 1\n }\n );\n return markr;\n }\n }).addTo(window.map);\n window.layerGrp.addLayer(layer);\n window.layerControl.addOverlay(layer, type);\n \n });\n addPopups(window.layerGrp);\n}", "function loadDataIntoMap(type)\n{\n var colors;\n var data;\n var points = [];\n var count;\n var lat, lon, desc;\n if (type === '311')\n {\n colors = complaints_colors;\n data = query_result_311;\n lat = \"latitude\";\n lon = \"longitude\";\n desc = \"descriptor\";\n count = {'Alarms': 0, 'Banging/Pounding': 0, 'Car/Truck Horn': 0, 'Engine Idling': 0,\n 'Construction Equipment': 0, 'Construction Before/After Hours': 0, 'Jack Hammering': 0};\n cleanMap(layers_311, layer_311, overlays_311); \n } else if (type === 'Permits')\n {\n colors = permits_colors;\n data = query_result_permits;\n lat = \"latitude_wgs84\";\n lon = \"longitude_wgs84\";\n desc = \"permit_type_description\";\n count = {'ALTERATION': 0, 'PLUMBING': 0, 'EQUIPMENT WORK': 0,\n 'EQUIPMENT': 0, 'FOUNDATION': 0, 'NEW BUILDING': 0, 'SIGN': 0,\n 'FULL DEMOLITION': 0};\n cleanMap(layers_permits, layer_permits, overlays_permits);\n }\n\n var overlays = {};\n var markers = {};\n var layers = {};\n for (var key in colors)\n markers[key] = [];\n\n var all_markers = [];\n\n $.each(data, function (index, rec)\n {\n if (rec.hasOwnProperty(lat) && rec.hasOwnProperty(lon))\n {\n var marker;\n for (key in colors)\n {\n if (rec[desc].indexOf(key) > -1)\n {\n points.push([rec[lon], rec[lat], key]);\n count[key] += 1;\n\n marker = L.circleMarker([rec[lat], rec[lon]], marker_style(key, type));\n markers[key].push(marker);\n all_markers.push(marker);\n break;\n }\n }\n }\n });\n \n var all_layers = L.featureGroup(all_markers);\n for (var key in markers)\n {\n layers[key] = L.featureGroup(markers[key]).addTo(map);\n layers[key].bringToFront();\n }\n map.fitBounds(all_layers.getBounds());\n\n for (var key in colors)\n {\n overlays['<div style=\"background:' + getColor(key, type) + '; border-radius: 50%; width: 10px; height: 10px; display:inline-block;\"></div> ' + key] = layers[key];\n }\n\n var layer = L.control.layers(null, overlays, {position: 'bottomright'}).addTo(map);\n\n if (type === '311')\n {\n layers_311 = layers;\n layer_311 = layer;\n overlays_311 = overlays;\n points_311 = pointInPolygon(points, complaints_colors);\n } else if (type === 'Permits')\n {\n layers_permits = layers;\n layer_permits = layer;\n overlays_permits = overlays;\n points_permits = pointInPolygon(points, permits_colors);\n }\n}", "function initMapContent(map) {\n var mapOptions = getMapOptionsFromMap(map);\n var mapCriteria = mapOptions.mapVariables.map_criteria;\n var mapValues = mapOptions.mapVariables.map_symbol_values;\n var allMapCriteria = mapOptions.mapVariables.map_criteria_all;\n var pointsCluster = mapOptions.options.pointsCluster;\n\n $('.js-activity-layer-toggle').on('change', function() {\n var mapOpts = getMapOptionsFromElement(this);\n if (typeof mapOpts.dealLayer === 'undefined') return;\n if (this.checked) {\n mapOpts.map.addLayer(mapOpts.dealLayer);\n } else {\n mapOpts.map.removeLayer(mapOpts.dealLayer);\n }\n });\n\n var queryParams = $.merge(\n ['attrs=' + mapCriteria[1]], getActiveFilters()).join('&');\n $.ajax({\n url: '/activities/geojson?' + queryParams,\n cache: false,\n success: function(data) {\n var dataGrouped = {};\n data.features.forEach(function(feature) {\n var groupBy = feature.properties[mapCriteria[0]];\n if (typeof dataGrouped[groupBy] === 'undefined') {\n dataGrouped[groupBy] = [];\n }\n dataGrouped[groupBy].push(feature);\n });\n\n var dealLayer = L.layerGroup();\n\n for (var key in dataGrouped) {\n if (dataGrouped.hasOwnProperty(key)) {\n var geojson = {\n 'type': 'FeatureCollection',\n 'features': dataGrouped[key]\n };\n var geojsonLayer;\n if (pointsCluster === true) {\n // Define a cluster of markers for each map criteria value\n\n var marker = L.markerClusterGroup({\n showCoverageOnHover: false,\n zoomToBoundsOnClick: false,\n maxClusterRadius: 50,\n singleMarkerMode: true,\n // Store the current key so it can be accessed from\n // within the iconCreateFunction.\n options: {\n 'key': key\n },\n iconCreateFunction: function(cluster) {\n // Overwrite the default icons: Always use color of\n // the current map criteria value.\n var colors = getColors(mapValues.indexOf(this.options.key));\n var textColor = colors[1];\n var iconColor = chroma(colors[0]).alpha(0.6);\n var altIconColor = textColor === '#FFFFFF' ? iconColor.brighten(0.5) : iconColor.darken(0.5);\n\n var childCount = cluster.getChildCount();\n if (childCount === 1) {\n // For single features, flag if status is pending\n var feature = cluster.getAllChildMarkers()[0].feature;\n altIconColor = textColor === '#FFFFFF' ? iconColor.brighten(0.5) : iconColor.darken(0.5);\n if (feature.properties.status === 'pending') {\n altIconColor = 'white';\n }\n return L.divIcon({\n className: 'map-single-icon',\n iconSize: new L.Point(20, 20),\n html: '<div style=\"background-color: ' + altIconColor + '\"><div style=\"background-color: ' + iconColor + '\"></div></div>'\n });\n }\n\n return L.divIcon({\n html: '<div style=\"color: ' + textColor + '; background-color: ' + altIconColor + '\"><div style=\"background-color: ' + iconColor + '\"><span>' + childCount + '</span></div></div>',\n iconSize: L.point(40, 40),\n className: 'map-cluster-icon'\n });\n }\n });\n\n geojsonLayer = L.geoJson(geojson);\n marker.addLayer(geojsonLayer);\n\n marker.on('click', function(a) {\n showSingleFeatureDetails(a, mapOptions);\n });\n marker.on('clusterclick', function(a) {\n showClusterFeatureDetails(a, mapOptions);\n });\n\n dealLayer.addLayer(marker);\n } else {\n // No clustering: Show each feature as point.\n geojsonLayer = L.geoJson(geojson, {\n pointToLayer: function(geoJsonPoint, latlng) {\n var colors = getColors(mapValues.indexOf(key));\n var textColor = colors[1];\n var iconColor = chroma(colors[0]).alpha(0.6);\n var altIconColor = textColor === '#FFFFFF' ? iconColor.brighten(0.5) : iconColor.darken(0.5);\n if (geoJsonPoint.properties.status === 'pending') {\n altIconColor = 'white';\n }\n return L.marker(latlng, {\n icon: L.divIcon({\n className: 'map-single-icon',\n iconSize: new L.Point(20, 20),\n html: '<div style=\"background-color: ' + altIconColor + '\"><div style=\"background-color: ' + iconColor + '\"></div></div>'\n })\n });\n }\n });\n dealLayer.addLayer(geojsonLayer);\n }\n }\n }\n\n var mapOptions = getMapOptionsFromMap(map);\n if (mapOptions.options.pointsVisible === true) {\n map.addLayer(dealLayer);\n }\n mapOptions['dealLayer'] = dealLayer;\n\n // Map symbolization dropdown\n var symbolsHtml = [];\n symbolsHtml.push(\n '<a class=\"dropdown-button\" href=\"#\" data-activates=\"map-symbolization-dropdown-' + map.getContainer().id + '\" style=\"margin: 0; padding: 0; line-height: 22px; height: 22px;\">',\n mapCriteria[0],\n '<i class=\"material-icons right\" style=\"line-height: 22px;\">arrow_drop_down</i>',\n '</a>',\n '<ul id=\"map-symbolization-dropdown-' + map.getContainer().id + '\" class=\"dropdown-content\" style=\"width: 500px;\">'\n );\n allMapCriteria.forEach(function(c) {\n symbolsHtml.push(\n '<li>',\n '<a href=\"#\" class=\"js-change-map-symbolization\" data-map-id=\"' + map.getContainer().id + '\" data-translated-name=\"' + c[0].replace(\"'\", \"\\\\'\") + '\" data-internal-name=\"' + c[1].replace(\"'\", \"\\\\'\") + '\">' + c[0] + '</a>',\n '</li>'\n )\n });\n symbolsHtml.push('</ul>');\n $('#map-deals-symbolization-' + map.getContainer().id).html(symbolsHtml.join(''));\n initializeDropdown();\n\n $('.js-change-map-symbolization').on('click', function(e) {\n e.preventDefault();\n var $t = $(this);\n updateMapCriteria($t.data('map-id'), $t.data('translated-name'), $t.data('internal-name'));\n });\n\n // Legend\n var legendHtml = mapValues.map(function(v, i) {\n return [\n '<li style=\"line-height: 15px;\">',\n '<div class=\"vectorLegendSymbol\" style=\"background-color: ' + getColors(i)[0] + ';\">',\n '</div>',\n v,\n '</li>'\n ].join('');\n });\n $('#map-points-list-' + map.getContainer().id).html(legendHtml.join(''));\n }\n });\n}", "function initializeDataLayers(dataLayers) {\n\n dataLayers.forEach(function (layer) {\n dataLayers[dataLayers.indexOf(layer)] = new google.maps.Data();\n });\n\n}", "function makeDataLyrGroups() {\r\n var earlyYear = $(\".earlyYear\").first().val();\r\n var lateYear = $(\".lateYear\").first().val();\r\n for (var key in lyrGroups) {\r\n if (key === 'map') {\r\n var lateLayer = getDataTileLyr(lateYear);\r\n lyrGroups[key].data = L.layerGroup([lateLayer]);\r\n } else if (key === 'flickerMap') {\r\n var earlyLayer = getDataTileLyr(earlyYear);\r\n var lateLayer = getDataTileLyr(lateYear);\r\n lyrGroups[key].data = L.layerGroup([earlyLayer, lateLayer]);\r\n } else if (key === 'map1') {\r\n var earlyLayer = getDataTileLyr(earlyYear);\r\n lyrGroups[key].data = L.layerGroup([earlyLayer]);\r\n } else if (key === 'map2') {\r\n var lateLayer = getDataTileLyr(lateYear);\r\n lyrGroups[key].data = L.layerGroup([lateLayer]);\r\n } else if (key === 'map3') {\r\n var earlyLayer = getDataTileLyr(earlyYear);\r\n var lateLayer = getDataTileLyr(lateYear);\r\n lyrGroups[key].data = L.layerGroup([earlyLayer, lateLayer]);\r\n }\r\n }\r\n}", "function loadGeoJSONData() {\n d3.json(\"https://gist.githubusercontent.com/SkuliSkula/40b3417bd04c785faeadff3396c19c79/raw/1258f84e8ab2224819dfa7c9ba6383a4bcfa0ed5/iceland_min.geosjon\", \n function (error, data) {\n if (error) {\n return console.error(error);\n } \n initGeoVisualization(data);\n loadGasStations();\n });\n}", "function loadSaskGridData(){\r\n\r\n\tvar geoJsonUrl ='http://mblais-welldata.ca/geoserver/WellData/ows';\t\r\n\t\t\r\n\tvar wellVectorParameters = {\r\n\t\tservice: 'WFS',\r\n\t\tversion: '1.0.0',\r\n\t\trequest: 'getFeature',\r\n\t\ttypeName: 'WellData:sask_lsd_grid_wgs',\r\n\t\tmaxFeatures: 5000,\r\n\t\toutputFormat: 'application/json'\r\n\t\t};\r\n\t\t\t\r\n\tvar customParams = {\r\n\t\tbbox: map.getBounds().toBBoxString(),\r\n\t\t};\r\n\t\t\t\r\n\tvar parameters = L.Util.extend(wellVectorParameters, customParams);\r\n\t\t\r\n\t$.ajax({\r\n\t\turl: geoJsonUrl + L.Util.getParamString(parameters),\r\n\t\tdatatype: 'json',\r\n\t\ttype: 'GET',\r\n\t\tsuccess: loadGeoJson\r\n });\r\n\t\t\t\r\n\tfunction loadGeoJson(saskGridData){\r\n\t\t\tgeojsonLayerSaskGridData.addData(saskGridData);\r\n \t}\r\n}", "initializeGridBasedClusters () {\n\t\tlet maxX = this.params.maxX;\n\t\tlet maxY = this.params.maxY;\n\t\tlet minX = this.params.minX;\n\t\tlet minY = this.params.minY;\n\t\tlet dataSize = this.dataIn.length;\n\n\t\tlet numRow = Math.ceil( (maxY - minY) / this.params.cellHeight );\n\t\tlet numColumn = Math.ceil( (maxX - minX) / this.params.cellWidth );\n\n\t\tlet clusters = {\n\t\t\tclusters: [],\n\t\t\tdataLabel: [],\n\t\t\tdataSize: dataSize,\n\t\t\tnumRow: numRow,\n\t\t\tnumColumn: numColumn,\n\t\t\tnumCells: numRow * numColumn,\n\t\t};\n\n\t\tfor ( let i = 0; i < dataSize; i++ ) {\n\t\t\tclusters.dataLabel[i] = -1;\n\t\t}\n\n\t\tfor ( let i = 0; i < clusters.numCells; i++ ) {\n\t\t\tclusters.clusters[i] = {\n\t\t\t\tclusterSize: = 0, // counter over clusters\n\t\t\t\tvalid: false,\n\t\t\t\tgroup: [],\n\t\t\t\trepresent: [],\n\t\t\t};\n\t\t}\n\n\t\treturn clusters;\n\t}", "function displaygeojson(aquifer_number, displayallwells) {\n var region = $(\"#select_region\")\n .find(\"option:selected\")\n .val()\n //calls the loadjson ajax controller to open the aquifer shapefiles and return the appropriate geoJSON object for the aquifer\n $.ajax({\n url: apiServer + \"loadjson/\",\n type: \"GET\",\n data: { aquifer_number: aquifer_number, region: region },\n contentType: \"application/json\",\n error: function(status) {},\n success: function(response) {\n AquiferShape = response[\"data\"]\n name = response[\"aquifer\"]\n name = name.replace(/ /g, \"_\")\n var aquifer_center = []\n\n //find the center of the aquifer if an aquifer is selected. Add the aquifer to the map and zoom and pan to the center\n if (AquiferShape) {\n var AquiferLayer = L.geoJSON(AquiferShape, {\n onEachFeature: function(feature, layer) {\n feature.properties.bounds_calculated = layer.getBounds()\n var latcenter =\n (feature.properties.bounds_calculated._northEast.lat +\n feature.properties.bounds_calculated._southWest.lat) /\n 2\n var loncenter =\n (feature.properties.bounds_calculated._northEast.lng +\n feature.properties.bounds_calculated._southWest.lng) /\n 2\n aquifer_center = [latcenter, loncenter]\n },\n fillOpacity: 0.0,\n weight: 1\n })\n aquifer_group.addLayer(AquiferLayer)\n map.fitBounds(aquifer_group.getBounds())\n }\n //if no aquifer is loaded, zoom to the region boundaries\n else {\n map.fitBounds(region_group.getBounds())\n }\n\n aquifer_group.addTo(map)\n\n min_num = $(\"#required_data\")\n .find(\"option:selected\")\n .val()\n min_num = Number(min_num)\n id = aquifer_number\n\n var region = $(\"#select_region\")\n .find(\"option:selected\")\n .val()\n // This code calls the ajax controller get_aquifer_wells for a specific aquifer_id in a specific region\n // The code for get_aquifer_wells is in the model.py file\n // The controller queries the database for the appropriate region and aquifer_id number and returns response['data']\n // response['data'] is the geojson object of all wells in the aquifer with their properties and associated timeseries info\n $.ajax({\n url: apiServer + \"get_aquifer_wells/\",\n type: \"GET\",\n data: { aquifer_id: id, region: region },\n contentType: \"application/json\",\n error: function(status) {},\n success: function(response) {\n var well_points = response[\"data\"] //.features;\n //calls displayallwells\n displayallwells(aquifer_number, well_points, min_num)\n // Update the options that will be shown on the layer togglke for the map\n overlayMaps = {\n \"Aquifer Boundary\": aquifer_group,\n Wells: well_group,\n \"Water Table Surface\": interpolation_group\n }\n\n toggle.remove()\n toggle = L.control.layers(null, overlayMaps).addTo(map)\n }\n })\n }\n })\n}", "function loadPhotos(){\n var geoJson = [];\n\n for (var i = 0; i < photoList.length; i++) {\n var date = photoList[i].filename.slice(0,10);\n\n if (tracks[date]) {\n geoJson.push({\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": photoList[i].coordinates\n },\n \"properties\": {\n \"filename\": photoList[i].filename,\n \"caption\": photoList[i].caption\n }\n });\n }\n }\n\n photoLayer.on('layeradd', function(e) {\n var marker = e.layer,\n feature = marker.feature,\n filename = feature.properties.filename,\n caption = feature.properties.caption;\n\n var content = '<img width=\"200px\" src=\"photos/' +\n filename +\n '\"/><br/>';\n\n if (caption) { content = content + caption + '<br/>'; }\n\n content = content +\n '<a href=\"https://instagram.com/huntca\" target=\"_blank\">' +\n '📷 instagram/huntca' +\n '</a>';\n\n marker.bindPopup(content ,{\n closeButton: false,\n minWidth: 220,\n maxWidth: 220\n });\n\n marker.setIcon(L.icon({\n \"iconUrl\": \"photos/\" + filename,\n \"iconSize\": [50, 50],\n \"iconAnchor\": [25, 25],\n \"popupAnchor\": [0, -25],\n \"className\": \"dot\"\n }));\n });\n\n photoLayer.setGeoJSON(geoJson);\n photoCluster.addLayer(photoLayer);\n }", "function addCountiesToMap() {\nvar myStyle = {\n stroke: true,\n color: \"red\",\n weight: 1,\n fill: true,\n fillOpacity: 0,\n opacity: 1\n};\nvar geojsonLayer = new L.GeoJSON.AJAX(\"data/ukcounties.geojson\", {\n style: myStyle,\n onEachFeature: function onEachFeature(feature, layer) {\n layer.bindPopup(\"Region: \" + feature.properties.name);\n }\n});\ngeojsonLayer.addTo(map);\nconsole.log(\"Regional data has been added to the map\");\n}", "function addFeatures(nb) {\n var ext = map.getView().calculateExtent(map.getSize());\n var features = [];\n for (var i = 0; i < nb; ++i) {\n features[i] = new Feature(new Point([ext[0] + (ext[2] - ext[0]) * Math.random(), ext[1] + (ext[3] - ext[1]) * Math.random()]));\n features[i].set('id', i);\n features[i].setStyle(new Style({\n image: new Circle({\n stroke: new Stroke({\n color: \"rgba(0,0,192,0.5)\",\n width: 2\n }),\n fill: new Fill({\n color: \"rgba(0,0,192,0.3)\"\n }),\n radius: 5\n }),\n text: new Text({\n text: \"123\",\n fill: new Fill({\n color: '#000'\n })\n })\n }))\n }\n clusterSource.getSource().clear();\n clusterSource.getSource().addFeatures(features);\n}", "function loadStations(){\n for(var i = 0; i < stations.length; i++){\n \tvar temp = stations[i].geometry.coordinates + \"\";\n\t\tvar coords = temp.split(\",\");\n\t\tstationsArr.push(new Station(stations[i].properties.id, stations[i].properties.label, coords[0], coords[1], i));\n\t\tfeatures.push(stationsArr[i].getFeature());\n }\n \n clusters.addFeatures(features);\n}", "function filterData(filters) {\n resetCircleProps();\n removeMilestones();\n\n // fade the displayed points out\n map.setLayoutProperty('dirkShots', 'visibility', 'none');\n // map.setPaintProperty('dirkShots', 'circle-opacity', 0);\n\n // apply our filters\n map.setFilter('dirkShots', filters);\n\n if (filters.length >= 2) {\n map.setPaintProperty('dirkShots', 'circle-opacity', 0.55);\n map.setPaintProperty('dirkShots', 'circle-radius', { stops: [[17, 2], [18, 3.5], [19, 4]] });\n } else {\n map.setPaintProperty('dirkShots', 'circle-opacity', 0.4);\n map.setPaintProperty('dirkShots', 'circle-radius', { stops: [[17, 1], [18, 2.5], [19, 3]] });\n }\n\n // then after 1.2 seconds, fade our points back in. Large sets of points may\n // need more time to load and be painted.\n\n setTimeout(() => {\n map.setLayoutProperty('dirkShots', 'visibility', 'visible');\n }, 250);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(ie. anything between 0.0.0.0 and 255.255.255.255 is valid). split the string by . length should b 4. Check that each number is a valid number
function validIP(str) { numbers = str.split("."); if (numbers.length !== 4) return false; for (let i = 0; i < numbers.length; i++) { let number = parseInt(numbers[i]); if (number < 0 || number > 255) { return false; } } return true }
[ "function isValidIP(str) {\n if(str.split('.').length != 4) return false\n var arr = str.replace(/[^0-9]/g, '.').split('.')\n if(arr.length != 4) return false\n for(var i = 0; i < 4; i++){\n if(arr[i] < 0 || arr[i] > 255 || arr[i] == '') return false\n if(arr[i].length > 1 && arr[i][0] == 0) return false\n } \n console.log(arr);\n return true\n }", "function isValidIP(str) {\n // splits each at . and puts them into an array\n str = str.split('.');\n let countCheck = 0;\n // checks if any of the numbers start with 0\n for (let i = 0; i < str.length; i++) {\n let count = 0;\n if ((str[i][0] == 0) && (str[i][0].length > 1)) count++;\n console.log(count);\n if (count > 0) return false;\n if ((Number(str[i]) < 255) && (Number(str[i]) >= 0)) countCheck++;\n if (countCheck == 4) return true;\n }\n // number can range up to 255 between each\n\n // can only have 4 substrings\n return false;\n}", "function isValidIP(str) {\n console.log(str);\n\n if (str.indexOf(' ') > -1) return false;\n const arr = str.split('.');\n\n if (arr.length !== 4) {\n return false;\n }\n\n let isValid = true;\n\n arr.forEach(item => {\n if (isNaN(+item)) {\n isValid = false;\n }\n if (+item > 255 || +item < 0) {\n isValid = false;\n }\n if (+item > 0 && item.substring(0, 1) === '0') {\n isValid = false;\n }\n })\n return isValid;\n \n}", "function check_ip_format(ipname) {\r\n var tmp;\r\n var regx = /^[0-9]+$/;\r\n tmp = $('#' + ipname).val();\r\n spit_ip_array = tmp.split(\".\");\r\n if (spit_ip_array.length < 4) \r\n return 0;\r\n\r\n for (var i = 0; i < spit_ip_array.length; i++) {\r\n if (!regx.test(spit_ip_array[i])) \r\n return 0;\r\n else if (Number(spit_ip_array[i]) > 255) \r\n return 0;\r\n }\r\n\r\n return 1;\r\n}", "function isIPv4Address(inputString) {\n let good = true\n const regex = /[a-zA-Z]/g\n const arr = inputString.split('.')\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] === \"\") {\n good = false\n break\n } else if((arr[i] > 255) || (arr[i] < 0)) {\n good = false\n break\n } else if(regex.test(arr[i])) {\n good = false\n break\n } else if(arr[i].includes(0)) {\n const check = arr[i].split('')\n if((check.length > 1) && (check[0] === '0')) {\n good = false\n break\n }\n }\n }\n\n if(arr.length !== 4) {\n good = false\n }\n return good\n}", "function isIPv4Address(a) {\n let result = true\n a.split(\".\").length === 4 ? result = true : result = false\n a.split(\".\").map(function (e) {\n if (Number(e) < 0 || Number(e) > 255 || e.length === 0 || e.length > 4 || isNaN(e)) result = false\n })\n\n return result\n}", "function isIPv4Address(inputString) {\n inputString = inputString.split('.');\n if(inputString.length != 4){\n return false;\n }\n for(var i = 0; i < inputString.length; i++){\n if(inputString[i] < 0 || inputString[i] > 255 || inputString[i] === '' || isNaN(inputString[i]) ){\n return false;\n }\n }\n return true;\n}", "function isValidIP(objIP) \r\n\t{\r\n\t\tvar strIPtext = objIP.value; \r\n\t\tif ((strIPtext.length == 0) || IsAllSpaces(strIPtext)) \r\n\t\t{ \r\n\t\t\t// IP Empty\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\t\r\n\t\tif ( countChars(strIPtext,\".\") != 3) \r\n\t\t{ \r\n\t\t\t// Invalid Format, number of dots is not 3\r\n\t\t\treturn 2;\r\n\t\t}\r\n\t\tvar arrIP = strIPtext.split(\".\");\r\n\t\t\t\r\n\t\tfor(var i = 0; i < 4; i++)\r\n\t\t{\r\n\t\t\tif ( (arrIP[i].length < 1 ) || (arrIP[i].length > 3 ) )\r\n\t\t\t{\r\n\t\t\t\t// Invalid Format, continuous dots or more than 3 digits given between dots\r\n\t\t\t\treturn 2;\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\tif ( !isInteger(arrIP[i]) )\r\n\t\t\t{\r\n\t\t\t\t// non-integers present in the value\r\n\t\t\t\treturn 3;\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\tarrIP[i] = parseInt(arrIP[i]);\r\n\t\t\t\t\r\n\t\t\tif(i == 0)\r\n\t\t\t{\r\n\t\t\t\t// start IP value\r\n\t\t\t\tif(arrIP[i] == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\t// start IP value must not be 0\r\n\t\t\t\t\treturn 8;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(arrIP[i] > 223)\r\n\t\t\t\t{\r\n\t\t\t\t\t// start IP must not be > 223\r\n\t\t\t\t\treturn 4;\r\n\t\t\t\t}\r\n\t\t\t\tif(arrIP[i] == 127)\r\n\t\t\t\t{\r\n\t\t\t\t\t// start IP must not be 127 - Loopback ip\r\n\t\t\t\t\treturn 5;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t// the 2nd, 3rd and 4th IP values between the dots\r\n\t\t\t\t// these must not be more than 255\r\n\t\t\t\tif (arrIP[i] > 255)\r\n\t\t\t\t{\r\n\t\t\t\t\t// IP out of bound\r\n\t\t\t\t\treturn 6;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\r\n\t\tobjIP.value = arrIP.join(\".\");\r\n\t\t\t\r\n\t\tif(objIP.value == \"0.0.0.0\")\r\n\t\t{\r\n\t\t\t// IP all zeros\r\n\t\t\treturn 7;\r\n\t\t}\t\r\n\t\t\t\r\n\t\treturn 0;\r\n\t\t\t\r\n\t}\t// end of isValidIP", "function isIPv4Address(inputString) {\n let arr = inputString.split('.');\n if (arr.length !== 4) {\n return false;\n }\n return arr.every(i => i !== '' && +i < 256 && parseInt(i) >= 0);\n}", "function ipv4() {\n function checkNum(n) {\n return n >= '0' && n <= '9';\n }\n let num = 0;\n let count = 0;\n\n for (let i = 0; i < ip.length; i++) {\n if (Number(ip[i]) == NaN || ip[i] == ':') return 'Neither';\n if (\n ip[i] == '0' &&\n checkNum(ip[i + 1]) &&\n (ip[i - 1] == '.' || i == 0 || i + 1 > ip.length)\n ) {\n return 'Neither';\n }\n\n while (ip[i] != '.' && i < ip.length) {\n if (ip[i] >= '0' && ip[i] <= '9') {\n num = num * 10 + Number(ip[i]);\n i++;\n } else return 'Neither';\n }\n if (ip[i] == '.') count++;\n if (\n num > 255 ||\n (ip[i] == '.' && (ip[i + 1] == '.' || i + 1 > ip.length - 1))\n )\n return 'Neither';\n num = 0;\n }\n if (count != 3) return 'Neither';\n return 'IPv4';\n }", "function isIPv4Address(inputString) {\n const inputArray = inputString.split(\".\");\n return (\n inputArray.length === 4 &&\n inputArray.every(\n (number) =>\n +number > -1 &&\n +number < 256 &&\n String(+number).length === number.length\n )\n );\n}", "function vdt_validaIP(ip) {\n \n if (ip.indexOf('.') > 0) {\n var arr = ip.split('.');\n if (arr.length == 4) {\n var a = parseInt(arr[0]);\n var b = parseInt(arr[1]);\n var c = parseInt(arr[2]);\n var d = parseInt(arr[3]);\n if (a >= 1 && a <= 254 &&\n b >= 1 && b <= 254 &&\n c >= 1 && c <= 254 &&\n d >= 1 && d <= 254)\n return true;\n }\n }\n return false;\n}", "function isIpRangeOrNetwork(val) {\n var pieces = val.split(\".\"), i, block;\n if (pieces.length !== 4) {\n return false;\n }\n\n // go through each octet and make sure it is either\n // a number or a number with a / or a .\n for (i=0; i<pieces.length; i++) {\n block = pieces[i];\n block = block.replace(\"/\", \"\");\n block = block.replace(\"-\", \"\");\n if (!Ext.isNumeric(block)) {\n return false;\n }\n }\n return true;\n }", "function validIPAddresses(string) {\n let results = [];\n //now let's look through all the possible positions where we can insert a period!\n for (let i = 0; i < Math.min(string.length, 4); i++) {\n let curIP = [\"\", \"\", \"\", \"\"];\n //decide what will be our first part of IP\n curIP[0] = string.slice(0, i); //will give us whatever is before the 1st period we place\n if (!isValidPart(curIP[0])) continue;\n //once we found the place for first period=>found first valid part\n //let's find the next valid parts(the place where to insert the next period) that we can generate\n //with curIP[0]\n //i+1 becase we want to put next period at least one more position from previous and AT MOST 3 positions past i\n for (let j = i + 1; j < i + Math.min(string.length - i, 4); j++) {\n curIP[1] = string.slice(i, j); //we start from index i(after the previous valid part) and j -is where we place the next period\n if (!isValidPart(curIP[1])) continue;\n\n for (let k = j + 1; k < j + Math.min(string.length - j, 4); k++) {\n curIP[2] = string.slice(j, k); //we start from index j after the previous valid part) and untill k -is where we place the next period\n curIP[3] = string.slice(k); // the last 4th part is whatever is left after the third part\n if (isValidPart(curIP[2]) && isValidPart(curIP[3])) {\n results.push(curIP.join(\".\"));\n }\n }\n }\n }\n return results;\n}", "function validateAddress(entry) {\n var ip_port = entry.split(\" \");\n var blocks = ip_port[0].split(\".\");\n\n if (ip_port.length < 2)\n return false;\n\n if(blocks.length === 4) {\n return blocks.every(function(block) {\n return parseInt(block,10) >=0 && parseInt(block,10) <= 255;\n });\n }\n return false;\n}", "function isIPv4Address(inputString) {\n const octets = inputString.split('.'); // octets = ['172', '1', '254', '1']\n\n if (octets.length !== 4) return false; // .length = 4\n\n for (let i = 0; i < octets.length; i++) { // i = 0; length = 4\n const octet = octets[i]; // octets[0] = '172'\n if (isNaN(+octet)) return false; // isNaN(172) = false;\n if (+octet < 0 || +octet > 255) return false;\n if (octet.length > 1 && octet[0] === '0') return false;\n if (octet === '') return false;\n }\n\n return true;\n}", "function isProbablyIpv4(hostname) {\n // Cannot be shorted than 1.1.1.1\n if (hostname.length < 7) {\n return false;\n }\n // Cannot be longer than: 255.255.255.255\n if (hostname.length > 15) {\n return false;\n }\n let numberOfDots = 0;\n for (let i = 0; i < hostname.length; i += 1) {\n const code = hostname.charCodeAt(i);\n if (code === 46 /* '.' */) {\n numberOfDots += 1;\n }\n else if (code < 48 /* '0' */ || code > 57 /* '9' */) {\n return false;\n }\n }\n return (numberOfDots === 3 &&\n hostname.charCodeAt(0) !== 46 /* '.' */ &&\n hostname.charCodeAt(hostname.length - 1) !== 46 /* '.' */);\n}", "function ipAddrValueFormatCheck(ipAddr){\n if (!ipAddr) \n return false;\n var ipObjArr = ipAddr.split(\".\")\n if (ipObjArr.length != 4) \n return false;\n /* Check IP Address Octet Range */\n if (ipAddrOctetCheck(ipObjArr) == false) \n return false;\n return true;\n}", "function isValidIPv4Len(len)\r\n{\r\n if (len.length < 1 || isNaN(len) || parseInt(len) > 32 || parseInt(len) < 0 /*|| parseInt(len)%8!=0*/)\r\n {\r\n return false;\r\n }\r\n return true;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We need a way to get X
getX() { return this.x; }
[ "function getX() {\r\n\r\n return x;\r\n\r\n }", "function getX() {\n return this.x;\n }", "function getX() {\n\n\t\treturn this.x;\n\t}", "get x()\n\t{\n\t\tif (this._x != null)\n\t\t\treturn this._x;\n\n\t\t/*\n\t\tif (this.isInput)\n\t\t\treturn this.node.posSmooth.x;\n\n\t\treturn this.node.posSmooth.x + this.node.width;\n\t\t*/\n\n\t\treturn this.node.input.plugPositions()[this.isInput ? 'inputs'\n\t\t\t: 'outputs'].filter(o => o.plug === this)[0].x;\n\t}", "X(){return this.faceXAxis;}", "function getXValue() {\n\t/* jshint validthis: true */ // TODO: eslint\n\treturn this._xValue;\n} // end FUNCTION getXValue()", "getX(index) {\n return this.xy[index * 2];\n }", "getX(index) {\n return this.xy[index * 2];\n }", "get xValue() {\r\n return this.i.c;\r\n }", "getMouseX() {}", "X(x) {\n return x * this.state.zoom*METERS_PER_PIXEL +Math.floor(this.paper.width/2); \n }", "x(){\n return this.equipment.position[0];\n }", "get xPosition() { return this._xPosition; }", "function xX(d) {\n\t\t\treturn xScale(d[0]);\n\t\t}", "get xRange() {\n return this.getXRange();\n }", "function X(d) {\n return xscale(d[0]);\n }", "function X(d) {\n return xScale(d.x);\n }", "function getTransformX() {\n\t\t\t\tvar transformArray = $this.css(\"-webkit-transform\").split(\",\"); // matrix(1, 0, 0, 1, 0, 0)\n\t\t\t\tvar transformElement = $.trim(transformArray[4]); // remove the leading whitespace.\n\t\t\t\treturn transformX = Number(transformElement); // Remove the ). \n\t\t\t}", "get contentX() {\n return this.targetPosition[0];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TAB BUTTON ACTION FUNCTIONS copy tabcontent body contents
function copyContents(object) { // get tab contents let modalTabContent = object.closest('.modal-tab-content').querySelector('.modal-tab-content-body'); // obtain inner html from element let content = modalTabContent.innerHTML; // copy to clipboard navigator.clipboard.writeText(content); }
[ "function copyTabs() {\n getCurrentWindowTabs().then((tabs) => {\n let tabList = \"\";\n\n browser.storage.sync.get(\"outputFormat\").then((res) => {\n const outputFormat = res.outputFormat;\n\n for (var tab of tabs) {\n tabList += convertTabToListItem(tab, outputFormat);\n }\n browser.runtime.sendMessage({ content: tabList });\n\n document.querySelector(\"#message\").innerHTML =\n \"Copied \" + tabs.length + \" tabs\";\n });\n });\n}", "function copyTabSources() {\n text = \"\";\n sourceBuffer.forEach((elem) => {\n text += \n elem.repoId + \"\\t\" +\n elem.sourceId + \"\\t\" +\n elem.linesInFile + \"\\t\" +\n elem.sourceUrl + \"\\n\"\n });\n textArea = document.getElementById(\"copyText\");\n textArea.value = text;\n textArea.focus();\n textArea.select();\n}", "saveContentActive(content){\n this.tabsList[this.getActiveTabIndex()].setContent(content);\n }", "function handlePageActionClick(tab) {\n sendMessageToContentScript(tab, {});\n}", "async function copyMarkdownFromContext(info, tab) {\n try{\n await ensureScripts(tab.id);\n if (info.menuItemId == \"copy-markdown-link\") {\n const options = await getOptions();\n options.frontmatter = options.backmatter = '';\n const { markdown } = turndown(`<a href=\"${info.linkUrl}\">${info.linkText}</a>`, { ...options, downloadImages: false });\n //await browser.tabs.executeScript(tab.id, {code: `copyToClipboard(${JSON.stringify(markdown)})`});\n await navigator.clipboard.writeText(markdown);\n }\n else if (info.menuItemId == \"copy-markdown-image\") {\n await browser.tabs.executeScript(tab.id, {code: `copyToClipboard(\"![](${info.srcUrl})\")`});\n await navigator.clipboard.writeText(`![](${info.srcUrl})`);\n }\n else {\n const article = await getArticleFromContent(tab.id, info.menuItemId == \"copy-markdown-selection\");\n const { markdown } = await convertArticleToMarkdown(article, downloadImages = false);\n //await browser.tabs.executeScript(tab.id, { code: `copyToClipboard(${JSON.stringify(markdown)})` });\n await navigator.clipboard.writeText(markdown);\n }\n }\n catch (error) {\n // This could happen if the extension is not allowed to run code in\n // the page, for example if the tab is a privileged page.\n console.error(\"Failed to copy text: \" + error);\n };\n}", "function doCopy(dataType, dataAction, onSuccess){\n let options = {currentWindow:true};\n\tif (dataAction == 'single'){\n\t\toptions['active'] = true;\n\t}\n\tlet mime = (dataType == 'rich') ? 'text/html': 'text/plain';\n\tlet allText = '';\n\tchrome.tabs.query(options, (tabs)=>{\n\t\tfor (let i=0; i<tabs.length; i++){\n\t\t\tlet txt = 'ERROR - Sorry something went wrong.';\n\t\t\tlet tab_title = tabs[i].title;\n\t\t\tlet tab_url = tabs[i].url;\n\t\t\t// remove leading \"notification counts\" that websites have started to add\n\t\t\t// For info, watch : https://www.youtube.com/watch?v=bV0QNuhN9fU&t=64s\n\t\t\tlet matches = tab_title.match(/^(\\([0-9]+\\) )?(.*)$/);\t\t\t\n\t\t\tif (matches) {\n\t\t\t\ttab_title = matches[2];\n\t\t\t}\n\t\t\tif (dataType === 'dash') {\n\t\t\t\ttxt = tab_title + ' - ' + tab_url;\n\t\t\t}\n\t\t\telse if (dataType == 'bracket') {\n\t\t\t\ttxt = '[' + tab_title + '] ' + tab_url;\n\t\t\t}\n\t\t\telse if (dataType == 'newline') {\n\t\t\t\ttxt = tab_title + '\\n' + tab_url;\n\t\t\t}\n\t\t\telse if (dataType == 'html' || dataType == 'rich') {\n\t\t\t\ttxt = '<a href=\"' + tab_url + '\">' + tab_title + '</a>';\n\t\t\t}\n\t\t\telse if (dataType == 'md') {\n\t\t\t\tlet prefix = '';\n\t\t\t\tif (isImage(tab_url)){\n\t\t\t\t\tprefix = '!';\n\t\t\t\t}\n\t\t\t\ttxt = prefix + '[' + tab_title + '](' + tab_url + ')';\n\t\t\t}\n\t\t\telse if (dataType == 'bb') {\n\t\t\t\tif (isImage(tab_url)){\n\t\t\t\t\ttxt = '[img]'+tab_url+'[/img]';\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttxt = '[url='+tab_url+']'+tab_title+'[/url]';\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (dataType == 'url') {\n\t\t\t\ttxt = tab_url;\n\t\t\t}\n\t\t\telse if (dataType == 'title') {\n\t\t\t\ttxt = tab_title;\n\t\t\t}\n\t\t\tallText += txt;\n\t\t\tif (tabs.length > 1){\n\t\t\t\tallText += (dataType == 'html' || dataType == 'rich') ? '<br/>\\n' : '\\n';\n\t\t\t}\n\t\t}\n\n copyToClip(mime,allText);\n if (onSuccess){\n onSuccess(allText);\n }\n });\n \n\t\n\t// dataType is user's selection on menu\n\tgetDataTypes('dash', Lookup.DataTypes, Lookup.DefaultConfig, (loadedDataType, loadedDataTypes, loadedSortType)=>{\n\t\tsetDataTypes(dataType, loadedDataTypes, loadedSortType, ()=>{});\t\n\t\tinitContextMenu(dataType, loadedDataTypes, loadedSortType);\n\t});\n}", "function copyPage() {\n var $wp = $('.write-pages li'); // the list of book pages\n var $page = $($wp.get(editIndex)); // the current page\n var $copy = $page.clone();\n $page.after($copy);\n setModified();\n $editDialog.dialog('option', 'title', $('.wlPageCopied').html());\n }", "shareResultForumCopyButtonClickHandler() {\n UI.$shareResultForum.select();\n document.execCommand(\"copy\");\n }", "async function copyTabAsMarkdownLink(tab) {\n try {\n await ensureScripts(tab.id);\n const article = await getArticleFromContent(tab.id);\n const title = await formatTitle(article);\n //await browser.tabs.executeScript(tab.id, { code: `copyToClipboard(\"[${title}](${article.baseURI})\")` });\n await navigator.clipboard.writeText(`[${title}](${article.baseURI})`);\n }\n catch (error) {\n // This could happen if the extension is not allowed to run code in\n // the page, for example if the tab is a privileged page.\n console.error(\"Failed to copy as markdown link: \" + error);\n };\n}", "function copySimulationJobInPanel(){\n \t$(\"#\" + namespace + \"header-li-copy\").click();\n }", "function onCopy(e) {\n chrome.runtime.sendMessage({event: \"copy\"});\n}", "function copyContent(event) {\n\tlet textarea = document.getElementById(event.target.id.split(\"-copy\")[0]);\n\ttextarea.select();\n\tdocument.execCommand('copy');\n}", "function onCopyClick(){\r\n\t\t\r\n\t\tg_ucAdmin.validateDomElement(g_objBottomCopyPanel, \"bottom copy panel\");\r\n\t\t\r\n\t\tvar arrIDs = g_objItems.getSelectedItemIDs();\r\n\t\t\r\n\t\tif(arrIDs.length == 0)\r\n\t\t\treturn(false);\r\n\t\t\r\n\t\tg_objBottomCopyPanel.data(\"item_ids\", arrIDs);\r\n\t\t\r\n\t\t//set title\r\n\t\tif(arrIDs.length == 1){\r\n\t\t\tvar objItem = g_objItems.getSelectedItem();\r\n\t\t\tvar title = objItem.data(\"title\");\r\n\t\t}else{\t\t//multiple names\r\n\t\t\t\r\n\t\t\tvar title = arrIDs.length + \" templates\";\r\n\t\t}\r\n\t\t\r\n\t\tg_objBottomCopyPanel.find(\".uc-copypanel-addon\").html(title);\r\n\t\t\r\n\t\t//disable move button\r\n\t\tvar objButtonMove = g_objBottomCopyPanel.find(\".uc-button-copypanel-move\");\r\n\t\tobjButtonMove.addClass(\"button-disabled\");\r\n\t\t\r\n\t\t\r\n\t\tg_objBottomCopyPanel.show();\r\n\t\t\r\n\t}", "function copyTabComments() {\n text = \"\";\n commentBuffer.forEach((elem) => {\n text += elem.natLangId + \"\\t\" +\n elem.progLang + \"\\t\" + \n elem.repoId + \"\\t\" + \n elem.sourceId + \"\\t\" + \n elem.commentId + \"\\t\" + \n elem.comment.split(\"\\t\").join(\"\\\\t\") + \"\\t\" + \n elem.label + \"\\n\"\n });\n textArea = document.getElementById(\"copyText\");\n textArea.value = text;\n textArea.focus();\n textArea.select();\n}", "onChromeClick() {\n\t\treturn sendMessage({\n\t\t\ttype: CREATE_TAB,\n\t\t\turl: `view-source:${this.state.tabUrl}`\n\t\t});\n\t}", "function copyToClipboard() {\n var node = $('#theModal .command-line').get(0);\n selectContent(node);\n document.execCommand('copy');\n }", "function copy_SelText_PageAddress(info, tab)\r\n{\r\n\tvar textToCopy = info.selectionText + \" | \" + info.pageUrl;\r\n\tcopyTextToClipboard(\"textToCopy\", textToCopy);\r\n}", "function jiraCopy() {\n // content to be copied\n var copyText = `Template to copy to your clipboard here`;\n // create a textarea element\n let input = document.createElement('textarea');\n // setting it's type to be text\n input.setAttribute('type','text');\n // setting the input value to equal to the Jira template\n input.value = copyText;\n // appending it to the document\n document.body.appendChild(input);\n // calling the select, to select the text displayed\n // if it's not in the doc I wont be able to do that\n input.select()\n // calling the copy cmd\n document.execCommand('copy');\n document.querySelector('#jiraCopyBtn').innerHTML = \"COPIED\";\n // removing the input from the document\n document.body.removeChild(input);\n }", "function Tabcontent() {\r\n $('.menu .item').tab({\r\n cache: false,\r\n alwaysRefresh: true,\r\n history: true,\r\n historyType: 'hash',\r\n apiSettings: {\r\n loadingDuration : 1000,\r\n url: 'modules/{$tab}.html'\r\n }\r\n });\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Derivation of a common shared secret for importing / exporting encrypted credentials depending on input.selectImport
async function getSharedSecret(selectElement) { const transfer = await sendMessage({ action: 'get-transfer-settings' }); const idx = selectElement.value; return idx < 0 ? getMySecretBlocks(master, false, 'SHARED_SECRET') // long secret derived from master key : getMySecretBlocks(master, true, transfer[idx].name); // short secret derived from master key + the transfer name }
[ "function importSecretKey() { \n let rawPassword = str2ab(password.value); // convert the password entered in the input to an array buffer\n return window.crypto.subtle.importKey(\n \"raw\", //raw\n rawPassword, // array buffer password\n {\n length: DEC.algoLength,\n name: DEC.algoName1\n }, //the algorithm you are using\n false, //whether the derived key is extractable \n DEC.perms1 //limited to the options encrypt and decrypt\n );\n\n}", "_getSharedSecret() {\n // Once every ~256 attempts, we will get a key that starts with a `00` byte, which\n // can lead to problems initializing AES if we don't force a 32 byte BE buffer.\n return Buffer.from(this.key.derive(this.ephemeralPub.getPublic()).toArray('be', 32));\n }", "computeSharedSecret(other) {\n const pubKey = SigningKey.computePublicKey(other);\n return (0, index_js_1.hexlify)(secp256k1.getSharedSecret((0, index_js_1.getBytesCopy)(this.#privateKey), (0, index_js_1.getBytes)(pubKey)));\n }", "computeSharedSecret(other) {\n const pubKey = SigningKey.computePublicKey(other);\n return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey)));\n }", "formatSecret() {\n return \"0x\" + this.secret.toString('hex')\n }", "function secretFile() {\n return path.join(ssbLoc(), \"secret\")\n}", "getSecret () {\n const secret = crypto.randomBytes(32);\n const hash = crypto.createHash('sha256').update(secret).digest('hex');\n\n return {\n secret: secret,\n hash: hash\n };\n }", "function getKeyMaterial() {\n const password = window.prompt(\"Enter your password \");\n const enc = new TextEncoder();\n return window.crypto.subtle.importKey(\n 'raw',\n enc.encode(password), {\n name: 'PBKDF2'\n },\n false,\n ['deriveBits', 'deriveKey']);\n}", "function getKeyMaterial() {\n let password = window.prompt(\"Enter your password\");\n let enc = new TextEncoder();\n return window.crypto.subtle.importKey(\n \"raw\",\n enc.encode(password),\n {name: \"PBKDF2\"},\n false,\n [\"deriveBits\", \"deriveKey\"]\n );\n }", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n command_1.issueCommand('set-secret', {}, val);\r\n}", "function getKeyMaterial() {\n const password = window.prompt(\"Enter your password\");\n const enc = new TextEncoder();\n return window.crypto.subtle.importKey(\n \"raw\", \n enc.encode(password), \n {name: \"PBKDF2\"}, \n false, \n [\"deriveBits\", \"deriveKey\"]\n );\n }", "function getKeyMaterial() {\n const password = window.prompt(\"Enter your password\");\n const enc = new TextEncoder();\n return window.crypto.subtle.importKey(\n \"raw\",\n enc.encode(password),\n { name: \"PBKDF2\" },\n false,\n [\"deriveBits\", \"deriveKey\"]\n );\n }", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n // the runner will error with not implemented\r\n // leaving the function but raising the error earlier\r\n command_1.issueCommand('set-secret', {}, val);\r\n throw new Error('Not implemented.');\r\n}", "function PasswordEncryption(password) {\n return password;\n}", "function exportSecret(name, val) {\n exportVariable(name, val);\n // the runner will error with not implemented\n // leaving the function but raising the error earlier\n command_1.issueCommand('set-secret', {}, val);\n throw new Error('Not implemented.');\n}", "function setSecret(data) {\n secret = data;\n}", "deriveKeys () {\n this.masterSecret = PRF256(this.preMasterSecret, 'master secret',\n concat([this.clientRandom, this.serverRandom]), 48)\n\n const keys = PRF256(this.masterSecret, 'key expansion',\n concat([this.serverRandom, this.clientRandom]), 2 * (20 + 16) + 16)\n\n this.clientWriteMacKey = keys.slice(0, 20)\n this.serverWriteMacKey = keys.slice(20, 40)\n this.clientWriteKey = keys.slice(40, 56)\n this.serverWriteKey = keys.slice(56, 72)\n this.iv = Array.from(keys.slice(72))\n .reduce((sum, c, i) =>\n (sum + BigInt(c) << (BigInt(8) * BigInt(i))), BigInt(0))\n }", "bootstrapSecretStorage(opts) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.bootstrapSecretStorage(opts);\n }", "getOTPSecret() {\n this.generateNewOwnerKey();\n const bin = crypto.randomBytes(20);\n const base32 = b32.encode(bin).toString(\"utf8\").replace(/=/g, \"\");\n\n var secret = base32\n .toLowerCase()\n .replace(/(\\w{4})/g, \"$1 \")\n .trim()\n .split(\" \")\n .join(\"\")\n .toUpperCase();\n //secret = \"JBSWY3DPEHPK3PXP\"; // for testing\n this.walletData = Object.assign(this.walletData, {secret: secret, salt: bin.readUIntLE(0, 3)})\n \n //DEBUG\n console.log(\"DEBUG:\", getTOTP(this.walletData.secret, 2));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
executes script /srv/jboss/tools/jbossslotmanager.sh on machineName with passedInArgument as parameter e.g executeSlotManagerScriptServer("vtjbs03.retraite.lan", "getallfreeslots")
function executeSlotManagerScriptServer(machineName, passedInArgument) { var os = getMachine(machineName); // e.g. /srv/jboss/tools/jboss-slot-manager.sh var jbossSlotManagerScript = getJbossSlotManagerScript(); var criteria = new ResourceCriteria(); criteria.addFilterResourceKey(jbossSlotManagerScript); criteria.addFilterParentResourceId(os.id) var servers = ResourceManager.findResourcesByCriteria(criteria); // we found no script server instance if (servers.size() == 0) { println("No Script server " + jbossSlotManagerScript + " found on machine " + machineName); return null; } // we have an existing script server instance else if (servers.size()==1) { var scriptServer = servers.get(0); //set the config properties for the operation var config = new Configuration(); config.put(new PropertySimple("arguments", passedInArgument) ); // we schedule the execution of the script without using the result variable that is returned var result = OperationManager.scheduleResourceOperation(scriptServer.id, "execute", 0, 1, 0, 10000000, config, "description"); // search in Operations History for the right var opcrit = ResourceOperationHistoryCriteria(); var array = []; array[0] = scriptServer.id; opcrit.addFilterResourceIds(array); // fetchResults has to be set to true, otherwise the "output" value is not retrived opcrit.fetchResults(true); opcrit.addFilterOperationName("execute"); // we need to add a sleep of 3 seconds to be sure that the database was updated, therefore the operationsArray is up to date java.lang.Thread.currentThread().sleep(3000); var operationsArray = OperationManager.findResourceOperationHistoriesByCriteria(opcrit); // get the operation data var lastHistoryOperationIndex = 0; var arraySize = operationsArray.totalSize.toString(); if ( arraySize =! 0) { lastHistoryOperationIndex = arraySize - 1; } var lastHistoryOperation = operationsArray.get(lastHistoryOperationIndex); // get the results var returnConfigurationObject = lastHistoryOperation.getResults(); var outputValueOfScript = returnConfigurationObject.getSimpleValue("output"); return outputValueOfScript; } else { throw error("multiple ressources correspond to your criteria getAllAvailableSlots("+ machineName + "," + jbossSlotManagerScript +")"); } }
[ "function createSlotManagerScriptServer(machineName) {\n\n var os = getMachine(machineName);\n\n // e.g. /srv/jboss/tools/jboss-slot-manager.sh\n var jbossSlotManagerScript = getJbossSlotManagerScript();\n\n var jbossSlotManagerScriptDirectory = jbossSlotManagerScript.substring(0, jbossSlotManagerScript.lastIndexOf('/'));\n\n var jbossSlotManagerScriptDescription = \"jboss-slot-manager.sh [get-free-slot , get-all-free-slots , get-all-slots-used-and-free]\";\n\n var conf = new Configuration();\n conf.put(new PropertySimple(\"executable\", jbossSlotManagerScript));\n conf.put(new PropertySimple(\"workingDirectory\", jbossSlotManagerScriptDirectory));\n conf.put(new PropertySimple(\"fixedDescription\", jbossSlotManagerScriptDescription));\n\n server = DiscoveryBoss.manuallyAddResource(getScriptServerType().id, os.id, conf);\n return server;\n}", "function execSite(name) {\n var script = 'site/' + name + '.js';\n port.postMessage({script: script});\n}", "function runScript(name, args) {\n var ScriptExecutionInfo = { \"ScriptName\": name, \"Arguments\": args};\n var seiJson = JSON.stringify(ScriptExecutionInfo);\n\n if (typeof(JSViz) != 'undefined' && JSViz.version.major > 2){\n // Spotfire 7.5:\n Spotfire.modify(\"script\", ScriptExecutionInfo);\n }\n else if (proClient && window.Spotfire){\n // Spotfire 6/7 Professional:\n window.Spotfire.RunScript(seiJson);\n }\n else {\n // Spotfire 6/7 Web Player:\n values = { \"script\": \"script\", \"ScriptExecutionInfo\": seiJson};\n XmlHttp.post(window.location.href, values, CustomVisualization.update, errorHandler);\n }\n}", "function callStartScript(arg){\n jQuery.ajax({ \n \ttype: \"POST\",\n url: \"cgi_bin/starting_script.php\",\n dataType: \"script\",\n data:{setting: arg}, \n async: true,\n success: function(body){ \n alert('response received: ' + arg); \n } \n }); \n\n}", "function runScript(script) {\n\t\t$.ajax({\n\t\t\turl: \"http://\" + settings.esp32_host + \"/run\",\n\t\t\tcontentType: \"application/javascript\",\n\t\t\tmethod: \"POST\",\n\t\t\tdata: script,\n\t\t\tsuccess: function() {\n\t\t\t\tconsole.log(\"Code sent for execution.\");\n\t\t\t}\n\t\t}); // .ajax\n\t}", "function callStopScript(arg){\n jQuery.ajax({ \n \ttype: \"POST\",\n url: \"cgi_bin/stopping_script.php\",\n dataType: \"script\",\n data:{setting: arg}, \n async: true,\n success: function(body){ \n alert('response received: ' + arg); \n } \n }); \n\n}", "function runMachine(clickedId) {\n // if bought snickers\n if(clickedId == \"snickers\") {\n aVendingMachone.buySnickers()\n } else if(clickedId == \"kitkat\") { // if bought kitkat\n aVendingMachone.buyKitkat()\n } else { // if bought lays\n aVendingMachone.buyLays()\n }\n\n // render the page everytime something is bought\n machineDiv.innerHTML = aVendingMachone.render()\n}", "function widget(cmd)\n{\n\tprocess.kill()\n\tprocess = new QProcess()\n process.start(Amarok.Info.scriptPath()+\"/widget.sh\", [cmd])\n}", "function LaunchRemoteRazzle(params)\r\n{\r\n var vRet = 'ok';\r\n var strCmd = '';\r\n\r\n // Arbitrarily use the first enlistment\r\n var strSDRoot = PublicData.aBuild[0].hMachine[g_MachineName].aEnlistment[0].strRootDir;\r\n\r\n if (!params.IsEqualNoCase(g_MachineName))\r\n {\r\n return 'Unknown machine name: ' + params;\r\n }\r\n\r\n // If the process is already started, do nothing.\r\n\r\n if (g_pidRemoteRazzle == 0)\r\n {\r\n var strMach;\r\n\r\n if (PrivateData.aEnlistmentInfo == null || PrivateData.aEnlistmentInfo[0] == null ||\r\n PrivateData.aEnlistmentInfo[0].hEnvObj[ENV_PROCESSOR_ARCHITECTURE] == null)\r\n {\r\n vRet = 'Unable to determine processor architecture; PROCESSOR_ARCHITECTURE env var missing';\r\n return vRet;\r\n }\r\n\r\n strMach = PrivateData.aEnlistmentInfo[0].hEnvObj[ENV_PROCESSOR_ARCHITECTURE];\r\n\r\n // For remote.exe below, \"BldCon\" is the remote session id, and /T sets the title of the command window\r\n strCmd = strSDRoot\r\n + '\\\\Tools\\\\'\r\n + strMach\r\n + '\\\\remote.exe /s \"'\r\n + MakeRazzleCmd(strSDRoot, RAZOPT_PERSIST)\r\n + ' && set __MTSCRIPT_ENV_ID=\" BldCon /T \"BldCon Remote Razzle\"';\r\n\r\n LogMsg('Spawning remote razzle: ' + strCmd);\r\n\r\n g_pidRemoteRazzle = RunLocalCommand(strCmd,\r\n strSDRoot,\r\n 'Remote',\r\n true,\r\n false,\r\n false);\r\n\r\n if (g_pidRemoteRazzle == 0)\r\n {\r\n vRet = 'Error spawning remote.exe server: ' + GetLastRunLocalError();\r\n }\r\n\r\n // Give remote.exe a chance to set up it's winsock connection\r\n Sleep(500);\r\n }\r\n\r\n return vRet;\r\n}", "function selectSlot() {\n\t// find its absolute slot position\n\t//var boxNum = document.getElementById();\n\t//var slotNum = document.getElementById();\n\tvar absSlot = (boxNum*30) + slotNum;\n\n\t// create json string\n\tvar str = \"{ absSlot:\" + absSlot + \" }\";\n\tvar jsonObj = JSON.stringify(str);\n\n\t// POST request\n\tvar request = $.ajax({url: '/getpokemonatslot', type: 'POST'});\n\trequest.done(function(msg) {\n\t\tconsole.log(msg);\n\t\t// load the pokemon into current pokemon\n\t});\n}", "function bankSlots(amount) {\r\n chrome.tabs.getSelected(null, function(tab){\r\n var c = \"var s = document.createElement('script');\\\r\n s.textContent = \\\"bankMax+=0+\"+amount+\"; updateBank();\\\";\\\r\n document.head.appendChild(s);\"\r\n chrome.tabs.executeScript(tab.id, {code: c});\r\n });\r\n}", "execute_uuid(uuid, app_name, app_arg, loops, event_uuid) {\n var options;\n options = {\n 'execute-app-name': app_name,\n 'execute-app-arg': app_arg\n };\n if (loops != null) {\n options.loops = loops;\n }\n if (event_uuid != null) {\n options['Event-UUID'] = event_uuid;\n }\n return this.sendmsg_uuid(uuid, 'execute', options);\n }", "function showSlotPage(column, slots, title, back, callback) {\n\t\tvar backButton, li, slotPage;\n\t\tfunction updateLi() {\n\t\t\tvar label;\n\t\t\tlabel = '';\n\t\t\tslotPage.find('.jmuiSlot div:nth-child(2)').each(function () {\n\t\t\t\tlabel += $(this).text() + ' ';\n\t\t\t});\n\t\t\tli.text(label);\n\t\t}\n\t\tfunction addSlot(slotMachine, slot) {\n\t\t\tvar decDiv, incDiv, index, interval, isStatic, slotDiv, timeout, valDiv;\n\t\t\tfunction calcWidth() {\n\t\t\t\tvar i, width;\n\t\t\t\twidth = 0;\n\t\t\t\tif (isStatic) {\n\t\t\t\t\twidth = slot.staticSlot.length;\n\t\t\t\t} else {\n\t\t\t\t\tfor (i = 0; i < slot.choices.length; i += 1) {\n\t\t\t\t\t\tif (slot.choices[i].label.length > width) {\n\t\t\t\t\t\t\twidth = slot.choices[i].label.length;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twidth = (width * 0.75).toString() + 'em';\n\t\t\t\treturn width;\n\t\t\t}\n\t\t\tfunction increment(inc) {\n\t\t\t\tindex += inc;\n\t\t\t\tif (index >= slot.choices.length) {\n\t\t\t\t\tindex = 0;\n\t\t\t\t} else if (index < 0) {\n\t\t\t\t\tindex = slot.choices.length - 1;\n\t\t\t\t}\n\t\t\t\tvalDiv.val(slot.choices[index].value);\n\t\t\t\tvalDiv.text(slot.choices[index].label);\n\t\t\t\tupdateLi();\n\t\t\t}\n\t\t\tfunction stopTimers() {\n\t\t\t\tif (timeout) {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\ttimeout = undefined;\n\t\t\t\t}\n\t\t\t\tif (interval) {\n\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\tinterval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction touchStart(e) {\n\t\t\t\tvar inc;\n\t\t\t\tif (!$.ui.defaultPrevented(e)) {\n\t\t\t\t\tstopTimers();\n\t\t\t\t\tcancelEvent(e); // Needs cancelEvent to prevent bogus select/copy UI\n\t\t\t\t\tinc = this === incDiv[0] ? 1 : -1;\n\t\t\t\t\t$(this).addClass('jmuiPressed');\n\t\t\t\t\ttimeout = setTimeout(function () { // Needs to be in a timer otherwise 1st inc is not displayed properly ???\n\t\t\t\t\t\tincrement(inc);\n\t\t\t\t\t\ttimeout = setTimeout(function () {\n\t\t\t\t\t\t\ttimeout = undefined;\n\t\t\t\t\t\t\tinterval = setInterval(function () {\n\t\t\t\t\t\t\t\tincrement(inc);\n\t\t\t\t\t\t\t}, 100);\n\t\t\t\t\t\t}, 400);\n\t\t\t\t\t}, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction touchEnd(e) {\n\t\t\t\tcancelEvent(e);\n\t\t\t\tstopTimers();\n\t\t\t\t$(this).removeClass('jmuiPressed');\n\t\t\t}\n\t\t\tisStatic = !!slot.staticSlot;\n\t\t\tindex = slot.index || 0;\n\t\t\tslotDiv = $(window.document.createElement('div'));\n\t\t\tslotDiv.addClass('jmuiSlot');\n\t\t\tif (isStatic) {\n\t\t\t\tslotDiv.addClass('jmuiStatic');\n\t\t\t}\n\t\t\tslotDiv.style('width', calcWidth());\n\t\t\tincDiv = $(window.document.createElement('div'));\n\t\t\tincDiv.html(isStatic ? '&nbsp;' : '+');\n\t\t\tslotDiv[0].appendChild(incDiv[0]);\n\t\t\tvalDiv = $(window.document.createElement('div'));\n\t\t\tif (isStatic) {\n\t\t\t\tvalDiv.text(slot.staticSlot);\n\t\t\t} else if (slot.choices.length > 0) {\n\t\t\t\tvalDiv.val(slot.choices[index].value);\n\t\t\t\tvalDiv.text(slot.choices[index].label);\n\t\t\t}\n\t\t\tslotDiv[0].appendChild(valDiv[0]);\n\t\t\tdecDiv = $(window.document.createElement('div'));\n\t\t\tdecDiv.html(isStatic ? '&nbsp;' : '-');\n\t\t\tslotDiv[0].appendChild(decDiv[0]);\n\t\t\tslotMachine[0].appendChild(slotDiv[0]);\n\t\t\tif (isStatic || slot.choices.length > 0) {\n\t\t\t\tif ($.isTouch) {\n\t\t\t\t\tincDiv.bind('touchstart', isStatic ? cancelEvent : touchStart);\n\t\t\t\t\tincDiv.bind('touchend', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t\tdecDiv.bind('touchstart', isStatic ? cancelEvent : touchStart);\n\t\t\t\t\tdecDiv.bind('touchend', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t} else {\n\t\t\t\t\tincDiv.bind('mousedown', isStatic ? cancelEvent : touchStart);\n\t\t\t\t\tincDiv.bind('mouseup', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t\tincDiv.bind('mouseout', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t\tdecDiv.bind('mousedown', isStatic ? cancelEvent : touchStart);\n\t\t\t\t\tdecDiv.bind('mouseup', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t\tdecDiv.bind('mouseout', isStatic ? cancelEvent : touchEnd);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($.isTouch) {\n\t\t\t\tvalDiv.bind('touchstart', cancelEvent);\n\t\t\t\tvalDiv.bind('touchend', cancelEvent);\n\t\t\t} else {\n\t\t\t\tvalDiv.bind('mousedown', cancelEvent);\n\t\t\t\tvalDiv.bind('mouseup', cancelEvent);\n\t\t\t}\n\t\t}\n\t\tfunction addSlots() {\n\t\t\tvar i, slotMachine;\n\t\t\tslotMachine = slotPage.find('.jmuiSlotMachine');\n\t\t\tslotMachine.empty();\n\t\t\tfor (i = 0; i < slots.length; i += 1) {\n\t\t\t\taddSlot(slotMachine, slots[i]);\n\t\t\t}\n\t\t}\n\t\tfunction backButtonTap() {\n\t\t\tvar values;\n\t\t\tvalues = [];\n\t\t\tslotPage.find('.jmuiSlot div:nth-child(2)').each(function () {\n\t\t\t\tvalues.push($(this).val());\n\t\t\t});\n\t\t\tif(parseInt(values[0]) > Date.getDaysInMonth(values[2],values[1])) {\n\t\t\t\twindow.mCapture.msgBox(function(){},\"Invalid Date\",\"Please enter a valid day for the selected month\",\"OK\");\n\t\t\t\treturn;\n\t\t\t}else{\n\t\t\t\tbackButton.unbind($.ui.tapEvent, backButtonTap);\n\t\t\t\tcallback(values);\n\t\t\t}\n\t\t}\n\t\tif (!title || title.constructor !== String) {\n\t\t\ttitle = '';\n\t\t}\n\t\tif (!back || back.constructor !== String) {\n\t\t\tback = 'Back';\n\t\t}\n\t\tslotPage = column.find('.jmuiSlotPage');\n\t\tif (!slotPage || slotPage.length <= 0) {\n\t\t\tslotPage = $(window.document.createElement('div'));\n\t\t\tslotPage.addClass('jmuiPage', 'jmuiSlotPage');\n\t\t\tslotPage.html('<div class=\"jmuiHeader\"><div class=\"jmuiToolbar\"><h1>List</h1><div class=\"jmuiGoBack jmuiBackButton\">Back</div></div></div><div class=\"jmuiNativeScroller\"><div><div class=\"md_slotContainer\"><h2></h2><ul><li class=\"jmuiColorPress\"></li></ul></div><div class=\"jmuiSlotMachine\"></div></div></div>');\n\t\t\tbindScroller(slotPage);\n\t\t\tcolumn[0].appendChild(slotPage[0]);\n\t\t}\n\t\tli = slotPage.find('li');\n\t\tslotPage.find('h2').text(title);\n\t\tbackButton = slotPage.find('.jmuiBackButton');\n\t\tbackButton.text(back);\n\t\tgenerateTaps(backButton);\n\t\tbackButton.bind($.ui.tapEvent, backButtonTap);\n\t\tslotPage.find('.jmuiToolbar > h1').text(title);\n\t\taddSlots();\n\t\tupdateLi();\n\t\tgotoPage(slotPage, 'jmuiSlide', false, true);\n\t}", "function deployApplication(uri, script, reqs, name)\n{\n var url = uri + '/deploy';\n var data;\n if (reqs) {\n var requirements = JSON.parse(reqs);\n data = JSON.stringify({'script': script, 'deploy_info': requirements, 'name': name});\n } else {\n data = JSON.stringify({'script': script, 'name': name});\n }\n console.log(\"deployApplication url: \" + url + \" data: \" + data);\n $.ajax({\n timeout: 20000,\n beforeSend: function() {\n startSpin();\n },\n complete: function() {\n stopSpin();\n },\n url: url,\n type: 'POST',\n data: data,\n success: function(data) {\n console.log(\"deployApplication - Success\");\n },\n error: function() {\n alert(\"Failed to deploy application, url: \" + url + \" data: \" + data);\n }\n });\n}", "function runSynchronizeSharedRoomsForButton3(){\n\t try { \t \n\t\t var result = Workflow.callMethod('AbCommonResources-SpaceService-synchronizeSharedRooms');\n } \n catch (e) {\n Workflow.handleError(e);\n }\n View.alert(getMessage('synchronizeSharedRooms'));\n}", "function executeScript() {\n var args = [];\n\n if (argv[\"debug-brk\"]) {\n args.push(\"--debug-brk=\" + argv[\"debug-port\"]);\n } else {\n args.push(\"--debug=\" + argv[\"debug-port\"]);\n }\n\n args = args.concat(argv[\"_\"]);\n\n return child_process.spawn(process.execPath, args, { stdio: \"inherit\" }).on(\"exit\", process.exit);\n}", "function StartServer (){\n\t\t\n Network.InitializeServer(maxPlayers, 25001, !Network.HavePublicAddress);\n MasterServer.RegisterHost(\"Star_Arena\", serverNameField); \n}", "function dimSlots(theMarble : GameObject) {\n\tselectedMarble = null;\n\tgameObject.BroadcastMessage(\"dimslot\");\n}", "function OnEventSourceEventSlave(RemoteObj, cmd, params)\r\n{\r\n var aDepotIdx;\r\n var i;\r\n switch(cmd)\r\n {\r\n case 'ScriptError':\r\n NotifyScriptError(RemoteObj, params);\r\n break;\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the twitch API to see if a given twitch streamer is online. Modifies the "Online" database. INPUT: A document containing information from the "Players" database. OUTPUT: Maintains the "Online" database with twitch streamers that are online playing League.
function processTwitchRequest(data) { var twitchRequest = https.get(twitchAPI + data.twitchUsername, function(res) { var twitchData = ''; /* Append the twitch stream data */ res.on('error', function(err) { handleResponseError(err); }); res.on('data', function(twitchInfo) { twitchData += twitchInfo; }); /* Handle if a streamer is on or offline */ res.on('end', function() { var parsedTwitchData = JSON.parse(twitchData); mongoClient.connect(database, function(err, db) { if(err) { /* Handle the error */ handleDbError(err); } var collection = db.collection(dbOnline); /* Make a function to close the database. This way the db can be closed from the parent scope when we KNOW the children are done. */ function closeDb() { db.close(); } /* User is online and playing League. See if they need to be added to the "Online" database */ if(parsedTwitchData._total > 0 && parsedTwitchData.streams[0].game == lolGame) { /* use the data from twitch to see if this user is already in the "Online" database */ var onlineCursor = collection.find({twitchUsername: parsedTwitchData.streams[0].channel.display_name}); onlineCursor.nextObject(function(err, item) { if(err) { /* Handle the error */ handleCursorError(err); } /* They are already in the "Online" database. Do nothing */ if(item != null) { /* TODO: make a priority queue and give this twitch streamer the lowest priority */ } /* item is null. The user just came online, add them to the "Online" database */ else { collection.insert(data); } closeDb(); }); } /* The user is not online or not playing League. Remove them from the "Online" database */ else { collection.remove(data); closeDb(); } }); }); }); }
[ "function checkIfOnline(callback) {\n var interval = setInterval(function() {\n client.api({\n url: 'https://api.twitch.tv/kraken/streams/' + auth.username.toLowerCase(),\n method: 'GET',\n headers: {\n 'Accept': 'application/vnd.twitchtv.v3+json',\n 'Client-ID': auth.clientID\n }\n }, function(err, res, body) {\n // check if stream value is null (meaning they are offline)\n if(body.stream == null) {\n console.log('Stream is offline, checking in 5 seconds...')\n } else {\n console.log('Stream is online.')\n clearInterval(interval) // stop interval\n startTimer(body.stream.created_at) // call ze callback\n\n // get other stream details\n game = body.stream.game\n }\n })\n }, 5000)\n }", "function _isStreamerOnline(callback) {\n let url = 'https://api.twitch.tv/kraken/streams/' + callback.name;\n $.ajax({\n type: 'GET',\n url: url,\n headers: {\n 'Client-ID': CLIENT_ID\n },\n success: function(data) {\n if (data.stream === null) {\n _getOfflineStreamerInformation(callback);\n } else {\n _renderOnlineStreamer(callback);\n }\n },\n error: function (failure) {\n console.log(\"SOMETHING WENT WRONG\", failure);\n }\n });\n }", "function updateOnline(username, online) {\n return User.update({ username: username }, { online: online });\n}", "function updateUsersOnlineStatus(name){\n var findUser = allChatUsers.filter(e => e.name == name);\n \n //Look if name is found in socketIDAndUserName list, if found\n if(Object.values(socketIDAndUserName).includes(name)){\n //then user is online\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = true;\n findUser[0].isOnline = true;\n }\n else{//offline\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = false;\n findUser[0].isOnline = false;\n }\n\n //DONE Broadcast users online status and broadcast global changed\n broadcastUserStatusChanged(name);\n\n updateGlobalUsers();//UNFIN?\n }", "function fnIsStreamOnline(twitch_id,cb){\n var stream_id=twitch_id;\n var sUrl=\"https://api.twitch.tv/kraken/streams?channel=\"+stream_id;\n\n var options = {\n method: 'GET', \n headers: { \n 'Client-ID': sClientId,\n 'Accept': 'application/vnd.twitchtv.v5+json'\n },\n rejectUnauthorized: true\n };\n request(sUrl,options\n , function (err, data) {\n if (err){\n\n }\n data=JSON.parse(data);\n cb(data);\n })\n}", "isOnline() {\n if (this.id != null && this.manager != null) {\n return this.app.players.isPlayerOnline(this);\n }\n\n return false;\n }", "function checkOnline(data) {\n if (data.stream) {\n var tempName = data.stream.channel.name;\n $(\"#\" + tempName).removeClass(\"offline\");\n $(\"#\" + tempName).addClass(\"online\");\n }\n console.log(data);\n }", "function isOnline() {\n for (var k in networks) {\n if (networks.hasOwnProperty(k) && networks[k].status && networks[k].status == social.STATUS_NETWORK['ONLINE']) {\n return true;\n }\n }\n return false;\n}", "function isOnline(row) {\n var section = generateCourseInfoArray(row)[2];\n return section.charAt(0) === 'W';\n}", "function isOnline(user) {\n$.getJSON(streamAPI + user, function(data){\n\t\n var available = data.stream; \n /*redundancy?*/\n if (available) {\n\treturn true;\n } else {\n return false;\n };\n \n });\n}", "function isStreaming() {\n $.each(users, function(index, value) {\n $.getJSON(urlQuery(\"streams\", value), function(data) {\n if (data.stream)\n addStreamingUsers(data);\n else\n addOfflineUsers(value);\n });\n })\n}", "userIsOnline(){\n this.server.get('/api/user-is-online', (req, res) => {\n try {\n const bind = {\n username: req.query.username\n };\n\n var isOnline = false;\n\n this.App.onlineUsers.forEach(user => {\n if (user.username == bind.username) {\n isOnline = true;\n return\n }\n });\n\n res.send(isOnline ? \"online\" : \"offline\")\n }\n catch (err){\n this.App.throwErr(err, this.prefix, res)\n }\n })\n }", "function updateUsersOnline () {\n io.emit('usersOnline', clients)\n }", "_online() {\n // if we've requested to be offline by disconnecting, don't reconnect.\n if (this.currentStatus.status != 'offline') this.reconnect();\n }", "function online (){\n return rooms[roomId].indexOf(user) !== -1;\n }", "_online() {\n // if we've requested to be offline by disconnecting, don't reconnect.\n if (this.currentStatus.status != \"offline\") this.reconnect();\n }", "async checkStreamStatus() {\n\n let newOnlineStreamers = await twitch.updateOnlineStreams();\n\n for (let streamerData of newOnlineStreamers) {\n await this.announceStream(streamerData);\n }\n }", "function online() {\n\tconnectionManager.start(receptionist);\n\tdiscoveryManager.goOnline();\n}", "_online() {\n // if we've requested to be offline by disconnecting, don't reconnect.\n if (this.currentStatus.status != 'offline') this.reconnect();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the shelfinfo inside a book. If the shelf value is none, then the book is removed from the app component's state
updateShelf(book, shelf) { if(shelf.value === 'none') { const bookIndex = this.state.books.findIndex(bk => bk.id === book.id); this.state.books.splice(bookIndex, 1); } else { book.shelf = shelf; } this.setState(this.state); }
[ "updateShelf(e, book) {\n if (e === 'currentlyReading') {\n book.shelf = \"currentlyReading\";\n this.currentListAddItem(book.id, book);\n } else if (e === 'wantToRead') {\n book.shelf = 'wantToRead';\n this.wantToListAddItem(book.id, book);\n } else if (e === 'read') {\n book.shelf = 'read';\n this.readListAddItem(book.id, book);\n } else if (e === 'none'){\n this.booksOnShelvesRemoveItem(book.id);\n this.currentListRemoveItem(book.id);\n this.readListRemoveItem(book.id);\n this.wantToListRemoveItem(book.id);\n }\n }", "updateShelf(currentShelf) {\n if (this.props.bookShelf === 'none') {\n this.props.books.push(this.props.book);\n this.props.book.shelf = currentShelf;\n }\n else {\n this.props.books.forEach((book, index) => {\n if (book.id === this.props.bookId) {\n this.props.books.splice(index, 1);\n this.props.books.push(this.props.book);\n }\n }\n );\n this.props.book.shelf = currentShelf;\n }\n }", "onChangeShelf(book, shelf) {\n if (!shelf)\n return;\n BooksAPI.update(book, shelf).then(() => {\n this.setState(currentState => ({\n books: [\n ...currentState.books.filter(sb => sb.id !== book.id), {\n ...book,\n shelf\n }\n ]\n }));\n });\n }", "onChangeShelf(book, newShelf){\n book.shelf = newShelf;\n\n BooksAPI.update(book, newShelf).then(() => {\n this.setState((state) => ({\n books: state.books.filter((b) => b.id !== book.id).concat([book])\n }))\n });\n }", "function updateShelf() {\n $(\"#bookShelf\").empty();\n $(\"#bookShelf\").append(\"<p>Favorite: <strong>\" + favorite + \"</strong></p>\");\n $(\"#bookShelf\").append(\"<p>Last Read: <strong>\" + read + \"</strong></p>\");\n $(\"#bookShelf\").append(\"<p>Next to Read: <strong>\" + toRead + \"</strong></p>\");\n }", "updateBook(key, shelf) {\n const z = this.state\n z.results[key].shelf=shelf\n bapi.update(z.results[key], shelf).then(()=> {\n this.setState(z)\n this.props.parent.updateState()\n })\n }", "function handleShelfChange(book, eve) {\n update(book, eve.target.value);\n }", "changeShelf(book, newShelf){\r\n BooksAPI.update(book, newShelf)\r\n}", "updateShelfValue(book, shelfValue) {\n BooksAPI.update(book, shelfValue).then((updated) => {\n //After the update, GET all the books.\n this.getAllBooks();\n\n //After the update, change the `queriedBooks` variable if we are on search page\n if (this.state.queriedBooks.length > 0) {\n const queriedBooks = this.state.queriedBooks.map(queriedBook => {\n if (queriedBook.id === book.id) {\n queriedBook.shelf = shelfValue;\n }\n return queriedBook;\n })\n this.setState({queriedBooks});\n }\n })\n }", "onBookMove(alteredBook, shelf) {\n\n if (alteredBook.shelf !== shelf) {\n BooksAPI.update(alteredBook, shelf).then(response => {\n\n // update the shelf\n alteredBook.shelf = shelf;\n\n var latestBooks = this.state.books.filter(book => book.id !== alteredBook.id)\n latestBooks.push(alteredBook);\n this.setState({books : latestBooks})\n })\n }\n }", "handleShelfMove(newShelf, book) {\n // first we copy the books array\n const books = this.state.books.slice();\n // then we find our book and update its shelf.\n books.forEach(stateBook => {\n if (stateBook.id === book.id) {\n stateBook.shelf = newShelf;\n }\n });\n // then we update the state.\n this.setState({\n books: books\n });\n // finally we tell our parent component that a book moved shelf\n // and let it update its collection of books.\n this.props.handleShelfMove(newShelf, book)\n }", "mergeShelfInfo(books) {\r\n const mergedBooks = books.map(book => {\r\n book.shelf = \"none\";\r\n this.props.bookInventory.forEach(bookInventory => {\r\n if (book.id === bookInventory.id) {\r\n book.shelf = bookInventory.shelf;\r\n }\r\n });\r\n return book;\r\n });\r\n this.setState({\r\n books: mergedBooks\r\n });\r\n }", "moveTo(shelf, book) {\n // we update the status of the books\n BooksAPI.update(book, shelf).then(() => {\n this.fetchBooks();\n });\n }", "removeBook(currentShelf) {\n if (currentShelf === 'none') {\n this.props.books.forEach((book, index) => {\n if (book.id === this.props.bookId) {\n this.props.books.splice(index, 1);\n }\n }\n );\n }\n }", "switchShelf(){\n\t\tlet select = document.getElementById(this.props.book.id);\n\t\tlet val = select.options[select.selectedIndex].value;\n\t\tnotify.show(\"making changes...please wait.\", \"info\", 1000, \"#FFFFFF\");\n\t\tBooksAPI.update(this.props.book, val).then((data)=>{\n\t\t\tthis.props.updateBooks(this.props.book, val);\n\t\t});\n\t}", "moveBook(book, shelf) {\n if (shelf !== 'none') {\n BooksAPI.update(book, shelf).then(\n ()=>{\n // update the BooksApp library\n this.props.reloadFunc();\n // update the selector for the book shown on the search page\n this.setState(\n prevState=>{\n let tempLib = prevState.library;\n tempLib.forEach(\n (item, idx)=>{\n if (item.id === book.id) {\n tempLib[idx].shelf = shelf;\n }\n }\n );\n return ({library: tempLib});\n }\n )},\n e=>console.log(e)\n );\n }\n }", "updateBook(bookToUpdate) {\n BooksAPI.update(bookToUpdate.book, bookToUpdate.shelf).then((shelfBooks) => {\n this.fetchMyReads().then(() => {\n NotificationManager.success('Book added to \"' + bookToUpdate.shelf + '\"', '');\n })\n })\n }", "updateBookAndSearch(book, shelf, books) {\n BooksAPI.update(book, shelf)\n .then(() => {\n this.props.getBooks();\n book.shelf = shelf;\n let updatedSearchResults = books;\n updatedSearchResults.forEach((b) => {\n (b.id === book.id) && (b.shelf = book.shelf);\n })\n this.setState({\n books: updatedSearchResults\n });\n this.myBooksOnShelf[book.id] = book.shelf; \n });\n }", "insertInLibrary(shelf, queryBook) {\n // Store the current shelf the given book is on.\n let oldShelf = queryBook.shelf;\n // Check if the current book shelf is different from the one passed\n // by the user selection.\n if (oldShelf !== shelf) {\n // Update the API and insert `queryBook` in the library at the given shelf.\n BooksAPI.update(queryBook, shelf).then(\n // Pass the Promise a request to the API to get the updated books collection.\n BooksAPI.getAll().then((books) => {\n // As the API returns the JSON object containing the collection of books\n // stored in our library, pass it to the state books array.\n this.setState({ books });\n })\n )\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toggle delete button from 'delete' to 'revert' for content marked as to be deleted and remove/show other buttons in item
function toggleDeleteRevertButton($container) { $container.find('.btn-browse-delete-revert, .js-browse__buttons--primary, .js-browse__buttons--secondary').toggle(); }
[ "function toggleDeleteRevertChildren($item) {\n var $childContainer = $item.find('.js-browse__item .page__container'),\n isDeleting = $item.children('.page__container').hasClass('deleted');\n\n if (isDeleting) {\n $childContainer.addClass('deleted');\n } else {\n $childContainer.removeClass('deleted');\n\n // If a child item has previously been deleted but is being shown by a parent then undo the toggle buttons\n if ($childContainer.find('.btn-browse-delete-revert').length) {\n // toggleDeleteRevertButton($childContainer.find('.btn-browse-delete-revert'));\n toggleDeleteRevertButton($childContainer);\n }\n }\n\n $childContainer.find('.page__buttons').toggleClass('deleted');\n}", "function showDeleteButtons () {\n $element.parent().find('.delete-button').css('visibility', 'visible');\n }", "function hideDeleteButtons () {\n $element.parent().find('.delete-button').css('visibility', 'hidden');\n }", "function hideDeleteButtons(){\n $('li').find('.delmark').hide();\n }", "resetDeleteButtons() {\n const buttonsDelete = this.elements.content.getElementsByClassName('button-delete');\n\n buttonsDelete.forEach((e) => {\n e.style.display = 'block';\n });\n\n const buttonsReallyDelete = this.elements.content.getElementsByClassName('button-really-delete');\n\n buttonsReallyDelete.forEach((e) => {\n e.style.display = 'none';\n });\n }", "clickOnDeleteButton() {\n commonActions.click(this.deleteButton);\n }", "function toggleDeleteButton() {\n if ($('.person-container.active').length) {\n $deleteBtn.show();\n } else {\n $deleteBtn.hide();\n }\n }", "unhideDeleteButton() {\n this.menu.querySelector(`.${CSS.toolboxDeleteColumn}`).classList.remove(CSS.displayNone);\n }", "function handleDeleteButton() {\n var $toolbar = $('.toolbar');\n if($('td input[type=\"checkbox\"]:checked').length > 0) {\n $toolbar.find('.delete').removeClass('hide');\n } else {\n $toolbar.find('.delete').addClass('hide');\n }\n}", "hideDeleteButton() {\n this.menu.querySelector(`.${CSS.toolboxDeleteColumn}`).classList.add(CSS.displayNone);\n }", "setDeleteConfirmation() {\n this.showDeleteConfirmation = true;\n this.menu.querySelector(`.${CSS.toolboxDelete}`).classList.add(CSS.deleteConfirm);\n }", "function _btnDeleteReset() {\n\t\t\tedit.btnDelete = false;\n\t\t\tedit.btnDeleteText = 'Delete Event';\n\t\t}", "function setDeletable( li )\n{\n let button = li.querySelector(\"span.for-delete-button\");\n if (button)\n {\n button.className = \"delete-button\";\n button.title = i18nGet(\"digglerDeleteTool.label\");\n button.addEventListener( \"click\", event => {\n event.preventDefault();\n deleteEntry( li );\n } );\n }\n}", "function addDeleteButton(deleteButton){\n console.log(deleteButton);\n $(deleteButton).on('click',function(){\n let id= deleteButton.getAttribute('id');\n $(`#post-container-${id}`).remove();\n new Noty({\n theme : 'sunset',\n text : 'Post Deleted',\n timeout:1000,\n progressBar:true,\n layout : 'topRight'\n }).show();\n });\n }", "_onShowDeletedClicked(e) {\n e.preventDefault();\n e.stopPropagation();\n\n /*\n * Replace the current contents (\"This file was deleted ... \") with a\n * spinner. This will be automatically replaced with the file contents\n * once loaded from the server.\n */\n $(e.target).parent()\n .html('<span class=\"djblets-o-spinner\"></span>');\n\n this.trigger('showDeletedClicked');\n }", "function addMenuDeleteButton() {\r\n\tjQuery('#menu-to-edit li.menu-item').each(function(){\r\n\t\t\r\n\t\tvar delete_el \t= jQuery('.menu-item-actions a.item-delete', this);\r\n\t\tvar anchor \t\t= '<a class=\"top-item-delete\" id=\"' + delete_el.attr('id') + '\" href=\"' + delete_el.attr('href') + '\">' + delete_el.text() + '</a>';\r\n\t\tvar controls\t= jQuery('.item-controls', this);\r\n\t\tvar count\t\t= jQuery('a.top-item-delete', controls).size();\r\n\t\t\r\n\t\t// delete button already present?\r\n\t\tif ( count == 0 ) {\r\n\t\t\tcontrols.prepend( anchor + ' | ');\r\n\t\t}\r\n\t});\r\n}", "function showDelete() {\n if (status.tagVisibility !== 'hidden') {\n var boundingBox = path.getBoundingBox(),\n x = boundingBox.x + boundingBox.width - 20,\n y = boundingBox.y;\n\n // Show a delete button\n $(\"#delete-icon-holder\").css({\n visibility: 'visible',\n left : x + 25, // + width - 5,\n top : y - 20\n });\n }\n }", "function delete_formset_item(prefix,element){\n\t\tparentForm = element.parents('.formsetfieldwrap');\n\t\t//Set the \"id_...-DELETE\" <input> tag to true. This input replaces Django's delete checkbox.\n\t\tparentForm.find('input:hidden[id $= \"-DELETE\"]').val('on');\n\t\t//Make the deletion visible\n\t\tparentForm.fadeTo(300,0.3);\n\t\telement.fadeOut(300,0);\n\t}", "function clickDelete() {\n\tviewAddToDo.style.display = \"none\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds internal labels on the nodes, after an update.
function updateInternalLabels(active) { graph.element.selectAll('.internal-label').remove() if (active) { graph.element .selectAll('.node--internal') .append('text') .attr('class', ' internal-label') .attr('dy', 20) .attr('x', -13) .style('text-anchor', 'end') .style('font', `${graph.style.labels_size}px sans-serif`) .text(d => d.data.id) } }
[ "function updateLabels() {\n\tlabels = []\n\tfor (var i in nodes) {\n\t\tif ('label' in nodes[i]) {\n\t\t\tlabels.push({'id':nodes[i]['id'], 'label':nodes[i]['label']})\n\t\t}\n\t}\n}", "function addInternalLabels() {\n graph.style.parentLabels = !graph.style.parentLabels\n updateInternalLabels(graph.style.parentLabels)\n }", "function updateLabels() {\n forEachLinode(working, hosts_to_build, (host, hostob) => {\n return {\n call: {\n action: 'linode.update',\n params: {\n LinodeID: hostob.LinodeID,\n Label: host,\n lpm_displayGroup: 'Docker Cluster'\n }\n },\n result: (data) => {\n }\n };\n }, addPrivateIP );\n }", "function addLabels() {\n var numArticles = articlesChangeLOC.length;\n for (var i = 0; i < numArticles; i++) {\n (function(index) {\n if (undefined === articlesChangeLOC[index].labels) {\n $.get('/api/v2/help_center/articles/' + articlesChangeLOC[index].id + '/labels.json').done(function(data) {\n articlesChangeLOC[index].labels = data.labels;\n })\n }\n })(i)\n }\n }", "function ToggleNodeLabels() {\n var updateJson = [];\n for (k in GraphObj.Nodes) {\n var n = GraphObj.Nodes[k];\n var lab = n.Id;\n if (PageStateObj.StandardsLabel == GraphLabels.NGSS) {\n lab = n.NGSSCode;\n if (lab == 'NULL') {\n lab = BLANK_STD_LABLE\n }\n \n }\n var nodeUpdate = { id: n.Id, label: lab };\n updateJson[updateJson.length] = nodeUpdate;\n }\n VISJS_NODES.update(updateJson)\n}", "addLabels(labels) {\n for (const [address, label] of labels) {\n this.knownLabels.set(address, label);\n }\n }", "addLabel(newLabelOrLabels) {\n this.labels = this.labels.concat(newLabelOrLabels);\n }", "function updateLeafLabels(active) {\n graph.element.selectAll('.node--leaf text').remove()\n if (active) {\n graph.element.selectAll('.node--leaf')\n .append('text')\n .attr('class', 'leafLabel')\n .attr('dy', 5)\n .attr('x', 13)\n .style('text-anchor', 'start')\n .style('font', `${graph.style.labels_size}px sans-serif`)\n .text(d => d.data.id)\n .on('mouseover', mouseOveredDendrogram(true))\n .on('mouseout', mouseOveredDendrogram(false))\n }\n }", "setLabels () {\n for (const labelID of this.data.labelIDs) {\n this.createLabel(labelID);\n }\n }", "function updateLabels() {\n label = label.data(data.topics, function(d) { return d.name; });\n\n label.exit().remove();\n\n var labelEnter = label.enter().append(\"a\")\n .attr(\"class\", \"g-label\")\n .attr(\"href\", function(d) { return \"#\" + encodeURIComponent(d.name); })\n .call(force.drag)\n .call(linkTopic);\n\n labelEnter.append(\"div\")\n .attr(\"class\", \"g-name\")\n .text(function(d) { return d.name; });\n\n labelEnter.append(\"div\")\n .attr(\"class\", \"g-value\");\n\n label\n .style(\"font-size\", function(d) { return Math.max(8, d.r / 2) + \"px\"; })\n .style(\"width\", function(d) { return d.r * 2.5 + \"px\"; });\n\n // Create a temporary span to compute the true text width.\n label.append(\"span\")\n .text(function(d) { return d.name; })\n .each(function(d) { d.dx = Math.max(d.r * 2.5, this.getBoundingClientRect().width); })\n .remove();\n\n label\n .style(\"width\", function(d) { return d.dx + \"px\"; })\n .select(\".g-value\")\n .text(function(d) { return formatShortCount(d.parties[0].count) + \" - \" + formatShortCount(d.parties[1].count); });\n\n // Compute the height of labels when wrapped.\n label.each(function(d) { d.dy = this.getBoundingClientRect().height; });\n}", "update_lbl() {\n if (this.m2m_attrs.lbl == undefined) this.m2m_attrs.lbl = [];\n this.m2m_attrs.lbl[0] = 'esi';\n this.m2m_attrs.lbl[1] = JSON.stringify(['esi:ee', this.subs(), this.esi_attrs.control]);\n }", "function updateLabels() {\n label = label.data(data.topics, function(d) {\n return d.name;\n });\n\n label.exit().remove();\n\n var labelEnter = label.enter().append(\"a\")\n .attr(\"class\", \"g-label\")\n .attr(\"id\", function(d) {\n return encodeURIComponent(d.name);\n })\n .call(force.drag)\n .call(linkTopic);\n\n labelEnter.append(\"div\")\n .attr(\"class\", \"g-name\")\n .text(function(d) {\n return d.name;\n });\n\n labelEnter.append(\"div\")\n .attr(\"class\", \"g-value\");\n\n label\n .style(\"font-size\", function(d) {\n return Math.max(8, r(d.count) / 2.2) + \"px\";\n })\n .style(\"width\", function(d) {\n return r(d.count) * 2.5 + \"px\";\n });\n\n // Create a temporary span to compute the true text width.\n label.append(\"span\")\n .text(function(d) {\n return d.name;\n })\n .each(function(d) { d.dx = Math.max(2.5 * r(d.count), this.getBoundingClientRect().width); })\n .remove();\n\n label\n .style(\"width\", function(d) {\n return d.dx + \"px\";\n })\n .select(\".g-value\")\n .text(function(d) {\n return d.count + (d.r > 60 ? \" mentions\" : \"\");\n });\n\n // Compute the height of labels when wrapped.\n label.each(function(d) { d.dy = this.getBoundingClientRect().height; });\n }", "function setPositionOfOldLabelsOnNewLabels( oldLabelNodes, labelNodes ){\n\t labelNodes.forEach(function ( labelNode ){\n\t for ( var i = 0; i < oldLabelNodes.length; i++ ) {\n\t var oldNode = oldLabelNodes[i];\n\t if ( oldNode.equals(labelNode) ) {\n\t labelNode.x = oldNode.x;\n\t labelNode.y = oldNode.y;\n\t labelNode.px = oldNode.px;\n\t labelNode.py = oldNode.py;\n\t break;\n\t }\n\t }\n\t });\n\t }", "function _toggleNodeLabels()\r\n{\r\n\t// update visibility of labels \r\n\t\r\n\t_nodeLabelsVisible = !_nodeLabelsVisible;\r\n\t_vis.nodeLabelsVisible(_nodeLabelsVisible);\r\n\t\r\n\t// update check icon of the corresponding menu item\r\n\t\r\n\tvar item = $(\"#show_node_labels\");\r\n\t\r\n\tif (_nodeLabelsVisible)\r\n\t{\r\n\t\titem.addClass(CHECKED_CLASS);\r\n\t}\r\n\telse\r\n\t{\r\n\t\titem.removeClass(CHECKED_CLASS);\r\n\t}\r\n}", "function update_labels(totalETX = etxPathVals) {\n\n let node = d3.selectAll('.node');\n\n console.log(node);\n\n //Reset labels\n node.selectAll(\"text\").remove();\n\n node.append(\"text\")\n .text((d) => totalETX[d.id].toFixed(2))\n .attr(\"x\", (d) => d.x)\n .attr(\"y\", (d) => d.y);\n}", "function setPositionOfOldLabelsOnNewLabels( oldLabelNodes, labelNodes ){\n labelNodes.forEach(function ( labelNode ){\n for ( var i = 0; i < oldLabelNodes.length; i++ ) {\n var oldNode = oldLabelNodes[i];\n if ( oldNode.equals(labelNode) ) {\n labelNode.x = oldNode.x;\n labelNode.y = oldNode.y;\n labelNode.px = oldNode.px;\n labelNode.py = oldNode.py;\n break;\n }\n }\n });\n }", "setInternalNodeLabels(annotationName) {\n this.internalNodeLabelAnnotationName = annotationName;\n this.update();\n }", "addLabel(label) {\n if (label.length > 0) {\n this.labels.push(label);\n this.haschanges = true;\n }\n }", "function addNewLabel() {\n // If not empty\n if (data.label) {\n // If not in list\n if (data.labels.indexOf(data.label) === -1) {\n data.labels.push(data.label);\n }\n }\n \n data.label = \"\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a span from an array, returning undefined if no spans are left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) { for (var r, i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]); return r; }
[ "function removeMarkedSpan(spans, span) { // 5537\n for (var r, i = 0; i < spans.length; ++i) // 5538\n if (spans[i] != span) (r || (r = [])).push(spans[i]); // 5539\n return r; // 5540\n } // 5541", "function removeMarkedSpan(spans, span) {\n for (var r, i = 0; i < spans.length; ++i)\n if (spans[i] != span) (r || (r = [])).push(spans[i]);\n return r;\n }", "function removeMarkedSpan(spans, span) {\n for (var r, i = 0; i < spans.length; ++i)\n if (spans[i] != span) (r || (r = [])).push(spans[i]);\n return r;\n }", "function removeSpan(id) {\n for( var i=0; i<spans.length; i++){ \n if ( spans[i].id === id) { spans.splice(i,1); }\n }\n}", "function removeSpans() {\n\tspans = [];\n\tindex = false;\n\tdocument.body.innerHTML = document.body.innerHTML.replace(/(<\\/?span[^>]*>)/igm, \"\");\n}", "function clearEmptySpans(spans) { // 5644\n for (var i = 0; i < spans.length; ++i) { // 5645\n var span = spans[i]; // 5646\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) // 5647\n spans.splice(i--, 1); // 5648\n } // 5649\n if (!spans.length) return null; // 5650\n return spans; // 5651\n } // 5652", "function removeSpanElement() {\n if (spanElement && spanElement.remove) {\n spanElement.remove();\n }\n spanElement = null;\n }", "function clearEmptySpans(spans) {\n for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n { spans.splice(i--, 1); }\n }\n if (!spans.length) { return null }\n return spans\n }", "function clearEmptySpans(spans) {\n\t\t for (var i = 0; i < spans.length; ++i) {\n\t\t var span = spans[i];\n\t\t if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n\t\t spans.splice(i--, 1);\n\t\t }\n\t\t if (!spans.length) return null;\n\t\t return spans;\n\t\t }", "function clearEmptySpans(spans) {\n for (var i = 0; i < spans.length; ++i) {\n var span = spans[i]\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n { spans.splice(i--, 1) }\n }\n if (!spans.length) { return null }\n return spans\n }", "function span (array) {\n return array && peek(array) - array[0] || 0;\n}", "function getOldSpans(doc, change) { // 7200\n var found = change[\"spans_\" + doc.id]; // 7201\n if (!found) return null; // 7202\n for (var i = 0, nw = []; i < change.text.length; ++i) // 7203\n nw.push(removeClearedSpans(found[i])); // 7204\n return nw; // 7205\n } // 7206", "function array_remove(arr, pos) {\n var part1=arr.concat([]);\n var part2=part1.splice(pos+1);\n return part1.splice(0, pos).concat(part2);\n}", "function getOldSpans(doc, change) {\n\t var found = change[\"spans_\" + doc.id];\n\t if (!found) return null;\n\t for (var i = 0, nw = []; i < change.text.length; ++i)\n\t nw.push(removeClearedSpans(found[i]));\n\t return nw;\n\t }", "function deleteSpan(context) {\n return context.deleteValue(SPAN_KEY);\n}", "function span(array) {\n return array && peek(array) - array[0] || 0;\n }", "function getOldSpans(doc, change) {\n\t\t var found = change[\"spans_\" + doc.id];\n\t\t if (!found) return null;\n\t\t for (var i = 0, nw = []; i < change.text.length; ++i)\n\t\t nw.push(removeClearedSpans(found[i]));\n\t\t return nw;\n\t\t }", "function getOldSpans(doc, change) {\n\t\t var found = change[\"spans_\" + doc.id];\n\t\t if (!found) { return null }\n\t\t var nw = [];\n\t\t for (var i = 0; i < change.text.length; ++i)\n\t\t { nw.push(removeClearedSpans(found[i])); }\n\t\t return nw\n\t\t }", "function removingHighlightSpan(){\n const spanTags = document.querySelectorAll(\".js-stringMatched\");\n let text = \"\";\n \n for (let i = 0, len = spanTags.length; i < len; i++){\n let h3 = spanTags[i].parentNode;\n text = h3.textContent;\n h3.innerHTML = text;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A callback function for ``nextMolecule`` and ``getMolecule``. When the server sends back the structure of the next molecule to be rendered, this function is run. It updates ``currentMolecule`` and renders the new molecule.
function updateState() { [molInchi, molStructure] = JSON.parse(this.responseText); viewer.loadMoleculeStr(undefined, molStructure); // Allow new requests to be sent. buttonsOn = true; }
[ "function update() {\n makeMolecules();\n}", "function nextMolecule(username)\n{\n buttonsOn = false;\n\n let nextMolRequest = new XMLHttpRequest();\n nextMolRequest.addEventListener(\"load\", requestListener('nextMolecule'));\n nextMolRequest.addEventListener(\"load\", updateState);\n nextMolRequest.open(\"GET\", `/mols/${username}/next`);\n nextMolRequest.send();\n}", "function next() {\r\n console.log( \"next\" );\r\n if ( index < components.length -1 ) {\r\n executeComponent( components, index +1, callback );\r\n }\r\n\r\n else {\r\n callback();\r\n }\r\n }", "function next() {\n console.log( \"next\" );\n if ( index < components.length -1 ) {\n executeComponent( components, index +1, callback );\n }\n\n else {\n callback();\n }\n }", "function recycleMolecule() {\n deleteMolecule();\n newMolecule();\n}", "function reloadMolecules() {\n\tvar container = jQuery(\"ul#molecules\");\n\tjQuery.ajax({\n\t\turl: \"MoleculeData\",\n\t\tdataType: \"json\",\n\t\tcache:false,\n\t\tsuccess: function(data){\n\t\t\t//empty navigation container\n\t\t\tcontainer.empty();\n\t\t\t//add all molecules to sidebar\n\t\t\tjQuery.each(data, function(k,v){\n\t\t\t\tvar li = jQuery(\"<li style='cursor:pointer;' id='\"+v.id+\"'><a href='#'>\"+v.name+\"(\"+v.formula+\")</a></li>\");\n\t\t\t\tli.data('data', v);\n\t\t\t\tli.find('a').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\tloadMolecule(v);\n\t\t\t\t});\n\t\t\t\tcontainer.append(li);\t\n\t\t\t});\n\t\t\t// select first molecule if no other is selected\n\t\t\tif (jQuery(\"ul#molecules\").find('li.active').size()===0){\n\t\t\t\tjQuery(\"ul#molecules\").find('li:first > a').click();\n\t\t\t}\n\t\t\t\n\t\t}\n\t});\n}", "function sync () {\n\t\t\t\tpairs_to_box();\n\t\t\t\trender();\n\t\t\t}", "function next() {\n if (currentContactIndex < (contactArray.length-1)) {\n currentContactIndex++;\n }\n currentContact = contactArray[currentContactIndex];\n viewCurrentContact();\n}", "function newMolecule() {\n var key = getUniqueMoleculeText();\n\n // Dont add to DOM if ID already exists. Up for\n // modifications in case multiple drafts of New Molecule need to be\n // simultaneously worked upon.\n if ($('#Container' + key).length !== 0) {\n return;\n }\n\n // Load the Unique Molecule Ids into the select\n var container = document.getElementById(\"container\");\n\n var div = document.createElement(\"div\");\n div.id = \"Container\" + key;\n div.className += \" ui-widget-content inlineDivs\";\n console.log(getCanvasWidth());\n $(\"#Container\" + key).width(getCanvasWidth());\n //container.insertBefore(div, container.firstChild); // OR container.append(div); if div to be added below.\n container.append(div);\n\n $( function() {\n $(\"#Container\" + key).resizable({handles: 'e, w'});\n $(\"#Container\" + key).draggable({containment: \"#container\"});\n });\n\n var colorScheme = [\"#2AA9CC\", \"#FCF78A\", \"#4FFFC5\", \"#FFA09B\", \"#CC3F87\", \"#32FF47\", \"#E8C72E\", \"#942EE8\", \"#3FD6FF\"];\n\n var options = {\n domElement: \"#Container\",\n uniqueId: 1,\n width: getCanvasWidth(), \n height: getCanvasHeight(),\n borderThickness: getCanvasBorderThickness(),\n borderColor: getCanvasBorderColor(),\n background: getCanvasBackgroundColor(),\n charge: getMoleculeCharge(),\n friction: getMoleculeFriction(),\n alpha: getMoleculeAlpha(),\n theta: getMoleculeTheta(),\n linkStrength: getMoleculeLinkStrength(),\n gravity: getMoleculeGravity(),\n maxAtomRadius: getMaxAtomRadius(),\n colorScheme: colorScheme,\n bondThickness: getBondThickness(),\n bondColor: getBondColor(),\n atomBorderThickness: getAtomBorderThickness(),\n atomBorderColor: getAtomBorderColor(),\n atomTextColor: getAtomTextColor(),\n atomSizeBasis: getAtomSizeBasis(),\n boundingBox: isCanvasBoundingBox(),\n borderRadiusX: getCanvasBorderRadiusX(),\n borderRadiusY: getCanvasBorderRadiusY(),\n detailedTooltips: showDetailedTooltips()\n };\n\n\n for (var i = 0; i < Examples[key].nodes.length; i++) {\n Examples[key].nodes[i][\"size\"] = Elements[Examples[key].nodes[i][\"atom\"]][getAtomSizeBasis()];\n }\n\n eval(\"var options\"+key+\"=JSON.parse(JSON.stringify(options))\");\n eval(\"options\"+key)[\"domElement\"]=\"#Container\"+key;\n eval(\"options\"+key)[\"uniqueId\"]=key;\n eval(\"molecule\"+key+\"=new Molecule(JSON.parse(JSON.stringify(Examples[key])),eval('options'+key))\");\n eval(\"molecule\"+key).render();\n}", "function showNextArticle() {\n var count = wikiArticles.length;\n var article = wikiArticles[count - 1]; // current article.\n $('.wiki-articles .wiki-article').detach(); // remove old article.\n $('.wiki-articles').html(renderArticle(article)); // replace with the current article.\n $('.indicator').removeClass('processing'); // hide the \"processing\" message.\n // If this is not the first article, add the last article to the sidebar.\n if (count > 1) {\n $('.init').removeClass('init'); // removes class that hides the sidebar title.\n $('#viewed-articles ul').prepend(renderSidebarItem(wikiArticles[count - 2]));\n }\n }", "function activateMolecule() {\n molecules.forEach(molecule => {\n molecule.render();\n molecule.checkEdges();\n molecule.radiateMolecule();\n molecule.reset();\n });\n}", "function renderNextChampion() {\n getOptions(function (items) {\n var region = items.region;\n var summoner = items.summoner;\n if(summoner == '') {\n goToSettings();\n return;\n }\n getNextChampion(region, summoner, function(championName, championImageUrl) {\n setChampion(championName, championImageUrl);\n }, function(msg) {\n showError(msg);\n });\n })\n}", "function next() {\n\n show( ( getIndex() + 1 ) % layers.length, 'right' );\n\n }", "function updateNextSongDiv(songDivIndx) {\r\n\tvar songObj = getPlayedSong(songDivIndx);\r\n\tvar nextSongDiv = $(\"#scheduler .playedSongs .songsContainer\")[0].children[songDivIndx];\r\n\tvar songTitleDiv = nextSongDiv.getElementsByClassName('songTitle')[0];\r\n\tvar artistDiv = nextSongDiv.getElementsByClassName('artist')[0];\r\n\tvar timeDiv = nextSongDiv.getElementsByClassName('time')[0];\r\n\tnewSongObj = listOfPlayedSongs[songDivIndx];\r\n\tsongTitleDiv.innerHTML = newSongObj.title;\r\n\tartistDiv.innerHTML = newSongObj.artist;\r\n\ttimeDiv.innerHTML = newSongObj.time;\r\n}", "function refreshMolecule() {\n var key = getUniqueMoleculeText();\n eval(\"molecule\"+key).configureForces();\n}", "next () {\n this.currentGrid = this.grid.getSplittedBinaryData()\n this.pickNewBlock()\n }", "requestNextFrame() {\n requestAnimationFrame(this.renderDMD.bind(this));\n }", "nextMaterial(){\n this.materialsIndex++;\n this.materialsIndex = this.materialsIndex % this.materialsID.length;\n }", "async nextLayout() {\n // Update layoutIndex.\n this.layoutIndex = (this.layoutIndex + 1) % this.playlist.length;\n\n // Show this layout next:\n let layout = this.playlist[this.layoutIndex];\n\n // Reset moduleIndex\n this.moduleIndex = -1;\n\n // The time that we'll switch to a new layout.\n this.newLayoutTime = inFuture(layout.duration * 1000);\n\n if (monitor.isEnabled()) {\n monitor.update({playlist: {\n time: now(),\n event: `change layout`,\n deadline: this.newLayoutTime\n }});\n }\n\n log(`Next Layout: ${this.layoutIndex}`);\n\n // If the wall isn't already faded out, fade it out:\n let concurrentWork = [];\n if (this.modulePlayer.oldModule.name != '_empty') {\n // Give the wall 1 second to get ready to fade out.\n this.lastDeadline_ = now() + 1000;\n concurrentWork.push(this.modulePlayer.playModule(RunningModule.empty(this.lastDeadline_)));\n }\n // Shuffle the module list:\n this.modules = Array.from(layout.modules);\n random.shuffle(this.modules);\n this.nextModule();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the images for the dot of index dotNumber
function showContentDot(dotNumber){ var dots = document.getElementsByClassName("h5p-image-gallery-dot"); // start rowindex of images showing var start = dotNumber*maximumNumberofRows; // end rowindex of images showing var end = start+maximumNumberofRows; // if dots exists - show only content of dot with index dotNumber if (dots.length > 1){ images.forEach(function(element, index){ var imageElement = document.getElementById('h5p-image-gallery-image-'+index); if (element.image.row >= start && element.image.row < end){ imageElement.style.display = 'inline-block'; } else{ imageElement.style.display = 'none'; } }); for (var i = 0; i < dots.length; i++){ dots[i].classList.remove('h5p-image-gallery-dotCurrent'); } // add color to current dot var dotOn = document.getElementById('h5p-image-gallery-dot-'+dotNumber); dotOn.classList.add('h5p-image-gallery-dotCurrent'); // keep track of current dot index currentDot(dotNumber); } }
[ "#displayClickableDots() {\n\n const dotControls = this.#controls.querySelector(\".dot-controls\");\n\n // remove any existing dots. needed if pictures gets changed later.\n while(dotControls.firstChild){\n dotControls.removeChild(dotControls.firstChild);\n }\n\n this.#pictures.forEach((pic, index) => {\n const dot = document.createElement(\"button\");\n this.#addClassesToElement(dot, \"dot-index\");\n \n dot.addEventListener(\"click\", () => {\n if (index === this.#currentPicIndex) {\n return;\n }\n\n this.#previousPicIndex = this.#currentPicIndex;\n \n this.#loadImage.call(this, index);\n this.#currentPicIndex = index;\n });\n\n dotControls.append(dot);\n });\n }", "function showImage(index) {\n\tvar count = 0;\n\t$('.images').each(function() {\n\t\tif (count === index) {\n\t\t\t$(this).fadeIn(fadeInSpeed);\n\t\t}\n\t\telse {\n\t\t\t$(this).hide();\n\t\t}\n\t\tcount++;\n\t});\n\n\thighlightDot(index);\n}", "function getDotIndex(ev) {\n let index = ev.target.getAttribute(\"data-index\");\n idx = Number(index);\n changeImages(index);\n}", "function dotClicked(e) {\n //extract id from dot\n dotNum = e.target.id;\n\n //if no dot was clicked exit\n if (!dotNum) return;\n\n //get photo number\n photoNum = dotNum.slice(-1);\n current = Number(photoNum);\n\n //change image\n changeImage(current);\n\n // restart the intervaltimer\n clearInterval(slideShowTimer);\n slideShow();\n}", "show(){\n for(var i = 0;i<this.dots.length;i++){\n this.dots[i].show();\n }\n }", "function displayPosition(idx) {\n $(\"#pos-info\").html(`<p>Image ${idx + 1} of ${IMAGES.length}</p>`);\n }", "function setActiveDot() {\n for (var i = 0; i < imageCount; i++) {\n if (i == index) {\n dot_container.children[i].className += \" active\";\n } else {\n dot_container.children[i].className = \"dot\";\n }\n }\n }", "function showFirstDot(){\n var dots = document.getElementsByClassName(\"h5p-image-gallery-dot\");\n if (dots.length > 0){\n showContentDot(0);\n }\n}", "function plusImgs(n) {\n showImages((imageIndex += n));\n}", "function createDots() {\n for (let i = 0; i < $(\".slider img\").length - 1; i++) {\n let dot = \"<li> </li>\"\n $(\".dots ul\").append(dot);\n }\n }", "function show_annabot(x, y) {\n var name = imagename(x, y);\n document.images[name].src = ANNABOT_SRC;\n}", "function processDots(){\n var refHex = getHexOnClick();\n var hOffset = roffsetFromCube(EVEN, refHex);\n \n if(hOffset.row <= dotArray.length-1 && hOffset.row >= 0 &&\n hOffset.col <= dotArray[0].length-1 && hOffset.col >= 0){\n var refDot = dotArray[hOffset.row][hOffset.col];\n addDot(refDot);\n }\n }", "function createDot() {\n\tvar dot = Ti.UI.createView( {\n\t\tbackgroundImage: '/images/dot.png',\n\t\twidth: Layout.PAGER_DOT_SIZE,\n\t\theight: Layout.PAGER_DOT_SIZE,\n\t\tleft: Layout.WHITESPACE_GAP,\n\t\tbottom: '2dip',\n\t\topacity: 0.5} );\n\treturn dot;\n}", "function createDots (count) {\n var text = \"\";\n for(i=0; i< count; i++) {\n text = \"<a href='javascript:;' class='dot' id='\"+i+\"'></a>\"+text;\n }\n $(\"#slideshow #dots\").append(text);\n }", "function makeEvents(i){\n var dotElement = document.getElementById('h5p-image-gallery-dot-'+i);\n dotElement.onclick = function(){\n showContentDot(i);\n }\n}", "function show_img_index(index) {\n\tvar numIndex = parseInt(index);\n\ttry {\n\t\tfor (var a = 0; a <= listNameOfImg.length - 1; a++) {\n\t\t\tif (a == numIndex) {\n\t\t\t\timgNew.setAttribute(\"src\", listImg[a]);\n\t\t\t\timgNew.setAttribute(\"alt\", listNameOfImg[a]);\n\t\t\t\tslide();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthrow \"Image error!\";\n\t} catch (err) {\n\t\twindow.alert(err);\n\t}\n}", "function showThreePics() {\n makeArrayOfThreeNumbers();\n left.src = allProducts[newArray[0]].filePath;\n allProducts[newArray[0]].views += 1;\n center.src = allProducts[newArray[1]].filePath;\n allProducts[newArray[1]].views += 1;\n right.src = allProducts[newArray[2]].filePath;\n allProducts[newArray[2]].views += 1;\n}", "function makeDot(colorIndex, pos){\n //make a dot sprite from the dots group\n //use the colorArray (see line 39) to select the image\n //use the 'mod' (same as remainder) of the colorIndex to choose a color (4%4 == 0, 5%4 == 1, 6%4 == 2, etc)\n if(colorArray[colorIndex%4] == player.color)\n {\n colorIndex++;\n }\n var dot = dots.create(pos.x, pos.y, colorArray[colorIndex%4]);\n\n dot.color = colorIndex%4; //set the dot color to the color based on the mod\n\n dot.anchor.setTo(0.5, 0.5); //set the anchor to the middle, not the side\n dot.scale.set(0.5, 0.5); //set the scale to half size, the image is twice as large as we want it to show up in the game\n }", "getDotId(index) {\r\n return `dot${index}`;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for movePlayer to animate player sprite while walking.
function walkingAnimation(direction) { var spriteX = ""; var spriteY1 = "50%"; var spriteY2 = "100%"; direction = (direction) ? direction : playerDirection; switch (direction) { case "up": spriteX = "33.333%"; break; case "down": spriteX = "0%"; break; case "left": spriteX = "66.666%"; break; case "right": spriteX = "100%"; break; default: }; if (playerState !== "walking") { clearInterval(walkingAnimationInterval); walkingAnimationInterval = null; $("#player").css("background-position", spriteX + " 0%"); walkingSound.pause(); } else if (playerState === "walking" && walkingAnimationInterval === null) { $("#player").css("background-position", spriteX + " 0%") walkingAnimationInterval = setInterval(function() { if(walkingSpriteToken === 0) { $("#player").css("background-position", spriteX + " " + spriteY1); walkingSpriteToken = 1; } else { $("#player").css("background-position", spriteX + " " + spriteY2); walkingSpriteToken = 0; } }, 150); walkingSound.play(); } }
[ "animateMove(){\n\t\tthis._state = \"walking\"\n\t\tthis.currentMoveFkt();\n\t\tthis._animationTimer--;\n\t}", "animateWallJump()\n {\n if(this.player.stateManager.wallJump.direction == WallDirection.LEFT)\n {\n this.direction = 'left';\n }\n else\n {\n this.direction = 'right';\n }\n this.player.animations.play('wall_jump_' + this.direction);\n }", "function movePlayer() {\n // If the player has to move/is moving...\n if (playerMoving === true) {\n // Add 1 to the current walk frame\n playerWalkFrame++;\n // If the current walk frame is greater or equal to the number of elements in the walk pattern...\n if (playerWalkFrame >= walkPattern.length) {\n // Set the current walk frame back to 0\n playerWalkFrame = 0;\n }\n }\n // Else, if the player is not moving...\n else {\n // Make the player standing by setting its walk frame to 1\n playerWalkFrame = 1;\n // Stop moving the player by setting its velocity to 0\n playerVelocityX = 0;\n playerVelocityY = 0;\n }\n // Make the player walk, move and rotate\n walk($playerCharacter, playerVelocityX, playerVelocityY, playerWalkFrame);\n}", "function walk() {\n // If the player has to move/is moving...\n if (playerMoving === true) {\n // Remove the player's class\n $('#player').removeAttr('class');\n // And add a new class corresponding to the current walk frame\n $('#player').addClass(walkPattern[currentWalkFrame]);\n // Add 1 to the current wlak frame\n currentWalkFrame ++;\n // If the current walk frame is greater or equal to the numer of element in the walk pattern...\n if (currentWalkFrame >= walkPattern.length) {\n // Set the current walk frame back to 0\n currentWalkFrame = 0;\n }\n }\n // Else, if the player is not moving...\n else {\n // Remove the player class\n $('#player').removeAttr('class');\n // And add the second element of the walk pattern as the new class\n $('#player').addClass(walkPattern[1]);\n }\n}", "function movePlayer(dir){\n\t\n\t// if not animation set to moving direction set it and start the animation\n\tif(player.animation()!='move'+DIRECTIONS[dir]){\n\t\tvar start = player.animation().startsWith('idle');\n\t\tplayer.setAnimation('move'+DIRECTIONS[dir]);\n\t\tif(start)\n\t\t\tplayer.start();\n\t\tif(curMovement)\n\t\t\tcurMovement.stop();\n\t\tcurMovement = playerMovements[dir];\n\t\tplayerMovements[dir].start();\n\t}\n}", "changePlayerAnimation () {\n\n if (Math.abs(this.player.deltaY) > Math.abs(this.player.deltaX)) {\n // change to up//down texture\n \n if (this.player.deltaY > 0) {\n\n this.player.animations.play('walk-down');\n this.direction = 'down';\n\n } else if ( this.player.deltaY < 0) {\n\n this.player.animations.play('walk-up'); \n this.direction = 'up';\n }\n\n } else if (this.player.deltaX > 0) {\n\n this.player.animations.play('walk-right');\n this.direction = 'right';\n\n } else if (this.player.deltaX < 0) {\n\n this.player.animations.play('walk-left');\n this.direction = 'left';\n\n } else if (this.speech.alive) {\n\n if (this.speech.name == 'player') {\n this.player.animations.play('talk');\n } else {\n // this.talkingSprite = this.getSprite(this.speech.name);\n // this.talkingSprite.animations.play('talk');\n this.player.animations.stop();\n }\n\n } else { \n //stop\n this.talkingSprite ? this.talkingSprite.animations.stop():null;\n\n if (this.direction == 'left' || this.direction == 'up') {\n this.player.animations.stop();\n this.player.frameName = 'stand-left';\n } else {\n this.player.animations.stop();\n this.player.frameName = 'stand-right';\n }\n } \n }", "function playerStartedPath() {\n\t\tSprite_Player.startAnimation('WALK');\n\t}", "function move() {\n movingPlayer = true;\n}", "updateAnimation() {\n if (this.isMoving()) {\n if (this.dirX == -1)\n this.animator.changeFrameSet(this.frameSets[\"swim-left\"],\n \"loop\", 5);\n else\n this.animator.changeFrameSet(this.frameSets[\"swim-right\"],\n \"loop\", 5);\n } else {\n if (this.dirX == -1)\n this.animator.changeFrameSet(this.frameSets[\"idle-left\"],\n \"pause\");\n else\n this.animator.changeFrameSet(this.frameSets[\"idle-right\"],\n \"pause\");\n }\n \n this.animator.animate();\n }", "function animateCharacter() {\n isJumping = (timePassedSinceJump < JUMP_TIME * 2) && !isWounded;\n animateRunningCharacter();\n animateJumpingCharacter();\n animateStandingCharacter();\n animateSleepingCharacter();\n animateWoundedCharacter();\n animateDeadCharacter();\n if (!isMovingLeft && !isMovingRight || isJumping) {\n AUDIO_RUNNING.pause(); // pauses running audio when standing or jumping\n }\n }", "function movePlayers() {\n for (let id in players) {\n if (id != PLAYER_ID) {\n if (cursors[id].left)\n {\n players[id].anims.play('walk_left', true);\n players[id].setVelocity(-speed, 0);\n }\n else if (cursors[id].right)\n {\n players[id].anims.play('walk_right', true);\n players[id].setVelocity(speed, 0);\n }\n else if (cursors[id].up)\n {\n players[id].anims.play('walk_up', true);\n players[id].setVelocity(0, -speed);\n }\n else if (cursors[id].down)\n {\n players[id].anims.play('walk_down', true);\n players[id].setVelocity(0, speed);\n }\n else\n {\n var sprite = players[id].anims.currentAnim.key.split('_');\n sprite.push('2.png');\n players[id].play(sprite.join('_'));\n players[id].setVelocity(0, 0);\n }\n }\n }\n}", "function moveSprite() {\n if(keyIsDown(RIGHT_ARROW)) {\n playerSprite.velocity.x = 10;\n mirrorSprite.velocity.x = 10;\n playerSprite.changeAnimation('rightWalk');\n mirrorSprite.changeAnimation('rightWalk');\n lastKeyPressed = keyRight;\n keyHeld = true;\n }\n else if(keyIsDown(LEFT_ARROW)) {\n playerSprite.velocity.x = -10;\n mirrorSprite.velocity.x = -10;\n playerSprite.changeAnimation('leftWalk');\n mirrorSprite.changeAnimation('leftWalk');\n lastKeyPressed = keyLeft;\n keyHeld = true;\n }\n else {\n playerSprite.velocity.x = 0;\n mirrorSprite.velocity.x = 0;\n keyHeld = false;\n }\n\n if(keyIsDown(DOWN_ARROW)) {\n playerSprite.velocity.y = 10;\n mirrorSprite.velocity.y = 10;\n playerSprite.changeAnimation('frontWalk');\n mirrorSprite.changeAnimation('backWalk');\n lastKeyPressed = keyFront;\n keyHeld = true;\n }\n else if(keyIsDown(UP_ARROW)) {\n playerSprite.velocity.y = -10;\n mirrorSprite.velocity.y = -10;\n playerSprite.changeAnimation('backWalk');\n mirrorSprite.changeAnimation('frontWalk');\n lastKeyPressed = keyBack;\n keyHeld = true;\n }\n else {\n playerSprite.velocity.y = 0;\n mirrorSprite.velocity.y = 0;\n }\n\n// Use lastKeyPressed to use idle animations\n if(!keyHeld) {\n if(lastKeyPressed === keyRight) {\n playerSprite.changeAnimation('rightIdle');\n mirrorSprite.changeAnimation('rightIdle');\n }\n if(lastKeyPressed === keyLeft) {\n playerSprite.changeAnimation('leftIdle');\n mirrorSprite.changeAnimation('leftIdle');\n }\n if(lastKeyPressed === keyFront) {\n playerSprite.changeAnimation('regular');\n mirrorSprite.changeAnimation('backIdle');\n }\n if(lastKeyPressed === keyBack) {\n playerSprite.changeAnimation('backIdle');\n mirrorSprite.changeAnimation('regular');\n }\n }\n}", "walk() {\n if (this.state == 'walking') {\n return;\n }\n if (this.isJumpCooldown()) {\n return;\n }\n if (this.isLandPlaying()) {\n return;\n }\n this.state = 'walking';\n this.playAnimation(this.walkingAnimationName);\n }", "function movePlayer()\n {\n player.attractionPoint(2, xpos, ypos);\n }", "function renderWalkAnimation(){\n\t\t\t\tvar x = p.x - 64/2;\n\t\t\t\tvar y = p.y - (64/2)-10;\n\n\t\t\t\ttickCount += 1;\n\t\t\t\tif(tickCount > ticksPerFrame){\n\t\t\t\t\ttickCount = 0;\n\t\t\t\t\tif(frameIndex < numberOfFrames - 1){\n\t\t\t\t\t\tframeIndex += 1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tframeIndex = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t// left\n\t\t\t\t\tif(Keys.left == true){\n\t\t\t\t\t\tctx.drawImage(character,frameIndex*64,64*9,64,64,x,y,64,64);\n\t\t\t\t\t\tlastFrame = \"left\";\n\t\t\t\t\t}\n\t\t\t\t\t// right\n\t\t\t\t\telse if(Keys.right == true){\n\t\t\t\t\t\tctx.drawImage(character,frameIndex*64,64*11,64,64,x,y,64,64);\n\t\t\t\t\t\tlastFrame = \"right\";\n\t\t\t\t\t}\n\t\t\t\t\t// up\n\t\t\t\t\telse if(Keys.up == true){\n\t\t\t\t\t\tctx.drawImage(character,frameIndex*64,64*10,64,64,x,y,64,64);\n\t\t\t\t\t\tlastFrame = \"up\";\n\t\t\t\t\t}\n\t\t\t\t\t// down\n\t\t\t\t\telse if(Keys.down == true){\n\t\t\t\t\t\tctx.drawImage(character,frameIndex*64,64*8,64,64,x,y,64,64);\n\t\t\t\t\t\tlastFrame = \"down\";\n\t\t\t\t\t}\n\t\t\t\t\t// else the player faces the last direction they were moving\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(lastFrame == \"left\")ctx.drawImage(character,0,64*9,64,64,x,y,64,64);\n\t\t\t\t\t\tif(lastFrame == \"right\")ctx.drawImage(character,0,64*11,64,64,x,y,64,64);\n\t\t\t\t\t\tif(lastFrame == \"up\")ctx.drawImage(character,0,64*10,64,64,x,y,64,64);\n\t\t\t\t\t\tif(lastFrame == \"down\")ctx.drawImage(character,0,64*8,64,64,x,y,64,64);\n\t\t\t\t\t}\n\t\t\t}", "animateGround()\n {\n if(this.player.stateManager.currentState != this.player.stateManager.ground)\n {\n return;\n }\n\n this.calculateDirection();\n\n // play the idle animation if the player is stationary\n if(this.player.inputManager.getHorizontalInput() == 0)\n {\n this.player.animations.play('idle_' + this.direction);\n return;\n }\n \n\n // determine the slant of the ground\n var slant = '';\n\n if(this.player.stateManager.ground.standingDirection == StandingDirection.LEFT)// if I'm on a slant to my right\n {\n slant = (this.direction == 'right' ? '_up_diagonal' : '_down_diagonal');\n }\n else if(this.player.stateManager.ground.standingDirection == StandingDirection.RIGHT)// if I'm on a slant to my left\n {\n slant = (this.direction == 'right' ? '_down_diagonal' : '_up_diagonal');\n }\n\n this.player.animations.play('run_' + this.direction + slant);\n }", "function movementAnimationUpdate(){\n\t//killer.updateMovement();\n}", "function move(unit) {\n movingUnit = unit;\n\tmovingPlayer = true;\n}", "function move( object, x, y, seconds, onFinished ) {\n\t\treturn new Animation( new Move( object, x, y, seconds, onFinished ) ).play();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forward instructions to individual components. The manager calls this method to make the panel focus or show a property field or a tab, possibly suggesting a position. The distance that the form in the panel was scrolled since a position was last transmitted can be used to replicate that movement immediately while converting jumps due to inconsistent field sizes to softscroll operations.
function fireShow(content/*:Content*/, tabTitle/*:String*/, property/*:String*/, isFocus/*:Boolean*/, setCurrentProperty/*:Boolean*/, sendState/*:Boolean*/, position/*:Number*/, distance/*:Number*/, scrollOnly/*:Boolean*/)/*:void*/ { this.externallyControlled$hWxS = true; this.currentContent$hWxS = content; this.currentProperty$hWxS = property; this.currentTabTitle$hWxS = tabTitle; this.currentSetCurrentProperty$hWxS = setCurrentProperty; this.currentPosition$hWxS = position; this.doFireShow$hWxS(isFocus, sendState, distance, scrollOnly); }
[ "focus() {\n super.focus();\n // If (this._mathfield) {\n // // Don't call this._mathfield.focus(): it checks the focus state,\n // // but super.focus() just changed it...\n // this._mathfield.keyboardDelegate.focus();\n // this._mathfield.model.announce('line');\n // }\n }", "updatePosition() {\n if (this.component) {\n this.component.updatePosition();\n }\n }", "function repositionInputFields(obj)\n\t{\n\t\tshowInputs();\n\t}", "move_FormTab_Up(){\n this.formTab.waitForExist();\n browser.touchAction('~Form', ['longPress', {action: 'moveTo', x: 0, y: (this.Y_Axis_FormTab-400)}, 'release']);\n }", "_showForm(mapE) {\n this.#mapEvent = mapE;\n form.classList.remove('hidden');\n inputDistance.focus();\n }", "_showForm(mapE) {\n this.mapEvent = mapE; // needs to pass to form submit event handler\n form.classList.remove('hidden');\n inputDistance.focus();\n }", "function move() {\n clickedField.placePiece(focusField.piece);\n focusField.removeHighlight();\n removeAvailableFields();\n focusField.removePiece();\n focusField = null;\n}", "updateViewablePositionForAutocomplete() {\n if (this.displayer && this.inputWrapper) {\n this.inputWrapper.current.scrollLeft =\n this.displayer.current.clientWidth > this.inputWrapper.current.clientWidth\n ? this.displayer.current.clientWidth - this.inputWrapper.current.clientWidth\n : 0;\n }\n }", "dispatchStepFocus() {\n /**\n * Event that fires when focusing on step.\n *\n * @event\n * @name stepfocus\n * @public\n */\n this.dispatchEvent(new CustomEvent('stepfocus'));\n }", "function focusShowLocationCard() {\n dispatch(showLocation());\n dispatch(\n setMouseCoordinates({\n x:\n section.current.offsetParent.offsetLeft +\n section.current.offsetLeft +\n section.current.clientHeight,\n y:\n section.current.offsetParent.offsetTop +\n section.current.offsetTop,\n }),\n );\n dispatch(setLocationData(data));\n }", "_focus() {\n if (!this.searchSelectInput || !this.novoSelect.panel) {\n return;\n }\n // save and restore scrollTop of panel, since it will be reset by focus()\n // note: this is hacky\n const panel = this.novoSelect.panel.nativeElement;\n const scrollTop = panel.scrollTop;\n // focus\n this.searchSelectInput.nativeElement.focus();\n panel.scrollTop = scrollTop;\n }", "function updateComponentPositions() {\r\n // The last call was moving the component.\r\n if (lastCall == 'processComponent.mouseup') {\r\n\r\n // You need the scale of the workspace incase the user zoomed\r\n var workspaceDiv = jQuery('#process-div')[0];\r\n var scale = workspaceDiv.getBoundingClientRect().width / workspaceDiv.offsetWidth;\r\n\r\n if (jQuery('.process-component').length > 0) {\r\n jQuery('.process-component').each(function(index, value) {\r\n\r\n // Node position info.\r\n var divPosition = jQuery(value).position();\r\n var id = jQuery(value).attr('id');\r\n\r\n var draggableParent = jQuery('#' + id);\r\n var compName = jQuery('#' + id + ' .compName').text();\r\n componentOptions[id].top = Math.round(parseFloat(divPosition.top) / scale);\r\n componentOptions[id].left = Math.round(parseFloat(divPosition.left) / scale);\r\n });\r\n }\r\n if (currentDigraph.components != null && currentDigraph.components.length > 0) {\r\n jQuery.each(currentDigraph.components, function(componentInd, component) {\r\n if (component != undefined && component != null) {\r\n component.top = componentOptions[component.component_id].top;\r\n component.left = componentOptions[component.component_id].left;\r\n }\r\n });\r\n }\r\n }\r\n}", "_jumpToStep(evt) {\n if (evt.currentTarget == undefined) {\n // a child step wants to invoke a jump between steps\n this._setNavState(evt);\n }\n else {\n // the main navigation step ui is invoking a jump between steps\n if (!this.props.stepsNavigation) {\n evt.preventDefault();\n evt.stopPropagation();\n\n return;\n }\n if(_.isEmpty(this.refs)){\n this._setNavState(this.state.compState + 1);\n }else{\n let validate = this.refs&&this.refs.activeComponent&&this.refs.activeComponent.isValidated?this.refs.activeComponent.isValidated():true;\n let isupdated = this.refs&&this.refs.activeComponent&&this.refs.activeComponent.isUpdated?this.refs.activeComponent.isUpdated():true;\n if (this.props.dontValidate || typeof this.refs.activeComponent.isValidated == 'undefined' || this.refs.activeComponent.isValidated() ) {\n if (evt.currentTarget.value === (this.props.steps.length - 1) &&\n this.state.compState === (this.props.steps.length - 1)) {\n this._setNavState(this.props.steps.length);\n }\n else {\n this._setNavState(evt.currentTarget.value);\n }\n }else if(!this.props.dontValidate && !validate){\n this.setState({\n maditoryModalOpen: true,\n });\n this._setNavState(this.state.compState);\n return\n }\n\n if (typeof this.refs.activeComponent.isUpdated == 'undefined' || this.refs.activeComponent.isUpdated() ) {\n if (evt.currentTarget.value === (this.props.steps.length - 1) &&\n this.state.compState === (this.props.steps.length - 1)) {\n this._setNavState(this.props.steps.length);\n }\n else {\n this._setNavState(evt.currentTarget.value);\n }\n }else if(!this.props.dontValidate && !isupdated){\n this.setState({\n modalOpen: true,\n });\n this._setNavState(this.state.compState);\n return\n }\n }\n\n }\n }", "updateForm() {\n this.$step.innerText = this.currentStep;\n\n // TODO: Validation\n\n this.slides.forEach(slide => {\n slide.classList.remove(\"active\");\n\n if (slide.dataset.step == this.currentStep) {\n slide.classList.add(\"active\");\n }\n });\n\n this.$stepInstructions[0].parentElement.parentElement.hidden = this.currentStep >= 6;\n this.$step.parentElement.hidden = this.currentStep >= 6;\n document.getElementById('form-donate').scrollIntoView();\n }", "function updateFocus() {\n\t// Draw the orders: a line and a label (show when there is room)\t\n\tfocusOrders();\n\t\n\t// Draw the families: a rect, a line, and a label (show when there is room)\n\tfocusFamilies();\n\t\n\t// Draw rectangles for each visible species in the focus view\n\tfocusSpecies();\n\t\n\n\t\t\n\t\t\n}", "scroll()\n\t{\n\t\t// If the form hasn't been unmounted yet\n\t\tif (this.refs.field)\n\t\t{\n\t\t\tconst element = ReactDOM.findDOMNode(this.refs.field)\n\n\t\t\t// https://developer.mozilla.org/ru/docs/Web/API/Element/scrollIntoViewIfNeeded\n\t\t\tif (element.scrollIntoViewIfNeeded)\n\t\t\t{\n\t\t\t\telement.scrollIntoViewIfNeeded(false)\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tscrollIntoViewIfNeeded(element, false, { duration: 800 })\n\t\t\t}\n\t\t}\n\t}", "@bind\n position() {\n if (this.for && this.show) {\n const options = {}; // FIXME: move this to a computed prop\n if (this.my) {\n options.my = this.my\n }\n if (this.at) {\n options.at = this.at;\n }\n domPosition(this, this.for, options);\n }\n }", "focus () {\n\t\tthis.manager.focusLayer(this);\n\t}", "function setupFocus() {\n focusPosX = width / 2;\n focusPosY = height / 2 + height / 8;\n focusWidth = width / 4;\n focusHeight = height / 12;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
walks a hash and hides all nonmatching languages
function ls_hideAllExcept(lang_element_hash, language) { for (var n in lang_element_hash) { if (n == language) { lang_element_hash[n].style.display = ''; } else { lang_element_hash[n].style.display = 'none'; } } }
[ "function actionDropUnused() {\n const enKeys = [];\n\n const gatherKeys = (value, parentKey = '') => {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return;\n }\n const keys = Object.keys(value);\n keys.forEach(k => {\n const path = `${parentKey ? `${parentKey}.` : ''}${k}`;\n enKeys.push(path);\n gatherKeys(value[k], path);\n });\n };\n\n const dropUnusedKeys = (value, language, parentKey = '') => {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return;\n }\n const keys = Object.keys(value);\n keys.forEach(k => {\n const path = `${parentKey ? `${parentKey}.` : ''}${k}`;\n if (enKeys.indexOf(path) === -1) {\n console.log(`Drop ${language}.${path}`);\n delete value[k];\n return;\n }\n dropUnusedKeys(value[k], language, path);\n });\n };\n\n // Gather all possible translations in the en locale.\n walk(data => {\n const translations = data.en;\n if (!translations) {\n return;\n }\n gatherKeys(translations);\n });\n\n // Remove translations not in the en locale.\n walk(data => {\n const languages = Object.keys(data).filter(l => l !== 'en');\n languages.forEach(language => {\n const translations = data[language];\n dropUnusedKeys(translations, language);\n });\n return data;\n });\n}", "function hideLanguages() {\n $('.leaflet-control-lang a.lang').each(function() {\n $(this).hide();\n });\n}", "function generateHiddenDictionary(dictionary) {\n let hidden = [];\n for (let word of dictionary) {\n hidden.push(hideWord(word));\n }\n return hidden;\n}", "function getIgnoreKeywords_allWords_nonEnglishWords() {\n\t\treturn [\n\t\t];\n\t}", "function removeKeyFromLevels(k) {\n\tlet lvls = Object.keys(levelDictionaries['custom']);\n\tfor(lvl of lvls) {\n\t\tlet keyCode = k.id.toString().replace('custom','');\n\t\t//console.log(levelDictionaries.custom.lvl[keyCode]);\n\t\t// replace any instances of letter previously found on key\n\t\tlevelDictionaries['custom'][lvl] = levelDictionaries['custom'][lvl].replace(k.children[0].innerHTML, '');\n\t\t// replace mapping for letter previously found on key\n\t\tlayoutMaps['custom'][keyCode] = \" \";\n\t}\n}", "function unloadLang(key) {\n delete languages[key];\n }", "wordsNotLemmatized() {\n return this._tokens.filter(o => o.tokentype == \"RUS\" && o.form_ids.length == 0).map(o => o.token)\n }", "function unloadLang(key) {\n delete languages[key];\n }", "function unloadLang(key) {\r\n delete languages[key];\r\n }", "function unloadLang(key) {\n delete languages[key];\n }", "function checkForMissingTranslations()\n{ \n var en_translations = langs['en-us']; // dont' change\n \n for (var lang_to_check in langs)\n {\n Debug.info(\"checking \" + lang_to_check);\n for (var en_str_to_check in en_translations)\n {\n //Logger.log(\"checking: \" + en_str_to_check);\n if (!(en_str_to_check in langs[lang_to_check]))\n {\n Debug.info(lang_to_check + \" is missing: \" + en_str_to_check);\n }\n }\n }\n}", "function getIgnoreKeywords_allWords_V_Words() {\n\t\treturn [\n\t\t\t'variably',\n\t\t\t'various',\n\t\t\t'verily',\n\t\t\t'very',\n\t\t\t'view',\t\n\t\t\t'views',\n\t\t\t'virtually',\n\t\t\t'viz',\n\t\t];\n\t}", "function getLanguages(i) {\n let l = Object.keys(i[0])\n l.splice(l.indexOf('key'), 1) // Remove the Key column\n return l\n}", "function getAllNonEnglishTitles() {\nreturn data.filter(movie => movie.language !== 'English');\n}", "function getLanguages(){\n return[{key:\"af\",value:\"Afrikaans\"},{key:\"az\",value:\"Azerbaijani\"},{key:\"id\",value:\"Indonesian\"},{key:\"ms\",value:\"Malay\"},{key:\"bs\",value:\"Bosnian\"},{key:\"ca\",value:\"Catalan\"},{key:\"cs\",value:\"Czech\"},{key:\"da\",value:\"Danish\"},{key:\"de\",value:\"German\"},{key:\"et\",value:\"Estonian\"},{key:\"en-GB\",value:\"English (United Kingdom)\"},{key:\"en\",value:\"English\"},{key:\"es\",value:\"Spanish (Spain)\"},{key:\"es-419\",value:\"Spanish (Latin America)\"},{key:\"es-US\",value:\"Spanish (United States)\"},{key:\"eu\",value:\"Basque\"},{key:\"fil\",value:\"Filipino\"},{key:\"fr\",value:\"French\"},{key:\"fr-CA\",value:\"French (Canada)\"},{key:\"gl\",value:\"Galician\"},{key:\"hr\",value:\"Croatian\"},{key:\"zu\",value:\"Zulu\"},{key:\"is\",value:\"Icelandic\"},{key:\"it\",value:\"Italian\"},{key:\"sw\",value:\"Swahili\"},{key:\"lv\",value:\"Latvian\"},{key:\"lt\",value:\"Lithuanian\"},{key:\"hu\",value:\"Hungarian\"},{key:\"nl\",value:\"Dutch\"},{key:\"no\",value:\"Norwegian\"},{key:\"uz\",value:\"Uzbek\"},{key:\"pl\",value:\"Polish\"},{key:\"pt-PT\",value:\"Portuguese (Portugal)\"},{key:\"pt\",value:\"Portuguese (Brazil)\"},{key:\"ro\",value:\"Romanian\"},{key:\"sq\",value:\"Albanian\"},{key:\"sk\",value:\"Slovak\"},{key:\"sl\",value:\"Slovenian\"},{key:\"sr-Latn\",value:\"Serbian (Latin)\"},{key:\"fi\",value:\"Finnish\"},{key:\"sv\",value:\"Swedish\"},{key:\"vi\",value:\"Vietnamese\"},{key:\"tr\",value:\"Turkish\"},{key:\"be\",value:\"Belarusian\"},{key:\"bg\",value:\"Bulgarian\"},{key:\"ky\",value:\"Kyrgyz\"},{key:\"kk\",value:\"Kazakh\"},{key:\"mk\",value:\"Macedonian\"},{key:\"mn\",value:\"Mongolian\"},{key:\"ru\",value:\"Russian\"},{key:\"sr\",value:\"Serbian\"},{key:\"uk\",value:\"Ukrainian\"},{key:\"el\",value:\"Greek\"},{key:\"hy\",value:\"Armenian\"},{key:\"iw\",value:\"Hebrew\"},{key:\"ur\",value:\"Urdu\"},{key:\"ar\",value:\"Arabic\"},{key:\"fa\",value:\"Persian\"},{key:\"ne\",value:\"Nepali\"},{key:\"mr\",value:\"Marathi\"},{key:\"hi\",value:\"Hindi\"},{key:\"bn\",value:\"Bangla\"},{key:\"pa\",value:\"Punjabi\"},{key:\"gu\",value:\"Gujarati\"},{key:\"ta\",value:\"Tamil\"},{key:\"te\",value:\"Telugu\"},{key:\"kn\",value:\"Kannada\"},{key:\"ml\",value:\"Malayalam\"},{key:\"si\",value:\"Sinhala\"},{key:\"th\",value:\"Thai\"},{key:\"lo\",value:\"Lao\"},{key:\"my\",value:\"Myanmar (Burmese)\"},{key:\"ka\",value:\"Georgian\"},{key:\"am\",value:\"Amharic\"},{key:\"km\",value:\"Khmer\"},{key:\"zh-CN\",value:\"Chinese\"},{key:\"zh-TW\",value:\"Chinese (Taiwan)\"},{key:\"zh-HK\",value:\"Chinese (Hong Kong)\"},{key:\"ja\",value:\"Japanese\"},{key:\"ko\",value:\"Korean\"}]\n}", "function invertHash(hash, optionalFilterFn){\r\n\t\treturn $.each(hash, function(key,val){\r\n\t\t\tif( val !== undefined && ( !optionalFilterFn || optionalFilterFn(val,key) ) ){\r\n\t\t\t\thash[val] = key;\r\n\t\t\t}\r\n\t\t})\r\n\t}", "function GetPickedCodesInAllLanguages(){\n var codes = GetPickedCodes();\n var all_codes = {};\n $.each(languages_in_corpus,function(idx,lang){\n all_codes[lang] = [];\n });\n $.each(codes,function(idx,code){\n $.each(languages_in_corpus,function(idx,lang){\n var pat = new RegExp(\"(_?)\" + picked_lang + \"$\",\"g\");\n all_codes[lang].push(code.replace(pat,\"$1\" + lang));\n });\n });\n return all_codes;\n }", "function getSkipWords() {\n\t\tif($('.ignore-common-words').is(':checked')) {\n\t\t\treturn getIgnoreKeywordsHash();\n\t\t}\n\t\t\n\t\treturn {};\n\t}", "get uniqueHiddenLettersInPhrase() {\n const letterElements = document.getElementsByClassName('letter');\n let uniqueHiddenLetters = '';\n\n for (let letterElement of letterElements) {\n if (uniqueHiddenLetters.indexOf(letterElement.textContent) === -1 && letterElement.classList.contains('hide')) {\n uniqueHiddenLetters += letterElement.textContent;\n }\n }\n return uniqueHiddenLetters;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of Authorizer. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Authorizer.__pulumiType; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AggregateAuthorization.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === WebAclAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CertificateAuthority.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RolePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PermissionSetInlinePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === BucketPolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CertificateAuthorityCertificate.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrincipalAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Association.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RestApiPolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ResourcePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Policy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PermissionSet.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DelegatedAdministrator.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === TopicPolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Role.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Permission.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkAcl.__pulumiType;\n }", "function isAuthProvider(object) {\n return object.getUser !== undefined;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple twocup switches (arr). Ronny can record the switches but can't work out where the ball is. Write a programme to help him do this. Rules: There will only ever be three cups. Only two cups will be swapped at a time. The cups and their switches will be refered to by their index in a row of three, beginning at one. So [[1,2]] means the cup at position one, is swapped with the cup at position two. Arr will be an array of integers 1 3 organised in pairs. There won't be any empty subarrays. If arr is just an empty array b should be returned. Examples: (b) = 2, (arr) = [[1,2]] The ball is under cup number : 1 (b) = 1, (arr) = [[2,3],[1,2],[1,2]] The ball is under cup number : 1 (b) = 2, (arr) = [[1,3],[1,2],[2,1],[2,3]] The ball is under cup number : 3
function cupAndBalls(b, arr){ let cupWithBall = b; for (let i = 0; i < arr.length; i++){ if (arr[i][0] === cupWithBall){ cupWithBall = arr[i][1]; }else if (arr[i][1] === cupWithBall){ cupWithBall = arr[i][0]; } } return cupWithBall; }
[ "function cupSwapping(arr) {\r\n let ballPosition = 'B';\r\n for (swap of arr) {\r\n if (swap.includes(ballPosition)) {\r\n ballPosition = swap.replace(ballPosition, '');\r\n }\r\n }\r\n return ballPosition;\r\n}", "function getSiteswapFromTossArray(tossArr,showHand) {\r\n\r\n\tfunction getSiteswapFromToss(toss) {\r\n\t\tvar s = toss.numBeats;\r\n\t\tif ((toss.numBeats % 2 == 1 && !toss.crossing) || (toss.numBeats % 2 == 0 && toss.crossing))\r\n\t\t\ts += 'x';\r\n\t\treturn s;\r\n\t}\r\n\r\n\tvar siteswap = \"\";\r\n\r\n\t/* each beat in toss array creates a new siteswap */\r\n\tfor (var beat = 0; beat < tossArr.length; beat++) {\r\n\t\t\r\n\t\tvar leftSiteswap = \"\";\r\n\t\tvar rightSiteswap = \"\";\r\n\t\tvar leftCt = 0;\r\n\t\tvar rightCt = 0;\r\n\t\tfor (var toss = 0; toss < tossArr[beat].length; toss++) {\r\n\t\t\tvar s = getSiteswapFromToss(tossArr[beat][toss]);\r\n\t\t\tvar hand = tossArr[beat][toss].hand != undefined ? tossArr[beat][toss].hand : beat % 2;\r\n\t\t\tif (hand == LEFT) {\r\n\t\t\t\tleftSiteswap += s;\r\n\t\t\t\tleftCt++;\r\n\t\t\t} else {\r\n\t\t\t\trightSiteswap += s;\r\n\t\t\t\trightCt++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (leftCt > 1) {\r\n\t\t\tleftSiteswap = \"[\" + leftSiteswap + \"]\";\r\n\t\t}\r\n\t\tif (rightCt > 1) {\r\n\t\t\trightSiteswap = \"[\" + rightSiteswap + \"]\";\r\n\t\t}\r\n\r\n\t\tif (leftCt > 0 && rightCt > 0) {\r\n\t\t\tsiteswap += (\"(\" + leftSiteswap + \",\" + rightSiteswap + \")\");\r\n\t\t} \r\n\t\telse if (leftCt > 0) {\r\n\t\t\tif (showHand) {\r\n\t\t\t\tleftSiteswap = \"L\" + leftSiteswap;\r\n\t\t\t}\r\n\t\t\tsiteswap += leftSiteswap;\r\n\t\t}\r\n\t\telse if (rightCt > 0) {\r\n\t\t\tif (showHand) {\r\n\t\t\t\trightSiteswap = \"R\" + rightSiteswap;\r\n\t\t\t}\r\n\t\t\tsiteswap += rightSiteswap;\r\n\t\t} \r\n\t\telse {\r\n\t\t\tsiteswap += \"0\";\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn siteswap;\r\n\r\n}", "function bustHiddenSingles(arr) {\n let def = [];\n for (let y = 0; y < arr.length; y++) { // Moving between items and searching arrays.\n for (let x = 0; x < arr[y].length; x++) {\n if (typeof arr[y][x] === \"object\") { \n def = arr[y][x];\n for (let m = 0; m < arr[y].length; m++) { // Searching other arrays on x and delete difference.\n if (typeof arr[y][m] === \"object\" && x !== m) {\n def = def.filter(function(el) { return !arr[y][m].includes(el); });\n }\n }\n if (def.length === 1){ // If difference heave only one item this item its hidden single.\n arr[y][x] = def[0];\n return bustOpenPairs(arr);\n }\n }\n }\n }\n def = [];\n for (let y = 0; y < arr.length; y++) { // Moving between items and searching arrays.\n for (let x = 0; x < arr[y].length; x++) { \n if (typeof arr[y][x] === \"object\"){ \n def = arr[y][x];\n for (let m = 0; m < arr[x].length; m++) { // Searching other arrays on y and delete difference.\n if (typeof arr[m][x] === \"object\" && y !== m) {\n def = def.filter(function(el) { return !arr[m][x].includes(el); });\n }\n }\n if (def.length === 1){ // If difference heave only one item this item its hidden single.\n arr[y][x] = def[0];\n return bustOpenPairs(arr);\n }\n }\n }\n }\n def = [];\n for (let y = 0; y < arr.length; y++) { // Moving between items and searching arrays.\n for (let x = 0; x < arr[y].length; x++) {\n if (typeof arr[y][x] === \"object\"){ \n def = arr[y][x];\n if (x < 3 && y < 3) { // Searching other arrays on squares and delete difference.\n for (let k = 0; k < 3; k++) {\n next:\n for (let m = 0; m < 3; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n }\n }\n if (x >= 3 && x < 6 && y < 3) {\n for (let k = 0 ; k < 3; k++) {\n next:\n for (let m = 3; m < 6; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n }\n }\n if (x >= 6 && y < 3) {\n for (let k = 0 ; k < 3; k++) {\n next:\n for (let m = 6; m < 9; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); }); \n } \n } \n }\n if (x < 3 && y >= 3 && y < 6) {\n for (let k = 3; k < 6; k++) {\n next:\n for (let m = 0; m < 3; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n } \n }\n if (x >= 3 && x < 6 && y >= 3 && y < 6) {\n for (let k = 3; k < 6; k++) {\n next:\n for (let m = 3; m < 6; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); }); \n } \n }\n }\n if (x >= 6 && y >= 3 && y < 6) {\n for (let k = 3; k < 6; k++) {\n next:\n for (let m = 6; m < 9; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); }); \n } \n } \n }\n if (x < 3 && y >= 6) {\n for (let k = 6; k < 9; k++) {\n next:\n for (let m = 0; m < 3; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n } \n }\n if (x >=3 && x < 6 && y >= 6) {\n for (let k = 6; k < 9; k++) {\n next:\n for (let m = 3; m < 6; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n } \n }\n if (x >= 6 && y >= 6) {\n for (let k = 6; k < 9; k++) {\n next:\n for (let m = 6; m < 9; m++) {\n if (typeof arr[k][m] !== \"object\" || typeof arr[k][m] === \"object\" && k === y && m === x) {\n continue next;\n }\n def = def.filter(function(el) { return !arr[k][m].includes(el); });\n } \n } \n }\n if (def.length === 1){ // If difference heave only one item this item its hidden single.\n arr[y][x] = def[0];\n return bustOpenPairs(arr); \n } \n } \n }\n }\n return bustOpenPairs(arr); // Recursion.\n }", "function flagSort(arr) {\n if (!arr || arr.length <= 1) {\n return arr;\n }\n\n let totalBlues = _numOf(arr, 'b'); // O(n)\n let firstWhiteIdx = totalBlues / 2;\n let lastWhiteIdx = arr.length - 1 - firstWhiteIdx;\n let leftSwapIdx = 0;\n let rightSwapIdx = arr.length - 2;\n let blueCount = 0;\n\n for (let i = firstWhiteIdx; i < lastWhiteIdx; i++) {\n if (arr[i] === 'b') {\n blueCount++;\n\n if (!blueCount % 2) {\n _swap(arr, i, leftSwapIdx);\n leftSwapIdx++;\n } else {\n _swap(arr, i, rightSwapIdx);\n rightSwapIdx--;\n }\n }\n if (arr[i] === 's') {\n _swap(arr, i, arr.length - 1);\n }\n }\n\n let mid = Math.floor(arr.length / 2);\n _swap(arr, lastWhiteIdx, arr.length - 1);\n _swap(arr, mid, lastWhiteIdx);\n\n return arr;\n}", "function getbumps(arrin) {\n /* find elements with bump on*/\n var arr = arrin.filter(bump);\n /* sort by row and xpos for not mixin up the different rows*/\n arr.sort(function (a, b) {\n return a.row * 2 * game.width + a.xpos - (b.row * 2 * game.width + b.xpos);\n });\n\n /*loop through bumpable elements*/\n for (var i = 0; i < arr.length; i++) {\n var eni = arr[i];\n /* has elment hit a rock?*/\n var arrb = allItems.filter(blocked, eni);\n if (arrb.length > 0) {\n /* relocate element outside rock an turn direction*/\n if (eni.direction > 0) {\n eni.xpos = arrb[0].xpos - (eni.rightb - eni.leftb) - (eni.rightb - arrb[0].leftb);\n } else {\n eni.xpos = arrb[0].rightb + (arrb[0].rightb - eni.leftb);\n }\n eni.direction = eni.direction * -1;\n }\n\n\n if (i === arr.length - 1) break;\n var enj = arr[i + 1];\n /* has element overlaying bound with \"right\" neighbour?*/\n if (enj.row === eni.row && eni.leftb < enj.leftb && eni.rightb > enj.leftb) {\n /* same or different direction for turn on not*/\n if (eni.direction != enj.direction) {\n eni.direction = eni.direction * -1;\n enj.direction = enj.direction * -1;\n }\n /* exchange elements speed and relocate \"right\" neighbour outside element*/\n var tempspeed = eni.speed;\n eni.speed = enj.speed;\n enj.speed = tempspeed;\n enj.xpos = eni.rightb + (eni.rightb - enj.leftb);\n }\n }\n }", "function swapNibbles(arr) \n {\n\t\t// swap nibbles at first and last of the array\n\t\t// j is used for saving last 4 index of the array\n\t\tvar temp, j = arr.length - 4;\n\t\tfor (var i = 0; i < 4; i++) { // loop runs 4 times and swap first four element to last four elements\n\t\t\ttemp = arr[i];\n\t\t\tarr[i] = arr[j];\n\t\t\tarr[j] = temp;\n\t\t\tj++;\n\t\t}\n\t\treturn arr;\n\t}", "function possibleMovesBishop(i, j, c){\n var possibleMoves =[];\n for(var k=1; k<BOARD_SIZE-i && k<BOARD_SIZE-j; k++){\n \n if(board[i+k][j+k]=='b'){\n possibleMoves.push([i+k,j+k]);\n continue;\n }\n else if(board[i+k][j+k].charAt(0)==c){\n break;\n }\n else if(board[i+k][j+k].charAt(0)!=c){\n possibleMoves.push([i+k,j+k]);\n break;\n }\n }\n for(var k=1; i-k>=0 && j-k>=0; k++){\n \n if(board[i-k][j-k]=='b'){\n possibleMoves.push([i-k,j-k]);\n continue;\n }\n else if(board[i-k][j-k].charAt(0)==c){\n break;\n }\n else if(board[i-k][j-k].charAt(0)!=c){\n possibleMoves.push([i-k,j-k]);\n break;\n }\n }\n for(var k=1; i-k>=0 && k<BOARD_SIZE-j; k++){\n \n if(board[i-k][j+k]=='b'){\n possibleMoves.push([i-k,j+k]);\n continue;\n }\n else if(board[i-k][j+k].charAt(0)==c){\n break;\n }\n else if(board[i-k][j+k].charAt(0)!=c){\n possibleMoves.push([i-k,j+k]);\n break;\n }\n }\n for(var k=1; k<BOARD_SIZE-i && j-k>=0; k++){\n \n if(board[i+k][j-k]=='b'){\n possibleMoves.push([i+k,j-k]);\n continue;\n }\n else if(board[i+k][j-k].charAt(0)==c){\n break;\n }\n else if(board[i+k][j-k].charAt(0)!=c){\n possibleMoves.push([i+k,j-k]);\n break;\n }\n }\n \n return possibleMoves;\n}", "function boardToubler(pI)\n{\n\tvar rAA = new Array();\n\tvar track= new Array();\n\tvar ranP=null;\n\tvar tempP = null;\n\tvar tempR=null;\n\n\t\n\n//\talert(\"return\"+pI);\n\tvar pAA = null;\n\tpAA = new Array();\n\n\tdocument.getElementById(\"imagesp\").innerHTML=\"\";\n\tvar i =0;\n\tfor (i=0;i<9;i++)\n\t{\n//\tfor (i=0;i<pI.length;i++){\n// $(\"<img/>\").attr(\"src\", pAA[i].media.m).attr(\"title\",pAA[i].title).appendTo(\"#imagesp\");\n//\tif (i == 4)\n\t var iiD=$(\"<br style=\\\"clear:both;\\\"/>\");\n//\tif (i==0)\n//\t\tvar iD=\"<div class=\\\"quickflip-wrapper3 qw\"+i+\"\\\" style=\\\"float:left;display:inline;\\\">\";\n//\telse\n\t\tvar iD=\"<div class=\\\"flipbox-container qw\"+i+\"\\\" style=\\\"float:left;display:inline;\\\">\";\n\n\n//\t\tvar iD=\"<div class=\\\"quickflip-wrapper3\\\" >\";\n//\tiD=iD+\"<div ><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" width=\\\"50px\\\" height=\\\"50px\\\"/></a></div>\";\n//flipbox\tiD=iD+\"<div class=\\\"di2\\\"><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" /></a></div>\";\n//\tiD=iD+\"<div class=\\\"flipbox di2\\\"><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" /></a></div>\";\n//\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"FlipCta\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\n//\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"\"+pAA[i].media.m+\"\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\n\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"images/Yoursky.gif\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\n\n//\tiD=iD+\"<div ><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"> <img src=\\\"images/ss036.gif\\\" /></a> </div>\";\n\tiD=iD+\"</div>\";\n\tiD=$(iD);\n\tif(i==4){\n//\tif(i%5==0){\n//\talert (\"id:\"+iD.attr(\"class\"));\t\n\tvar ele= $(iD.children()[0]).children().children();\n//\talert (\"id:\"+ ele[1].nodeName);\t\n//good\talert (\"id:\"+ $(ele[1]).attr(\"class\"));\t\n//\tiD=$(\"<br style=\\\"clear:both;\\\"/>\");\n\talert (\"id:\"+ $(ele[0]).attr(\"src\"));\t\n//\talert (\"id:\"+iD.children().attr(\"class\"));\t\n//\talert (\"id:\"+iD.children().length);\t\n\t}\n\n//\talert (\"id:\"+iD);\t\n//---------replace img iE with string iD\n\n// var iE=$(\"<img/>\").attr(\"src\", pAA[i].media.m).attr(\"title\",pAA[i].title);\n\n\n//\t}\n\t\t// iE.wrap(\"<a href=' \"+iE.attr(\"src\")+\"' </a>\");\n//\t\t iE.wrap(\"<a href=\\\"\"+iE.attr(\"src\")+\"\\\"> </a>\");\n//\t\t iE.wrap(\"<p></p>\");\n\n//__switch\t\t iE=iE.wrap($(\"<div id=\\\"headp\\\"> </div>\"));\n//\t\t iE=iE.wrap($(\"<div id=\\\"hea\\\"> </div>\"));\n\n//\t\t\tiE.wrap(\"<p></p>\");\t\t \n\t\t\t\t\t\t\t//change to img\n//\t\t iE=iE.wrap($(\"<a href=\\\" \"+iE.attr(\"src\")+\"\\\" />\"));\n\n//not used\t\t iE.bind(\"click\",{pId:iE.attr(\"src\")},clickPic);\n\n\n//++++++++++++++++++was used for iE\n//\t\t iE.bind(\"click\",{pId:iE},clickPic);\n//\t\t\tiE=iE.wrap\n\n\n\n//insetead of-- iE.wrap(\"<a href=\\\"\"+iE.attr(\"src\")+\"\\\" />\");\n//\t\t\tiE.wrap(\"<div id=\\\"head\\\"></div>\");\n\n//comment out green on top\n//\t\t\tiE.after($(\"<div id=\\\"tailp\\\"></div>\"))\n\n//\t\t iE.bind(\"click\",{pId:\"src\"},checkPic);\n//\t\t iD.bind(\"quickflip\",{pId:\"src\"},checkPic);\n//______________compete click________________\n//\t\t iD.bind(\"click\",{pId:iD)},checkPic);\n//--switch to div\t\tiE.parent().appendTo(\"#imagesp\");\n//\t\t\t($(\"<div id=\\\"tailp\\\"></div>\")).appendTo('#imagesp\");\n\n//++++++++++++++replace with iD\n//\t\tiE.appendTo(\"#imagesp\");\n//\t\tdocument.getElementById(\"imagesp\").append(iD);\n//\t\t$(\"#imagesp\").append(iD);\n//\t\t$(\"#imdiv\").append(iD);\n\n//______________compete click________________\n//try to remove click flip\t\tiD.quickFlip();\n//\t\tiD.quickFlipper({panelWidth:60,panelHeight:60});\n//\t\tiD.quickFlipper();\n//\t\tiD.quickFlipper();\n//\t\t iD.bind(\"quickFlip\",{pId:\"src\"},checkPic);\n//working\t\t iD.bind(\"click\",{pId:iD},clickPic);\n\t\t iD.bind(\"click\",{pId:iD},clickPic);\n\n\t\tif (i%4==0 && i!=0){\t\t//break lines but not the first\n\n\t\t\tiiD.appendTo(\"#imagesp\");\n\t\t}\n\n\t\tiD.appendTo(\"#imagesp\");\n//\t\t$(\"<div id=\\\"headp\\\"></div>\").append(iE.parent()).appendTo(\"#imagesp\");\n//\t\t$(\"<div id=\\\"headp\\\"></div>\").appendTo(\"#imagesp\");\n//\t\t$(\"<div id=\\\"tailp\\\"></div>\").appendTo(\"#imagesp\");\n\t\t// iE.trigger(\"click\",checkPic,{pId:iE.attr(\"src\")});\n//\t$('.'+iD.attr(\"src\")).quickFlip();\n\n}\n//).done(\n//function(){$('.quickflip-wrapper3').quickFlipper();}\n//);\n\n\n/*\n$(\"#imagesp> img\").each(function(i,item){\n\t$(this).wrap(\"<a href=\\\" \"+ $(this).attr(\"src\") +\"\\\" </a>\");\n\n});\n*/\n//$('.quickflip-wrapper3').quickFlipper();\n\n}", "function tossCoins() {\n // Initialize our coin array\n let coinFlip = [];\n // Keep track of how many tosses made.\n count++;\n if(count <= 6) {\n // Randomly generate a true or false 3 times\n for(i = 0; i < 3; i++) {\n //Math.random() < 0.5 returns a boolean true or false 50% chances witch is nice.\n coinFlip.push((Math.random() < 0.5));\n }\n // Now we have an array of booleans ex. [true, false, false ]\n console.log(coinFlip);\n\n // Convert the booleans to either 2 (Tails yin) or 3 (Heads yang)\n for(i = 0; i < 3; i++){\n if(coinFlip[i]) {\n coinFlip[i] = 2;\n } else {\n coinFlip[i] = 3;\n }\n }\n\n // Duplicating array so we can work on it seperatly, apparently arrays get passed by referrence\n // so we were running into trouble here, it was being altered to strings and not numbers like what we want for our next\n // function\n let coinValues = coinFlip.slice(0);\n drawCoins(coinFlip);\n\n drawHexagram(coinValues);\n } else {\n console.log(\"Completed a full hexagram. Shake again to start over.\");\n count = 0;\n }\n}", "function boardToubler(pI)\r\n{\r\n\tvar rAA = new Array();\r\n\tvar track= new Array();\r\n\tvar ranP=null;\r\n\tvar tempP = null;\r\n\tvar tempR=null;\r\n\r\n\t\r\n\r\n//\talert(\"return\"+pI);\r\n\tvar pAA = null;\r\n\tpAA = new Array();\r\n\r\n\tdocument.getElementById(\"imagesp\").innerHTML=\"\";\r\n\tvar i =0;\r\n\tfor (i=0;i<9;i++)\r\n\t{\r\n//\tfor (i=0;i<pI.length;i++){\r\n// $(\"<img/>\").attr(\"src\", pAA[i].media.m).attr(\"title\",pAA[i].title).appendTo(\"#imagesp\");\r\n//\tif (i == 4)\r\n\t var iiD=$(\"<br style=\\\"clear:both;\\\"/>\");\r\n//\tif (i==0)\r\n//\t\tvar iD=\"<div class=\\\"quickflip-wrapper3 qw\"+i+\"\\\" style=\\\"float:left;display:inline;\\\">\";\r\n//\telse\r\n\t\tvar iD=\"<div class=\\\"flipbox-container qw\"+i+\"\\\" style=\\\"float:left;display:inline;\\\">\";\r\n\r\n\r\n//\t\tvar iD=\"<div class=\\\"quickflip-wrapper3\\\" >\";\r\n//\tiD=iD+\"<div ><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" width=\\\"50px\\\" height=\\\"50px\\\"/></a></div>\";\r\n//flipbox\tiD=iD+\"<div class=\\\"di2\\\"><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" /></a></div>\";\r\n//\tiD=iD+\"<div class=\\\"flipbox di2\\\"><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"><img src=\\\"\"+pAA[i].media.m+\"\\\" title=\\\"\"+pAA[i].title+\"\\\" /></a></div>\";\r\n//\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"FlipCta\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\r\n//\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"\"+pAA[i].media.m+\"\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\r\n\tiD=iD+\"<div class=\\\"flipbox di1\\\"><a href=\\\"#\\\" id=\\\"images/Yoursky.gif\\\"> <img src=\\\"images/Yoursky.gif\\\" /></a> </div>\";\r\n\r\n//\tiD=iD+\"<div ><a href=\\\"#\\\" class=\\\"quickFlipCta\\\"> <img src=\\\"images/ss036.gif\\\" /></a> </div>\";\r\n\tiD=iD+\"</div>\";\r\n\tiD=$(iD);\r\n\tif(i==4){\r\n//\tif(i%5==0){\r\n//\talert (\"id:\"+iD.attr(\"class\"));\t\r\n\tvar ele= $(iD.children()[0]).children().children();\r\n//\talert (\"id:\"+ ele[1].nodeName);\t\r\n//good\talert (\"id:\"+ $(ele[1]).attr(\"class\"));\t\r\n//\tiD=$(\"<br style=\\\"clear:both;\\\"/>\");\r\n\talert (\"id:\"+ $(ele[0]).attr(\"src\"));\t\r\n//\talert (\"id:\"+iD.children().attr(\"class\"));\t\r\n//\talert (\"id:\"+iD.children().length);\t\r\n\t}\r\n\r\n//\talert (\"id:\"+iD);\t\r\n//---------replace img iE with string iD\r\n\r\n// var iE=$(\"<img/>\").attr(\"src\", pAA[i].media.m).attr(\"title\",pAA[i].title);\r\n\r\n\r\n//\t}\r\n\t\t// iE.wrap(\"<a href=' \"+iE.attr(\"src\")+\"' </a>\");\r\n//\t\t iE.wrap(\"<a href=\\\"\"+iE.attr(\"src\")+\"\\\"> </a>\");\r\n//\t\t iE.wrap(\"<p></p>\");\r\n\r\n//__switch\t\t iE=iE.wrap($(\"<div id=\\\"headp\\\"> </div>\"));\r\n//\t\t iE=iE.wrap($(\"<div id=\\\"hea\\\"> </div>\"));\r\n\r\n//\t\t\tiE.wrap(\"<p></p>\");\t\t \r\n\t\t\t\t\t\t\t//change to img\r\n//\t\t iE=iE.wrap($(\"<a href=\\\" \"+iE.attr(\"src\")+\"\\\" />\"));\r\n\r\n//not used\t\t iE.bind(\"click\",{pId:iE.attr(\"src\")},clickPic);\r\n\r\n\r\n//++++++++++++++++++was used for iE\r\n//\t\t iE.bind(\"click\",{pId:iE},clickPic);\r\n//\t\t\tiE=iE.wrap\r\n\r\n\r\n\r\n//insetead of-- iE.wrap(\"<a href=\\\"\"+iE.attr(\"src\")+\"\\\" />\");\r\n//\t\t\tiE.wrap(\"<div id=\\\"head\\\"></div>\");\r\n\r\n//comment out green on top\r\n//\t\t\tiE.after($(\"<div id=\\\"tailp\\\"></div>\"))\r\n\r\n//\t\t iE.bind(\"click\",{pId:\"src\"},checkPic);\r\n//\t\t iD.bind(\"quickflip\",{pId:\"src\"},checkPic);\r\n//______________compete click________________\r\n//\t\t iD.bind(\"click\",{pId:iD)},checkPic);\r\n//--switch to div\t\tiE.parent().appendTo(\"#imagesp\");\r\n//\t\t\t($(\"<div id=\\\"tailp\\\"></div>\")).appendTo('#imagesp\");\r\n\r\n//++++++++++++++replace with iD\r\n//\t\tiE.appendTo(\"#imagesp\");\r\n//\t\tdocument.getElementById(\"imagesp\").append(iD);\r\n//\t\t$(\"#imagesp\").append(iD);\r\n//\t\t$(\"#imdiv\").append(iD);\r\n\r\n//______________compete click________________\r\n//try to remove click flip\t\tiD.quickFlip();\r\n//\t\tiD.quickFlipper({panelWidth:60,panelHeight:60});\r\n//\t\tiD.quickFlipper();\r\n//\t\tiD.quickFlipper();\r\n//\t\t iD.bind(\"quickFlip\",{pId:\"src\"},checkPic);\r\n//working\t\t iD.bind(\"click\",{pId:iD},clickPic);\r\n\t\t iD.bind(\"click\",{pId:iD},clickPic);\r\n\r\n\t\tif (i%4==0 && i!=0){\t\t//break lines but not the first\r\n\r\n\t\t\tiiD.appendTo(\"#imagesp\");\r\n\t\t}\r\n\r\n\t\tiD.appendTo(\"#imagesp\");\r\n//\t\t$(\"<div id=\\\"headp\\\"></div>\").append(iE.parent()).appendTo(\"#imagesp\");\r\n//\t\t$(\"<div id=\\\"headp\\\"></div>\").appendTo(\"#imagesp\");\r\n//\t\t$(\"<div id=\\\"tailp\\\"></div>\").appendTo(\"#imagesp\");\r\n\t\t// iE.trigger(\"click\",checkPic,{pId:iE.attr(\"src\")});\r\n//\t$('.'+iD.attr(\"src\")).quickFlip();\r\n\r\n}\r\n//).done(\r\n//function(){$('.quickflip-wrapper3').quickFlipper();}\r\n//);\r\n\r\n\r\n/*\r\n$(\"#imagesp> img\").each(function(i,item){\r\n\t$(this).wrap(\"<a href=\\\" \"+ $(this).attr(\"src\") +\"\\\" </a>\");\r\n\r\n});\r\n*/\r\n//$('.quickflip-wrapper3').quickFlipper();\r\n\r\n}", "async function cocktailSort(arr, draw_arr) {\n const n = arr.length;\n let _c = 0;\n\n let swapped = false;\n do {\n swapped = false;\n for (let j = 0; j < n - 1; j++) {\n if (arr[j + 1] < arr[j]) {\n swap(arr, j + 1, j);\n swapped = true;\n\n await draw_arr(arr, 3, j + 1, j);\n }\n _c++;\n await draw_arr(arr, 2);\n }\n if (!swapped)\n break;\n for (let j = n - 1; j >= 0; j--) {\n if (arr[j + 1] < arr[j]) {\n swap(arr, j + 1, j);\n swapped = true;\n\n await draw_arr(arr, 3, j + 1, j);\n }\n _c++;\n await draw_arr(arr, 2);\n }\n await draw_arr(arr, 1);\n\n } while (swapped == true);\n\n console.log(`cocktail sort ${_c}`);\n return arr;\n}", "chooseFaceUp(a){\n console.log(this.hand[a[0]],this.hand[a[1]],this.hand[a[2]]);\n this.faceup.push(this.hand[a[0]]);\n this.faceup.push(this.hand[a[1]]);\n this.faceup.push(this.hand[a[2]]);\n a.sort(function(a,b){ // Sort the index to be in order\n return a-b;\n });\n this.hand.splice(a[2], 1);\n this.hand.splice(a[1], 1);\n this.hand.splice(a[0], 1);\n }", "generateClbPips(tile) {\n let a = [];\n let b = [];\n let c = [];\n let d = [];\n let k = [];\n let amux = undefined;\n let bmux = undefined;\n let cmux = undefined;\n let dmux = undefined;\n let kmux = undefined;\n const row = tile[0];\n const col = tile[1];\n\n // Inputs to A\n if (tile[0] == \"A\") {\n // Top\n a = [ \"row.A.long.2:col.=.clb:row.A.long.2:==.A\", \"row.A.local.1:col.=.clb:row.A.local.1:==.A\",\n \"row.A.local.2:col.=.clb:row.A.local.2:==.A\", \"row.A.local.3:col.=.clb:row.A.local.3:==.A\",\n \"row.A.local.4:col.=.clb:row.A.local.4:==.A\", \"row.A.long.3:col.=.clb:row.A.long.3:==.A\"]\n // Connection to pad. Hardcoding seems the easiest way.\n const pad = {A: 1, B: 3, C: 5, D: 7, E: 9, F: 11, G: 13, H: 15}[tile[1]];\n a.push( \"row.A.io2:col.=.clb::==.A:PAD\" + pad + \".I\");\n // Mux tree: 16-bit active 0, 8-bit active 0, 4-bit active 0, 2-bit active 1, 1-bit muxes between pairs.\n amux = {30: 0, 13: 1, 24: 2, 12: 3, 21: 4, 25: 5, 31: 6}[this.mux['A']];\n } else {\n // Not top\n a = [ \"row.=.local.1:==.A\", \"row.=.local.3:==.A\", \"row.=.local.4:==.A\", \"row.=.local.5:==.A\", \"row.=.long.1:==.A\",\n \"==.A:row.=.io4\"];\n // Mux tree: 4-bit active 1, 2-bit active 0, 1-bit active 0, 0-bit muxes between pair.\n amux = {3: 0, 15: 1, 4: 2, 2: 3, 14: 4, 5: 5}[this.mux['A']];\n }\n\n\n // Inputs to B\n if (tile[1] == \"A\") {\n // Left\n b = [ \"col.=.long.2:==.B\", \"col.=.local.1:==.B\", \"col.=.local.2:==.B\", \"col.=.local.3:==.B\", \"col.=.local.4:==.B\",\n \"col.=.long.3:==.B\", \"col.=.long.4:==.B\", \"col.=.clk:==.B:CLK.AA.O:==.B\"];\n // Pad connections\n const pad = {A: 58, B: 56, C: 54, D: 52, E: 51, F: 49, G: 47, H: 46}[tile[1]];\n b.push(\"col.=.io3:==.B:\" + \"PAD\" + pad + \".I:==.B\");\n if (tile == \"AA\") {\n // Special case for tile AA since there's no tile above.\n b.push(\"col.=.x:==.B:PAD1.I:==.B\");\n } else {\n b.push(\"col.=.x:==.B:-=.X:==.B\");\n }\n if (tile == \"AA\") {\n // Special case for top left :-(\n bmux = {15: 0, 22: 1, 26: 2, 28: 3, 63: 4, 23: 5, 27: 6, 29: 7, 14: 8, 62: 9}[this.mux['B']];\n } else {\n // Other left\n bmux = {22: 0, 15: 1, 28: 2, 63: 3, 23: 4, 26: 5, 27: 6, 29: 7, 14: 8, 62: 9}[this.mux['B']];\n }\n\n } else {\n // Not left\n\n b = [ \"col.=.local.1:==.B\", \"col.=.local.2:==.B\", \"col.=.local.3:==.B\", \"col.=.local.4:==.B\", \"col.=.local.5:==.B\",\n \"col.=.local.6:==.B:=-.X:==.A\",\n \"col.=.long.1:==.B\", \"col.=.long.2:==.B\", \n \"col.=.clk:==.B:CLK.AA.O:==.B\", \"col.=.x:==.B:-=.X:==.B\"];\n if (tile[0] == \"A\") {\n // Top row is special case (top left AA is earlier)\n bmux = {22: 0, 26: 1, 28: 2, 63: 3, 15: 4, 14: 5, 23: 6, 27: 7, 29: 8, 62: 9}[this.mux['B']];\n } else {\n // Mux tree: 32-bit active 1, 16-bit active 0, 8-bit active 0, 4-bit active 0, 2-bit active 0, 1-bit muxs between pairs.\n bmux = {15: 0, 28: 1, 63: 2, 23: 3, 22: 4, 14: 5, 26: 6, 27: 7, 29: 8, 62: 9}[this.mux['B']];\n }\n }\n\n // Inputs to C\n\n if (tile[1] == \"A\") {\n // Left\n c = [ \"col.=.long.2:==.C\", \"col.=.local.1:==.C\", \"col.=.local.2:==.C\", \"col.=.local.3:==.C\", \"col.=.local.4:==.C\",\n \"col.=.long.3:==.C\", \"col.=.long.4:==.C\"];\n if (tile == \"HA\") {\n // Special case for tile HA since there's no tile below\n c.push(\"col.=.x:==.C:PAD45.I:==.C\");\n } else {\n c.push(\"col.=.x:==.C:+=.X:==.C\");\n }\n if (tile == \"AA\") {\n // Special case for top left\n cmux = {6: 0, 7: 1, 11: 2, 13: 3, 30: 4, 10: 5, 12: 6, 31: 7}[this.mux[\"C\"]];\n } else {\n // Other left\n cmux = {7: 0, 12: 1, 13: 2, 30: 3, 6: 4, 11: 5, 10: 6, 31: 7}[this.mux[\"C\"]];\n }\n } else {\n c = [ \"col.=.local.1:==.C\", \"col.=.local.2:==.C\", \"col.=.local.3:==.C\", \"col.=.local.4:==.C\", \"col.=.local.5:==.C\",\n \"col.=.long.1:==.C\", \"col.=.long.2:==.C\", \"col.=.x:==.C:-=.X:==.C\"];\n if (tile[0] == \"A\") {\n // Top (except AA)\n cmux = {7: 0, 11: 1, 13: 2, 30: 3, 6: 4, 10: 5, 12: 6, 31: 7}[this.mux[\"C\"]];\n } else {\n cmux = {12: 0, 13: 1, 30: 2, 6: 3, 7: 4, 11: 5, 10: 6, 31: 7}[this.mux['C']];\n }\n }\n\n // Inputs to k\n if (tile[1] == \"A\") {\n // Left\n k = [ \"col.=.long.4:==.K\", \"col.=.clk:==.K:CLK.AA.O:==.K\"];\n } else {\n k = [ \"col.=.long.2:==.K\", \"col.=.clk:==.K:CLK.AA.O:==.K\"];\n }\n kmux = {2: 0, 1: 1, 3: undefined}[this.mux['K']]; // 3 is used for no-connection\n\n // Inputs to D\n d = [];\n if (tile[0] == \"H\") {\n // Bottom, has an extra input with different mux\n const pad = {A: 45, B: 43, C: 41, D: 39, E: 37, F: 35, G: 33, H: 31}[tile[1]];\n d = [ \"row.+.io2:==.D:==.D:PAD\" + pad + \".I\",\n \"row.+.long.1:==.D\", \"row.+.local.1:==.D\", \"row.+.local.2:==.D\", \"row.+.local.3:==.D\", \"row.+.local.4:==.D\", \"row.+.long.2:==.D\"];\n dmux = {31: 0, 25: 1, 21: 2, 12: 3, 24: 4, 13: 5, 30: 6}[this.mux['D']];\n } else {\n // Not bottom\n d = [ \"row.+.io3:==.D:==.D:+=.X\",\n \"row.+.local.1:==.D\", \"row.+.local.3:==.D\", \"row.+.local.4:==.D\", \"row.+.local.5:==.D\", \"row.+.long.1:==.D\"];\n dmux = {5: 0, 3: 1, 15: 2, 4: 3, 2: 4, 14: 5}[this.mux['D']];\n }\n this.apips = [];\n this.bpips = [];\n this.cpips = [];\n this.kpips = [];\n this.dpips = [];\n a.forEach(p => this.apips.push(ClbDecoder.processClbPip(p, tile, tile + \".A\")));\n b.forEach(p => this.bpips.push(ClbDecoder.processClbPip(p, tile, tile + \".B\")));\n c.forEach(p => this.cpips.push(ClbDecoder.processClbPip(p, tile, tile + \".C\")));\n k.forEach(p => this.kpips.push(ClbDecoder.processClbPip(p, tile, tile + \".K\")));\n d.forEach(p => this.dpips.push(ClbDecoder.processClbPip(p, tile, tile + \".D\")));\n if (amux != undefined && amux != null) {\n this.apips[amux][4] = true; // Select the appropriate pip\n }\n if (bmux != undefined && bmux != null) {\n this.bpips[bmux][4] = true; // Select the appropriate pip\n }\n if (cmux != undefined && cmux != null) {\n this.cpips[cmux][4] = true; // Select the appropriate pip\n }\n if (kmux != undefined && kmux != null) {\n this.kpips[kmux][4] = true; // Select the appropriate pip\n }\n if (dmux != undefined && dmux != null) {\n this.dpips[dmux][4] = true; // Select the appropriate pip\n }\n }", "chooseFaceUp(a){\n console.log(this.hand[a[0]],this.hand[a[1]],this.hand[a[2]]);\n this.faceup.push(this.hand[a[0]]);\n this.faceup.push(this.hand[a[1]]);\n this.faceup.push(this.hand[a[2]]);\n a.sort(function(a,b){ // Sort the index to be in order\n return a-b;\n });\n this.removeFromHand(a[2]);\n this.removeFromHand(a[1]);\n this.removeFromHand(a[0]);\n }", "function boatTriumph(triumphBoat, takenBoats){\n\tvar tBoat = getBoardIndex(triumphBoat[0], triumphBoat[1]); //not needed, since move already processed\n\t\n\tfor(i=0; i < (takenBoats.length/2); i++){\n\t\tvar square = getBoardIndex(takenBoats[i*2], takenBoats[i*2+1]);\n\t\tboard[square] = -1;\n\t\tdrawSquareInColor(takenBoats[i*2], takenBoats[i*2+1], getSquareColor( takenBoats[i*2], takenBoats[i*2+1]));\n\t}\n\t\n}", "function mineSwipper(array, row, col) {\n var result = [];\n for (let i = 0; i < row; i++) {\n let row = [];\n result[i] = row;\n for (let j = 0; j < col; j++) {\n result[i][j] = 0;\n }\n }\n for (bomb of array) {\n let row_id = bomb[0];\n let col_id = bomb[1];\n result[row_id][col_id] = -1;\n for (let i = row_id - 1; i <= row_id + 1; i++) {\n for (let j = col_id - 1; j <= col_id + 1; j++) {\n if (0 <= i && i < row && 0 <= j && j < col) {\n if (result[i][j] !== -1) {\n result[i][j] += 1;\n }\n }\n }\n\n }\n }\n console.log(result);\n}", "function pingPong(arr, win) {\r\n\tlet result = [];\r\n for (let i = 0; i < arr.length; i++){\r\n result.push(arr[i])\r\n result.push('Pong!')\r\n }\r\n if( win === true){\r\n return result\r\n } else return result.slice(0, result.length -1)\r\n}", "function swapTowardCenter(arr){\n for (let i = 0; i < arr.length/2; i++) {\n var temporaryVarForSwitchingIndex = arr[i]\n arr[i] = arr[arr.length - 1-i] \n arr[arr.length - 1-i] = temporaryVarForSwitchingIndex \n \n }\n return arr \n}", "function almostSorted(arr) {\n if(arr.length === 0 || arr.length === 1) {\n console.log('yes');\n return;\n }\n\n const dips = [];\n const bumps = [];\n\n if(arr[0] > arr[1]) {\n bumps.push(new Element(0, arr[0]));\n }\n\n for(let i = 1; i < arr.length - 1; i++) {\n if(arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) {\n bumps.push(new Element(i, arr[i]));\n }\n else if(arr[i - 1] > arr[i] && arr[i + 1] > arr[i]) {\n dips.push(new Element(i, arr[i]));\n }\n }\n\n if(arr[arr.length - 1] < arr[arr.length - 2]) {\n dips.push(new Element(arr.length - 1, arr[arr.length - 1]));\n }\n\n if(dips.length === 0 && bumps.length === 0) {\n console.log('yes');\n }\n else if(dips.length === 2 && bumps.length === 2) {\n console.log('yes');\n console.log(`swap ${bumps[0].index + 1} ${dips[1].index + 1}`);\n }\n else if(dips.length === 1 && bumps.length === 1) {\n if(dips[0].index - bumps[0].index === 1) {\n if((bumps[0].index === 0 || dips[0].value > arr[bumps[0].index - 1])\n && (dips[0].index === arr.length - 1 || bumps[0].value < arr[dips[0].index + 1])) {\n console.log('yes');\n console.log(`swap ${bumps[0].index + 1} ${dips[0].index + 1}`);\n }\n else {\n console.log('no');\n }\n }\n else {\n console.log('yes');\n console.log(`reverse ${bumps[0].index + 1} ${dips[0].index + 1}`);\n }\n }\n else {\n console.log('no');\n }\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get EdmType of all properties from $metadata
function getEdmTypeOfAll(entityTypeObject) { return getAllColumnProperties("type", entityTypeObject); }
[ "function getEntityTypeProperties(oSmartControl) {\n\t\t\t\tvar oEntityType = getMetaModelEntityType(oSmartControl);\n\t\t\t\treturn oEntityType.property;\n\t\t\t}", "function resolveEntityTypes(entity) {\n for (var propertyName in entity) {\n if (propertyName === \"PartitionKey\" || propertyName === \"RowKey\" || propertyName === \"Timestamp\") {\n continue;\n }\n var property = entity[propertyName];\n property.$ = resolvePropertyType(property);\n }\n return entity;\n}", "async function findMetadataTypeRecords(){\n\n let metadataTypesUsingObject = [];\n if(!options.objectInMetadataTypes) return metadataTypesUsingObject;\n\n let mdTypeUtils = require('../metadata-types/utils/CustomMetadataTypes');\n\n let metadataTypeCustomFields = await mdTypeUtils.getCustomMetadataTypeFields(connection);\n\n if(!metadataTypeCustomFields.length) return metadataTypesUsingObject;\n\n //we need to do a metadata retrieve of all these custom fields so that we can inspect them\n //and see which ones are of the type EntityDefinition\n let customFieldsMetadata = await mdapi.readMetadata('CustomField',metadataTypeCustomFields);\n\n let entityDefinitionFields = [];\n\n customFieldsMetadata.forEach(fieldMd => {\n if(fieldMd.referenceTo && fieldMd.referenceTo == 'EntityDefinition'){\n entityDefinitionFields.push(fieldMd.fullName);\n }\n });\n\n if(!entityDefinitionFields.length) return metadataTypesUsingObject;\n\n let searchValue;\n\n //in standard objects the name and id are the same, and so the entity\n //definition id is also the name i.e Account or Opportunity\n if(entryPoint.name == entryPoint.id){\n searchValue = entryPoint.name;\n }\n else{\n //for custom objects, the entity definition id is the 15 digit version\n //of the object id\n searchValue = entryPoint.id.substring(0,15);\n }\n\n metadataTypesUsingObject = await mdTypeUtils.queryMetadataTypeForValue(connection,entityDefinitionFields,searchValue);\n\n return metadataTypesUsingObject;\n }", "function resolvePropertyType(property, propertyName) {\n var propertyValue = property._;\n var propertyType = property.$ || \"\";\n if (propertyType) {\n return propertyType;\n }\n if (propertyName && (propertyName === \"PartitionKey\" || propertyName === \"RowKey\")) {\n return AzureStorage.TableUtilities.EdmType.STRING;\n }\n if (propertyName && propertyName === \"Timestamp\") {\n // May or may not be called ever?\n return AzureStorage.TableUtilities.EdmType.DATETIME;\n }\n if (_.isBoolean(propertyValue)) {\n return AzureStorage.TableUtilities.EdmType.BOOLEAN;\n }\n if (_.isDate(propertyValue)) {\n return AzureStorage.TableUtilities.EdmType.DATETIME;\n }\n if (_.isNumber(propertyValue)) {\n // Analyze the Javascript number to determine the correct EDM type.\n return resolveNumber(Number(propertyValue));\n }\n return AzureStorage.TableUtilities.EdmType.STRING;\n}", "function extractCustomMetadata(metadata) {\n return {\n structuralTypes: _(metadata.schema.entityType).filter(function (type) {\n return _.any(type.property, function (p) {\n return !!p.custom;\n });\n }).map(function (typeMetadata) {\n var propertiesWithCustomMetadata = _(typeMetadata.property).filter(function (property) {\n return !!property.custom;\n });\n return {\n shortName: typeMetadata.name,\n namespace: metadata.schema.namespace,\n dataProperties: _.map(propertiesWithCustomMetadata, function (propertyMetadata) {\n return {\n name: propertyMetadata.name,\n description: propertyMetadata.description,\n custom: propertyMetadata.custom\n };\n })\n };\n })\n };\n }", "getPropertyTypes() {\n let properties = [];\n for (let part of Object.values(this.parts)) {\n if (part.properties) {\n properties.push(part.properties);\n }\n }\n return properties;\n }", "getMetadata(entity) {\n return this.entityMetadatas.findByTarget(entity);\n }", "function getPropertyType(typeName, property) {\n var prototype = getEntityPrototype(typeName)\n var propertyType = null\n for (var i = 0; i < prototype.Fields.length; i++) {\n if (prototype.Fields[i] == property) {\n propertyType = prototype.FieldsType[i]\n break\n }\n }\n return propertyType\n}", "getMetaData(propertyName, type) {\n return meta_manager_1.MetaManager.get(this).filter((current) => {\n return current.property === propertyName\n && current.type === type;\n });\n }", "function EntityType(type) {\n return function (target, targetKey, parameterIndex) {\n let baseType = Object.getPrototypeOf(target).constructor;\n if (baseType != Object && getProperties(baseType.prototype).length > 0) {\n EntityType()(baseType.prototype);\n let children = Reflect.getOwnMetadata(EdmChildren, baseType) || [];\n if (children.indexOf(target.constructor) < 0) {\n children.unshift(target.constructor);\n }\n Reflect.defineMetadata(EdmChildren, children, baseType);\n }\n if (typeof parameterIndex == \"number\") {\n let parameterNames = utils_1.getFunctionParameters(target, targetKey);\n let existingParameters = Reflect.getOwnMetadata(EdmParameters, target, targetKey) || [];\n let paramName = parameterNames[parameterIndex];\n let param = existingParameters.filter(p => p.name == paramName)[0];\n if (param) {\n param.type = type;\n }\n else {\n existingParameters.push(param = {\n name: paramName,\n type: type\n });\n }\n Reflect.defineMetadata(EdmEntityType, true, param.type);\n Reflect.defineMetadata(EdmParameters, existingParameters, target, targetKey);\n }\n else {\n if (typeof target == \"function\") {\n register(target);\n }\n let desc = Object.getOwnPropertyDescriptor(target, targetKey);\n if (targetKey && targetKey != EdmType && ((desc && typeof desc.value != \"function\") || (!desc && typeof target[targetKey] != \"function\"))) {\n let properties = Reflect.getOwnMetadata(EdmProperties, target) || [];\n if (properties.indexOf(targetKey) < 0)\n properties.push(targetKey);\n Reflect.defineMetadata(EdmProperties, properties, target);\n }\n if (type)\n Reflect.defineMetadata(EdmEntityType, true, type);\n Reflect.defineMetadata(EdmEntityType, type || true, target, targetKey);\n Reflect.defineMetadata(EdmType, type, target, targetKey);\n }\n };\n}", "function cfnFlywheelEntityRecognitionConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFlywheel_EntityRecognitionConfigPropertyValidator(properties).assertSuccess();\n return {\n EntityTypes: cdk.listMapper(cfnFlywheelEntityTypesListItemPropertyToCloudFormation)(properties.entityTypes),\n };\n}", "getMetadata(object) {\n object = object || this;\n const metadata = {\n phetioTypeName: object.phetioType.typeName,\n phetioDocumentation: object.phetioDocumentation,\n phetioState: object.phetioState,\n phetioReadOnly: object.phetioReadOnly,\n phetioEventType: js_EventType.phetioType.toStateObject(object.phetioEventType),\n phetioHighFrequency: object.phetioHighFrequency,\n phetioPlayback: object.phetioPlayback,\n phetioDynamicElement: object.phetioDynamicElement,\n phetioIsArchetype: object.phetioIsArchetype,\n phetioFeatured: object.phetioFeatured,\n phetioDesigned: object.phetioDesigned\n };\n if (object.phetioArchetypePhetioID) {\n metadata.phetioArchetypePhetioID = object.phetioArchetypePhetioID;\n }\n return metadata;\n }", "getEntityTypeId() {\n return this._registry.get('properties', 'entityTypeId')\n }", "async function findMetadataTypeRecords(){\n\n let metadataTypesUsingClass = [];\n if(!options.classInMetadataTypes) return metadataTypesUsingClass;\n\n let mdTypeUtils = require('../metadata-types/utils/CustomMetadataTypes');\n\n let metadataTypeCustomFields = await mdTypeUtils.getCustomMetadataTypeFields(connection);\n\n if(!metadataTypeCustomFields.length) return metadataTypesUsingClass;\n\n let fieldsThatReferenceClasses = [];\n\n //we assume that any field that has any of these identifiers\n //in its name, could possibly hold a value that matches the apex class name\n let classIndentifiers = ['class','handler','type','instance','trigger'];\n\n metadataTypeCustomFields.forEach(field => {\n\n //when checking if the field has any of the identifiers, we need\n //to check only the field name, excluding the object name\n //this prevents false positives like trigger_handler__mdt.not_valid__c\n //where it's the object name that matches the identifier, as opposed to the\n //actual field nae\n let fieldName = field.split('.')[1].toLowerCase();\n\n let fieldHasIndentifier = classIndentifiers.some(ci => {\n return fieldName.includes(ci);\n });\n if(fieldHasIndentifier){\n //however here, we push the entire field name\n fieldsThatReferenceClasses.push(field);\n }\n });\n\n if(!fieldsThatReferenceClasses.length) return metadataTypesUsingClass;\n\n let searchValue = entryPoint.name;\n\n metadataTypesUsingClass = await mdTypeUtils.queryMetadataTypeForValue(connection,fieldsThatReferenceClasses,searchValue);\n\n return metadataTypesUsingClass;\n\n }", "function getAllPropertyTypes() {\r\n return get('/propertytype/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function getMetadataDefinitions() {\n\t // Metadata definitions often apply to multiple\n\t // resource types. It is optimal to make a single\n\t // request for all desired resource types.\n\t /*var resourceTypes = {\n\t flavor: 'OS::Nova::Flavor',\n\t image: 'OS::Glance::Image',\n\t volume: 'OS::Cinder::Volumes'\n\t };\n\t angular.forEach(resourceTypes, function (resourceType, key) {\n\t glanceAPI.getNamespaces({\n\t 'resource_type': resourceType\n\t }, true)\n\t .then(function (data) {\n\t var namespaces = data.data.items;\n\t // This will ensure that the metaDefs model object remains\n\t // unchanged until metadefs are fully loaded. Otherwise,\n\t // partial results are loaded and can result in some odd\n\t // display behavior.\n\t if (namespaces.length) {\n\t model.metadataDefs[key] = namespaces;\n\t }\n\t });\n\t });*/\n\t }", "get PropertyType()\r\n {\r\n return this._propertyType; \r\n }", "function getSequelizeTypeByDesignType(target, propertyName) {\n var type = Reflect.getMetadata('design:type', target, propertyName);\n var dataType = data_type_1.inferDataType(type);\n if (dataType) {\n return dataType;\n }\n throw new Error(\"Specified type of property '\" + propertyName + \"'\\n cannot be automatically resolved to a sequelize data type. Please\\n define the data type manually\");\n}", "function isEntityType(target, propertyKey) {\n return typeof propertyKey == \"string\"\n ? !Reflect.hasMetadata(EdmComplexType, target.prototype, propertyKey) && Reflect.hasMetadata(EdmEntityType, target.prototype, propertyKey)\n : !Reflect.hasMetadata(EdmComplexType, target) && Reflect.hasMetadata(EdmEntityType, target);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Foward calls to define_method on the top object to Object
function top_define_method() { var args = $slice(arguments); var block = top_define_method.$$p; top_define_method.$$p = null; return Opal.send(_Object, 'define_method', args, block) }
[ "function bridgeMethods(fromObject, toObject) {\n fromObject.cancel = toObject.cancel.bind(toObject);\n fromObject.getRequest = toObject.getRequest.bind(toObject);\n fromObject.getResponse = toObject.getResponse.bind(toObject);\n fromObject.getError = toObject.getError.bind(toObject);\n}", "_override(object, methodName, callback) {\n const obj = object;\n obj[methodName] = callback(object[methodName]);\n }", "function around (obj, method, fn) {\n var old = obj[method]\n \n obj[method] = function () {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n return fn.call(this, old, args)\n }\n }", "replace(object, method) {\r\n /* eslint-disable-next-line @typescript-eslint/no-this-alias -- Function this is necessary in the function bellow, so class this has to be saved into a variable here. */\r\n const me = this;\r\n const original = object[method];\r\n if (!original) {\r\n throw new Error(\"Method \" + method + \" undefined\");\r\n }\r\n object[method] = function (...args) {\r\n // add this call to the queue\r\n me.queue({\r\n args: args,\r\n fn: original,\r\n context: this,\r\n });\r\n };\r\n }", "function around (obj, method, fn) {\r\n var old = obj[method]\r\n\r\n obj[method] = function () {\r\n var args = new Array(arguments.length)\r\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\r\n return fn.call(this, old, args)\r\n }\r\n}", "function around (obj, method, fn) {\n var old = obj[method]\n\n obj[method] = function () {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n return fn.call(this, old, args)\n }\n}", "_callUpdaters(obj){\n if (Utils.isDefined(obj)) {\n Object.getOwnPropertyNames(obj).forEach(prop => {\n let v = obj[prop];\n if (Utils.isFunction(v)) {\n obj[prop] = v.call(this);\n }\n //can become mergeable object after fn call\n v = obj[prop];\n if (Utils._isMergeableValue(v)) {\n Utils._callUpdaters(v);\n }\n });\n }\n }", "function objMaker(methodsInitializer, initArgs, superObject) {\n var methods = apply(methodsInitializer, initArgs);\n\n function dispatch(methodName, callSuper, self) {\n self = self || dispatch; //if self given use it, otherwise use this function\n if (!callSuper) {\n var method = methods(methodName);\n if (method) {\n return function () {\n return applyWithSelf(method, self, arguments);\n };\n }\n }\n if (superObject) { //re-call with superObject (this can happen recursively)\n return function () {\n //when calling super, make sure self is set to the method receiver\n return apply(superObject(methodName, false, self), arguments);\n }\n }\n throw 'Method ' + methodName + ' not known';\n }\n\n return dispatch;\n}", "function around(obj, method, fn) {\n var old = obj[method];\n\n obj[method] = function() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) args[i] = arguments[i];\n return fn.call(this, old, args);\n };\n}", "function around(obj, method, fn) {\n var old = obj[method];\n\n obj[method] = function () {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) args[i] = arguments[i];\n return fn.call(this, old, args);\n };\n}", "function around(obj, method, fn) {\n var old = obj[method];\n\n obj[method] = function () {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.call(this, old, args);\n };\n}", "function around(obj, method, fn) {\n\tvar old = obj[method];\n\n\tobj[method] = function() {\n\t\tvar args = new Array(arguments.length);\n\t\tfor (var i = 0; i < args.length; i++) args[i] = arguments[i];\n\t\treturn fn.call(this, old, args);\n\t};\n}", "function overrideMethods(obj, newMethod) {\n for (const name of Object.getOwnPropertyNames(Object.getPrototypeOf(obj))) {\n const method = obj[name];\n if(name === 'constructor') continue;\n obj[name] = ( async (...args) => {\n await newMethod.call(obj, method, ...args);\n });\n }\n}", "function SuperObject(obj){\n\n}", "GetRealObject() {\n\n }", "function fillIn(type, methodName, filler) {\n var proto = type.prototype;\n proto[methodName] = proto[methodName] || filler;\n }", "function relay(object, methods) {\n\tvar o1 = this;\n\tif ( typeof methods === 'string' ) {\n\t\tmethods = [methods];\n\t}\n\tvar i = methods.length;\n\tmethods.forEach(function (method) {\n\t\to1[method] = function () {\n\t\t\tobject[method].apply(object, arguments);\n\t\t}\n\t});\n}", "function bind(obj, method) {\n var fn = obj[method];\n obj[method] = function () {\n fn.apply(obj, arguments);\n };\n }", "function forward(params) {\n if (params.methods !== undefined) {\n params.methods.split(' ').forEach(function(method) {\n params.from[method] = params.to[method].bind(params.to)\n })\n }\n if (params.properties !== undefined) {\n params.properties.split(' ').forEach(function(prop) {\n params.from.__defineGetter__(prop, function() { return params.to[prop] })\n })\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bloomberg has requested that the Butler dashboard only be available to their Enterprise admins. This function will return whether a user can access the Butler directory on a board
canShowButlerUI() { if (this.hasEnterprise()) { if ( featureFlagClient .get('workflowers.butler-ent-admin-only-allowlist', []) .includes(this.get('idEnterprise')) ) { return ( this.getEnterprise().isAdmin(Auth.me()) || (this.get('idOrganization') && this.getOrganization()?.isAdmin(Auth.me())) ); } } return true; }
[ "function isAdmin()\n{\n if (!isLoggedIn())\n {\n return false;\n }\n\n return unstoreObject('user').userRole === 'ADMINISTRATOR';\n}", "function isAdmin() {\n return (window.location.href.indexOf(\"admin\") !== -1);\n }", "function isAdmin() {\n try {\n return ADMIN_USERS.indexOf(Meteor.user().services.github.username) !== -1\n } catch(e) {\n return false;\n }\n }", "isManager() {\n const data = localStorage.getItem('simpleAdminApp');\n if (!data) return false;\n const { user } = JSON.parse(data);\n return !!(user && user.role && user.role === 2);\n }", "elevatedPermissions() {\n return store.getState().loggedIn && (store.getState().permissions === 'ADMINISTRATOR' || store.getState().permissions === 'MANAGER');\n }", "function is_privileged(user, data){\n if (data['owner'] != user &&\n data['admins'].indexOf(user) == -1){\n return false\n }else{\n return true\n }\n}", "function isAdmin()\n\t\t{\n\t\t\tvar user = storage.get('user');\n\t\t\treturn ( user.permission_admin ) ? true : false;\n\t\t}", "isAdmin() {\n const { auth } = this.props;\n const project_url = this.props.match.params.projectUrl;\n return auth.role === 'admin' && auth.adminProjects.includes(project_url);\n }", "function isProjectAdmin() {\n var found = false;\n\n $.each(divvy.admins, function(index, value) {\n if (divvy.currentUser == value.username) {\n found = true;\n }\n });\n\n return found;\n }", "function isAdmin() {\n return !!(service.currentUser && service.currentUser.admin);\n }", "hasAdministrationPermissions(user) {\n return user && (user.isAdministrator || this.isMember(user, 'powerusers'));\n }", "hasDashboardAccess(nextProps) {\n let props = this.props;\n if (nextProps !== undefined) {\n props = nextProps;\n }\n\n // For anything that is not a dashboard, return true.\n if (!props.location.pathname.includes(\"dashboard\")) {\n return true;\n }\n\n const userGroups = groups(props.user);\n\n if (userGroups.length === 0) {\n console.error(\"This user does not seem to belong to any groups. Application access will be severely limited.\");\n }\n\n // If the user is in the \"administrator\" group then just return true.\n // They have access to everything.\n if (isAdmin(props.user)) {\n return true;\n }\n\n // Note: It is possible that a dashboard loads without being configured.\n // This would mean that `props.activeDashboard` would be undefined.\n // These are path based dynamic dashboards (dashboard \"types\") and can have an entry\n // in configuration (currently dashboardState.json) but do not necessarily need one.\n // So the default behavior here will be to block access to these dashboards unless\n // the user is in the \"administrator\" group.\n \n const activeDashboard = _.find(dashboardState.dashboards, {\n id: this.props.params.id || dashboardState.activeDashboard\n })\n \n const dashboardGroups = activeDashboard && activeDashboard.groups ? activeDashboard.groups : [];\n\n if (activeDashboard === undefined) {\n dashboardGroups.push(\"administrator\");\n }\n\n if (userGroups.length > 0 && dashboardGroups.length > 0) {\n if (_.intersection(userGroups, dashboardGroups).length > 0) {\n return true;\n }\n }\n\n return false;\n }", "function isPublic() {\n return session_1.current == null || session_1.current.role == null || session_1.current.role == \"Alpbrothers WWW\";\n }", "function isOnlyAdmin(entity) {\n if ($scope.userList.adminUsers.length === 1) {\n return $scope.userList.adminUsers[0].userName === entity.userName;\n }\n return false;\n }", "function isAdminUser(request) {\n return request.auth.credentials.scope.find(scope => scope === 'admin');\n }", "canAdministrateTeam(team) {\n return this.canAdministrateGroup(team)\n }", "function ActivityAllowed() { return ((CurrentScreen == \"ChatRoom\") || ((CurrentScreen == \"Private\") && LogQuery(\"RentRoom\", \"PrivateRoom\"))) }", "isConfigManager(){\n return this.isUserRole(Authorization.ROLE_CONFIG_MANAGER);\n }", "isAdmin(data){\n if (data && data.role && data.role.rolename){\n if (typeof data.role.rolename == 'string'){\n if (data.role.rolename.toLowerCase() == 'admin'){\n return true;\n }\n }\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watcher listeners New file created.
function onNewFile(file) { console.log("onNewFile() - watch_old: " + this.watchDir + " process_old: " + this.processedDir); var watchFile = this.watchDir + '/' + file; var processedFile = this.processedDir + '/' + file.toLowerCase(); console.log("onNewFile() - watch_new: " + watchFile + " process_new: " + processedFile); fs.rename(watchFile, processedFile, onError); }
[ "function addWatcher (newPath) {\n fileWatcher = chokidar.watch(newPath, {\n persistent: true,\n ignored: /(^|[/\\\\])\\../ //For .DS_Store on MacOS\n });\n // console.log(newPath)\n //Signals to setMovieFolder that a watcher exists\n isWatching = true;\n fileWatcher.on('ready', async () => {\n // Retrieve files being watched\n let watched = fileWatcher.getWatched();\n watched = watched[newPath]\n // console.log(watched)\n // Calls sync function\n await onReadySync(watched);\n fileWatcher.on('add', filePath => insertMovie(filePath));\n fileWatcher.on('unlink', filePath => removeMovie(filePath));\n fileWatcher.on('error', error => {\n console.error(`FILEWATCHER ERROR: ${error}`)\n }); \n });\n}", "function watchrCreateHandler(changeType,filePath,fileCurrentStat,filePreviousStat) {\n if(changeType == 'create') {\n console.log(\"watchr filePath \" + filePath);\n var routeMatch = routePattern.exec(filePath);\n console.log(\"watchr route match \" + routeMatch);\n var viewMatch = viewPattern.exec(filePath);\n console.log(\"watchr view match \" + viewMatch); \n if(routeMatch && viewMatch) {\n // new view\n var route = routeMatch[1].replace(/\\\\/g, \"/\");\n var view = viewMatch[1];\n console.log(\"watchr route \" + route);\n console.log(\"watchr view \" + view);\n registerView(route, view); \n } else if (fs.statSync(__dirname + '/' + filePath).isDirectory()) {\n // new folder\n var route = filePath.replace(/\\\\/g, \"/\");\n console.log(\"watchr route \" + route);\n watchRoute(route);\n }\n }\n}", "function fileListener() {\n const fileWatcher = coc_nvim_1.workspace.createFileSystemWatcher(`**/{${PRETTIER_CONFIG_FILES.join(',')}}`);\n fileWatcher.onDidChange(prettier.clearConfigCache);\n fileWatcher.onDidCreate(prettier.clearConfigCache);\n fileWatcher.onDidDelete(prettier.clearConfigCache);\n return fileWatcher;\n}", "addFile(path,callbackModified,callbackAdded,callbackRemoved,callbackNotValid){\n if(this.hasFile(path)){\n return;\n }\n const self = this;\n\n function onWatchProcessed(){\n if(++self._watchesProcessed < self._watches.length){\n return;\n }\n const timeDiff = Date.now() - self._watchTimeStart;\n const delay = self._watchDelay;\n\n //Update took longer than default watch rate\n if(timeDiff >= delay){\n self._watch();\n }\n //Wait\n else {\n setTimeout(FileWatcher.prototype._watch.bind(self), delay - timeDiff);\n }\n }\n\n function watch(file){\n let watch_;\n const request = new XMLHttpRequest();\n request.addEventListener('readystatechange', function(){\n if(this.readyState != 4){\n return;\n }\n const status = this.status;\n if(status === 200){\n const time = new Date(request.getResponseHeader('Last-Modified'));\n //error\n if(time.toString() == 'Invalid Date'){\n if(file.hasEventListener(FileEvent.FILE_NOT_VALID)){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_NOT_VALID));\n }\n return;\n }\n //no change\n if(time === file.timeModifiedNew){\n return;\n }\n //file touched\n if(time > file.timeModifiedNew){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_MODIFIED,this.responseText));\n file.timeModifiedOld = file.timeModifiedNew;\n file.timeModifiedNew = time;\n }\n onWatchProcessed();\n }\n //file removed\n else if(status === 404){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_REMOVED));\n self._watchesInvalid.push(watch_);\n onWatchProcessed();\n }\n });\n\n watch_ = {file: file, request: request};\n self._watches.push(watch_);\n\n self._watch();\n }\n\n function addFile(file){\n const request = new XMLHttpRequest();\n request.open('GET',file.path);\n request.addEventListener('readystatechange', function(){\n if(this.readyState != 4){\n return;\n }\n const status = this.status;\n if(status === 200){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_ADDED,request.responseText));\n watch(file);\n } else if(status === 404){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_REMOVED));\n }\n });\n request.send();\n }\n\n const request = new XMLHttpRequest();\n request.open('HEAD',path);\n\n //Get initial file info\n request.addEventListener('readystatechange',function(){\n if(this.readyState != 4){\n return;\n }\n const status = this.status;\n if(status == 200){\n\n const file = new File(path);\n if(callbackNotValid){\n file.addEventListener(FileEvent.FILE_NOT_VALID,callbackNotValid);\n }\n const time = new Date(request.getResponseHeader('Last-Modified'));\n //file not valid\n if(time.toString() == 'Invalid Date'){\n if(file.hasEventListener(FileEvent.FILE_NOT_VALID)){\n file.dispatchEvent(new FileEvent(FileEvent.FILE_NOT_VALID));\n }\n }\n //add initial time\n file.timeModifiedNew = time;\n\n //add listener\n if(callbackAdded){\n file.addEventListener(FileEvent.FILE_ADDED,callbackAdded);\n }\n if(callbackModified){\n file.addEventListener(FileEvent.FILE_MODIFIED,callbackModified);\n }\n if(callbackRemoved){\n file.addEventListener(FileEvent.FILE_REMOVED,callbackRemoved);\n }\n\n addFile(file);\n\n } else if(status == 404){\n if(callbackNotValid){\n callbackNotValid();\n return;\n }\n console.log('File does not exist. File: ' + path);\n }\n });\n\n request.send();\n }", "watch() {\n fs.watch(this.file, (event, file) => {\n if (event === 'change')\n this.routes = Router.forge(this.file);\n })\n }", "function registerFileChangeListener() {\n\n var $documentManager = DocumentManager;\n var $projectManager = ProjectManager;\n FileSystem.on('change', function (event, file) {\n // Bail if not a file or file is outside current project root.\n if (file === null || file.isFile !== true || file.fullPath.indexOf(ProjectManager.getProjectRoot().fullPath) === -1) {\n return false;\n }\n\n //TODO trello anzhihun update trello comments on file change.\n// console.log('Brackets-Trello: change file ' + file.fullPath + ', event = ' + event);\n if (ParseUtils.isSupported(LanguageManager.getLanguageForPath(file.fullPath).getId())) {\n // Just find again now\n asynFindTrelloComments();\n }\n\n });\n\n FileSystem.on('rename', function (event, oldName, newName) {\n //TODO trello anzhihun update trello comments on file name change.\n// console.log('Brackets-Trello: rename old file ' + oldName + ' to ' + newName + ', event = ' + event);\n if (ParseUtils.isSupported(LanguageManager.getLanguageForPath(oldName).getId()) ||\n ParseUtils.isSupported(LanguageManager.getLanguageForPath(newName).getId())) {\n // Just find again now\n asynFindTrelloComments();\n }\n });\n \n $projectManager.on('projectOpen', function(event, directory){\n // reparse \n asynFindTrelloComments();\n });\n }", "function filesWatcher() {\n const watcher = chokidar.watch(['src'], {\n ignored: ['.DS_Store', 'src/js/.jshintrc', 'src/js/.babelrc'],\n persistent: true,\n depth: 3,\n awaitWriteFinish: {\n stabilityThreshold: 500,\n pollInterval: 500\n },\n });\n\n watcher.on('change', path => {\n if (path.endsWith('.js')) {\n return handleJavascript(path);\n }\n if (path.endsWith('.css')) {\n return handlePostCSS(path);\n }\n })\n watcher.on('ready', () => notify('Watching files', 'Initial scan complete. Ready for changes'))\n}", "watch () {\n const opts = { persistent: false }\n this.watcher = fs.watch(this.filename, opts, (type) => {\n if (type === 'rename') { console.error(this.filename + ': removed?!') }\n if (this.wake) this.wake()\n })\n }", "function handleNewFiles() {\n var fileName;\n do {\n // If there is a file, move it from staging into the application folder\n fileName = inbox.nextFile();\n if (fileName) {\n console.log(\"/private/data/\" + fileName + \" is now available\");\n // refresh weather now\n weatherFromFile();\n }\n } while (fileName);\n}", "startWatching () {\n\t\tconst path = this.config.inboundEmailServer.inboundEmailDirectory;\n\t\tthis.log(`Watching ${path}...`);\n\t\tFS.watch(path, this.onFileChange.bind(this));\n\t}", "listen(dirWatcher, timeout){\n dirWatcher.watch(this._inputPath, timeout);\n\n dirWatcher.eventEmitter.on('dirwatcher:create', data=>{\n this.import(data.path).then((importedData)=>{\n writeInFile(data.path, this._outPath, importedData);\n });\n //writeInFile(data.path, this._outPath, this.importSync(data.path));\n });\n\n dirWatcher.eventEmitter.on('dirwatcher:update', data=> {\n this.import(data.path).then((importedData)=>{\n writeInFile(data.path, this._outPath, importedData);\n });\n });\n\n dirWatcher.eventEmitter.on('dirwatcher:remove', data=> {\n let path = setPathOutFile(data.path, this._outPath);\n\n if(fs.existsSync(path)){\n fs.unlinkSync(path);\n }else{\n console.log(`File ${getNameFile(data.path)} was deleted`);\n }\n });\n }", "function addWatcherListener(watcher) {\n watcher.on('change', function(event) {\n console.log('Updated!: ' + event.path);\n });\n}", "function addEventListeners() {\n\n // Compile all files and close watcher\n if( _build ) {\n _watcher.on( Event.ADD, onAddHandler );\n }\n\n // Watch for file changes\n else {\n _watcher.on( Event.ADD, onAddHandler );\n _watcher.on( Event.CHANGE, onChangeHandler );\n _watcher.on( Event.UNLINK, onUnlinkHandler );\n _watcher.on( Event.ERROR, onErrorHandler );\n }\n\n _watcher.close();\n}", "function startWatcher() {\n \n fs.watch(dir, function onChange(event, filename) {\n \n if(filename != null) {\n console.log(\"Templatefile %s changed.\", filename);\n compileSingleFile(filename);\n } else {\n console.log(\"Some templatefile changed. Recompiling all...\");\n compileAllFiles();\n }\n \n render();\n console.log(\"Recompilation finished.\");\n \n });\n \n console.log(\"Watcher for templates started.\");\n \n}", "watch() {\n fs.readdir(this.watchDir, (err, files) => {\n if (err) throw err;\n for (var index in files) {\n this.emit(\"process\", files[index]);\n }\n });\n }", "watchFiles(files) {\n this.listenTo(files, 'reset', () => this._populateFromFiles(files));\n this._populateFromFiles(files);\n }", "startFileWatcher() {\n const baseDir = process.cwd();\n\n this._reloadWatchers = [];\n\n const watchPaths = this._app.packageJson.getDevRoutesWatch();\n for (let i = watchPaths.length - 1; i >= 0; i--) {\n const path = Path.join(baseDir, watchPaths[i]);\n\n console.log('Live reload started for path', path);\n\n this._reloadWatchers[i] = Fs.watch(path, {recursive: true}, (evType, filename) => {\n if (filename) {\n console.log('Live change detected in file', filename ,'. Reloading...');\n\n for (let i = this._reloadWatchers.length - 1; i >= 0; i--) {\n this._reloadWatchers[i].close();\n }\n\n window.location.reload(true);\n }\n });\n }\n }", "watch() {\n fs.readdir(this.watchDir, (err, files) => {\n if (err) throw err;\n for (let index in files) {\n this.emit('process', files[index]);\n }\n });\n }", "_watchForChanges (path) {\n this.api.configs.watchFileAndAct(path, () => {\n // remove old listeners\n this.fileListeners.get(path).forEach(listener => {\n // an listener can support multiple events, so we need iterate all\n const events = (typeof listener.event === 'string')\n ? [ listener.event ]\n : listener.event\n\n for (const event of events) {\n // get array of functions\n const listeners = this.events.get(event)\n\n // get listener index\n const index = listeners.indexOf(listener)\n\n // remove listener\n listeners.splice(index, 1)\n }\n })\n\n // load the listeners again\n this._loadFile(path, true)\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RANDOM 2D SQUARE ARRAY/MATRIX
function randomSquareMatrix(n) { let A = new Array(n); for (let i = 0 ; i < n; i++) { A[i] = new Array(n); for (let j = 0; j < n; j++) { A[i][j] = Math.floor(rng()*10); } } return A; }
[ "randomize() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.cols; j++) {\n this.data[i][j] = Math.random() * 2 - 1;\n }\n }\n }", "static getRandomBool2DArray(x, y)\n {\n let res = new My2DArray(x,y);\n for(let i = 0; i < x; i++)for(let j = 0; j < y; j++)\n {\n res.set(i ,j, Math.floor(Math.random()*2)); \n }\n return res; \n }", "randomize(){\n for(let i = 0; i < this.rows; ++i){\n for(let j = 0; j < this.cols; ++j){\n this.matrix[i][j] = Math.floor(Math.random() * 10);\n }\n }\n }", "randomise() {\r\n for(var mY = 0; mY < this.sizeY; mY++) {\r\n for(var mX = 0; mX < this.sizeX; mX++) {\r\n this.matrixElement[mX][mY].value = 2*Math.random() - 1;\r\n }\r\n }\r\n }", "function MatrixRandomGen(row, col) {\n var array = [];\n for (var i = 0; i < row; ++i) {\n array[i] = [];\n for (var j = 0; j < col; ++j) {\n array[i][j] = Math.floor(Math.random() * 100);\n }\n }\n return array;\n}", "function randomWorld() {\n let world = [];\n const p = 0.2;\n\n for (let rowIndex = 0; rowIndex < PIXELS; rowIndex++) {\n let row = [];\n\n for (let colIndex = 0; colIndex < PIXELS; colIndex++) {\n row.push(Math.random() <= p);\n }\n\n world.push(row);\n }\n\n return world;\n}", "getRandomMatrixArray(cols, rows) {\n\t\t// TODO : add some check for rows and cols size\n\t\tlet matrix = [];\n\t\tfor (let i = 0; i < cols; i++) {\n\t\t\tmatrix.push([]);\n\t\t\tfor (let j = 0; j < rows; j++) {\n\t\t\t\tmatrix[i].push(this.getRandomIntegerBetween(0, this.maxSymbolIndex - 1));\n\t\t\t}\n\t\t}\n\t\treturn matrix;\n\t}", "function initRandomMatrix(width, height) {\n var rnd = function() {\n return Math.floor( 2 * Math.random() );\n };\n\n var matrix = [];\n for (var ii = 0 ; ii < width ; ii++) {\n var row = new Array(height);\t\t// Float32Array\n for (var jj = 0 ; jj < height; jj++) {\n row[jj] = rnd();\n }\n matrix.push(row);\n }\n return matrix;\n}", "function matrixGenerator(x, y) {\n let matrix = []\n let randomValue \n\n for (let i = 0; i < y; i++) {\n matrix.push([])\n\n\n }\n for (let i = 0; i < x; i++) {\n \n\n for (let i = 0; i < y; i++) {\n matrix[i].push(randomValue = Math.floor(Math.random() *10))\n \n }\n \n }\n\n return matrix\n \n}", "function randomArr(size) {\n returnArr = [];\n var wH = makeWH(size)\n //console.log(wH)\n traverseGrid(wH[0], wH[1], function(x, y){\n if(Math.random() < .5) {\n returnArr.push({'x': x, 'y': y})\n }\n })\n return returnArr;\n }", "function fillRandom() {\n grid = makeGrid(cols, rows);\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < rows; j++) {\n grid[i][j] = Math.floor(Math.random() * 2);\n }\n }\n}", "randomise(){ // initialise with optimal weights coming soon TM\n for (var i = 0; i < this.rows; i++){\n for (var j = 0; j < this.columns; j++){\n this.matrix[i][j] = Math.random() * 2 - 1;\n }\n }\n }", "function randomGrid() {\n if (generate) return\n const randGrid = new Array(cols).fill(null)\n .map(() => new Array(rows).fill(null)\n .map(() => Math.floor(Math.random() * 2)));\n setGrid(randGrid)\n genCount.current = 0\n }", "function randomWorldGenerator(n) {\n var randomBoard = [];\n for (var i = 0; i < n; i++) {\n var column = [];\n for (var j = 0; j < n; j++) {\n // generate a random integer between 0 and 1 included\n column[j] = Math.floor(Math.random() * 2);\n }\n randomBoard[i] = column;\n }\n return randomBoard;\n}", "function createRandomGrid(width, height) {\n grid = new Array(width);\n prevGrid = new Array(height);\n\n //populate the 1d array \"grid\" with arrays,\n //thus creating a 2d grid\n for (var i = 0; i < width; i++) {\n grid[i] = new Array(height);\n prevGrid[i] = new Array(height);\n for (var j = 0; j < height; j++) {\n if (Math.random() < 0.5) {\n grid[i][j] = false;\n } else {\n grid[i][j] = true;\n }\n prevGrid[i][j] = false;\n }\n }\n}", "function generateRandomWorld(n) {\n let grid = [];\n for (let i = 0; i < n; i++) {\n let line = [];\n for (let j = 0; j < n; j++) {\n // generate a random integer value between 0 and 1\n line[j] = Math.floor(Math.random() * 2);\n }\n grid[i] = line;\n }\n return grid;\n}", "function getRandomArbitrary() {\n\t\treturn Math.random() * (num_row * num_col);\n\t}", "function randArray(height,width,min,MAX) {\n\tsquare = new Array(height);\n\tfor(i=0;i<height;i++) {\n\t\tsquare[i]=new Array(width);\n\t\tfor(j=0;j<width;j++) {\n\t\t\tsquare[i][j]=Math.floor(Math.random()*MAX)+min;\n\t\t}\n\t}\n\treturn square;\n}", "function getRandomCoordinates() {\n var row = Math.floor(Math.random() * totalRows) + 1;\n var col = Math.floor(Math.random() * totalCols) + 1;\n return [row, col];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the label for the Input insinde the PromptWindow. Property type: string
get promptLabel() { return this.nativeElement ? this.nativeElement.promptLabel : undefined; }
[ "set _label(value){Helper$2.UpdateInputAttribute(this,\"label\",value)}", "function _labelFromInput() {\n return {\n \"category\": htElement.welInputLabel.data('category'),\n \"name\": htElement.welInputLabel.val()\n };\n }", "set _label(value) {\n Helper.UpdateInputAttribute(this, \"label\", value);\n }", "function TextBoxCaptionInput() {\n //debugger;\n var person = prompt(\"Please enter label:\", \"\");\n if (person == null || person == \"\") {\n TextboxCaption = \"\";\n return false;\n }\n else {\n TextboxCaption = person;\n TextboxCaption = TextboxCaption.replace(/\\n/g, '').trim();\n if (VerifyUserInput(TextboxCaption)) {\n return true;\n }\n return false;\n }\n}", "function promptGesture(label) {\n return prompt(`\\t\\t${label}`, { echo: '*' });\n}", "function checkLabel(name, value) {\n let input = doc.querySelector(`.shortcut-input[name=\"${name}\"]`);\n let label = input.previousElementSibling;\n if (label.dataset.l10nId) {\n is(label.dataset.l10nId, value, \"The l10n-id is set\");\n } else {\n is(label.textContent, value, \"The textContent is set\");\n }\n }", "static promptTextCreator(input) {\n return `Use \"${input.toUpperCase()}\"`;\n }", "static getStaticText(label) {\n return SuiLyricDialog.dialogElements.find((x) => x.staticText).staticText.find((x) => x[label])[label];\n }", "get hintLabel() { return this._hintLabel; }", "function prompt() {\n\n function keyupHandler(e) {\n var key_code = e.which,\n _this = this,\n v = this.value,\n $span,\n $ul;\n\n // No name entered\n if (!v) {\n // Hint\n return false;\n } else {\n // Detects Enter key\n if (key_code === 13) {\n confirmGroupName(v);\n } \n };\n }\n\n function inputBlurHandler() {\n var v = this.value,\n _this = this;\n if (!v) {\n setTimeout(function() {\n // Hint\n $(_this).focus();\n }, 1);\n };\n\n return true;\n };\n\n var input_css = {\n 'position' : 'relative',\n 'background' : 'transparent',\n 'border-style' : 'none',\n 'font-size' : '0.9em',\n 'font-weight' : '300',\n 'border' : 'none',\n 'margin' : '0 0 0.4em 0.3em',\n 'padding' : '0',\n 'line-height' : '2em',\n '-webkit-box-shadow' : 'none',\n '-moz-box-shadow' : 'none',\n 'box-shadow' : 'none',\n 'z-index' : '1500'\n };\n\n function onFocus() {\n $(this).css({\n 'outline': 'none'\n })\n };\n\n return $(document.createElement('input'))\n .attr('type', 'text')\n .attr('placeholder', Nest.options.groupNamePlaceholder)\n .addClass('nest-folder-input-prompt')\n .keyup(keyupHandler)\n .css(input_css)\n .focus(onFocus)\n .blur(inputBlurHandler);\n }", "function modalInput() {\n return 'Res želite izprazniti košarico?';\n}", "getDialogLabel() {\n\t\t\tlet label = LIST_DIALOG[SYM__DIALOG_LABEL];\n\n\t\t\tif (label == null) {\n\t\t\t\tconst control = DOM.createElement(\"div\", {\n\t\t\t\t\tstyle: {\n\t\t\t\t\t\tmarginBottom: \"10px\",\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tconst updateFc = (state) => {\n\t\t\t\t\tif (updateFc[SYM__DIALOG_LABEL_CURRENT_STATE] === state)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tLIST_DIALOG[SYM__DIALOG_UPDATE_LABEL](control, state);\n\t\t\t\t};\n\n\t\t\t\tupdateFc[SYM__CONTROL] = control;\n\n\t\t\t\tlabel = LIST_DIALOG[SYM__DIALOG_LABEL] = updateFc;\n\t\t\t}\n\n\t\t\treturn label;\n\t\t}", "function sample1Prompt(){\n var Fn = \"[sample1Prompt] \";\n var szPromptType = selectGetSelVal(getElementById2(\"szPromptType\"));\n var szMsg = (szPromptType == PROMPT_TYPE.NUMBER) ?\n \"Please Insert a <B>Number</b>\" : \n \"Please Insert a <B>Text</b>\"; \n var objOpt ={\n szPromptType: szPromptType,\n szPromptLabel: getElementById2 (\"szPromptLabel\").value,\n szPromptValue: getElementById2 (\"szPromptValue\").value,\n iPromptMin: parseInt (getElementById2(\"iPromptMin\").value),\n iPromptMax: parseInt (getElementById2 (\"iPromptMax\").value),\n iPromptWidth: parseInt(getElementById2 (\"iPromptWidth\").value),\n fnCallback:callbackPrompt\n }; \n jslogObj (JSLOG_DEBUG,Fn + \"objOpt\", objOpt );\n Popup (POPUP_TYPE.PROMPT,szMsg,objOpt);\n\n}", "function createInputLabel(name, id, placeholder, label) {\n let div = document.createElement(\"div\");\n div.classList.add(\"label-w-input\");\n\n let nameInp = document.createElement(\"input\");\n nameInp.type = \"text\";\n nameInp.name = name;\n nameInp.id = id;\n nameInp.placeholder = placeholder;\n nameInp.classList.add(\"form-inp\");\n\n let nameLab = document.createElement(\"label\");\n nameLab.for = id;\n nameLab.innerText = label;\n\n div.append(nameLab);\n div.append(nameInp);\n\n return div;\n}", "createInputPrompt() {\n return new InputPrompt();\n }", "get label() {\n\n // return the human friendly string\n return this[label];\n }", "function promptEntry(s) {\r\n window.status = pEntryPrompt + s\r\n}", "get LabelTemplate() {\n if (!this.label || !this.isSlotHasChildren) {\n return null;\n }\n return html `\n <ef-label\n part=\"label\"\n .lineClamp=${this.getLineClamp()}>\n ${this.label}\n </ef-label>\n `;\n }", "async enterText(){\n let value = await RandomUtils.generateRandomString();\n await this.stringField.enterText(value)\n this.inputValue = value;\n if (this.checkYourAnswersValue === null){\n this.checkYourAnswersValue = value;\n }\n this.label = await this._getLabel();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch content after click navbar
function fetchContentAfterClickNav(){ navUlList.forEach(navList => { navList.addEventListener('click', event => { const navHref = navList.getAttribute('data-a-href'); if(navHref === null) { return; } fetchPageContent(navHref); addActiveClass(navHref); }); }); dropdownContent.forEach(dropNav => { dropNav.addEventListener('click', event => { const navHref = dropNav.getAttribute('data-a-href'); fetchPageContent(navHref); addActiveClass(navHref); }); }); sidenavUlList.forEach(sideNav => { sideNav.addEventListener('click', event => { const navHref = sideNav.getAttribute('data-a-href'); if(navHref === null) { return; } fetchPageContent(navHref); addActiveClass(navHref); }); }); sidenavCollapsibleContent.forEach(sideDropdown => { sideDropdown.addEventListener('click', event => { const navHref = sideDropdown.getAttribute('data-a-href'); fetchPageContent(navHref); addActiveClass(navHref); }); }); }
[ "function getMainNavigationContent() {\n mainNavSrv.getNavigationContents().then(function (result) {\n \n });\n }", "function navbarListener() {\n const home = document.querySelector('[action=\"/\"]');\n const sportNews = document.querySelector('[action=\"/sportNews\"]');\n const musicNews = document.querySelector('[action=\"/musicNews\"]');\n\n\n home.addEventListener('click', (event) => {\n fetch('/allNews', displayNews);\n home.className = 'active';\n if (sportNews.className === 'active' || musicNews.className === 'active') {\n sportNews.className = '';\n musicNews.className = '';\n }\n });\n sportNews.addEventListener('click', (event) => {\n fetch('/sportNews', displayNews);\n sportNews.className = 'active';\n if (home.className === 'active' || musicNews.className === 'active') {\n home.className = '';\n musicNews.className = '';\n }\n });\n musicNews.addEventListener('click', (event) => {\n fetch('/musicNews', displayNews);\n musicNews.className = 'active';\n if (home.className === 'active' || sportNews.className === 'active') {\n home.className = '';\n sportNews.className = '';\n }\n });\n}", "static onClickPushContent() {\n let navbar = ViewHelper.get('NavbarMain');\n\t\tlet $element = $('.context-menu-target-element');\n let pushId = $element.data('id');\n\n\t\t$element.parent().addClass('loading');\n\n // API call to push the Content by id\n apiCall('post', 'content/push/' + pushId)\n\n // Upon success, reload all Content models\n .then(() => {\n return reloadResource('content');\n })\n\n // Reload the UI\n .then(() => {\n navbar.reload();\n }) \n .catch(UI.errorModal);\n }", "function connexion(){\n\n $('#content').load('inc/connexion.php');\n removeClassActive('navConnexion');\n \n $('.navbar-toggler').click();\n\n}", "function handleNavigation(){\r\n document.body.scrollTo({ y: 0 });\r\n var path = window.location.pathname;\r\n var hash = window.location.hash ? window.location.hash.substr(1) : '';\r\n \r\n getPage(path).then($html => {\r\n // remove old content\r\n while ($content.firstChild)\r\n $content.removeChild($content.firstChild);\r\n \r\n // add new content\r\n $content.appendChild($html);\r\n\r\n // update UI\r\n updateUi(path, hash);\r\n });\r\n}", "function loadTopMenuContent() {\r\n\tloadData(\"member/topMenu\", \"mainnav\");\r\n}", "function navClick() {\n $(\"button\").on(\"click\", function () {\n loadCitySummary($(this).val());\n });\n}", "function fetchMenu () {\n var urlMenu = 'https://json-data.herokuapp.com/restaurant/menu/1'\n $.get(urlMenu).done(renderMenu).fail(responseFail)\n }", "function showMenu() {\n $.get(serverUrl + 'api/user/', USER_INFO, function (code, statut) {\n $('#content').empty().html(code);\n $(\"#connect_page\").bind(\"click\", redirectConnect);\n // contient les boutons du menu\n bindButton();\n // Lorsqu'on affiche le menu, on affiche aussi la liste des contacts selon\n // leur disponibilité\n getContactsList();\n });\n\n}", "function getMainNav() {\n function myResponse() {\n var myArr = JSON.parse(this.responseText);\n makeMainNav(myArr);\n };\n XML_REQUEST.open('get', API_URL, true);\n XML_REQUEST.send();\n XML_REQUEST.onload = myResponse;\n }", "static onClickPullContent() {\n let navbar = ViewHelper.get('NavbarMain');\n let contentEditor = ViewHelper.get('ContentEditor');\n let pullId = $('.context-menu-target-element').data('id');\n\n // API call to pull the Content by id\n apiCall('post', 'content/pull/' + pullId, {})\n \n // Upon success, reload all Content models \n .then(() => {\n return reloadResource('content');\n })\n\n // Reload the UI\n .then(() => {\n navbar.reload();\n\n\t\t\tlocation.hash = '/content/' + pullId;\n\t\t\n\t\t\tlet editor = ViewHelper.get('ContentEditor');\n\n\t\t\tif(editor && editor.model.id == pullId) {\n editor.model = null;\n\t\t\t\teditor.fetch();\n\t\t\t}\n }) \n .catch(UI.errorModal);\n }", "function loadnavbar (selection) {\n if (session.get('user') && (session.get('user').role == 'Admin')) {\n $('header').removeClass('hidden');\n $('footer').removeClass('hidden');\n var template = _.template($('#navbar-template').html()); \n $(\"nav\").html(template);\n Fluff.admin.showUserLabel();\n if (selection) {\n navselect(selection);\n }\n }\n}", "function mainNav(page) {\n getPage(page);\n}", "function mainNavigationAction(){\n\t\t\t\tvar $activeLinks = $links.filter('.active');\n\t\t\t\tif ( $activeLinks.length > 0 ){\n\t\t\t\t\t$activeLinks.each(function(){\n\t\t\t\t\t\tvar $this = $(this);\n\t\t\t\t\t\tvar page = $this.data().page;\n\t\t\t\t\t\tvar $contentWrapper = $this.closest('.the1panel-tabcontent').find('.options-pages');\n\t\t\t\t\t\t$contentWrapper.find('.page').hide().filter('.'+page).show();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}", "function loadMenus() {\r\n debugger;\r\n API.getMenus()\r\n .then(res => \r\n setMenus(res.data)\r\n )\r\n .catch(err => console.log(err));\r\n }", "renderNav() { // public: Gets the HTML page for the navigation div and displays it in the nav div, then calls getFile to get the nav details and buildNavBar to display them\n const DOMelement = document.getElementById(\"navDiv\");\n return this.render(DOMelement, \"nav\")\n .then(function() {\n return this.getFile(\"nav.JSON\", true, \"[]\");\n }.bind(this))\n .then(function(responseText) {\n this.buildNavBar(responseText);\n }.bind(this));\n }", "function topNav(){\n\t$(\"#topNav a\").live('click', function(e) {\n\t\tvar fileName = $(this).attr('href').substring(1);\n\t\tvar info = {\"ajax\": \"true\"};\n\t\tvar path = fileName + '.php';\n\n\t\tdefaultTheme(); // Change to default theme\n\t\t\n\t\t// Toggle current class\n\t\t$(\"#topNav a.current\").removeClass('current');\n\t\t$(this).addClass('current');\n\n\t\t// Make the ajax call\n\t\t$.post(path, info , function(data){\n\t\t\t$(\"#content\").html(data).hide().fadeIn('500');\n\t\t\t// Depending on which sidenav is click, call the following function\n\t\t\tswitch(fileName){\n\t\t\t\tcase 'posters':\n\t\t\t\t\tposter();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'about':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'artists':\n\t\t\t\t\tartists();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'contact':\n\t\t\t\t\tcontact();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}, 'html');\n\t\treturn false;\n\t});\n}", "function loadMenuContent() {\r\n\tloadData(\"member/memberMenu\", \"menuContent\");\r\n}", "function loadAboutContent() {\n loadContent(\"about\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates arr of requestBodies for given section
function requestBodiesSection(section) { let sectionRequests = []; // Copy request body object so we can pass new reference // Aka not change the old object accident let copyDR = defaultRequest; let copyDCG = defaultChannelGrouping; let copyTop10 = top10Articles; let copySocial = socialNetwork; // Adds pagePath filter to default request body sectionRequests.push(addPagePathLevel1Filter(section, copyDR)); sectionRequests.push(addPagePathLevel1Filter(section, copyDCG)); sectionRequests.push(addPagePathLevel1Filter(section, copyTop10)); sectionRequests.push(addPagePathLevel1Filter(section, copySocial)); return sectionRequests; }
[ "function jsonSections(sections, block) {\r\n\r\n return sections.map(function(section) {\r\n // Temporary inserting of partial\r\n var partial = section;\r\n if (partial.markup() && partial.markup().toString().match(/^[^\\n]+\\.(html|hbs)$/)) {\r\n partial.file = partial.markup().toString();\r\n partial.name = path.basename(partial.file, path.extname(partial.file));\r\n partial.file = path.dirname(block.filePath) + '/' + partial.file;\r\n partial.markupText = fs.readFileSync(partial.file, 'utf8');\r\n section.markup = function() {\r\n return partial.markupText;\r\n };\r\n }\r\n\r\n return {\r\n header: generateDescription(section.header(), {noWrapper: true}),\r\n description: generateDescription(section.description()),\r\n modifiers: jsonModifiers(section.modifiers()),\r\n deprecated: section.deprecated(),\r\n experimental: section.experimental(),\r\n reference: section.reference(),\r\n markup: section.markup() ? section.markup().toString() : null\r\n };\r\n });\r\n}", "function extractBodiesData() {\n var currentArgs = [];\n var beginIndex = 0;\n var endIndex;\n for (var i = 0; i < injectable_bodies.length; i++) {\n //an array with names and a function\n currentArgs = injectable_bodies[i];\n endIndex = beginIndex + currentArgs.length - 1;\n\n bodiesData.push({\n \"servicesNames\": all_but_last(currentArgs),\n \"beginIndex\": beginIndex,\n \"endIndex\": endIndex,\n \"bodyFunction\": currentArgs[currentArgs.length - 1]\n });\n\n beginIndex = endIndex;\n }\n }", "getRequestBodiesFromConfig(documentationConfig) {\n const requestBodies = {};\n if (!documentationConfig.requestModels) {\n throw new Error(`Required requestModels in: ${JSON.stringify(documentationConfig, null, 2)}`);\n }\n // Does this event have a request model?\n if (documentationConfig.requestModels) {\n // For each request model type (Sorted by \"Content-Type\")\n for (const requestModelType of Object.keys(documentationConfig.requestModels)) {\n // get schema reference information\n const requestModel = this.config.models.filter((model) => model.name === documentationConfig.requestModels[requestModelType]).pop();\n if (requestModel) {\n const reqModelConfig = {\n schema: {\n $ref: `#/components/schemas/${documentationConfig.requestModels[requestModelType]}`,\n },\n };\n this.attachExamples(requestModel, reqModelConfig);\n const reqBodyConfig = {\n content: {\n [requestModelType]: reqModelConfig,\n },\n };\n if (documentationConfig.requestBody && 'description' in documentationConfig.requestBody) {\n reqBodyConfig.description = documentationConfig.requestBody.description;\n }\n utils_1.merge(requestBodies, reqBodyConfig);\n }\n }\n }\n return requestBodies;\n }", "function sectionBuilder(sectionName) {\n let section = elementBuilder(\"section\", sectionName, body);\n section.setAttribute(\"id\", sectionName);\n let sectionContainer = elementBuilder(\"div\", \"container\", section);\n let sectionRow = elementBuilder(\"div\", \"row\", sectionContainer);\n let sectionElements = [section, sectionContainer, sectionRow];\n return sectionElements;\n}", "createSections () {\n\n var sectionEl;\n var sectionData;\n var arr = [];\n\n for (var sectionId in this.sectionsData) {\n\n // current section's data\n sectionData = this.sectionsData[sectionId];\n\n // create section wrapper now to prevent having go through background-loading\n // HTML strings to dummy elements, just to be able append HTML. This also prevents\n // overwriting issues when using innerHTML = '<string>'.\n sectionEl = document.createElement('section');\n sectionEl.style.visibility = 'hidden';\n sectionEl.style.display = 'none';\n sectionEl.id = sectionId;\n\n // pass data to populate newly created section\n var section = new SectionFactory( sectionId, sectionData );\n\n // active sections must have an id, and if not, there was an issue with creation.\n if (section.id) {\n\n // SectionController creates top section element, but sections classes\n // need reference to it to inject HTML themselves.\n if (section.assignParentContainer) section.assignParentContainer(sectionEl);\n\n // add section wrapper to DOM\n this.viewContainer.appendChild(sectionEl);\n }\n\n // store list of active sections\n arr.push(section);\n }\n\n return arr;\n }", "function partial_section_builder (sectionKey, sectionObj){\r\n\r\n\tthis.sectionHTMLTag = new Object(); // use this to avoid other conflicts\r\n\t// var HTML_Section = \"HTML\" + sectionKey;\r\n\t// Locate the appropriate HTML tag to insert the CV data to\r\n\tfor (var nextVar in sectionObj) {\r\n\t\t// console.log(sectionKey, nextVar, sectionObj[nextVar]);\r\n\t\t// if the HTML is tag is found as a var add to this var directly\r\n\t\tvar tagName = \"HTML\" + nextVar;\r\n\t\tif (HTMLObject.hasOwnProperty(tagName) && typeof sectionObj[nextVar] !== \"object\" ) { // do this for items that would have a value.\r\n\t\t\t// create additional properties for the new html object created above\r\n\t\t\t// treat location as a special object\r\n\t\t\tsectionHTMLTag[tagName] = HTMLObject[tagName].replace(\"%data%\", sectionObj[nextVar]);\r\n\t\t}\r\n\t\telse { //analyse and build the strings where there are objects in concern.. first the location information\r\n\t\t\t// console.log(typeof sectionObj[nextVar] === \"object\"); console.log(nextVar === \"location\" ); console.log(HTMLObject.hasOwnProperty(tagName) );\r\n\t\t\tif (typeof sectionObj[nextVar] === \"object\" && HTMLObject.hasOwnProperty(tagName) ) { // this is an object see if you can find a htmlTag for it. then build it\r\n\t\t\t\t// pass this to the object array builder function and create a new array element on the section tag to add this.\r\n\t\t\t\tvar objTag = build_objArray_string(sectionObj[nextVar], tagName);\r\n\t\t\t\tthis.sectionHTMLTag[nextVar] = new Array();\r\n\t\t\t\tfor (var objProp in objTag) {\r\n\t\t\t\t\tthis.sectionHTMLTag[nextVar].push(objTag[objProp]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn this.sectionHTMLTag;\r\n}", "function getBodyArray() {\n body = [];\n\n // Determine how many [WORK,CARRY,MOVE,MOVE] we can fit.\n // WORK = 100\n // CARRY = 50\n // MOVE = 50\n availableBodyChunks = Math.floor(totalEnergy / 250);\n\n for (let i = 0; i < availableBodyChunks; i++) {\n body.push(WORK);\n body.push(CARRY);\n body.push(MOVE);\n body.push(MOVE);\n }\n\n return body;\n }", "async handleNewSection() {\n const sections = await this.request.getSections()\n sections.forEach(section => new Section(section, this.dl))\n }", "function getSections() {\n $.getJSON(sectionRequest)\n .done(function(data){\n $.each(data.response.results, function (ind, val) {\n sectionIds.push(val.id);\n sectionNames.push(val.webTitle);\n });\n $.each(sectionIds, function (ind, val){\n sectionAssoc[val] = sectionNames[ind];\n });\n $.each(sectionAssoc, function (key, val){\n autocompleteArray.push({ value: val, data: key});\n });\n sectionIds.sort();\n populateSections();\n })\n .fail(function(){\n alert('Error Contacting Server - Section Name Request');\n });\n // draft empty result check\n // NON FUNCTIONAL\n // $.each(sectionIds, function (ind, val){\n // request[1] = val;\n // request[3] = 1;\n // thisRequest = request.join('');\n // $.getJSON(thisRequest)\n // .done(function(data) {\n // if (data.response.total === 0) {\n // emptySections.push(val);\n // console.log(emptySections);\n // }\n // })\n // .fail(function(){\n // alert('Error Contacting Server - Empty Section Test');\n // });\n // });\n }", "function createSection() {\n const i = document.getElementsByTagName('section').length + 1;\n const sect = document.createElement('section');\n sect.setAttribute('id', `section${i}`);\n sect.setAttribute('data-nav', `Section ${i}`);\n document.getElementById('mainBody').appendChild(sect);\n createContainer(i);\n createHeader(i);\n createPara(i);\n createPara2(i);\n updateNav();\n}", "function nodeSections (node) {\n return (node.sections || []).concat(node.headers || [])\n}", "static merge(...requestBodies) {\n const result = new RequestBody();\n return requestBodies.reduce((base, requestBody) => {\n base.stringData = requestBody.stringData || base.stringData;\n Object.assign(base.objectData, requestBody.objectData);\n return base;\n }, result);\n }", "function createApiCallBody() {\n\t\tconst requestBody = selectedDevice.zones.map(zone => {\n\t\t\treturn {\n\t\t\t\tid: zone.id,\n\t\t\t\tsortOrder: 1\n\t\t\t}\n\t\t})\n\t\treturn requestBody;\n\t}", "createSections() {\n for(let s = 0; s < 5; s++) {\n let sectionElem = document.createElement(\"section\");\n this.area.appendChild(sectionElem);\n }\n }", "section(buffer, def) {\n const ret = [];\n for (let n = 0; n < def.records; n++) {\n const offset = def.record_length * n;\n ret.push(this.record(buffer.slice(offset, offset + def.record_length), def, n));\n }\n return ret;\n }", "function getReqBody(p1, p2) {\n if (p2) {\n return [\n {\n \"username\": `username${p1}`,\n \"firstName\": `firstName${p1}`,\n \"lastName\": `lastName${p1}`\n },\n {\n \"username\": `username${p2}`,\n \"firstName\": `firstName${p2}`,\n \"lastName\": `lastName${p2}`\n }\n ];\n };\n if (p1) {\n return {\n \"username\": `username${p1}`,\n \"firstName\": `firstName${p1}`,\n \"lastName\": `lastName${p1}`\n };\n };\n return {\n \"username\": \"username\",\n \"firstName\": \"firstName\",\n \"lastName\": \"lastName\"\n };\n}", "function normalizePage(content) {\n var data = {\n \"head-start\": [],\n \"head\": [],\n \"head-end\": [],\n body: []\n };\n\n if (typeof content === \"string\") {\n data.body.push(content);\n } else {\n [\"head-start\", \"head\", \"head-end\", \"body\"].forEach(function (section) {\n var sectionContent = content[section];\n if (!sectionContent) {\n return;\n }\n\n if (!_.isArray(sectionContent)) {\n data[section].push(sectionContent);\n } else {\n data[section] = sectionContent;\n }\n });\n }\n\n return data;\n}", "function bodyPartGenerator(response, bodyPart, rotationPart){\n var generatedPart = {\n element: response.select(bodyPart),\n rotationPointX: response.select(rotationPart).attr(\"cx\"),\n rotationPointY: response.select(rotationPart).attr(\"cy\")\n };\n \n return generatedPart;\n}", "function getSections() {\n \n if (!mocksUtils.checkAuth()) {\n return [401, null, null];\n }\n\n var sections = [\n { name: \"Content\", cssclass: \"icon-umb-content\", alias: \"content\" },\n { name: \"Media\", cssclass: \"icon-umb-media\", alias: \"media\" },\n { name: \"Settings\", cssclass: \"icon-umb-settings\", alias: \"settings\" },\n { name: \"Developer\", cssclass: \"icon-umb-developer\", alias: \"developer\" },\n { name: \"Users\", cssclass: \"icon-umb-users\", alias: \"users\" },\n { name: \"Developer\", cssclass: \"icon-umb-developer\", alias: \"developer\" },\n { name: \"Users\", cssclass: \"icon-umb-users\", alias: \"users\" }\n ];\n \n return [200, sections, null];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fun??o para validar a pesquisa por faixa de Quadra pesquisa v?lida se os Setores Comeciais forem iguais e o n?mero inicial for menor ou igual ao final
function validaPesquisaFaixaQuadra(){ var form = document.ImovelOutrosCriteriosActionForm; retorno = true; if(form.quadraOrigemID.value != form.quadraDestinoID.value){ if(form.setorComercialOrigemCD.value != setorComercialDestinoCD.value){ retorno = false; alert("Para realizar a pesquisa por faixa de Quadras as Localidade e os Setores Comerciais iniciais e finais devem ser iguais."); form.quadraDestinoID.focus(); } } if((form.quadraOrigemID.value != "" ) && (form.quadraOrigemID.value > form.quadraDestinoID.value)){ alert("O n?mero da Quadra Final deve ser maior ou igual ao Inicial."); form.quadraDestinoID.focus(); retorno = false; } return retorno; }
[ "function validaPesquisaFaixaSetor(){\r\n\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\t\r\n\tretorno = true;\r\n\t\r\n\tif(form.setorComercialOrigemCD.value != form.setorComercialDestinoCD.value){\r\n\t\tif(form.localidadeOrigemID.value != form.localidadeDestinoID.value){\r\n\t\t\r\n\t\t\talert(\"Para realizar a pesquisa por faixa de Setor Comercial as Localidade inicial e final devem ser iguais.\");\r\n\t\t\tform.setorComercialDestinoID.focus();\r\n\t\t\tretorno = false;\r\n\t\t}\t\t\r\n\t}\r\n\t\r\n\tif((form.setorComercialOrigemCD.value != \"\" )\r\n\t\t&& (form.setorComercialOrigemCD.value > form.setorComercialDestinoCD.value)){\r\n\t\talert(\"O c?digo do Setor Comercial Final deve ser maior ou igual ao Inicial.\");\r\n\t\t\tform.setorComercialDestinoID.focus();\r\n\t\t\tretorno = false;\r\n\t}\r\n\t\r\n\treturn retorno;\r\n\r\n}", "function validaced(){\n \n\n \n /**\n * Algoritmo para validar cedulas de Ecuador\n * @Author : Victor Diaz De La Gasca.\n * @Fecha : Quito, 15 de Marzo del 2013 \n * @Email : vicmandlagasca@gmail.com\n * @Pasos del algoritmo\n * 1.- Se debe validar que tenga 10 numeros\n * 2.- Se extrae los dos primero digitos de la izquierda y compruebo que existan las regiones\n * 3.- Extraigo el ultimo digito de la cedula\n * 4.- Extraigo Todos los pares y los sumo\n * 5.- Extraigo Los impares los multiplico x 2 si el numero resultante es mayor a 9 le restamos 9 al resultante\n * 6.- Extraigo el primer Digito de la suma (sumaPares + sumaImpares)\n * 7.- Conseguimos la decena inmediata del digito extraido del paso 6 (digito + 1) * 10\n * 8.- restamos la decena inmediata - suma / si la suma nos resulta 10, el decimo digito es cero\n * 9.- Paso 9 Comparamos el digito resultante con el ultimo digito de la cedula si son iguales todo OK sino existe error. \n */\n\n var cedula = document.getElementById('cedula').value;\n\n //Preguntamos si la cedula consta de 10 digitos\n if(cedula.length == 10){\n \n //Obtenemos el digito de la region que sonlos dos primeros digitos\n var digito_region = cedula.substring(0,2);\n \n //Pregunto si la region existe ecuador se divide en 24 regiones\n if( digito_region >= 1 && digito_region <=24 ){\n \n // Extraigo el ultimo digito\n var ultimo_digito = cedula.substring(9,10);\n\n //Agrupo todos los pares y los sumo\n var pares = parseInt(cedula.substring(1,2)) + parseInt(cedula.substring(3,4)) + parseInt(cedula.substring(5,6)) + parseInt(cedula.substring(7,8));\n\n //Agrupo los impares, los multiplico por un factor de 2, si la resultante es > que 9 le restamos el 9 a la resultante\n var numero1 = cedula.substring(0,1);\n var numero1 = (numero1 * 2);\n if( numero1 > 9 ){ var numero1 = (numero1 - 9); }\n\n var numero3 = cedula.substring(2,3);\n var numero3 = (numero3 * 2);\n if( numero3 > 9 ){ var numero3 = (numero3 - 9); }\n\n var numero5 = cedula.substring(4,5);\n var numero5 = (numero5 * 2);\n if( numero5 > 9 ){ var numero5 = (numero5 - 9); }\n\n var numero7 = cedula.substring(6,7);\n var numero7 = (numero7 * 2);\n if( numero7 > 9 ){ var numero7 = (numero7 - 9); }\n\n var numero9 = cedula.substring(8,9);\n var numero9 = (numero9 * 2);\n if( numero9 > 9 ){ var numero9 = (numero9 - 9); }\n\n var impares = numero1 + numero3 + numero5 + numero7 + numero9;\n\n //Suma total\n var suma_total = (pares + impares);\n\n //extraemos el primero digito\n var primer_digito_suma = String(suma_total).substring(0,1);\n\n //Obtenemos la decena inmediata\n var decena = (parseInt(primer_digito_suma) + 1) * 10;\n\n //Obtenemos la resta de la decena inmediata - la suma_total esto nos da el digito validador\n var digito_validador = decena - suma_total;\n\n //Si el digito validador es = a 10 toma el valor de 0\n if(digito_validador == 10)\n var digito_validador = 0;\n\n //Validamos que el digito validador sea igual al de la cedula\n if(digito_validador == ultimo_digito){\n console.log('la cedula:' + cedula + ' es correcta');\n }else{\n document.getElementById('cedula').value=\"\";\n console.log('la cedula:' + cedula + ' es incorrecta');\n }\n \n }else{\n // imprimimos en consola si la region no pertenece\n document.getElementById('cedula').value = \"Este formato no es válido\";\n /*alert(\"ced no es ecuatoriana\");*/\n /*console.log('Esta cedula no pertenece a ninguna region');*/\n }\n }else{\n //imprimimos en consola si la cedula tiene mas o menos de 10 digitos\n document.getElementById('cedula').value = \"\";\n /*alert(\"Formato incprrecto\");*/\n /*console.log('Esta cedula tiene menos de 10 Digitos');*/\n } \n \n}", "function cuantasMinas(tab,x,y){\n minasEnc=0;\n //Comprobamos adyacentes\n if(x>0){\n if(tab[x-1][y]==-1){\n minasEnc++;\n }\n }\n \n \n if(x<tab.length-1){\n if(tab[x+1][y]==-1){\n minasEnc++;\n }\n }\n if(y>0){\n if(tab[x][y-1]==-1){\n minasEnc++;\n }\n }\n \n \n if(y<tab[x].length-1){\n if(tab[x][y+1]==-1){\n minasEnc++;\n }\n }\n \n \n if(y>0 && x>0){\n if(tab[x-1][y-1]==-1){\n minasEnc++;\n }\n }\n if(y>0 && x<tab.length-1){\n if(tab[x+1][y-1]==-1){\n minasEnc++;\n }\n }\n \n \n if(x>0 && y<tab[x].length-1){\n if(tab[x-1][y+1]==-1){\n minasEnc++;\n }\n }\n \n \n if(x<tab.length-1 && y<tab[x].length-1){\n if(tab[x+1][y+1]==-1){\n minasEnc++;\n }\n }\n \n \n \n \n \n //Devolvemos el resultado\n return minasEnc;\n}", "function checkSqu(squ){\n let firstColInSqu , firstRowInSqu;\n \n //get the first row and col of square\n if(squ == 0) {firstRowInSqu = 0 ; firstColInSqu = 0;}\n else if(squ == 1){firstRowInSqu = 0 ; firstColInSqu = 3;}\n else if(squ == 2){firstRowInSqu = 0 ; firstColInSqu = 6;}\n else if(squ == 3){firstRowInSqu = 3 ; firstColInSqu = 0;}\n else if(squ == 4){firstRowInSqu = 3 ; firstColInSqu = 3;}\n else if(squ == 5){firstRowInSqu = 3 ; firstColInSqu = 6;}\n else if(squ == 6){firstRowInSqu = 6 ; firstColInSqu = 0;}\n else if(squ == 7){firstRowInSqu = 6 ; firstColInSqu = 3;}\n else {firstRowInSqu = 6 ; firstColInSqu = 6;}\n\n \n //go through all columns and rows in the same sqaure and check if there is dublicated number\n let num = [false,false,false,false,false,false,false,false,false];\n for(let row = firstRowInSqu ; row < firstRowInSqu + 3; row++){\n for(let col = firstColInSqu ; col < firstColInSqu + 3 ; col++){\n try{\n if(num[document.getElementById(`${square}${row}${row}`).value - 1] && document.getElementById(`${square}${row}${row}`).value != \"\"){\n return false;\n }\n else{\n num[document.getElementById(`${square}${row}${row}`).value - 1] = true;\n }\n }\n catch(e){\n }\n }\n }\n return true;\n}", "function validarDiagonales(i, j) {\r\n\r\n if (i != 0 && j != 0) {\r\n i--;\r\n j--;\r\n if (minas[i][j] >= 1 && minas[i][j] <= 8) {\r\n $('#' + i + 'p' + j).attr('class', 'bloque' + minas[i][j]);\r\n minas[i][j] = minas[i][j] * 100;\r\n }\r\n i++;\r\n j++;\r\n }\r\n\r\n if (i != (espacioNivel - 1) && j != (espacioNivel - 1)) {\r\n i++;\r\n j++;\r\n if (minas[i][j] >= 1 && minas[i][j] <= 8) {\r\n $('#' + i + 'p' + j).attr('class', 'bloque' + minas[i][j]);\r\n minas[i][j] = minas[i][j] * 100;\r\n }\r\n i--;\r\n j--;\r\n }\r\n\r\n if (i != (espacioNivel - 1) && j != 0) {\r\n i++\r\n j--;\r\n if (minas[i][j] >= 1 && minas[i][j] <= 8) {\r\n $('#' + i + 'p' + j).attr('class', 'bloque' + minas[i][j]);\r\n minas[i][j] = minas[i][j] * 100;\r\n }\r\n i--;\r\n j++;\r\n }\r\n\r\n if (i != 0 && j != (espacioNivel - 1)) {\r\n i--;\r\n j++;\r\n if (minas[i][j] >= 1 && minas[i][j] <= 8) {\r\n $('#' + i + 'p' + j).attr('class', 'bloque' + minas[i][j]);\r\n minas[i][j] = minas[i][j] * 100;\r\n }\r\n i++;\r\n j--;\r\n }\r\n\r\n}", "function verificar_items_iguales()\r\n{ \r\n var aux = false\r\n for (var col=0;col<7;col++)\r\n {\r\n for (var fil=1;fil<6;fil++)\r\n { \r\n if (tablero[col][fil] == tablero[col][fil+1] && tablero[col][fil] == tablero[col][fil-1])\r\n {\r\n tablero_check[col][fil] = 0 \r\n tablero_check[col][fil+1] = 0 \r\n tablero_check[col][fil-1] = 0 \r\n aux = true \r\n }\r\n }\r\n } \r\n\r\n for (var fil=0;fil<7;fil++)\r\n {\r\n for (var col=1;col<6;col++)\r\n { \r\n if (tablero[col][fil] == tablero[col+1][fil] && tablero[col][fil] == tablero[col-1][fil])\r\n {\r\n tablero_check[col][fil] = 0 \r\n tablero_check[col+1][fil] = 0 \r\n tablero_check[col-1][fil] = 0 \r\n aux = true \r\n }\r\n }\r\n } \r\n return aux \r\n}", "trySolveByCrossGroup(grid,r,c) {\n let sqrIndex = this.getIndex(r,c);\n let grpIndex = this.getGroupIndex(r, c);\n\n // Get all possible values not in Group, row, or Column.\n var indexSet = this.possibleValues.difference(new Set(this.getGroup(grid,r,c)));\n indexSet = indexSet.difference(new Set(this.getRow(grid,r)));\n indexSet = indexSet.difference(new Set(this.getCol(grid,c)));\n\n let rStart = Math.floor(grpIndex / 3) * 3;\n let cStart = (grpIndex % 3) * 3;\n\n for (let row = rStart; row < rStart + 3; row++) {\n for (let col = cStart; col < cStart + 3; col++) {\n let index = this.getIndex(row,col)\n \n // Only null value columns / rows can be a possible placement for indexSet, lets try to eliminate these options\n if (grid[index] === null &&\n this.getGroupIndex(row,col) === grpIndex &&\n index !== sqrIndex) \n {\n //console.log(\"Null Square: \" + row + ':' + col);\n let squareSet = new Set(this.getRow(grid,row))\n .union(new Set(this.getCol(grid,col)));\n\n indexSet = indexSet.intersection(squareSet); // non intersecting values cannot be placed reliably, filter possibles\n }\n }\n }\n\n if (indexSet.size === 1) {\n //console.log('Solved - ' + r + ':' + c + ' = ' + indexSet.getByIndex(0));\n grid[this.getIndex(r,c)] = indexSet.getByIndex(0);\n return true;\n } else {\n return false;\n }\n }", "function validirajProizvod(ime1 ='', kolicina1, cijena1, kategorija1, popust1, barKod1 = '')\n{\n //Provjeravamo da li su uopće poslane vrijednosti u query-ju\n if(ime1 == null || kolicina1 == null || cijena1 == null || kategorija1 == null || popust1 == null || barKod1 == null)\n {\n console.log(\"Neispravni podaci!\");\n return false;\n }\n \n //Provjeravamo ispravnost unesenih numeričkih vrijednosti\n if (Number.isInteger(kolicina1) == false || kolicina1 < 0 || \n !(typeof cijena1 == 'number') || !(typeof popust1 == 'number') ||\n Number.isInteger(kategorija1) == false)\n {\n console.log(\"Neispravni podaci!\");\n return false;\n }\n if (!(typeof ime1 == 'string') || !(typeof barKod1 == 'string') || ime1.length == 0 || barKod1.length == 0)\n {\n console.log(\"Neispravni podaci!\");\n return false;\n }\n\n console.log(\"Ispravna validacija podataka\");\n return true;\n}", "function validSolution(puzzleCpy){\n var rowValues = 0;\n var colValues = 0;\n for(var i = 0; i < gridSize; i++){\n rowValues = 0;\n colValues = 0;\n \n for(var j = 0; j < gridSize; j++){\n var letterInd1 = letterArr.indexOf(puzzleCpy[i][j])\n if(letterInd1 > -1){\n rowValues ^= 1<<letterInd1;\n }\n var letterInd2 = letterArr.indexOf(puzzleCpy[j][i])\n if(letterInd2 > -1){\n colValues ^= 1<<letterInd2;\n }\n }\n \n if(rowValues < maxOptionsByte || colValues < maxOptionsByte){\n return false;\n }\n }\n return true;\n }", "function checkValida(ficha){\n var valida=false\n for (i=0; i<fichasValidas.length; i++){\n for (j=0; j<fichasValidas[i].length; j++){ \n\n if(fichasValidas[i][j].coord[0]*anchoficha==ficha.coord[0]\n &&fichasValidas[i][j].coord[1]*altoficha==ficha.coord[1]\n &&ficha.rot==i){\n valida=true;\n }\n \n }\n }\n return valida;\n }", "function movimentoValido(m, i, j, k){\n if(k === 0) return true;\n\n // linha\n for(let a = 0; a < qtdX; a++)\n if(m[i][a] === k) return false;\n\n // coluna\n for(let a = 0; a < qtdY; a++)\n if(m[a][j] === k) return false;\n\n // quadrado\n let I = Math.trunc(i/3)*3;\n let J = Math.trunc(j/3)*3;\n for(let a = I; a < I+3; a++)\n for(let b = J; b < J+3; b++)\n if(m[a][b] === k) return false;\n\n return true;\n}", "function verificarCantHuespXReserva(cantPersonas) {\n //traer los textos del select, buscar con indexOf si tienen single, double,\n // etc y comparar de acuerdo a eso con la cant de huespedes ingresada\n /* Para obtener el texto del select donde esta el precio */\n\n var capacidad; //para guardar la capacidad seleccionada\n var comboCap = document.formAltaReserva.habitacionReserva;\n var seleccionado = comboCap.options[comboCap.selectedIndex].text; //recupero el texto del select\n\n if (seleccionado.indexOf('Single')) {\n capacidad = 1;\n } else if (seleccionado.indexOf('Doble')) {\n capacidad = 2;\n } else if (seleccionado.indexOf('Triple')) {\n capacidad = 3;\n } else if (seleccionado.indexOf('Múltiple')) {\n capacidad = 8;\n }\n\n alert(capacidad + \" \" + cantPersonas);\n\n if (cantPersonas > capacidad) {\n alert('La cantidad de personas supera la capacidad de la habitacion');\n return false;\n }\n if (cantPersonas <= capacidad) {\n return true;\n }\n\n\n}", "function checkSquares(){\n\n\tfor(let i = 0; i < 9; i++){\n\t\tlet sq = []\n\t\tfor(let j = 0; j < 3; j++){\n\t\t\tfor(let k = 0; k < 3; k++){\n\n\t\t\t\tlet superRow = Math.floor(i / 3)\n\t\t\t\tlet superCol = Math.floor(i % 9) % 3\n\t\t\t\tlet id = (superRow * 27) + (j * 9) + (superCol * 3) + k\n\t\t\t\tlet n = parseInt(document.getElementById(id).innerHTML)\n\t\t\t\tsq.push(n)\n\t\t\t\tif(n < 1 || n > 9 || isNaN(n)){\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(sq)\n\n\t\tif(!allDiff(sq)){\n\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function possElim() {\n for (x = 1; x <= 9; x++) {\n var nA = gameArr.filter(n => n.quad === x);\n var quadReq = [\n { val: 1, rows: [], columns: [] },\n { val: 2, rows: [], columns: [] },\n { val: 3, rows: [], columns: [] },\n { val: 4, rows: [], columns: [] },\n { val: 5, rows: [], columns: [] },\n { val: 6, rows: [], columns: [] },\n { val: 7, rows: [], columns: [] },\n { val: 8, rows: [], columns: [] },\n { val: 9, rows: [], columns: [] }\n ];\n\n // get all squares in quadrant\n for (var i = 0; i < 9; i++) {\n if (nA[i].val !== 0) {\n quadReq.splice(quadReq.map(e => e.val).indexOf(nA[i].val), 1);\n }\n }\n\n // fill quadReq array with possible rows and columns for each required value in the quadrant\n quadReq.forEach(function(req) {\n nA.forEach(function(n) {\n if (n.possible) {\n n.possible.forEach(function(poss) {\n if (req.val === poss) {\n req.rows.push(n.row);\n req.columns.push(n.col);\n }\n });\n }\n });\n\n req.rows = Array.from(new Set(req.rows));\n req.columns = Array.from(new Set(req.columns));\n\n // remove conflicting possibilities from other squares in the row in different quadrants\n if (req.rows.length === 1) {\n gameArr.forEach(function(square) {\n if (\n square.row === req.rows[0] &&\n square.quad != x &&\n square.possible\n ) {\n var index = square.possible.indexOf(req.val);\n if (index >= 0) {\n square.possible.splice(index, 1);\n pE++;\n }\n }\n });\n }\n\n // remove conflicting possibilities from other squares in the column in different quadrants\n if (req.columns.length === 1) {\n gameArr.forEach(function(square) {\n if (\n square.col === req.columns[0] &&\n square.quad != x &&\n square.possible\n ) {\n var index = square.possible.indexOf(req.val);\n if (index >= 0) {\n square.possible.splice(index, 1);\n pE++;\n }\n }\n });\n }\n });\n }\n\n // If there are two squares with only two numbers, which are the same, those numbers can be removed from every other square in the quadrant\n}", "function alturaTraianguloIsosceles(trianguloGrandeLadoA, trianguloGrandeLadoB, trianguloGrandeBase) {\n if(trianguloGrandeLadoA != trianguloGrandeLadoB) {\n console.error(\"Los lados a y b no son iguales\")\n }else {\n let trianguloPequeñoLadoA; //pendiente\n const trianguloPequeñoLadoB = trianguloGrandeBase / 2;\n const trianguloPequeñoLadoBase = trianguloGrandeLadoA;\n\n const trianguloPequeñoLadoBCuadrado = trianguloPequeñoLadoB * trianguloPequeñoLadoB;\n\n const trianguloPequeñoBaseCuadrado = trianguloPequeñoBase * trianguloPequeñoBase;\n\n const trianguloPequeñoLadoA = math.sqrt(trianguloPequeñoBaseCuadrado - trianguloPequeñoLadoBCuadrado);\n\n const trianguloGrandeAltura = trianguloPequeñoLadoA;\n return trianguloGrandeAltura;\n }\n}", "function validarDisparoEnemigo(x,y) {\n //matriz[x][y].nombre!='va'\n if(matriz[x][y].nombre==='h'){\n return true;\n }\n else{\n return false;\n }\n}", "isPossibleValueValid(possibleValue,currentSquare){\r\n \r\n let isValid = false\r\n let currentRow = this.grid.gridObj[currentSquare[0]]\r\n let currentCol = this.grid.getColByCoordinate(currentSquare)\r\n \r\n if(!currentRow.includes(possibleValue)){\r\n if(!currentCol.includes(possibleValue)){\r\n let currentBox = this.grid.getBox(currentSquare, false)\r\n \r\n if(!currentBox.includes(possibleValue)){\r\n isValid = true\r\n }\r\n }\r\n }\r\n return isValid\r\n }", "function valid_sudoku(table) {\n for (let row = 0; row < table.length; row++) {\n let rowHash = {};\n for (let num of table[row]) {\n if (isNaN(parseInt(num))) {\n continue;\n }\n if (rowHash[num]) {\n return false;\n } else {\n rowHash[num] = 1;\n }\n }\n }\n for (let col = 0; col < table.length; col++) {\n let colHash = {};\n for (let i = 0; i < table.length; i++) {\n let num = table[i][col];\n if (isNaN(parseInt(num))) {\n continue;\n }\n if (colHash[num]) {\n return false;\n } else {\n colHash[num] = 1;\n }\n }\n }\n // const numOfRows = 9;\n // const numOfCols = 9;\n //TODO sq of rows\n for (let rowStart = 0; rowStart < 9; rowStart += 3) {\n for (let colStart = 0; colStart < 9; colStart += 3) {\n let boxHash = {};\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n let currNum = table[rowStart + i][colStart + j];\n if (isNaN(parseInt(currNum))) {\n continue;\n }\n if (boxHash[currNum]) {\n return false;\n } else {\n boxHash[currNum] = 1;\n }\n }\n }\n }\n }\n return true;\n}", "validValue() {\n\n /*\n Test for checking if the value exists in the same row or column\n */\n for (let i = 0; i < 9; i++) {\n\n if(gridCells[this.r][i].value == this.value && this.c != i){\n return false;\n }\n\n if(gridCells[i][this.c].value == this.value && this.r != i){\n return false;\n }\n\n }\n\n\n\n /*\n Test for checking if the value exists in the same 9x9 square\n */\n\n let r = parseInt(this.r / 3) * 3;\n let c = parseInt(this.c / 3) * 3;\n\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n\n if(gridCells[(r+i)][c+j].value == this.value && gridCells[(r+i)][c+j] != this){\n return false;\n }\n }\n }\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sends the chat message to the server
function sendMessage() { let message = data.value; data.value = ""; // tell server to execute 'sendchat' and send along one parameter socket.emit("sendchat", message); }
[ "function sendMessage() {\n \t\tvar message = data.value;\n\t\tdata.value = \"\";\n\t\t// tell server to execute 'sendchat' and send along one parameter\n\t\tsocket.emit('sendchat', message);\n\t}", "function sendMessage() {\n let message = data.value;\n data.value = \"\";\n // tell server to execute 'sendchat' and send along one parameter\n socket.emit(\"sendchat\", message);\n}", "function sendChat (message){\n UI.addChatMessage(\"me: \"+message);\n rtc._socket.send(JSON.stringify({\n eventName:\"chat_msg\",\n data:{\n msg:message,\n room:App.getRoom(),\n nick:App.getNick()\n }\n }),function(err){\n console.log(err);\n });\n }", "function sendMessage() {\n\t \tvar msg = chatinput.val();\n\n\t \tif (!msg) {\n\t \t\treturn;\n\t \t}\n\n\t \tif (msg == 'clear') {\n\t \t\tchatcontent.text('');\n\t \t\tchatinput.val('');\n\t \t\treturn;\n\t \t}\n\n\t \tif (name != chatuser.val()) {\n\t \t\tnameChange();\n\t \t}\n\n\t \tsocket.emit('message', { text: msg, points: points });\n\t \tchatinput.val('');\n\t }", "function sendMessage() {\n text = $('#txtMsg').val();\n if (text == \"\") return;\n $('#txtMsg').val('');\n $.post('/chat/send_chat', { msg: text });\n getNewMessages();\n }", "function PlayerChat( message ){ \n\tsocket.emit( \"chat up\", { 'sessionId': sessionId, 'message': message, 'channelId': currentChannel } );\n}", "function sendChat(text) {\n let chatRequest = {\n type: \"chat\",\n text: text,\n gameID: currentGameID,\n playerID: currentPlayerID\n }\n\n socket.send(JSON.stringify(chatRequest));\n}", "function SendToChat(text) {\n client.say(current_channel, text);\n}", "function _send(message, chatstate) {\n var elem = $msg({\n to: contact.jid,\n from: jtalk.me.jid,\n type: \"chat\"\n });\n\n if (message) elem.c(\"body\", message);\n if (chatstate) {\n elem.c(chatstate, {xmlns: Strophe.NS.CHATSTATE});\n }\n\n connection.send(elem);\n }", "function sendMessage() {\n if (angular.isDefined(chat.messageText) && chat.messageText !== \"\") {\n $wamp.call('com.chat.talkto.'+chat.currentConversation.guid, [chat.messageText, {username:chat.user.username, guid:chat.user.guid}]).then(\n function(res) {\n chat.currentConversation.messages.push({\n from: chat.user.username,\n time: moment().format('hh:mm:ss'),\n message: chat.messageText\n });\n\n scrollToLastMessage();\n \n chat.messageText = \"\";\n $log.info(res);\n }\n ).catch(function(error) {\n $log.info(error);\n });\n }\n }", "function chatSend (str) {\n\t\t\td20.textchat.doChatInput(str);\n\t\t}", "function sendMessage(data) {\r\n //Hacemos que el servidor emita el mensaje hacia todos los clientes\r\n //para que se sincronicen:\r\n socket.broadcast.emit(\"sendMessage\", {mensaje: data.mensaje, username: data.username});\r\n }", "send() {\n let data = {\n text: this.text,\n user: this.user,\n room: this.room\n };\n\n socket.emit('send-message', {\n message: data\n });\n }", "function sendMessageToServer(message) {\n socket.send(message);\n }", "function sendMessageToServer(message) {\n socket.send(message);\n }", "function sendMessage(message) {\n chat.perform(\"send_message\", message);\n}", "function submitChat() {\n // Retrieve the chat text from the input\n const chatText = document.getElementById(\"chat-input\").value;\n\n // Clear the input field for the next message\n document.getElementById(\"chat-input\").value = \"\";\n\n // Emit the text and user to the server\n socket.emit(\"submitChat\", { chatText, chatUser });\n}", "function sendMessage() {\n // Create a new message object\n var message = {\n text: $scope.messageText\n };\n\n // Emit a 'chatMessage' message event\n PlaygroundService.emit('chatMessage', message);\n\n // Clear the message text\n $scope.messageText = '';\n }", "function sendChatMessage(message)\n {\n\t var httpRequest = new XMLHttpRequest();\n\t var jsonmsg = { \"message\" : message};\n\t httpRequest.open(\"POST\", \"http://localhost:3000/chats\", true);\n\t httpRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n\n\t chats.push(message);\n\n\t httpRequest.send(JSON.stringify(jsonmsg));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /team route to retrieve all the teams.
function getTeams(req, res) { //Query the DB and if no errors, send all the books const query = Team.find({}); query.exec((err, teams) => { if (err) res.send(err); //If no errors, send them back to the client res.json(teams); }); }
[ "function teams() {\n\t return $http.get(\n\t\t HygieiaConfig.local ? testTeamsRoute : (buildTeamsRoute))\n\t\t .then(function(response) {\n\t\t\treturn response.data;\n\t\t });\n\t}", "getAllTeams() {\n return new Promise((resolve, reject) => {\n const options = {\n method: 'GET',\n url: `${controllerUrl}/view`,\n headers: {}\n }\n request(options, (err, response, body) => {\n if (err || response.statusCode !== 200)\n return reject(err || response);\n if (response.statusCode === 200) {\n this.teams = body; // saves the request response.\n }\n resolve(response);\n });\n });\n }", "function getTeam(req, res) {\n Team.findById(req.params.id, (err, team) => {\n if (err) res.send(err);\n //If no errors, send it back to the client\n res.json(team);\n });\n}", "function getTeams() {\n $.get(\"/api/teams\", renderTeamList);\n}", "function getLeagueTeams(req, rsp,next) {\n debug(\"/teams for:\"+req.params.id);\n leaguesModel.getTeams(parseInt(req.params.id),(err, fixtures) => {\n if (err!==undefined) debug(\"/league read ERROR:\"+err);\n debug(\"/teams read:\"+fixtures[0]);\n rsp.render(\"teams\", {title: fixtures[0], fixtures: fixtures.fixtures })\n });\n}", "get teams() {\n return new TeamApi(this._client);\n }", "getGameListByTeam(team_id) {\n return this.http.get(gameUrl + '?teamid=' + team_id);\n }", "getTeams() {\n\t\treturn this.api.teams.get();\n\t}", "async getTeam () {\n\t\tthis.team = await this.request.data.teams.getById(this.id);\n\t\tif (!this.team) {\n\t\t\tthrow this.errorHandler.error('notFound', { info: 'team' });\n\t\t}\n\t}", "function loadTeams() {\n doAjax(TEAM_URL + '/get').then(data => {\n data.forEach(team => {\n console.log('Team ->', team.name);\n });\n });\n}", "function getTeams(req, res) {\n let parser = new FifaindexParser();\n let scraper = new Scraper();\n\n return new Promise((resolve, reject) => {\n let teams = [];\n let page = 1;\n\n // function wrapper to enable recursion\n const recursiveGet = page => {\n scraper.getContent(parser.getUrl(req.body.stars, req.body.overallMin, req.body.overallMax, req.body.teamType, page))\n .then(html => {\n teams = teams.concat(parser.parse(html));\n\n if (parser.more(html)) {\n recursiveGet(page + 1);\n } else {\n resolve(teams);\n }\n })\n .catch(error => {\n reject(error);\n });\n };\n\n recursiveGet(page);\n });\n}", "function getTeamList() {\n if (\"caches\" in window) {\n caches.match(ENDPOINT_EPL + \"teams\").then(function (response) {\n if (response) {\n response.json().then(function (data) {\n showTeamList(data);\n })\n }\n })\n }\n\n fetchAPI(ENDPOINT_EPL + \"teams\")\n .then(data => {\n showTeamList(data);\n })\n .catch(error);\n}", "async function getAllTeamMembers(req, res) {\n const { teamID } = req.params;\n console.log(teamID);\n try {\n const team = await teamsSchema_1.default.findOne({ _id: teamID });\n console.log('team', team);\n if (team) {\n const { members } = team;\n return res.status(200).json({\n message: `All members in ${team.teamName} team`,\n members: members,\n // team: team,\n });\n }\n }\n catch (err) {\n return res.status(400).json({\n error: err.message,\n });\n }\n}", "get allTeams () {\n const getter = this.github.teams.list({ org: this.repo.owner })\n .then(this.paginate.bind(this))\n .then(responses => {\n return responses.reduce((teams, res) => {\n return teams.concat(res.data)\n }, [])\n })\n Object.defineProperty(this, 'allTeams', getter)\n return getter\n }", "getTeamsFromTournament(tournament) {\n this.restClient.getTeams(tournament.id)\n .subscribe(teams => this.teams = teams, error => this.error = error);\n }", "async function getAllTeams(){\n return await season_utils.getTeamsBySeasonId(18334);\n}", "getGamesByTeam(team) {\n TTTPost(\"/games-by-team\", {\n team_id: team.team_id\n })\n .then(res => {\n this.setState({team: team, games: res.data.games});\n });\n }", "async getTeam () {\n\t\tthis.team = await this.data.teams.getById(this.stream.get('teamId'));\n\t}", "function fetchTeams({org}) {\n return this.getData({path:`/orgs/${org}/teams`})\n .then(response => {\n return response.data;\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }