query
stringlengths
9
14.6k
document
stringlengths
8
5.39M
metadata
dict
negatives
sequencelengths
0
30
negative_scores
sequencelengths
0
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
Example binToHex(["0111110", "1000000", "1000000", "1111110", "1000001", "1000001", "0111110"])
function binToHex(bins) { return bins.map(bin => ("00" + (parseInt(bin, 2).toString(16))).substr(-2).toUpperCase()).join(""); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function binToHex(a) {\r\n\tvar newVal = \"\";\r\n\tfor (i = 0; i < a.length/8; i++) \r\n\t\tnewVal += (\"00\" + parseInt(a.slice(8*i, 8*i+8),2).toString(16)).slice(-2);\r\n\treturn newVal;\r\n}", "function binToHex(bin) {\n for (var fourBitChunks = [], c = 0; c < bin.length; c += 4)\n fourBitChunks.push(parseInt(bin.substr(c, 4), 2).toString(16).toUpperCase());\n return fourBitChunks;\n}", "function hex(x) {\n for (var i = 0; i < x.length; i++)\n x[i] = makeHex(x[i]);\n return x.join('');\n}", "function binl2hex(binarray) \n{ \n var hex_tab = \"0123456789abcdef\" \n var str = \"\" \n for(var i = 0; i < binarray.length * 4; i++) \n { \n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + \n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8)) & 0xF) \n } \n return str \n}", "function binl2hex(binarray) \n{ \nvar hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\"; \nvar str = \"\"; \nfor(var i = 0; i < binarray.length * 4; i++) \n{ \nstr += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + \nhex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); \n} \nreturn str; \n}", "function binaryToHexString(bin) {\n let result = \"\";\n binToHex(bin).forEach(str => {result += str});\n return result;\n}", "function hexlify (arr) {\n return arr.map(function (byte) {\n return ('0' + (byte & 0xFF).toString(16)).slice(-2);\n }).join('');\n}", "function binHexa(obj) {\r\n var hexaVal =[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"];\r\n var decVal =[\"0000\",\"0001\",\"0010\",\"0011\",\"0100\",\"0101\",\"0110\",\"0111\",\"1000\",\"1001\",\"1010\",\"1011\",\"1100\",\"1101\",\"1110\",\"1111\"];\r\n var pas0;\r\n var valeurHex=\"\";\r\n var valeurDec1=obj[0]+obj[1]+obj[2]+obj[3];\r\n var valeurDec2=obj[4]+obj[5]+obj[6]+obj[7];\r\n for(pas0=0;pas0<hexaVal.length;pas0++){\r\n if (valeurDec1==decVal[pas0]){\r\n valeurHex=hexaVal[pas0];\r\n }\r\n }\r\n for(pas0=0;pas0<hexaVal.length;pas0++){\r\n if (valeurDec2==decVal[pas0]){\r\n valeurHex+=hexaVal[pas0];\r\n }\r\n }\r\n return valeurHex;\r\n}", "function binb2hex(binarray){\n\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\n var str = \"\";\n\n for (var i = 0; i < binarray.length * 4; i++) {\n\n str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +\n\n hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);\n\n }\n\n return str;\n\n }", "function asHex(value) {\n return Array.from(value).map(function (i) {\n return (\"00\" + i.toString(16)).slice(-2);\n }).join('');\n}", "function binl2hex(binarray)\r\n{\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for(var i = 0; i < binarray.length * 4; i++)\r\n {\r\n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +\r\n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);\r\n }\r\n return str;\r\n}", "function binl2hex(binarray)\r\n{\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for(var i = 0; i < binarray.length * 4; i++)\r\n {\r\n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +\r\n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);\r\n }\r\n return str;\r\n}", "function binl2hex(binarray)\r\n{\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for(var i = 0; i < binarray.length * 4; i++)\r\n {\r\n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +\r\n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);\r\n }\r\n return str;\r\n}", "function hexToBin(a) {\r\n\tvar newVal = \"\";\r\n\tfor (i = 0; i < a.length; i++) \r\n\t\tnewVal += (\"0000\" + parseInt(a.charAt(i),16).toString(2)).slice(-4);\r\n\treturn newVal;\r\n}", "function binb2hex( data )\n{\n for( var hex='', i=0; i<data.length; i++ )\n {\n while( data[i] < 0 ) data[i] += 0x100000000;\n hex += ('0000000'+(data[i].toString(16))).slice( -8 );\n }\n return hex.toUpperCase();\n}", "function asHex(value) {\n return Array.from(value)\n .map(function (i) { return (\"00\" + i.toString(16)).slice(-2); })\n .join('');\n}", "function binl2hex(binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for (var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +\n hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 )) & 0xF);\n }\n return str;\n}", "function binb2hex(binarray) {\n\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\n var str = \"\";\n\n for (var i = 0; i < binarray.length * 4; i++) {\n\n str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +\n\n hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);\n\n }\n\n return str;\n\n}", "function binb2hex(binarray) {\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for (var i = 0; i < binarray.length * 4; i++) {\r\n str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);\r\n }\r\n return str;\r\n}", "function binl2hex(binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for (var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +\n hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 )) & 0xF);\n }\n return str;\n }", "function binb2hex(binarray)\r\n{\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for(var i = 0; i < binarray.length * 4; i++)\r\n {\r\n str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\r\n hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\r\n }\r\n return str;\r\n}", "function binl2hex(binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n\n for (var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 0xF);\n }\n\n return str;\n}", "function binb2hex(binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for (var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);\n }\n return str;\n}", "function binl2hex(binarray) {\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for (var i = 0; i < binarray.length * 4; i++) {\r\n str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +\r\n hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 )) & 0xF);\r\n }\r\n return str;\r\n }", "function binb2hex(binarray) {\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for (var i = 0; i < binarray.length * 4; i++) {\r\n str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +\r\n hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);\r\n }\r\n return str;\r\n}", "function binl2hex(binarray)\n{\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for(var i = 0; i < binarray.length * 4; i++)\n {\n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +\n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);\n }\n return str;\n}", "function binl2hex(binarray)\n{\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for(var i = 0; i < binarray.length * 4; i++)\n {\n str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +\n hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);\n }\n return str;\n}", "function arrayOfHexaColors() {\n let output = [];\n let arglength = arguments.length;\n if (arglength > 0) {\n let input = arguments;\n for (let i = 0; i < arglength; i++) {\n output.push(arguments[i].toString(16));\n }\n }\n return output;\n}", "function toHexString(arr) {\n return Array.prototype.map.call(arr, (x) => (\"00\" + x.toString(16)).slice(-2)).join(\"\");\n}", "function array_to_hex(x){\r\n var hexstring = \"0123456789ABCDEF\";\r\n /* var hexstring = \"0123456789abcdef\"; */\r\n var output_string = \"\";\r\n \r\n for (var i = 0; i < x.length * 4; i++) {\r\n var tmp_i = shift_right(i, 2);\r\n \r\n output_string += hexstring.charAt((shift_right(x[tmp_i], ((i % 4) * 8 + 4))) & 0xF) +\r\n hexstring.charAt(shift_right(x[tmp_i], ((i % 4) * 8)) & 0xF);\r\n }\r\n return output_string;\r\n}" ]
[ "0.7413676", "0.70409733", "0.7034735", "0.6969076", "0.69535136", "0.69194937", "0.68874204", "0.6870118", "0.6826296", "0.6817666", "0.680198", "0.680198", "0.680198", "0.67952865", "0.67902726", "0.67830145", "0.6762924", "0.6740234", "0.67265904", "0.6723809", "0.67170584", "0.67115045", "0.670939", "0.6707228", "0.67068", "0.67042863", "0.67042863", "0.66927475", "0.6653412", "0.66495794" ]
0.74536294
0
Build a list of configuration (custom launcher names).
function buildConfiguration(type, target) { const targetBrowsers = Object.keys(browserConfig) .map(browserName => [browserName, browserConfig[browserName][type]]) .filter(([, config]) => config.target === target) .map(([browserName]) => browserName); // For browsers that run locally, the browser name shouldn't be prefixed with the target // platform. We only prefix the external platforms in order to distinguish between // local and remote browsers in our "customLaunchers" for Karma. if (target === 'local') { return targetBrowsers; } return targetBrowsers.map(browserName => { return `${target.toUpperCase()}_${browserName.toUpperCase()}`; }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static Configurators() {\n const customizeNothing = []; // no customization steps\n return [ customizeNothing ];\n }", "function updateArgProcessorList() {\n var argProcessorList = new commandLineUtils.ArgProcessorList();\n\n // App type\n addProcessorFor(argProcessorList, 'apptype', 'Enter your application type (native, hybrid_remote, or hybrid_local):', 'App type must be native, hybrid_remote, or hybrid_local.', \n function(val) { return ['native', 'hybrid_remote', 'hybrid_local'].indexOf(val) >= 0; });\n\n // App name\n addProcessorFor(argProcessorList, 'appname', 'Enter your application name:', 'Invalid value for application name: \\'$val\\'.', /^\\S+$/);\n\n // Output dir\n addProcessorForOptional(argProcessorList, 'outputdir', 'Enter the output directory for your app (defaults to the current directory):');\n return argProcessorList;\n}", "configLocator (options = {}) {\n let goinstallation = atom.config.get('go-config.goinstallation')\n let stat = this.statishSync(goinstallation)\n if (isTruthy(stat)) {\n let d = goinstallation\n if (stat.isFile()) {\n d = path.dirname(goinstallation)\n }\n return this.findExecutablesInPath(d, this.executables, options)\n }\n\n return []\n }", "function configureRuntime () {\n return (\n build()\n // Brand is used for default config files (if any).\n .brand(BRAND)\n // The default plugin is the directory we're in right now, so\n // the commands sub-directory will contain the first right of\n // refusal to handle user's requests.\n .loadDefault(__dirname)\n // TODO: maybe there's other places you'd like to load plugins from?\n // .load(`~/.${BRAND}`)\n\n // These are the magic tokens found inside command js sources\n // which plugin authors use to specify the command users can type\n // as well as the help they see.\n .token('commandName', `${BRAND}Command`)\n .token('commandDescription', `${BRAND}Description`)\n // let's build it\n .createRuntime()\n )\n}", "generateLaunchAgentPlist() {\n const programArguments = ['/usr/local/bin/gsts']\n\n for (let [key, value] of Object.entries(this.args)) {\n if (key.includes('daemon') || value === undefined) {\n continue;\n }\n\n programArguments.push(`--${key}${typeof value === 'boolean' ? '' : `=${value}`}`);\n }\n\n const payload = {\n Label: PROJECT_NAMESPACE,\n EnvironmentVariables: {\n PATH: '/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin'\n },\n RunAtLoad: true,\n StartInterval: 600,\n StandardErrorPath: this.args['daemon-out-log-path'],\n StandardOutPath: this.args['daemon-error-log-path'],\n ProgramArguments: programArguments\n };\n\n return plist.build(payload);\n }", "get miniConfig() {\n return [\n {\n type: \"button-group\",\n buttons: [\n this.boldButton,\n this.italicButton,\n this.removeFormatButton,\n ],\n },\n this.linkButtonGroup,\n this.scriptButtonGroup,\n {\n type: \"button-group\",\n buttons: [this.orderedListButton, this.unorderedListButton],\n },\n ];\n }", "processConfig() {\n /** merge type for arrays */\n const action = actions.importConfig(this.config);\n this.store.dispatch(action);\n const { config: storedConfig } = this.store.getState();\n\n storedConfig.windows.forEach((miradorWindow, layoutOrder) => {\n const windowId = `window-${uuid()}`;\n const manifestId = miradorWindow.manifestId || miradorWindow.loadedManifest;\n\n this.store.dispatch(actions.addWindow({\n // these are default values ...\n id: windowId,\n layoutOrder,\n manifestId,\n thumbnailNavigationPosition: storedConfig.thumbnailNavigation.defaultPosition,\n // ... overridden by values from the window configuration ...\n ...miradorWindow,\n }));\n });\n }", "list() {\n let config = this.readSteamerConfig();\n\n for (let key in config) {\n if (config.hasOwnProperty(key)) {\n this.info(key + '=' + config[key] || '');\n }\n }\n\n }", "_splitConfig() {\n const res = [];\n if (typeof (this.options.targetXPath) !== 'undefined') {\n // everything revolves around an xpath\n if (Array.isArray(this.options.targetXPath)) {\n // group up custom classes according to index\n const groupedCustomClasses = this._groupCustomClasses();\n // need to ensure it's array and not string so that code doesnt mistakenly separate chars\n const renderToPathIsArray = Array.isArray(this.options.renderToPath);\n // a group should revolve around targetXPath\n // break up the array, starting from the first element\n this.options.targetXPath.forEach((xpath, inner) => {\n // deep clone as config may have nested objects\n const config = cloneDeep(this.options);\n // overwrite targetXPath\n config.targetXPath = xpath;\n // sync up renderToPath array\n if (renderToPathIsArray && typeof (this.options.renderToPath[inner]) !== 'undefined') {\n config.renderToPath = this.options.renderToPath[inner] ? this.options.renderToPath[inner] : null;\n } else {\n // by default, below parent of target\n config.renderToPath = '..';\n }\n // sync up relatedElementActions array\n if (this.options.relatedElementActions\n && typeof (this.options.relatedElementActions[inner]) !== 'undefined'\n && Array.isArray(this.options.relatedElementActions[inner])) {\n config.relatedElementActions = this.options.relatedElementActions[inner];\n }\n // sync up customClasses\n if (typeof (groupedCustomClasses[inner]) !== 'undefined') {\n config.customClasses = groupedCustomClasses[inner];\n }\n // duplicate ignoredPriceElements string / array if exists\n if (this.options.ignoredPriceElements) {\n config.ignoredPriceElements = this.options.ignoredPriceElements;\n }\n // that's all, append\n res.push(config);\n });\n } else {\n // must be a single string\n res.push(this.options);\n }\n }\n return res;\n }", "getActiveConfigurations() {\n return __awaiter(this, void 0, void 0, function* () {\n return yield Gestalt_1.Gestalt.get(`/bots/${this.bot.id}/clients/${this.type}`);\n });\n }", "function loadConfigs() {\n if (allthings.configs !== null) {\n for (let i = 0; i < allthings.configs.length; i++) {\n let opt = `Team:${allthings.configs[i].team} Name:${\n\tallthings.configs[i].name\n }`;\n var el = document.createElement(\"option\");\n el.name = opt;\n el.textContent = opt;\n el.value = opt;\n document.getElementById(\"selectConfig\").appendChild(el);\n }\n }\n}", "generateConfigs() {\n this._createDirs();\n this._readFiles(this.source)\n .then(files => {\n console.log('Loaded ', files.length, ' files');\n const configs = this._loadConfigs(files);\n const common = this._getCommonJson(configs);\n\n this._writeData(common, 'default', 'json');\n this._generateFilesWithoutCommon(configs, common);\n this._generateCustomEnvironmentVariablesJson();\n })\n .catch(error => console.log(error));\n }", "getEntries(configurationFiles) {\n let entries = [];\n try {\n if (!configurationFiles['angular-config'].generated) {\n const { parsed } = configurationFiles['angular-config'];\n entries = entries.concat(getAngularJSONEntries(parsed));\n } else {\n const { parsed } = configurationFiles['angular-cli'];\n entries = entries.concat(getAngularCLIEntries(parsed));\n }\n } catch (e) {\n console.warn(\n `${configurationFiles['angular-config'].path} is malformed: ${e.message}`\n );\n }\n if (\n configurationFiles.package.parsed &&\n configurationFiles.package.parsed.main\n ) {\n entries.push(path_1.absolute(configurationFiles.package.parsed.main));\n }\n entries.push('/src/main.ts');\n entries.push('/main.ts');\n return entries;\n }", "function configureEntries (entryBase) {\n return function (entries, dir) {\n var app = path.basename(dir);\n var targets = glob.sync(dir + \"/**/target.js\");\n\n targets.forEach(function(target) {\n var targetName = path.basename(path.dirname(target));\n entries[app + \"__\" + targetName] = entryBase.slice().concat([target]);\n });\n\n return entries;\n }\n}", "function createConfiguration() {\r\n switch (selected_layout_id) {\r\n case CONFIGS.ONE_DEVICE:\r\n _configManager.setConfig('test-1d', 'test-1d', 'bob', 'dev', 1, 1, device_array.slice(0));\r\n break;\r\n case CONFIGS.TWO_DEVICES_1:\r\n _configManager.setConfig('test-2d1', 'test-2d', 'bob', 'dev', 2, 1, device_array.slice(0));\r\n break;\r\n case CONFIGS.TWO_DEVICES_2:\r\n _configManager.setConfig('test-2d2', 'test-2d2', 'bob', 'dev', 1, 2, device_array.slice(0));\r\n break;\r\n case CONFIGS.THREE_DEVICES_3:\r\n _configManager.setConfig('test-3d1', 'test-3d1', 'bob', 'dev', 3, 1, device_array.slice(0));\r\n break;\r\n case CONFIGS.THREE_DEVICES_4:\r\n _configManager.setConfig('test-3d2', 'test-3d2', 'bob', 'dev', 1, 3, device_array.slice(0));\r\n break;\r\n case CONFIGS.FOUR_DEVICES_5:\r\n _configManager.setConfig('test-4d1', 'test-4d1', 'bob', 'dev', 2, 2, device_array.slice(0));\r\n break;\r\n case CONFIGS.FOUR_DEVICES_6:\r\n _configManager.setConfig('test-4d2', 'test-4d2', 'bob', 'dev', 4, 1, device_array.slice(0));\r\n break;\r\n case CONFIGS.FIVE_DEVICES_7:\r\n _configManager.setConfig('test-5d', 'test-5d', 'bob', 'dev', 3, 2, device_array.slice(0));\r\n break;\r\n case CONFIGS.SIX_DEVICES_8:\r\n _configManager.setConfig('test-6d', 'test-6d', 'bob', 'dev', 3, 2, device_array.slice(0));\r\n break;\r\n }\r\n }", "function listAllConfigs() {\n\n\t// list the title\n\tconsole.log( \"Available .gitconfig files:\\n\" );\n\n\t// return the symbolic link value\n\tfs.readlink( GITCONFIG, ( err, linkString ) => {\n\n\t\t// get the symbolic link value\n\t\t// -- returns the actual file name\n\t\tlinkString = linkString && path.basename( linkString );\n\n\t\t// read the contents of the directory\n\t\tfs.readdirSync( GITCONFIGS ).forEach( ( configurations ) => {\n\t\t\tif( configurations[ 0 ] !== '.' ) {\n\n\t\t\t\t// list the file names\n\t\t\t\t// -- if the active config mark it\n\t\t\t\tconsole.log(\n\t\t\t\t\t' %s %s',\n\t\t\t\t\tlinkString == configurations ? '>' : ' ',\n\t\t\t\t\tconfigurations\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t});\n}", "function LoadConfig(){\n var cfg = fs.readFileSync(path.join(app.getPath('userData'), '../../Local/Crashday/config/launcher.config'))\n var colls = fs.readFileSync(path.join(app.getPath('userData'), '../../Local/Crashday/config/collections.config'), {flag: 'a+'})\n try{\n cfg = JSON.parse(cfg)\n } catch(e){\n cfg = {}\n }\n\n if(!cfg.hasOwnProperty('WorkshopItems'))\n cfg['WorkshopItems'] = []\n\n\n try{\n \tcolls = JSON.parse(colls)\n } catch(e){\n \tcolls = {}\n }\n\n if(!colls.hasOwnProperty('Collections'))\n colls['Collections'] = {}\n\n if(!colls.hasOwnProperty('CrashdayPath')){\n colls['CrashdayPath'] = ''\n }\n else{\n if(!fs.existsSync(colls['CrashdayPath'])) {\n colls['CrashdayPath'] = ''\n }\n }\n\n if(colls['CrashdayPath'] == '')\n $.toast({title: 'crashday.exe not found',\n content: 'Specify crashday.exe path in settings to enable auto scanning for newly subscribed mods. Otherwise default launcher has to be started after subscribing to new mods.',\n type: 'error', delay: 5000, container: $('#toaster')})\n\n //check for new mods in the workshop folder\n var p = path.join(colls['CrashdayPath'], '../../workshop/content/508980')\n var unlistedMods = 0\n var listedMods = 0\n var emptyFolders = 0\n var otherFiles = 0\n if(fs.existsSync(p)){\n fs.readdirSync(p).forEach(file => {\n var foundFile = false\n var name = parseInt(file, 10)\n //skip not numbered folder names\n if(name == NaN) {\n otherFiles++\n return\n }\n \n folder = fs.statSync(path.join(p, file))\n if(!folder.isDirectory()) {\n otherFiles++\n return\n }\n //check there is a mod file in mod folder\n files = fs.readdirSync(path.join(p, file))\n if(files.length == 0) {\n emptyFolders++\n return\n }\n\n for(n in cfg['WorkshopItems'])\n {\n if(cfg['WorkshopItems'][n][0] == name)\n {\n listedMods++\n foundFile = true\n }\n }\n if(!foundFile){\n cfg['WorkshopItems'].push([name, false])\n unlistedMods++\n }\n })\n }\n\n console.log(`Found ${listedMods} listed mods, ${unlistedMods} unlisted mods, ${emptyFolders} empty folders and ${otherFiles} other files in Workshop folder`)\n\n if(unlistedMods > 0){\n $.toast({title: 'New mods found',\n content: 'Launcher found and added ' + unlistedMods + ' new mods.',\n type: 'info', delay: 5000, container: $('#toaster')})\n }\n\n return [cfg, colls]\n}", "_setLabels () {\n const target = '\"labels\":[\"os=linux\"';\n const labels = this._opts.Labels;\n if (!labels || !labels.length) {\n return;\n }\n\n const labelsStr = labels\n .map(str => `\"${str}\"`)\n .join(',');\n\n let newLaunchConfig = this\n ._getLaunchConfigCode()\n .map(str => {\n if (!(typeof str === 'string' || str instanceof String)) {\n return str\n }\n\n if (str.indexOf(target) == -1) {\n return str\n }\n\n return str.replace(target, `${target},${labelsStr}`)\n });\n\n this._setLaunchConfigCode(newLaunchConfig);\n }", "function makeConfig() {\n\tif (config)\n\t\tthrow new Error('Config can only be created once');\n\n\toptions = project.custom.webpack || {}\n\t_.defaultsDeep(options,defaultOptions);\n\n\tif (options.config) {\n\t\tconfig = options.config;\n\t} else {\n\t\tlet configPath = path.resolve(options.configPath);\n\t\tif (!fs.existsSync(configPath)) {\n\t\t\tthrow new Error(`Unable to location webpack config path ${configPath}`);\n\t\t}\n\n\t\tlog(`Making compiler with config path ${configPath}`);\n\t\tconfig = require(configPath);\n\n\t\tif (_.isFunction(config))\n\t\t\tconfig = config()\n\t}\n\n\n\tconfig.target = 'node';\n\n\t// Output config\n\toutputPath = path.resolve(process.cwd(),'target');\n\tif (!fs.existsSync(outputPath))\n\t\tmkdirp.sync(outputPath);\n\n\tconst output = config.output = config.output || {};\n\toutput.library = '[name]';\n\n\t// Ensure we have a valid output target\n\tif (!_.includes([CommonJS,CommonJS2],output.libraryTarget)) {\n\t\tconsole.warn('Webpack config library target is not in',[CommonJS,CommonJS2].join(','))\n\t\toutput.libraryTarget = CommonJS2\n\t}\n\n\t// Ref the target\n\tlibraryTarget = output.libraryTarget\n\n\toutput.filename = '[name].js';\n\toutput.path = outputPath;\n\n\tlog('Building entry list');\n\tconst entries = config.entry = {};\n\n\tconst functions = project.getAllFunctions();\n\tfunctions.forEach(fun => {\n\n\t\t// Runtime checks\n\t\t// No python or Java :'(\n\n\t\tif (!/node/.test(fun.runtime)) {\n\t\t\tlog(`${fun.name} is not a webpack function`);\n\t\t\treturn\n\t\t}\n\n\n\t\tconst handlerParts = fun.handler.split('/').pop().split('.');\n\t\tlet modulePath = fun.getRootPath(handlerParts[0]), baseModulePath = modulePath;\n\t\tif (!fs.existsSync(modulePath)) {\n\t\t\tfor (let ext of config.resolve.extensions) {\n\t\t\t\tmodulePath = `${baseModulePath}${ext}`;\n\t\t\t\tlog(`Checking: ${modulePath}`);\n\t\t\t\tif (fs.existsSync(modulePath))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!fs.existsSync(modulePath))\n\t\t\tthrow new Error(`Failed to resolve entry with base path ${baseModulePath}`);\n\n\t\tconst handlerPath = require.resolve(modulePath);\n\n\t\tlog(`Adding entry ${fun.name} with path ${handlerPath}`);\n\t\tentries[fun.name] = handlerPath;\n\t});\n\n\tlog(`Final entry list ${Object.keys(config.entry).join(', ')}`);\n}", "function generateBuildConfig(){\n var jsBaseDir = './js';\n var lessBaseDir = './less';\n var fontsBaseDir= './fonts';\n\n var buildConfig = {\n jsBaseDir: jsBaseDir,\n fontsBaseDir: fontsBaseDir,\n fontsDestDir: './dist',\n jsDistDir: './dist',\n lessDistDir: './dist',\n lessBaseDir: lessBaseDir,\n //tell browserify to scan the js directory so we don't have to use relative paths when referencing modules (e.g. no ../components).\n paths:['./js'],\n //assume these extensions for require statements so we don't have to include in requires e.g. components/header vs components/header.jsx\n extensions:['.js'],\n\n //http://jshint.com/docs/options/\n jshintThese:[\n \"core/**/*\"\n ],\n jshint:{\n curly: true,\n strict: true,\n browserify: true\n },\n\n //http://lisperator.net/uglifyjs/codegen\n uglify:{\n mangle:true,\n output:{ //http://lisperator.net/uglifyjs/codegen\n beautify: false,\n quote_keys: true //this is needed because when unbundling/browser unpack, the defined modules need to be strings or we wont know what their names are.\n }\n //compress:false // we can refine if needed. http://lisperator.net/uglifyjs/compress\n }\n };\n\n\n return buildConfig;\n}", "getWebpackConfig() {\n // Now it can be a single compiler, or multicompiler\n // In any case, figure it out, create the compiler options\n // and return the stuff.\n // If the configuration is for multiple compiler mode\n // Then return an array of config.\n if (this.isMultiCompiler()) {\n // Return an array of configuration\n const config = [];\n this.projectConfig.files.forEach(file => {\n config.push(this.getSingleWebpackConfig(file));\n });\n return config;\n } // Otherwise, just return a single compiler mode config\n\n\n return this.getSingleWebpackConfig(this.projectConfig.files[0]);\n }", "function generateGulpResponsiveConfiguration(){\n\n // Loop the sizes array and create an object that fits the gulp-responsive reference\n var responsiveImages = sizes.map(function(item){\n var object = {\n width: item.width,\n rename: function(path) {\n path.dirname += `/${item.name}`;\n return path;\n }\n }\n if(item.height) {\n object.height = item.height;\n }\n return object;\n });\n\n // Loop the sizes array and create an object that fits the gulp-responsive reference\n // and is a retina version of the former\n var responsiveImages2x = sizes.map(function(item){\n var object = {\n width: item.width * 2,\n rename: function(path) {\n path.dirname += `/${item.name}`;\n path.basename += '@2x';\n return path;\n }\n }\n if(item.height) {\n object.height = item.height * 2;\n }\n return object;\n });\n \n return [ ...responsiveImages, ...responsiveImages2x ];\n}", "function createConfigList() {\n var hostUrl = decodeURIComponent(getQueryStringParameter(\"SPHostUrl\"));\n var currentcontext = new SP.ClientContext.get_current();\n var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);\n var hostweb = hostcontext.get_web();\n\n //Set ListCreationInfomation()\n var listCreationInfo = new SP.ListCreationInformation();\n listCreationInfo.set_title('spConfig');\n listCreationInfo.set_templateType(SP.ListTemplateType.genericList);\n var newList = hostweb.get_lists().add(listCreationInfo);\n newList.set_hidden(true);\n newList.set_onQuickLaunch(false);\n newList.update();\n\n //Set column data\n var newListWithColumns = newList.get_fields().addFieldAsXml(\"<Field Type='Note' DisplayName='Value' Required='FALSE' EnforceUniqueValues='FALSE' NumLines='6' RichText='TRUE' RichTextMode='FullHtml' StaticName='Value' Name='Value'/>\", true, SP.AddFieldOptions.defaultValue);\n\n //final load/execute\n context.load(newListWithColumns);\n context.executeQueryAsync(function () {\n console.log('spConfig list created successfully!');\n },\n function (sender, args) {\n console.error(sender);\n console.error(args);\n alert('Failed to create the spConfig list. ' + args.get_message());\n });\n }", "createConfig() {\n return {\n facets: [{ key: 'main', fixedFactSheetType: 'Application' }],\n ui: {\n elements: createElements(this.settings),\n timeline: createTimeline(),\n update: (selection) => this.handleSelection(selection)\n }\n };\n }", "commonOptions() {\n let config = this.config;\n let cmd = [];\n\n if (config.datadir) {\n cmd.push(`--datadir=${config.datadir}`);\n }\n\n if (Number.isInteger(config.verbosity) && config.verbosity >= 0 && config.verbosity <= 5) {\n switch (config.verbosity) {\n case 0:\n cmd.push(\"--lvl=crit\");\n break;\n case 1:\n cmd.push(\"--lvl=error\");\n break;\n case 2:\n cmd.push(\"--lvl=warn\");\n break;\n case 3:\n cmd.push(\"--lvl=info\");\n break;\n case 4:\n cmd.push(\"--lvl=debug\");\n break;\n case 5:\n cmd.push(\"--lvl=trace\");\n break;\n default:\n cmd.push(\"--lvl=info\");\n break;\n }\n }\n\n return cmd;\n }", "static getExtraConfig () {\n return {}\n }", "function list(appName, callback) {\n var uri = format('/%s/apps/%s/config/', deis.version, appName);\n commons.get(uri, function onListResponse(err, result) {\n callback(err, result ? result.values : null);\n });\n }", "function get_config() {\n // This is a placeholder, obtaining values from command line options.\n // Subsequent developments may access a configuration file\n // and extract an initial default configuration from that.\n //\n // See also: https://nodejs.org/api/process.html#process_process_env\n if (program.debug) {\n meld.CONFIG.debug = program.debug;\n } \n if (program.verbose) {\n meld.CONFIG.verbose = program.verbose;\n } \n if (program.author) {\n meld.CONFIG.author = program.author;\n } \n if (program.baseurl) {\n meld.CONFIG.baseurl = program.baseurl;\n }\n if (program.stdinurl) {\n meld.CONFIG.stdinurl = program.stdinurl;\n }\n}", "function getConfiguration(stats) {\n\tconst production = [getProductionModules(stats)]\n\tconst fermenting = getFermentingModules(stats, production[0])\n\tconst addons = getAddonsModules(stats)\n\n\t// concatinating arrays\n\t// const all = production.concat(fermenting).concat(addons)\n\tconst all = (production.concat(fermenting)).concat(addons)\n\n\treturn { production, fermenting, addons, all }\n}", "getConfig() {\n // NOTE(cais): We override the return type of getConfig() to `any` here,\n // because the `Sequential` class is a special case among `Container`\n // subtypes in that its getConfig() method returns an Array (not a\n // dict).\n const layers = [];\n for (const layer of this.layers) {\n const dict = {};\n dict['className'] = layer.getClassName();\n dict['config'] = layer.getConfig();\n layers.push(dict);\n }\n return { name: this.name, layers };\n }" ]
[ "0.5952684", "0.54929423", "0.5462945", "0.54263645", "0.53882575", "0.5377423", "0.534919", "0.5339271", "0.53169733", "0.53052163", "0.5300868", "0.5283008", "0.5272032", "0.52457243", "0.5242057", "0.5235154", "0.52095884", "0.5202356", "0.5185812", "0.5145657", "0.51259655", "0.5096008", "0.50841707", "0.507554", "0.5056314", "0.50410324", "0.50401795", "0.5036896", "0.5025826", "0.49988222" ]
0.5686087
1
There are two things needed to place a beacon: the position and a name TO DO: name will have to be unique. At this point, if there are two entries with the same name, it will return the first it finds (a) position: currently, the position is the PLAYER'S position when player places the marker block, so use 'self.position' (b) name: enter a name in quotation marks, like "beacon1" or "pool"
function beacon(me, beaconName){ //we place a marker at the position we want: box(blocks.beacon,1,2,1); //In the next lines, we build the beacon object: var loc = me.getLocation(); //the next line appends the beacon's name to the array that contains only the tag key (the name the player gives to the beacon) beaconNameArray.push(beaconName); //the position is returned as an object which has coordinates as properties (keys). We are extracting the properties x, y and z //and puting them in an array whic we call locx. Since I want the numbers to be easy to read, and extreme precision is not //important for this plugin, I also round the numbers var locx = [Math.round(loc.getX()),Math.round(loc.getY()),Math.round(loc.getZ())]; //The beacon object is then assembled and appended to the beaconArray array var beaconObj = {tag: beaconName, position: locx}; beaconArray.push(beaconObj); //finally, we display the result to the player, showing the name of the beacon and its coordinates. //TO DO: TAB list of beacons' names echo('You are at ' + beaconName + ' at position ' + locx[0] + ", " + locx[1] + ", " + locx[2]); /* these were used to debug: echo(beaconObj.tag + beaconObj.position); echo(beaconArray.length); echo(beaconArray[0]); echo(beaconNameArray[0]); */ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getNewdidFromPos(position) {\n\t//flag ( \"getNewdidFromPos():: Started! Called for position: \" + position );\n\t//a=GM_getValue(myacc())\n\tvar allVillagePos = GM_getValue(myacc() + \"_allVillagePos2\").split(\",\");\n\t//flag ( \"getNewdidFromPos: allVillagePos=\"+allVillagePos+\";\");\n\tfor (var i = 0; i < allVillagePos.length; i++) {\n\t\tvar tt = allVillagePos[i].split(\":\");\n\t\tif ( tt[1] == position) {\n\t\t\treturn tt[0];\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn null;\n}", "function findBeacons() {\n\tvar room = \"\";\n\t/*[] values;\n\tfor(var i=0;i>10;i++) {*/\n\t\tBeacon.rangeForBeacons(\"B9407F30-F5F8-466E-AFF9-25556B57FE6D\")\n\t\t.then(function(beacons_found) {\n\t\t // $(\"#beacon-list\").empty();\n\t\t var maxRSSI = 100;\n\t\t for(beaconIndex in beacons_found) {\n\t\t var beacon = beacons_found[beaconIndex]; \n\t\t /* var beaconDiv = $(\"<div />\").html(\"Major: \" + beacon.major + \n\t\t \"; Minor: \" + beacon.minor + \n\t\t \"; RSSI: \" + (beacon.rssi*-1));\n\t\t\n\t\t $(\"#beacon-list\").append(beaconDiv);*/\n\t\t if(beacon.rssi*-1 < maxRSSI) {\n\t\t \t room = getRoomName(beacon.minor);\n\t\t \t maxRSSI = beacon.rssi*-1;\n\t\t }\n\t\t }\n\t\t $(\"#myLocation\").text(/*\"Ole Johan Dahls Hus\" + */room);\n\t\t if(room == \"\") {\n\t\t\t setOffline();\n\t\t }\n\t\t newLocation(room);\n\t\t})\n\t\t.fail(function() {\n\t\t alert(\"failed serching for beacons!\");\n\t\t setOffline();\n\t\t});\n\t//}\n}", "function searchObject(type){\n\tvar target;\n console.log(\"123\");\n\tif(type==\"beacon\"){\n\t\t target=beaconMap[document.getElementById('beaconSearch').value];\n\t}else{\n\t\t target=reporterMap[document.getElementById('reporterSearch').value];\n console.log(target);\n\t}\n\t toggleBounce(target.marker);\n map.panTo(target.getPosi(),3000);\n if(map.getZoom()<17){\n\t map.setZoom(17);\n\t}\n var date = new Date(target.time*1000);\n\t\n document.getElementById(\"beaconInfo\").innerHTML=\"<h3 class='InfoTitle'>Loggy: \"+target.mac+\"</h3>\"+\"<p class='InfoBody'>Latitude: \"+target.lat+\"<br>\"+\"Longitude: \"+target.lng+\"<br>Last Update: \"+date.getFullYear()+\"-\"+(date.getMonth()+1)+\"-\"+date.getDate()+\" \"+date.getHours()+\":\"+date.getMinutes()+\":\"+date.getSeconds()+\"</p>\";\n \n}", "function locate_iBeacons() {\n kony.print(\"--Start locate_iBeacons--\");\n if (beaconManager === null) {\n kony.print(\"--creating beaconManager--\");\n beaconManager = new com.kony.BeaconManager(monitoringCallback, rangingCallback, errorCallback);\n kony.print(\"--beaconManager = new com.kony.BeaconManager(monitoringCallback, rangingCallback, errorCallback)--\");\n beaconManager.setMonitoringStartedForRegionCallback(monitoringStartedForRegionCallback);\n kony.print(\"--beaconManager.setMonitoringStartedForRegionCallback(monitoringStartedForRegionCallback);--\");\n beaconManager.setAuthorizationStatusChangedCallback(authorizationStatusChangedCallback);\n }\n if (beaconManager.authorizationStatus() != \"BeaconManagerAuthorizationStatusAuthorized\") {\n kony.print(\"Unathorized to use location services\");\n }\n if (!beaconManager.isMonitoringAvailableForBeaconRegions()) {\n kony.print(\"Monitoring not available\");\n return;\n }\n if (!beaconManager.isRangingAvailableForBeaconRegions()) {\n kony.print(\"Ranging not available\");\n return;\n }\n var proximityUUID = \"CAD6ACBA-9D1C-4772-90AA-0FEEF6868D30\";\n var identifier = \"com.kone.LatestKMSDemo\"\n var beaconRegion = new com.kony.BeaconRegion(proximityUUID, null, null, identifier);\n beaconRegion.setNotifyEntryStateOnDisplay(true);\n beaconManager.startMonitoringBeaconRegion(beaconRegion);\n}", "findFriendIdByName( nameToSearch ) {\n let friendId = this.ItemNotFound;\n let list = this.state[this.townName];\n \n for( let indx=0; indx<list.length; ++indx ) {\n if( list[indx].name === nameToSearch ) {\n friendId = list[indx].id;\n break;\n }\n }\n return friendId;\n }", "function bringPlayer(playerName,playerLocation) {\n\tvar playersIndex = players.indexOf(playerName);\t\n\t//first check to see if playerName exists\n\tif(playersIndex!==-1) {\n\n\t\t//need to update the playersLocations to bring the player from other location to playerLocation\n\t\tif(isMoveAllowed(playerLocation)) {\n\t\t\tplayersLocations[playersIndex]=playerLocation;\n\t\t} else {\n\t\t\tconsole.log(playerName+\" cannot be placed there.\");\n\t\t}\n\t} else {\n\t\tconsole.log(playerName+\" does not exist!\");\n\t}\n}", "function assignName() {\n var locationNameHolder = scope.querySelectorAll(\"[data-vf-js-location-nearest-name]\");\n if (!locationNameHolder) {\n // exit: container not found\n return;\n }\n if (locationNameHolder.length == 0) {\n // exit: content not found\n return;\n }\n // console.log('assignName','pushing the active location to the dom')\n locationNameHolder[0].innerHTML = locationName;\n }", "function getLocCode() {\r\n\tplayerLocCode = playerDetails.locCode;\r\n}", "function FindSpawn(index){\n\tif(!index.search){\n\t\tlet a=Math.floor(Math.random()*sX);\n\t\tlet b=Math.floor(Math.random()*sY);\n\t\tif(grid[a][b]==0){\n\t\t\tindex.x=a;\n\t\t\tindex.y=b;\n\t\t\tindex.search=true;\n\t\t}\n\t}\n}", "function examine(word) {\n let lookAt = itemLookUp[word]\n if (player.location.inv.includes(word)) {\n console.log(lookAt.desc)\n }\n}", "async function getPlayerbasicDetailsByPosition(player_name, position_name){\n const all_player_with_same_name = await axios.get(`${api_domain}/players/search/${player_name}`, {\n params: {\n api_token: process.env.api_token,\n include: \"team.league, position\", \n },\n })\n return all_player_with_same_name.data.data.map((player_info) => {\n if(player_info != undefined && player_info.team != undefined && player_info.position != undefined)\n {\n const { player_id, fullname, image_path, position_id } = player_info;\n if(fullname.includes(player_name))\n {\n if( player_info.position.data.name == position_name)\n {\n const { name } = player_info.team.data;\n if(player_info.team.data.league != undefined)\n {\n const {id} = player_info.team.data.league.data;\n if(id == 271) \n {\n return {\n id: player_id,\n name: fullname,\n image: image_path,\n position: position_id,\n position_name: player_info.position.data.name,\n team_name: name, \n };\n }\n }\n }\n } \n }\n }); \n }", "searchByName( nameToSearch ) {\n let itemId = this.ItemNotFound;\n let list = this.state[this.townName];\n let nameToSearchLowerCase = nameToSearch.toLocaleLowerCase();\n let nameToSearchSplit = nameToSearchLowerCase.split(' ');\n let name0ToSearch = nameToSearchSplit[0];\n let name1ToSearch = nameToSearchSplit[1];\n \n \n for( let indx=0; indx<list.length; ++indx ) {\n let name = list[indx].name.toString().toLocaleLowerCase();\n let nameSplit= name.split(' ');\n let name0 = nameSplit[0];\n let name1 = nameSplit[1];\n \n if( name0ToSearch && name1ToSearch && nameToSearchLowerCase === name ) {\n itemId = list[indx].id;\n break;\n } else\n if( !name1ToSearch && name0ToSearch && (name0 === name0ToSearch || name1 === name0ToSearch) ) {\n itemId = list[indx].id;\n break;\n }\n }\n console.log('searchByName :',itemId);\n \n return itemId;\n }", "function Player(name, marker) {\n this.name = name\n this.marker = marker\n}", "function spanNewPlayer(name : String, info : NetworkMessageInfo){\n\tvar lastPlayer = false;\n\t//Remove items from spawn array\n\tplayerArray.Remove(info);\n\tplayerNameArray.Remove(name);\n\t\n\tif (playerArray.Count == 0){\n\t\tlastPlayer = true;\n\t}\n\t\n\tvar player = info.sender;\n\n\tDebug.Log(\"SPAWNING the player, since I am the server\");\n\tvar playerIsMole : boolean = false;\n\t\n\tfor (molePos in MolePosition){\n\t\tif (playerList.length+1 == molePos){\n\t\t\tplayerIsMole = true;\n\t\t}\n\t} \n\n\tnetworkView.RPC(\"initPlayer\", player, player);\n\tnetworkView.RPC(\"spawnPlayer\", RPCMode.All, player, playerIsMole, name, lastPlayer);\n}", "function get_npc(name) {\r\n\tvar npc = parent.G.maps[character.map].npcs.filter(npc => npc.id == name);\r\n\r\n\tif (npc.length > 0) {\r\n\t\treturn npc[0];\r\n\t}\r\n\r\n\treturn null;\r\n}", "function searchByName(name) {\n var testName = name.toLowerCase();\n if (testName===\"bar\"||\"bars\"||\"restaurant\"||\"restaurants\"||\"food\"||\"beer\") {\n var request = {\n location: pos,\n radius: '500',\n type: ['bar', 'restaurant']\n };\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, callback);\n } else {\n var request = {\n query: name,\n fields: ['photos', 'formatted_address', 'name', 'rating', 'opening_hours', 'geometry'],\n locationBias: {radius: 50, center: pos}\n };\n service = new google.maps.places.PlacesService(map);\n service.findPlaceFromQuery(request, callback);\n };\n}", "function get_npc(name) {\n var npc = parent.G.maps[character.map].npcs.filter(npc => npc.id == name);\n\n if (npc.length > 0) {\n return npc[0];\n }\n\n return null;\n}", "function find_closest_asset_address(player_enter_x, player_enter_z) {\n var closest_distance = 9999999;\n\n var closet_coor = null;\n\n // for each coordinate our coordinate map\n for (var i = 0; i < coordinate_map.length; i++) {\n var coor = coordinate_map[i]\n\n // determine the distance from that coordinate to the player enter position\n var distance = find_distance(player_enter_x, player_enter_z, coor.x, coor.z)\n\n // if this coordinate is closer set it as our closest\n if (distance < closest_distance) {\n closest_distance = distance\n closet_coor = coor;\n }\n }\n\n // return the address of the closest coordinate\n if (closet_coor != null) {\n return closet_coor.address\n } else {\n return \"\";\n }\n}", "function getBpFromName(name) {\n\tconsole.log(storyCardFaceUp);\n\tconsole.log(storyCardFaceUp.foe);\n\tconsole.log(name);\n\tfor (var i = 0; i < cardTypeList.length; i++) {\n\t\t// console.log(cardTypeList[i]);\n\t\t// console.log(name);\n\t\tif (cardTypeList[i].name === name)\n\t\t\tif (cardTypeList[i].hasOwnProperty('bp')) {\n\t\t\t if(storyCardFaceUp.foe === name) return cardTypeList[i].bonusbp;\n\t\t\t return cardTypeList[i].bp;\n\t\t\t}\n\t}\n\treturn \"card not found\";\n}", "function rangingCallback(beaconRegion, beacons) {\n kony.print(\"Beacons found for BeaconRegion: \", kony.type(beaconRegion), \" \", beaconRegion, \" Beacons: \", beacons);\n var beaconLabel = \"No beacons\";\n var proximityLabel = \"...\";\n if (beacons.length > 0) {\n beacon = beacons[0];\n proximityUUIDString = beacon.getProximityUUIDString();\n major = beacon.getMajor();\n minor = beacon.getMinor();\n beaconLabel = beacon.getProximityUUIDString() + \" \" + beacon.getMajor() + \" \" + beacon.getMinor();\n proximityLabel = beacon.getProximity();\n }\n if ((prevProximityUUIDString != proximityUUIDString) && (ksid != null)) {\n beaconUpdate();\n }\n}", "function getPlayerData(list, playerName) {\n for (let p = 0; p < list.length; p++) {\n const player = list[p];\n if (player.name === playerName) {\n return player;\n }\n }\n // console.log(\"Unable to find player \", playerName, \"in list:\\n\", list);\n}", "function getPlayerData(list, playerName) {\n for (let p = 0; p < list.length; p++) {\n const player = list[p];\n if (player.name === playerName) {\n return player;\n }\n }\n console.log(\"Unable to find player \", playerName, \"in list:\\n\", list);\n}", "addMarker(level, openings, itemObj, startPosX = -1, startPosY = -1) {\n let startPos = startPosX + startPosY;\n if (startPos >= 0 && openings.indexOf(startPos) === -1 && startPos < this.maze.length) {\n level[startPos] = itemObj;\n }\n else {\n let randomCell = Math.floor(Math.random() * openings.length);\n let addMarkerPosn = openings.splice(randomCell, 1)[0];\n level[addMarkerPosn] = itemObj;\n }\n }", "function updateMap(time){\n // console.log(\"----------------------------\");\n if(showBeacon){\n var position1 = JSON.parse(httpGet(beaconPosiSource)); //two dimensional JSON array\n // console.log(\"----------------------------\");\n var position = new ibeaconBeanGroup(position1).getAllBestLocations();\n\n // console.log(position1);\n \n // console.log(position);\n\n\t\tfor(var i=0;i<position.length;i++){\n\t\t\tif(typeof(beaconMap[position[i].mac])=='undefined'){\n\t\t\t\tbeaconMap[position[i].mac] = new beaconMarker(position[i]);\n\t\t\t\tbeaconMap[position[i].mac].setColor(colorBar[i%7]);\n console.log(\"beaconMap[position[i].mac])=='undefined'\");\n\t\t\t}else{\n\n\t\t\t\tif(!beaconMap[position[i].mac].equal(position[i])){\n\t\t\t\t\tbeaconMap[position[i].mac].setPosi(position[i]);\n console.log(position[i]);\n\t\t\t\t\tbeaconMap[position[i].mac].time=parseInt(position[i].time);\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n \n \n }\n window.setTimeout(\"updateMap(\"+time+\")\",time);\n}", "getEmptySpawn() {\n for (let mySpawnName in this.spawnNames) {\n let mySpawn = Game.spawns[this.spawnNames[mySpawnName]];\n if (mySpawn && mySpawn.energy < mySpawn.energyCapacity) {\n return mySpawn;\n }\n } \n return null;\n }", "map_attribute_name_to_buffer_name( name ) \n { \n return { object_space_pos: \"positions\" }[ name ]; // Use a simple lookup table.\n }", "function showMarker(name,address){\n var l = self.restaurantList().length;\n for(var i=0;i<l;i++){\n var rName = self.restaurantList()[i].restaurant.name;\n var position = self.restaurantList()[i].marker.marker.position;\n var rAddress = self.restaurantList()[i].restaurant.address;\n if(name === rName && address === rAddress){\n map.panTo(position);\n map.setZoom(15);\n populateInfoWindow(self.restaurantList()[i].marker.marker,\n largeInfowindow,\n self.restaurantList()[i].marker.content);\n self.restaurantList()[i].marker.marker.setAnimation(\n google.maps.Animation.BOUNCE);\n\n break;\n }\n }\n }", "function Awake (){\n\t//get the parent of the markers\n\tGlobe = transform.parent;\n\t//Just setting the name again, to make sure.\n\tboardObject = \"CountryBoard\";\n\t//When start, look for the plane\n\tBoard = GameObject.Find(boardObject);\n}", "function updateCoordinates(name) {\n name.position.y = floor(random(10, (width) / 10)) * 10;\n name.position.x = floor(random(10, (height) / 10)) * 10;\n }", "function insertRecordOfWhoWasSeen(){\n var data = {};\n data['name'] = $('#insertName').val();\n data['posX'] = clickedPositionX;\n data['posY'] = clickedPositionY;\n \n $.get('../insert',data);\n \n $('#insertModal').modal('hide');\n drawCircleOnMap(clickedPositionX, clickedPositionY, data['name'][0], 30, '#b8dbd3', 3500);\n }" ]
[ "0.55945784", "0.55155414", "0.5372061", "0.53548574", "0.52936345", "0.5292482", "0.52400655", "0.52102", "0.5159438", "0.51353896", "0.51154304", "0.5113312", "0.51111436", "0.5110201", "0.5109417", "0.5098488", "0.50911343", "0.50832295", "0.5079928", "0.5076207", "0.5045602", "0.5038288", "0.5030733", "0.50182706", "0.5015086", "0.50018305", "0.4996816", "0.49821067", "0.49794316", "0.49780127" ]
0.7198466
0
Setup canvas based on the video input
function setup_canvases() { canvas.width = video_element.scrollWidth; canvas.height = video_element.scrollHeight; output_element.width = video_element.scrollWidth; output_element.height = video_element.scrollHeight; console.log("Canvas size is " + video_element.scrollWidth + " x " + video_element.scrollHeight); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_setupCanvas() {\n\t\tconst {video, elements} = this;\n\n\t\tconst virtualCanvas = elements.virtualCanvas = document.createElement('canvas');\n\n\t\tthis.context = elements.canvas.getContext('2d');\n\t\tthis.virtualContext = virtualCanvas.getContext('2d');\n\n\t\telements.canvas.width = virtualCanvas.width = video.videoWidth;\n\t\telements.canvas.height = virtualCanvas.height = video.videoHeight;\n\t}", "canvasApp() {\n this.context = this.canvas.getContext(\"2d\");\n this.videoLoop();\n }", "function makeCanvases() {\n w = _this.media.videoWidth;\n h = _this.media.videoHeight;\n \n // create a canvas to display the color-changed video, and a div to hold the canvas\n var candiv = document.createElement('div');\n candiv.style.position = 'absolute';\n _mediaHolder.appendChild(candiv);\n candiv.style.top = _media.offsetTop + 'px'; // so that the canvas will appear over the video\n candiv.style.left = _media.offsetLeft + 'px';\n _colorCanvas = document.createElement('canvas');\n _colorCanvas.style.display = 'none';\n _colorCanvas.width = w;\n _colorCanvas.height = h;\n candiv.appendChild(_colorCanvas);\n \n _colctx = _colorCanvas.getContext('2d');\n options.colorCanvas = _colorCanvas;\n \n // create a buffer canvas to hold each frame for processing\n // note that it just \"floats\" and is never appended to the document\n _bufferCanvas = document.createElement('canvas');\n _bufferCanvas.style.display = 'none';\n _bufferCanvas.width = w;\n _bufferCanvas.height = h;\n _bufctx = _bufferCanvas.getContext('2d');\n options.bufferCanvas = _bufferCanvas;\n console.log('The variable bufctx is ' + _bufctx);\n \n \n if (_coloring === \"color-no-change\"){\n return;\n }\n else if (_coloring === \"blackwhite\"){\n _media.addEventListener('play', function(){\n var framecounter = 0;\n console.log('Playing. The variable bufctx is ' + _bufctx);\n options.redrawID = makeBW(_media, _bufctx, _colctx, w, h, framecounter);\n });\n }\n else if (_coloring === \"sepia\"){\n _media.addEventListener('play', function(){\n var framecounter = 0;\n options.redrawID = makeSepia(_media, _bufctx, _colctx, w, h, framecounter);\n });\n }\n else if (_coloring === \"custom\"){\n _media.addEventListener('play', function(){\n var framecounter = 0;\n options.redrawID = adjustColor(_media, _bufctx, _colctx, w, h, framecounter, _redAdd, _greenAdd, _blueAdd);\n });\n }\n }", "constructor() {\n super();\n /**\n * video source file or stream\n * @type {string}\n * @private\n */\n this._source = '';\n\n /**\n * use camera\n * @type {boolean}\n * @private\n */\n this._useCamera = false;\n\n /**\n * is component ready\n * @type {boolean}\n */\n this.isReady = false;\n\n /**\n * is video playing\n * @type {boolean}\n */\n this.isPlaying = false;\n\n /**\n * width of scaled video\n * @type {int}\n */\n this.videoScaledWidth = 0;\n\n /**\n * height of scaled video\n * @type {int}\n */\n this.videoScaledHeight = 0;\n\n /**\n * how the video is scaled\n * @type {string}\n * @default letterbox\n */\n this.videoScaleMode = 'contain';\n\n /**\n * what type of data comes back with frame data event\n * @type {string}\n * @default imagedataurl\n */\n this.frameDataMode = 'none';\n\n /**\n * determines whether to use the canvas element for display instead of the video element\n * @type {boolean}\n * @default false\n */\n this.useCanvasForDisplay = false;\n\n /**\n * canvas filter function (manipulate pixels)\n * @type {method}\n * @default 0 ms\n */\n this.canvasFilter = this.canvasFilter ? this.canvasFilter : null;\n\n /**\n * refresh interval when using the canvas for display\n * @type {int}\n * @default 0 ms\n */\n this.canvasRefreshInterval = 0;\n\n /**\n * video element\n * @type {HTMLElement}\n * @private\n */\n this.videoElement = null;\n\n /**\n * camera sources list\n * @type {Array}\n */\n this.cameraSources = [];\n\n /**\n * canvas element\n * @type {Canvas}\n * @private\n */\n this.canvasElement = null;\n\n /**\n * component shadow root\n * @type {ShadowRoot}\n * @private\n */\n this.root = null;\n\n /**\n * interval timer to draw frame redraws\n * @type {int}\n * @private\n */\n this.tick = null;\n\n /**\n * canvas context\n * @type {CanvasContext}\n * @private\n */\n this.canvasctx = null;\n\n /**\n * has the canvas context been overridden from the outside?\n * @type {boolean}\n * @private\n */\n this._canvasOverride = false;\n\n /**\n * width of component\n * @type {int}\n * @default 0\n */\n this.width = 0;\n\n /**\n * height of component\n * @type {int}\n * @default 0\n */\n this.height = 0;\n\n /**\n * left offset for letterbox of video\n * @type {int}\n * @default 0\n */\n this.letterBoxLeft = 0;\n\n /**\n * top offset for letterbox of video\n * @type {int}\n * @default 0\n */\n this.letterBoxTop = 0;\n\n /**\n * aspect ratio of video\n * @type {number}\n */\n this.aspectRatio = 0;\n\n /**\n * render scale for canvas frame data\n * best used when grabbing frame data at a different size than the shown video\n * @attribute canvasScale\n * @type {float}\n * @default 1.0\n */\n this.canvasScale = 1.0;\n\n /**\n * visible area bounding box\n * whether letterboxed or cropped, will report visible video area\n * does not include positioning in element, so if letterboxing, x and y will be reported as 0\n * @type {{x: number, y: number, width: number, height: number}}\n */\n this.visibleVideoRect = { x: 0, y: 0, width: 0, height: 0 };\n\n this.template = `\n <style>\n ccwc-video {\n display: inline-block;\n background-color: black;\n position: relative;\n overflow: hidden;\n }\n \n ccwc-video > canvas {\n position: absolute;\n }\n \n ccwc-video > video {\n position: absolute;\n }\n </style>\n\n <video autoplay=\"true\"></video>\n <canvas></canvas>`;\n }", "async function populateVideo() {\n // We grab the feed off the user's webcam\n const stream = await navigator.mediaDevices.getUserMedia({\n video: { width: 1280, height: 720 },\n });\n\n // We set the object to be the stream\n video.srcObject = stream; // usually when dealing with video files we use video.src = 'videoName.mp4'\n await video.play();\n\n // size the canvases to be the same size as the video\n console.log(video.videoWidth, video.videoHeight);\n\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n faceCanvas.width = video.videoWidth;\n faceCanvas.height = video.videoHeight;\n}", "function paintToCanvas() {\n // you will find that the canvas height is bigger than the current window size even though its size is set to 640*480\n // because the width of the canvas is set to 100% which means it will take 100% of the space availabe of its parent container (photobooth)\n // Since the width of the photobooth is appx 1330px \n // the canvas will also take width of 1330px\n // since the width is 1330px the height will be 999px in order to maintain the aspect ratio (640*480)\n // the canvas is taking aspect ratio from our defined size (i.e 640 * 480)\n // therefore you can change the aspect ratio by changing the width and height of the canvas\n // if you remove the width 100% from its css , it will regain the size of 640*480\n\n // width and height = 640 * 480 \n // because the resolution we get from the video feed is by default 640*480 and is pre-defined by the system webcam\n // setting canvas width and height = 640*480\n const width = video.videoWidth;\n const height = video.videoHeight;\n [canvas.width, canvas.height] = [width, height];\n\n // the video playing in the canvas is not a actual video\n // but rather a image showing every few millisecond (giving us a video like visual)\n // So every 16ms the image captured from the video feed will be pasted/drawed on the canvas.\n // So we can say our video on canvas is showing 1 frame every 16 milliseconds\n return setInterval(() => {\n // ctx.drawImage will draw the image captured from the video feed\n // 0,0 are the x and y coordinate of the top left corner of the canvas\n // it will indicate that from which point the image drawing will start\n // width and height is of the destination contex(canvas)\n ctx.drawImage(video, 0, 0, width, height);\n\n // FROM HERE AFTERWARDS pixels MEANS VARIABLE\n\n // ctx.getImageData will give the data of the image(from the video playing on the canvas) \n // pixels will store the image data in form of array of rgb values for individual pixels\n let pixels = ctx.getImageData(0, 0, width, height);\n\n // Rendering different effects for the pixels\n // Every image captured from the video feed every 16ms will go through these function everytime\n // The pixels returned by these function will have different rgb values as compared to the original pixels\n\n // This is for red filter\n // pixels = redEffect(pixels);\n\n // This is for rgbSplit(tiktok) filter\n // pixels = rgbSplit(pixels);\n\n // This is for green screen\n pixels = greenScreen(pixels);\n\n // globalAlpha will determine how transparent will be the filters (0 - fully transparent, 1-opaque)\n // ctx.globalAlpha = 0.8\n\n // this will put the modified pixels back into the canvas\n // thus showing the filter on the video\n ctx.putImageData(pixels, 0, 0)\n }, 16);\n}", "function drawCameraIntoCanvas() {\n // Draw the video element into the canvas\n ctx.drawImage(video, 0, 0, pageContent.offsetWidth, pageContent.offsetHeight);\n ctx.fillStyle = '#000000';\n ctx.fillRect(0, 0, pageContent.offsetWidth, pageContent.offsetHeight);\n ctx.lineWidth = 5;\n ctx.fillStyle = '#00FFFF';\n ctx.strokeStyle = '#00FFFF';\n\n // We can call both functions to draw all keypoints and the skeletons\n drawKeypoints();\n drawSkeleton();\n window.requestAnimationFrame(drawCameraIntoCanvas);\n}", "function installcanvas () {\n\n // if there's an iframe\n var iframe = document.getElementById('tool_content');\n if (iframe) {\n \t\taddEventListener(\"message\", installfromiframe('#content', 'about:blank', ''), false);\n } \n \n // multiple videos as per\n // https://canvas.harvard.edu/courses/340/wiki/supplemental-materials-for-lab-1-reporter-gene-analysis-using-transgenic-animals?module_item_id=630 \n else {\n\n // video locations that may need a click to access \n var containers = [].slice.call(document.getElementsByClassName('instructure_file_link_holder'));\n containers = containers.concat([].slice.call(document.getElementsByClassName('instructure_inline_media_comment')));\n // known video locations\n var matches = document.body.innerHTML.match(/me_flash_\\d_container/g);\n\n // if any known videos exist, launch those\n if (matches) {\n\n // loop through all known videos\n for (var i = 0; i < matches.length; i++) {\n\n // pull out the video number\n matches[i] = matches[i].replace(/\\D/g, \"\");\n\n // parameters for the videoplayer\n var parameter = {};\n\n // only supporting mp4 at the moment\n parameter.audio = false;\n\n // set number for video classes \n parameter.number = matches[i];\n\n // get source for available video\n parameter.source = document.getElementById('mep_' + matches[i]).childNodes[0].childNodes[0].childNodes[1].src + '?1';\n if (parameter.source) {\n\n // get locally stored data \n var hist = JSON.parse(localStorage.getItem(parameter.source));\n if (hist) {\n parameter.time = hist.time;\n }\n\n // prepare new container\n var container = $('<div/>');\n\n // maximize player's width\n container.css('margin', '10px 0 0 0');\n container.css('padding', '0');\n container.css('width', '100%');\n parameter.playing = false;\n\n // find if the video is playing\n if ($('#mep_' + matches[i]).find('.mejs-pause')[0]){\n parameter.playing = true;\n }\n\n // replace old container with new\n $('#mep_' + matches[i]).replaceWith(container);\n\n // install player\n install(container, parameter);\n }\n }\n }\n\n // click on all possible video containers, watch if things change\n if (containers.length != 0) {\n\n // watch for changes for each container\n for(var i = 0; i < containers.length; i++) {\n\n // use mutation observer as per \n // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n\n // see if changes are to the child of the container\n if (mutation.type === 'childList') {\n\n // look through each child\n Array.prototype.forEach.call(mutation.target.children, function (child) {\n\n // match (only once per video) -- same code as if (matches) branch\n matches = document.body.innerHTML.match(/me_flash_\\d_container/g);\n if (matches) {\n for (var i = 0; i < matches.length; i++) {\n matches[i] = matches[i].replace(/\\D/g, '');\n\n // parameters for the videoplayer\n var parameter = {};\n parameter.audio = false;\n\n // set number for video classes \n parameter.number = matches[i];\n\n // get source for available video\n parameter.source = document.getElementById('mep_' + matches[i]).childNodes[0].childNodes[0].childNodes[1].src + '?1';\n if (parameter.source) {\n\n // get locally stored data for time\n var hist = JSON.parse(localStorage.getItem(parameter.source));\n if (hist) {\n parameter.time = hist.time;\n }\n\n // prepare new container\n var container = $('<div/>');\n\n // maximize player's width\n container.css('margin', '10px 0 0 0');\n container.css('padding', '0');\n container.css('width', '100%');\n\n // replace old container with new\n $('#mep_' + matches[i]).replaceWith(container);\n\n parameter.playing = false;\n\n // install player\n install(container, parameter);\n }\n }\n }\n });\n }\n });\n });\n\n // actually start observing\n observer.observe(containers[i], {\n childList: true,\n characterData: true,\n subtree: true\n });\n }\n\n // simulate click, waits for link to appear\n $('.media_comment_thumbnail').click(); \n } \n\n // no possible video containers, apologize\n else {\n apologize();\n }\n }\n}", "function init() {\n\t\tconsole.log('init');\n\t\t// Put event listeners into place\n\t\t// Notice that in this specific case handlers are loaded on the onload event\n\t\twindow.addEventListener(\n\t\t\t'DOMContentLoaded',\n\t\t\tfunction() {\n\t\t\t\t// Grab elements, create settings, etc.\n\t\t\t\tvar canvas = document.getElementById('canvas');\n\t\t\t\tvar context = canvas.getContext('2d');\n\t\t\t\t// context.transform(3,0,0,1,canvas.width,canvas.heigth);\n\t\t\t\tvar video = document.getElementById('video');\n\t\t\t\tvar mediaConfig = {\n\t\t\t\t\tvideo: true\n\t\t\t\t};\n\t\t\t\tvar errBack = function(e) {\n\t\t\t\t\tconsole.log('An error has occurred!', e);\n\t\t\t\t};\n\n\t\t\t\tlet aspectRatio = 2;\n\n\t\t\t\t// Put video listeners into place\n\t\t\t\tif (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n\t\t\t\t\tnavigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {\n\t\t\t\t\t\taspectRatio = stream.getVideoTracks()[0].getSettings().aspectRatio;\n\t\t\t\t\t\tdocument.getElementById('video-spinner').style.display = 'block';\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Trigger photo take\n\t\t\t\tdocument.getElementById('snap').addEventListener('click', function() {\n\t\t\t\t\tdocument.getElementsByClassName('canvas-container')[0].style.visibility = 'visible';\n\t\t\t\t\tlet heigth = 480;\n\n\t\t\t\t\tcontext.save();\n\t\t\t\t\tcontext.translate(480 * aspectRatio, 0);\n\t\t\t\t\tcontext.scale(-1, 1);\n\t\t\t\t\tcontext.drawImage(video, 0, 0, aspectRatio * heigth, heigth);\n\t\t\t\t\tcontext.restore();\n\t\t\t\t\tstate.photoSnapped = true; // photo has been taken\n\t\t\t\t});\n\n\t\t\t\t// Trigger when upload button is pressed\n\t\t\t\tif (document.getElementById('upload'))\n\t\t\t\t\tdocument.getElementById('upload').addEventListener('click', () => {\n\t\t\t\t\t\tdocument.getElementById('video-spinner').style.display = 'block';\n\t\t\t\t\t\t// uploadImage();\n\t\t\t\t\t\tselectImage();\n\t\t\t\t\t});\n\n\t\t\t\tif (document.getElementById('upload_search'))\n\t\t\t\t\tdocument.getElementById('upload_search').addEventListener('click', () => {\n\t\t\t\t\t\tdocument.getElementById('video-spinner').style.display = 'block';\n\t\t\t\t\t\t// searchImage();\n\t\t\t\t\t});\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}", "function drawCameraIntoCanvas() {\n // Draw the video element into the canvas\n ctx.drawImage(video, 0, 0, 640, 480);\n // We can call both functions to draw all keypoints and the skeletons\n drawKeypoints();\n drawSkeleton();\n window.requestAnimationFrame(drawCameraIntoCanvas);\n}", "function startVideo(){\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d').\n drawImage(video, 0, 0, canvas.width, canvas.height);\n $scope.sendPicture();\n}", "function paintToCanvas() {\n // We need to make sure canvas and video are the same width/height\n const width = video.videoWidth;\n const height = video.videoHeight;\n canvas.width = width;\n canvas.height = height;\n\n // Every couple seconds, take image from webcam and put it onto canvas\n return setInterval(() => {\n // drawImage: pass it an image/video and it will place it on the canvas\n ctx.drawImage(video, 0, 0, width, height);\n\n // Take pixels out\n let pixels = ctx.getImageData(0, 0, width, height); // huge array of pixels\n\n // Play around with pixels\n switch (this.className) {\n case 'red':\n pixels = redEffect(pixels);\n break;\n case 'split':\n ctx.globalAlpha = 0.1;\n pixels = rgbSplit(pixels);\n break;\n case 'green':\n pixels = greenScreen(pixels);\n }\n\n // Put pixels back into canvas\n ctx.putImageData(pixels, 0, 0);\n }, 16);\n}", "function drawCameraIntoCanvas() {\n // Draw the video element into the canvas\n drawKeypoints();\n window.requestAnimationFrame(drawCameraIntoCanvas);\n}", "function currentFrameCanvas(){\n let video = document.getElementById(\"video_id\");\n canvas = document.getElementById('screenShot');\n canvas.width = width;\n canvas.height = height;\n canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);\n}", "function drawCameraIntoCanvas() {\n\n // draw the video element into the canvas\n ctx.drawImage(video, 0, 0, video.width, video.height);\n \n if (body) {\n // draw circle for left and right Eye\n const leftWrist = body.getBodyPart(bodyParts.leftWrist);\n const rightWrist = body.getBodyPart(bodyParts.rightWrist);\n\n\n\n // draw left Eye\n ctx.beginPath();\n ctx.arc(leftWrist.position.x, leftWrist.position.y, 5, 0, 2 * Math.PI);\n ctx.fillStyle = 'white';\n ctx.fill();\n\n // draw right Eye\n ctx.beginPath();\n ctx.arc(rightWrist.position.x, rightWrist.position.y, 5, 0, 2 * Math.PI);\n ctx.fillStyle = 'white';\n ctx.fill();\n\n\n ctx.beginPath();\n ctx.moveTo(leftWrist.position.x,leftWrist.position.y);\n ctx.lineTo(rightWrist.position.x,rightWrist.position.y, 150);\n ctx.lineWidth = 10;\n ctx.strokeStyle = 'white';\n ctx.stroke();\n }\n requestAnimationFrame(drawCameraIntoCanvas);\n}", "function createCanvas() {\n // console.log(parseInt(pixelByPixel.value));\n selectedFrameData = null;\n selectedFrameData = {};\n layerCount = 0;\n framesArray = [],\n currentFrame = 0,\n playbackRunning = false,\n playbackInterval = null,\n unsavedFrame = false;\n removeListeners();\n resetFrames();\n resetLayers();\n resetSelectionState();\n addDisplayFrame(0);\n setCurrentFrame(0);\n initCanvas(\"2d\", parseInt(pixelByPixel.value));\n}", "function paintToCanvas() {\n // get the width and height of the actual live feed video\n const width = video.videoWidth;\n const height = video.videoHeight;\n\n // set canvas width and height to be the same as the live feed video\n canvas.width = width;\n canvas.height = height;\n\n // every 16ms, take the image from the webcam and put it into the canvas\n return setInterval(() => {\n ctx.drawImage(video, 0, 0, width, height);\n\n // take the pixels out\n let pixels = ctx.getImageData(0, 0, width, height);\n\n // mess with them\n // pixels = redEffect(pixels);\n\n // pixels = redSplit(pixels);\n // ctx.globalAlpha = 0.8;\n\n pixels = greenScreen(pixels);\n\n // put them back\n ctx.putImageData(pixels, 0, 0);\n }, 16);\n}", "function initPreview() {\n\t\n\t//clear the canvas first\n\tcanvasPreviewContext.clearRect(0, 0, canvasPreview.width, canvasPreview.height);\n\t\n\t//what file type are we dealing with\n\tif (fileType == \"VIDEO\") {\n\t\t\n\t\tsampleWidth = 50;\n\t\tsampleHeight = Math.floor((9/16)*sampleWidth);\n\t\tvideoArea.width = sampleWidth;\n\t\tvideoArea.height = sampleHeight;\n\t\t\n\t\t//reset size of the canvas\n\t\tcanvasPreview.width = sampleWidth;\n\t\tcanvasPreview.height = sampleHeight;\n\t\tpreviewArea.style.width = sampleWidth + \"px\";\n\t\tpreviewArea.style.height = sampleHeight + \"px\";\n\t\t\n\t\t//set the video in the videoArea so it starts playing\n\t\tvideoArea.type = file.type;\n\t\tvideoArea.src = fileURL;\n\t\t\n\t\t//set fileWidth\n\t\tfileWidth = sampleWidth;\n\t\tfileHeight = sampleHeight;\n\t\t\n\t\t//make a sample first\n\t\t/*canvasPreviewContext.drawImage(videoArea, 0, 0, videoArea.width, videoArea.height);*/\n\t\t\n\t\t//initBuffers();\n\t\t\n\t\t\n\t\t/*document.onclick = function() {\n\t\t\tinitCubes();\n\t\t}*/\n\t\t\n\t\t//keep updating cubes based on the options\n\t\t//startUpdateCubesInterval();\n\t\tsetTimeout(initPlanes, 2000);\n\t\tstartUpdatePlanesInterval();\n\t\tstopUpdateCubesInterval();\n\t\t\n\t\t//keep rendering the screen based on mouse/camera position\n\t\tstartThreeInterval();\n\n\t\t\n\t} else if (fileType == \"IMAGE\") {\n\t\t\n\t\t\n\t\tsampleWidth = 30;\n\t\tsampleHeight = Math.floor((9/16)*sampleWidth);\n\t\t\n\t\t//load the image data and display in the preview\n\t\tvar img = new Image();\n\t\timg.onload = function() {\n\n\t\t\t//get the image dimensions so we can drawImage at the right aspect ratio\n\t\t\tsetNewFileDimensions(img);\n\t\t\t\n\t\t\t//draw the image onto the canvas\n\t\t canvasPreviewContext.drawImage(img, 0, 0, fileWidth, fileHeight);\n\t\t\t\n\t\t\t//initBuffers();\n\t\t\tinitCubes();\n\t\t\t//initPlanes();\n\t\t\t\n\t\t\t//keep updating cubes based on the options\n\t\t\tstartUpdateCubesInterval();\n\t\t\tstopUpdatePlanesInterval();\n\t\t\t\n\t\t\t//keep rendering the screen based on mouse/camera position\n\t\t\tstartThreeInterval();\n\n\t\t}\n\t\t\n\t\t//set the src of our new file\n\t\timg.src = fileURL;\n\t\t\n\t\t//we should clear the video tag\n\t\tvideoArea.type = \"\";\n\t\tvideoArea.src = \"\";\n\t\tvideoArea.pause();\n\t\t\n\t\t//we should stop sampling the video if its there\n\t\tstopSamplingVideo();\n\t\t\n\t}\n\t\n}", "function FrameInitalizer(canvas, form, video, options) {\n //Opt parse.\n options = options || {};\n this.drawFrame = options.override_frame_draw || this._drawFrame\n this.drawImage = options.override_image_draw || this._drawImage\n this.drawPolygons = options.override_polygon_draw || this._drawPolygons\n //I might add a string to the OnChange functions that says where they were called from.\n //I could also add stuff like OnClear or whatever, not really sure I wanna go for that.\n //A return a reference to the previous state?\n //You shouldn't need these unless you do web worker stuff anyways.\n this.onImageChange = options.on_image_change_functor || (function(self) {\n return; //self.drawFrame() //Do nothing, if they want to draw on every update, let them set this.\n });\n this.onPolygonChange = options.on_polygon_change_functor || (function(self) {\n return; //self.drawFrame(); //Do nothing, if they want to draw on every update, let them set this.\n });\n this.source = options.source || null;\n this.number_of_frames = options.number_of_frames || 1;\n //Mandatory positional args.\n this.canvas = canvas;\n this.form = form;\n this.video = video; //video element;\n this.frames = [new _FrameTracker(0)];\n this.frame_index = 0;\n this.updateFrameList(1);\n }", "function initialize() {\n // Create a canvas element to which we will copy video.\n canvas = document.createElement('canvas');\n var webcamDimensions = webcam.getDimensions();\n canvas.width = webcamDimensions.width;\n canvas.height = webcamDimensions.height;\n\n // We need a context for the canvas in order to copy to it.\n context = canvas.getContext('2d');\n\n // create an AR Marker detector using the canvas as the data source\n detector = ardetector.create( canvas );\n\n // Create an AR View for displaying the augmented reality scene\n view = arview.create( webcam.getDimensions(), canvas );\n\n // Set the ARView camera projection matrix according to the detector\n view.setCameraMatrix( detector.getCameraMatrix(10,1000) );\n\n // Place the arview's GL canvas into the DOM.\n document.getElementById(\"application\").appendChild( view.glCanvas );\n }", "function setup() {\n createCanvas(640, 480, P2D); // canvas has same dimensions as my webcam\n background(0);\n stroke(0, 255, 0);\n noFill();\n\n // make sure the framerate is the same between sending and receiving\n frameRate(30);\n\n // Set to true to turn on logging for the webrtc client\n WebRTCPeerClient.setDebug(true);\n\n // To connect to server over public internet pass the ngrok address\n // See https://github.com/lisajamhoury/WebRTC-Simple-Peer-Examples#to-run-signal-server-online-with-ngrok\n WebRTCPeerClient.initSocketClient('https://XXXXXXXX.ngrok.io/');\n\n // Start the peer client\n WebRTCPeerClient.initPeerClient();\n\n // start your video\n // your webcam will always appear below the canvas\n myVideo = createCapture(VIDEO);\n myVideo.size(width, height);\n myVideo.hide();\n\n ////// HOW TO DEFINE OTHER PERSON'S VIDEO? //////\n // otherVideo = createCapture(VIDEO);\n // otherVideo.size(width, height);\n\n}", "function paintToCanvas() { //to display webcame live in a specified canvas with videos actual height and width\n\n const width = video.videoWidth; //getting actual height and width of video\n const height = video.videoHeight;\n canvas.width = width; //setting the canvas width and height accordingly \n canvas.height = height;\n return setInterval(() => { //by setintertval method we are drawing the recieved video's image in after every 16milli sec \n ctx.drawImage(video, 0, 0, width, height); //here we are drawing the image recieved in canvas\n let pixels = ctx.getImageData(0, 0, width, height) //here we are getting the canvas image to make some effect\n // console.log(pixels)\n // debugger;\n // pixels = redeffect(pixels) //here redeffect is called\n // console.log(hola);\n pixels = rgbsplit(pixels) // we are calling rgb split to make some changes in the pixels thats is the image we get from canvas\n ctx.globalAlpha=0.8; \n // pixels = greenscreen(pixels)\n ctx.putImageData(pixels, 0, 0); //after we get the changed pixels we put it back in the canvas\n }, 16);\n}", "function setup() {\n createCanvas(640, 480);\n video = select(\"video\") || createCapture(VIDEO);\n video.size(width, height);\n\n const poseNet = ml5.poseNet(video, { flipHorizontal: true }, () => {\n select(\"#status\").hide();\n });\n\n poseNet.on(\"pose\", (newPoses) => {\n poses = newPoses;\n });\n\n // Hide the video element, and just show the canvas\n video.hide();\n}", "function ytInject() {\n injectStyle();\n injectCanvas();\n injectButton();\n\n $(window).resize(function() {\n var main = $('#vt-main-div').get(0);\n var canvas = $('#vt-canvas').get(0);\n\n main.style.height = $('.video-stream').height();\n main.style.width = $('.video-stream').width();\n $('#vt-canvas').height($('vt-main-div').height());\n $('#vt-canvas').width($('vt-main-div').width());\n\n //Scale the canvas to achieve proper resolution\n canvas.width=$('#vt-main-div').width()*window.devicePixelRatio;\n canvas.height=$('#vt-main-div').height()*window.devicePixelRatio;\n canvas.style.width=$('#vt-main-div').width() + \"px\";\n canvas.style.height=$('#vt-main-div').height() + \"px\";\n });\n}", "setup(canvas) {\n this.engine.renderer.setup(canvas);\n this.start();\n }", "function start() {\n if (initialized)\n return;\n\n let myCanvas = document.getElementById(\"canvas\");\n myCanvas.classList.toggle(\"hide\");\n\n let button = document.getElementById(\"webcamButton\");\n button.classList.add(\"hide\");\n\n window.ctx = myCanvas.getContext('2d', {alpha: false});\n\n var mycamvas = new camvas(window.ctx, processFrame);\n initialized = true;\n}", "function drawVedio() {\n setTimeout(() => {\n canvas.getContext(\"2d\").drawImage(video, 0, 0, 100, 100);\n drawVedio();\n }, 0);\n }", "function setupMotionDetection() {\n md_canvas = document.getElementById('mdCanvas');\n test_canvas = document.getElementById('testCanvas');\n md_canvas.width = vid_width;\n md_canvas.height = vid_height;\n}", "function prepareCanvas() {\n canvas = window._canvas = new fabric.Canvas('canvas');\n canvas.backgroundColor = '#ffffff';\n canvas.isDrawingMode = 1;\n canvas.freeDrawingBrush.color = \"black\";\n canvas.freeDrawingBrush.width = 1;\n canvas.renderAll();\n //setup listeners \n canvas.on('mouse:up', function(e) {\n getFrame();\n mousePressed = false\n });\n canvas.on('mouse:down', function(e) {\n mousePressed = true\n });\n canvas.on('mouse:move', function(e) {\n recordCoor(e)\n });\n}", "function setupCanvas() {\n// setup everything else\n\tconsole.log(\"Setting up canvas...\")\n\tcanvas = document.getElementById(\"drone-sim-canvas\");\n\twindow.addEventListener(\"keyup\", keyFunctionUp, false);\n\twindow.addEventListener(\"keydown\", keyFunctionDown, false);\n\twindow.onresize = doResize;\n\tcanvas.width = window.innerWidth-16;\n\tcanvas.height = window.innerHeight-200;\n\tconsole.log(\"Done.\")\n}" ]
[ "0.78905183", "0.73323876", "0.7324095", "0.6902919", "0.6802968", "0.6754874", "0.674903", "0.67110926", "0.6707982", "0.66969913", "0.66809857", "0.6675698", "0.6649001", "0.65843296", "0.65676445", "0.65668964", "0.65466964", "0.65347123", "0.6457012", "0.6453839", "0.6424336", "0.64237124", "0.6419021", "0.63978547", "0.6386163", "0.6385013", "0.63836545", "0.63807344", "0.63210124", "0.63173777" ]
0.7507471
1
Connect the proper camera to the video element, trying to get a camera with facing mode of "user".
async function connect_camera() { try { let stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: false }); video_element.srcObject = stream; video_element.setAttribute('playsinline', true); video_element.setAttribute('controls', true); // remove controls separately setTimeout(function() { video_element.removeAttribute('controls'); }); } catch(error) { console.error("Got an error while looking for video camera: " + error); return null; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async function setupCamera() {\n const video = document.getElementById('video')\n video.width = videoWidth\n video.height = videoHeight\n\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: {\n facingMode: 'user',\n width: videoWidth,\n height: videoHeight\n }\n })\n video.srcObject = stream\n\n return new Promise(resolve => {\n video.onloadedmetadata = () => {\n resolve(video)\n }\n })\n}", "function cameraSetup(){\n\t// Get access to the camera!\n\tif('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {\n\t\t// Not adding `{ audio: true }` since we only want video now\n\t\tnavigator.mediaDevices.getUserMedia({\n\t\t\t//Kamera Constrains:\n\t\t\t\n\t\t\tvideo: \n\t\t\t{\n\t\t\t\twidth: {ideal: 50},\n\t\t\t\theight: {ideal: 50},\n\t\t\t\tfacingMode: ['environment']\n\t\t\t}\n\t\t\t}).then(function(stream) {\n\t\t\t\tstreamVideo = stream;\n\t\t\t\tcameraOk = true;\n\t\t\t\tvideo.srcObject = stream;\n\t\t\t\tvideo.play();\n\n\t\t\t\tvar track = stream.getVideoTracks()[0];\n\t\t\t\t//Taschenlampe einschalten:\n\t\t\t\tconst imageCapture = new ImageCapture(track)\n\t\t\t\tconst photoCapabilities = imageCapture.getPhotoCapabilities().then(() => {\n\t\t\t\t\ttrack.applyConstraints({\n\t\t\t\t\t\tadvanced: [{torch: true}]\n\t\t\t\t\t});\n\t\t\t\t});\n\n\n\n\t\t\t});\n\t\t}\n\n\n\t}", "async function setupCamera() {\n const video = document.getElementById('video');\n const canvas = document.getElementById('canvas');\n if (!video || !canvas) return null;\n\n let msg = '';\n log('Setting up camera');\n // setup webcam. note that navigator.mediaDevices requires that page is accessed via https\n if (!navigator.mediaDevices) {\n log('Camera Error: access not supported');\n return null;\n }\n let stream;\n const constraints = {\n audio: false,\n video: { facingMode: 'user', resizeMode: 'crop-and-scale' },\n };\n if (window.innerWidth > window.innerHeight) constraints.video.width = { ideal: window.innerWidth };\n else constraints.video.height = { ideal: window.innerHeight };\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraints);\n } catch (err) {\n if (err.name === 'PermissionDeniedError' || err.name === 'NotAllowedError') msg = 'camera permission denied';\n else if (err.name === 'SourceUnavailableError') msg = 'camera not available';\n log(`Camera Error: ${msg}: ${err.message || err}`);\n return null;\n }\n // @ts-ignore\n if (stream) video.srcObject = stream;\n else {\n log('Camera Error: stream empty');\n return null;\n }\n const track = stream.getVideoTracks()[0];\n const settings = track.getSettings();\n if (settings.deviceId) delete settings.deviceId;\n if (settings.groupId) delete settings.groupId;\n if (settings.aspectRatio) settings.aspectRatio = Math.trunc(100 * settings.aspectRatio) / 100;\n log(`Camera active: ${track.label}`); // ${str(constraints)}\n log(`Camera settings: ${str(settings)}`);\n canvas.addEventListener('click', () => {\n // @ts-ignore\n if (video && video.readyState >= 2) {\n // @ts-ignore\n if (video.paused) {\n // @ts-ignore\n video.play();\n detectVideo(video, canvas);\n } else {\n // @ts-ignore\n video.pause();\n }\n }\n // @ts-ignore\n log(`Camera state: ${video.paused ? 'paused' : 'playing'}`);\n });\n return new Promise((resolve) => {\n video.onloadeddata = async () => {\n // @ts-ignore\n canvas.width = video.videoWidth;\n // @ts-ignore\n canvas.height = video.videoHeight;\n // @ts-ignore\n video.play();\n detectVideo(video, canvas);\n resolve(true);\n };\n });\n}", "async function setupCamera() {\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n throw new Error(\n 'Browser API navigator.mediaDevices.getUserMedia not available');\n }\n\n const video = document.getElementById('video');\n video.width = videoWidth;\n video.height = videoHeight;\n\n const mobile = isMobile();\n const stream = await navigator.mediaDevices.getUserMedia({\n 'audio': false,\n 'video': {\n facingMode: 'user',\n width: mobile ? undefined : videoWidth,\n height: mobile ? undefined : videoHeight,\n },\n });\n video.srcObject = stream;\n\n return new Promise((resolve) => {\n video.onloadedmetadata = () => {\n resolve(video);\n };\n });\n}", "async function setupCamera() {\n const video = document.getElementById('video');\n video.width = maxVideoSize;\n video.height = maxVideoSize;\n\n if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n const mobile = isMobile();\n const stream = await navigator.mediaDevices.getUserMedia({\n 'audio': false,\n 'video': {\n facingMode: 'environment',\n width: mobile ? undefined : maxVideoSize,\n height: mobile ? undefined: maxVideoSize}\n });\n video.srcObject = stream;\n\n return new Promise(resolve => {\n video.onloadedmetadata = () => {\n resolve(video);\n };\n });\n } else {\n const errorMessage = \"This browser does not support video capture, or this device does not have a camera\";\n alert(errorMessage);\n return Promise.reject(errorMessage);\n }\n}", "async function setupCamera() {\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n throw new Error(\n 'Browser API navigator.mediaDevices.getUserMedia not available');\n }\n\n const video = document.getElementById('webcam-video');\n video.width = videoWidth;\n video.height = videoHeight;\n\n // const mobile = isMobile();\n const stream = await navigator.mediaDevices.getUserMedia({\n 'audio': false,\n 'video': {\n facingMode: 'user',\n width: videoWidth,\n height: videoHeight,\n },\n });\n video.srcObject = stream;\n\n return new Promise((resolve) => {\n video.onloadedmetadata = () => {\n resolve(video);\n };\n });\n}", "async function setupCamera() {\n const video = document.getElementById('video');\n video.width = maxVideoSize;\n video.height = maxVideoSize;\n\n if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n const mobile = isMobile();\n const stream = await navigator.mediaDevices.getUserMedia({\n 'audio': false,\n 'video': {\n facingMode: 'user',\n width: mobile ? undefined : maxVideoSize,\n height: mobile ? undefined: maxVideoSize}\n });\n video.srcObject = stream;\n\n return new Promise(resolve => {\n video.onloadedmetadata = () => {\n resolve(video);\n };\n });\n } else {\n const errorMessage = \"This browser does not support video capture, or this device does not have a camera\";\n alert(errorMessage);\n return Promise.reject(errorMessage);\n }\n}", "function startCamera() {\n\n let constraints = {\n audio: false,\n video: {\n width: 640,\n height: 480,\n frameRate: 30\n }\n }\n\n video.setAttribute('width', 640);\n video.setAttribute('height', 480);\n video.setAttribute('autoplay', '');\n video.setAttribute('muted', '');\n video.setAttribute('playsinline', '');\n\n // Start video playback once the camera was fetched.\n function onStreamFetched(mediaStream) {\n video.srcObject = mediaStream;\n // Check whether we know the video dimensions yet, if so, start BRFv4.\n function onStreamDimensionsAvailable() {\n if (video.videoWidth === 0) {\n setTimeout(onStreamDimensionsAvailable, 100);\n } else {\n\n }\n }\n onStreamDimensionsAvailable();\n }\n\n window.navigator.mediaDevices.getUserMedia(constraints).then(onStreamFetched).catch(function() {\n alert(\"No camera available.\");\n });\n}", "function startvideo() {\n webcam.style.width = document.width + 'px';\n webcam.style.height = document.height + 'px';\n webcam.setAttribute('autoplay', '');\n webcam.setAttribute('muted', '');\n\twebcam.setAttribute('playsinline', '');\n\n var constraints = {\n audio: false,\n video: {\n facingMode: 'user'\n }\n }\n \tnavigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {\n webcam.srcObject = stream;\n initImages();\n animate();\n });\n}", "function loadCamera() {\n // setup camera capture\n videoInput = createCapture(VIDEO);\n videoInput.size(400, 300);\n videoInput.position(0, 0);\n videoInput.id(\"v\");\n var mv = document.getElementById(\"v\");\n mv.muted = true;\n}", "async function setupCamera() {\r\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\r\n throw new Error(\r\n 'Browser API navigator.mediaDevices.getUserMedia not available');\r\n }\r\n\r\n const camera = document.getElementById('camera');\r\n camera.width = cameraWidth;\r\n camera.height = cameraHeight;\r\n\r\n const mobile = isMobile();\r\n\r\n const stream = await navigator.mediaDevices.getUserMedia({\r\n 'audio': false,\r\n 'video': {\r\n facingMode: 'user',\r\n width: mobile ? undefined : cameraWidth,\r\n height: mobile ? undefined : cameraHeight,\r\n },\r\n });\r\n camera.srcObject = stream;\r\n\r\n return new Promise((resolve) => {\r\n camera.onloadedmetadata = () => {\r\n resolve(camera);\r\n };\r\n });\r\n}", "async start() {\n if (this.webcamConfig.facingMode) {\n util.assert((this.webcamConfig.facingMode === 'user') ||\n (this.webcamConfig.facingMode === 'environment'), () => `Invalid webcam facing mode: ${this.webcamConfig.facingMode}. ` +\n `Please provide 'user' or 'environment'`);\n }\n try {\n this.stream = await navigator.mediaDevices.getUserMedia({\n video: {\n deviceId: this.webcamConfig.deviceId,\n facingMode: this.webcamConfig.facingMode ?\n this.webcamConfig.facingMode :\n 'user',\n width: this.webcamVideoElement.width,\n height: this.webcamVideoElement.height\n }\n });\n }\n catch (e) {\n // Modify the error message but leave the stack trace intact\n e.message = `Error thrown while initializing video stream: ${e.message}`;\n throw e;\n }\n if (!this.stream) {\n throw new Error('Could not obtain video from webcam.');\n }\n // Older browsers may not have srcObject\n try {\n this.webcamVideoElement.srcObject = this.stream;\n }\n catch (error) {\n console.log(error);\n this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);\n }\n // Start the webcam video stream\n this.webcamVideoElement.play();\n this.isClosed = false;\n return new Promise(resolve => {\n // Add event listener to make sure the webcam has been fully initialized.\n this.webcamVideoElement.onloadedmetadata = () => {\n resolve();\n };\n });\n }", "function cameraStart() {\n if(selfie === true){\n cameraView.classList.replace(\"user\", \"environment\");\n cameraOutput.classList.replace(\"user\", \"environment\");\n cameraSensor.classList.replace(\"user\", \"environment\");\n constraints = rearConstraints;\n selfie = false;\n }\n else{\n cameraView.classList.replace(\"environment\", \"user\");\n cameraOutput.classList.replace(\"environment\", \"user\");\n cameraSensor.classList.replace(\"environment\", \"user\");\n constraints = userConstraints;\n selfie = true;\n }\n\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cameraStartFront() { \n frontCamera = true\n var constraints = { video: { facingMode: \"user\" }, audio: false };\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cameraStart() {\n cameraView = document.querySelector(\"#webcam\");\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cam() {\n snapBtn.addEventListener('click', enroll);\n // detectButton.addEventListener('click', detect);\n navigator.mediaDevices.getUserMedia({\n audio: false,\n video: {\n width: 500,\n height: 500\n }\n })\n .then(stream => {\n video.srcObject = stream;\n video.onloadedmetadata = video.play()\n })\n .catch(err => console.error(err));\n}", "_switchCamera() {\n if (this.isVideoTrack() && this.videoType === _service_RTC_VideoType__WEBPACK_IMPORTED_MODULE_10___default.a.CAMERA && typeof this.track._switchCamera === 'function') {\n this.track._switchCamera();\n\n this._facingMode = this._facingMode === _service_RTC_CameraFacingMode__WEBPACK_IMPORTED_MODULE_7___default.a.ENVIRONMENT ? _service_RTC_CameraFacingMode__WEBPACK_IMPORTED_MODULE_7___default.a.USER : _service_RTC_CameraFacingMode__WEBPACK_IMPORTED_MODULE_7___default.a.ENVIRONMENT;\n }\n }", "function getCamera(){\n document.getElementById('ownGifs').style.display=\"none\"\n document.getElementById('createGif').style.display=\"none\";\n document.getElementById('camera').style.display=\"inline-block\";\n var video = document.querySelector('video');\n stream = navigator.mediaDevices.getUserMedia(constraints)\n .then(function(mediaStream) {\n video.srcObject = mediaStream;\n video.onloadedmetadata = function(e) {\n video.play(); // Starting reproduce video cam\n };\n recorder = RecordRTC(mediaStream, { \n // disable logs\n disableLogs: true,\n type: \"gif\",\n frameRate: 1,\n width: 360,\n hidden: 240,\n quality: 10});\n })\n .catch(function(err) { \n\n }); // always check for errors at the end.\n\n \n}", "async function setupCamera (config) {\n const { videoWidth, videoHeight } = config\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n throw new Error(\n 'Browser API navigator.mediaDevices.getUserMedia not available'\n )\n }\n\n const video = document.getElementById('video')\n video.width = videoWidth\n video.height = videoHeight\n\n const mobile = isMobile()\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: {\n facingMode: 'user',\n width: mobile ? undefined : videoWidth,\n height: mobile ? undefined : videoHeight\n }\n })\n video.srcObject = stream\n\n return new Promise(resolve => {\n video.onloadedmetadata = () => {\n resolve(video)\n }\n })\n}", "function cameraStart() {\r\n navigator.mediaDevices\r\n .getUserMedia(constraints)\r\n .then(function(stream) {\r\n track = stream.getTracks()[0];\r\n cameraView.srcObject = stream;\r\n })\r\n .catch(function(error) {\r\n console.error(\"Oops. Something is broken.\", error);\r\n });\r\n}", "function cameraStart() {\r\n navigator.mediaDevices\r\n .getUserMedia(constraints)\r\n .then(function(stream) {\r\n track = stream.getTracks()[0];\r\n cameraView.srcObject = stream;\r\n })\r\n .catch(function(error) {\r\n console.error(\"Oops. Something is broken.\", error);\r\n });\r\n}", "async start() {\n if (this.webcamConfig.facingMode) {\n _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"util\"].assert((this.webcamConfig.facingMode === 'user') ||\n (this.webcamConfig.facingMode === 'environment'), () => `Invalid webcam facing mode: ${this.webcamConfig.facingMode}. ` +\n `Please provide 'user' or 'environment'`);\n }\n try {\n this.stream = await navigator.mediaDevices.getUserMedia({\n video: {\n deviceId: this.webcamConfig.deviceId,\n facingMode: this.webcamConfig.facingMode ?\n this.webcamConfig.facingMode :\n 'user',\n width: this.webcamVideoElement.width,\n height: this.webcamVideoElement.height\n }\n });\n }\n catch (e) {\n // Modify the error message but leave the stack trace intact\n e.message = `Error thrown while initializing video stream: ${e.message}`;\n throw e;\n }\n if (!this.stream) {\n throw new Error('Could not obtain video from webcam.');\n }\n // Older browsers may not have srcObject\n try {\n this.webcamVideoElement.srcObject = this.stream;\n }\n catch (error) {\n console.log(error);\n this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);\n }\n // Start the webcam video stream\n this.webcamVideoElement.play();\n this.isClosed = false;\n return new Promise(resolve => {\n // Add event listener to make sure the webcam has been fully initialized.\n this.webcamVideoElement.onloadedmetadata = () => {\n resolve();\n };\n });\n }", "function cameraStart() {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function (stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function (error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function startVideo(){\n //gets the webcam, takes object as the first param, video is key, empty object as param\n navigator.getUserMedia(\n {video: {}},\n //whats coming from our webcam, setting it as source\n stream =>video.srcObject = stream,\n err => console.log(err))\n}", "function cameraStart() {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cameraStart() {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cameraStart() {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function cameraStart() {\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(function(stream) {\n track = stream.getTracks()[0];\n cameraView.srcObject = stream;\n })\n .catch(function(error) {\n console.error(\"Oops. Something is broken.\", error);\n });\n}", "function setupCamera() {\n camera = new PerspectiveCamera(35, config.Screen.RATIO, 0.1, 300);\n camera.position.set(0, 8, 20);\n //camera.rotation.set(0,0,0);\n //camera.lookAt(player.position);\n console.log(\"Finished setting up Camera...\"\n + \"with x\" + camera.rotation.x + \" y:\" + camera.rotation.y + \" z:\" + camera.rotation.z);\n }", "async function setupCamera() {\n let depthStream = await DepthCamera.getDepthStream();\n const depthVideo = document.getElementById('depthStream');\n depthVideo.srcObject = depthStream;\n return DepthCamera.getCameraCalibration(depthStream);\n}" ]
[ "0.76734245", "0.74210167", "0.7339442", "0.7298811", "0.72884417", "0.72826576", "0.72387886", "0.7193497", "0.7098979", "0.709148", "0.70444125", "0.7037726", "0.70060045", "0.6965139", "0.6923468", "0.6908866", "0.6832422", "0.68167394", "0.6798288", "0.67865056", "0.6764955", "0.6762703", "0.6756786", "0.67466146", "0.67402864", "0.67402864", "0.6718014", "0.6718014", "0.667351", "0.6665457" ]
0.8200102
0
converts it to a base b number. Return the new number as a string E.g. base_converter(5, 2) == "101" base_converter(31, 16) == "1f"
function baseConverter(num, b) { if (num === 0) { return "" }; const digit = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; return baseConverter((num/b), b) + digit[num % b]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function baseConverter(num, base) {\n const bases = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n const possibleBases = bases.slice(0, base)\n\n let result = [];\n\n while (num >= base) {\n result.unshift(possibleBases[num % base])\n num = Math.floor(num / base)\n }\n result.unshift(num)\n return result.join(\"\")\n}", "function baseConverter(decNumber, base) {\n\n\tvar remStack = new Stack(),\n\t\trem,\n\t\tbaseString = '';\n\t\tdigits = '0123456789ABCDEF';\n\n\twhile(decNumber > 0) {\n\t\trem = Math.floor(decNumber % base);\n\t\tremStack.push(rem);\n\t\tdecNumber = Math.floor(decNumber / base);\n\t}\n\n\twhile(!remStack.isEmpty()) {\n\t\tbaseString += digits[remStack.pop()];\n\t}\n\n\treturn baseString;\n}", "function strBaseConverter (number,ob,nb) {\n number = number.toUpperCase();\n var list = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var dec = 0;\n for (var i = 0; i <= number.length; i++) {\n dec += (list.indexOf(number.charAt(i))) * (Math.pow(ob , (number.length - i - 1)));\n }\n number = '';\n var magnitude = Math.floor((Math.log(dec)) / (Math.log(nb)));\n for (var i = magnitude; i >= 0; i--) {\n var amount = Math.floor(dec / Math.pow(nb,i));\n number = number + list.charAt(amount);\n dec -= amount * (Math.pow(nb,i));\n }\n return number;\n}", "function baseConvert(base, number) {\n if (checkNum()) {\n let conversion = 0;\n let digits = number.split('').map(Number).reverse();\n base = Number(base);\n for (let place = digits.length - 1; place >= 0; place--) {\n conversion += (Math.pow(base, place)) * digits[place];\n }\n return conversion;\n }\n }", "toBase10(value, b = 62) {\n const limit = value.length;\n let result = base.indexOf(value[0]);\n for (let i = 1; i < limit; i++) {\n result = b * result + base.indexOf(value[i]);\n }\n return result;\n }", "function h$ghcjsbn_showBase(b, base) {\n h$ghcjsbn_assertValid_b(b, \"showBase\");\n h$ghcjsbn_assertValid_s(base, \"showBase\");\n if(h$ghcjsbn_cmp_bb(b, h$ghcjsbn_zero_b) === 1) {\n return \"0\";\n } else {\n return h$ghcjsbn_showBase_rec(b, base, Math.log(base), 0);\n }\n}", "function h$ghcjsbn_showBase(b, base) {\n h$ghcjsbn_assertValid_b(b, \"showBase\");\n h$ghcjsbn_assertValid_s(base, \"showBase\");\n if(h$ghcjsbn_cmp_bb(b, h$ghcjsbn_zero_b) === 1) {\n return \"0\";\n } else {\n return h$ghcjsbn_showBase_rec(b, base, Math.log(base), 0);\n }\n}", "function h$ghcjsbn_showBase(b, base) {\n h$ghcjsbn_assertValid_b(b, \"showBase\");\n h$ghcjsbn_assertValid_s(base, \"showBase\");\n if(h$ghcjsbn_cmp_bb(b, h$ghcjsbn_zero_b) === 1) {\n return \"0\";\n } else {\n return h$ghcjsbn_showBase_rec(b, base, Math.log(base), 0);\n }\n}", "function h$ghcjsbn_showBase(b, base) {\n h$ghcjsbn_assertValid_b(b, \"showBase\");\n h$ghcjsbn_assertValid_s(base, \"showBase\");\n if(h$ghcjsbn_cmp_bb(b, h$ghcjsbn_zero_b) === 1) {\n return \"0\";\n } else {\n return h$ghcjsbn_showBase_rec(b, base, Math.log(base), 0);\n }\n}", "function convertBase(str, fromBase, toBase) {\n const digits = parseToDigitsArray(str, fromBase);\n if (digits === null) return null;\n\n let outArray = [];\n let power = [1];\n for (let i = 0; i < digits.length; i += 1) {\n // invariant: at this point, fromBase^i = power\n if (digits[i]) {\n outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);\n }\n power = multiplyByNumber(fromBase, power, toBase);\n }\n\n let out = '';\n for (let i = outArray.length - 1; i >= 0; i -= 1) {\n out += outArray[i].toString(toBase);\n }\n // if the original input was equivalent to zero, then 'out' will still be empty ''. Let's check for zero.\n if (out === '') {\n let sum = 0;\n for (let i = 0; i < digits.length; i += 1) {\n sum += digits[i];\n }\n if (sum === 0) out = '0';\n }\n\n return out;\n}", "function base(dec, base) {\n var len = base.length;\n var ret = '';\n while(dec > 0) {\n ret = base.charAt(dec % len) + ret;\n dec = Math.floor(dec / len);\n }\n return ret;\n}", "function $builtin_base_convert_helper(obj, base) {\n var prefix = \"\";\n switch(base){\n case 2:\n prefix = '0b'; break\n case 8:\n prefix = '0o'; break\n case 16:\n prefix = '0x'; break\n default:\n console.log('invalid base:' + base)\n }\n\n if(obj.__class__ === $B.long_int){\n var res = prefix + obj.value.toString(base)\n return res\n }\n\n var value = $B.$GetInt(obj)\n\n if(value === undefined){\n // need to raise an error\n throw _b_.TypeError.$factory('Error, argument must be an integer or' +\n ' contains an __index__ function')\n }\n\n if(value >= 0){return prefix + value.toString(base)}\n return '-' + prefix + (-value).toString(base)\n}", "function h$ghcjsbn_showBase(b, base) {\n ASSERTVALID_B(b, \"showBase\");\n ASSERTVALID_S(base, \"showBase\");\n if(h$ghcjsbn_cmp_bb(b, h$ghcjsbn_zero_b) === GHCJSBN_EQ) {\n return \"0\";\n } else {\n return h$ghcjsbn_showBase_rec(b, base, Math.log(base), 0);\n }\n}", "function toBaseOut(str,baseIn,baseOut,alphabet){var j,arr=[0],arrL,i=0,len=str.length;for(;i<len;){for(arrL=arr.length;arrL--;arr[arrL]*=baseIn){;}arr[0]+=alphabet.indexOf(str.charAt(i++));for(j=0;j<arr.length;j++){if(arr[j]>baseOut-1){if(arr[j+1]==null)arr[j+1]=0;arr[j+1]+=arr[j]/baseOut|0;arr[j]%=baseOut}}}return arr.reverse()}// Convert a numeric string of baseIn to a numeric string of baseOut.", "function decimalToBase(decNumber, base) {\n if (!Number.isInteger(decNumber) || !Number.isInteger(base)) {\n throw TypeError('input number is not an integer');\n }\n if (!(base >= 2 && base <= 36)) {\n throw Error('invalid base')\n }\n\n const remStack = new Stack();\n const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\n let number = decNumber;\n let rem;\n let stringified = '';\n\n while (number > 0) {\n rem = number % base;\n remStack.push(rem);\n number = Math.floor(number / base);\n }\n\n while (!remStack.isEmpty()) {\n stringified += digits[remStack.pop()].toString();\n }\n\n return stringified;\n}", "toBase(value, b = 62) {\n let r = value % b;\n let result = base[r];\n let q = Math.floor(value / b);\n while (q) {\n r = q % b;\n q = Math.floor(q / b);\n result = base[r] + result;\n }\n return result;\n }", "function baseConvert(obj, begBase, endBase ){\n if (begBase < 2 && endBase > 36){\n throw new Error(\"Bases are not valid\");\n }else {\n return parseInt(obj, begBase).toString(endBase);\n }\n}", "function convertBase( str, baseOut, baseIn, sign ) {\n\t var d, e, k, r, x, xc, y,\n\t i = str.indexOf( '.' ),\n\t dp = DECIMAL_PLACES,\n\t rm = ROUNDING_MODE;\n\n\t if ( baseIn < 37 ) str = str.toLowerCase();\n\n\t // Non-integer.\n\t if ( i >= 0 ) {\n\t k = POW_PRECISION;\n\n\t // Unlimited precision.\n\t POW_PRECISION = 0;\n\t str = str.replace( '.', '' );\n\t y = new BigNumber(baseIn);\n\t x = y.pow( str.length - i );\n\t POW_PRECISION = k;\n\n\t // Convert str as if an integer, then restore the fraction part by dividing the\n\t // result by its base raised to a power.\n\t y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n\t y.e = y.c.length;\n\t }\n\n\t // Convert the number as integer.\n\t xc = toBaseOut( str, baseIn, baseOut );\n\t e = k = xc.length;\n\n\t // Remove trailing zeros.\n\t for ( ; xc[--k] == 0; xc.pop() );\n\t if ( !xc[0] ) return '0';\n\n\t if ( i < 0 ) {\n\t --e;\n\t } else {\n\t x.c = xc;\n\t x.e = e;\n\n\t // sign is needed for correct rounding.\n\t x.s = sign;\n\t x = div( x, y, dp, rm, baseOut );\n\t xc = x.c;\n\t r = x.r;\n\t e = x.e;\n\t }\n\n\t d = e + dp + 1;\n\n\t // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n\t i = xc[d];\n\t k = baseOut / 2;\n\t r = r || d < 0 || xc[d + 1] != null;\n\n\t r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n\t : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n\t rm == ( x.s < 0 ? 8 : 7 ) );\n\n\t if ( d < 1 || !xc[0] ) {\n\n\t // 1^-dp or 0.\n\t str = r ? toFixedPoint( '1', -dp ) : '0';\n\t } else {\n\t xc.length = d;\n\n\t if (r) {\n\n\t // Rounding up may mean the previous digit has to be rounded up and so on.\n\t for ( --baseOut; ++xc[--d] > baseOut; ) {\n\t xc[d] = 0;\n\n\t if ( !d ) {\n\t ++e;\n\t xc.unshift(1);\n\t }\n\t }\n\t }\n\n\t // Determine trailing zeros.\n\t for ( k = xc.length; !xc[--k]; );\n\n\t // E.g. [4, 11, 15] becomes 4bf.\n\t for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n\t str = toFixedPoint( str, e );\n\t }\n\n\t // The caller will add the sign.\n\t return str;\n\t }", "function convertBase( str, baseOut, baseIn, sign ) {\n\t var d, e, k, r, x, xc, y,\n\t i = str.indexOf( '.' ),\n\t dp = DECIMAL_PLACES,\n\t rm = ROUNDING_MODE;\n\n\t if ( baseIn < 37 ) str = str.toLowerCase();\n\n\t // Non-integer.\n\t if ( i >= 0 ) {\n\t k = POW_PRECISION;\n\n\t // Unlimited precision.\n\t POW_PRECISION = 0;\n\t str = str.replace( '.', '' );\n\t y = new BigNumber(baseIn);\n\t x = y.pow( str.length - i );\n\t POW_PRECISION = k;\n\n\t // Convert str as if an integer, then restore the fraction part by dividing the\n\t // result by its base raised to a power.\n\t y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n\t y.e = y.c.length;\n\t }\n\n\t // Convert the number as integer.\n\t xc = toBaseOut( str, baseIn, baseOut );\n\t e = k = xc.length;\n\n\t // Remove trailing zeros.\n\t for ( ; xc[--k] == 0; xc.pop() );\n\t if ( !xc[0] ) return '0';\n\n\t if ( i < 0 ) {\n\t --e;\n\t } else {\n\t x.c = xc;\n\t x.e = e;\n\n\t // sign is needed for correct rounding.\n\t x.s = sign;\n\t x = div( x, y, dp, rm, baseOut );\n\t xc = x.c;\n\t r = x.r;\n\t e = x.e;\n\t }\n\n\t d = e + dp + 1;\n\n\t // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n\t i = xc[d];\n\t k = baseOut / 2;\n\t r = r || d < 0 || xc[d + 1] != null;\n\n\t r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n\t : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n\t rm == ( x.s < 0 ? 8 : 7 ) );\n\n\t if ( d < 1 || !xc[0] ) {\n\n\t // 1^-dp or 0.\n\t str = r ? toFixedPoint( '1', -dp ) : '0';\n\t } else {\n\t xc.length = d;\n\n\t if (r) {\n\n\t // Rounding up may mean the previous digit has to be rounded up and so on.\n\t for ( --baseOut; ++xc[--d] > baseOut; ) {\n\t xc[d] = 0;\n\n\t if ( !d ) {\n\t ++e;\n\t xc.unshift(1);\n\t }\n\t }\n\t }\n\n\t // Determine trailing zeros.\n\t for ( k = xc.length; !xc[--k]; );\n\n\t // E.g. [4, 11, 15] becomes 4bf.\n\t for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n\t str = toFixedPoint( str, e );\n\t }\n\n\t // The caller will add the sign.\n\t return str;\n\t }", "function convertBase( str, baseOut, baseIn, sign ) {\n\t var d, e, k, r, x, xc, y,\n\t i = str.indexOf( '.' ),\n\t dp = DECIMAL_PLACES,\n\t rm = ROUNDING_MODE;\n\t\n\t if ( baseIn < 37 ) str = str.toLowerCase();\n\t\n\t // Non-integer.\n\t if ( i >= 0 ) {\n\t k = POW_PRECISION;\n\t\n\t // Unlimited precision.\n\t POW_PRECISION = 0;\n\t str = str.replace( '.', '' );\n\t y = new BigNumber(baseIn);\n\t x = y.pow( str.length - i );\n\t POW_PRECISION = k;\n\t\n\t // Convert str as if an integer, then restore the fraction part by dividing the\n\t // result by its base raised to a power.\n\t y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n\t y.e = y.c.length;\n\t }\n\t\n\t // Convert the number as integer.\n\t xc = toBaseOut( str, baseIn, baseOut );\n\t e = k = xc.length;\n\t\n\t // Remove trailing zeros.\n\t for ( ; xc[--k] == 0; xc.pop() );\n\t if ( !xc[0] ) return '0';\n\t\n\t if ( i < 0 ) {\n\t --e;\n\t } else {\n\t x.c = xc;\n\t x.e = e;\n\t\n\t // sign is needed for correct rounding.\n\t x.s = sign;\n\t x = div( x, y, dp, rm, baseOut );\n\t xc = x.c;\n\t r = x.r;\n\t e = x.e;\n\t }\n\t\n\t d = e + dp + 1;\n\t\n\t // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n\t i = xc[d];\n\t k = baseOut / 2;\n\t r = r || d < 0 || xc[d + 1] != null;\n\t\n\t r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n\t : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n\t rm == ( x.s < 0 ? 8 : 7 ) );\n\t\n\t if ( d < 1 || !xc[0] ) {\n\t\n\t // 1^-dp or 0.\n\t str = r ? toFixedPoint( '1', -dp ) : '0';\n\t } else {\n\t xc.length = d;\n\t\n\t if (r) {\n\t\n\t // Rounding up may mean the previous digit has to be rounded up and so on.\n\t for ( --baseOut; ++xc[--d] > baseOut; ) {\n\t xc[d] = 0;\n\t\n\t if ( !d ) {\n\t ++e;\n\t xc.unshift(1);\n\t }\n\t }\n\t }\n\t\n\t // Determine trailing zeros.\n\t for ( k = xc.length; !xc[--k]; );\n\t\n\t // E.g. [4, 11, 15] becomes 4bf.\n\t for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n\t str = toFixedPoint( str, e );\n\t }\n\t\n\t // The caller will add the sign.\n\t return str;\n\t }", "function convertBase( str, baseOut, baseIn, sign ) {\n\t var d, e, k, r, x, xc, y,\n\t i = str.indexOf( '.' ),\n\t dp = DECIMAL_PLACES,\n\t rm = ROUNDING_MODE;\n\t\n\t if ( baseIn < 37 ) str = str.toLowerCase();\n\t\n\t // Non-integer.\n\t if ( i >= 0 ) {\n\t k = POW_PRECISION;\n\t\n\t // Unlimited precision.\n\t POW_PRECISION = 0;\n\t str = str.replace( '.', '' );\n\t y = new BigNumber(baseIn);\n\t x = y.pow( str.length - i );\n\t POW_PRECISION = k;\n\t\n\t // Convert str as if an integer, then restore the fraction part by dividing the\n\t // result by its base raised to a power.\n\t y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n\t y.e = y.c.length;\n\t }\n\t\n\t // Convert the number as integer.\n\t xc = toBaseOut( str, baseIn, baseOut );\n\t e = k = xc.length;\n\t\n\t // Remove trailing zeros.\n\t for ( ; xc[--k] == 0; xc.pop() );\n\t if ( !xc[0] ) return '0';\n\t\n\t if ( i < 0 ) {\n\t --e;\n\t } else {\n\t x.c = xc;\n\t x.e = e;\n\t\n\t // sign is needed for correct rounding.\n\t x.s = sign;\n\t x = div( x, y, dp, rm, baseOut );\n\t xc = x.c;\n\t r = x.r;\n\t e = x.e;\n\t }\n\t\n\t d = e + dp + 1;\n\t\n\t // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n\t i = xc[d];\n\t k = baseOut / 2;\n\t r = r || d < 0 || xc[d + 1] != null;\n\t\n\t r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n\t : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n\t rm == ( x.s < 0 ? 8 : 7 ) );\n\t\n\t if ( d < 1 || !xc[0] ) {\n\t\n\t // 1^-dp or 0.\n\t str = r ? toFixedPoint( '1', -dp ) : '0';\n\t } else {\n\t xc.length = d;\n\t\n\t if (r) {\n\t\n\t // Rounding up may mean the previous digit has to be rounded up and so on.\n\t for ( --baseOut; ++xc[--d] > baseOut; ) {\n\t xc[d] = 0;\n\t\n\t if ( !d ) {\n\t ++e;\n\t xc = [1].concat(xc);\n\t }\n\t }\n\t }\n\t\n\t // Determine trailing zeros.\n\t for ( k = xc.length; !xc[--k]; );\n\t\n\t // E.g. [4, 11, 15] becomes 4bf.\n\t for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n\t str = toFixedPoint( str, e );\n\t }\n\t\n\t // The caller will add the sign.\n\t return str;\n\t }", "function convertBase( str, baseOut, baseIn, sign ) {\r\n\t var d, e, k, r, x, xc, y,\r\n\t i = str.indexOf( '.' ),\r\n\t dp = DECIMAL_PLACES,\r\n\t rm = ROUNDING_MODE;\r\n\r\n\t if ( baseIn < 37 ) str = str.toLowerCase();\r\n\r\n\t // Non-integer.\r\n\t if ( i >= 0 ) {\r\n\t k = POW_PRECISION;\r\n\r\n\t // Unlimited precision.\r\n\t POW_PRECISION = 0;\r\n\t str = str.replace( '.', '' );\r\n\t y = new BigNumber(baseIn);\r\n\t x = y.pow( str.length - i );\r\n\t POW_PRECISION = k;\r\n\r\n\t // Convert str as if an integer, then restore the fraction part by dividing the\r\n\t // result by its base raised to a power.\r\n\t y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\r\n\t y.e = y.c.length;\r\n\t }\r\n\r\n\t // Convert the number as integer.\r\n\t xc = toBaseOut( str, baseIn, baseOut );\r\n\t e = k = xc.length;\r\n\r\n\t // Remove trailing zeros.\r\n\t for ( ; xc[--k] == 0; xc.pop() );\r\n\t if ( !xc[0] ) return '0';\r\n\r\n\t if ( i < 0 ) {\r\n\t --e;\r\n\t } else {\r\n\t x.c = xc;\r\n\t x.e = e;\r\n\r\n\t // sign is needed for correct rounding.\r\n\t x.s = sign;\r\n\t x = div( x, y, dp, rm, baseOut );\r\n\t xc = x.c;\r\n\t r = x.r;\r\n\t e = x.e;\r\n\t }\r\n\r\n\t d = e + dp + 1;\r\n\r\n\t // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\r\n\t i = xc[d];\r\n\t k = baseOut / 2;\r\n\t r = r || d < 0 || xc[d + 1] != null;\r\n\r\n\t r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\r\n\t : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n\t rm == ( x.s < 0 ? 8 : 7 ) );\r\n\r\n\t if ( d < 1 || !xc[0] ) {\r\n\r\n\t // 1^-dp or 0.\r\n\t str = r ? toFixedPoint( '1', -dp ) : '0';\r\n\t } else {\r\n\t xc.length = d;\r\n\r\n\t if (r) {\r\n\r\n\t // Rounding up may mean the previous digit has to be rounded up and so on.\r\n\t for ( --baseOut; ++xc[--d] > baseOut; ) {\r\n\t xc[d] = 0;\r\n\r\n\t if ( !d ) {\r\n\t ++e;\r\n\t xc.unshift(1);\r\n\t }\r\n\t }\r\n\t }\r\n\r\n\t // Determine trailing zeros.\r\n\t for ( k = xc.length; !xc[--k]; );\r\n\r\n\t // E.g. [4, 11, 15] becomes 4bf.\r\n\t for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\r\n\t str = toFixedPoint( str, e );\r\n\t }\r\n\r\n\t // The caller will add the sign.\r\n\t return str;\r\n\t }", "function convertBase(str, baseIn, baseOut) {\n var j,\n arr = [0],\n arrL,\n i = 0,\n strL = str.length;\n\n for (; i < strL;) {\n for (arrL = arr.length; arrL--;) {arr[arrL] *= baseIn;}\n arr[0] += NUMERALS.indexOf(str.charAt(i++));\n for (j = 0; j < arr.length; j++) {\n if (arr[j] > baseOut - 1) {\n if (arr[j + 1] === void 0) arr[j + 1] = 0;\n arr[j + 1] += arr[j] / baseOut | 0;\n arr[j] %= baseOut;\n }\n }\n }\n\n return arr.reverse();\n }", "function convertFromBaseTenToBaseX( xbase, inval ) {\n\n return inval.toString( xbase ).toUpperCase();\n\n /* let xinval = inval;\n let remainder = hexidecimal[ xinval % xbase ];\n while ( xinval >= xbase ) {\n let r1 = subtract( xinval, ( xinval % xbase ) );\n xinval = divide( r1, xbase );\n // in this case we do not want to add we want to append the strings together\n if ( xinval >= xbase ) {\n remainder = hexidecimal[ xinval % xbase ] + remainder;\n } else {\n remainder = hexidecimal[ xinval ] + remainder;\n }\n }\n return remainder; */\n}", "function dec_to_bho(number, change_base) {\n if (change_base == B ){\n return parseInt(number + '', 10)\n .toString(2);} else\n if (change_base == H ){\n return parseInt(number + '', 10)\n .toString(8);} else \n if (change_base == O ){\n return parseInt(number + '', 10)\n .toString(8);} else\n console.log(\"pick H, B, or O\");\n\n }", "function convertBase(str, baseOut, baseIn, sign) {\n var d,\n e,\n k,\n r,\n x,\n xc,\n y,\n i = str.indexOf('.'),\n dp = DECIMAL_PLACES,\n rm = ROUNDING_MODE;\n\n if (baseIn < 37) str = str.toLowerCase();\n\n // Non-integer.\n if (i >= 0) {\n k = POW_PRECISION;\n\n // Unlimited precision.\n POW_PRECISION = 0;\n str = str.replace('.', '');\n y = new BigNumber(baseIn);\n x = y.pow(str.length - i);\n POW_PRECISION = k;\n\n // Convert str as if an integer, then restore the fraction part by dividing the\n // result by its base raised to a power.\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e), 10, baseOut);\n y.e = y.c.length;\n }\n\n // Convert the number as integer.\n xc = toBaseOut(str, baseIn, baseOut);\n e = k = xc.length;\n\n // Remove trailing zeros.\n for (; xc[--k] == 0; xc.pop()) {}\n if (!xc[0]) return '0';\n\n if (i < 0) {\n --e;\n } else {\n x.c = xc;\n x.e = e;\n\n // sign is needed for correct rounding.\n x.s = sign;\n x = div(x, y, dp, rm, baseOut);\n xc = x.c;\n r = x.r;\n e = x.e;\n }\n\n d = e + dp + 1;\n\n // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n i = xc[d];\n k = baseOut / 2;\n r = r || d < 0 || xc[d + 1] != null;\n\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));\n\n if (d < 1 || !xc[0]) {\n\n // 1^-dp or 0.\n str = r ? toFixedPoint('1', -dp) : '0';\n } else {\n xc.length = d;\n\n if (r) {\n\n // Rounding up may mean the previous digit has to be rounded up and so on.\n for (--baseOut; ++xc[--d] > baseOut;) {\n xc[d] = 0;\n\n if (!d) {\n ++e;\n xc = [1].concat(xc);\n }\n }\n }\n\n // Determine trailing zeros.\n for (k = xc.length; !xc[--k];) {}\n\n // E.g. [4, 11, 15] becomes 4bf.\n for (i = 0, str = ''; i <= k; str += ALPHABET.charAt(xc[i++])) {}\n str = toFixedPoint(str, e);\n }\n\n // The caller will add the sign.\n return str;\n }", "function convertBase(str, baseOut, baseIn, sign) {\n var d,\n e,\n k,\n r,\n x,\n xc,\n y,\n i = str.indexOf('.'),\n dp = DECIMAL_PLACES,\n rm = ROUNDING_MODE;\n\n if (baseIn < 37) str = str.toLowerCase();\n\n // Non-integer.\n if (i >= 0) {\n k = POW_PRECISION;\n\n // Unlimited precision.\n POW_PRECISION = 0;\n str = str.replace('.', '');\n y = new BigNumber(baseIn);\n x = y.pow(str.length - i);\n POW_PRECISION = k;\n\n // Convert str as if an integer, then restore the fraction part by dividing the\n // result by its base raised to a power.\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e), 10, baseOut);\n y.e = y.c.length;\n }\n\n // Convert the number as integer.\n xc = toBaseOut(str, baseIn, baseOut);\n e = k = xc.length;\n\n // Remove trailing zeros.\n for (; xc[--k] == 0; xc.pop()) {}\n if (!xc[0]) return '0';\n\n if (i < 0) {\n --e;\n } else {\n x.c = xc;\n x.e = e;\n\n // sign is needed for correct rounding.\n x.s = sign;\n x = div(x, y, dp, rm, baseOut);\n xc = x.c;\n r = x.r;\n e = x.e;\n }\n\n d = e + dp + 1;\n\n // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n i = xc[d];\n k = baseOut / 2;\n r = r || d < 0 || xc[d + 1] != null;\n\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));\n\n if (d < 1 || !xc[0]) {\n\n // 1^-dp or 0.\n str = r ? toFixedPoint('1', -dp) : '0';\n } else {\n xc.length = d;\n\n if (r) {\n\n // Rounding up may mean the previous digit has to be rounded up and so on.\n for (--baseOut; ++xc[--d] > baseOut;) {\n xc[d] = 0;\n\n if (!d) {\n ++e;\n xc.unshift(1);\n }\n }\n }\n\n // Determine trailing zeros.\n for (k = xc.length; !xc[--k];) {}\n\n // E.g. [4, 11, 15] becomes 4bf.\n for (i = 0, str = ''; i <= k; str += ALPHABET.charAt(xc[i++])) {}\n str = toFixedPoint(str, e);\n }\n\n // The caller will add the sign.\n return str;\n }", "function convertBase(str, baseOut, baseIn, sign) {\n var d,\n e,\n k,\n r,\n x,\n xc,\n y,\n i = str.indexOf('.'),\n dp = DECIMAL_PLACES,\n rm = ROUNDING_MODE;\n if (baseIn < 37) str = str.toLowerCase(); // Non-integer.\n\n if (i >= 0) {\n k = POW_PRECISION; // Unlimited precision.\n\n POW_PRECISION = 0;\n str = str.replace('.', '');\n y = new BigNumber(baseIn);\n x = y.pow(str.length - i);\n POW_PRECISION = k; // Convert str as if an integer, then restore the fraction part by dividing the\n // result by its base raised to a power.\n\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e), 10, baseOut);\n y.e = y.c.length;\n } // Convert the number as integer.\n\n\n xc = toBaseOut(str, baseIn, baseOut);\n e = k = xc.length; // Remove trailing zeros.\n\n for (; xc[--k] == 0; xc.pop()) {\n }\n\n if (!xc[0]) return '0';\n\n if (i < 0) {\n --e;\n } else {\n x.c = xc;\n x.e = e; // sign is needed for correct rounding.\n\n x.s = sign;\n x = div(x, y, dp, rm, baseOut);\n xc = x.c;\n r = x.r;\n e = x.e;\n }\n\n d = e + dp + 1; // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n\n i = xc[d];\n k = baseOut / 2;\n r = r || d < 0 || xc[d + 1] != null;\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));\n\n if (d < 1 || !xc[0]) {\n // 1^-dp or 0.\n str = r ? toFixedPoint('1', -dp) : '0';\n } else {\n xc.length = d;\n\n if (r) {\n // Rounding up may mean the previous digit has to be rounded up and so on.\n for (--baseOut; ++xc[--d] > baseOut;) {\n xc[d] = 0;\n\n if (!d) {\n ++e;\n xc.unshift(1);\n }\n }\n } // Determine trailing zeros.\n\n\n for (k = xc.length; !xc[--k];) {\n } // E.g. [4, 11, 15] becomes 4bf.\n\n\n for (i = 0, str = ''; i <= k; str += ALPHABET.charAt(xc[i++])) {\n }\n\n str = toFixedPoint(str, e);\n } // The caller will add the sign.\n\n\n return str;\n } // Perform division in the specified base. Called by div and convertBase.", "function convertBase( str, baseOut, baseIn, sign ) {\n var d, e, k, r, x, xc, y,\n i = str.indexOf( '.' ),\n dp = DECIMAL_PLACES,\n rm = ROUNDING_MODE;\n\n if ( baseIn < 37 ) str = str.toLowerCase();\n\n // Non-integer.\n if ( i >= 0 ) {\n k = POW_PRECISION;\n\n // Unlimited precision.\n POW_PRECISION = 0;\n str = str.replace( '.', '' );\n y = new BigNumber(baseIn);\n x = y.pow( str.length - i );\n POW_PRECISION = k;\n\n // Convert str as if an integer, then restore the fraction part by dividing the\n // result by its base raised to a power.\n y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n y.e = y.c.length;\n }\n\n // Convert the number as integer.\n xc = toBaseOut( str, baseIn, baseOut );\n e = k = xc.length;\n\n // Remove trailing zeros.\n for ( ; xc[--k] == 0; xc.pop() );\n if ( !xc[0] ) return '0';\n\n if ( i < 0 ) {\n --e;\n } else {\n x.c = xc;\n x.e = e;\n\n // sign is needed for correct rounding.\n x.s = sign;\n x = div( x, y, dp, rm, baseOut );\n xc = x.c;\n r = x.r;\n e = x.e;\n }\n\n d = e + dp + 1;\n\n // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n i = xc[d];\n k = baseOut / 2;\n r = r || d < 0 || xc[d + 1] != null;\n\n r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n rm == ( x.s < 0 ? 8 : 7 ) );\n\n if ( d < 1 || !xc[0] ) {\n\n // 1^-dp or 0.\n str = r ? toFixedPoint( '1', -dp ) : '0';\n } else {\n xc.length = d;\n\n if (r) {\n\n // Rounding up may mean the previous digit has to be rounded up and so on.\n for ( --baseOut; ++xc[--d] > baseOut; ) {\n xc[d] = 0;\n\n if ( !d ) {\n ++e;\n xc.unshift(1);\n }\n }\n }\n\n // Determine trailing zeros.\n for ( k = xc.length; !xc[--k]; );\n\n // E.g. [4, 11, 15] becomes 4bf.\n for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n str = toFixedPoint( str, e );\n }\n\n // The caller will add the sign.\n return str;\n }", "function convertBase( str, baseOut, baseIn, sign ) {\n var d, e, k, r, x, xc, y,\n i = str.indexOf( '.' ),\n dp = DECIMAL_PLACES,\n rm = ROUNDING_MODE;\n\n if ( baseIn < 37 ) str = str.toLowerCase();\n\n // Non-integer.\n if ( i >= 0 ) {\n k = POW_PRECISION;\n\n // Unlimited precision.\n POW_PRECISION = 0;\n str = str.replace( '.', '' );\n y = new BigNumber(baseIn);\n x = y.pow( str.length - i );\n POW_PRECISION = k;\n\n // Convert str as if an integer, then restore the fraction part by dividing the\n // result by its base raised to a power.\n y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\n y.e = y.c.length;\n }\n\n // Convert the number as integer.\n xc = toBaseOut( str, baseIn, baseOut );\n e = k = xc.length;\n\n // Remove trailing zeros.\n for ( ; xc[--k] == 0; xc.pop() );\n if ( !xc[0] ) return '0';\n\n if ( i < 0 ) {\n --e;\n } else {\n x.c = xc;\n x.e = e;\n\n // sign is needed for correct rounding.\n x.s = sign;\n x = div( x, y, dp, rm, baseOut );\n xc = x.c;\n r = x.r;\n e = x.e;\n }\n\n d = e + dp + 1;\n\n // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\n i = xc[d];\n k = baseOut / 2;\n r = r || d < 0 || xc[d + 1] != null;\n\n r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\n : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\n rm == ( x.s < 0 ? 8 : 7 ) );\n\n if ( d < 1 || !xc[0] ) {\n\n // 1^-dp or 0.\n str = r ? toFixedPoint( '1', -dp ) : '0';\n } else {\n xc.length = d;\n\n if (r) {\n\n // Rounding up may mean the previous digit has to be rounded up and so on.\n for ( --baseOut; ++xc[--d] > baseOut; ) {\n xc[d] = 0;\n\n if ( !d ) {\n ++e;\n xc.unshift(1);\n }\n }\n }\n\n // Determine trailing zeros.\n for ( k = xc.length; !xc[--k]; );\n\n // E.g. [4, 11, 15] becomes 4bf.\n for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\n str = toFixedPoint( str, e );\n }\n\n // The caller will add the sign.\n return str;\n }" ]
[ "0.78933334", "0.7787537", "0.76196146", "0.746665", "0.74133676", "0.7408443", "0.7408443", "0.7408443", "0.7408443", "0.7367569", "0.7335649", "0.72488385", "0.7197895", "0.7121101", "0.7059255", "0.7058206", "0.69450194", "0.6917524", "0.6917524", "0.68824667", "0.68824667", "0.68236697", "0.6814816", "0.6798944", "0.6797506", "0.67898643", "0.67898643", "0.67874205", "0.67802835", "0.67802835" ]
0.81513506
0
Add room name to DOM
function outputRoomName(room) { const roomName = document.getElementById('room-name'); roomName.innerHTML = room; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function outputRoomName(room) {\n roomName.innerHTML = `<li class=\"contact\">\n <div class=\"wrap\">\n <div class=\"meta\">\n <p class=\"name\">${room}</p>\n </div>\n </div>\n </li>`\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n \n roomName.innerText = room;\n}", "function outputRoomName(room) {\r\n roomName.innerText = room;\r\n}", "function outputRoomName(room) {\r\n roomName.innerText = room;\r\n}", "function outputRoomName(room){\n roomName.innerHTML = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room) {\n roomName.innerText = room;\n}", "function outputRoomName(room){\n roomName.innerText = room;\n}", "function outputRoomName(room){\n roomName.innerHTML = room;\n }", "function outputRoomName(room){\n roomName.innerText = room;\n}", "function outputRoomName(room){\n roomName.innerText=room;\n}", "function outputRoomname(room){\n roomName.innerText = room;\n}", "function outputRoomname(room){\n roomName.innerText= room;\n}", "function outputRoomName(room){\n\n roomName.innerText=room;\n\n}", "function setRoom(name) {\n\t$('#joinRoom').remove();\n\t$('h1').text('Room name : ' + name);\n\t$('body').append('<input type=\"hidden\" id=\"roomName\" value=\"'+name+'\"/>');\n\t$('body').addClass('active');\n}", "function setChatroom(room) {\n $('#chatroom h1').append(room);\n}", "function createRoom(name)\n\t{\n\t\tdocument.getElementsByClassName('dropdown-item selected')[0].className = 'dropdown-item'\n\n\t\tvar room = document.createElement('div')\n\t\troom.className = 'dropdown-item selected'\n\t\troom.innerText = name\n\t\tcreateDropdownClickMethod(room)\n\t\tget('create-room-name').value = ''\n\n\t\tdropdown.appendChild(room)\n\t\tdropdown.className = 'dropdown closed'\n\t}", "function setRoom(name) {\r\n $('#createRoom').remove();\r\n $('h1').text(name);\r\n // $('#subTitle').text(name + \" || link: \"+ location.href);\r\n $('body').addClass('active');\r\n}", "function addRoom(room){\n $outer.append(Mustache.render(roomTemplate, room));\n }", "function populateRoomListView(user) {\n var name = document.getElementById(\"roomName\");\n var desc = document.getElementById(\"roomDesc\");\n var destroydate = document.getElementById(\"roomDest\");\n //var privacy = document.getElementById(\"privacy\");\n name.innerHTML = \"<strong>\"+room.Name+\"</strong>\";\n desc.innerHTML = room.Description;\n}", "function setRoom(name) {\n $('form').remove();\n $('h1').text(name);\n $('#subTitle').text('Link to join: ' + location.href);\n $('body').addClass('active');\n }", "function createRoomButton(roomInfo) {\n var header = roomInfo.name.charAt(0);\n\n var id = roomInfo.id;\n var room = `<li>\n <a href=\"#\" data-id=`+ roomInfo.id + `>\n <input type=\"hidden\" id=`+ id +` value=`+ roomInfo.name +` />\n <div class=\"media\" data-id=`+ roomInfo.id + ` class=\"list-group-item\">\n <div class=\"chat-user-img online align-self-center mr-3\" data-id=`+ roomInfo.id + ` >\n <div class=\"avatar-xs\" data-id=`+ roomInfo.id + `>\n <span class=\"avatar-title rounded-circle bg-soft-primary text-primary\" data-id=`+ roomInfo.id + `>\n ` + header.toUpperCase() + `\n </span>\n </div>\n </div>\n <div class=\"media-body overflow-hidden\" data-id=`+ roomInfo.id + `>\n <h5 class=\"text-truncate font-size-15 mb-1\" data-id=`+ roomInfo.id + `>` + roomInfo.name + `</h5>\n <p class=\"chat-user-message text-truncate mb-0\" data-id=`+ roomInfo.id + `>Hey! there I'm available</p>\n </div>\n </div>\n </a>\n </li>`;\n\n return room;\n}" ]
[ "0.7907107", "0.7804841", "0.7804841", "0.7804841", "0.7804841", "0.7804841", "0.7804841", "0.77756387", "0.7764691", "0.7764691", "0.77535206", "0.7694868", "0.7694868", "0.7694868", "0.7694868", "0.76699555", "0.7601553", "0.7549329", "0.7530662", "0.74739176", "0.7458124", "0.73475415", "0.72127086", "0.70887303", "0.69283646", "0.67928314", "0.66517746", "0.6555788", "0.65383327", "0.6499427" ]
0.7851127
1
Vanilla JS to delete tasks in 'Trash' column
function emptyTrash() { /* Clear tasks from 'Trash' column */ document.getElementById("trash").innerHTML = ""; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteTasks() {\n const mutateCursor = getCursorToMutate();\n if (mutateCursor) {\n clickTaskMenu(mutateCursor, 'task-overflow-menu-delete', false);\n } else {\n withUnique(\n openMoreMenu(),\n 'li[data-action-hint=\"multi-select-toolbar-overflow-menu-delete\"]',\n click,\n );\n }\n }", "function deleteTask()\n {\n var child = this.parentNode.parentNode;\n var parent = child.parentNode;\n parent.removeChild(child);\n var id= parent.id;\n var value = child.innerText;\n if (id == \"taskList\")\n {\n obj.taskListArr.splice(obj.taskListArr.indexOf(value), 1);\n }\n else \n {\n obj.taskCompletedArr.splice(obj.taskCompletedArr.indexOf(value), 1);\n } \n dataStorageUpdt();\n }", "function emptyTrash() {\n /* Clear tasks from 'Trash' column */\n document.getElementById(\"monday\").innerHTML = \"\";\n document.getElementById(\"tuesday\").innerHTML = \"\";\n document.getElementById(\"wednesday\").innerHTML = \"\";\n document.getElementById(\"thursday\").innerHTML = \"\";\n document.getElementById(\"friday\").innerHTML = \"\";\n document.getElementById(\"saturday\").innerHTML = \"\";\n}", "function deleteTask(e) {\n let index = this.dataset.index;\n let tyList = this.parentElement.parentElement.parentElement;\n if (tyList.getAttribute(\"id\") == \"lists\") {\n tasks.splice(index, 1);\n localStorage.setItem(\"tasks\", JSON.stringify(tasks));\n render(lists, tasks);\n }\n if (tyList.getAttribute(\"id\") == \"listOfChecked\") {\n tasksChecked.splice(index, 1);\n localStorage.setItem(\"tasksChecked\", JSON.stringify(tasksChecked));\n render(listOfChecked, tasksChecked);\n }\n}", "function removeTask(event){\n // Get the index of the task to be removed\n let index = findIndexById(event.target.parentElement.id);\n\n // Confirm if the user wants to remove said task\n if(confirm(`Do you want to remove this task? \"${toDos[index].content}\"`)){\n // Use splice to delete the task object and reorder the array then update local storage\n toDos.splice(index, 1);\n ls.setJSON(key, JSON.stringify(toDos));\n\n // Update the list displayed to the user\n displayList();\n }\n}", "function deleteTask() {\n const buttonDelete = document.querySelectorAll('.button-delete')\n buttonDelete.forEach(button => {\n button.onclick = function (event) {\n event.path.forEach(el => {\n if (el.classList?.contains(listItemClass)) {\n let id = +el.id\n listTask = listTask.filter(task => {\n if (task.id === id) {\n el.remove()\n return false\n }\n return true\n })\n showInfoNoTask()\n }\n })\n setTaskValue()\n localStorage.setItem('listTask', JSON.stringify(listTask))\n }\n })\n }", "removeTask () {\n\t\tthis.deleter.addEventListener('click', (e) => {\n\t\t\tfetch('/items/'+e.target.parentNode.parentNode.parentNode.childNodes[0].getAttribute('data-task'), {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t\theaders: {\n\t\t\t\t'Accept': 'application/json',\n\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t},\n\t\t\t\t\n\t\t\t})\n\t\t\t.then(res => res.text()) \n\t\t\t.then(res => console.log(res))\n\t\t\t.catch(error => console.error(error));\n\t\t\te.target.parentNode.parentNode.parentNode.remove();\n\t\t\tupdateProgess(numberOfCompletedTasks());\n\t\t});\n\n\t\t// We need to also remove tasks from the backend\n\t}", "function removeTask(elem) {\n elem.parentNode.parentNode.removeChild(elem.parentNode);\n LIST[elem.id].trash = true;\n}", "function deleteTask (e){\n for (var i = 0 ; i< loginUser.tasks.length; i ++){\n if(parseInt(loginUser.tasks[i].id) === parseInt(e.target.getAttribute('data-id'))){\n if(loginUser.tasks[i].status === false){\n taskToDo--;\n $('#countOfTask').text('').text('Task to do: '+ taskToDo);\n }\n loginUser.tasks.splice(i, 1);\n $('#task' + e.target.getAttribute('data-id')).remove();\n collectionOfUser.update(\n {\n id : loginUser.id,\n tasks : loginUser.tasks\n },\n function(user){\n loginUser = user;\n },\n error \n );\n }\n }\n }", "function delete_task(e) {\n console.log('delete task btn pressed...');\n e.target.parentElement.remove();\n\n }", "function deleteLS(delItem){\n console.log(\"delete activated\");\n let task;\n if(localStorage.getItem('task') === null)\n {\n task=[];\n }\n else\n {\n task=JSON.parse(localStorage.getItem('task'));\n\n\n }\n\n \n task.forEach(function(tasks,index){\n \n if(delItem.innerHTML === tasks){\n \n\n \n \n task.splice(index,1);\n }\n })\n localStorage.setItem('task',JSON.stringify(task));\n}", "function deleteTask(id) {\r\n let Note = document.getElementById(id); \r\n //removes note from page\r\n document.getElementById(\"shoeNotesFromLS\").removeChild(Note); \r\n let indexOfTaskToRemove = tasks.findIndex(task => task.id === id);\r\n //removes from array of tasks\r\n tasks.splice(indexOfTaskToRemove, 1);\r\n //removes from array in local storage\r\n if (tasks.length != 0) {\r\n localStorage.tasks = JSON.stringify(tasks);\r\n }\r\n else {\r\n localStorage.removeItem(\"tasks\");\r\n }\r\n \r\n}", "function deleteTask(e) {\n e.preventDefault();\n if (e.target.className === 'delete-task') {\n e.target.parentElement.remove();\n deleteTaskLocalStorage(e.target.parentElement.textContent);\n\n //alert('Tweet eliminado')\n }\n\n}", "function removeTask(e) {\n if (e.target.parentElement.classList.contains('delete-item')) {\n if (confirm('Are you sure?')) {\n e.target.parentElement.parentElement.remove();\n\n removeTaskFromLocalStorage(Number(e.target.parentElement.parentElement.id.substring(5)))\n }\n }\n}", "function deleteTask(event) {\n const taskListItem = this.parentNode.parentNode;\n const keyValue = taskListItem.querySelector('input').dataset.key\n taskListItem.parentNode.removeChild(taskListItem);\n\n\n manageTasksAjax(event, '', keyValue, 'delete')\n}", "function removeTask(e) {\n // Clicking on the delete button causes the removal of that list item\n if (e.target.parentElement.classList.contains('delete-item')){\n e.target.parentElement.parentElement.remove();\n removeLocalStorage(e.target.parentElement.parentElement.textContent);\n // Refresh the list to mirror local storage contents as all duplicates are removed\n getTasks(e);\n }\n e.preventDefault();\n}", "function deleteList(c) {\n\tconst taskDel = document.querySelector(`.item-${c}`);\n\ttaskDel.firstElementChild.addEventListener(\"click\", () => {\n\t\tif (confirm(\"Are you sure?\")) {\n\t\t\ttaskDel.remove();\n\t\t\tconsole.log(taskDel.textContent);\n\t\t\tremoveFromStorage(taskDel.textContent);\n\t\t}\n\t});\n}", "function removeTask(e){\n if (e.target.parentElement.classList.contains('delete-item')){\n if(confirm('u sure, dude?')){\n e.target.parentElement.parentElement.remove(); \n\n //remove from local storage\n removeTaskFromLocalStorage(e.target.parentElement.parentElement);\n }\n }\n}", "function removeTask(e) {\n\tif (e.target.parentElement.classList.contains('delete-item')) {\n\t\tif (confirm('Are You Sure?')) {\n\t\t\te.target.parentElement.parentElement.remove();\n\t\t\t/*Ako parentElement ima klasu delete-item onda hocu da...*/\n\n\t\t\t//-Remove from LS-//\n\t\t\tremoveTasksFromLocalStorage(e.target.parentElement.parentElement);//Funkcija za brisanje iz LS\n\t\t}\n\t}\n}", "function deleteTask(description) {\n\tvar username = localStorage.getItem(\"username\"); \n\tdatabase.ref('/task/'+username+'/'+description).remove();\n\tswal('Task deleted','','success').then((result) => {\n\t\twindow.location.reload();\n\t});\n\t\n\t\n}", "function removeTask(e) {\n if(e.target.parentElement.classList.contains\n ('delete-item')) {\n if(confirm('Are You Sure?')) {\n e.target.parentElement.parentElement.remove();\n //Remove from LS\n removeTaskFromLocalStorage\n (e.target.parentElement.parentElement);\n\n \n }\n}\n\n}", "function clearTasks(e){\n //taskList.innerHTML = '';\n while(taskList.firstChild){\n taskList.removeChild(taskList.firstChild);\n }\n let deletedTasks;\n \n deletedTasks = localStorage.getItem('tasks')\n \n localStorage.setItem('deletedTasks',deletedTasks)\n localStorage.removeItem('tasks')\n //localStorage.clear()\n e.preventDefault()\n}", "function removeTask(e) {\r\n let li = e.target.parentElement.parentElement;\r\n let a = e.target.parentElement;\r\n if (a.classList.contains('delete-item')) {\r\n if (confirm('Are You Sure ?')) {\r\n li.remove();\r\n removeFromLS(li);\r\n }\r\n }\r\n}", "function deleteTask() {\n this.parentNode.parentNode.removeChild(this.parentNode);\n }", "function deleteTaskFromToDoList(event) {\n event.target.parentElement.remove();\n}", "function deleteTask(event)\n{\n //gets button id\n let id = event.target.id;\n\n //gets task position from button id\n let taskPosition = id.replace(/\\D/g,'');\n\n //removes task from task array\n taskArr.splice(taskPosition - 1, 1); \n\n //loop through task array to adjust position\n for(let i = 0; i < taskArr.length; i++)\n {\n taskArr[i].position = i + 1;\n };\n\n //rewrites task list\n rewritesList();\n}", "function removeTask(e) {\n\n if (e.target.parentElement.classList.contains('delete-item')) {\n if (confirm('Are you sure!!')) {\n e.target.parentElement.parentElement.remove();\n }\n }\n removeItemFromLocalStorage(e.target.parentElement.parentElement);\n}", "function removeTask(){\n\t\t$(\".remove\").unbind(\"click\").click(function(){\n\t\t\tvar single = $(this).closest(\"li\");\n\t\t\t\n\t\t\ttoDoList.splice(single.index(), 1);\n\t\t\tsingle.remove();\n\t\t\ttoDoCount();\n\t\t\tnotToDoCount();\n\t\t\taddClear();\n\t\t});\n\t}", "function deleteAllCompletedTodos() {\n // Write your code here...\n}", "function deleteAllCompletedTodos() {\n // Write your code here...\n}" ]
[ "0.7403256", "0.72473013", "0.7158116", "0.7153182", "0.71489525", "0.7123197", "0.70864403", "0.70445865", "0.70080054", "0.6972743", "0.6972021", "0.69592506", "0.6953322", "0.69066185", "0.6871405", "0.68564725", "0.6838206", "0.6827074", "0.68257725", "0.6818862", "0.68032724", "0.6795183", "0.6789422", "0.67869186", "0.6783482", "0.67824054", "0.67822033", "0.67680055", "0.6765169", "0.6765169" ]
0.7694405
0
handleMessage: do the entire sequence for this message. subscribe: send the machine if available, else send error. any other command: send error. This method returns a promise that usually resolves. It rejects only if there is a bug or internal error.
handleMessage(clientId, data) { return new Promise( (resolve, reject) => { log(`client ${clientId}: |${data}|`); if (data.match(/^\s*subscribe\s+/)) { const m = data.match(/subscribe\s+(\w+)/); if (m) { let machine = m[1]; this.subscribe(clientId, machine) .then( () => { log(`subscribed ${clientId} to machine ${machine}`); resolve(); }) .catch( errMsg => { const fullMsg = `error: ${errMsg}`; log(fullMsg); this.sendMessage(clientId, fullMsg) .then(resolve) .catch(reject); }); } else { const msg = `error: bad subscribe command`; log(`sending ${msg} to client ${clientId}`); this.sendMessage(clientId, `${msg}`) .then(resolve) .catch(reject); } } else if (data.match(/^command\s+/)) { const m = data.match(/^\s*command\s+(\w+)/); const arr = data.split('\n').filter( e => e.length > 0); if (!m) { log(`did not match command pattern`); return reject(`bad command line: ${arr[0]}`); } log(`emitting command ${m[1]} ${clientId}: |${arr.slice(1)}|`); this.emit('command', m[1], clientId, arr.slice(1)); return resolve(); } else { const msg = `bad command: |${trunc(data)}|`; console.log(`sending ${msg} to client ${clientId}`); this.sendMessage(clientId, msg) .then(resolve) .catch(reject); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async function handleMessage(msg, reply) {\n let response = 'success';\n try {\n if (msg.command == 'capture') {\n if (!msg.streamId) {\n throw new Error('No stream ID received');\n }\n await startCapture(msg.streamId);\n } else if (msg.command == 'stop') {\n stopCapture();\n } else {\n throw new Error(\n `Unexpected message: ${JSON.stringify(message)}`);\n }\n } catch (e) {\n response = e.toString();\n }\n reply(response);\n}", "function sendMessage(message) {\n return new RSVP.Promise(function (resolve, reject) {\n spec._processor.onmessage = function (event) {\n if (event.data.error) {\n return reject(event.data.error);\n } else {\n return resolve(event.data.data);\n }\n };\n return spec._processor.postMessage(message);\n });\n }", "receiveMessage(message) {\n return new Promise((resolve, reject) => {\n if (message instanceof Message){\n this.messageEventCallbacks.forEach(cb=>{\n cb(message);\n });\n }\n resolve();\n })\n }", "function handleMessage(message) {\n if (closed)\n fail(new Error('Client cannot send messages after being closed'));\n\n //TODO for debugging purposes\n pubsub.emit('message', message);\n\n const commandName = message.command;\n delete message.command;\n\n //look for command in list of commands and check if exists\n const commandModule = commands[commandName];\n if (commandModule) {\n //TODO move this into the command modules\n //check params\n try {\n ow(message, commandModule.paramType);\n } catch (error) {\n throw new MyaError(`Invalid arguments passed to ${commandModule}`, 'INVALID_ARGUMENTS', error);\n }\n\n //run the command\n commandModule.run(client, message);\n } else {\n throw new MyaError(`Command ${commandName} does not exist`, 'COMMAND_NOT_FOUND');\n }\n }", "_handleMessage(message) {\n // command response\n if (message.id) {\n const callback = this._callbacks[message.id];\n if (!callback) {\n return;\n }\n // interpret the lack of both 'error' and 'result' as success\n // (this may happen with node-inspector)\n if (message.error) {\n callback(true, message.error);\n } else {\n callback(false, message.result || {});\n }\n // unregister command response callback\n delete this._callbacks[message.id];\n // notify when there are no more pending commands\n if (Object.keys(this._callbacks).length === 0) {\n this.emit('ready');\n }\n }\n // event\n else if (message.method) {\n const {method, params, sessionId} = message;\n this.emit('event', message);\n this.emit(method, params, sessionId);\n this.emit(`${method}.${sessionId}`, params, sessionId);\n }\n }", "function handleShellMessage(kernel, msg) {\n var future;\n try {\n future = kernel.sendShellMessage(msg, true);\n }\n catch (e) {\n return Promise.reject(e);\n }\n return new Promise(function (resolve) { future.onReply = resolve; });\n }", "function handleShellMessage(kernel, msg) {\n var future;\n try {\n future = kernel.sendShellMessage(msg, true);\n }\n catch (e) {\n return Promise.reject(e);\n }\n return new Promise(function (resolve, reject) {\n future.onReply = function (reply) {\n resolve(reply);\n };\n });\n }", "async __receiveMsg() {\n let msg;\n try {\n msg = await this.sqs.receiveMessage({\n QueueUrl: this.queueUrl,\n MaxNumberOfMessages: this.maxNumberOfMessages,\n WaitTimeSeconds: this.waitTimeSeconds,\n VisibilityTimeout: this.visibilityTimeout,\n }).promise();\n } catch (err) {\n this.emit('error', err, 'api');\n return;\n }\n\n let msgs = [];\n if (msg.Messages) {\n if (!Array.isArray(msg.Messages)) {\n this.emit('error', new Error('SQS Api returned non-list'), 'api');\n return;\n }\n msgs = msg.Messages;\n }\n this.debug('received %d messages', msgs.length);\n\n // We never want this to actually throw. The __handleMsg function should\n // take care of emitting the error event\n try {\n if (this.sequential) {\n for (let msg of msgs) {\n await this.__handleMsg(msg);\n }\n } else {\n await Promise.all(msgs.map(x => this.__handleMsg(x)));\n }\n } catch (err) {\n let error = new Error('__handleMsg is rejecting when it ought not to. ' +\n 'This is a programming error in QueueListener.__handleMsg()');\n error.underlyingErr = err;\n error.underlyingStack = err.stack || '';\n this.debug('This really should not happen... %j', error);\n this.emit('error', error, 'api');\n }\n\n if (this.running) {\n // Same as the call in .start(), but here we do a small timeout of 50ms\n // just to make sure that we're not totally starving eveything\n setTimeout(async () => {\n await this.__receiveMsg();\n }, 50);\n } else {\n this.emit('stopped');\n }\n }", "_sendCommMessages() {\n let topMessage;\n return Promise.try(() => {\n if (!this.comm) {\n // TODO: try to init comm channel here\n throw new Error('Comm channel not initialized, not sending message.');\n }\n while (this.messageQueue.length) {\n topMessage = this.messageQueue.shift();\n this.comm.send(this._transformMessage(topMessage));\n this.debug(`sending comm message: ${COMM_NAME} ${topMessage.msgType}`);\n }\n }).catch((err) => {\n console.error('ERROR sending comm message', err.message, err, topMessage);\n throw new Error('ERROR sending comm message: ' + err.message);\n });\n }", "send(message) {\n\n\n return new Promise((resolve, reject) => {\n if (this._connected) {\n\n let delivery = false;\n\n\n if (!message.id) {\n message.id = this.autoId();\n }\n\n this._ws.send(JSON.stringify(message));\n\n const cb = (data) => {\n delivery = true;\n return resolve(data);\n };\n\n\n const key = `__reply__${get(message, 'id')}`;\n\n this.on(key, cb);\n\n this._timeout = setTimeout(() => {\n if (!delivery) {\n this._event.off(key, cb);\n return reject(\"Unable send message to the server.\");\n } else {\n clearTimeout(this._timeout);\n }\n\n }, 10000);\n\n } else {\n return reject(\"You are not connected\");\n }\n });\n }", "async function handleMessage(message){\n\t\tconsole.debug(\"[DEBUG] Message from: \", message);\n\t\tif (message.request === \"GETACTIVETASKS\"){ // get all tasks and return them\n console.debug(\"[BACKEND] Message received: \", message);\n\t\t\tawait returnActiveTasks(message, sendResponse);\t\t\t\n } \n else if (message.request === 'ADDNEWTASK'){ // add the payload as new data\n let payload = message.payload;\n let hash = \"\" + payload.title + payload.creationDate;\n payload.hash = hash;\n saveNewTaskToDatabase(payload);\n }\n else if (message.request === 'DELETETASK'){ // delete task from database\n await delteTaskFromDatabase(message);\n }\n else if (message.request === 'RESOLVETASK'){ // move task from active to resolved store\n await resolveTask(message);\n }\n else if (message.request === 'GETRESOLVEDTASKS'){ // get all removed tasks and return them\n await returnResolvedTasks(message, sendResponse);\n }\n else if (message.request === 'GETRESOLVEDTASKBYHASH'){\n await returnResolvedTaskByHash(message, sendResponse);\n }\n \n else {\n\t\t\tconsole.error(\"[ERROR] Unable to handle request from: \", message);\n\t\t}\n\t}", "joinSystemMsgRoom() {\n\n // Received direct message from cloud\n io.socket.on( 'sysmsg:' + _deviceUDID, ( data ) => {\n if ( _sysMsgCb ) {\n this.$rootScope.$apply( () => {\n _sysMsgCb( data );\n } );\n } else {\n console.log( 'Dropping sio DEVICE_DM message rx (no cb)' );\n }\n } )\n\n return new Promise( ( resolve, reject ) => {\n\n io.socket.post( '/ogdevice/subSystemMessages', {\n deviceUDID: _deviceUDID\n }, ( resData, jwres ) => {\n this.$log.debug( resData );\n if ( jwres.statusCode !== 200 ) {\n reject( jwres );\n } else {\n this.$log.debug( \"Successfully joined sysmsg room for this device\" );\n resolve();\n }\n } );\n } );\n\n }", "function handleMessage(msg) { // process message asynchronously\n setTimeout(function () {\n messageHandler(msg);\n }, 0);\n }", "async _onMessage(connection, message) {\n switch (message.type) {\n case signalr.MessageType.Invocation:\n try {\n var method = this._methods[message.target.toLowerCase()];\n var result = await method.apply(this, message.arguments);\n connection.completion(message.invocationId, result);\n }\n catch (e) {\n connection.completion(message.invocationId, null, 'There was an error invoking the hub');\n }\n break;\n case signalr.MessageType.StreamItem:\n break;\n case signalr.MessageType.Ping:\n // TODO: Detect client timeout\n break;\n default:\n console.error(`Invalid message type: ${message.type}.`);\n break;\n }\n }", "function doSendMessage(message) {\n return new Promise(resolve => {\n chrome.runtime.sendMessage(chrome.runtime.id, message, {}, resolve);\n });\n}", "waitForMessage_() {\n this.wait_(4, buffer => {\n this.wait_(buffer.readUInt32BE(0), buffer => {\n this.push(this.getMessage_(buffer));\n process.nextTick(() => this.waitForMessage_());\n });\n });\n }", "function simulate(messageHandler, message) {\n console.log('[In]', message);\n return processMessage(messageHandler, message).then(response => {\n if (response === false) {\n console.log('-');\n }\n else {\n console.log('[Out]', response);\n }\n });\n}", "function consume({ connection, channel }) {\n return new Promise((resolve, reject) => {\n channel.consume(\"processing.results\", async function (msg) {\n // parse message\n let msgBody = msg.content.toString();\n let data = JSON.parse(msgBody);\n let requestId = data.requestId;\n let processingResults = data.processingResults;\n console.log(\"[x]Received a result message, requestId:\", requestId, \"processingResults:\", processingResults);\n\n\n // acknowledge message as received\n await channel.ack(msg);\n // send notification to browsers\n app.io.sockets.emit(requestId + '_new message', \"SUCESS\");\n\n });\n\n // handle connection closed\n connection.on(\"close\", (err) => {\n return reject(err);\n });\n\n // handle errors\n connection.on(\"error\", (err) => {\n return reject(err);\n });\n });\n }", "onMessage(data) {\n const {id, error, result} = JSON.parse(data);\n const promise = this.currentMessages[id];\n if(!promise) return;\n \n if(error) {\n promise.reject(error);\n } else {\n promise.resolve(result);\n }\n\n delete this.currentMessages[id];\n }", "subscribeToMessageChannel() {\n this.subscription = subscribe(\n this.messageContext,\n RECORD_SELECTED_CHANNEL,\n (message) => {\n console.log(message);\n this.handleMessage(message); \n }\n );\n \n\n }", "function sendMessage(message) {\r\n return new Promise( (resolve, reject) => {\r\n console.log(\"sendMessage\", message);\r\n setTimeout(() => {\r\n if(!ALLOW_RANDOM_FAILURE || Math.random < 0.5){\r\n echoServer.emit(\"sendMessage\", {\r\n name: MY_USER_NAME,\r\n message,\r\n });\r\n console.log(\"message sent\", message);\r\n resolve(\"OK\");\r\n } else {\r\n reject(\"TIMEOUT\");\r\n }\r\n }, Math.random() * 150);\r\n });\r\n}", "__receiveMessage(msg) {\n var implCmdName = '_cmd_' + msg.type;\n if (!(implCmdName in this)) {\n logic(this, 'badMessageTypeError', { type: msg.type });\n return;\n }\n try {\n let namedContext = msg.handle &&\n this.bridgeContext.maybeGetNamedContext(msg.handle);\n if (namedContext) {\n if (namedContext.pendingCommand) {\n console.warn('deferring', msg);\n namedContext.commandQueue.push(msg);\n } else {\n let promise = namedContext.pendingCommand =\n this._processCommand(msg, implCmdName);\n if (promise) {\n this._trackCommandForNamedContext(namedContext, promise);\n }\n }\n } else {\n let promise = this._processCommand(msg, implCmdName);\n // If the command went async, then it's also possible that the command\n // grew a namedContext and that we therefore need to get it and set up the\n // bookkeeping so that if any other commands come in on this handle before\n // the promise is resolved that we can properly queue them.\n if (promise && msg.handle) {\n namedContext = this.bridgeContext.maybeGetNamedContext(msg.handle);\n if (namedContext) {\n namedContext.pendingCommand = promise;\n this._trackCommandForNamedContext(namedContext, promise);\n }\n }\n }\n } catch (ex) {\n logic(this, 'cmdError', { type: msg.type, ex, stack: ex.stack });\n }\n }", "function promiseMessage(messageName, params = {}, paramsAsCPOW = {}) {\n let requestName, responseName;\n\n if (typeof messageName === 'string') {\n requestName = responseName = messageName;\n }\n else {\n requestName = messageName.request;\n responseName = messageName.response;\n }\n\n // A message manager for the current browser.\n let mm = gBrowser.selectedBrowser.messageManager;\n\n return new Promise((resolve) => {\n // TODO: Make sure the response is associated with this request.\n mm.sendAsyncMessage(requestName, params, paramsAsCPOW);\n\n let onMessage = (message) => {\n mm.removeMessageListener(responseName, onMessage);\n\n resolve(message.data);\n };\n\n mm.addMessageListener(responseName, onMessage);\n });\n }", "send(message) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.gatewayInstance) {\n throw new Error('No gateway instance initialized for the Text messages service');\n }\n else if (!message) {\n throw new Error('No message provided for the Text gateway service');\n }\n return this.gatewayInstance.send(message);\n });\n }", "async process(message, phrase) {\n const commandDefs = this.command.argumentDefaults;\n const handlerDefs = this.handler.argumentDefaults;\n const optional = Util_1.default.choice(typeof this.prompt === \"object\" && this.prompt && this.prompt.optional, commandDefs.prompt && commandDefs.prompt.optional, handlerDefs.prompt && handlerDefs.prompt.optional);\n const doOtherwise = async (failure) => {\n const otherwise = Util_1.default.choice(this.otherwise, commandDefs.otherwise, handlerDefs.otherwise);\n const modifyOtherwise = Util_1.default.choice(this.modifyOtherwise, commandDefs.modifyOtherwise, handlerDefs.modifyOtherwise);\n let text = await Util_1.default.intoCallable(otherwise).call(this, message, {\n phrase,\n failure\n });\n if (Array.isArray(text)) {\n text = text.join(\"\\n\");\n }\n if (modifyOtherwise) {\n text = await modifyOtherwise.call(this, message, text, {\n phrase,\n failure: failure\n });\n if (Array.isArray(text)) {\n text = text.join(\"\\n\");\n }\n }\n if (text) {\n const sent = await message.channel.send(text);\n if (message.util)\n message.util.addMessage(sent);\n }\n return Flag_1.default.cancel();\n };\n if (!phrase && optional) {\n if (this.otherwise != null) {\n return doOtherwise(null);\n }\n return Util_1.default.intoCallable(this.default)(message, {\n phrase,\n failure: null\n });\n }\n const res = await this.cast(message, phrase);\n if (Argument.isFailure(res)) {\n if (this.otherwise != null) {\n return doOtherwise(res);\n }\n if (this.prompt != null) {\n return this.collect(message, phrase, res);\n }\n return this.default == null ? res : Util_1.default.intoCallable(this.default)(message, { phrase, failure: res });\n }\n return res;\n }", "async function receiveMessage() {\n const sqs = new AWS.SQS();\n\n try {\n // to simplify running multiple workers in parallel, \n // fetch one message at a time\n const data = await sqs.receiveMessage({\n QueueUrl: config.queue.url,\n VisibilityTimeout: config.queue.visibilityTimeout,\n MaxNumberOfMessages: 1\n }).promise();\n\n if (data.Messages && data.Messages.length > 0) {\n const message = data.Messages[0];\n const params = JSON.parse(message.Body);\n\n // while processing is not complete, update the message's visibilityTimeout\n const intervalId = setInterval(_ => sqs.changeMessageVisibility({\n QueueUrl: config.queue.url,\n ReceiptHandle: message.ReceiptHandle,\n VisibilityTimeout: config.queue.visibilityTimeout\n }), 1000 * 60);\n\n // processMessage should return a boolean status indicating success or failure\n const status = await processMessage(params);\n clearInterval(intervalId);\n \n // if message was not processed successfully, send it to the\n // error queue (add metadata in future if needed)\n if (!status) {\n await sqs.sendMessage({\n QueueUrl: config.queue.errorUrl,\n MessageBody: JSON.stringify(params),\n }).promise();\n }\n\n // remove original message from queue once processed\n await sqs.deleteMessage({\n QueueUrl: config.queue.url,\n ReceiptHandle: message.ReceiptHandle\n }).promise();\n }\n } catch (e) {\n // catch exceptions related to sqs\n logger.error(e);\n } finally {\n // schedule receiving next message\n setTimeout(receiveMessage, config.queue.pollInterval);\n }\n}", "function send_message_to_client(client, msg){\n return new Promise((resolve, reject) => {\n var msg_chan = new MessageChannel();\n msg_chan.port1.onmessage = function(event){\n if(event.data.error){\n reject(event.data.error);\n }else{\n resolve(event.data);\n }\n };\n\n client.postMessage(\"SW Says: '\"+msg+\"'\", [msg_chan.port2]);\n });\n}", "handleMessage(msg) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!msg.author)\n return; // this is a bug and shouldn't really happen\n if (this.ignoreBots && msg.author.bot)\n return;\n // Construct a partial context (without prefix or command name)\n const partialContext = Object.assign({\n client: this,\n }, this.contextAdditions);\n // Is the message properly prefixed? If not, we can ignore it\n const matchResult = yield this.splitPrefixFromContent(msg, partialContext);\n if (!matchResult)\n return;\n // It is! We can\n const [prefix, content] = matchResult;\n // If there is no content past the prefix, we don't have a command\n if (!content) {\n // But a lone mention will trigger the default command instead\n if (!prefix || !prefix.match(this.mentionPrefixRegExp))\n return;\n const defaultCommand = this.defaultCommand;\n if (!defaultCommand)\n return;\n defaultCommand.execute(msg, [], Object.assign({\n client: this,\n prefix,\n }, this.contextAdditions));\n return;\n }\n // Separate command name from arguments and find command object\n const args = content.split(' ');\n const commandName = args.shift();\n if (commandName === undefined)\n return;\n const command = this.commandForName(commandName);\n // Construct a full context object now that we have all the info\n const fullContext = Object.assign({\n prefix,\n commandName,\n }, partialContext);\n // If the message has command but that command is not found\n if (!command) {\n this.emit('invalidCommand', msg, args, fullContext);\n return;\n }\n // Do the things\n this.emit('preCommand', command, msg, args, fullContext);\n const executed = yield command.execute(msg, args, fullContext);\n if (executed)\n this.emit('postCommand', command, msg, args, fullContext);\n });\n }", "message(msg) {\n const sessionPath = this.sessionClient.sessionPath(projectId, sessionId);\n const request = {\n session: sessionPath,\n queryInput: {\n text: {\n text: msg,\n languageCode: languageCode,\n },\n },\n };\n\n const processMessage = (resolve, reject) => {\n this.sessionClient\n .detectIntent(request)\n .then(responses => {\n if (responses.length === 0 || !responses[0].queryResult) {\n reject(new Error('incorrect Dialog Flow answer'));\n } else {\n resolve(responses[0].queryResult);\n }\n })\n .catch(err => {\n console.error('ERROR:', err);\n reject(err);\n });\n }\n return new Promise(processMessage);\n }", "subscribeToMessageChannel() {\n if (!this.subscription) {\n this.subscription = subscribe(\n this.messageContext,\n sObjectSelected,\n (message) => this.handleMessage(message),\n { scope: APPLICATION_SCOPE }\n );\n }\n }" ]
[ "0.62991405", "0.6008539", "0.58747715", "0.581249", "0.57012355", "0.5655519", "0.5601487", "0.55965835", "0.55960613", "0.5570987", "0.554621", "0.55416393", "0.55300313", "0.54769", "0.54657245", "0.5454042", "0.54484653", "0.53516346", "0.5329301", "0.5327847", "0.5322457", "0.5315284", "0.52806383", "0.52544695", "0.5227921", "0.52278745", "0.5221724", "0.5216168", "0.52104986", "0.51834863" ]
0.6933967
0
"subscribe() returns a promise. write a \"provide\" command followed by the serialization of the ind(...TRUNCATED)
"subscribe(clientId, machine) {\n return new Promise( (resolve, reject) => {\n if (typeof ma(...TRUNCATED)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
["function ProductionEngineSubscription(machine) {\n //console.log('created pe subs: ', machine.i(...TRUNCATED)
["0.5257558","0.51723474","0.4928612","0.48542452","0.48314035","0.48277408","0.48249453","0.4764846(...TRUNCATED)
0.68615836
0

No dataset card yet

Downloads last month
46